Question: Generate PostgreSQL SQL for: List all cartoon directed by "Ben Jones".

CREATE TABLE Cartoon (Title VARCHAR, Directed_by VARCHAR)

SELECT Title FROM Cartoon WHERE Directed_by = 'Ben Jones';


Question: Determine the total financial capability training hours for employees in microfinance organizations in Asia

CREATE TABLE AsiaMicrofinance (id INT, employee_id INT, training_hours INT); INSERT INTO AsiaMicrofinance (id, employee_id, training_hours) VALUES (1, 1, 25), (2, 2, 35);

SELECT SUM(training_hours) FROM AsiaMicrofinance;


Question: Generate PostgreSQL SQL for: What is the average number of Wins in a PGA Championship with a Top-5 less than 2?

CREATE TABLE table_name_87 (wins INTEGER, tournament VARCHAR, top_5 VARCHAR)

SELECT AVG(wins) FROM table_name_87 WHERE tournament = 'pga championship' AND top_5 < 2;


Question: Generate PostgreSQL SQL for: Which representative was the Ambassador Extraordinary and Plenipotentiary and had a Termination of Mission date September 20, 1996?

CREATE TABLE table_name_83 (representative VARCHAR, title VARCHAR, termination_of_mission VARCHAR)

SELECT representative FROM table_name_83 WHERE title = 'ambassador extraordinary and plenipotentiary' AND termination_of_mission = 'september 20, 1996';


Question: Generate PostgreSQL SQL for: Which Game has a Score of 4–1?

CREATE TABLE table_name_47 (game INTEGER, score VARCHAR)

SELECT SUM(game) FROM table_name_47 WHERE score = '4–1';


Question: What is the total water usage for each product category in the last year?

CREATE TABLE Product (id INT, name VARCHAR(255), category VARCHAR(255), water_usage FLOAT, sale_date DATE);

SELECT category, SUM(water_usage) as total_water_usage FROM Product WHERE sale_date >= (CURRENT_DATE - INTERVAL '1 year') GROUP BY category;


Question: Generate PostgreSQL SQL for: What is the total brup for the team?

CREATE TABLE table_18064020_21 (brup VARCHAR, name VARCHAR)

SELECT brup FROM table_18064020_21 WHERE name = 'total';


Question: What is the maximum temperature recorded in each year of astrophysics research?

CREATE TABLE astrophysics_research_temperature (id INT PRIMARY KEY, project_year INT, temperature FLOAT);

SELECT project_year, MAX(temperature) as max_temperature FROM astrophysics_research_temperature GROUP BY project_year;


Question: List all airports with a runway length greater than 3000 meters

CREATE TABLE Airports (airport_id int, airport_name varchar(255), runway_length decimal(10,2), location varchar(255));

SELECT airport_id, airport_name, runway_length, location FROM Airports WHERE runway_length > 3000;


Question: PostgreSQL regression test 'timestamptz': Write the SELECT query (example 127).

Explanation: Regression test for Timestamptz in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT '4714-11-23 23:59:59+00 BC'::timestamptz;  -- out of range
SELECT '294276-12-31 23:59:59+00'::timestamptz) AS _sub;


Question: Generate PostgreSQL SQL for: Which district is jamie l. whitten from?

CREATE TABLE table_1342233_24 (district VARCHAR, incumbent VARCHAR)

SELECT district FROM table_1342233_24 WHERE incumbent = 'Jamie L. Whitten';


Question: List all genetic research projects in Japan using CRISPR technology?

CREATE TABLE research_projects (id INT, name TEXT, country TEXT, methods TEXT); INSERT INTO research_projects (id, name, country, methods) VALUES (1, 'GenomeEdge', 'Japan', 'CRISPR, Sequencing');

SELECT name FROM research_projects WHERE country = 'Japan' AND methods LIKE '%CRISPR%';


Question: Delete all records from the 'weapons' table where the 'country' is 'Russia'

CREATE TABLE weapons (id INT PRIMARY KEY, weapon_name VARCHAR(50), country VARCHAR(50)); INSERT INTO weapons (id, weapon_name, country) VALUES (1, 'AK-47', 'Russia'); INSERT INTO weapons (id, weapon_name, country) VALUES (2, 'RPG-7', 'Russia');

DELETE FROM weapons WHERE country = 'Russia';


Question: Show a SQL definition from the pg_partman project (pg_partman--2.1.0--2.2.0, item 31).

/*
 * Function to manage pre-creation of the next partitions in a set.
 * Also manages dropping old partitions if the retention option is set.
 * If p_parent_table is passed, will only run run_maintenance() on that one table (no matter what the configuration table may have set for it)
 * Otherwise, will run on all tables in the config table with p_run_maintenance() set to true.
 * For large partition sets, running analyze can cause maintenance to take longer than expected. Can set p_analyze to false to avoid a forced analyze run.
 * Be aware that constraint exclusion may not work properly until an analyze on the partition set is run.
 */
CREATE FUNCTION run_maintenance(p_parent_table text DEFAULT NULL, p_analyze boolean DEFAULT true, p_jobmon boolean DEFAULT true, p_debug boolean DEFAULT false) RETURNS void
    LANGUAGE plpgsql SECURITY DEFINER
    AS $$
DECLARE

ex_context                      text;
ex_detail                       text;
ex_hint                         text;
ex_message                      text;
v_adv_lock                      boolean;
v_check_subpart                 int;
v_create_count                  int := 0;
v_current_partition             text;
v_current_partition_id          bigint;
v_current_partition_timestamp   timestamp;
v_datetime_string               text;
v_drop_count                    int := 0;
v_id_position                   int;
v_job_id                        bigint;
v_jobmon                        boolean;
v_jobmon_schema                 text;
v_last_partition                text;
v_last_partition_created        boolean;
v_last_partition_id             bigint;
v_last_partition_timestamp      timestamp;
v_max_id_parent                 bigint;
v_max_time_parent               timestamp;
v_next_partition_id             bigint;
v_next_partition_timestamp      timestamp;
v_old_search_path               text;
v_parent_schema                 text;
v_parent_tablename              text;
v_premade_count                 int;
v_premake_id_max                bigint;
v_premake_id_min                bigint;
v_premake_timestamp_min         timestamp;
v_premake_timestamp_max         timestamp;
v_quarter                       text;
v_row                           record;
v_row_max_id                    record;
v_row_max_time                  record;
v_row_sub                       record;
v_skip_maint                    boolean;
v_step_id                       bigint;
v_step_overflow_id              bigint;
v_step_serial_id                bigint;
v_sub_id_max                    bigint;
v_sub_id_max_suffix             bigint;
v_sub_id_min                    bigint;
v_sub_parent                    text;
v_sub_timestamp_max             timestamp;
v_sub_timestamp_max_suffix      timestamp;
v_sub_timestamp_min             timestamp;
v_tablename                     text;
v_tables_list_sql               text;
v_time_position                 int;
v_year                          text;

BEGIN

v_adv_lock := pg_try_advisory_xact_lock(hashtext('pg_partman run_maintenance'));
IF v_adv_lock = 'false' THEN
    RAISE NOTICE 'Partman maintenance already running.';
    RETURN;
END IF;

IF p_jobmon THEN
    SELECT nspname INTO v_jobmon_schema FROM pg_catalog.pg_namespace n, pg_catalog.pg_extension e WHERE e.extname = 'pg_jobmon' AND e.extnamespace = n.oid;
    IF v_jobmon_schema IS NOT NULL THEN
        SELECT current_setting('search_path') INTO v_old_search_path;
        EXECUTE format('SELECT set_config(%L, %L, %L)', 'search_path', '@extschema@,'||v_jobmon_schema, 'false');
    END IF;
END IF;

IF v_jobmon_schema IS NOT NULL THEN
    v_job_id := add_job('PARTMAN RUN MAINTENANCE');
    v_step_id := add_step(v_job_id, 'Running maintenance loop');
END IF;

-- Check for consistent data in part_config_sub table. Was unable to get this working properly as either a constraint or trigger.
-- Would either delay raising an error until the next write (which I cannot predict) or disallow future edits to update a sub-partition set's configuration.
-- This way at least provides a consistent way to check that I know will run. If anyone can get a working constraint/trigger, please help!
-- Don't have to worry about this in the serial trigger maintenance since subpartitioning requires run_maintenance().
FOR v_row IN
    SELECT sub_parent FROM @extschema@.part_config_sub
LOOP
    SELECT count(*) INTO v_check_subpart FROM @extschema@.check_subpart_sameconfig(v_row.sub_parent);
    IF v_check_subpart > 1 THEN
        RAISE EXCEPTION 'Inconsistent data in part_config_sub table. Sub-partition tables that are themselves sub-partitions cannot have differing configuration values among their siblings.
        Run this query: "SELECT * FROM @extschema@.check_subpart_sameconfig(''%'');" This should only return a single row or nothing.
        If multiple rows are returned, results are all children of the given parent. Update the differing values to be consistent for your desired values.', v_row.sub_parent;
    END IF;
END LOOP;

v_row := NULL; -- Ensure it's reset

v_tables_list_sql := 'SELECT parent_table
                , partition_type
                , partition_interval
                , control
                , premake
                , datetime_string
                , undo_in_progress
                , sub_partition_set_full
                , epoch
            FROM @extschema@.part_config
            WHERE sub_partition_set_full = false';

IF p_parent_table IS NULL THEN
    v_tables_list_sql := v_tables_list_sql || ' AND use_run_maintenance = true';
ELSE
    v_tables_list_sql := v_tables_list_sql || format(' AND parent_table = %L', p_parent_table);
END IF;

