Question: What is the total number of hours spent on professional development by teachers in urban schools?

CREATE TABLE schools (school_id INT, school_type VARCHAR(20), teacher_id INT, hours_pd INT); INSERT INTO schools (school_id, school_type, teacher_id, hours_pd) VALUES (1, 'Urban', 1, 5), (2, 'Rural', 2, 3), (3, 'Urban', 3, 4), (4, 'Suburban', 4, 6), (5, 'Urban', 5, 2);

SELECT school_type, SUM(hours_pd) as total_hours FROM schools WHERE school_type = 'Urban' GROUP BY school_type;


Question: Find the number of fraudulent transactions and their total value, excluding transactions with a value less than 1000, for each employee in the sales department.

CREATE TABLE transactions (transaction_id INT, employee_id INT, transaction_type VARCHAR(20), transaction_value DECIMAL(10,2), is_fraudulent BOOLEAN);

SELECT employee_id, COUNT(*) as fraud_count, SUM(transaction_value) as total_fraud_value FROM transactions WHERE transaction_type = 'Sales' AND is_fraudulent = TRUE AND transaction_value >= 1000 GROUP BY employee_id;


Question: Generate PostgreSQL SQL for: Who was the GT2 Winning Team if Greg Mansell Leo Mansell was the LMP1 Winning Team?

CREATE TABLE table_24865763_2 (gt2_winning_team VARCHAR, lmp1_winning_team VARCHAR)

SELECT gt2_winning_team FROM table_24865763_2 WHERE lmp1_winning_team = 'Greg Mansell Leo Mansell';


Question: Which customers have accounts in the 'High Value' category and have made at least one transaction?

CREATE TABLE customers (customer_id INT, name TEXT); INSERT INTO customers (customer_id, name) VALUES (1, 'John Doe'); INSERT INTO customers (customer_id, name) VALUES (2, 'Jane Smith'); CREATE TABLE accounts (account_id INT, account_type TEXT, customer_id INT); INSERT INTO accounts (account_id, account_type, customer_id) VALUES (1, 'High Value', 1); INSERT INTO accounts (account_id, account_type, customer_id) VALUES (2, 'Standard', 2); CREATE TABLE customer_transactions (transaction_id INT, customer_id INT); INSERT INTO customer_transactions (transaction_id, customer_id) VALUES (1, 1);

SELECT customers.name FROM customers JOIN accounts ON customers.customer_id = accounts.customer_id JOIN customer_transactions ON customers.customer_id = customer_transactions.customer_id WHERE accounts.account_type = 'High Value';


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

SELECT jsb FROM jsonb_populate_record(NULL::jsbrec, '{"jsb": "123.45"}') q;

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

SELECT count(*) FROM (SELECT jsb FROM jsonb_populate_record(NULL::jsbrec, '{"jsb": "123.45"}') q) AS _sub;


Question: Generate PostgreSQL SQL for: What is the Status with an Author that is colbert?

CREATE TABLE table_name_25 (status VARCHAR, authors VARCHAR)

SELECT status FROM table_name_25 WHERE authors = 'colbert';


Question: What is the average water temperature in salmon farms in Norway?

CREATE TABLE salmon_farms (id INT, name TEXT, country TEXT); CREATE TABLE temperature_readings (id INT, farm_id INT, temperature FLOAT); INSERT INTO salmon_farms (id, name, country) VALUES (1, 'Farm X', 'Norway'), (2, 'Farm Y', 'Norway'), (3, 'Farm Z', 'Canada'); INSERT INTO temperature_readings (id, farm_id, temperature) VALUES (1, 1, 12.5), (2, 1, 13.0), (3, 2, 11.0), (4, 2, 11.5), (5, 3, 7.0);

SELECT AVG(temperature) FROM temperature_readings TR JOIN salmon_farms SF ON TR.farm_id = SF.id WHERE SF.country = 'Norway';


Question: Generate PostgreSQL SQL for: What is the name of the church that is located in florø?

CREATE TABLE table_name_29 (church_name VARCHAR, location_of_the_church VARCHAR)

SELECT church_name FROM table_name_29 WHERE location_of_the_church = 'florø';


Question: What is the average mental health score of students per school in the last year?

CREATE TABLE student_mental_health (student_id INT, school_id INT, mental_health_score INT, date DATE); INSERT INTO student_mental_health (student_id, school_id, mental_health_score, date) VALUES (1, 101, 75, '2021-09-01'); INSERT INTO student_mental_health (student_id, school_id, mental_health_score, date) VALUES (2, 101, 80, '2021-09-02');

SELECT school_id, AVG(mental_health_score) as avg_mental_health_score FROM student_mental_health WHERE date >= DATEADD(year, -1, GETDATE()) GROUP BY school_id ORDER BY avg_mental_health_score DESC;


Question: Insert new labor productivity records for mines in Arizona with productivity scores above 4.5.

CREATE TABLE labor_productivity (id INT, mine_id INT, productivity_score FLOAT, FOREIGN KEY (mine_id) REFERENCES mines(id)); CREATE TABLE mines (id INT, name VARCHAR(50), location VARCHAR(50), PRIMARY KEY(id)); INSERT INTO mines (id, name, location) VALUES (13, 'Arizona Mine', 'Arizona'); INSERT INTO mines (id, name, location) VALUES (14, 'Southwest Mine', 'Arizona');

INSERT INTO labor_productivity (id, mine_id, productivity_score) VALUES (9, 13, 4.6), (10, 14, 4.8);


Question: Generate PostgreSQL SQL for: How many Silver medals did the Nation of Croatia receive with a Total medal of more than 1?

CREATE TABLE table_name_3 (silver INTEGER, nation VARCHAR, bronze VARCHAR, total VARCHAR)

SELECT MIN(silver) FROM table_name_3 WHERE bronze = 1 AND total > 1 AND nation = 'croatia';


Question: PostgreSQL regression test 'with': Write the SELECT query (example 73).

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

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


Question: Generate PostgreSQL SQL for: What was the year of Megáll az Idö?

CREATE TABLE table_name_60 (year VARCHAR, original_title VARCHAR)

SELECT year FROM table_name_60 WHERE original_title = 'megáll az idö';


Question: What is the total quantity of coal, iron, and gold mined by each mine?

CREATE TABLE Mine (MineID int, MineName varchar(50), Location varchar(50)); CREATE TABLE Coal (CoalID int, MineID int, CoalQuantity int); CREATE TABLE Iron (IronID int, MineID int, IronQuantity int); CREATE TABLE Gold (GoldID int, MineID int, GoldQuantity int); INSERT INTO Mine VALUES (1, 'ABC Mine', 'Colorado'), (2, 'DEF Mine', 'Wyoming'), (3, 'GHI Mine', 'West Virginia'); INSERT INTO Coal VALUES (1, 1, 5000), (2, 2, 7000), (3, 3, 6000); INSERT INTO Iron VALUES (1, 1, 8000), (2, 2, 9000), (3, 3, 10000); INSERT INTO Gold VALUES (1, 1, 12000), (2, 2, 15000), (3, 3, 18000);

SELECT MineName, SUM(CoalQuantity) as TotalCoalQuantity, SUM(IronQuantity) as TotalIronQuantity, SUM(GoldQuantity) as TotalGoldQuantity FROM Mine LEFT JOIN Coal ON Mine.MineID = Coal.MineID LEFT JOIN Iron ON Mine.MineID = Iron.MineID LEFT JOIN Gold ON Mine.MineID = Gold.MineID GROUP BY MineName;


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

SELECT magic, version, ntuples, bsize, bmsize, bmshift, maxbucket, highmask,
lowmask, ovflpoint, firstfree, nmaps, procid, spares, mapp FROM
hash_metapage_info(get_raw_page('test_hash_a_idx', 5));

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


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

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

SELECT count(*) FROM (select '(!,()'::textrange) AS _sub;


Question: Generate PostgreSQL SQL for: What is the attendance of week 12?

CREATE TABLE table_name_63 (attendance INTEGER, week VARCHAR)

SELECT MIN(attendance) FROM table_name_63 WHERE week = 12;


Question: How many 'Assault' and 'Robbery' crimes were reported in each district for 2021, from the 'CrimeStats' table?

CREATE TABLE CrimeStats (district VARCHAR(20), crimeType VARCHAR(20), year INT, number INT);

SELECT district, crimeType, SUM(number) FROM CrimeStats WHERE (crimeType IN ('Assault', 'Robbery') AND year = 2021) GROUP BY district, crimeType;


Question: What is the total installed capacity of renewable energy projects, broken down by country and project type?

CREATE TABLE renewable_energy (country VARCHAR(50), project_type VARCHAR(50), installed_capacity INT); INSERT INTO renewable_energy (country, project_type, installed_capacity) VALUES ('USA', 'Wind', 3000), ('USA', 'Solar', 5000), ('Mexico', 'Wind', 2000), ('Mexico', 'Solar', 4000);

SELECT country, project_type, SUM(installed_capacity) FROM renewable_energy GROUP BY country, project_type;


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

SELECT schema_to_xml('testxmlschema', true, false, '');

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

SELECT count(*) FROM (SELECT schema_to_xml('testxmlschema', true, false, '')) AS _sub;


Question: How many local vendors have partnered with our platform in Spain?

CREATE TABLE vendors (id INT, name TEXT, country TEXT); INSERT INTO vendors (id, name, country) VALUES (1, 'Vendor A', 'Spain'), (2, 'Vendor B', 'France');

SELECT COUNT(*) FROM vendors WHERE country = 'Spain';


Question: What is the publication rate of graduate students in the Art department?

CREATE TABLE students (id INT, name VARCHAR(100), department VARCHAR(50), publication_count INT); INSERT INTO students VALUES (1, 'Taylor Brown', 'Art', 1);

SELECT department, AVG(publication_count) FROM students WHERE department = 'Art' GROUP BY department;


Question: What is the total number of players who play sports and action games?

CREATE TABLE Players (PlayerID INT, GameType VARCHAR(10)); INSERT INTO Players (PlayerID, GameType) VALUES (1, 'Sports'), (2, 'Strategy'), (3, 'Action'), (4, 'Simulation');

SELECT COUNT(*) FROM Players WHERE GameType IN ('Sports', 'Action');


Question: Generate PostgreSQL SQL for: Find the name of medication used on the patient who stays in room 111?

CREATE TABLE Prescribes (Patient VARCHAR, Medication VARCHAR); CREATE TABLE Medication (name VARCHAR, Code VARCHAR); CREATE TABLE patient (SSN VARCHAR); CREATE TABLE stay (Patient VARCHAR)

SELECT T4.name FROM stay AS T1 JOIN patient AS T2 ON T1.Patient = T2.SSN JOIN Prescribes AS T3 ON T3.Patient = T2.SSN JOIN Medication AS T4 ON T3.Medication = T4.Code WHERE room = 111;


Question: What is the total billing amount for cases with a successful outcome in New York?

CREATE TABLE cases (case_id INT, case_outcome VARCHAR(20), billing_amount DECIMAL(10, 2), case_location VARCHAR(20)); INSERT INTO cases (case_id, case_outcome, billing_amount, case_location) VALUES (1, 'Successful', 3000, 'New York'), (2, 'Unsuccessful', 2000, 'New York');

SELECT SUM(billing_amount) FROM cases WHERE case_outcome = 'Successful' AND case_location = 'New York';


Question: Generate PostgreSQL SQL for: What is the Money ($) amount of the Player with a To par of e?

CREATE TABLE table_name_2 (money___$__ VARCHAR, to_par VARCHAR)

SELECT money___$__ FROM table_name_2 WHERE to_par = 'e';


Question: Generate PostgreSQL SQL for: What company has more than 195.34 billion in sales, ranked greater than 7, more than 11.29 billion in profits, and a market value greater than 198.14 billion?

CREATE TABLE table_name_62 (company VARCHAR, market_value__billion_$_ VARCHAR, profits__billion_$_ VARCHAR, sales__billion_$_ VARCHAR, rank VARCHAR)

SELECT company FROM table_name_62 WHERE sales__billion_$_ > 195.34 AND rank > 7 AND profits__billion_$_ > 11.29 AND market_value__billion_$_ > 198.14;


Question: What is the total weight of astronauts from the USA?

CREATE TABLE MedicalProfiles(astronaut_id INT, height INT, weight INT, nationality VARCHAR(50));

SELECT SUM(weight) FROM MedicalProfiles WHERE nationality = 'USA';


Question: What is the count of employees who have completed compliance training?

CREATE TABLE Training (EmployeeID INT, TrainingName VARCHAR(50)); INSERT INTO Training (EmployeeID, TrainingName) VALUES (1, 'Diversity and Inclusion Training'), (2, 'Cybersecurity Training'), (3, 'Compliance Training'), (4, 'Cybersecurity Training');

SELECT COUNT(DISTINCT EmployeeID) FROM Training WHERE TrainingName = 'Compliance Training';


Question: Generate PostgreSQL SQL for: What is the total number of loses of the club with a 4 position and less than 23 goals conceded?

CREATE TABLE table_name_96 (loses VARCHAR, position VARCHAR, goals_conceded VARCHAR)

SELECT COUNT(loses) FROM table_name_96 WHERE position = 4 AND goals_conceded < 23;


Question: Generate PostgreSQL SQL for: What was the original air date for the episode with 3.90 u.s. viewers (millions)?

CREATE TABLE table_12722302_2 (original_air_date VARCHAR, us_viewers__million_ VARCHAR)

SELECT original_air_date FROM table_12722302_2 WHERE us_viewers__million_ = '3.90';


Question: How many customers in each size category have purchased in the last 3 months?

