Question: Generate PostgreSQL SQL for: Who was the Mariners opponent at the game attended by 7,893?

CREATE TABLE table_name_49 (opponent VARCHAR, attendance VARCHAR)

SELECT opponent FROM table_name_49 WHERE attendance = '7,893';


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

-- Test functions for control data
SELECT count(*) > 0 AS ok FROM pg_control_checkpoint();

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


Question: What is the most common hashtag used in posts made by users from India?

CREATE TABLE posts (id INT, user_id INT, content TEXT, hashtags TEXT, post_date DATE); INSERT INTO posts (id, user_id, content, hashtags, post_date) VALUES (1, 1, 'Hello World', '#datascience', '2022-06-01'), (2, 1, 'I love data', '#ai', '2022-06-02'), (3, 2, 'Namaste', '#india', '2022-06-03'); CREATE TABLE users (id INT, name VARCHAR(100), country VARCHAR(50)); INSERT INTO users (id, name, country) VALUES (1, 'Akshay', 'India'), (2, 'Bhavna', 'India');

SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(hashtags, ' ', n.n), ' ', -1) hashtag, COUNT(*) count FROM posts JOIN users ON posts.user_id = users.id CROSS JOIN (SELECT 1 n UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5) n WHERE users.country = 'India' GROUP BY hashtag ORDER BY count DESC LIMIT 1;


Question: What was the total revenue for vegan skincare products in the US in Q3 2021?

CREATE TABLE skincare_sales (sale_date DATE, product_vegan BOOLEAN, revenue DECIMAL(10,2)); INSERT INTO skincare_sales (sale_date, product_vegan, revenue) VALUES ('2021-07-01', TRUE, 60.00), ('2021-07-02', FALSE, 50.00);

SELECT SUM(revenue) FROM skincare_sales WHERE product_vegan = TRUE AND sale_date BETWEEN '2021-07-01' AND '2021-09-30';


Question: Generate PostgreSQL SQL for: Who was the partner for the jazz piece in the bottom three?

CREATE TABLE table_name_40 (partner VARCHAR, style VARCHAR, results VARCHAR)

SELECT partner FROM table_name_40 WHERE style = 'jazz' AND results = 'bottom three';


Question: PL/pgSQL test: Plpython Types (example 89).

SELECT * FROM test_type_conversion_array_int4(NULL);

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


Question: Generate PostgreSQL SQL for: Which model number does bombardier manufacture?

CREATE TABLE table_name_28 (model_no VARCHAR, manufacturer VARCHAR)

SELECT model_no FROM table_name_28 WHERE manufacturer = 'bombardier';


Question: List all news articles related to 'corruption' or 'ethics', returning their title, content, and author's name.

CREATE TABLE articles_ext (id INT, title VARCHAR(255), content TEXT, author_id INT); INSERT INTO articles_ext (id, title, content, author_id) VALUES (1, 'Article 1', 'Corruption is...', 1), (2, 'Article 2', 'Ethics in...', 2); CREATE TABLE authors_ext (id INT, name VARCHAR(255)); INSERT INTO authors_ext (id, name) VALUES (1, 'Author 1'), (2, 'Author 2');

SELECT a.title, a.content, au.name FROM articles_ext a JOIN authors_ext au ON a.author_id = au.id WHERE a.title LIKE '%corruption%' OR a.title LIKE '%ethics%' OR a.content LIKE '%corruption%' OR a.content LIKE '%ethics%';


Question: How many deep-sea expeditions have been conducted in the Arctic ocean by research vessels registered in the United States?

CREATE TABLE deep_sea_expeditions (expedition_id INTEGER, ocean TEXT, research_vessel_flag TEXT); CREATE TABLE research_vessels (vessel_id INTEGER, vessel_name TEXT, vessel_flag TEXT);

SELECT COUNT(expedition_id) FROM deep_sea_expeditions JOIN research_vessels ON deep_sea_expeditions.research_vessel_flag = research_vessels.vessel_flag WHERE ocean = 'Arctic' AND research_vessels.vessel_flag = 'United States';


Question: Update the exhibition 'Art of the Indigenous' to extend its duration until the end of 2024.

CREATE TABLE Exhibitions (exhibition_id INT, exhibition_name VARCHAR(50), start_date DATE, end_date DATE); INSERT INTO Exhibitions (exhibition_id, exhibition_name, start_date, end_date) VALUES (1, 'Art of the Indigenous', '2023-01-01', '2023-12-31');

UPDATE Exhibitions SET end_date = '2024-12-31' WHERE exhibition_name = 'Art of the Indigenous';


Question: How many employees have been trained in circular economy principles since the beginning of the program?

CREATE TABLE employee_training (employee_id INT, training_date DATE, topic VARCHAR(50));

SELECT COUNT(*) FROM employee_training WHERE topic = 'Circular Economy';


Question: Generate PostgreSQL SQL for: What was the official ITV1 HD rating in millions for the episode that had an official ITV1 rating of 8.98 million?

CREATE TABLE table_27319183_5 (official_itv1_hd_rating__millions_ VARCHAR, official_itv1_rating__millions_ VARCHAR)

SELECT official_itv1_hd_rating__millions_ FROM table_27319183_5 WHERE official_itv1_rating__millions_ = '8.98';


Question: Use generate_series to create a calendar table for date-based reporting.

SELECT d::date AS calendar_date,
       EXTRACT(dow FROM d) AS day_of_week,
       EXTRACT(week FROM d) AS iso_week,
       to_char(d, 'Month') AS month_name
FROM generate_series('2025-01-01'::date, '2025-12-31'::date, '1 day'::interval) AS d;

Explanation: generate_series with date arguments produces one row per day. Combined with EXTRACT and to_char for reporting dimensions.


Question: What was the average rental duration for adaptive bikes in February 2022?

CREATE TABLE bike_share (bike_id INT, bike_type VARCHAR(255), rental_start_time TIMESTAMP, rental_end_time TIMESTAMP); INSERT INTO bike_share (bike_id, bike_type, rental_start_time, rental_end_time) VALUES (6, 'Adaptive', '2022-02-01 10:00:00', '2022-02-01 12:00:00');

SELECT AVG(TIMESTAMPDIFF(SECOND, rental_start_time, rental_end_time)) AS avg_rental_duration FROM bike_share WHERE bike_type = 'Adaptive' AND rental_start_time >= '2022-02-01' AND rental_start_time < '2022-03-01';


Question: Generate PostgreSQL SQL for: What is the date of the game between Melbourne and Footscray?

CREATE TABLE table_name_78 (date VARCHAR, home_team VARCHAR)

SELECT date FROM table_name_78 WHERE home_team = 'melbourne';


Question: Generate PostgreSQL SQL for: With 14 under the date, what is the tonnage of the ship?

CREATE TABLE table_name_19 (tonnage VARCHAR, date VARCHAR)

SELECT tonnage FROM table_name_19 WHERE date = '14';


Question: Write the DDL statement from PostgreSQL regression test 'gin' (example 2).

create index gin_test_idx on gin_test_tbl using gin (i)
  with (fastupdate = on, gin_pending_list_limit = 4096);

Explanation: DDL from PostgreSQL core regression test for Gin.


Question: Generate PostgreSQL SQL for: How many overs when there are 5231 runs and fewer than 37 matches?

CREATE TABLE table_name_33 (overs INTEGER, runs VARCHAR, matches VARCHAR)

SELECT SUM(overs) FROM table_name_33 WHERE runs = 5231 AND matches < 37;


Question: Generate PostgreSQL SQL for: What is the home team score when st kilda is the away team?

CREATE TABLE table_name_51 (home_team VARCHAR, away_team VARCHAR)

SELECT home_team AS score FROM table_name_51 WHERE away_team = 'st kilda';


Question: Generate PostgreSQL SQL for: what is the attendance when the location is veterans stadium, the game is more than 3 and the time is 2:21?

CREATE TABLE table_name_39 (attendance INTEGER, time VARCHAR, location VARCHAR, game VARCHAR)

SELECT AVG(attendance) FROM table_name_39 WHERE location = 'veterans stadium' AND game > 3 AND time = '2:21';


Question: What is the total playtime of player 'Olivia'?

CREATE TABLE player_sessions (id INT, player_name TEXT, playtime INT); INSERT INTO player_sessions (id, player_name, playtime) VALUES (1, 'Olivia', 120); INSERT INTO player_sessions (id, player_name, playtime) VALUES (2, 'Olivia', 150); INSERT INTO player_sessions (id, player_name, playtime) VALUES (3, 'William', 100);

SELECT SUM(playtime) FROM player_sessions WHERE player_name = 'Olivia';


Question: Generate PostgreSQL SQL for: What is the date with the catalogue # cocy-80093?

CREATE TABLE table_name_37 (date VARCHAR, catalogue__number VARCHAR)

SELECT date FROM table_name_37 WHERE catalogue__number = 'cocy-80093';


Question: What is the number of unique animals in the 'animal_population' table that are not endangered?

CREATE TABLE animal_population (id INT, animal_name VARCHAR(50), population INT, endangered_status VARCHAR(50));

SELECT COUNT(DISTINCT animal_name) FROM animal_population WHERE endangered_status != 'Endangered';


Question: Generate PostgreSQL SQL for: What place is Nolan Henke in?

CREATE TABLE table_name_10 (place VARCHAR, player VARCHAR)

SELECT place FROM table_name_10 WHERE player = 'nolan henke';


Question: Generate PostgreSQL SQL for: What are the different parties of representative? Show the party name and the number of representatives in each party.

CREATE TABLE representative (Party VARCHAR)

SELECT Party, COUNT(*) FROM representative GROUP BY Party;


Question: How many regions have wildlife habitats?

CREATE TABLE regions (region_id INT, region_name TEXT);CREATE TABLE wildlife_habitat (habitat_id INT, region_id INT); INSERT INTO regions (region_id, region_name) VALUES (1, 'Region A'), (2, 'Region B'), (3, 'Region C'); INSERT INTO wildlife_habitat (habitat_id, region_id) VALUES (1, 1), (2, 1), (3, 2), (4, 3), (5, 3);

SELECT region_id, region_name, COUNT(*) FROM regions JOIN wildlife_habitat ON regions.region_id = wildlife_habitat.region_id GROUP BY region_id, region_name HAVING COUNT(*) > 0;


Question: What is the average salary of workers in the workforce development sector, grouped by their job title and region?

CREATE TABLE workers (worker_id INT, sector VARCHAR(255), job_title VARCHAR(255), region VARCHAR(255), salary DECIMAL(10,2)); INSERT INTO workers (worker_id, sector, job_title, region, salary) VALUES (1, 'Workforce Development', 'Engineer', 'North America', 80000.00), (2, 'Workforce Development', 'Technician', 'North America', 50000.00), (3, 'Workforce Development', 'Manager', 'Europe', 90000.00);

SELECT job_title, region, AVG(salary) FROM workers WHERE sector = 'Workforce Development' GROUP BY job_title, region;


Question: Generate PostgreSQL SQL for: Which Manufacturer has a Grid smaller than 9, and a Time of +22.517?

CREATE TABLE table_name_47 (manufacturer VARCHAR, grid VARCHAR, time VARCHAR)

SELECT manufacturer FROM table_name_47 WHERE grid < 9 AND time = '+22.517';


Question: What is the sum of diversity metric scores for companies founded by individuals who identify as disabled in the cybersecurity industry?

CREATE TABLE companies (id INT, name TEXT, industry TEXT, founding_date DATE, founder_identity TEXT, diversity_metric FLOAT); INSERT INTO companies (id, name, industry, founding_date, founder_identity, diversity_metric) VALUES (1, 'CyberSecure', 'Cybersecurity', '2018-01-01', 'Disabled', 0.65);

SELECT SUM(diversity_metric) FROM companies WHERE industry = 'Cybersecurity' AND founder_identity = 'Disabled';


Question: Get the names and number of stories of all buildings in 'buildings' table taller than 300 meters

CREATE TABLE buildings (building_id INT PRIMARY KEY, building_name VARCHAR(100), number_of_stories INT, height FLOAT, country VARCHAR(50));

SELECT building_name, number_of_stories FROM buildings WHERE height > 300;


Question: What is the rank of each defendant's age within their court case?

CREATE TABLE court_cases (case_id INT, court_date DATE); INSERT INTO court_cases (case_id, court_date) VALUES (1, '2022-01-01'), (2, '2021-12-20'), (3, '2022-02-15'); CREATE TABLE defendant_info (defendant_id INT, case_id INT, age INT, gender VARCHAR(50)); INSERT INTO defendant_info (defendant_id, case_id, age, gender) VALUES (1, 1, 35, 'Male'), (2, 2, 27, 'Female'), (3, 1, 42, 'Non-binary'), (4, 3, 19, 'Female'), (5, 3, 50, 'Male'), (6, 1, 32, 'Male');

SELECT defendant_id, case_id, age, ROW_NUMBER() OVER (PARTITION BY case_id ORDER BY age) as age_rank FROM defendant_info;


Question: Identify regulatory frameworks in the US and their respective digital assets.

CREATE TABLE DigitalAssets (AssetId INT, AssetName VARCHAR(50), RegulatorId INT); CREATE TABLE Regulators (RegulatorId INT, RegulatorName VARCHAR(50), Region VARCHAR(50)); INSERT INTO DigitalAssets (AssetId, AssetName, RegulatorId) VALUES (1, 'ETH', 1); INSERT INTO DigitalAssets (AssetId, AssetName, RegulatorId) VALUES (2, 'BTC', 2); INSERT INTO DigitalAssets (AssetId, AssetName, RegulatorId) VALUES (3, 'LTC', 3); INSERT INTO Regulators (RegulatorId, RegulatorName, Region) VALUES (1, 'Regulator1', 'US'); INSERT INTO Regulators (RegulatorId, RegulatorName, Region) VALUES (2, 'Regulator2', 'US'); INSERT INTO Regulators (RegulatorId, RegulatorName, Region) VALUES (3, 'Regulator3', 'Canada');