FOR v_row IN EXECUTE v_tables_list_sql
LOOP

    CONTINUE WHEN v_row.undo_in_progress;
    v_skip_maint := true; -- reset every loop

    SELECT schemaname, tablename INTO v_parent_schema, v_parent_tablename FROM pg_catalog.pg_tables WHERE schemaname ||'.'|| tablename = v_row.parent_table;

    SELECT partition_tablename INTO v_last_partition FROM @extschema@.show_partitions(v_row.parent_table, 'DESC') LIMIT 1;
    IF p_debug THEN
        RAISE NOTICE 'run_maint: parent_table: %, v_last_partition: %', v_row.parent_table, v_last_partition;
    END IF;

    IF v_row.partition_type = 'time' OR v_row.partition_type = 'time-custom' THEN

        v_time_position := (length(v_last_partition) - position('p_' in reverse(v_last_partition))) + 2;
        IF v_row.partition_interval::interval <> '3 months' OR (v_row.partition_interval::interval = '3 months' AND v_row.partition_type = 'time-custom') THEN
           v_last_partition_timestamp := to_timestamp(substring(v_last_partition from v_time_position), v_row.datetime_string);
        ELSE
            -- to_timestamp doesn't recognize 'Q' date string formater. Handle it
            v_year := split_part(substring(v_last_partition FROM v_time_position), 'q', 1);
            v_quarter := split_part(substring(v_last_partition FROM v_time_position), 'q', 2);
            CASE
                WHEN v_quarter = '1' THEN
                    v_last_partition_timestamp := to_timestamp(v_year || '-01-01', 'YYYY-MM-DD');
                WHEN v_quarter = '2' THEN
                    v_last_partition_timestamp := to_timestamp(v_year || '-04-01', 'YYYY-MM-DD');
                WHEN v_quarter = '3' THEN
                    v_last_partition_timestamp := to_timestamp(v_year || '-07-01', 'YYYY-MM-DD');
                WHEN v_quarter = '4' THEN
                    v_last_partition_timestamp := to_timestamp(v_year || '-10-01', 'YYYY-MM-DD');
            END CASE;
        END IF;

        -- Loop through child tables starting from highest to get current max value in partition set
        -- Avoids doing a scan on entire partition set and/or getting any values accidentally in parent.
        FOR v_row_max_time IN
            SELECT partition_schemaname, partition_tablename FROM @extschema@.show_partitions(v_row.parent_table, 'DESC')
        LOOP
            IF v_row.epoch = false THEN
                EXECUTE format('SELECT max(%I)::text FROM %I.%I'
                                    , v_row.control
                                    , v_row_max_time.partition_schemaname
                                    , v_row_max_time.partition_tablename
                                ) INTO v_current_partition_timestamp;
            ELSE
                EXECUTE format('SELECT to_timestamp(max(%I))::text FROM %I.%I'
                                    , v_row.control
                                    , v_row_max_time.partition_schemaname
                                    , v_row_max_time.partition_tablename
                                ) INTO v_current_partition_timestamp;
            END IF;
            IF v_current_partition_timestamp IS NOT NULL THEN
                SELECT suffix_timestamp INTO v_current_partition_timestamp FROM show_partition_name(v_row.parent_table, v_current_partition_timestamp::text);
                EXIT;
            END IF;
        END LOOP;
        -- Check for values in the parent table. If they are there and greater than all child values, use that instead
        -- This allows maintenance to continue working properly if there is a large gap in data insertion. Data will remain in parent, but new tables will be created
        IF v_row.epoch = false THEN
            EXECUTE format('SELECT max(%I) FROM ONLY %I.%I', v_row.control, v_parent_schema, v_parent_tablename) INTO v_max_time_parent;
        ELSE
            EXECUTE format('SELECT to_timestamp(max(%I)) FROM ONLY %I.%I', v_row.control, v_parent_schema, v_parent_tablename) INTO v_max_time_parent;
        END IF;
        IF p_debug THEN
            RAISE NOTICE 'run_maint: v_current_partition_timestamp: %, v_max_time_parent: %', v_current_partition_timestamp, v_max_time_parent;
        END IF;
        IF v_max_time_parent > v_current_partition_timestamp THEN
            SELECT suffix_timestamp INTO v_current_partition_timestamp FROM show_partition_name(v_row.parent_table, v_max_time_parent::text);
        END IF;
        IF v_current_partition_timestamp IS NULL THEN
            -- Partition set is completely empty. Nothing to do
            CONTINUE;
        END IF;

        -- If this is a subpartition, determine if the last child table has been made. If so, mark it as full so future maintenance runs can skip it
        SELECT sub_min::timestamp, sub_max::timestamp INTO v_sub_timestamp_min, v_sub_timestamp_max FROM @extschema@.check_subpartition_limits(v_row.parent_table, 'time');
        IF v_sub_timestamp_max IS NOT NULL THEN
            SELECT suffix_timestamp INTO v_sub_timestamp_max_suffix FROM @extschema@.show_partition_name(v_row.parent_table, v_sub_timestamp_max::text);
            IF v_sub_timestamp_max_suffix = v_last_partition_timestamp THEN
                -- Final partition for this set is created. Set full and skip it
                UPDATE @extschema@.part_config SET sub_partition_set_full = true WHERE parent_table = v_row.parent_table;
                CONTINUE;
            END IF;
        END IF;

        -- Check and see how many premade partitions there are.
        v_premade_count = round(EXTRACT('epoch' FROM age(v_last_partition_timestamp, v_current_partition_timestamp)) / EXTRACT('epoch' FROM v_row.partition_interval::interval));
        v_next_partition_timestamp := v_last_partition_timestamp;
        IF p_debug THEN
            RAISE NOTICE 'run_maint before loop: current_partition_timestamp: %, v_premade_count: %, v_sub_timestamp_min: %, v_sub_timestamp_max: %'
                , v_current_partition_timestamp
                , v_premade_count
                , v_sub_timestamp_min
                , v_sub_timestamp_max;
        END IF;
        -- Loop premaking until config setting is met. Allows it to catch up if it fell behind or if premake changed
        WHILE (v_premade_count < v_row.premake) LOOP
            IF p_debug THEN
                RAISE NOTICE 'run_maint: parent_table: %, v_premade_count: %, v_next_partition_timestamp: %', v_row.parent_table, v_premade_count, v_next_partition_timestamp;
            END IF;
            IF v_next_partition_timestamp < v_sub_timestamp_min OR v_next_partition_timestamp > v_sub_timestamp_max THEN
                -- With subpartitioning, no need to run if the timestamp is not in the parent table's range
                EXIT;
            END IF;
            BEGIN
                v_next_partition_timestamp := v_next_partition_timestamp + v_row.partition_interval::interval;
            EXCEPTION WHEN datetime_field_overflow THEN
                v_premade_count := v_row.premake; -- do this so it can exit the premake check loop and continue in the outer for loop
                IF v_jobmon_schema IS NOT NULL THEN
                    v_step_overflow_id := add_step(v_job_id, 'Attempted partition time interval is outside PostgreSQL''s supported time range.');
                    PERFORM update_step(v_step_overflow_id, 'CRITICAL', 'Child partition creation skippd for parent table '||v_partition_time);
                END IF;
                RAISE WARNING 'Attempted partition time interval is outside PostgreSQL''s supported time range. Child partition creation skipped for parent table %', v_row.parent_table;
                CONTINUE;
            END;
            v_last_partition_created := @extschema@.create_partition_time(v_row.parent_table, ARRAY[v_next_partition_timestamp], p_analyze);
            IF v_last_partition_created THEN
                v_create_count := v_create_count + 1;
                PERFORM @extschema@.create_function_time(v_row.parent_table, v_job_id);
            END IF;

            v_premade_count = round(EXTRACT('epoch' FROM age(v_next_partition_timestamp, v_current_partition_timestamp)) / EXTRACT('epoch' FROM v_row.partition_interval::interval));
        END LOOP;
    ELSIF v_row.partition_type = 'id' THEN
        -- Loop through child tables starting from highest to get current max value in partition set
        -- Avoids doing a scan on entire partition set and/or getting any values accidentally in parent.
        FOR v_row_max_id IN
            SELECT partition_schemaname, partition_tablename FROM @extschema@.show_partitions(v_row.parent_table, 'DESC')
        LOOP
            EXECUTE format('SELECT max(%I)::text FROM %I.%I'
                            , v_row.control
                            , v_row_max_id.partition_schemaname
                            , v_row_max_id.partition_tablename) INTO v_current_partition_id;
            IF v_current_partition_id IS NOT NULL THEN
                SELECT suffix_id INTO v_current_partition_id FROM show_partition_name(v_row.parent_table, v_current_partition_id::text);
                EXIT;
            END IF;
        END LOOP;
        -- Check for values in the parent table. If they are there and greater than all child values, use that instead
        -- This allows maintenance to continue working properly if there is a large gap in data insertion. Data will remain in parent, but new tables will be created
        EXECUTE format('SELECT max(%I) FROM ONLY %I.%I', v_row.control, v_parent_schema, v_parent_tablename) INTO v_max_id_parent;
        IF v_max_id_parent > v_current_partition_id THEN
            SELECT suffix_id INTO v_current_partition_id FROM show_partition_name(v_row.parent_table, v_max_id_parent::text);
        END IF;
        IF v_current_partition_id IS NULL THEN
            -- Partition set is completely empty. Nothing to do
            CONTINUE;
        END IF;

        v_id_position := (length(v_last_partition) - position('p_' in reverse(v_last_partition))) + 2;
        v_last_partition_id = substring(v_last_partition from v_id_position)::bigint;
        -- Determine if this table is a child of a subpartition parent. If so, get limits to see if run_maintenance even needs to run for it.
        SELECT sub_min::bigint, sub_max::bigint INTO v_sub_id_min, v_sub_id_max FROM @extschema@.check_subpartition_limits(v_row.parent_table, 'id');
        IF v_sub_id_max IS NOT NULL THEN
            SELECT suffix_id INTO v_sub_id_max_suffix FROM @extschema@.show_partition_name(v_row.parent_table, v_sub_id_max::text);
            IF v_sub_id_max_suffix = v_last_partition_id THEN
                -- Final partition for this set is created. Set full and skip it
                UPDATE @extschema@.part_config SET sub_partition_set_full = true WHERE parent_table = v_row.parent_table;
                CONTINUE;
            END IF;
        END IF;

        v_next_partition_id := v_last_partition_id;
        v_premade_count := ((v_last_partition_id - v_current_partition_id) / v_row.partition_interval::bigint);
        -- Loop premaking until config setting is met. Allows it to catch up if it fell behind or if premake changed.
        WHILE (v_premade_count < v_row.premake) LOOP
            IF p_debug THEN
                RAISE NOTICE 'run_maint: parent_table: %, v_premade_count: %, v_next_partition_id: %', v_row.parent_table, v_premade_count, v_next_partition_id;
            END IF;
            IF v_next_partition_id < v_sub_id_min OR v_next_partition_id > v_sub_id_max THEN
                -- With subpartitioning, no need to run if the id is not in the parent table's range
                EXIT;
            END IF;
            v_next_partition_id := v_next_partition_id + v_row.partition_interval::bigint;
            v_last_partition_created := @extschema@.create_partition_id(v_row.parent_table, ARRAY[v_next_partition_id], p_analyze);
            IF v_last_partition_created THEN
                v_create_count := v_create_count + 1;
                PERFORM @extschema@.create_function_id(v_row.parent_table, v_job_id);
            END IF;
            v_premade_count := ((v_next_partition_id - v_current_partition_id) / v_row.partition_interval::bigint);
        END LOOP;

    END IF; -- end main IF check for time or id

    -- Manage additonal constraints if set
    PERFORM @extschema@.apply_constraints(p_parent_table := v_row.parent_table, p_job_id := v_job_id, p_debug := p_debug);

END LOOP; -- end of creation loop

-- Manage dropping old partitions if retention option is set
FOR v_row IN
    SELECT parent_table FROM @extschema@.part_config WHERE retention IS NOT NULL AND undo_in_progress = false AND
        (partition_type = 'time' OR partition_type = 'time-custom')
LOOP
    IF p_parent_table IS NULL THEN
        v_drop_count := v_drop_count + @extschema@.drop_partition_time(v_row.parent_table);
    ELSE -- Only run retention on table given in parameter
        IF p_parent_table <> v_row.parent_table THEN
            CONTINUE;
        ELSE
            v_drop_count := v_drop_count + @extschema@.drop_partition_time(v_row.parent_table);
        END IF;
    END IF;
    IF v_drop_count > 0 THEN
        PERFORM @extschema@.create_function_time(v_row.parent_table, v_job_id);
    END IF;
END LOOP;
FOR v_row IN
    SELECT parent_table FROM @extschema@.part_config WHERE retention IS NOT NULL AND undo_in_progress = false AND partition_type = 'id'
LOOP
    IF p_parent_table IS NULL THEN
        v_drop_count := v_drop_count + @extschema@.drop_partition_id(v_row.parent_table);
    ELSE -- Only run retention on table given in parameter
        IF p_parent_table <> v_row.parent_table THEN
            CONTINUE;
        ELSE
            v_drop_count := v_drop_count + @extschema@.drop_partition_id(v_row.parent_table);
        END IF;
    END IF;
    IF v_drop_count > 0 THEN
        PERFORM @extschema@.create_function_id(v_row.parent_table, v_job_id);
    END IF;
END LOOP;

IF v_jobmon_schema IS NOT NULL THEN
    PERFORM update_step(v_step_id, 'OK', format('Partition maintenance finished. %s partitions made. %s partitions dropped.', v_create_count, v_drop_count));
    IF v_step_overflow_id IS NOT NULL OR v_step_serial_id IS NOT NULL THEN
        PERFORM fail_job(v_job_id);
    ELSE
        PERFORM close_job(v_job_id);
    END IF;
    EXECUTE format('SELECT set_config(%L, %L, %L)', 'search_path', v_old_search_path, 'false');
END IF;

EXCEPTION
    WHEN OTHERS THEN
        GET STACKED DIAGNOSTICS ex_message = MESSAGE_TEXT,
                                ex_context = PG_EXCEPTION_CONTEXT,
                                ex_detail = PG_EXCEPTION_DETAIL,
                                ex_hint = PG_EXCEPTION_HINT;
        IF v_jobmon_schema IS NOT NULL THEN
            IF v_job_id IS NULL THEN
                EXECUTE format('SELECT %I.add_job(''PARTMAN RUN MAINTENANCE'')', v_jobmon_schema) INTO v_job_id;
                EXECUTE format('SELECT %I.add_step(%s, ''EXCEPTION before job logging started'')', v_jobmon_schema, v_job_id, p_parent_table) INTO v_step_id;
            ELSIF v_step_id IS NULL THEN
                EXECUTE format('SELECT %I.add_step(%s, ''EXCEPTION before first step logged'')', v_jobmon_schema, v_job_id) INTO v_step_id;
            END IF;
            EXECUTE format('SELECT %I.update_step(%s, ''CRITICAL'', %L)', v_jobmon_schema, v_step_id, 'ERROR: '||coalesce(SQLERRM,'unknown'));
            EXECUTE format('SELECT %I.fail_job(%s)', v_jobmon_schema, v_job_id);
        END IF;
        RAISE EXCEPTION '%
CONTEXT: %
DETAIL: %
HINT: %', ex_message, ex_context, ex_detail, ex_hint;
END
$$;

Explanation: SQL definition from the open-source pg_partman PostgreSQL project.


Question: Generate PostgreSQL SQL for: What was the result of Robert L. F. Sikes' election bid?

CREATE TABLE table_1342256_10 (result VARCHAR, incumbent VARCHAR)

SELECT result FROM table_1342256_10 WHERE incumbent = 'Robert L. F. Sikes';


Question: Generate PostgreSQL SQL for: What shows for miles [One Way] when the fans took 340?

CREATE TABLE table_name_89 (one_way VARCHAR, miles_ INTEGER, fans_took VARCHAR)

SELECT AVG(miles_)[one_way] FROM table_name_89 WHERE fans_took = '340';


Question: Write the PL/pgSQL object from PostgreSQL regression test 'polymorphism' (example 29).

drop function polyf(x anycompatiblerange, y anycompatiblearray);

Explanation: PL/pgSQL object from PostgreSQL core test for Polymorphism.


Question: PostgreSQL regression test 'identity': Write the SELECT query (example 114).

Explanation: Regression test for Identity in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT * FROM itest7c) AS _sub;


Question: What is the minimum playtime for players from each country?

CREATE TABLE PlayerPlaytimes (PlayerID int, Country varchar(50), Playtime int); INSERT INTO PlayerPlaytimes (PlayerID, Country, Playtime) VALUES (1, 'USA', 200), (2, 'Canada', 150), (3, 'Australia', 250), (4, 'England', 300), (5, 'USA', 350), (6, 'Canada', 400), (7, 'Australia', 450), (8, 'England', 500);

SELECT Country, MIN(Playtime) FROM PlayerPlaytimes GROUP BY Country;


Question: Calculate the percentage change in the number of tourists visiting India from 2017 to 2019

CREATE TABLE IndiaVisitorCount (year INT, tourists INT); INSERT INTO IndiaVisitorCount (year, tourists) VALUES (2017, 16000000), (2019, 18000000);

SELECT (SUM(CASE WHEN year = 2019 THEN tourists ELSE 0 END) - SUM(CASE WHEN year = 2017 THEN tourists ELSE 0 END)) * 100.0 / SUM(CASE WHEN year = 2017 THEN tourists ELSE 0 END) AS pct_change FROM IndiaVisitorCount;


Question: What's the number of medical supply deliveries to Haiti and Honduras in 2021 and 2022?

CREATE TABLE deliveries (id INT, country TEXT, year INT, supplies INT); INSERT INTO deliveries (id, country, year, supplies) VALUES (1, 'Haiti', 2021, 500), (2, 'Honduras', 2022, 700);

