Question: What is the total carbon sequestered by forests in a specific country, and the average carbon sequestration per hectare for those forests?

CREATE TABLE Forests (id INT, name VARCHAR(255), hectares FLOAT, country VARCHAR(255), carbon_sequestration_tonnes INT); INSERT INTO Forests (id, name, hectares, country, carbon_sequestration_tonnes) VALUES (1, 'Amazon Rainforest', 55000000.0, 'Brazil', 120000000);

SELECT country, SUM(carbon_sequestration_tonnes) as total_carbon_sequestration, AVG(carbon_sequestration_tonnes/hectares) as avg_carbon_sequestration_per_hectare FROM Forests GROUP BY country;


Question: Generate PostgreSQL SQL for: Where does the judge who serves Beacon Falls , Naugatuck , Middlebury , Prospect reside?

CREATE TABLE table_26758262_1 (judges_residence VARCHAR, municipalities_served VARCHAR)

SELECT judges_residence FROM table_26758262_1 WHERE municipalities_served = 'Beacon Falls , Naugatuck , Middlebury , Prospect';


Question: Generate PostgreSQL SQL for: On week 7, what were the opponents?

CREATE TABLE table_25380472_2 (opponent VARCHAR, week VARCHAR)

SELECT opponent FROM table_25380472_2 WHERE week = 7;


Question: Generate PostgreSQL SQL for: Which category does drama league award belong to?

CREATE TABLE table_name_91 (category VARCHAR, award VARCHAR)

SELECT category FROM table_name_91 WHERE award = 'drama league award';


Question: Generate PostgreSQL SQL for: What is the loss for the game against @ expos, with a save of parrett (2)?

CREATE TABLE table_name_28 (loss VARCHAR, opponent VARCHAR, save VARCHAR)

SELECT loss FROM table_name_28 WHERE opponent = '@ expos' AND save = 'parrett (2)';


Question: Generate PostgreSQL SQL for: What is the score for the home team Notts County?

CREATE TABLE table_name_97 (score VARCHAR, home_team VARCHAR)

SELECT score FROM table_name_97 WHERE home_team = 'notts county';


Question: Generate PostgreSQL SQL for: What is varricchio's unit?

CREATE TABLE table_name_75 (unit VARCHAR, authors VARCHAR)

SELECT unit FROM table_name_75 WHERE authors = 'varricchio';


Question: Generate PostgreSQL SQL for: How many episodes have a share of 16.2% and an episode number of less than 1?

CREATE TABLE table_name_82 (total_viewers VARCHAR, share VARCHAR, episode_no VARCHAR)

SELECT COUNT(total_viewers) FROM table_name_82 WHERE share = '16.2%' AND episode_no < 1;


Question: What is the difference in athlete wellbeing scores between the first and last game for each athlete?

CREATE TABLE AthleteWellbeing (ScoreID INT, AthleteID INT, GameID INT, WellbeingScore INT); INSERT INTO AthleteWellbeing VALUES (1, 1, 1, 80), (2, 1, 2, 85), (3, 2, 1, 90), (4, 2, 2, 95), (5, 3, 1, 70), (6, 3, 2, 75);

SELECT AthleteID, FIRST_VALUE(WellbeingScore) OVER (PARTITION BY AthleteID ORDER BY GameID) as FirstGameWellbeingScore, LAST_VALUE(WellbeingScore) OVER (PARTITION BY AthleteID ORDER BY GameID ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) as LastGameWellbeingScore, LAST_VALUE(WellbeingScore) OVER (PARTITION BY AthleteID ORDER BY GameID ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) - FIRST_VALUE(WellbeingScore) OVER (PARTITION BY AthleteID ORDER BY GameID) as Difference FROM AthleteWellbeing;


Question: Generate PostgreSQL SQL for: What is the vote % for Cliff Breitkreuz?

CREATE TABLE table_name_24 (votes__percentage VARCHAR, candidate VARCHAR)

SELECT votes__percentage FROM table_name_24 WHERE candidate = 'cliff breitkreuz';


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

SELECT ia1d FROM jsonb_populate_record(NULL::jsbrec, '{"ia1d": [1, "2", null, 4]}') q;

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

SELECT count(*) FROM (SELECT ia1d FROM jsonb_populate_record(NULL::jsbrec, '{"ia1d": [1, "2", null, 4]}') q) AS _sub;


Question: Which public transportation routes have the highest frequency in Southeast Asia?

CREATE TABLE Public_Transit_Routes (id INT PRIMARY KEY, route VARCHAR(50), mode VARCHAR(50), frequency INT, region VARCHAR(50));

SELECT Public_Transit_Routes.route, Public_Transit_Routes.frequency FROM Public_Transit_Routes WHERE Public_Transit_Routes.region = 'Southeast Asia' ORDER BY Public_Transit_Routes.frequency DESC;


Question: Generate PostgreSQL SQL for: What was Kilgore's percentage when Potts (I) had 4% and Kaine (D) 47%, in the poll from October 30, 2005?

CREATE TABLE table_name_47 (kilgore__r_ VARCHAR, date VARCHAR, potts__i_ VARCHAR, kaine__d_ VARCHAR)

SELECT kilgore__r_ FROM table_name_47 WHERE potts__i_ = '4%' AND kaine__d_ = '47%' AND date = 'october 30, 2005';


Question: What is the nutritional information for all organic products?

CREATE TABLE Nutrition_Facts (Product_ID INT, Calories INT, Sodium_Milligrams INT, Sugar_Grams INT); CREATE TABLE Organic_Certified_Products (Product_ID INT, Organic_Certified INT); CREATE VIEW Organic_Products_Nutrition AS SELECT Nutrition_Facts.*, Organic_Certified_Products.Organic_Certified FROM Nutrition_Facts INNER JOIN Organic_Certified_Products ON Nutrition_Facts.Product_ID = Organic_Certified_Products.Product_ID WHERE Organic_Certified_Products.Organic_Certified = 1;

SELECT * FROM Organic_Products_Nutrition;


Question: Add new records to the 'digital_trends' table for trends with IDs 9 and 10, names 'Machine Learning' and 'Blockchain', and popularity scores of 85 and 60, respectively

CREATE TABLE digital_trends (trend_id INT, name VARCHAR(20), popularity_score INT);

INSERT INTO digital_trends (trend_id, name, popularity_score) VALUES (9, 'Machine Learning', 85), (10, 'Blockchain', 60);


Question: What is the total number of community policing programs in Miami and their respective budgets?"

CREATE TABLE miami_community_policing (id INT, program_name VARCHAR(255), city VARCHAR(255), budget INT); INSERT INTO miami_community_policing (id, program_name, city, budget) VALUES (1, 'Bike Patrol', 'Miami', 60000);

SELECT program_name, SUM(budget) as total_budget FROM miami_community_policing WHERE city = 'Miami' GROUP BY program_name;


Question: Generate PostgreSQL SQL for: What is the February number of the game with the Vancouver Canucks as the opponent and a game number greater than 55?

CREATE TABLE table_name_48 (february VARCHAR, opponent VARCHAR, game VARCHAR)

SELECT COUNT(february) FROM table_name_48 WHERE opponent = 'vancouver canucks' AND game > 55;


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

create function polyf(anycompatiblerange) returns anycompatiblemultirange
as 'select multirange($1);' language sql;

Explanation: DDL from PostgreSQL core regression test for Polymorphism.


Question: Find the percentage change in transportation budget between 2021 and 2022 in Texas.

CREATE TABLE TransportationBudget (state VARCHAR(20), year INT, budget INT); INSERT INTO TransportationBudget (state, year, budget) VALUES ('Texas', 2021, 5000000), ('Texas', 2022, 5500000);

SELECT ((new_budget - old_budget) * 100.0 / old_budget) AS pct_change FROM (SELECT b1.budget AS old_budget, b2.budget AS new_budget FROM TransportationBudget b1, TransportationBudget b2 WHERE b1.state = b2.state AND b1.year = 2021 AND b2.year = 2022 AND b1.state = 'Texas') AS subquery;


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

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


Question: PL/pgSQL test: Plpython Trigger (example 38).

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


Question: Generate PostgreSQL SQL for: What was the week on December 10, 1989?

CREATE TABLE table_name_39 (week VARCHAR, date VARCHAR)

SELECT week FROM table_name_39 WHERE date = 'december 10, 1989';


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

CREATE OPERATOR ~ (
	LEFTARG = hstore,
	RIGHTARG = hstore,
	PROCEDURE = hs_contained,
	COMMUTATOR = '@',
	RESTRICT = contsel,
	JOIN = contjoinsel
);

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


Question: Show a SQL definition from the timescaledb project (compat, item 46).

CREATE OR REPLACE FUNCTION _timescaledb_internal.to_unix_microseconds(ts timestamp with time zone) RETURNS bigint LANGUAGE PLPGSQL AS $$
BEGIN
  IF current_setting('timescaledb.enable_deprecation_warnings', true)::bool THEN
    RAISE WARNING 'function _timescaledb_internal.to_unix_microseconds(timestamp with time zone) is deprecated and has been moved to _timescaledb_functions schema. this compatibility function will be removed in a future version.';
  END IF;
  RETURN _timescaledb_functions.to_unix_microseconds($1);
END$$
SET search_path TO pg_catalog,pg_temp;

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


Question: What is the total number of military equipment sales for each defense contractor in the past 12 months, along with the name of the contractor and the total sales volume?

CREATE TABLE military_equipment_sales (id INT, defense_contractor_id INT, sale_date DATE, sales INT); INSERT INTO military_equipment_sales (id, defense_contractor_id, sale_date, sales) VALUES (1, 1, '2021-01-01', 5000000), (2, 1, '2021-02-01', 7000000), (3, 2, '2021-03-01', 6000000), (4, 3, '2021-04-01', 8000000); CREATE TABLE defense_contractors (id INT, name VARCHAR(255)); INSERT INTO defense_contractors (id, name) VALUES (1, 'Lockheed Martin'), (2, 'Boeing'), (3, 'Raytheon');

SELECT d.name, SUM(m.sales) as total_sales FROM military_equipment_sales m JOIN defense_contractors d ON m.defense_contractor_id = d.id WHERE m.sale_date >= DATEADD(year, -1, GETDATE()) GROUP BY d.name;


Question: What percentage of patients with PTSD in Japan experienced improvement after medication?

CREATE TABLE patients (id INT, improvement TEXT, condition TEXT, country TEXT); INSERT INTO patients (id, improvement, condition, country) VALUES (1, 'Improved', 'PTSD', 'Japan'); INSERT INTO patients (id, improvement, condition, country) VALUES (2, 'Not Improved', 'Anxiety', 'USA');

SELECT (COUNT(*) * 100.0 / (SELECT COUNT(*) FROM patients WHERE condition = 'PTSD')) AS percentage FROM patients WHERE improvement = 'Improved' AND condition = 'PTSD' AND country = 'Japan';


Question: Generate PostgreSQL SQL for: What is the location for a club of telecom?

CREATE TABLE table_name_61 (location VARCHAR, club VARCHAR)

SELECT location FROM table_name_61 WHERE club = 'telecom';


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

SELECT SUBSTRING('abcdefg' SIMILAR 'a#"%#"x|g' ESCAPE '#') AS "bcdef";

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

SELECT count(*) FROM (SELECT SUBSTRING('abcdefg' SIMILAR 'a#"%#"x|g' ESCAPE '#') AS "bcdef") AS _sub;


Question: Write the DML statement from PostgreSQL regression test 'index_including' (example 91).

INSERT INTO tbl SELECT x, 2*x, 3*x, box('4,4,4,4') FROM generate_series(1,1000) AS x;

Explanation: DML from PostgreSQL core regression test for Index Including.


Question: Write the DDL statement from PostgreSQL regression test 'vacuum' (example 250).

CREATE TABLE vacowned_parted (a int) PARTITION BY LIST (a);

Explanation: DDL from PostgreSQL core regression test for Vacuum.


Question: Generate PostgreSQL SQL for: who write the episode 5 in no. in season

CREATE TABLE table_19417244_2 (written_by VARCHAR, no_in_season VARCHAR)

SELECT written_by FROM table_19417244_2 WHERE no_in_season = 5;


Question: What are the building permit numbers, permit types, and permit issuance dates for projects that have started in Q1 2022?

CREATE TABLE building_permits (permit_number INT, permit_type TEXT, issuance_date DATE); CREATE TABLE project_timelines (project_id INT, permit_number INT, start_date DATE); INSERT INTO building_permits (permit_number, permit_type, issuance_date) VALUES (1, 'Residential', '2022-01-15'), (2, 'Commercial', '2022-02-20'), (3, 'Residential', '2021-12-10'), (4, 'Sustainable', '2022-03-05'); INSERT INTO project_timelines (project_id, permit_number, start_date) VALUES (1, 1, '2022-02-01'), (2, 2, '2022-03-10'), (3, 3, '2021-12-15'), (4, 4, '2022-03-15');

SELECT building_permits.permit_number, building_permits.permit_type, building_permits.issuance_date FROM building_permits INNER JOIN project_timelines ON building_permits.permit_number = project_timelines.permit_number WHERE project_timelines.start_date BETWEEN '2022-01-01' AND '2022-03-31';


Question: Delete records of workouts with a duration more than 90 minutes for all members from the 'Workouts' table

CREATE TABLE Workouts (WorkoutID INT, MemberID INT, Duration INT, MembershipType VARCHAR(20));

DELETE FROM Workouts WHERE Duration > 90;


Question: Show a query using PostgreSQL contrib extension 'btree_gin' (example 11).

SELECT * FROM test_date WHERE i<'2004-10-26'::timestamp ORDER BY i;

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


Question: How many labor rights violations have been reported in each region?

