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

CREATE OPERATOR @ (
        LEFTARG = ltree,
	RIGHTARG = ltxtquery,
	PROCEDURE = ltxtq_exec,
	COMMUTATOR = '@',
	RESTRICT = contsel,
	JOIN = contjoinsel
);


Question: Generate PostgreSQL SQL for: What was the score for the Toshiba Senior Classic?

CREATE TABLE table_11621799_1 (score VARCHAR, tournament VARCHAR)

SELECT score FROM table_11621799_1 WHERE tournament = 'Toshiba Senior Classic';


Question: Generate PostgreSQL SQL for: What average game has @ florida panthers as the opponent, 0-1-2 as the record, with an october greater than 8?

CREATE TABLE table_name_17 (game INTEGER, october VARCHAR, opponent VARCHAR, record VARCHAR)

SELECT AVG(game) FROM table_name_17 WHERE opponent = '@ florida panthers' AND record = '0-1-2' AND october > 8;


Question: Generate PostgreSQL SQL for: Where is the team that is managed by richard barnwell from?

CREATE TABLE table_27409644_1 (location VARCHAR, manager VARCHAR)

SELECT location FROM table_27409644_1 WHERE manager = 'Richard Barnwell';


Question: Find the total area of soybean fields in the 'field_sizes' table that are larger than 500 acres and are located in Brazil.

CREATE TABLE field_sizes (crop_type VARCHAR(50), location VARCHAR(50), area_acres FLOAT); INSERT INTO field_sizes (crop_type, location, area_acres) VALUES ('Soybean', 'Brazil', 650); INSERT INTO field_sizes (crop_type, location, area_acres) VALUES ('Soybean', 'Brazil', 475);

SELECT SUM(area_acres) FROM field_sizes WHERE crop_type = 'Soybean' AND location = 'Brazil' AND area_acres > 500;


Question: Generate PostgreSQL SQL for: How many dfb-pokal did kevin-prince boateng have?

CREATE TABLE table_22167196_1 (dfb_pokal VARCHAR, player VARCHAR)

SELECT COUNT(dfb_pokal) FROM table_22167196_1 WHERE player = 'Kevin-Prince Boateng';


Question: What is the total number of animals in the 'community_education' view, grouped by continent?

CREATE TABLE animal_population (animal VARCHAR(50), continent VARCHAR(50), population INT); INSERT INTO animal_population (animal, continent, population) VALUES ('Tiger', 'Asia', 500), ('Elephant', 'Africa', 300), ('Giraffe', 'Africa', 200), ('Penguin', 'Antarctica', 100); CREATE VIEW community_education AS SELECT animal, CONCAT('South ', continent) AS continent FROM animal_population WHERE continent IN ('America', 'Asia');

SELECT continent, COUNT(*) FROM community_education GROUP BY continent;


Question: What is the minimum diversity score for content creators who identify as LGBTQ+ in Europe?

CREATE TABLE content_creators (id INT, name VARCHAR(50), diversity_score INT, country VARCHAR(50), gender VARCHAR(10), sexual_orientation VARCHAR(20)); INSERT INTO content_creators (id, name, diversity_score, country, gender, sexual_orientation) VALUES (1, 'Creator1', 80, 'UK', 'Female', 'LGBTQ+'), (2, 'Creator2', 85, 'France', 'Male', 'Straight'), (3, 'Creator3', 90, 'Germany', 'Non-binary', 'LGBTQ+'), (4, 'Creator4', 75, 'Italy', 'Female', 'Straight');

SELECT MIN(diversity_score) FROM content_creators WHERE country IN ('UK', 'France', 'Germany', 'Italy') AND sexual_orientation = 'LGBTQ+';


Question: What is the total revenue for events in Los Angeles, CA in the last quarter?

CREATE TABLE Events (id INT, city VARCHAR(20), country VARCHAR(20), date DATE, price DECIMAL(5,2)); INSERT INTO Events (id, city, country, date, price) VALUES (1, 'Los Angeles', 'USA', '2023-01-01', 20.00), (2, 'Los Angeles', 'USA', '2023-03-15', 30.00);

SELECT SUM(price) as total_revenue FROM Events WHERE city = 'Los Angeles' AND country = 'USA' AND date >= DATEADD(quarter, -1, GETDATE());


Question: How many subscribers are there in each region for broadband services?

CREATE TABLE broadband_subscribers (subscriber_id INT, subscriber_name VARCHAR(50), region VARCHAR(50), plan_type VARCHAR(50), monthly_charges DECIMAL(5,2));INSERT INTO broadband_subscribers (subscriber_id, subscriber_name, region, plan_type, monthly_charges) VALUES (1, 'John Doe', 'North', 'Basic', 34.99), (2, 'Jane Smith', 'South', 'Premium', 59.99), (3, 'Bob Johnson', 'East', 'Basic', 34.99), (4, 'Alice Williams', 'West', 'Premium', 59.99);

SELECT region, COUNT(*) as subscriber_count FROM broadband_subscribers GROUP BY region;


Question: What is the total number of assistive technology items provided for students with visual or hearing impairments?

CREATE TABLE Assistive_Tech (Student_ID INT, Student_Name TEXT, Disability_Type TEXT, Assistive_Tech_Item TEXT); INSERT INTO Assistive_Tech (Student_ID, Student_Name, Disability_Type, Assistive_Tech_Item) VALUES (7, 'Alex Thompson', 'Hearing Impairment', 'Hearing Aid'), (8, 'Jasmine Chen', 'Visual Impairment', 'Screen Reader'), (9, 'Ethan Nguyen', 'None', 'None');

SELECT SUM(CASE WHEN Disability_Type IN ('Visual Impairment', 'Hearing Impairment') THEN 1 ELSE 0 END) FROM Assistive_Tech WHERE Assistive_Tech_Item IS NOT NULL;


Question: Generate PostgreSQL SQL for: Which Total has a Rank of 5, and a Bronze smaller than 0?

CREATE TABLE table_name_67 (total INTEGER, rank VARCHAR, bronze VARCHAR)

SELECT AVG(total) FROM table_name_67 WHERE rank = '5' AND bronze < 0;


Question: Generate PostgreSQL SQL for: Who is the Runner-up in Tournament of seiersberg

CREATE TABLE table_name_95 (runner_up VARCHAR, tournament VARCHAR)

SELECT runner_up FROM table_name_95 WHERE tournament = 'seiersberg';


Question: Generate PostgreSQL SQL for: Who were all of the opponents in 1984?

CREATE TABLE table_1399994_5 (opponents VARCHAR, year VARCHAR)

SELECT opponents FROM table_1399994_5 WHERE year = '1984';


Question: Generate PostgreSQL SQL for: What high points did San Francisco have in a game later than 69?

CREATE TABLE table_name_39 (high_points VARCHAR, game VARCHAR, team VARCHAR)

SELECT high_points FROM table_name_39 WHERE game > 69 AND team = 'san francisco';


Question: Show a query using PostgreSQL contrib extension 'postgres_fdw' (example 419).

INSERT INTO parent_tbl (a) VALUES(1),(5);

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


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

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

SELECT count(*) FROM (select * from rngfuncbar()) AS _sub;


Question: Generate PostgreSQL SQL for: Name the won promotion for kalmar ff

CREATE TABLE table_2119448_3 (won_promotion VARCHAR, lost_promotion_playoffs VARCHAR)

SELECT won_promotion FROM table_2119448_3 WHERE lost_promotion_playoffs = 'Kalmar FF';


Question: What is the total number of buses and trams in the 'south' region?

CREATE TABLE vehicle_counts (region VARCHAR(10), vehicle_type VARCHAR(10), count INT); INSERT INTO vehicle_counts (region, vehicle_type, count) VALUES ('east', 'buses', 100), ('west', 'buses', 120), ('north', 'buses', 150), ('south', 'buses', 80), ('east', 'trams', 20), ('west', 'trams', 30), ('north', 'trams', 40), ('south', 'trams', 50);

SELECT SUM(count) FROM vehicle_counts WHERE region = 'south' AND (vehicle_type = 'buses' OR vehicle_type = 'trams');


Question: Update the location of the virtual tour with an id of 1

CREATE TABLE virtual_tours (id INT PRIMARY KEY, name VARCHAR(255), location VARCHAR(255), tour_type VARCHAR(255)); INSERT INTO virtual_tours (id, name, location, tour_type) VALUES (1, 'Paris Virtual Tour', 'Paris', 'museum_tour'); INSERT INTO virtual_tours (id, name, location, tour_type) VALUES (2, 'Rome Virtual Tour', 'Rome', 'city_tour');

UPDATE virtual_tours SET location = 'France' WHERE id = 1;


Question: Generate PostgreSQL SQL for: What was the result of the 2011 US Open when the 2007 was F?

CREATE TABLE table_name_59 (tournament VARCHAR)

SELECT 2011 FROM table_name_59 WHERE 2007 = 'f' AND tournament = 'us open';


Question: What are the cybersecurity incidents reported in the last 6 months?

CREATE TABLE cyber_incidents (id INT, incident_date DATE, description VARCHAR(255)); INSERT INTO cyber_incidents (id, incident_date, description) VALUES (1, '2022-01-01', 'Phishing attack'), (2, '2022-03-15', 'Ransomware attack'), (3, '2022-04-20', 'Data breach'), (4, '2022-06-05', 'Malware attack');

SELECT description, incident_date FROM cyber_incidents WHERE incident_date >= DATE(NOW()) - INTERVAL 6 MONTH;


Question: Find the average speed of electric vehicles in New York and London?

CREATE TABLE vehicle_speed (id INT, type VARCHAR(20), city VARCHAR(20), speed INT); INSERT INTO vehicle_speed (id, type, city, speed) VALUES (1, 'electric', 'New York', 50), (2, 'electric', 'London', 60), (3, 'gasoline', 'New York', 40);

SELECT AVG(speed) FROM vehicle_speed WHERE type = 'electric' AND city IN ('New York', 'London');


Question: Write the DML statement from PostgreSQL regression test 'jsonb' (example 839).

update test_jsonb_subscript set test_json = NULL where id = 3;

Explanation: DML from PostgreSQL core regression test for Jsonb.


Question: Display the average monthly maintenance cost for each equipment type in the 'EquipmentMaintenance' table

CREATE TABLE EquipmentMaintenance (id INT, type VARCHAR(255), cost FLOAT, date DATE);

SELECT type, AVG(cost) as avg_monthly_cost FROM EquipmentMaintenance WHERE date >= '2021-01-01' AND date <= '2021-12-31' GROUP BY type;


Question: Which medical conditions were diagnosed for astronauts from Egypt?

CREATE TABLE Astronaut (id INT PRIMARY KEY, name VARCHAR(50), age INT, gender VARCHAR(10), nationality VARCHAR(50)); CREATE TABLE Medical (id INT PRIMARY KEY, astronaut_id INT, medical_condition VARCHAR(50), examination_date DATE, FOREIGN KEY (astronaut_id) REFERENCES Astronaut(id));

SELECT Medical.medical_condition FROM Astronaut INNER JOIN Medical ON Astronaut.id = Medical.astronaut_id WHERE Astronaut.nationality = 'Egypt';


Question: Which organic grocery stores in New York City sell locally sourced fruits?

CREATE TABLE Store (id INT, name VARCHAR(50), city VARCHAR(50)); INSERT INTO Store (id, name, city) VALUES (1, 'Green Earth', 'New York'); INSERT INTO Store (id, name, city) VALUES (2, 'Healthy Harvest', 'Los Angeles'); CREATE TABLE Inventory (id INT, store_id INT, item VARCHAR(50), is_local BOOLEAN, is_organic BOOLEAN); INSERT INTO Inventory (id, store_id, item, is_local, is_organic) VALUES (1, 1, 'Apples', TRUE, TRUE); INSERT INTO Inventory (id, store_id, item, is_local, is_organic) VALUES (2, 1, 'Bananas', FALSE, TRUE); INSERT INTO Inventory (id, store_id, item, is_local, is_organic) VALUES (3, 2, 'Oranges', TRUE, TRUE); INSERT INTO Inventory (id, store_id, item, is_local, is_organic) VALUES (4, 2, 'Grapes', FALSE, TRUE);

SELECT s.name FROM Store s JOIN Inventory i ON s.id = i.store_id WHERE s.city = 'New York' AND i.is_local = TRUE AND i.is_organic = TRUE AND i.item LIKE 'F%';


Question: Calculate the percentage of vegan customers in each city.

CREATE TABLE Customers (CustomerID INT, Name TEXT, City TEXT, IsVegan BOOLEAN);

SELECT City, IsVegan, COUNT(IsVegan) * 100.0 / (SELECT COUNT(*) FROM Customers) AS Percentage FROM Customers WHERE IsVegan = TRUE GROUP BY City;


Question: Generate PostgreSQL SQL for: What player has a no pick position in 1976?

CREATE TABLE table_name_33 (player VARCHAR, position VARCHAR, year VARCHAR)

SELECT player FROM table_name_33 WHERE position = 'no pick' AND year = 1976;


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

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

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


Question: What is the maximum horsepower of sports cars released in 2022?

CREATE TABLE SportsCars (VIN VARCHAR(20), Model VARCHAR(20), Horsepower INT, ProductionYear INT); INSERT INTO SportsCars (VIN, Model, Horsepower, ProductionYear) VALUES ('AA11BB2233', 'ModelX', 500, 2022), ('CC22DD3344', 'ModelY', 600, 2022);

SELECT MAX(Horsepower) FROM SportsCars WHERE ProductionYear = 2022 AND Model LIKE '%Sports Car%';


Question: Write the DML statement from PostgreSQL regression test 'vacuum' (example 316).

INSERT INTO vac_rewrite_toast values (1, repeat('a', 7000));

