Question: What is the average age of players who have played Virtual Reality games?

CREATE TABLE players (id INT, age INT, country VARCHAR(50), vrgames BOOLEAN); INSERT INTO players (id, age, country, vrgames) VALUES (1, 25, 'Canada', true), (2, 30, 'USA', false);

SELECT AVG(age) FROM players WHERE vrgames = true;


Question: Generate PostgreSQL SQL for: What is the HDTV when documentaries are the content?

CREATE TABLE table_name_84 (hdtv VARCHAR, content VARCHAR)

SELECT hdtv FROM table_name_84 WHERE content = 'documentaries';


Question: Generate PostgreSQL SQL for: Who won group III when group 1 was of the racing club?

CREATE TABLE table_name_99 (group_iII VARCHAR, group_i VARCHAR)

SELECT group_iII FROM table_name_99 WHERE group_i = 'racing club';


Question: Generate PostgreSQL SQL for: What was the total crowd size for the him team footscray?

CREATE TABLE table_name_95 (crowd VARCHAR, home_team VARCHAR)

SELECT COUNT(crowd) FROM table_name_95 WHERE home_team = 'footscray';


Question: Generate PostgreSQL SQL for: Which stage number did son bou arrive at?

CREATE TABLE table_name_22 (stage VARCHAR, arrival VARCHAR)

SELECT COUNT(stage) FROM table_name_22 WHERE arrival = 'son bou';


Question: Generate PostgreSQL SQL for: What was the attendance record for Leicester City?

CREATE TABLE table_name_17 (attendance VARCHAR, home_team VARCHAR)

SELECT attendance FROM table_name_17 WHERE home_team = 'leicester city';


Question: What is the total investment and investment rank for companies in the 'USA'?

CREATE TABLE company (id INT, name VARCHAR(50), founding_year INT, industry VARCHAR(50), country VARCHAR(50)); INSERT INTO company (id, name, founding_year, industry, country) VALUES (1, 'Acme Inc', 2010, 'Tech', 'USA'); CREATE TABLE investment (id INT, company_id INT, investment_amount INT, investment_round VARCHAR(50), investment_date DATE); INSERT INTO investment (id, company_id, investment_amount, investment_round, investment_date) VALUES (1, 1, 5000000, 'Series A', '2012-04-01');

SELECT company_id, SUM(investment_amount) as total_investment, RANK() OVER (PARTITION BY company_id ORDER BY SUM(investment_amount) DESC) as investment_rank FROM investment WHERE (SELECT country FROM company WHERE id = company_id) = 'USA' GROUP BY company_id;


Question: Generate PostgreSQL SQL for: What is the average week number of all the matches where less than 22,604 people attended?

CREATE TABLE table_name_75 (week INTEGER, attendance INTEGER)

SELECT AVG(week) FROM table_name_75 WHERE attendance < 22 OFFSET 604;


Question: Generate PostgreSQL SQL for: Which Placings have a Nation of west germany, and Points larger than 303.72?

CREATE TABLE table_name_31 (placings INTEGER, nation VARCHAR, points VARCHAR)

SELECT SUM(placings) FROM table_name_31 WHERE nation = 'west germany' AND points > 303.72;


Question: Generate PostgreSQL SQL for: What NFL team did the Tight End position belong to?

CREATE TABLE table_name_62 (nfl_team VARCHAR, position VARCHAR)

SELECT nfl_team FROM table_name_62 WHERE position = 'tight end';


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

CREATE OPERATOR - (
	LEFTARG = hstore,
	RIGHTARG = text[],
	PROCEDURE = delete
);

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


Question: Generate PostgreSQL SQL for: What team was in 1st plate in a year later than 1956?

CREATE TABLE table_name_84 (year INTEGER)

SELECT 1 AS st_place_team FROM table_name_84 WHERE year > 1956;


Question: List all unique waste types from the 'waste_types' table

CREATE TABLE waste_types (waste_type_id INT, waste_type_name VARCHAR(50));

SELECT DISTINCT waste_type_name FROM waste_types;


Question: What is the total data usage for mobile customers in the city of London in the past week?

CREATE TABLE mobile_customers (customer_id INT, city VARCHAR(20), data_usage FLOAT); INSERT INTO mobile_customers (customer_id, city, data_usage) VALUES (1, 'London', 3000), (2, 'Paris', 4000), (3, 'London', 2500);

SELECT SUM(data_usage) FROM mobile_customers WHERE city = 'London' AND last_usage_date >= DATEADD(week, -1, CURRENT_DATE);


Question: Generate PostgreSQL SQL for: What was the attendance on August 23?

CREATE TABLE table_name_77 (attendance VARCHAR, date VARCHAR)

SELECT COUNT(attendance) FROM table_name_77 WHERE date = 'august 23';


Question: Generate PostgreSQL SQL for: Name the awardee for tingya

CREATE TABLE table_24446718_3 (awardee_s_ VARCHAR, name_of_film VARCHAR)

SELECT awardee_s_ FROM table_24446718_3 WHERE name_of_film = 'Tingya';


Question: List all suppliers from the United States that provide materials to companies with ethical manufacturing practices.

CREATE TABLE suppliers (id INT, name TEXT, country TEXT, ethical_practices BOOLEAN); INSERT INTO suppliers (id, name, country, ethical_practices) VALUES (1, 'XYZ Supplies', 'USA', TRUE), (2, 'LMN Supplies', 'Canada', FALSE), (3, 'OPQ Supplies', 'USA', TRUE); CREATE TABLE purchases (id INT, supplier_id INT, company_id INT, ethical_manufacturing BOOLEAN); INSERT INTO purchases (id, supplier_id, company_id, ethical_manufacturing) VALUES (1, 1, 1, TRUE), (2, 2, 1, FALSE), (3, 3, 1, TRUE);

SELECT s.name FROM suppliers s JOIN purchases p ON s.id = p.supplier_id WHERE s.country = 'USA' AND p.ethical_manufacturing = TRUE;


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

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


Question: Find the dispensaries with a total sales amount greater than $100,000 for hybrid strains in Washington state.

CREATE TABLE DispensarySales(id INT, dispensary VARCHAR(255), state VARCHAR(255), strain_type VARCHAR(255), sales_amount DECIMAL(10,2));

SELECT dispensary FROM DispensarySales WHERE state = 'Washington' AND strain_type = 'Hybrid' GROUP BY dispensary HAVING SUM(sales_amount) > 100000;


Question: Generate PostgreSQL SQL for: What is Record, when Score is 104-99?

CREATE TABLE table_name_55 (record VARCHAR, score VARCHAR)

SELECT record FROM table_name_55 WHERE score = '104-99';


Question: Generate PostgreSQL SQL for: Which Captain 2 has a Result of final?

CREATE TABLE table_name_50 (captain_2 VARCHAR, result VARCHAR)

SELECT captain_2 FROM table_name_50 WHERE result = 'final';


Question: What is the maximum crop yield for farmers in the Quechua community?

CREATE TABLE farmers (name VARCHAR(255), tribe VARCHAR(255), crop_yield INT); INSERT INTO farmers (name, tribe, crop_yield) VALUES ('Juan Lopez', 'Quechua', 1200), ('Maria Rodriguez', 'Quechua', 1500), ('Pedro Gutierrez', 'Quechua', 1000), ('Ana Martinez', 'Quechua', 1300);

SELECT MAX(crop_yield) FROM farmers WHERE tribe = 'Quechua';


Question: Generate PostgreSQL SQL for: Which species has a Voges-Proskauer reading of negative and an indole reading of negative?

CREATE TABLE table_name_43 (species VARCHAR, voges_proskauer VARCHAR, indole VARCHAR)

SELECT species FROM table_name_43 WHERE voges_proskauer = 'negative' AND indole = 'negative';


Question: Update the 'publication_date' of an article with 'article_id' 1 in the 'articles' table

CREATE TABLE articles (article_id INT PRIMARY KEY, title VARCHAR(255), content TEXT, publication_date DATE);

UPDATE articles SET publication_date = '2022-01-15' WHERE article_id = 1;


Question: What is the average salary for each department, along with the number of employees in that department?

CREATE TABLE Employees (EmployeeID INT, FirstName VARCHAR(50), LastName VARCHAR(50), Department VARCHAR(50), Salary DECIMAL(10,2)); INSERT INTO Employees (EmployeeID, FirstName, LastName, Department, Salary) VALUES (1, 'John', 'Doe', 'Mining', 75000.00); INSERT INTO Employees (EmployeeID, FirstName, LastName, Department, Salary) VALUES (2, 'Jane', 'Doe', 'Environment', 70000.00); INSERT INTO Employees (EmployeeID, FirstName, LastName, Department, Salary) VALUES (3, 'Mike', 'Smith', 'Mining', 80000.00);

SELECT Department, AVG(Salary) as 'AvgSalary', COUNT(*) as 'EmployeeCount' FROM Employees GROUP BY Department;


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

SELECT ts_rank(' a:1 sa:2C d g'::tsvector, 'a | sa:*');

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

SELECT count(*) FROM (SELECT ts_rank(' a:1 sa:2C d g'::tsvector, 'a | sa:*')) AS _sub;


Question: Generate PostgreSQL SQL for: Who was recruited from Calgary?

CREATE TABLE table_name_34 (player VARCHAR, college VARCHAR)

SELECT player FROM table_name_34 WHERE college = 'calgary';


Question: Update the salary of employees in the IT department by a 5% increase.

CREATE TABLE SalaryData (EmployeeID INT, Department VARCHAR(50), Salary DECIMAL(10, 2)); INSERT INTO SalaryData VALUES (1, 'IT', 50000); INSERT INTO SalaryData VALUES (2, 'HR', 55000); INSERT INTO SalaryData VALUES (3, 'Finance', 60000);

UPDATE SalaryData SET Salary = Salary * 1.05 WHERE Department = 'IT';


CREATE TABLE workplaces (id INT, name TEXT, safety_rating INT, union_sector TEXT); INSERT INTO workplaces (id, name, safety_rating, union_sector) VALUES (1, 'ABC Company', 88, 'Manufacturing'); INSERT INTO workplaces (id, name, safety_rating, union_sector) VALUES (2, 'XYZ Corporation', 92, 'Transportation');

SELECT *, LAG(safety_rating) OVER (PARTITION BY union_sector ORDER BY id) as previous_rating FROM workplaces;


Question: What is the average speed of spacecraft launched by NASA?

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

SELECT AVG(max_speed) FROM spacecraft WHERE country = 'United States';


Question: Generate PostgreSQL SQL for: What is the distance from Jaffa of Jerusalem station?

CREATE TABLE table_name_1 (distance_from_jaffa VARCHAR, name_location VARCHAR)

SELECT distance_from_jaffa FROM table_name_1 WHERE name_location = 'jerusalem';


Question: What is the average playtime for players who play games in AR, by country?

CREATE TABLE Players (PlayerID INT, Country VARCHAR(20), AR boolean, Playtime INT); INSERT INTO Players (PlayerID, Country, AR, Playtime) VALUES (1, 'Japan', true, 80), (2, 'South Korea', false, 60), (3, 'China', true, 90);

SELECT Country, AVG(Playtime) FROM Players WHERE AR = true GROUP BY Country;


Question: What is the total number of vulnerabilities found in the 'NetworkDevices' table, grouped by severity?

CREATE TABLE NetworkDevices (id INT, device_name VARCHAR(50), severity VARCHAR(10), discovered_date DATE); INSERT INTO NetworkDevices (id, device_name, severity, discovered_date) VALUES (1, 'Router1', 'High', '2021-08-01'), (2, 'Switch1', 'Medium', '2021-07-15'), (3, 'Firewall1', 'Low', '2021-06-01');

SELECT severity, COUNT(*) as total_vulnerabilities FROM NetworkDevices GROUP BY severity;


Question: What is the transaction amount for the most recent transaction of each client?

SELECT client_id, MAX(transaction_amount) as max_transaction_amount FROM transactions GROUP BY client_id;


Question: What are the average innovation scores for each product category, grouped by month?

CREATE TABLE Product(Id INT, Category VARCHAR(50), ManufacturerId INT); CREATE TABLE InnovationScore(Id INT, Score INT, ProductId INT, ScoreDate DATE);

SELECT p.Category, DATE_FORMAT(i.ScoreDate, '%Y-%m') AS Month, AVG(i.Score) AS AverageScore FROM InnovationScore i JOIN Product p ON i.ProductId = p.Id GROUP BY p.Category, Month;


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

select f3, myaggn05a(f1) from t group by f3 order by f3;

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

SELECT count(*) FROM (select f3, myaggn05a(f1) from t group by f3 order by f3) AS _sub;


Question: What is the average ESG score for each sector in 2022?

CREATE TABLE companies (company_id INT, company_name VARCHAR(255), sector VARCHAR(255), esg_score INT, year INT); INSERT INTO companies (company_id, company_name, sector, esg_score, year) VALUES (1, 'GreenTech Inc', 'Technology', 85, 2022), (2, 'EcoFarms Ltd', 'Agriculture', 75, 2022), (3, 'CleanEnergy Co', 'Energy', 90, 2022);

SELECT sector, AVG(esg_score) as avg_esg_score FROM companies WHERE year = 2022 GROUP BY sector;


Question: Generate PostgreSQL SQL for: What was the earliest Round for Central Florida?

CREATE TABLE table_name_32 (round INTEGER, team VARCHAR)

SELECT MIN(round) FROM table_name_32 WHERE team = 'central florida';


Question: Generate PostgreSQL SQL for: What were the home team scores at york park?

CREATE TABLE table_16388478_2 (home_team VARCHAR, ground VARCHAR)

SELECT home_team AS score FROM table_16388478_2 WHERE ground = 'York Park';


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

INSERT INTO num_exp_add VALUES (1,0,'0');

