Question: Show a SQL definition from the pg_partman project (pg_partman--2.3.2--2.3.3, item 10).

/*
 * Create the trigger function for the parent table of a time-based partition set
 */
CREATE OR REPLACE FUNCTION create_function_time(p_parent_table text, p_job_id bigint DEFAULT NULL) RETURNS void
    LANGUAGE plpgsql SECURITY DEFINER
    AS $$
DECLARE

ex_context                      text;
ex_detail                       text;
ex_hint                         text;
ex_message                      text;
v_control                       text;
v_count                         int;
v_current_partition_name        text;
v_current_partition_timestamp   timestamptz;
v_datetime_string               text;
v_epoch                         boolean;
v_final_partition_timestamp     timestamptz;
v_function_name                 text;
v_job_id                        bigint;
v_jobmon                        boolean;
v_jobmon_schema                 text;
v_old_search_path               text;
v_new_length                    int;
v_next_partition_name           text;
v_next_partition_timestamp      timestamptz;
v_parent_schema                 text;
v_parent_tablename              text;
v_partition_interval            interval;
v_prev_partition_name           text;
v_prev_partition_timestamp      timestamptz;
v_step_id                       bigint;
v_trig_func                     text;
v_optimize_trigger              int;
v_type                          text;

BEGIN

SELECT partition_type
    , partition_interval::interval
    , epoch
    , control
    , optimize_trigger
    , datetime_string
    , jobmon
INTO v_type
    , v_partition_interval
    , v_epoch
    , v_control
    , v_optimize_trigger
    , v_datetime_string
    , v_jobmon
FROM @extschema@.part_config
WHERE parent_table = p_parent_table
AND (partition_type = 'time' OR partition_type = 'time-custom');

IF NOT FOUND THEN
    RAISE EXCEPTION 'ERROR: no config found for %', p_parent_table;
END IF;

IF v_jobmon THEN
    SELECT nspname INTO v_jobmon_schema FROM pg_namespace n, 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
    IF p_job_id IS NULL THEN
        v_job_id := add_job(format('PARTMAN CREATE FUNCTION: %s', p_parent_table));
    ELSE
        v_job_id = p_job_id;
    END IF;
    v_step_id := add_step(v_job_id, format('Creating partition function for table %s', p_parent_table));
END IF;

SELECT schemaname, tablename INTO v_parent_schema, v_parent_tablename
FROM pg_catalog.pg_tables
WHERE schemaname = split_part(p_parent_table, '.', 1)::name
AND tablename = split_part(p_parent_table, '.', 2)::name;

v_function_name := @extschema@.check_name_length(v_parent_tablename, '_part_trig_func', FALSE);