Explanation: DML from PostgreSQL core regression test for Vacuum.


Question: How many unique customers purchased sustainable clothing in the last 6 months?

CREATE TABLE Customers (id INT, name VARCHAR(50), sustainable_purchase_date DATE); INSERT INTO Customers (id, name, sustainable_purchase_date) VALUES (1, 'Alice', '2022-01-01'), (2, 'Bob', '2022-02-15'), (3, 'Charlie', '2022-03-05'), (4, 'David', '2022-04-10'), (5, 'Eve', '2022-05-25'), (6, 'Frank', '2022-06-12');

SELECT COUNT(DISTINCT id) FROM Customers WHERE sustainable_purchase_date >= DATEADD(MONTH, -6, GETDATE());


Question: Generate PostgreSQL SQL for: Which match was the final score 7–6 (7–0) , 6–7 (5–7) , 4–6, 6–2, 6–7 (5–7)?

CREATE TABLE table_26202812_7 (no VARCHAR, score_in_the_final VARCHAR)

SELECT no FROM table_26202812_7 WHERE score_in_the_final = '7–6 (7–0) , 6–7 (5–7) , 4–6, 6–2, 6–7 (5–7)';


Question: Generate PostgreSQL SQL for: When was a competition held at Pietermaritzburg?

CREATE TABLE table_name_83 (date VARCHAR, venue VARCHAR)

SELECT date FROM table_name_83 WHERE venue = 'pietermaritzburg';


Question: Generate PostgreSQL SQL for: What is the overall pick number that Derrick Harvey was when he was picked in a round after round 1?

CREATE TABLE table_name_26 (overall INTEGER, name VARCHAR, round VARCHAR)

SELECT MIN(overall) FROM table_name_26 WHERE name = 'derrick harvey' AND round > 1;


Question: Generate PostgreSQL SQL for: What is the total number of laps during the race that had a time of +9.682?

CREATE TABLE table_name_6 (laps VARCHAR, time_retired VARCHAR)

SELECT COUNT(laps) FROM table_name_6 WHERE time_retired = '+9.682';


Question: Write the DDL statement from PostgreSQL regression test 'update' (example 71).

CREATE TABLE part_c_1_100 (e varchar, d int, c numeric, b bigint, a text);

Explanation: DDL from PostgreSQL core regression test for Update.


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

-- any_column_privs_are ( schema, table, user, privileges[], description )
CREATE OR REPLACE FUNCTION any_column_privs_are ( NAME, NAME, NAME, NAME[], TEXT )
RETURNS TEXT AS $$
DECLARE
    grants TEXT[] := _get_ac_privs( $3, quote_ident($1) || '.' || quote_ident($2) );
BEGIN
    IF grants[1] = 'undefined_table' THEN
        RETURN ok(FALSE, $5) || E'\n' || diag(
            '    Table ' || quote_ident($1) || '.' || quote_ident($2) || ' does not exist'
        );
    ELSIF grants[1] = 'undefined_role' THEN
        RETURN ok(FALSE, $5) || E'\n' || diag(
            '    Role ' || quote_ident($3) || ' does not exist'
        );
    END IF;
    RETURN _assets_are('privileges', grants, $4, $5);
END;
$$ LANGUAGE plpgsql;

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


Question: Generate PostgreSQL SQL for: What percentage of voters voted for a third party in the county that had 802 third party voters?

CREATE TABLE table_20278716_2 (others__percentage VARCHAR, others__number VARCHAR)

SELECT others__percentage FROM table_20278716_2 WHERE others__number = 802;


Question: Generate PostgreSQL SQL for: How many poles had a moto2 class?

CREATE TABLE table_name_75 (pole VARCHAR, class VARCHAR)

SELECT pole FROM table_name_75 WHERE class = 'moto2';


Question: PostgreSQL regression test 'horology': Write the SELECT query (example 38).

SELECT time without time zone 'T040506.789+08';

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

SELECT count(*) FROM (SELECT time without time zone 'T040506.789+08') AS _sub;


Question: Generate PostgreSQL SQL for: What was the result of the match that had a score of 58-6?

CREATE TABLE table_name_92 (result VARCHAR, score VARCHAR)

SELECT result FROM table_name_92 WHERE score = '58-6';


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

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

SELECT count(*) FROM (select jsonb_path_query('"2023-08-15"', '$.time()')) AS _sub;


Question: Write the DML statement from PostgreSQL regression test 'union' (example 159).

INSERT INTO t2c VALUES ('vw'), ('cd'), ('mn'), ('ef');

Explanation: DML from PostgreSQL core regression test for Union.


Question: Insert records for properties in New York with a green_certification of 'ENERGY STAR' into the GreenCertified view.

CREATE TABLE GreenBuildings (id INT, building_id INT, address VARCHAR(100), green_certification VARCHAR(50)); CREATE VIEW GreenCertified AS SELECT building_id, COUNT(green_certification) as num_certified FROM GreenBuildings WHERE green_certification IS NOT NULL GROUP BY building_id;

INSERT INTO GreenCertified (building_id, num_certified) SELECT building_id, 1 FROM GreenBuildings WHERE state = 'NY' AND green_certification = 'ENERGY STAR';


Question: Generate PostgreSQL SQL for: What is the production code that was written by matt robinson?

CREATE TABLE table_2818164_7 (production_code VARCHAR, written_by VARCHAR)

SELECT production_code FROM table_2818164_7 WHERE written_by = 'Matt Robinson';


Question: Generate PostgreSQL SQL for: What numbered game featured a High rebounds of radoslav nesterović (8), and a High assists of josé calderón (9)?

CREATE TABLE table_name_12 (game VARCHAR, high_rebounds VARCHAR, high_assists VARCHAR)

SELECT COUNT(game) FROM table_name_12 WHERE high_rebounds = 'radoslav nesterović (8)' AND high_assists = 'josé calderón (9)';


Question: List the names of rural healthcare centers in the US that serve more than 200 patients.

CREATE TABLE healthcare_centers_us (name TEXT, location TEXT, patients_served INT); INSERT INTO healthcare_centers_us (name, location, patients_served) VALUES ('HC A', 'Rural Alabama', 250), ('HC B', 'Rural Alaska', 150), ('HC C', 'Rural California', 225);

SELECT name FROM healthcare_centers_us WHERE location LIKE 'Rural%' AND patients_served > 200;


Question: What is the total number of publications by assistant professors in the Engineering college?

CREATE TABLE faculty(id INT, rank TEXT, college TEXT); CREATE TABLE publications(id INT, faculty_id INT, year INT); INSERT INTO faculty(id, rank, college) VALUES (1, 'assistant professor', 'Engineering'), (2, 'associate professor', 'Liberal Arts'); INSERT INTO publications(id, faculty_id, year) VALUES (1, 1, 2020), (2, 1, 2021), (3, 2, 2019);

SELECT COUNT(*) FROM publications JOIN faculty ON publications.id = faculty.id WHERE rank = 'assistant professor' AND college = 'Engineering';


Question: What is the total revenue for organic skincare products in the USA?

CREATE TABLE skincare_sales (id INT, product VARCHAR(50), revenue DECIMAL(10,2), country VARCHAR(50)); INSERT INTO skincare_sales (id, product, revenue, country) VALUES (1, 'Organic Facial Cleanser', 500.00, 'USA');

SELECT SUM(revenue) FROM skincare_sales WHERE product LIKE '%Organic%' AND country = 'USA';


Question: What is the average age of athletes in the 'Soccer' team in the 'athletes' table?

CREATE TABLE athletes (athlete_id INT, name VARCHAR(50), age INT, team VARCHAR(20)); INSERT INTO athletes (athlete_id, name, age, team) VALUES (1, 'Jane Doe', 30, 'Soccer'); INSERT INTO athletes (athlete_id, name, age, team) VALUES (2, 'Jim Brown', 28, 'Basketball'); INSERT INTO athletes (athlete_id, name, age, team) VALUES (3, 'Marie Jones', 26, 'Soccer');

SELECT AVG(age) FROM athletes WHERE team = 'Soccer';


Question: Create a table named 'events' with columns 'name', 'date', and 'attendance'

CREATE TABLE events (name VARCHAR(255), date DATE, attendance INT);


Question: What is the total number of marine life research sites in the Pacific and Atlantic oceans?

CREATE TABLE marine_sites (site_id INT, site_name TEXT, ocean TEXT); INSERT INTO marine_sites (site_id, site_name, ocean) VALUES (1, 'Research Site A', 'Pacific'), (2, 'Research Site B', 'Atlantic'), (3, 'Research Site C', 'Pacific');

SELECT COUNT(*) FROM marine_sites WHERE ocean IN ('Pacific', 'Atlantic');


Question: Show a query using PostgreSQL contrib extension 'postgres_fdw' (example 739).

insert into itrtest values (1, 'test1'), (2, 'test2') returning *;


Question: Generate PostgreSQL SQL for: Who won the South African Grand Prix?

CREATE TABLE table_name_63 (race VARCHAR)

SELECT race AS Winner FROM table_name_63 WHERE race = 'south african grand prix';


Question: What is the total transaction volume for all clients in the Asia-Pacific region, excluding transactions from the banking sector?

CREATE TABLE client (client_id INT, client_name VARCHAR(50), region VARCHAR(50)); INSERT INTO client (client_id, client_name, region) VALUES (1, 'ABC Corp', 'Asia-Pacific'), (2, 'XYZ Bank', 'Americas'); CREATE TABLE transaction (transaction_id INT, client_id INT, sector VARCHAR(50), amount DECIMAL(10,2)); INSERT INTO transaction (transaction_id, client_id, sector, amount) VALUES (1, 1, 'Retail', 5000), (2, 1, 'Real Estate', 7000), (3, 2, 'Banking', 10000), (4, 1, 'Technology', 8000);

SELECT SUM(amount) FROM transaction WHERE client_id IN (SELECT client_id FROM client WHERE region = 'Asia-Pacific') AND sector != 'Banking';


Question: Generate PostgreSQL SQL for: What is the FIS Nordic World Ski Championship years when the winter Olympics took place in 1968?

CREATE TABLE table_name_93 (fis_nordic_world_ski_championships VARCHAR, winter_olympics VARCHAR)

SELECT fis_nordic_world_ski_championships FROM table_name_93 WHERE winter_olympics = 1968;


Question: Generate PostgreSQL SQL for: What engine does driver james hunt have?

CREATE TABLE table_name_94 (engine VARCHAR, driver VARCHAR)

SELECT engine FROM table_name_94 WHERE driver = 'james hunt';


Question: Select all tanks from the military_equipment table

CREATE TABLE military_equipment (equipment_id INT, name VARCHAR(255), type VARCHAR(255), country_of_origin VARCHAR(255), year INT); INSERT INTO military_equipment (equipment_id, name, type, country_of_origin, year) VALUES (1, 'M1 Abrams', 'Tank', 'USA', 1980), (2, 'Leopard 2', 'Tank', 'Germany', 1979), (3, 'F-16', 'Fighter Jet', 'USA', 1976);

SELECT * FROM military_equipment WHERE type = 'Tank';


Question: Generate PostgreSQL SQL for: What's the name of the title for the Maserati A6GCS?

CREATE TABLE table_name_81 (race_title VARCHAR, vehicle VARCHAR)

SELECT race_title FROM table_name_81 WHERE vehicle = 'maserati a6gcs';


Question: Generate PostgreSQL SQL for: Which status accompanies the score 21.5?

CREATE TABLE table_name_94 (status VARCHAR, score VARCHAR)

SELECT status FROM table_name_94 WHERE score = 21.5;


Question: Calculate the total volume of wastewater treated in 'Lima' for each month of the year 2020

CREATE TABLE wastewater_treatment (region VARCHAR(50), date DATE, volume FLOAT); INSERT INTO wastewater_treatment (region, date, volume) VALUES ('Lima', '2020-01-01', 500), ('Lima', '2020-02-01', 550), ('Lima', '2020-03-01', 600);

SELECT date, SUM(volume) FROM wastewater_treatment WHERE region = 'Lima' AND date BETWEEN '2020-01-01' AND '2020-12-31' GROUP BY date;


Question: What is the minimum ocean acidity level ever recorded in the Caribbean Sea, grouped by measurement month?

CREATE TABLE ocean_acidity_records (record_id INTEGER, month INTEGER, acidity_level FLOAT, ocean TEXT);

SELECT month, MIN(acidity_level) FROM ocean_acidity_records WHERE ocean = 'Caribbean Sea' GROUP BY month;


Question: Generate PostgreSQL SQL for: What is John Edwards, when John Kerry is "70%"?

CREATE TABLE table_name_41 (john_edwards VARCHAR, john_kerry VARCHAR)

SELECT john_edwards FROM table_name_41 WHERE john_kerry = '70%';


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

SELECT tableoid::regclass, * FROM salespeople ORDER BY tableoid::regclass::text COLLATE "C", salesperson_id;

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

SELECT count(*) FROM (SELECT tableoid::regclass, * FROM salespeople ORDER BY tableoid::regclass::text COLLATE "C", salesperson_id) AS _sub;


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

ALTER OPERATOR FAMILY alt_opf5 USING btree ADD OPERATOR 1 < (int4, int2), FUNCTION 1 btint42cmp(int4, int2);

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


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

ALTER EXTENSION pgtap ADD FUNCTION check_test( TEXT, BOOLEAN );

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


Question: Determine virtual reality games that have more than 800 players and released in 2019

CREATE TABLE vr_games (game VARCHAR(20), players INT, release_year INT); INSERT INTO vr_games (game, players, release_year) VALUES ('Game1', 1000, 2019); INSERT INTO vr_games (game, players, release_year) VALUES ('Game2', 500, 2018);

SELECT game FROM vr_games WHERE players > 800 AND release_year = 2019;