SELECT da.AssetName, r.RegulatorName FROM DigitalAssets da INNER JOIN Regulators r ON da.RegulatorId = r.RegulatorId WHERE r.Region = 'US';


Question: What is the total volume of wastewater treated in Jakarta in 2019?

CREATE TABLE wastewater_treatment(city VARCHAR(20), year INT, volume INT); INSERT INTO wastewater_treatment(city, year, volume) VALUES ('Jakarta', 2015, 12000), ('Jakarta', 2016, 13000), ('Jakarta', 2017, 14000), ('Jakarta', 2018, 15000), ('Jakarta', 2019, 0);

SELECT SUM(volume) FROM wastewater_treatment WHERE city = 'Jakarta' AND year = 2019;


Question: Generate PostgreSQL SQL for: What stadium was the game played at when the result was hunter mariners def. sheffield eagles?

CREATE TABLE table_name_43 (stadium VARCHAR, result VARCHAR)

SELECT stadium FROM table_name_43 WHERE result = 'hunter mariners def. sheffield eagles';


Question: Generate PostgreSQL SQL for: How many earnings have Wins larger than 3?

CREATE TABLE table_name_70 (earnings___ INTEGER, wins INTEGER)

SELECT SUM(earnings___) AS $__ FROM table_name_70 WHERE wins > 3;


Question: How many traffic accidents were there in each neighborhood in the last 3 months, grouped by day?

CREATE TABLE neighborhoods (id INT, name TEXT);CREATE TABLE accidents (id INT, neighborhood_id INT, date DATE);

SELECT n.name, DATEADD(day, DATEDIFF(day, 0, a.date), 0) AS truncated_date, COUNT(a.id) FROM neighborhoods n JOIN accidents a ON n.id = a.neighborhood_id WHERE a.date >= DATEADD(month, -3, GETDATE()) GROUP BY n.id, truncated_date ORDER BY truncated_date;


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

select split_part('joeuser@mydatabase','@@',1) AS "joeuser@mydatabase";

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

SELECT count(*) FROM (select split_part('joeuser@mydatabase','@@',1) AS "joeuser@mydatabase") AS _sub;


Question: Generate PostgreSQL SQL for: Which republican was first elected in 1886 in the district of ohio 17?

CREATE TABLE table_name_16 (result VARCHAR, district VARCHAR, party VARCHAR, first_elected VARCHAR)

SELECT result FROM table_name_16 WHERE party = 'republican' AND first_elected = '1886' AND district = 'ohio 17';


Question: Generate PostgreSQL SQL for: Which Gold has a Rank larger than 6, and a Nation of netherlands, and a Bronze smaller than 0?

CREATE TABLE table_name_25 (gold INTEGER, bronze VARCHAR, rank VARCHAR, nation VARCHAR)

SELECT SUM(gold) FROM table_name_25 WHERE rank > 6 AND nation = 'netherlands' AND bronze < 0;


Question: What are the unique threat_actors involved in incidents that occurred in the 'Industrial' sector?

CREATE TABLE incidents (id INT, threat_actor VARCHAR(255), incident_type VARCHAR(255), sector VARCHAR(255)); INSERT INTO incidents (id, threat_actor, incident_type, sector) VALUES (1, 'APT28', 'Network Intrusion', 'Financial'), (2, 'APT33', 'Data Exfiltration', 'Industrial'), (3, 'APT34', 'Network Intrusion', 'Government'), (4, 'APT29', 'Data Exfiltration', 'Industrial'), (5, 'APT35', 'Network Intrusion', 'Industrial');

SELECT DISTINCT threat_actor FROM incidents WHERE sector = 'Industrial';


Question: List the names and categories of all projects that were completed in 2020 or earlier and have a budget greater than the average budget for all completed projects.

CREATE TABLE projects (id INT, name VARCHAR(255), category VARCHAR(255), budget FLOAT, year INT, status VARCHAR(255)); INSERT INTO projects (id, name, category, budget, year, status) VALUES (11, 'Traffic Signal Upgrade', 'Transportation', 100000.00, 2019, 'Completed');

SELECT name, category FROM projects WHERE (year <= 2020 OR year IS NULL) AND status = 'Completed' AND budget > (SELECT AVG(budget) FROM projects WHERE status = 'Completed');


Question: Generate PostgreSQL SQL for: What was the lowest lost entry for a team with fewer than 21 goals for?

CREATE TABLE table_name_39 (lost INTEGER, goals_for INTEGER)

SELECT MIN(lost) FROM table_name_39 WHERE goals_for < 21;


Question: Show a query using PostgreSQL contrib extension 'spi' (example 27).

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


Question: Show a SQL definition from the timescaledb project (size_utils, item 8).

-- Get relation size of hypertable
-- like pg_relation_size(hypertable)
--
-- hypertable - hypertable to get size of
--
-- Returns:
-- table_bytes        - Disk space used by hypertable (like pg_relation_size(hypertable))
-- index_bytes        - Disk space used by indexes
-- toast_bytes        - Disk space of toast tables
-- total_bytes        - Total disk space used by the specified table, including all indexes and TOAST data

CREATE OR REPLACE FUNCTION @extschema@.hypertable_detailed_size(
    hypertable              REGCLASS)
RETURNS TABLE (table_bytes BIGINT,
               index_bytes BIGINT,
               toast_bytes BIGINT,
               total_bytes BIGINT,
               node_name   NAME)
LANGUAGE PLPGSQL VOLATILE STRICT AS
$BODY$
DECLARE
        table_name       NAME = NULL;

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


Question: Generate PostgreSQL SQL for: Which Week had a Result of w 23-17?

CREATE TABLE table_name_58 (week INTEGER, result VARCHAR)

SELECT SUM(week) FROM table_name_58 WHERE result = 'w 23-17';


Question: Generate PostgreSQL SQL for: What is the points when played is less than 38?

CREATE TABLE table_name_6 (points INTEGER, played INTEGER)

SELECT SUM(points) FROM table_name_6 WHERE played < 38;


Question: List the names and locations of Europium producers that started production after 2015.

CREATE TABLE europium_production (producer_id INT PRIMARY KEY, name VARCHAR(255), location VARCHAR(255), start_year INT);

SELECT name, location FROM europium_production WHERE start_year > 2015;


Question: Generate PostgreSQL SQL for: Who has the low lap total in a maserati with grid 2?

CREATE TABLE table_name_47 (laps INTEGER, constructor VARCHAR, grid VARCHAR)

SELECT MIN(laps) FROM table_name_47 WHERE constructor = 'maserati' AND grid = 2;


Question: Generate PostgreSQL SQL for: Who was the constructor of car 22?

CREATE TABLE table_15491596_1 (constructor VARCHAR, no VARCHAR)

SELECT constructor FROM table_15491596_1 WHERE no = 22;


Question: What is the total billing amount for cases in Texas handled by attorneys who have passed the bar exam in that state?

CREATE TABLE attorneys (attorney_id INT, name TEXT, state TEXT, passed_bar_exam_tx BOOLEAN); INSERT INTO attorneys (attorney_id, name, state, passed_bar_exam_tx) VALUES (1, 'Jane Doe', 'Texas', TRUE), (2, 'John Smith', 'California', FALSE), (3, 'Sara Connor', 'Texas', TRUE), (4, 'Tom Williams', 'New York', FALSE); CREATE TABLE cases (case_id INT, attorney_id INT, billing_amount INT, state TEXT); INSERT INTO cases (case_id, attorney_id, billing_amount, state) VALUES (1, 1, 10000, 'Texas'), (2, 2, 8000, 'California'), (3, 3, 15000, 'Texas'), (4, 4, 6000, 'New York');

SELECT SUM(cases.billing_amount) FROM cases INNER JOIN attorneys ON cases.attorney_id = attorneys.attorney_id WHERE attorneys.passed_bar_exam_tx = TRUE AND cases.state = attorneys.state;


Question: How many unique donors have donated to programs related to Children's Welfare in total?

CREATE TABLE Donors (DonorID INT, DonorName TEXT); CREATE TABLE Donations (DonationID INT, DonorID INT, ProgramID INT); CREATE TABLE Programs (ProgramID INT, ProgramName TEXT); INSERT INTO Donors (DonorID, DonorName) VALUES (1, 'Anna'), (2, 'Bella'), (3, 'Charlie'); INSERT INTO Donations (DonationID, DonorID, ProgramID) VALUES (1, 1, 1), (2, 1, 2), (3, 2, 2), (4, 3, 3); INSERT INTO Programs (ProgramID, ProgramName) VALUES (1, 'Children''s Education'), (2, 'Children''s Health'), (3, 'Women''s Rights');

SELECT COUNT(DISTINCT d.DonorID) FROM Donations d JOIN Programs p ON d.ProgramID = p.ProgramID WHERE p.ProgramName LIKE '%Children%';


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

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

SELECT count(*) FROM (SELECT not bool 'f' AS true) AS _sub;


Question: What's the total donation amount for each program in Q4 2022, only for programs with more than 500 participants?

CREATE TABLE programs_q4_2022 (id INT, program_name VARCHAR(50), participants INT, donation_amount DECIMAL(10,2)); INSERT INTO programs_q4_2022 (id, program_name, participants, donation_amount) VALUES (1, 'Program M', 600, 8000.00), (2, 'Program N', 400, 7000.00), (3, 'Program O', 800, 9000.00), (4, 'Program P', 300, 6000.00), (5, 'Program Q', 700, 10000.00);

SELECT program_name, SUM(donation_amount) as total_donation FROM programs_q4_2022 WHERE participants > 500 GROUP BY program_name;


Question: Write the DDL statement from PostgreSQL regression test 'foreign_key' (example 759).

create table other_partitioned_fk_1 partition of other_partitioned_fk
  for values in (2048);

Explanation: DDL from PostgreSQL core regression test for Foreign Key.


Question: Generate PostgreSQL SQL for: What is the date of the game when the venue is Princes Park?

CREATE TABLE table_name_40 (date VARCHAR, venue VARCHAR)

SELECT date FROM table_name_40 WHERE venue = 'princes park';


Question: Which artists have had concerts in both New York and Los Angeles?

CREATE TABLE concerts (id INT, artist_name VARCHAR(255), city VARCHAR(255), revenue FLOAT); INSERT INTO concerts (id, artist_name, city, revenue) VALUES (1, 'Taylor Swift', 'Los Angeles', 500000.00), (2, 'BTS', 'New York', 750000.00), (3, 'Adele', 'London', 600000.00), (4, 'Taylor Swift', 'New York', 600000.00);

SELECT artist_name FROM concerts WHERE city IN ('New York', 'Los Angeles') GROUP BY artist_name HAVING COUNT(DISTINCT city) = 2;


Question: Generate PostgreSQL SQL for: What status has paleopanax as the name?

CREATE TABLE table_name_78 (status VARCHAR, name VARCHAR)

SELECT status FROM table_name_78 WHERE name = 'paleopanax';


Question: Write the DDL statement from PostgreSQL regression test 'eager_aggregate' (example 84).

CREATE TABLE eager_agg_tab_ml_p2_s1 PARTITION OF eager_agg_tab_ml_p2 FOR VALUES FROM (10) TO (15);

Explanation: DDL from PostgreSQL core regression test for Eager Aggregate.


Question: Generate PostgreSQL SQL for: Which Oricon has a Romaji title of nakitakunalu?

CREATE TABLE table_name_17 (oricon INTEGER, romaji_title VARCHAR)

SELECT MAX(oricon) FROM table_name_17 WHERE romaji_title = 'nakitakunalu';


Question: Generate PostgreSQL SQL for: Which opponent has a Date of april 14?

CREATE TABLE table_name_20 (opponent VARCHAR, date VARCHAR)

SELECT opponent FROM table_name_20 WHERE date = 'april 14';


Question: What is the distribution of customer complaints by region in the past month?

CREATE TABLE customer_complaints (complaint_id INT, complaint_type VARCHAR(50), region VARCHAR(50), complaint_date DATE); INSERT INTO customer_complaints (complaint_id, complaint_type, region, complaint_date) VALUES (1, 'Billing', 'San Francisco', '2021-03-01'), (2, 'Network', 'San Francisco', '2021-03-05'), (3, 'Billing', 'New York', '2021-03-10'), (4, 'Billing', 'Los Angeles', '2021-03-15');

SELECT region, complaint_type, COUNT(*) as complaints, PERCENT_RANK() OVER (PARTITION BY region ORDER BY complaints DESC) as complaint_percentile FROM customer_complaints WHERE complaint_date >= DATEADD(month, -1, CURRENT_DATE) GROUP BY region, complaint_type;


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

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

SELECT count(*) FROM (SELECT '92233720368547758.07'::money::numeric) AS _sub;


Question: Write the DML statement from PostgreSQL regression test 'brin_bloom' (example 54).

INSERT INTO brintest_bloom SELECT
	repeat(stringu1, 42)::bytea,
	substr(stringu1, 1, 1)::"char",
	stringu1::name, 142857 * tenthous,
	thousand,
	twothousand,
	repeat(stringu1, 42),
	unique1::oid,
	(four + 1.0)/(hundred+1),
	odd::float8 / (tenthous + 1),
	format('%s:00:%s:00:%s:00', to_hex(odd), to_hex(even), to_hex(hundred))::macaddr,
	inet '10.2.3.4' + tenthous,
	cidr '10.2.3/24' + tenthous,
	substr(stringu1, 1, 1)::bpchar,
	date '1995-08-15' + tenthous,
	time '01:20:30' + thousand * interval '18.5 second',
	timestamp '1942-07-23 03:05:09' + tenthous * interval '36.38 hours',
	timestamptz '1972-10-10 03:00' + thousand * interval '1 hour',
	justify_days(justify_hours(tenthous * interval '12 minutes')),
	timetz '01:30:20' + hundred * interval '15 seconds',
	tenthous::numeric(36,30) * fivethous * even / (hundred + 1),
	format('%s%s-%s-%s-%s-%s%s%s', to_char(tenthous, 'FM0000'), to_char(tenthous, 'FM0000'), to_char(tenthous, 'FM0000'), to_char(tenthous, 'FM0000'), to_char(tenthous, 'FM0000'), to_char(tenthous, 'FM0000'), to_char(tenthous, 'FM0000'), to_char(tenthous, 'FM0000'))::uuid,
	format('%s/%s%s', odd, even, tenthous)::pg_lsn