IF v_type = 'time' THEN
    v_trig_func := format('CREATE OR REPLACE FUNCTION %I.%I() RETURNS trigger LANGUAGE plpgsql AS $t$
            DECLARE
            v_count                 int;
            v_partition_name        text;
            v_partition_timestamp   timestamptz;
        BEGIN
        IF TG_OP = ''INSERT'' THEN
            '
    , v_parent_schema
    , v_function_name);

    IF v_epoch = false THEN
        CASE
            WHEN v_partition_interval = '15 mins' THEN
                v_trig_func := v_trig_func||format('v_partition_timestamp := date_trunc(''hour'', NEW.%I) +
                    ''15min''::interval * floor(date_part(''minute'', NEW.%I) / 15.0);' , v_control , v_control);
                v_current_partition_timestamp := date_trunc('hour', CURRENT_TIMESTAMP) +
                    '15min'::interval * floor(date_part('minute', CURRENT_TIMESTAMP) / 15.0);
            WHEN v_partition_interval = '30 mins' THEN
                v_trig_func := v_trig_func||format('v_partition_timestamp := date_trunc(''hour'', NEW.%I) +
                    ''30min''::interval * floor(date_part(''minute'', NEW.%I) / 30.0);' , v_control , v_control);
                v_current_partition_timestamp := date_trunc('hour', CURRENT_TIMESTAMP) +
                    '30min'::interval * floor(date_part('minute', CURRENT_TIMESTAMP) / 30.0);
            WHEN v_partition_interval = '1 hour' THEN
                v_trig_func := v_trig_func||format('v_partition_timestamp := date_trunc(''hour'', NEW.%I);', v_control);
                v_current_partition_timestamp := date_trunc('hour', CURRENT_TIMESTAMP);
             WHEN v_partition_interval = '1 day' THEN
                v_trig_func := v_trig_func||format('v_partition_timestamp := date_trunc(''day'', NEW.%I);', v_control);
                v_current_partition_timestamp := date_trunc('day', CURRENT_TIMESTAMP);
            WHEN v_partition_interval = '1 week' THEN
                v_trig_func := v_trig_func||format('v_partition_timestamp := date_trunc(''week'', NEW.%I);', v_control);
                v_current_partition_timestamp := date_trunc('week', CURRENT_TIMESTAMP);
            WHEN v_partition_interval = '1 month' THEN
                v_trig_func := v_trig_func||format('v_partition_timestamp := date_trunc(''month'', NEW.%I);', v_control);
                v_current_partition_timestamp := date_trunc('month', CURRENT_TIMESTAMP);
            WHEN v_partition_interval = '3 months' THEN
                v_trig_func := v_trig_func||format('v_partition_timestamp := date_trunc(''quarter'', NEW.%I);', v_control);
                v_current_partition_timestamp := date_trunc('quarter', CURRENT_TIMESTAMP);
            WHEN v_partition_interval = '1 year' THEN
                v_trig_func := v_trig_func||format('v_partition_timestamp := date_trunc(''year'', NEW.%I);', v_control);
                v_current_partition_timestamp := date_trunc('year', CURRENT_TIMESTAMP);
        END CASE;
    ELSE -- epoch is true
        CASE
            WHEN v_partition_interval = '15 mins' THEN
                v_trig_func := v_trig_func||format('v_partition_timestamp := date_trunc(''hour'', to_timestamp(NEW.%I)) +
                    ''15min''::interval * floor(date_part(''minute'', NEW.%I) / 15.0);' , v_control , v_control);
                v_current_partition_timestamp := date_trunc('hour', CURRENT_TIMESTAMP) +
                    '15min'::interval * floor(date_part('minute', CURRENT_TIMESTAMP) / 15.0);
            WHEN v_partition_interval = '30 mins' THEN
                v_trig_func := v_trig_func||format('v_partition_timestamp := date_trunc(''hour'', to_timestamp(NEW.%I)) +
                    ''30min''::interval * floor(date_part(''minute'', NEW.%I) / 30.0);' , v_control , v_control);
                v_current_partition_timestamp := date_trunc('hour', CURRENT_TIMESTAMP) +
                    '30min'::interval * floor(date_part('minute', CURRENT_TIMESTAMP) / 30.0);
            WHEN v_partition_interval = '1 hour' THEN
                v_trig_func := v_trig_func||format('v_partition_timestamp := date_trunc(''hour'', to_timestamp(NEW.%I));', v_control);
                v_current_partition_timestamp := date_trunc('hour', CURRENT_TIMESTAMP);
             WHEN v_partition_interval = '1 day' THEN
                v_trig_func := v_trig_func||format('v_partition_timestamp := date_trunc(''day'', to_timestamp(NEW.%I));', v_control);
                v_current_partition_timestamp := date_trunc('day', CURRENT_TIMESTAMP);
            WHEN v_partition_interval = '1 week' THEN
                v_trig_func := v_trig_func||format('v_partition_timestamp := date_trunc(''week'', to_timestamp(NEW.%I));', v_control);
                v_current_partition_timestamp := date_trunc('week', CURRENT_TIMESTAMP);
            WHEN v_partition_interval = '1 month' THEN
                v_trig_func := v_trig_func||format('v_partition_timestamp := date_trunc(''month'', to_timestamp(NEW.%I));', v_control);
                v_current_partition_timestamp := date_trunc('month', CURRENT_TIMESTAMP);
            WHEN v_partition_interval = '3 months' THEN
                v_trig_func := v_trig_func||format('v_partition_timestamp := date_trunc(''quarter'', to_timestamp(NEW.%I));', v_control);
                v_current_partition_timestamp := date_trunc('quarter', CURRENT_TIMESTAMP);
            WHEN v_partition_interval = '1 year' THEN
                v_trig_func := v_trig_func||format('v_partition_timestamp := date_trunc(''year'', to_timestamp(NEW.%I));', v_control);
                v_current_partition_timestamp := date_trunc('year', CURRENT_TIMESTAMP);
        END CASE;
    END IF;

    v_current_partition_name := @extschema@.check_name_length(v_parent_tablename, to_char(v_current_partition_timestamp, v_datetime_string), TRUE);
    v_next_partition_timestamp := v_current_partition_timestamp + v_partition_interval::interval;

    IF v_epoch = false THEN
        v_trig_func := v_trig_func ||format('
            IF NEW.%I >= %L AND NEW.%I < %L THEN '
                , v_control
                , v_current_partition_timestamp
                , v_control
                , v_next_partition_timestamp);
    ELSE
        v_trig_func := v_trig_func ||format('
            IF to_timestamp(NEW.%I) >= %L AND to_timestamp(NEW.%I) < %L THEN '
                , v_control
                , v_current_partition_timestamp
                , v_control
                , v_next_partition_timestamp);
    END IF;
        SELECT count(*) INTO v_count FROM pg_catalog.pg_tables WHERE schemaname = v_parent_schema::name AND tablename = v_current_partition_name::name;
        IF v_count > 0 THEN
            v_trig_func := v_trig_func || format('
                INSERT INTO %I.%I VALUES (NEW.*); ', v_parent_schema, v_current_partition_name);
        ELSE
            v_trig_func := v_trig_func || '
                -- Child table for current values does not exist in this partition set, so write to parent
                RETURN NEW;';
        END IF;
    FOR i IN 1..v_optimize_trigger LOOP
        v_prev_partition_timestamp := v_current_partition_timestamp - (v_partition_interval::interval * i);
        v_next_partition_timestamp := v_current_partition_timestamp + (v_partition_interval::interval * i);
        v_final_partition_timestamp := v_next_partition_timestamp + (v_partition_interval::interval);
        v_prev_partition_name := @extschema@.check_name_length(v_parent_tablename, to_char(v_prev_partition_timestamp, v_datetime_string), TRUE);
        v_next_partition_name := @extschema@.check_name_length(v_parent_tablename, to_char(v_next_partition_timestamp, v_datetime_string), TRUE);

        -- Check that child table exist before making a rule to insert to them.
        -- Handles optimize_trigger being larger than premake (to go back in time further) and edge case of changing optimize_trigger immediately after running create_parent().
        SELECT count(*) INTO v_count FROM pg_catalog.pg_tables WHERE schemaname = v_parent_schema::name AND tablename = v_prev_partition_name::name;
        IF v_count > 0 THEN
            IF v_epoch = false THEN
                v_trig_func := v_trig_func ||format('
            ELSIF NEW.%I >= %L AND NEW.%I < %L THEN
                INSERT INTO %I.%I VALUES (NEW.*);'
                    , v_control
                    , v_prev_partition_timestamp
                    , v_control
                    , v_prev_partition_timestamp + v_partition_interval::interval
                    , v_parent_schema
                    , v_prev_partition_name);
            ELSE
                v_trig_func := v_trig_func ||format('
            ELSIF to_timestamp(NEW.%I) >= %L AND to_timestamp(NEW.%I) < %L THEN
                INSERT INTO %I.%I VALUES (NEW.*);'
                    , v_control
                    , v_prev_partition_timestamp
                    , v_control
                    , v_prev_partition_timestamp + v_partition_interval::interval
                    , v_parent_schema
                    , v_prev_partition_name);

            END IF;
        END IF;
        SELECT count(*) INTO v_count FROM pg_catalog.pg_tables WHERE schemaname = v_parent_schema::name AND tablename = v_next_partition_name::name;
        IF v_count > 0 THEN
            IF v_epoch = false THEN
                v_trig_func := v_trig_func ||format('
            ELSIF NEW.%I >= %L AND NEW.%I < %L THEN
                INSERT INTO %I.%I VALUES (NEW.*);'
                    , v_control
                    , v_next_partition_timestamp
                    , v_control
                    , v_final_partition_timestamp
                    , v_parent_schema
                    , v_next_partition_name);
            ELSE
                v_trig_func := v_trig_func ||format('
            ELSIF to_timestamp(NEW.%I) >= %L AND to_timestamp(NEW.%I) < %L THEN
                INSERT INTO %I.%I VALUES (NEW.*);'
                    , v_control
                    , v_next_partition_timestamp
                    , v_control
                    , v_final_partition_timestamp
                    , v_parent_schema
                    , v_next_partition_name);

            END IF;
        END IF;

    END LOOP;

    v_trig_func := v_trig_func||format('
            ELSE
                v_partition_name := @extschema@.check_name_length(%L, to_char(v_partition_timestamp, %L), TRUE);
                SELECT count(*) INTO v_count FROM pg_catalog.pg_tables WHERE schemaname = %L::name AND tablename = v_partition_name::name;
                IF v_count > 0 THEN
                    EXECUTE format(''INSERT INTO %%I.%%I VALUES($1.*)'', %L, v_partition_name) USING NEW;
                ELSE
                    RETURN NEW;
                END IF;
            END IF;'
            , v_parent_tablename
            , v_datetime_string
            , v_parent_schema
            , v_parent_schema);

    v_trig_func := v_trig_func ||'
        END IF;
        RETURN NULL;
        EXCEPTION WHEN OTHERS THEN
            RAISE WARNING ''pg_partman insert into child table failed, row inserted into parent (%.%). ERROR: %'', TG_TABLE_SCHEMA, TG_TABLE_NAME, COALESCE(SQLERRM, ''unknown'');
            RETURN NEW;
        END $t$;';

    EXECUTE v_trig_func;

    IF v_jobmon_schema IS NOT NULL THEN
        PERFORM update_step(v_step_id, 'OK', format('Added function for current time interval: %s to %s'
                                                        , v_current_partition_timestamp
                                                        , v_final_partition_timestamp-'1sec'::interval));
    END IF;

ELSIF v_type = 'time-custom' THEN

    v_trig_func := format('CREATE OR REPLACE FUNCTION %I.%I() RETURNS trigger LANGUAGE plpgsql AS $t$
        DECLARE
            v_child_schemaname  text;
            v_child_table       text;
            v_child_tablename   text;
        BEGIN
            '
        , v_parent_schema
        , v_function_name);

    IF v_epoch = false THEN
        v_trig_func := v_trig_func || format('

        SELECT child_table INTO v_child_table
        FROM @extschema@.custom_time_partitions
        WHERE partition_range @> NEW.%I
        AND parent_table = %L;'
        , v_control
        , v_parent_schema||'.'||v_parent_tablename);

    ELSE -- epoch true
        v_trig_func := v_trig_func || format('

        SELECT child_table INTO v_child_table
        FROM @extschema@.custom_time_partitions
        WHERE partition_range @> to_timestamp(NEW.%I)
        AND parent_table = %L;'
        , v_control
        , v_parent_schema||'.'||v_parent_tablename);

    END IF;

    v_trig_func := v_trig_func || '

        SELECT schemaname, tablename INTO v_child_schemaname, v_child_tablename
        FROM pg_catalog.pg_tables
        WHERE schemaname = split_part(v_child_table, ''.'', 1)::name
        AND tablename = split_part(v_child_table, ''.'', 2)::name;
        IF v_child_schemaname IS NOT NULL AND v_child_tablename IS NOT NULL THEN
            EXECUTE format(''INSERT INTO %I.%I VALUES ($1.*)'', v_child_schemaname, v_child_tablename) USING NEW;
        ELSE
            RETURN NEW;
        END IF;

        RETURN NULL;
        EXCEPTION WHEN OTHERS THEN
            RAISE WARNING ''pg_partman insert into child table failed, row inserted into parent (%.%). ERROR: %'', TG_TABLE_SCHEMA, TG_TABLE_NAME, COALESCE(SQLERRM, ''unknown'');
            RETURN NEW;
        END $t$;';

    EXECUTE v_trig_func;

    IF v_jobmon_schema IS NOT NULL THEN
        PERFORM update_step(v_step_id, 'OK', format('Added function for custom time table: %s', p_parent_table));
    END IF;

ELSE
    RAISE EXCEPTION 'ERROR: Invalid time partitioning type given: %', v_type;
END IF;

IF v_jobmon_schema IS NOT NULL THEN
    PERFORM close_job(v_job_id);
    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 CREATE FUNCTION: %s'')', v_jobmon_schema, p_parent_table) INTO v_job_id;
                EXECUTE format('SELECT %I.add_step(%s, ''Partition function maintenance for table %s failed'')', 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 to par that goes with the score 68-74-69=211?

CREATE TABLE table_name_70 (to_par VARCHAR, score VARCHAR)

SELECT to_par FROM table_name_70 WHERE score = 68 - 74 - 69 = 211;


Question: Generate PostgreSQL SQL for: Which gold Coast has a Melbourne of yes, a Perth of yes, an Auckland of no, and a Sydney of no?

CREATE TABLE table_name_36 (gold_coast VARCHAR, sydney VARCHAR, auckland VARCHAR, melbourne VARCHAR, perth VARCHAR)

SELECT gold_coast FROM table_name_36 WHERE melbourne = 'yes' AND perth = 'yes' AND auckland = 'no' AND sydney = 'no';


Question: Generate PostgreSQL SQL for: How many games did they play the carolina hurricanes?

CREATE TABLE table_23453931_8 (game VARCHAR, opponent VARCHAR)

SELECT COUNT(game) FROM table_23453931_8 WHERE opponent = 'Carolina Hurricanes';


Question: Generate PostgreSQL SQL for: What was the final score for the game at giants stadium when the indianapolis colts were the visiting team?

CREATE TABLE table_name_9 (final_score VARCHAR, visiting_team VARCHAR, stadium VARCHAR)

SELECT final_score FROM table_name_9 WHERE visiting_team = 'indianapolis colts' AND stadium = 'giants stadium';


Question: Which indigenous communities are represented in the 'arctic_communities' table, and what is their total population?

CREATE TABLE arctic_communities (name TEXT, population INTEGER);

SELECT name, SUM(population) FROM arctic_communities GROUP BY name;


Question: Generate PostgreSQL SQL for: Which Position has a Round larger than 4, and a Player of patrick johnson?

CREATE TABLE table_name_45 (position VARCHAR, round VARCHAR, player VARCHAR)

SELECT position FROM table_name_45 WHERE round > 4 AND player = 'patrick johnson';


Question: What is the minimum funding amount received by companies founded in the United States?

CREATE TABLE company (id INT, name VARCHAR(50), country VARCHAR(50)); CREATE TABLE investment_round (id INT, company_id INT, funding_amount INT); INSERT INTO company (id, name, country) VALUES (1, 'Acme Corp', 'USA'); INSERT INTO investment_round (id, company_id, funding_amount) VALUES (1, 1, 500000); INSERT INTO investment_round (id, company_id, funding_amount) VALUES (2, 1, 750000); INSERT INTO company (id, name, country) VALUES (2, 'Maple Leaf Technologies', 'Canada'); INSERT INTO investment_round (id, company_id, funding_amount) VALUES (3, 2, 250000);

SELECT MIN(ir.funding_amount) AS min_funding_amount FROM company c JOIN investment_round ir ON c.id = ir.company_id WHERE c.country = 'USA';


Question: Insert new records for the players who have recently signed up for the esports tournament.

CREATE TABLE EsportsTournament (TournamentID INT, PlayerID INT, TournamentDate DATE); INSERT INTO EsportsTournament (TournamentID, PlayerID, TournamentDate) VALUES (1, 6, '2021-07-01'), (2, 7, '2021-07-01'), (3, 8, '2021-07-01');

INSERT INTO EsportsTournament (TournamentID, PlayerID, TournamentDate) VALUES (4, 9, '2021-07-01'), (5, 10, '2021-07-01'), (6, 11, '2021-07-01');


Question: Generate PostgreSQL SQL for: List the names of technicians who have not been assigned to repair machines.

CREATE TABLE technician (Name VARCHAR, technician_id VARCHAR); CREATE TABLE repair_assignment (Name VARCHAR, technician_id VARCHAR)

SELECT Name FROM technician WHERE NOT technician_id IN (SELECT technician_id FROM repair_assignment);


Question: Generate PostgreSQL SQL for: What home team score has a Away team of melbourne?

CREATE TABLE table_name_63 (home_team VARCHAR, away_team VARCHAR)

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


Question: Generate PostgreSQL SQL for: What is the Term of office for Leonard Reynolds of NSW?

CREATE TABLE table_name_1 (term_of_office VARCHAR, state VARCHAR, member VARCHAR)

SELECT term_of_office FROM table_name_1 WHERE state = 'nsw' AND member = 'leonard reynolds';


Question: Generate PostgreSQL SQL for: Which MWEHL team has player Ben Johnson?

CREATE TABLE table_name_29 (mwehl_team VARCHAR, player VARCHAR)

SELECT mwehl_team FROM table_name_29 WHERE player = 'ben johnson';


Question: Show all orders for the most caloric product.

CREATE TABLE products (id INT PRIMARY KEY, name VARCHAR(255), category VARCHAR(255), supplier_id INT, FOREIGN KEY (supplier_id) REFERENCES suppliers(id)); CREATE TABLE nutrients (id INT PRIMARY KEY, product_id INT, calories INT, FOREIGN KEY (product_id) REFERENCES products(id)); CREATE TABLE orders (id INT PRIMARY KEY, product_id INT, order_date DATE, quantity INT, FOREIGN KEY (product_id) REFERENCES products(id)); INSERT INTO products (id, name, category, supplier_id) VALUES (6, 'Avocado', 'Fruits', 6); INSERT INTO nutrients (id, product_id, calories) VALUES (6, 6, 234); INSERT INTO orders (id, product_id, order_date, quantity) VALUES (6, 6, '2022-01-08', 30);

SELECT o.id, o.product_id, o.order_date, o.quantity FROM orders o JOIN products p ON o.product_id = p.id WHERE p.id = (SELECT product_id FROM nutrients WHERE calories = (SELECT MAX(calories) FROM nutrients));


Question: Update the depth of all marine protected areas in the Indian Ocean by 10%.

CREATE TABLE marine_protected_areas (id INT, name VARCHAR(255), location VARCHAR(255), depth FLOAT); INSERT INTO marine_protected_areas (id, name, location, depth) VALUES (1, 'MPA 1', 'Pacific Ocean', 123.4), (2, 'MPA 2', 'Atlantic Ocean', 150.0), (3, 'MPA 3', 'Indian Ocean', 75.0);

UPDATE marine_protected_areas SET depth = depth * 1.1 WHERE location = 'Indian Ocean';


Question: Generate PostgreSQL SQL for: What is the average agricultural panel of the composition with a labour panel less than 6, more than 0 nominations by Taoiseach, and a total less than 4?

CREATE TABLE table_name_62 (agricultural_panel INTEGER, total VARCHAR, labour_panel VARCHAR, nominated_by_the_taoiseach VARCHAR)

SELECT AVG(agricultural_panel) FROM table_name_62 WHERE labour_panel < 6 AND nominated_by_the_taoiseach > 0 AND total < 4;


Question: Generate PostgreSQL SQL for: Find the last name of the individuals that have been contact individuals of an organization.

CREATE TABLE individuals (individual_last_name VARCHAR, individual_id VARCHAR); CREATE TABLE organization_contact_individuals (individual_id VARCHAR)

SELECT DISTINCT t1.individual_last_name FROM individuals AS t1 JOIN organization_contact_individuals AS t2 ON t1.individual_id = t2.individual_id;


Question: What are the names and total cargo weight of all shipments that have been delayed and originated from the 'North America' region?

CREATE TABLE Warehouse (id INT, name TEXT, region TEXT); INSERT INTO Warehouse (id, name, region) VALUES (1, 'New York Warehouse', 'North America'), (2, 'Los Angeles Warehouse', 'North America'), (3, 'Sao Paulo Warehouse', 'South America'); CREATE TABLE Shipment (id INT, warehouse_id INT, cargo_weight INT, delivery_status TEXT); INSERT INTO Shipment (id, warehouse_id, cargo_weight, delivery_status) VALUES (1, 1, 5000, 'Delayed'), (2, 1, 3000, 'On Time'), (3, 2, 4000, 'Delayed'), (4, 3, 6000, 'On Time');

SELECT Warehouse.name, SUM(Shipment.cargo_weight) as total_cargo_weight FROM Warehouse INNER JOIN Shipment ON Warehouse.id = Shipment.warehouse_id WHERE Warehouse.region = 'North America' AND Shipment.delivery_status = 'Delayed' GROUP BY Warehouse.name;


Question: Write the DML statement from PostgreSQL regression test 'rangetypes' (example 305).

insert into test_range_elem select i from generate_series(1,100) i;

Explanation: DML from PostgreSQL core regression test for Rangetypes.


Question: Update the price of renewable energy in France to 14.00.

CREATE TABLE renewable_energy (country VARCHAR(20), price DECIMAL(5,2)); INSERT INTO renewable_energy (country, price) VALUES ('France', 12.50), ('France', 13.20), ('Germany', 10.00), ('Germany', 11.50);

UPDATE renewable_energy SET price = 14.00 WHERE country = 'France';


Question: What is the total weight of non-organic meat products in the FOOD_ITEMS table?

CREATE TABLE FOOD_ITEMS (id INT, name VARCHAR(50), category VARCHAR(50), is_organic BOOLEAN, weight FLOAT); INSERT INTO FOOD_ITEMS (id, name, category, is_organic, weight) VALUES (1, 'Chicken Breast', 'Meat', false, 0.4), (2, 'Ground Beef', 'Meat', false, 0.8);

SELECT SUM(weight) FROM FOOD_ITEMS WHERE is_organic = false AND category = 'Meat';


Question: What is the minimum sustainability rating for any destination in the Pacific Islands with at least 500 visitors?

CREATE TABLE PacificIslandsDestinations (destination_id INT, name VARCHAR(50), country VARCHAR(50), sustainability_rating INT, visitor_count INT); INSERT INTO PacificIslandsDestinations (destination_id, name, country, sustainability_rating, visitor_count) VALUES (1, 'Eco Retreat', 'Fiji', 4, 600); INSERT INTO PacificIslandsDestinations (destination_id, name, country, sustainability_rating, visitor_count) VALUES (2, 'Green Island', 'Tahiti', 5, 800);

SELECT MIN(sustainability_rating) FROM PacificIslandsDestinations WHERE country IN ('Pacific Islands') AND visitor_count >= 500;


Question: What is the total number of cybersecurity incidents reported for each type of incident in FY2021?

CREATE TABLE FiscalYear (fiscal_year INT, year INT); INSERT INTO FiscalYear (fiscal_year, year) VALUES (2021, 2021), (2022, 2022), (2023, 2023); CREATE TABLE IncidentTypes (id INT, type VARCHAR(30)); INSERT INTO IncidentTypes (id, type) VALUES (1, 'Malware'), (2, 'Phishing'), (3, 'Ransomware'), (4, 'Data Breach'); CREATE TABLE Incidents (id INT, fiscal_year_id INT, incident_type_id INT, reported_date DATE, description TEXT); INSERT INTO Incidents (id, fiscal_year_id, incident_type_id, reported_date, description) VALUES (1, 1, 1, '2021-01-01', 'A computer was infected with malware.'), (2, 1, 3, '2021-02-15', 'A ransomware attack encrypted sensitive data.'), (3, 1, 2, '2021-03-05', 'A phishing email was sent to employees.'), (4, 1, 1, '2021-04-10', 'A server was compromised with malware.');

SELECT i.type, COUNT(*) FROM Incidents i INNER JOIN FiscalYear fy ON i.fiscal_year_id = fy.id WHERE fy.year = 2021 GROUP BY i.type;


Question: Generate PostgreSQL SQL for: Which college has a nose tackle position?

CREATE TABLE table_name_30 (college VARCHAR, position VARCHAR)

SELECT college FROM table_name_30 WHERE position = 'nose tackle';


Question: Generate PostgreSQL SQL for: When did the game with North Melbourne as the away team take place?

CREATE TABLE table_name_89 (date VARCHAR, away_team VARCHAR)

SELECT date FROM table_name_89 WHERE away_team = 'north melbourne';


Question: Generate PostgreSQL SQL for: What is the name of the station in Toolamba that is currently demolished?

CREATE TABLE table_name_26 (name VARCHAR, current_status VARCHAR, location VARCHAR)

SELECT name FROM table_name_26 WHERE current_status = 'demolished' AND location = 'toolamba';


Question: Generate PostgreSQL SQL for: What is the Time (EEST), when the Stage is ss8?

CREATE TABLE table_name_5 (time__eest_ VARCHAR, stage VARCHAR)

SELECT time__eest_ FROM table_name_5 WHERE stage = 'ss8';


Question: Display the names of all countries that have held AI safety conferences and the number of such conferences.

CREATE TABLE countries (id INT, name TEXT); INSERT INTO countries (id, name) VALUES (1, 'USA'), (2, 'Canada'), (3, 'UK'), (4, 'Australia'); CREATE TABLE conferences (id INT, country_id INT, name TEXT, topic TEXT); INSERT INTO conferences (id, country_id, name, topic) VALUES (1, 1, 'Conf1', 'AI Safety'), (2, 1, 'Conf2', 'AI Safety'), (3, 3, 'Conf3', 'AI Safety'), (4, 4, 'Conf4', 'AI Safety');

SELECT countries.name, COUNT(conferences.id) as conferences_count FROM countries INNER JOIN conferences ON countries.id = conferences.country_id WHERE conferences.topic = 'AI Safety' GROUP BY countries.name;


Question: Generate PostgreSQL SQL for: How many engine b5204 t3?

CREATE TABLE table_1147705_1 (engine_displacement VARCHAR, engine_type VARCHAR)

SELECT COUNT(engine_displacement) FROM table_1147705_1 WHERE engine_type = 'B5204 T3';


Question: Show a query using PostgreSQL contrib extension 'pg_buffercache' (example 40).

SELECT * FROM pg_buffercache_mark_dirty_relation('temp_pg_buffercache');

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


Question: Generate PostgreSQL SQL for: What was the score of the game on 1 september?

CREATE TABLE table_name_49 (score VARCHAR, date VARCHAR)

SELECT score FROM table_name_49 WHERE date = '1 september';


Question: Generate PostgreSQL SQL for: What is the smallest rank when there are more than 2 games?

CREATE TABLE table_name_52 (rank INTEGER, games INTEGER)

SELECT MIN(rank) FROM table_name_52 WHERE games > 2;


Question: pgTAP test for Fktap (assertion 60).

-- Make sure check_test() works properly with no name argument.
SELECT * FROM check_test(
    fk_ok( 'fk', 'pk_id', 'pk', 'id' ),
    true
);

Explanation: SQL assertion from pgTAP test suite for Fktap.


Question: Generate PostgreSQL SQL for: Which Attendance has an Opponent of @ oilers, and a Date of may 25?

CREATE TABLE table_name_25 (attendance INTEGER, opponent VARCHAR, date VARCHAR)

SELECT MAX(attendance) FROM table_name_25 WHERE opponent = '@ oilers' AND date = 'may 25';


Question: Generate PostgreSQL SQL for: Who had the highest rebounds against detroit?

CREATE TABLE table_name_65 (high_rebounds VARCHAR, team VARCHAR)

SELECT high_rebounds FROM table_name_65 WHERE team = 'detroit';


Question: What is the minimum depth required for cold-water corals to grow?

CREATE TABLE coral_reefs (reef_name TEXT, min_depth_m INT, max_depth_m INT); INSERT INTO coral_reefs (reef_name, min_depth_m, max_depth_m) VALUES ('Great Barrier Reef', 0, 50), ('Coral Garden', 200, 500), ('Midnight Express', 700, 1000);

SELECT MIN(min_depth_m) FROM coral_reefs WHERE min_depth_m > 0;


Question: What is the daily trading volume for the USDC stablecoin on the Stellar network?

CREATE TABLE stellar_usdc (transaction_id INT, volume DECIMAL, timestamp TIMESTAMP);

SELECT SUM(volume) FROM stellar_usdc WHERE timestamp >= NOW() - INTERVAL '1 day' GROUP BY DATE(timestamp);


Question: Generate PostgreSQL SQL for: In which year did he finish 11th?

CREATE TABLE table_name_31 (year VARCHAR, result VARCHAR)

SELECT COUNT(year) FROM table_name_31 WHERE result = '11th';


Question: Generate PostgreSQL SQL for: In 1972, what was the highest number of points with a Ford engine and an entrant of Brooke Bond Oxo Team Surtees?

CREATE TABLE table_name_41 (pts INTEGER, year VARCHAR, engine VARCHAR, entrant VARCHAR)

SELECT MAX(pts) FROM table_name_41 WHERE engine = 'ford' AND entrant = 'brooke bond oxo team surtees' AND year = 1972;


Question: Generate PostgreSQL SQL for: In what year was Letecke Zavody N.P., Jinonice the manufacturer?

CREATE TABLE table_name_90 (year VARCHAR, manufacturer VARCHAR)

SELECT year FROM table_name_90 WHERE manufacturer = 'letecke zavody n.p., jinonice';


Question: What is the total number of hospitals and the total number of beds per state?

CREATE TABLE hospitals (state varchar(2), num_hospitals int, num_beds int); INSERT INTO hospitals (state, num_hospitals, num_beds) VALUES ('NY', 201, 20100), ('CA', 486, 50000), ('TX', 413, 45000), ('FL', 214, 22000);

SELECT state, SUM(num_hospitals) as total_hospitals, SUM(num_beds) as total_beds FROM hospitals GROUP BY state;


Question: Add a new aircraft manufacturing plant in Canada

CREATE TABLE plants (plant_id INT PRIMARY KEY, name VARCHAR(100), city VARCHAR(50), country VARCHAR(50));

INSERT INTO plants (plant_id, name, city, country) VALUES (4, 'Mirage Manufacturing', 'Toronto', 'Canada');


Question: Which advocacy campaigns were launched in 'advocacy' table, and when, excluding campaigns launched in 2021?

CREATE TABLE advocacy (id INT, campaign VARCHAR(50), launch_date DATE, end_date DATE); INSERT INTO advocacy (id, campaign, launch_date, end_date) VALUES (1, 'Child Rights', '2021-01-01', '2021-12-31'), (2, 'Gender Equality', '2021-02-01', '2021-12-31'), (3, 'Human Rights', '2020-01-01', '2020-12-31');

SELECT campaign, launch_date FROM advocacy WHERE launch_date < '2021-01-01';


Question: Generate PostgreSQL SQL for: Name the round of 32 in conference usa

CREATE TABLE table_10722506_6 (round_of_32 VARCHAR, conference VARCHAR)

SELECT round_of_32 FROM table_10722506_6 WHERE conference = 'conference USA';


Question: Write the DML statement from PostgreSQL regression test 'truncate' (example 2).

Explanation: DML from PostgreSQL core regression test for Truncate.


Question: pgTAP test for Resultset (assertion 90).

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

Explanation: SQL assertion from pgTAP test suite for Resultset.


Question: What is the total number of pallets handled by the 'Warehouse A'?

CREATE TABLE Warehouse (name varchar(20), pallets_handled int); INSERT INTO Warehouse (name, pallets_handled) VALUES ('Warehouse A', 1500), ('Warehouse B', 2000);

SELECT SUM(pallets_handled) FROM Warehouse WHERE name = 'Warehouse A';


Question: What is the total cost of the 'ProjectX'?

CREATE TABLE ProjectCost (project_name TEXT, phase TEXT, cost INT); INSERT INTO ProjectCost (project_name, phase, cost) VALUES ('ProjectX', 'Phase1', 10000), ('ProjectX', 'Phase2', 20000), ('ProjectY', 'Phase1', 15000);

SELECT SUM(cost) FROM ProjectCost WHERE project_name = 'ProjectX';


Question: PostgreSQL regression test 'jsonb': Write the SELECT query (example 160).

SELECT jsonb_typeof('"hello"') AS string;

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

SELECT count(*) FROM (SELECT jsonb_typeof('"hello"') AS string) AS _sub;


Question: Generate PostgreSQL SQL for: Name the high points 31-27

CREATE TABLE table_22669044_9 (high_points VARCHAR, record VARCHAR)

SELECT high_points FROM table_22669044_9 WHERE record = '31-27';


Question: Which artists have conducted the most workshops by region?

CREATE TABLE ArtistWorkshops (id INT, artist_name VARCHAR(255), region VARCHAR(255), workshops INT); INSERT INTO ArtistWorkshops (id, artist_name, region, workshops) VALUES (1, 'Artist A', 'North', 5), (2, 'Artist B', 'South', 3), (3, 'Artist C', 'North', 7), (4, 'Artist D', 'East', 2);

SELECT region, artist_name, SUM(workshops) FROM ArtistWorkshops GROUP BY region, artist_name;


Question: Which artists have produced the most pieces?

CREATE TABLE Artists (ArtistID int, Name varchar(50), Nationality varchar(50)); CREATE TABLE ArtPieces (ArtPieceID int, Title varchar(50), YearCreated int, ArtistID int);

SELECT Artists.Name, COUNT(ArtPieces.ArtPieceID) AS ArtPiecesCount FROM Artists INNER JOIN ArtPieces ON Artists.ArtistID = ArtPieces.ArtistID GROUP BY Artists.Name ORDER BY ArtPiecesCount DESC;


Question: Write the DDL statement from PostgreSQL regression test 'publication' (example 587).

CREATE TABLE pub_testpart1.parent1 (a int) partition by list (a);

Explanation: DDL from PostgreSQL core regression test for Publication.


Question: What is the highest ticket price for a play in London?

CREATE TABLE plays (title VARCHAR(255), location VARCHAR(255), price DECIMAL(5,2)); INSERT INTO plays (title, location, price) VALUES ('Hamilton', 'London', 250.00), ('Macbeth', 'London', 150.00), ('Romeo and Juliet', 'London', 120.00);

SELECT MAX(price) FROM plays WHERE location = 'London';


Question: pgTAP test for Pgtap--0.91.0--0.92.0 (assertion 28).

-- view_owner_is ( schema, view, user )
CREATE OR REPLACE FUNCTION view_owner_is ( NAME, NAME, NAME )
RETURNS TEXT AS $$
    SELECT view_owner_is(
        $1, $2, $3,
        'View ' || quote_ident($1) || '.' || quote_ident($2) || ' should be owned by ' || quote_ident($3)
    );
$$ LANGUAGE sql;

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


Question: Write the DML statement from PostgreSQL regression test 'numeric_big' (example 80).

Explanation: DML from PostgreSQL core regression test for Numeric Big.


Question: How many hybrid cars are sold in Tokyo in the year 2022?

CREATE TABLE car_sales(id INT, manufacturer VARCHAR(20), model VARCHAR(20), year INT, sale_type VARCHAR(20), units_sold INT);

SELECT SUM(units_sold) FROM car_sales WHERE manufacturer = 'Toyota' AND model LIKE 'Prius%' AND city = 'Tokyo' AND year = 2022 AND sale_type = 'Retail';


Question: How many publications were made by graduate students in the Mathematics department in 2020?

CREATE TABLE students (student_id INT, name VARCHAR(50), department VARCHAR(50), graduate_status VARCHAR(10)); INSERT INTO students VALUES (1, 'Alice Johnson', 'Mathematics', 'Graduate'); INSERT INTO students VALUES (2, 'Bob Brown', 'Mathematics', 'Undergraduate'); INSERT INTO students VALUES (3, 'Charlie Davis', 'Physics', 'Graduate'); CREATE TABLE publications (publication_id INT, student_id INT, year INT, title VARCHAR(100)); INSERT INTO publications VALUES (1, 1, 2019, 'Theory of Numbers'); INSERT INTO publications VALUES (2, 1, 2020, 'Calculus for Beginners'); INSERT INTO publications VALUES (3, 3, 2019, 'Quantum Mechanics');

SELECT COUNT(*) FROM publications p INNER JOIN students s ON p.student_id = s.student_id WHERE s.department = 'Mathematics' AND s.graduate_status = 'Graduate' AND p.year = 2020;


Question: What is the total revenue of tours that promote cultural heritage preservation?

CREATE TABLE tours (id INT, name VARCHAR(255), description TEXT, revenue FLOAT); INSERT INTO tours (id, name, description, revenue) VALUES (1, 'Historic Landmarks Tour', 'Discover cultural heritage sites in Paris.', 9000.00), (2, 'Traditional Villages Tour', 'Explore authentic Italian villages and their culture.', 8000.00);

SELECT SUM(revenue) FROM tours WHERE description LIKE '%cultural heritage%';


Question: Generate PostgreSQL SQL for: What is Money ( $ ), when Player is Greg Norman?

CREATE TABLE table_name_1 (money___$__ VARCHAR, player VARCHAR)

SELECT money___$__ FROM table_name_1 WHERE player = 'greg norman';


Question: Generate PostgreSQL SQL for: Name the driver for june 23 and team of penske racing

CREATE TABLE table_16493961_1 (driver VARCHAR, date VARCHAR, team VARCHAR)

SELECT driver FROM table_16493961_1 WHERE date = 'June 23' AND team = 'Penske Racing';


Question: Generate PostgreSQL SQL for: How many entries are there for founded when the location was springfield, ohio?

CREATE TABLE table_24195232_1 (founded VARCHAR, location VARCHAR)

SELECT COUNT(founded) FROM table_24195232_1 WHERE location = 'Springfield, Ohio';


Question: What is the minimum age of candidates who ran for office in each election?

CREATE TABLE election (year INT, candidates INT); CREATE TABLE candidate (name VARCHAR(255), age INT, election_year INT); INSERT INTO election (year, candidates) VALUES (2016, 10), (2018, 15), (2020, 20), (2022, 25), (2024, 30); INSERT INTO candidate (name, age, election_year) VALUES ('Candidate A', 40, 2016), ('Candidate B', 35, 2016), ('Candidate C', 45, 2018), ('Candidate D', 50, 2018), ('Candidate E', 55, 2020);

SELECT election_year, MIN(age) FROM candidate GROUP BY election_year;


Question: Generate PostgreSQL SQL for: Which state is frederick bamford a member of?

CREATE TABLE table_name_24 (state VARCHAR, member VARCHAR)

SELECT state FROM table_name_24 WHERE member = 'frederick bamford';


Question: What is the average manufacturing cost of aircrafts manufactured in the US?

CREATE TABLE AircraftManufacturing(id INT, manufacturer VARCHAR(255), country VARCHAR(255), cost FLOAT); INSERT INTO AircraftManufacturing(id, manufacturer, country, cost) VALUES (1, 'Boeing', 'USA', 120000000), (2, 'Airbus', 'Europe', 150000000), (3, 'Lockheed Martin', 'USA', 180000000);

SELECT AVG(cost) FROM AircraftManufacturing WHERE country = 'USA';


Question: Write the DML statement from PostgreSQL regression test 'rangetypes' (example 116).

INSERT INTO numrange_test2 VALUES(numrange(1.1, 2.2,'()'));


Question: PostgreSQL regression test 'numeric': Write the SELECT query (example 1010).

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

SELECT count(*) FROM (SELECT factorial(15)) AS _sub;


Question: What is the average KDA ratio for each player in the 'gaming' tournament?

CREATE TABLE players (id INT, name VARCHAR(50)); CREATE TABLE games (id INT, player_id INT, kills INT, deaths INT, assists INT); INSERT INTO players VALUES (1, 'Aarav Singh'); INSERT INTO players VALUES (2, 'Bella Rodriguez'); INSERT INTO games VALUES (1, 1, 12, 6, 8); INSERT INTO games VALUES (2, 1, 18, 4, 12); INSERT INTO games VALUES (3, 2, 7, 3, 2); INSERT INTO games VALUES (4, 2, 10, 5, 6);

SELECT player_id, AVG( kills / NULLIF(deaths, 0) + assists / NULLIF(deaths, 0)) as avg_kda_ratio FROM games GROUP BY player_id;


Question: Generate PostgreSQL SQL for: What is the lowest 09-10 i/o best?

CREATE TABLE table_24990183_5 (Id VARCHAR)

SELECT MIN(09 AS _10_i_o_best) FROM table_24990183_5;


Question: Generate PostgreSQL SQL for: What is Place, when Score is "75-71-72-70=288"?

CREATE TABLE table_name_33 (place VARCHAR, score VARCHAR)

SELECT place FROM table_name_33 WHERE score = 75 - 71 - 72 - 70 = 288;


Question: Delete a record from the 'habitats' table

CREATE TABLE habitats (id INT PRIMARY KEY, name VARCHAR(255), location VARCHAR(255), size FLOAT);


Question: What is the total CO2 emission per quarter for each mine?

SELECT mine_id, DATE_TRUNC('quarter', emission_date) AS quarter, SUM(co2_amount) AS total_emission FROM co2_emissions GROUP BY mine_id, quarter ORDER BY mine_id, quarter;


Question: What is the minimum cost of manufacturing the aircraft models 'Falcon 9' and 'Falcon 1'?

CREATE TABLE AircraftManufacturing(model VARCHAR(20), total_cost INT); INSERT INTO AircraftManufacturing VALUES('Falcon 1', 500000),('Falcon 9', 600000);

SELECT MIN(total_cost) FROM AircraftManufacturing WHERE model IN ('Falcon 9', 'Falcon 1');


Question: List policy numbers and claim amounts for policyholders living in 'Ontario' who have filed a claim.

CREATE TABLE Policies (PolicyNumber INT, PolicyholderID INT, PolicyState VARCHAR(20)); CREATE TABLE Claims (PolicyholderID INT, ClaimAmount DECIMAL(10,2), PolicyState VARCHAR(20)); INSERT INTO Policies (PolicyNumber, PolicyholderID, PolicyState) VALUES (2001, 9, 'Ontario'), (2002, 10, 'Ontario'); INSERT INTO Claims (PolicyholderID, ClaimAmount, PolicyState) VALUES (9, 800, 'Ontario'), (10, 900, 'Ontario');

SELECT Policies.PolicyNumber, Claims.ClaimAmount FROM Policies JOIN Claims ON Policies.PolicyholderID = Claims.PolicyholderID WHERE Policies.PolicyState = 'Ontario';


Question: pgTAP test for Hastap (assertion 299).

/****************************************************************************/
-- Test is_partitioned().
CREATE FUNCTION test_is_partitioned() RETURNS SETOF TEXT AS $$
DECLARE
    tap record;
BEGIN
    IF pg_version_num() >= 100000 THEN
        FOR tap IN SELECT * FROM check_test(
            is_partitioned( '__SDFSDFD__' ),
            false,
            'is_partitioned(non-existent part)',
            'Table "__SDFSDFD__" should be partitioned',
            ''
        ) AS b LOOP
            RETURN NEXT tap.b;
        END LOOP;

        FOR tap IN SELECT * FROM check_test(
            is_partitioned( '__SDFSDFD__', 'howdy' ),
            false,
            'is_partitioned(non-existent part, desc)',
            'howdy',
            ''
        ) AS b LOOP
            RETURN NEXT tap.b;
        END LOOP;

        FOR tap IN SELECT * FROM check_test(
            is_partitioned( 'foo', '__SDFSDFD__', 'desc' ),
            false,
            'is_partitioned(sch, non-existent part, desc)',
            'desc',
            ''
        ) AS b LOOP
            RETURN NEXT tap.b;
        END LOOP;

        FOR tap IN SELECT * FROM check_test(
            is_partitioned( 'public', 'apart', 'desc' ),
            true,
            'is_partitioned(sch, part, desc)',
            'desc',
            ''
        ) AS b LOOP
            RETURN NEXT tap.b;
        END LOOP;

        FOR tap IN SELECT * FROM check_test(
            is_partitioned( 'public', 'apart'::name ),
            true,
            'is_partitioned(sch, part)',
            'Table public.apart should be partitioned',
            ''
        ) AS b LOOP
            RETURN NEXT tap.b;
        END LOOP;

        FOR tap IN SELECT * FROM check_test(
            is_partitioned( 'apart', 'yowza' ),
            true,
            'is_partitioned(part, desc)',
            'yowza',
            ''
        ) AS b LOOP
            RETURN NEXT tap.b;
        END LOOP;

        FOR tap IN SELECT * FROM check_test(
            is_partitioned( 'apart' ),
            true,
            'is_partitioned(part)',
            'Table apart should be partitioned',
            ''
        ) AS b LOOP
            RETURN NEXT tap.b;
        END LOOP;

    ELSE
        FOR tap IN SELECT * FROM check_test(
            has_view( '__SDFSDFD__' ),
            false,
            'is_partitioned(non-existent part)',
            'View "__SDFSDFD__" should exist',
            ''
        ) AS b LOOP
            RETURN NEXT tap.b;
        END LOOP;

        FOR tap IN SELECT * FROM check_test(
            has_view( '__SDFSDFD__', 'howdy' ),
            false,
            'is_partitioned(non-existent part, desc)',
            'howdy',
            ''
        ) AS b LOOP
            RETURN NEXT tap.b;
        END LOOP;

        FOR tap IN SELECT * FROM check_test(
            has_view( 'foo', '__SDFSDFD__', 'desc' ),
            false,
            'is_partitioned(sch, non-existent part, desc)',
            'desc',
            ''
        ) AS b LOOP
            RETURN NEXT tap.b;
        END LOOP;

        FOR tap IN SELECT * FROM check_test(
            has_view( 'information_schema', 'tables', 'desc' ),
            true,
            'is_partitioned(sch, part, desc)',
            'desc',
            ''
        ) AS b LOOP
            RETURN NEXT tap.b;
        END LOOP;

        FOR tap IN SELECT * FROM check_test(
            has_view( 'information_schema', 'tables', 'desc' ),
            true,
            'is_partitioned(sch, part)',
            'desc',
            ''
        ) AS b LOOP
            RETURN NEXT tap.b;
        END LOOP;

        FOR tap IN SELECT * FROM check_test(
            has_view( 'information_schema', 'tables', 'desc' ),
            true,
            'is_partitioned(part, desc)',
            'desc',
            ''
        ) AS b LOOP
            RETURN NEXT tap.b;
        END LOOP;

        FOR tap IN SELECT * FROM check_test(
            has_view( 'pg_tables' ),
            true,
            'is_partitioned(part)',
            'View pg_tables should exist',
            ''
        ) AS b LOOP
            RETURN NEXT tap.b;
        END LOOP;
    END IF;
    RETURN;
END;
$$ language PLPGSQL;

Explanation: SQL assertion from pgTAP test suite for Hastap.


Question: Generate PostgreSQL SQL for: How much capacity has 1944 as the founded?

CREATE TABLE table_name_84 (capacity VARCHAR, founded VARCHAR)

SELECT COUNT(capacity) FROM table_name_84 WHERE founded = 1944;


Question: PostgreSQL regression test 'rangefuncs': Write the SELECT query (example 149).

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

SELECT count(*) FROM (select pg_get_viewdef('vw_rngfunc')) AS _sub;


Question: Generate PostgreSQL SQL for: How many figures are provided for Weeks' field goals?

CREATE TABLE table_25711913_8 (field_goals VARCHAR, player VARCHAR)

SELECT COUNT(field_goals) FROM table_25711913_8 WHERE player = 'Weeks';


Question: Generate PostgreSQL SQL for: What shareholder has 2.55 percent of votes?

CREATE TABLE table_206419_3 (shareholder VARCHAR, percent_of_votes VARCHAR)

SELECT shareholder FROM table_206419_3 WHERE percent_of_votes = '2.55';


Question: How many cybersecurity incidents were reported in the defense industry in the last 6 months?

CREATE TABLE Cybersecurity_Incidents_2 (id INT, industry VARCHAR(50), year INT, month INT, reported_count INT);

SELECT SUM(reported_count) FROM Cybersecurity_Incidents_2 WHERE industry = 'defense' AND year = YEAR(CURRENT_DATE) AND month >= MONTH(CURRENT_DATE) - 6;


Question: What was the total organic matter (in kg) in soil samples from each region in 2020?

CREATE TABLE soil_samples (id INT, region_id INT, organic_matter_kg FLOAT, date DATE);

SELECT region_id, SUM(organic_matter_kg) FROM soil_samples WHERE YEAR(date) = 2020 GROUP BY region_id;


Question: Find the total revenue for vegetarian dishes across all restaurants.

CREATE TABLE restaurants (id INT, name VARCHAR(255)); INSERT INTO restaurants (id, name) VALUES (1, 'Restaurant A'), (2, 'Restaurant B'); CREATE TABLE dishes (id INT, name VARCHAR(255), type VARCHAR(255), revenue INT, restaurant_id INT); INSERT INTO dishes (id, name, type, revenue, restaurant_id) VALUES (1, 'Quinoa Salad', 'vegetarian', 500, 1), (2, 'Chickpea Curry', 'vegetarian', 800, 1), (3, 'Cheeseburger', 'non-vegetarian', 1200, 1), (4, 'Pizza Margherita', 'vegetarian', 700, 2), (5, 'Fish and Chips', 'non-vegetarian', 1500, 2);

SELECT SUM(revenue) FROM dishes WHERE type = 'vegetarian';


Question: Generate PostgreSQL SQL for: On September 10, 1989 how many people attended the game?

CREATE TABLE table_name_65 (attendance VARCHAR, date VARCHAR)

SELECT attendance FROM table_name_65 WHERE date = 'september 10, 1989';


Question: How many users have no preference for any finish?

CREATE TABLE user_preference (id INT, user_id INT, product_id INT, finish VARCHAR(50), PRIMARY KEY (id)); INSERT INTO user_preference (id, user_id, product_id, finish) VALUES (1, 1, 1, 'Matte'), (2, 2, 1, 'Matte'), (3, 3, 2, 'Gloss'), (4, 4, NULL, NULL);

SELECT COUNT(*) as no_preference_users FROM user_preference WHERE finish IS NULL;


Question: Insert a new 'oil_platform' record for 'Blue Star Inc.' off the coast of Nigeria

CREATE TABLE oil_platform (id INT PRIMARY KEY, name TEXT, operator TEXT, location TEXT, depth FLOAT);

INSERT INTO oil_platform (name, operator, location, depth) VALUES ('Poseidon', 'Blue Star Inc.', 'Offshore Nigeria', 1200.5);


Question: How many albums were released each year by music artists?

CREATE TABLE Music_Albums (id INT, title VARCHAR(100), release_year INT, artist VARCHAR(100)); INSERT INTO Music_Albums (id, title, release_year, artist) VALUES (1, 'Back in Black', 1980, 'AC/DC'), (2, 'Thriller', 1982, 'Michael Jackson'), (3, 'The Dark Side of the Moon', 1973, 'Pink Floyd');

SELECT release_year, COUNT(*) FROM Music_Albums GROUP BY release_year;


Question: Generate PostgreSQL SQL for: What digital reaction has a hot 100 reaction of 4 (+4)?

CREATE TABLE table_name_81 (hot_digital_songs_reaction VARCHAR, hot_100_reaction VARCHAR)

SELECT hot_digital_songs_reaction FROM table_name_81 WHERE hot_100_reaction = '4 (+4)';


Question: What is the maximum number of wins for a player from Japan, for games that started in the last 60 days?

CREATE TABLE games (game_id INT, player_id INT, game_date DATE, wins INT); CREATE TABLE players (player_id INT, player_country VARCHAR(255));

SELECT MAX(wins) FROM games JOIN players ON games.player_id = players.player_id WHERE players.player_country = 'Japan' AND games.game_date >= (CURRENT_DATE - INTERVAL '60' DAY);


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

CREATE FUNCTION ltree_le(ltree,ltree)
RETURNS bool
AS 'MODULE_PATHNAME'
LANGUAGE C STRICT IMMUTABLE PARALLEL SAFE;

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


Question: What is the average age of female workers in the 'mining_operations' table?

CREATE TABLE mining_operations (id INT, name VARCHAR(50), position VARCHAR(50), age INT);

SELECT AVG(age) FROM mining_operations WHERE position = 'worker' AND gender = 'female';


Question: pgTAP test for Roletap (assertion 15).

SELECT * FROM check_test(
    roles_are( array_append(___myroles(current_role), '__howdy__'), 'whatever' ),
    false,
    'roles_are(roles, desc) missing and extras',
    'whatever',
    '    Extra roles:
        ' || quote_ident(current_role) || '
    Missing roles:
        __howdy__'
);

Explanation: SQL assertion from pgTAP test suite for Roletap.


Question: Generate PostgreSQL SQL for: Which Run 4 has a Run 1 of 57.37, and a Run 3 smaller than 57.45?

CREATE TABLE table_name_32 (run_4 INTEGER, run_1 VARCHAR, run_3 VARCHAR)

SELECT SUM(run_4) FROM table_name_32 WHERE run_1 = 57.37 AND run_3 < 57.45;


Question: Generate PostgreSQL SQL for: What CFL teams are part of Simon Fraser college?

CREATE TABLE table_10975034_4 (cfl_team VARCHAR, college VARCHAR)

SELECT cfl_team FROM table_10975034_4 WHERE college = 'Simon Fraser';


Question: What is the minimum health equity metric score achieved by any community?

CREATE TABLE community_health_equity (community_id INT, score INT); INSERT INTO community_health_equity (community_id, score) VALUES (1, 85), (2, 90), (3, 80), (4, 95), (5, 88);

SELECT MIN(score) FROM community_health_equity;


Question: Write the DML statement from PostgreSQL regression test 'brin' (example 71).

INSERT INTO brintest_2 VALUES ('(-1, 0)');

Explanation: DML from PostgreSQL core regression test for Brin.


Question: Generate PostgreSQL SQL for: Which member has an Electorate of kennedy?

CREATE TABLE table_name_50 (member VARCHAR, electorate VARCHAR)

SELECT member FROM table_name_50 WHERE electorate = 'kennedy';


Question: Generate PostgreSQL SQL for: How many years correspond to longitude of 36.8e and diameter greater than 697?

CREATE TABLE table_name_72 (year_named VARCHAR, longitude VARCHAR, diameter__km_ VARCHAR)

SELECT COUNT(year_named) FROM table_name_72 WHERE longitude = '36.8e' AND diameter__km_ > 697;


Question: Generate PostgreSQL SQL for: What is the score of the scores when Game had a Record of 17-29?

CREATE TABLE table_name_27 (game INTEGER, record VARCHAR)

SELECT SUM(game) FROM table_name_27 WHERE record = '17-29';


Question: What is the total cost of all projects in 'Bridge' category?

CREATE TABLE projects (id INT, name VARCHAR(255), category VARCHAR(255), cost FLOAT); INSERT INTO projects (id, name, category, cost) VALUES (1, 'Sample Bridge', 'Bridge', 5000000);

SELECT SUM(cost) FROM projects WHERE category = 'Bridge';


Question: How many individuals were impacted by access to justice initiatives in Latin America in 2020?

CREATE TABLE initiatives (initiative_id INT, year INT, individuals_impacted INT); INSERT INTO initiatives (initiative_id, year, individuals_impacted) VALUES (1, 2018, 500), (2, 2020, 800); CREATE TABLE locations (initiative_id INT, region VARCHAR(20)); INSERT INTO locations (initiative_id, region) VALUES (1, 'North America'), (2, 'Latin America');

SELECT SUM(initiatives.individuals_impacted) FROM initiatives INNER JOIN locations ON initiatives.initiative_id = locations.initiative_id WHERE locations.region = 'Latin America' AND initiatives.year = 2020;


Question: Find the number of unique mental health conditions that have been treated in each region.

CREATE TABLE treatments (id INT, condition_id INT, region VARCHAR(50)); INSERT INTO treatments (id, condition_id, region) VALUES (1, 1, 'Asia'), (2, 1, 'Europe'), (3, 2, 'Asia'), (4, 2, 'Europe'), (5, 3, 'Asia');

SELECT region, COUNT(DISTINCT condition_id) FROM treatments GROUP BY region;


Question: What is the minimum age of all country artists in the database?

CREATE TABLE artists (artist_id INT, artist_name VARCHAR(100), artist_age INT, genre VARCHAR(50)); INSERT INTO artists VALUES (1, 'Artist A', 35, 'Country'); INSERT INTO artists VALUES (2, 'Artist B', 28, 'Country'); INSERT INTO artists VALUES (3, 'Artist C', 45, 'Pop');

SELECT MIN(artist_age) FROM artists WHERE genre = 'Country';


Question: Generate PostgreSQL SQL for: Who was the away team at the Football Park match?

CREATE TABLE table_name_18 (away_team VARCHAR, ground VARCHAR)

SELECT away_team FROM table_name_18 WHERE ground = 'football park';


Question: Update the inspection_date for record with restaurant_id 123 to be '2022-08-01' in the food_inspections table

CREATE TABLE food_inspections (restaurant_id INT, inspection_date DATE);

UPDATE food_inspections SET inspection_date = '2022-08-01' WHERE restaurant_id = 123;


Question: PostgreSQL regression test 'money': Write the SELECT query (example 64).

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

SELECT count(*) FROM (SELECT '-123456789012345678'::money) AS _sub;


Question: Which cities in Japan have populations over 2 million, and what are their populations?

CREATE TABLE japan_cities (name TEXT, population INTEGER); INSERT INTO japan_cities (name, population) VALUES ('Tokyo', 37400068), ('Yokohama', 3668000);

SELECT name, population FROM japan_cities WHERE population > 2000000;


Question: What are the traditional dances, their origins, and the communities that perform them in South America?

CREATE TABLE Dances (id INT, name TEXT, origin TEXT); INSERT INTO Dances (id, name, origin) VALUES (1, 'Samba', 'Brazil'); CREATE TABLE Communities (id INT, dance_id INT, name TEXT); INSERT INTO Communities (id, dance_id, name) VALUES (1, 1, 'Cariocas');

SELECT D.name, D.origin, C.name FROM Dances D INNER JOIN Communities C ON D.id = C.dance_id WHERE C.name = 'Cariocas';


Question: Generate PostgreSQL SQL for: In the Hamburg Masters Tournament, during which Jiří Novák was absent(A) in 1996, how did he do in 2003?

CREATE TABLE table_name_71 (tournament VARCHAR)

SELECT 2003 FROM table_name_71 WHERE 1996 = 'a' AND tournament = 'hamburg masters';


Question: Generate PostgreSQL SQL for: What train number is heading to amritsar?

CREATE TABLE table_12095519_1 (train_no VARCHAR, destination VARCHAR)

SELECT train_no FROM table_12095519_1 WHERE destination = 'Amritsar';


Question: Generate PostgreSQL SQL for: What is the name of the algorithm with a directed/undirected of both and a subgraph-centric basis?

CREATE TABLE table_name_12 (name VARCHAR, directed___undirected VARCHAR, basis VARCHAR)

SELECT name FROM table_name_12 WHERE directed___undirected = 'both' AND basis = 'subgraph-centric';


Question: Which organizations focus on ethical AI in Africa?

CREATE TABLE organization (name VARCHAR(50), focus VARCHAR(50), location VARCHAR(50)); INSERT INTO organization (name, focus, location) VALUES ('AI for Good', 'Ethical AI', 'Kenya'), ('TechEthics Africa', 'Ethical AI', 'South Africa'), ('Data Justice NGO', 'Data Ethics', 'Nigeria');

SELECT name FROM organization WHERE focus = 'Ethical AI' AND location = 'Africa';


Question: List the number of mental health parity violations by state in 2021 and 2022.

CREATE TABLE MentalHealthParityViolations (ViolationId INT, Year INT, State VARCHAR(255)); INSERT INTO MentalHealthParityViolations (ViolationId, Year, State) VALUES (1, 2021, 'California'); INSERT INTO MentalHealthParityViolations (ViolationId, Year, State) VALUES (2, 2021, 'Texas'); INSERT INTO MentalHealthParityViolations (ViolationId, Year, State) VALUES (3, 2022, 'New York'); INSERT INTO MentalHealthParityViolations (ViolationId, Year, State) VALUES (4, 2022, 'Florida');

SELECT Year, State, COUNT(*) FROM MentalHealthParityViolations WHERE Year IN (2021, 2022) GROUP BY Year, State;


Question: Generate PostgreSQL SQL for: What is the most amount of goals any of the players had?

CREATE TABLE table_23963781_3 (goals INTEGER)

SELECT MAX(goals) FROM table_23963781_3;


Question: Insert a new volunteer record for Carlos with country Mexico.

CREATE TABLE Volunteers (id INT, name VARCHAR(255), country VARCHAR(255));

INSERT INTO Volunteers (name, country) VALUES ('Carlos', 'Mexico');


Question: Generate PostgreSQL SQL for: Find the distinct majors of students who have treasurer votes.

CREATE TABLE VOTING_RECORD (Treasurer_Vote VARCHAR); CREATE TABLE STUDENT (Major VARCHAR, StuID VARCHAR)

SELECT DISTINCT T1.Major FROM STUDENT AS T1 JOIN VOTING_RECORD AS T2 ON T1.StuID = T2.Treasurer_Vote;


Question: Generate PostgreSQL SQL for: What are the record(s) for the team with a winning percentage of .464?

CREATE TABLE table_15313204_1 (records VARCHAR, pct VARCHAR)

SELECT records FROM table_15313204_1 WHERE pct = '.464';


Question: Show a SQL definition from the pg_partman project (pg_partman--4.6.1--4.6.2, item 1).

CREATE OR REPLACE FUNCTION @extschema@.apply_constraints(p_parent_table text, p_child_table text DEFAULT NULL, p_analyze boolean DEFAULT FALSE, p_job_id bigint DEFAULT NULL) RETURNS void
    LANGUAGE plpgsql
    AS $$
DECLARE

ex_context                      text;
ex_detail                       text;
ex_hint                         text;
ex_message                      text;
v_child_exists                  text;
v_child_tablename               text;
v_col                           text;
v_constraint_cols               text[];
v_constraint_col_type           text;
v_constraint_name               text;
v_constraint_valid              boolean;
v_constraint_values             record;
v_control                       text;
v_control_type                  text;
v_datetime_string               text;
v_epoch                         text;
v_existing_constraint_name      text;
v_job_id                        bigint;
v_jobmon                        boolean;
v_jobmon_schema                 text;
v_last_partition                text;
v_last_partition_id             bigint;
v_last_partition_timestamp      timestamptz;
v_max_id                        bigint;
v_max_timestamp                 timestamptz;
v_new_search_path               text;
v_old_search_path               text;
v_optimize_constraint           int;
v_parent_schema                 text;
v_parent_table                  text;
v_parent_tablename              text;
v_partition_interval            text;
v_partition_suffix              text;
v_premake                       int;
v_sql                           text;
v_step_id                       bigint;
v_suffix_position               int;
v_type                          text;

BEGIN
/*
 * Apply constraints managed by partman extension
 */

SELECT parent_table
    , partition_type
    , control
    , premake
    , partition_interval
    , optimize_constraint
    , epoch
    , datetime_string
    , constraint_cols
    , jobmon
    , constraint_valid
INTO v_parent_table
    , v_type
    , v_control
    , v_premake
    , v_partition_interval
    , v_optimize_constraint
    , v_epoch
    , v_datetime_string
    , v_constraint_cols
    , v_jobmon
    , v_constraint_valid
FROM @extschema@.part_config
WHERE parent_table = p_parent_table
AND constraint_cols IS NOT NULL;

IF v_constraint_cols IS NULL THEN
    RAISE DEBUG 'apply_constraints: Given parent table (%) not set up for constraint management (constraint_cols is NULL)', p_parent_table;
    -- Returns silently to allow this function to be simply called by maintenance processes without having to check if config options are set.
    RETURN;
END IF;

SELECT schemaname, tablename
INTO v_parent_schema, v_parent_tablename
FROM pg_catalog.pg_tables
WHERE schemaname = split_part(v_parent_table, '.', 1)::name
AND tablename = split_part(v_parent_table, '.', 2)::name;

SELECT general_type INTO v_control_type FROM @extschema@.check_control_type(v_parent_schema, v_parent_tablename, v_control);

SELECT current_setting('search_path') INTO v_old_search_path;
IF length(v_old_search_path) > 0 THEN
   v_new_search_path := '@extschema@,pg_temp,'||v_old_search_path;
ELSE
    v_new_search_path := '@extschema@,pg_temp';
END IF;
IF v_jobmon THEN
    SELECT nspname INTO v_jobmon_schema FROM pg_catalog.pg_namespace n, pg_catalog.pg_extension e WHERE e.extname = 'pg_jobmon'::name AND e.extnamespace = n.oid;
    IF v_jobmon_schema IS NOT NULL THEN
        v_new_search_path := format('%s,%s',v_jobmon_schema, v_new_search_path);
    END IF;
END IF;
EXECUTE format('SELECT set_config(%L, %L, %L)', 'search_path', v_new_search_path, 'false');

IF v_jobmon_schema IS NOT NULL THEN
    IF p_job_id IS NULL THEN
        v_job_id := add_job(format('PARTMAN CREATE CONSTRAINT: %s', v_parent_table));
    ELSE
        v_job_id = p_job_id;
    END IF;
END IF;

-- If p_child_table is null, figure out the partition that is the one right before the optimize_constraint value backwards.
IF p_child_table IS NULL THEN
    IF v_jobmon_schema IS NOT NULL THEN
        v_step_id := add_step(v_job_id, 'Applying additional constraints: Automatically determining most recent child on which to apply constraints');
    END IF;

    SELECT partition_tablename INTO v_last_partition FROM @extschema@.show_partitions(v_parent_table, 'DESC') LIMIT 1;

    IF v_control_type = 'time' OR (v_control_type = 'id' AND v_epoch <> 'none') THEN
        SELECT child_start_time INTO v_last_partition_timestamp FROM @extschema@.show_partition_info(v_parent_schema||'.'||v_last_partition, v_partition_interval, v_parent_table);
        v_partition_suffix := to_char(v_last_partition_timestamp - (v_partition_interval::interval * (v_optimize_constraint + v_premake + 1) ), v_datetime_string);
    ELSIF v_control_type = 'id' THEN
        SELECT child_start_id INTO v_last_partition_id FROM @extschema@.show_partition_info(v_parent_schema||'.'||v_last_partition, v_partition_interval, v_parent_table);
        v_partition_suffix := (v_last_partition_id - (v_partition_interval::bigint * (v_optimize_constraint + v_premake + 1) ))::text;
    END IF;

    RAISE DEBUG 'apply_constraint: v_parent_tablename: %, v_last_partition: %, v_last_partition_timestamp: %, v_partition_suffix: %'
                , v_parent_tablename, v_last_partition, v_last_partition_timestamp, v_partition_suffix;

    v_child_tablename := @extschema@.check_name_length(v_parent_tablename, v_partition_suffix, TRUE);

    IF v_jobmon_schema IS NOT NULL THEN
        PERFORM update_step(v_step_id, 'OK', format('Target child table: %s.%s', v_parent_schema, v_child_tablename));
    END IF;
ELSE
    v_child_tablename = split_part(p_child_table, '.', 2);
END IF;

IF v_jobmon_schema IS NOT NULL THEN
    v_step_id := add_step(v_job_id, 'Applying additional constraints: Checking if target child table exists');
END IF;

SELECT tablename FROM pg_catalog.pg_tables INTO v_child_exists WHERE schemaname = v_parent_schema::name AND tablename = v_child_tablename::name;
IF v_child_exists IS NULL THEN
    IF v_jobmon_schema IS NOT NULL THEN
        PERFORM update_step(v_step_id, 'NOTICE', format('Target child table (%s) does not exist. Skipping constraint creation.', v_child_tablename));
        IF p_job_id IS NULL THEN
            PERFORM close_job(v_job_id);
        END IF;
    END IF;
    RAISE DEBUG 'Target child table (%) does not exist. Skipping constraint creation.', v_child_tablename;
    EXECUTE format('SELECT set_config(%L, %L, %L)', 'search_path', v_old_search_path, 'false');
    RETURN;
ELSE
    IF v_jobmon_schema IS NOT NULL THEN
        PERFORM update_step(v_step_id, 'OK', 'Done');
    END IF;
END IF;

FOREACH v_col IN ARRAY v_constraint_cols
LOOP
    SELECT con.conname
    INTO v_existing_constraint_name
    FROM pg_catalog.pg_constraint con
    JOIN pg_class c ON c.oid = con.conrelid
    JOIN pg_catalog.pg_namespace n ON c.relnamespace = n.oid
    JOIN pg_catalog.pg_attribute a ON con.conrelid = a.attrelid
    WHERE c.relname = v_child_tablename::name
        AND n.nspname = v_parent_schema::name
        AND con.conname LIKE 'partmanconstr_%'
        AND con.contype = 'c'
        AND a.attname = v_col::name
        AND ARRAY[a.attnum] OPERATOR(pg_catalog.<@) con.conkey
        AND a.attisdropped = false;

    IF v_jobmon_schema IS NOT NULL THEN
        v_step_id := add_step(v_job_id, format('Applying additional constraints: Applying new constraint on column: %s', v_col));
    END IF;

    IF v_existing_constraint_name IS NOT NULL THEN
        IF v_jobmon_schema IS NOT NULL THEN
            PERFORM update_step(v_step_id, 'NOTICE', format('Partman managed constraint already exists on this table (%s) and column (%s). Skipping creation.', v_child_tablename, v_col));
        END IF;
        RAISE DEBUG 'Partman managed constraint already exists on this table (%) and column (%). Skipping creation.', v_child_tablename, v_col ;
        CONTINUE;
    END IF;

    -- Ensure column name gets put on end of constraint name to help avoid naming conflicts
    v_constraint_name := @extschema@.check_name_length('partmanconstr_'||v_child_tablename, p_suffix := '_'||v_col);

    EXECUTE format('SELECT min(%I)::text AS min, max(%I)::text AS max FROM %I.%I', v_col, v_col, v_parent_schema, v_child_tablename) INTO v_constraint_values;

    IF v_constraint_values IS NOT NULL THEN
        v_sql := format('ALTER TABLE %I.%I ADD CONSTRAINT %I CHECK (%I >= %L AND %I <= %L)'
                            , v_parent_schema
                            , v_child_tablename
                            , v_constraint_name
                            , v_col
                            , v_constraint_values.min
                            , v_col
                            , v_constraint_values.max);

        IF v_constraint_valid = false THEN
            v_sql := format('%s NOT VALID', v_sql);
        END IF;

        RAISE DEBUG 'Constraint creation query: %', v_sql;
        EXECUTE v_sql;

        IF v_jobmon_schema IS NOT NULL THEN
            PERFORM update_step(v_step_id, 'OK', format('New constraint created: %s', v_sql));
        END IF;
    ELSE
        RAISE DEBUG 'Given column (%) contains all NULLs. No constraint created', v_col;
        IF v_jobmon_schema IS NOT NULL THEN
            PERFORM update_step(v_step_id, 'NOTICE', format('Given column (%s) contains all NULLs. No constraint created', v_col));
        END IF;
    END IF;

END LOOP;

IF p_analyze THEN
    IF v_jobmon_schema IS NOT NULL THEN
        v_step_id := add_step(v_job_id, format('Applying additional constraints: Running analyze on partition set: %s', v_parent_table));
    END IF;
    RAISE DEBUG 'Running analyze on partition set: %', v_parent_table;
    EXECUTE format('ANALYZE %I.%I', v_parent_schema, v_parent_tablename);

    IF v_jobmon_schema IS NOT NULL THEN
        PERFORM update_step(v_step_id, 'OK', 'Done');
    END IF;
END IF;

IF v_jobmon_schema IS NOT NULL THEN
    PERFORM close_job(v_job_id);
END IF;

EXECUTE format('SELECT set_config(%L, %L, %L)', 'search_path', v_old_search_path, 'false');

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 CREATE CONSTRAINT: %s'')', v_jobmon_schema, p_parent_table) 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: List all distinct risk assessment models and their average scores

CREATE TABLE RiskAssessment (ModelID INT, ModelName VARCHAR(50), PolicyholderID INT, Score INT); INSERT INTO RiskAssessment (ModelID, ModelName, PolicyholderID, Score) VALUES (1, 'Standard', 1, 80), (2, 'Comprehensive', 2, 85), (3, 'Standard', 3, 90), (4, 'Comprehensive', 4, 75), (5, 'Standard', 5, 95), (6, 'Comprehensive', 6, 80);

SELECT ModelName, AVG(Score) FROM RiskAssessment GROUP BY ModelName;


Question: Show total hours billed and total billing amount for each attorney in 'billing' table

CREATE TABLE billing (attorney_id INT, client_id INT, hours_billed INT, billing_rate DECIMAL(5,2));

SELECT attorney_id, SUM(hours_billed), SUM(hours_billed * billing_rate) FROM billing GROUP BY attorney_id;


Question: What is the total water consumption for the state of California in the last quarter?

CREATE TABLE MonthlyWaterUsage (Month DATE, State VARCHAR(20), Usage FLOAT); INSERT INTO MonthlyWaterUsage (Month, State, Usage) VALUES ('2022-01-01', 'California', 2500), ('2022-02-01', 'California', 3000), ('2022-03-01', 'California', 3500);

SELECT SUM(Usage) FROM MonthlyWaterUsage WHERE State = 'California' AND Month >= DATEADD(QUARTER, -1, GETDATE());


Question: Generate PostgreSQL SQL for: Name the most attendance for 25 january 2004

CREATE TABLE table_name_64 (attendance INTEGER, date VARCHAR)

SELECT MAX(attendance) FROM table_name_64 WHERE date = '25 january 2004';


Question: Generate PostgreSQL SQL for: What is the average for the player with BBM 5/85?

CREATE TABLE table_27922491_8 (average VARCHAR, bbm VARCHAR)

SELECT average FROM table_27922491_8 WHERE bbm = '5/85';


Question: What is the number of research projects in each department, broken down by department?

CREATE TABLE research_projects (id INT, title VARCHAR(255), department VARCHAR(100), funding DECIMAL(10,2)); INSERT INTO research_projects (id, title, department, funding) VALUES (1, 'Robotics Project', 'Engineering', 50000.00), (2, 'Theory Project', 'Mathematics', 0.00), (3, 'AI Project', 'Computer Science', 80000.00);

SELECT department, COUNT(*) as project_count FROM research_projects GROUP BY department;


Question: Which claims had a payment amount greater than $1000 in Texas?

CREATE TABLE ClaimsData (ClaimID INT, Payment DECIMAL(5,2), State VARCHAR(20)); INSERT INTO ClaimsData VALUES (1, 500.00, 'California'), (2, 1500.00, 'Texas'), (3, 800.00, 'California');

SELECT ClaimID, Payment FROM ClaimsData WHERE State = 'Texas' AND Payment > 1000;


Question: What is the maximum balance for customers from Germany?

CREATE TABLE customers (id INT, name VARCHAR(255), country VARCHAR(255)); INSERT INTO customers (id, name, country) VALUES (1, 'John Doe', 'USA'), (2, 'Jane Smith', 'Canada'), (3, 'Jim Brown', 'UK'), (4, 'Heidi Klum', 'Germany'); CREATE TABLE accounts (id INT, customer_id INT, balance DECIMAL(10, 2)); INSERT INTO accounts (id, customer_id, balance) VALUES (1, 1, 12000.00), (2, 1, 8000.00), (3, 2, 5000.00), (4, 4, 20000.00);

SELECT MAX(a.balance) FROM accounts a JOIN customers c ON a.customer_id = c.id WHERE c.country = 'Germany';


Question: Show a query using PostgreSQL contrib extension 'citext' (example 376).

SELECT regexp_split_to_table('hello world'::citext, E'\\s+') AS words;

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


Question: Generate PostgreSQL SQL for: What is the venue when the result was position of 17th?

CREATE TABLE table_name_27 (venue VARCHAR, position VARCHAR)

SELECT venue FROM table_name_27 WHERE position = '17th';


Question: Write the DML statement from PostgreSQL regression test 'constraints' (example 141).

INSERT INTO UNIQUE_TBL (t) VALUES ('seven');

Explanation: DML from PostgreSQL core regression test for Constraints.


Question: PostgreSQL regression test 'collate': Write the SELECT query (example 10).

SELECT * FROM collate_test1 WHERE b >= 'abc' COLLATE "C";

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

SELECT count(*) FROM (SELECT * FROM collate_test1 WHERE b >= 'abc' COLLATE "C") AS _sub;


Question: PostgreSQL Mvcc: show example 9.

SELECT pg_advisory_lock(id) FROM foo WHERE id = 12345; -- ok SELECT pg_advisory_lock(id) FROM foo WHERE id > 12345 LIMIT 100; -- danger! SELECT pg_advisory_lock(q.id) FROM ( SELECT id FROM foo WHERE id > 12345 LIMIT 100 ) q; -- ok;

Explanation: Example from PostgreSQL documentation on Mvcc.


Question: How many infectious disease cases were reported per month in 2021, in Texas?

CREATE TABLE infectious_diseases (id INT, state VARCHAR(2), report_date DATE, disease_type VARCHAR(20)); INSERT INTO infectious_diseases (id, state, report_date, disease_type) VALUES (1, 'TX', '2021-01-15', 'COVID-19'); INSERT INTO infectious_diseases (id, state, report_date, disease_type) VALUES (2, 'CA', '2021-02-20', 'Influenza'); INSERT INTO infectious_diseases (id, state, report_date, disease_type) VALUES (3, 'TX', '2021-03-05', 'Measles');

SELECT MONTH(report_date) as month, COUNT(*) as cases FROM infectious_diseases WHERE state = 'TX' AND YEAR(report_date) = 2021 GROUP BY month;


Question: Write the DML statement from PostgreSQL regression test 'float4' (example 18).

INSERT INTO FLOAT4_TBL(f1) VALUES ('-10e-400');

Explanation: DML from PostgreSQL core regression test for Float4.


Question: Generate PostgreSQL SQL for: What rank did the nation with athlete peter snell category:articles with hcards have?

CREATE TABLE table_22355_11 (rank VARCHAR, athlete VARCHAR)

SELECT COUNT(rank) FROM table_22355_11 WHERE athlete = 'Peter Snell Category:Articles with hCards';


Question: What is the average depth of all trenches in the Pacific Ocean?

CREATE TABLE ocean_trenches (name VARCHAR(50), location VARCHAR(50), avg_depth FLOAT); INSERT INTO ocean_trenches

SELECT AVG(avg_depth) FROM ocean_trenches WHERE location = 'Pacific Ocean';


Question: Generate PostgreSQL SQL for: What is the Away Team score of North Melbourne?

CREATE TABLE table_name_24 (away_team VARCHAR)

SELECT away_team AS score FROM table_name_24 WHERE away_team = 'north melbourne';


Question: What is the average claim amount by policy type and month?

SELECT PolicyType, EXTRACT(MONTH FROM ClaimDate) AS Month, AVG(ClaimAmount) AS AvgClaimAmount FROM Claims GROUP BY PolicyType, Month;


Question: What was the total revenue for eco-friendly garments in India in Q2 2021?

CREATE TABLE india_eco_friendly_garments (garment_type VARCHAR(255), sales_amount DECIMAL(10,2), quarter INT, year INT); INSERT INTO india_eco_friendly_garments (garment_type, sales_amount, quarter, year) VALUES ('Shirt', 700.00, 2, 2021), ('Pants', 800.00, 2, 2021);

SELECT SUM(sales_amount) FROM india_eco_friendly_garments WHERE quarter = 2 AND year = 2021;


Question: Show a query using PostgreSQL contrib extension 'pgcrypto' (example 8).

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


Question: What is the average revenue per night for hotels in Spain?

CREATE TABLE hotels (id INT, name TEXT, country TEXT, is_eco_friendly BOOLEAN, daily_revenue INT); INSERT INTO hotels (id, name, country, is_eco_friendly, daily_revenue) VALUES (1, 'Barcelona Eco Hotel', 'Spain', true, 300), (2, 'Madrid Hotel', 'Spain', false, 250), (3, 'Ibiza Green Hotel', 'Spain', true, 400);

SELECT AVG(daily_revenue) FROM hotels WHERE country = 'Spain';


Question: Write the DML statement from PostgreSQL regression test 'numeric' (example 250).

Explanation: DML from PostgreSQL core regression test for Numeric.


Question: What is the risk score for each policyholder?


Question: Generate PostgreSQL SQL for: What is the candidate for south carolina 4?

CREATE TABLE table_1342256_40 (candidates VARCHAR, district VARCHAR)

SELECT candidates FROM table_1342256_40 WHERE district = 'South Carolina 4';


Question: Identify the programs with no funding

CREATE TABLE program_funding_2 (program_id INT, amount DECIMAL(10,2)); INSERT INTO program_funding_2 (program_id, amount) VALUES (1, 5000.00), (2, 7000.00), (4, 3000.00);

SELECT p.name FROM programs p LEFT JOIN program_funding_2 f ON p.id = f.program_id WHERE f.program_id IS NULL;


Question: Generate PostgreSQL SQL for: Which tournament had the result of a W in 2009?

CREATE TABLE table_name_67 (tournament VARCHAR)

SELECT tournament FROM table_name_67 WHERE 2009 = 'w';


Question: What's the total investment amount for 'renewable energy' and 'sustainable agriculture' strategies combined, by year?

CREATE TABLE investments_strategies_amount (id INT, investment_year INT, strategy VARCHAR(30), investment_amount FLOAT); INSERT INTO investments_strategies_amount (id, investment_year, strategy, investment_amount) VALUES (1, 2019, 'renewable energy', 120000), (2, 2020, 'sustainable agriculture', 185000), (3, 2018, 'renewable energy', 175000);

SELECT investment_year, SUM(investment_amount) FROM investments_strategies_amount WHERE strategy IN ('renewable energy', 'sustainable agriculture') GROUP BY investment_year;


Question: Generate PostgreSQL SQL for: What player has a date of 12-02-2003?

CREATE TABLE table_name_98 (player VARCHAR, date VARCHAR)

SELECT player FROM table_name_98 WHERE date = '12-02-2003';


Question: What is the average social impact score by region?

CREATE TABLE social_impact_data (id INT, region VARCHAR(50), score INT); INSERT INTO social_impact_data (id, region, score) VALUES (1, 'Northeast', 80), (2, 'Southeast', 85), (3, 'Midwest', 75), (4, 'West', 90);

SELECT region, AVG(score) as avg_score FROM social_impact_data GROUP BY region;


Question: Generate PostgreSQL SQL for: What score was given at the August 17, 2005 match?

CREATE TABLE table_name_47 (score VARCHAR, date VARCHAR)

SELECT score FROM table_name_47 WHERE date = 'august 17, 2005';


Question: Generate PostgreSQL SQL for: Where did the cable-stayed Badong Bridge  open in 2005?

CREATE TABLE table_name_18 (location VARCHAR, name VARCHAR, type VARCHAR, opened VARCHAR)

SELECT location FROM table_name_18 WHERE type = 'cable-stayed' AND opened = 2005 AND name = 'badong bridge';


Question: Who are the most influential artists in the 'Influential_Artists' table?

CREATE TABLE Influential_Artists (artist_id INT, artist_name VARCHAR(255), influence_score FLOAT);

SELECT artist_name FROM Influential_Artists ORDER BY influence_score DESC LIMIT 1;


Question: Generate PostgreSQL SQL for: Please show each industry and the corresponding number of companies in that industry.

CREATE TABLE Companies (Industry VARCHAR)

SELECT Industry, COUNT(*) FROM Companies GROUP BY Industry;


Question: Generate PostgreSQL SQL for: What is the enrollment ratio for preschool in the region where enrollment ratio for tertiary is 29.55?

CREATE TABLE table_25042332_22 (preschool__0_5_years_ VARCHAR, tertiary__18_24_years_ VARCHAR)

SELECT preschool__0_5_years_ FROM table_25042332_22 WHERE tertiary__18_24_years_ = '29.55';


Question: What is the maximum number of members in a union?

CREATE TABLE union_membership (id INT, union VARCHAR(20), member_count INT); INSERT INTO union_membership (id, union, member_count) VALUES (1, 'construction', 3500), (2, 'education', 8000), (3, 'manufacturing', 5000);

SELECT MAX(member_count) FROM union_membership;


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

SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE mod(a,20) <= ANY (ARRAY[1, NULL, 2, 3]) AND mod(b::int,10) IN (1, 2, NULL, 3)');

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) <= ANY (ARRAY[1, NULL, 2, 3]) AND mod(b::int,10) IN (1, 2, NULL, 3)')) AS _sub;


Question: Generate PostgreSQL SQL for: Who built the conant creek pegram truss railroad bridge?

CREATE TABLE table_name_71 (built VARCHAR, name VARCHAR)

SELECT built FROM table_name_71 WHERE name = 'conant creek pegram truss railroad bridge';


Question: Generate PostgreSQL SQL for: What is the Director for the episode titled “some lapse of time”?

CREATE TABLE table_name_85 (director VARCHAR, title VARCHAR)

SELECT director FROM table_name_85 WHERE title = '“some lapse of time”';


Question: What is the total quantity of gold mined by each mine, partitioned by quarter and ordered by the most mined?

CREATE TABLE mine (mine_id INT, mine_name VARCHAR(50), location VARCHAR(50), quantity_gold_mined INT); INSERT INTO mine (mine_id, mine_name, location, quantity_gold_mined) VALUES (1, 'Jade Mine', 'South Africa', 2000), (2, 'Emerald Mine', 'Russia', 3000), (3, 'Ruby Mine', 'Chile', 4000);

SELECT mine_name, SUM(quantity_gold_mined) OVER (PARTITION BY DATE_TRUNC('quarter', date) ORDER BY SUM(quantity_gold_mined) DESC) as total_gold_mined FROM mine_gold_stats;


Question: PostgreSQL regression test 'partition_aggregate': Write the SELECT query (example 25).

SELECT c, sum(a), avg(b), count(*) FROM pagg_tab GROUP BY 1 HAVING avg(d) < 15 ORDER BY 1, 2, 3;

Explanation: Regression test for Partition Aggregate in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT c, sum(a), avg(b), count(*) FROM pagg_tab GROUP BY 1 HAVING avg(d) < 15 ORDER BY 1, 2, 3) AS _sub;


Question: Generate PostgreSQL SQL for: What country has a Youth (15-24) Literacy Rate Total of 99%, and a Youth Men of 98%?

CREATE TABLE table_name_50 (country VARCHAR, youth__15_24__literacy_rate_total VARCHAR, youth_men VARCHAR)

SELECT country FROM table_name_50 WHERE youth__15_24__literacy_rate_total = '99%' AND youth_men = '98%';


Question: Generate PostgreSQL SQL for: What team was the opponent on 09/20/1975?

CREATE TABLE table_name_62 (opponent VARCHAR, date VARCHAR)

SELECT opponent FROM table_name_62 WHERE date = '09/20/1975';


Question: Generate PostgreSQL SQL for: Show the name of storms which don't have affected region in record.

CREATE TABLE affected_region (name VARCHAR, storm_id VARCHAR); CREATE TABLE storm (name VARCHAR, storm_id VARCHAR)

SELECT name FROM storm WHERE NOT storm_id IN (SELECT storm_id FROM affected_region);


Question: Show all records in the space_exploration table where the mission_status is 'Completed' or agency is 'ESA'

CREATE TABLE space_exploration (id INT, mission_name VARCHAR(255), mission_status VARCHAR(255), agency VARCHAR(255), launch_date DATE);

SELECT * FROM space_exploration WHERE mission_status = 'Completed' OR agency = 'ESA';


Question: Find the maximum and minimum number of employees for companies in the e-commerce sector.

CREATE TABLE companies (id INT, name TEXT, industry TEXT, employees INT, founding_date DATE);

SELECT MAX(employees), MIN(employees) FROM companies WHERE industry = 'E-commerce';


Question: Find the number of graduate students enrolled in each department, excluding those enrolled in the 'Computer Science' department.

CREATE TABLE graduate_students (id INT, department VARCHAR(20), enrollment_status VARCHAR(10)); INSERT INTO graduate_students (id, department, enrollment_status) VALUES (1, 'Computer Science', 'Enrolled'), (2, 'Physics', 'Enrolled'), (3, 'Mathematics', 'Not Enrolled');

SELECT department, COUNT(*) as enrollment_count FROM graduate_students WHERE department != 'Computer Science' GROUP BY department;


Question: PL/pgSQL test: Plpgsql Trap (example 7).

create function trap_matching_test(int) returns int as $$
declare x int;
	sx smallint;
	y int;
begin
	begin	-- start a subtransaction
		x := 100 / $1;
		sx := $1;
		select into y data from match_source where id =
			(select id from match_source b where ten = $1);
	exception
		when data_exception then  -- category match
			raise notice 'caught data_exception';
			x := -1;
		when NUMERIC_VALUE_OUT_OF_RANGE OR CARDINALITY_VIOLATION then
			raise notice 'caught numeric_value_out_of_range or cardinality_violation';
			x := -2;
	end;
	return x;
end$$ language plpgsql;

Explanation: PL/pgSQL example from PostgreSQL source test for Plpgsql Trap.


Question: Generate PostgreSQL SQL for: What year was the Grand Prix Passing Shot Bordeaux that had Runners-up of Diego Nargiso?

CREATE TABLE table_name_96 (year VARCHAR, tournament_name VARCHAR, runners_up VARCHAR)

SELECT year FROM table_name_96 WHERE tournament_name = 'grand prix passing shot bordeaux' AND runners_up = 'diego nargiso';


Question: Generate PostgreSQL SQL for: What was the model that had years 2004-?

CREATE TABLE table_name_67 (model VARCHAR, years VARCHAR)

SELECT model FROM table_name_67 WHERE years = '2004-';


Question: What are the names and quantities of chemicals produced by factories located in California?

CREATE TABLE factories (id INT, name TEXT, location TEXT); INSERT INTO factories (id, name, location) VALUES (1, 'Factory A', 'California'), (2, 'Factory B', 'Texas'); CREATE TABLE chemical_produced (factory_id INT, chemical_name TEXT, quantity INT); INSERT INTO chemical_produced (factory_id, chemical_name, quantity) VALUES (1, 'Chemical X', 100), (1, 'Chemical Y', 200), (2, 'Chemical Z', 300);

SELECT chemical_name, quantity FROM chemical_produced CP JOIN factories F ON CP.factory_id = F.id WHERE F.location = 'California';


Question: Update 'emergency_response' table to set all response times above 60 minutes to 60 minutes

CREATE TABLE emergency_response (id INT, incident_id INT, response_time INT, PRIMARY KEY(id));

UPDATE emergency_response SET response_time = 60 WHERE response_time > 60;


Question: Generate PostgreSQL SQL for: What is the highest Year, when Opponent is #2 Syracuse?

CREATE TABLE table_name_52 (year INTEGER, opponent VARCHAR)

SELECT MAX(year) FROM table_name_52 WHERE opponent = '#2 syracuse';


Question: Generate PostgreSQL SQL for: What is the build date when total produced is 2?

CREATE TABLE table_name_80 (build_date VARCHAR, total_produced VARCHAR)

SELECT build_date FROM table_name_80 WHERE total_produced = 2;


Question: Generate PostgreSQL SQL for: When John Senden was the runner-up, what was the To Par?

CREATE TABLE table_name_76 (to_par VARCHAR, runner_s__up VARCHAR)

SELECT to_par FROM table_name_76 WHERE runner_s__up = 'john senden';


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

SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a < 1 AND b < ''1''');

SELECT count(*) FROM (SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a < 1 AND b < ''1''')) AS _sub;