Explanation: DML from PostgreSQL core regression test for Numeric.


Question: Generate PostgreSQL SQL for: what are the endings of examples achilles, appendices, fæces

CREATE TABLE table_17798093_20 (ending VARCHAR, examples VARCHAR)

SELECT ending FROM table_17798093_20 WHERE examples = 'Achilles, appendices, fæces';


Question: What is the total number of high severity incidents in the 'IncidentReports' table?

CREATE TABLE IncidentReports (id INT, incident_name VARCHAR(50), severity VARCHAR(10), incident_type VARCHAR(50)); INSERT INTO IncidentReports (id, incident_name, severity, incident_type) VALUES (1, 'Incident1', 'High', 'Malware'), (2, 'Incident2', 'Medium', 'Phishing'), (3, 'Incident3', 'Low', 'Unpatched Software'), (4, 'Incident4', 'High', 'SQL Injection'), (5, 'Incident5', 'Low', 'Denial of Service');

SELECT COUNT(*) as total_high_severity_incidents FROM IncidentReports WHERE severity = 'High';


Question: What are the total construction costs for each type of building permit in the city of Seattle for the year 2020?

CREATE TABLE building_permits (permit_type TEXT, city TEXT, cost INTEGER, year INTEGER);INSERT INTO building_permits (permit_type, city, cost, year) VALUES ('Residential', 'Seattle', 200000, 2020), ('Commercial', 'Seattle', 500000, 2020), ('Industrial', 'Seattle', 300000, 2020);

SELECT permit_type, SUM(cost) FROM building_permits WHERE city = 'Seattle' AND year = 2020 GROUP BY permit_type;


Question: Generate PostgreSQL SQL for: Which organization administered the poll that showed a lead margin of 5.5?

CREATE TABLE table_name_88 (poll_source VARCHAR, lead_margin VARCHAR)

SELECT poll_source FROM table_name_88 WHERE lead_margin = 5.5;


Question: PostgreSQL regression test 'cluster': Write the SELECT query (example 48).

SELECT a,b,c,substring(d for 30), length(d) from clstr_tst ORDER BY a;

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

SELECT count(*) FROM (SELECT a,b,c,substring(d for 30), length(d) from clstr_tst ORDER BY a) AS _sub;


Question: Generate PostgreSQL SQL for: How many stages were won by Robbie McEwen?

CREATE TABLE table_17672470_19 (stage VARCHAR, winner VARCHAR)

SELECT COUNT(stage) FROM table_17672470_19 WHERE winner = 'Robbie McEwen';


Question: What are the average recycling rates in percentage for each district in Southeast Asia in 2020?

CREATE TABLE recycling_rates_southeast_asia (district VARCHAR(50), year INT, recycling_rate FLOAT); INSERT INTO recycling_rates_southeast_asia (district, year, recycling_rate) VALUES ('Bangkok', 2020, 30.0), ('Ho_Chi_Minh_City', 2020, 25.0), ('Jakarta', 2020, 22.0), ('Kuala_Lumpur', 2020, 35.0), ('Singapore', 2020, 45.0);

SELECT district, AVG(recycling_rate) FROM recycling_rates_southeast_asia WHERE year = 2020 GROUP BY district;


Question: Generate PostgreSQL SQL for: How many outcomes occur for score in the final of 6–3, 6–4, 7–6 (13–11)?

CREATE TABLE table_26202940_6 (outcome VARCHAR, score_in_the_final VARCHAR)

SELECT COUNT(outcome) FROM table_26202940_6 WHERE score_in_the_final = '6–3, 6–4, 7–6 (13–11)';


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

--Similar to normal vacuum tests, but PG11 introduced ability to vacuum multiple tables at once, we make sure that works for hypertables as well.
CREATE TABLE vacuum_test(time timestamp, temp float);

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


Question: Generate PostgreSQL SQL for: who got the first position when  Ehime Shimanami got the third position?

CREATE TABLE table_21632864_1 (champions VARCHAR, third_place VARCHAR)

SELECT champions FROM table_21632864_1 WHERE third_place = 'Ehime Shimanami';


Question: What is the maximum age of a mental health professional in Georgia?

CREATE TABLE MentalHealthProfessional (ProfessionalID INT, Age INT, Specialty VARCHAR(50), State VARCHAR(20)); INSERT INTO MentalHealthProfessional (ProfessionalID, Age, Specialty, State) VALUES (1, 50, 'Psychologist', 'Georgia'); INSERT INTO MentalHealthProfessional (ProfessionalID, Age, Specialty, State) VALUES (2, 45, 'Social Worker', 'Georgia'); INSERT INTO MentalHealthProfessional (ProfessionalID, Age, Specialty, State) VALUES (3, 55, 'Counselor', 'Georgia');

SELECT MAX(Age) FROM MentalHealthProfessional WHERE State = 'Georgia';


Question: Generate PostgreSQL SQL for: What was the table position for the team whose outgoing manager was Brian Laws?

CREATE TABLE table_26593762_3 (position_in_table VARCHAR, outgoing_manager VARCHAR)

SELECT position_in_table FROM table_26593762_3 WHERE outgoing_manager = 'Brian Laws';


Question: Generate PostgreSQL SQL for: Name the tries with tries against of 38

CREATE TABLE table_name_35 (tries_for VARCHAR, tries_against VARCHAR)

SELECT tries_for FROM table_name_35 WHERE tries_against = '38';


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


Question: Generate PostgreSQL SQL for: What was the event for vinny magalhães?

CREATE TABLE table_name_74 (event VARCHAR, opponent VARCHAR)

SELECT event FROM table_name_74 WHERE opponent = 'vinny magalhães';


Question: PL/pgSQL test: Plperl Plperlu (example 5).

create or replace function foo(text) returns text language plperl  as 'shift';

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


Question: What is the percentage of mobile subscribers who have experienced a network issue in the last month, grouped by device model?

CREATE TABLE mobile_subscribers_network_issues (subscriber_id INT, name VARCHAR(255), device_model VARCHAR(255), last_network_issue_date DATE); INSERT INTO mobile_subscribers_network_issues (subscriber_id, name, device_model, last_network_issue_date) VALUES (1, 'John Doe', 'iPhone 12', '2022-01-15'), (2, 'Jane Doe', 'iPhone 12', '2022-02-01'), (3, 'Maria Garcia', 'Samsung Galaxy S21', NULL);

SELECT device_model, 100.0 * COUNT(CASE WHEN last_network_issue_date IS NOT NULL AND last_network_issue_date >= DATE_SUB(CURDATE(), INTERVAL 1 MONTH) THEN 1 END) / COUNT(*) AS percentage FROM mobile_subscribers_network_issues GROUP BY device_model;


Question: What is the maximum container count in a single cargo transaction for port 'HOU'?

CREATE TABLE ports (port_id INT, port_name VARCHAR(20)); INSERT INTO ports (port_id, port_name) VALUES (1, 'LA'), (2, 'LB'), (3, 'HOU'); CREATE TABLE cargo (cargo_id INT, port_id INT, container_count INT); INSERT INTO cargo (cargo_id, port_id, container_count) VALUES (1, 1, 5000), (2, 1, 3000), (3, 2, 4000), (4, 3, 6000), (5, 3, 7000), (6, 3, 8000);

SELECT MAX(container_count) FROM cargo WHERE port_id = (SELECT port_id FROM ports WHERE port_name = 'HOU');


Question: Generate PostgreSQL SQL for: Which royal house has the name huai?

CREATE TABLE table_name_88 (royal_house VARCHAR, name VARCHAR)

SELECT royal_house FROM table_name_88 WHERE name = 'huai';


Question: Generate PostgreSQL SQL for: In what category was character Jacqui Mcqueen nominated before 2011?

CREATE TABLE table_name_67 (category VARCHAR, character VARCHAR, year VARCHAR)

SELECT category FROM table_name_67 WHERE character = 'jacqui mcqueen' AND year < 2011;


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

DROP TRIGGER d1_update_trig ON part_d_1_15;

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


Question: What is the total cargo weight handled by each port during the second half of 2022?

CREATE TABLE ports (id INT, name TEXT, country TEXT); CREATE TABLE cargo_movements (id INT, port_id INT, cargo_type TEXT, weight INT, date DATE); INSERT INTO ports (id, name, country) VALUES (1, 'Port of Singapore', 'Singapore'), (2, 'Port of Shanghai', 'China'), (3, 'Port of Busan', 'South Korea'); INSERT INTO cargo_movements (id, port_id, cargo_type, weight, date) VALUES (1, 1, 'Bulk', 10000, '2022-07-01'), (2, 1, 'Breakbulk', 8000, '2022-07-02'), (3, 2, 'Bulk', 12000, '2022-07-01'), (4, 2, 'Breakbulk', 9000, '2022-07-02'), (5, 3, 'Bulk', 15000, '2022-07-01'), (6, 3, 'Breakbulk', 11000, '2022-07-02');

SELECT p.name, SUM(cm.weight) FROM ports p JOIN cargo_movements cm ON p.id = cm.port_id WHERE MONTH(cm.date) > 6 GROUP BY p.name;


Question: Generate PostgreSQL SQL for: How many silver when the team is northwest territories and gold is less than 34?

CREATE TABLE table_name_14 (silver VARCHAR, team VARCHAR, gold VARCHAR)

SELECT COUNT(silver) FROM table_name_14 WHERE team = 'northwest territories' AND gold < 34;


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

CREATE TABLE AircraftManufacturing (id INT, manufacturer VARCHAR(255), country VARCHAR(255), cost FLOAT); INSERT INTO AircraftManufacturing VALUES (1, 'Boeing', 'USA', 120000000), (2, 'Airbus', 'Europe', 150000000), (3, 'Lockheed Martin', 'USA', 200000000);

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


Question: Generate PostgreSQL SQL for: What is the average Worst score for Mario Lopez as the Best dancer and Tango as the Dance?

CREATE TABLE table_name_81 (worst_score INTEGER, best_dancer VARCHAR, dance VARCHAR)

SELECT AVG(worst_score) FROM table_name_81 WHERE best_dancer = 'mario lopez' AND dance = 'tango';


Question: Generate PostgreSQL SQL for: What tournament has 1r as the 2011?

CREATE TABLE table_name_12 (tournament VARCHAR)

SELECT tournament FROM table_name_12 WHERE 2011 = '1r';


Question: Determine the change in the number of community health workers by race over time?

CREATE TABLE community_health_workers (id INT, name VARCHAR(50), age INT, race VARCHAR(50), hire_date DATE); INSERT INTO community_health_workers (id, name, age, race, hire_date) VALUES (1, 'John Doe', 35, 'White', '2020-01-01'), (2, 'Jane Smith', 40, 'Black', '2019-01-01'), (3, 'Jose Rodriguez', 30, 'Hispanic', '2021-01-01');

SELECT race, COUNT(*) as current_count, LAG(COUNT(*)) OVER (PARTITION BY race ORDER BY hire_date) as previous_count FROM community_health_workers GROUP BY race, hire_date;


Question: What is the average orbital velocity of the International Space Station?

CREATE TABLE space_objects (name TEXT, orbital_velocity_km_s INTEGER); INSERT INTO space_objects (name, orbital_velocity_km_s) VALUES ('ISS', 27600), ('Hubble Space Telescope', 28600), ('Moon', 1680);

SELECT AVG(orbital_velocity_km_s) FROM space_objects WHERE name = 'ISS';


Question: Generate PostgreSQL SQL for: What is Year is Walt Disney Pictures Imagemovers Digital?

CREATE TABLE table_name_59 (year INTEGER, studio_s_ VARCHAR)

SELECT SUM(year) FROM table_name_59 WHERE studio_s_ = 'walt disney pictures imagemovers digital';


Question: How many professional development workshops were held in 2021?

CREATE TABLE workshops (workshop_id INT, year INT, PRIMARY KEY (workshop_id, year)); INSERT INTO workshops (workshop_id, year) VALUES (1, 2021), (2, 2021), (3, 2021);

SELECT COUNT(*) FROM workshops WHERE year = 2021;


Question: List all investments made by customers in Sydney with an investment amount greater than 5000.

CREATE TABLE investment (id INT, customer_id INT, investment_date DATE, amount DECIMAL(10, 2)); INSERT INTO investment (id, customer_id, investment_date, amount) VALUES (1, 1, '2022-01-01', 6000.00), (2, 2, '2022-01-02', 7000.00); CREATE TABLE customer (id INT, name VARCHAR(255), address VARCHAR(255)); INSERT INTO customer (id, name, address) VALUES (1, 'John Smith', 'Sydney'), (2, 'Jane Doe', 'Melbourne');

SELECT * FROM investment i JOIN customer c ON i.customer_id = c.id WHERE c.address = 'Sydney' AND i.amount > 5000;


Question: Find the number of unique educational programs in 'community_education' table

CREATE TABLE community_education (id INT, program VARCHAR(50), location VARCHAR(50), date DATE);

SELECT COUNT(DISTINCT program) FROM community_education;


Question: How many students received accommodations in "Latin America" region in 2020?

CREATE TABLE Accommodations (student_id INT, region VARCHAR(20), accommodation_date DATE); INSERT INTO Accommodations (student_id, region, accommodation_date) VALUES (1, 'West Coast', '2020-01-01'), (2, 'East Coast', '2019-12-31'), (3, 'West Coast', '2020-02-01'), (4, 'Southwest', '2019-01-01'), (5, 'Latin America', '2020-03-01');

SELECT COUNT(*) FROM Accommodations WHERE region = 'Latin America' AND EXTRACT(YEAR FROM accommodation_date) = 2020;


Question: Update the price of all vegan nail polishes to $12.99