FROM tenk1 ORDER BY unique2 LIMIT 5 OFFSET 5;

Explanation: DML from PostgreSQL core regression test for Brin Bloom.


Question: Generate PostgreSQL SQL for: What is Place, when Player is "Phil Mickelson"?

CREATE TABLE table_name_17 (place VARCHAR, player VARCHAR)

SELECT place FROM table_name_17 WHERE player = 'phil mickelson';


Question: Insert new records for mobile subscribers with their respective data usage in the North region.

CREATE TABLE mobile_subscribers_3 (subscriber_id INT, data_usage FLOAT, region VARCHAR(20)); INSERT INTO mobile_subscribers_3 (subscriber_id, data_usage, region) VALUES (7, 22.6, 'North'), (8, 29.8, 'North'), (9, 20.1, 'North');

INSERT INTO mobile_subscribers SELECT * FROM mobile_subscribers_3 WHERE region = 'North';


Question: Generate PostgreSQL SQL for: Who is the Driver on Bob Keselowski's team?

CREATE TABLE table_name_57 (driver_s_ VARCHAR, owner_s_ VARCHAR)

SELECT driver_s_ FROM table_name_57 WHERE owner_s_ = 'bob keselowski';


Question: Generate PostgreSQL SQL for: What are the fewest wickets when player's career spanned 1946-1960 and maidens were more than 419?

CREATE TABLE table_name_84 (wickets INTEGER, career VARCHAR, maidens VARCHAR)

SELECT MIN(wickets) FROM table_name_84 WHERE career = '1946-1960' AND maidens > 419;


Question: Generate PostgreSQL SQL for: Which Region that has a growth of −3.6%?

CREATE TABLE table_name_24 (region VARCHAR, _percentage_growth VARCHAR)

SELECT region FROM table_name_24 WHERE _percentage_growth = '−3.6';


Question: Which users have played all games in the 'gaming' database?

SELECT user_id FROM users_games_2 GROUP BY user_id HAVING COUNT(DISTINCT game_id) = (SELECT COUNT(DISTINCT game_id) FROM users_games_2);


Question: What is the average completion time for sustainable building projects in Washington?

CREATE TABLE project_timelines (id INT, project_id INT, project_type TEXT, completion_date DATE); INSERT INTO project_timelines (id, project_id, project_type, completion_date) VALUES (1, 111, 'Sustainable', '2022-10-01'), (2, 222, 'Sustainable', '2022-11-15'), (3, 333, 'Conventional', '2022-09-30');

SELECT AVG(DATEDIFF(completion_date, issue_date)) FROM building_permits bp JOIN project_timelines pt ON bp.permit_number = pt.project_id WHERE bp.project_state = 'Washington' AND pt.project_type = 'Sustainable';


Question: List the names and daily transaction counts of all digital assets on the 'Solana' blockchain.

CREATE TABLE crypto_assets (asset_id INT, asset_name VARCHAR(50), blockchain_id INT, daily_transactions INT); INSERT INTO crypto_assets (asset_id, asset_name, blockchain_id, daily_transactions) VALUES (1, 'Solana Token', 2, 10000); INSERT INTO crypto_assets (asset_id, asset_name, blockchain_id, daily_transactions) VALUES (2, 'Serum', 2, 8000); INSERT INTO blockchains (blockchain_id, blockchain_name) VALUES (2, 'Solana');

SELECT crypto_assets.asset_name, crypto_assets.daily_transactions FROM crypto_assets INNER JOIN blockchains ON crypto_assets.blockchain_id = blockchains.blockchain_id WHERE blockchains.blockchain_name = 'Solana';


Question: Show a SQL definition from the timescaledb project (drop_schema, item 10).

CREATE TABLE hypertable_schema.test2 (time timestamptz, temp float, location int);


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

SELECT name, 'A' = name AS "eq_A" FROM try WHERE name <> 'â';

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


Question: What is the average response time for emergency calls in the "downtown" region?

CREATE TABLE EmergencyCalls (id INT, region VARCHAR(20), response_time INT);

SELECT AVG(response_time) FROM EmergencyCalls WHERE region = 'downtown';


Question: What is the total number of donations and the total donation amount for each month in the year 2020?

CREATE TABLE DonationHistory (DonationID int, DonationDate date); INSERT INTO DonationHistory (DonationID, DonationDate) VALUES (1, '2020-01-01'), (2, '2020-02-01'), (3, '2020-03-01'); CREATE TABLE Donations (DonationID int, DonationAmount numeric); INSERT INTO Donations (DonationID, DonationAmount) VALUES (1, 500), (2, 1200), (3, 250);

SELECT EXTRACT(MONTH FROM DonationDate) as Month, COUNT(*) as NumDonations, SUM(DonationAmount) as TotalDonationAmount FROM DonationHistory JOIN Donations ON DonationHistory.DonationID = Donations.DonationID WHERE EXTRACT(YEAR FROM DonationDate) = 2020 GROUP BY Month;


Question: What is the total playtime (in minutes) for each game in the "MobileGamingCommunity"?

CREATE TABLE Games (GameID INT PRIMARY KEY, GameName VARCHAR(50), GamingCommunity VARCHAR(50)); CREATE TABLE GameSessions (SessionID INT PRIMARY KEY, GameName VARCHAR(50), Playtime MINUTE, FOREIGN KEY (GameName) REFERENCES Games(GameName)); INSERT INTO Games (GameID, GameName, GamingCommunity) VALUES (1, 'ClashOfClans', 'MobileGamingCommunity'), (2, 'PUBGMobile', 'MobileGamingCommunity'), (3, 'FortniteMobile', 'MobileGamingCommunity'); INSERT INTO GameSessions (SessionID, GameName, Playtime) VALUES (1, 'ClashOfClans', 120), (2, 'ClashOfClans', 150), (3, 'PUBGMobile', 200), (4, 'FortniteMobile', 250);

SELECT GameName, SUM(Playtime) FROM GameSessions JOIN Games ON GameSessions.GameName = Games.GameName WHERE Games.GamingCommunity = 'MobileGamingCommunity' GROUP BY GameName;


Question: What is the average economic diversification investment in the 'economic_diversification' schema?

CREATE TABLE economic_diversification.investments (id INT, investment_type VARCHAR(50), amount FLOAT); INSERT INTO economic_diversification.investments (id, investment_type, amount) VALUES (1, 'Renewable Energy', 500000), (2, 'Tourism', 750000), (3, 'Manufacturing', 1000000);

SELECT AVG(amount) FROM economic_diversification.investments;


Question: Generate PostgreSQL SQL for: Who's captain of the team whose stadium has a capacity of 17800 people?

CREATE TABLE table_23214833_1 (team_captain VARCHAR, capacity VARCHAR)

SELECT team_captain FROM table_23214833_1 WHERE capacity = 17800;


Question: Find the average safety score for each vehicle model in a specific country.

CREATE TABLE Vehicle_Models (model_id INT, model VARCHAR(50), country_id INT); INSERT INTO Vehicle_Models (model_id, model, country_id) VALUES (1001, 'Tesla Model 3', 1); CREATE TABLE Safety_Tests (test_id INT, model_id INT, result INT, test_type VARCHAR(50)); INSERT INTO Safety_Tests (test_id, model_id, result, test_type) VALUES (1, 1001, 95, 'Crash Test'); CREATE TABLE Country (country_id INT, country_name VARCHAR(50)); INSERT INTO Country (country_id, country_name) VALUES (1, 'USA');

SELECT vm.model, AVG(st.result) as "Average Safety Score" FROM Vehicle_Models vm JOIN Safety_Tests st ON vm.model_id = st.model_id JOIN Country c ON vm.country_id = c.country_id WHERE c.country_name = 'USA' GROUP BY vm.model;


Question: Find the policyholder with the highest claim amount in the 'Low Risk' underwriting group.

CREATE TABLE underwriting (id INT, group VARCHAR(10), name VARCHAR(20), claim_amount DECIMAL(10,2)); INSERT INTO underwriting (id, group, name, claim_amount) VALUES (1, 'High Risk', 'John Doe', 5000.00), (2, 'Low Risk', 'Jane Smith', 2500.00), (3, 'High Risk', 'Mike Johnson', 7000.00), (4, 'Low Risk', 'Emma White', 3000.00);

SELECT name, claim_amount FROM (SELECT name, claim_amount, ROW_NUMBER() OVER (PARTITION BY group ORDER BY claim_amount DESC) rn FROM underwriting WHERE group = 'Low Risk') sub WHERE rn = 1;


Question: Generate PostgreSQL SQL for: Which Position  has a Level of tier 3 and a Season smaller than 1999?

CREATE TABLE table_name_38 (position VARCHAR, level VARCHAR, season VARCHAR)

SELECT position FROM table_name_38 WHERE level = 'tier 3' AND season < 1999;


Question: What is the average salary for workers in the 'service_database' database who are members of a union and work in the 'cleaning' department?

CREATE TABLE cleaners (id INT, name VARCHAR(50), salary DECIMAL(10, 2), is_union_member BOOLEAN, department VARCHAR(50)); INSERT INTO cleaners (id, name, salary, is_union_member, department) VALUES (1, 'Olivia', 90000.00, true, 'cleaning'), (2, 'Owen', 95000.00, true, 'cleaning'), (3, 'Olga', 80000.00, true, 'management');

SELECT AVG(salary) FROM cleaners WHERE is_union_member = true AND department = 'cleaning';


Question: Identify the number of sustainable tourism initiatives implemented in the 'Americas' region by year.

CREATE TABLE sustainable_tourism (id INT, initiative_name VARCHAR(100), region VARCHAR(50), implementation_year INT); INSERT INTO sustainable_tourism (id, initiative_name, region, implementation_year) VALUES (1, 'Green Lodging', 'Americas', 2018), (2, 'Solar-Powered Sightseeing', 'Europe', 2020);

SELECT implementation_year, COUNT(*) as num_initiatives FROM sustainable_tourism WHERE region = 'Americas' GROUP BY implementation_year;


Question: Generate PostgreSQL SQL for: What was the name of the couple if the number of dances is 6?

CREATE TABLE table_23662272_4 (couple VARCHAR, number_of_dances VARCHAR)

SELECT couple FROM table_23662272_4 WHERE number_of_dances = 6;


Question: Generate PostgreSQL SQL for: Which player has 17 blocks?

CREATE TABLE table_24912693_4 (player VARCHAR, blocks VARCHAR)

SELECT player FROM table_24912693_4 WHERE blocks = 17;


Question: What is the total number of workers in the 'Hospitality' industry who are part of a union?

CREATE TABLE workers (id INT, industry VARCHAR(255), salary FLOAT, union_member BOOLEAN); INSERT INTO workers (id, industry, salary, union_member) VALUES (1, 'Manufacturing', 50000.0, true), (2, 'Hospitality', 40000.0, true), (3, 'Retail', 30000.0, false);

SELECT COUNT(*) FROM workers WHERE industry = 'Hospitality' AND union_member = true;


Question: Write the DDL statement from PostgreSQL regression test 'brin_bloom' (example 73).

CREATE INDEX brin_test_bloom_b_idx ON brin_test_bloom USING brin (b) WITH (pages_per_range = 2);

Explanation: DDL from PostgreSQL core regression test for Brin Bloom.


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

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

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


Question: What is the total balance of clients with investment accounts in the San Francisco branch?

CREATE TABLE clients (client_id INT, name TEXT, dob DATE, branch TEXT);CREATE TABLE accounts (account_id INT, client_id INT, account_type TEXT, balance DECIMAL);INSERT INTO clients VALUES (5, 'Charlie Brown', '1998-07-03', 'San Francisco');INSERT INTO accounts VALUES (105, 5, 'Investment', 15000);

SELECT SUM(accounts.balance) FROM clients INNER JOIN accounts ON clients.client_id = accounts.client_id WHERE accounts.account_type = 'Investment' AND clients.branch = 'San Francisco';


Question: Generate PostgreSQL SQL for: What city did Yugoslavia play Norway in?

CREATE TABLE table_name_2 (city VARCHAR, opponent VARCHAR)

SELECT city FROM table_name_2 WHERE opponent = 'norway';


Question: Generate PostgreSQL SQL for: What is the Game on May 24 with Road Team Seattle?

CREATE TABLE table_name_76 (game VARCHAR, road_team VARCHAR, date VARCHAR)

SELECT game FROM table_name_76 WHERE road_team = 'seattle' AND date = 'may 24';


Question: What are the wholesale orders with a payment amount greater than $500 for the current month, and their corresponding payment dates?

CREATE TABLE wholesale_orders (id INT PRIMARY KEY, dispensary_id INT, strain_id INT, quantity INT, order_date DATE); CREATE TABLE wholesale_payments (id INT PRIMARY KEY, order_id INT, payment_amount FLOAT, payment_date DATE);

SELECT wholesale_orders.dispensary_id, wholesale_orders.order_date, wholesale_payments.payment_amount, wholesale_payments.payment_date FROM wholesale_orders INNER JOIN wholesale_payments ON wholesale_orders.id = wholesale_payments.order_id WHERE wholesale_payments.payment_date BETWEEN DATE_SUB(CURRENT_DATE, INTERVAL DAY(CURRENT_DATE) - 1 DAY) AND CURRENT_DATE AND wholesale_payments.payment_amount > 500;