Question: Generate PostgreSQL SQL for: What is the minimum stations owned since kero-tv?

CREATE TABLE table_1847523_2 (owned_since INTEGER, station VARCHAR)

SELECT MIN(owned_since) FROM table_1847523_2 WHERE station = 'KERO-TV';


Question: Generate PostgreSQL SQL for: What is the average Bronze, when Rank is greater than 6, when Nation is Italy (ITA), and when Total is less than 1?

CREATE TABLE table_name_78 (bronze INTEGER, total VARCHAR, rank VARCHAR, nation VARCHAR)

SELECT AVG(bronze) FROM table_name_78 WHERE rank > 6 AND nation = 'italy (ita)' AND total < 1;


Question: PostgreSQL regression test 'timestamp': Write the SELECT query (example 14).

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

SELECT count(*) FROM (SELECT pg_sleep(0.1)) AS _sub;


Question: What is the total annual production of Terbium from all mines in 2020?

CREATE TABLE mine (id INT, name TEXT, location TEXT, Terbium_annual_production FLOAT, timestamp TIMESTAMP); INSERT INTO mine (id, name, location, Terbium_annual_production, timestamp) VALUES (1, 'Australian Mine', 'Australia', 1500.5, '2020-01-01'), (2, 'Californian Mine', 'USA', 1700.3, '2020-01-01'), (3, 'Brazilian Mine', 'Brazil', 1000.0, '2020-01-01');

SELECT SUM(Terbium_annual_production) FROM mine WHERE EXTRACT(YEAR FROM timestamp) = 2020;


Question: Generate PostgreSQL SQL for: What is the title of the episode that aired on december 12, 1953?

CREATE TABLE table_15824796_3 (title VARCHAR, original_air_date VARCHAR)

SELECT title FROM table_15824796_3 WHERE original_air_date = 'December 12, 1953';


Question: Generate PostgreSQL SQL for: What is the maximum folded value of the team whose stadium is Fraser Field?

CREATE TABLE table_24334261_1 (folded INTEGER, stadium VARCHAR)

SELECT MAX(folded) FROM table_24334261_1 WHERE stadium = 'Fraser Field';


Question: Generate PostgreSQL SQL for: How many numbers were recorded under max speed for 1 USAF space flight and total flights 34?

CREATE TABLE table_221315_3 (max_speed__mph_ VARCHAR, usaf_space_flights VARCHAR, total_flights VARCHAR)

SELECT COUNT(max_speed__mph_) FROM table_221315_3 WHERE usaf_space_flights = 1 AND total_flights = 34;


Question: PostgreSQL regression test 'create_table_like': Write the SELECT query (example 19).

SELECT * FROM test_like_id_2;  -- identity was not copied
CREATE TABLE test_like_id_3 (LIKE test_like_id_1 INCLUDING IDENTITY);

Explanation: Regression test for Create Table Like in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT * FROM test_like_id_2;  -- identity was not copied
CREATE TABLE test_like_id_3 (LIKE test_like_id_1 INCLUDING IDENTITY)) AS _sub;


Question: Identify the total workout time (in minutes) for users in the "East" region who have exercised for over 120 minutes in a session, for each session type, in the last week.

CREATE TABLE user_profile (user_id INT, region VARCHAR(20), PRIMARY KEY (user_id)); CREATE TABLE workout_sessions (session_date DATE, user_id INT, session_type VARCHAR(30), workout_mins INT, PRIMARY KEY (session_date, user_id)); INSERT INTO user_profile (user_id, region) VALUES (1, 'East'), (2, 'North'), (3, 'East'); INSERT INTO workout_sessions (session_date, user_id, session_type, workout_mins) VALUES ('2022-04-01', 1, 'Cardio', 150), ('2022-04-02', 2, 'Strength', 100), ('2022-04-03', 3, 'Cardio', 180), ('2022-04-04', 1, 'Yoga', 90), ('2022-04-04', 3, 'Strength', 130);

SELECT session_type, SUM(workout_mins) as total_workout_mins FROM workout_sessions JOIN user_profile ON workout_sessions.user_id = user_profile.user_id WHERE user_profile.region = 'East' AND workout_mins > 120 AND session_date >= DATE(NOW()) - INTERVAL 7 DAY GROUP BY session_type;


Question: Generate PostgreSQL SQL for: What is the lowest Overall, when Player is "Dan Jennings", and when Round is greater than 9?

CREATE TABLE table_name_23 (overall INTEGER, player VARCHAR, round VARCHAR)

SELECT MIN(overall) FROM table_name_23 WHERE player = 'dan jennings' AND round > 9;


Question: What is the average age of inmates in Illinois prisons who have not participated in restorative justice programs?

CREATE TABLE prisons (id INT, state VARCHAR(2)); INSERT INTO prisons (id, state) VALUES (1, 'Illinois'); CREATE TABLE inmates (id INT, age INT, prison_id INT, restorative_justice BOOLEAN);

SELECT AVG(inmates.age) FROM inmates INNER JOIN prisons ON inmates.prison_id = prisons.id WHERE prisons.state = 'Illinois' AND inmates.restorative_justice = FALSE;


Question: What is the average word count of articles in 'reputable_news' table for each author who is over 40 years old?

CREATE TABLE reputable_news (article_id INT, author_name VARCHAR(50), author_age INT, word_count INT, publication_date DATE);

SELECT author_name, AVG(word_count) FROM reputable_news WHERE author_age > 40 GROUP BY author_name;


Question: What is the difference between the maximum and minimum expedition depths for the 'Deep Sea Divers' organization?

CREATE TABLE expedition (org VARCHAR(20), depth INT); INSERT INTO expedition VALUES ('Ocean Explorer', 2500), ('Ocean Explorer', 3000), ('Sea Discoverers', 2000), ('Marine Investigators', 4000), ('Marine Investigators', 4500), ('Deep Sea Divers', 7000), ('Deep Sea Divers', 6500);

SELECT MAX(depth) - MIN(depth) FROM expedition WHERE org = 'Deep Sea Divers';


Question: Which excavation site has the most total artifacts?

CREATE TABLE excavation_sites (id INT, site_name VARCHAR(255)); CREATE TABLE artifacts (id INT, excavation_site_id INT, artifact_type VARCHAR(255));

SELECT e.site_name, COUNT(a.id) AS total_artifacts FROM excavation_sites e JOIN artifacts a ON e.id = a.excavation_site_id GROUP BY e.site_name ORDER BY total_artifacts DESC LIMIT 1;


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

INSERT INTO caster (text)          VALUES ('04:05:06'::time);

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


Question: Create a table to store product safety records

CREATE TABLE product_safety (safety_record_id INT PRIMARY KEY, product_id INT, safety_test_date DATE, safety_result TEXT);


Question: Generate PostgreSQL SQL for: What date has 79-48 as the record?

CREATE TABLE table_name_47 (date VARCHAR, record VARCHAR)

SELECT date FROM table_name_47 WHERE record = '79-48';


Question: Generate PostgreSQL SQL for: What is the total for 3rd place on season 9?

CREATE TABLE table_name_41 (total VARCHAR, place VARCHAR, season VARCHAR)

SELECT total FROM table_name_41 WHERE place = '3rd' AND season = '9';


Question: Generate PostgreSQL SQL for: Which GDP per capita (US$) (2004) has a Literacy (2003) of 90%, and an Area (km²) of 1247689.5?

CREATE TABLE table_name_53 (gdp_per_capita__us INTEGER, literacy__2003_ VARCHAR, area__km²_ VARCHAR)

SELECT AVG(gdp_per_capita__us) AS $___2004_ FROM table_name_53 WHERE literacy__2003_ = '90%' AND area__km²_ = 1247689.5;


Question: Generate PostgreSQL SQL for: What pick was the player from Apopka, FL in the 2002 MLB draft

CREATE TABLE table_11677100_8 (mlb_draft VARCHAR, hometown VARCHAR)

SELECT mlb_draft FROM table_11677100_8 WHERE hometown = 'Apopka, FL';


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

SELECT xmlserialize(DOCUMENT '<foo><bar><val x="y">42</val><val x="y">text node<val>73</val></val></bar></foo>' AS text INDENT);

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

SELECT count(*) FROM (SELECT xmlserialize(DOCUMENT '<foo><bar><val x="y">42</val><val x="y">text node<val>73</val></val></bar></foo>' AS text INDENT)) AS _sub;


Question: What is the maximum number of workers on a single project in the state of New York?

CREATE TABLE Projects (project_id INT, state VARCHAR(255), num_workers INT); INSERT INTO Projects (project_id, state, num_workers) VALUES (1, 'New York', 10), (2, 'New York', 15);

SELECT MAX(num_workers) FROM Projects WHERE state = 'New York';


Question: Generate PostgreSQL SQL for: What was the score for United States when the player was Mike Reid and the To par was e?

CREATE TABLE table_name_30 (score VARCHAR, player VARCHAR, country VARCHAR, to_par VARCHAR)

SELECT score FROM table_name_30 WHERE country = 'united states' AND to_par = 'e' AND player = 'mike reid';


Question: Generate PostgreSQL SQL for: Find all the male members of club "Hopkins Student Enterprises". Show the first name and last name.

CREATE TABLE club (clubid VARCHAR, clubname VARCHAR); CREATE TABLE student (fname VARCHAR, lname VARCHAR, stuid VARCHAR, sex VARCHAR); CREATE TABLE member_of_club (clubid VARCHAR, stuid VARCHAR)

SELECT t3.fname, t3.lname FROM club AS t1 JOIN member_of_club AS t2 ON t1.clubid = t2.clubid JOIN student AS t3 ON t2.stuid = t3.stuid WHERE t1.clubname = 'Hopkins Student Enterprises' AND t3.sex = 'M';


Question: What is the total number of volunteers and total number of hours contributed for the entire organization?

CREATE TABLE organizations (org_id INT, org_name TEXT);CREATE TABLE volunteers (vol_id INT, org_id INT, hours_contributed INT, volunteer_name TEXT); INSERT INTO organizations VALUES (1, 'Habitat for Humanity'); INSERT INTO organizations VALUES (2, 'Red Cross'); INSERT INTO volunteers VALUES (1, 1, 10, 'John Doe'); INSERT INTO volunteers VALUES (2, 1, 15, 'Jane Smith'); INSERT INTO volunteers VALUES (3, 2, 20, 'Mary Johnson');

SELECT organizations.org_name, COUNT(DISTINCT volunteers.vol_id) AS total_volunteers, SUM(volunteers.hours_contributed) AS total_hours FROM organizations INNER JOIN volunteers ON organizations.org_id = volunteers.org_id GROUP BY organizations.org_name;


Question: Show a query using PostgreSQL contrib extension 'unaccent' (example 16).

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


Question: What is the distribution of AI safety principles across different regions?

CREATE TABLE ai_safety_principles (principle_name TEXT, region TEXT); INSERT INTO ai_safety_principles (principle_name, region) VALUES ('Beneficence', 'Asia'), ('Nonmaleficence', 'Europe'), ('Autonomy', 'Americas'), ('Justice', 'Africa');

SELECT principle_name, region, COUNT(*) FROM ai_safety_principles GROUP BY principle_name, region;


Question: Generate PostgreSQL SQL for: Which country has is Len Mattiace in T10 place?

CREATE TABLE table_name_54 (country VARCHAR, place VARCHAR, player VARCHAR)

SELECT country FROM table_name_54 WHERE place = 't10' AND player = 'len mattiace';


Question: What is the average cost of renewable energy infrastructure for projects in the 'renewable_energy' schema, grouped by infrastructure type?

CREATE TABLE renewable_energy (project_id INT, infrastructure_type TEXT, cost FLOAT); INSERT INTO renewable_energy (project_id, infrastructure_type, cost) VALUES (1, 'solar farm', 500000.0), (1, 'wind farm', 700000.0), (2, 'geothermal plant', 900000.0), (2, 'hydroelectric dam', 1000000.0);

SELECT infrastructure_type, AVG(cost) FROM renewable_energy WHERE project_id IN (SELECT project_id FROM projects WHERE schema_name = 'renewable_energy') GROUP BY infrastructure_type;


Question: Generate PostgreSQL SQL for: Who was the Centerfold model in the issue in which the Interview subject was José Napoleón Duarte?

CREATE TABLE table_name_96 (centerfold_model VARCHAR, interview_subject VARCHAR)

SELECT centerfold_model FROM table_name_96 WHERE interview_subject = 'josé napoleón duarte';


Question: What is the total number of labor rights violations for unions in the manufacturing sector, grouped by union name?

CREATE TABLE union_manufacturing (union_id INT, union_name TEXT, sector TEXT, violations INT); INSERT INTO union_manufacturing (union_id, union_name, sector, violations) VALUES (1, 'Union P', 'Manufacturing', 30), (2, 'Union Q', 'Manufacturing', 40), (3, 'Union R', 'Retail', 20);

SELECT union_name, SUM(violations) FROM union_manufacturing WHERE sector = 'Manufacturing' GROUP BY union_name;


Question: Generate PostgreSQL SQL for: What 2009 has statistics by surface in 2012?

SELECT 2009 FROM table_name_66 WHERE 2012 = 'statistics by surface';


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

select jsonb_path_query('[]', 'strict $.double()');

SELECT count(*) FROM (select jsonb_path_query('[]', 'strict $.double()')) AS _sub;


Question: Which causes received the highest donation amounts in a specific region?

CREATE TABLE Donations (DonationID INT, Cause VARCHAR(50), Amount DECIMAL(10,2), Region VARCHAR(50)); INSERT INTO Donations (DonationID, Cause, Amount, Region) VALUES (1, 'Education', 2000, 'Africa'), (2, 'Health', 3000, 'Asia'), (3, 'Education', 1000, 'Africa'), (4, 'Environment', 4000, 'Europe');