Question: Generate PostgreSQL SQL for: For Saint-Paul parish, if it has an area of over 228.65 kilometers how many people live there?

CREATE TABLE table_name_59 (population VARCHAR, official_name VARCHAR, area_km_2 VARCHAR)

SELECT COUNT(population) FROM table_name_59 WHERE official_name = 'saint-paul' AND area_km_2 > 228.65;


Question: What is the minimum rating of sustainable beauty products sold in Asia?

CREATE TABLE sustainability (id INT, product VARCHAR(255), sustainable BOOLEAN, rating FLOAT, region VARCHAR(255)); INSERT INTO sustainability (id, product, sustainable, rating, region) VALUES (1, 'Moisturizer', true, 4.5, 'Asia'), (2, 'Toner', false, 3.0, 'Asia'), (3, 'Cleanser', true, 4.0, 'Asia');

SELECT MIN(rating) FROM sustainability WHERE sustainable = true AND region = 'Asia';


Question: What is the total funding received by the 'Artificial Intelligence' research grant?

CREATE TABLE Grants (ID INT, Name VARCHAR(50), Category VARCHAR(50), Amount FLOAT); INSERT INTO Grants (ID, Name, Category, Amount) VALUES (1, 'AI Research', 'Artificial Intelligence', 500000), (2, 'ML Project', 'Machine Learning', 300000);