CREATE TABLE nail_polish_sales(product_id INT, sale_price FLOAT); INSERT INTO nail_polish_sales(product_id, sale_price) VALUES (1, 9.99); INSERT INTO nail_polish_sales(product_id, sale_price) VALUES (2, 10.99); CREATE TABLE product_info(product_id INT, is_vegan BOOLEAN); INSERT INTO product_info(product_id, is_vegan) VALUES (1, TRUE); INSERT INTO product_info(product_id, is_vegan) VALUES (2, FALSE); CREATE TABLE product_categories(product_id INT, category_name VARCHAR(50)); INSERT INTO product_categories(product_id, category_name) VALUES (1, 'Nail Polish'); INSERT INTO product_categories(product_id, category_name) VALUES (2, 'Makeup');

UPDATE nail_polish_sales SET sale_price = 12.99 FROM nail_polish_sales INNER JOIN product_info ON nail_polish_sales.product_id = product_info.product_id INNER JOIN product_categories ON nail_polish_sales.product_id = product_categories.product_id WHERE product_info.is_vegan = TRUE AND product_categories.category_name = 'Nail Polish';


Question: Generate PostgreSQL SQL for: What is KK -1 if KK -3 is 1,100?

CREATE TABLE table_name_79 (kk___1 VARCHAR, kk___3 VARCHAR)

SELECT kk___1 FROM table_name_79 WHERE kk___3 = '1,100';


Question: Add a new union named 'United Workers Union' with a membership count of 5000 to the union_members table

CREATE TABLE union_members (union_id SERIAL PRIMARY KEY, union_name TEXT, membership_count INT);

INSERT INTO union_members (union_name, membership_count) VALUES ('United Workers Union', 5000);


Question: What is the total number of hours played for the game 'League of Legends'?

CREATE TABLE PlayerActivity (PlayerID INT, Game VARCHAR(100), HoursPlayed INT); INSERT INTO PlayerActivity (PlayerID, Game, HoursPlayed) VALUES (1, 'Overwatch', 500); INSERT INTO PlayerActivity (PlayerID, Game, HoursPlayed) VALUES (2, 'League of Legends', 1000); INSERT INTO PlayerActivity (PlayerID, Game, HoursPlayed) VALUES (3, 'Fortnite', 750);

SELECT SUM(HoursPlayed) FROM PlayerActivity WHERE Game = 'League of Legends';


Question: Show the average popularity score for each region in 'trends_by_region' table

CREATE TABLE trends_by_region (id INT PRIMARY KEY, region VARCHAR(255), trend_name VARCHAR(255), popularity_score INT);

SELECT region, AVG(popularity_score) FROM trends_by_region GROUP BY region;


Question: Delete records from the 'digital_assets' table where the 'asset_type' is 'CBDC' and the 'circulating_supply' is less than 1000000

CREATE TABLE digital_assets (asset_id INT PRIMARY KEY, asset_name VARCHAR(100), asset_type VARCHAR(50), circulating_supply INT);

DELETE FROM digital_assets WHERE asset_type = 'CBDC' AND circulating_supply < 1000000;


Question: Generate PostgreSQL SQL for: What was the date of the game with a goal of 7?

CREATE TABLE table_name_27 (date VARCHAR, goal VARCHAR)

SELECT date FROM table_name_27 WHERE goal = 7;


Question: What is the total revenue generated from ticket sales for each sport?

CREATE TABLE sports (sport VARCHAR(255)); CREATE TABLE ticket_prices (sport VARCHAR(255), price DECIMAL(5,2)); CREATE TABLE ticket_sales (sport VARCHAR(255), tickets INT); INSERT INTO sports VALUES ('Basketball'), ('Football'), ('Hockey'), ('Soccer'); INSERT INTO ticket_prices VALUES ('Basketball', 80.50), ('Basketball', 75.20), ('Football', 120.00), ('Football', 110.50), ('Hockey', 65.00), ('Hockey', 70.00), ('Soccer', 40.00), ('Soccer', 45.00); INSERT INTO ticket_sales VALUES ('Basketball', 2500), ('Basketball', 3000), ('Football', 5000), ('Football', 6000), ('Hockey', 2000), ('Hockey', 2500), ('Soccer', 1000), ('Soccer', 1500);

SELECT sport, SUM(price * tickets) as total_revenue FROM ticket_prices INNER JOIN ticket_sales ON ticket_prices.sport = ticket_sales.sport GROUP BY sport;


Question: What is the total number of tourists who visited cultural heritage sites in India last year?

CREATE TABLE countries (country_id INT, country TEXT); INSERT INTO countries (country_id, country) VALUES (1, 'India'); CREATE TABLE years (year_id INT, year TEXT); INSERT INTO years (year_id, year) VALUES (1, '2022'); CREATE TABLE tourism (tourist_id INT, country_id INT, year_id INT, site_type TEXT); INSERT INTO tourism (tourist_id, country_id, year_id, site_type) VALUES (1, 1, 1, 'cultural_heritage'), (2, 1, 1, 'beach'), (3, 1, 1, 'cultural_heritage');

SELECT COUNT(*) FROM tourism WHERE country_id = (SELECT country_id FROM countries WHERE country = 'India') AND year_id = (SELECT year_id FROM years WHERE year = '2022') AND site_type = 'cultural_heritage';


Question: What is the change in online travel agency bookings per month for hotels in the 'africa_hotels' view?

CREATE VIEW africa_hotels AS SELECT * FROM hotels WHERE continent = 'Africa'; CREATE VIEW online_travel_agency_bookings AS SELECT hotel_id, COUNT(*) as bookings, DATE_TRUNC('month', booking_date) as month FROM online_travel_agency GROUP BY hotel_id, month;

SELECT l.name, LAG(o.bookings) OVER (PARTITION BY l.id ORDER BY o.month) as previous_month_bookings, o.bookings as current_month_bookings FROM africa_hotels l JOIN online_travel_agency_bookings o ON l.id = o.hotel_id ORDER BY o.month;


Question: Generate PostgreSQL SQL for: What event ended in 3:02 of round 1?

CREATE TABLE table_name_92 (event VARCHAR, round VARCHAR, time VARCHAR)

SELECT event FROM table_name_92 WHERE round = 1 AND time = '3:02';


Question: Generate PostgreSQL SQL for: what is the minimum of 60 -64?

CREATE TABLE table_16457934_4 (Id VARCHAR)

SELECT MIN(60 AS _to_64) FROM table_16457934_4;


Question: Which state has the lowest average salary for workers in the 'service' industry?

CREATE TABLE service_workers (id INT, name VARCHAR(255), state VARCHAR(255), industry VARCHAR(255), salary DECIMAL(10,2)); INSERT INTO service_workers (id, name, state, industry, salary) VALUES (1, 'James White', 'Texas', 'service', 30000.00), (2, 'Emily Green', 'Florida', 'service', 32000.00);

SELECT state, AVG(salary) FROM service_workers WHERE industry = 'service' GROUP BY state ORDER BY AVG(salary) ASC LIMIT 1;


Question: Write the DDL statement from PostgreSQL regression test 'dependency' (example 31).

Explanation: DDL from PostgreSQL core regression test for Dependency.


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

SELECT * FROM numrange_test WHERE range_contained_by(numrange(-1e7,-10000.1), nr);

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

SELECT count(*) FROM (SELECT * FROM numrange_test WHERE range_contained_by(numrange(-1e7,-10000.1), nr)) AS _sub;


Question: What is the number of police officers in Colorado and the number of crimes reported in the state?

CREATE TABLE states (id INT, name VARCHAR(255)); INSERT INTO states (id, name) VALUES (1, 'Colorado'); CREATE TABLE police_departments (id INT, state_id INT, officers INT); INSERT INTO police_departments (id, state_id, officers) VALUES (1, 1, 5000), (2, 1, 6000), (3, 1, 7000), (4, 1, 8000); CREATE TABLE crimes (id INT, state_id INT, reported INT); INSERT INTO crimes (id, state_id, reported) VALUES (1, 1, 50000), (2, 1, 60000), (3, 1, 70000), (4, 1, 80000);

SELECT SUM(police_departments.officers) AS total_officers, SUM(crimes.reported) AS total_crimes FROM police_departments INNER JOIN states ON police_departments.state_id = states.id INNER JOIN crimes ON states.id = crimes.state_id WHERE states.name = 'Colorado';


Question: Generate PostgreSQL SQL for: What is the Type of castle from the 14th Century which Condition is preserved?

CREATE TABLE table_name_72 (type VARCHAR, date VARCHAR, condition VARCHAR)

SELECT type FROM table_name_72 WHERE date = '14th century' AND condition = 'preserved';


Question: What is the maximum installed capacity (in MW) of renewable energy projects in the 'europe' region, partitioned by country?

CREATE TABLE renewable_energy_projects (id INT, country VARCHAR(50), region VARCHAR(50), capacity FLOAT); INSERT INTO renewable_energy_projects (id, country, region, capacity) VALUES (1, 'Germany', 'europe', 3000.00), (2, 'France', 'europe', 2500.00), (3, 'Spain', 'europe', 3500.00);

SELECT region, country, MAX(capacity) as max_capacity FROM renewable_energy_projects WHERE region = 'europe' GROUP BY country, region;


Question: Identify teachers who have not attended any professional development in the last 6 months.

CREATE TABLE Teachers (id INT, name VARCHAR(20)); INSERT INTO Teachers (id, name) VALUES (1, 'Jane Doe'), (2, 'Robert Smith'), (3, 'Alice Johnson'); CREATE TABLE ProfessionalDevelopment (teacher_id INT, attended_date DATE); INSERT INTO ProfessionalDevelopment (teacher_id, attended_date) VALUES (1, '2022-01-01'), (2, '2022-02-15'), (3, '2021-06-20'), (4, '2022-06-01');

SELECT t.name FROM Teachers t LEFT JOIN ProfessionalDevelopment pd ON t.id = pd.teacher_id WHERE pd.teacher_id IS NULL OR pd.attended_date < DATE_SUB(CURRENT_DATE, INTERVAL 6 MONTH);


Question: Generate PostgreSQL SQL for: What district re-elected a Republican?

CREATE TABLE table_name_21 (district VARCHAR, party VARCHAR, results VARCHAR)

SELECT district FROM table_name_21 WHERE party = 'republican' AND results = 're-elected';


Question: Generate PostgreSQL SQL for: What is the school of the player from the College of Michigan?

CREATE TABLE table_name_35 (school VARCHAR, college VARCHAR)

SELECT school FROM table_name_35 WHERE college = 'michigan';


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

CREATE TABLE beta_neg_p2 PARTITION OF beta_neg FOR VALUES FROM (200) TO (300);

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


Question: Identify the number of maintenance requests for each vehicle type and year in the 'maintenance' table

CREATE SCHEMA IF NOT EXISTS public_transport;CREATE TABLE IF NOT EXISTS public_transport.maintenance (maintenance_id SERIAL PRIMARY KEY, vehicle_type TEXT, request_date DATE);INSERT INTO public_transport.maintenance (vehicle_type, request_date) VALUES ('Bus', '2022-02-01'), ('Tram', '2022-02-02'), ('Bus', '2022-03-03'), ('Tram', '2022-03-04');

SELECT EXTRACT(YEAR FROM request_date) AS year, vehicle_type, COUNT(*) FROM public_transport.maintenance GROUP BY EXTRACT(YEAR FROM request_date), vehicle_type;


Question: Generate PostgreSQL SQL for: What number was the person eliminated at 22:50?

CREATE TABLE table_29692554_2 (eliminated VARCHAR, time VARCHAR)

SELECT eliminated FROM table_29692554_2 WHERE time = '22:50';


Question: What are the types and unit costs of equipment that have been shipped to the Middle East?

CREATE TABLE Equipment (id INT, equipment_type VARCHAR(255), manufacturer VARCHAR(255), production_year INT, unit_cost DECIMAL(10,2)); CREATE TABLE Shipments (id INT, equipment_type VARCHAR(255), quantity INT, destination VARCHAR(255), delivery_date DATE, equipment_id INT); INSERT INTO Equipment (id, equipment_type, manufacturer, production_year, unit_cost) VALUES (5, 'Missile System', 'Raytheon', 2019, 8000000); INSERT INTO Shipments (id, equipment_type, quantity, destination, delivery_date, equipment_id) VALUES (5, 'Missile System', 5, 'Middle East', '2023-02-20', 5);

SELECT Equipment.equipment_type, Equipment.unit_cost FROM Equipment INNER JOIN Shipments ON Equipment.id = Shipments.equipment_id WHERE Shipments.destination = 'Middle East';


Question: What is the average claim amount for policies in the 'personal_auto' table?

CREATE TABLE personal_auto (policy_id INT, claim_amount DECIMAL(10,2)); INSERT INTO personal_auto (policy_id, claim_amount) VALUES (1, 250.50), (2, 400.75), (3, 120.00);

SELECT AVG(claim_amount) FROM personal_auto;


Question: Which vehicles were showcased at the last auto show in Detroit?

CREATE TABLE AutoShowInfo (Show VARCHAR(50), City VARCHAR(50), Year INT, Vehicle VARCHAR(50)); INSERT INTO AutoShowInfo (Show, City, Year, Vehicle) VALUES ('North American International Auto Show', 'Detroit', 2020, 'Tesla Model Y'), ('North American International Auto Show', 'Detroit', 2020, 'Ford Mustang Mach-E'), ('North American International Auto Show', 'Detroit', 2020, 'Chevrolet Corvette Stingray'), ('Geneva International Motor Show', 'Geneva', 2020, 'Porsche Taycan'), ('Geneva International Motor Show', 'Geneva', 2020, 'Aston Martin DBX');

SELECT Vehicle FROM AutoShowInfo WHERE Show = 'North American International Auto Show' AND City = 'Detroit' AND Year = 2020;