CREATE TABLE Labor_Rights (region VARCHAR(20), violation_reported BOOLEAN); INSERT INTO Labor_Rights (region, violation_reported) VALUES ('Northeast', true), ('Northeast', false), ('Midwest', true);

SELECT region, SUM(violation_reported) as total_violations FROM Labor_Rights GROUP BY region;


Question: What is the average price of gluten-free dishes?

CREATE TABLE menu_pricing_2 (item_id INT, item_name VARCHAR(50), is_gluten_free BOOLEAN, price DECIMAL(5, 2)); INSERT INTO menu_pricing_2 (item_id, item_name, is_gluten_free, price) VALUES (1, 'Pizza', FALSE, 12.99), (2, 'Salad', TRUE, 9.99), (3, 'Soup', FALSE, 5.99);

SELECT AVG(price) FROM menu_pricing_2 WHERE is_gluten_free = TRUE;


Question: What is the total water usage by residential customers in a specific neighborhood in 2022?

CREATE TABLE water_usage (id INT PRIMARY KEY, customer_id INT, usage_date DATE, usage_type VARCHAR(255), amount FLOAT); CREATE TABLE customers (id INT PRIMARY KEY, name VARCHAR(255), neighborhood VARCHAR(255));

SELECT SUM(wu.amount) as total_water_usage FROM water_usage wu JOIN customers c ON wu.customer_id = c.id WHERE wu.usage_type = 'Residential' AND wu.usage_date BETWEEN '2022-01-01' AND '2022-12-31' AND c.neighborhood = 'Specific Neighborhood';


Question: Generate PostgreSQL SQL for: What opponent has a result of 3–6, 6–2, 4–6?

CREATE TABLE table_name_74 (opponent VARCHAR, result VARCHAR)

SELECT opponent FROM table_name_74 WHERE result = '3–6, 6–2, 4–6';


Question: What is the average humidity (%) in tea plantations in Sri Lanka during the last month?

CREATE TABLE humidity_data (humidity DECIMAL(3,1), reading_date DATE, location TEXT); INSERT INTO humidity_data (humidity, reading_date, location) VALUES (82.5, '2021-07-01', 'Sri Lanka'), (85.3, '2021-07-02', 'Sri Lanka'), (79.2, '2021-01-01', 'Sri Lanka');

SELECT AVG(humidity) FROM humidity_data WHERE location = 'Sri Lanka' AND reading_date > DATE_SUB(CURDATE(), INTERVAL 1 MONTH) AND location LIKE '%tea%';


Question: Generate PostgreSQL SQL for: How many heats did Runners from Guinea-Bissau run, with rank higher than 33?

CREATE TABLE table_name_78 (heat INTEGER, nationality VARCHAR, rank VARCHAR)

SELECT SUM(heat) FROM table_name_78 WHERE nationality = 'guinea-bissau' AND rank < 33;


Question: Show a SQL definition from the zombodb project (_mappings, item 21).

CREATE OR REPLACE FUNCTION zdb.define_analyzer(name text, definition json) RETURNS void
    LANGUAGE sql
    VOLATILE STRICT AS
$$
DELETE
FROM zdb.analyzers
WHERE name = $1;
INSERT INTO zdb.analyzers(name, definition)
VALUES ($1, $2);
$$;

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


Question: Generate PostgreSQL SQL for: What is Year Named, when Longitude is 227.5E?

CREATE TABLE table_name_42 (year_named VARCHAR, longitude VARCHAR)

SELECT year_named FROM table_name_42 WHERE longitude = '227.5e';


Question: Which menu category has the highest inventory value for non-organic items?

CREATE TABLE non_organic_categories (id INT, category VARCHAR(255), total_value DECIMAL(5,2)); INSERT INTO non_organic_categories (id, category, total_value) VALUES (1, 'Proteins', 199.00), (2, 'Grains', 74.25);

SELECT category, total_value FROM non_organic_categories ORDER BY total_value DESC LIMIT 1;


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

SELECT JSON_VALUE(jsonb '{"d1": "H"}', '$.a2' RETURNING queryfuncs_test_domain DEFAULT 'foo'::queryfuncs_test_domain ON EMPTY);

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

SELECT count(*) FROM (SELECT JSON_VALUE(jsonb '{"d1": "H"}', '$.a2' RETURNING queryfuncs_test_domain DEFAULT 'foo'::queryfuncs_test_domain ON EMPTY)) AS _sub;


Question: Write the DDL statement from PostgreSQL regression test 'create_view' (example 77).

Explanation: DDL from PostgreSQL core regression test for Create View.


Question: PL/pgSQL test: Plpython Error (example 56).

/* test error logged with an underlying exception that includes a detail
 * string (bug #18070).
 */
CREATE FUNCTION python_error_detail() RETURNS SETOF text AS $$
  plan = plpy.prepare("SELECT to_date('xy', 'DD') d")
  for row in plpy.cursor(plan):
    yield row['d']
$$ LANGUAGE plpython3u;

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


Question: Generate PostgreSQL SQL for: Find the student ID and personal name of the student with at least two enrollments.

CREATE TABLE Student_Course_Enrolment (student_id VARCHAR); CREATE TABLE Students (personal_name VARCHAR, student_id VARCHAR)

SELECT T1.student_id, T2.personal_name FROM Student_Course_Enrolment AS T1 JOIN Students AS T2 ON T1.student_id = T2.student_id GROUP BY T1.student_id HAVING COUNT(*) >= 2;


Question: What is the geopolitical risk assessment for country Y?

CREATE TABLE geopolitical_risk (country VARCHAR, risk_level VARCHAR, assessment_date DATE);

SELECT risk_level FROM geopolitical_risk WHERE country = 'Country Y';


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

CREATE FUNCTION seg_out(seg)
RETURNS cstring
AS 'MODULE_PATHNAME'
LANGUAGE C STRICT IMMUTABLE PARALLEL SAFE;


Question: What is the average weight of cargo imported and exported by the company 'Poseidon Shipping'

CREATE TABLE ports (id INT, name VARCHAR(50), country VARCHAR(50)); CREATE TABLE cargo_operations (id INT, port_id INT, company VARCHAR(50), type VARCHAR(50), weight INT); INSERT INTO ports (id, name, country) VALUES (1, 'Port of Oakland', 'USA'), (2, 'Port of Singapore', 'Singapore'), (3, 'Port of Hong Kong', 'China'), (4, 'Port of Rotterdam', 'Netherlands'); INSERT INTO cargo_operations (id, port_id, company, type, weight) VALUES (1, 1, 'Poseidon Shipping', 'import', 5000), (2, 1, 'Poseidon Shipping', 'export', 7000), (3, 3, 'Poseidon Shipping', 'import', 8000), (4, 3, 'Poseidon Shipping', 'export', 9000), (5, 4, 'Poseidon Shipping', 'import', 6000), (6, 4, 'Poseidon Shipping', 'export', 4000), (7, 1, 'Poseidon Shipping', 'import', 5500), (8, 1, 'Poseidon Shipping', 'export', 7500);

SELECT AVG(weight) FROM cargo_operations WHERE company = 'Poseidon Shipping' AND (type = 'import' OR type = 'export');


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

CREATE OPERATOR >= (
	PROCEDURE = isnge,
	LEFTARG = ismn,
	RIGHTARG = ismn13,
	COMMUTATOR = <=,
	NEGATOR = <,
	RESTRICT = scalargtsel,
	JOIN = scalargtjoinsel );


Question: Generate PostgreSQL SQL for: How many countries had a per capita withdrawal (m 3 /p/yr) of 372?

CREATE TABLE table_15909409_2 (country VARCHAR, per_capita_withdrawal__m_3__p_yr_ VARCHAR)

SELECT COUNT(country) FROM table_15909409_2 WHERE per_capita_withdrawal__m_3__p_yr_ = 372;


Question: What are the flight numbers and airlines of flights with safety incidents reported in the year 2022?

CREATE TABLE Flights (id INT PRIMARY KEY, flight_number VARCHAR(10), airline VARCHAR(50), departure_date DATE); INSERT INTO Flights (id, flight_number, airline, departure_date) VALUES (1, 'UA123', 'United Airlines', '2022-01-01'), (2, 'DL456', 'Delta Airlines', '2022-02-01');

SELECT f.flight_number, f.airline FROM Flights f INNER JOIN SafetyIncidents si ON f.id = si.flight_id WHERE YEAR(si.incident_date) = 2022;


Question: What is the total number of clothing items made from sustainable materials?

CREATE TABLE Clothing (id INT, sustainable BOOLEAN); INSERT INTO Clothing VALUES (1, true), (2, false), (3, true), (4, true), (5, false); CREATE TABLE SustainableMaterials (id INT, clothing_id INT, material TEXT); INSERT INTO SustainableMaterials VALUES (1, 1, 'OrganicCotton'), (2, 3, 'Tencel'), (3, 4, 'Hemp'), (4, 2, 'Bamboo');

SELECT COUNT(*) FROM Clothing INNER JOIN SustainableMaterials ON Clothing.id = SustainableMaterials.clothing_id WHERE Clothing.sustainable = true;


Question: What is the average age of artists who performed at music festivals in Germany in 2021?

CREATE TABLE artists (artist_id INT, artist_name VARCHAR(255), artist_age INT, country VARCHAR(255)); INSERT INTO artists (artist_id, artist_name, artist_age, country) VALUES (1, 'John Doe', 35, 'USA'); CREATE TABLE festival_performances (performance_id INT, artist_id INT, festival_name VARCHAR(255), festival_country VARCHAR(255), festival_year INT); INSERT INTO festival_performances (performance_id, artist_id, festival_name, festival_country, festival_year) VALUES (1, 1, 'MusicFest', 'Germany', 2021);

SELECT AVG(a.artist_age) FROM artists a JOIN festival_performances fp ON a.artist_id = fp.artist_id WHERE fp.festival_country = 'Germany' AND fp.festival_year = 2021;


Question: Virtual tour usage in the Asia Pacific region.

CREATE TABLE virtual_tours (tour_id INT, name TEXT, region TEXT); INSERT INTO virtual_tours (tour_id, name, region) VALUES (1, 'Asia Pacific Tour', 'Asia Pacific');

SELECT region, COUNT(*) FROM virtual_tours WHERE region = 'Asia Pacific';


Question: Generate PostgreSQL SQL for: What is the average rank for Hungary?

CREATE TABLE table_name_82 (rank INTEGER, country VARCHAR)

SELECT AVG(rank) FROM table_name_82 WHERE country = 'hungary';


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

update test_jsonb_subscript set test_json['a'][1]['c'][2] = '1';

Explanation: DML from PostgreSQL core regression test for Jsonb.


Question: Generate PostgreSQL SQL for: What is the largest points number where the difference is 12?

CREATE TABLE table_name_69 (points INTEGER, difference VARCHAR)

SELECT MAX(points) FROM table_name_69 WHERE difference = '12';


Question: Generate PostgreSQL SQL for: If the call sign is DXYR, what is the branding?

CREATE TABLE table_19874169_3 (branding VARCHAR, callsign VARCHAR)

SELECT branding FROM table_19874169_3 WHERE callsign = 'DXYR';


Question: Generate PostgreSQL SQL for: What is the total for the place when the singer is Mariza Ikonomi when points are larger than 20?

CREATE TABLE table_name_88 (place VARCHAR, singer VARCHAR, points VARCHAR)

SELECT COUNT(place) FROM table_name_88 WHERE singer = 'mariza ikonomi' AND points > 20;


Question: What is the total number of workplaces with a safety rating above 85 in the 'workplace_safety' table?

CREATE TABLE workplace_safety (safety_rating INT, workplace_id INT);

SELECT COUNT(*) FROM workplace_safety WHERE safety_rating > 85;


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

SELECT '[{"attributes" : [], "ndistinct" : 1}]'::pg_ndistinct;

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

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


Question: Update the population of the Giant Panda to 1800.

CREATE TABLE Animals (id INT, name VARCHAR(255), population INT, status VARCHAR(255)); INSERT INTO Animals (id, name, population, status) VALUES (1, 'Amur Leopard', 90, 'Endangered'), (2, 'Black Rhino', 5000, 'Critically Endangered'), (3, 'Giant Panda', 1600, 'Vulnerable');

UPDATE Animals SET population = 1800 WHERE name = 'Giant Panda';


Question: Generate PostgreSQL SQL for: Which month in 2013 did the U.S. use the ruby birthstone?

CREATE TABLE table_name_76 (month VARCHAR, us__2013_ VARCHAR)

SELECT month FROM table_name_76 WHERE us__2013_ = 'ruby';


Question: Generate PostgreSQL SQL for: What is the season with a Skip of Eve Muirhead and a third of Kerry Barr?

CREATE TABLE table_name_42 (season VARCHAR, skip VARCHAR, third VARCHAR)

SELECT season FROM table_name_42 WHERE skip = 'eve muirhead' AND third = 'kerry barr';


Question: Generate PostgreSQL SQL for: Name the segment d for s cufflink

CREATE TABLE table_15187735_18 (segment_d VARCHAR, segment_a VARCHAR)

SELECT segment_d FROM table_15187735_18 WHERE segment_a = 's Cufflink';


Question: Delete records with a city of 'Los Angeles' from the warehouse table

CREATE TABLE warehouse (warehouse_id INT, warehouse_name VARCHAR(50), city VARCHAR(50), country VARCHAR(50));

DELETE FROM warehouse WHERE city = 'Los Angeles';


Question: Show a query using PostgreSQL contrib extension 'earthdistance' (example 34).

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


Question: Generate PostgreSQL SQL for: How many dogs went through any treatments?

CREATE TABLE Treatments (dog_id VARCHAR)