SELECT SUM(Amount) FROM Grants WHERE Category = 'Artificial Intelligence';


Question: What are the mental health scores for students in 'Intro to Psychology'?

CREATE TABLE mental_health (student_id INT, course_name TEXT, score INT); INSERT INTO mental_health (student_id, course_name, score) VALUES (123, 'Intro to Psychology', 75), (456, 'Intro to Psychology', 85), (789, 'Intro to Psychology', 95);

SELECT student_id, score FROM mental_health WHERE course_name = 'Intro to Psychology';


Question: pgTAP test for Ownership (assertion 96).

SELECT * FROM check_test(
    function_owner_is('public', 'somefunction', ARRAY['integer'], 'no one', 'mumble'),
	false,
    'function_owner_is(sch, function, args[integer], non-user, desc)',
    'mumble',
    '        have: ' || current_user || '
        want: no one'
);

Explanation: SQL assertion from pgTAP test suite for Ownership.


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

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

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


Question: PostgreSQL regression test 'stats_import': Write the SELECT query (example 221).

SELECT e.most_common_vals, e.most_common_val_nulls,
       e.most_common_freqs, e.most_common_base_freqs
FROM pg_stats_ext AS e
WHERE e.statistics_schemaname = 'stats_import' AND
    e.statistics_name = 'test_stat_mcv_exprs' AND
    e.inherited = false \gx