SELECT Cause, SUM(Amount) as TotalDonation FROM Donations WHERE Region = 'Asia' GROUP BY Cause ORDER BY TotalDonation DESC;


Question: Find the total number of smart contracts associated with digital assets having a value greater than 80?

CREATE TABLE digital_assets (asset_id INT, asset_name VARCHAR(50), value DECIMAL(10,2)); INSERT INTO digital_assets (asset_id, asset_name, value) VALUES (1, 'Asset1', 50.5), (2, 'Asset2', 100.2), (3, 'Asset3', 75.0); CREATE TABLE smart_contracts (contract_id INT, asset_id INT, contract_name VARCHAR(50)); INSERT INTO smart_contracts (contract_id, asset_id, contract_name) VALUES (101, 1, 'Contract1'), (102, 2, 'Contract2'), (103, 3, 'Contract3');

SELECT COUNT(*) FROM smart_contracts INNER JOIN digital_assets ON smart_contracts.asset_id = digital_assets.asset_id WHERE digital_assets.value > 80;


Question: Generate PostgreSQL SQL for: Which Country has a Score of 69-66=135?

CREATE TABLE table_name_76 (country VARCHAR, score VARCHAR)

SELECT country FROM table_name_76 WHERE score = 69 - 66 = 135;


Question: What is the maximum salary of unionized workers in the 'Retail' industry?

CREATE TABLE Workers (EmployeeID INT, Industry VARCHAR(20), UnionMember BOOLEAN, Salary FLOAT); INSERT INTO Workers (EmployeeID, Industry, UnionMember, Salary) VALUES (1, 'Retail', true, 35000.0), (2, 'Retail', true, 36000.0), (3, 'Retail', false, 33000.0);

SELECT MAX(Salary) FROM Workers WHERE Industry = 'Retail' AND UnionMember = true;


Question: What is the maximum depth of any marine protected area in the Indian region?

CREATE TABLE marine_protected_areas (name VARCHAR(255), location VARCHAR(255), depth FLOAT); INSERT INTO marine_protected_areas (name, location, depth) VALUES ('MPA 1', 'Indian', 150.7); INSERT INTO marine_protected_areas (name, location, depth) VALUES ('MPA 2', 'Atlantic', 200.3);

SELECT MAX(depth) FROM marine_protected_areas WHERE location = 'Indian';


Question: Write the DDL statement from PostgreSQL regression test 'alter_table' (example 348).

Explanation: DDL from PostgreSQL core regression test for Alter Table.


Question: List all arctic research stations in Russia and their respective altitudes.

CREATE TABLE ResearchStations (name TEXT, country TEXT, altitude INTEGER);

SELECT name, altitude FROM ResearchStations WHERE country = 'Russia';


Question: Generate PostgreSQL SQL for: What was the Opponent before Week 11 with an Attendance of 63,571?

CREATE TABLE table_name_94 (opponent VARCHAR, week VARCHAR, attendance VARCHAR)

SELECT opponent FROM table_name_94 WHERE week < 11 AND attendance = '63,571';


Question: How many properties are there in the 'affordable_housing' table for each city?

CREATE TABLE affordable_housing (id INT, address VARCHAR(255), city VARCHAR(255), state VARCHAR(255)); INSERT INTO affordable_housing (id, address, city, state) VALUES (1, '789 Pine St', 'Seattle', 'WA'), (2, '321 Cedar Rd', 'Seattle', 'WA'), (3, '543 Elm Ave', 'Portland', 'OR');

SELECT city, COUNT(*) FROM affordable_housing GROUP BY city;


Question: Generate PostgreSQL SQL for: What is the 2012 club for the Billy Miller Category:Articles with hcards (Name)?

CREATE TABLE table_name_55 (name VARCHAR)

SELECT 2012 AS _club FROM table_name_55 WHERE name = 'billy miller category:articles with hcards';


Question: How many alternative dispute resolution methods were used for civil cases in each county?

CREATE TABLE civil_cases (case_id INT, case_county VARCHAR(20)); CREATE TABLE dispute_resolution (case_id INT, resolution_type VARCHAR(20));

SELECT cc.case_county, COUNT(dr.resolution_type) FROM civil_cases cc INNER JOIN dispute_resolution dr ON cc.case_id = dr.case_id GROUP BY cc.case_county;


Question: What is the total mass of space debris grouped by the debris type in the space_debris table?

CREATE TABLE space_debris (debris_type VARCHAR(30), mass FLOAT, debris_id INT); INSERT INTO space_debris VALUES ('Fuel Tank', 1500.20, 1), ('Upper Stage', 3000.50, 2), ('Payload Adapter', 700.30, 3), ('Instrument', 100.10, 4);

SELECT debris_type, SUM(mass) OVER (PARTITION BY debris_type) FROM space_debris;


Question: Generate PostgreSQL SQL for: Can you tell me the Opponent that has the Date of october 11, 1953?

CREATE TABLE table_name_62 (opponent VARCHAR, date VARCHAR)

SELECT opponent FROM table_name_62 WHERE date = 'october 11, 1953';


Question: Generate PostgreSQL SQL for: When was the game played where St Kilda was the home team?

CREATE TABLE table_name_4 (date VARCHAR, home_team VARCHAR)

SELECT date FROM table_name_4 WHERE home_team = 'st kilda';


Question: Generate PostgreSQL SQL for: What final score was there on October 8, 2006?

CREATE TABLE table_name_96 (score_in_the_final VARCHAR, date VARCHAR)

SELECT score_in_the_final FROM table_name_96 WHERE date = 'october 8, 2006';


Question: What is the average transaction amount for customers from the United States and Canada?

CREATE TABLE transactions (id INT, customer_id INT, amount DECIMAL(10,2), country VARCHAR(50)); INSERT INTO transactions (id, customer_id, amount, country) VALUES (1, 101, 500.00, 'USA'), (2, 102, 350.00, 'Canada'), (3, 103, 700.00, 'USA'), (4, 104, 600.00, 'Canada');

SELECT AVG(amount) FROM transactions WHERE country IN ('USA', 'Canada');


Question: Delete the record for the sale of 'Artillery Systems' to 'Asia' by 'Red Shield LLC' if the sale quantity is less than 50.

CREATE TABLE RedShieldSales(id INT, contractor VARCHAR(255), region VARCHAR(255), equipment VARCHAR(255), quantity INT);INSERT INTO RedShieldSales(id, contractor, region, equipment, quantity) VALUES (1, 'Red Shield LLC', 'Asia', 'Artillery Systems', 45);

DELETE FROM RedShieldSales WHERE contractor = 'Red Shield LLC' AND region = 'Asia' AND equipment = 'Artillery Systems' AND quantity < 50;


Question: Generate PostgreSQL SQL for: What is the Score of the Pittsburgh Home game on March 3 with 61 Points?

CREATE TABLE table_name_18 (score VARCHAR, date VARCHAR, home VARCHAR, points VARCHAR)

SELECT score FROM table_name_18 WHERE home = 'pittsburgh' AND points = 61 AND date = 'march 3';


Question: Generate PostgreSQL SQL for: Which Leading Scorer has an Opponent of @ indiana?

CREATE TABLE table_name_10 (Leading VARCHAR, opponent VARCHAR)

SELECT Leading AS scorer FROM table_name_10 WHERE opponent = '@ indiana';


Question: What is the total number of medical supply distributions in Haiti?

CREATE TABLE medical_supplies (id INT, location VARCHAR(255), distribution_date DATE); INSERT INTO medical_supplies (id, location, distribution_date) VALUES (1, 'Haiti', '2022-01-01'), (2, 'Syria', '2022-01-02'), (3, 'Haiti', '2022-01-03');

SELECT COUNT(*) FROM medical_supplies WHERE location = 'Haiti';


Question: What is the total labor cost for all building projects in Florida?

CREATE TABLE labor_costs (id INT, project_state TEXT, project_type TEXT, labor_cost DECIMAL(10,2)); INSERT INTO labor_costs (id, project_state, project_type, labor_cost) VALUES (1, 'Florida', 'Residential', 15000.00), (2, 'Florida', 'Commercial', 25000.00), (3, 'California', 'Sustainable', 12000.00);

SELECT SUM(labor_cost) FROM labor_costs WHERE project_state = 'Florida';


Question: What is the maximum number of therapy sessions attended by a patient in Oregon?

CREATE TABLE therapy_attendance (patient_id INT, sessions_attended INT, location VARCHAR(50)); INSERT INTO therapy_attendance (patient_id, sessions_attended, location) VALUES (1, 12, 'Oregon'), (2, 10, 'Washington'), (3, 15, 'Oregon'), (4, 8, 'California'), (5, 20, 'Oregon');

SELECT location, MAX(sessions_attended) FROM therapy_attendance GROUP BY location;


Question: What is the total revenue generated from concert ticket sales for artists from Australia?

CREATE TABLE artists (artist_id INT, artist_name VARCHAR(255), country VARCHAR(255)); CREATE TABLE concerts (concert_id INT, artist_id INT, concert_name VARCHAR(255), country VARCHAR(255), revenue INT); INSERT INTO artists (artist_id, artist_name, country) VALUES (101, 'Taylor Swift', 'USA'), (102, 'BTS', 'South Korea'), (103, 'Olivia Newton-John', 'Australia'); INSERT INTO concerts (concert_id, artist_id, concert_name, country, revenue) VALUES (1, 101, 'Pop Music Festival', 'UK', 500000), (2, 102, 'K-Pop Music Festival', 'Japan', 700000), (3, 103, 'Country Music Festival', 'Australia', 600000), (4, 101, 'Rock Music Festival', 'USA', 800000);

SELECT SUM(revenue) FROM concerts JOIN artists ON concerts.artist_id = artists.artist_id WHERE artists.country = 'Australia';


Question: How many new male members joined in Q1 2022 from the US?

CREATE TABLE members (member_id INT, gender VARCHAR(10), join_date DATE, country VARCHAR(50)); INSERT INTO members (member_id, gender, join_date, country) VALUES (1, 'Female', '2021-01-15', 'Canada'), (2, 'Male', '2022-03-28', 'USA');

SELECT COUNT(*) FROM members WHERE gender = 'Male' AND join_date >= '2022-01-01' AND join_date < '2022-04-01' AND country = 'USA';


Question: Generate PostgreSQL SQL for: What is the value in 2009 corresponding to Career Statistics in 2003?

SELECT 2009 FROM table_name_96 WHERE 2003 = 'career statistics';


Question: Generate PostgreSQL SQL for: What is Home, when Score is 103-93?

CREATE TABLE table_name_95 (home VARCHAR, score VARCHAR)

SELECT home FROM table_name_95 WHERE score = '103-93';


Question: Who are the female actors with more than 10 movies acted?

CREATE TABLE actors (name VARCHAR(255), gender VARCHAR(10), movies INTEGER); INSERT INTO actors (name, gender, movies) VALUES ('ActorA', 'Female', 12), ('ActorB', 'Male', 15), ('ActorC', 'Female', 8), ('ActorD', 'Female', 20), ('ActorE', 'Male', 18), ('ActorF', 'Male', 10), ('ActorG', 'Female', 11);

SELECT name FROM actors WHERE gender = 'Female' AND movies > 10;


Question: What is the total quantity of 'Dress' type garments produced by each manufacturer in the 'Spring 2022' season?

CREATE TABLE Manufacturers (ManufacturerID INT, ManufacturerName VARCHAR(50)); INSERT INTO Manufacturers (ManufacturerID, ManufacturerName) VALUES (1, 'Manufacturer A'), (2, 'Manufacturer B'); CREATE TABLE Garments (GarmentID INT, GarmentType VARCHAR(20), ManufacturerID INT, ProductionDate DATE); INSERT INTO Garments (GarmentID, GarmentType, ManufacturerID, ProductionDate) VALUES (1, 'Dress', 1, '2022-03-15'), (2, 'Top', 1, '2022-03-16'), (3, 'Dress', 2, '2022-04-01');

SELECT M.ManufacturerName, SUM(CASE WHEN G.GarmentType = 'Dress' THEN 1 ELSE 0 END) as TotalDresses FROM Manufacturers M JOIN Garments G ON M.ManufacturerID = G.ManufacturerID WHERE G.ProductionDate BETWEEN '2022-03-01' AND '2022-06-30' GROUP BY M.ManufacturerName;


Question: Count the number of users who prefer each brand, for products that do not include water as an ingredient, partitioned by preferred brand.

CREATE TABLE ConsumerPreferences (UserID INT, PreferredBrand VARCHAR(50), PreferredProduct VARCHAR(50), PreferredIngredients VARCHAR(255)); INSERT INTO ConsumerPreferences (UserID, PreferredBrand, PreferredProduct, PreferredIngredients) VALUES (1, 'Origins', 'Ginzing Energy-Boosting Gel Moisturizer', 'Water, Glycerin'); INSERT INTO ConsumerPreferences (UserID, PreferredBrand, PreferredProduct, PreferredIngredients) VALUES (2, 'Lush', 'Tea Totaler Facial Oil', 'Water, Glycerin, Rosehip Oil');

SELECT PreferredBrand, PreferredProduct, PreferredIngredients, COUNT(*) OVER (PARTITION BY PreferredBrand) as 'BrandPopularity' FROM ConsumerPreferences WHERE PreferredIngredients NOT LIKE '%Water%';


Question: What is the military spending by country and year?

CREATE TABLE military_spending (id INT, country VARCHAR(255), amount FLOAT, year INT); INSERT INTO military_spending (id, country, amount, year) VALUES (1, 'Brazil', 25.6, 2018); INSERT INTO military_spending (id, country, amount, year) VALUES (2, 'South Africa', 30.8, 2019);

SELECT country, year, SUM(amount) as total_spending FROM military_spending GROUP BY country, year;