SELECT COUNT(DISTINCT dog_id) FROM Treatments;


Question: Generate PostgreSQL SQL for: What is the Player in T5 Place?

CREATE TABLE table_name_71 (player VARCHAR, place VARCHAR)

SELECT player FROM table_name_71 WHERE place = 't5';


Question: Generate PostgreSQL SQL for: Which  company's type is joint venture, and has principle activities listed as Cargo Airline and an incorporation of China?

CREATE TABLE table_name_37 (company VARCHAR, incorporated_in VARCHAR, type VARCHAR, principal_activities VARCHAR)

SELECT company FROM table_name_37 WHERE type = 'joint venture' AND principal_activities = 'cargo airline' AND incorporated_in = 'china';


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

INSERT INTO num_exp_mul VALUES (3,5,'70671.23589621');

Explanation: DML from PostgreSQL core regression test for Numeric.


Question: Which destinations in Africa have implemented more than 3 sustainable practices and have a travel warning issued?

CREATE TABLE sustainable_practices (destination_id INT, practice_id INT, year INT, implemented BOOLEAN); CREATE VIEW sustainable_destinations AS SELECT destination_id, COUNT(*) as num_practices FROM sustainable_practices WHERE implemented = TRUE GROUP BY destination_id; CREATE TABLE travel_warnings (destination_id INT, warning_level VARCHAR(10), warning_text TEXT, start_date DATE, end_date DATE); CREATE VIEW current_travel_warnings AS SELECT destination_id FROM travel_warnings WHERE CURRENT_DATE BETWEEN start_date AND end_date;

SELECT d.country FROM destinations d JOIN sustainable_destinations s ON d.id = s.destination_id JOIN current_travel_warnings ctw ON d.id = ctw.destination_id WHERE d.region = 'Africa' AND s.num_practices > 3;


Question: What is the maximum budget allocated for any category in the North region in the year 2020?

CREATE TABLE Budget (Year INT, Region VARCHAR(50), Category VARCHAR(50), Amount INT); INSERT INTO Budget (Year, Region, Category, Amount) VALUES (2020, 'North', 'Education', 5000000), (2020, 'North', 'Public Transportation', 6000000);

SELECT MAX(Amount) FROM Budget WHERE Year = 2020 AND Region = 'North';


Question: What is the revenue by day of the week for all restaurants?

CREATE TABLE sales (id INT, restaurant_id INT, sale_date DATE, sales DECIMAL(10,2)); CREATE VIEW day_sales AS SELECT restaurant_id, EXTRACT(DOW FROM sale_date) as day_of_week, SUM(sales) as total_sales FROM sales GROUP BY restaurant_id, day_of_week;

SELECT d.day_of_week, SUM(ds.total_sales) as total_sales FROM day_sales ds JOIN day_sales d ON ds.day_of_week = d.day_of_week GROUP BY d.day_of_week;


Question: Generate PostgreSQL SQL for: What is the highest round in which a player was picked for the Center position?

CREATE TABLE table_name_24 (round INTEGER, position VARCHAR)

SELECT MAX(round) FROM table_name_24 WHERE position = 'center';


Question: What is the minimum and maximum number of animals on pasture-based farms in Wisconsin?

CREATE TABLE pasture_farms (id INT, farm_name VARCHAR(50), state VARCHAR(20), num_animals INT); INSERT INTO pasture_farms (id, farm_name, state, num_animals) VALUES (1, 'Farm 1', 'Wisconsin', 50), (2, 'Farm 2', 'Wisconsin', 75), (3, 'Farm 3', 'Wisconsin', 100), (4, 'Farm 4', 'Wisconsin', 125), (5, 'Farm 5', 'Wisconsin', 150);

SELECT state, MIN(num_animals) as min_animals, MAX(num_animals) as max_animals FROM pasture_farms WHERE state = 'Wisconsin';


Question: Generate PostgreSQL SQL for: How many top 5s when he was on team #28/#49 jay robinson racing?

CREATE TABLE table_2216245_2 (top_5 INTEGER, team_s_ VARCHAR)

SELECT MAX(top_5) FROM table_2216245_2 WHERE team_s_ = '#28/#49 Jay Robinson Racing';


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

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


Question: PL/pgSQL test: Plpgsql Call (example 43).

CREATE PROCEDURE test_proc10(IN a int, OUT b int, IN c int DEFAULT 11)
LANGUAGE plpgsql
AS $$
BEGIN
  RAISE NOTICE 'a: %, b: %, c: %', a, b, c;
  b := a - c;
END;
$$;

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


Question: Generate PostgreSQL SQL for: What year did jaroslav vojtek category:articles with hcards Direct?

CREATE TABLE table_22032599_1 (year__ceremony_ VARCHAR, director VARCHAR)

SELECT year__ceremony_ FROM table_22032599_1 WHERE director = 'Jaroslav Vojtek Category:Articles with hCards';


Question: List the names and types of all farms in the 'farming' database that are located in a specific region.

CREATE TABLE farm (id INT, name VARCHAR(255), type VARCHAR(255), region VARCHAR(255)); INSERT INTO farm (id, name, type, region) VALUES (1, 'Smith Farm', 'organic', 'Midwest'), (2, 'Johnson Farm', 'conventional', 'South'), (3, 'Brown Farm', 'organic', 'Midwest'), (4, 'Davis Farm', 'conventional', 'West');

SELECT name, type FROM farm WHERE region = 'Midwest';


Question: Generate PostgreSQL SQL for: How many draws were there when there were points less than 23, 6 losses, and more than 21 against?

CREATE TABLE table_name_49 (drawn VARCHAR, against VARCHAR, points VARCHAR, lost VARCHAR)

SELECT COUNT(drawn) FROM table_name_49 WHERE points < 23 AND lost = 6 AND against > 21;


Question: What is the total number of marine species that have been observed in the Indian Ocean?

CREATE TABLE species (id INT, name TEXT, location TEXT); INSERT INTO species (id, name, location) VALUES (1, 'Clownfish', 'Indian Ocean'); INSERT INTO species (id, name, location) VALUES (2, 'Dolphin', 'Atlantic Ocean');

SELECT COUNT(*) FROM species WHERE location = 'Indian Ocean';


Question: Generate PostgreSQL SQL for: When zachary sanders is the performer how many first aired are there?

CREATE TABLE table_191105_2 (first_aired VARCHAR, performed_by VARCHAR)

SELECT COUNT(first_aired) FROM table_191105_2 WHERE performed_by = 'Zachary Sanders';


Question: List all unique digital initiatives by museums located in the Asia-Pacific region.

CREATE TABLE Digital_Initiatives (id INT, museum VARCHAR(255), initiative VARCHAR(255)); INSERT INTO Digital_Initiatives (id, museum, initiative) VALUES (1, 'National Museum of Australia', 'Virtual Tour'), (2, 'British Museum', 'Online Collection'), (3, 'Metropolitan Museum of Art', 'Digital Archive'), (4, 'National Museum of China', 'Interactive Exhibit');

SELECT DISTINCT initiative FROM Digital_Initiatives WHERE museum LIKE 'National Museum%';


Question: Generate PostgreSQL SQL for: What was the date of the game when the record of the series was 0–1?

CREATE TABLE table_name_10 (date VARCHAR, series VARCHAR)

SELECT date FROM table_name_10 WHERE series = '0–1';


Question: Insert new records for 3 autonomous shuttle stations in Seattle into the 'autonomous_stations' table

CREATE TABLE autonomous_stations (id INT, station_name VARCHAR(255), location VARCHAR(255), num_vehicles INT);

INSERT INTO autonomous_stations (id, station_name, location, num_vehicles) VALUES (1, 'Seattle Shuttle 1', 'Seattle', 5), (2, 'Seattle Shuttle 2', 'Seattle', 5), (3, 'Seattle Shuttle 3', 'Seattle', 5);


Question: PL/pgSQL test: Plpgsql Transaction (example 94).

INSERT INTO test3 (y) VALUES (3);  -- won't get here
END;

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


Question: Generate PostgreSQL SQL for: What is Brian Mateer's Speed?

CREATE TABLE table_name_1 (speed VARCHAR, rider VARCHAR)

SELECT speed FROM table_name_1 WHERE rider = 'brian mateer';


Question: Generate PostgreSQL SQL for: What is the Catalog number of the CD Single?

CREATE TABLE table_name_13 (catalog VARCHAR, format VARCHAR)

SELECT catalog FROM table_name_13 WHERE format = 'cd single';


Question: What is the total number of students enrolled in each district, and what is the average mental health score for students in each district?

CREATE TABLE districts (district_id INT, district_name TEXT); CREATE TABLE students (student_id INT, district_id INT, mental_health_score INT); INSERT INTO districts VALUES (1, 'District A'), (2, 'District B'); INSERT INTO students VALUES (1, 1, 60), (2, 1, 75), (3, 2, 45), (4, 2, 30);

SELECT d.district_name, COUNT(s.student_id) as num_students, AVG(s.mental_health_score) as avg_mental_health_score FROM students s JOIN districts d ON s.district_id = d.district_id GROUP BY s.district_id;


Question: What is the total number of art exhibitions and dance events in the year 2020?

CREATE TABLE ArtExhibitions (id INT, year INT, visitors INT); INSERT INTO ArtExhibitions (id, year, visitors) VALUES (1, 2018, 500), (2, 2019, 700), (3, 2020, 600), (4, 2021, 800); CREATE TABLE DanceEvents (id INT, year INT, visitors INT); INSERT INTO DanceEvents (id, year, visitors) VALUES (1, 2019, 300), (2, 2020, 400), (3, 2021, 500);

SELECT SUM(visitors) FROM ArtExhibitions WHERE year = 2020; SELECT SUM(visitors) FROM DanceEvents WHERE year = 2020;


Question: Generate PostgreSQL SQL for: Where did Collingwood play as the home team?

CREATE TABLE table_name_28 (venue VARCHAR, home_team VARCHAR)

SELECT venue FROM table_name_28 WHERE home_team = 'collingwood';


Question: pgTAP test for Pgtap--1.2.0--1.3.0 (assertion 2).

-- col_is_pk( schema, table, column[] )
CREATE OR REPLACE FUNCTION col_is_pk ( NAME, NAME, NAME[] )
RETURNS TEXT AS $$
    SELECT col_is_pk( $1, $2, $3, 'Columns ' || quote_ident($1) || '.' || quote_ident($2) || '(' || _ident_array_to_string($3, ', ') || ') should be a primary key' );
$$ LANGUAGE sql;

Explanation: SQL assertion from pgTAP test suite for Pgtap--1.2.0--1.3.0.


Question: Generate PostgreSQL SQL for: When batavo is the main sponsor and olympikus is the kit manufacturer who are the minor sponsors?

CREATE TABLE table_187239_1 (minor_sponsors VARCHAR, kit_manufacturer VARCHAR, main_sponsor VARCHAR)

SELECT minor_sponsors FROM table_187239_1 WHERE kit_manufacturer = 'Olympikus' AND main_sponsor = 'Batavo';


Question: pgTAP test for Aretap (assertion 103).

SELECT * FROM check_test(
    groups_are( ___mygroups('meanies'), 'whatever' ),
    false,
    'groups_are(groups, desc) extras',
    'whatever',
    '    Extra groups:
        meanies'
);

Explanation: SQL assertion from pgTAP test suite for Aretap.


Question: Which countries have participated in more than two peacekeeping operations?

CREATE TABLE Country (ID INT, Name VARCHAR(50)); INSERT INTO Country (ID, Name) VALUES (1, 'USA'), (2, 'Canada'), (3, 'Mexico'), (4, 'Brazil'), (5, 'Argentina'); CREATE TABLE Mission (ID INT, CountryID INT, Type VARCHAR(50), Year INT); INSERT INTO Mission (ID, CountryID, Type, Year) VALUES (1, 1, 'Peacekeeping', 2010), (2, 1, 'Peacekeeping', 2012), (3, 2, 'Peacekeeping', 2015), (4, 3, 'Peacekeeping', 2018), (5, 4, 'Peacekeeping', 2010), (6, 4, 'Peacekeeping', 2012), (7, 4, 'Peacekeeping', 2014), (8, 5, 'Peacekeeping', 2019), (9, 5, 'Peacekeeping', 2020);

SELECT Country.Name FROM Country JOIN Mission ON Country.ID = Mission.CountryID WHERE Mission.Type = 'Peacekeeping' GROUP BY Country.Name HAVING COUNT(*) > 2;


Question: What is the total revenue generated from ads on Facebook in Q2 2021, for users in the 'celebrity' category?

CREATE TABLE ads (ad_id INT, user_id INT, platform VARCHAR(255), ad_revenue DECIMAL(10,2)); INSERT INTO ads (ad_id, user_id, platform, ad_revenue) VALUES (1, 1, 'Facebook', 1500.50), (2, 2, 'Twitter', 800.00), (3, 3, 'Facebook', 1200.75);

SELECT SUM(ad_revenue) FROM ads WHERE platform = 'Facebook' AND MONTH(ad_date) BETWEEN 4 AND 6 AND YEAR(ad_date) = 2021 AND user_id IN (SELECT user_id FROM users WHERE category = 'celebrity');


Question: Update address in 'rural_clinics' where id=1

CREATE TABLE if not exists 'rural_clinics' (id INT, name TEXT, address TEXT, PRIMARY KEY(id));

UPDATE 'rural_clinics' SET address = 'New Address' WHERE id = 1;


Question: Generate PostgreSQL SQL for: Which employee has showed up in most circulation history documents. List the employee's name and the number of drafts and copies.

CREATE TABLE Circulation_History (Id VARCHAR); CREATE TABLE Employees (Id VARCHAR)

