Question: What is the total amount of research grants awarded to female faculty members in the 'faculty' and 'research_grants' tables?

CREATE TABLE faculty (id INT, name VARCHAR(255), gender VARCHAR(10), department VARCHAR(255)); INSERT INTO faculty (id, name, gender, department) VALUES (1, 'Alice', 'Female', 'Physics'), (2, 'Bob', 'Male', 'Mathematics'), (3, 'Charlie', 'Male', 'Chemistry'), (4, 'Diana', 'Female', 'Biology');

SELECT SUM(rg.amount) FROM research_grants rg JOIN faculty f ON rg.department = f.department WHERE f.gender = 'Female';


Question: Write the DML statement from PostgreSQL regression test 'transactions' (example 131).

Explanation: DML from PostgreSQL core regression test for Transactions.


Question: Generate PostgreSQL SQL for: What is the Report on November 15, 2000?

CREATE TABLE table_name_18 (report VARCHAR, date VARCHAR)

SELECT report FROM table_name_18 WHERE date = 'november 15, 2000';


Question: Generate PostgreSQL SQL for: What is the score of the season in the host city kėdainiai?

CREATE TABLE table_name_59 (score VARCHAR, host_city VARCHAR)

SELECT score FROM table_name_59 WHERE host_city = 'kėdainiai';


Question: Generate PostgreSQL SQL for: What round was jerry corcoran drafted in as pick number 114?

CREATE TABLE table_name_63 (round INTEGER, pick VARCHAR, player VARCHAR)

SELECT MAX(round) FROM table_name_63 WHERE pick > 114 AND player = 'jerry corcoran';


Question: What is the average flight time for each aircraft model by year?

CREATE TABLE aircraft_flights (id INT, model VARCHAR(50), flight_hours DECIMAL(5,2), year INT); INSERT INTO aircraft_flights (id, model, flight_hours, year) VALUES (1, 'Boeing 737', 3500.5, 2019), (2, 'Airbus A320', 3200.2, 2019), (3, 'Boeing 787', 3800.8, 2018), (4, 'SpaceX Starship', 5000, 2022);

SELECT model, year, AVG(flight_hours) as avg_flight_time FROM aircraft_flights GROUP BY model, year;


Question: Show a query using PostgreSQL contrib extension 'pageinspect' (example 18).

SELECT * FROM hash_bitmap_info('test_hash_a_idx', 4);

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


Question: Generate PostgreSQL SQL for: For the call sign w242at what's the city the license plate is registered to?

CREATE TABLE table_name_78 (city_of_license VARCHAR, call_sign VARCHAR)

SELECT city_of_license FROM table_name_78 WHERE call_sign = 'w242at';


Question: Insert new records for 3 donors from the 'Donors' table

CREATE TABLE Donors (DonorID INT, FirstName VARCHAR(50), LastName VARCHAR(50), DonationDate DATE, Amount DECIMAL(10,2));


Question: What is the total carbon tax revenue (in USD) for each country, ranked from highest to lowest?

CREATE TABLE carbon_tax (country VARCHAR(50), revenue FLOAT); INSERT INTO carbon_tax (country, revenue) VALUES ('Country A', 5000000), ('Country B', 6000000), ('Country C', 4000000), ('Country D', 7000000);

SELECT country, revenue, ROW_NUMBER() OVER (ORDER BY revenue DESC) as rank FROM carbon_tax;


Question: pgTAP test for Ownership (assertion 134).

SELECT * FROM check_test(
    type_owner_is('sometype', '__no-one', 'mumble'),
	false,
    'type_owner_is(type, non-user, desc)',
    'mumble',
    '        have: ' || current_user || '
        want: __no-one'
);

Explanation: SQL assertion from pgTAP test suite for Ownership.


Question: Insert new labor productivity data

CREATE TABLE productivity (id INT PRIMARY KEY, company VARCHAR(100), value DECIMAL(5,2));

INSERT INTO productivity (company, value) VALUES ('Teck Resources', 320);


Question: Who are the producers with the highest average rating for TV shows about social justice?

CREATE TABLE shows (id INT, title TEXT, rating FLOAT, producer TEXT, genre TEXT); INSERT INTO shows (id, title, rating, producer, genre) VALUES (1, 'Show1', 7.5, 'Producer1', 'Social Justice'), (2, 'Show2', 8.2, 'Producer2', 'Social Justice'), (3, 'Show3', 6.8, 'Producer1', 'Comedy'), (4, 'Show4', 9.0, 'Producer3', 'Social Justice'), (5, 'Show5', 7.0, 'Producer1', 'Social Justice');

SELECT producer, AVG(rating) FROM shows WHERE genre = 'Social Justice' GROUP BY producer ORDER BY AVG(rating) DESC;


Question: Show the total revenue from concert ticket sales for each genre.

CREATE TABLE Genres (GenreID INT, GenreName VARCHAR(255)); INSERT INTO Genres (GenreID, GenreName) VALUES (1, 'Pop'), (2, 'Rock'), (3, 'Jazz'), (4, 'Hip Hop'), (5, 'Country'); CREATE TABLE Concerts (ConcertID INT, GenreID INT, Venue VARCHAR(255), TicketPrice DECIMAL(5,2)); INSERT INTO Concerts (ConcertID, GenreID, Venue, TicketPrice) VALUES (1, 1, 'Venue1', 50.00), (2, 2, 'Venue2', 60.00), (3, 3, 'Venue3', 40.00), (4, 4, 'Venue4', 70.00), (5, 5, 'Venue5', 30.00), (6, 1, 'Venue6', 55.00), (7, 2, 'Venue7', 65.00), (8, 3, 'Venue8', 45.00);

SELECT G.GenreName, SUM(C.TicketPrice) as TotalRevenue FROM Genres G JOIN Concerts C ON G.GenreID = C.GenreID GROUP BY G.GenreName;


Question: Find the average landfill capacity in APAC for countries with a capacity greater than 100,000 cubic meters.

CREATE TABLE LandfillCapacityAPAC (id INT, country VARCHAR(50), region VARCHAR(50), capacity_cubic_meters INT); INSERT INTO LandfillCapacityAPAC (id, country, region, capacity_cubic_meters) VALUES (1, 'China', 'APAC', 120000), (2, 'Japan', 'APAC', 90000), (3, 'India', 'APAC', 150000);

SELECT AVG(capacity_cubic_meters) FROM LandfillCapacityAPAC WHERE capacity_cubic_meters > 100000 AND region = 'APAC';


Question: PostgreSQL regression test 'xml': Write the SELECT query (example 115).

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

SELECT count(*) FROM (SELECT xmlagg(data) FROM xmltest) AS _sub;


Question: What is the maximum number of humanitarian assistance personnel deployed by a single organization?

CREATE TABLE humanitarian_assistance (id INT PRIMARY KEY, organization VARCHAR(100), personnel INT); INSERT INTO humanitarian_assistance (id, organization, personnel) VALUES (1, 'Org 1', 1200), (2, 'Org 2', 1500), (3, 'Org 3', 1000);

SELECT MAX(personnel) FROM humanitarian_assistance;


Question: List the number of mobile and broadband subscribers per region for the most recent quarter.

CREATE TABLE regions (region_id INT, region_name VARCHAR(50)); INSERT INTO regions (region_id, region_name) VALUES (1, 'North'), (2, 'South'), (3, 'East'), (4, 'West'); CREATE TABLE mobile_subscribers (subscriber_id INT, region_id INT, join_date DATE); INSERT INTO mobile_subscribers (subscriber_id, region_id, join_date) VALUES (1, 1, '2021-01-01'), (2, 2, '2021-03-01'), (3, 3, '2021-02-01'), (4, 4, '2021-04-01'); CREATE TABLE broadband_subscribers (subscriber_id INT, region_id INT, join_date DATE); INSERT INTO broadband_subscribers (subscriber_id, region_id, join_date) VALUES (5, 1, '2021-01-15'), (6, 2, '2021-03-15'), (7, 3, '2021-02-15'), (8, 4, '2021-04-15');

SELECT r.region_name, COUNT(m.subscriber_id) AS mobile_count, COUNT(b.subscriber_id) AS broadband_count FROM regions r LEFT JOIN mobile_subscribers m ON r.region_id = m.region_id LEFT JOIN broadband_subscribers b ON r.region_id = b.region_id WHERE QUARTER(m.join_date) = QUARTER(CURRENT_DATE()) AND YEAR(m.join_date) = YEAR(CURRENT_DATE()) GROUP BY r.region_id;


Question: Generate PostgreSQL SQL for: What is the highest administrative panel value with an agricultural panel less than 1 and a labour panel value less than 5?

CREATE TABLE table_name_56 (administrative_panel INTEGER, agricultural_panel VARCHAR, labour_panel VARCHAR)

SELECT MAX(administrative_panel) FROM table_name_56 WHERE agricultural_panel < 1 AND labour_panel < 5;


Question: Generate PostgreSQL SQL for: where catalog number is 81258 , what are all the studio ?

CREATE TABLE table_11222744_2 (studio VARCHAR, catalog_number VARCHAR)

SELECT studio FROM table_11222744_2 WHERE catalog_number = '81258';


Question: Identify the unique age ranges of members who participated in 'yoga' or 'spinning' classes.

CREATE TABLE member_classes (member_id INT, class_type VARCHAR(50), age INT); INSERT INTO member_classes (member_id, class_type, age) VALUES (1, 'yoga', 30), (2, 'spinning', 35), (3, 'yoga', 40), (4, 'spinning', 25), (5, 'yoga', 30);

SELECT DISTINCT FLOOR(age / 10) * 10 AS age_range FROM member_classes WHERE class_type IN ('yoga', 'spinning');


Question: Add a new court named 'High Court of New Zealand' located in 'Wellington'

CREATE TABLE courts (id INT, name VARCHAR(50), location VARCHAR(50));

INSERT INTO courts (id, name, location) VALUES (3, 'High Court of New Zealand', 'Wellington');


Question: Generate PostgreSQL SQL for: What is the average start with wins larger than 0 and 32nd position?

CREATE TABLE table_name_34 (starts INTEGER, wins VARCHAR, position VARCHAR)

SELECT AVG(starts) FROM table_name_34 WHERE wins > 0 AND position = '32nd';


Question: What is the average data usage for each mobile subscriber in Mbytes?

CREATE TABLE mobile_subscribers (subscriber_id INT, data_usage FLOAT); INSERT INTO mobile_subscribers (subscriber_id, data_usage) VALUES (1, 50.5), (2, 75.3), (3, 32.1);

SELECT subscriber_id, data_usage/1024/1024 AS avg_data_usage_mb FROM mobile_subscribers;


Question: Find the number of male and female fans who have attended basketball games in the last year

CREATE TABLE fans (fan_id INT, gender VARCHAR(10), last_attended_game DATE); INSERT INTO fans (fan_id, gender, last_attended_game) VALUES (1, 'Male', '2022-02-15'), (2, 'Female', '2022-03-01'), (3, 'Male', '2021-12-31');

SELECT gender, COUNT(*) as num_fans FROM fans WHERE last_attended_game >= DATEADD(year, -1, GETDATE()) GROUP BY gender;


Question: What is the total number of space missions led by women?

CREATE TABLE space_missions (id INT, name VARCHAR(255), leader VARCHAR(255), year INT); INSERT INTO space_missions (id, name, leader, year) VALUES (1, 'Mars Rover', 'Dr. Jessica Watkins', 2022); INSERT INTO space_missions (id, name, leader, year) VALUES (2, 'ISS Expedition', 'Anousheh Ansari', 2023);

SELECT COUNT(*) FROM space_missions WHERE leader IN (SELECT name FROM astronauts WHERE gender = 'Female');


Question: List all clients who have a Shariah-compliant personal loan or a socially responsible auto loan?

CREATE TABLE client_loans (client_id INT, loan_type VARCHAR(20)); INSERT INTO client_loans (client_id, loan_type) VALUES (1, 'Shariah-compliant personal loan'), (2, 'Socially responsible auto loan'), (3, 'Shariah-compliant mortgage');

SELECT client_id FROM client_loans WHERE loan_type IN ('Shariah-compliant personal loan', 'Socially responsible auto loan');


Question: Calculate the average severity of vulnerabilities for each software application

CREATE TABLE vulnerabilities (id INT, software_app VARCHAR(50), severity INT);

SELECT software_app, AVG(severity) as avg_severity FROM vulnerabilities GROUP BY software_app;


Question: Generate PostgreSQL SQL for: What NFL team was the player with pick number 28 drafted to?

CREATE TABLE table_20996923_25 (nfl_team VARCHAR, pick__number VARCHAR)

SELECT nfl_team FROM table_20996923_25 WHERE pick__number = 28;


Question: Generate PostgreSQL SQL for: What is the place when the player is Bob Gilder and the money was $20,903?

CREATE TABLE table_name_88 (place VARCHAR, money___$__ VARCHAR, player VARCHAR)

SELECT place FROM table_name_88 WHERE money___$__ = '20,903' AND player = 'bob gilder';


Question: Write the DML statement from PostgreSQL regression test 'subselect' (example 138).

Explanation: DML from PostgreSQL core regression test for Subselect.


Question: Generate PostgreSQL SQL for: What is the sum of Pleasure, when Drug is "LSD", and when Psychological Dependence is greater than 1.1?

CREATE TABLE table_name_57 (pleasure INTEGER, drug VARCHAR, psychological_dependence VARCHAR)

SELECT SUM(pleasure) FROM table_name_57 WHERE drug = 'lsd' AND psychological_dependence > 1.1;


Question: What is the drought impact on agriculture in California in terms of water usage reduction?

CREATE TABLE drought_impact (state VARCHAR(20), sector VARCHAR(20), reduction FLOAT); INSERT INTO drought_impact (state, sector, reduction) VALUES ('California', 'Industrial', 0.1), ('California', 'Agriculture', 0.2), ('California', 'Domestic', 0.15);