-- Incorrect extended stats kind, mcv not supported
SELECT pg_catalog.pg_restore_extended_stats(
  'schemaname', 'stats_import',
  'relname', 'test',
  'statistics_schemaname', 'stats_import',
  'statistics_name', 'test_stat_dependencies',
  'inherited', false,
  'most_common_vals', '{{four,NULL},
                        {one,"(1,1.1,ONE,01-01-2001,\"{\"\"xkey\"\": \"\"xval\"\"}\")"},
                        {tre,"(3,3.3,TRE,03-03-2003,)"},
                        {two,"(2,2.2,TWO,02-02-2002,\"[true, 4, \"\"six\"\"]\")"}}'::text[],
  'most_common_freqs', '{0.25,0.25,0.25,0.25}'::double precision[],
  'most_common_base_freqs', '{0.0625,0.0625,0.0625,0.0625}'::double precision[]);

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

SELECT count(*) FROM (SELECT e.most_common_vals, e.most_common_val_nulls,
       e.most_common_freqs, e.most_common_base_freqs
FROM pg_stats_ext AS e
WHERE e.statistics_schemaname = 'stats_import' AND
    e.statistics_name = 'test_stat_mcv_exprs' AND
    e.inherited = false \gx

-- Incorrect extended stats kind, mcv not supported
SELECT pg_catalog.pg_restore_extended_stats(
  'schemaname', 'stats_import',
  'relname', 'test',
  'statistics_schemaname', 'stats_import',
  'statistics_name', 'test_stat_dependencies',
  'inherited', false,
  'most_common_vals', '{{four,NULL},
                        {one,"(1,1.1,ONE,01-01-2001,\"{\"\"xkey\"\": \"\"xval\"\"}\")"},
                        {tre,"(3,3.3,TRE,03-03-2003,)"},
                        {two,"(2,2.2,TWO,02-02-2002,\"[true, 4, \"\"six\"\"]\")"}}'::text[],
  'most_common_freqs', '{0.25,0.25,0.25,0.25}'::double precision[],
  'most_common_base_freqs', '{0.0625,0.0625,0.0625,0.0625}'::double precision[])) AS _sub;