SELECT supplies FROM deliveries WHERE country IN ('Haiti', 'Honduras') AND year BETWEEN 2021 AND 2022;


Question: Generate PostgreSQL SQL for: What is the nationality of the draft pick player who plays centre position and is going to Calgary Flames?

CREATE TABLE table_2897457_2 (nationality VARCHAR, position VARCHAR, nhl_team VARCHAR)

SELECT nationality FROM table_2897457_2 WHERE position = 'Centre' AND nhl_team = 'Calgary Flames';


Question: Update the industry for a specific company.

CREATE TABLE Companies (id INT, name TEXT, industry TEXT, country TEXT, founder_gender TEXT); INSERT INTO Companies (id, name, industry, country, founder_gender) VALUES (1, 'Acme Inc', 'Tech', 'USA', 'Female'); INSERT INTO Companies (id, name, industry, country, founder_gender) VALUES (2, 'Beta Corp', 'Biotech', 'Canada', 'Male');

UPDATE Companies SET industry = 'Fintech' WHERE name = 'Beta Corp';


Question: Write the SQL definition from PostgreSQL contrib extension 'contrib' (item 2).

CREATE FUNCTION levenshtein (text,text,int,int,int) RETURNS int
AS 'MODULE_PATHNAME','levenshtein_with_costs'
LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;

Explanation: SQL definition from the 'contrib' PostgreSQL contrib extension.


Question: PL/pgSQL test: Plpython Spi (example 33).

CREATE FUNCTION cursor_fetch() RETURNS int AS $$
res = plpy.cursor("select fname, lname from users")
assert len(res.fetch(3)) == 3
assert len(res.fetch(3)) == 1
assert len(res.fetch(3)) == 0
assert len(res.fetch(3)) == 0
try:
    # use next() and not __next__(), the method name changed in
    # http://www.python.org/dev/peps/pep-3114/
    next(res)
except StopIteration:
    pass
else:
    assert False, "StopIteration not raised"
$$ LANGUAGE plpython3u;

Explanation: PL/pgSQL example from PostgreSQL source test for Plpython Spi.


Question: Generate PostgreSQL SQL for: Which week has Game site of Candlestick Park?

CREATE TABLE table_name_32 (week VARCHAR, game_site VARCHAR)

SELECT week FROM table_name_32 WHERE game_site = 'candlestick park';


Question: Generate PostgreSQL SQL for: Which settlement has the cyrillic and other name of локве (romanian: locve)?

CREATE TABLE table_2562572_44 (settlement VARCHAR, cyrillic_name_other_names VARCHAR)

SELECT settlement FROM table_2562572_44 WHERE cyrillic_name_other_names = 'Локве (Romanian: Locve)';


Question: Generate PostgreSQL SQL for: What is the displacement when the fuel system is carburettor, and a power of ps (kw; hp), and also has a model of 2000?

CREATE TABLE table_name_20 (displacement VARCHAR, model VARCHAR, fuel_system VARCHAR, power VARCHAR)

SELECT displacement FROM table_name_20 WHERE fuel_system = 'carburettor' AND power = 'ps (kw; hp)' AND model = '2000';


Question: PostgreSQL regression test 'sqljson': Write the SELECT query (example 206).

SELECT JSON_ARRAY(JSON_ARRAY('{ "a" : 123 }' RETURNING varchar(2)));

Explanation: Regression test for Sqljson in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT JSON_ARRAY(JSON_ARRAY('{ "a" : 123 }' RETURNING varchar(2)))) AS _sub;


Question: Generate PostgreSQL SQL for: Of weightlifters who weighed more than 136.16, who had the highest Total?

CREATE TABLE table_name_82 (total__kg_ INTEGER, bodyweight INTEGER)

SELECT MAX(total__kg_) FROM table_name_82 WHERE bodyweight > 136.16;


Question: Who are the male founders that have not received any funding?

CREATE TABLE founders(id INT, name VARCHAR(50), gender VARCHAR(10), industry VARCHAR(20)); INSERT INTO founders VALUES (1, 'Alice', 'Female', 'Tech'); INSERT INTO founders VALUES (2, 'Bob', 'Male', 'Finance'); CREATE TABLE funding(id INT, founder_id INT, amount INT); INSERT INTO funding VALUES (1, 1, 500000); INSERT INTO funding VALUES (2, 1, 750000);

SELECT founders.name FROM founders LEFT JOIN funding ON founders.id = funding.founder_id WHERE founders.gender = 'Male' AND funding.id IS NULL;


Question: What is the average rating of hotels in the US that offer virtual tours?

CREATE TABLE hotels (hotel_id INT, hotel_name TEXT, country TEXT, rating FLOAT, virtual_tour BOOLEAN); INSERT INTO hotels (hotel_id, hotel_name, country, rating, virtual_tour) VALUES (1, 'Hotel X', 'USA', 4.2, true), (2, 'Hotel Y', 'Canada', 4.5, false);

SELECT AVG(rating) FROM hotels WHERE country = 'USA' AND virtual_tour = true;


Question: Generate PostgreSQL SQL for: Who drive 74 laps in a grid larger than 9?

CREATE TABLE table_name_25 (driver VARCHAR, laps VARCHAR, grid VARCHAR)

SELECT driver FROM table_name_25 WHERE laps = 74 AND grid > 9;


Question: What is the total production of wells in the Arabian Sea?

CREATE TABLE wells (well_id INT, name VARCHAR(50), location VARCHAR(50), production FLOAT); INSERT INTO wells (well_id, name, location, production) VALUES (1, 'F1', 'Arabian Sea', 4000), (2, 'F2', 'Arabian Sea', 3000), (3, 'F3', 'Arabian Sea', 5000);

SELECT SUM(production) FROM wells WHERE location = 'Arabian Sea';


Question: Show a query using PostgreSQL contrib extension 'pg_trgm' (example 118).

Explanation: Example query from the 'pg_trgm' extension test/demo.


Question: Generate PostgreSQL SQL for: What was John Watson's time/retired?

CREATE TABLE table_name_46 (time_retired VARCHAR, driver VARCHAR)

SELECT time_retired FROM table_name_46 WHERE driver = 'john watson';


Question: Generate PostgreSQL SQL for: what's the naturalisation  by marriage with numer of jamaicans granted british citizenship being 3165

CREATE TABLE table_11214212_1 (naturalisation_by_marriage VARCHAR, numer_of_jamaicans_granted_british_citizenship VARCHAR)

SELECT naturalisation_by_marriage FROM table_11214212_1 WHERE numer_of_jamaicans_granted_british_citizenship = 3165;


Question: What is the average account balance of customers who are high net worth individuals (HNWI) in the Asia-Pacific region?

CREATE TABLE customers (id INT, name VARCHAR(255), account_balance DECIMAL(10, 2), region VARCHAR(50)); INSERT INTO customers (id, name, account_balance, region) VALUES (1, 'Li Wei', 2000000.00, 'Asia-Pacific'), (2, 'Kim Park', 500000.00, 'Asia-Pacific');

SELECT AVG(account_balance) FROM customers WHERE region = 'Asia-Pacific' AND account_balance > 1000000.00;


Question: How many vegetarian and non-vegetarian dishes are available in each store, and what is the total calorie count for each?

CREATE TABLE Dishes (DishID int, Name varchar(50), Type varchar(10), Calories int, StoreID int); INSERT INTO Dishes (DishID, Name, Type, Calories, StoreID) VALUES (1, 'Veggie Burger', 'Vegetarian', 400, 1);

SELECT Stores.Name, SUM(CASE WHEN Dishes.Type = 'Vegetarian' THEN 1 ELSE 0 END) AS VegetarianDishes, SUM(CASE WHEN Dishes.Type = 'Non-Vegetarian' THEN 1 ELSE 0 END) AS NonVegetarianDishes, SUM(Dishes.Calories) AS TotalCalories FROM Dishes INNER JOIN Stores ON Dishes.StoreID = Stores.StoreID GROUP BY Stores.Name;


Question: Generate PostgreSQL SQL for: What is the Status of the dinosaur, whose notes are, "n coelurosauria"?

CREATE TABLE table_name_73 (status VARCHAR, notes VARCHAR)

SELECT status FROM table_name_73 WHERE notes = 'n coelurosauria';


Question: Generate PostgreSQL SQL for: Which home team score has an Away team of melbourne?

CREATE TABLE table_name_71 (home_team VARCHAR, away_team VARCHAR)

SELECT home_team AS score FROM table_name_71 WHERE away_team = 'melbourne';


Question: Delete records in the 'unfair_outcomes' table where the 'outcome' is 'unfavorable' and the 'bias_type' is 'gender'

CREATE TABLE unfair_outcomes (id INT PRIMARY KEY, algorithm_name VARCHAR(50), outcome VARCHAR(20), bias_type VARCHAR(20), description TEXT);

DELETE FROM unfair_outcomes WHERE outcome = 'unfavorable' AND bias_type = 'gender';


Question: PostgreSQL regression test 'jsonb_jsonpath': Write the SELECT query (example 356).

select jsonb_path_query('null', '$.boolean()', silent => true);

Explanation: Regression test for Jsonb Jsonpath in PostgreSQL core test suite.

SELECT count(*) FROM (select jsonb_path_query('null', '$.boolean()', silent => true)) AS _sub;


Question: Generate PostgreSQL SQL for: What is the protein name when aa length is 202 aa?

CREATE TABLE table_26708105_5 (protein_name VARCHAR, aa_length VARCHAR)

SELECT protein_name FROM table_26708105_5 WHERE aa_length = '202 aa';


Question: Generate PostgreSQL SQL for: What is the year that the Roughriders left the conference?

CREATE TABLE table_name_25 (year_left INTEGER, mascot VARCHAR)

SELECT MAX(year_left) FROM table_name_25 WHERE mascot = 'roughriders';


Question: Find the number of players who have played "Adventure Game B" and identify their gender.

CREATE TABLE Adventure_Game_B (player_id INT, name VARCHAR(50), age INT, gender VARCHAR(10)); INSERT INTO Adventure_Game_B (player_id, name, age, gender) VALUES (1, 'John Doe', 25, 'Male'), (2, 'Jane Smith', 30, 'Female'), (7, 'David Kim', 29, 'Male');

SELECT COUNT(*), gender FROM Adventure_Game_B GROUP BY gender;


Question: Identify the smart city technology adoption project with the lowest adoption rate

CREATE TABLE smart_city_projects (id INT, name VARCHAR(50), location VARCHAR(50), adoption_rate FLOAT);

SELECT * FROM smart_city_projects WHERE adoption_rate = (SELECT MIN(adoption_rate) FROM smart_city_projects);


Question: Write the SQL definition from PostgreSQL contrib extension 'contrib' (item 1).

/* contrib/pg_trgm/pg_trgm--1.3.sql */

-- complain if script is sourced in psql, rather than via CREATE EXTENSION
\echo Use "CREATE EXTENSION pg_trgm" to load this file. \quit

-- Deprecated function
CREATE FUNCTION set_limit(float4)
RETURNS float4
AS 'MODULE_PATHNAME'
LANGUAGE C STRICT VOLATILE PARALLEL UNSAFE;


Question: Calculate the average CO2 emissions for projects in the 'environment' schema

CREATE SCHEMA IF NOT EXISTS environment; CREATE TABLE environment.projects (id INT, name VARCHAR(100), co2_emissions FLOAT); INSERT INTO environment.projects (id, name, co2_emissions) VALUES (1, 'Solar Farm', 50), (2, 'Wind Turbine Park', 25), (3, 'Hydroelectric Plant', 10);

SELECT AVG(co2_emissions) FROM environment.projects;


Question: Generate PostgreSQL SQL for: What was the match type in Budapest where the opponent was Luxembourg?

CREATE TABLE table_name_64 (match_type VARCHAR, location VARCHAR, opponenent VARCHAR)

SELECT match_type FROM table_name_64 WHERE location = 'budapest' AND opponenent = 'luxembourg';


Question: Generate PostgreSQL SQL for: What is the highest value for Points 2 when the goal average 1 is 0.65?

CREATE TABLE table_17359181_1 (points_2 INTEGER, goal_average_1 VARCHAR)

SELECT MAX(points_2) FROM table_17359181_1 WHERE goal_average_1 = '0.65';


Question: Delete all workouts performed by 'John Doe' in 'Park City' gym using DELETE command

CREATE TABLE workouts (workout_id INT, member_id INT, gym_id INT, workout_date DATE, calories INT); INSERT INTO workouts (workout_id, member_id, gym_id, workout_date, calories) VALUES (1, 1, 1, '2022-01-01', 300), (2, 2, 1, '2022-01-02', 400), (3, 1, 2, '2022-01-03', 500); CREATE TABLE members (member_id INT, name TEXT, age INT, gender TEXT); INSERT INTO members (member_id, name, age, gender) VALUES (1, 'John Doe', 30, 'Male'), (2, 'Jane Doe', 28, 'Female'); CREATE TABLE gyms (gym_id INT, name TEXT, city TEXT); INSERT INTO gyms (gym_id, name, city) VALUES (1, 'Park City', 'New York'), (2, 'Central Park', 'New York');

DELETE FROM workouts WHERE member_id IN (SELECT member_id FROM members WHERE name = 'John Doe') AND gym_id IN (SELECT gym_id FROM gyms WHERE city = 'New York' AND name = 'Park City');


Question: What is the total CO2 emission in the Arctic regions for each year?

CREATE TABLE CO2Emissions (region VARCHAR(255), year INT, CO2_emission FLOAT); INSERT INTO CO2Emissions (region, year, CO2_emission) VALUES ('Arctic Ocean', 2019, 120000), ('Arctic Ocean', 2020, 125000), ('Greenland', 2019, 150000), ('Greenland', 2020, 160000);