CREATE TABLE Size_Categories (size_id INT, size_category VARCHAR(255)); INSERT INTO Size_Categories (size_id, size_category) VALUES (1, 'XS'), (2, 'S'), (3, 'M'), (4, 'L'), (5, 'XL'), (6, 'XXL'), (7, 'XXXL'); CREATE TABLE Purchase_History (customer_id INT, purchase_date DATE, size_id INT); INSERT INTO Purchase_History (customer_id, purchase_date, size_id) VALUES (1, '2022-03-15', 3), (2, '2022-03-01', 2), (3, '2022-03-10', 5), (4, '2022-03-20', 4), (5, '2022-03-25', 7), (6, '2022-03-30', 1), (7, '2022-04-01', 6);

SELECT size_category, COUNT(*) FROM Size_Categories JOIN Purchase_History ON Size_Categories.size_id = Purchase_History.size_id WHERE purchase_date BETWEEN DATE_SUB(CURRENT_DATE, INTERVAL 3 MONTH) AND CURRENT_DATE GROUP BY size_category;


Question: Generate PostgreSQL SQL for: Who was the driver in round 8?

CREATE TABLE table_27913160_3 (driver VARCHAR, round VARCHAR)

SELECT driver FROM table_27913160_3 WHERE round = 8;


Question: Generate PostgreSQL SQL for: Which title has a translation in it of 1000 lies?

CREATE TABLE table_name_32 (title VARCHAR, translation VARCHAR)

SELECT title FROM table_name_32 WHERE translation = '1000 lies';


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

DELETE FROM temporal_fk_rng2rng WHERE id = '[3,4)';

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


Question: Generate PostgreSQL SQL for: Who are the rowers for Australia?

CREATE TABLE table_name_54 (rowers VARCHAR, country VARCHAR)

SELECT rowers FROM table_name_54 WHERE country = 'australia';


Question: What is the average time to resolution for security incidents in the finance department, and how does it compare to the average for the entire organization?

CREATE TABLE incidents (incident_id INT, incident_date DATE, resolution_date DATE, department VARCHAR(50));

SELECT AVG(DATEDIFF(resolution_date, incident_date)) as avg_resolution_time_finance FROM incidents WHERE department = 'finance'; SELECT AVG(DATEDIFF(resolution_date, incident_date)) as avg_resolution_time_org FROM incidents;


Question: Show the average cultural competency score for community health workers in each region

CREATE TABLE community_health_workers (id INT PRIMARY KEY, name VARCHAR(255), region VARCHAR(255), years_experience INT, cultural_competency_score INT); INSERT INTO community_health_workers (id, name, region, years_experience, cultural_competency_score) VALUES (1, 'Ada Williams', 'Southeast', 8, 95), (2, 'Brian Johnson', 'Midwest', 5, 80), (3, 'Carla Garcia', 'West', 12, 90), (4, 'Ella Jones', 'Northeast', 6, 85), (5, 'Farhad Ahmed', 'South', 10, 93), (6, 'Graciela Gutierrez', 'Central', 11, 94), (7, 'Hee Jeong Lee', 'Northwest', 7, 87), (8, 'Ibrahim Hussein', 'East', 9, 96), (9, 'Jasmine Patel', 'Southwest', 8, 91);

SELECT region, AVG(cultural_competency_score) as avg_score FROM community_health_workers GROUP BY region;


Question: Generate PostgreSQL SQL for: What are the names of tourist attractions that can be reached by walk or is at address 660 Shea Crescent?

CREATE TABLE Tourist_Attractions (Name VARCHAR, Location_ID VARCHAR, How_to_Get_There VARCHAR); CREATE TABLE Locations (Location_ID VARCHAR, Address VARCHAR)

SELECT T2.Name FROM Locations AS T1 JOIN Tourist_Attractions AS T2 ON T1.Location_ID = T2.Location_ID WHERE T1.Address = '660 Shea Crescent' OR T2.How_to_Get_There = 'walk';


Question: What is the total volume of marine protected areas in the Pacific Ocean?

CREATE TABLE marine_protected_areas (area_name TEXT, area_size INTEGER, avg_depth REAL, ocean_basin TEXT);

SELECT SUM(area_size) FROM marine_protected_areas WHERE ocean_basin = 'Pacific';


Question: Delete records of machines that have been under maintenance for over a year.

CREATE TABLE machines (id INT, model VARCHAR(50), year INT, status VARCHAR(50), maintenance_start_date DATE); INSERT INTO machines (id, model, year, status, maintenance_start_date) VALUES (1, 'CNC Mill', 2015, 'Operational', '2021-02-01'); INSERT INTO machines (id, model, year, status, maintenance_start_date) VALUES (2, '3D Printer', 2018, 'Under Maintenance', '2022-05-10');

DELETE FROM machines WHERE status = 'Under Maintenance' AND maintenance_start_date <= DATEADD(year, -1, GETDATE());


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

INSERT INTO FLOAT4_TBL(f1) VALUES ('123            5');

Explanation: DML from PostgreSQL core regression test for Float4.


Question: Generate PostgreSQL SQL for: Which country has Hydra Head Records on February 2005?

CREATE TABLE table_name_96 (country VARCHAR, label VARCHAR, date VARCHAR)

SELECT country FROM table_name_96 WHERE label = 'hydra head records' AND date = 'february 2005';


Question: Generate PostgreSQL SQL for: What is 4zr's callsign?

CREATE TABLE table_name_67 (callsign VARCHAR, on_air_id VARCHAR)

SELECT callsign FROM table_name_67 WHERE on_air_id = '4zr';


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

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

SELECT count(*) FROM (select jsonb_path_query('"12:34:56 +05:30"', '$.date()')) AS _sub;


Question: Show the most common marine species by location.

CREATE TABLE SpeciesLocation (ID INT, Species VARCHAR(50), Location VARCHAR(50), Count INT, ObservationDate DATE); INSERT INTO SpeciesLocation (ID, Species, Location, Count, ObservationDate) VALUES (1, 'Starfish', 'Atlantic', 300, '2020-01-01'), (2, 'Dolphin', 'Pacific', 250, '2020-01-02'), (3, 'Shark', 'Atlantic', 400, '2020-01-03'), (4, 'Jellyfish', 'Atlantic', 500, '2020-01-04');

SELECT Location, Species, Count, RANK() OVER (PARTITION BY Location ORDER BY Count DESC) as Rank FROM SpeciesLocation;


Question: Identify hotels in 'Asia' that have adopted AI chatbots and offer a 'spa' facility.

CREATE TABLE hotel_tech (hotel_id INT, hotel_name TEXT, region TEXT, ai_chatbot BOOLEAN, spa BOOLEAN); INSERT INTO hotel_tech (hotel_id, hotel_name, region, ai_chatbot, spa) VALUES (1, 'Hotel Marina', 'Asia', TRUE, TRUE), (2, 'Hotel Bellagio', 'Europe', FALSE, FALSE);

SELECT hotel_name FROM hotel_tech WHERE region = 'Asia' AND ai_chatbot = TRUE AND spa = TRUE;


Question: What is the average price of samarium in Japan in 2017?

CREATE TABLE japan_samarium (id INT, year INT, price DECIMAL); INSERT INTO japan_samarium (id, year, price) VALUES (1, 2015, 250), (2, 2016, 260), (3, 2017, 270);

SELECT AVG(price) FROM japan_samarium WHERE year = 2017;


Question: Generate PostgreSQL SQL for: What is the  p1 diameter (mm) when .300 lapua magnum is the chambering?

CREATE TABLE table_26967904_2 (p1_diameter__mm_ VARCHAR, chambering VARCHAR)

SELECT p1_diameter__mm_ FROM table_26967904_2 WHERE chambering = '.300 Lapua Magnum';


Question: What is the percentage of female content creators in the Pacific region?

CREATE TABLE content_creators (id INT, gender VARCHAR, region VARCHAR); INSERT INTO content_creators (id, gender, region) VALUES (1, 'Female', 'Pacific'); INSERT INTO content_creators (id, gender, region) VALUES (2, 'Male', 'Atlantic');

SELECT region, gender, COUNT(*) as count, ROUND(COUNT(*) * 100.0 / (SELECT COUNT(*) FROM content_creators WHERE region = 'Pacific'), 2) as percentage FROM content_creators WHERE region = 'Pacific' GROUP BY region, gender;


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

-- Here, RLS checks should succeed while moving row from part_a_10_a_20 to
-- part_d_1_15. Even though the UPDATE is setting 'c' to an odd number, the
-- trigger at the destination partition again makes it an even number.
UPDATE range_parted set a = 'b', c = 151 WHERE a = 'a' and c = 200;

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


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

CREATE TABLE prt1_adv_p1 PARTITION OF prt1_adv FOR VALUES FROM (100) TO (200);

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


Question: Generate PostgreSQL SQL for: How many circuits had a winning team of #1 patrón highcroft racing ang gtc winning team #81 alex job racing ?

CREATE TABLE table_24037660_2 (circuit VARCHAR, lmp_winning_team VARCHAR, gtc_winning_team VARCHAR)

SELECT COUNT(circuit) FROM table_24037660_2 WHERE lmp_winning_team = '#1 Patrón Highcroft Racing' AND gtc_winning_team = '#81 Alex Job Racing';


Question: Rank suppliers by their sustainability scores.

CREATE TABLE suppliers (id INT, name VARCHAR(50), country VARCHAR(50), sustainability_score INT); INSERT INTO suppliers (id, name, country, sustainability_score) VALUES (1, 'GreenTech', 'USA', 85); INSERT INTO suppliers (id, name, country, sustainability_score) VALUES (2, 'EcoInnovations', 'Canada', 90);

SELECT *, ROW_NUMBER() OVER (ORDER BY sustainability_score DESC) as rank FROM suppliers;


Question: What are the names and construction dates of all tunnels in Japan that have a length greater than 5000 meters?

CREATE TABLE Tunnels (TunnelID INT, Name TEXT, Length FLOAT, ConstructionYear INT, Country TEXT); INSERT INTO Tunnels (TunnelID, Name, Length, ConstructionYear, Country) VALUES (1, 'Seikan Tunnel', 53.85, 1988, 'Japan');

SELECT Tunnels.Name, Tunnels.ConstructionYear FROM Tunnels WHERE Tunnels.Length > 5000.0 AND Tunnels.Country = 'Japan';


Question: Calculate the revenue by dish type.

CREATE TABLE orders (id INT, dish_id INT, dish_type TEXT, price FLOAT); INSERT INTO orders (id, dish_id, dish_type, price) VALUES (1, 1, 'vegetarian', 7.50), (2, 3, 'non-vegetarian', 11.25), (3, 2, 'vegetarian', 8.95), (4, 1, 'vegetarian', 7.50), (5, 4, 'vegan', 9.75), (6, 5, 'vegan', 10.50), (7, 2, 'vegetarian', 8.95), (8, 1, 'vegetarian', 7.50);

SELECT dish_type, SUM(price) FROM orders GROUP BY dish_type;


Question: Generate PostgreSQL SQL for: What is the score for the game with the record of 3–12?

CREATE TABLE table_27698941_6 (score VARCHAR, record VARCHAR)

SELECT score FROM table_27698941_6 WHERE record = '3–12';


Question: Generate PostgreSQL SQL for: How many fastest laps for the nation with 32 (30) entries and starts and fewer than 2 podiums?

CREATE TABLE table_name_74 (fastest_laps INTEGER, race_entries__starts_ VARCHAR, podiums VARCHAR)

SELECT MIN(fastest_laps) FROM table_name_74 WHERE race_entries__starts_ = '32 (30)' AND podiums < 2;


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

INSERT INTO num_input_test(n1) VALUES ('123._456');

Explanation: DML from PostgreSQL core regression test for Numeric.


Question: List travel advisories issued for Colombia in Q2 2022.

CREATE TABLE travel_advisories (country VARCHAR(20), quarter INT, advisory VARCHAR(100)); INSERT INTO travel_advisories (country, quarter, advisory) VALUES ('Colombia', 2, 'Avoid non-essential travel'), ('Peru', 2, 'Exercise increased caution');

SELECT advisory FROM travel_advisories WHERE country = 'Colombia' AND quarter = 2;


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

SELECT roundtrip('[null, null]', 'ARRAY');

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


Question: Delete outdated building permits from the BuildingPermits table.

CREATE TABLE BuildingPermits (PermitID INT, PermitNumber VARCHAR(50), IssueDate DATE, ExpirationDate DATE, ProjectID INT, FOREIGN KEY (ProjectID) REFERENCES Projects(ProjectID));

DELETE FROM BuildingPermits WHERE ExpirationDate < CURDATE();


Question: Generate PostgreSQL SQL for: What is the highest number drawn when the position was 12?

CREATE TABLE table_name_50 (drawn INTEGER, position VARCHAR)

SELECT MAX(drawn) FROM table_name_50 WHERE position = 12;


Question: What is the total duration of all classical songs?

CREATE TABLE songs (id INT, title TEXT, length FLOAT, genre TEXT); INSERT INTO songs (id, title, length, genre) VALUES (1, 'Song1', 3.2, 'classical'), (2, 'Song2', 4.1, 'rock'), (3, 'Song3', 3.8, 'pop'), (4, 'Song4', 2.1, 'classical'), (5, 'Song5', 5.3, 'classical');

SELECT SUM(length) FROM songs WHERE genre = 'classical';


Question: Determine the percentage of regions with a high risk rating in the last 6 months.

CREATE TABLE GeopoliticalRiskAssessments (Id INT, Region VARCHAR(255), RiskRating VARCHAR(255), AssessmentDate DATE); INSERT INTO GeopoliticalRiskAssessments (Id, Region, RiskRating, AssessmentDate) VALUES (5, 'Europe', 'High', '2021-12-01'); INSERT INTO GeopoliticalRiskAssessments (Id, Region, RiskRating, AssessmentDate) VALUES (6, 'Africa', 'Medium', '2022-02-15');