Question: Generate PostgreSQL SQL for: What is the sum of the pick in round 17?

CREATE TABLE table_name_10 (pick INTEGER, round VARCHAR)

SELECT SUM(pick) FROM table_name_10 WHERE round = 17;


Question: What is the total revenue generated by cultural heritage tours in Italy in the last quarter?

CREATE TABLE tours (tour_id INT, tour_name TEXT, country TEXT, revenue FLOAT, tour_date DATE); INSERT INTO tours (tour_id, tour_name, country, revenue, tour_date) VALUES (1, 'Roman Colosseum Tour', 'Italy', 10000.00, '2022-01-01'); INSERT INTO tours (tour_id, tour_name, country, revenue, tour_date) VALUES (2, 'Florence Uffizi Gallery Tour', 'Italy', 8000.00, '2022-03-15'); INSERT INTO tours (tour_id, tour_name, country, revenue, tour_date) VALUES (3, 'Roman Colosseum Tour', 'Italy', 12000.00, '2022-04-01');

SELECT SUM(revenue) FROM tours WHERE country = 'Italy' AND tour_date >= '2022-01-01' AND tour_date < '2022-04-01';


Question: PostgreSQL Perform: show example 25.

EXPLAIN SELECT * FROM tenk1 t1, tenk2 t2 WHERE t1.unique1 < 10 AND t2.unique2 < 10 AND t1.hundred < t2.hundred; QUERY PLAN -------------------------------------------------------------------&zwsp;-------------------------- Nested Loop (cost=4.65..49.36 rows=33 width=488) Join Filter: (t1.hundred < t2.hundred) -> Bitmap Heap Scan on tenk1 t1 (cost=4.36..39.38 rows=10 width=244) Recheck Cond: (unique1 < 10) -> Bitmap Index Scan on tenk1_unique1 (cost=0.00..4.36 rows=10 width=0) Index Cond: (unique1 < 10) -> Materialize (cost=0.29..8.51 rows=10 width=244) -> Index Scan using tenk2_unique2 on tenk2 t2 (cost=0.29..8.46 rows=10 width=244) Index Cond: (unique2 < 10);

Explanation: Example from PostgreSQL documentation on Perform.


Question: What is the average carbon offset (in metric tons) for carbon offset programs in Europe that were initiated in 2018?

CREATE TABLE if not exists carbon_offset_programs (program_id integer, program_start_date date, program_location varchar(255), carbon_offset_tons integer); INSERT INTO carbon_offset_programs (program_id, program_start_date, program_location, carbon_offset_tons) VALUES (1, '2018-01-01', 'France', 2000), (2, '2018-06-01', 'Germany', 2500), (3, '2018-12-31', 'Spain', 1500);

SELECT program_location, AVG(carbon_offset_tons) as avg_offset FROM carbon_offset_programs WHERE program_start_date BETWEEN '2018-01-01' AND '2018-12-31' AND program_location LIKE 'Europe%' GROUP BY program_location;


Question: Generate PostgreSQL SQL for: What was the surface tye during the match with the opponent of richard fromberg?

CREATE TABLE table_name_3 (surface VARCHAR, opponent VARCHAR)

SELECT surface FROM table_name_3 WHERE opponent = 'richard fromberg';


Question: How many military bases are located in each state in the 'military_bases' and 'states' tables?

CREATE TABLE states (state_id INT, state_name VARCHAR(50)); CREATE TABLE military_bases (base_id INT, base_name VARCHAR(50), state_id INT); INSERT INTO states VALUES (1, 'Alabama'), (2, 'Alaska'), (3, 'Arizona'); INSERT INTO military_bases VALUES (1, 'Fort Rucker', 1), (2, 'Fort Wainwright', 2), (3, 'Fort Huachuca', 3);

SELECT s.state_name, COUNT(m.base_id) as bases_in_state FROM states s JOIN military_bases m ON s.state_id = m.state_id GROUP BY s.state_name;


Question: Generate PostgreSQL SQL for: Switzerland has how many gold and less than 0 silver?

CREATE TABLE table_name_61 (gold INTEGER, nation VARCHAR, silver VARCHAR)

SELECT MAX(gold) FROM table_name_61 WHERE nation = 'switzerland' AND silver < 0;


Question: Generate PostgreSQL SQL for: How many characteristics does the product named "sesame" have?

CREATE TABLE product_characteristics (product_id VARCHAR); CREATE TABLE products (product_id VARCHAR, product_name VARCHAR)

SELECT COUNT(*) FROM products AS t1 JOIN product_characteristics AS t2 ON t1.product_id = t2.product_id WHERE t1.product_name = 'sesame';


Question: How many gold medals were won in total in the last 3 Summer Olympics?

CREATE TABLE olympics (year INT, season VARCHAR(50), total_gold INT); INSERT INTO olympics VALUES (2021, 'Summer', 307), (2018, 'Winter', 106), (2020, 'Summer', 339);

SELECT SUM(total_gold) FROM olympics WHERE season = 'Summer' AND year IN (2016, 2018, 2020);


Question: what is the average duration of education programs in the 'community_education' table?

CREATE TABLE community_education (education_id INT, education_name VARCHAR(50), start_date DATE, end_date DATE); INSERT INTO community_education (education_id, education_name, start_date, end_date) VALUES (1, 'Animal Tracking', '2021-01-01', '2021-12-31'), (2, 'Habitat Conservation', '2021-04-01', '2021-12-31'), (3, 'Wildlife Photography', '2021-07-01', '2021-10-31');

SELECT AVG(DATEDIFF(end_date, start_date)) FROM community_education;


Question: Generate PostgreSQL SQL for: Which School has a Previous Conference of none (new school), and a Year Joined larger than 1960, and a Location of versailles?

CREATE TABLE table_name_78 (school VARCHAR, location VARCHAR, previous_conference VARCHAR, year_joined VARCHAR)

SELECT school FROM table_name_78 WHERE previous_conference = 'none (new school)' AND year_joined > 1960 AND location = 'versailles';


Question: Generate PostgreSQL SQL for: When the game was played at Mile High Stadium before week 9, what was the result?

CREATE TABLE table_name_87 (result VARCHAR, week VARCHAR, game_site VARCHAR)

SELECT result FROM table_name_87 WHERE week < 9 AND game_site = 'mile high stadium';


Question: Generate PostgreSQL SQL for: Which Office has a Representative of scott pelath?

CREATE TABLE table_name_81 (office VARCHAR, representative VARCHAR)

SELECT office FROM table_name_81 WHERE representative = 'scott pelath';


Question: Generate PostgreSQL SQL for: Show the county name and population of all counties.

CREATE TABLE county (County_name VARCHAR, Population VARCHAR)

SELECT County_name, Population FROM county;


Question: Generate PostgreSQL SQL for: What's the air date of part 1 of the episode whose part 2 aired on December 2, 2007?

CREATE TABLE table_13241993_3 (part_1 VARCHAR, part_2 VARCHAR)

SELECT part_1 FROM table_13241993_3 WHERE part_2 = 'December 2, 2007';


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

INSERT INTO textrange_test VALUES('[,"q")');

Explanation: DML from PostgreSQL core regression test for Rangetypes.


Question: Generate PostgreSQL SQL for: Name the least attendance with visitor of edmonton

CREATE TABLE table_name_98 (attendance INTEGER, visitor VARCHAR)

SELECT MIN(attendance) FROM table_name_98 WHERE visitor = 'edmonton';


Question: Generate PostgreSQL SQL for: Game Site of hoosier dome, and a Result of l 7–31 involved what attendance?

CREATE TABLE table_name_29 (attendance VARCHAR, game_site VARCHAR, result VARCHAR)

SELECT attendance FROM table_name_29 WHERE game_site = 'hoosier dome' AND result = 'l 7–31';


Question: What is the total number of satellites in orbit around Earth?

CREATE TABLE SatelliteOrbits (SatelliteID INT, Name VARCHAR(100), Orbit VARCHAR(50));

SELECT COUNT(*) FROM SatelliteOrbits WHERE Orbit = 'Earth';


Question: Generate PostgreSQL SQL for: In 2008, what was the world ranking that ranked 5th in L.A.?

CREATE TABLE table_name_54 (world_ranking__1_ VARCHAR, ranking_la__2_ VARCHAR, year_of_publication VARCHAR)

SELECT world_ranking__1_ FROM table_name_54 WHERE ranking_la__2_ = '5th' AND year_of_publication = '2008';


Question: What is the average citizen feedback score for transportation services in the South region in 2022?

CREATE TABLE Feedback (Year INT, Service VARCHAR(255), Region VARCHAR(255), Score DECIMAL(3,2)); INSERT INTO Feedback (Year, Service, Region, Score) VALUES (2022, 'Bus', 'South', 8.25), (2022, 'Train', 'South', 8.50), (2022, 'Taxi', 'South', 8.75);

SELECT AVG(Score) FROM Feedback WHERE Year = 2022 AND Region = 'South' AND Service IN ('Bus', 'Train');


Question: PL/pgSQL test: Plpgsql Array (example 14).

do $$ declare a int[] := array[1,2,3];
begin
  -- test scenarios for optimization of updates of R/W expanded objects
  a := array_append(a, 42);  -- optimizable using "transfer" method
  a := a || a[3];  -- optimizable using "inplace" method
  a := a[1] || a;  -- ditto, but let's test array_prepend
  a := a || a;     -- not optimizable
  raise notice 'a = %', a;
end$$;

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


Question: What is the number of employees hired in the last 12 months by department?

CREATE TABLE EmployeeHire (HireID INT, HireDate DATE, Department VARCHAR(20)); INSERT INTO EmployeeHire (HireID, HireDate, Department) VALUES (1, '2022-01-01', 'IT'), (2, '2022-02-01', 'HR'), (3, '2022-03-01', 'Marketing'), (4, '2021-04-01', 'IT');

SELECT Department, COUNT(*) FROM EmployeeHire WHERE HireDate >= DATEADD(month, -12, GETDATE()) GROUP BY Department;


Question: Generate PostgreSQL SQL for: Which Position has Goals against larger than 32, and points larger than 30?

CREATE TABLE table_name_22 (position VARCHAR, goals_against VARCHAR, points VARCHAR)

SELECT position FROM table_name_22 WHERE goals_against > 32 AND points > 30;


Question: What is the change in mental health score from the beginning to the end of the school year for each student?

CREATE TABLE student_mental_health_year (student_id INT, date DATE, score INT);

SELECT student_id, LAG(score) OVER (PARTITION BY student_id ORDER BY date) as beginning_score, score as end_score, score - LAG(score) OVER (PARTITION BY student_id ORDER BY date) as change FROM student_mental_health_year WHERE EXTRACT(MONTH FROM date) IN (5, 6, 7) AND EXTRACT(YEAR FROM date) = 2022;


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

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

SELECT count(*) FROM (SELECT ts_lexize('hunspell', 'unbooking')) AS _sub;


Question: Insert new sustainable fabric 'Piñatex' with a sustainability rating of 4.6 and production cost of 3.5.

CREATE TABLE fabrics (id INT, name VARCHAR(255), sustainability_rating FLOAT, production_cost FLOAT);

INSERT INTO fabrics (name, sustainability_rating, production_cost) VALUES ('Piñatex', 4.6, 3.5);


Question: What is the maximum price of organic skincare products in France?

CREATE TABLE skincare (id INT, name TEXT, price DECIMAL, is_organic BOOLEAN, country TEXT); INSERT INTO skincare (id, name, price, is_organic, country) VALUES (1, 'Cleanser', 19.99, true, 'France'); INSERT INTO skincare (id, name, price, is_organic, country) VALUES (2, 'Toner', 15.99, true, 'France'); INSERT INTO skincare (id, name, price, is_organic, country) VALUES (3, 'Moisturizer', 29.99, true, 'France');

SELECT MAX(price) FROM skincare WHERE is_organic = true AND country = 'France';


Question: What is the earliest delivery date for each type of military equipment?

CREATE TABLE EquipmentDeliveries (DeliveryID INT, Equipment VARCHAR(50), Quantity INT, DeliveryDate DATE); INSERT INTO EquipmentDeliveries (DeliveryID, Equipment, Quantity, DeliveryDate) VALUES (7, 'Tanks', 5, '2022-06-30'); INSERT INTO EquipmentDeliveries (DeliveryID, Equipment, Quantity, DeliveryDate) VALUES (8, 'Artillery', 3, '2023-02-14');

SELECT Equipment, MIN(DeliveryDate) AS EarliestDeliveryDate FROM EquipmentDeliveries GROUP BY Equipment;


Question: PostgreSQL regression test 'rangetypes': Write the SELECT query (example 20).

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

SELECT count(*) FROM (select '[",",","]'::textrange) AS _sub;


Question: Which electric vehicle models have the highest safety ratings?

CREATE TABLE SafetyRatings (Model VARCHAR(50), Rating INT); INSERT INTO SafetyRatings (Model, Rating) VALUES ('Tesla Model 3', 5), ('Chevrolet Bolt', 5), ('Nissan Leaf', 4);

SELECT Model, Rating FROM SafetyRatings ORDER BY Rating DESC;


Question: pgTAP test for Runtests (assertion 12).

CREATE OR REPLACE FUNCTION whatever.shutdownmore() RETURNS SETOF TEXT AS $$
    SELECT pass('shutting down more');
$$ LANGUAGE SQL;

Explanation: SQL assertion from pgTAP test suite for Runtests.


Question: What is the total wastewater treatment capacity in Ghana in cubic meters?

CREATE TABLE wastewater_treatment_m3 (country VARCHAR(20), region VARCHAR(20), value FLOAT); INSERT INTO wastewater_treatment_m3 (country, region, value) VALUES ('Ghana', NULL, 2000000);

SELECT value FROM wastewater_treatment_m3 WHERE country = 'Ghana';