Question: What is the maximum billing amount for cases handled by female attorneys?

CREATE TABLE AttorneyGender (AttorneyID INT, Gender VARCHAR(10)); INSERT INTO AttorneyGender (AttorneyID, Gender) VALUES (1, 'Female'), (2, 'Male'), (3, 'Female');

SELECT MAX(BillingAmount) FROM AttorneyBilling JOIN AttorneyGender ON AttorneyBilling.AttorneyID = AttorneyGender.AttorneyID WHERE Gender = 'Female';


Question: Generate PostgreSQL SQL for: What Tournament on October 24, 1982 had Alycia Moulton as the Partner?

CREATE TABLE table_name_23 (tournament VARCHAR, date VARCHAR, partner VARCHAR)

SELECT tournament FROM table_name_23 WHERE date = 'october 24, 1982' AND partner = 'alycia moulton';


Question: Show the total revenue for each month in 2022.

CREATE TABLE MonthlyRevenue (Month VARCHAR(10), Revenue INT); INSERT INTO MonthlyRevenue (Month, Revenue) VALUES ('January', 5000), ('February', 6000), ('March', 7000);

SELECT Month, SUM(Revenue) FROM MonthlyRevenue WHERE Month IN ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December') AND YEAR(STR_TO_DATE(Month, '%B')) = 2022 GROUP BY Month;