Question: Identify the names and locations of all marine protected areas (MPAs) in the Arctic region.

CREATE TABLE MARINE_PROTECTED_AREAS (NAME TEXT, LOCATION TEXT, REGION TEXT); INSERT INTO MARINE_PROTECTED_AREAS (NAME, LOCATION, REGION) VALUES ('Arctic National Wildlife Refuge', 'Alaska, USA', 'Arctic'), ('Norwegian Arctic Archipelago', 'Svalbard, Norway', 'Arctic'), ('Gulf of Bothnia National Park', 'Sweden', 'Arctic'), ('Franz Josef Land Nature Reserve', 'Russia', 'Arctic'), ('Arctic Bay Wildlife Sanctuary', 'Canada', 'Arctic');

SELECT NAME, LOCATION FROM MARINE_PROTECTED_AREAS WHERE REGION = 'Arctic';


Question: What is the total number of marine species in the Atlantic Ocean that are affected by maritime safety issues?

CREATE TABLE marine_species (id INT, name TEXT, ocean TEXT, affected_by_safety_issues BOOLEAN); INSERT INTO marine_species (id, name, ocean, affected_by_safety_issues) VALUES (1, 'Krill', 'Southern', TRUE), (2, 'Blue Whale', 'Atlantic', FALSE), (3, 'Penguin', 'Southern', TRUE), (4, 'Squid', 'Atlantic', TRUE);

SELECT COUNT(*) FROM marine_species WHERE ocean = 'Atlantic' AND affected_by_safety_issues = TRUE;


Question: Generate PostgreSQL SQL for: What is Fred Stolle's final year of competing in a championship?

CREATE TABLE table_2201724_1 (year INTEGER)


Question: Generate PostgreSQL SQL for: What are the dates of birth of entrepreneurs with investor "Simon Woodroffe" or "Peter Jones"?

CREATE TABLE entrepreneur (People_ID VARCHAR, Investor VARCHAR); CREATE TABLE people (Date_of_Birth VARCHAR, People_ID VARCHAR)

SELECT T2.Date_of_Birth FROM entrepreneur AS T1 JOIN people AS T2 ON T1.People_ID = T2.People_ID WHERE T1.Investor = 'Simon Woodroffe' OR T1.Investor = 'Peter Jones';


Question: Generate PostgreSQL SQL for: Who is the visitor with a 14-10 record?

CREATE TABLE table_name_71 (visitor VARCHAR, record VARCHAR)

SELECT visitor FROM table_name_71 WHERE record = '14-10';


Question: Insert new records into the fashion_trends table with the latest trending garment types in the African market.

CREATE TABLE fashion_trends (id INT, garment_type VARCHAR(255), region VARCHAR(255), popularity INT); INSERT INTO fashion_trends (id, garment_type, region, popularity) VALUES (1, 'Ankara Dress', 'Africa', 90), (2, 'Kente Cloth Pants', 'Africa', 80), (3, 'Dashiki Shirt', 'Africa', 70);

INSERT INTO fashion_trends (id, garment_type, region, popularity) VALUES (4, 'Boubou', 'Africa', 85), (5, 'Kufi Hat', 'Africa', 95), (6, 'Fila Jacket', 'Africa', 88);


Question: Generate PostgreSQL SQL for: Name the Points which has a Team of sportivo luqueño, and Wins larger than 1?

CREATE TABLE table_name_41 (points INTEGER, team VARCHAR, wins VARCHAR)

SELECT MIN(points) FROM table_name_41 WHERE team = 'sportivo luqueño' AND wins > 1;


Question: Show a query using PostgreSQL contrib extension 'postgres_fdw' (example 187).

SELECT t1.c1, t2.c2, t3.c3 FROM ft2 t1 FULL JOIN ft2 t2 ON (t1.c1 = t2.c1) RIGHT JOIN ft4 t3 ON (t2.c1 = t3.c1) OFFSET 10 LIMIT 10;

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


Question: Display the number of unique ports visited by vessels, grouped by flag state.

CREATE TABLE FLAG_STATES (ID INT, NAME VARCHAR(50), CONTINENT VARCHAR(50)); INSERT INTO FLAG_STATES VALUES (1, 'Panama', 'Americas'); INSERT INTO FLAG_STATES VALUES (2, 'Singapore', 'Asia');

SELECT F.NAME AS FLAG_STATE, COUNT(DISTINCT P.PORT) AS PORT_COUNT, RANK() OVER(ORDER BY COUNT(DISTINCT P.PORT) DESC) AS RANK FROM PORT_CALLS PC JOIN VESSELS V ON PC.VESSEL_ID = V.ID JOIN FLAG_STATES F ON V.FLAG_STATE = F.NAME GROUP BY F.ID, F.NAME;


Question: Generate PostgreSQL SQL for: Which team has a League from of ontario hockey league, and a Player of tony dehart?

CREATE TABLE table_name_22 (nhl_team VARCHAR, league_from VARCHAR, player VARCHAR)

SELECT nhl_team FROM table_name_22 WHERE league_from = 'ontario hockey league' AND player = 'tony dehart';


Question: What is the average age of patients who have received psychotherapy in California?

CREATE TABLE patients (id INT, name TEXT, age INT, state TEXT);CREATE TABLE treatments (id INT, patient_id INT, therapy TEXT);INSERT INTO patients (id, name, age, state) VALUES (1, 'John Doe', 45, 'California');INSERT INTO treatments (id, patient_id, therapy) VALUES (1, 1, 'Psychotherapy');

SELECT AVG(patients.age) FROM patients INNER JOIN treatments ON patients.id = treatments.patient_id WHERE patients.state = 'California' AND treatments.therapy = 'Psychotherapy';


Question: What is the total number of marine species observed in the Arctic region?

CREATE TABLE marine_species (name varchar(255), region varchar(255), observations int); INSERT INTO marine_species (name, region, observations) VALUES ('Polar Bear', 'Arctic', 2500), ('Walrus', 'Arctic', 1200), ('Arctic Fox', 'Arctic', 800);

SELECT SUM(observations) FROM marine_species WHERE region = 'Arctic';


Question: Generate PostgreSQL SQL for: What is the round of 54 holes in which Phil Mickelson was the runner-up?

CREATE TABLE table_name_33 (runner_s__up VARCHAR)

SELECT 54 AS _holes FROM table_name_33 WHERE runner_s__up = 'phil mickelson';


Question: PostgreSQL regression test 'tstypes': Write the SELECT query (example 27).

SELECT * FROM pg_input_error_info('a <100000> b', 'tsquery');

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

SELECT count(*) FROM (SELECT * FROM pg_input_error_info('a <100000> b', 'tsquery')) AS _sub;


Question: Generate PostgreSQL SQL for: What is the lowest 2009 value with a 2010 value of 141 and a 1985 value bigger than 165?

SELECT MIN(2009) FROM table_name_18 WHERE 2010 = 141 AND 1985 > 165;


Question: How many heritage sites were established before 1900?

CREATE TABLE Heritage_Sites (id INT, site_name VARCHAR(100), country VARCHAR(50), year_established INT, UNIQUE (id));

SELECT COUNT(*) FROM Heritage_Sites WHERE year_established < 1900;


Question: pgTAP test for Functap (assertion 209).

-- Test diagnostics
SELECT * FROM check_test(
    is_normal_function( 'zippo' ),
    false,
    'is_normal_function(nofunc)',
    'Function zippo() should be a normal function',
    '    Function zippo() does not exist'
);

Explanation: SQL assertion from pgTAP test suite for Functap.


Question: Generate PostgreSQL SQL for: Find the name and address of the customers who have both New and Pending orders.

CREATE TABLE customers (customer_name VARCHAR, customer_address VARCHAR, customer_id VARCHAR); CREATE TABLE customer_orders (customer_id VARCHAR, order_status_code VARCHAR)

SELECT T1.customer_name, T1.customer_address FROM customers AS T1 JOIN customer_orders AS T2 ON T1.customer_id = T2.customer_id WHERE T2.order_status_code = 'New' INTERSECT SELECT T1.customer_name, T1.customer_address FROM customers AS T1 JOIN customer_orders AS T2 ON T1.customer_id = T2.customer_id WHERE T2.order_status_code = 'Pending';


Question: Update the renewable energy source for 'ProjectD' in the US to 'Geothermal'.

CREATE TABLE green_buildings (project_name VARCHAR(50), country VARCHAR(50), renewable_energy_source VARCHAR(50)); INSERT INTO green_buildings (project_name, country, renewable_energy_source) VALUES ('ProjectD', 'US', 'Solar');

UPDATE green_buildings SET renewable_energy_source = 'Geothermal' WHERE project_name = 'ProjectD' AND country = 'US';


Question: Generate PostgreSQL SQL for: What is the average earnings of poker players with height higher than 200?

CREATE TABLE people (People_ID VARCHAR, Height INTEGER); CREATE TABLE poker_player (Earnings INTEGER, People_ID VARCHAR)

SELECT AVG(T2.Earnings) FROM people AS T1 JOIN poker_player AS T2 ON T1.People_ID = T2.People_ID WHERE T1.Height > 200;


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

create table idxpart (a int, b int, c text) partition by range (a);

Explanation: DDL from PostgreSQL core regression test for Indexing.


Question: Write the DDL statement from PostgreSQL regression test 'select_views' (example 16).

CREATE VIEW my_credit_card_usage_normal AS
       SELECT * FROM my_credit_card_secure l NATURAL JOIN credit_usage r;

Explanation: DDL from PostgreSQL core regression test for Select Views.


Question: Generate PostgreSQL SQL for: Which goals/game ratio has fewer than 201 goals and fewer than 170 appearances?

CREATE TABLE table_name_29 (goals VARCHAR, Game VARCHAR, appearances VARCHAR)

SELECT goals / Game AS Ratio FROM table_name_29 WHERE goals < 201 AND appearances < 170;


Question: Generate PostgreSQL SQL for: Name the Programming which has an Aspect of 4:3, and a PSIP Short Name of ibc-tv?

CREATE TABLE table_name_18 (programming VARCHAR, aspect VARCHAR, psip_short_name VARCHAR)

SELECT programming FROM table_name_18 WHERE aspect = '4:3' AND psip_short_name = 'ibc-tv';


Question: What is the average number of food safety violations per inspection for each location?

CREATE TABLE food_safety_inspections (location VARCHAR(255), inspection_date DATE, violations INT); INSERT INTO food_safety_inspections (location, inspection_date, violations) VALUES ('Location A', '2022-01-01', 3), ('Location B', '2022-01-02', 5), ('Location A', '2022-01-03', 2), ('Location C', '2022-01-04', 4), ('Location A', '2022-01-05', 1);

SELECT location, AVG(violations) as average_violations FROM food_safety_inspections GROUP BY location;


Question: Generate PostgreSQL SQL for: What hometown was FR Year, and ha Brown's Gymnastics club?

CREATE TABLE table_name_20 (hometown VARCHAR, year VARCHAR, club VARCHAR)

SELECT hometown FROM table_name_20 WHERE year = 'fr' AND club = 'brown's gymnastics';


Question: Show a SQL definition from the zombodb project (zombodb--3000.0.3--3000.0.4, item 15).

CREATE OR REPLACE FUNCTION zdb.t_test_agg(aggregate_name text, fields text[], t_type zdb.ttesttype) RETURNS jsonb AS 'MODULE_PATHNAME', 't_test_fields_agg_wrapper' IMMUTABLE LANGUAGE c PARALLEL SAFE STRICT;

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


Question: Generate PostgreSQL SQL for: Which type of surface do Amer Delic Robert Kendrick's opponents have?

CREATE TABLE table_name_53 (surface VARCHAR, opponents VARCHAR)

SELECT surface FROM table_name_53 WHERE opponents = 'amer delic robert kendrick';


Question: What is the total waste generated by each mining operation, categorized by waste type?

CREATE TABLE mining_operations (operation_id INT, operation_name VARCHAR(50)); CREATE TABLE waste_generated (operation_id INT, waste_type VARCHAR(50), quantity_generated INT); INSERT INTO mining_operations (operation_id, operation_name) VALUES (1, 'Operation A'), (2, 'Operation B'), (3, 'Operation C'); INSERT INTO waste_generated (operation_id, waste_type, quantity_generated) VALUES (1, 'Tailings', 1000), (1, 'Rock', 2000), (2, 'Tailings', 1500), (2, 'Rock', 500), (3, 'Tailings', 2500);

SELECT mining_operations.operation_name, waste_generated.waste_type, SUM(waste_generated.quantity_generated) AS total_waste_generated FROM mining_operations INNER JOIN waste_generated ON mining_operations.operation_id = waste_generated.operation_id GROUP BY mining_operations.operation_name, waste_generated.waste_type;


Question: Generate PostgreSQL SQL for: What was the position of the player from the college of Nevada with a round over 5?

CREATE TABLE table_name_23 (position VARCHAR, round VARCHAR, college VARCHAR)

SELECT position FROM table_name_23 WHERE round > 5 AND college = 'nevada';


Question: PostgreSQL regression test 'aggregates': Write the SELECT query (example 286).

select aggfns(distinct a,a,c order by c using ~<~)
  from (values (1,3,'foo'),(0,null,null),(2,2,'bar'),(3,1,'baz')) v(a,b,c),
       generate_series(1,2) i;

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

SELECT count(*) FROM (select aggfns(distinct a,a,c order by c using ~<~)
  from (values (1,3,'foo'),(0,null,null),(2,2,'bar'),(3,1,'baz')) v(a,b,c),
       generate_series(1,2) i) AS _sub;


Question: Insert a new record into the 'regulatory_frameworks' table for the country 'Jamaica' and framework 'DLT Regulation'

CREATE TABLE regulatory_frameworks (framework_id INT PRIMARY KEY, country VARCHAR(100), framework VARCHAR(100));