Question: Generate PostgreSQL SQL for: What is the high score for the player with 0 stumps, 4 catches, more than 14 inns and an average smaller than 56.1?

CREATE TABLE table_name_52 (high_score INTEGER, inns VARCHAR, average VARCHAR, stump VARCHAR, catches VARCHAR)

SELECT SUM(high_score) FROM table_name_52 WHERE stump = 0 AND catches = 4 AND average < 56.1 AND inns > 14;


Question: What is the average price of products in the Natural category, ranked by average price in descending order?

CREATE TABLE products (product_id INT, category VARCHAR(20), price DECIMAL(5,2)); INSERT INTO products (product_id, category, price) VALUES (1, 'Natural', 25.99), (2, 'Organic', 30.49), (3, 'Natural', 29.99), (4, 'Conventional', 15.99);

SELECT AVG(price) as avg_price, category FROM products GROUP BY category ORDER BY avg_price DESC;


Question: Generate PostgreSQL SQL for: state the number of location attendance where record is 15–10 (5–7)

CREATE TABLE table_20010140_10 (location_attendance VARCHAR, record VARCHAR)

SELECT COUNT(location_attendance) FROM table_20010140_10 WHERE record = '15–10 (5–7)';


Question: Generate PostgreSQL SQL for: Which tournament had a score of  6–7 (0–7) , 6–2, 4–6?

CREATE TABLE table_name_3 (tournament VARCHAR, score VARCHAR)

SELECT tournament FROM table_name_3 WHERE score = '6–7 (0–7) , 6–2, 4–6';


Question: Generate PostgreSQL SQL for: Name the No. 10 which has a No. 8 of jackson, and a No. 9 of jayden?

CREATE TABLE table_name_94 (no_10 VARCHAR, no_8 VARCHAR, no_9 VARCHAR)

SELECT no_10 FROM table_name_94 WHERE no_8 = 'jackson' AND no_9 = 'jayden';


Question: List the names of countries that have both eco-friendly hotels and cultural heritage sites, but no virtual tours or museums.

CREATE TABLE eco_hotels (hotel_id INT, country VARCHAR(20), name VARCHAR(50)); INSERT INTO eco_hotels (hotel_id, country, name) VALUES (1, 'India', 'Green Resort'), (2, 'Mexico', 'Eco Retreat'), (3, 'Nepal', 'Sustainable Suites'); CREATE TABLE cultural_sites (site_id INT, country VARCHAR(20), type VARCHAR(20)); INSERT INTO cultural_sites (site_id, country, type) VALUES (1, 'India', 'heritage'), (2, 'Mexico', 'heritage'), (3, 'Nepal', 'heritage'); CREATE TABLE virtual_tours (tour_id INT, country VARCHAR(20), type VARCHAR(20)); INSERT INTO virtual_tours (tour_id, country, type) VALUES (1, 'India', 'virtual'), (2, 'Mexico', 'virtual'); CREATE TABLE museums (museum_id INT, country VARCHAR(20), type VARCHAR(20)); INSERT INTO museums (museum_id, country, type) VALUES (1, 'India', 'museum'), (2, 'Mexico', 'museum');

(SELECT country FROM eco_hotels WHERE name IS NOT NULL) INTERSECT (SELECT country FROM cultural_sites WHERE type = 'heritage') EXCEPT (SELECT country FROM (SELECT * FROM virtual_tours WHERE type = 'virtual' UNION ALL SELECT * FROM museums WHERE type = 'museum') AS combined_data);


Question: Generate PostgreSQL SQL for: What years did the Representative from Iowa with a lifespan of 1880–1942 serve?

CREATE TABLE table_name_20 (years VARCHAR, state VARCHAR, lifespan VARCHAR)

SELECT years FROM table_name_20 WHERE state = 'iowa' AND lifespan = '1880–1942';


Question: Generate PostgreSQL SQL for: What is the largest number for tropical Lows for the 1990–91 season with more than 10 tropical cyclones?

CREATE TABLE table_name_13 (tropical_lows INTEGER, season VARCHAR, tropical_cyclones VARCHAR)

SELECT MAX(tropical_lows) FROM table_name_13 WHERE season = '1990–91' AND tropical_cyclones > 10;


Question: What is the average age of players who play 'Racing' games?

CREATE TABLE Players (player_id INT, name VARCHAR(255), age INT, game_genre VARCHAR(255)); INSERT INTO Players (player_id, name, age, game_genre) VALUES (1, 'John', 27, 'FPS'), (2, 'Sarah', 30, 'RPG'), (3, 'Alex', 22, 'FPS'), (4, 'Max', 25, 'Strategy'), (5, 'Zoe', 28, 'Racing'), (6, 'Ella', 24, 'Racing');

SELECT AVG(age) FROM Players WHERE game_genre = 'Racing';


Question: Generate PostgreSQL SQL for: What is the an-stem for the word which has an ö-stems of siangar and an u-stem ending of syni?

CREATE TABLE table_name_18 (masculine_an_stems VARCHAR, feminine_ō_stems VARCHAR, masculine_u_stems VARCHAR)

SELECT masculine_an_stems FROM table_name_18 WHERE feminine_ō_stems = 'siangar' AND masculine_u_stems = 'syni';


Question: Generate PostgreSQL SQL for: Which Pick has a Round larger than 17, and a Name of gene stewart?

CREATE TABLE table_name_46 (pick VARCHAR, round VARCHAR, name VARCHAR)

SELECT COUNT(pick) FROM table_name_46 WHERE round > 17 AND name = 'gene stewart';


Question: Generate PostgreSQL SQL for: What was the average number of attendance for the game on November 29, 1981 played after week 13?

CREATE TABLE table_name_40 (attendance INTEGER, date VARCHAR, week VARCHAR)

SELECT AVG(attendance) FROM table_name_40 WHERE date = 'november 29, 1981' AND week > 13;


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

SELECT to_timestamp('05 Dec 2000'::citext, 'DD Mon YYYY'::citext)
     = to_timestamp('05 Dec 2000',         'DD Mon YYYY') AS t;


Question: What is the average age of community health workers by their race?

CREATE TABLE community_health_workers (worker_id INT, name VARCHAR(50), age INT, race VARCHAR(50)); INSERT INTO community_health_workers (worker_id, name, age, race) VALUES (1, 'John Doe', 35, 'White'), (2, 'Jane Smith', 40, 'Black'), (3, 'Maria Garcia', 45, 'Hispanic');

SELECT race, AVG(age) as avg_age FROM community_health_workers GROUP BY race;


Question: Generate PostgreSQL SQL for: What's the score of Jeff Maggert in T2 place?

CREATE TABLE table_name_36 (score VARCHAR, place VARCHAR, player VARCHAR)

SELECT score FROM table_name_36 WHERE place = 't2' AND player = 'jeff maggert';


Question: What explainable AI techniques were applied in the past year for speech recognition tasks, in the Explainable AI database?

CREATE TABLE techniques (id INT, name VARCHAR(255), domain VARCHAR(255), published_date DATE);

SELECT name FROM techniques WHERE domain = 'Speech Recognition' AND YEAR(published_date) = YEAR(CURRENT_DATE());


Question: Generate PostgreSQL SQL for: What is the class of 2009?

CREATE TABLE table_name_26 (class VARCHAR, year VARCHAR)

SELECT class FROM table_name_26 WHERE year = 2009;


Question: What is the health equity metric trend for the past year?

SELECT date, metric FROM health_equity_metrics ORDER BY date;


Question: What was the average sale price for 'Cubist' artworks in the 'Guggenheim' museum?

CREATE TABLE Artworks (artwork_id INT, movement VARCHAR(255), sale_price DECIMAL(10, 2), museum_name VARCHAR(255));

SELECT AVG(sale_price) FROM Artworks WHERE movement = 'Cubist' AND museum_name = 'Guggenheim';


Question: What is the average word count of articles written by female authors?

CREATE TABLE news_articles (id INT, title VARCHAR(100), content TEXT, word_count INT, author_gender VARCHAR(10));

SELECT AVG(word_count) FROM news_articles WHERE author_gender = 'Female';


Question: Generate PostgreSQL SQL for: Who came in 3rd place in Krško , Slovenia Matije Gubca Stadium

CREATE TABLE table_19317584_2 (city_and_venue VARCHAR)

SELECT 3 AS rd_placed FROM table_19317584_2 WHERE city_and_venue = 'Krško , Slovenia Matije Gubca Stadium';


Question: List the destinations with at least 5 tourists from Australia in 2023.

CREATE TABLE tourism_data (id INT, name VARCHAR(50), country VARCHAR(50), destination VARCHAR(50), visit_year INT); INSERT INTO tourism_data (id, name, country, destination, visit_year) VALUES (1, 'Sarah Thompson', 'Australia', 'Sydney', 2023), (2, 'James Clark', 'Australia', 'Melbourne', 2023), (3, 'Grace White', 'Australia', 'Perth', 2023), (4, 'Lucas Green', 'Australia', 'Adelaide', 2023), (5, 'Emily Black', 'Australia', 'Brisbane', 2023), (6, 'Mia Taylor', 'Australia', 'Cairns', 2022);

SELECT DISTINCT destination FROM tourism_data WHERE country = 'Australia' AND visit_year = 2023 GROUP BY destination HAVING COUNT(*) >= 5;


Question: Which autonomous vehicles have the highest and lowest adoption rates in 'tokyo'?

CREATE TABLE if not exists vehicle_types (vehicle_type varchar(20)); INSERT INTO vehicle_types (vehicle_type) VALUES ('autonomous'), ('manual'); CREATE TABLE if not exists adoption_rates (vehicle_type varchar(20), city varchar(20), adoption_rate float); INSERT INTO adoption_rates (vehicle_type, city, adoption_rate) VALUES ('autonomous', 'tokyo', 25.6), ('manual', 'tokyo', 74.1), ('autonomous', 'tokyo', 26.8), ('manual', 'tokyo', 73.9);

SELECT vehicle_type, MAX(adoption_rate) as highest_rate, MIN(adoption_rate) as lowest_rate FROM adoption_rates WHERE city = 'tokyo' GROUP BY vehicle_type;


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

SELECT keys AS keys_leaf_1
  FROM gist_page_items(get_raw_page('test_gist_idx_inc', 1), 'test_gist_idx_inc')
  WHERE itemoffset = 1;

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


Question: Generate PostgreSQL SQL for: What is the top goal for the result of 2–3?

CREATE TABLE table_name_39 (goal INTEGER, result VARCHAR)

SELECT MAX(goal) FROM table_name_39 WHERE result = '2–3';


Question: Generate PostgreSQL SQL for: The score of 73-71-70=214 belongs to what country?

CREATE TABLE table_name_77 (country VARCHAR, score VARCHAR)

SELECT country FROM table_name_77 WHERE score = 73 - 71 - 70 = 214;


Question: How many cruelty-free haircare products were sold in Canada in the last 6 months?

CREATE TABLE HaircareProducts (product_id INT, product_name VARCHAR(255), is_cruelty_free BOOLEAN, sales_date DATE);

SELECT COUNT(*) FROM HaircareProducts WHERE is_cruelty_free = TRUE AND sales_date >= DATE_SUB(CURRENT_DATE, INTERVAL 6 MONTH) AND country = 'Canada';


Question: What is the maximum capacity of a renewable energy project for each type?

CREATE TABLE projects (name TEXT, type TEXT, capacity INTEGER); INSERT INTO projects (name, type, capacity) VALUES ('Project 1', 'Wind', 100), ('Project 2', 'Solar', 200), ('Project 3', 'Wind', 300);

SELECT type, MAX(capacity) FROM projects GROUP BY type;


Question: What is the minimum flight hours for aircrafts manufactured by Airbus?

CREATE TABLE FlightSafety(id INT, aircraft_id INT, manufacturer VARCHAR(255), flight_hours INT); INSERT INTO FlightSafety(id, aircraft_id, manufacturer, flight_hours) VALUES (1, 1001, 'Boeing', 12000), (2, 1002, 'Airbus', 10500), (3, 1003, 'Boeing', 18000), (4, 1004, 'Airbus', 12000), (5, 1005, 'Airbus', 11000);

SELECT MIN(flight_hours) FROM FlightSafety WHERE manufacturer = 'Airbus';


Question: Generate PostgreSQL SQL for: Which college is Kellen Davis from?

CREATE TABLE table_name_44 (college VARCHAR, player VARCHAR)

SELECT college FROM table_name_44 WHERE player = 'kellen davis';


Question: What is the average response time for emergency calls on weekends?

CREATE TABLE emergencies (eid INT, call_time TIME, response_time INT);

SELECT AVG(response_time) FROM emergencies WHERE DAYOFWEEK(call_time) IN (1, 7);


Question: Generate PostgreSQL SQL for: Which driver had a grid of 18?

CREATE TABLE table_name_58 (driver VARCHAR, grid VARCHAR)

SELECT driver FROM table_name_58 WHERE grid = '18';


Question: Create a table named "maintenance" with columns "maintenance_id", "vehicle_id", "date", and "description".

CREATE TABLE maintenance (maintenance_id INT, vehicle_id INT, date DATE, description VARCHAR(255));


Question: Display the concerts with a revenue greater than the average revenue of concerts in 'New York'.

CREATE TABLE Concerts (ConcertID INT, Artist VARCHAR(50), City VARCHAR(50), Revenue DECIMAL(10,2)); INSERT INTO Concerts (ConcertID, Artist, City, Revenue) VALUES (1, 'Taylor Swift', 'Los Angeles', 500000.00), (2, 'BTS', 'New York', 750000.00), (3, 'Adele', 'London', 600000.00), (4, 'Taylor Swift', 'New York', 350000.00);

SELECT * FROM Concerts WHERE City = 'New York' GROUP BY City; SELECT * FROM Concerts WHERE Revenue > (SELECT AVG(Revenue) FROM (SELECT Revenue FROM Concerts WHERE City = 'New York' GROUP BY City));