SELECT COUNT(*) * 100.0 / (SELECT COUNT(*) FROM GeopoliticalRiskAssessments WHERE AssessmentDate >= DATEADD(month, -6, GETDATE())) as Percentage FROM GeopoliticalRiskAssessments WHERE RiskRating = 'High';


Question: Write a SQL query to retrieve the names, claim dates, and claim amounts for claims with a status of 'Approved'

SELECT p.name, c.claim_date, c.claim_amount FROM claims c JOIN policyholders p ON c.policyholder_id = p.policyholder_id WHERE c.status = 'Approved';


Question: What are the names of all wheelchair-accessible bus stops?

CREATE TABLE Stops(id INT, name TEXT, wheelchair_accessible BOOLEAN);

SELECT name FROM Stops WHERE wheelchair_accessible = TRUE;


Question: PostgreSQL Plpgsql: show example 72.

CREATE OR REPLACE FUNCTION testfunc(integer) RETURNS integer AS $$ .... $$ LANGUAGE plpgsql;

Explanation: Example from PostgreSQL documentation on Plpgsql.


Question: Generate PostgreSQL SQL for: How many warfare deaths befell the choctaw nation?

CREATE TABLE table_name_33 (deaths_from_warfare VARCHAR, nation VARCHAR)

SELECT deaths_from_warfare FROM table_name_33 WHERE nation = 'choctaw';


Question: What is the average cost of materials for bridges constructed in California?

CREATE TABLE Bridges (BridgeID INT, Location VARCHAR(20), Cost FLOAT); INSERT INTO Bridges (BridgeID, Location, Cost) VALUES (1, 'California', 5000000);

SELECT AVG(Cost) FROM Bridges WHERE Location = 'California' AND BridgeID IN (SELECT BridgeID FROM Bridges WHERE Location = 'California');


Question: PostgreSQL regression test 'create_index': Write the SELECT query (example 363).

SELECT count(*) FROM tenk1
  WHERE hundred = 42 AND (thousand = 42 OR thousand = 99);

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

SELECT count(*) FROM (SELECT count(*) FROM tenk1
  WHERE hundred = 42 AND (thousand = 42 OR thousand = 99)) AS _sub;


Question: What is the average capacity of clinics in rural Montana?

CREATE TABLE clinics (id INT, name VARCHAR(50), type VARCHAR(50), capacity INT, region VARCHAR(50)); INSERT INTO clinics (id, name, type, capacity, region) VALUES (1, 'Clinic A', 'Primary Care', 50, 'Rural Montana');

SELECT AVG(clinics.capacity) FROM clinics WHERE clinics.region = 'Rural Montana';


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

Explanation: DDL from PostgreSQL core regression test for Rowsecurity.


Question: What is the total revenue for each salesperson who sold garments with a price above '200'?

CREATE TABLE sales (id INT, salesperson_id INT, garment_id INT, region TEXT, price INT); INSERT INTO sales (id, salesperson_id, garment_id, region, price) VALUES (1, 1, 1, 'Paris', 250), (2, 1, 2, 'London', 120), (3, 2, 3, 'Paris', 180), (4, 2, 4, 'London', 220), (5, 3, 5, 'Berlin', 200), (6, 3, 6, 'Berlin', 160);

SELECT salesperson_id, SUM(price) AS total_revenue FROM sales WHERE price > 200 GROUP BY salesperson_id;


Question: How many students with disabilities are enrolled in each region?

CREATE TABLE StudentsWithDisabilities (ID INT, Name VARCHAR(50), Disability VARCHAR(50), Region VARCHAR(50)); INSERT INTO StudentsWithDisabilities (ID, Name, Disability, Region) VALUES (1, 'John Doe', 'Visual Impairment', 'Northeast'); INSERT INTO StudentsWithDisabilities (ID, Name, Disability, Region) VALUES (2, 'Jane Smith', 'Hearing Impairment', 'Southeast'); INSERT INTO StudentsWithDisabilities (ID, Name, Disability, Region) VALUES (3, 'Bob Johnson', 'Learning Disability', 'Midwest');

SELECT Region, COUNT(*) as NumStudents FROM StudentsWithDisabilities GROUP BY Region;


Question: How many algorithmic fairness incidents were reported in Oceania in the last month?

CREATE TABLE fairness_incidents (incident_id INT, incident_date DATE, region TEXT); INSERT INTO fairness_incidents (incident_id, incident_date, region) VALUES (1, '2022-06-15', 'Oceania'), (2, '2022-07-11', 'Oceania'), (3, '2022-08-01', 'Oceania');

SELECT COUNT(*) FROM fairness_incidents WHERE region = 'Oceania' AND incident_date >= '2022-07-01' AND incident_date < '2022-08-01';


Question: Generate PostgreSQL SQL for: Name the lowest average for interview more than 9.57 and delaware and evening gown more than 9.77

CREATE TABLE table_name_42 (average INTEGER, evening_gown VARCHAR, interview VARCHAR, country VARCHAR)

SELECT MIN(average) FROM table_name_42 WHERE interview > 9.57 AND country = 'delaware' AND evening_gown > 9.77;


Question: Generate PostgreSQL SQL for: Which School has a #/ County of 85 wabash, and an IHSAA Football Class of A, and a Mascot of norsemen?

CREATE TABLE table_name_43 (school VARCHAR, mascot VARCHAR, _number___county VARCHAR, ihsaa_football_class VARCHAR)

SELECT school FROM table_name_43 WHERE _number___county = '85 wabash' AND ihsaa_football_class = 'a' AND mascot = 'norsemen';


Question: Show a query using PostgreSQL contrib extension 'intarray' (example 79).

SELECT count(*) from test__int WHERE a @> '{20,23}' or a @> '{50,68}';

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


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

select jsonb_path_query('1', 'lax $[*]');

SELECT count(*) FROM (select jsonb_path_query('1', 'lax $[*]')) AS _sub;


Question: How many TEUs were handled by each port in the cargo_handling table in chronological order?

CREATE TABLE cargo_handling (port_id INT, port_name VARCHAR(50), teu_count INT, handling_date DATE); INSERT INTO cargo_handling (port_id, port_name, teu_count, handling_date) VALUES (1, 'Port_A', 2000, '2022-01-01'), (2, 'Port_B', 3000, '2022-01-02'), (3, 'Port_C', 1000, '2022-01-03');

SELECT port_name, teu_count, ROW_NUMBER() OVER (PARTITION BY port_name ORDER BY handling_date) as rn FROM cargo_handling;


Question: Delete all records of volunteers who have not served any hours in the last year.

CREATE TABLE volunteers (id INT, name TEXT, volunteer_date DATE, hours_served INT);

DELETE FROM volunteers WHERE id NOT IN (SELECT id FROM volunteers WHERE hours_served > 0 AND volunteer_date > DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR));


Question: What is the average donation amount per month in the 'donations' table?

CREATE TABLE donations (id INT, donation_date DATE, amount DECIMAL(10,2));

SELECT AVG(amount) AS avg_monthly_donation FROM donations WHERE donation_date BETWEEN '2022-01-01' AND '2022-12-31' GROUP BY EXTRACT(MONTH FROM donation_date);


Question: PostgreSQL Indices: show example 23.

CREATE INDEX mytable_cat_data ON mytable (category, data);

Explanation: Example from PostgreSQL documentation on Indices.


Question: How many creative AI applications have been developed in Africa?

CREATE TABLE ai_applications (app_id INT, name TEXT, country TEXT, category TEXT); INSERT INTO ai_applications (app_id, name, country, category) VALUES (1, 'ArtBot', 'Nigeria', 'Creative'), (2, 'MusicGen', 'South Africa', 'Creative'), (3, 'DataViz', 'US', 'Analytical'), (4, 'ChatAssist', 'Canada', 'Assistive');

SELECT COUNT(*) FROM ai_applications WHERE country IN (SELECT country FROM ai_applications WHERE category = 'Creative') AND category = 'Creative';


Question: Generate PostgreSQL SQL for: Wins of 0 involves what team?

CREATE TABLE table_name_96 (team VARCHAR, wins VARCHAR)

SELECT team FROM table_name_96 WHERE wins = 0;


Question: Generate PostgreSQL SQL for: What is the lowest average of the contestant with an interview of 8.275 and an evening gown bigger than 8.7?

CREATE TABLE table_name_31 (average INTEGER, interview VARCHAR, evening_gown VARCHAR)

SELECT MIN(average) FROM table_name_31 WHERE interview = 8.275 AND evening_gown > 8.7;


Question: What is the total number of primary care clinics and their average rating, grouped by state?

CREATE TABLE public.healthcare_access (id SERIAL PRIMARY KEY, state TEXT, city TEXT, facility_type TEXT, patients_served INT, rating INT); INSERT INTO public.healthcare_access (state, city, facility_type, patients_served, rating) VALUES ('California', 'San Diego', 'Primary Care Clinic', 7000, 8), ('New York', 'New York City', 'Primary Care Clinic', 12000, 7), ('California', 'Los Angeles', 'Specialty Clinic', 6000, 9);

SELECT state, facility_type, AVG(rating) AS avg_rating, COUNT(*) FILTER (WHERE facility_type = 'Primary Care Clinic') AS clinic_count FROM public.healthcare_access GROUP BY state, facility_type;


Question: Generate PostgreSQL SQL for: What is the candidates for fred e. busbey?

CREATE TABLE table_1342149_13 (candidates VARCHAR, incumbent VARCHAR)

SELECT candidates FROM table_1342149_13 WHERE incumbent = 'Fred E. Busbey';


Question: What is the minimum dissolved oxygen level for each species across all tanks?

CREATE TABLE Tank_Oxygen (tank VARCHAR(50), species VARCHAR(50), dissolved_oxygen FLOAT); INSERT INTO Tank_Oxygen (tank, species, dissolved_oxygen) VALUES ('Tank1', 'Salmon', 6.2), ('Tank1', 'Trout', 7.0), ('Tank2', 'Salmon', 6.5), ('Tank2', 'Tilapia', 5.6);

SELECT species, MIN(dissolved_oxygen) FROM Tank_Oxygen GROUP BY species;


Question: Find the earliest launch date of any satellite still in orbit.

CREATE TABLE satellites_in_orbit (id INT, satellite_id VARCHAR(50), launch_date DATE, in_orbit BOOLEAN);

SELECT MIN(launch_date) FROM satellites_in_orbit WHERE in_orbit = TRUE;


Question: Generate PostgreSQL SQL for: What is the College of the Player from San Miguel Beermen PBA Team?

CREATE TABLE table_name_31 (college VARCHAR, pba_team VARCHAR)

SELECT college FROM table_name_31 WHERE pba_team = 'san miguel beermen';


Question: Generate PostgreSQL SQL for: Who constructed grid 14?

CREATE TABLE table_name_34 (constructor VARCHAR, grid VARCHAR)

SELECT constructor FROM table_name_34 WHERE grid = 14;


Question: Show an example of PostgreSQL CREATE FOREIGN DATA WRAPPER (example 3).

CREATE FOREIGN DATA WRAPPER mywrapper OPTIONS (debug 'true');

Explanation: PostgreSQL CREATE FOREIGN DATA WRAPPER command.


Question: Generate PostgreSQL SQL for: What Country had a Player with a Score of 72-66-72=210?

CREATE TABLE table_name_17 (country VARCHAR, score VARCHAR)

SELECT country FROM table_name_17 WHERE score = 72 - 66 - 72 = 210;


Question: list the names of employees who have never published an article

CREATE TABLE Employees (id INT, name VARCHAR(50)); CREATE TABLE Articles (id INT, author_id INT, published_date DATE); INSERT INTO Employees (id, name) VALUES (1, 'John Doe'); INSERT INTO Employees (id, name) VALUES (2, 'Jane Smith'); INSERT INTO Articles (id, author_id, published_date) VALUES (1, 1, '2022-01-01'); INSERT INTO Articles (id, author_id, published_date) VALUES (2, 2, '2022-01-02');

SELECT e.id, e.name FROM Employees e LEFT JOIN Articles a ON e.id = a.author_id WHERE a.id IS NULL;


Question: Generate PostgreSQL SQL for: How many outcome have a score of 7–6 (9–7) , 6–3?

CREATE TABLE table_22834834_3 (outcome VARCHAR, score_in_the_final VARCHAR)

SELECT COUNT(outcome) FROM table_22834834_3 WHERE score_in_the_final = '7–6 (9–7) , 6–3';


Question: Generate PostgreSQL SQL for: WHAT IS THE MEANING WITH Pīnyīn of chē?

CREATE TABLE table_name_61 (meaning VARCHAR, pīnyīn VARCHAR)

SELECT meaning FROM table_name_61 WHERE pīnyīn = 'chē';


Question: Generate PostgreSQL SQL for: Name the car number for 1997

CREATE TABLE table_1688640_4 (car__number VARCHAR, year_started VARCHAR)

SELECT car__number FROM table_1688640_4 WHERE year_started = 1997;


Question: How many employees in the USA are working in the mining industry by department, ordered by the number of employees in descending order?

CREATE TABLE employees (id INT, mine_name TEXT, location TEXT, department TEXT, employee_id INT, hire_date DATE); INSERT INTO employees (id, mine_name, location, department, employee_id, hire_date) VALUES (1, 'Golden Mine', 'USA', 'Mining', 1001, '2020-01-01'), (2, 'Silver Mine', 'USA', 'Geology', 1002, '2020-01-02'), (3, 'Bronze Mine', 'USA', 'Engineering', 1003, '2020-01-03');

SELECT department, COUNT(employee_id) as num_employees FROM employees WHERE location = 'USA' GROUP BY department ORDER BY num_employees DESC;


Question: What is the maximum production cost for fair trade products?