SELECT Employees.employee_name, COUNT(*) FROM Employees JOIN Circulation_History ON Circulation_History.employee_id = Employees.employee_id GROUP BY Circulation_History.document_id, Circulation_History.draft_number, Circulation_History.copy_number ORDER BY COUNT(*) DESC LIMIT 1;


Question: Generate PostgreSQL SQL for: When did the draw happen?

CREATE TABLE table_name_76 (date VARCHAR, result VARCHAR)

SELECT date FROM table_name_76 WHERE result = 'draw';


Question: Write the DML statement from PostgreSQL regression test 'uuid' (example 13).

Explanation: DML from PostgreSQL core regression test for Uuid.


Question: Generate PostgreSQL SQL for: What is the score for the game that has an attendance of 5,298?

CREATE TABLE table_name_9 (score VARCHAR, attendance VARCHAR)

SELECT score FROM table_name_9 WHERE attendance = '5,298';


Question: Generate PostgreSQL SQL for: How many group legs were won with player Mark Dudbridge?

CREATE TABLE table_24334163_1 (Winners VARCHAR, player VARCHAR)

SELECT Winners AS group_legs_won FROM table_24334163_1 WHERE player = 'Mark Dudbridge';


Question: Delete the OTA data for the 'NA' region from the 'ota_stats' table that is older than 2021.

CREATE TABLE ota_stats (id INT, ota_name TEXT, region TEXT, date DATE, clicks INT, bookings INT); INSERT INTO ota_stats (id, ota_name, region, date, clicks, bookings) VALUES (1, 'OTA1', 'NA', '2021-01-01', 100, 20), (2, 'OTA2', 'NA', '2021-02-01', 150, 30), (3, 'OTA3', 'EMEA', '2021-01-01', 50, 10);

DELETE FROM ota_stats WHERE region = 'NA' AND date < '2021-01-01';


Question: Generate PostgreSQL SQL for: Which Country has a Network of nelonen?

CREATE TABLE table_name_61 (country VARCHAR, network VARCHAR)

SELECT country FROM table_name_61 WHERE network = 'nelonen';


Question: Generate PostgreSQL SQL for: What is the smallest total number of medals for rank 11 and more than 0 silver medals?

CREATE TABLE table_name_25 (total INTEGER, rank VARCHAR, silver VARCHAR)

SELECT MIN(total) FROM table_name_25 WHERE rank = '11' AND silver > 0;


Question: List all marine species that are found in more than one ocean basin

CREATE TABLE species (id INT, name VARCHAR(255), habitat VARCHAR(255)); CREATE TABLE ocean_basin (id INT, name VARCHAR(255)); CREATE TABLE species_ocean_basin (species_id INT, ocean_basin_id INT);

SELECT species.name FROM species JOIN species_ocean_basin ON species.id = species_ocean_basin.species_id JOIN ocean_basin ON species_ocean_basin.ocean_basin_id = ocean_basin.id GROUP BY species.name HAVING COUNT(DISTINCT ocean_basin.name) > 1;


Question: How many donations were made in the first half of 2021?

SELECT COUNT(*) FROM Donations WHERE YEAR(donation_date) = 2021 AND MONTH(donation_date) <= 6;


Question: Generate PostgreSQL SQL for: What is the copa mercosur 1999 result for team grêmio, who did not qualify for the Copa Libertadores 1999 and Copa Conmebol 1999?

CREATE TABLE table_name_51 (copa_mercosur_1999 VARCHAR, team VARCHAR, copa_libertadores_1999 VARCHAR, copa_conmebol_1999 VARCHAR)

SELECT copa_mercosur_1999 FROM table_name_51 WHERE copa_libertadores_1999 = 'did not qualify' AND copa_conmebol_1999 = 'did not qualify' AND team = 'grêmio';


Question: Generate PostgreSQL SQL for: If the title is Paradox Lost and the reader is Briggs, Nicholas Nicholas Briggs, what are all of the notes?

CREATE TABLE table_20174050_7 (notes VARCHAR, reader VARCHAR, title VARCHAR)

SELECT notes FROM table_20174050_7 WHERE reader = 'Briggs, Nicholas Nicholas Briggs' AND title = 'Paradox Lost';


Question: Generate PostgreSQL SQL for: What week has a Record of 12-2?

CREATE TABLE table_name_99 (week VARCHAR, record VARCHAR)

SELECT week FROM table_name_99 WHERE record = '12-2';


Question: Generate PostgreSQL SQL for: Who did the fastest lap in the dutch grand prix?

CREATE TABLE table_1140077_2 (fastest_lap VARCHAR, race VARCHAR)

SELECT fastest_lap FROM table_1140077_2 WHERE race = 'Dutch Grand Prix';


Question: Show a SQL definition from the zombodb project (_mappings, item 19).

CREATE OR REPLACE FUNCTION zdb.define_filter(name text, definition json) RETURNS void
    LANGUAGE sql
    VOLATILE STRICT AS
$$
DELETE
FROM zdb.filters
WHERE name = $1;
INSERT INTO zdb.filters(name, definition)
VALUES ($1, $2);
$$;


Question: Rank exhibitions by the number of repeat visitors, ordered from the highest to the lowest?

CREATE TABLE Exhibitions (ExhibitionID INT, Name VARCHAR(50)); INSERT INTO Exhibitions (ExhibitionID, Name) VALUES (1, 'Impressionists'), (2, 'Ancient Art'); CREATE TABLE Visits (VisitID INT, VisitorID INT, ExhibitionID INT); INSERT INTO Visits (VisitID, VisitorID, ExhibitionID) VALUES (1, 1, 1), (2, 2, 1), (3, 3, 2), (4, 1, 1), (5, 4, 2);

SELECT ExhibitionID, Name, RANK() OVER (ORDER BY COUNT(VisitorID) DESC) AS RepeatVisitorRank FROM Visits V JOIN Exhibitions E ON V.ExhibitionID = E.ExhibitionID GROUP BY ExhibitionID, Name ORDER BY RepeatVisitorRank DESC;


Question: What is the total number of safety tests conducted by 'FutureAutomobiles'?

CREATE TABLE SafetyTestingCounts (ID INT, Manufacturer VARCHAR(255), NumTests INT); INSERT INTO SafetyTestingCounts (ID, Manufacturer, NumTests) VALUES (1, 'Green Motors', 50), (2, 'FutureAutomobiles', 75), (3, 'Blue Cars', 60);

SELECT SUM(NumTests) FROM SafetyTestingCounts WHERE Manufacturer = 'FutureAutomobiles';


Question: PostgreSQL regression test 'stats': Write the SELECT query (example 372).

SELECT sum(reuses) AS reuses, sum(reads) AS reads, sum(evictions) AS evictions
  FROM pg_stat_io WHERE context = 'vacuum' \gset io_sum_vac_strategy_after_
SELECT :io_sum_vac_strategy_after_reads > :io_sum_vac_strategy_before_reads;

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

SELECT count(*) FROM (SELECT sum(reuses) AS reuses, sum(reads) AS reads, sum(evictions) AS evictions
  FROM pg_stat_io WHERE context = 'vacuum' \gset io_sum_vac_strategy_after_
SELECT :io_sum_vac_strategy_after_reads > :io_sum_vac_strategy_before_reads) AS _sub;


Question: What is the most frequently ordered vegetarian item at location 1?

CREATE TABLE sales_data_5 (sale_id INT, location_id INT, item_id INT, quantity_sold INT, sale_date DATE); INSERT INTO sales_data_5 (sale_id, location_id, item_id, quantity_sold, sale_date) VALUES (1, 1, 1, 50, '2021-05-01'), (2, 2, 2, 90, '2021-05-02'), (3, 1, 3, 80, '2021-05-03');

SELECT location_id, item_id, SUM(quantity_sold) as total_sold FROM sales_data_5 WHERE location_id = 1 AND is_vegetarian = TRUE GROUP BY location_id, item_id ORDER BY total_sold DESC LIMIT 1;


Question: What are the total labor hours for all sustainable building projects in the city of Seattle?

CREATE TABLE project (id INT, city VARCHAR(20), type VARCHAR(20), hours INT); INSERT INTO project (id, city, type, hours) VALUES (1, 'Seattle', 'Sustainable', 500), (2, 'NYC', 'Sustainable', 800), (3, 'Seattle', 'Traditional', 300);

SELECT SUM(hours) FROM project WHERE city = 'Seattle' AND type = 'Sustainable';


Question: PostgreSQL regression test 'vacuum': Write the SELECT query (example 69).

SELECT reltuples, relhassubclass
  FROM pg_class WHERE oid = 'past_parted'::regclass;

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

SELECT count(*) FROM (SELECT reltuples, relhassubclass
  FROM pg_class WHERE oid = 'past_parted'::regclass) AS _sub;


Question: Generate PostgreSQL SQL for: What Venue has a Status of five nations, and Against of 0?

CREATE TABLE table_name_89 (venue VARCHAR, status VARCHAR, against VARCHAR)

SELECT venue FROM table_name_89 WHERE status = 'five nations' AND against = 0;


Question: What is the minimum budget for a climate finance project in South America?

CREATE TABLE climate_finance_projects (project_id INT, project_name VARCHAR(255), location VARCHAR(255), budget DECIMAL(10,2)); INSERT INTO climate_finance_projects (project_id, project_name, location, budget) VALUES (1, 'Renewable Energy in Brazil', 'Brazil', 3000000.00), (2, 'Energy Efficiency in Argentina', 'Argentina', 2000000.00), (3, 'Climate Resilience in Colombia', 'Colombia', 1000000.00);

SELECT MIN(budget) FROM climate_finance_projects WHERE location = 'South America';


Question: Generate PostgreSQL SQL for: What are the official languages of the countries of players from Maryland or Duke college?

CREATE TABLE country (Official_native_language VARCHAR, Country_id VARCHAR); CREATE TABLE match_season (Country VARCHAR, College VARCHAR)

SELECT T1.Official_native_language FROM country AS T1 JOIN match_season AS T2 ON T1.Country_id = T2.Country WHERE T2.College = 'Maryland' OR T2.College = 'Duke';


Question: What is the total number of unique volunteers who have contributed more than '50' hours to each organization?

CREATE TABLE Organizations (org_id INT, org_name TEXT); CREATE TABLE Volunteers (vol_id INT, volunteer_name TEXT, hours_contributed INT, org_id INT);

SELECT O.org_name, COUNT(DISTINCT V.vol_id) as total_volunteers FROM Organizations O INNER JOIN Volunteers V ON O.org_id = V.org_id WHERE V.hours_contributed > 50 GROUP BY O.org_name;


Question: Show a query using PostgreSQL contrib extension 'jsonb_plpython' (example 36).

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


Question: Which accommodations were provided to each student in the AccommodationHistory table?

CREATE TABLE AccommodationHistory (studentID INT, accommodationType VARCHAR(50), startDate DATE, endDate DATE);

SELECT studentID, GROUP_CONCAT(accommodationType) FROM AccommodationHistory GROUP BY studentID;


Question: Show a query using PostgreSQL contrib extension 'btree_gin' (example 6).

SELECT * FROM test_time WHERE i<='08:55:08'::time ORDER BY i;

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


Question: Update the 'rare_earth_market' table to reflect the current market price of Dysprosium as $210 per kg.

CREATE TABLE rare_earth_market (id INT, element TEXT, current_price FLOAT);

UPDATE rare_earth_market SET current_price = 210 WHERE element = 'Dysprosium';


Question: What is the total amount spent on ingredients for each menu item, excluding items with no sales, grouped by category?

CREATE TABLE menu_items (id INT, name TEXT, category TEXT, sales INT); CREATE TABLE ingredient_costs (menu_item_id INT, ingredient TEXT, cost INT);

SELECT menu_items.category, SUM(ingredient_costs.cost) FROM ingredient_costs JOIN menu_items ON ingredient_costs.menu_item_id = menu_items.id WHERE menu_items.sales > 0 GROUP BY menu_items.category;


Question: Generate PostgreSQL SQL for: What was the score against home team, Richmond?

CREATE TABLE table_name_28 (away_team VARCHAR, home_team VARCHAR)

SELECT away_team AS score FROM table_name_28 WHERE home_team = 'richmond';


Question: What is the percentage of uninsured individuals by race and ethnicity, and how does it compare to the overall percentage?

CREATE TABLE RaceEthnicityData (RaceEthnicity VARCHAR(255), Uninsured DECIMAL(3,1)); INSERT INTO RaceEthnicityData (RaceEthnicity, Uninsured) VALUES ('Asian', 5.0), ('Black', 12.0), ('Hispanic', 18.0), ('White', 8.0); CREATE TABLE OverallData (OverallUninsured DECIMAL(3,1)); INSERT INTO OverallData (OverallUninsured) VALUES (10.0);

SELECT RaceEthnicity, Uninsured, Uninsured * 100.0 / (SELECT OverallUninsured FROM OverallData) AS Percentage FROM RaceEthnicityData;


Question: Generate PostgreSQL SQL for: What was Johnnie Parsons rank when he completed over 200 laps?

CREATE TABLE table_name_67 (rank VARCHAR, laps INTEGER)

SELECT rank FROM table_name_67 WHERE laps > 200;


Question: What is the total number of games designed by female designers, and the number of esports events where at least one of these games was played?

CREATE TABLE Games (GameID INT, GameName VARCHAR(50), Genre VARCHAR(20)); CREATE TABLE GameDesigners (DesignerID INT, DesignerName VARCHAR(50), Gender VARCHAR(10)); CREATE TABLE GameDesign (GameID INT, DesignerID INT); CREATE TABLE EsportsEvents (EventID INT, GameID INT, EventName VARCHAR(50));