Question: What is the total number of veterans employed in the defense industry in the United States as of January 2022?

CREATE TABLE veteran_employment (employee_id INT, industry_sector VARCHAR(50), employment_date DATE, is_veteran BOOLEAN);

SELECT COUNT(employee_id) FROM veteran_employment WHERE industry_sector LIKE '%defense%' AND employment_date = '2022-01-01' AND is_veteran = TRUE;


Question: What is the total assets under management (AUM) for investment strategies with a risk level of 'moderate'?

CREATE TABLE investment_strategies (strategy_id INT, name VARCHAR(50), risk_level VARCHAR(50), AUM DECIMAL(10,2)); INSERT INTO investment_strategies (strategy_id, name, risk_level, AUM) VALUES (1, 'Growth', 'Moderate', 5000000.00), (2, 'Income', 'Conservative', 3000000.00);

SELECT SUM(AUM) FROM investment_strategies WHERE risk_level = 'Moderate';


Question: Which natural foundations have the highest customer ratings?

CREATE TABLE cosmetics_info(product_name TEXT, is_natural BOOLEAN, rating DECIMAL); INSERT INTO cosmetics_info(product_name, is_natural, rating) VALUES('Natural Foundation 1', true, 4.5);

SELECT product_name FROM cosmetics_info WHERE is_natural = true AND rating = (SELECT MAX(rating) FROM cosmetics_info WHERE is_natural = true);


Question: Generate PostgreSQL SQL for: What was the number of the crowd when the Wollongong Hawks were the home team?

CREATE TABLE table_name_53 (crowd INTEGER, home_team VARCHAR)

SELECT SUM(crowd) FROM table_name_53 WHERE home_team = 'wollongong hawks';


Question: Delete the 'Teen' size from the 'Size' table

CREATE TABLE Size (id INT PRIMARY KEY, name VARCHAR(50), average_spending DECIMAL(5,2));


Question: Compare the landfill capacity of cities in the 'East Coast' region with those in the 'West Coast' region.

CREATE TABLE cities (city_name VARCHAR(50), region VARCHAR(50)); INSERT INTO cities (city_name, region) VALUES ('New York', 'East Coast'), ('Boston', 'East Coast'), ('San Francisco', 'West Coast'), ('Los Angeles', 'West Coast'); CREATE TABLE landfill_capacity (city_name VARCHAR(50), capacity INT); INSERT INTO landfill_capacity (city_name, capacity) VALUES ('New York', 5000), ('Boston', 4000), ('San Francisco', 3000), ('Los Angeles', 6000);

SELECT c.region, AVG(lc.capacity) as avg_capacity FROM landfill_capacity lc JOIN cities c ON lc.city_name = c.city_name GROUP BY c.region;


Question: Generate PostgreSQL SQL for: What is Moving From, when Ends is before 2011?

CREATE TABLE table_name_65 (moving_from VARCHAR, ends INTEGER)

SELECT moving_from FROM table_name_65 WHERE ends < 2011;


Question: Generate PostgreSQL SQL for: What is the Score with a Team with @ houston?

CREATE TABLE table_name_35 (score VARCHAR, team VARCHAR)

SELECT score FROM table_name_35 WHERE team = '@ houston';


Question: How many public bike sharing programs are available in each city?

CREATE TABLE City (city_id INT, city_name VARCHAR(50)); CREATE TABLE Program (program_id INT, program_name VARCHAR(50), city_id INT);

SELECT city_name, COUNT(*) as num_programs FROM City JOIN Program ON City.city_id = Program.city_id GROUP BY city_name;


Question: Identify the number of eco-friendly hotels in each city in Spain.

CREATE TABLE eco_friendly_hotels (hotel_id INT, name TEXT, city TEXT); INSERT INTO eco_friendly_hotels (hotel_id, name, city) VALUES (1, 'EcoHotel Madrid', 'Madrid'), (2, 'EcoHotel Barcelona', 'Barcelona'), (3, 'EcoHotel Valencia', 'Valencia');

SELECT city, COUNT(*) as hotel_count FROM eco_friendly_hotels WHERE city IN (SELECT city FROM countries WHERE name = 'Spain') GROUP BY city;


Question: What is the minimum budget for a resilience project in the 'Energy' sector?

CREATE TABLE ResilienceProjects (ProjectID int, Sector varchar(10), Budget int); INSERT INTO ResilienceProjects (ProjectID, Sector, Budget) VALUES (1, 'Water', 500000), (2, 'Transport', 800000), (3, 'Energy', 600000);

SELECT MIN(Budget) AS MinBudget FROM ResilienceProjects WHERE Sector = 'Energy';


Question: PostgreSQL regression test 'largeobject': Write the SELECT query (example 99).

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

SELECT count(*) FROM (SELECT lo_creat(42)) AS _sub;


Question: What is the percentage of patients in each region who have visited a hospital or clinic in the past year, grouped by region?

CREATE TABLE patients (patient_id INT, region VARCHAR(20), visited_last_year BOOLEAN); INSERT INTO patients (patient_id, region, visited_last_year) VALUES (1, 'Rural', true), (2, 'Urban', false), (3, 'Rural', true); CREATE TABLE hospitals (hospital_id INT, region VARCHAR(20), beds INT); INSERT INTO hospitals (hospital_id, region, beds) VALUES (1, 'Rural', 50), (2, 'Urban', 100); CREATE TABLE clinics (clinic_id INT, region VARCHAR(20), beds INT); INSERT INTO clinics (clinic_id, region, beds) VALUES (1, 'Rural', 10), (2, 'Urban', 20); CREATE TABLE visits (patient_id INT, hospital_id INT, clinic_id INT, visit_year INT); INSERT INTO visits (patient_id, hospital_id, clinic_id, visit_year) VALUES (1, 1, NULL, 2022), (2, NULL, 2, 2022), (3, 1, NULL, 2022);

SELECT s.region, (COUNT(p.patient_id) FILTER (WHERE p.visited_last_year = true) * 100.0 / COUNT(p.patient_id)) as percentage FROM patients p JOIN hospitals h ON p.region = h.region JOIN clinics c ON p.region = c.region JOIN states s ON p.region = s.region JOIN visits v ON p.patient_id = v.patient_id WHERE v.visit_year = 2022 GROUP BY s.region;


Question: Generate PostgreSQL SQL for: which Event that has an Opponent of kendall grove?

CREATE TABLE table_name_2 (event VARCHAR, opponent VARCHAR)

SELECT event FROM table_name_2 WHERE opponent = 'kendall grove';


Question: Generate PostgreSQL SQL for: What date was the episode that aired at 7:30 pm ET?

CREATE TABLE table_name_26 (date VARCHAR, time VARCHAR)

SELECT date FROM table_name_26 WHERE time = '7:30 pm et';


Question: Generate PostgreSQL SQL for: What score has an opponent gan teik chai lin woon fui?

CREATE TABLE table_name_6 (score VARCHAR, opponent VARCHAR)

SELECT score FROM table_name_6 WHERE opponent = 'gan teik chai lin woon fui';


Question: Generate PostgreSQL SQL for: What was the total number of votes in the 2005 elections?

CREATE TABLE table_19698421_1 (total_votes INTEGER, year VARCHAR)

SELECT MIN(total_votes) FROM table_19698421_1 WHERE year = '2005';


Question: Generate PostgreSQL SQL for: What day is collingwood the home side?

CREATE TABLE table_name_79 (date VARCHAR, home_team VARCHAR)

SELECT date FROM table_name_79 WHERE home_team = 'collingwood';


Question: List all countries with deep-sea exploration programs and their start dates.

CREATE TABLE countries (country_name TEXT, exploration_start_date DATE); INSERT INTO countries (country_name, exploration_start_date) VALUES ('Japan', '1950-04-01'), ('USA', '1960-01-01'), ('France', '1985-12-22');

SELECT country_name, exploration_start_date FROM countries WHERE country_name IN ('Japan', 'USA', 'France');


Question: Which country has the largest marine protected area?

CREATE TABLE marine_protected_areas (name VARCHAR(255), country VARCHAR(255), area_size FLOAT); INSERT INTO marine_protected_areas (name, country, area_size) VALUES ('Ross Sea', 'New Zealand', 800000);

SELECT country, MAX(area_size) as max_size FROM marine_protected_areas;


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

SELECT INTERVAL '1.5 months' AS "One month 15 days";

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

SELECT count(*) FROM (SELECT INTERVAL '1.5 months' AS "One month 15 days") AS _sub;


Question: What is the average rating of art programs in the Eastern region with a budget over $10,000?

CREATE TABLE programs (id INT, region VARCHAR(50), budget DECIMAL(10,2), rating INT); INSERT INTO programs (id, region, budget, rating) VALUES (1, 'Midwest', 8000, 8), (2, 'Northeast', 12000, 9), (3, 'West Coast', 7000, 7), (4, 'Southeast', 15000, 10), (5, 'Eastern', 11000, 6);

SELECT AVG(rating) FROM programs WHERE region = 'Eastern' AND budget > 10000;


Question: Generate PostgreSQL SQL for: List the name of physicians who took some appointment.

CREATE TABLE appointment (Physician VARCHAR); CREATE TABLE physician (name VARCHAR, EmployeeID VARCHAR)

SELECT T2.name FROM appointment AS T1 JOIN physician AS T2 ON T1.Physician = T2.EmployeeID;


Question: What is the total quantity of fair trade products sold in Europe?

CREATE TABLE Sales (SaleID INT, Product VARCHAR(20), Quantity INT, Region VARCHAR(20)); INSERT INTO Sales VALUES (1, 'Fair Trade Coffee', 200, 'Europe'); INSERT INTO Sales VALUES (2, 'Fair Trade Tea', 300, 'Europe');

SELECT SUM(Quantity) FROM Sales WHERE Product LIKE '%Fair Trade%' AND Region = 'Europe';


Question: Generate PostgreSQL SQL for: Can you tell me the Source that has the Rank of 78?

CREATE TABLE table_name_86 (source VARCHAR, rank VARCHAR)

SELECT source FROM table_name_86 WHERE rank = 78;


Question: How many local cultural events are organized in Japan annually?

CREATE TABLE CulturalEvents (event_id INT, event_name TEXT, country TEXT, year_of_occurrence INT); INSERT INTO CulturalEvents (event_id, event_name, country, year_of_occurrence) VALUES (1, 'Japanese Flower Festival', 'Japan', 2022); INSERT INTO CulturalEvents (event_id, event_name, country, year_of_occurrence) VALUES (2, 'Japanese Art Exhibition', 'Japan', 2021); INSERT INTO CulturalEvents (event_id, event_name, country, year_of_occurrence) VALUES (3, 'Japanese Traditional Dance Festival', 'Japan', 2019);

SELECT COUNT(*) FROM CulturalEvents WHERE country = 'Japan' GROUP BY year_of_occurrence;


Question: Generate PostgreSQL SQL for: what is the date of vacancy when the date of appointment is 1 january 2009?

CREATE TABLE table_name_54 (date_of_vacancy VARCHAR, date_of_appointment VARCHAR)

SELECT date_of_vacancy FROM table_name_54 WHERE date_of_appointment = '1 january 2009';


Question: Delete the view for health equity metrics

CREATE OR REPLACE VIEW health_equity_view AS SELECT * FROM health_equity;


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

-- Function changes row_security setting and so invalidates plan
create function rls_f(text) returns text
begin atomic
 select set_config('rls_test.blah', $1, true) || set_config('row_security', 'false', true) || string_agg(c, ',' order by c) from rls_t;

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


Question: Generate PostgreSQL SQL for: The Dallas Burn had a 12-9-7 record and what number of goals for?

CREATE TABLE table_1253396_5 (goals_for VARCHAR, overall_record VARCHAR)

SELECT goals_for FROM table_1253396_5 WHERE overall_record = '12-9-7';


Question: What is the average speed of spacecraft in the space_exploration table?

CREATE TABLE space_exploration (id INT, name VARCHAR(20), launch_date DATE, max_speed FLOAT); INSERT INTO space_exploration (id, name, launch_date, max_speed) VALUES (1, 'Voyager 1', '1977-09-05', 61000), (2, 'New Horizons', '2006-01-19', 58000), (3, 'Parker Solar Probe', '2018-08-12', 724200);

SELECT AVG(max_speed) FROM space_exploration;


Question: List all indigenous food systems that use 'permaculture' techniques.

CREATE TABLE indigenous_food_systems (id INT, name TEXT, location TEXT, techniques TEXT); INSERT INTO indigenous_food_systems (id, name, location, techniques) VALUES (1, 'System 1', 'Location 1', 'Permaculture, Agroforestry'), (2, 'System 2', 'Location 2', 'Agroecology');

SELECT name FROM indigenous_food_systems WHERE techniques LIKE '%Permaculture%';


Question: Generate PostgreSQL SQL for: Which home town was the high school Catholic University located in?

CREATE TABLE table_12032893_1 (home_town VARCHAR, high_school VARCHAR)

SELECT home_town FROM table_12032893_1 WHERE high_school = 'Catholic University';


Question: Generate PostgreSQL SQL for: For the category of most popular star with a result of won for 2007, what was the award?

CREATE TABLE table_name_27 (award VARCHAR, year VARCHAR, result VARCHAR, category VARCHAR)

SELECT award FROM table_name_27 WHERE result = 'won' AND category = 'most popular star' AND year = 2007;


Question: Generate PostgreSQL SQL for: In what poll is John Oxendine at 32%?

CREATE TABLE table_name_67 (poll_source VARCHAR, john_oxendine VARCHAR)

SELECT poll_source FROM table_name_67 WHERE john_oxendine = '32%';


Question: What is the maximum billing amount for cases handled by attorneys from Jakarta with more than 7 years of experience?