INSERT INTO regulatory_frameworks (country, framework) VALUES ('Jamaica', 'DLT Regulation');


Question: Insert a new well with specific details.

CREATE TABLE wells (well_id INT, well_type VARCHAR(10), location VARCHAR(20), production_rate FLOAT);

INSERT INTO wells (well_id, well_type, location, production_rate) VALUES (5, 'onshore', 'Brazil', 1500);


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

CREATE INDEX hash_idx ON hash_temp_heap USING hash (x);

Explanation: DDL from PostgreSQL core regression test for Hash Index.


Question: Generate PostgreSQL SQL for: Frank Nobilo plays for what country?

CREATE TABLE table_name_43 (country VARCHAR, player VARCHAR)

SELECT country FROM table_name_43 WHERE player = 'frank nobilo';


Question: What is the total number of teachers who have participated in lifelong learning programs, and what are the average and total costs?

CREATE TABLE teacher_ll (teacher_id INT, ll_program_id INT, PRIMARY KEY(teacher_id, ll_program_id)); CREATE TABLE ll_program (ll_program_id INT, ll_program_name VARCHAR(50), num_teachers INT, avg_cost DECIMAL(5,2), total_cost DECIMAL(10,2), PRIMARY KEY(ll_program_id)); INSERT INTO teacher_ll (teacher_id, ll_program_id) VALUES (1, 1), (1, 2), (2, 1), (3, 2); INSERT INTO ll_program (ll_program_id, ll_program_name, num_teachers, avg_cost, total_cost) VALUES (1, 'Coding Bootcamp', 50, 1500, 75000), (2, 'Data Science Specialization', 30, 2000, 60000);

SELECT COUNT(DISTINCT teacher_id) as total_teachers, AVG(avg_cost) as avg_ll_cost, SUM(total_cost) as total_ll_cost FROM teacher_ll tl INNER JOIN ll_program lp ON tl.ll_program_id = lp.ll_program_id;


Question: Generate PostgreSQL SQL for: Which is the lowest played with 28-10 points and goals higher than 29?

CREATE TABLE table_name_97 (played INTEGER, points VARCHAR, goals_for VARCHAR)

SELECT MIN(played) FROM table_name_97 WHERE points = '28-10' AND goals_for > 29;


Question: Write the DDL statement from PostgreSQL regression test 'rowsecurity' (example 547).

CREATE VIEW rls_view WITH (security_invoker) AS
    SELECT * FROM z1 WHERE f_leak(b);

Explanation: DDL from PostgreSQL core regression test for Rowsecurity.


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

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


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

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

SELECT count(*) FROM (select int4range(1, 3)::int4multirange) AS _sub;


Question: List all marine species with a conservation status of 'Critically Endangered'?

CREATE TABLE species (id INT, name VARCHAR(255), conservation_status VARCHAR(255)); INSERT INTO species (id, name, conservation_status) VALUES (1, 'Atlantic Salmon', 'Endangered'), (2, 'Blue Whale', 'Critically Endangered');

SELECT name FROM species WHERE conservation_status = 'Critically Endangered';


Question: Generate PostgreSQL SQL for: What is the to par when the tournament involved was the Transitions Championship?

CREATE TABLE table_name_45 (to_par VARCHAR, tournament VARCHAR)

SELECT to_par FROM table_name_45 WHERE tournament = 'transitions championship';


Question: Generate PostgreSQL SQL for: Which Score has an Opponent in the final of mehdi tahiri?

CREATE TABLE table_name_96 (score VARCHAR, opponent_in_the_final VARCHAR)

SELECT score FROM table_name_96 WHERE opponent_in_the_final = 'mehdi tahiri';


Question: What is the total tonnage of all cargo handled by the 'cargo_handling' table in the year 2021?

CREATE TABLE cargo_handling (id INT, cargo_id INT, handling_date DATE, tonnage INT, PRIMARY KEY(id));

SELECT SUM(tonnage) FROM cargo_handling WHERE YEAR(handling_date) = 2021;


Question: What is the average price of properties with a sustainable rating above 70 in each city?

CREATE TABLE Sustainable_Ratings (id INT, property_id INT, sustainable_rating INT); CREATE VIEW High_Sustainable_Properties AS SELECT sr.property_id, p.address, sr.sustainable_rating FROM Sustainable_Ratings sr JOIN Property p ON sr.property_id = p.id WHERE sr.sustainable_rating > 70;

SELECT hsp.address, AVG(p.price) as avg_price FROM High_Sustainable_Properties hsp JOIN Property p ON hsp.property_id = p.id GROUP BY hsp.address;


Question: Generate PostgreSQL SQL for: What was the result on 1990-11-04?

CREATE TABLE table_name_55 (result VARCHAR, date VARCHAR)

SELECT result FROM table_name_55 WHERE date = '1990-11-04';


Question: What is the average safety score for each AI algorithm, ranked by the highest average?

CREATE TABLE ai_algorithms (ai_algorithm_id INT, algorithm_name VARCHAR(50), safety_score FLOAT); INSERT INTO ai_algorithms (ai_algorithm_id, algorithm_name, safety_score) VALUES (1, 'Algorithm A', 0.8), (2, 'Algorithm B', 0.9), (3, 'Algorithm C', 0.7);

SELECT algorithm_name, AVG(safety_score) as avg_safety_score FROM ai_algorithms GROUP BY algorithm_name ORDER BY avg_safety_score DESC;


Question: Generate PostgreSQL SQL for: How many different colleges do attend the tryout test?

SELECT COUNT(DISTINCT cName) FROM tryout;


Question: Find the user with the lowest financial wellbeing score in the FinancialWellbeing table.

CREATE TABLE FinancialWellbeing (userID VARCHAR(20), wellbeingScore INT); INSERT INTO FinancialWellbeing (userID, wellbeingScore) VALUES ('Ahmed', 6), ('Sara', 8), ('Mohammed', 5), ('Aisha', 7);

SELECT userID, MIN(wellbeingScore) FROM FinancialWellbeing;


Question: What are the total expenses for each department in the 'city_expenses' database?

CREATE TABLE department (id INT, name VARCHAR(50), budget DECIMAL(10,2)); INSERT INTO department (id, name, budget) VALUES (1, 'Public Works', 500000.00), (2, 'Education', 800000.00), (3, 'Health', 700000.00);

SELECT name, SUM(budget) FROM department GROUP BY name;


Question: Generate PostgreSQL SQL for: What day in November has a record of 15-6-1?

CREATE TABLE table_name_91 (november INTEGER, record VARCHAR)

SELECT AVG(november) FROM table_name_91 WHERE record = '15-6-1';


Question: Find dishes that contain both tomatoes and onions as ingredients.

CREATE TABLE ingredients (id INT, name VARCHAR(255)); INSERT INTO ingredients (id, name) VALUES (1, 'Tomatoes'), (2, 'Onions'), (3, 'Garlic'), (4, 'Cheese'), (5, 'Tofu'), (6, 'Chicken'), (7, 'Beef'), (8, 'Tomato Sauce'), (9, 'Onion Rings'); CREATE TABLE dish_ingredients (dish_id INT, ingredient_id INT); INSERT INTO dish_ingredients (dish_id, ingredient_id) VALUES (1, 1), (1, 2), (1, 3), (1, 8), (2, 2), (2, 3), (2, 4), (3, 1), (3, 2), (3, 6), (4, 2), (4, 9), (5, 3), (5, 4), (5, 7);

SELECT dish_ingredients.dish_id FROM dish_ingredients INNER JOIN ingredients ON dish_ingredients.ingredient_id = ingredients.id WHERE ingredients.name IN ('Tomatoes', 'Onions') GROUP BY dish_ingredients.dish_id HAVING COUNT(DISTINCT ingredients.name) = 2;


Question: How many songs were released by 'Female Artists' in the 'Pop' genre before 2010?

CREATE TABLE artists (artist_id INT, artist_name VARCHAR(100), gender VARCHAR(10)); INSERT INTO artists (artist_id, artist_name, gender) VALUES (1, 'Taylor Swift', 'Female'), (2, 'Ed Sheeran', 'Male'), (3, 'Kendrick Lamar', 'Male'), (4, 'Ariana Grande', 'Female'); CREATE TABLE songs (song_id INT, song_name VARCHAR(100), release_year INT, genre VARCHAR(50), artist_id INT); INSERT INTO songs (song_id, song_name, release_year, genre, artist_id) VALUES (1, 'Shape of You', 2017, 'Pop', 2), (2, 'Thinking Out Loud', 2014, 'Pop', 2), (3, 'Bohemian Rhapsody', 1975, 'Rock', 3), (4, 'Problem', 2014, 'Pop', 4), (5, 'The Way', 2013, 'Pop', 4);

SELECT COUNT(*) FROM songs s INNER JOIN artists a ON s.artist_id = a.artist_id WHERE a.gender = 'Female' AND s.genre = 'Pop' AND s.release_year < 2010;


Question: Write the DDL statement from PostgreSQL regression test 'join' (example 879).

Explanation: DDL from PostgreSQL core regression test for Join.


Question: What is the policy type and corresponding risk score for each policy, ordered by risk score in ascending order, for policies issued in 'Illinois'?

CREATE TABLE Policies (PolicyID INT, PolicyType VARCHAR(20), IssueState VARCHAR(20), RiskScore DECIMAL(5,2)); INSERT INTO Policies (PolicyID, PolicyType, IssueState, RiskScore) VALUES (1, 'Auto', 'Illinois', 0.10), (2, 'Home', 'Illinois', 0.05), (3, 'Life', 'Illinois', 0.15);

SELECT PolicyType, RiskScore FROM Policies WHERE IssueState = 'Illinois' ORDER BY RiskScore ASC;


Question: Generate PostgreSQL SQL for: What is the highest number of viewers for a rating greater than 9.4?

CREATE TABLE table_name_47 (viewers__m_ INTEGER, rating INTEGER)

SELECT MAX(viewers__m_) FROM table_name_47 WHERE rating > 9.4;


Question: What is the total yield for each crop type in the 'Agroecology' schema?

CREATE SCHEMA Agroecology; CREATE TABLE crop_yields (crop_type TEXT, yield NUMERIC) IN Agroecology; INSERT INTO crop_yields (crop_type, yield) VALUES ('Wheat', 12000), ('Rice', 15000), ('Corn', 20000), ('Wheat', 14000), ('Rice', 16000);

SELECT crop_type, SUM(yield) as total_yield FROM Agroecology.crop_yields GROUP BY crop_type;


Question: Display the total calories for each dish category in the menu_categories and menu tables.

CREATE TABLE menu_categories (category_id INT, category_name TEXT); CREATE TABLE menu (menu_id INT, category_id INT, dish_name TEXT, calories INT);

SELECT menu_categories.category_name, SUM(menu.calories) FROM menu INNER JOIN menu_categories ON menu.category_id = menu_categories.category_id GROUP BY menu_categories.category_name;


Question: Generate PostgreSQL SQL for: On what date was Arthur Jones the away captain at Sydney Cricket Ground?

CREATE TABLE table_name_33 (date VARCHAR, away_captain VARCHAR, venue VARCHAR)

SELECT date FROM table_name_33 WHERE away_captain = 'arthur jones' AND venue = 'sydney cricket ground';


Question: Calculate the percentage difference between the recycling rates of two specific districts.

CREATE TABLE RecyclingRates (id INT, district VARCHAR(20), recycling_rate DECIMAL(5,2)); INSERT INTO RecyclingRates (id, district, recycling_rate) VALUES (1, 'DistrictA', 0.65), (2, 'DistrictB', 0.70), (3, 'DistrictC', 0.55);

SELECT (SELECT R2.recycling_rate FROM RecyclingRates R2 WHERE R2.district = 'DistrictB') - (SELECT R1.recycling_rate FROM RecyclingRates R1 WHERE R1.district = 'DistrictA') AS difference;


Question: Generate PostgreSQL SQL for: whatthe minimum round where grand prix is german grand prix

CREATE TABLE table_1137704_2 (round INTEGER, grand_prix VARCHAR)

SELECT MIN(round) FROM table_1137704_2 WHERE grand_prix = 'German grand_prix';


Question: Generate PostgreSQL SQL for: What is the name of the building at the Jewellery quarter?

CREATE TABLE table_name_61 (name VARCHAR, location VARCHAR)

SELECT name FROM table_name_61 WHERE location = 'jewellery quarter';


Question: Generate PostgreSQL SQL for: How many floors have 207 w. hastings st. as the address?

CREATE TABLE table_name_1 (floors VARCHAR, street_address VARCHAR)

SELECT COUNT(floors) FROM table_name_1 WHERE street_address = '207 w. hastings st.';


Question: Generate PostgreSQL SQL for: Which High rebounds have High points of chris bosh (18)?

CREATE TABLE table_name_50 (high_rebounds VARCHAR, high_points VARCHAR)

SELECT high_rebounds FROM table_name_50 WHERE high_points = 'chris bosh (18)';


Question: Generate PostgreSQL SQL for: What Time has a Year of 1984?

CREATE TABLE table_name_77 (time VARCHAR, year VARCHAR)

SELECT time FROM table_name_77 WHERE year = 1984;


Question: What is the average number of public libraries per state in the United States?

CREATE TABLE State (StateName VARCHAR(50), Country VARCHAR(50), NumberOfPublicLibraries INT); INSERT INTO State (StateName, Country, NumberOfPublicLibraries) VALUES ('California', 'United States', 1500), ('Texas', 'United States', 500), ('New York', 'United States', 1000);

SELECT AVG(NumberOfPublicLibraries) FROM State WHERE Country = 'United States';


Question: Generate PostgreSQL SQL for: What is the 2007 for the 2003 desert prince?

SELECT 2007 FROM table_name_48 WHERE 2003 = 'desert prince';