SELECT reduction FROM drought_impact WHERE state = 'California' AND sector = 'Agriculture';


Question: Generate PostgreSQL SQL for: What is the epa rated combined fuel economy for the all-electric vehicle with dirty electric grid rocky mountains (denver) of 330 g/mi (205 g/km)?

CREATE TABLE table_23840623_4 (epa_rated_combined_fuel_economy VARCHAR, operating_mode VARCHAR, dirty_electric_grid_rocky_mountains__denver_ VARCHAR)

SELECT epa_rated_combined_fuel_economy FROM table_23840623_4 WHERE operating_mode = 'All-electric' AND dirty_electric_grid_rocky_mountains__denver_ = '330 g/mi (205 g/km)';


Question: What is the total biomass of fish in the Pacific ocean?

CREATE TABLE pacific_fish (id INT, name VARCHAR(50), biomass FLOAT); INSERT INTO pacific_fish (id, name, biomass) VALUES (1, 'Tuna', 3500.2), (2, 'Salmon', 2800.9), (3, 'Mackerel', 2200.6), (4, 'Squid', 1800.5);


Question: Generate PostgreSQL SQL for: what are all the district with incumbent being sam hobbs

CREATE TABLE table_1342270_3 (district VARCHAR, incumbent VARCHAR)

SELECT district FROM table_1342270_3 WHERE incumbent = 'Sam Hobbs';


Question: How many visual artists are represented in the database, and what is the distribution by their age group?

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

SELECT FLOOR((YEAR(CURRENT_DATE) - YEAR(birth_date)) / 10) * 10 as age_group, COUNT(*) as artist_count FROM artists GROUP BY age_group;


Question: Generate PostgreSQL SQL for: what are all the percent (1990) where state is united states

CREATE TABLE table_1182314_5 (percent__1990_ VARCHAR, state VARCHAR)

SELECT percent__1990_ FROM table_1182314_5 WHERE state = 'United states';


Question: Generate PostgreSQL SQL for: The Estevan Bruins (WCHL) are affiliated with what NHL team?

CREATE TABLE table_name_51 (nhl_team VARCHAR, college_junior_club_team VARCHAR)

SELECT nhl_team FROM table_name_51 WHERE college_junior_club_team = 'estevan bruins (wchl)';


Question: Display union_name and position for employees in the 'employees' table who are members of unions with names starting with 'B'

CREATE TABLE labor_unions (id INT, union_name VARCHAR(50), members INT); CREATE TABLE employees (id INT, union_id INT, name VARCHAR(50), position VARCHAR(50));

SELECT e.name, e.position, l.union_name FROM employees e JOIN labor_unions l ON e.union_id = l.id WHERE l.union_name LIKE 'B%';


Question: Generate PostgreSQL SQL for: Which Score has a Money ( £ ) of 90,400, and a Country of south africa, and a Player of thomas aiken? Question 1

CREATE TABLE table_name_38 (score VARCHAR, player VARCHAR, money___£__ VARCHAR, country VARCHAR)

SELECT score FROM table_name_38 WHERE money___£__ = '90,400' AND country = 'south africa' AND player = 'thomas aiken';


Question: What is the total revenue of eco-tourism businesses in Costa Rica?

CREATE TABLE Revenue (id INT, country TEXT, type TEXT, amount FLOAT); INSERT INTO Revenue (id, country, type, amount) VALUES (1, 'Costa Rica', 'Eco-tourism', 800000), (2, 'Costa Rica', 'Hotels', 600000), (3, 'Costa Rica', 'Eco-tourism', 900000), (4, 'Costa Rica', 'Tour operators', 700000);

SELECT SUM(amount) FROM Revenue WHERE country = 'Costa Rica' AND type = 'Eco-tourism';


Question: What was the average price per pound for each product category sold in Oregon in 2021?

CREATE TABLE sales (date DATE, dispensary VARCHAR(255), product VARCHAR(255), price DECIMAL(10,2), weight DECIMAL(10,2)); INSERT INTO sales VALUES ('2021-10-01', 'Dispensary A', 'Flower', 45.00, 10), ('2021-10-01', 'Dispensary B', 'Concentrate', 50.00, 20); CREATE TABLE dispensaries (name VARCHAR(255), state VARCHAR(2)); INSERT INTO dispensaries VALUES ('Dispensary A', 'OR'), ('Dispensary B', 'WA');

SELECT p.product as product_category, AVG(price / weight) as avg_price_per_pound FROM sales JOIN dispensaries ON sales.dispensary = dispensaries.name WHERE EXTRACT(YEAR FROM date) = 2021 AND state = 'OR' GROUP BY p.product;


Question: Generate PostgreSQL SQL for: What's the Length with the Version of Album Version?

CREATE TABLE table_name_60 (length VARCHAR, version VARCHAR)

SELECT length FROM table_name_60 WHERE version = 'album version';


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

INSERT INTO trunc_faa VALUES (5, 'five', 'FIVE');

Explanation: DML from PostgreSQL core regression test for Truncate.


Question: Update the risk category of policyholders living in New York to 'High Risk'.

CREATE TABLE Policyholders (ID INT, Name VARCHAR(50), Age INT, Gender VARCHAR(10), City VARCHAR(50), State VARCHAR(20), ZipCode VARCHAR(10), RiskCategory VARCHAR(10));

UPDATE Policyholders SET RiskCategory = 'High Risk' WHERE State = 'New York';


Question: What is the total quantity of eco-friendly dyes used in textile production in Europe?

CREATE TABLE TextileProduction (id INT, dye VARCHAR(255), region VARCHAR(255), quantity INT); INSERT INTO TextileProduction (id, dye, region, quantity) VALUES (1, 'Natural Dye', 'Europe', 500), (2, 'Synthetic Dye', 'Asia', 700), (3, 'Low-Impact Dye', 'South America', 600);

SELECT SUM(quantity) FROM TextileProduction WHERE dye IN ('Natural Dye', 'Low-Impact Dye') AND region = 'Europe';


Question: Generate PostgreSQL SQL for: What is the chassis of the Honda Engine from 2008?

CREATE TABLE table_name_68 (chassis VARCHAR, engine VARCHAR, year VARCHAR)

SELECT chassis FROM table_name_68 WHERE engine = 'honda' AND year = 2008;


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

ALTER EXTENSION pgtap ADD FUNCTION hasnt_trigger ( NAME, NAME, NAME );

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


Question: Find the number of distinct animal species in each habitat

CREATE TABLE species (id INT, name VARCHAR(255));CREATE TABLE animals (id INT, species_id INT, habitat_id INT); INSERT INTO species (id, name) VALUES (1, 'Lion'), (2, 'Elephant'), (3, 'Giraffe'); INSERT INTO animals (id, species_id, habitat_id) VALUES (1, 1, 2), (2, 2, 1), (3, 3, 2);

SELECT h.name AS habitat_name, COUNT(DISTINCT a.species_id) AS distinct_species FROM animals a INNER JOIN habitats h ON a.habitat_id = h.id GROUP BY h.name;


Question: Generate PostgreSQL SQL for: What is the latest year when Call of Duty 4: Modern Warfare was the game?

CREATE TABLE table_name_63 (year INTEGER, game VARCHAR)

SELECT MAX(year) FROM table_name_63 WHERE game = 'call of duty 4: modern warfare';


Question: Show a query using PostgreSQL contrib extension 'tablefunc' (example 75).

SELECT * FROM connectby('connectby_int', 'keyid', 'parent_keyid', '2', 0, '~') AS t(keyid int, parent_keyid int, level int, branch float);

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


Question: What is the average dissolved oxygen level for each species of fish in the fish_stock table?

CREATE TABLE fish_stock (species VARCHAR(50), location VARCHAR(50), dissolved_oxygen FLOAT); INSERT INTO fish_stock (species, location, dissolved_oxygen) VALUES ('Tilapia', 'Lake Victoria', 6.5), ('Tilapia', 'Lake Tanganyika', 7.0), ('Salmon', 'Pacific Ocean', 8.0);

SELECT species, AVG(dissolved_oxygen) FROM fish_stock GROUP BY species;


Question: Show a SQL definition from the pg_partman project (pg_partman--1.6.1--1.7.0, item 16).

/*
 * Function to create a child table in a time-based partition set
 */
CREATE OR REPLACE FUNCTION create_time_partition (p_parent_table text, p_partition_times timestamp[])
RETURNS text
    LANGUAGE plpgsql SECURITY DEFINER
    AS $$
DECLARE

v_all                           text[] := ARRAY['SELECT', 'INSERT', 'UPDATE', 'DELETE', 'TRUNCATE', 'REFERENCES', 'TRIGGER'];
v_analyze                       boolean := FALSE;
v_control                       text;
v_grantees                      text[];
v_hasoids                       boolean;
v_job_id                        bigint;
v_jobmon                        boolean;
v_jobmon_schema                 text;
v_old_search_path               text;
v_parent_grant                  record;
v_parent_owner                  text;
v_parent_schema                 text;
v_parent_tablename              text;
v_partition_name                text;
v_partition_suffix              text;
v_parent_tablespace             text;
v_part_interval                 interval;
v_partition_timestamp_end       timestamp;
v_partition_timestamp_start     timestamp;
v_quarter                       text;
v_revoke                        text[];
v_sql                           text;
v_step_id                       bigint;
v_step_overflow_id              bigint;
v_tablename                     text;
v_trunc_value                   text;
v_time                          timestamp;
v_type                          text;
v_year                          text;

BEGIN

SELECT type
    , control
    , part_interval
    , jobmon
INTO v_type
    , v_control
    , v_part_interval
    , v_jobmon