SELECT COUNT(DISTINCT Games.GameID), COUNT(DISTINCT EsportsEvents.EventID) FROM Games INNER JOIN GameDesign ON Games.GameID = GameDesign.GameID INNER JOIN GameDesigners ON GameDesign.DesignerID = GameDesigners.DesignerID LEFT JOIN EsportsEvents ON Games.GameID = EsportsEvents.GameID WHERE GameDesigners.Gender = 'Female';


Question: Generate PostgreSQL SQL for: What are the highest points for the team of marlboro brm with brm p180 as the chassis?

CREATE TABLE table_name_43 (points INTEGER, team VARCHAR, chassis VARCHAR)

SELECT MAX(points) FROM table_name_43 WHERE team = 'marlboro brm' AND chassis = 'brm p180';


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

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


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

CREATE FUNCTION _int_overlap_sel(internal, oid, internal, integer)
RETURNS float8
AS 'MODULE_PATHNAME'
LANGUAGE C STRICT STABLE;

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


Question: Generate PostgreSQL SQL for: When вуха (vúkha) is the belarusian how many slovaks are there?

CREATE TABLE table_26757_4 (slovak VARCHAR, belarusian VARCHAR)

SELECT COUNT(slovak) FROM table_26757_4 WHERE belarusian = 'вуха (vúkha)';


Question: Which ocean has the lowest average sea surface temperature?'

CREATE TABLE ocean_temperatures (ocean TEXT, avg_temp FLOAT); INSERT INTO ocean_temperatures (ocean, avg_temp) VALUES ('Pacific', 28.0); INSERT INTO ocean_temperatures (ocean, avg_temp) VALUES ('Atlantic', 27.5); INSERT INTO ocean_temperatures (ocean, avg_temp) VALUES ('Arctic', 0.0);

SELECT ocean, MIN(avg_temp) FROM ocean_temperatures;


Question: Generate PostgreSQL SQL for: Show all the Store_Name of drama workshop groups.

CREATE TABLE Drama_Workshop_Groups (Store_Name VARCHAR)

SELECT Store_Name FROM Drama_Workshop_Groups;


Question: Write the DML statement from PostgreSQL regression test 'spgist' (example 12).

insert into spgist_box_tbl(b)
select box(point(i,j),point(i+s,j+s))
  from generate_series(1,100,5) i,
       generate_series(1,100,5) j,
       generate_series(1,10) s;

Explanation: DML from PostgreSQL core regression test for Spgist.


Question: List all marine species that have a conservation status of 'Vulnerable' in the Southern Ocean?

CREATE TABLE species (id INT, name VARCHAR(255), conservation_status VARCHAR(255), ocean_basin VARCHAR(255)); INSERT INTO species (id, name, conservation_status, ocean_basin) VALUES (1, 'Atlantic Salmon', 'Endangered', 'Atlantic'), (2, 'Blue Whale', 'Critically Endangered', 'Pacific'), (3, 'Southern Ocean Orca', 'Vulnerable', 'Southern');

SELECT name FROM species WHERE conservation_status = 'Vulnerable' AND ocean_basin = 'Southern';


Question: Generate PostgreSQL SQL for: Name the numbers of the nba draft where the player went to kentucky

CREATE TABLE table_11677760_31 (nba_draft VARCHAR, college VARCHAR)

SELECT nba_draft FROM table_11677760_31 WHERE college = 'Kentucky';


Question: What is the total amount of research grants awarded to graduate students from the Computer Science department in the last 2 years?

CREATE TABLE GrantRecipients(StudentID INT, Department VARCHAR(50), GrantID INT, GrantAmt FLOAT, GrantDate DATE); INSERT INTO GrantRecipients (StudentID, Department, GrantID, GrantAmt, GrantDate) VALUES (1, 'Computer Science', 1, 150000.00, '2021-01-01');

SELECT SUM(GrantAmt) FROM GrantRecipients WHERE Department = 'Computer Science' AND YEAR(GrantDate) >= YEAR(CURRENT_DATE()) - 2;


Question: Generate PostgreSQL SQL for: What was the result of the election incumbent Brent Spence took place in?

CREATE TABLE table_1342218_17 (result VARCHAR, incumbent VARCHAR)

SELECT result FROM table_1342218_17 WHERE incumbent = 'Brent Spence';


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

SELECT regexp_replace(data, '^(.{100}).*(.{100})$', '\1..\2') FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1')
WHERE data NOT LIKE '%INSERT: %';

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


Question: List the chemical_ids and total production quantities for chemicals produced in Argentina

CREATE TABLE chemical_production (id INT PRIMARY KEY, chemical_id VARCHAR(10), quantity INT, country VARCHAR(50)); INSERT INTO chemical_production (id, chemical_id, quantity, country) VALUES (1, 'XY987', 700, 'Brazil'), (2, 'GH247', 600, 'India'), (3, 'XY987', 300, 'Australia'), (4, 'GH247', 500, 'India'), (5, 'GH247', 800, 'Brazil'), (6, 'XY987', 200, 'Chile'), (7, 'LM345', 150, 'Argentina'), (8, 'XY987', 400, 'Argentina');

SELECT chemical_id, SUM(quantity) FROM chemical_production WHERE country = 'Argentina' GROUP BY chemical_id;


Question: Identify the number of unique passengers who have traveled on each route during the month of March 2023

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

SELECT routes.route_name, COUNT(DISTINCT passengers.passenger_id) FROM passengers JOIN passenger_trips ON passengers.passenger_id = passenger_trips.passenger_id JOIN routes ON passenger_trips.route_id = routes.route_id WHERE passenger_trips.trip_date BETWEEN '2023-03-01' AND '2023-03-31' GROUP BY routes.route_id, routes.route_name;


Question: What is the average CO2 emissions reduction for projects using carbon capture technology?

CREATE TABLE co2_emissions (project_id INT, co2_reduction INT); INSERT INTO co2_emissions (project_id, co2_reduction) VALUES (1, 5000), (2, 6000), (3, 7000), (4, 4000), (5, 8000);

SELECT AVG(co2_reduction) FROM co2_emissions WHERE project_id IN (SELECT project_id FROM carbon_capture);


Question: Generate PostgreSQL SQL for: What was roberto travern's record when he fought against john salter?

CREATE TABLE table_name_60 (record VARCHAR, opponent VARCHAR)

SELECT record FROM table_name_60 WHERE opponent = 'john salter';


Question: What is the total number of underage visitors who have visited the museum in the last 3 months, by day?

CREATE TABLE Visitors (VisitorID INT, Age INT, VisitDate DATE); INSERT INTO Visitors (VisitorID, Age, VisitDate) VALUES (1, 14, '2022-05-01'); INSERT INTO Visitors (VisitorID, Age, VisitDate) VALUES (2, 17, '2022-05-03'); INSERT INTO Visitors (VisitorID, Age, VisitDate) VALUES (3, 12, '2022-05-05');

SELECT VisitDate, COUNT(VisitorID) as Count FROM Visitors WHERE Age < 18 AND VisitDate >= DATE_SUB(CURRENT_DATE, INTERVAL 3 MONTH) GROUP BY VisitDate;


Question: What is the average price of dishes in each menu category, excluding the cheapest and most expensive dishes?

CREATE TABLE menu (category VARCHAR(255), price FLOAT); INSERT INTO menu (category, price) VALUES ('Appetizers', 7.99), ('Entrees', 14.99), ('Desserts', 5.99), ('Drinks', 2.99), ('Sides', 1.99);

SELECT category, AVG(price) FROM (SELECT category, price FROM menu WHERE price NOT IN (SELECT MIN(price) FROM menu WHERE category = menu.category) AND price NOT IN (SELECT MAX(price) FROM menu WHERE category = menu.category)) AS filtered_menu GROUP BY category;


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

ALTER TEXT SEARCH TEMPLATE alt_ts_temp2 SET SCHEMA alt_nsp2;    -- failed (name conflict)

-- invalid: non-lowercase quoted identifiers
CREATE TEXT SEARCH TEMPLATE tstemp_case ("Init" = init_function);

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


Question: Generate PostgreSQL SQL for: How much money did David Toms get?

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

SELECT money___$__ FROM table_name_16 WHERE player = 'david toms';


Question: Write the DML statement from PostgreSQL regression test 'create_index' (example 452).

INSERT INTO concur_reindex_tab3 VALUES  (3, '[1,2]');

Explanation: DML from PostgreSQL core regression test for Create Index.


Question: Which textile suppliers prioritize sustainability?

CREATE TABLE TextileSuppliers (SupplierID INT, SupplierName TEXT, SustainabilityRating INT); INSERT INTO TextileSuppliers (SupplierID, SupplierName, SustainabilityRating) VALUES (1, 'GreenFabrics', 9), (2, 'EcoWeave', 8), (3, 'StandardTextiles', 5);

SELECT SupplierName FROM TextileSuppliers WHERE SustainabilityRating >= 8;


Question: What is the average transaction amount for each customer-region pair?

CREATE TABLE Transactions (id INT, customer_id INT, region VARCHAR(10), amount DECIMAL(10, 2)); INSERT INTO Transactions (id, customer_id, region, amount) VALUES (1, 10, 'Europe', 100), (2, 10, 'Asia', 200), (3, 11, 'Asia', 300), (4, 12, 'Europe', 400), (5, 10, 'Americas', 500), (6, 13, 'Americas', 600);

SELECT customer_id, region, AVG(amount) as avg_amount FROM Transactions GROUP BY customer_id, region;


Question: Generate PostgreSQL SQL for: What were the high points on March 29?

CREATE TABLE table_name_88 (high_points VARCHAR, date VARCHAR)

SELECT high_points FROM table_name_88 WHERE date = 'march 29';


Question: What is the total number of emergency calls received in the "northwest" neighborhood in the months of January and February?

CREATE TABLE monthly_emergency_calls (date DATE, neighborhood VARCHAR(20), calls INT); INSERT INTO monthly_emergency_calls (date, neighborhood, calls) VALUES ('2022-01-01', 'northwest', 50), ('2022-02-01', 'northwest', 60), ('2022-01-02', 'northwest', 55), ('2022-02-02', 'northwest', 65);

SELECT SUM(calls) FROM monthly_emergency_calls WHERE neighborhood = 'northwest' AND EXTRACT(MONTH FROM date) IN (1, 2);


Question: Generate PostgreSQL SQL for: What is the highest 3620 value with a 5432 of 5432 and a 15122 greater than 15122?


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

insert into insertconflicttest values (4, 'Mango') on conflict (fruit, key) do update set fruit = excluded.fruit;

Explanation: DML from PostgreSQL core regression test for Insert Conflict.


Question: Generate PostgreSQL SQL for: what is the notes when the time is 7:58.71?

CREATE TABLE table_name_44 (notes VARCHAR, time VARCHAR)

SELECT notes FROM table_name_44 WHERE time = '7:58.71';


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

SELECT a, b::testdomain_p FROM collate_test2 ORDER BY 2;

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

SELECT count(*) FROM (SELECT a, b::testdomain_p FROM collate_test2 ORDER BY 2) AS _sub;


Question: Generate PostgreSQL SQL for: What current conference is Post University a member of?

CREATE TABLE table_12936521_2 (current_conference VARCHAR, institution VARCHAR)

SELECT current_conference FROM table_12936521_2 WHERE institution = 'Post University';


Question: Generate PostgreSQL SQL for: how many airport with rank being 4

CREATE TABLE table_13836704_9 (airport VARCHAR, rank VARCHAR)

SELECT COUNT(airport) FROM table_13836704_9 WHERE rank = 4;


Question: What is the minimum coral cover for the last 10 years?

SELECT MIN(coral_cover) FROM coral_cover WHERE year BETWEEN (YEAR(CURRENT_DATE) - 10) AND YEAR(CURRENT_DATE);


Question: What is the total number of military equipment sold by Boeing to the Australian government in 2021?

CREATE TABLE military_sales_4 (supplier VARCHAR(255), buyer VARCHAR(255), equipment VARCHAR(255), year INTEGER, quantity INTEGER); INSERT INTO military_sales_4 (supplier, buyer, equipment, year, quantity) VALUES ('Boeing', 'Australian Government', 'Super Hornet Fighter Jet', 2021, 5), ('Boeing', 'Australian Government', 'Chinook Helicopter', 2021, 2);

SELECT SUM(quantity) FROM military_sales_4 WHERE supplier = 'Boeing' AND buyer = 'Australian Government' AND year = 2021;


Question: Determine the percentage change in monthly production of Lanthanum and Cerium from 2015 to 2016

CREATE TABLE production (element VARCHAR(10), year INT, month INT, quantity INT); INSERT INTO production (element, year, month, quantity) VALUES ('Lanthanum', 2015, 1, 100), ('Lanthanum', 2015, 2, 110), ('Lanthanum', 2016, 1, 120), ('Lanthanum', 2016, 2, 130), ('Cerium', 2015, 1, 140), ('Cerium', 2015, 2, 150), ('Cerium', 2016, 1, 160), ('Cerium', 2016, 2, 170);

SELECT element, (SUM(quantity * CASE WHEN year = 2016 THEN 1 ELSE -1 END) / SUM(quantity) * 100) AS percentage_change FROM production WHERE element IN ('Lanthanum', 'Cerium') GROUP BY element;


Question: Generate PostgreSQL SQL for: Which Player has Goals larger than 10, and a Debut year smaller than 1993, and Years at club of 1990–1993?

CREATE TABLE table_name_71 (player VARCHAR, years_at_club VARCHAR, goals VARCHAR, debut_year VARCHAR)

SELECT player FROM table_name_71 WHERE goals > 10 AND debut_year < 1993 AND years_at_club = '1990–1993';


Question: What is the maximum number of accessible technology initiatives in a region?