Question: Which countries have the highest yield for soybean in the 'yields' table?

CREATE TABLE yields (id INT, crop VARCHAR(255), year INT, country VARCHAR(255), yield INT); INSERT INTO yields (id, crop, year, country, yield) VALUES (1, 'Corn', 2020, 'USA', 12000), (2, 'Soybean', 2020, 'Brazil', 4000), (3, 'Wheat', 2020, 'China', 8000);

SELECT country, yield FROM yields WHERE crop = 'Soybean' ORDER BY yield DESC;


Question: Write the DDL statement from PostgreSQL regression test 'rowsecurity' (example 290).

CREATE VIEW rec2v WITH (security_barrier) AS SELECT * FROM rec2;


Question: How many cases were handled by attorneys who have more than 10 years of experience?

CREATE TABLE Attorneys (AttorneyID INT, LastName VARCHAR(255), YearsOfExperience INT); INSERT INTO Attorneys (AttorneyID, LastName, YearsOfExperience) VALUES (1, 'Patel', 15), (2, 'Singh', 12), (3, 'Kim', 8); CREATE TABLE Cases (CaseID INT, AttorneyID INT);

SELECT COUNT(*) FROM Cases INNER JOIN Attorneys ON Cases.AttorneyID = Attorneys.AttorneyID WHERE Attorneys.YearsOfExperience > 10;


Question: How many female and male graduate students are there in each department?

CREATE TABLE dept_students (id INT, department VARCHAR(255), gender VARCHAR(10), student_count INT); INSERT INTO dept_students (id, department, gender, student_count) VALUES (1, 'Physics', 'Male', 15), (2, 'Physics', 'Female', 10), (3, 'Computer Science', 'Male', 20), (4, 'Computer Science', 'Female', 18);

SELECT department, gender, SUM(student_count) AS total_students FROM dept_students GROUP BY department, gender;


Question: List all the indigenous food systems in Brazil with their respective contact emails.

CREATE TABLE indigenous_food_systems (system_id INT, name TEXT, location TEXT, contact_email TEXT, country TEXT); INSERT INTO indigenous_food_systems (system_id, name, location, contact_email, country) VALUES (1, 'Forest Foods', 'tribal village', 'forestfoods@example.com', 'Brazil');

SELECT name, contact_email FROM indigenous_food_systems WHERE country = 'Brazil';


Question: Generate PostgreSQL SQL for: With the version of 1.5a, what is the release date?

CREATE TABLE table_2263152_1 (release_date VARCHAR, version VARCHAR)

SELECT release_date FROM table_2263152_1 WHERE version = '1.5a';


Question: Generate PostgreSQL SQL for: What is the county where kerry# is 59740?

CREATE TABLE table_1302886_1 (county VARCHAR, kerry_number VARCHAR)

SELECT county FROM table_1302886_1 WHERE kerry_number = 59740;


Question: Which water treatment plants are located in drought-prone areas with a drought status of 'extreme'?

CREATE TABLE water_plants (id INT, name VARCHAR(255), lat FLOAT, long FLOAT); INSERT INTO water_plants (id, name, lat, long) VALUES (1, 'Plant C', 37.7749, -122.4194), (2, 'Plant D', 29.7604, -95.3698); CREATE TABLE drought_status (id INT, region VARCHAR(255), status VARCHAR(255)); INSERT INTO drought_status (id, region, status) VALUES (1, 'California', 'extreme'), (2, 'Texas', 'moderate');

SELECT w.name, ds.status FROM water_plants w JOIN drought_status ds ON ST_DWithin(ST_SetSRID(ST_MakePoint(w.long, w.lat), 4326), ST_SetSRID(ST_MakePoint(ds.long, ds.lat), 4326), 100000) WHERE ds.status = 'extreme';


Question: Generate PostgreSQL SQL for: What is the French word for the Italian word nazione?

CREATE TABLE table_15040_8 (french VARCHAR, italian VARCHAR)

SELECT french FROM table_15040_8 WHERE italian = 'nazione';


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

select armor('', array[null], array['foo']);

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


Question: Generate PostgreSQL SQL for: How many points did the team who had 132 total points have in round 1?

CREATE TABLE table_24784769_1 (round1 INTEGER, total_points VARCHAR)

SELECT MAX(round1) FROM table_24784769_1 WHERE total_points = 132;


Question: Generate PostgreSQL SQL for: What is the start of the race with 676 laps?

CREATE TABLE table_name_29 (start VARCHAR, laps VARCHAR)

SELECT start FROM table_name_29 WHERE laps = '676';


Question: What is the average age of athletes in the 'athlete_wellbeing' table who play 'Basketball'?

CREATE TABLE athlete_wellbeing (athlete_id INT, name VARCHAR(50), age INT, sport VARCHAR(50)); INSERT INTO athlete_wellbeing (athlete_id, name, age, sport) VALUES (1, 'John Doe', 25, 'Basketball'); INSERT INTO athlete_wellbeing (athlete_id, name, age, sport) VALUES (2, 'Jane Smith', 28, 'Basketball'); INSERT INTO athlete_wellbeing (athlete_id, name, age, sport) VALUES (3, 'Jim Brown', 30, 'Football');

SELECT AVG(age) FROM athlete_wellbeing WHERE sport = 'Basketball';


Question: What is the total number of traditional art pieces by type, region, and continent?

CREATE TABLE Art (ArtID INT, Type VARCHAR(255), Region VARCHAR(255), Continent VARCHAR(255), Quantity INT); INSERT INTO Art (ArtID, Type, Region, Continent, Quantity) VALUES (1, 'Painting', 'Asia', 'Asia', 25), (2, 'Sculpture', 'Africa', 'Africa', 18), (3, 'Textile', 'South America', 'South America', 30), (4, 'Pottery', 'Europe', 'Europe', 20), (5, 'Jewelry', 'North America', 'North America', 12);

SELECT Type, Region, Continent, SUM(Quantity) as Total_Quantity FROM Art GROUP BY Type, Region, Continent;


Question: Generate PostgreSQL SQL for: Where was the game located on January 23, 2008?

CREATE TABLE table_name_93 (location VARCHAR, date VARCHAR)

SELECT location FROM table_name_93 WHERE date = 'january 23, 2008';


Question: What is the failure rate of aircraft by manufacturer?

CREATE SCHEMA Aircraft;CREATE TABLE Aircraft.FlightSafetyRecords (manufacturer VARCHAR(50), failure INT);INSERT INTO Aircraft.FlightSafetyRecords (manufacturer, failure) VALUES ('Boeing', 15), ('Airbus', 10), ('Comac', 5), ('Embraer', 3);

SELECT manufacturer, 100.0 * AVG(failure) AS failure_rate FROM Aircraft.FlightSafetyRecords GROUP BY manufacturer;


Question: Calculate the average speed for each vessel in the 'Tankers' fleet in the past week.

CREATE TABLE Fleets (id INT, name VARCHAR(255)); INSERT INTO Fleets (id, name) VALUES (1, 'Tankers'); CREATE TABLE VesselSpeeds (id INT, fleet_id INT, speed INT, speed_date DATE); INSERT INTO VesselSpeeds (id, fleet_id, speed, speed_date) VALUES (1, 1, 20, '2021-08-01'), (2, 1, 25, '2021-08-02');

SELECT fleet_id, AVG(speed) as avg_speed FROM VesselSpeeds  WHERE fleet_id = 1 AND speed_date >= DATEADD(week, -1, GETDATE())  GROUP BY fleet_id;


Question: Write the DDL statement from PostgreSQL regression test 'rules' (example 455).

create rule r1 as on update to rules_base do instead
  select * from rules_base where f1 = 1 for update;

Explanation: DDL from PostgreSQL core regression test for Rules.


Question: Generate PostgreSQL SQL for: What original air date has 5.85 u.s. viewers (million)?

CREATE TABLE table_27117365_1 (original_air_date VARCHAR, us_viewers__million_ VARCHAR)

SELECT original_air_date FROM table_27117365_1 WHERE us_viewers__million_ = '5.85';


Question: What is the total number of high severity vulnerabilities found in the last month?

CREATE TABLE Vulnerabilities (id INT, report_date DATE, severity INT); INSERT INTO Vulnerabilities (id, report_date, severity) VALUES (1, '2022-04-01', 3), (2, '2022-04-15', 5), (3, '2022-05-01', 7);

SELECT COUNT(*) FROM Vulnerabilities WHERE severity >= 5 AND report_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH);


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

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