SELECT region, year, SUM(CO2_emission) as total_emission FROM CO2Emissions GROUP BY year, region;


Question: What is the total number of workers in factories that have implemented fair labor practices in Spain and Italy?

CREATE TABLE factories (factory_id INT, country VARCHAR(50), labor_practices VARCHAR(50)); CREATE TABLE workers (worker_id INT, factory_id INT, position VARCHAR(50)); INSERT INTO factories (factory_id, country, labor_practices) VALUES (1, 'Spain', 'fair'), (2, 'Italy', 'unfair'), (3, 'Spain', 'fair'), (4, 'Italy', 'fair'); INSERT INTO workers (worker_id, factory_id, position) VALUES (1, 1, 'manager'), (2, 1, 'engineer'), (3, 2, 'worker'), (4, 3, 'manager'), (5, 3, 'engineer'), (6, 4, 'manager');

SELECT COUNT(workers.worker_id) FROM workers INNER JOIN factories ON workers.factory_id = factories.factory_id WHERE factories.country IN ('Spain', 'Italy') AND factories.labor_practices = 'fair';


Question: Generate PostgreSQL SQL for: When did the New England Patriots play as the visiting team?

CREATE TABLE table_name_23 (date VARCHAR, visiting_team VARCHAR)

SELECT date FROM table_name_23 WHERE visiting_team = 'new england patriots';


Question: Add a new record for the 'Indian Ocean' to the 'marine_region' table.

CREATE TABLE marine_region (id INT, region_name VARCHAR(50), min_ocean_ph FLOAT, max_ocean_ph FLOAT); INSERT INTO marine_region (id, region_name, min_ocean_ph, max_ocean_ph) VALUES (1, 'Atlantic Ocean', 7.5, 8.1), (2, 'Pacific Ocean', 7.6, 8.2);

INSERT INTO marine_region (region_name, min_ocean_ph, max_ocean_ph) VALUES ('Indian Ocean', 7.4, 8.3);


Question: What is the number of volunteers and total volunteer hours for each program?

CREATE TABLE volunteers (volunteer_id INT, program_id VARCHAR(20), hours INT); INSERT INTO volunteers (volunteer_id, program_id, hours) VALUES (1, 'Education', 50), (2, 'Health', 75), (3, 'Education', 100); CREATE TABLE donations (donor_id INT, program_id VARCHAR(20), amount DECIMAL(10,2)); INSERT INTO donations (donor_id, program_id, amount) VALUES (1, 'Education', 500.00), (2, 'Health', 300.00), (3, 'Education', 250.00);

SELECT program_id, COUNT(DISTINCT volunteer_id) AS num_volunteers, SUM(hours) AS total_hours FROM volunteers GROUP BY program_id;


Question: What is the total revenue for each category in the last month?

CREATE TABLE dishes (dish_id INT, dish VARCHAR(50), category VARCHAR(50), created_at TIMESTAMP);CREATE TABLE orders (order_id INT, dish_id INT, price DECIMAL(5,2));

SELECT c.category, SUM(o.price) as total_revenue FROM dishes d JOIN orders o ON d.dish_id = o.dish_id WHERE d.created_at >= NOW() - INTERVAL '1 month' GROUP BY c.category;


Question: What is the total billing amount for cases with a favorable outcome in the 'California' region?

CREATE TABLE cases (id INT, attorney_id INT, outcome TEXT, billing_amount INT); INSERT INTO cases (id, attorney_id, outcome, billing_amount) VALUES (1, 1, 'Favorable', 10000); CREATE TABLE attorneys (id INT, name TEXT, region TEXT, title TEXT); INSERT INTO attorneys (id, name, region, title) VALUES (1, 'Jim Smith', 'California', 'Associate');

SELECT SUM(billing_amount) FROM cases JOIN attorneys ON cases.attorney_id = attorneys.id WHERE attorneys.region = 'California' AND cases.outcome = 'Favorable';


Question: Generate PostgreSQL SQL for: Which surface has a Date of 5 november 2011?

CREATE TABLE table_name_40 (surface VARCHAR, date VARCHAR)

SELECT surface FROM table_name_40 WHERE date = '5 november 2011';


Question: What is the total mental health parity score for healthcare providers working in each state?

CREATE TABLE healthcare_providers (id INT, name VARCHAR(100), state VARCHAR(50), mental_health_parity_score INT); INSERT INTO healthcare_providers (id, name, state, mental_health_parity_score) VALUES (1, 'Jack', 'California', 85), (2, 'Kate', 'Texas', 80), (3, 'Luke', 'New York', 90);

SELECT state, SUM(mental_health_parity_score) FROM healthcare_providers GROUP BY state;


Question: Generate PostgreSQL SQL for: What is 2nd Party, when Election is "1865"?

CREATE TABLE table_name_82 (election VARCHAR)

SELECT 2 AS nd_party FROM table_name_82 WHERE election = '1865';


Question: Generate PostgreSQL SQL for: What are the names of products whose availability equals to 1?

CREATE TABLE view_product_availability (product_id VARCHAR, available_yn VARCHAR); CREATE TABLE products_for_hire (product_name VARCHAR, product_id VARCHAR)

SELECT T2.product_name FROM view_product_availability AS T1 JOIN products_for_hire AS T2 ON T1.product_id = T2.product_id WHERE T1.available_yn = 1;


Question: What is the average age of users who prefer watching sports news?

CREATE TABLE users (id INT, age INT, preference VARCHAR(20)); INSERT INTO users (id, age, preference) VALUES (1, 35, 'sports'), (2, 45, 'politics'), (3, 28, 'sports');

SELECT AVG(age) FROM users WHERE preference = 'sports';


Question: Generate PostgreSQL SQL for: Who is the director and what number is the episode for episode #1 of Are You Afraid of the Dark season 3?

CREATE TABLE table_10470082_4 (director VARCHAR, _number VARCHAR)

SELECT COUNT(director) FROM table_10470082_4 WHERE _number = 1;


Question: Write the SQL definition from PostgreSQL contrib extension 'contrib' (item 1).

/* contrib/pageinspect/pageinspect--1.5.sql */

-- complain if script is sourced in psql, rather than via CREATE EXTENSION
\echo Use "CREATE EXTENSION pageinspect" to load this file. \quit

--
-- get_raw_page()
--
CREATE FUNCTION get_raw_page(text, int4)
RETURNS bytea
AS 'MODULE_PATHNAME', 'get_raw_page'
LANGUAGE C STRICT PARALLEL SAFE;


Question: pgTAP test for Resultset (assertion 105).

INSERT INTO names (name) VALUES ('Lillian');

Explanation: SQL assertion from pgTAP test suite for Resultset.


Question: Update the financial capability score of clients in Egypt to 1 point higher than their current score, if their score is currently between 5 and 8.

CREATE TABLE financial_capability_eg (client_id INT, financial_capability_score INT, country VARCHAR(50)); INSERT INTO financial_capability_eg (client_id, financial_capability_score, country) VALUES (1, 5, 'Egypt'), (2, 3, 'Egypt'), (3, 6, 'Egypt');

WITH updated_scores AS (UPDATE financial_capability_eg SET financial_capability_score = financial_capability_score + 1 WHERE country = 'Egypt' AND financial_capability_score >= 5 AND financial_capability_score <= 8) SELECT * FROM updated_scores;


Question: Generate PostgreSQL SQL for: Who was the coach who had 215 losses?

CREATE TABLE table_name_33 (coach VARCHAR, losses VARCHAR)

SELECT coach FROM table_name_33 WHERE losses = 215;


Question: PostgreSQL regression test 'misc_functions': Write the SELECT query (example 47).

Explanation: Regression test for Misc Functions in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT test_canonicalize_path('../abc/..')) AS _sub;


Question: Write the PL/pgSQL object from PostgreSQL regression test 'opr_sanity' (example 8).

-- probin should be non-empty for C functions, null everywhere else
SELECT p1.oid, p1.proname
FROM pg_proc as p1
WHERE prolang = 13 AND (probin IS NULL OR probin = '' OR probin = '-');

Explanation: PL/pgSQL object from PostgreSQL core test for Opr Sanity.


Question: Generate PostgreSQL SQL for: What are the completion dates of all the tests that have result "Fail"?

CREATE TABLE Student_Tests_Taken (registration_id VARCHAR, test_result VARCHAR); CREATE TABLE Student_Course_Enrolment (date_of_completion VARCHAR, registration_id VARCHAR)

SELECT T1.date_of_completion FROM Student_Course_Enrolment AS T1 JOIN Student_Tests_Taken AS T2 ON T1.registration_id = T2.registration_id WHERE T2.test_result = 'Fail';


Question: pgTAP test for Resultset (assertion 252).

SELECT * FROM check_test(
    bag_eq(
        'SELECT id, name FROM annames WHERE name NOT IN (''Anna'', ''Angelina'')',
        'expect'
    ),
    false,
    'bag_eq(select, prepared) fail missings',
    '',
    '    Missing records:
        [(](44,Anna|86,Angelina)[)]
        [(](44,Anna|86,Angelina)[)]',
    true
);


Question: Generate PostgreSQL SQL for: What teams rank is higher than 4 with a speed of 104.574mph?

CREATE TABLE table_name_91 (team VARCHAR, rank VARCHAR, speed VARCHAR)

SELECT team FROM table_name_91 WHERE rank > 4 AND speed = '104.574mph';


Question: What is the average waste production per factory in India and China?

CREATE TABLE waste_data (country VARCHAR(255), year INT, quantity INT); INSERT INTO waste_data (country, year, quantity) VALUES ('China', 2018, 5000), ('India', 2018, 3000), ('Bangladesh', 2018, 2000), ('China', 2019, 6000), ('India', 2019, 4000), ('Bangladesh', 2019, 3000);

SELECT country, AVG(quantity) as avg_waste FROM waste_data WHERE country IN ('China', 'India') GROUP BY country;


Question: Generate PostgreSQL SQL for: What is the venue of the match with a score of 33-22?

CREATE TABLE table_name_45 (venue VARCHAR, score VARCHAR)

SELECT venue FROM table_name_45 WHERE score = '33-22';


Question: Find the total usage hours of autonomous vehicles in the autonomous_vehicles table

CREATE TABLE autonomous_vehicle_usage (id INT PRIMARY KEY, user_id INT, vehicle_id INT, usage_hours TIMESTAMP);

SELECT SUM(usage_hours) FROM autonomous_vehicle_usage JOIN autonomous_vehicles ON autonomous_vehicle_usage.vehicle_id = autonomous_vehicles.id;


Question: List all vendors that the ethical fashion brand 'EcoFriendlyFashions' sources sustainable materials from, along with the total quantity of materials sourced from each vendor.

CREATE TABLE vendor_materials (id INT PRIMARY KEY, brand VARCHAR(255), vendor VARCHAR(255), material_type VARCHAR(255), quantity INT); INSERT INTO vendor_materials (id, brand, vendor, material_type, quantity) VALUES (1, 'EcoFriendlyFashions', 'Vendor1', 'Organic Cotton', 2000), (2, 'EcoFriendlyFashions', 'Vendor2', 'Recycled Polyester', 1500), (3, 'GreenFashions', 'Vendor3', 'Organic Cotton', 1000), (4, 'GreenFashions', 'Vendor4', 'Tencel', 2000);

SELECT vm.vendor, SUM(vm.quantity) as total_quantity FROM vendor_materials vm WHERE vm.brand = 'EcoFriendlyFashions' GROUP BY vm.vendor;


Question: What is the average citizen satisfaction score for public services in Tokyo in 2021?

CREATE TABLE TokyoSatisfaction (service VARCHAR(30), score INT, year INT); INSERT INTO TokyoSatisfaction (service, score, year) VALUES ('Public Services', 80, 2021), ('Public Services', 85, 2021), ('Public Services', 75, 2021), ('Public Services', 90, 2021);

SELECT AVG(score) FROM TokyoSatisfaction WHERE service = 'Public Services' AND year = 2021;


Question: PostgreSQL regression test 'stats_ext': Write the SELECT query (example 519).

SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE mod(a,20) IN (1, 2, 51, 52, NULL) AND mod(b::int,10) IN ( 1, 2, NULL)');

Explanation: Regression test for Stats Ext in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE mod(a,20) IN (1, 2, 51, 52, NULL) AND mod(b::int,10) IN ( 1, 2, NULL)')) AS _sub;


Question: What is the percentage of prepaid mobile customers in each city who have broadband subscriptions?

CREATE TABLE prepaid_city_customers (customer_id INT, city VARCHAR(50), prepaid BOOLEAN); INSERT INTO prepaid_city_customers (customer_id, city, prepaid) VALUES (1, 'Seattle', FALSE), (2, 'Bellevue', TRUE), (3, 'Seattle', FALSE); ALTER TABLE broadband_subscriptions ADD COLUMN city VARCHAR(50); UPDATE broadband_subscriptions SET city = (SELECT city FROM city_customers WHERE city_customers.customer_id = broadband_subscriptions.customer_id);

SELECT pc.city, (COUNT(CASE WHEN bs.subscription = TRUE THEN 1 END) * 100.0 / COUNT(bs.customer_id)) AS percentage FROM prepaid_city_customers pc JOIN broadband_subscriptions bs ON pc.customer_id = bs.customer_id GROUP BY pc.city;


Question: Generate PostgreSQL SQL for: Which Score has Opponents in the final of john bromwich frank sedgman?

CREATE TABLE table_name_92 (score VARCHAR, opponents_in_the_final VARCHAR)

SELECT score FROM table_name_92 WHERE opponents_in_the_final = 'john bromwich frank sedgman';