Question: Generate PostgreSQL SQL for: Where was the GTE Suncoast Classic tournament held?

CREATE TABLE table_11622562_1 (location VARCHAR, tournament VARCHAR)

SELECT location FROM table_11622562_1 WHERE tournament = 'GTE Suncoast Classic';


Question: Generate PostgreSQL SQL for: Name the Player which has a To par of –6?

CREATE TABLE table_name_99 (player VARCHAR, to_par VARCHAR)

SELECT player FROM table_name_99 WHERE to_par = '–6';


Question: What is the total maintenance cost for military equipment in the European region in the first half of 2021?

CREATE TABLE military_equipment (equipment_id INT, region VARCHAR(10), maintenance_cost DECIMAL(10,2), maintenance_date DATE); INSERT INTO military_equipment VALUES (1, 'Europe', 5000.00, '2021-03-01'), (2, 'Asia', 6000.00, '2021-04-01'), (3, 'Europe', 4000.00, '2021-06-01');

SELECT SUM(maintenance_cost) FROM military_equipment WHERE region = 'Europe' AND maintenance_date >= DATE '2021-01-01' AND maintenance_date < DATE '2021-07-01';


Question: Generate PostgreSQL SQL for: What is the Decision listed when the Home was Colorado?

CREATE TABLE table_name_28 (decision VARCHAR, home VARCHAR)

SELECT decision FROM table_name_28 WHERE home = 'colorado';


Question: Calculate the percentage of women visiting community health centers in New York

CREATE TABLE community_health_centers (id INT, name TEXT, state TEXT, gender TEXT, count INT); INSERT INTO community_health_centers (id, name, state, gender, count) VALUES (1, 'Center A', 'New York', 'Female', 100), (2, 'Center B', 'New York', 'Male', 75), (3, 'Center C', 'Texas', 'Female', 150);

SELECT state, (SUM(CASE WHEN gender = 'Female' THEN count ELSE 0 END) * 100.0 / SUM(count)) AS percentage FROM community_health_centers WHERE state = 'New York' GROUP BY state;


Question: How many landfills were operational in 2018, excluding data from North America and Europe?

CREATE TABLE LandfillCapacity (year INT, region VARCHAR(50), landfill VARCHAR(50), capacity FLOAT, filled_volume FLOAT); INSERT INTO LandfillCapacity (year, region, landfill, capacity, filled_volume) VALUES (2018, 'North America', 'Landfill A', 100000, 95000), (2018, 'Europe', 'Landfill B', 120000, 110000), (2018, 'Asia', 'Landfill C', 150000, 145000), (2018, 'South America', 'Landfill D', 80000, 75000), (2018, 'Africa', 'Landfill E', 70000, 65000);

SELECT COUNT(*) FROM LandfillCapacity WHERE year = 2018 AND region NOT IN ('North America', 'Europe');


Question: Delete athlete records from the "athletes" table for athletes who are not part of any team

CREATE TABLE athletes (id INT PRIMARY KEY, name VARCHAR(50), age INT, team VARCHAR(50));

DELETE FROM athletes WHERE team IS NULL;


Question: Show the number of Carbon Offset Programs in the United States

CREATE TABLE carbon_offset_programs (id INT, name VARCHAR(100), country VARCHAR(50)); INSERT INTO carbon_offset_programs (id, name, country) VALUES (1, 'Program 1', 'USA'), (2, 'Program 2', 'USA'), (3, 'Program 3', 'Canada');

SELECT COUNT(*) FROM carbon_offset_programs WHERE country = 'USA';


Question: Show a query using PostgreSQL contrib extension 'sepgsql' (example 39).

INSERT INTO t4 VALUES (1,'mmm'), (2,'nnn'), (3,'ooo');

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


Question: Generate PostgreSQL SQL for: What is the sum of the weight that all weightlifters managed to clean and jerk, among weightlifters who had a snatch of more than 95 and a Total of more than 200?

CREATE TABLE table_name_8 (_jerk VARCHAR, clean_ VARCHAR, total__kg_ VARCHAR, snatch VARCHAR)

SELECT COUNT(clean_) & _jerk FROM table_name_8 WHERE total__kg_ = 200 AND snatch > 95;


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

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

SELECT count(*) FROM (select jsonb_path_query('[0, 1, -2, -3.4, 5.6]', '$[*].abs()')) AS _sub;


Question: How many infrastructure projects were completed in 2021 and 2022?

CREATE TABLE infrastructure_projects (id INT, project_name VARCHAR(50), location VARCHAR(50), completion_year INT); INSERT INTO infrastructure_projects (id, project_name, location, completion_year) VALUES (1, 'Highway 101 Expansion', 'California', 2022), (2, 'Bridge Replacement', 'New York', 2021), (3, 'Transit System Upgrade', 'Texas', 2023);

SELECT completion_year, COUNT(*) as num_projects FROM infrastructure_projects WHERE completion_year IN (2021, 2022) GROUP BY completion_year;


Question: What is the maximum temperature recorded in the Antarctic Ocean?

CREATE TABLE antarctic_ocean_temperature (location TEXT, temperature REAL); INSERT INTO antarctic_ocean_temperature (location, temperature) VALUES ('Antarctic Ocean', 2.8), ('Weddell Sea', 1.8), ('Ross Sea', 0.8);

SELECT MAX(temperature) FROM antarctic_ocean_temperature;


Question: Generate PostgreSQL SQL for: What school did player number 21 play for?

CREATE TABLE table_10015132_11 (school_club_team VARCHAR, no VARCHAR)

SELECT school_club_team FROM table_10015132_11 WHERE no = '21';


Question: What is the maximum speed of vessels with 'YANG' prefix that carried dangerous goods in the Pacific Ocean in 2017?

CREATE TABLE Vessels (ID INT, Name TEXT, Speed FLOAT, Dangerous_Goods BOOLEAN, Prefix TEXT, Year INT);CREATE VIEW Pacific_Ocean_Vessels AS SELECT * FROM Vessels WHERE Region = 'Pacific Ocean';

SELECT MAX(Speed) FROM Pacific_Ocean_Vessels WHERE Prefix = 'YANG' AND Dangerous_Goods = 1 AND Year = 2017;


Question: Calculate the average energy storage capacity for each energy type

CREATE TABLE energy_storage (energy_type VARCHAR(50), capacity FLOAT); INSERT INTO energy_storage (energy_type, capacity) VALUES ('Batteries', 45.6), ('Flywheels', 32.7), ('Batteries', 54.3);

SELECT energy_type, AVG(capacity) FROM energy_storage GROUP BY energy_type;


Question: Delete records in circular_economy_initiatives where initiative_type is 'Composting'

CREATE TABLE circular_economy_initiatives (id INT, initiative_type VARCHAR(20), start_year INT, end_year INT);

WITH data_to_delete AS (DELETE FROM circular_economy_initiatives WHERE initiative_type = 'Composting' RETURNING *) DELETE FROM circular_economy_initiatives WHERE id IN (SELECT id FROM data_to_delete);


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

SELECT stats_reset IS NOT NULL AS has_stats_reset
  FROM pg_stat_all_tables WHERE relid = 'test_last_scan'::regclass;

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

SELECT count(*) FROM (SELECT stats_reset IS NOT NULL AS has_stats_reset
  FROM pg_stat_all_tables WHERE relid = 'test_last_scan'::regclass) AS _sub;


Question: Generate PostgreSQL SQL for: Find the weight of the youngest dog.

CREATE TABLE pets (weight VARCHAR, pet_age VARCHAR)

SELECT weight FROM pets ORDER BY pet_age LIMIT 1;


Question: Generate PostgreSQL SQL for: What is the record at the neutral site for when the overall record is ui, 27-16?

CREATE TABLE table_16201038_4 (at_neutral_site VARCHAR, overall_record VARCHAR)

SELECT at_neutral_site FROM table_16201038_4 WHERE overall_record = 'UI, 27-16';


Question: List all heritage sites and their respective conservation status, along with the number of artifacts in each site.

CREATE TABLE heritage_sites (id INT, name VARCHAR(50), location VARCHAR(30), status VARCHAR(20), artifacts INT); INSERT INTO heritage_sites (id, name, location, status, artifacts) VALUES (1, 'Site1', 'NYC', 'Good', 50), (2, 'Site2', 'LA', 'Fair', 75), (3, 'Site3', 'Sydney', 'Poor', 60);

SELECT h.status, h.name, h.location, h.artifacts FROM heritage_sites h ORDER BY h.status;


Question: Generate PostgreSQL SQL for: Who had the fastest lap in round 1?

CREATE TABLE table_29162856_1 (fastest_lap VARCHAR, round VARCHAR)

SELECT fastest_lap FROM table_29162856_1 WHERE round = 1;


Question: Generate PostgreSQL SQL for: How many numbers correspond to the score in the final of  6–3, 6–4, 7–6 (13–11)?

CREATE TABLE table_26202940_6 (no VARCHAR, score_in_the_final VARCHAR)

SELECT COUNT(no) FROM table_26202940_6 WHERE score_in_the_final = '6–3, 6–4, 7–6 (13–11)';


Question: How many unique organizations provided support in Kenya?

CREATE TABLE organizations (id INT, name TEXT, location TEXT); INSERT INTO organizations (id, name, location) VALUES (1, 'WFP', 'Kenya'), (2, 'UNHCR', 'Tanzania'), (3, 'Save the Children', 'Kenya');

SELECT COUNT(DISTINCT name) FROM organizations WHERE location = 'Kenya';


Question: What is the average sustainability score for each textile material?

CREATE TABLE TextileSources (SourceID INT, Country VARCHAR(255), Material VARCHAR(255), SustainabilityScore INT); INSERT INTO TextileSources (SourceID, Country, Material, SustainabilityScore) VALUES (1, 'India', 'Cotton', 85), (2, 'Brazil', 'Rayon', 70);

SELECT Material, AVG(SustainabilityScore) AS AvgSustainabilityScore FROM TextileSources GROUP BY Material;


Question: What is the minimum fare for 'Ferry' mode of transport?

CREATE TABLE Fares(fare INT, journey_date DATE, mode_of_transport VARCHAR(20)); INSERT INTO Fares(fare, journey_date, mode_of_transport) VALUES (15, '2022-01-01', 'Ferry'), (20, '2022-01-02', 'Ferry'), (25, '2022-01-03', 'Ferry');

SELECT MIN(fare) FROM Fares WHERE mode_of_transport = 'Ferry';


Question: Generate PostgreSQL SQL for: What is the top rank with a time of 2:19.86?

CREATE TABLE table_name_25 (rank INTEGER, time VARCHAR)

SELECT MAX(rank) FROM table_name_25 WHERE time = '2:19.86';


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

CREATE POLICY p1 ON dob_t1 TO regress_rls_dob_role1 USING (true);

Explanation: DDL from PostgreSQL core regression test for Rowsecurity.


Question: Calculate the average length and diameter of pipeline segments with a start location in Valdez.

CREATE TABLE PipelineSegments (SegmentID INT, SegmentName VARCHAR(50), Length DECIMAL(10,2), Diameter DECIMAL(10,2), StartLocation VARCHAR(50), EndLocation VARCHAR(50)); INSERT INTO PipelineSegments (SegmentID, SegmentName, Length, Diameter, StartLocation, EndLocation) VALUES (1, 'Alaska Pipeline Segment 1', 12.34, 34.56, 'Prudhoe Bay', 'Valdez'); INSERT INTO PipelineSegments (SegmentID, SegmentName, Length, Diameter, StartLocation, EndLocation) VALUES (2, 'Alaska Pipeline Segment 2', 15.67, 45.67, 'Valdez', 'Anchorage');

SELECT StartLocation, AVG(Length) AS Avg_Length, AVG(Diameter) AS Avg_Diameter FROM PipelineSegments WHERE StartLocation = 'Valdez' GROUP BY StartLocation;


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

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

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


Question: Generate PostgreSQL SQL for: List all the scientists' names, their projects' names, and the hours worked by that scientist on each project, in alphabetical order of project name, and then scientist name.

CREATE TABLE AssignedTo (Scientist VARCHAR, Project VARCHAR); CREATE TABLE Projects (Name VARCHAR, Hours VARCHAR, Code VARCHAR); CREATE TABLE Scientists (Name VARCHAR, SSN VARCHAR)

SELECT T1.Name, T3.Name, T3.Hours FROM Scientists AS T1 JOIN AssignedTo AS T2 ON T1.SSN = T2.Scientist JOIN Projects AS T3 ON T2.Project = T3.Code ORDER BY T3.Name, T1.Name;


Question: Generate PostgreSQL SQL for: What city of license is associated with call sign w244bk?

CREATE TABLE table_name_44 (city_of_license VARCHAR, call_sign VARCHAR)

SELECT city_of_license FROM table_name_44 WHERE call_sign = 'w244bk';


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

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

SELECT count(*) FROM (select '100'::int2 / '0'::int8) AS _sub;


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

ALTER EXTENSION pgtap ADD FUNCTION _keys ( NAME, NAME, CHAR );

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


Question: Which attorneys have handled cases with a total billing amount greater than $5000 for clients from underrepresented communities?

CREATE TABLE Attorneys (id INT, name VARCHAR(50), underrepresented_client BOOLEAN); CREATE TABLE Cases (id INT, attorney_id INT, billing_amount DECIMAL(5,2), underrepresented_client BOOLEAN); INSERT INTO Attorneys (id, name, underrepresented_client) VALUES (1, 'Attorney1', TRUE), (2, 'Attorney2', FALSE), (3, 'Attorney3', TRUE); INSERT INTO Cases (id, attorney_id, billing_amount, underrepresented_client) VALUES (1, 1, 2000.00, TRUE), (2, 1, 1500.00, TRUE), (3, 2, 3000.00, FALSE), (4, 3, 800.00, TRUE);