CREATE TABLE products (product_id INT, product_name VARCHAR(255), production_cost DECIMAL(5,2), fair_trade BOOLEAN); INSERT INTO products (product_id, product_name, production_cost, fair_trade) VALUES (1, 'Fair Trade Coffee', 8.99, true); INSERT INTO products (product_id, product_name, production_cost, fair_trade) VALUES (2, 'Fair Trade Tea', 6.50, true);

SELECT MAX(production_cost) FROM products WHERE fair_trade = true;


Question: Generate PostgreSQL SQL for: For entries with a lost of 5, what is the sum of the draw entry?

CREATE TABLE table_name_23 (draw INTEGER, lost VARCHAR)

SELECT SUM(draw) FROM table_name_23 WHERE lost = 5;


Question: What is the average age of vessels that have had safety incidents in the Mediterranean in 2021?

CREATE TABLE Region (region_id INT PRIMARY KEY, region_name VARCHAR(255)); INSERT INTO Region (region_id, region_name) VALUES (1, 'Mediterranean'); CREATE TABLE Vessel (vessel_id INT PRIMARY KEY, vessel_name VARCHAR(255), region_id INT, build_date DATE); CREATE TABLE Safety_Incident (incident_id INT PRIMARY KEY, vessel_id INT, incident_date DATE);

SELECT AVG(DATEDIFF('day', V.build_date, GETDATE())) FROM Vessel V JOIN Safety_Incident SI ON V.vessel_id = SI.vessel_id WHERE SI.incident_date >= '2021-01-01' AND SI.incident_date < '2022-01-01' AND V.region_id = (SELECT region_id FROM Region WHERE region_name = 'Mediterranean');


Question: Generate PostgreSQL SQL for: What percentage of The Bronx voters occured when Manhattan had 29.9% of voters?

CREATE TABLE table_1108394_34 (the_bronx VARCHAR, manhattan VARCHAR)

SELECT the_bronx FROM table_1108394_34 WHERE manhattan = '29.9_percentage';


Question: How many solar power plants are there in California and Texas?

CREATE TABLE solar_plants (state VARCHAR(50), num_plants INT); INSERT INTO solar_plants (state, num_plants) VALUES ('California', 2153), ('Texas', 1194);

SELECT SUM(num_plants) FROM solar_plants WHERE state IN ('California', 'Texas');


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

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


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

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

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


Question: Generate PostgreSQL SQL for: What is Championship, when Outcome is "runner-up", and when Opponents In Final is "Gigi Fernández Natalia Zvereva"?

CREATE TABLE table_name_55 (championship VARCHAR, outcome VARCHAR, opponents_in_final VARCHAR)

SELECT championship FROM table_name_55 WHERE outcome = 'runner-up' AND opponents_in_final = 'gigi fernández natalia zvereva';


Question: Generate PostgreSQL SQL for: Which player played in 2007?

CREATE TABLE table_name_17 (player VARCHAR, season VARCHAR)

SELECT player FROM table_name_17 WHERE season = '2007';


Question: Find the second-highest salary in the 'administrative' department?

CREATE TABLE departments (id INT, name VARCHAR(50)); CREATE TABLE employees (id INT, name VARCHAR(50), dept_id INT, salary DECIMAL(10, 2));

SELECT salary FROM (SELECT salary FROM employees WHERE dept_id = (SELECT id FROM departments WHERE name = 'administrative') ORDER BY salary DESC LIMIT 2) t ORDER BY salary LIMIT 1;


Question: How many traditional arts are practiced in Oceania?

CREATE TABLE traditional_arts (id INT, name TEXT, type TEXT, region TEXT); INSERT INTO traditional_arts (id, name, type, region) VALUES (1, 'Aboriginal Rock Art', 'Painting', 'Oceania');

SELECT COUNT(*) FROM traditional_arts WHERE region = 'Oceania';


Question: What is the average ticket price for each concert in 'music_festivals' table?

CREATE TABLE music_festivals (festival_id INT, concert_name VARCHAR(255), location VARCHAR(255), date DATE, ticket_price DECIMAL(5,2));

SELECT concert_name, AVG(ticket_price) FROM music_festivals GROUP BY concert_name;


Question: Write the DML statement from PostgreSQL regression test 'foreign_key' (example 262).

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


Question: Generate PostgreSQL SQL for: Who wrote the episode that was directed by Milan Cheylov?

CREATE TABLE table_29219286_1 (written_by VARCHAR, directed_by VARCHAR)

SELECT written_by FROM table_29219286_1 WHERE directed_by = 'Milan Cheylov';


Question: What is the average labor cost for manufacturing garments with the 'silk' fabric type?

CREATE TABLE garment_manufacturing (id INT PRIMARY KEY, garment_id INT, manufacturing_date DATE, labor_hours INT, labor_cost DECIMAL(5,2)); INSERT INTO garment_manufacturing (id, garment_id, manufacturing_date, labor_hours, labor_cost) VALUES (1, 1001, '2022-01-03', 2.5, 25.00), (2, 1002, '2022-01-04', 3.0, 30.00); CREATE TABLE fabric_garment (id INT PRIMARY KEY, fabric_type VARCHAR(50), garment_id INT); INSERT INTO fabric_garment (id, fabric_type, garment_id) VALUES (1, 'denim', 1001), (2, 'silk', 1002);

SELECT AVG(gm.labor_cost) AS avg_labor_cost FROM garment_manufacturing gm JOIN fabric_garment fg ON gm.garment_id = fg.garment_id WHERE fg.fabric_type = 'silk';


Question: Generate PostgreSQL SQL for: If the rebounds are at 87, what are the amount of steals?

CREATE TABLE table_25342713_5 (steals VARCHAR, rebounds VARCHAR)

SELECT steals FROM table_25342713_5 WHERE rebounds = 87;


Question: Calculate the average age difference between athletes in basketball and football.

CREATE TABLE athletes(athlete_id INT, name VARCHAR(50), age INT, sport VARCHAR(20));

SELECT AVG(basketball_age - football_age) AS avg_age_difference FROM (SELECT AVG(age) AS basketball_age FROM athletes WHERE sport = 'basketball') AS basketball, (SELECT AVG(age) AS football_age FROM athletes WHERE sport = 'football') AS football;


Question: What is the number of patients treated for mental health issues by each healthcare provider?

CREATE TABLE Patients (PatientID int, ProviderID int, MentalHealthIssue int);CREATE TABLE Providers (ProviderID int, ProviderName varchar(50));

SELECT ProviderName, COUNT(PatientID) as PatientCount FROM Patients JOIN Providers ON Patients.ProviderID = Providers.ProviderID GROUP BY ProviderID, ProviderName;


Question: PostgreSQL regression test 'foreign_data': Write the SELECT query (example 247).

SELECT * FROM information_schema.foreign_table_options ORDER BY 1, 2, 3, 4;

Explanation: Regression test for Foreign Data in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT * FROM information_schema.foreign_table_options ORDER BY 1, 2, 3, 4) AS _sub;


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

CREATE VIEW v8 AS SELECT * FROM base_table WHERE EXISTS (SELECT 1);

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


Question: Generate PostgreSQL SQL for: What was the last year MCA had a Release?

CREATE TABLE table_name_40 (year_of_release INTEGER, label VARCHAR)

SELECT MAX(year_of_release) FROM table_name_40 WHERE label = 'mca';


Question: How many individuals received support in each country?

CREATE TABLE SupportRecipients (Id INT, Country VARCHAR(50), SupportType VARCHAR(50)); INSERT INTO SupportRecipients (Id, Country, SupportType) VALUES (1, 'Syria', 'Food'), (2, 'Bangladesh', 'Shelter'), (3, 'Syria', 'Medical'), (4, 'Brazil', 'Food');

SELECT Country, COUNT(*) FROM SupportRecipients GROUP BY Country;


Question: What is the revenue from medical sales in Colorado in Q2 2022?

CREATE TABLE Sales (id INT, dispensary TEXT, state TEXT, sale_type TEXT, revenue INT); INSERT INTO Sales (id, dispensary, state, sale_type, revenue) VALUES (1, 'Bud Mart', 'CO', 'medical', 15000), (2, 'Green Earth', 'WA', 'recreational', 20000), (3, 'Emerald City', 'WA', 'medical', 10000);

SELECT SUM(revenue) as q2_medical_revenue FROM Sales WHERE state = 'CO' AND sale_type = 'medical' AND quarter(order_date) = 2 AND year(order_date) = 2022;


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

SELECT '൧' ~ '\d' COLLATE PG_UNICODE_FAST;

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

SELECT count(*) FROM (SELECT '൧' ~ '\d' COLLATE PG_UNICODE_FAST) AS _sub;


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

SELECT f.* FROM FLOAT4_TBL f WHERE f.f1 = '1004.3';

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

SELECT count(*) FROM (SELECT f.* FROM FLOAT4_TBL f WHERE f.f1 = '1004.3') AS _sub;


Question: Identify the conservation status and number of protected areas for marine species in the Indian Ocean.

CREATE TABLE marine_species_indian_ocean (species_name VARCHAR(255), habitat VARCHAR(255)); INSERT INTO marine_species_indian_ocean (species_name, habitat) VALUES ('Whale Shark', 'Indian Ocean'), ('Dugong', 'Indian Ocean'); CREATE TABLE conservation_efforts_indian_ocean (species_name VARCHAR(255), conservation_status VARCHAR(255), protected_areas INT); INSERT INTO conservation_efforts_indian_ocean (species_name, conservation_status, protected_areas) VALUES ('Whale Shark', 'Vulnerable', 25), ('Dugong', 'Endangered', 15);

SELECT m.species_name, c.conservation_status, COUNT(c.protected_areas) AS protected_areas_count FROM marine_species_indian_ocean m INNER JOIN conservation_efforts_indian_ocean c ON m.species_name = c.species_name GROUP BY m.species_name, c.conservation_status;


Question: What is the total number of buses in the 'transportation' schema?

CREATE SCHEMA transportation; CREATE TABLE transportation.buses (id INT PRIMARY KEY, model VARCHAR(255), year INT); INSERT INTO transportation.buses (id, model, year) VALUES (1, 'Mini Bus', 2015), (2, 'City Bus', 2018), (3, 'Electric Bus', 2020);

SELECT COUNT(*) FROM transportation.buses;


Question: What is the average number of posts per user in the users and posts tables?

CREATE TABLE users (id INT, name VARCHAR(50)); INSERT INTO users (id, name) VALUES (1, 'Alice'), (2, 'Bob'), (3, 'Charlie'); CREATE TABLE posts (id INT, user_id INT, content TEXT); INSERT INTO posts (id, user_id, content) VALUES (1, 1, 'Hello'), (2, 1, 'World'), (3, 2, 'SQL');

SELECT AVG(post_per_user) FROM (SELECT COUNT(p.id) AS post_per_user FROM posts p JOIN users u ON p.user_id = u.id GROUP BY u.id) AS subquery;


Question: Insert records of new recruits who joined the army in 2023 into the army_recruits table

CREATE TABLE army_recruits (recruit_id INT, name VARCHAR(50), rank VARCHAR(50), join_date DATE);

INSERT INTO army_recruits (recruit_id, name, rank, join_date) VALUES (1, 'Minh Nguyen', 'Private', '2023-04-01'), (2, 'Aisha Said', 'Private', '2023-07-15'), (3, 'Konstantinos Papadopoulos', 'Private', '2023-11-27');


Question: How many refugees were supported by each organization by age group and gender in Q1 2021?

CREATE TABLE refugee_support (refugee_id INT, organization_id INT, age INT, gender VARCHAR(10), support_date DATE); INSERT INTO refugee_support (refugee_id, organization_id, age, gender, support_date) VALUES (1, 201, 23, 'Male', '2021-01-12'), (2, 201, 30, 'Female', '2021-02-03'), (3, 202, 18, 'Male', '2021-03-25'), (4, 203, 45, 'Female', '2021-01-05');

SELECT organization_id, gender, age_group, COUNT(*) as supported_refugees FROM (SELECT organization_id, gender, CASE WHEN age <= 17 THEN 'Minor' WHEN age BETWEEN 18 AND 64 THEN 'Adult' ELSE 'Senior' END as age_group FROM refugee_support WHERE EXTRACT(QUARTER FROM support_date) = 1 AND EXTRACT(YEAR FROM support_date) = 2021) t GROUP BY organization_id, gender, age_group;


Question: What is the average yield for strains in each category?

CREATE TABLE strains (id INT, name TEXT, category TEXT, yield FLOAT); INSERT INTO strains (id, name, category, yield) VALUES (1, 'Purple Kush', 'Indica', 0.5), (2, 'Northern Lights', 'Indica', 0.6), (3, 'Granddaddy Purple', 'Indica', 0.7), (4, 'Sour Diesel', 'Sativa', 0.6), (5, 'Blue Dream', 'Hybrid', 0.7), (6, 'Green Crack', 'Sativa', 0.8), (7, 'OG Kush', 'Hybrid', 0.9);

SELECT category, AVG(yield) FROM strains GROUP BY category;


Question: Find the average depth of marine life research sites in the Southern Hemisphere

CREATE TABLE marine_sites (site_id INT, site_name VARCHAR(255), longitude DECIMAL(9,6), latitude DECIMAL(9,6), depth DECIMAL(5,2)); CREATE VIEW southern_hemisphere_sites AS SELECT * FROM marine_sites WHERE latitude BETWEEN -90 AND 0;

SELECT AVG(depth) FROM southern_hemisphere_sites;


Question: PostgreSQL regression test 'sqljson': Write the SELECT query (example 163).

SELECT JSON_OBJECTAGG(mod(i,100): (i)::text FORMAT JSON WITH UNIQUE)
FROM generate_series(0, 199) i;

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