CREATE TABLE accessible_technology_initiatives (id INT, initiative_name VARCHAR(50), region VARCHAR(50)); INSERT INTO accessible_technology_initiatives (id, initiative_name, region) VALUES (1, 'Accessible Software Distribution', 'Asia'), (2, 'Hardware Adaptation for Persons with Disabilities', 'Europe'), (3, 'Inclusive Technology Education', 'Africa'), (4, 'Assistive Technology Research', 'North America');

SELECT region, COUNT(*) as initiative_count FROM accessible_technology_initiatives GROUP BY region ORDER BY initiative_count DESC LIMIT 1;


Question: What are the unique severity levels in the 'incidents' table?

CREATE TABLE incidents (incident_id INT, region VARCHAR(50), severity VARCHAR(10)); INSERT INTO incidents (incident_id, region, severity) VALUES (1, 'region_1', 'medium'), (2, 'region_2', 'high'), (3, 'region_3', 'high'), (4, 'region_1', 'low'), (5, 'region_3', 'medium');

SELECT DISTINCT severity FROM incidents;


Question: Increase the size of farm 'Earthy Bounty' by 25

CREATE TABLE farms (id INT, name TEXT, location TEXT, size FLOAT); INSERT INTO farms (id, name, location, size) VALUES (1, 'Earthy Bounty', 'US', 200.0);

UPDATE farms SET size = size + 25 WHERE name = 'Earthy Bounty';


Question: How can we update donor information for a specific region?

CREATE TABLE Donors (DonorID INT, Region VARCHAR(50), Name VARCHAR(50), Age INT, Donation DECIMAL(10,2)); INSERT INTO Donors (DonorID, Region, Name, Age, Donation) VALUES (1, 'Africa', 'John Doe', 30, 500), (2, 'Asia', 'Jane Smith', 40, 700), (3, 'Europe', 'Alice Johnson', 50, 900);

UPDATE Donors SET Name = 'James Brown', Age = 45 WHERE Region = 'Africa';


Question: Generate PostgreSQL SQL for: The Utah Jazz Player from UTEP was what nationality?

CREATE TABLE table_name_51 (nationality VARCHAR, school_club_team VARCHAR)

SELECT nationality FROM table_name_51 WHERE school_club_team = 'utep';


Question: List all policies with a premium greater than $2000 for policyholders living in 'California' or 'New York'.

CREATE TABLE Policies (PolicyID INT, Premium DECIMAL(10, 2), PolicyholderState VARCHAR(10)); INSERT INTO Policies (PolicyID, Premium, PolicyholderState) VALUES (1, 2500, 'California'), (2, 1500, 'New York'), (3, 1000, 'California');

SELECT * FROM Policies WHERE PolicyholderState IN ('California', 'New York') AND Premium > 2000;


Question: Generate PostgreSQL SQL for: Who were the candidates when Shirley Chisholm was the incumbent?

CREATE TABLE table_1341663_33 (candidates VARCHAR, incumbent VARCHAR)

SELECT candidates FROM table_1341663_33 WHERE incumbent = 'Shirley Chisholm';


Question: Show me the highest confidence threat indicator for each category that was updated in 2021.

CREATE TABLE ThreatIntel (id INT PRIMARY KEY, indicator_type VARCHAR(255), indicator_value VARCHAR(255), confidence INT, category VARCHAR(255), description TEXT, last_updated DATE); INSERT INTO ThreatIntel (id, indicator_type, indicator_value, confidence, category, description, last_updated) VALUES (1, 'IP', '138.197.228.54', 90, 'Malware', 'Known malware C&C server', '2021-01-10'), (2, 'Domain', 'example-malware[.]com', 85, 'Phishing', 'Phishing domain', '2021-02-15');

SELECT category, MAX(confidence) FROM ThreatIntel WHERE last_updated >= '2021-01-01' GROUP BY category;


Question: What is the maximum ticket price for classical concerts?

CREATE TABLE concert_prices (id INT, type VARCHAR(10), price DECIMAL(5,2)); INSERT INTO concert_prices (id, type, price) VALUES (1, 'classical', 35.50), (2, 'pop', 20.00), (3, 'classical', 40.00), (4, 'jazz', 28.30);

SELECT MAX(price) FROM concert_prices WHERE type = 'classical';


Question: Generate PostgreSQL SQL for: with games more than 22 what is the rebound total?

CREATE TABLE table_name_12 (rebounds INTEGER, games INTEGER)

SELECT SUM(rebounds) FROM table_name_12 WHERE games > 22;


Question: Which countries have the lowest number of suppliers with organic products in the SupplyChainTransparency table?

CREATE TABLE SupplyChainTransparency(supplier_id INT, supplier_country VARCHAR(50), is_organic BOOLEAN);

SELECT supplier_country, COUNT(*) as num_suppliers FROM SupplyChainTransparency WHERE is_organic = TRUE GROUP BY supplier_country ORDER BY num_suppliers ASC LIMIT 1;


Question: What is the average cost of materials used in each type of public works project?

CREATE TABLE project_material_costs (id INT, project_type VARCHAR(255), material_type VARCHAR(255), cost FLOAT); INSERT INTO project_material_costs (id, project_type, material_type, cost) VALUES (1, 'Bridge', 'Steel', 150000.00), (2, 'Road', 'Asphalt', 50000.00), (3, 'Building', 'Concrete', 200000.00), (4, 'Bridge', 'Concrete', 300000.00);

SELECT project_type, AVG(cost) as avg_cost FROM project_material_costs GROUP BY project_type;


Question: Generate PostgreSQL SQL for: What is the engine for the Bettenhausen Motorsports team?

CREATE TABLE table_name_3 (engine VARCHAR, team VARCHAR)

SELECT engine FROM table_name_3 WHERE team = 'bettenhausen motorsports';


Question: Generate PostgreSQL SQL for: What formated cataloged alca-9196?

CREATE TABLE table_name_10 (format VARCHAR, catalog VARCHAR)

SELECT format FROM table_name_10 WHERE catalog = 'alca-9196';


Question: Generate PostgreSQL SQL for: What team did the Red Sox play against on June 3?

CREATE TABLE table_name_16 (opponent VARCHAR, date VARCHAR)

SELECT opponent FROM table_name_16 WHERE date = 'june 3';


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

CREATE TEMP TABLE x (
	a serial,
	b int,
	c text not null default 'stuff',
	d text,
	e text
) ;

Explanation: DDL from PostgreSQL core regression test for Copy2.


Question: Calculate the percentage of the total cargo tonnage that each shipping line is responsible for, for all shipping lines operating in the North America region.

CREATE TABLE shipping_lines(line_id INT, line_name TEXT, region TEXT);CREATE TABLE cargo(cargo_id INT, line_id INT, port_id INT, tonnage INT);INSERT INTO shipping_lines VALUES (1,'Line A','North America'),(2,'Line B','North America'),(3,'Line C','Asia');INSERT INTO cargo VALUES (1,1,1,500),(2,1,1,800),(3,2,2,300),(4,3,3,500),(5,1,1,700);

SELECT s.line_name, (SUM(c.tonnage) * 100.0 / (SELECT SUM(tonnage) FROM cargo)) as percentage FROM shipping_lines s JOIN cargo c ON s.line_id = c.line_id WHERE s.region = 'North America' GROUP BY s.line_name;


Question: What is the total number of research expeditions per year?

CREATE TABLE expeditions (year INT, expedition_count INT);

SELECT year, SUM(expedition_count) FROM expeditions GROUP BY year;


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

-- Create the operator class
CREATE OPERATOR CLASS gist_macaddr8_ops
DEFAULT FOR TYPE macaddr8 USING gist
AS
	OPERATOR	1	<  ,
	OPERATOR	2	<= ,
	OPERATOR	3	=  ,
	OPERATOR	4	>= ,
	OPERATOR	5	>  ,
	OPERATOR	6	<> ,
	FUNCTION	1	gbt_macad8_consistent (internal, macaddr8, int2, oid, internal),
	FUNCTION	2	gbt_macad8_union (internal, internal),
	FUNCTION	3	gbt_macad8_compress (internal),
	FUNCTION	4	gbt_decompress (internal),
	FUNCTION	5	gbt_macad8_penalty (internal, internal, internal),
	FUNCTION	6	gbt_macad8_picksplit (internal, internal),
	FUNCTION	7	gbt_macad8_same (gbtreekey16, gbtreekey16, internal),
	FUNCTION	9	gbt_macad8_fetch (internal),
	FUNCTION	11	gbt_macad8_sortsupport (internal),
	FUNCTION	12 ("any", "any") gist_translate_cmptype_btree (int),
	STORAGE		gbtreekey16;


Question: Generate PostgreSQL SQL for: What is the Format of the French Frequency with a Call sign of CKRL-FM?

CREATE TABLE table_name_56 (format VARCHAR, notes VARCHAR, call_sign VARCHAR)

SELECT format FROM table_name_56 WHERE notes = 'french' AND call_sign = 'ckrl-fm';


Question: Generate PostgreSQL SQL for: Which Set 3 has a Score of 3–2, and a Set 2 of 25–23, and a Time of 19:00?

CREATE TABLE table_name_86 (set_3 VARCHAR, time VARCHAR, score VARCHAR, set_2 VARCHAR)

SELECT set_3 FROM table_name_86 WHERE score = '3–2' AND set_2 = '25–23' AND time = '19:00';


Question: What is the percentage of veterans employed in each state?

CREATE TABLE veteran_employment (state TEXT, num_veterans INT, total_employees INT); INSERT INTO veteran_employment VALUES ('California', 10000, 50000), ('Texas', 12000, 60000);

SELECT state, (num_veterans::DECIMAL(10,2) / total_employees::DECIMAL(10,2)) * 100 AS veteran_percentage FROM veteran_employment;


Question: Generate PostgreSQL SQL for: who had high points on march 14?

CREATE TABLE table_27700375_10 (high_points VARCHAR, date VARCHAR)

SELECT high_points FROM table_27700375_10 WHERE date = 'March 14';


Question: What are the auto show locations for the 'GreenTech' auto show in 2022?

CREATE TABLE AutoShowInfo (ID INT, Show VARCHAR(255), Location VARCHAR(255), Year INT); INSERT INTO AutoShowInfo (ID, Show, Location, Year) VALUES (1, 'GreenTech', 'Detroit', 2022), (2, 'GreenTech', 'Tokyo', 2023), (3, 'EcoExpo', 'Paris', 2022);

SELECT Location FROM AutoShowInfo WHERE Show = 'GreenTech' AND Year = 2022;


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

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

SELECT count(*) FROM (SELECT '2011-03-27 03:00:00 MSK'::timestamptz) AS _sub;


Question: Generate PostgreSQL SQL for: For what episode was the nominee (s) Walon Green, Joe Sachs nominated as a result?

CREATE TABLE table_name_52 (episode VARCHAR, result VARCHAR, nominee_s_ VARCHAR)

SELECT episode FROM table_name_52 WHERE result = 'nominated' AND nominee_s_ = 'walon green, joe sachs';


Question: Write the DDL statement from PostgreSQL regression test 'partition_info' (example 56).

CREATE MATERIALIZED VIEW ptif_test_matview AS SELECT 1;

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


Question: Find the total number of rural healthcare facilities in each state.

CREATE TABLE HealthcareFacilities (ID INT, Name TEXT, Location TEXT, State TEXT); INSERT INTO HealthcareFacilities VALUES (1, 'Rural General Hospital', 'Smalltown, KY', 'KY'); INSERT INTO HealthcareFacilities VALUES (2, 'Rural Health Clinic', 'Village, WV', 'WV'); INSERT INTO HealthcareFacilities VALUES (3, 'Rural General Hospital', 'Othertown, KY', 'KY');

SELECT State, COUNT(*) AS Total FROM HealthcareFacilities GROUP BY State;


Question: Generate PostgreSQL SQL for: Which Date has a Game of game 3?

CREATE TABLE table_name_90 (date VARCHAR, game VARCHAR)

SELECT date FROM table_name_90 WHERE game = 'game 3';


Question: Generate PostgreSQL SQL for: Which Grid has a Time of +13.999?

CREATE TABLE table_name_65 (grid INTEGER, time VARCHAR)

SELECT MIN(grid) FROM table_name_65 WHERE time = '+13.999';


Question: Write the DDL statement from PostgreSQL regression test 'random' (example 35).

CREATE FUNCTION ks_test_uniform_random_numeric_in_range()
RETURNS boolean AS
$$
DECLARE
  n int := 1000;        -- Number of samples
  c float8 := 1.94947;  -- Critical value for 99.9% confidence
  ok boolean;
BEGIN
  ok := (
    WITH samples AS (
      SELECT random(0, 0.999999) r FROM generate_series(1, n) ORDER BY 1
    ), indexed_samples AS (
      SELECT (row_number() OVER())-1.0 i, r FROM samples
    )
    SELECT max(abs(i/n-r)) < c / sqrt(n) FROM indexed_samples
  );
  RETURN ok;
END
$$
LANGUAGE plpgsql;

Explanation: DDL from PostgreSQL core regression test for Random.


Question: What is the minimum BMI of users aged 40-50?

CREATE TABLE users (id INT, age INT, gender VARCHAR(10), height INT, weight INT); INSERT INTO users (id, age, gender, height, weight) VALUES (1, 45, 'Male', 175, 80); INSERT INTO users (id, age, gender, height, weight) VALUES (2, 35, 'Female', 165, 60); INSERT INTO users (id, age, gender, height, weight) VALUES (3, 50, 'Male', 180, 90); INSERT INTO users (id, age, gender, height, weight) VALUES (4, 48, 'Female', 170, 70);