SELECT Attorneys.name FROM Attorneys INNER JOIN (SELECT attorney_id, SUM(billing_amount) AS total_billing FROM Cases WHERE underrepresented_client = TRUE GROUP BY attorney_id) AS subquery ON Attorneys.id = subquery.attorney_id WHERE total_billing > 5000;


Question: PostgreSQL regression test 'date': Write the SELECT query (example 192).

SELECT EXTRACT(ISODOW        FROM DATE '2020-08-11');

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

SELECT count(*) FROM (SELECT EXTRACT(ISODOW        FROM DATE '2020-08-11')) AS _sub;


Question: Generate PostgreSQL SQL for: Which season has the Celtic club?

CREATE TABLE table_name_53 (season VARCHAR, club VARCHAR)

SELECT season FROM table_name_53 WHERE club = 'celtic';


Question: Generate PostgreSQL SQL for: How many IRST figures for the show that premiered on Canale 5 (2006)?

CREATE TABLE table_28803803_1 (irst VARCHAR, original_channel VARCHAR)

SELECT COUNT(irst) FROM table_28803803_1 WHERE original_channel = 'Canale 5 (2006)';


Question: What is the total size of protected habitats for each animal type?

CREATE TABLE Protected_Habitats (id INT, animal_type VARCHAR(50), size INT);

SELECT animal_type, SUM(size) FROM Protected_Habitats GROUP BY animal_type;


Question: Who are the customers with a transaction amount higher than the average transaction amount?

CREATE TABLE customer_transactions_2 (customer_id INT, customer_name VARCHAR(20), transaction_id INT, transaction_amount DECIMAL(10,2)); INSERT INTO customer_transactions_2 (customer_id, customer_name, transaction_id, transaction_amount) VALUES (1, 'Ravi Patel', 1, 1000.00), (2, 'Sophia Lee', 2, 500.00), (3, 'Hugo Chen', 3, 2000.00);

SELECT customer_name FROM customer_transactions_2 WHERE transaction_amount > (SELECT AVG(transaction_amount) FROM customer_transactions_2);


Question: Generate PostgreSQL SQL for: What's the method for a record of 4-2 and round smaller than 3?

CREATE TABLE table_name_78 (method VARCHAR, round VARCHAR, record VARCHAR)

SELECT method FROM table_name_78 WHERE round < 3 AND record = '4-2';


Question: Which excavation sites have more than 3 tool artifacts?

CREATE TABLE site_a (artifact_id INT, artifact_type VARCHAR(255)); INSERT INTO site_a (artifact_id, artifact_type) VALUES (1, 'Pottery'), (2, 'Tools'), (3, 'Tools'), (4, 'Tools'); CREATE TABLE site_b (artifact_id INT, artifact_type VARCHAR(255)); INSERT INTO site_b (artifact_id, artifact_type) VALUES (5, 'Pottery'), (6, 'Tools'), (7, 'Tools');

SELECT context FROM (SELECT 'site_a' AS context, COUNT(*) as count FROM site_a WHERE artifact_type = 'Tools' UNION ALL SELECT 'site_b' AS context, COUNT(*) as count FROM site_b WHERE artifact_type = 'Tools') AS subquery WHERE count > 3;


Question: How many space missions have been led by female astronauts?

CREATE TABLE SpaceMissions (MissionID INT, Name VARCHAR(50), LaunchDate DATE, Destination VARCHAR(50), Commander VARCHAR(50)); INSERT INTO SpaceMissions VALUES (1, 'Apollo 18', '1975-12-02', 'Moon', 'Jane Smith'), (2, 'Apollo 19', '1976-09-15', 'Moon', 'John Doe'), (3, 'Apollo 20', '1977-02-03', 'Moon', 'John Doe'), (4, 'Apollo 21', '1978-12-12', 'Moon', 'Jane Smith'), (5, 'Apollo 22', '1980-07-04', 'Mars', 'John Doe'), (6, 'Apollo 23', '1981-05-05', 'Mars', 'John Doe'), (7, 'Apollo 24', '1983-06-18', 'Mars', 'Jane Smith'), (8, 'Apollo 25', '1985-03-06', 'Mars', 'John Doe'), (9, 'Apollo 26', '1987-11-20', 'Mars', 'Jane Smith'), (10, 'Apollo 27', '1990-09-25', 'Ceres', 'John Doe');

SELECT COUNT(*) FROM SpaceMissions WHERE Commander IN ('Jane Smith', 'Emily Johnson', 'Sophia Garcia');


Question: What is the percentage of security incidents caused by each attack vector for a specific country in the last year?

CREATE TABLE security_incidents (id INT, timestamp TIMESTAMP, country VARCHAR(255), attack_vector VARCHAR(255), incident_type VARCHAR(255)); INSERT INTO security_incidents (id, timestamp, country, attack_vector, incident_type) VALUES (1, '2021-01-01 12:00:00', 'Germany', 'Network', 'Ransomware'), (2, '2021-02-05 10:30:00', 'France', 'Email', 'Phishing');

SELECT attack_vector, 100.0 * COUNT(*) / (SELECT COUNT(*) FROM security_incidents WHERE timestamp >= NOW() - INTERVAL 1 YEAR AND country = 'Germany') as percentage FROM security_incidents WHERE timestamp >= NOW() - INTERVAL 1 YEAR AND country = 'Germany' GROUP BY attack_vector;


Question: Display the causes and total donation amounts for donors with the last name 'Smith', joining the donors and donations tables.

CREATE TABLE donors (id INT, first_name VARCHAR(255), last_name VARCHAR(255)); INSERT INTO donors (id, first_name, last_name) VALUES (1, 'John', 'Doe'), (2, 'Jane', 'Smith'); CREATE TABLE donations (id INT, donor_id INT, amount DECIMAL(10, 2)); INSERT INTO donations (id, donor_id, amount) VALUES (1, 1, 500), (2, 1, 250), (3, 2, 750);

SELECT c.name, SUM(donations.amount) as total_donation FROM donors d JOIN donations ON d.id = donations.donor_id JOIN causes c ON donations.cause_id = c.id WHERE d.last_name = 'Smith' GROUP BY c.name;


Question: Populate the virtual_reality table

CREATE TABLE virtual_reality (vr_id INT PRIMARY KEY, name VARCHAR(50), release_date DATE, manufacturer VARCHAR(50));

INSERT INTO virtual_reality (vr_id, name, release_date, manufacturer) VALUES (1, 'Oculus Quest 2', '2020-10-13', 'Facebook Technologies'), (2, 'HTC Vive Pro 2', '2021-06-01', 'HTC Corporation'), (3, 'Valve Index', '2019-06-28', 'Valve Corporation');


Question: Generate PostgreSQL SQL for: What is the GP winner for the Race winners valentin giraud / nicolas musset, and a place genk?

CREATE TABLE table_name_2 (gp_winner VARCHAR, race_winners VARCHAR, place VARCHAR)

SELECT gp_winner FROM table_name_2 WHERE race_winners = 'valentin giraud / nicolas musset' AND place = 'genk';


Question: What is the total number of mobile and broadband subscribers for each network type?

CREATE TABLE subscriber_data (subscriber_type VARCHAR(20), network_type VARCHAR(20), subscriber_count INT); INSERT INTO subscriber_data (subscriber_type, network_type, subscriber_count) VALUES ('Mobile', '4G', 5000), ('Broadband', 'Fiber', 3000), ('Mobile', '5G', 7000), ('Broadband', 'Cable', 4000);

SELECT network_type, SUM(subscriber_count) FROM subscriber_data GROUP BY network_type;


Question: pgTAP test for Privs (assertion 83).

-- Try another user.
REVOKE CREATE ON TABLESPACE pg_default FROM public;

Explanation: SQL assertion from pgTAP test suite for Privs.


Question: Which threat actors have targeted systems with a CVE score greater than 7 in the last year?

CREATE TABLE threat_actors (threat_actor_id INT, threat_actor_name VARCHAR(255));CREATE TABLE targeted_systems (system_id INT, system_name VARCHAR(255), sector VARCHAR(255), threat_actor_id INT);CREATE TABLE cve_scores (system_id INT, score INT, scan_date DATE);CREATE TABLE scan_dates (scan_date DATE, system_id INT);

SELECT ta.threat_actor_name FROM threat_actors ta INNER JOIN targeted_systems ts ON ta.threat_actor_id = ts.threat_actor_id INNER JOIN cve_scores c ON ts.system_id = c.system_id INNER JOIN scan_dates sd ON ts.system_id = sd.system_id WHERE c.score > 7 AND sd.scan_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR);


Question: Generate PostgreSQL SQL for: What is the team name for Chungju?

CREATE TABLE table_name_11 (team VARCHAR, city VARCHAR)

SELECT team FROM table_name_11 WHERE city = 'chungju';


Question: What is the percentage of the global terbium production in 2020 that comes from African countries?

CREATE TABLE mines (id INT, name TEXT, location TEXT, production_quantity INT, year INT, element TEXT); INSERT INTO mines (id, name, location, production_quantity, year, element) VALUES (1, 'Kentor Gold', 'South Africa', 300, 2020, 'terbium'), (2, 'Thor Mining', 'Botswana', 200, 2020, 'terbium'); CREATE TABLE global_production (element TEXT, year INT, production_quantity INT); INSERT INTO global_production (element, year, production_quantity) VALUES ('terbium', 2020, 5000);

SELECT (SUM(CASE WHEN location = 'Africa' THEN production_quantity ELSE 0 END) / (SELECT SUM(production_quantity) FROM global_production WHERE element = 'terbium' AND year = 2020)) * 100 FROM mines WHERE year = 2020 AND element = 'terbium';


Question: List all policyholders with home insurance policies in Texas who are over 60 years old

CREATE TABLE policyholders (policy_id INT, policyholder_age INT, policy_type VARCHAR(20)); CREATE TABLE policies (policy_id INT, policy_state VARCHAR(2));

SELECT DISTINCT policyholder_age, policy_type FROM policyholders JOIN policies ON policyholders.policy_id = policies.policy_id WHERE policies.policy_state = 'TX' AND policyholder_age > 60;


Question: What's the average ESG score for nonprofits in the 'Healthcare' field?

CREATE TABLE if not exists nonprofits (id INT PRIMARY KEY, name TEXT, field TEXT, location TEXT, annual_budget DECIMAL(10,2)); INSERT INTO nonprofits (id, name, field, location, annual_budget) VALUES (1, 'Health Hope', 'Healthcare', 'Chicago', 125000.00); CREATE TABLE if not exists esg_factors (id INT PRIMARY KEY, nonprofit_id INT, environmental_score DECIMAL(3,2), social_score DECIMAL(3,2), governance_score DECIMAL(3,2)); INSERT INTO esg_factors (id, nonprofit_id, environmental_score, social_score, governance_score) VALUES (1, 1, 4.2, 4.5, 4.8);

SELECT AVG(environmental_score) AS avg_environmental_score, AVG(social_score) AS avg_social_score, AVG(governance_score) AS avg_governance_score FROM esg_factors WHERE nonprofit_id IN (SELECT id FROM nonprofits WHERE field = 'Healthcare');


Question: Generate PostgreSQL SQL for: Which Result has a Venue of A, and an Opponent of manchester united?

CREATE TABLE table_name_96 (result VARCHAR, venue VARCHAR, opponent VARCHAR)

SELECT result FROM table_name_96 WHERE venue = 'a' AND opponent = 'manchester united';


Question: What is the average construction cost per project type in the transportation domain?

CREATE TABLE transportation_projects (id INT, project_type VARCHAR(255), construction_cost FLOAT); INSERT INTO transportation_projects (id, project_type, construction_cost) VALUES (1, 'Bridge', 5000000), (2, 'Road', 2000000), (3, 'Highway', 15000000);

SELECT project_type, AVG(construction_cost) FROM transportation_projects GROUP BY project_type;


Question: What is the maximum fare for each route type in the 'route' table?

CREATE TABLE route (id INT, name TEXT, type TEXT, fare FLOAT); INSERT INTO route (id, name, type, fare) VALUES (1, 'Central Line', 'Underground', 3.5), (2, 'Circle Line', 'Underground', 4.2), (3, 'Jubilee Line', 'Underground', 5.0), (4, 'Bus Route 123', 'Bus', 2.5), (5, 'Bus Route 456', 'Bus', 3.0);

SELECT type, MAX(fare) as max_fare FROM route GROUP BY type;


Question: Generate PostgreSQL SQL for: What is the customer first, last name and id with least number of accounts.

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

SELECT T2.customer_first_name, T2.customer_last_name, T1.customer_id FROM Accounts AS T1 JOIN Customers AS T2 ON T1.customer_id = T2.customer_id GROUP BY T1.customer_id ORDER BY COUNT(*) LIMIT 1;


Question: Determine the difference in yield between the highest and lowest yield crops in the Atlantic region in 2022.

CREATE TABLE crops (id INT, name VARCHAR(50), yield INT, acrate DECIMAL(5,2), region VARCHAR(50), year INT); INSERT INTO crops (id, name, yield, acrate, region, year) VALUES (1, 'Corn', 200, 2.3, 'Atlantic', 2022), (2, 'Soybeans', 120, 2.2, 'Atlantic', 2022), (3, 'Wheat', 180, 2.5, 'Atlantic', 2022);

SELECT MAX(yield) - MIN(yield) FROM crops WHERE region = 'Atlantic' AND year = 2022;


Question: Generate PostgreSQL SQL for: What position does Bobby Micho, who was picked later than 186 others, play on the Broncos team?

CREATE TABLE table_name_30 (position VARCHAR, pick__number VARCHAR, player VARCHAR)

SELECT position FROM table_name_30 WHERE pick__number > 186 AND player = 'bobby micho';