SELECT count(*) FROM (SELECT JSON_OBJECTAGG(mod(i,100): (i)::text FORMAT JSON WITH UNIQUE)
FROM generate_series(0, 199) i) AS _sub;


Question: Generate PostgreSQL SQL for: what is the earliest date for the album that had a catalog number of 3645, was formatted as a cd and was under the luaka bop label?

CREATE TABLE table_name_2 (date INTEGER, label VARCHAR, catalog VARCHAR, format VARCHAR)

SELECT MIN(date) FROM table_name_2 WHERE catalog = '3645' AND format = 'cd' AND label = 'luaka bop';


Question: How many exploratory wells have been drilled in 'Alberta' since 2020?

CREATE TABLE wells (id VARCHAR(10), name VARCHAR(10), type VARCHAR(20), region VARCHAR(20)); INSERT INTO wells (id, name, type, region) VALUES ('W004', 'D', 'exploratory', 'Alberta'), ('W005', 'E', 'production', 'Alberta');

SELECT COUNT(*) FROM wells WHERE type = 'exploratory' AND region = 'Alberta' AND date >= '2020-01-01';


Question: What is the average hourly wage for male workers?

CREATE TABLE HourlyWageData (EmployeeID INT, Gender VARCHAR(10), HourlyWage DECIMAL(10, 2)); INSERT INTO HourlyWageData (EmployeeID, Gender, HourlyWage) VALUES (1, 'Male', 30.00), (2, 'Female', 25.00), (3, 'Male', 35.00);

SELECT AVG(HourlyWage) FROM HourlyWageData WHERE Gender = 'Male';


Question: Generate PostgreSQL SQL for: What Date has the Region Europe and a Catalog of 74321 45851 2?

CREATE TABLE table_name_33 (date VARCHAR, region VARCHAR, catalog VARCHAR)

SELECT date FROM table_name_33 WHERE region = 'europe' AND catalog = '74321 45851 2';


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

CREATE INDEX botharrayidx ON array_index_op_test USING gin (i, t);

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


Question: Generate PostgreSQL SQL for: what is the district where the result is re-elected and the incumbent is richard kelly?

CREATE TABLE table_1341663_10 (district VARCHAR, result VARCHAR, incumbent VARCHAR)

SELECT district FROM table_1341663_10 WHERE result = 'Re-elected' AND incumbent = 'Richard Kelly';


Question: List all countries and their total marine conservation area ('mca') size in square kilometers.

CREATE TABLE country (id INT, name VARCHAR(50)); CREATE TABLE mca (id INT, country_id INT, name VARCHAR(50), size_sqkm FLOAT); INSERT INTO country (id, name) VALUES (1, 'Australia'), (2, 'Canada'); INSERT INTO mca (id, country_id, name, size_sqkm) VALUES (1, 1, 'Great Barrier Reef', 344400), (2, 2, 'Pacific Rim National Park', 51800);

SELECT country.name, SUM(mca.size_sqkm) FROM country INNER JOIN mca ON country.id = mca.country_id GROUP BY country.name;


Question: Write the DML statement from PostgreSQL regression test 'timestamp' (example 77).

INSERT INTO TIMESTAMP_TBL VALUES ('Feb 16 17:32:01 0597');

Explanation: DML from PostgreSQL core regression test for Timestamp.


Question: Generate PostgreSQL SQL for: What Premier League Manager has an Adidas sponsor and a Newcastle United club?

CREATE TABLE table_name_52 (manager VARCHAR, manufacturer VARCHAR, club VARCHAR)

SELECT manager FROM table_name_52 WHERE manufacturer = 'adidas' AND club = 'newcastle united';


Question: What is the total volume of timber harvested in each region for 2020?

SELECT region, SUM(volume) AS total_volume FROM harvest WHERE year = 2020 GROUP BY region;


Question: Generate PostgreSQL SQL for: How many journalists are there?


Question: Generate PostgreSQL SQL for: Which Monday Mona/Mani also had a Thursday Thunor/Thor of Tongersdei?

CREATE TABLE table_name_84 (monday_mona__máni VARCHAR, thursday_thunor___thor VARCHAR)

SELECT monday_mona__máni FROM table_name_84 WHERE thursday_thunor___thor = 'tongersdei';


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

SELECT array_agg(a ORDER BY x||y) FROM collate_test10;  -- fail

SELECT a, b FROM collate_test1 UNION ALL SELECT a, b FROM collate_test1 ORDER BY 2;

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

SELECT count(*) FROM (SELECT array_agg(a ORDER BY x||y) FROM collate_test10;  -- fail

SELECT a, b FROM collate_test1 UNION ALL SELECT a, b FROM collate_test1 ORDER BY 2) AS _sub;


Question: What is the minimum depth at which the Greenland Shark is found?

CREATE TABLE shark_depths (shark VARCHAR(255), min_depth FLOAT); INSERT INTO shark_depths (shark, min_depth) VALUES ('Greenland Shark', 2000.0), ('Hammerhead Shark', 100.0);

SELECT min_depth FROM shark_depths WHERE shark = 'Greenland Shark';


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

SELECT * FROM pg_input_error_info('[{"attributes" : [2,3], "degree" : 1.000}]', 'pg_dependencies');

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

SELECT count(*) FROM (SELECT * FROM pg_input_error_info('[{"attributes" : [2,3], "degree" : 1.000}]', 'pg_dependencies')) AS _sub;


Question: List the carbon sequestration rates for all forests in 'Region C'.

CREATE TABLE ForestCarbonSeq(forest_name TEXT, carbon_seq_rate REAL, region TEXT); INSERT INTO ForestCarbonSeq (forest_name, carbon_seq_rate, region) VALUES ('Forest 1', 5.6, 'Region C'), ('Forest 2', 6.3, 'Region D'), ('Forest 3', 4.8, 'Region C');

SELECT carbon_seq_rate FROM ForestCarbonSeq WHERE region = 'Region C';


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

CREATE POLICY policy_range_parted ON range_parted for UPDATE USING (true) WITH CHECK (c % 2 = 0);

Explanation: DDL from PostgreSQL core regression test for Update.


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

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

SELECT count(*) FROM (select jsonb_path_query('"12:34:56+3"', '$.datetime().type()')) AS _sub;


Question: What is the average price of fair trade coffee beans sold by each retailer?

CREATE TABLE retailers (retailer_id INT, retailer_name TEXT);CREATE TABLE products (product_id INT, product_name TEXT, is_fair_trade BOOLEAN, product_category TEXT, price INT);CREATE TABLE inventory (retailer_id INT, product_id INT);

SELECT retailers.retailer_name, AVG(products.price) as avg_price FROM retailers JOIN inventory ON retailers.retailer_id = inventory.retailer_id JOIN products ON inventory.product_id = products.product_id WHERE products.is_fair_trade = TRUE AND products.product_category = 'coffee beans' GROUP BY retailers.retailer_name;


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

SELECT tablename, rulename, definition FROM pg_rules
	WHERE tablename = 'hats';

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

SELECT count(*) FROM (SELECT tablename, rulename, definition FROM pg_rules
	WHERE tablename = 'hats') AS _sub;


Question: What is the prevalence of heart disease in rural areas of Texas compared to urban areas?

CREATE TABLE heart_disease (patient_id INT, age INT, gender VARCHAR(20), location VARCHAR(20));

SELECT (COUNT(*) FILTER (WHERE location = 'Rural Texas'))::float / COUNT(*) FROM heart_disease;


Question: What is the percentage of electric vehicles sold in North America in 2020?

CREATE TABLE VehicleSales (id INT, vehicle_type VARCHAR(255), sale_date DATE, units_sold INT, country VARCHAR(255)); INSERT INTO VehicleSales (id, vehicle_type, sale_date, units_sold, country) VALUES (1, 'Gasoline', '2017-01-01', 500, 'USA'); INSERT INTO VehicleSales (id, vehicle_type, sale_date, units_sold, country) VALUES (2, 'Electric', '2020-01-01', 800, 'Canada');

SELECT (COUNT(*) FILTER (WHERE vehicle_type = 'Electric')) * 100.0 / COUNT(*) FROM VehicleSales WHERE sale_date >= '2020-01-01' AND country IN ('USA', 'Canada');


Question: Generate PostgreSQL SQL for: What is the country of player ian woosnam?

CREATE TABLE table_name_93 (country VARCHAR, player VARCHAR)

SELECT country FROM table_name_93 WHERE player = 'ian woosnam';


Question: Delete the record of the 'Vanguard 1' satellite

CREATE TABLE space_debris (name TEXT, type TEXT, location TEXT); INSERT INTO space_debris (name, type, location) VALUES ('Vanguard 1', 'Satellite', 'Low Earth Orbit');

DELETE FROM space_debris WHERE name = 'Vanguard 1';


Question: What is the percentage of AI safety incidents related to data privacy in each country?

CREATE TABLE safety_incidents (incident_id INT, country VARCHAR(50), incident_type VARCHAR(50)); INSERT INTO safety_incidents (incident_id, country, incident_type) VALUES (1, 'CountryA', 'Data Privacy'), (2, 'CountryB', 'Model Malfunction'), (3, 'CountryA', 'Data Privacy');

SELECT country, COUNT(*) * 100.0 / (SELECT COUNT(*) FROM safety_incidents) as pct_data_privacy_incidents FROM safety_incidents WHERE incident_type = 'Data Privacy' GROUP BY country;


Question: What is the average mental health score of students who have participated in professional development programs?

CREATE TABLE students (student_id INT, mental_health_score INT, participated_in_pd BOOLEAN); INSERT INTO students (student_id, mental_health_score, participated_in_pd) VALUES (1, 75, true), (2, 80, false), (3, 60, true);

SELECT AVG(mental_health_score) FROM students WHERE participated_in_pd = true;


Question: Generate PostgreSQL SQL for: What is the name of the nurse has the most appointments?

CREATE TABLE nurse (name VARCHAR, employeeid VARCHAR); CREATE TABLE appointment (prepnurse VARCHAR)

SELECT T1.name FROM nurse AS T1 JOIN appointment AS T2 ON T1.employeeid = T2.prepnurse GROUP BY T1.employeeid ORDER BY COUNT(*) DESC LIMIT 1;


Question: Generate PostgreSQL SQL for: What is the amount of the 1st prize when the Winner was ken green (4)?

CREATE TABLE table_name_56 (winner VARCHAR)

SELECT 1 AS st_prize___$__ FROM table_name_56 WHERE winner = 'ken green (4)';


Question: Generate PostgreSQL SQL for: who is the away team on 21 september?

CREATE TABLE table_name_42 (away_team VARCHAR, date VARCHAR)

SELECT away_team FROM table_name_42 WHERE date = '21 september';


Question: How many unique strains were available in Colorado in 2020 and 2021?

CREATE TABLE strains (id INT, state VARCHAR(50), year INT, strain VARCHAR(50)); INSERT INTO strains (id, state, year, strain) VALUES (1, 'Colorado', 2020, 'Blue Dream'), (2, 'Colorado', 2021, 'Green Crack'), (3, 'California', 2020, 'Sour Diesel');

SELECT COUNT(DISTINCT strain) FROM strains WHERE state = 'Colorado' AND (year = 2020 OR year = 2021);


Question: Generate PostgreSQL SQL for: What rank does the person participating in American Civil war and indian wars?

CREATE TABLE table_name_65 (rank VARCHAR, active_service VARCHAR)

SELECT rank FROM table_name_65 WHERE active_service = 'american civil war and indian wars';


Question: List all unique marine species observed by expeditions, ordered alphabetically.

CREATE TABLE expedition (org VARCHAR(20), species VARCHAR(50)); INSERT INTO expedition VALUES ('Ocean Explorer', 'Dolphin'), ('Ocean Explorer', 'Tuna'), ('Sea Discoverers', 'Shark'), ('Sea Discoverers', 'Whale'), ('Marine Investigators', 'Starfish');

SELECT DISTINCT species FROM expedition ORDER BY species;


Question: Insert a new outreach event into the 'events' table

CREATE TABLE events (id INT PRIMARY KEY, site_id INT, date DATE, attendees INT, notes TEXT);

INSERT INTO events (id, site_id, date, attendees, notes) VALUES (1, 1, '2023-06-10', 200, 'Lecture on Pompeii frescoes');


Question: What is the average sustainability score of suppliers that provide linen?

CREATE TABLE supplier_sustainability (supplier_id INT, name TEXT, sustainability_score INT); INSERT INTO supplier_sustainability (supplier_id, name, sustainability_score) VALUES (1, 'Supplier A', 85), (2, 'Supplier B', 90), (3, 'Supplier C', 70), (4, 'Supplier D', 60), (5, 'Supplier E', 50), (6, 'Supplier F', 95), (7, 'Supplier G', 80); CREATE TABLE supplier_materials (supplier_id INT, material TEXT); INSERT INTO supplier_materials (supplier_id, material) VALUES (3, 'linen'), (6, 'linen'), (7, 'linen');

SELECT AVG(sustainability_score) FROM supplier_sustainability s JOIN supplier_materials m ON s.supplier_id = m.supplier_id WHERE material = 'linen';


Question: What is the number of teachers who have completed professional development courses on open pedagogy in urban and rural areas?

CREATE TABLE teacher_pd (teacher_id INT, location VARCHAR(50), course VARCHAR(50)); INSERT INTO teacher_pd (teacher_id, location, course) VALUES (1, 'Urban', 'Open Pedagogy 101'), (2, 'Rural', 'Open Pedagogy 101'), (3, 'Urban', 'Open Pedagogy 202');

SELECT location, COUNT(DISTINCT teacher_id) as num_teachers FROM teacher_pd WHERE course = 'Open Pedagogy 101' GROUP BY location;


Question: What is the average cultural competency score of community health workers by state?