SELECT count(*) FROM (select '{"a": {"b":{"c": "foo"}}}'::jsonb #>> array['a']) AS _sub;


Question: Generate PostgreSQL SQL for: What building in Louisville had more than 35 floors?

CREATE TABLE table_name_56 (name VARCHAR, city VARCHAR, floors VARCHAR)

SELECT name FROM table_name_56 WHERE city = 'louisville' AND floors > 35;


Question: What is the average lead time for each product line in the 'supply_chain' schema?

CREATE TABLE supply_chain.lead_time (product_line VARCHAR(50), lead_time INT); INSERT INTO supply_chain.lead_time (product_line, lead_time) VALUES ('Product Line A', 30), ('Product Line A', 45), ('Product Line B', 60), ('Product Line B', 75);

SELECT product_line, AVG(lead_time) as average_lead_time FROM supply_chain.lead_time GROUP BY product_line;


Question: Generate PostgreSQL SQL for: What was the margin of victory when the winning score was –14 (70-68-67=205)?

CREATE TABLE table_name_59 (margin_of_victory VARCHAR, winning_score VARCHAR)

SELECT margin_of_victory FROM table_name_59 WHERE winning_score = –14(70 - 68 - 67 = 205);


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

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

SELECT count(*) FROM (select interval '2147483647 centuries') AS _sub;


Question: Generate PostgreSQL SQL for: Which name was in a position less than 4 with 2 losses?

CREATE TABLE table_name_78 (name VARCHAR, position VARCHAR, lost VARCHAR)

SELECT name FROM table_name_78 WHERE position < 4 AND lost = 2;


Question: Generate PostgreSQL SQL for: What was the date of the game played in El Paso, Texas?

CREATE TABLE table_23718905_6 (date VARCHAR, city VARCHAR)

SELECT date FROM table_23718905_6 WHERE city = 'El Paso, Texas';


Question: Generate PostgreSQL SQL for: Which Season has a Club of real madrid, and a Rank smaller than 6, and less than 121 goals?

CREATE TABLE table_name_7 (season VARCHAR, goals VARCHAR, club VARCHAR, rank VARCHAR)

SELECT season FROM table_name_7 WHERE club = 'real madrid' AND rank < 6 AND goals < 121;


Question: Generate PostgreSQL SQL for: What Motion Picture after 2003 had Viola Davis nominated for Best Supporting Actress?

CREATE TABLE table_name_70 (motion_picture VARCHAR, award VARCHAR, actor VARCHAR, year VARCHAR, result VARCHAR)

SELECT motion_picture FROM table_name_70 WHERE year > 2003 AND result = 'nominated' AND actor = 'viola davis' AND award = 'best supporting actress';


Question: Identify the number of ethical labor practice violations for each supplier, along with their supplier type and last inspection date.

CREATE TABLE suppliers (supplier_id INT, supplier_type VARCHAR(255));CREATE TABLE violations (violation_id INT, violation_count INT, FK_supplier_id REFERENCES suppliers(supplier_id));CREATE TABLE inspections (inspection_id INT, last_inspection_date DATE, FK_supplier_id REFERENCES suppliers(supplier_id));

SELECT s.supplier_type, v.violation_count, i.last_inspection_date FROM suppliers s JOIN violations v ON s.supplier_id = v.supplier_id JOIN inspections i ON s.supplier_id = i.supplier_id GROUP BY s.supplier_id, v.violation_count, i.last_inspection_date;


Question: How many green buildings are there in total in the database?

CREATE TABLE green_buildings (id INT, building_name VARCHAR(100), country VARCHAR(50)); INSERT INTO green_buildings (id, building_name, country) VALUES (1, 'Green Building 1', 'Canada'), (2, 'Green Building 2', 'Mexico');


Question: Generate PostgreSQL SQL for: What is the name of the video game magazine that was issued bimonthly?

CREATE TABLE table_name_36 (title VARCHAR, magazine_type VARCHAR, frequency VARCHAR)

SELECT title FROM table_name_36 WHERE magazine_type = 'video game' AND frequency = 'bimonthly';


Question: Which rural infrastructure projects in the 'rural_infrastructure' table were not initiated in the same year as any community development initiatives in the 'community_development' table?

CREATE TABLE rural_infrastructure (id INT, project_name VARCHAR(50), initiation_year INT); INSERT INTO rural_infrastructure (id, project_name, initiation_year) VALUES (1, 'Irrigation System Upgrade', 2008), (2, 'Rural Road Expansion', 2022); CREATE TABLE community_development (id INT, initiative_name VARCHAR(50), initiation_year INT); INSERT INTO community_development (id, initiative_name, initiation_year) VALUES (1, 'Youth Empowerment Program', 2010), (2, 'Renewable Energy Workshops', 2022);

SELECT project_name FROM rural_infrastructure WHERE initiation_year NOT IN (SELECT initiation_year FROM community_development);


Question: List the names and treatment start dates of patients who have been treated with Cognitive Behavioral Therapy (CBT) or Dialectical Behavior Therapy (DBT)

CREATE TABLE patients (patient_id INT, name VARCHAR(50), age INT, state VARCHAR(50)); CREATE TABLE therapy_sessions (session_id INT, patient_id INT, therapist_id INT, session_date DATE, therapy_type VARCHAR(50)); INSERT INTO patients VALUES (1, 'John Doe', 35, 'California'); INSERT INTO patients VALUES (2, 'Jane Smith', 28, 'California'); INSERT INTO therapy_sessions VALUES (1, 1, 101, '2022-01-01', 'CBT'); INSERT INTO therapy_sessions VALUES (2, 2, 102, '2022-02-01', 'DBT');

SELECT patients.name, therapy_sessions.session_date FROM patients JOIN therapy_sessions ON patients.patient_id = therapy_sessions.patient_id WHERE therapy_sessions.therapy_type IN ('CBT', 'DBT');


Question: What are the most common mental health conditions in a specific age group?

CREATE TABLE Patients (PatientID INT, Age INT, Gender VARCHAR(10)); CREATE TABLE MentalHealthConditions (ConditionID INT, PatientID INT, Condition VARCHAR(50));

SELECT Patients.Age, MentalHealthConditions.Condition, COUNT(MentalHealthConditions.ConditionID) FROM Patients INNER JOIN MentalHealthConditions ON Patients.PatientID = MentalHealthConditions.PatientID WHERE Patients.Age BETWEEN 20 AND 30 GROUP BY Patients.Age, MentalHealthConditions.Condition ORDER BY Patients.Age, COUNT(MentalHealthConditions.ConditionID) DESC;


Question: What is the average revenue of products in the 'Organic' subcategory?

CREATE TABLE products (product_id INT, name TEXT, revenue FLOAT, subcategory TEXT); INSERT INTO products (product_id, name, revenue, subcategory) VALUES (1, 'Organic Cotton Shirt', 25.00, 'Clothing'), (2, 'Organic Avocados', 5.00, 'Food'); CREATE TABLE subcategories (subcategory TEXT, category TEXT); INSERT INTO subcategories (subcategory, category) VALUES ('Clothing', 'Apparel'), ('Food', 'Groceries');

SELECT AVG(revenue) FROM products INNER JOIN subcategories ON products.subcategory = subcategories.subcategory WHERE subcategories.subcategory = 'Clothing' AND subcategories.category = 'Apparel';


Question: Generate PostgreSQL SQL for: How many deaths did eseta cause?

CREATE TABLE table_name_34 (deaths VARCHAR, name VARCHAR)

SELECT deaths FROM table_name_34 WHERE name = 'eseta';


Question: How many TV shows are there for each genre?

CREATE TABLE tv_show (tv_show_id INT, title VARCHAR(50), genre VARCHAR(50)); INSERT INTO tv_show (tv_show_id, title, genre) VALUES (1, 'Show 1', 'Comedy'), (2, 'Show 2', 'Drama'), (3, 'Show 3', 'Comedy');

SELECT genre, COUNT(title) FROM tv_show GROUP BY genre;


Question: What is the minimum depth of the Puerto Rico Trench?

CREATE TABLE ocean_floor_mapping (name VARCHAR(255), location VARCHAR(255), min_depth FLOAT); INSERT INTO ocean_floor_mapping (name, location, min_depth) VALUES ('Puerto Rico Trench', 'Atlantic Ocean', 8605.0);

SELECT min_depth FROM ocean_floor_mapping WHERE name = 'Puerto Rico Trench';


Question: Generate PostgreSQL SQL for: What is the date for a CD format with a Region of Europe?

CREATE TABLE table_name_54 (date VARCHAR, region VARCHAR, format VARCHAR)

SELECT date FROM table_name_54 WHERE region = 'europe' AND format = 'cd';


Question: Write the DDL statement from PostgreSQL regression test 'groupingsets' (example 175).

create table gs_group_1 as
select g100, g10, sum(g::numeric), count(*), max(g::text)
from gs_data_1 group by cube (g1000, g100,g10);

Explanation: DDL from PostgreSQL core regression test for Groupingsets.


Question: Find the community health worker with the lowest cultural competency score.

CREATE TABLE community_health_workers_2 (worker_id INT, region VARCHAR(10), cultural_competency_score INT); INSERT INTO community_health_workers_2 (worker_id, region, cultural_competency_score) VALUES (1, 'Northeast', 70), (2, 'Southeast', 75), (3, 'Midwest', 80);

SELECT worker_id, MIN(cultural_competency_score) FROM community_health_workers_2;


Question: List all artworks created in the year 1905, in ascending order by the number of exhibitions they have been featured in.

CREATE TABLE Artworks (id INT, name TEXT, creation_date DATE, exhibitions INT);

SELECT name, exhibitions FROM (SELECT name, exhibitions, ROW_NUMBER() OVER (ORDER BY exhibitions ASC) as rn FROM Artworks WHERE creation_date = '1905-01-01') t WHERE rn <= 10;


Question: Generate PostgreSQL SQL for: Name the player for seattle

CREATE TABLE table_15621965_14 (player VARCHAR, school_club_team VARCHAR)

SELECT player FROM table_15621965_14 WHERE school_club_team = 'Seattle';


Question: Insert a new record for a donation of $250 made by 'Jamal' on '2022-04-01'.

CREATE TABLE Donations (DonationID INT, DonorID INT, Amount FLOAT, DonationDate DATE); INSERT INTO Donations (DonationID, DonorID, Amount, DonationDate) VALUES (1, 1, 500.00, '2021-01-01'), (2, 2, 800.00, '2021-02-01');

INSERT INTO Donations (DonationID, DonorID, Amount, DonationDate) VALUES (3, (SELECT DonorID FROM Donors WHERE Name = 'Jamal'), 250.00, '2022-04-01');


Question: What is the total budget for all agricultural innovation projects in the 'rural_dev' schema?

CREATE TABLE agricultural_innovation (project_name VARCHAR(255), budget INT); INSERT INTO agricultural_innovation (project_name, budget) VALUES ('Precision Agriculture', 1000000), ('Smart Irrigation', 800000);

SELECT SUM(budget) FROM agricultural_innovation;


Question: What is the total budget allocated for public safety and environmental protection services in the state of California in 2021?

CREATE TABLE budget_allocation (year INT, state VARCHAR(20), service VARCHAR(20), amount INT); INSERT INTO budget_allocation VALUES (2021, 'California', 'Public Safety', 3000000), (2021, 'California', 'Environmental Protection', 4000000);

SELECT SUM(amount) FROM budget_allocation WHERE state = 'California' AND (service = 'Public Safety' OR service = 'Environmental Protection') AND year = 2021;


Question: Generate PostgreSQL SQL for: What is the total of the first season in Segunda División that has a City of cañete?

CREATE TABLE table_name_44 (first_season_of_current_spell_in_segunda_división INTEGER, city VARCHAR)

SELECT SUM(first_season_of_current_spell_in_segunda_división) FROM table_name_44 WHERE city = 'cañete';


Question: Identify the bridges in the transportation division that require maintenance in the next 6 months and display their maintenance schedule.

CREATE TABLE bridges (id INT, name VARCHAR(50), division VARCHAR(50), maintenance_date DATE); INSERT INTO bridges (id, name, division, maintenance_date) VALUES (1, 'Bridge A', 'Transportation', '2024-02-01'), (2, 'Bridge B', 'Transportation', '2023-07-15'), (3, 'Bridge C', 'Transportation', '2025-03-20');

SELECT name, maintenance_date FROM bridges WHERE division = 'Transportation' AND maintenance_date BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 6 MONTH);


Question: Generate PostgreSQL SQL for: What is Outcome, when Tournament is "Chiang Mai , Thailand"?

CREATE TABLE table_name_90 (outcome VARCHAR, tournament VARCHAR)

SELECT outcome FROM table_name_90 WHERE tournament = 'chiang mai , thailand';


Question: Generate PostgreSQL SQL for: What is the latest episode written by  John Shiban & Thomas Schnauz?

CREATE TABLE table_26736342_1 (no_in_series INTEGER, written_by VARCHAR)

SELECT MAX(no_in_series) FROM table_26736342_1 WHERE written_by = 'John Shiban & Thomas Schnauz';


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

/* contrib/citext/citext--1.4.sql */

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

--
--  PostgreSQL code for CITEXT.
--
-- Most I/O functions, and a few others, piggyback on the "text" type
-- functions via the implicit cast to text.
--

--
-- Shell type to keep things a bit quieter.
--

CREATE TYPE citext;

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


Question: PostgreSQL regression test 'sqljson_queryfuncs': Write the SELECT query (example 50).

SELECT JSON_VALUE(jsonb '"aaa"', '$' RETURNING int DEFAULT 111 ON ERROR);

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

SELECT count(*) FROM (SELECT JSON_VALUE(jsonb '"aaa"', '$' RETURNING int DEFAULT 111 ON ERROR)) AS _sub;


Question: How many trains in Berlin pass through a station with 5000 or more daily passengers?

CREATE TABLE train_stations (id INT, name TEXT, city TEXT, daily_passengers INT);  CREATE TABLE train_routes (id INT, station_id INT, route_id INT);  CREATE VIEW high_traffic_stations AS SELECT station_id FROM train_routes JOIN train_stations ON train_stations.id = station_id WHERE daily_passengers >= 5000;

SELECT COUNT(*) FROM high_traffic_stations;


Question: What is the average response time for fire calls in the state of California?

CREATE TABLE fire_calls (id INT, state VARCHAR(255), response_time FLOAT); INSERT INTO fire_calls (id, state, response_time) VALUES (1, 'California', 6.5), (2, 'California', 7.2), (3, 'Texas', 5.4);

SELECT AVG(response_time) FROM fire_calls WHERE state = 'California';


Question: Generate PostgreSQL SQL for: Where is the home venue of Bengaluru FC?

CREATE TABLE table_name_95 (home_venue VARCHAR, team VARCHAR)

SELECT home_venue FROM table_name_95 WHERE team = 'bengaluru fc';


Question: List all the community development initiatives in 'rural Africa' that were funded by 'international aid organizations' and their respective budgets.

CREATE TABLE initiatives (id INT, name TEXT, region TEXT, funder TEXT, budget FLOAT); INSERT INTO initiatives (id, name, region, funder, budget) VALUES (1, 'Initiative 1', 'rural Africa', 'African Aid Organization', 100000), (2, 'Initiative 2', 'urban Africa', 'International Aid Organization', 200000);

SELECT initiatives.name, initiatives.region, initiatives.funder, initiatives.budget FROM initiatives WHERE initiatives.region = 'rural Africa' AND initiatives.funder = 'International Aid Organization';


Question: Generate PostgreSQL SQL for: What is the Suffix of the intensive and valency change of 0?

CREATE TABLE table_name_21 (suffix VARCHAR, valency_change VARCHAR, type VARCHAR)

SELECT suffix FROM table_name_21 WHERE valency_change = '0' AND type = 'intensive';


Question: Delete the mental health parity report for the state of New York in 2021

CREATE TABLE mental_health_parity_reports (report_id INT, state VARCHAR(255), year INT, total_complaints INT); INSERT INTO mental_health_parity_reports (report_id, state, year, total_complaints) VALUES (1, 'California', 2022, 250), (2, 'New York', 2021, 300), (3, 'Texas', 2022, 200);

DELETE FROM mental_health_parity_reports WHERE state = 'New York' AND year = 2021;


Question: Generate PostgreSQL SQL for: How many locations had a density (pop/km²) of 91.8 in the 2011 census?

CREATE TABLE table_1425958_1 (density__pop_km²_ VARCHAR)

SELECT COUNT(2011 AS _census) FROM table_1425958_1 WHERE density__pop_km²_ = '91.8';


Question: What is the average age of patients with diabetes in each state?

CREATE TABLE patients (id INT, name TEXT, age INT, state TEXT, has_diabetes BOOLEAN); INSERT INTO patients (id, name, age, state, has_diabetes) VALUES (1, 'John Doe', 65, 'California', true), (2, 'Jane Smith', 45, 'Texas', false);

SELECT patients.state, AVG(patients.age) FROM patients WHERE patients.has_diabetes = true GROUP BY patients.state;


Question: What is the total waste generation in gram by material type for the year 2020 in the city of San Francisco?

CREATE TABLE waste_generation(city VARCHAR(20), year INT, material VARCHAR(20), weight FLOAT); INSERT INTO waste_generation(city, year, material, weight) VALUES ('San Francisco', 2020, 'Plastic', 1500), ('San Francisco', 2020, 'Glass', 2000), ('San Francisco', 2020, 'Paper', 1200), ('San Francisco', 2020, 'Metal', 1700), ('San Francisco', 2020, 'Organic', 2500), ('Los Angeles', 2020, 'Plastic', 2000), ('Los Angeles', 2020, 'Glass', 3000), ('Los Angeles', 2020, 'Paper', 1800), ('Los Angeles', 2020, 'Metal', 2100), ('Los Angeles', 2020, 'Organic', 3500);

SELECT material, SUM(weight) FROM waste_generation WHERE city = 'San Francisco' AND year = 2020 GROUP BY material;


Question: Which smart city projects have a budget greater than $600,000?

CREATE TABLE IF NOT EXISTS smart_cities (  project_id INT,   project_name VARCHAR(255),   budget FLOAT,   PRIMARY KEY (project_id)); INSERT INTO smart_cities (project_id, project_name, budget) VALUES (1, 'Intelligent Lighting', 500000), (2, 'Smart Waste Management', 750000), (3, 'E-Governance Services', 600000);

SELECT * FROM smart_cities WHERE budget > 600000;


Question: PostgreSQL regression test 'jsonpath': Write the SELECT query (example 94).

select '$ ? (@ like_regex "pattern" flag "a")'::jsonpath;

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

SELECT count(*) FROM (select '$ ? (@ like_regex "pattern" flag "a")'::jsonpath) AS _sub;


Question: Generate PostgreSQL SQL for: What are all the spectral types for star mismis24-# is 1sw?

CREATE TABLE table_10432351_1 (spectral_type VARCHAR, star__pismis24__number_ VARCHAR)

SELECT spectral_type FROM table_10432351_1 WHERE star__pismis24__number_ = '1SW';