Question: Insert a new 'education' record into the 'education_programs' table

CREATE TABLE education_programs (id INT, name VARCHAR(50), description TEXT, target_audience VARCHAR(50), duration INT);

INSERT INTO education_programs (id, name, description, target_audience, duration) VALUES (1, 'Wildlife Warriors', 'A program to educate children about wildlife conservation.', 'Children (Ages 8-12)', 12);


Question: Generate PostgreSQL SQL for: When was Laurent-Marie-Joseph Imbert / St. Imbert, who was beatified after 1909 and canonised after 1984, martyred?

CREATE TABLE table_name_65 (martyred INTEGER, canonised VARCHAR, beatified VARCHAR, name VARCHAR)

SELECT MAX(martyred) FROM table_name_65 WHERE beatified > 1909 AND name = 'laurent-marie-joseph imbert / st. imbert' AND canonised > 1984;


Question: What is the total amount of research grants awarded to each department in the past 3 years, and what is the maximum grant amount awarded to a single student during this time period?

CREATE TABLE research_grants (grant_id INT, student_id INT, dept_name VARCHAR(50), grant_amount INT, grant_date DATE);

SELECT rg.dept_name, SUM(rg.grant_amount) as total_grant_amount, MAX(rg.grant_amount) as max_grant_amount FROM research_grants rg WHERE rg.grant_date >= DATE_SUB(CURRENT_DATE(), INTERVAL 3 YEAR) GROUP BY rg.dept_name;


Question: Generate PostgreSQL SQL for: How many entries are shown for viewers when the airdate was 26 november 2009?

CREATE TABLE table_24399615_3 (viewers VARCHAR, airdate VARCHAR)

SELECT COUNT(viewers) FROM table_24399615_3 WHERE airdate = '26 November 2009';


Question: Generate PostgreSQL SQL for: What's the court ranking of 5th son of tadayori and has revenues of 10,000 koku?

CREATE TABLE table_name_32 (court_rank VARCHAR, revenues VARCHAR, lineage VARCHAR)

SELECT court_rank FROM table_name_32 WHERE revenues = '10,000 koku' AND lineage = '5th son of tadayori';


Question: Generate PostgreSQL SQL for: Which Series has a Home of 2–0, and an Opponent of panathinaikos?

CREATE TABLE table_name_96 (series VARCHAR, home VARCHAR, opponent VARCHAR)

SELECT series FROM table_name_96 WHERE home = '2–0' AND opponent = 'panathinaikos';


Question: What is the total number of accommodations provided for students in the 'Science' department?

CREATE TABLE Students (student_id INT, department VARCHAR(255)); CREATE TABLE Accommodations (accommodation_id INT, student_id INT, accommodation_type VARCHAR(255));

SELECT COUNT(*) as total_accommodations FROM Accommodations WHERE student_id IN ( SELECT student_id FROM Students WHERE department = 'Science' );


Question: What is the minimum data usage for postpaid mobile customers in the city of Los Angeles?

CREATE TABLE mobile_customers (customer_id INT, data_usage FLOAT, city VARCHAR(20), plan_type VARCHAR(10)); INSERT INTO mobile_customers (customer_id, data_usage, city, plan_type) VALUES (1, 3.5, 'Los Angeles', 'postpaid'), (2, 4.2, 'New York', 'postpaid'), (3, 3.8, 'Los Angeles', 'prepaid');

SELECT MIN(data_usage) FROM mobile_customers WHERE city = 'Los Angeles' AND plan_type = 'postpaid';


Question: Calculate the total revenue of sativa-based products sold in Oregon dispensaries in Q1 2022.

CREATE TABLE products (type VARCHAR(10), category VARCHAR(10), price DECIMAL(5,2), quantity INT); INSERT INTO products (type, category, price, quantity) VALUES ('oil', 'sativa', 70, 50), ('flower', 'sativa', 100, 75), ('edible', 'sativa', 60, 40); CREATE TABLE dispensaries (state VARCHAR(20), sales INT); INSERT INTO dispensaries (state, sales) VALUES ('Oregon', 1800), ('Oregon', 2000); CREATE TABLE time_periods (quarter INT); INSERT INTO time_periods (quarter) VALUES (1), (2);

SELECT SUM(products.price * products.quantity) FROM products JOIN dispensaries ON TRUE WHERE products.category = 'sativa' AND dispensaries.state = 'Oregon' AND time_periods.quarter = 1;


Question: Generate PostgreSQL SQL for: What was the margin of victory over Steve Rintoul?

CREATE TABLE table_name_61 (margin_of_victory VARCHAR, runner_s__up VARCHAR)

SELECT margin_of_victory FROM table_name_61 WHERE runner_s__up = 'steve rintoul';


Question: What is the total number of military bases in the country, grouped by their base type?

CREATE TABLE military_bases (id INT, name VARCHAR(255), base_type VARCHAR(255), country VARCHAR(255));INSERT INTO military_bases (id, name, base_type, country) VALUES (1, 'Fort Bragg', 'Army', 'USA'), (2, 'Camp Pendleton', 'Marine', 'USA'), (3, 'CFB Petawawa', 'Army', 'Canada');

SELECT base_type, COUNT(*) as total_bases FROM military_bases GROUP BY base_type;


Question: List all legal technology grants awarded by a specific organization

CREATE TABLE grants (id INT PRIMARY KEY, organization VARCHAR(255), category VARCHAR(255), amount DECIMAL(10,2), date_awarded DATE);

SELECT * FROM grants WHERE organization = 'Legal Code Foundation';


Question: Generate PostgreSQL SQL for: What number of rank has more than 2 medals in total with less than 4 bronze?

CREATE TABLE table_name_26 (rank VARCHAR, total VARCHAR, bronze VARCHAR)

SELECT COUNT(rank) FROM table_name_26 WHERE total > 2 AND bronze < 4;


Question: List dispensaries that have sold more than 100 units of a specific strain, 'Blue Dream', in the last month.

CREATE TABLE Dispensaries (DispensaryID INT, DispensaryName VARCHAR(50)); CREATE TABLE Strains (StrainID INT, StrainName VARCHAR(50)); CREATE TABLE Sales (SaleID INT, DispensaryID INT, StrainID INT, QuantitySold INT, SaleDate DATE);

SELECT D.DispensaryID, D.DispensaryName FROM Dispensaries D JOIN Sales S ON D.DispensaryID = S.DispensaryID JOIN Strains ST ON S.StrainID = ST.StrainID WHERE StrainName = 'Blue Dream' AND S.SaleDate >= DATEADD(month, -1, GETDATE()) GROUP BY D.DispensaryID, D.DispensaryName HAVING SUM(QuantitySold) > 100;


Question: How many wind energy projects were completed in Canada in 2021?

CREATE TABLE renewable_energy (id INT, project TEXT, location TEXT, year INT, type TEXT, status TEXT); INSERT INTO renewable_energy (id, project, location, year, type, status) VALUES (1, 'Alberta Wind Energy', 'Canada', 2021, 'wind', 'completed'), (2, 'British Columbia Solar Energy', 'Canada', 2021, 'solar', 'in progress');

SELECT COUNT(*) FROM renewable_energy WHERE location = 'Canada' AND year = 2021 AND type = 'wind' AND status = 'completed';


Question: What is the average sale price of military equipment by type for defense contractor XYZ?

CREATE TABLE EquipmentTypes (equipment_type VARCHAR(50), manufacturer VARCHAR(50), sale_price DECIMAL(10, 2)); INSERT INTO EquipmentTypes (equipment_type, manufacturer, sale_price) VALUES ('Tank', 'XYZ', 5000000.00); INSERT INTO EquipmentTypes (equipment_type, manufacturer, sale_price) VALUES ('Fighter Jet', 'XYZ', 80000000.00);

SELECT equipment_type, AVG(sale_price) as avg_sale_price FROM EquipmentTypes WHERE manufacturer = 'XYZ' GROUP BY equipment_type;


Question: How many public libraries were there in 'CityA' as of 2020?

CREATE TABLE Libraries(city VARCHAR(20), year INT, num_libraries INT); INSERT INTO Libraries VALUES ('CityA', 2018, 5), ('CityA', 2019, 6), ('CityA', 2020, 7), ('CityC', 2018, 4), ('CityC', 2019, 5), ('CityC', 2020, 6);

SELECT num_libraries FROM Libraries WHERE city = 'CityA' AND year = 2020;


Question: Generate PostgreSQL SQL for: Who was the runner(s)-up for the Feb 18, 1996 tournament?

CREATE TABLE table_name_39 (runner_s__up VARCHAR, date VARCHAR)

SELECT runner_s__up FROM table_name_39 WHERE date = 'feb 18, 1996';


Question: Generate PostgreSQL SQL for: What is the incident type description for the incident type with code "VIOLENCE"?

CREATE TABLE Ref_Incident_Type (incident_type_description VARCHAR, incident_type_code VARCHAR)

SELECT incident_type_description FROM Ref_Incident_Type WHERE incident_type_code = 'VIOLENCE';


Question: Generate PostgreSQL SQL for: How many phone hardware models are produced by the company named "Nokia Corporation"?

CREATE TABLE phone (Company_name VARCHAR)

SELECT COUNT(*) FROM phone WHERE Company_name = 'Nokia Corporation';


Question: What is the most common diagnosis in rural areas of Wyoming?

CREATE TABLE diagnoses (diagnosis_id INT, diagnosis VARCHAR(50), patient_id INT, visit_date DATE, location VARCHAR(20));

SELECT diagnosis, COUNT(*) FROM diagnoses WHERE location = 'Rural Wyoming' GROUP BY diagnosis ORDER BY COUNT(*) DESC LIMIT 1;


Question: Generate PostgreSQL SQL for: Where was the 1966 final played?

CREATE TABLE table_name_12 (finals_venue__surface_ VARCHAR, year VARCHAR)

SELECT finals_venue__surface_ FROM table_name_12 WHERE year = 1966;


Question: Generate PostgreSQL SQL for: What away team has a Tie no of 5?

CREATE TABLE table_name_97 (away_team VARCHAR, tie_no VARCHAR)

SELECT away_team FROM table_name_97 WHERE tie_no = '5';


Question: Generate PostgreSQL SQL for: What series has dan povenmire as the director, with museum scream as the title?

CREATE TABLE table_name_46 (series VARCHAR, director VARCHAR, title VARCHAR)

SELECT series FROM table_name_46 WHERE director = 'dan povenmire' AND title = 'museum scream';


Question: Generate PostgreSQL SQL for: Who as the home team for game on 5 october 2011?

CREATE TABLE table_24949975_1 (home_team VARCHAR, date VARCHAR)

SELECT home_team FROM table_24949975_1 WHERE date = '5 October 2011';


Question: Generate PostgreSQL SQL for: What is the first episode with a netflix episode code of s02e20?

CREATE TABLE table_15187735_4 (episode INTEGER, netflix VARCHAR)

SELECT MIN(episode) FROM table_15187735_4 WHERE netflix = 'S02E20';


Question: What are the names and countries of all AI researchers who are over the age of 40 and have published at least one research paper?

CREATE TABLE Researchers (id INT, name VARCHAR(255), age INT, country VARCHAR(255), paper VARCHAR(255));

SELECT name, country FROM Researchers WHERE age > 40 AND paper IS NOT NULL;


Question: What is the total number of permits issued for residential and commercial buildings in the City of Angels?

CREATE TABLE building_permit (permit_id INT, building_type VARCHAR(10), location VARCHAR(20));INSERT INTO building_permit (permit_id, building_type, location) VALUES (1, 'Residential', 'City of Angels');INSERT INTO building_permit (permit_id, building_type, location) VALUES (2, 'Commercial', 'City of Angels');

SELECT SUM(permit_id) FROM building_permit WHERE location = 'City of Angels';


Question: List the types of fish and their quantities that are farmed in each country using sustainable methods, excluding fish from Canada.

CREATE TABLE FarmI (species VARCHAR(20), country VARCHAR(20), quantity INT, farming_method VARCHAR(20)); INSERT INTO FarmI (species, country, quantity, farming_method) VALUES ('Salmon', 'Canada', 7000, 'Sustainable'); INSERT INTO FarmI (species, country, quantity, farming_method) VALUES ('Trout', 'Canada', 4000, 'Sustainable'); INSERT INTO FarmI (species, country, quantity, farming_method) VALUES ('Salmon', 'Norway', 6000, 'Sustainable'); INSERT INTO FarmI (species, country, quantity, farming_method) VALUES ('Trout', 'Norway', 3000, 'Sustainable'); INSERT INTO FarmI (species, country, quantity, farming_method) VALUES ('Herring', 'Scotland', 2500, 'Sustainable');

SELECT country, species, SUM(quantity) FROM FarmI WHERE farming_method = 'Sustainable' AND country != 'Canada' GROUP BY country, species;


Question: Generate PostgreSQL SQL for: What is the home team of the game on February 4?

CREATE TABLE table_name_74 (home VARCHAR, date VARCHAR)

SELECT home FROM table_name_74 WHERE date = 'february 4';


Question: Generate PostgreSQL SQL for: What is the event in a year before 1989?

CREATE TABLE table_name_37 (event VARCHAR, year INTEGER)

SELECT event FROM table_name_37 WHERE year < 1989;


Question: What is the maximum budget for biotech startups founded in 2020?

CREATE TABLE startup_funding (name VARCHAR(255), year INT, budget FLOAT); INSERT INTO startup_funding (name, year, budget) VALUES ('StartupA', 2020, 5000000), ('StartupB', 2020, 7000000), ('StartupC', 2019, 6000000);

SELECT MAX(budget) FROM startup_funding WHERE year = 2020;


Question: Generate PostgreSQL SQL for: What is the Region with a Catalog that is vlmx 1087-3?