Question: Create a table for tracking volunteer hours, with columns for VolunteerID, Program, Hours, and Date.

CREATE TABLE VolunteerHours (VolunteerID INT, Program VARCHAR(50), Hours INT, VolunteerDate DATE);


Question: Generate PostgreSQL SQL for: When the winning team of mathiasen motorsports has a pole position of jonathan bomarito, who has the fastest lap?

CREATE TABLE table_name_97 (fastest_lap VARCHAR, winning_team VARCHAR, pole_position VARCHAR)

SELECT fastest_lap FROM table_name_97 WHERE winning_team = 'mathiasen motorsports' AND pole_position = 'jonathan bomarito';


Question: What is the maximum labor cost in the affordable housing sector in 2021?

CREATE TABLE labor_costs (project_id INT, sector VARCHAR(50), labor_cost FLOAT, year INT); INSERT INTO labor_costs (project_id, sector, labor_cost, year) VALUES (1, 'Affordable Housing', 28000, 2021), (2, 'Conventional', 30000, 2021), (3, 'Affordable Housing', 32000, 2021);

SELECT MAX(labor_cost) FROM labor_costs WHERE sector = 'Affordable Housing' AND year = 2021;


Question: Show the number of military equipment maintenance requests for 'Fighter Jet' type in 2020

CREATE TABLE maintenance_requests (request_id INT, equipment_type VARCHAR(255), date DATE); INSERT INTO maintenance_requests (request_id, equipment_type, date) VALUES (4, 'Fighter Jet', '2020-02-05'), (5, 'Fighter Jet', '2020-06-10'), (6, 'Fighter Jet', '2020-12-15');

SELECT equipment_type, COUNT(*) FROM maintenance_requests WHERE equipment_type = 'Fighter Jet' AND date BETWEEN '2020-01-01' AND '2020-12-31' GROUP BY equipment_type;


Question: PostgreSQL regression test 'int8': Write the SELECT query (example 46).

SELECT q1, q2, q1 * q2 AS multiply FROM INT8_TBL;

Explanation: Regression test for Int8 in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT q1, q2, q1 * q2 AS multiply FROM INT8_TBL) AS _sub;


Question: What is the maximum number of tickets sold for any event in the 'events' table?

CREATE TABLE events (id INT PRIMARY KEY, event_name VARCHAR(100), event_type VARCHAR(50), num_tickets_sold INT);

SELECT MAX(num_tickets_sold) AS max_tickets_sold FROM events;


Question: Generate PostgreSQL SQL for: What number is the player that played 1998-2001

CREATE TABLE table_10015132_21 (no INTEGER, years_in_toronto VARCHAR)

SELECT MIN(no) FROM table_10015132_21 WHERE years_in_toronto = '1998-2001';


Question: What is the average square footage of co-owned properties in the state of New York?

CREATE TABLE properties (id INT, state VARCHAR(20), size INT, co_owned BOOLEAN); INSERT INTO properties (id, state, size, co_owned) VALUES (1, 'New York', 1200, TRUE), (2, 'New York', 1500, FALSE), (3, 'New York', 1800, TRUE);

SELECT AVG(size) FROM properties WHERE state = 'New York' AND co_owned = TRUE;


Question: pgTAP test for Pgtap--Unpackaged--0.91.0 (assertion 654).

ALTER EXTENSION pgtap ADD FUNCTION throws_like ( TEXT, TEXT, TEXT );

Explanation: SQL assertion from pgTAP test suite for Pgtap--Unpackaged--0.91.0.


Question: Generate PostgreSQL SQL for: What was the away score when the home team was Melbourne?

CREATE TABLE table_name_84 (away_team VARCHAR, home_team VARCHAR)

SELECT away_team AS score FROM table_name_84 WHERE home_team = 'melbourne';


Question: What is the maximum number of public participations in a single initiative?

CREATE TABLE participations (initiative_id INT, num_participants INT); INSERT INTO participations (initiative_id, num_participants) VALUES (1, 500), (2, 700), (3, 300), (4, 800), (5, 600);

SELECT MAX(num_participants) FROM participations;


Question: Generate PostgreSQL SQL for: On what surface was Ivan Lendl a partner with a runner-up outcome and final score of 2–6, 6–7?

CREATE TABLE table_name_66 (surface VARCHAR, score_in_the_final VARCHAR, outcome VARCHAR, partner VARCHAR)

SELECT surface FROM table_name_66 WHERE outcome = 'runner-up' AND partner = 'ivan lendl' AND score_in_the_final = '2–6, 6–7';


Question: What is the sum of all flood resilience investments in the South and their respective average costs?

CREATE TABLE FloodResilience (id INT, project VARCHAR(20), region VARCHAR(20), cost FLOAT); INSERT INTO FloodResilience (id, project, region, cost) VALUES (1, 'FloodGate', 'South', 2000000.0), (2, 'Levee', 'South', 3000000.0), (3, 'FloodGate', 'South', 2500000.0);

SELECT project, SUM(cost) as total_cost FROM FloodResilience WHERE region = 'South' GROUP BY project;


Question: Generate PostgreSQL SQL for: What is the position of the player who's hometown is North Babylon, NY?

CREATE TABLE table_20785990_2 (position VARCHAR, home_town VARCHAR)

SELECT position FROM table_20785990_2 WHERE home_town = 'North Babylon, NY';


Question: Find the number of icebergs in the Arctic ocean larger than 10 km²

CREATE TABLE icebergs (id INT, name VARCHAR(255), size_km2 FLOAT);

SELECT COUNT(*) FROM icebergs WHERE size_km2 > 10 AND region = 'Arctic Ocean';


Question: Delete all unused autonomous buses in Boston.

CREATE TABLE public.buses (id SERIAL PRIMARY KEY, name TEXT, in_use BOOLEAN, city TEXT); INSERT INTO public.buses (name, in_use, city) VALUES ('Autonomous Bus 1', FALSE, 'Boston'), ('Autonomous Bus 2', TRUE, 'Boston');

DELETE FROM public.buses WHERE city = 'Boston' AND name LIKE 'Autonomous Bus%' AND in_use = FALSE;


Question: Find the number of articles published on investigative journalism topics in the last 6 months, grouped by month.

CREATE TABLE articles (id INT, title VARCHAR(255), publish_date DATE, topic VARCHAR(255)); INSERT INTO articles (id, title, publish_date, topic) VALUES (1, 'Investigative Article 1', '2022-01-01', 'investigative');

SELECT COUNT(*), DATE_FORMAT(publish_date, '%Y-%m') AS Month FROM articles WHERE topic = 'investigative' AND publish_date >= DATE_SUB(NOW(), INTERVAL 6 MONTH) GROUP BY Month;


Question: Generate PostgreSQL SQL for: What venue had less than 7.4 extra and the result of 4th?

CREATE TABLE table_name_58 (venue VARCHAR, extra VARCHAR, result VARCHAR)

SELECT venue FROM table_name_58 WHERE extra < 7.4 AND result = '4th';


Question: Find the minimum age of all animals in the 'vulnerable' status

CREATE TABLE animals (id INT, name VARCHAR(50), status VARCHAR(20), age INT); INSERT INTO animals (id, name, status, age) VALUES (1, 'Tiger', 'Endangered', 10); INSERT INTO animals (id, name, status, age) VALUES (2, 'Elephant', 'Vulnerable', 30); INSERT INTO animals (id, name, status, age) VALUES (3, 'Rhino', 'Critically Endangered', 5);

SELECT MIN(age) FROM animals WHERE status = 'Vulnerable';


Question: PL/pgSQL test: Pltcl Queries (example 5).

select tcl_record_arg(row('tkey', 42, 'ref2')::T_comp1, 'ref1');

Explanation: PL/pgSQL example from PostgreSQL source test for Pltcl Queries.


Question: What's the total number of communication satellites launched by the United States?

CREATE TABLE Satellite (Id INT, Name VARCHAR(100), LaunchDate DATETIME, Country VARCHAR(50), Function VARCHAR(50)); INSERT INTO Satellite (Id, Name, LaunchDate, Country, Function) VALUES (2, 'Intelsat 702', '1997-04-03', 'United States', 'Communications');

SELECT COUNT(*) FROM Satellite WHERE Country = 'United States' AND Function = 'Communications';


Question: Generate PostgreSQL SQL for: How many positions is player Tom Glavine?

CREATE TABLE table_21721351_18 (position VARCHAR, player VARCHAR)

SELECT COUNT(position) FROM table_21721351_18 WHERE player = 'Tom Glavine';


Question: Write the PL/pgSQL object from PostgreSQL regression test 'drop_if_exists' (example 148).

-- cleanup
DROP FUNCTION test_ambiguous_funcname(int);

Explanation: PL/pgSQL object from PostgreSQL core test for Drop If Exists.


Question: Generate PostgreSQL SQL for: When has a cause of gas explosion, a Death toll smaller than 63, and a Location of penygraig?

CREATE TABLE table_name_60 (date VARCHAR, location VARCHAR, cause VARCHAR, death_toll VARCHAR)

SELECT date FROM table_name_60 WHERE cause = 'gas explosion' AND death_toll < 63 AND location = 'penygraig';


Question: What is the average property size in the sustainable_urbanism table?

CREATE TABLE sustainable_urbanism (property_id INT, size FLOAT, location VARCHAR(255)); INSERT INTO sustainable_urbanism (property_id, size, location) VALUES (1, 1200, 'Eco City'), (2, 1500, 'Green Valley');

SELECT AVG(size) FROM sustainable_urbanism;


Question: Show a query using PostgreSQL contrib extension 'cube' (example 176).

Explanation: Example query from the 'cube' extension test/demo.


Question: Generate PostgreSQL SQL for: Name the opponent which has a home/away of home and date of july 27

CREATE TABLE table_name_9 (opponent VARCHAR, home_away VARCHAR, date VARCHAR)

SELECT opponent FROM table_name_9 WHERE home_away = 'home' AND date = 'july 27';


Question: What are the average safety scores for vehicles released in 2018 and 2019?

CREATE TABLE vehicle_safety_scores (make VARCHAR(100), model VARCHAR(100), safety_score INT, year INT);

SELECT AVG(safety_score) FROM vehicle_safety_scores WHERE year IN (2018, 2019) GROUP BY year;


Question: What is the minimum budget for a single public works project in the state of California?

CREATE TABLE project (id INT PRIMARY KEY, name TEXT, budget INT, status TEXT, city_id INT, FOREIGN KEY (city_id) REFERENCES city(id));

SELECT MIN(budget) FROM project WHERE city_id IN (SELECT id FROM city WHERE state = 'CA') AND status = 'Open';


Question: Generate PostgreSQL SQL for: What Per capita income has a Median family income of $50,755?

CREATE TABLE table_name_38 (per_capita_income VARCHAR, median_family_income VARCHAR)

SELECT per_capita_income FROM table_name_38 WHERE median_family_income = '$50,755';


Question: What is the average donation size by individual donors in the healthcare sector?

CREATE TABLE donors (id INT, name VARCHAR(50), amount INT, sector VARCHAR(20)); INSERT INTO donors (id, name, amount, sector) VALUES (1, 'John', 75, 'education'), (2, 'Jane', 120, 'health'), (3, 'Mike', 30, 'education'), (4, 'Olivia', 80, 'healthcare'), (5, 'Patrick', 180, 'healthcare');

SELECT AVG(amount) FROM donors WHERE sector = 'healthcare' AND id NOT IN (SELECT DISTINCT org_id FROM grants);


Question: Add a new wind turbine with id 5 and capacity 2000 in the 'renewable_energy' table

CREATE TABLE renewable_energy (id INT, type VARCHAR(50), capacity INT);

INSERT INTO renewable_energy (id, type, capacity) VALUES (5, 'wind turbine', 2000);


Question: Increase the rating of product 3 by 0.5.

CREATE TABLE products (product_id INT, rating FLOAT); INSERT INTO products (product_id, rating) VALUES (1, 4.5), (2, 3.2), (3, 4.8);

UPDATE products SET rating = rating + 0.5 WHERE product_id = 3;


Question: Generate PostgreSQL SQL for: Tell me the average final rank for loe more than 10 and point less than 43

CREATE TABLE table_name_8 (final_rank INTEGER, lose VARCHAR, point VARCHAR)

SELECT AVG(final_rank) FROM table_name_8 WHERE lose > 10 AND point < 43;


Question: Calculate the percentage of employees who received a promotion in the last 6 months, and display the result with two decimal places.

CREATE TABLE Employees (EmployeeID INT, PromotionDate DATE);

SELECT ROUND(COUNT(*) * 100.0 / (SELECT COUNT(*) FROM Employees) , 2) AS PromotionPercentage FROM Employees WHERE PromotionDate >= DATEADD(month, -6, GETDATE());


Question: Generate PostgreSQL SQL for: Which organisation type hires most research staff?

CREATE TABLE Research_Staff (employer_organisation_id VARCHAR); CREATE TABLE Organisations (organisation_type VARCHAR, organisation_id VARCHAR)

SELECT T1.organisation_type FROM Organisations AS T1 JOIN Research_Staff AS T2 ON T1.organisation_id = T2.employer_organisation_id GROUP BY T1.organisation_type ORDER BY COUNT(*) DESC LIMIT 1;


Question: PostgreSQL regression test 'window': Write the SELECT query (example 70).

SELECT sum(unique1) over (w range between unbounded preceding and current row exclude group),
	unique1, four
FROM tenk1 WHERE unique1 < 10 WINDOW w AS (order by four);

Explanation: Regression test for Window in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT sum(unique1) over (w range between unbounded preceding and current row exclude group),
	unique1, four
FROM tenk1 WHERE unique1 < 10 WINDOW w AS (order by four)) AS _sub;


Question: What is the maximum number of simultaneous high severity vulnerabilities that have been discovered in the past month?