CREATE TABLE Attorneys (AttorneyID INT, YearsOfExperience INT, City VARCHAR(255)); INSERT INTO Attorneys (AttorneyID, YearsOfExperience, City) VALUES (1, 10, 'Jakarta'); INSERT INTO Attorneys (AttorneyID, YearsOfExperience, City) VALUES (2, 3, 'New York'); INSERT INTO Attorneys (AttorneyID, YearsOfExperience, City) VALUES (3, 7, 'Jakarta'); CREATE TABLE Cases (CaseID INT, AttorneyID INT, BillingAmount INT); INSERT INTO Cases (CaseID, AttorneyID, BillingAmount) VALUES (1, 1, 2000); INSERT INTO Cases (CaseID, AttorneyID, BillingAmount) VALUES (2, 1, 3000); INSERT INTO Cases (CaseID, AttorneyID, BillingAmount) VALUES (3, 2, 1000); INSERT INTO Cases (CaseID, AttorneyID, BillingAmount) VALUES (4, 3, 1500);

SELECT MAX(BillingAmount) FROM Cases JOIN Attorneys ON Cases.AttorneyID = Attorneys.AttorneyID WHERE Attorneys.City = 'Jakarta' AND Attorneys.YearsOfExperience > 7;


Question: Delete records of soldiers who were discharged before 2010-01-01 from the soldiers_discharge_data table

CREATE TABLE soldiers_discharge_data (soldier_id INT, name VARCHAR(50), rank VARCHAR(50), discharge_date DATE);

DELETE FROM soldiers_discharge_data WHERE discharge_date < '2010-01-01';


Question: Generate PostgreSQL SQL for: Name the wraps per inch for 120-240

CREATE TABLE table_20297668_1 (wraps_per_inch__wpi_ VARCHAR, m_100g VARCHAR)

SELECT wraps_per_inch__wpi_ FROM table_20297668_1 WHERE m_100g = '120-240';


Question: Generate PostgreSQL SQL for: What is the population for the place with an area of 2.33 km2?

CREATE TABLE table_2588674_1 (population__2000_census__ INTEGER, area_km² VARCHAR)

SELECT MAX(population__2000_census__) FROM table_2588674_1 WHERE area_km² = '2.33';


Question: Generate PostgreSQL SQL for: WHich Category in White has a Black of 38,05%?

CREATE TABLE table_name_35 (white VARCHAR, black VARCHAR)

SELECT white FROM table_name_35 WHERE black = '38,05%';


Question: What is the total REE production in 2020?

CREATE TABLE production (year INT, element TEXT, quantity INT); INSERT INTO production (year, element, quantity) VALUES (2015, 'Dysprosium', 100), (2016, 'Dysprosium', 150), (2017, 'Dysprosium', 200), (2018, 'Dysprosium', 250), (2019, 'Dysprosium', 300), (2020, 'Dysprosium', 350), (2015, 'Neodymium', 500), (2016, 'Neodymium', 600), (2017, 'Neodymium', 700), (2018, 'Neodymium', 800), (2019, 'Neodymium', 900), (2020, 'Neodymium', 1000);

SELECT SUM(quantity) FROM production WHERE year = 2020 AND element IN ('Dysprosium', 'Neodymium');


Question: Generate PostgreSQL SQL for: Which episode number aired on 18 october 2012?

CREATE TABLE table_25721_3 (episode_no INTEGER, airdate VARCHAR)

SELECT MIN(episode_no) FROM table_25721_3 WHERE airdate = '18 October 2012';


Question: Generate PostgreSQL SQL for: Where is the Eastern Creek Raceway located?

CREATE TABLE table_name_19 (location___state VARCHAR, circuit VARCHAR)

SELECT location___state FROM table_name_19 WHERE circuit = 'eastern creek raceway';


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

SELECT tablename, null_frac
FROM pg_stats
WHERE schemaname like 'pg_temp%'
AND tablename = 'stats_temp'
AND inherited = false
AND attname = 'i';

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

SELECT count(*) FROM (SELECT tablename, null_frac
FROM pg_stats
WHERE schemaname like 'pg_temp%'
AND tablename = 'stats_temp'
AND inherited = false
AND attname = 'i') AS _sub;


Question: What is the total number of military bases and their corresponding city in the United States?

CREATE TABLE military_bases (id INT PRIMARY KEY, name VARCHAR(255), type VARCHAR(255), location VARCHAR(255)); INSERT INTO military_bases (id, name, type, location) VALUES (1, 'Fort Bragg', 'Army Base', 'Fayetteville, NC');

SELECT COUNT(*) as total_bases, location FROM military_bases WHERE location LIKE '%, USA' GROUP BY location;


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

ALTER EXTENSION pgtap ADD FUNCTION _temptable ( anyarray, TEXT );

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


Question: Delete all regions with no countries from the regions table

CREATE TABLE countries (id INT, name VARCHAR(50), region VARCHAR(50)); CREATE TABLE regions (id INT, name VARCHAR(50)); INSERT INTO regions (id, name) VALUES (1, 'North America'), (2, 'Europe'), (3, 'Asia'), (4, 'Antarctica'); INSERT INTO countries (id, name, region) VALUES (1, 'USA', 'North America'), (2, 'Russia', 'Europe'), (3, 'China', 'Asia'), (4, 'Terra Nova', 'Antarctica');

DELETE FROM regions WHERE id NOT IN (SELECT region FROM countries);


Question: Generate PostgreSQL SQL for: When David McNamara was the opponent in the final, what was the tier?

CREATE TABLE table_name_59 (tier VARCHAR, opponent_in_the_final VARCHAR)

SELECT tier FROM table_name_59 WHERE opponent_in_the_final = 'david mcnamara';


Question: Generate PostgreSQL SQL for: Who had the highest assists during game 78?

CREATE TABLE table_27721131_11 (high_assists VARCHAR, game VARCHAR)

SELECT high_assists FROM table_27721131_11 WHERE game = 78;


Question: How many donors have made donations greater than $1000 in the Europe region?

CREATE TABLE donors (id INT, name TEXT, region TEXT, donation_amount DECIMAL(10,2)); INSERT INTO donors (id, name, region, donation_amount) VALUES (1, 'John Smith', 'Asia-Pacific', 500.00), (2, 'Jane Doe', 'Europe', 1500.00), (3, 'James Lee', 'Asia-Pacific', 2000.00);

SELECT COUNT(*) FROM donors WHERE donation_amount > 1000 AND region = 'Europe';


Question: List the case IDs and outcomes for cases that were resolved in New York or Illinois.

CREATE TABLE cases (case_id INT, case_outcome VARCHAR(10), case_state VARCHAR(10)); INSERT INTO cases (case_id, case_outcome, case_state) VALUES (1, 'Won', 'New York'), (2, 'Lost', 'Illinois'), (3, 'Pending', 'Texas');

SELECT case_id, case_outcome FROM cases WHERE case_state = 'New York' UNION SELECT case_id, case_outcome FROM cases WHERE case_state = 'Illinois';


Question: Who are the customers with a high account balance in the 'Americas' region?

CREATE TABLE customers (id INT, name VARCHAR(50), region VARCHAR(50), account_balance DECIMAL(10,2)); INSERT INTO customers (id, name, region, account_balance) VALUES (1, 'John Doe', 'New York', 50000.00); INSERT INTO customers (id, name, region, account_balance) VALUES (2, 'Jane Smith', 'California', 60000.00); INSERT INTO customers (id, name, region, account_balance) VALUES (3, 'Bob Johnson', 'APAC', 30000.00); INSERT INTO customers (id, name, region, account_balance) VALUES (4, 'Alice Williams', 'APAC', 40000.00);

SELECT * FROM customers WHERE region = 'Americas' AND account_balance > 40000.00;


Question: What is the maximum ocean acidification level in the North Pacific Ocean?

CREATE TABLE ocean_acidification (id INT, location TEXT, level FLOAT); INSERT INTO ocean_acidification (id, location, level) VALUES (1, 'North Pacific', 8.1); INSERT INTO ocean_acidification (id, location, level) VALUES (2, 'South Pacific', 7.7); INSERT INTO ocean_acidification (id, location, level) VALUES (3, 'North Atlantic', 7.9);

SELECT MAX(level) FROM ocean_acidification WHERE location = 'North Pacific';


Question: Generate PostgreSQL SQL for: Who is the home team at kardinia park?

CREATE TABLE table_name_16 (home_team VARCHAR, venue VARCHAR)

SELECT home_team FROM table_name_16 WHERE venue = 'kardinia park';


Question: Count the number of properties in Los Angeles with a listing price above $600,000 and inclusive housing features.

CREATE TABLE properties (id INT, city VARCHAR(20), listing_price INT, inclusive_housing BOOLEAN); INSERT INTO properties (id, city, listing_price, inclusive_housing) VALUES (1, 'Los Angeles', 700000, true); INSERT INTO properties (id, city, listing_price, inclusive_housing) VALUES (2, 'Los Angeles', 600000, false);

SELECT COUNT(*) FROM properties WHERE city = 'Los Angeles' AND listing_price > 600000 AND inclusive_housing = true;


Question: What is the average attendance for cultural events in the city of 'New York'?

CREATE TABLE cultural_events (id INT, city VARCHAR(20), attendance INT); INSERT INTO cultural_events (id, city, attendance) VALUES (1, 'New York', 2000), (2, 'Los Angeles', 3000), (3, 'New York', 2500);

SELECT AVG(attendance) FROM cultural_events WHERE city = 'New York';


Question: PostgreSQL regression test 'constraints': Write the SELECT query (example 211).

SELECT conname FROM pg_constraint WHERE conrelid = 'parted_fk_naming_1'::regclass AND contype = 'f';

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

SELECT count(*) FROM (SELECT conname FROM pg_constraint WHERE conrelid = 'parted_fk_naming_1'::regclass AND contype = 'f') AS _sub;


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

SELECT '0'::seg >> '0 .. 1'::seg AS bool;

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


Question: Show the number of employees in each department, sorted by the number of employees in descending order in the "employees" table.

CREATE TABLE employees (id INT, name VARCHAR(50), department VARCHAR(20)); INSERT INTO employees (id, name, department) VALUES (1, 'Anna Smith', 'News'), (2, 'John Doe', 'News'), (3, 'Sara Connor', 'News'), (4, 'Mike Johnson', 'Sports'), (5, 'Emma White', 'Sports'), (6, 'Alex Brown', 'IT');

SELECT department, COUNT(*) AS num_employees FROM employees GROUP BY department ORDER BY num_employees DESC;


Question: Generate PostgreSQL SQL for: What is the Date of the Everton Away game?

CREATE TABLE table_name_95 (date VARCHAR, away_team VARCHAR)

SELECT date FROM table_name_95 WHERE away_team = 'everton';


Question: List the case numbers, outcomes, and corresponding legal precedent IDs for cases in the 'criminal' schema, ordered by case number.

CREATE SCHEMA criminal; CREATE TABLE case_outcomes (case_number INT, outcome VARCHAR(255)); CREATE TABLE legal_precedents (precedent_id INT, case_number INT);

SELECT co.case_number, co.outcome, lp.precedent_id FROM criminal.case_outcomes co INNER JOIN criminal.legal_precedents lp ON co.case_number = lp.case_number ORDER BY co.case_number;


Question: What are the names and average attendance of all stadiums that have hosted a game in the last 5 years?

CREATE TABLE stadiums (id INT, name TEXT, capacity INT); CREATE TABLE games (id INT, stadium_id INT, home_team_id INT, away_team_id INT, home_team_score INT, away_team_score INT, game_date DATE); CREATE TABLE attendance (game_id INT, team_id INT, fans_attended INT);

SELECT s.name, AVG(a.fans_attended) FROM stadiums s INNER JOIN games g ON s.id = g.stadium_id INNER JOIN attendance a ON g.id = a.game_id WHERE g.game_date >= DATE_SUB(CURRENT_DATE, INTERVAL 5 YEAR) GROUP BY s.name;


Question: Generate PostgreSQL SQL for: What is the territory with 17 screens?

CREATE TABLE table_name_91 (territory VARCHAR, screens VARCHAR)

SELECT territory FROM table_name_91 WHERE screens = 17;


Question: What is the maximum seating capacity of public ferries in Hong Kong?

CREATE TABLE public_ferries(id INT, ferry_number INT, city VARCHAR(20), max_seating_capacity INT);

SELECT MAX(max_seating_capacity) FROM public_ferries WHERE city = 'Hong Kong';


Question: Generate PostgreSQL SQL for: What years in orlando have the United States as the nationality, and montana as the school/club team?

CREATE TABLE table_name_16 (years_in_orlando VARCHAR, nationality VARCHAR, school_club_team VARCHAR)

SELECT years_in_orlando FROM table_name_16 WHERE nationality = 'united states' AND school_club_team = 'montana';


Question: List the departments with no research grants.

CREATE TABLE Departments (DepartmentID INT, DepartmentName VARCHAR(50), ResearchGrants INT);

SELECT DepartmentName FROM Departments WHERE ResearchGrants = 0;


Question: Calculate the percentage of products sold for each brand in the 'ethical_labor2' table, ordered by the percentage in descending order.

CREATE TABLE ethical_labor2 (product_id INT, brand VARCHAR(255), quantity_sold INT); INSERT INTO ethical_labor2 (product_id, brand, quantity_sold) VALUES (4, 'BrandV', 500), (5, 'BrandW', 800), (6, 'BrandX', 700);

SELECT brand, (SUM(quantity_sold) OVER (PARTITION BY brand) * 100.0 / SUM(quantity_sold) OVER ()) AS percentage_sold FROM ethical_labor2 GROUP BY brand ORDER BY percentage_sold DESC;


Question: Generate PostgreSQL SQL for: How much did Jerry Barber score to come in at T9?

CREATE TABLE table_name_79 (score VARCHAR, place VARCHAR, player VARCHAR)