SELECT MIN(weight / POW(height / 100.0, 2)) as min_bmi FROM users WHERE age BETWEEN 40 AND 50;


Question: Which ZIP codes have the highest obesity rates in Texas?

CREATE TABLE zips (id INT, zip VARCHAR(10), state VARCHAR(255)); INSERT INTO zips (id, zip, state) VALUES (1, '12345', 'Texas'); CREATE TABLE health_surveys (id INT, zip VARCHAR(10), obesity_rate DECIMAL(5,2)); INSERT INTO health_surveys (id, zip, obesity_rate) VALUES (1, '12345', 35.6);

SELECT z.zip, h.obesity_rate FROM zips z JOIN (SELECT zip, MAX(obesity_rate) AS max_obesity_rate FROM health_surveys WHERE state = 'Texas' GROUP BY zip) hs ON z.zip = hs.zip JOIN health_surveys h ON z.zip = h.zip WHERE z.state = 'Texas' ORDER BY h.obesity_rate DESC;


Question: PL/pgSQL test: Plperl Setup (example 13).

-- Must reconnect to avoid failure with non-MULTIPLICITY Perl interpreters
\c -
SET search_path = plperl_setup_scratch;

Explanation: PL/pgSQL example from PostgreSQL source test for Plperl Setup.


Question: Generate PostgreSQL SQL for: Who had an Iflop of 2.5%?

CREATE TABLE table_name_55 (party VARCHAR, ifop_5_30_09 VARCHAR)

SELECT party FROM table_name_55 WHERE ifop_5_30_09 = '2.5%';


Question: What is the number of new hires in the last 3 months, grouped by hiring manager and total tenure at the company, ordered by the highest number of new hires?

CREATE TABLE Employees (EmployeeID INT, HiringManager VARCHAR(20), Tenure INT, HireDate DATE); INSERT INTO Employees (EmployeeID, HiringManager, Tenure, HireDate) VALUES (1, 'John Doe', 2, '2020-01-01'), (2, 'Jane Smith', 5, '2019-01-01'), (3, 'John Doe', 3, '2021-01-01'), (4, 'Jane Smith', 1, '2022-01-01'), (5, 'John Doe', 6, '2018-01-01');

SELECT HiringManager, Tenure, COUNT(*) as Num_NewHires FROM Employees WHERE HireDate >= DATE_SUB(CURRENT_DATE, INTERVAL 3 MONTH) GROUP BY HiringManager, Tenure ORDER BY Num_NewHires DESC;


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

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

SELECT count(*) FROM (SELECT xml 'abc' IS NOT DOCUMENT) AS _sub;


Question: Generate PostgreSQL SQL for: What's the part number of the model with TDP of 2.9 (max.4.1~5.4) w?

CREATE TABLE table_24096813_15 (part_number_s_ VARCHAR, tdp VARCHAR)

SELECT part_number_s_ FROM table_24096813_15 WHERE tdp = '2.9 (Max.4.1~5.4) W';


Question: Generate PostgreSQL SQL for: Who had the highest rebounds of the game on April 7?

CREATE TABLE table_name_15 (high_rebounds VARCHAR, date VARCHAR)

SELECT high_rebounds FROM table_name_15 WHERE date = 'april 7';


Question: What was the total R&D expenditure for 'DrugL''s clinical trials in 2020?

CREATE TABLE clinical_trials (drug_name TEXT, rd_expenditure FLOAT, year INT); INSERT INTO clinical_trials (drug_name, rd_expenditure, year) VALUES ('DrugL', 9000000.0, 2020), ('DrugL', 7000000.0, 2019);

SELECT drug_name, SUM(rd_expenditure) FROM clinical_trials WHERE drug_name = 'DrugL' AND year = 2020;


Question: Generate PostgreSQL SQL for: Name the melbourne for adelaide of no with auckland of yes and gold coast of yes

CREATE TABLE table_name_49 (melbourne VARCHAR, gold_coast VARCHAR, adelaide VARCHAR, auckland VARCHAR)

SELECT melbourne FROM table_name_49 WHERE adelaide = 'no' AND auckland = 'yes' AND gold_coast = 'no';


Question: Generate PostgreSQL SQL for: What are the titles of segment b when segment c is standby generators (part 1)?

CREATE TABLE table_15187735_21 (segment_b VARCHAR, segment_c VARCHAR)

SELECT segment_b FROM table_15187735_21 WHERE segment_c = 'Standby Generators (Part 1)';


Question: Generate PostgreSQL SQL for: What is the name of the race from round 1?

CREATE TABLE table_name_90 (race_name VARCHAR, round VARCHAR)

SELECT race_name FROM table_name_90 WHERE round = 1;


Question: Generate PostgreSQL SQL for: Who was the away team when North Melbourne was the home team?

CREATE TABLE table_name_17 (away_team VARCHAR, home_team VARCHAR)

SELECT away_team FROM table_name_17 WHERE home_team = 'north melbourne';


Question: Generate PostgreSQL SQL for: Which Casualties have a hostile Nature of incident and Circumstances of mortar attack?

CREATE TABLE table_name_67 (casualties VARCHAR, nature_of_incident VARCHAR, circumstances VARCHAR)

SELECT casualties FROM table_name_67 WHERE nature_of_incident = 'hostile' AND circumstances = 'mortar attack';


Question: What are the names of all military innovation projects that have not yet started?

CREATE TABLE military_innovation (project_id INT, name TEXT, start_date DATE); INSERT INTO military_innovation (project_id, name, start_date) VALUES (1, 'Project A', '2022-01-01'), (2, 'Project B', '2023-01-01'), (3, 'Project C', NULL);

SELECT name FROM military_innovation WHERE start_date IS NULL;


Question: What is the total CO2 emission for each country per year?

CREATE TABLE country (country_id INT, country_name VARCHAR(255)); INSERT INTO country (country_id, country_name) VALUES (1, 'CountryA'), (2, 'CountryB'); CREATE TABLE co2_emission (year INT, country_id INT, co2_emission INT); INSERT INTO co2_emission (year, country_id, co2_emission) VALUES (2000, 1, 1500), (2000, 2, 2000), (2001, 1, 1600), (2001, 2, 2200), (2002, 1, 1400), (2002, 2, 1800);

SELECT country_id, SUM(co2_emission) as total_emission FROM co2_emission GROUP BY country_id, YEAR(year);


Question: How many high-risk customers are there in California?

CREATE TABLE customers (customer_id INT, customer_name VARCHAR(50), state VARCHAR(20), risk_level VARCHAR(10)); INSERT INTO customers (customer_id, customer_name, state, risk_level) VALUES (1, 'John Doe', 'CA', 'high'), (2, 'Jane Smith', 'NY', 'medium');

SELECT COUNT(*) FROM customers WHERE state = 'CA' AND risk_level = 'high';


Question: Display the number of visitors to sustainable tourism events in Canada for each year

CREATE TABLE visitors (id INT, event_type VARCHAR(50), year INT, country VARCHAR(50)); INSERT INTO visitors (id, event_type, year, country) VALUES (1, 'Sustainable', 2018, 'Canada'), (2, 'Non-Sustainable', 2019, 'Canada'), (3, 'Sustainable', 2017, 'Canada');

SELECT year, COUNT(*) FROM visitors WHERE event_type = 'Sustainable' AND country = 'Canada' GROUP BY year;


Question: PostgreSQL regression test 'limit': Write the SELECT query (example 5).

SELECT ''::text AS zero, unique1, unique2, stringu1
		FROM onek WHERE unique1 < 50
		ORDER BY unique1 DESC LIMIT 8 OFFSET 99;

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

SELECT count(*) FROM (SELECT ''::text AS zero, unique1, unique2, stringu1
		FROM onek WHERE unique1 < 50
		ORDER BY unique1 DESC LIMIT 8 OFFSET 99) AS _sub;


Question: Generate PostgreSQL SQL for: What time is MDT when EDT is set and PDT is 6:00 a.m.?

CREATE TABLE table_name_58 (mdt___6_utc_ VARCHAR, edt___4_utc_ VARCHAR, pdt___7_utc_ VARCHAR)

SELECT mdt___6_utc_ FROM table_name_58 WHERE edt___4_utc_ = 'set' AND pdt___7_utc_ = '6:00 a.m.';


Question: Generate PostgreSQL SQL for: what is the total number of publisher where cover date is may 1939

CREATE TABLE table_1217448_1 (publisher VARCHAR, cover_date VARCHAR)

SELECT COUNT(publisher) FROM table_1217448_1 WHERE cover_date = 'May 1939';


Question: Generate PostgreSQL SQL for: Name the sum of gold which has a silver more than 1

CREATE TABLE table_name_23 (gold INTEGER, silver INTEGER)

SELECT SUM(gold) FROM table_name_23 WHERE silver > 1;


Question: Generate PostgreSQL SQL for: What is the democratic seat plurality with 29% democrat?

CREATE TABLE table_name_94 (democratic_seat_plurality VARCHAR, percentage_democrats VARCHAR)

SELECT democratic_seat_plurality FROM table_name_94 WHERE percentage_democrats = '29%';


Question: What is the total number of union members in the education sector?

CREATE TABLE union_members (id INT, workplace_id INT, member_name TEXT, member_join_date DATE, member_status TEXT); CREATE TABLE workplaces (id INT, name TEXT, location TEXT, sector TEXT, total_employees INT, successful_cb BOOLEAN, cb_year INT); INSERT INTO workplaces (id, name, location, sector, total_employees, successful_cb, cb_year) VALUES (1, 'School A', 'City X', 'education', 50, true, 2020), (2, 'University B', 'City Y', 'education', 3000, true, 2019); INSERT INTO union_members (id, workplace_id, member_name, member_join_date, member_status) VALUES (1, 1, 'John Doe', '2018-01-01', 'active'), (2, 1, 'Jane Smith', '2019-05-15', 'active'), (3, 2, 'Mike Johnson', '2020-03-01', 'active');

SELECT SUM(um.member_status = 'active'::INTEGER) FROM union_members um JOIN workplaces w ON um.workplace_id = w.id WHERE w.sector = 'education';


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

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

SELECT count(*) FROM (SELECT pg_partition_root('ptif_li_child')) AS _sub;


Question: Generate PostgreSQL SQL for: what's the dbeingtribution with grsecurity being optional and compile time buffer checks being yes

CREATE TABLE table_1357052_6 (distribution VARCHAR, grsecurity VARCHAR, compile_time_buffer_checks VARCHAR)

SELECT distribution FROM table_1357052_6 WHERE grsecurity = 'Optional' AND compile_time_buffer_checks = 'Yes';


Question: PostgreSQL regression test 'create_view': Write the SELECT query (example 259).

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

SELECT count(*) FROM (select pg_get_viewdef('tt16v', true)) AS _sub;


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

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


Question: PostgreSQL regression test 'arrays': Write the SELECT query (example 135).

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


Question: List all the completed rural infrastructure projects in the 'rural_infrastructure' table.

CREATE TABLE rural_infrastructure (id INT PRIMARY KEY, project_name VARCHAR(100), budget INT, start_date DATE, end_date DATE, status VARCHAR(20));

SELECT * FROM rural_infrastructure WHERE status = 'completed';


Question: Drop the 'claims' table

CREATE TABLE claims (claim_id INT PRIMARY KEY, policyholder_id INT, claim_amount DECIMAL(10, 2), claim_date DATE);


Question: Generate PostgreSQL SQL for: What is the highest Average, when Goals is "34", and when Matches is less than 37?

CREATE TABLE table_name_41 (average INTEGER, goals VARCHAR, matches VARCHAR)

SELECT MAX(average) FROM table_name_41 WHERE goals = 34 AND matches < 37;


Question: pgTAP test for Privs (assertion 64).