CREATE TABLE table_name_27 (region VARCHAR, catalog VARCHAR)

SELECT region FROM table_name_27 WHERE catalog = 'vlmx 1087-3';


Question: What is the number of members who have been members for more than 1 year?

CREATE TABLE gym_memberships (id INT, member_name VARCHAR(50), start_date DATE, end_date DATE, membership_type VARCHAR(50), price DECIMAL(5,2));

SELECT COUNT(DISTINCT member_name) AS long_term_members FROM gym_memberships WHERE DATEDIFF(CURDATE(), start_date) > 365;


Question: Who are the top three employees with the highest salaries in the Engineering department?

CREATE TABLE Employees (EmployeeID INT, FirstName VARCHAR(50), LastName VARCHAR(50), Department VARCHAR(50), Salary DECIMAL(10,2)); INSERT INTO Employees (EmployeeID, FirstName, LastName, Department, Salary) VALUES (1, 'John', 'Doe', 'Engineering', 75000.00), (2, 'Jane', 'Doe', 'Engineering', 80000.00), (3, 'Mike', 'Smith', 'Marketing', 60000.00), (4, 'Samantha', 'Johnson', 'Engineering', 85000.00), (5, 'David', 'Brown', 'Engineering', 82000.00);

SELECT EmployeeID, FirstName, LastName, Department, Salary, RANK() OVER (PARTITION BY Department ORDER BY Salary DESC) AS Rank FROM Employees WHERE Department = 'Engineering';


Question: Delete the supplier from 'USA' with id 4

CREATE TABLE suppliers (id INT PRIMARY KEY, name VARCHAR(100), address VARCHAR(255), city VARCHAR(100), country VARCHAR(100));

DELETE FROM suppliers WHERE id = 4 AND country = 'USA';


Question: Generate PostgreSQL SQL for: What player placed t10?

CREATE TABLE table_name_17 (player VARCHAR, place VARCHAR)

SELECT player FROM table_name_17 WHERE place = 't10';


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

SELECT 'init' FROM pg_create_logical_replication_slot('regression_slot_t', 'test_decoding', true);

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


Question: Show a SQL definition from the timescaledb project (util_time, item 11).

CREATE OR REPLACE FUNCTION _timescaledb_functions.cagg_watermark(hypertable_id INTEGER)
RETURNS INT8 AS '@MODULE_PATHNAME@', 'ts_continuous_agg_watermark' LANGUAGE C STABLE STRICT PARALLEL RESTRICTED;


Question: Find the number of juvenile cases that were resolved through community supervision, broken down by race/ethnicity, for the past year.

CREATE TABLE JuvenileCases (Id INT, Race VARCHAR(50), Program VARCHAR(50), ResolutionDate DATE); INSERT INTO JuvenileCases (Id, Race, Program, ResolutionDate) VALUES (1, 'Hispanic', 'Community Supervision', '2021-03-21'), (2, 'Black', 'Probation', '2020-12-12'), (3, 'Asian', 'Community Supervision', '2021-06-15');

SELECT Race, COUNT(*) as NumCases FROM JuvenileCases WHERE Program = 'Community Supervision' AND YEAR(ResolutionDate) = 2021 GROUP BY Race;


Question: Generate PostgreSQL SQL for: What is the value in 2008-09 for the Autumn Gold event?

CREATE TABLE table_name_9 (event VARCHAR)

SELECT 2008 AS _09 FROM table_name_9 WHERE event = 'autumn gold';


Question: Delete all wind energy projects in Germany before 2010.

CREATE TABLE energy_projects (name TEXT, country TEXT, technology TEXT, capacity_mw INTEGER, year INTEGER); INSERT INTO energy_projects (name, country, technology, capacity_mw, year) VALUES ('Project A', 'Germany', 'Wind', 10, 2005), ('Project B', 'Germany', 'Wind', 15, 2012);

DELETE FROM energy_projects WHERE country = 'Germany' AND technology = 'Wind' AND year < 2010;


Question: How many crimes were committed in the last 30 days in each district in Los Angeles?

CREATE TABLE la_districts (id INT, district_name VARCHAR(255));CREATE TABLE crimes (id INT, district_id INT, crime_date DATE);INSERT INTO la_districts (id, district_name) VALUES (1, 'Hollywood'), (2, 'Downtown'), (3, 'Venice');INSERT INTO crimes (id, district_id, crime_date) VALUES (1, 1, '2022-03-01'), (2, 1, '2022-03-15'), (3, 2, '2022-03-05'), (4, 2, '2022-03-20'), (5, 3, '2022-03-10'), (6, 3, '2022-03-25');

SELECT d.district_name, COUNT(c.id) crimes_in_last_30_days FROM la_districts d JOIN crimes c ON d.id = c.district_id WHERE c.crime_date >= CURDATE() - INTERVAL 30 DAY GROUP BY d.id;


Question: Generate PostgreSQL SQL for: Which Club has a Founded smaller than 1882, and a League of fa premier league?

CREATE TABLE table_name_76 (club VARCHAR, founded VARCHAR, league VARCHAR)

SELECT club FROM table_name_76 WHERE founded < 1882 AND league = 'fa premier league';


Question: What is the total number of volunteers and total hours donated by them in '2018'?

CREATE TABLE Volunteers (VolunteerID int, VolunteerName varchar(50), HoursDonated int, VolunteerYear int); INSERT INTO Volunteers (VolunteerID, VolunteerName, HoursDonated, VolunteerYear) VALUES (1, 'Samantha Green', 30, 2018), (2, 'Taylor White', 20, 2018), (3, 'Uma Black', 15, 2018), (4, 'Victor Red', 25, 2018);

SELECT COUNT(VolunteerName) as TotalVolunteers, SUM(HoursDonated) as TotalHours FROM Volunteers WHERE VolunteerYear = 2018;


Question: Create a table named 'space_missions' with columns mission_name, start_date, end_date, mission_type

CREATE TABLE space_missions (mission_name VARCHAR(100) PRIMARY KEY, start_date DATE, end_date DATE, mission_type VARCHAR(50));


Question: Display the number of sustainable tourism certifications obtained by each country in Asia.

CREATE TABLE countries (country_id INT, name TEXT, region TEXT, num_certifications INT);

SELECT name, num_certifications FROM countries WHERE region = 'Asia';


Question: Who are the diplomats with the highest salaries?

CREATE TABLE diplomacy_staff (staff_id INT, name VARCHAR(255), position VARCHAR(255), salary INT); INSERT INTO diplomacy_staff (staff_id, name, position, salary) VALUES (1, 'John Doe', 'Ambassador', 75000), (2, 'Jane Smith', 'Consul', 50000), (3, 'Michael Johnson', 'Diplomatic Attaché', 60000), (4, 'Sarah Brown', 'Ambassador', 90000), (5, 'David Williams', 'Consul', 80000);

SELECT name, position, salary FROM diplomacy_staff ORDER BY salary DESC;


Question: What is the average safety rating of AI models developed for education applications, and how many of these models have been developed by organizations based in Asia?

CREATE TABLE AIModels (id INT, model_name VARCHAR(50), organization VARCHAR(50), application_type VARCHAR(50), safety_rating INT), AIOrganizations (id INT, organization VARCHAR(50), region VARCHAR(50)); INSERT INTO AIModels (id, model_name, organization, application_type, safety_rating) VALUES (1, 'AI4Education', 'Microsoft', 'Education', 85), (2, 'AI4Learning', 'Google', 'Education', 90), (3, 'AI4Teaching', 'IBM', 'Education', 88), (4, 'AI4Students', 'Alibaba', 'Education', 92), (5, 'AI4Classroom', 'Tencent', 'Education', 80); INSERT INTO AIOrganizations (id, organization, region) VALUES (1, 'Microsoft', 'North America'), (2, 'Google', 'North America'), (3, 'IBM', 'North America'), (4, 'Alibaba', 'Asia'), (5, 'Tencent', 'Asia');

SELECT AVG(safety_rating) as avg_safety_rating FROM AIModels WHERE application_type = 'Education'; SELECT COUNT(*) as asian_org_count FROM AIOrganizations WHERE region = 'Asia' AND organization IN (SELECT organization FROM AIModels WHERE application_type = 'Education');


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

SELECT '[{"attributes" : [2,3], "dependency" : [1,null], "degree": 1.000}]'::pg_dependencies;

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

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


Question: How many sustainable suppliers are there in total for each country?

CREATE TABLE suppliers (id INT, name VARCHAR(255), country VARCHAR(255), sustainable BOOLEAN); CREATE VIEW sustainable_suppliers AS SELECT name FROM suppliers WHERE sustainable = TRUE;

SELECT country, COUNT(*) as total_sustainable_suppliers FROM suppliers WHERE sustainable = TRUE GROUP BY country;


Question: Write the DML statement from PostgreSQL regression test 'box' (example 11).

INSERT INTO BOX_TBL (f1) VALUES ('asdfasdf(ad');

Explanation: DML from PostgreSQL core regression test for Box.


Question: What is the total amount of donations received by each community center in New York?

CREATE TABLE community_centers (id INT, name TEXT, city TEXT); INSERT INTO community_centers (id, name, city) VALUES (1, 'Manhattan Community Center', 'New York'), (2, 'Bronx Community Center', 'New York'); CREATE TABLE donations (id INT, center_id INT, amount DECIMAL); INSERT INTO donations (id, center_id, amount) VALUES (1, 1, 5000.00), (2, 1, 7000.00), (3, 2, 3000.00);

SELECT c.name, SUM(d.amount) as total_donations FROM community_centers c INNER JOIN donations d ON c.id = d.center_id WHERE c.city = 'New York' GROUP BY c.name;


Question: Generate PostgreSQL SQL for: Show first name and id for all customers with at least 2 accounts.

CREATE TABLE Customers (customer_first_name VARCHAR, customer_id VARCHAR); CREATE TABLE Accounts (customer_id VARCHAR)

SELECT T2.customer_first_name, T1.customer_id FROM Accounts AS T1 JOIN Customers AS T2 ON T1.customer_id = T2.customer_id GROUP BY T1.customer_id HAVING COUNT(*) >= 2;


Question: Insert a new record into the dispensaries table for a new recreational dispensary with a name of 'Dispensary E' and a total revenue of 80000.00 in Q1 2022.

CREATE TABLE dispensaries (id INT, name VARCHAR(255), type VARCHAR(255), total_revenue DECIMAL(10,2));

INSERT INTO dispensaries (id, name, type, total_revenue) VALUES (5, 'Dispensary E', 'recreational', 80000.00);


Question: What is the average water temperature in the Indian Ocean Monitoring Station for each month?

CREATE TABLE indian_ocean_monitoring_station (date DATE, temperature FLOAT);

SELECT EXTRACT(MONTH FROM date) AS month, AVG(temperature) AS avg_temperature FROM indian_ocean_monitoring_station GROUP BY month;


Question: What is the minimum water consumption for each day in the month of September for the water treatment plant with ID 4 in the state of Florida in 2020?

CREATE TABLE water_treatment_plant (plant_id INT, state VARCHAR(50), year INT, month INT, day INT, water_consumption FLOAT); INSERT INTO water_treatment_plant (plant_id, state, year, month, day, water_consumption) VALUES (4, 'Florida', 2020, 9, 1, 12345.6), (4, 'Florida', 2020, 9, 2, 23456.7), (4, 'Florida', 2020, 9, 3, 34567.8);

SELECT day, MIN(water_consumption) as min_water_consumption FROM water_treatment_plant WHERE plant_id = 4 AND state = 'Florida' AND year = 2020 AND month = 9 GROUP BY day;


Question: List the number of veterans hired per state in the 'VeteranEmployment' table

CREATE TABLE VeteranEmployment (id INT, state VARCHAR(255), veteran_hired INT);

SELECT state, COUNT(*) as veterans_hired_count FROM VeteranEmployment GROUP BY state;


Question: Find the total number of electric and hybrid buses in the 'public_transportation' table.

CREATE TABLE public_transportation (id INT, type VARCHAR(20), make VARCHAR(20), model VARCHAR(20), year INT, fuel_type VARCHAR(20));

SELECT SUM(fuel_type = 'electric' OR fuel_type = 'hybrid') FROM public_transportation;


Question: What is the minimum number of containers handled in a single day by cranes in the Port of Rotterdam in April 2021?

CREATE TABLE Port_Rotterdam_Crane_Stats (crane_name TEXT, handling_date DATE, containers_handled INTEGER); INSERT INTO Port_Rotterdam_Crane_Stats (crane_name, handling_date, containers_handled) VALUES ('CraneI', '2021-04-01', 70), ('CraneJ', '2021-04-02', 60), ('CraneK', '2021-04-03', 50), ('CraneL', '2021-04-04', 80);

SELECT MIN(containers_handled) FROM Port_Rotterdam_Crane_Stats WHERE handling_date >= '2021-04-01' AND handling_date <= '2021-04-30';


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

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


Question: How many military equipment maintenance requests were submitted in Q1 2022 for the Navy?

CREATE TABLE Maintenance_Requests (Id INT, Request_Date DATE, Equipment_Type VARCHAR(50), Agency VARCHAR(50)); INSERT INTO Maintenance_Requests (Id, Request_Date, Equipment_Type, Agency) VALUES (1, '2022-01-01', 'Ship', 'Navy'); INSERT INTO Maintenance_Requests (Id, Request_Date, Equipment_Type, Agency) VALUES (2, '2022-04-01', 'Submarine', 'Navy');

SELECT COUNT(*) FROM Maintenance_Requests WHERE Request_Date BETWEEN '2022-01-01' AND '2022-03-31' AND Agency = 'Navy';


Question: How many students with visual impairments have received accommodations in the last year, broken down by country?