CREATE TABLE states (state_id INT, state_name VARCHAR(100)); INSERT INTO states (state_id, state_name) VALUES (1, 'California'), (2, 'Texas'), (3, 'New York'); CREATE TABLE community_health_workers (worker_id INT, state_id INT, cultural_competency_score INT); INSERT INTO community_health_workers (worker_id, state_id, cultural_competency_score) VALUES (1, 1, 85), (2, 1, 90), (3, 2, 80), (4, 3, 95), (5, 1, 92);

SELECT S.state_name, AVG(cultural_competency_score) as avg_score FROM community_health_workers CHW JOIN states S ON CHW.state_id = S.state_id GROUP BY S.state_name;


Question: What is the total military equipment sales revenue for contractor Y?

CREATE TABLE revenue(id INT, contractor VARCHAR(50), revenue NUMERIC);

SELECT SUM(revenue) FROM revenue WHERE contractor = 'Y';


Question: How many public schools are there in the city of Chicago, and what are their names?

CREATE TABLE PublicSchools (SchoolID INT, SchoolName VARCHAR(100), City VARCHAR(100)); INSERT INTO PublicSchools (SchoolID, SchoolName, City) VALUES (1, 'Johnson Elementary School', 'Chicago'), (2, 'Washington High School', 'Chicago'), (3, 'Lincoln Middle School', 'Chicago');

SELECT COUNT(*) as NumberOfSchools, SchoolName FROM PublicSchools WHERE City = 'Chicago' GROUP BY SchoolName;


Question: Generate PostgreSQL SQL for: How many losses are there for team tembetary?

CREATE TABLE table_18703133_6 (losses VARCHAR, team VARCHAR)

SELECT losses FROM table_18703133_6 WHERE team = 'Tembetary';


Question: Generate PostgreSQL SQL for: Which manufacturer is grid 11?

CREATE TABLE table_name_93 (manufacturer VARCHAR, grid VARCHAR)

SELECT manufacturer FROM table_name_93 WHERE grid = '11';


Question: What is the number of peacekeeping operations participated in by each country in the 'peacekeeping' table, excluding those with less than 3 operations, ordered by the number of operations in ascending order?

CREATE TABLE peacekeeping (id INT, country VARCHAR(50), num_operations INT);

SELECT country, COUNT(*) as num_operations FROM peacekeeping GROUP BY country HAVING COUNT(*) >= 3 ORDER BY num_operations ASC;


Question: What is the total socially responsible lending for each country?

CREATE TABLE socially_responsible_lending_data (lending_id INT, amount DECIMAL(15, 2), country VARCHAR(50)); INSERT INTO socially_responsible_lending_data (lending_id, amount, country) VALUES (1, 5000000, 'Brazil'), (2, 7000000, 'India'), (3, 6000000, 'South Africa'), (4, 8000000, 'Indonesia'), (5, 9000000, 'China'); CREATE VIEW socially_responsible_lending_view AS SELECT country, SUM(amount) as total_lending FROM socially_responsible_lending_data GROUP BY country;

SELECT country, total_lending FROM socially_responsible_lending_view;


Question: Delete a community education program from the 'education' table

CREATE TABLE education (id INT PRIMARY KEY, title VARCHAR(50), description TEXT, attendees INT, date DATE);

DELETE FROM education WHERE title = 'Rainforest Restoration';


Question: How many people have benefited from digital divide initiatives in Africa in the last 5 years?

CREATE TABLE Digital_Divide_Initiatives (Year INT, Beneficiaries INT);

SELECT SUM(Beneficiaries) FROM Digital_Divide_Initiatives WHERE Year BETWEEN 2016 AND 2021;


Question: Generate PostgreSQL SQL for: Name the most bits 14-12 for output from accumulator to character bus

CREATE TABLE table_14249278_1 (bits_14_12 INTEGER, description VARCHAR)

SELECT MIN(bits_14_12) FROM table_14249278_1 WHERE description = 'Output from accumulator to character bus';


Question: Calculate the total investment amount per ESG category.

CREATE TABLE esg_categories (id INT, category TEXT, description TEXT, total_investment FLOAT); INSERT INTO esg_categories (id, category, description, total_investment) VALUES (1, 'E', 'Environmental', 30000), (2, 'S', 'Social', 25000), (3, 'G', 'Governance', 45000);

SELECT category, SUM(total_investment) FROM esg_categories GROUP BY category;


Question: Generate PostgreSQL SQL for: Which track has a Japanese title of メロディー?

CREATE TABLE table_name_12 (track INTEGER, japanese_title VARCHAR)

SELECT MAX(track) FROM table_name_12 WHERE japanese_title = 'メロディー';


Question: Generate PostgreSQL SQL for: what is the play when the company is national theatre of greece?

CREATE TABLE table_name_11 (play VARCHAR, company VARCHAR)

SELECT play FROM table_name_11 WHERE company = 'national theatre of greece';


Question: Generate PostgreSQL SQL for: What date had a margin victory of 2 strokes?

CREATE TABLE table_name_91 (date VARCHAR, margin_of_victory VARCHAR)

SELECT date FROM table_name_91 WHERE margin_of_victory = '2 strokes';


Question: Generate PostgreSQL SQL for: Which Laps have a Finish of 15?

CREATE TABLE table_name_30 (laps VARCHAR, finish VARCHAR)

SELECT laps FROM table_name_30 WHERE finish = '15';


Question: Generate PostgreSQL SQL for: What is the highest score of round 1 where they also shot 90 in round 2

CREATE TABLE table_14708760_3 (round_1 INTEGER, round_2 VARCHAR)

SELECT MAX(round_1) FROM table_14708760_3 WHERE round_2 = 90;


Question: Generate PostgreSQL SQL for: When the VFL played Victoria Park what was the home team score?

CREATE TABLE table_name_11 (home_team VARCHAR, venue VARCHAR)

SELECT home_team AS score FROM table_name_11 WHERE venue = 'victoria park';


Question: Generate PostgreSQL SQL for: Which Sydney's Melbourne was no, when Auckland was yes?

CREATE TABLE table_name_94 (sydney VARCHAR, melbourne VARCHAR, auckland VARCHAR)

SELECT sydney FROM table_name_94 WHERE melbourne = 'no' AND auckland = 'yes';


Question: What is the trend of mental health scores by race/ethnicity?

CREATE TABLE student_mental_health (student_id INT, score INT, race_ethnicity VARCHAR(20)); INSERT INTO student_mental_health (student_id, score, race_ethnicity) VALUES (1, 80, 'Asian'), (1, 85, 'Asian'), (2, 70, 'Hispanic'), (2, 75, 'Hispanic'), (3, 90, 'African American'), (3, 95, 'African American');

SELECT race_ethnicity, AVG(score) as avg_score FROM student_mental_health GROUP BY race_ethnicity ORDER BY race_ethnicity;


Question: What is the average speed of shared electric scooters in Seattle and Portland?

CREATE TABLE shared_scooters (scooter_id INT, city VARCHAR(20), avg_speed DECIMAL(5,2)); INSERT INTO shared_scooters (scooter_id, city, avg_speed) VALUES (1, 'Seattle', 12.5), (2, 'Seattle', 14.3), (3, 'Portland', 13.9), (4, 'Portland', 11.8);

SELECT AVG(avg_speed) FROM shared_scooters WHERE city IN ('Seattle', 'Portland') GROUP BY city;


Question: Find the average daily production of oil for each platform in Q4 2020

CREATE TABLE platform_production_figures (platform_id INT, production_date DATE, oil_production FLOAT);

SELECT platform_id, AVG(oil_production) as avg_oil_production FROM platform_production_figures WHERE production_date BETWEEN '2020-10-01' AND '2020-12-31' GROUP BY platform_id;


Question: What was the success rate of legal aid clinics in different regions?

CREATE TABLE legal_aid (clinic_name VARCHAR(20), region VARCHAR(20), success_rate DECIMAL(3,2)); INSERT INTO legal_aid (clinic_name, region, success_rate) VALUES ('Clinic A', 'Northeast', 0.85), ('Clinic B', 'Southeast', 0.70), ('Clinic C', 'Midwest', 0.90);

SELECT region, AVG(success_rate) as avg_success_rate FROM legal_aid GROUP BY region;


Question: Generate PostgreSQL SQL for: What horse has the number 25?

CREATE TABLE table_20095300_1 (name VARCHAR, number VARCHAR)

SELECT name FROM table_20095300_1 WHERE number = 25;


Question: PostgreSQL regression test 'float8': Write the SELECT query (example 104).

SELECT ln(f.f1) from FLOAT8_TBL f where f.f1 = '0.0' ;

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

SELECT count(*) FROM (SELECT ln(f.f1) from FLOAT8_TBL f where f.f1 = '0.0' ) AS _sub;


Question: Generate PostgreSQL SQL for: Find the name of the airport in the city of Goroka.

CREATE TABLE airports (name VARCHAR, city VARCHAR)

SELECT name FROM airports WHERE city = 'Goroka';


Question: Calculate total assets by investment type and region.

CREATE TABLE investments (id INT, type VARCHAR(255), region VARCHAR(255), amount FLOAT); INSERT INTO investments VALUES (1, 'Stocks', 'Asia', 50000), (2, 'Bonds', 'Europe', 75000), (3, 'Real Estate', 'Americas', 100000);

SELECT type, SUM(amount) as total_assets, region FROM investments GROUP BY type, region;


Question: Generate PostgreSQL SQL for: Which details has the out of line label and the year of 2005?

CREATE TABLE table_name_9 (details VARCHAR, label VARCHAR, year VARCHAR)

SELECT details FROM table_name_9 WHERE label = 'out of line' AND year = 2005;


Question: How many electric vehicles are sold in China per month?

CREATE TABLE CNElectricVehicleSales (id INT, date DATE, sales INT);

SELECT DATE_FORMAT(date, '%Y-%m') as month, SUM(sales) FROM CNElectricVehicleSales GROUP BY month;


Question: Write the DDL statement from PostgreSQL regression test 'partition_aggregate' (example 89).

CREATE TABLE pagg_tab_ml_p3_s1(c text, a int, b int);

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


Question: Generate PostgreSQL SQL for: What shows for laps when the Time/Retired was +1:08.577?

CREATE TABLE table_name_48 (laps VARCHAR, time_retired VARCHAR)

SELECT laps FROM table_name_48 WHERE time_retired = '+1:08.577';


Question: Generate PostgreSQL SQL for: What date sent has orion as the constellation?

CREATE TABLE table_name_63 (date_sent VARCHAR, constellation VARCHAR)

SELECT date_sent FROM table_name_63 WHERE constellation = 'orion';


Question: Generate PostgreSQL SQL for: In games where st kilda was the away team, what was the smallest crowd?

CREATE TABLE table_name_68 (crowd INTEGER, away_team VARCHAR)

SELECT MIN(crowd) FROM table_name_68 WHERE away_team = 'st kilda';


Question: Generate PostgreSQL SQL for: What car has a March 90ca Chassis?

CREATE TABLE table_name_44 (engine VARCHAR, chassis VARCHAR)

SELECT engine FROM table_name_44 WHERE chassis = 'march 90ca';


Question: Generate PostgreSQL SQL for: Who were the scorers in the game against neuchâtel xamax played on 10 December 1985?

CREATE TABLE table_name_64 (scorers VARCHAR, opponent VARCHAR, date VARCHAR)

SELECT scorers FROM table_name_64 WHERE opponent = 'neuchâtel xamax' AND date = '10 december 1985';


Question: Which country produced the most Dysprosium in 2020?

CREATE TABLE yearly_production (country VARCHAR(255), element VARCHAR(255), year INT, production INT); INSERT INTO yearly_production (country, element, year, production) VALUES ('China', 'Dysprosium', 2020, 1200), ('Australia', 'Dysprosium', 2020, 800), ('United States', 'Dysprosium', 2020, 500);

SELECT country, MAX(production) as max_production FROM yearly_production WHERE element = 'Dysprosium' AND year = 2020 GROUP BY country;


Question: What are the average warehouse management costs for each warehouse in Q2 2022?

CREATE TABLE warehouse_costs (warehouse_id INT, warehouse_location VARCHAR(255), cost DECIMAL(10,2), quarter INT, year INT); INSERT INTO warehouse_costs (warehouse_id, warehouse_location, cost, quarter, year) VALUES (1, 'NYC Warehouse', 2500.00, 2, 2022), (2, 'LA Warehouse', 3000.00, 2, 2022), (3, 'CHI Warehouse', 2000.00, 2, 2022);

SELECT warehouse_location, AVG(cost) as avg_cost FROM warehouse_costs WHERE quarter = 2 AND year = 2022 GROUP BY warehouse_location;


Question: Find the ratio of R&D expenditures between 'AstraZeneca' and 'Novartis'.

CREATE TABLE rd_expenditures (company TEXT, year INT, amount FLOAT); INSERT INTO rd_expenditures (company, year, amount) VALUES ('AstraZeneca', 2020, 22000000), ('Novartis', 2020, 16000000);

SELECT (SELECT SUM(amount) FROM rd_expenditures WHERE company = 'AstraZeneca' AND year = 2020) / (SELECT SUM(amount) FROM rd_expenditures WHERE company = 'Novartis' AND year = 2020);


Question: Show a query using PostgreSQL contrib extension 'pg_stat_statements' (example 149).

SELECT a FROM pgss_schema_2.tab_search_diff_2;

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


Question: Identify the programs with the largest decrease in volunteers from the previous month.

CREATE TABLE volunteer_changes (program TEXT, month INT, num_volunteers INT); INSERT INTO volunteer_changes VALUES ('Feeding Program', 1, 10), ('Education Program', 1, 15), ('Feeding Program', 2, 8), ('Education Program', 2, 12), ('Feeding Program', 3, 12), ('Education Program', 3, 16);