Question: What is the average speed of vessels that transport hazardous materials?

CREATE TABLE Vessels (VesselID INT, Name TEXT, Type TEXT, MaxSpeed FLOAT); CREATE TABLE Cargo (CargoID INT, VesselID INT, Material TEXT, Quantity INT); INSERT INTO Vessels VALUES (1, 'Tanker 1', 'Oil Tanker', 15.5); INSERT INTO Cargo VALUES (1, 1, 'Hazardous', NULL);

SELECT AVG(Vessels.MaxSpeed) FROM Vessels INNER JOIN Cargo ON Vessels.VesselID = Cargo.VesselID WHERE Cargo.Material = 'Hazardous';


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

--
-- gist_page_items()
--
CREATE FUNCTION gist_page_items(IN page bytea,
    IN index_oid regclass,
    OUT itemoffset smallint,
    OUT ctid tid,
    OUT itemlen smallint,
    OUT dead boolean,
    OUT keys text)
RETURNS SETOF record
AS 'MODULE_PATHNAME', 'gist_page_items'
LANGUAGE C STRICT PARALLEL SAFE;

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


Question: Generate PostgreSQL SQL for: In what county is the school of Merrillville?

CREATE TABLE table_name_17 (county VARCHAR, school VARCHAR)

SELECT county FROM table_name_17 WHERE school = 'merrillville';