SELECT score FROM table_name_79 WHERE place = 't9' AND player = 'jerry barber';


Question: Generate PostgreSQL SQL for: What's the termini of the route with junctions of i-35 fm 3338 sh 255?

CREATE TABLE table_name_2 (termini VARCHAR, junctions VARCHAR)

SELECT termini FROM table_name_2 WHERE junctions = 'i-35 fm 3338 sh 255';


Question: Generate PostgreSQL SQL for: What number value has the Other transliteration of muoy roy?

CREATE TABLE table_name_90 (value VARCHAR, other VARCHAR)

SELECT value FROM table_name_90 WHERE other = 'muoy roy';


Question: Generate PostgreSQL SQL for: Name the horizontal 0 for  明弦（ry日月）

CREATE TABLE table_25519358_1 (horizontal_0_a VARCHAR, hypotenuse_0_c VARCHAR)

SELECT horizontal_0_a FROM table_25519358_1 WHERE hypotenuse_0_c = '明弦（RY日月）';


Question: List all animals and their ages from the 'animal_population' table, ordered by age.

CREATE TABLE animal_population (animal_id INT, animal_type VARCHAR(10), age INT); INSERT INTO animal_population (animal_id, animal_type, age) VALUES (1, 'hippo', 18); INSERT INTO animal_population (animal_id, animal_type, age) VALUES (2, 'rhino', 12); INSERT INTO animal_population (animal_id, animal_type, age) VALUES (3, 'hippo', 20);

SELECT * FROM animal_population ORDER BY age;


Question: How many social impact investments were made in 'Africa' in 2020?

CREATE TABLE investments (id INT, location VARCHAR(50), investment_year INT, investment_type VARCHAR(20)); INSERT INTO investments (id, location, investment_year, investment_type) VALUES (1, 'Africa', 2020, 'social impact'), (2, 'Europe', 2019, 'social impact'), (3, 'Africa', 2020, 'traditional'), (4, 'North America', 2021, 'social impact');

SELECT COUNT(*) FROM investments WHERE location = 'Africa' AND investment_year = 2020 AND investment_type = 'social impact';


Question: Generate PostgreSQL SQL for: What year had an edition of 115th?

CREATE TABLE table_name_21 (year INTEGER, edition VARCHAR)

SELECT AVG(year) FROM table_name_21 WHERE edition = '115th';


Question: What is the minimum depth of all marine protected areas in the Arctic Ocean?

CREATE TABLE marine_protected_areas (name VARCHAR(255), depth FLOAT, ocean VARCHAR(255));

SELECT MIN(depth) FROM marine_protected_areas WHERE ocean = 'Arctic';


Question: Generate PostgreSQL SQL for: What was the final score when the Maple Leafs played the Columbus Blue Jackets?

CREATE TABLE table_16864968_7 (score VARCHAR, opponent VARCHAR)

SELECT score FROM table_16864968_7 WHERE opponent = 'Columbus Blue Jackets';


Question: Generate PostgreSQL SQL for: Name the call sign for ERP W of 27

CREATE TABLE table_name_65 (call_sign VARCHAR, erp_w VARCHAR)

SELECT call_sign FROM table_name_65 WHERE erp_w = 27;


Question: PostgreSQL regression test 'create_am': Write the SELECT query (example 87).

SELECT relam FROM pg_class WHERE relname = 'am_partitioned';

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

SELECT count(*) FROM (SELECT relam FROM pg_class WHERE relname = 'am_partitioned') AS _sub;


Question: How many clinical trials were conducted by each organization in 2019?

CREATE TABLE clinical_trials (trial_id INT, organization_id INT, country VARCHAR(255), approval_date DATE); INSERT INTO clinical_trials (trial_id, organization_id, country, approval_date) VALUES (1, 1, 'USA', '2019-01-01'), (2, 1, 'Canada', '2019-04-01'), (3, 2, 'Mexico', '2019-07-01');

SELECT organization_id, COUNT(*) as num_trials FROM clinical_trials WHERE YEAR(approval_date) = 2019 GROUP BY organization_id;


Question: Generate PostgreSQL SQL for: What was the rate for 73 RYds?

CREATE TABLE table_name_22 (rate VARCHAR, ryds VARCHAR)

SELECT rate FROM table_name_22 WHERE ryds = '73';


Question: Drop the 'satellite_deployment' table

CREATE TABLE satellite_deployment (id INT PRIMARY KEY, name VARCHAR(255), country VARCHAR(255), launch_date DATE);


Question: Generate PostgreSQL SQL for: How many female students have milk or egg allergies?

CREATE TABLE Student (StuID VARCHAR, sex VARCHAR); CREATE TABLE has_allergy (StuID VARCHAR, allergy VARCHAR)

SELECT COUNT(*) FROM has_allergy AS T1 JOIN Student AS T2 ON T1.StuID = T2.StuID WHERE T2.sex = 'F' AND T1.allergy = 'Milk' OR T1.allergy = 'Eggs';


Question: Insert a new menu item 'Veggie Burger' into the 'Dinner' menu with a price of 13.99

CREATE TABLE Menu (menu_name VARCHAR(20), item_name VARCHAR(30), price DECIMAL(5,2));

INSERT INTO Menu (menu_name, item_name, price) VALUES ('Dinner', 'Veggie Burger', 13.99);


Question: Write the DDL statement from PostgreSQL regression test 'create_index' (example 13).

CREATE INDEX tenk2_hundred ON tenk2 USING btree(hundred int4_ops);

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


Question: Which country had the largest decrease in Yttrium production from 2020 to 2021?

CREATE TABLE YttriumProduction (country VARCHAR(50), year INT, production INT); INSERT INTO YttriumProduction (country, year, production) VALUES ('China', 2020, 1200), ('China', 2021, 1100), ('USA', 2020, 1000), ('USA', 2021, 1100), ('Australia', 2020, 800), ('Australia', 2021, 700);

SELECT country, MIN(production_change) FROM (SELECT country, (production - LAG(production) OVER (PARTITION BY country ORDER BY year)) AS production_change FROM YttriumProduction) AS subquery WHERE production_change IS NOT NULL GROUP BY country;


Question: How many art pieces were created by artists from Africa in the 'sculpture' medium?

CREATE TABLE art_pieces (id INT, title TEXT, artist_name TEXT, medium TEXT, region TEXT); INSERT INTO art_pieces (id, title, artist_name, medium, region) VALUES (1, 'African Mask', 'Unknown', 'sculpture', 'Africa');

SELECT COUNT(*) FROM art_pieces WHERE medium = 'sculpture' AND region = 'Africa';


Question: What is the total revenue for music artists by genre?

CREATE TABLE Music_Artists_Genre (id INT, name VARCHAR(100), genre VARCHAR(50), revenue DECIMAL(10,2)); INSERT INTO Music_Artists_Genre (id, name, genre, revenue) VALUES (1, 'Adele', 'Pop', 1000000.00), (2, 'Eminem', 'Rap', 800000.00), (3, 'Metallica', 'Rock', 1200000.00);

SELECT genre, SUM(revenue) FROM Music_Artists_Genre GROUP BY genre;


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

SELECT timestamp with time zone 'J2452271T040506.789-08';

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

SELECT count(*) FROM (SELECT timestamp with time zone 'J2452271T040506.789-08') AS _sub;


Question: What is the total revenue generated by attorneys from the 'Boston' region in the 'Criminal' practice area?

CREATE TABLE Attorneys (AttorneyID INT, Name TEXT, Region TEXT, Practice TEXT, Revenue FLOAT); INSERT INTO Attorneys (AttorneyID, Name, Region, Practice, Revenue) VALUES (1, 'John Doe', 'Boston', 'Criminal', 50000.00); INSERT INTO Attorneys (AttorneyID, Name, Region, Practice, Revenue) VALUES (2, 'Jane Smith', 'New York', 'Civil', 75000.00);

SELECT SUM(Revenue) FROM Attorneys WHERE Region = 'Boston' AND Practice = 'Criminal';


Question: Generate PostgreSQL SQL for: Which Mascot has an Enrollment of 640?

CREATE TABLE table_name_63 (mascot VARCHAR, enrollment VARCHAR)

SELECT mascot FROM table_name_63 WHERE enrollment = 640;


Question: How many users have interacted with content related to the hashtag "#climatechange" in the last year?

CREATE TABLE users (id INT); CREATE TABLE posts (id INT, user_id INT, hashtags TEXT);

SELECT COUNT(DISTINCT users.id) FROM users INNER JOIN posts ON users.id = posts.user_id WHERE FIND_IN_SET('climatechange', posts.hashtags) > 0 AND posts.created_at >= DATE_SUB(NOW(), INTERVAL 1 YEAR);


Question: Generate PostgreSQL SQL for: How many episodes are numbered 12x03?

CREATE TABLE table_23292220_13 (first_broadcast VARCHAR, episode VARCHAR)

SELECT COUNT(first_broadcast) FROM table_23292220_13 WHERE episode = '12x03';


Question: Generate PostgreSQL SQL for: What is Norway's least ends lost?

CREATE TABLE table_16922657_2 (Ends INTEGER, country VARCHAR, Norway VARCHAR)

SELECT MIN(Ends) AS lost FROM table_16922657_2 WHERE country = Norway;


Question: What is the rank of each mediator based on the number of cases handled, with ties broken by age?

CREATE TABLE Mediators (MediatorID INT, Name VARCHAR(50), Age INT, Experience INT); INSERT INTO Mediators (MediatorID, Name, Age, Experience) VALUES (1, 'John Doe', 45, 12), (2, 'Jane Smith', 38, 7), (3, 'Alice Johnson', 42, 18), (4, 'Bob Brown', 50, 25); CREATE TABLE Cases (CaseID INT, MediatorID INT, Date DATE); INSERT INTO Cases (CaseID, MediatorID, Date) VALUES (1, 1, '2021-01-01'), (2, 1, '2021-02-01'), (3, 2, '2021-03-01'), (4, 3, '2021-04-01'), (5, 3, '2021-05-01'), (6, 4, '2021-06-01');

SELECT MediatorID, Name, RANK() OVER (ORDER BY COUNT(*) DESC, Age) as Rank FROM Mediators JOIN Cases ON Mediators.MediatorID = Cases.MediatorID GROUP BY MediatorID, Name;


Question: Generate PostgreSQL SQL for: Name the date for pescara

CREATE TABLE table_name_76 (date VARCHAR, circuit VARCHAR)

SELECT date FROM table_name_76 WHERE circuit = 'pescara';


Question: What are the total sales figures per region for the 'sales_by_region' table?

SELECT region, SUM(sales_q1 + sales_q2 + sales_q3 + sales_q4) as total_sales FROM sales_by_region GROUP BY region;


Question: Generate PostgreSQL SQL for: What is the To par of the Player with a Score of 70-71=141?

CREATE TABLE table_name_58 (to_par INTEGER, score VARCHAR)

SELECT AVG(to_par) FROM table_name_58 WHERE score = 70 - 71 = 141;


Question: Generate PostgreSQL SQL for: What is the date for the home detroit and visitor was chicago?

CREATE TABLE table_name_82 (date VARCHAR, home VARCHAR, visitor VARCHAR)

SELECT date FROM table_name_82 WHERE home = 'detroit' AND visitor = 'chicago';


Question: Find the maximum number of artworks created by an individual artist

CREATE TABLE Artists (ArtistID INT PRIMARY KEY, ArtistName VARCHAR(255), NumberOfArtworks INT); INSERT INTO Artists (ArtistID, ArtistName, NumberOfArtworks) VALUES (1, 'Vincent van Gogh', 2100), (2, 'Pablo Picasso', 1347), (3, 'Claude Monet', 1643), (4, 'Jackson Pollock', 287);

SELECT MAX(NumberOfArtworks) AS MaxArtworks FROM Artists;


Question: What is the difference in the number of flights operated by 'Intergalactic' and 'UniversalAirlines'?

CREATE TABLE flights (id INT, airline VARCHAR(255)); INSERT INTO flights (id, airline) VALUES (1, 'Intergalactic'), (2, 'UniversalAirlines'), (3, 'Intergalactic'), (4, 'UniversalAirlines'), (5, 'Intergalactic');

SELECT COUNT(*) FILTER (WHERE airline = 'Intergalactic') - COUNT(*) FILTER (WHERE airline = 'UniversalAirlines') as difference;


Question: Generate PostgreSQL SQL for: What is the reunion weight of the contestant who lost 74.4 lbs at the finale?

CREATE TABLE table_28654454_5 (reunion_weight VARCHAR, lbs_lost_finale VARCHAR)

SELECT reunion_weight FROM table_28654454_5 WHERE lbs_lost_finale = '74.4';


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

end $$;

-- fail because cursor has no query bound to it

create or replace function forc_bad() returns void as $$
declare
  c refcursor;

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


Question: What is the total amount spent on raw materials for each product line, including the cost of sub-components?

CREATE TABLE raw_materials (id INT, product_line VARCHAR(50), amount INT, sub_components VARCHAR(50)); INSERT INTO raw_materials (id, product_line, amount, sub_components) VALUES (1, 'product1', 10000, 'component1,component2'); INSERT INTO raw_materials (id, product_line, amount, sub_components) VALUES (2, 'product2', 15000, 'component3,component4');

SELECT product_line, SUM(amount + (SELECT SUM(amount) FROM raw_materials WHERE sub_components LIKE CONCAT('%', product_line, '%'))) FROM raw_materials GROUP BY product_line;


Question: Write the DML statement from PostgreSQL regression test 'join' (example 323).

Explanation: DML from PostgreSQL core regression test for Join.


Question: Generate PostgreSQL SQL for: How many players were drafted by the Edmonton Oilers?

CREATE TABLE table_2840500_2 (player VARCHAR, nhl_team VARCHAR)

SELECT COUNT(player) FROM table_2840500_2 WHERE nhl_team = 'Edmonton Oilers';


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

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