CREATE TABLE vulnerability_timeline(id INT, severity VARCHAR(50), vulnerability_date DATE, vulnerabilities INT);

SELECT severity, MAX(vulnerabilities) as max_simultaneous_vulnerabilities FROM vulnerability_timeline WHERE severity = 'high' AND vulnerability_date > DATE(NOW()) - INTERVAL 30 DAY;


Question: pgTAP test for Privs (assertion 20).

CREATE OR REPLACE FUNCTION run_extra_fails() RETURNS SETOF TEXT LANGUAGE plpgsql AS $$
DECLARE
    allowed_privs TEXT[];
    test_privs    TEXT[] := '{}';
    missing_privs TEXT[] := '{}';
    tap           record;
    last_index    INTEGER;
BEGIN
    -- Test table failure.
    allowed_privs := _table_privs();
    last_index    := array_upper(allowed_privs, 1);
    FOR i IN 1..last_index - 2 LOOP
        test_privs := test_privs || allowed_privs[i];
    END LOOP;
    FOR i IN last_index - 1..last_index LOOP
        missing_privs := missing_privs || allowed_privs[i];
    END LOOP;

    FOR tap IN SELECT * FROM check_test(
        table_privs_are( 'ha', 'sometab', current_user, test_privs, 'whatever' ),
            false,
            'table_privs_are(sch, tab, role, some privs, desc)',
            'whatever',
            '    Extra privileges:
        ' || array_to_string(missing_privs, E'\n        ')
    ) AS b LOOP RETURN NEXT tap.b; END LOOP;

    FOR tap IN SELECT * FROM check_test(
            table_privs_are( 'sometab', current_user, test_privs, 'whatever' ),
            false,
            'table_privs_are(tab, role, some privs, desc)',
            'whatever',
            '    Extra privileges:
        ' || array_to_string(missing_privs, E'\n        ')
    ) AS b LOOP RETURN NEXT tap.b; END LOOP;
END;
$$;

Explanation: SQL assertion from pgTAP test suite for Privs.


Question: List the number of mental health appointments for each cultural competency level, in descending order.

CREATE TABLE CulturalCompetency (ID INT, Level TEXT); INSERT INTO CulturalCompetency (ID, Level) VALUES (1, 'Beginner'); INSERT INTO CulturalCompetency (ID, Level) VALUES (2, 'Intermediate'); INSERT INTO CulturalCompetency (ID, Level) VALUES (3, 'Advanced'); CREATE TABLE MentalHealthAppointment (AppointmentID INT, CulturalCompetencyID INT);

SELECT CulturalCompetencyID, COUNT(AppointmentID) as NumAppointments FROM MentalHealthAppointment GROUP BY CulturalCompetencyID ORDER BY NumAppointments DESC;


Question: Generate PostgreSQL SQL for: What 2007-08 season has marcianise as the city?

CREATE TABLE table_name_60 (city VARCHAR)

SELECT 2007 AS _08_season FROM table_name_60 WHERE city = 'marcianise';


Question: What percentage of sustainable fabric sourcing is done from African countries?

CREATE TABLE FabricSourcing (Brand VARCHAR(255), Country VARCHAR(255), FabricType VARCHAR(255), Quantity INT); INSERT INTO FabricSourcing (Brand, Country, FabricType, Quantity) VALUES ('BrandD', 'EG', 'Organic Cotton', 5000), ('BrandE', 'NG', 'Recycled Polyester', 7000), ('BrandF', 'KE', 'Tencel', 6000);

SELECT (COUNT(*) * 100.0 / (SELECT COUNT(*) FROM FabricSourcing)) AS Percentage FROM FabricSourcing WHERE Country IN ('EG', 'NG', 'KE');


Question: Generate PostgreSQL SQL for: Which member is from the state of SA and the grey electorate?

CREATE TABLE table_name_74 (member VARCHAR, state VARCHAR, electorate VARCHAR)

SELECT member FROM table_name_74 WHERE state = 'sa' AND electorate = 'grey';


Question: What is the distribution of artists by the medium they work in?

CREATE TABLE artists (id INT, name VARCHAR(255), birth_date DATE, medium VARCHAR(50));

SELECT medium, COUNT(*) as artist_count FROM artists GROUP BY medium;


Question: Generate PostgreSQL SQL for: What county is the township of Osborn in?

CREATE TABLE table_18600760_15 (county VARCHAR, township VARCHAR)

SELECT county FROM table_18600760_15 WHERE township = 'Osborn';


Question: Generate PostgreSQL SQL for: What is the location of the 200m backstroke?

CREATE TABLE table_name_75 (location VARCHAR, event VARCHAR)

SELECT location FROM table_name_75 WHERE event = '200m backstroke';


Question: Generate PostgreSQL SQL for: List all opponents from the 4-4 scoring game.

CREATE TABLE table_24561550_1 (opponent VARCHAR, record VARCHAR)

SELECT opponent FROM table_24561550_1 WHERE record = '4-4';


Question: Which fair trade organizations are involved in shoe production in Portugal?

CREATE TABLE Shoes (id INT, name VARCHAR(255), style VARCHAR(255), price DECIMAL(10, 2), country VARCHAR(255), fair_trade_org VARCHAR(255)); INSERT INTO Shoes (id, name, style, price, country, fair_trade_org) VALUES (1, 'Sneakers', 'Casual', 79.99, 'Portugal', 'FTA Portugal'); INSERT INTO Shoes (id, name, style, price, country, fair_trade_org) VALUES (2, 'Sandals', 'Summer', 49.99, 'Portugal', 'FTA Iberia');

SELECT DISTINCT fair_trade_org FROM Shoes WHERE country = 'Portugal' AND fair_trade_org IS NOT NULL;


Question: How many startups have been founded by individuals with disabilities in the last 3 years?

CREATE TABLE founders(id INT, startup_id INT, founder_name TEXT, founder_identity TEXT); INSERT INTO founders VALUES (1, 1, 'John Doe', 'White Male'); INSERT INTO founders VALUES (2, 1, 'Jane Smith', 'Female Asian'); INSERT INTO founders VALUES (3, 2, 'Alice Johnson', 'Black Female');

SELECT COUNT(*) FROM founders JOIN startups ON founders.startup_id = startups.id WHERE founders.founder_identity = 'Individual with Disability' AND startups.founding_year >= YEAR(CURRENT_DATE) - 3;


Question: Generate PostgreSQL SQL for: What is the result of the europe/africa group i, round robin game in Murcia (esp) before 1999?

CREATE TABLE table_name_9 (result VARCHAR, competition VARCHAR, location VARCHAR, year VARCHAR)

SELECT result FROM table_name_9 WHERE location = 'murcia (esp)' AND year < 1999 AND competition = 'europe/africa group i, round robin';


Question: Populate the games table with new data

CREATE TABLE games (game_id INT PRIMARY KEY, name VARCHAR(50), genre VARCHAR(50), rating DECIMAL(3,2));

INSERT INTO games (game_id, name, genre, rating) VALUES (1, 'Apex Legends', 'Battle Royale', 8.5), (2, 'Valorant', 'First Person Shooter', 8.3), (3, 'Among Us', 'Party Game', 8.8);


Question: How many fans are from each region in the fan_demographics table?

CREATE TABLE fan_demographics (fan_id INT, fan_name VARCHAR(50), region VARCHAR(50)); INSERT INTO fan_demographics (fan_id, fan_name, region) VALUES (1, 'FanA', 'North America'), (2, 'FanB', 'South America'), (3, 'FanC', 'Asia'), (4, 'FanD', 'Europe');

SELECT region, COUNT(*) as num_fans FROM fan_demographics GROUP BY region;


Question: Generate PostgreSQL SQL for: Show names for all employees who have certificates on both Boeing 737-800 and Airbus A340-300.

CREATE TABLE Employee (name VARCHAR, eid VARCHAR); CREATE TABLE Certificate (eid VARCHAR, aid VARCHAR); CREATE TABLE Aircraft (aid VARCHAR, name VARCHAR)

SELECT T1.name FROM Employee AS T1 JOIN Certificate AS T2 ON T1.eid = T2.eid JOIN Aircraft AS T3 ON T3.aid = T2.aid WHERE T3.name = 'Boeing 737-800' INTERSECT SELECT T1.name FROM Employee AS T1 JOIN Certificate AS T2 ON T1.eid = T2.eid JOIN Aircraft AS T3 ON T3.aid = T2.aid WHERE T3.name = 'Airbus A340-300';


Question: Generate PostgreSQL SQL for: What is Moondancer's Primary Military Speciality?

CREATE TABLE table_name_39 (primary_military_speciality VARCHAR, code_name VARCHAR)

SELECT primary_military_speciality FROM table_name_39 WHERE code_name = 'moondancer';


Question: Generate PostgreSQL SQL for: What is the content of the Television service of Vesti?

CREATE TABLE table_name_58 (content VARCHAR, television_service VARCHAR)

SELECT content FROM table_name_58 WHERE television_service = 'vesti';


Question: Generate PostgreSQL SQL for: Which highest Overall has a Pick # of 4, and a Round larger than 7?

CREATE TABLE table_name_65 (overall INTEGER, pick__number VARCHAR, round VARCHAR)

SELECT MAX(overall) FROM table_name_65 WHERE pick__number = 4 AND round > 7;


Question: Count the number of patients who improved after therapy in the United States?

CREATE TABLE patient_outcomes (patient_id INT, improvement_status VARCHAR(255), country VARCHAR(255)); INSERT INTO patient_outcomes (patient_id, improvement_status, country) VALUES (1, 'Improved', 'USA'); INSERT INTO patient_outcomes (patient_id, improvement_status, country) VALUES (2, 'Not Improved', 'USA');

SELECT COUNT(*) FROM patient_outcomes WHERE improvement_status = 'Improved' AND country = 'USA';


Question: Generate PostgreSQL SQL for: Which title's genre was jazz when it was nominated in 1996?

CREATE TABLE table_name_15 (title VARCHAR, year VARCHAR, genre VARCHAR, result VARCHAR)

SELECT title FROM table_name_15 WHERE genre = 'jazz' AND result = 'nominated' AND year = '1996';


Question: Generate PostgreSQL SQL for: WHat is the Valency change of associative type?

CREATE TABLE table_name_1 (valency_change VARCHAR, type VARCHAR)

SELECT valency_change FROM table_name_1 WHERE type = 'associative';


Question: Show a query using PostgreSQL contrib extension 'cube' (example 123).


Question: Generate PostgreSQL SQL for: How many registed students do each course have? List course name and the number of their registered students?

CREATE TABLE students (student_id VARCHAR); CREATE TABLE courses (course_name VARCHAR, course_id VARCHAR); CREATE TABLE student_course_registrations (course_id VARCHAR, student_id VARCHAR)

SELECT T3.course_name, COUNT(*) FROM students AS T1 JOIN student_course_registrations AS T2 ON T1.student_id = T2.student_id JOIN courses AS T3 ON T2.course_id = T3.course_id GROUP BY T2.course_id;


Question: How many impact investments were made by Blue Capital in regions with high poverty rates?

CREATE TABLE Blue_Capital (id INT, region VARCHAR(20), impact_investment FLOAT); INSERT INTO Blue_Capital (id, region, impact_investment) VALUES (1, 'Africa', 200000), (2, 'Asia', 300000);

SELECT SUM(impact_investment) FROM Blue_Capital WHERE region IN ('Africa', 'Asia');


Question: Generate PostgreSQL SQL for: In 1900 with 62 wins and a win percentage less than 0.457, what was the GB [c]?

CREATE TABLE table_name_98 (gb_ VARCHAR, c_ VARCHAR, reds_season VARCHAR, win_percentage VARCHAR, wins VARCHAR)

SELECT gb_[c_] FROM table_name_98 WHERE win_percentage < 0.457 AND wins = 62 AND reds_season = 1900;


Question: What is the maximum calories burned in a single workout by members aged 40-50?

CREATE TABLE workout_data (member_id INT, calories FLOAT, workout_date DATE); INSERT INTO workout_data (member_id, calories, workout_date) VALUES (1, 300, '2021-01-15'), (2, 450, '2022-03-28');

SELECT MAX(calories) FROM workout_data JOIN members ON workout_data.member_id = members.member_id WHERE members.age BETWEEN 40 AND 50;


Question: PostgreSQL regression test 'jsonb_jsonpath': Write the SELECT query (example 534).

SELECT count(*) FROM (select jsonb_path_query('"12:34:56"', '$.time().string()')) AS _sub;


Question: What is the total waste generation by material type in Tokyo?

CREATE TABLE waste_generation (location VARCHAR(50), material_type VARCHAR(50), quantity INT); INSERT INTO waste_generation (location, material_type, quantity) VALUES ('Tokyo', 'Plastic', 1200), ('Tokyo', 'Paper', 1800), ('Tokyo', 'Metal', 1400);

SELECT material_type, SUM(quantity) FROM waste_generation WHERE location = 'Tokyo' GROUP BY material_type;


Question: Generate PostgreSQL SQL for: What date has dallas cowboys as the opponent?

CREATE TABLE table_name_91 (date VARCHAR, opponent VARCHAR)

SELECT date FROM table_name_91 WHERE opponent = 'dallas cowboys';


Question: Write the DML statement from PostgreSQL regression test 'multirangetypes' (example 528).

insert into float8multirange_test values(float8multirange(float8range(-100.00007, '1.111113e9')), 42);

Explanation: DML from PostgreSQL core regression test for Multirangetypes.


Question: What is the average length of dams built between 1950 and 1960?

CREATE TABLE Dams (name TEXT, year INT, length FLOAT, location TEXT);

SELECT AVG(length) FROM Dams WHERE year BETWEEN 1950 AND 1960;