SELECT * FROM check_test(
    language_privs_are( 'plpgsql', current_user, '{USAGE}' ),
    true,
    'language_privs_are(lang, role, privs, desc)',
    'Role ' || quote_ident(current_user) || ' should be granted USAGE on language plpgsql',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Privs.


Question: List the number of unique mental health conditions per patient in Texas.

CREATE TABLE patient_mental_health_info (patient_id INT, condition VARCHAR(50)); INSERT INTO patient_mental_health_info (patient_id, condition) VALUES (1, 'Anxiety'), (1, 'Depression'), (2, 'Depression'), (3, 'PTSD'), (3, 'Anxiety'); CREATE TABLE patient_state (patient_id INT, state VARCHAR(50)); INSERT INTO patient_state (patient_id, state) VALUES (1, 'Texas'), (2, 'Texas'), (3, 'California');

SELECT patient_id, COUNT(DISTINCT condition) AS unique_conditions FROM patient_mental_health_info JOIN patient_state ON patient_state.patient_id = patient_mental_health_info.patient_id WHERE state = 'Texas' GROUP BY patient_id;


Question: What is the total revenue generated from each garment type in the year 2022?

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

SELECT garment_type, YEAR(sale_date) AS year, SUM(revenue) AS total_revenue FROM sales WHERE YEAR(sale_date) = 2022 GROUP BY garment_type, year;


Question: Add a new record to the "programs" table for a program named 'Arts and Crafts' with an ID of 5.

CREATE TABLE programs (id INT, name TEXT); INSERT INTO programs (id, name) VALUES (1, 'Feeding the Hungry'), (2, 'Tutoring Kids'), (3, 'Cleaning the Environment'), (4, 'Medical Aid');

INSERT INTO programs (id, name) VALUES (5, 'Arts and Crafts');


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

-- check it works with OUT parameters

CREATE FUNCTION crosstab_out(text, text,
  OUT rowid text, OUT rowdt timestamp,
  OUT temperature int4, OUT test_result text,
  OUT test_startdate timestamp, OUT volts float8)
RETURNS setof record
AS '$libdir/tablefunc','crosstab_hash'
LANGUAGE C STABLE STRICT;

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


Question: Update the risk assessment score for policyholder 4 to 600 based on their recent claim activity.

CREATE TABLE Policyholders (PolicyID INT, CoverageLimit DECIMAL(10,2), RiskAssessmentScore INT); INSERT INTO Policyholders (PolicyID, CoverageLimit, RiskAssessmentScore) VALUES (1, 750000.00, 400), (2, 400000.00, 350), (4, 50000.00, 250); CREATE TABLE Claims (ClaimID INT, PolicyID INT, ClaimAmount DECIMAL(10,2)); INSERT INTO Claims (ClaimID, PolicyID, ClaimAmount) VALUES (1, 1, 5000.00), (2, 4, 2500.00);

WITH UpdatedScores AS (UPDATE Policyholders SET RiskAssessmentScore = 600 WHERE PolicyID = 4 RETURNING *) SELECT * FROM UpdatedScores;


Question: Generate PostgreSQL SQL for: In how many years was Tom Fleming the final television commentator?

CREATE TABLE table_17766232_7 (year_s_ VARCHAR, final_television_commentator VARCHAR)

SELECT COUNT(year_s_) FROM table_17766232_7 WHERE final_television_commentator = 'Tom Fleming';


Question: Generate PostgreSQL SQL for: What were his winnings when he had 14 top 10s?

CREATE TABLE table_2169966_2 (winnings VARCHAR, top_10 VARCHAR)

SELECT winnings FROM table_2169966_2 WHERE top_10 = 14;


Question: Generate PostgreSQL SQL for: What club is R. H. C. Human who has a right arm medium pace bowling style a member of?

CREATE TABLE table_name_41 (club VARCHAR, bowling_style VARCHAR, name VARCHAR)

SELECT club FROM table_name_41 WHERE bowling_style = 'right arm medium pace' AND name = 'r. h. c. human';


Question: Generate PostgreSQL SQL for: In what year is the notes distance 1.83m?

CREATE TABLE table_name_82 (year VARCHAR, notes VARCHAR)

SELECT year FROM table_name_82 WHERE notes = '1.83m';


Question: List all chemical products and their corresponding safety protocol numbers for facilities in California.

CREATE TABLE chemical_products (id INT, product TEXT, safety_protocol INT); CREATE TABLE storage_facilities (id INT, name TEXT, state TEXT); INSERT INTO chemical_products (id, product, safety_protocol) VALUES (1, 'Product1', 123), (2, 'Product2', 456); INSERT INTO storage_facilities (id, name, state) VALUES (1, 'Facility1', 'California'), (2, 'Facility2', 'California');

SELECT cp.product, cp.safety_protocol, sf.name FROM chemical_products cp INNER JOIN storage_facilities sf ON cp.id = sf.id WHERE sf.state = 'California';


Question: Delete all records with 'Copper coin' artifact_type from the 'site_k_artifacts' table.

CREATE TABLE site_k_artifacts (id INT PRIMARY KEY, site_id INT, artifact_type VARCHAR(50), quantity INT); INSERT INTO site_k_artifacts (id, site_id, artifact_type, quantity) VALUES (1, 8, 'Stone tool', 15), (2, 8, 'Pottery shard', 20), (3, 8, 'Copper coin', 5), (4, 8, 'Bronze coin', 10);

DELETE FROM site_k_artifacts WHERE artifact_type = 'Copper coin';


Question: Write the DML statement from PostgreSQL regression test 'returning' (example 102).

UPDATE foo SET f4 = f4 + 1 RETURNING old.f3;  -- should fail
UPDATE foo SET f4 = f4 + 1 RETURNING old, new;

Explanation: DML from PostgreSQL core regression test for Returning.


Question: Generate PostgreSQL SQL for: What sort of Fuel/Trans does the Grey & Red locomotive have?

CREATE TABLE table_name_15 (fuel__trans VARCHAR, colour VARCHAR)

SELECT fuel__trans FROM table_name_15 WHERE colour = 'grey & red';


Question: What are the most common types of marine pollution in the Indian Ocean?

CREATE TABLE marine_pollution (pollution_id INT, type VARCHAR(50), ocean VARCHAR(20));

SELECT type, COUNT(*) FROM marine_pollution WHERE ocean = 'Indian Ocean' GROUP BY type ORDER BY COUNT(*) DESC LIMIT 1;


Question: Delete all records from the 'decentralized_applications' table where the 'app_category' is 'Gaming'

CREATE TABLE decentralized_applications (app_id INT PRIMARY KEY, app_name VARCHAR(100), app_category VARCHAR(50));

DELETE FROM decentralized_applications WHERE app_category = 'Gaming';


Question: What is the total amount of waste generated by each mining operation in 2020?

CREATE TABLE waste_generation (operation_id INT, operation_name TEXT, year INT, waste_generated INT);

SELECT operation_name, SUM(waste_generated) AS total_waste_generated FROM waste_generation WHERE year = 2020 GROUP BY operation_name;


Question: Write the DML statement from PostgreSQL regression test 'without_overlaps' (example 542).

INSERT INTO temporal_mltrng (id, valid_at) VALUES
  ('[6,7)', datemultirange(daterange('2018-01-01', '2018-02-01'))),
  ('[6,7)', datemultirange(daterange('2018-02-01', '2018-03-01')));

Explanation: DML from PostgreSQL core regression test for Without Overlaps.


Question: What is the average energy efficiency (in kWh/m2) of buildings in the 'asia_pacific' region, partitioned by country and ordered by energy efficiency in ascending order?

CREATE TABLE buildings (id INT, country VARCHAR(50), region VARCHAR(50), energy_efficiency FLOAT); INSERT INTO buildings (id, country, region, energy_efficiency) VALUES (1, 'China', 'asia_pacific', 2.34), (2, 'Japan', 'asia_pacific', 1.23), (3, 'India', 'asia_pacific', 3.45);

SELECT region, country, AVG(energy_efficiency) as avg_energy_efficiency FROM buildings WHERE region = 'asia_pacific' GROUP BY country, region ORDER BY avg_energy_efficiency ASC;


Question: What is the total number of volunteer hours per month for the year 2019?

CREATE TABLE volunteer_hours (id INT, volunteer_id INT, hours INT, hour_date DATE);

SELECT EXTRACT(MONTH FROM hour_date) as month, SUM(hours) as total_hours FROM volunteer_hours WHERE YEAR(hour_date) = 2019 GROUP BY month;


Question: Update the depth of the 'Tonga Trench' in the ocean_floor_mapping table to 10900.

CREATE TABLE ocean_floor_mapping (location TEXT, depth INTEGER); INSERT INTO ocean_floor_mapping (location, depth) VALUES ('Challenger Deep', 10994), ('Mariana Trench', 10972), ('Tonga Trench', 10823);

UPDATE ocean_floor_mapping SET depth = 10900 WHERE location = 'Tonga Trench';


Question: Generate PostgreSQL SQL for: What was the standing in the season that the pct% was 0.769?

CREATE TABLE table_2110959_1 (standing VARCHAR, pct__percentage VARCHAR)

SELECT standing FROM table_2110959_1 WHERE pct__percentage = '0.769';


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

SELECT pg_clear_extended_stats(schemaname => 'stats_import',
  relname => 'test',
  statistics_schemaname => 'stats_import',
  statistics_name => 'test_stat_clone',
  inherited => false);

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

SELECT count(*) FROM (SELECT pg_clear_extended_stats(schemaname => 'stats_import',
  relname => 'test',
  statistics_schemaname => 'stats_import',
  statistics_name => 'test_stat_clone',
  inherited => false)) AS _sub;


Question: Count the number of oil wells in the Niger Delta and their total daily production

CREATE TABLE oil_wells (well_id INT, location VARCHAR(20), daily_production FLOAT); INSERT INTO oil_wells (well_id, location, daily_production) VALUES (1, 'Niger Delta', 150.2), (2, 'Niger Delta', 160.3), (3, 'Niger Delta', 140.1);

SELECT location, COUNT(*), SUM(daily_production) FROM oil_wells WHERE location = 'Niger Delta' GROUP BY location;


Question: Generate PostgreSQL SQL for: What episode number in the series had 2.77 million U.S. viewers?

CREATE TABLE table_24319661_5 (no_in_series INTEGER, us_viewers__million_ VARCHAR)

SELECT MAX(no_in_series) FROM table_24319661_5 WHERE us_viewers__million_ = '2.77';


Question: Generate PostgreSQL SQL for: What year was the start 33?

CREATE TABLE table_name_97 (year INTEGER, start VARCHAR)

SELECT SUM(year) FROM table_name_97 WHERE start = '33';


Question: Generate PostgreSQL SQL for: What country placed t6 with player Vijay Singh?

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

SELECT country FROM table_name_91 WHERE place = 't6' AND player = 'vijay singh';


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

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

SELECT count(*) FROM (select '42'::jsonb #>> array['0']) AS _sub;


Question: What is the total square footage of building projects per labor category?

CREATE TABLE labor_statistics (labor_category VARCHAR(50), average_wage NUMERIC(10,2)); INSERT INTO labor_statistics (labor_category, average_wage) VALUES ('Carpenters', '35.56'), ('Electricians', '38.42'), ('Plumbers', '42.15'); CREATE TABLE project_data (project_id SERIAL PRIMARY KEY, labor_category VARCHAR(50), square_footage INTEGER); INSERT INTO project_data (project_id, labor_category, square_footage) VALUES (1, 'Carpenters', 15000), (2, 'Electricians', 20000), (3, 'Plumbers', 25000);

SELECT labor_category, SUM(square_footage) FROM project_data GROUP BY labor_category;


Question: pgTAP test for Trigger (assertion 3).

CREATE TABLE public.users(
    nick  text NOT NULL PRIMARY KEY,
    pass  text NOT NULL
);

Explanation: SQL assertion from pgTAP test suite for Trigger.


Question: Update nutrition data for 'Green Earth' to reflect new certifications.

CREATE TABLE NutritionData (SupplierID INT, Certification TEXT); INSERT INTO NutritionData (SupplierID, Certification) VALUES (1, 'Organic'), (2, 'Non-GMO');

UPDATE NutritionData SET Certification = 'Biodynamic' WHERE SupplierID = (SELECT SupplierID FROM Suppliers WHERE SupplierName = 'Green Earth');


Question: Generate PostgreSQL SQL for: How many different high assists results are there for the game played on February 24?

CREATE TABLE table_23248940_9 (high_assists VARCHAR, date VARCHAR)

SELECT COUNT(high_assists) FROM table_23248940_9 WHERE date = 'February 24';


Question: What is the minimum funding received by a startup founded by a person with a disability in the finance sector?

CREATE TABLE startups(id INT, name TEXT, industry TEXT, founder_ability TEXT, funding FLOAT); INSERT INTO startups (id, name, industry, founder_ability, funding) VALUES (1, 'FinanceAbility', 'Finance', 'Disabled', 2000000);

SELECT MIN(funding) FROM startups WHERE industry = 'Finance' AND founder_ability = 'Disabled';


Question: What is the total investment in agricultural innovation in South Asia in the past 3 years?

CREATE TABLE investment (id INT, project TEXT, location TEXT, investment_amount INT, year INT); INSERT INTO investment (id, project, location, investment_amount, year) VALUES (1, 'Potato Seed Project', 'India', 200000, 2019), (2, 'Corn Seed Project', 'Pakistan', 300000, 2020), (3, 'Rice Seed Project', 'Bangladesh', 150000, 2018), (4, 'Wheat Seed Project', 'Sri Lanka', 250000, 2021);

SELECT SUM(investment_amount) FROM investment WHERE location LIKE 'South%' AND year BETWEEN 2019 AND 2021;


Question: Generate PostgreSQL SQL for: What is the average crowd when the home team is north melbourne?

CREATE TABLE table_name_31 (crowd INTEGER, home_team VARCHAR)

SELECT AVG(crowd) FROM table_name_31 WHERE home_team = 'north melbourne';


Question: Generate PostgreSQL SQL for: What is the total number of years when Mika Miyazato won the silver?

CREATE TABLE table_name_11 (year VARCHAR, silver VARCHAR)

SELECT COUNT(year) FROM table_name_11 WHERE silver = 'mika miyazato';


Question: Generate PostgreSQL SQL for: What colors does David Langdon use?

CREATE TABLE table_19624708_1 (colours VARCHAR, owner VARCHAR)

SELECT colours FROM table_19624708_1 WHERE owner = 'David Langdon';


Question: What is the total quantity of materials used in production for each brand?

CREATE TABLE brands (id INT, name VARCHAR(50)); CREATE TABLE materials_used (id INT, brand_id INT, material VARCHAR(50), quantity INT); INSERT INTO brands (id, name) VALUES (1, 'Brand A'), (2, 'Brand B'), (3, 'Brand C'); INSERT INTO materials_used (id, brand_id, material, quantity) VALUES (1, 1, 'Organic Cotton', 100), (2, 1, 'Recycled Polyester', 150), (3, 2, 'Organic Cotton', 200), (4, 3, 'Recycled Polyester', 125);

SELECT b.name, SUM(mu.quantity) as total_quantity FROM brands b INNER JOIN materials_used mu ON b.id = mu.brand_id GROUP BY b.name;


Question: Delete all records from the military equipment table that are older than 10 years

CREATE TABLE military_equipment (equipment_type VARCHAR(255), purchase_date DATE); INSERT INTO military_equipment (equipment_type, purchase_date) VALUES ('Tank', '2011-01-01'), ('Jet', '2012-01-01'), ('Submarine', '2005-01-01');

DELETE FROM military_equipment WHERE purchase_date < '2011-01-01';