Question: Write the DDL statement from PostgreSQL regression test 'plpgsql' (example 655).

create function arrayassign1() returns text[] language plpgsql as $$
declare
 r record;
begin
  r := row(12, '{foo,bar,baz}')::rtype;
  r.ar[2] := 'replace';
  return r.ar;
end$$;

Explanation: DDL from PostgreSQL core regression test for Plpgsql.


Question: List biosensor technologies in descending order based on their maximum temperature

CREATE SCHEMA if not exists biosensors;CREATE TABLE if not exists biosensors.temperature (id INT, biosensor_name VARCHAR(255), temperature DECIMAL(10,2)); INSERT INTO biosensors.temperature (id, biosensor_name, temperature) VALUES (1, 'BioTherm', 37.5), (2, 'BioSense', 38.2), (3, 'BioTemp', 37.8), (4, 'BioCool', 35.0);

SELECT biosensor_name, MAX(temperature) max_temperature FROM biosensors.temperature GROUP BY biosensor_name ORDER BY max_temperature DESC;


Question: Generate PostgreSQL SQL for: Which From club had a Transfer fee of £3.87m?

CREATE TABLE table_name_40 (from_club VARCHAR, transfer_fee VARCHAR)

SELECT from_club FROM table_name_40 WHERE transfer_fee = '£3.87m';