Question: What is the average cost of materials for bridge construction projects in the state of California?

CREATE TABLE bridge (id INT, name TEXT, state TEXT, cost FLOAT); INSERT INTO bridge (id, name, state, cost) VALUES (1, 'Bridge A', 'California', 5000000); INSERT INTO bridge (id, name, state, cost) VALUES (2, 'Bridge B', 'California', 7000000);

SELECT AVG(cost) FROM bridge WHERE state = 'California' AND name LIKE '%bridge%';


Question: Write the SQL definition from PostgreSQL contrib extension 'contrib' (item 6).

CREATE FUNCTION heap_page_item_attrs(
    IN page bytea,
    IN rel_oid regclass,
    OUT lp smallint,
    OUT lp_off smallint,
    OUT lp_flags smallint,
    OUT lp_len smallint,
    OUT t_xmin xid,
    OUT t_xmax xid,
    OUT t_field3 int4,
    OUT t_ctid tid,
    OUT t_infomask2 integer,
    OUT t_infomask integer,
    OUT t_hoff smallint,
    OUT t_bits text,
    OUT t_oid oid,
    OUT t_attrs bytea[]
    )
RETURNS SETOF record AS $$
SELECT * from heap_page_item_attrs(page, rel_oid, false);
$$ LANGUAGE SQL;

Explanation: SQL definition from the 'contrib' PostgreSQL contrib extension.


Question: What is the total number of visitors from North America who attended all exhibitions?

CREATE TABLE Exhibitions (ExhibitionID INT, ExhibitionName VARCHAR(255), Country VARCHAR(255)); INSERT INTO Exhibitions (ExhibitionID, ExhibitionName, Country) VALUES (1, 'Contemporary Art Exhibition', 'USA'), (2, 'Modern Art Exhibition', 'Canada'), (3, 'Impressionist Exhibition', 'Mexico');

SELECT COUNT(DISTINCT Country) FROM Exhibitions WHERE Country IN ('USA', 'Canada', 'Mexico');


Question: Generate PostgreSQL SQL for: How many movies were made before 2000?

SELECT COUNT(*) FROM Movie WHERE YEAR < 2000;


Question: How many individuals have been incarcerated in the past month, broken down by the type of facility and the number of prior offenses?

CREATE TABLE incarceration_records (id INT, facility_type TEXT, num_prior_offenses INT, incarceration_date DATE);

SELECT facility_type, num_prior_offenses, COUNT(*) FROM incarceration_records WHERE incarceration_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH) GROUP BY facility_type, num_prior_offenses;


Question: What is the total drug approval cost for 'DrugE' in '2020'?

CREATE TABLE approvals (drug_name TEXT, year INTEGER, cost INTEGER); INSERT INTO approvals (drug_name, year, cost) VALUES ('DrugE', 2020, 3000000);

SELECT cost FROM approvals WHERE drug_name = 'DrugE' AND year = 2020;


Question: What was the total number of tickets sold for theater performances in Q1 2022?

CREATE TABLE Events (EventID INT, EventType VARCHAR(50), StartDate DATE, EndDate DATE); INSERT INTO Events (EventID, EventType, StartDate, EndDate) VALUES (1, 'Dance Performance', '2022-04-01', '2022-04-03'), (2, 'Theater Performance', '2022-01-01', '2022-01-31'); CREATE TABLE Tickets (TicketID INT, EventID INT, Quantity INT); INSERT INTO Tickets (TicketID, EventID, Quantity) VALUES (1, 1, 100), (2, 2, 200);

SELECT SUM(Quantity) FROM Events INNER JOIN Tickets ON Events.EventID = Tickets.EventID WHERE Events.EventType = 'Theater Performance' AND QUARTER(StartDate) = 1;


Question: What is the average monetary aid received per family in Central America, grouped by disaster type, ordered by the highest average?

CREATE TABLE disaster_response (family_id INT, region VARCHAR(20), disaster_type VARCHAR(20), amount_aid FLOAT); INSERT INTO disaster_response (family_id, region, disaster_type, amount_aid) VALUES (1, 'Central America', 'Flood', 5000), (2, 'Central America', 'Earthquake', 7000), (3, 'Central America', 'Flood', 6000);

SELECT disaster_type, AVG(amount_aid) as avg_aid FROM disaster_response WHERE region = 'Central America' GROUP BY disaster_type ORDER BY avg_aid DESC;


Question: Delete the garment records with a price less than 20.00 or greater than 40.00 in the Garment table.

CREATE TABLE Garment (garment_id INT PRIMARY KEY, garment_name VARCHAR(50), category VARCHAR(50), price DECIMAL(10,2)); INSERT INTO Garment (garment_id, garment_name, category, price) VALUES (1, 'Cotton T-Shirt', 'Tops', 20.00), (2, 'Jeans Pants', 'Bottoms', 40.00), (3, 'Linen Blouse', 'Tops', 30.00);

DELETE FROM Garment WHERE price < 20.00 OR price > 40.00;


Question: Find the total number of marine species recorded in the North Atlantic and South Atlantic.

CREATE TABLE marine_species (id INT, species_name VARCHAR(255), region VARCHAR(255)); INSERT INTO marine_species (id, species_name, region) VALUES (1, 'Oceanic whitetip shark', 'North Atlantic');

(SELECT COUNT(*) FROM marine_species WHERE region IN ('North Atlantic', 'South Atlantic'));


Question: Generate PostgreSQL SQL for: How many feet in length are there when the length is 106.1 meters?

CREATE TABLE table_16226584_1 (length_feet VARCHAR, length_meters VARCHAR)

SELECT COUNT(length_feet) FROM table_16226584_1 WHERE length_meters = '106.1';


Question: What is the total number of users who have posted at least one post and have at least one follower in the 'social_media' and 'user_followers' tables?

CREATE TABLE social_media (user_id INT, posts_count INT); CREATE TABLE user_followers (user_id INT, followers_count INT);

SELECT COUNT(DISTINCT sm.user_id) FROM social_media sm INNER JOIN user_followers uf ON sm.user_id = uf.user_id WHERE sm.posts_count > 0 AND uf.followers_count > 0;


Question: Generate PostgreSQL SQL for: Which Away team played when they had a Crowd of over 29,000 people?

CREATE TABLE table_name_14 (away_team VARCHAR, crowd INTEGER)

SELECT away_team FROM table_name_14 WHERE crowd > 29 OFFSET 000;


Question: Show the number of trips taken by each passenger on the 'Green Line' during the month of January 2023

CREATE TABLE passengers (passenger_id INT, passenger_name VARCHAR(20)); CREATE TABLE passenger_trips (trip_id INT, passenger_id INT, route_id INT, trip_date DATE);

SELECT passengers.passenger_name, COUNT(passenger_trips.trip_id) FROM passengers JOIN passenger_trips ON passengers.passenger_id = passenger_trips.passenger_id WHERE passenger_trips.route_id = 2 AND passenger_trips.trip_date BETWEEN '2023-01-01' AND '2023-01-31' GROUP BY passengers.passenger_id, passengers.passenger_name;


Question: Generate PostgreSQL SQL for: Can you tell me the sum of Goals against that has the Goals for larger than 10, and the Position of 3, and the Wins smaller than 6?

CREATE TABLE table_name_14 (goals_against INTEGER, wins VARCHAR, goals_for VARCHAR, position VARCHAR)

SELECT SUM(goals_against) FROM table_name_14 WHERE goals_for > 10 AND position = 3 AND wins < 6;


Question: Generate PostgreSQL SQL for: What is the sum of FA Cup goals when there are 19 league goals?

CREATE TABLE table_name_5 (fa_cup_goals INTEGER, league_goals VARCHAR)

SELECT SUM(fa_cup_goals) FROM table_name_5 WHERE league_goals = '19';


Question: Insert a new record into the "MarinePollution" table with values (1, 'Asia', 'Oil Spill')

CREATE TABLE MarinePollution (Id INT, Region VARCHAR(20), Type VARCHAR(10));

INSERT INTO MarinePollution (Id, Region, Type) VALUES (1, 'Asia', 'Oil Spill');


Question: Find the youngest female patient in the 'patients' table.

CREATE TABLE patients (patient_id INT, name VARCHAR(50), age INT, gender VARCHAR(10), condition VARCHAR(50)); INSERT INTO patients (patient_id, name, age, gender, condition) VALUES (1, 'John Doe', 30, 'Male', 'Anxiety Disorder'); INSERT INTO patients (patient_id, name, age, gender, condition) VALUES (2, 'Jane Smith', 35, 'Female', 'Depression'); INSERT INTO patients (patient_id, name, age, gender, condition) VALUES (4, 'Bob Brown', 45, 'Male', 'Depression');

SELECT * FROM patients WHERE gender = 'Female' ORDER BY age ASC LIMIT 1;


Question: Generate PostgreSQL SQL for: What's the least enrolled when the mascot was the Trojans?

CREATE TABLE table_name_8 (enrollment INTEGER, mascot VARCHAR)

SELECT MIN(enrollment) FROM table_name_8 WHERE mascot = 'trojans';


Question: Update the organic_produce to false for record with restaurant_id 123 in the sustainable_sourcing table

CREATE TABLE sustainable_sourcing (restaurant_id INT, organic_produce BOOLEAN);

UPDATE sustainable_sourcing SET organic_produce = false WHERE restaurant_id = 123;


Question: What is the average rating for public safety and waste management in CityX?

CREATE TABLE Feedback (City VARCHAR(20), Category VARCHAR(20), Rating INT); INSERT INTO Feedback (City, Category, Rating) VALUES ('CityX', 'Public Safety', 7); INSERT INTO Feedback (City, Category, Rating) VALUES ('CityX', 'Waste Management', 8);

SELECT City, AVG(CASE WHEN Category = 'Public Safety' THEN Rating ELSE 0 END) AS 'Public Safety Avg Rating', AVG(CASE WHEN Category = 'Waste Management' THEN Rating ELSE 0 END) AS 'Waste Management Avg Rating' FROM Feedback WHERE City = 'CityX' GROUP BY City;


Question: Generate PostgreSQL SQL for: Which position has new Jersey Devils as the nhl team?

CREATE TABLE table_2897457_3 (position VARCHAR, nhl_team VARCHAR)

SELECT position FROM table_2897457_3 WHERE nhl_team = 'New Jersey Devils';


Question: Show the average population size for each species in the species table.

CREATE TABLE species (id INT PRIMARY KEY, name VARCHAR(50), population INT);

SELECT name, AVG(population) as avg_population FROM species GROUP BY name;


Question: What is the total production quantity (in metric tons) of Europium from the mine with the ID 2 for the year 2018?

CREATE TABLE production (id INT, mine_id INT, year INT, element TEXT, production_quantity INT); INSERT INTO production (id, mine_id, year, element, production_quantity) VALUES (1, 2, 2018, 'Europium', 120), (2, 3, 2018, 'Europium', 180), (3, 4, 2018, 'Europium', 240), (4, 2, 2018, 'Gadolinium', 300), (5, 3, 2018, 'Gadolinium', 420), (6, 4, 2018, 'Gadolinium', 540);

SELECT SUM(production_quantity) FROM production WHERE mine_id = 2 AND year = 2018 AND element = 'Europium';


Question: What is the average cultural competency score for mental health providers in each state?

CREATE TABLE mental_health_providers (id INT, name VARCHAR(50), state VARCHAR(50), cultural_competency_score DECIMAL(3,2)); INSERT INTO mental_health_providers (id, name, state, cultural_competency_score) VALUES (1, 'Dr. Sarah Johnson', 'California', 4.75), (2, 'Dr. Michael Davis', 'Texas', 4.50), (3, 'Dr. Emily Garcia', 'Florida', 4.25);

SELECT state, AVG(cultural_competency_score) FROM mental_health_providers GROUP BY state;


Question: PostgreSQL regression test 'pg_ndistinct': Write the SELECT query (example 58).

SELECT * FROM pg_input_error_info('[{"attributes" : [2,3], "ndistinct" : [null]}]', 'pg_ndistinct');

Explanation: Regression test for Pg Ndistinct in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT * FROM pg_input_error_info('[{"attributes" : [2,3], "ndistinct" : [null]}]', 'pg_ndistinct')) AS _sub;


Question: Which investment strategies have a return on investment (ROI) greater than 5% and have at least one client utilizing them?

CREATE TABLE InvestmentStrategies (StrategyID int, StrategyName varchar(50), ROI decimal(5,2)); INSERT INTO InvestmentStrategies (StrategyID, StrategyName, ROI) VALUES (1, 'Conservative', 2), (2, 'Moderate', 3), (3, 'Aggressive', 5), (4, 'High Risk', 10); CREATE TABLE ClientStrategies (ClientID int, StrategyID int); INSERT INTO ClientStrategies (ClientID, StrategyID) VALUES (10, 1), (11, 1), (12, 2), (13, 3), (14, 2), (15, 4);

SELECT i.StrategyName, i.ROI FROM InvestmentStrategies i INNER JOIN ClientStrategies cs ON i.StrategyID = cs.StrategyID WHERE i.ROI > 5 GROUP BY i.StrategyName, i.ROI HAVING COUNT(cs.ClientID) > 0;


Question: What is the total number of cultural heritage sites in Spain that were built before the year 1800?

CREATE TABLE CulturalHeritageSites (name VARCHAR(50), location VARCHAR(20), year INT);

SELECT COUNT(*) FROM CulturalHeritageSites WHERE location = 'Spain' AND year < 1800;


Question: What's the average age of players who play sports games in South America?