CREATE TABLE student_accommodations (student_id INT, disability_type VARCHAR(255), country VARCHAR(255), date DATE); INSERT INTO student_accommodations (student_id, disability_type, country, date) VALUES (1, 'Visual Impairment', 'USA', '2021-03-22'); INSERT INTO student_accommodations (student_id, disability_type, country, date) VALUES (2, 'Visual Impairment', 'Canada', '2021-04-01');

SELECT country, COUNT(*) as num_students FROM student_accommodations WHERE disability_type = 'Visual Impairment' AND date BETWEEN DATE_SUB(NOW(), INTERVAL 1 YEAR) AND NOW() GROUP BY country;


Question: Calculate the total production for each month of the year

CREATE TABLE monthly_production (id INT, field_name VARCHAR(50), production_date DATE, qty FLOAT); INSERT INTO monthly_production (id, field_name, production_date, qty) VALUES (1, 'Galkynysh', '2019-01-01', 50000); INSERT INTO monthly_production (id, field_name, production_date, qty) VALUES (2, 'Samotlor', '2019-02-12', 60000);

SELECT MONTH(production_date) as month, SUM(qty) as total_qty FROM monthly_production GROUP BY month;


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

CREATE TABLE prt4_n_p2 PARTITION OF prt4_n FOR VALUES FROM (300) TO (500);


Question: Generate PostgreSQL SQL for: How many positive votes for Tennessee in 2006?

CREATE TABLE table_name_73 (yes_vote VARCHAR, date VARCHAR, state VARCHAR)

SELECT yes_vote FROM table_name_73 WHERE date = '2006' AND state = 'tennessee';


Question: Find the 2nd most visited destination for each year in the 'visits' table.

CREATE TABLE visits (visit_id INT, destination TEXT, visit_date DATE); INSERT INTO visits (visit_id, destination, visit_date) VALUES (1, 'New York', '2022-01-01'), (2, 'New York', '2022-02-01'), (3, 'Vancouver', '2022-03-01');

SELECT destination, EXTRACT(YEAR FROM visit_date) AS visit_year, RANK() OVER (PARTITION BY EXTRACT(YEAR FROM visit_date) ORDER BY COUNT(*) DESC) AS visit_rank FROM visits GROUP BY destination, EXTRACT(YEAR FROM visit_date) HAVING visit_rank = 2;


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

ALTER EXTENSION pgtap ADD FUNCTION function_lang_is( NAME, NAME[], NAME, TEXT );


Question: Generate PostgreSQL SQL for: What is the Score of the game against Philadelphia 76ers?

CREATE TABLE table_name_2 (score VARCHAR, opponent VARCHAR)

SELECT score FROM table_name_2 WHERE opponent = 'philadelphia 76ers';


Question: List all support programs and their respective coordinators, ordered alphabetically by support program name.

CREATE TABLE support_programs (id INT, name TEXT, coordinator TEXT);

SELECT * FROM support_programs ORDER BY name;


Question: Generate PostgreSQL SQL for: What position does the player from texas a&m play?

CREATE TABLE table_name_32 (position VARCHAR, school VARCHAR)

SELECT position FROM table_name_32 WHERE school = 'texas a&m';


Question: Insert a new record for a player from 'Brazil' who uses Oculus and prefers PC gaming.

CREATE TABLE Players (PlayerID INT, Country VARCHAR(20), VRPlatform VARCHAR(10), PrefersPC BOOLEAN);

INSERT INTO Players (PlayerID, Country, VRPlatform, PrefersPC) VALUES (3, 'Brazil', 'Oculus', TRUE);


Question: Find the difference in stream counts between consecutive rows for each country.

CREATE TABLE users (id INT, country VARCHAR(50), stream_count INT); INSERT INTO users (id, country, stream_count) VALUES (1, 'USA', 100), (2, 'Canada', 120), (3, 'USA', 150), (4, 'Mexico', 80);

SELECT country, stream_count - LAG(stream_count) OVER(PARTITION BY country ORDER BY id) AS stream_count_diff FROM users;


Question: Generate PostgreSQL SQL for: Which Local authority has Services of greater anglia?

CREATE TABLE table_name_33 (local_authority VARCHAR, services VARCHAR)

SELECT local_authority FROM table_name_33 WHERE services = 'greater anglia';


Question: Generate PostgreSQL SQL for: What is the lowest Total, when Second is "55"?

CREATE TABLE table_name_2 (total INTEGER, second VARCHAR)

SELECT MIN(total) FROM table_name_2 WHERE second = 55;


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

BEGIN
    FOR id IN SELECT 1/(x-1000) FROM generate_series(1,1000) x LOOP
        INSERT INTO test1 VALUES(id);

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


Question: Generate PostgreSQL SQL for: What is the model with a engine type with b5244 s2?

CREATE TABLE table_name_97 (model VARCHAR, engine_type VARCHAR)

SELECT model FROM table_name_97 WHERE engine_type = 'b5244 s2';


Question: Generate PostgreSQL SQL for: The swimmer in lane 7 has what as the smallest rank?

CREATE TABLE table_name_81 (rank INTEGER, lane VARCHAR)

SELECT MIN(rank) FROM table_name_81 WHERE lane = 7;


Question: What is the total CO2 emissions of manufacturing processes for all silk garments, in the 'manufacturing' table?

CREATE TABLE manufacturing (id INT, garment_id INT, garment_material VARCHAR(50), co2_emissions DECIMAL(10, 2), process_date DATE);

SELECT SUM(co2_emissions) AS total_co2_emissions FROM manufacturing WHERE garment_material = 'silk';


Question: Generate PostgreSQL SQL for: How many games or records were played on the Miami Orange Bowl?

CREATE TABLE table_17386066_2 (record VARCHAR, stadium VARCHAR)

SELECT COUNT(record) FROM table_17386066_2 WHERE stadium = 'Miami Orange Bowl';


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

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


Question: Generate PostgreSQL SQL for: What is the 1952 rate when the 1954 is more than 4.2?

SELECT SUM(1952) FROM table_name_37 WHERE 1954 > 4.2;


Question: What is the maximum length of a dam in the 'dams' table?

CREATE TABLE dams (dam_id INT, dam_name VARCHAR(50), location VARCHAR(50), length DECIMAL(10,2), reservoir_capacity INT);


Question: What is the percentage of games won by each team in the 2022 NBA playoffs?

CREATE TABLE nba_teams (team_id INT, team_name VARCHAR(255)); INSERT INTO nba_teams VALUES (1, 'TeamA'), (2, 'TeamB'), (3, 'TeamC'); CREATE TABLE nba_games (game_id INT, home_team_id INT, away_team_id INT, home_score INT, away_score INT, playoff_round VARCHAR(255)); INSERT INTO nba_games VALUES (1, 1, 2, 90, 85, 'First Round'), (2, 1, 3, 80, 85, 'First Round'), (3, 2, 1, 95, 90, 'First Round'), (4, 2, 3, 88, 82, 'First Round');

SELECT t.team_name, (SUM(CASE WHEN g.home_team_id = t.team_id THEN 1 ELSE 0 END) + SUM(CASE WHEN g.away_team_id = t.team_id THEN 1 ELSE 0 END) - SUM(CASE WHEN (g.home_team_id = t.team_id AND g.home_score < g.away_score) OR (g.away_team_id = t.team_id AND g.home_score > g.away_score) THEN 1 ELSE 0 END)) * 100.0 / COUNT(*) AS win_percentage FROM nba_teams t JOIN nba_games g ON t.team_id IN (g.home_team_id, g.away_team_id) WHERE g.playoff_round = 'First Round' GROUP BY t.team_name;


Question: What is the total number of volunteers from the country of Australia?

CREATE TABLE volunteers (id INT, country TEXT); INSERT INTO volunteers (id, country) VALUES (1, 'Australia'), (2, 'Mexico'), (3, 'Australia');

SELECT COUNT(*) FROM volunteers WHERE country = 'Australia';


Question: Generate PostgreSQL SQL for: List all document type codes and document type names.

CREATE TABLE Ref_document_types (document_type_code VARCHAR, document_type_name VARCHAR)

SELECT document_type_code, document_type_name FROM Ref_document_types;


Question: What is the total amount of climate finance committed to renewable energy projects in Africa?

CREATE TABLE renewable_energy_projects (project_id INT, project_name VARCHAR(255), location VARCHAR(255), funded_by VARCHAR(255), amount DECIMAL(10,2)); INSERT INTO renewable_energy_projects (project_id, project_name, location, funded_by, amount) VALUES (1, 'Solar Farm in Kenya', 'Kenya', 'Global Green Fund', 5000000.00), (2, 'Wind Power in South Africa', 'South Africa', 'Climate Action Bank', 7000000.00);

SELECT SUM(amount) FROM renewable_energy_projects WHERE location = 'Africa' AND funded_by IS NOT NULL;


Question: Generate PostgreSQL SQL for: How many gold medals on average were earned by Italy when they held the rank of 4?

CREATE TABLE table_name_5 (gold INTEGER, nation VARCHAR, rank VARCHAR)

SELECT AVG(gold) FROM table_name_5 WHERE nation = 'italy' AND rank > 4;


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

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

SELECT count(*) FROM (SELECT * FROM pg_partition_tree(0)) AS _sub;


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

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


Question: What is the number of cases and win rate for female attorneys in the West region?

CREATE TABLE Cases (CaseID INT, AttorneyID INT, CaseOutcome VARCHAR(50)); INSERT INTO Cases (CaseID, AttorneyID, CaseOutcome) VALUES (1, 1, 'Won'), (2, 1, 'Lost'), (3, 2, 'Won'), (4, 2, 'Won'), (5, 3, 'Lost'), (6, 3, 'Lost'), (7, 4, 'Won'), (8, 4, 'Lost'), (9, 5, 'Lost'), (10, 5, 'Won');   CREATE TABLE Attorneys (AttorneyID INT, AttorneyName VARCHAR(50), Gender VARCHAR(50)); INSERT INTO Attorneys (AttorneyID, AttorneyName, Gender) VALUES (1, 'Jane Doe', 'Female'), (2, 'John Smith', 'Male'), (3, 'Sara Connor', 'Female'), (4, 'David Kim', 'Male'), (5, 'Emily Johnson', 'Female');

SELECT a.AttorneyName, a.Gender, COUNT(c.CaseID) AS TotalCases, COUNT(c.CaseID) * 100.0 / SUM(COUNT(c.CaseID)) OVER (PARTITION BY a.Gender) AS WinRate FROM Attorneys a JOIN Cases c ON a.AttorneyID = c.AttorneyID WHERE a.Gender = 'Female' AND a.Region = 'West' GROUP BY a.AttorneyName, a.Gender;


Question: Generate PostgreSQL SQL for: What's the fewest number of pages for the title al-jiniral fi matahatihi?

CREATE TABLE table_name_39 (pages INTEGER, title VARCHAR)

SELECT MIN(pages) FROM table_name_39 WHERE title = 'al-jiniral fi matahatihi';


Question: What is the total revenue for each region where garments were sold with a price greater than '250'?

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 region, SUM(price) AS total_revenue FROM sales WHERE price > 250 GROUP BY region;


Question: Update the donation amount for 'The Life You Can Save' to $35,000 in the 'philanthropic_trends' table.

CREATE TABLE philanthropic_trends (organization_name TEXT, donation_amount INTEGER); INSERT INTO philanthropic_trends (organization_name, donation_amount) VALUES ('Effctive Altruism Funds', 50000), ('GiveWell', 40000), ('The Life You Can Save', 30000);

UPDATE philanthropic_trends SET donation_amount = 35000 WHERE organization_name = 'The Life You Can Save';


Question: Generate PostgreSQL SQL for: Which mideast regional state contains the city of Seattle?

CREATE TABLE table_name_53 (state VARCHAR, region VARCHAR, city VARCHAR)

SELECT state FROM table_name_53 WHERE region = 'mideast' AND city = 'seattle';


Question: Determine the average number of students enrolled in courses offered by 'Columbia U' each season.

CREATE TABLE course_enrollment (course_id INT, university VARCHAR(20), num_students INT); INSERT INTO course_enrollment (course_id, university, num_students) VALUES (1, 'Columbia U', 30), (2, 'Yale U', 20), (3, 'Columbia U', 40);

SELECT AVG(num_students) FROM course_enrollment WHERE university = 'Columbia U';


Question: Generate PostgreSQL SQL for: What spacecraft had an EVA that ended at 17:28?

CREATE TABLE table_name_66 (spacecraft VARCHAR, end_time VARCHAR)

SELECT spacecraft FROM table_name_66 WHERE end_time = '17:28';


Question: Generate PostgreSQL SQL for: What is the To par of the New Zealand Player?

CREATE TABLE table_name_79 (to_par VARCHAR, country VARCHAR)

SELECT to_par FROM table_name_79 WHERE country = 'new zealand';


Question: PostgreSQL regression test 'amutils': Write the SELECT query (example 10).

select col, prop, pg_index_column_has_property(o, col, prop)
  from (values ('foocover'::regclass)) v1(o),
       (values (1,'orderable'),(2,'asc'),(3,'desc'),
               (4,'nulls_first'),(5,'nulls_last'),
               (6,'distance_orderable'),(7,'returnable'),
               (8, 'bogus')) v2(idx,prop),
       generate_series(1,3) col
 order by col, idx;

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

SELECT count(*) FROM (select col, prop, pg_index_column_has_property(o, col, prop)
  from (values ('foocover'::regclass)) v1(o),
       (values (1,'orderable'),(2,'asc'),(3,'desc'),
               (4,'nulls_first'),(5,'nulls_last'),
               (6,'distance_orderable'),(7,'returnable'),
               (8, 'bogus')) v2(idx,prop),
       generate_series(1,3) col
 order by col, idx) AS _sub;