SELECT program, num_volunteers, LAG(num_volunteers) OVER (PARTITION BY program ORDER BY month) as previous_month_volunteers, num_volunteers - LAG(num_volunteers) OVER (PARTITION BY program ORDER BY month) as volunteer_change FROM volunteer_changes;


Question: What is the total number of posts made by users from 'Jakarta' and 'Tokyo'?

CREATE TABLE posts (id INT PRIMARY KEY, user_id INT, content TEXT, post_date DATE, city VARCHAR(50)); INSERT INTO posts (id, user_id, content, post_date, city) VALUES (1, 1, 'Hello World!', '2021-01-01', 'Jakarta'); INSERT INTO posts (id, user_id, content, post_date, city) VALUES (2, 2, 'I love data!', '2021-01-02', 'Tokyo'); INSERT INTO posts (id, user_id, content, post_date, city) VALUES (3, 3, 'Privacy matters!', '2021-01-03', 'Jakarta');

SELECT city, COUNT(*) as total_posts FROM posts WHERE city IN ('Jakarta', 'Tokyo') GROUP BY city;


Question: What is the total amount of climate finance invested in renewable energy in Europe?

CREATE TABLE FinanceInvestment (Country TEXT, Sector TEXT, Investment_Amount NUMERIC); INSERT INTO FinanceInvestment (Country, Sector, Investment_Amount) VALUES ('France', 'Renewable Energy', 3000000), ('Germany', 'Renewable Energy', 4000000), ('Spain', 'Renewable Energy', 5000000);

SELECT SUM(Investment_Amount) FROM FinanceInvestment WHERE Country IN ('France', 'Germany', 'Spain') AND Sector = 'Renewable Energy';


Question: Generate PostgreSQL SQL for: What is the Theme of Christie Paquet after 2004 with an Issue Price of $34.95?

CREATE TABLE table_name_54 (theme VARCHAR, year VARCHAR, artist VARCHAR, issue_price VARCHAR)

SELECT theme FROM table_name_54 WHERE artist = 'christie paquet' AND issue_price = '$34.95' AND year > 2004;


Question: Generate PostgreSQL SQL for: What is the total number of players who had a money list rank of 96?

CREATE TABLE table_20590020_2 (best_finish VARCHAR, money_list_rank VARCHAR)

SELECT COUNT(best_finish) FROM table_20590020_2 WHERE money_list_rank = 96;


Question: Generate PostgreSQL SQL for: Which record has a score of 135–134?

CREATE TABLE table_name_7 (record VARCHAR, score VARCHAR)

SELECT record FROM table_name_7 WHERE score = '135–134';


Question: Generate PostgreSQL SQL for: What was the total number of years than had best improved singer (躍進歌手)?

CREATE TABLE table_name_52 (year INTEGER, category VARCHAR)

SELECT SUM(year) FROM table_name_52 WHERE category = 'best improved singer (躍進歌手)';


Question: List the teams that have more than 15 players.

CREATE TABLE players (player_id INT, name VARCHAR(50), age INT, position VARCHAR(50), team VARCHAR(50));

SELECT team FROM players GROUP BY team HAVING COUNT(*) > 15;


Question: What is the total waste generation by city for the year 2021 for the state of New York?'

CREATE TABLE city_waste_generation (city VARCHAR(20), state VARCHAR(20), year INT, quantity FLOAT); INSERT INTO city_waste_generation (city, state, year, quantity) VALUES ('New York City', 'New York', 2021, 1000000); INSERT INTO city_waste_generation (city, state, year, quantity) VALUES ('Buffalo', 'New York', 2021, 150000);

SELECT SUM(quantity) as total_quantity FROM city_waste_generation WHERE state = 'New York' AND year = 2021;


Question: List all defense projects with timelines starting in 2020 or later.

CREATE TABLE defense_projects (project_name VARCHAR(255), start_date DATE, end_date DATE); INSERT INTO defense_projects (project_name, start_date, end_date) VALUES ('Project A', '2021-01-01', '2023-12-31'), ('Project B', '2019-01-01', '2022-12-31'), ('Project C', '2020-01-01', '2024-12-31');

SELECT project_name FROM defense_projects WHERE start_date >= '2020-01-01';


Question: Generate PostgreSQL SQL for: What is the name of the driver in 1955?

CREATE TABLE table_name_18 (driver VARCHAR, year VARCHAR)

SELECT driver FROM table_name_18 WHERE year = '1955';


Question: Generate PostgreSQL SQL for: Where was the game in which Will Bynum (5) did the high assists played?

CREATE TABLE table_27755603_2 (location_attendance VARCHAR, high_assists VARCHAR)

SELECT location_attendance FROM table_27755603_2 WHERE high_assists = 'Will Bynum (5)';


Question: Update policy records for policyholders with policy_id 101, 102, and 103 in the 'Policy' table.

CREATE TABLE Policy (policy_id INT, policyholder_state VARCHAR(20));

UPDATE Policy SET policyholder_state = 'NY' WHERE policy_id IN (101, 102, 103);


Question: Generate PostgreSQL SQL for: What is the latest Year with Marianne Jean-Baptiste as the Golden Globe Actor?

CREATE TABLE table_name_50 (year INTEGER, actor VARCHAR)

SELECT MAX(year) FROM table_name_50 WHERE actor = 'marianne jean-baptiste';


Question: How many exploration and appraisal wells were drilled in 2018 and 2019?

CREATE TABLE wells (id INT, year INT, well_type VARCHAR(255), status VARCHAR(255)); INSERT INTO wells (id, year, well_type, status) VALUES (1, 2018, 'Exploration', 'Drilled'), (2, 2018, 'Appraisal', 'Drilled'), (3, 2019, 'Exploration', 'Drilled'), (4, 2019, 'Appraisal', 'Drilled'), (5, 2017, 'Production', 'Drilled');

SELECT SUM(CASE WHEN year IN (2018, 2019) AND status = 'Drilled' AND (well_type = 'Exploration' OR well_type = 'Appraisal') THEN 1 ELSE 0 END) as e_and_a_wells FROM wells;


Question: Generate PostgreSQL SQL for: who is the the president with date of inauguration being 4june1979

CREATE TABLE table_12134383_1 (president VARCHAR, date_of_inauguration VARCHAR)

SELECT president FROM table_12134383_1 WHERE date_of_inauguration = '4June1979';


Question: Generate PostgreSQL SQL for: Who was the 1st member of the parliament that was dissolved 23 february 1510?

CREATE TABLE table_name_51 (dissolved VARCHAR)

SELECT 1 AS st_member FROM table_name_51 WHERE dissolved = '23 february 1510';


Question: Generate PostgreSQL SQL for: What is the height of the player who attended Hartford?

CREATE TABLE table_11734041_2 (height_in_ft VARCHAR, school_club_team_country VARCHAR)

SELECT height_in_ft FROM table_11734041_2 WHERE school_club_team_country = 'Hartford';


Question: List all suppliers for organic fruits and vegetables, along with their contact information and product details.

CREATE TABLE Suppliers (SupplierID int, Name varchar(50), Contact varchar(50), Industry varchar(50)); INSERT INTO Suppliers (SupplierID, Name, Contact, Industry) VALUES (1, 'Green Valley', 'contact@greenvalley.com', 'Organic Fruits'); CREATE TABLE Products (ProductID int, Name varchar(50), SupplierID int, Details varchar(50)); INSERT INTO Products (ProductID, Name, SupplierID, Details) VALUES (1, 'Apples', 1, 'Organic');

SELECT Suppliers.Name, Suppliers.Contact, Products.Name, Products.Details FROM Suppliers INNER JOIN Products ON Suppliers.SupplierID = Products.SupplierID WHERE Suppliers.Industry = 'Organic Fruits' AND Products.Details = 'Organic';


Question: List all unique funding sources for arts and culture programs in the 'Northeast' region, excluding those with a total funding amount less than $10,000.

CREATE TABLE FundingSources (funding_source VARCHAR(20), region VARCHAR(20), total_funding DECIMAL(10,2)); INSERT INTO FundingSources (funding_source, region, total_funding) VALUES ('Cultural Trust', 'Northeast', 25000), ('Arts Foundation', 'Northeast', 12000), ('City Grants', 'Southeast', 15000);

SELECT DISTINCT funding_source FROM FundingSources WHERE region = 'Northeast' AND total_funding >= 10000;


Question: List all mobile subscribers in the Americas who have exceeded their data usage limit in the last month.

CREATE TABLE mobile_subscribers (id INT, region VARCHAR(20), data_usage INT, usage_date DATE); CREATE TABLE data_limits (id INT, subscriber_id INT, limit INT);

SELECT m.id, m.region, m.data_usage, m.usage_date FROM mobile_subscribers m INNER JOIN data_limits d ON m.id = d.subscriber_id WHERE m.region = 'Americas' AND m.usage_date > DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH) AND m.data_usage > d.limit;


Question: Generate PostgreSQL SQL for: What district is Charles H. Wilson the incumbent of?

CREATE TABLE table_1341663_6 (district VARCHAR, incumbent VARCHAR)

SELECT district FROM table_1341663_6 WHERE incumbent = 'Charles H. Wilson';


Question: Find the total cost of all projects in the Water_Infrastructure table

CREATE TABLE Water_Infrastructure (project_id INT, project_name VARCHAR(255), location VARCHAR(255), cost FLOAT);

SELECT SUM(cost) FROM Water_Infrastructure;


Question: What is the count of claims for policy number 1004?

CREATE TABLE claims (claim_id INT, policy_id INT); INSERT INTO claims (claim_id, policy_id) VALUES (1, 1001), (2, 1002), (3, 1003), (4, 1002), (5, 1004), (6, 1004);

SELECT COUNT(*) FROM claims WHERE policy_id = 1004;


Question: What is the average fare for buses in the 'san_francisco' schema?

CREATE TABLE san_francisco.bus_fares (id INT, route_id INT, fare DECIMAL); INSERT INTO san_francisco.bus_fares (id, route_id, fare) VALUES (1, 101, 2.5), (2, 102, 2), (3, 103, 3);

SELECT AVG(fare) FROM san_francisco.bus_fares;


Question: pgTAP test for Resultset (assertion 433).