CREATE TABLE Players (PlayerID INT, Age INT, Gender VARCHAR(10), Location VARCHAR(20)); INSERT INTO Players (PlayerID, Age, Gender, Location) VALUES (1, 22, 'Female', 'Brazil'); INSERT INTO Players (PlayerID, Age, Gender, Location) VALUES (2, 35, 'Male', 'Argentina'); CREATE TABLE Games (GameID INT, GameName VARCHAR(20), Genre VARCHAR(20)); INSERT INTO Games (GameID, GameName, Genre) VALUES (1, 'Soccer Star', 'Sports');

SELECT AVG(Players.Age) FROM Players INNER JOIN Games ON Players.Location = Games.GameName WHERE Games.Genre = 'Sports' AND Players.Location IN ('Brazil', 'Argentina');


Question: how many wildlife habitats are there in each region?

CREATE TABLE wildlife_habitats (id INT, region VARCHAR(255), habitat_type VARCHAR(255));

SELECT region, COUNT(DISTINCT id) as num_habitats FROM wildlife_habitats GROUP BY region;


Question: PostgreSQL regression test 'copy2': Write the SELECT query (example 240).

Explanation: Regression test for Copy2 in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT * FROM check_ign_err2) AS _sub;


Question: Generate PostgreSQL SQL for: What is the home city for the team whose home ground is dnb nor arena?

CREATE TABLE table_2522473_1 (home_city VARCHAR, home_ground VARCHAR)

SELECT home_city FROM table_2522473_1 WHERE home_ground = 'DnB Nor Arena';


Question: Generate PostgreSQL SQL for: When did they play at the wachovia center?

CREATE TABLE table_name_75 (date VARCHAR, location_attendance VARCHAR)

SELECT date FROM table_name_75 WHERE location_attendance = 'wachovia center';


Question: Write the DDL statement from PostgreSQL regression test 'indexing' (example 17).

create index concurrently on idxpart (a);

Explanation: DDL from PostgreSQL core regression test for Indexing.


Question: Generate PostgreSQL SQL for: What was the attendance when North Melbourne was the away team?

CREATE TABLE table_name_77 (crowd INTEGER, away_team VARCHAR)

SELECT AVG(crowd) FROM table_name_77 WHERE away_team = 'north melbourne';


Question: What is the total number of climate finance projects in Southeast Asia, and how many of them were successful?

CREATE TABLE climate_finance (region VARCHAR(50), project VARCHAR(50), success BOOLEAN); INSERT INTO climate_finance (region, project, success) VALUES ('Southeast Asia', 'Solar Power Plant', TRUE), ('Southeast Asia', 'Wind Farm', FALSE);

SELECT COUNT(*), SUM(success) FROM climate_finance WHERE region = 'Southeast Asia';


Question: Generate PostgreSQL SQL for: what score has a location and attendance of montreal forum and the date of may 10?

CREATE TABLE table_name_49 (score VARCHAR, location_attendance VARCHAR, date VARCHAR)

SELECT score FROM table_name_49 WHERE location_attendance = 'montreal forum' AND date = 'may 10';


Question: What is the average duration of space missions for each astronaut?

CREATE TABLE astronauts (id INT, name VARCHAR(50));CREATE TABLE missions (id INT, astronaut_id INT, duration INT); INSERT INTO astronauts VALUES (1, 'Melissa Lewis'); INSERT INTO missions VALUES (1, 1), (2, 1), (3, 1); INSERT INTO missions VALUES (1, 1), (2, 1), (3, 1), (4, 1);

SELECT astronauts.name, AVG(missions.duration) as avg_duration FROM astronauts INNER JOIN missions ON astronauts.id = missions.astronaut_id GROUP BY astronauts.name;


Question: Generate PostgreSQL SQL for: What is the score of the home team that played Collingwood?

CREATE TABLE table_name_70 (home_team VARCHAR, away_team VARCHAR)

SELECT home_team AS score FROM table_name_70 WHERE away_team = 'collingwood';


Question: What is the average climate finance provided to Indigenous communities in Canada for climate communication initiatives between 2016 and 2020?

CREATE TABLE climate_finance (year INT, community VARCHAR(50), initiative VARCHAR(50), amount FLOAT); INSERT INTO climate_finance (year, community, initiative, amount) VALUES (2016, 'Indigenous community in Canada', 'climate communication', 25000);

SELECT AVG(amount) FROM climate_finance WHERE initiative = 'climate communication' AND community LIKE '%Indigenous community in Canada%' AND year BETWEEN 2016 AND 2020;


Question: Generate PostgreSQL SQL for: What is the status of the institution that was founded in 1996?

CREATE TABLE table_name_64 (status VARCHAR, founded VARCHAR)

SELECT status FROM table_name_64 WHERE founded = 1996;


Question: Generate PostgreSQL SQL for: Which player played 2004-05

CREATE TABLE table_11545282_18 (player VARCHAR, years_for_jazz VARCHAR)

SELECT player FROM table_11545282_18 WHERE years_for_jazz = '2004-05';


Question: pgTAP test for Pgtap--Unpackaged--0.91.0 (assertion 210).

ALTER EXTENSION pgtap ADD FUNCTION has_check ( NAME, TEXT );


Question: Delete a soldier record from the 'soldiers' table with ID 102

CREATE TABLE soldiers (id INT PRIMARY KEY, name VARCHAR(50), rank VARCHAR(50), branch VARCHAR(50)); INSERT INTO soldiers (id, name, rank, branch) VALUES (102, 'Jane Doe', 'Lieutenant', 'Navy');


Question: Generate PostgreSQL SQL for: Which English has Plautdietsch of aupel?

CREATE TABLE table_name_64 (english VARCHAR, plautdietsch VARCHAR)

SELECT english FROM table_name_64 WHERE plautdietsch = 'aupel';


Question: Generate PostgreSQL SQL for: Gold of 0, and a Silver smaller than 3, and a Rank larger than 9, and a Total of 1 has how many numbers of bronze?

CREATE TABLE table_name_1 (bronze VARCHAR, total VARCHAR, rank VARCHAR, gold VARCHAR, silver VARCHAR)

SELECT COUNT(bronze) FROM table_name_1 WHERE gold = 0 AND silver < 3 AND rank > 9 AND total = 1;


Question: Generate PostgreSQL SQL for: What Album has a Year that's larger than 2001?

CREATE TABLE table_name_39 (album VARCHAR, year INTEGER)

SELECT album FROM table_name_39 WHERE year > 2001;


Question: Which artists have released music under multiple genres?

CREATE TABLE artist_genre (artist_id INT, artist_name VARCHAR(255), genre VARCHAR(255)); CREATE TABLE artist (artist_id INT, artist_name VARCHAR(255));

SELECT artist_name FROM artist_genre GROUP BY artist_name HAVING COUNT(DISTINCT genre) > 1;


Question: Generate PostgreSQL SQL for: What year did the term end for those elected in 1990

CREATE TABLE table_1602620_1 (term_ended VARCHAR, elected VARCHAR)

SELECT term_ended FROM table_1602620_1 WHERE elected = 1990;


Question: Find the maximum quantity of products in the 'furniture' category

CREATE TABLE products (product_id INT, category VARCHAR(20), quantity INT); INSERT INTO products (product_id, category, quantity) VALUES (1, 'furniture', 25), (2, 'furniture', 50), (3, 'furniture', 75);

SELECT MAX(quantity) FROM products WHERE category = 'furniture';


Question: Generate PostgreSQL SQL for: Name the pole position for belgian grand prix

CREATE TABLE table_name_75 (pole_position VARCHAR, grand_prix VARCHAR)

SELECT pole_position FROM table_name_75 WHERE grand_prix = 'belgian grand prix';


Question: What is the average waiting time of cargo ships from African countries at the Port of Los Angeles?

CREATE TABLE ports (port_id INT, port_name VARCHAR(100), country VARCHAR(100)); INSERT INTO ports (port_id, port_name, country) VALUES (1, 'Port of Los Angeles', 'USA'); CREATE TABLE cargo_ships (ship_id INT, ship_name VARCHAR(100), port_id INT, waiting_time INT); INSERT INTO cargo_ships (ship_id, ship_name, port_id, waiting_time) VALUES (1, 'African Ship 1', 1, 200), (2, 'African Ship 2', 1, 250), (3, 'African Ship 3', 1, 300);

SELECT AVG(waiting_time) FROM cargo_ships WHERE country = 'Africa';


Question: Generate PostgreSQL SQL for: what is the owner of the c501

CREATE TABLE table_name_2 (owner VARCHAR, locomotive VARCHAR)

SELECT owner FROM table_name_2 WHERE locomotive = 'c501';


Question: How many crimes were committed in each neighborhood for the year 2020?

CREATE TABLE neighborhoods (id INT, name TEXT, district TEXT); INSERT INTO neighborhoods (id, name, district) VALUES (1, 'Downtown', 'City Center'), (2, 'Richfield', 'North District'); CREATE TABLE crimes (id INT, neighborhood_id INT, type TEXT, year INT, month INT, day INT); INSERT INTO crimes (id, neighborhood_id, type, year, month, day) VALUES (1, 1, 'Theft', 2020, 1, 1), (2, 1, 'Assault', 2019, 12, 31), (3, 2, 'Burglary', 2020, 2, 14);

SELECT n.name, c.type, COUNT(c.id) as total_crimes FROM neighborhoods n JOIN crimes c ON n.id = c.neighborhood_id WHERE c.year = 2020 GROUP BY n.id, c.type;


Question: Generate PostgreSQL SQL for: What is the most draws when goals against are more than 33, losses are 13 and goals for is less than 51?

CREATE TABLE table_name_1 (draws INTEGER, goals_for VARCHAR, goals_against VARCHAR, losses VARCHAR)

SELECT MAX(draws) FROM table_name_1 WHERE goals_against > 33 AND losses = 13 AND goals_for < 51;


Question: What is the average rating of Gluten-free products?

CREATE TABLE products (product_id INT, name VARCHAR(255), rating DECIMAL(2,1), gluten_free BOOLEAN);

SELECT AVG(rating) FROM products WHERE gluten_free = TRUE;


Question: Write the DML statement from PostgreSQL regression test 'updatable_views' (example 40).

Explanation: DML from PostgreSQL core regression test for Updatable Views.


Question: Generate PostgreSQL SQL for: In what even was the compulsory dance scored 23.75?

CREATE TABLE table_22644589_4 (event VARCHAR, compulsory_dance__cd_ VARCHAR)

SELECT event FROM table_22644589_4 WHERE compulsory_dance__cd_ = '23.75';


Question: What is the average weight of packages shipped to Texas from the New York warehouse?

CREATE TABLE Warehouse (id INT, name VARCHAR(255)); INSERT INTO Warehouse (id, name) VALUES (1, 'New York'), (2, 'Texas'); CREATE TABLE Packages (id INT, weight FLOAT, warehouse_id INT, shipment_date DATE); INSERT INTO Packages (id, weight, warehouse_id, shipment_date) VALUES (1, 5.6, 1, '2021-01-01'), (2, 7.2, 1, '2021-01-02'), (3, 3.1, 2, '2021-01-03');

SELECT AVG(weight) FROM Packages WHERE warehouse_id = (SELECT id FROM Warehouse WHERE name = 'Texas') AND shipment_date BETWEEN '2021-01-01' AND '2021-12-31';


Question: What is the number of financial capability training sessions conducted per region?

CREATE TABLE sessions (region VARCHAR(50), session_date DATE);

SELECT region, COUNT(*) FROM sessions GROUP BY region;


Question: Generate PostgreSQL SQL for: How many entries are shown for entered at 21:09?

CREATE TABLE table_29692554_2 (entered VARCHAR, time VARCHAR)

SELECT COUNT(entered) FROM table_29692554_2 WHERE time = '21:09';


Question: What is the total R&D expenditure for each disease area?

CREATE TABLE rd_expenditure (drug_name TEXT, disease_area TEXT, rd_cost INTEGER); INSERT INTO rd_expenditure (drug_name, disease_area, rd_cost) VALUES ('DrugA', 'Oncology', 20000000), ('DrugB', 'Cardiovascular', 15000000), ('DrugC', 'Oncology', 30000000), ('DrugD', 'Neurology', 25000000);

SELECT disease_area, SUM(rd_cost) FROM rd_expenditure GROUP BY disease_area;


Question: What is the average veteran unemployment rate for the last 12 months, rounded to the nearest integer?

CREATE TABLE veteran_unemployment (unemployment_rate FLOAT, report_date DATE); INSERT INTO veteran_unemployment (unemployment_rate, report_date) VALUES (4.1, '2021-12-01'), (4.3, '2021-11-01'), (4.5, '2021-10-01');

SELECT ROUND(AVG(unemployment_rate)) FROM veteran_unemployment WHERE report_date >= DATE_SUB(CURRENT_DATE, INTERVAL 12 MONTH);


Question: PostgreSQL regression test 'create_index': Write the SELECT query (example 309).

SELECT count(*) FROM onek_with_null WHERE unique1 IS NULL AND unique1 > 500;

Explanation: Regression test for Create Index in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT count(*) FROM onek_with_null WHERE unique1 IS NULL AND unique1 > 500) AS _sub;


Question: What is the total number of units with inclusive housing policies in the 'urban' area?

CREATE TABLE incl_hsg_policy (policy_id INT, area VARCHAR(20), units INT); INSERT INTO incl_hsg_policy (policy_id, area, units) VALUES (1, 'urban', 50);

SELECT SUM(units) FROM incl_hsg_policy WHERE area = 'urban';


Question: Generate PostgreSQL SQL for: When turquoise is the map colour how many avg. trips per mile (×1000)  are there?

CREATE TABLE table_17839_1 (avg_trips_per_mile__ VARCHAR, map_colour VARCHAR)

SELECT COUNT(avg_trips_per_mile__) AS ×1000_ FROM table_17839_1 WHERE map_colour = 'Turquoise';