FROM @extschema@.part_config
WHERE parent_table = p_parent_table
AND (type = 'time-static' OR type = 'time-dynamic' OR 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 'SELECT set_config(''search_path'',''@extschema@,'||v_jobmon_schema||''',''false'')';
    END IF;
END IF;

SELECT tableowner, schemaname, tablename, tablespace INTO v_parent_owner, v_parent_schema, v_parent_tablename, v_parent_tablespace FROM pg_tables WHERE schemaname ||'.'|| tablename = p_parent_table;

FOREACH v_time IN ARRAY p_partition_times LOOP

    v_partition_suffix := to_char(v_time, 'YYYY');
    IF v_part_interval < '1 year' AND v_part_interval <> '1 week' THEN
        v_partition_suffix := v_partition_suffix ||'_'|| to_char(v_time, 'MM');
        IF v_part_interval < '1 month' AND v_part_interval <> '1 week' THEN
            v_partition_suffix := v_partition_suffix ||'_'|| to_char(v_time, 'DD');
            IF v_part_interval < '1 day' THEN
                v_partition_suffix := v_partition_suffix || '_' || to_char(v_time, 'HH24MI');
                IF v_part_interval < '1 minute' THEN
                    v_partition_suffix := v_partition_suffix || to_char(v_time, 'SS');
                END IF; -- end < minute IF
            END IF; -- end < day IF
        END IF; -- end < month IF
    END IF; -- end < year IF

    v_partition_timestamp_start := v_time;
    BEGIN
        v_partition_timestamp_end := v_time + v_part_interval;
    EXCEPTION WHEN datetime_field_overflow THEN
        RAISE WARNING 'Attempted partition time interval is outside PostgreSQL''s supported time range.
            Child partition creation after time % skipped', v_time;
        v_step_overflow_id := add_step(v_job_id, 'Attempted partition time interval is outside PostgreSQL''s supported time range.');
        PERFORM update_step(v_step_overflow_id, 'CRITICAL', 'Child partition creation after time '||v_time||' skipped');
        CONTINUE;
    END;

    IF v_part_interval = '1 week' THEN
        v_partition_suffix := to_char(v_time, 'IYYY') || 'w' || to_char(v_time, 'IW');
    END IF;

    -- "Q" is ignored in to_timestamp, so handle special case
    IF v_part_interval = '3 months' AND (v_type = 'time-static' OR v_type = 'time-dynamic') THEN
        v_year := to_char(v_time, 'YYYY');
        v_quarter := to_char(v_time, 'Q');
        v_partition_suffix := v_year || 'q' || v_quarter;
    END IF;

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

    SELECT tablename INTO v_tablename FROM pg_catalog.pg_tables WHERE schemaname ||'.'|| tablename = v_partition_name;
    IF v_tablename IS NOT NULL THEN
        CONTINUE;
    END IF;

    -- Ensure analyze is run if a new partition is created. Otherwise if one isn't, will be false and analyze will be skipped
    v_analyze := TRUE;

    IF v_jobmon_schema IS NOT NULL THEN
        v_job_id := add_job('PARTMAN CREATE TABLE: '||p_parent_table);
        v_step_id := add_step(v_job_id, 'Creating new partition '||v_partition_name||' with interval from '||v_partition_timestamp_start||' to '||(v_partition_timestamp_end-'1sec'::interval));
    END IF;

    v_sql := 'CREATE TABLE '||v_partition_name||' (LIKE '||p_parent_table||' INCLUDING DEFAULTS INCLUDING CONSTRAINTS INCLUDING INDEXES INCLUDING STORAGE INCLUDING COMMENTS)';
    SELECT relhasoids INTO v_hasoids FROM pg_class WHERE oid::regclass = p_parent_table::regclass;
    IF v_hasoids IS TRUE THEN
        v_sql := v_sql || ' WITH (OIDS)';
    END IF;
    EXECUTE v_sql;
    SELECT tablename INTO v_tablename FROM pg_catalog.pg_tables WHERE schemaname ||'.'|| tablename = v_partition_name;
    IF v_parent_tablespace IS NOT NULL THEN
        EXECUTE 'ALTER TABLE '||v_partition_name||' SET TABLESPACE '||v_parent_tablespace;
    END IF;
    EXECUTE 'ALTER TABLE '||v_partition_name||' ADD CONSTRAINT '||v_tablename||'_partition_check
        CHECK ('||v_control||'>='||quote_literal(v_partition_timestamp_start)||' AND '||v_control||'<'||quote_literal(v_partition_timestamp_end)||')';
    EXECUTE 'ALTER TABLE '||v_partition_name||' INHERIT '||p_parent_table;

    -- If custom time, set extra config options.
    IF v_type = 'time-custom' THEN
        INSERT INTO @extschema@.custom_time_partitions (parent_table, child_table, partition_range)
        VALUES ( p_parent_table, v_partition_name, tstzrange(v_partition_timestamp_start, v_partition_timestamp_end, '[)') );
    END IF;

    FOR v_parent_grant IN
        SELECT array_agg(DISTINCT privilege_type::text ORDER BY privilege_type::text) AS types, grantee
        FROM information_schema.table_privileges
        WHERE table_schema ||'.'|| table_name = p_parent_table
        GROUP BY grantee
    LOOP
        EXECUTE 'GRANT '||array_to_string(v_parent_grant.types, ',')||' ON '||v_partition_name||' TO '||v_parent_grant.grantee;
        SELECT array_agg(r) INTO v_revoke FROM (SELECT unnest(v_all) AS r EXCEPT SELECT unnest(v_parent_grant.types)) x;
        IF v_revoke IS NOT NULL THEN
            EXECUTE 'REVOKE '||array_to_string(v_revoke, ',')||' ON '||v_partition_name||' FROM '||v_parent_grant.grantee||' CASCADE';
        END IF;
        v_grantees := array_append(v_grantees, v_parent_grant.grantee::text);
    END LOOP;
    -- Revoke all privileges from roles that have none on the parent
    IF v_grantees IS NOT NULL THEN
        SELECT array_agg(r) INTO v_revoke FROM (
            SELECT DISTINCT grantee::text AS r FROM information_schema.table_privileges WHERE table_schema ||'.'|| table_name = v_partition_name
            EXCEPT
            SELECT unnest(v_grantees)) x;
        IF v_revoke IS NOT NULL THEN
            EXECUTE 'REVOKE ALL ON '||v_partition_name||' FROM '||array_to_string(v_revoke, ',');
        END IF;
    END IF;

    EXECUTE 'ALTER TABLE '||v_partition_name||' OWNER TO '||v_parent_owner;

    IF v_jobmon_schema IS NOT NULL THEN
        PERFORM update_step(v_step_id, 'OK', 'Done');
        IF v_step_overflow_id IS NOT NULL THEN
            PERFORM fail_job(v_job_id);
        ELSE
            PERFORM close_job(v_job_id);
        END IF;
    END IF;

END LOOP;

IF v_analyze THEN
    EXECUTE 'ANALYZE '||p_parent_table;
END IF;

IF v_jobmon_schema IS NOT NULL THEN
    EXECUTE 'SELECT set_config(''search_path'','''||v_old_search_path||''',''false'')';
END IF;

RETURN v_partition_name;

EXCEPTION
    WHEN OTHERS THEN
        IF v_jobmon_schema IS NOT NULL THEN
            IF v_job_id IS NULL THEN
                EXECUTE 'SELECT '||v_jobmon_schema||'.add_job(''PARTMAN CREATE TABLE: '||p_parent_table||''')' INTO v_job_id;
                EXECUTE 'SELECT '||v_jobmon_schema||'.add_step('||v_job_id||', ''EXCEPTION before job logging started'')' INTO v_step_id;
            ELSIF v_step_id IS NULL THEN
                EXECUTE 'SELECT '||v_jobmon_schema||'.add_step('||v_job_id||', ''EXCEPTION before first step logged'')' INTO v_step_id;
            END IF;
            EXECUTE 'SELECT '||v_jobmon_schema||'.update_step('||v_step_id||', ''CRITICAL'', ''ERROR: '||coalesce(SQLERRM,'unknown')||''')';
            EXECUTE 'SELECT '||v_jobmon_schema||'.fail_job('||v_job_id||')';
        END IF;
        RAISE EXCEPTION '%', SQLERRM;
END
$$;

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


Question: What is the average number of employees for startups founded in 2019?

CREATE TABLE startup (id INT, name TEXT, founding_year INT, num_employees INT); INSERT INTO startup (id, name, founding_year, num_employees) VALUES (1, 'Startup19', 2019, 200); INSERT INTO startup (id, name, founding_year, num_employees) VALUES (2, 'TechStart', 2018, 100);

SELECT AVG(num_employees) FROM startup WHERE founding_year = 2019;


Question: Update community policing event details for event ID 201 in district 4

CREATE TABLE districts (id INT, name VARCHAR(255)); INSERT INTO districts (id, name) VALUES (4, 'Southriver'); CREATE TABLE community_policing_events (id INT, district_id INT, title VARCHAR(255), date DATE); INSERT INTO community_policing_events (id, district_id, title, date) VALUES (201, 4, 'Neighborhood Watch Meeting', '2023-03-15'), (202, 4, 'Coffee with a Cop', '2023-03-18');

UPDATE community_policing_events SET title = 'Community Safety Meeting', date = '2023-03-17' WHERE id = 201;


Question: Generate PostgreSQL SQL for: What is the highest Points, when Position is less than 4, when Equipment is Zabel - VMC, and when Bike No is less than 1?

CREATE TABLE table_name_19 (points INTEGER, bike_no VARCHAR, position VARCHAR, equipment VARCHAR)

SELECT MAX(points) FROM table_name_19 WHERE position < 4 AND equipment = 'zabel - vmc' AND bike_no < 1;


Question: Delete all records in the 'ocean_acidification' table where the 'level' is above 8.0

CREATE TABLE ocean_acidification (id INT, date DATE, location VARCHAR(50), level DECIMAL(3,1)); INSERT INTO ocean_acidification (id, date, location, level) VALUES (1, '2021-08-15', 'Caribbean Sea', 7.9); INSERT INTO ocean_acidification (id, date, location, level) VALUES (2, '2022-03-02', 'Sargasso Sea', 8.1);

DELETE FROM ocean_acidification WHERE level > 8.0;


Question: Generate PostgreSQL SQL for: What is the smallest number for old membership total?

CREATE TABLE table_27671835_3 (old_membership_total INTEGER)

SELECT MIN(old_membership_total) FROM table_27671835_3;


Question: Generate PostgreSQL SQL for: What is the lowest drawn that has games less than 7?

CREATE TABLE table_name_83 (drawn INTEGER, games INTEGER)

SELECT MIN(drawn) FROM table_name_83 WHERE games < 7;


Question: What is the maximum number of passengers that can be carried by Airbus A380?

CREATE TABLE AircraftSpecifications (Id INT, Manufacturer VARCHAR(50), Model VARCHAR(50), MaxPassengers INT); INSERT INTO AircraftSpecifications (Id, Manufacturer, Model, MaxPassengers) VALUES (1, 'Airbus', 'A380', 853);

SELECT MaxPassengers FROM AircraftSpecifications WHERE Manufacturer = 'Airbus' AND Model = 'A380';


Question: List all the unique safety protocol IDs and their corresponding safety measures from the safety_protocols table.

CREATE TABLE safety_protocols (protocol_id INT, safety_measure TEXT); INSERT INTO safety_protocols (protocol_id, safety_measure) VALUES (1, 'Use personal protective equipment'), (2, 'Regular equipment maintenance'), (3, 'Emergency drills');

SELECT protocol_id, safety_measure FROM safety_protocols;


Question: Generate PostgreSQL SQL for: What is the elevation msnm for a population censo 2007(hab) of 77.392*?

CREATE TABLE table_name_59 (elevation_msnm VARCHAR, population_censo_2007_hab_ VARCHAR)

SELECT elevation_msnm FROM table_name_59 WHERE population_censo_2007_hab_ = '77.392*';


Question: pgTAP test for Index (assertion 55).

Explanation: SQL assertion from pgTAP test suite for Index.


Question: What is the total number of traditional arts centers and the number of centers dedicated to dance in each continent, excluding Antarctica?

CREATE TABLE Arts_Centers (Center_Name VARCHAR(50), Country VARCHAR(50), Type VARCHAR(50)); INSERT INTO Arts_Centers (Center_Name, Country, Type) VALUES ('Sydney Opera House', 'Australia', 'Opera'), ('Teatro Colon', 'Argentina', 'Ballet');

SELECT Continent, COUNT(*) AS Total_Arts_Centers, SUM(CASE WHEN Type = 'Dance' THEN 1 ELSE 0 END) AS Dance_Centers FROM Arts_Centers JOIN (SELECT 'Australia' AS Country, 'Oceania' AS Continent UNION ALL SELECT 'Argentina' AS Country, 'South America' AS Continent) AS Continents ON Arts_Centers.Country = Continents.Country GROUP BY Continent;


Question: PostgreSQL regression test 'strings': Write the SELECT query (example 429).

SELECT sha224('The quick brown fox jumps over the lazy dog.');

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

SELECT count(*) FROM (SELECT sha224('The quick brown fox jumps over the lazy dog.')) AS _sub;


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

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

SELECT count(*) FROM (SELECT '["a","b","c",[1,2],null]'::jsonb -> 2) AS _sub;


Question: What is the minimum depth of all coastal waters?

CREATE TABLE coastal_waters (name VARCHAR(255), depth FLOAT); INSERT INTO coastal_waters (name, depth) VALUES ('Gulf of Mexico', 250.0), ('Baltic Sea', 459.0), ('Black Sea', 2212.0);


Question: What is the maximum impact measurement for companies based in Asia?

CREATE TABLE companies (company_id INT, region VARCHAR(50), impact_measurement FLOAT); INSERT INTO companies (company_id, region, impact_measurement) VALUES (1, 'Asia', 9.2), (2, 'Europe', 7.6), (3, 'Asia', 8.9);

SELECT MAX(impact_measurement) FROM companies WHERE region = 'Asia';


Question: Generate PostgreSQL SQL for: What was the winning score for the Andy Williams-San Diego Open Invitational tournament?

CREATE TABLE table_name_60 (winning_score VARCHAR, tournament VARCHAR)

SELECT winning_score FROM table_name_60 WHERE tournament = 'andy williams-san diego open invitational';


Question: Generate PostgreSQL SQL for: Team Rusport has the best of 59.654 and what qual 1?

CREATE TABLE table_name_15 (qual_1 VARCHAR, team VARCHAR, best VARCHAR)

SELECT qual_1 FROM table_name_15 WHERE team = 'rusport' AND best = '59.654';


Question: Insert a new record into the community_engagement table with the following data: 'Seattle', 'USA', 'Cultural festival', 2000.

CREATE TABLE community_engagement (city VARCHAR(50), country VARCHAR(50), event VARCHAR(50), attendees INT);

INSERT INTO community_engagement (city, country, event, attendees) VALUES ('Seattle', 'USA', 'Cultural festival', 2000);


Question: What is the total inventory cost for each menu item category in the current quarter?

CREATE TABLE Inventory (inventory_id INT PRIMARY KEY, menu_item VARCHAR(50), inventory_quantity INT, inventory_cost DECIMAL(5,2), inventory_date DATE);  CREATE TABLE Menu (menu_item VARCHAR(50) PRIMARY KEY, menu_item_category VARCHAR(50));

SELECT menu_item_category, SUM(inventory_cost * inventory_quantity) FROM Inventory i JOIN Menu m ON i.menu_item = m.menu_item WHERE i.inventory_date >= DATEADD(quarter, DATEDIFF(quarter, 0, GETDATE()), 0) GROUP BY menu_item_category;


Question: Generate PostgreSQL SQL for: Who was the outgoing manager that was replaced by Thomas Von Heesen?

CREATE TABLE table_name_80 (outgoing_manager VARCHAR, replaced_by VARCHAR)

SELECT outgoing_manager FROM table_name_80 WHERE replaced_by = 'thomas von heesen';


Question: Generate PostgreSQL SQL for: Which Year has a Competition of european championships, and Notes of 66.81 m?

CREATE TABLE table_name_26 (year INTEGER, competition VARCHAR, notes VARCHAR)

SELECT SUM(year) FROM table_name_26 WHERE competition = 'european championships' AND notes = '66.81 m';


Question: Generate PostgreSQL SQL for: What is the score of Colorado when they were a visitor and had a Smith decision?

CREATE TABLE table_name_32 (score VARCHAR, decision VARCHAR, visitor VARCHAR)

SELECT score FROM table_name_32 WHERE decision = 'smith' AND visitor = 'colorado';


Question: Generate PostgreSQL SQL for: what row is the  population of Latin America/Caribbean when Asia is 4,894 (46.1%)?

CREATE TABLE table_19017269_5 (latin_america_caribbean VARCHAR, asia VARCHAR)

SELECT COUNT(latin_america_caribbean) FROM table_19017269_5 WHERE asia = '4,894 (46.1%)';


Question: What are the names of categories with no projects?

CREATE TABLE project (id INT, name VARCHAR(50), location VARCHAR(50), start_date DATE, end_date DATE, category VARCHAR(20)); INSERT INTO project (id, name, location, start_date, end_date, category) VALUES (4, 'Utility Relocation', 'City D', '2021-01-01', '2021-12-31', 'Utilities'); CREATE TABLE category (id INT, name VARCHAR(20)); INSERT INTO category (id, name) VALUES (1, 'Resilience'), (2, 'Design'), (3, 'Infrastructure');

SELECT c.name FROM category c WHERE c.name NOT IN (SELECT DISTINCT category FROM project);


Question: Generate PostgreSQL SQL for: Find the name of amenities Smith Hall dorm have.

CREATE TABLE has_amenity (dormid VARCHAR, amenid VARCHAR); CREATE TABLE dorm_amenity (amenity_name VARCHAR, amenid VARCHAR); CREATE TABLE dorm (dormid VARCHAR, dorm_name VARCHAR)

SELECT T3.amenity_name FROM dorm AS T1 JOIN has_amenity AS T2 ON T1.dormid = T2.dormid JOIN dorm_amenity AS T3 ON T2.amenid = T3.amenid WHERE T1.dorm_name = 'Smith Hall';


Question: Generate PostgreSQL SQL for: When Melbourne was the Away team, what was their score?

CREATE TABLE table_name_75 (away_team VARCHAR)

SELECT away_team AS score FROM table_name_75 WHERE away_team = 'melbourne';


Question: Generate PostgreSQL SQL for: For majors with 8 events played and more than 1 made cut, what is the most top-10s recorded?

CREATE TABLE table_name_9 (top_10 INTEGER, cuts_made VARCHAR, events VARCHAR)

SELECT MAX(top_10) FROM table_name_9 WHERE cuts_made > 1 AND events = 8;


Question: What is the average fuel efficiency of electric vehicles by model?

CREATE TABLE ElectricVehicleFuelEfficiency(Model VARCHAR(50), Make VARCHAR(50), MilesPerGallon FLOAT);

SELECT Model, AVG(MilesPerGallon) FROM ElectricVehicleFuelEfficiency GROUP BY Model;


Question: What is the total budget allocation for education services in CityA for the current fiscal year?

CREATE TABLE fiscal_year (fiscal_year INT, start_date DATE, end_date DATE); INSERT INTO fiscal_year VALUES (2022, '2022-01-01', '2022-12-31'), (2023, '2023-01-01', '2023-12-31'); CREATE TABLE budget_allocation (service VARCHAR(20), fiscal_year INT, amount INT); INSERT INTO budget_allocation VALUES ('Education', 2022, 500000), ('Healthcare', 2022, 800000), ('Education', 2023, 600000), ('Healthcare', 2023, 900000); CREATE TABLE cities (id INT, name VARCHAR(20)); INSERT INTO cities VALUES (1, 'CityA'), (2, 'CityB'), (3, 'CityC');

SELECT SUM(amount) FROM budget_allocation WHERE service = 'Education' AND fiscal_year = (SELECT fiscal_year FROM fiscal_year WHERE start_date <= CURRENT_DATE AND end_date >= CURRENT_DATE) AND city_id = (SELECT id FROM cities WHERE name = 'CityA');


Question: Calculate the percentage of volunteers who are under 18 years old, and list them along with their total volunteer hours for the current year.

CREATE TABLE Volunteers (VolunteerID INT, VolunteerName VARCHAR(50), DateOfBirth DATE); INSERT INTO Volunteers (VolunteerID, VolunteerName, DateOfBirth) VALUES (1, 'James Brown', '1993-01-01'), (2, 'Jessica White', '2003-01-01'); CREATE TABLE VolunteerHours (VolunteerID INT, Hours INT, VolunteerDate DATE); INSERT INTO VolunteerHours (VolunteerID, Hours, VolunteerDate) VALUES (1, 5, '2021-01-01'), (1, 6, '2021-02-01'), (1, 7, '2021-03-01'), (2, 4, '2021-01-01'), (2, 3, '2021-02-01'), (2, 2, '2021-03-01');

SELECT ROUND(COUNT(CASE WHEN TIMESTAMPDIFF(YEAR, Volunteers.DateOfBirth, CURDATE()) < 18 THEN Volunteers.VolunteerID END) / COUNT(*) * 100, 2) AS Under18Percentage, Volunteers.VolunteerName, SUM(VolunteerHours.Hours) AS TotalHoursForYear FROM Volunteers INNER JOIN VolunteerHours ON Volunteers.VolunteerID = VolunteerHours.VolunteerID AND VolunteerHours.VolunteerDate <= CURDATE() AND YEAR(VolunteerHours.VolunteerDate) = YEAR(CURDATE()) GROUP BY Volunteers.VolunteerName;


Question: What is the total number of menu items sold in the Western region?

CREATE TABLE menu (menu_id INT, menu_name TEXT, menu_type TEXT, price DECIMAL, daily_sales INT, region TEXT);

SELECT SUM(daily_sales) FROM menu WHERE region = 'Western';


Question: What is the maximum ocean acidification level recorded in the Atlantic region in the last 5 years?"

CREATE TABLE ocean_acidification_levels (location TEXT, acidification_level REAL, measurement_date DATE);   CREATE TABLE atlantic_region (region_name TEXT, region_description TEXT);

SELECT MAX(oal.acidification_level) FROM ocean_acidification_levels oal INNER JOIN atlantic_region ar ON oal.location LIKE '%Atlantic%' AND oal.measurement_date >= (CURRENT_DATE - INTERVAL '5 years');


Question: What is the average life expectancy in 'Los Angeles County'?

CREATE TABLE life_expectancy_data (county VARCHAR(255), life_expectancy FLOAT); INSERT INTO life_expectancy_data (county, life_expectancy) VALUES ('Los Angeles County', 81.7), ('Orange County', 83.2);

SELECT life_expectancy FROM life_expectancy_data WHERE county = 'Los Angeles County';


Question: Generate PostgreSQL SQL for: Name the competition for score of 3-0

CREATE TABLE table_name_42 (competition VARCHAR, score VARCHAR)

SELECT competition FROM table_name_42 WHERE score = '3-0';


Question: What is the total number of education projects in each continent?

CREATE TABLE Projects (project_id INT, project_location VARCHAR(50), project_type VARCHAR(50)); INSERT INTO Projects (project_id, project_location, project_type) VALUES (1, 'India', 'Community Development'), (2, 'Canada', 'Education'), (3, 'Kenya', 'Education');

SELECT project_location, COUNT(*) AS 'Total Projects' FROM Projects WHERE project_type = 'Education' GROUP BY project_location;


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

--
-- gin_leafpage_items()
--
CREATE FUNCTION gin_leafpage_items(IN page bytea,
    OUT first_tid tid,
    OUT nbytes int2,
    OUT tids tid[])
RETURNS SETOF record
AS 'MODULE_PATHNAME', 'gin_leafpage_items'
LANGUAGE C STRICT PARALLEL SAFE;

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


Question: What are the average soil moisture levels for vineyards in France and Spain?

CREATE TABLE VineyardSoilMoisture (country VARCHAR(20), region VARCHAR(30), moisture FLOAT); INSERT INTO VineyardSoilMoisture (country, region, moisture) VALUES ('France', 'Bordeaux', 42.3), ('France', 'Burgundy', 48.1), ('Spain', 'Rioja', 39.5), ('Spain', 'Ribera del Duero', 45.6);

SELECT AVG(moisture) FROM VineyardSoilMoisture WHERE country IN ('France', 'Spain') AND region IN ('Bordeaux', 'Burgundy', 'Rioja', 'Ribera del Duero');


Question: What are the names of all restaurants that serve vegetarian options?

CREATE TABLE Restaurants (name VARCHAR(255), vegetarian BOOLEAN); INSERT INTO Restaurants (name, vegetarian) VALUES ('Bistro Veggie', TRUE), ('Pizza House', FALSE), ('Vegan Delight', TRUE);

SELECT name FROM Restaurants WHERE vegetarian = TRUE;


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

-- test perl -> hstore
CREATE FUNCTION test2() RETURNS hstore
LANGUAGE plperl
TRANSFORM FOR TYPE hstore
AS $$
$val = {a => 1, b => 'boo', c => undef};
return $val;
$$;

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


Question: Generate PostgreSQL SQL for: List the most common result of the musicals.

SELECT RESULT FROM musical GROUP BY RESULT ORDER BY COUNT(*) DESC LIMIT 1;


Question: Identify the number of unique countries that imported Terbium in 2021.

CREATE TABLE TerbiumImports (country VARCHAR(50), year INT); INSERT INTO TerbiumImports (country, year) VALUES ('USA', 2021), ('China', 2021), ('Japan', 2021), ('USA', 2021), ('South Korea', 2021);

SELECT COUNT(DISTINCT country) FROM TerbiumImports WHERE year = 2021;


Question: What is the maximum number of workforce development programs offered by companies in a single country?

CREATE TABLE companies (id INT, name TEXT, country TEXT, num_workforce_programs INT); INSERT INTO companies (id, name, country, num_workforce_programs) VALUES (1, 'Empowerment Enterprises', 'USA', 3); INSERT INTO companies (id, name, country, num_workforce_programs) VALUES (2, 'Skillset Solutions', 'Canada', 2); INSERT INTO companies (id, name, country, num_workforce_programs) VALUES (3, 'Proficiency Partners', 'Mexico', 4); INSERT INTO companies (id, name, country, num_workforce_programs) VALUES (4, 'Abilities Associates', 'Brazil', 5); INSERT INTO companies (id, name, country, num_workforce_programs) VALUES (5, 'Capability Creations', 'USA', 1); INSERT INTO companies (id, name, country, num_workforce_programs) VALUES (6, 'Knowledge Kingdom', 'Canada', 6);

SELECT MAX(num_workforce_programs) AS max_programs FROM companies WHERE country IN ('USA', 'Canada', 'Mexico', 'Brazil');


Question: Which biotech startups have received funding over 10 million and are located in California?

CREATE TABLE startups (id INT, name VARCHAR(50), location VARCHAR(50), funding FLOAT); INSERT INTO startups (id, name, location, funding) VALUES (1, 'Genetech', 'California', 12000000); INSERT INTO startups (id, name, location, funding) VALUES (2, 'Zymergen', 'California', 25000000);

SELECT name FROM startups WHERE funding > 10000000 AND location = 'California';


Question: Show an example of PostgreSQL ALTER FOREIGN DATA WRAPPER (example 1).

ALTER FOREIGN DATA WRAPPER dbi OPTIONS (ADD foo '1', DROP bar);

Explanation: PostgreSQL ALTER FOREIGN DATA WRAPPER command.


Question: What is the average number of points scored by basketball players in each game in the last month?

CREATE TABLE basketball_games (id INT, game_date DATE, sport VARCHAR(50), average_points_per_player DECIMAL(5,2));

SELECT AVG(average_points_per_player) FROM basketball_games WHERE sport = 'basketball' AND game_date >= DATEADD(month, -1, GETDATE());


Question: Get all products that use 'Recycled Material' from 'material' table

CREATE TABLE material (material_id VARCHAR(10), name VARCHAR(50), description TEXT, primary key (material_id));

SELECT * FROM product p JOIN product_material pm ON p.product_id = pm.product_id JOIN material m ON pm.material_id = m.material_id WHERE m.name = 'Recycled Material';


Question: What was the total value of military equipment sales to India in H1 2021?

CREATE TABLE military_sales (id INT, region VARCHAR, sale_value DECIMAL, sale_date DATE); INSERT INTO military_sales (id, region, sale_value, sale_date) VALUES (1, 'India', 20000, '2021-02-12'); INSERT INTO military_sales (id, region, sale_value, sale_date) VALUES (2, 'India', 18000, '2021-04-28'); INSERT INTO military_sales (id, region, sale_value, sale_date) VALUES (3, 'India', 15000, '2021-01-15');

SELECT SUM(sale_value) FROM military_sales WHERE region = 'India' AND sale_date BETWEEN '2021-01-01' AND '2021-06-30';


Question: Generate PostgreSQL SQL for: What is the Hometown of Candidate Lenny Veltman?

CREATE TABLE table_name_73 (hometown VARCHAR, candidate VARCHAR)

SELECT hometown FROM table_name_73 WHERE candidate = 'lenny veltman';


Question: Generate PostgreSQL SQL for: What is the average attendance of the game with 38 opponent and less than 14 Falcons points?

CREATE TABLE table_name_63 (attendance INTEGER, opponents VARCHAR, falcons_points VARCHAR)

SELECT AVG(attendance) FROM table_name_63 WHERE opponents = 38 AND falcons_points < 14;


Question: Generate PostgreSQL SQL for: With less than 1 Championship, what es the Established date of the Niagara Rugby Union League?

CREATE TABLE table_name_40 (established INTEGER, championships VARCHAR, league VARCHAR)

SELECT SUM(established) FROM table_name_40 WHERE championships < 1 AND league = 'niagara rugby union';


Question: Generate PostgreSQL SQL for: What is Date, when Team is "Orlando"?

CREATE TABLE table_name_72 (date VARCHAR, team VARCHAR)

SELECT date FROM table_name_72 WHERE team = 'orlando';


Question: What is the average budget for climate adaptation projects in South America?

CREATE TABLE project_budget (project_id INT, budget DECIMAL); INSERT INTO project_budget (project_id, budget) VALUES (1, 5000000.00);

SELECT AVG(budget) FROM project_budget JOIN climate_project ON project_budget.project_id = climate_project.project_id WHERE climate_project.project_type = 'Adaptation' AND climate_project.project_region = 'South America';


Question: How many AI safety incidents occurred in the 'asia' region in 2020?

CREATE TABLE ai_safety_incidents (region TEXT, year INTEGER, incidents INTEGER); INSERT INTO ai_safety_incidents (region, year, incidents) VALUES ('europe', 2020, 10), ('africa', 2020, 5), ('asia', 2020, 15);

SELECT SUM(incidents) FROM ai_safety_incidents WHERE region = 'asia' AND year = 2020;


Question: What is the total revenue for each menu category in a specific country?

CREATE TABLE menus (menu_id INT, category VARCHAR(255)); INSERT INTO menus VALUES (1, 'Appetizers'); INSERT INTO menus VALUES (2, 'Entrees'); INSERT INTO menus VALUES (3, 'Desserts'); CREATE TABLE sales (sale_id INT, menu_id INT, quantity INT, country VARCHAR(255), price DECIMAL(10, 2));

SELECT m.category, SUM(s.price * s.quantity) as total_revenue FROM menus m INNER JOIN sales s ON m.menu_id = s.menu_id WHERE s.country = 'USA' GROUP BY m.category;


Question: What is the total supply of ERC20 tokens issued by addresses located in India?

CREATE TABLE addresses (address VARCHAR(42), country VARCHAR(2)); INSERT INTO addresses (address, country) VALUES ('0x123', 'IN'), ('0x456', 'US'), ('0x789', 'IN'); CREATE TABLE erc20_tokens (token_name VARCHAR(10), address VARCHAR(42), total_supply BIGINT); INSERT INTO erc20_tokens (token_name, address, total_supply) VALUES ('TokenA', '0x123', 1000000), ('TokenB', '0x456', 2000000), ('TokenC', '0x789', 1500000);

SELECT SUM(total_supply) FROM erc20_tokens t JOIN addresses a ON t.address = a.address WHERE a.country = 'IN';


Question: How many 'species' are found in 'Boreal Forests'?

CREATE TABLE species (id INT, name VARCHAR(50), habitat VARCHAR(50)); INSERT INTO species (id, name, habitat) VALUES (1, 'Canadian Lynx', 'Boreal Forests');

SELECT COUNT(*) FROM species WHERE habitat = 'Boreal Forests';


Question: What was the total cost of all infrastructure projects in the Philippines in 2020?'

CREATE TABLE infrastructure_projects (id INT, country VARCHAR(255), year INT, cost FLOAT); INSERT INTO infrastructure_projects (id, country, year, cost) VALUES (1, 'Philippines', 2020, 500000.00), (2, 'Philippines', 2019, 600000.00);

SELECT SUM(cost) FROM infrastructure_projects WHERE country = 'Philippines' AND year = 2020;


Question: What are the total revenues for each transport mode, excluding the 'Premium' fare type?

CREATE TABLE Fares (FareID int, FareType varchar(50), TransportMode varchar(50), Revenue int); INSERT INTO Fares VALUES (1, 'Standard', 'Bus', 5000); INSERT INTO Fares VALUES (2, 'Discounted', 'Bus', 3000); INSERT INTO Fares VALUES (3, 'Standard', 'Subway', 7000); INSERT INTO Fares VALUES (4, 'Discounted', 'Subway', 4000); INSERT INTO Fares VALUES (5, 'Premium', 'Tram', 6000);

SELECT TransportMode, SUM(Revenue) FROM Fares WHERE FareType <> 'Premium' GROUP BY TransportMode;


Question: Get the status and count of shipments for each warehouse_id from the shipment table grouped by status and warehouse_id

CREATE TABLE shipment (shipment_id VARCHAR(10), status VARCHAR(20), warehouse_id VARCHAR(10), carrier_name VARCHAR(30), shipped_date DATE);

SELECT status, warehouse_id, COUNT(*) as count FROM shipment GROUP BY status, warehouse_id;


Question: Generate PostgreSQL SQL for: Who was the opponent on april 26, 2003?

CREATE TABLE table_name_25 (opponent VARCHAR, date VARCHAR)

SELECT opponent FROM table_name_25 WHERE date = 'april 26, 2003';


Question: Generate PostgreSQL SQL for: In what year was The House of Blue Leaves nominated for outstanding actress in a play?

CREATE TABLE table_name_62 (year INTEGER, nominated_work VARCHAR, category VARCHAR)

SELECT SUM(year) FROM table_name_62 WHERE nominated_work = 'the house of blue leaves' AND category = 'outstanding actress in a play';


Question: Find the average billing rate for attorneys in 'billing' table, excluding attorneys with less than 10 hours billed

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

SELECT AVG(billing_rate) FROM billing WHERE hours_billed >= 10;


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

CREATE FUNCTION gbt_macad_penalty(internal,internal,internal)
RETURNS internal
AS 'MODULE_PATHNAME'
LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;


Question: How many defense projects exceeded their budget in the last 3 years?

CREATE TABLE DefenseProjects (id INT, project_name VARCHAR(255), start_date DATE, end_date DATE, budget INT, actual_cost INT); INSERT INTO DefenseProjects (id, project_name, start_date, end_date, budget, actual_cost) VALUES (1, 'Project A', '2019-01-01', '2021-12-31', 10000000, 11000000), (2, 'Project B', '2018-01-01', '2020-12-31', 8000000, 7500000);

SELECT COUNT(*) FROM DefenseProjects WHERE actual_cost > budget AND start_date >= DATE_SUB(CURRENT_DATE, INTERVAL 3 YEAR);


Question: Generate PostgreSQL SQL for: What is the average Tournaments, when Highest Rank is "Maegashira 1"?

CREATE TABLE table_name_90 (tournaments INTEGER, highest_rank VARCHAR)

SELECT AVG(tournaments) FROM table_name_90 WHERE highest_rank = 'maegashira 1';


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

ALTER EXTENSION pgtap ADD FUNCTION finish ();


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

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

SELECT count(*) FROM (SELECT count(*) FROM quad_poly_tbl WHERE p @> polygon '((340,550),(343,552),(341,553))') AS _sub;


Question: What is the average number of employees for companies in the 'Data Science' sector with ethical AI?

CREATE TABLE ai_companies (id INT, name VARCHAR(20), location VARCHAR(20), sector VARCHAR(20), employees INT, ethical_ai BOOLEAN); INSERT INTO ai_companies (id, name, location, sector, employees, ethical_ai) VALUES (2, 'XYZ Tech', 'USA', 'Data Science', 30, true);

SELECT sector, AVG(employees) as avg_employees FROM ai_companies WHERE ethical_ai = true AND sector = 'Data Science' GROUP BY sector;


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

SELECT jsonb_exists_all('{"a":null, "b":"qq"}', ARRAY['c','d']);

SELECT count(*) FROM (SELECT jsonb_exists_all('{"a":null, "b":"qq"}', ARRAY['c','d'])) AS _sub;


Question: Show a SQL definition from the timescaledb project (vacuum, item 29).

CREATE TABLE vacuum_norm(time timestamp, temp float);

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


Question: Write the DDL statement from PostgreSQL regression test 'polymorphism' (example 99).

CREATE AGGREGATE myaggp19b(BASETYPE = anyelement, SFUNC = tf1p,
  STYPE = anyarray, INITCOND = '{}');

Explanation: DDL from PostgreSQL core regression test for Polymorphism.


Question: Insert new data into the 'drought_impact' table reflecting the drought conditions in 'Europe'

CREATE TABLE drought_impact (id INT PRIMARY KEY, location VARCHAR(20), impact_level VARCHAR(10));

INSERT INTO drought_impact (id, location, impact_level) VALUES (7, 'Mediterranean', 'severe'), (8, 'Northern Europe', 'moderate'), (9, 'Eastern Europe', 'mild');


Question: List all departments and the number of employees in each

CREATE TABLE departments (id INT, name VARCHAR(255)); INSERT INTO departments (id, name) VALUES (1, 'Human Resources'), (2, 'Public Works'), (3, 'Education'); CREATE TABLE employees (id INT, department_id INT, gender VARCHAR(10)); INSERT INTO employees (id, department_id, gender) VALUES (1, 1, 'Female'), (2, 2, 'Male'), (3, 3, 'Female'), (4, 1, 'Non-binary'), (5, 3, 'Male');

SELECT d.name, COUNT(e.id) as employee_count FROM departments d LEFT JOIN employees e ON d.id = e.department_id GROUP BY d.id;


Question: Generate PostgreSQL SQL for: Which years did the player from Providence play for the Grizzlies as small forward?

CREATE TABLE table_name_96 (years_for_grizzlies VARCHAR, position VARCHAR, school_club_team VARCHAR)

SELECT years_for_grizzlies FROM table_name_96 WHERE position = 'small forward' AND school_club_team = 'providence';


Question: Identify the total number of regulatory actions taken against smart contracts in the Antarctic region.

CREATE TABLE smart_contracts (contract_id INT, contract_name VARCHAR(50), region VARCHAR(50)); CREATE TABLE regulatory_actions (action_id INT, contract_id INT, action_date DATE); INSERT INTO smart_contracts (contract_id, contract_name, region) VALUES (1, 'Contract A', 'Antarctic'), (2, 'Contract B', 'Antarctic'); INSERT INTO regulatory_actions (action_id, contract_id, action_date) VALUES (1, 1, '2022-01-01'), (2, 1, '2022-02-01'), (3, 2, '2022-03-01');

SELECT COUNT(*) FROM regulatory_actions r JOIN smart_contracts s ON r.contract_id = s.contract_id WHERE s.region = 'Antarctic';


Question: Generate PostgreSQL SQL for: What were the goals at Sydney?

CREATE TABLE table_name_16 (goals VARCHAR, venue VARCHAR)

SELECT goals FROM table_name_16 WHERE venue = 'sydney';


Question: PostgreSQL regression test 'tsdicts': Write the SELECT query (example 35).

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

SELECT count(*) FROM (SELECT ts_lexize('hunspell_long', 'bookings')) AS _sub;


Question: Generate PostgreSQL SQL for: What Attack has a 30,00% GERB?

CREATE TABLE table_name_74 (attack VARCHAR, gerb VARCHAR)

SELECT attack FROM table_name_74 WHERE gerb = '30,00%';


Question: Generate PostgreSQL SQL for: It was announced on July 2, 2006 that what asset was acquired?

CREATE TABLE table_1373542_1 (asset_acquired VARCHAR, date_announced VARCHAR)

SELECT asset_acquired FROM table_1373542_1 WHERE date_announced = 'July 2, 2006';


Question: Who are the community leaders engaging in cultural preservation in Africa?

CREATE TABLE community_leaders (id INT, name TEXT, role TEXT, site TEXT, region TEXT); INSERT INTO community_leaders (id, name, role, site, region) VALUES (1, 'Farouk Topan', 'Scholar', 'Bagamoyo', 'Africa');

SELECT name FROM community_leaders WHERE region = 'Africa';


Question: What is the average runtime of all TV shows in the "tv_shows" table?

CREATE TABLE tv_shows (id INT, name VARCHAR(100), genre VARCHAR(50), runtime INT);


Question: What are the total number of research grants awarded to domestic and international graduate students?

CREATE TABLE research_grants (id INT, student_type VARCHAR(10), amount DECIMAL(10,2)); INSERT INTO research_grants (id, student_type, amount) VALUES (1, 'Domestic', 15000.00), (2, 'International', 20000.00);

SELECT SUM(amount) FROM research_grants WHERE student_type IN ('Domestic', 'International');


Question: Generate PostgreSQL SQL for: Find the first name and last name of the instructor of course that has course name

CREATE TABLE FACULTY (Fname VARCHAR, Lname VARCHAR, FacID VARCHAR); CREATE TABLE COURSE (Instructor VARCHAR, CName VARCHAR)

SELECT T2.Fname, T2.Lname FROM COURSE AS T1 JOIN FACULTY AS T2 ON T1.Instructor = T2.FacID WHERE T1.CName = 'COMPUTER LITERACY';


Question: Generate PostgreSQL SQL for: what is writtenand directed by shannon flynn?

CREATE TABLE table_24018430_3 (written_by VARCHAR, directed_by VARCHAR)

SELECT written_by FROM table_24018430_3 WHERE directed_by = 'Shannon Flynn';


Question: Generate PostgreSQL SQL for: Can you tell me the Annual change that has the Location of manaus?

CREATE TABLE table_name_48 (annual_change VARCHAR, location VARCHAR)

SELECT annual_change FROM table_name_48 WHERE location = 'manaus';


Question: What is the total number of artworks by Aboriginal artists in the 'ArtCollection' table?

CREATE TABLE ArtCollection (id INT, artist VARCHAR(50), title VARCHAR(100), year INT, type VARCHAR(50), PRIMARY KEY (id));

SELECT SUM(CASE WHEN artist LIKE '%Aboriginal%' THEN 1 ELSE 0 END) FROM ArtCollection;


Question: Generate PostgreSQL SQL for: WHAT IS THE TOTAL NUMBER OF SEATS IN Hamburgische Bürgerschaft WITH AN ABBR OF bündnis 90 / die grünen (gal)?

CREATE TABLE table_name_18 (seats_in_hamburgische_bürgerschaft VARCHAR, abbr VARCHAR)

SELECT COUNT(seats_in_hamburgische_bürgerschaft) FROM table_name_18 WHERE abbr = 'bündnis 90 / die grünen (gal)';


Question: What is the average CO2 emission per coal production in WA?

CREATE TABLE co2_production (site VARCHAR(20), state VARCHAR(20), co2_emission INT, production INT); INSERT INTO co2_production (site, state, co2_emission, production) VALUES ('SiteA', 'QLD', 2500, 1500), ('SiteB', 'NSW', 3000, 2000), ('SiteC', 'WA', 3500, 1800);

SELECT state, AVG(co2_emission/production) FROM co2_production WHERE state = 'WA';


Question: Generate PostgreSQL SQL for: what's the highest player number from the list from 2000-2001

CREATE TABLE table_16494599_5 (no INTEGER, years_for_grizzlies VARCHAR)

SELECT MAX(no) FROM table_16494599_5 WHERE years_for_grizzlies = '2000-2001';


Question: Show a query using PostgreSQL contrib extension 'seg' (example 150).

SELECT '0'::seg <@ '-1 .. 1'::seg AS bool;

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


Question: What is the maximum age of community health workers in each state?

CREATE TABLE community_health_workers (id INT, name VARCHAR(50), age INT, state VARCHAR(2)); INSERT INTO community_health_workers (id, name, age, state) VALUES (1, 'John Doe', 45, 'Texas'), (2, 'Jane Smith', 35, 'California'), (3, 'Alice Johnson', 40, 'California'), (4, 'Bob Brown', 50, 'New York');

SELECT state, MAX(age) FROM community_health_workers GROUP BY state;


Question: Which infrastructure projects in California have experienced cost overruns of over 30%?

CREATE TABLE projects (project_id INT, project_name VARCHAR(100), state CHAR(2), planned_cost FLOAT, actual_cost FLOAT); INSERT INTO projects VALUES (1, 'CA Bullet Train', 'CA', 60000000000, 80000000000), (2, 'LA Subway Extension', 'CA', 10000000000, 13000000000), (3, 'SF Bay Bridge Retrofit', 'CA', 7000000000, 9000000000);

SELECT * FROM projects WHERE state = 'CA' AND actual_cost > planned_cost * 1.3;


Question: What is the total waste generation rate in the 'Commercial' sector?

CREATE TABLE CommercialWaste (id INT, sector VARCHAR(20), waste_generation_rate FLOAT); INSERT INTO CommercialWaste (id, sector, waste_generation_rate) VALUES (1, 'Commercial', 1.5), (2, 'Commercial', 1.8);

SELECT SUM(waste_generation_rate) FROM CommercialWaste WHERE sector = 'Commercial';


Question: Write the DDL statement from PostgreSQL regression test 'expressions' (example 60).

create operator = (
  leftarg    = myint,
  rightarg   = myint,
  commutator = =,
  negator    = <>,
  procedure  = myinteq,
  restrict   = eqsel,
  join       = eqjoinsel,
  merges
);

Explanation: DDL from PostgreSQL core regression test for Expressions.


Question: pgTAP test for Partitions (assertion 36).

SELECT * FROM check_test(
    is_partition_of( 'nonesuch', 'parted', 'whatevs' ),
    false,
    'is_partition_of( non-ctab, ptab, desc )',
    'whatevs',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Partitions.


Question: Generate PostgreSQL SQL for: If the dry density is 800, what is the drying shrinkage %?

CREATE TABLE table_24969173_1 (drying_shrinkage___percentage_ VARCHAR, dry_density__kg_m3_ VARCHAR)

SELECT drying_shrinkage___percentage_ FROM table_24969173_1 WHERE dry_density__kg_m3_ = 800;


Question: Generate PostgreSQL SQL for: What are the scores in matches against Tony Roche?

CREATE TABLE table_2201724_1 (score_in_the_final VARCHAR, opponent_in_the_final VARCHAR)

SELECT score_in_the_final FROM table_2201724_1 WHERE opponent_in_the_final = 'Tony Roche';


Question: Generate PostgreSQL SQL for: What is the power kw@RPM of the 13.180 model?

CREATE TABLE table_11497980_1 (power_kw VARCHAR, model VARCHAR)

SELECT COUNT(power_kw) AS @rpm FROM table_11497980_1 WHERE model = '13.180';


Question: Generate PostgreSQL SQL for: What is the nationality of Louis floch

CREATE TABLE table_24565004_7 (nationality² VARCHAR, name VARCHAR)

SELECT nationality² FROM table_24565004_7 WHERE name = 'Louis Floch';


Question: pgTAP test for Ruletap (assertion 41).

SELECT * FROM check_test(
    rule_is_on( 'public', 'sometab', 'ins_me', 'i', 'whatever' ),
    true,
    'rule_is_on(schema, table, rule, i, desc)',
    'whatever',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Ruletap.


Question: What is the average manufacturing cost of spacecrafts produced in the US?

CREATE TABLE SpacecraftManufacturing (id INT, company VARCHAR(255), country VARCHAR(255), cost FLOAT); INSERT INTO SpacecraftManufacturing (id, company, country, cost) VALUES (1, 'SpaceX', 'USA', 50000000), (2, 'Blue Origin', 'USA', 70000000), (3, 'Roscosmos', 'Russia', 30000000);

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


Question: Find the five rural healthcare professionals with the highest salaries and their respective job titles.

CREATE TABLE professionals (name VARCHAR(255), job_title VARCHAR(255), salary NUMERIC(10, 2)); INSERT INTO professionals (name, job_title, salary) VALUES ('Professional A', 'Doctor', 90000), ('Professional B', 'Nurse', 60000);

SELECT name, job_title, salary FROM professionals ORDER BY salary DESC LIMIT 5;


Question: Delete the record of the vessel 'Endeavour' if it didn't transport any cargo in the last month.

CREATE TABLE Vessels (ID INT, Name VARCHAR(255), CargoQuantity INT, LastCargoArrival DATETIME); INSERT INTO Vessels (ID, Name, CargoQuantity, LastCargoArrival) VALUES (1, 'Endeavour', 0, '2022-01-01'), (2, 'Pioneer', 100, '2022-02-01');

DELETE FROM Vessels WHERE Name = 'Endeavour' AND CargoQuantity = 0 AND LastCargoArrival < DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH);


Question: Generate PostgreSQL SQL for: What is the symbol of the element with an empirical t of 190 and a calculated value of 135?

CREATE TABLE table_name_25 (symbol VARCHAR, empirical_† VARCHAR, calculated VARCHAR)

SELECT symbol FROM table_name_25 WHERE empirical_† = '190' AND calculated = '135';


Question: What is the total carbon offset for projects in the 'carbon_offset' table in the 'Americas' region?

CREATE TABLE carbon_offset (id INT, project_name TEXT, location TEXT, carbon_offset_value FLOAT); INSERT INTO carbon_offset (id, project_name, location, carbon_offset_value) VALUES (1, 'Project 1', 'Brazil', 1000.5), (2, 'Project 2', 'Canada', 1200.3);

SELECT SUM(carbon_offset_value) FROM carbon_offset WHERE location LIKE '%Americas%';


Question: Generate PostgreSQL SQL for: How many rounds were played on May 8?

CREATE TABLE table_25773116_2 (round VARCHAR, date VARCHAR)

SELECT COUNT(round) FROM table_25773116_2 WHERE date = 'May 8';


Question: Generate PostgreSQL SQL for: which episode did sarah millican and grayson perry appear in

CREATE TABLE table_29135051_3 (episode INTEGER, guest_s_ VARCHAR)

SELECT MIN(episode) FROM table_29135051_3 WHERE guest_s_ = 'Sarah Millican and Grayson Perry';


Question: Generate PostgreSQL SQL for: What Upper stage has Launches to date of 0, and Version of 532?

CREATE TABLE table_name_86 (upper_stage VARCHAR, launches_to_date VARCHAR, version VARCHAR)

SELECT upper_stage FROM table_name_86 WHERE launches_to_date = 0 AND version = '532';


Question: Generate PostgreSQL SQL for: When the Winning is 71-71-70-69=281, what is the To par?

CREATE TABLE table_name_7 (to_par VARCHAR, winning_score VARCHAR)

SELECT to_par FROM table_name_7 WHERE winning_score = 71 - 71 - 70 - 69 = 281;


Question: Generate PostgreSQL SQL for: Who's the Republican ticket with a Communist ticket of elizabeth gurley flynn?

CREATE TABLE table_name_32 (republican_ticket VARCHAR, communist_ticket VARCHAR)

SELECT republican_ticket FROM table_name_32 WHERE communist_ticket = 'elizabeth gurley flynn';


Question: What is the total donation amount by age group?

CREATE TABLE donor (did INT, age INT, total_donation DECIMAL(10, 2)); INSERT INTO donor (did, age, total_donation) VALUES (1, 30, 1500), (2, 45, 1200), (3, 22, 800), (4, 50, 1700), (5, 28, 900);

SELECT age_group, SUM(total_donation) as total_donation FROM (SELECT CASE WHEN age < 30 THEN '18-30' WHEN age < 50 THEN '31-50' ELSE '51+' END as age_group, total_donation FROM donor) t GROUP BY age_group;


Question: List the defense projects with their start and end dates in the Middle East?

CREATE TABLE projects(id INT, name VARCHAR(255), start_date DATE, end_date DATE, region VARCHAR(255));

SELECT name, start_date, end_date FROM projects WHERE region = 'Middle East';


Question: Generate PostgreSQL SQL for: What Position does the Team of KR and the Player of Marcus Walker have listed?

CREATE TABLE table_name_8 (position VARCHAR, team VARCHAR, player VARCHAR)

SELECT position FROM table_name_8 WHERE team = 'kr' AND player = 'marcus walker';


Question: How many members joined in the first six months of 2022, by age group?

CREATE TABLE memberships (membership_id INT, join_date DATE, age INT); INSERT INTO memberships (membership_id, join_date, age) VALUES (1, '2022-01-15', 25), (2, '2022-04-20', 32), (3, '2022-06-05', 28);

SELECT COUNT(*) as first_half_count, FLOOR(age / 10) * 10 as age_group FROM memberships WHERE join_date BETWEEN '2022-01-01' AND '2022-06-30' GROUP BY age_group;


Question: Show the total revenue generated per day for the past week

CREATE TABLE sales (sale_id INT, sale_date DATE, revenue DECIMAL(10,2));

SELECT DATE(sale_date) AS sale_day, SUM(revenue) AS total_revenue FROM sales WHERE sale_date >= DATE(NOW()) - INTERVAL 7 DAY GROUP BY sale_day;


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

create table idxpart_another_1 partition of idxpart_another for values from (0) to (100);

Explanation: DDL from PostgreSQL core regression test for Indexing.


Question: Generate PostgreSQL SQL for: What is the length when the expected start of revenue is more than 2017?

CREATE TABLE table_name_62 (length VARCHAR, expected_start_of_revenue_services INTEGER)

SELECT length FROM table_name_62 WHERE expected_start_of_revenue_services > 2017;


Question: What are the names and locations of healthcare workers in the "rural_healthcenters" table?

CREATE TABLE rural_healthcenters (id INT, name TEXT, location TEXT, position TEXT); INSERT INTO rural_healthcenters (id, name, location, position) VALUES (1, 'Healthcenter A', 'Rural Area 1', 'Doctor'), (2, 'Healthcenter B', 'Rural Area 2', 'Nurse'), (3, 'Healthcenter C', 'Rural Area 3', 'Admin');

SELECT name, location FROM rural_healthcenters;


Question: What is the total revenue generated from members in the "Young Adults" demographic segment for the year 2020?

CREATE SCHEMA fitness; CREATE TABLE membership (member_id INT, demographic_segment VARCHAR(20)); CREATE TABLE revenue (member_id INT, revenue DECIMAL(10,2), transaction_date DATE); INSERT INTO membership (member_id, demographic_segment) VALUES (1, 'Young Adults'), (2, 'Seniors'); INSERT INTO revenue (member_id, revenue, transaction_date) VALUES (1, 500, '2020-01-01'), (1, 600, '2020-02-01'), (2, 300, '2020-01-01');

SELECT SUM(revenue) FROM revenue INNER JOIN membership ON revenue.member_id = membership.member_id WHERE membership.demographic_segment = 'Young Adults' AND YEAR(transaction_date) = 2020;


Question: What is the total number of ad impressions and clicks for each advertiser, and what is the difference between them?

CREATE TABLE advertisers (id INT, name VARCHAR(50)); CREATE TABLE ad_impressions (advertiser_id INT, impression_time TIMESTAMP); CREATE TABLE ad_clicks (advertiser_id INT, click_time TIMESTAMP);

SELECT advertisers.name, COUNT(ad_impressions.advertiser_id) as total_impressions, COUNT(ad_clicks.advertiser_id) as total_clicks, COUNT(ad_impressions.advertiser_id) - COUNT(ad_clicks.advertiser_id) as difference FROM advertisers LEFT JOIN ad_impressions ON advertisers.id = ad_impressions.advertiser_id LEFT JOIN ad_clicks ON advertisers.id = ad_clicks.advertiser_id GROUP BY advertisers.name;


Question: Identify habitats with more than 30 animals and the number of species in each, excluding those habitats that are not protected

CREATE TABLE habitats (id INT, name VARCHAR(255), is_protected BOOLEAN);CREATE TABLE animals (id INT, species_id INT, habitat_id INT);CREATE TABLE species (id INT, name VARCHAR(255)); INSERT INTO habitats (id, name, is_protected) VALUES (1, 'Forest', TRUE), (2, 'Savannah', FALSE), (3, 'Mountain', TRUE); INSERT INTO animals (id, species_id, habitat_id) VALUES (1, 1, 2), (2, 2, 1), (3, 3, 2), (4, 1, 2), (5, 4, 1), (6, 5, 3); INSERT INTO species (id, name) VALUES (1, 'Lion'), (2, 'Elephant'), (3, 'Giraffe'), (4, 'Zebra'), (5, 'Snow Leopard');

SELECT h.name AS habitat_name, COUNT(DISTINCT a.species_id) AS species_count FROM animals a INNER JOIN habitats h ON a.habitat_id = h.id WHERE h.is_protected = TRUE GROUP BY h.name HAVING COUNT(a.id) > 30;


Question: Show a query using PostgreSQL contrib extension 'test_decoding' (example 28).

INSERT INTO replication_example(somedata, text) VALUES (3, 1);

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


Question: Write the DDL statement from PostgreSQL regression test 'partition_join' (example 68).

CREATE INDEX iprt1_e_p3_ab2 on prt1_e_p3(((a+b)/2));

Explanation: DDL from PostgreSQL core regression test for Partition Join.


Question: Determine the year with the highest Europium production.

SELECT Year, MAX(Quantity) FROM Europium_Production GROUP BY Year ORDER BY MAX(Quantity) DESC LIMIT 1;


Question: Generate PostgreSQL SQL for: What is the name of the race in Kenya with a time of 30:27?

CREATE TABLE table_name_96 (race VARCHAR, nation VARCHAR, time VARCHAR)

SELECT race FROM table_name_96 WHERE nation = 'kenya' AND time = '30:27';


Question: Show a query using PostgreSQL contrib extension 'btree_gist' (example 10).

SELECT count(*) FROM macaddr8tmp WHERE a <  '22:00:5c:e5:9b:0d'::macaddr8;

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


Question: Show the total number of unique IP addresses that have been associated with malicious activity in the last month, including any IP addresses that have been involved in more than one incident.

CREATE TABLE malicious_activity (id INT, ip VARCHAR(255), activity_date DATE); INSERT INTO malicious_activity (id, ip, activity_date) VALUES (1, '192.168.0.1', '2022-01-01'); INSERT INTO malicious_activity (id, ip, activity_date) VALUES (2, '192.168.0.2', '2022-01-05'); INSERT INTO malicious_activity (id, ip, activity_date) VALUES (3, '192.168.0.1', '2022-01-09');

SELECT COUNT(DISTINCT ip) as total_unique_ips FROM malicious_activity WHERE activity_date >= DATEADD(month, -1, GETDATE());


Question: What is the average temperature change in the Arctic per year since 1990?

CREATE TABLE weather_data (year INT, location VARCHAR(50), temperature FLOAT);

SELECT AVG(temperature_change) FROM (SELECT (temperature - LAG(temperature) OVER (ORDER BY year)) AS temperature_change FROM weather_data WHERE year >= 1990) AS subquery;


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

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


Question: What are the regulatory frameworks in place for smart contracts in the APAC region?

CREATE TABLE RegulatoryFramework (FrameworkID INT, FrameworkName VARCHAR(100), FrameworkDescription VARCHAR(255), FrameworkRegion VARCHAR(50)); INSERT INTO RegulatoryFramework (FrameworkID, FrameworkName, FrameworkDescription, FrameworkRegion) VALUES (1, 'FrameworkA', 'DescriptionA', 'APAC'), (2, 'FrameworkB', 'DescriptionB', 'APAC'), (3, 'FrameworkC', 'DescriptionC', 'Europe');

SELECT FrameworkName, FrameworkDescription FROM RegulatoryFramework WHERE FrameworkRegion = 'APAC';


Question: PostgreSQL regression test 'boolean': Write the SELECT query (example 26).

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

SELECT count(*) FROM (SELECT bool '' AS error) AS _sub;


Question: pgTAP test for Resultset (assertion 30).

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

Explanation: SQL assertion from pgTAP test suite for Resultset.


Question: Which mobile subscribers have not made a call in the last 30 days in the 'Europe' region?

CREATE TABLE mobile_subscribers (subscriber_id INT, region VARCHAR(50), last_call_date DATETIME); INSERT INTO mobile_subscribers (subscriber_id, region, last_call_date) VALUES (1, 'Europe', '2022-02-15'), (2, 'Europe', '2022-03-03'), (3, 'Europe', NULL), (4, 'Europe', '2022-02-20'), (5, 'Europe', '2022-03-05');

SELECT subscriber_id FROM mobile_subscribers WHERE region = 'Europe' AND last_call_date IS NULL OR last_call_date < DATE_SUB(CURDATE(), INTERVAL 30 DAY);


Question: What is the average donation amount per month?

CREATE TABLE Donations (DonationID INT, DonationDate DATE, DonationAmount DECIMAL(10,2)); INSERT INTO Donations (DonationID, DonationDate, DonationAmount) VALUES (1, '2022-01-01', 100.00), (2, '2022-01-15', 200.00), (3, '2022-02-01', 300.00), (4, '2022-02-15', 400.00);

SELECT AVG(DonationAmount) OVER (PARTITION BY EXTRACT(MONTH FROM DonationDate) ORDER BY EXTRACT(MONTH FROM DonationDate)) AS AvgDonationPerMonth FROM Donations;


Question: Generate PostgreSQL SQL for: Which event had a total of 28?

CREATE TABLE table_name_51 (event VARCHAR, total VARCHAR)

SELECT event FROM table_name_51 WHERE total = '28';


Question: Find the number of days in 'October 2021' with zero water usage for 'industrial' purposes in the 'water_usage' table

CREATE TABLE water_usage (id INT, usage FLOAT, purpose VARCHAR(20), date DATE); INSERT INTO water_usage (id, usage, purpose, date) VALUES (1, 0, 'industrial', '2021-10-01'); INSERT INTO water_usage (id, usage, purpose, date) VALUES (2, 150, 'residential', '2021-10-01');

SELECT COUNT(*) FROM (SELECT date FROM water_usage WHERE purpose = 'industrial' AND usage = 0 AND date BETWEEN '2021-10-01' AND '2021-10-31' GROUP BY date HAVING COUNT(*) = 1) as zero_days;


Question: Write the DDL statement from PostgreSQL regression test 'merge' (example 365).

CREATE TABLE part1 PARTITION OF pa_target FOR VALUES IN (1,4)
  WITH (autovacuum_enabled=off);

Explanation: DDL from PostgreSQL core regression test for Merge.


Question: What is the average trip duration for wildlife enthusiasts from Brazil?

CREATE TABLE wildlife_tourists (id INT, name VARCHAR, country VARCHAR, trip_duration FLOAT); INSERT INTO wildlife_tourists (id, name, country, trip_duration) VALUES (1, 'Ana Silva', 'Brazil', 10.3);

SELECT AVG(trip_duration) FROM wildlife_tourists WHERE country = 'Brazil';


Question: Generate PostgreSQL SQL for: How many times was incumbent Noble Jones Gregory first elected?

CREATE TABLE table_1342218_17 (first_elected VARCHAR, incumbent VARCHAR)

SELECT COUNT(first_elected) FROM table_1342218_17 WHERE incumbent = 'Noble Jones Gregory';


Question: Generate PostgreSQL SQL for: How many cards does customer Art Turcotte have?

CREATE TABLE Customers_cards (customer_id VARCHAR); CREATE TABLE Customers (customer_id VARCHAR, customer_first_name VARCHAR, customer_last_name VARCHAR)

SELECT COUNT(*) FROM Customers_cards AS T1 JOIN Customers AS T2 ON T1.customer_id = T2.customer_id WHERE T2.customer_first_name = 'Art' AND T2.customer_last_name = 'Turcotte';


Question: Find the total number of transactions and trading volume for each developer in the 'developers' and 'decentralized_exchanges' tables.

CREATE TABLE developers (developer_id INT, developer_name VARCHAR(255)); CREATE TABLE decentralized_exchanges (exchange_name VARCHAR(255), developer_id INT, transaction_count INT, trading_volume DECIMAL(10, 2));

SELECT d.developer_name, SUM(de.transaction_count) as total_transactions, SUM(de.trading_volume) as total_volume FROM developers d INNER JOIN decentralized_exchanges de ON d.developer_id = de.developer_id GROUP BY d.developer_name;


Question: Update the name of the eco-friendly hotel in Spain to 'Green Hotel Barcelona'.

CREATE TABLE hotels (id INT, name TEXT, country TEXT, type TEXT); INSERT INTO hotels (id, name, country, type) VALUES (1, 'Eco Hotel Madrid', 'Spain', 'eco');

UPDATE hotels SET name = 'Green Hotel Barcelona' WHERE id = 1 AND country = 'Spain' AND type = 'eco';


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

/* Now redefine */
CREATE FUNCTION pg_stat_statements(IN showtext boolean,
    OUT userid oid,
    OUT dbid oid,
    OUT toplevel bool,
    OUT queryid bigint,
    OUT query text,
    OUT plans int8,
    OUT total_plan_time float8,
    OUT min_plan_time float8,
    OUT max_plan_time float8,
    OUT mean_plan_time float8,
    OUT stddev_plan_time float8,
    OUT calls int8,
    OUT total_exec_time float8,
    OUT min_exec_time float8,
    OUT max_exec_time float8,
    OUT mean_exec_time float8,
    OUT stddev_exec_time float8,
    OUT rows int8,
    OUT shared_blks_hit int8,
    OUT shared_blks_read int8,
    OUT shared_blks_dirtied int8,
    OUT shared_blks_written int8,
    OUT local_blks_hit int8,
    OUT local_blks_read int8,
    OUT local_blks_dirtied int8,
    OUT local_blks_written int8,
    OUT temp_blks_read int8,
    OUT temp_blks_written int8,
    OUT blk_read_time float8,
    OUT blk_write_time float8,
    OUT wal_records int8,
    OUT wal_fpi int8,
    OUT wal_bytes numeric
)
RETURNS SETOF record
AS 'MODULE_PATHNAME', 'pg_stat_statements_1_9'
LANGUAGE C STRICT VOLATILE PARALLEL SAFE;

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


Question: What is the total number of animals in 'animal_population' table?

CREATE TABLE animal_population (id INT, species VARCHAR(50), population INT);INSERT INTO animal_population (id, species, population) VALUES (1, 'Tiger', 250), (2, 'Elephant', 500);

SELECT SUM(population) FROM animal_population;


Question: Generate PostgreSQL SQL for: What is the description of the color for most products?

CREATE TABLE ref_colors (color_description VARCHAR, color_code VARCHAR); CREATE TABLE products (color_code VARCHAR)

SELECT t2.color_description FROM products AS t1 JOIN ref_colors AS t2 ON t1.color_code = t2.color_code GROUP BY t2.color_description ORDER BY COUNT(*) DESC LIMIT 1;


Question: Generate PostgreSQL SQL for: How many losses have corinthians as the team, with an against greater than 26?

CREATE TABLE table_name_32 (lost INTEGER, team VARCHAR, against VARCHAR)

SELECT SUM(lost) FROM table_name_32 WHERE team = 'corinthians' AND against > 26;


Question: Which defense contracts have a total value greater than $50,000,000?

CREATE TABLE defense_contracts (contract_id INT, contract_value FLOAT, contract_description TEXT, vendor_name TEXT, agency_name TEXT); INSERT INTO defense_contracts (contract_id, contract_value, contract_description, vendor_name, agency_name) VALUES (1, 75000000, 'Aircraft maintenance services', 'ABC Aerospace', 'US Air Force'); INSERT INTO defense_contracts (contract_id, contract_value, contract_description, vendor_name, agency_name) VALUES (2, 30000000, 'Cybersecurity services', 'DEF Security Solutions', 'US Army');

SELECT contract_id, contract_value, contract_description, vendor_name, agency_name FROM defense_contracts WHERE contract_value > 50000000;


Question: Generate PostgreSQL SQL for: Orbital period of 89 to 128 min has what specific orbital energy?

CREATE TABLE table_name_73 (specific_orbital_energy VARCHAR, orbital_period VARCHAR)

SELECT specific_orbital_energy FROM table_name_73 WHERE orbital_period = '89 to 128 min';


Question: What is the total revenue for vegetarian menu items?

CREATE TABLE restaurants (id INT, name VARCHAR(255)); INSERT INTO restaurants (id, name) VALUES (1, 'Restaurant A'), (2, 'Restaurant B'), (3, 'Restaurant C'); CREATE TABLE menu_items (id INT, name VARCHAR(255), vegetarian BOOLEAN, restaurant_id INT); INSERT INTO menu_items (id, name, vegetarian, restaurant_id) VALUES (1, 'Tacos', FALSE, 1), (2, 'Pizza', TRUE, 2), (3, 'Fried Rice', FALSE, 3), (4, 'Burrito', TRUE, 1), (5, 'Spaghetti', FALSE, 2); CREATE TABLE orders (menu_item_id INT, revenue INT); INSERT INTO orders (menu_item_id, revenue) VALUES (1, 500), (2, 700), (3, 600), (4, 800), (5, 900);

SELECT SUM(o.revenue) as total_revenue FROM orders o JOIN menu_items mi ON o.menu_item_id = mi.id WHERE mi.vegetarian = TRUE;


Question: Determine the total number of volunteers for each gender, from the 'Volunteer_Info' table, grouped by Gender.

CREATE TABLE Volunteer_Info (VolunteerID INT, First_Name VARCHAR(50), Last_Name VARCHAR(50), Gender VARCHAR(10));

SELECT Gender, COUNT(*) AS Number_Of_Volunteers FROM Volunteer_Info GROUP BY Gender;


Question: Delete all posts with comments made by a user from Brazil before 2022-07-01.

CREATE TABLE posts (id INT, user_id INT, country VARCHAR(20), title TEXT, created_date DATE); INSERT INTO posts (id, user_id, country, title, created_date) VALUES (1, 12, 'Brazil', 'AI in Society', '2022-06-01'); CREATE TABLE comments (id INT, post_id INT, user_id INT, text TEXT, created_date DATE); INSERT INTO comments (id, post_id, user_id, text, created_date) VALUES (1, 1, 13, 'Interesting thoughts.', '2022-06-15'), (2, 1, 13, 'Good read.', '2022-07-10');

DELETE FROM posts WHERE id IN (SELECT post_id FROM comments c JOIN (SELECT post_id, MIN(created_date) as mindate FROM comments WHERE country = 'Brazil' GROUP BY post_id) d ON c.post_id = d.post_id WHERE c.country = 'Brazil' AND c.created_date < d.mindate);


Question: Generate PostgreSQL SQL for: What city is Gwang-Yang stadium in?

CREATE TABLE table_name_2 (city VARCHAR, stadium VARCHAR)

SELECT city FROM table_name_2 WHERE stadium = 'gwang-yang stadium';


Question: Who is the top donor in terms of total donation amount?

CREATE TABLE Donors (DonorID INT, Name TEXT, DonationAmount DECIMAL);

SELECT Name, SUM(DonationAmount) AS TotalDonation FROM Donors GROUP BY Name ORDER BY TotalDonation DESC LIMIT 1;


Question: Generate PostgreSQL SQL for: Name the original air date of 1/2 in season

CREATE TABLE table_16951593_1 (original_air_date VARCHAR, no_in_season VARCHAR)

SELECT original_air_date FROM table_16951593_1 WHERE no_in_season = '1/2';


Question: What is the total sales by ethical material and gender?

CREATE TABLE SalesByMaterialAndGender (SaleID INT, Material VARCHAR(50), Gender VARCHAR(50), Sales DECIMAL(5,2)); INSERT INTO SalesByMaterialAndGender (SaleID, Material, Gender, Sales) VALUES (1, 'Organic Cotton', 'Male', 500.50), (2, 'Hemp', 'Female', 250.20), (3, 'Recycled Polyester', 'Non-binary', 156.60), (4, 'Tencel', 'Male', 100.10);

SELECT Material, Gender, SUM(Sales) AS TotalSales FROM SalesByMaterialAndGender GROUP BY Material, Gender;


Question: What is the total cost of wind projects?

CREATE TABLE projects (project_id INT, project_name VARCHAR(50), project_type VARCHAR(50), project_cost FLOAT, project_start_date DATE); INSERT INTO projects (project_id, project_name, project_type, project_cost, project_start_date) VALUES (1, 'Solar Farm A', 'Solar', 5000000, '2020-01-01'), (2, 'Wind Farm B', 'Wind', 7000000, '2019-01-01');

SELECT SUM(project_cost) as total_wind_cost FROM projects WHERE project_type = 'Wind';


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

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

SELECT count(*) FROM (SELECT * FROM INT8_TBL WHERE q2 >= 4567890123456789) AS _sub;


Question: Insert new records into the 'inventory' table with the following data: (1001, 'Pre-rolls', 100, 20), (1002, 'Gelato', 50, 15), (1003, 'Sour Diesel', 75, 12)

CREATE TABLE inventory (inventory_id INT, product_name VARCHAR(255), quantity INT, price DECIMAL(5,2));

INSERT INTO inventory (inventory_id, product_name, quantity, price) VALUES (1001, 'Pre-rolls', 100, 20), (1002, 'Gelato', 50, 15), (1003, 'Sour Diesel', 75, 12);


Question: List all defense contracts with vendor companies located in Texas, sorted by contract value in descending order.

CREATE TABLE defense_contracts (contract_id INT, contract_value FLOAT, vendor_state VARCHAR(2)); INSERT INTO defense_contracts (contract_id, contract_value, vendor_state) VALUES (1, 1000000, 'TX'), (2, 500000, 'CA'), (3, 750000, 'TX');

SELECT * FROM defense_contracts WHERE vendor_state = 'TX' ORDER BY contract_value DESC;


Question: Show a query using PostgreSQL contrib extension 'hstore' (example 164).

insert into testhstore0 values (1, 'foo', 1.2, 3::float8);

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


Question: Generate PostgreSQL SQL for: what is the amount lost when there is 1 draw and 515 points?

CREATE TABLE table_name_72 (lost VARCHAR, drawn VARCHAR, points_for VARCHAR)

SELECT lost FROM table_name_72 WHERE drawn = '1' AND points_for = '515';


Question: List the names and case numbers of cases in 'cases' table that were assigned to attorney_id 5

CREATE TABLE cases (case_id INT, case_number VARCHAR(50), client_name VARCHAR(50), attorney_id INT);

SELECT cases.case_number, cases.client_name FROM cases WHERE cases.attorney_id = 5;


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

SELECT segment_number, file_offset
FROM pg_walfile_name_offset('0/0'::pg_lsn + :segment_size + 1),
     pg_split_walfile_name(file_name);

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

SELECT count(*) FROM (SELECT segment_number, file_offset
FROM pg_walfile_name_offset('0/0'::pg_lsn + :segment_size + 1),
     pg_split_walfile_name(file_name)) AS _sub;


Question: Generate PostgreSQL SQL for: When did the north melbourne team play?

CREATE TABLE table_name_7 (date VARCHAR, home_team VARCHAR)

SELECT date FROM table_name_7 WHERE home_team = 'north melbourne';


Question: pgTAP test for Hastap (assertion 181).

SELECT * FROM check_test(
  has_operator( 'integer', 'pg_catalog', '<=', 'text', 'bool', 'desc' ),
  false,
  'has_operator( left, schema, name, right, result, desc ) fail',
  'desc',
  ''
);

Explanation: SQL assertion from pgTAP test suite for Hastap.


Question: Generate PostgreSQL SQL for: What is Volume:Issue, when Weeks on Top is less than 5, and when Issue Date(s) are 10 July - 24 July?

CREATE TABLE table_name_75 (volume VARCHAR, weeks_on_top VARCHAR, issue_date_s_ VARCHAR)

SELECT volume AS :issue FROM table_name_75 WHERE weeks_on_top < 5 AND issue_date_s_ = '10 july - 24 july';


Question: Generate PostgreSQL SQL for: What is the lowest Game where Inning is 6th, and the Opposing Pitcher is cliff curtis?

CREATE TABLE table_name_14 (game INTEGER, inning VARCHAR, opposing_pitcher VARCHAR)

SELECT MIN(game) FROM table_name_14 WHERE inning = '6th' AND opposing_pitcher = 'cliff curtis';


Question: What is the percentage change in yield for each crop over the past year?

CREATE TABLE farming (id INT, name TEXT, location TEXT, crop TEXT, yield INT, year INT); INSERT INTO farming VALUES (1, 'Smith Farm', 'Colorado', 'Corn', 120, 2020), (2, 'Brown Farm', 'Nebraska', 'Soybeans', 45, 2020), (3, 'Jones Farm', 'Iowa', 'Wheat', 80, 2020), (1, 'Smith Farm', 'Colorado', 'Corn', 130, 2021), (2, 'Brown Farm', 'Nebraska', 'Soybeans', 50, 2021), (3, 'Jones Farm', 'Iowa', 'Wheat', 85, 2021);

SELECT crop, ROUND(100.0 * (yield - LAG(yield) OVER (PARTITION BY crop ORDER BY year)) / LAG(yield) OVER (PARTITION BY crop ORDER BY year), 2) as percentage_change FROM farming WHERE year > 2020;


Question: Generate PostgreSQL SQL for: What season has a number less than 90, Mitte as the league and spvgg ruhmannsfelden as the team?

CREATE TABLE table_name_95 (season VARCHAR, team VARCHAR, number VARCHAR, league VARCHAR)

SELECT season FROM table_name_95 WHERE number < 90 AND league = 'mitte' AND team = 'spvgg ruhmannsfelden';


Question: Generate PostgreSQL SQL for: What are average launches with 0 failures, rocket of Soyuz, and less than 12 successes?

CREATE TABLE table_name_3 (launches INTEGER, successes VARCHAR, failures VARCHAR, rocket VARCHAR)

SELECT AVG(launches) FROM table_name_3 WHERE failures = 0 AND rocket = 'soyuz' AND successes < 12;


Question: What is the number of infrastructure projects in the Western region of the US for each year since 2015, categorized by type?

CREATE TABLE Infrastructure_Projects (Project_ID INT, Project_Name VARCHAR(255), Project_Type VARCHAR(255), Year INT, State VARCHAR(255));

SELECT Year, Project_Type, COUNT(*) FROM Infrastructure_Projects WHERE State LIKE '%Western%' AND Year >= 2015 GROUP BY Year, Project_Type;


Question: Generate PostgreSQL SQL for: I want the NGC number for leo of irregular galaxy

CREATE TABLE table_name_16 (ngc_number VARCHAR, constellation VARCHAR, object_type VARCHAR)

SELECT ngc_number FROM table_name_16 WHERE constellation = 'leo' AND object_type = 'irregular galaxy';


Question: Generate PostgreSQL SQL for: Who won the Suntree Seniors Classic?

CREATE TABLE table_11622924_1 (winner VARCHAR, tournament VARCHAR)

SELECT winner FROM table_11622924_1 WHERE tournament = 'Suntree Seniors Classic';


Question: What is the maximum installed capacity of wind energy projects in Spain?

CREATE TABLE wind_projects (id INT, country VARCHAR(50), capacity FLOAT); INSERT INTO wind_projects (id, country, capacity) VALUES (1, 'Spain', 234.56), (2, 'Italy', 123.45), (3, 'Spain', 678.90);

SELECT MAX(capacity) FROM wind_projects WHERE country = 'Spain';


Question: Show a query using PostgreSQL contrib extension 'btree_gist' (example 13).

SELECT count(*) FROM float8tmp WHERE a  = -1890.0::float8;


Question: Generate PostgreSQL SQL for: When the record was 32-37 what was the score?

CREATE TABLE table_name_92 (score VARCHAR, record VARCHAR)

SELECT score FROM table_name_92 WHERE record = '32-37';


Question: Generate PostgreSQL SQL for: Name the name for deceased spouse being louis malle

CREATE TABLE table_24143253_1 (name VARCHAR, deceased_spouse VARCHAR)

SELECT name FROM table_24143253_1 WHERE deceased_spouse = 'Louis Malle';


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

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

SELECT count(*) FROM (select jsonb_path_query('{"a": 12, "b": {"a": 13}}', '$.a')) AS _sub;


Question: Generate PostgreSQL SQL for: What place was the viewed horse?

CREATE TABLE table_name_13 (placing VARCHAR, horse VARCHAR)

SELECT placing FROM table_name_13 WHERE horse = 'viewed';


Question: How many visual art exhibitions were held in Paris and London in 2020?

CREATE TABLE exhibitions (id INT, city VARCHAR(20), year INT, type VARCHAR(10)); INSERT INTO exhibitions (id, city, year, type) VALUES (1, 'Paris', 2020, 'visual art'), (2, 'London', 2019, 'visual art'), (3, 'Paris', 2020, 'performing art'), (4, 'London', 2020, 'visual art'), (5, 'New York', 2020, 'visual art');

SELECT COUNT(*) FROM exhibitions WHERE city IN ('Paris', 'London') AND year = 2020 AND type = 'visual art';


Question: Generate PostgreSQL SQL for: What is the average episode number where jimmy mulville was the 4th performer?

CREATE TABLE table_name_35 (episode INTEGER, performer_4 VARCHAR)

SELECT AVG(episode) FROM table_name_35 WHERE performer_4 = 'jimmy mulville';


Question: How many unique users have streamed songs from the country genre?

CREATE TABLE songs (id INT, title VARCHAR(255), genre VARCHAR(255), release_year INT); CREATE TABLE streams (stream_id INT, song_id INT, user_id INT, timestamp TIMESTAMP); INSERT INTO songs (id, title, genre, release_year) VALUES (1, 'Song1', 'Country', 2016), (2, 'Song2', 'Rock', 2010), (3, 'Song3', 'Country', 2015); INSERT INTO streams (stream_id, song_id, user_id, timestamp) VALUES (1, 1, 1, '2022-01-01 10:00:00'), (2, 2, 2, '2022-01-02 10:00:00'), (3, 1, 3, '2022-01-03 10:00:00'), (4, 3, 4, '2022-01-04 10:00:00'), (5, 1, 5, '2022-01-05 10:00:00');

SELECT COUNT(DISTINCT user_id) FROM streams JOIN songs ON streams.song_id = songs.id WHERE songs.genre = 'Country';


Question: pgTAP test for Resultset (assertion 301).

UPDATE dubs SET name = 'foo' WHERE pk = 1;


Question: Find the total production quantity (in metric tons) of Yttrium for the years 2014, 2015 and 2016.

CREATE TABLE production_data (year INT, element TEXT, production_quantity FLOAT); INSERT INTO production_data (year, element, production_quantity) VALUES (2014, 'Yttrium', 700); INSERT INTO production_data (year, element, production_quantity) VALUES (2015, 'Yttrium', 750); INSERT INTO production_data (year, element, production_quantity) VALUES (2016, 'Yttrium', 800);

SELECT SUM(production_quantity) FROM production_data WHERE element = 'Yttrium' AND year BETWEEN 2014 AND 2016;


Question: Generate PostgreSQL SQL for: Which away team that had 48 as a Tie no?

CREATE TABLE table_name_46 (away_team VARCHAR, tie_no VARCHAR)

SELECT away_team FROM table_name_46 WHERE tie_no = '48';


Question: Generate PostgreSQL SQL for: Which Delegate has a Placement in Miss Universe of fourth runner-up, and a Hometown of makati , rizal?

CREATE TABLE table_name_96 (delegate VARCHAR, placement_in_miss_universe VARCHAR, hometown VARCHAR)

SELECT delegate FROM table_name_96 WHERE placement_in_miss_universe = 'fourth runner-up' AND hometown = 'makati , rizal';


Question: How many marine species are found in the Atlantic basin, grouped by species name?

CREATE TABLE marine_species_atlantic (name VARCHAR(255), basin VARCHAR(255)); INSERT INTO marine_species_atlantic (name, basin) VALUES ('Species1', 'Atlantic'), ('Species2', 'Pacific'), ('Species3', 'Indian'), ('Species4', 'Atlantic');

SELECT name, COUNT(*) as num_species  FROM marine_species_atlantic  WHERE basin = 'Atlantic'  GROUP BY name;


Question: What is the total number of military personnel and their corresponding rank for each branch in the 'military_personnel' table, sorted by the total number of personnel in descending order?

CREATE TABLE military_personnel (id INT, branch VARCHAR(255), rank VARCHAR(255), personnel INT);

SELECT branch, SUM(personnel) as total_personnel FROM military_personnel GROUP BY branch ORDER BY total_personnel DESC;


Question: Generate PostgreSQL SQL for: How many touchdowns were made where field goals were less than 0?

CREATE TABLE table_name_81 (touchdowns INTEGER, field_goals INTEGER)

SELECT SUM(touchdowns) FROM table_name_81 WHERE field_goals < 0;


Question: Delete all records of suppliers from 'Country F' who do not supply parts to factories with Industry 4.0 practices.

CREATE TABLE Suppliers (ID INT, Country VARCHAR(20), Industry_4_0 BOOLEAN); INSERT INTO Suppliers (ID, Country, Industry_4_0) VALUES (1, 'Country A', TRUE), (2, 'Country B', FALSE), (3, 'Country A', FALSE), (4, 'Country F', TRUE), (5, 'Country F', FALSE);

DELETE FROM Suppliers WHERE Country = 'Country F' AND NOT EXISTS (SELECT 1 FROM Factories WHERE Suppliers.ID = Factories.Supplier_ID AND Factories.Industry_4_0 = TRUE);