-- Invert that.
SELECT * FROM check_test(
    results_ne(
        'nenames_ord',
        'SELECT id, name FROM annames WHERE name <> ''Antonio'''
    ),
    true,
    'results_ne(prepared, select) missing first row',
    '',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Resultset.


Question: Update the last name of member with ID 1 to 'Smith'.

CREATE TABLE Members (MemberID INT, FirstName VARCHAR(50), LastName VARCHAR(50)); INSERT INTO Members (MemberID, FirstName, LastName) VALUES (1, 'John', 'Doe'); INSERT INTO Members (MemberID, FirstName, LastName) VALUES (2, 'Jane', 'Doe');

UPDATE Members SET LastName = 'Smith' WHERE MemberID = 1;


Question: Generate PostgreSQL SQL for: What is the low rank for hale irwin with under 32 wins?

CREATE TABLE table_name_37 (rank INTEGER, player VARCHAR, wins VARCHAR)

SELECT MIN(rank) FROM table_name_37 WHERE player = 'hale irwin' AND wins < 32;


Question: Generate PostgreSQL SQL for: How many draft pick positions did Matt Bradley have?

CREATE TABLE table_2840500_4 (position VARCHAR, player VARCHAR)

SELECT COUNT(position) FROM table_2840500_4 WHERE player = 'Matt Bradley';


Question: Write the DML statement from PostgreSQL regression test 'fast_default' (example 26).

Explanation: DML from PostgreSQL core regression test for Fast Default.


Question: Generate PostgreSQL SQL for: What surface was the match on November 6, 1982 played on?

CREATE TABLE table_name_82 (surface VARCHAR, date VARCHAR)

SELECT surface FROM table_name_82 WHERE date = 'november 6, 1982';


Question: Generate PostgreSQL SQL for: What name has a qual 2 of 1:46.025?

CREATE TABLE table_name_33 (name VARCHAR, qual_2 VARCHAR)

SELECT name FROM table_name_33 WHERE qual_2 = '1:46.025';


Question: Generate PostgreSQL SQL for: What is Kris doolan's league number?

CREATE TABLE table_22683369_8 (league VARCHAR, player VARCHAR)

SELECT COUNT(league) FROM table_22683369_8 WHERE player = 'Kris Doolan';


Question: List all warehouses in North America and their corresponding capacities.

CREATE TABLE Warehouses (id INT, warehouse_name VARCHAR(50), warehouse_country VARCHAR(50), warehouse_capacity INT); INSERT INTO Warehouses (id, warehouse_name, warehouse_country, warehouse_capacity) VALUES (1, 'Seattle Warehouse', 'USA', 5000), (2, 'Toronto Warehouse', 'Canada', 4000), (3, 'Mexico City Warehouse', 'Mexico', 3000);

SELECT warehouse_country, warehouse_name, warehouse_capacity FROM Warehouses WHERE warehouse_country IN ('USA', 'Canada', 'Mexico');


Question: Generate PostgreSQL SQL for: Which landfall was in category 1 for Saffir-Simpson in 1999?

CREATE TABLE table_name_85 (landfall VARCHAR, saffir_simpson_category VARCHAR, year VARCHAR)

SELECT landfall FROM table_name_85 WHERE saffir_simpson_category = 1 AND year = 1999;


Question: What is the minimum transaction amount for clients with a credit score greater than 750 in Q2 2023?

CREATE TABLE clients (client_id INT, name VARCHAR(50), credit_score INT, last_transaction_date DATE);CREATE TABLE transactions (transaction_id INT, client_id INT, transaction_date DATE, total_amount DECIMAL(10,2));

SELECT MIN(total_amount) FROM transactions t INNER JOIN clients c ON t.client_id = c.client_id WHERE c.credit_score > 750 AND t.transaction_date BETWEEN '2023-04-01' AND '2023-06-30';


Question: What was the total program impact by program category in H1 2023?

CREATE TABLE program_categories (id INT, category VARCHAR(50), impact INT); INSERT INTO program_categories (id, category, impact) VALUES (1, 'Education', 200), (2, 'Healthcare', 300), (3, 'Environment', 150);

SELECT category, SUM(impact) FROM program_categories WHERE category IN ('Education', 'Healthcare', 'Environment') GROUP BY category;


Question: Which regions in Japan have the most volunteers?

CREATE TABLE regions (id INT, region_name TEXT); CREATE TABLE volunteers (id INT, region_id INT, volunteer_count INT); INSERT INTO regions (id, region_name) VALUES (1, 'Kanto'), (2, 'Kansai'), (3, 'Chubu'); INSERT INTO volunteers (id, region_id, volunteer_count) VALUES (1, 1, 300), (2, 2, 250), (3, 1, 200);

SELECT regions.region_name, SUM(volunteers.volunteer_count) as total_volunteers FROM regions JOIN volunteers ON regions.id = volunteers.region_id GROUP BY regions.region_name ORDER BY total_volunteers DESC;


Question: Show the average revenue for restaurants in each city.

CREATE TABLE Restaurants (restaurant_id INT, name TEXT, city TEXT, revenue FLOAT); INSERT INTO Restaurants (restaurant_id, name, city, revenue) VALUES (1, 'Asian Fusion', 'New York', 50000.00), (2, 'Bella Italia', 'Los Angeles', 60000.00), (3, 'Sushi House', 'New York', 70000.00), (4, 'Pizzeria La Rosa', 'Chicago', 80000.00);

SELECT city, AVG(revenue) FROM Restaurants GROUP BY city;


Question: How many marine mammals are there in the 'species' table, and what is their average conservation status ranking?

CREATE TABLE species (species_id INT, common_name VARCHAR(50), latin_name VARCHAR(50), conservation_status VARCHAR(50), class VARCHAR(50)); INSERT INTO species (species_id, common_name, latin_name, conservation_status, class) VALUES (1, 'Green Sea Turtle', 'Chelonia mydas', 'Vulnerable', 'Reptilia'), (2, 'Bottlenose Dolphin', 'Tursiops truncatus', 'Least Concern', 'Mammalia');

SELECT class, COUNT(*), AVG(CASE WHEN conservation_status = 'Critically Endangered' THEN 5 WHEN conservation_status = 'Endangered' THEN 4 WHEN conservation_status = 'Vulnerable' THEN 3 WHEN conservation_status = 'Near Threatened' THEN 2 WHEN conservation_status = 'Least Concern' THEN 1 ELSE 0 END) as conservation_rank FROM species WHERE class = 'Mammalia' GROUP BY class;


Question: Generate PostgreSQL SQL for: What is the density (hab/ km²) when the altitude m is 1300?

CREATE TABLE table_name_61 (density__hab__km²__ VARCHAR, altitude_m VARCHAR)

SELECT density__hab__km²__ FROM table_name_61 WHERE altitude_m = '1300';


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

select to_tsvector('simple', 'y z q') @@ '(x | y <-> z) <-> q' AS "true";

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

SELECT count(*) FROM (select to_tsvector('simple', 'y z q') @@ '(x | y <-> z) <-> q' AS "true") AS _sub;


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

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

SELECT count(*) FROM (select mr_polymorphic(int4range(1, 4))) AS _sub;


Question: What is the total quantity of sustainable material used by each supplier?

CREATE TABLE suppliers (supplier_id INT, supplier_name TEXT); CREATE TABLE materials (material_id INT, material_name TEXT, is_sustainable BOOLEAN); CREATE TABLE inventory (inventory_id INT, supplier_id INT, material_id INT, quantity INT); INSERT INTO suppliers (supplier_id, supplier_name) VALUES (1, 'Green Supplies'), (2, 'Eco Friendly Inc.'); INSERT INTO materials (material_id, material_name, is_sustainable) VALUES (1, 'Organic Cotton', TRUE), (2, 'Polyester', FALSE); INSERT INTO inventory (inventory_id, supplier_id, material_id, quantity) VALUES (1, 1, 1, 100), (2, 1, 2, 50), (3, 2, 1, 75), (4, 2, 2, 150);

SELECT supplier_id, SUM(quantity) FROM inventory JOIN materials ON inventory.material_id = materials.material_id WHERE is_sustainable = TRUE GROUP BY supplier_id;


Question: What is the highest temperature recorded in 'Berlin'?

CREATE TABLE weather (city VARCHAR(255), temperature FLOAT, date DATE); INSERT INTO weather (city, temperature, date) VALUES ('Berlin', 80, '2022-05-01'), ('Berlin', 85, '2022-06-15'), ('Berlin', 90, '2022-07-20');

SELECT MAX(temperature) FROM weather WHERE city = 'Berlin';


Question: What is the name and location of all heritage sites that have craft workshops?

CREATE TABLE heritage_sites (id INT, name VARCHAR, location VARCHAR); INSERT INTO heritage_sites (id, name, location) VALUES (1, 'Heritage Site A', 'City A'), (2, 'Heritage Site B', 'City B'); CREATE TABLE workshops (id INT, type VARCHAR, site_id INT); INSERT INTO workshops (id, type, site_id) VALUES (1, 'Craft', 1), (2, 'Performance', 2);

SELECT heritage_sites.name, heritage_sites.location FROM heritage_sites INNER JOIN workshops ON heritage_sites.id = workshops.site_id WHERE workshops.type = 'Craft';


Question: Generate PostgreSQL SQL for: How many grid numbers were there for the driver Giancarlo Fisichella?

CREATE TABLE table_name_3 (grid VARCHAR, driver VARCHAR)

SELECT COUNT(grid) FROM table_name_3 WHERE driver = 'giancarlo fisichella';


Question: Generate PostgreSQL SQL for: Name the district for nairs 8.2

CREATE TABLE table_23214055_2 (district VARCHAR, nairs VARCHAR)

SELECT district FROM table_23214055_2 WHERE nairs = '8.2';


Question: Write the DML statement from PostgreSQL regression test 'prepared_xacts' (example 25).

Explanation: DML from PostgreSQL core regression test for Prepared Xacts.


Question: Generate PostgreSQL SQL for: Who's the opposition at westpac stadium when the attendance is 31,853?

CREATE TABLE table_name_56 (opposition VARCHAR, stadium VARCHAR, attendance VARCHAR)

SELECT opposition FROM table_name_56 WHERE stadium = 'westpac stadium' AND attendance = '31,853';


Question: Which climate communication projects are not in 'North America'?

CREATE TABLE climate_communication (project_id INTEGER, project_name TEXT, location TEXT); INSERT INTO climate_communication (project_id, project_name, location) VALUES (1, 'Project I', 'North America'), (2, 'Project J', 'Europe');

SELECT project_name FROM climate_communication WHERE location != 'North America';


Question: What is the minimum dissolved oxygen level recorded in each monitoring zone in the past year?

CREATE TABLE yearly_dissolved_oxygen (zone_id INT, zone_name TEXT, date DATE, dissolved_oxygen FLOAT); INSERT INTO yearly_dissolved_oxygen (zone_id, zone_name, date, dissolved_oxygen) VALUES (1, 'Zone A', '2022-01-01', 8.1), (2, 'Zone B', '2022-01-01', 7.9), (3, 'Zone C', '2022-01-01', 8.5), (1, 'Zone A', '2022-01-02', 7.8), (2, 'Zone B', '2022-01-02', 8.2), (3, 'Zone C', '2022-01-02', 8.6);

SELECT zone_name, MIN(dissolved_oxygen) FROM yearly_dissolved_oxygen WHERE date >= DATE_SUB(CURDATE(), INTERVAL 1 YEAR) GROUP BY zone_name;


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

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


Question: Generate PostgreSQL SQL for: What is the highest crowd number of the game where the away team was south melbourne?

CREATE TABLE table_name_71 (crowd INTEGER, away_team VARCHAR)

SELECT MAX(crowd) FROM table_name_71 WHERE away_team = 'south melbourne';


Question: What is the highest number of consecutive successful free throws by each basketball player in the 2022 season?

CREATE TABLE free_throws (player_id INT, player_name VARCHAR(50), consecutive_successful_free_throws INT); INSERT INTO free_throws (player_id, player_name, consecutive_successful_free_throws) VALUES (1, 'LeBron James', 56), (2, 'Stephen Curry', 62), (3, 'Nikola Jokic', 45), (4, 'James Harden', 72), (5, 'Luka Doncic', 58);

SELECT player_name, MAX(consecutive_successful_free_throws) as max_consecutive_successful_free_throws FROM free_throws GROUP BY player_name;


Question: Show an example of PostgreSQL CREATE INDEX (example 1).

CREATE UNIQUE INDEX title_idx ON films (title);

Explanation: PostgreSQL CREATE INDEX command.


Question: What is the average depth of all underground mines?

CREATE TABLE underground_mines (mine_id INT, mine_name VARCHAR(50), depth FLOAT); INSERT INTO underground_mines (mine_id, mine_name, depth) VALUES (1, 'Mine X', 1200), (2, 'Mine Y', 1500), (3, 'Mine Z', 1800);

SELECT AVG(depth) FROM underground_mines WHERE method_name = 'Underground';


Question: Generate PostgreSQL SQL for: What was the distance for the winner or 2nd Waterline?

CREATE TABLE table_name_21 (distance VARCHAR, winner_or_2nd VARCHAR)

SELECT distance FROM table_name_21 WHERE winner_or_2nd = 'waterline';


Question: Generate PostgreSQL SQL for: What team is owned by Mark Smith and has Paul Clapprood as a crew chief?

CREATE TABLE table_name_8 (team VARCHAR, owner_s_ VARCHAR, crew_chief VARCHAR)

SELECT team FROM table_name_8 WHERE owner_s_ = 'mark smith' AND crew_chief = 'paul clapprood';


Question: Generate PostgreSQL SQL for: What is the time/retired if the driver is Marco Andretti?

CREATE TABLE table_17693171_1 (time_retired VARCHAR, driver VARCHAR)

SELECT time_retired FROM table_17693171_1 WHERE driver = 'Marco Andretti';


Question: Generate PostgreSQL SQL for: What district did Donald Ray Matthews belong to?

CREATE TABLE table_1341865_11 (district VARCHAR, incumbent VARCHAR)

SELECT district FROM table_1341865_11 WHERE incumbent = 'Donald Ray Matthews';


Question: Generate PostgreSQL SQL for: What Event has a Competition of world championships?

CREATE TABLE table_name_77 (event VARCHAR, competition VARCHAR)

SELECT event FROM table_name_77 WHERE competition = 'world championships';


Question: Generate PostgreSQL SQL for: How many performances are there?


Question: Delete any soil moisture readings that have a moisture level below 30.

CREATE TABLE Soil_Moisture (ID INT, Moisture FLOAT, Timestamp DATETIME); INSERT INTO Soil_Moisture (ID, Moisture, Timestamp) VALUES (1, 45, '2022-01-01 10:00:00'), (2, 28, '2022-01-15 12:00:00');

DELETE FROM Soil_Moisture WHERE Moisture < 30;


Question: How many mental health parity violations occurred in each region over the past year?

CREATE TABLE MentalHealthParity (ViolationID INT, Region VARCHAR(255), ViolationDate DATE); INSERT INTO MentalHealthParity (ViolationID, Region, ViolationDate) VALUES (1, 'Northeast', '2022-01-02'), (2, 'Southeast', '2022-03-04'), (3, 'Midwest', '2022-05-01'), (4, 'Southwest', '2022-07-15'), (5, 'West', '2022-09-30');

SELECT Region, COUNT(*) as ViolationCount FROM MentalHealthParity WHERE ViolationDate >= DATEADD(year, -1, GETDATE()) GROUP BY Region;


Question: Generate PostgreSQL SQL for: Which surface has wynne prakusya as the opponent in the final?

CREATE TABLE table_name_51 (surface VARCHAR, opponent_in_the_final VARCHAR)

SELECT surface FROM table_name_51 WHERE opponent_in_the_final = 'wynne prakusya';


Question: Generate PostgreSQL SQL for: Which chassis scored 52 points?

CREATE TABLE table_name_55 (chassis VARCHAR, points VARCHAR)

SELECT chassis FROM table_name_55 WHERE points = 52;


Question: What is the total number of network infrastructure investments in the 'Asia' region?

CREATE TABLE network_investments (investment_id INT, investment_amount FLOAT, investment_type VARCHAR(20), region VARCHAR(20)); INSERT INTO network_investments (investment_id, investment_amount, investment_type, region) VALUES (1, 500000, 'Cell Tower', 'Asia'), (2, 750000, 'Broadband Node', 'Europe'), (3, 300000, 'Cell Tower', 'Africa'), (4, 900000, 'Broadband Node', 'North America');

SELECT SUM(investment_amount) FROM network_investments WHERE region = 'Asia';


Question: Write the DML statement from PostgreSQL regression test 'rules' (example 129).

insert into rtest_empmass values ('meyer', '4000.00');

Explanation: DML from PostgreSQL core regression test for Rules.


Question: List all the broadband subscribers in Texas who have a plan with speeds over 100 Mbps?

CREATE TABLE broadband_subscribers (subscriber_id INT, home_location VARCHAR(50), plan_speed DECIMAL(10,2)); INSERT INTO broadband_subscribers (subscriber_id, home_location, plan_speed) VALUES (1, 'Texas', 150), (2, 'California', 75), (3, 'Texas', 120);

SELECT subscriber_id, home_location FROM broadband_subscribers WHERE plan_speed > 100 AND home_location = 'Texas';