Question: What is the total water consumption (in gallons) for each water usage category in the state of Florida in 2021?

CREATE TABLE states (id INT, name VARCHAR(255)); INSERT INTO states (id, name) VALUES (1, 'Florida'); CREATE TABLE water_usage_categories (id INT, name VARCHAR(255)); INSERT INTO water_usage_categories (id, name) VALUES (1, 'Residential'), (2, 'Commercial'), (3, 'Industrial'); CREATE TABLE water_consumption (category_id INT, state_id INT, consumption INT, date DATE); INSERT INTO water_consumption (category_id, state_id, consumption, date) VALUES (1, 1, 5000, '2021-01-01'), (1, 1, 5500, '2021-01-02'), (2, 1, 4000, '2021-01-01'), (2, 1, 4300, '2021-01-02'), (3, 1, 6000, '2021-01-01'), (3, 1, 6500, '2021-01-02');

SELECT category_id, state_id, SUM(consumption) as total_consumption FROM water_consumption WHERE state_id = 1 AND date BETWEEN '2021-01-01' AND '2021-12-31' GROUP BY category_id, state_id;


Question: What is the average horsepower of sports cars released between 2015 and 2020?

CREATE TABLE SportsCars (Id INT PRIMARY KEY, Name VARCHAR(100), Year INT, Horsepower INT); INSERT INTO SportsCars (Id, Name, Year, Horsepower) VALUES (1, 'Ferrari 488', 2015, 661), (2, 'Porsche 911 GT3', 2017, 500), (3, 'Audi R8 V10', 2016, 610), (4, 'McLaren 720S', 2017, 720), (5, 'Lamborghini Huracan', 2014, 602), (6, 'Chevrolet Corvette Z06', 2015, 650), (7, 'Mercedes-AMG GT R', 2018, 577), (8, 'Jaguar F-Type SVR', 2016, 575), (9, 'Nissan GT-R Nismo', 2017, 600), (10, 'Aston Martin DB11 V12', 2017, 600);

SELECT AVG(Horsepower) FROM SportsCars WHERE Year BETWEEN 2015 AND 2020 AND Name LIKE '%Sports%';


Question: Generate PostgreSQL SQL for: What is Player, when Score is "76-73-73=222"?

CREATE TABLE table_name_60 (player VARCHAR, score VARCHAR)

SELECT player FROM table_name_60 WHERE score = 76 - 73 - 73 = 222;


Question: Generate PostgreSQL SQL for: what is the location for saturday, april 21

CREATE TABLE table_27893892_2 (game_site VARCHAR, date VARCHAR)

SELECT game_site FROM table_27893892_2 WHERE date = 'Saturday, April 21';


Question: Generate PostgreSQL SQL for: What is the result from 2003 from the US Open?

CREATE TABLE table_name_80 (tournament VARCHAR)

SELECT 2003 FROM table_name_80 WHERE tournament = 'us open';


Question: Generate PostgreSQL SQL for: How many wins did Andrew Ranger have?

CREATE TABLE table_23239946_3 (wins VARCHAR, driver VARCHAR)

SELECT COUNT(wins) FROM table_23239946_3 WHERE driver = 'Andrew Ranger';


Question: What is the total number of art pieces in the museums of Australia?

CREATE TABLE museums (id INT, name VARCHAR(50), location VARCHAR(50), num_pieces INT); INSERT INTO museums (id, name, location, num_pieces) VALUES (1, 'Museum 1', 'Australia', 5000), (2, 'Museum 2', 'United States', 7000), (3, 'Museum 3', 'Canada', 3000);

SELECT SUM(num_pieces) FROM museums WHERE location = 'Australia';


Question: Generate PostgreSQL SQL for: What was the result when then opponents conference was Mac (east)?

CREATE TABLE table_28418916_3 (result VARCHAR, opponents_conference VARCHAR)

SELECT result FROM table_28418916_3 WHERE opponents_conference = 'MAC (East)';


Question: Generate PostgreSQL SQL for: What was the lowest lap with the ranking of 19?

CREATE TABLE table_name_99 (laps INTEGER, start VARCHAR)

SELECT MIN(laps) FROM table_name_99 WHERE start = '19';


Question: Generate PostgreSQL SQL for: What is the 2006 when the 2013 is 2r, and a Tournament was the us open?

CREATE TABLE table_name_91 (tournament VARCHAR)

SELECT 2006 FROM table_name_91 WHERE 2013 = '2r' AND tournament = 'us open';


Question: Generate PostgreSQL SQL for: What platform came out before 2009 with the game wii sports?

CREATE TABLE table_name_38 (platform_s_ VARCHAR, year VARCHAR, game VARCHAR)

SELECT platform_s_ FROM table_name_38 WHERE year < 2009 AND game = 'wii sports';


Question: Which countries had the highest and lowest museum attendance in the last 3 years?

SELECT M.Country, MAX(A.Visitors) AS MaxAttendance, MIN(A.Visitors) AS MinAttendance FROM Museums M INNER JOIN Attendance A ON M.MuseumID = A.MuseumID WHERE A.Year BETWEEN 2019 AND 2021 GROUP BY M.Country;


Question: Write the DDL statement from PostgreSQL regression test 'stats_ext' (example 607).

CREATE STATISTICS mcv_lists_bool_stats (mcv) ON a, b, c
  FROM mcv_lists_bool;

Explanation: DDL from PostgreSQL core regression test for Stats Ext.


Question: Generate PostgreSQL SQL for: what is the years for the displacement 4.0l (242cid)?

CREATE TABLE table_name_35 (years VARCHAR, displacement VARCHAR)

SELECT years FROM table_name_35 WHERE displacement = '4.0l (242cid)';


Question: How many natural disasters were recorded in the 'West Coast' region in 2020?

CREATE TABLE regions (id INT, name VARCHAR(255)); CREATE TABLE natural_disasters (id INT, region_id INT, year INT); INSERT INTO regions (id, name) VALUES (1, 'West Coast'); INSERT INTO natural_disasters (id, region_id, year) VALUES (1, 1, 2020);

SELECT COUNT(*) FROM natural_disasters WHERE region_id = (SELECT id FROM regions WHERE name = 'West Coast') AND year = 2020;


Question: What is the total number of games played by players in each continent, and what is the average age of players in each continent?

CREATE TABLE Players (PlayerID INT, Age INT, Gender VARCHAR(10), GamesPlayed INT, Country VARCHAR(20));

SELECT CONTINENT(Country) as Continent, COUNT(*) as TotalGames, AVG(Age) as AverageAge FROM Players GROUP BY Continent;


Question: Calculate the total tonnage of cargo transported by vessels with US flag in the second quarter of 2022?

CREATE TABLE Flag (flag_id INT PRIMARY KEY, flag_country VARCHAR(255)); INSERT INTO Flag (flag_id, flag_country) VALUES (1, 'United States'); CREATE TABLE Vessel (vessel_id INT PRIMARY KEY, vessel_name VARCHAR(255), flag_id INT); CREATE TABLE Cargo (cargo_id INT PRIMARY KEY, vessel_id INT, cargo_weight INT, PRIMARY KEY (cargo_id, vessel_id)); CREATE TABLE Vessel_Movement (vessel_id INT, movement_date DATE, PRIMARY KEY (vessel_id, movement_date));

SELECT SUM(C.cargo_weight) FROM Vessel V JOIN Cargo C ON V.vessel_id = C.vessel_id JOIN Vessel_Movement VM ON V.vessel_id = VM.vessel_id JOIN Flag F ON V.flag_id = F.flag_id WHERE VM.movement_date >= '2022-04-01' AND VM.movement_date < '2022-07-01' AND F.flag_country = 'United States';


Question: What is the total number of news articles by each author?

CREATE TABLE authors (id INT, name VARCHAR(50)); INSERT INTO authors (id, name) VALUES (1, 'John Doe'), (2, 'Jane Smith'); CREATE TABLE articles (id INT, author_id INT, title VARCHAR(100), content TEXT); INSERT INTO articles (id, author_id, title, content) VALUES (1, 1, 'Article 1', 'Content 1'), (2, 1, 'Article 2', 'Content 2'), (3, 2, 'Article 3', 'Content 3');

SELECT a.name, COUNT(*) as total_articles FROM articles a JOIN authors au ON a.author_id = au.id GROUP BY a.name;


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

--
-- OPERATORS
--

CREATE OPERATOR && (
	LEFTARG = _int4,
	RIGHTARG = _int4,
	PROCEDURE = _int_overlap,
	COMMUTATOR = '&&',
	RESTRICT = _int_overlap_sel,
	JOIN = _int_overlap_joinsel
);

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


Question: What is the total coal production by site in the last quarter?

CREATE TABLE site (site_id INT, site_name VARCHAR(50)); INSERT INTO site (site_id, site_name) VALUES (1, 'Site A'), (2, 'Site B'); CREATE TABLE production (production_id INT, site_id INT, product VARCHAR(10), production_date DATE, quantity INT); INSERT INTO production (production_id, site_id, product, production_date, quantity) VALUES (1, 1, 'coal', '2021-01-01', 500), (2, 1, 'coal', '2021-02-01', 600), (3, 1, 'coal', '2021-03-01', 700), (4, 2, 'coal', '2021-01-01', 800), (5, 2, 'coal', '2021-02-01', 900), (6, 2, 'coal', '2021-03-01', 1000);

SELECT site_name, SUM(quantity) AS total_coal_production FROM production JOIN site ON production.site_id = site.site_id WHERE product = 'coal' AND production_date >= DATEADD(quarter, -1, GETDATE()) GROUP BY site_name;


Question: Find the names and locations of all the museums that have a website.

CREATE TABLE museums (name VARCHAR(255), location VARCHAR(255), website VARCHAR(255));

SELECT name, location FROM museums WHERE website IS NOT NULL;


Question: Write the DML statement from PostgreSQL regression test 'arrays' (example 108).

insert into arrtest_f values(3,'cat1',1.18);

Explanation: DML from PostgreSQL core regression test for Arrays.


Question: Insert records for new electric vehicle models launched in 2022.

CREATE TABLE vehicle (id INT PRIMARY KEY, name VARCHAR(255), production_date DATE, model_year INT); INSERT INTO vehicle (id, name, production_date, model_year) VALUES (1, 'Tesla Model Y', '2022-03-14', 2022), (2, 'Volvo XC40 Recharge', '2022-08-16', 2022), (3, 'Ford Mustang Mach-E', '2022-10-18', 2022);

INSERT INTO vehicle (name, production_date, model_year) VALUES ('Hyundai Ioniq 5', '2022-09-01', 2022), ('Kia EV6', '2022-11-01', 2022);


Question: Generate PostgreSQL SQL for: What is the total number of ladies ranked who had less than 3 silvers, less than 2 total medals, and more than 0 bronze medals?

CREATE TABLE table_name_9 (rank VARCHAR, bronze VARCHAR, silver VARCHAR, total VARCHAR)

SELECT COUNT(rank) FROM table_name_9 WHERE silver < 3 AND total < 2 AND bronze > 0;


Question: How many artifacts were excavated per site each year?

CREATE TABLE excavation_sites (site_id INT, site_name VARCHAR(50), country VARCHAR(50)); INSERT INTO excavation_sites (site_id, site_name, country) VALUES (1, 'Site A', 'USA'); CREATE TABLE artifacts (artifact_id INT, site_id INT, excavation_year INT);

SELECT e.site_name, EXTRACT(YEAR FROM a.excavation_date) as excavation_year, COUNT(*) as artifacts_count FROM excavation_sites e JOIN artifacts a ON e.site_id = a.site_id GROUP BY e.site_id, e.site_name, excavation_year ORDER BY site_id, excavation_year;


Question: What is the minimum donation amount given by donors from each state?

CREATE TABLE donations (id INT, donor_state VARCHAR(255), donation_amount DECIMAL(10,2)); INSERT INTO donations (id, donor_state, donation_amount) VALUES (1, 'California', 1500.00), (2, 'California', 500.00), (3, 'Texas', 2000.00);

SELECT donor_state, MIN(donation_amount) FROM donations GROUP BY donor_state;


Question: Generate PostgreSQL SQL for: Which Viavoice 5/15/09 has a CSA 5/14/09 of 5%, and a TNS-Sofres 5/28/09 of 4.5%?

CREATE TABLE table_name_96 (viavoice_5_15_09 VARCHAR, csa_5_14_09 VARCHAR, tns_sofres_5_28_09 VARCHAR)

SELECT viavoice_5_15_09 FROM table_name_96 WHERE csa_5_14_09 = '5%' AND tns_sofres_5_28_09 = '4.5%';


Question: How many cases were opened and closed in each court during the current year?

CREATE TABLE CourtCases (ID INT, Court VARCHAR(20), CaseType VARCHAR(20), OpenDate DATE, CloseDate DATE); INSERT INTO CourtCases (ID, Court, CaseType, OpenDate, CloseDate) VALUES (1, 'Court1', 'Civil', '2022-01-01', '2022-06-30'), (2, 'Court2', 'Criminal', '2022-02-01', '2022-12-31'), (3, 'Court1', 'Civil', '2022-04-01', '2022-11-30');

SELECT Court, COUNT(CASE WHEN EXTRACT(MONTH FROM OpenDate) = EXTRACT(MONTH FROM CURRENT_DATE) AND EXTRACT(YEAR FROM OpenDate) = EXTRACT(YEAR FROM CURRENT_DATE) THEN 1 END) AS CasesOpened, COUNT(CASE WHEN EXTRACT(MONTH FROM CloseDate) = EXTRACT(MONTH FROM CURRENT_DATE) AND EXTRACT(YEAR FROM CloseDate) = EXTRACT(YEAR FROM CURRENT_DATE) THEN 1 END) AS CasesClosed FROM CourtCases GROUP BY Court;


Question: Generate PostgreSQL SQL for: What is the location and population of the institution called Bluefield College?

CREATE TABLE table_262534_2 (location__population_ VARCHAR, institution VARCHAR)

SELECT location__population_ FROM table_262534_2 WHERE institution = 'Bluefield College';


Question: Delete all records related to decentralized applications that have been banned in Japan.

CREATE TABLE dapps (id INT, name VARCHAR(255), status VARCHAR(255), country VARCHAR(255)); INSERT INTO dapps (id, name, status, country) VALUES (1, 'App 1', 'Banned', 'Japan'), (2, 'App 2', 'Active', 'USA');

DELETE FROM dapps WHERE status = 'Banned' AND country = 'Japan';


Question: Which clients have experienced multiple legal issues in the last year?

CREATE TABLE legal_issues (id INT PRIMARY KEY, client_name VARCHAR(255), issue VARCHAR(255), date DATE); INSERT INTO legal_issues (id, client_name, issue, date) VALUES (1, 'Alex Thompson', 'Divorce', '2021-01-01'); INSERT INTO legal_issues (id, client_name, issue, date) VALUES (2, 'Jamie Patel', 'Custody Battle', '2021-02-01');

SELECT v1.client_name, v1.issue, v1.date, COUNT(v2.id) as issue_count FROM legal_issues v1 JOIN legal_issues v2 ON v1.client_name = v2.client_name AND v2.date >= DATEADD(year, -1, v1.date) AND v2.date < v1.date GROUP BY v1.client_name, v1.issue, v1.date HAVING COUNT(v2.id) > 1;


Question: Generate PostgreSQL SQL for: Name the Event of sudesh peiris?

CREATE TABLE table_name_93 (event VARCHAR, name VARCHAR)

SELECT event FROM table_name_93 WHERE name = 'sudesh peiris';


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

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


Question: What is the maximum funding amount for Indian biotech startups?

CREATE TABLE biotech_startups (id INT, name VARCHAR(100), location VARCHAR(100), funding FLOAT); INSERT INTO biotech_startups (id, name, location, funding) VALUES (1, 'Startup A', 'India', 12000000); INSERT INTO biotech_startups (id, name, location, funding) VALUES (2, 'Startup B', 'India', 18000000); INSERT INTO biotech_startups (id, name, location, funding) VALUES (3, 'Startup C', 'India', 20000000);

SELECT MAX(funding) FROM biotech_startups WHERE location = 'India';


Question: What is the total value of agricultural crops produced by smallholder farmers in each state of Nigeria, and what percentage do they contribute to the total agricultural production?

CREATE TABLE states (id INT, name VARCHAR(50), country VARCHAR(50)); INSERT INTO states (id, name, country) VALUES (1, 'Abia', 'Nigeria'); CREATE TABLE smallholder_farmers (id INT, crop_value FLOAT, state_id INT); INSERT INTO smallholder_farmers (id, crop_value, state_id) VALUES (1, 10000.0, 1); CREATE TABLE total_agricultural_production (state_id INT, total_production FLOAT); INSERT INTO total_agricultural_production (state_id, total_production) VALUES (1, 50000.0);

SELECT s.name, SUM(sf.crop_value) as total_value, (SUM(sf.crop_value) / tap.total_production) * 100 as percentage FROM smallholder_farmers sf INNER JOIN states s ON sf.state_id = s.id INNER JOIN total_agricultural_production tap ON sf.state_id = tap.state_id GROUP BY s.name;


Question: Which locations have more than two successful explorations?

CREATE TABLE exploration (exploration_id INT, exploration_name VARCHAR(255), location VARCHAR(255), cost FLOAT, result VARCHAR(255)); INSERT INTO exploration (exploration_id, exploration_name, location, cost, result) VALUES (3, 'Exploration C', 'Nigeria', 1200000.0, 'Success'); INSERT INTO exploration (exploration_id, exploration_name, location, cost, result) VALUES (4, 'Exploration D', 'Nigeria', 1500000.0, 'Success'); INSERT INTO exploration (exploration_id, exploration_name, location, cost, result) VALUES (5, 'Exploration E', 'Angola', 1800000.0, 'Success'); INSERT INTO exploration (exploration_id, exploration_name, location, cost, result) VALUES (6, 'Exploration F', 'Angola', 2000000.0, 'Failure');

SELECT location, COUNT(*) FROM exploration WHERE result = 'Success' GROUP BY location HAVING COUNT(*) > 2;


Question: Write the DML statement from PostgreSQL regression test 'window' (example 144).

Explanation: DML from PostgreSQL core regression test for Window.


Question: Calculate the average monthly production cost for the 'Eco-friendly Polymer' chemical

CREATE TABLE monthly_cost (chemical VARCHAR(20), month INT, year INT, cost FLOAT); INSERT INTO monthly_cost (chemical, month, year, cost) VALUES ('Eco-friendly Polymer', 1, 2019, 450.25), ('Eco-friendly Polymer', 2, 2019, 470.33), ('Eco-friendly Polymer', 3, 2019, 495.10), ('Eco-friendly Polymer', 1, 2020, 460.00), ('Eco-friendly Polymer', 2, 2020, 480.00), ('Eco-friendly Polymer', 3, 2020, 500.00);

SELECT AVG(cost) FROM monthly_cost WHERE chemical = 'Eco-friendly Polymer';


Question: Generate PostgreSQL SQL for: Which model was made from 2001–2004, with a Torque of n·m (lb·ft) @ 3750, and an Engine code of n42b18 / n46b18?

CREATE TABLE table_name_72 (model VARCHAR, engine_code VARCHAR, years VARCHAR, torque VARCHAR)

SELECT model FROM table_name_72 WHERE years = '2001–2004' AND torque = 'n·m (lb·ft) @ 3750' AND engine_code = 'n42b18 / n46b18';


Question: Generate PostgreSQL SQL for: for the name of jamar jackson what is the class?

CREATE TABLE table_name_87 (class VARCHAR, name VARCHAR)

SELECT class FROM table_name_87 WHERE name = 'jamar jackson';


Question: What is the total number of accidents that occurred at the mining sites in 2020 where the cause was equipment failure?

CREATE TABLE Accidents (AccidentID INT, SiteID INT, Year INT, Cause VARCHAR(255)); INSERT INTO Accidents (AccidentID, SiteID, Year, Cause) VALUES (1, 1, 2020, 'Equipment Failure'), (2, 2, 2019, 'Human Error'), (3, 3, 2020, 'Weather');

SELECT COUNT(*) FROM Accidents WHERE Year = 2020 AND Cause = 'Equipment Failure';


Question: Generate PostgreSQL SQL for: List all players with highest assists from April 2.

CREATE TABLE table_23248910_10 (high_assists VARCHAR, date VARCHAR)

SELECT high_assists FROM table_23248910_10 WHERE date = 'April 2';


Question: Delete clinical trial data for 'DrugE' that was approved after 2018.

CREATE TABLE clinical_trial_data (drug_name TEXT, trial_status TEXT, approval_date DATE); INSERT INTO clinical_trial_data (drug_name, trial_status, approval_date) VALUES ('DrugE', 'Approved', '2019-01-01');

DELETE FROM clinical_trial_data WHERE drug_name = 'DrugE' AND approval_date > '2018-12-31';


Question: What is the average energy storage capacity in regions with wind and solar renewable energy sources

CREATE TABLE energy_storage (region VARCHAR(20), capacity INT);CREATE TABLE renewable_energy (region VARCHAR(20), source VARCHAR(20));

SELECT e.region, AVG(e.capacity) FROM energy_storage e JOIN renewable_energy r ON e.region = r.region WHERE r.source IN ('wind', 'solar') GROUP BY e.region;


Question: Generate PostgreSQL SQL for: Find the states where have some college students in tryout.

CREATE TABLE college (cName VARCHAR); CREATE TABLE tryout (cName VARCHAR)

SELECT DISTINCT state FROM college AS T1 JOIN tryout AS T2 ON T1.cName = T2.cName;


Question: What is the average size of green roofs in Canada?

CREATE TABLE Building (id INT, name VARCHAR(50), city VARCHAR(50), country VARCHAR(50), sqft INT, PRIMARY KEY (id)); INSERT INTO Building (id, name, city, country, sqft) VALUES (3, 'Calgary Tower', 'Calgary', 'Canada', 525600); INSERT INTO Building (id, name, city, country, sqft) VALUES (4, 'CN Tower', 'Toronto', 'Canada', 1090950); CREATE TABLE GreenRoof (id INT, building_id INT, planted_date DATE, size INT, PRIMARY KEY (id), FOREIGN KEY (building_id) REFERENCES Building (id)); INSERT INTO GreenRoof (id, building_id, planted_date, size) VALUES (3, 3, '2015-05-01', 35000); INSERT INTO GreenRoof (id, building_id, planted_date, size) VALUES (4, 4, '2018-07-01', 50000);

SELECT AVG(g.size) FROM GreenRoof g JOIN Building b ON g.building_id = b.id WHERE b.country = 'Canada';


Question: Generate PostgreSQL SQL for: Can you tell me the Combined that has the Victories of 14?

CREATE TABLE table_name_53 (combined VARCHAR, victories VARCHAR)

SELECT combined FROM table_name_53 WHERE victories = 14;


Question: How many virtual tours were conducted in 'Asian' hotels in the past week?

CREATE TABLE virtual_tours (tour_id INT, hotel_id INT, date DATE); INSERT INTO virtual_tours (tour_id, hotel_id, date) VALUES (6, 7, '2022-03-02'), (7, 7, '2022-03-05'), (8, 8, '2022-03-03'); CREATE TABLE hotels (hotel_id INT, region VARCHAR(50)); INSERT INTO hotels (hotel_id, region) VALUES (7, 'Asia'), (8, 'Europe'); CREATE TABLE dates (date DATE); INSERT INTO dates (date) VALUES ('2022-03-01'), ('2022-03-02'), ('2022-03-03'), ('2022-03-04'), ('2022-03-05'), ('2022-03-06'), ('2022-03-07');

SELECT COUNT(*) FROM virtual_tours JOIN hotels ON virtual_tours.hotel_id = hotels.hotel_id JOIN dates ON virtual_tours.date = dates.date WHERE hotels.region = 'Asia' AND dates.date >= DATEADD(day, -7, GETDATE());


Question: Update the description for ethic with id 1 to 'Minimize harm to subjects'

CREATE TABLE ethics (id INT, description VARCHAR(100)); INSERT INTO ethics (id, description) VALUES (1, 'Avoid bias in reporting');

UPDATE ethics SET description = 'Minimize harm to subjects' WHERE id = 1;


Question: Generate PostgreSQL SQL for: What was the GDP (in millions USD) of Hong Kong in 2009?

CREATE TABLE table_1496582_1 (gdp_millions_of_usd__2009_ INTEGER, country___territory VARCHAR)

SELECT MAX(gdp_millions_of_usd__2009_) FROM table_1496582_1 WHERE country___territory = 'Hong Kong';


Question: Generate PostgreSQL SQL for: What is the Club of mexico, Year of 2010, and a Competition of preseason, and a Result of w 0–1?

CREATE TABLE table_name_8 (club VARCHAR, result VARCHAR, competition VARCHAR, nation VARCHAR, year VARCHAR)

SELECT club FROM table_name_8 WHERE nation = 'mexico' AND year = 2010 AND competition = 'preseason' AND result = 'w 0–1';


Question: What is the retention rate of employees who have completed diversity and inclusion training?

CREATE TABLE EmployeeTraining (EmployeeID INT, TrainingType VARCHAR(50), TrainingCompletionDate DATE, EmploymentEndDate DATE); INSERT INTO EmployeeTraining (EmployeeID, TrainingType, TrainingCompletionDate, EmploymentEndDate) VALUES (1, 'Diversity and Inclusion', '2022-01-01', '2023-01-01'), (2, NULL, NULL, '2022-01-01');

SELECT (COUNT(*) * 100.0 / (SELECT COUNT(*) FROM EmployeeTraining WHERE TrainingType = 'Diversity and Inclusion' AND EmploymentEndDate IS NULL)) FROM EmployeeTraining WHERE TrainingType = 'Diversity and Inclusion' AND EmploymentEndDate IS NOT NULL;


Question: Generate PostgreSQL SQL for: What is the most common mill type, and how many are there?

SELECT TYPE, COUNT(*) FROM mill GROUP BY TYPE ORDER BY COUNT(*) DESC LIMIT 1;


Question: Generate PostgreSQL SQL for: How many players had the most assists against New Jersey?

CREATE TABLE table_15873014_3 (high_assists VARCHAR, team VARCHAR)

SELECT COUNT(high_assists) FROM table_15873014_3 WHERE team = 'New Jersey';


Question: Generate PostgreSQL SQL for: How many customers do we have?


Question: Create a view 'safety_protocols' that includes 'chemical_id', 'chemical_name', and 'safety_rating' columns from 'chemical_inventory' table and 'safety_ratings' table

CREATE TABLE safety_ratings (chemical_id INT, safety_rating INT);

CREATE VIEW safety_protocols AS SELECT chemical_inventory.chemical_id, chemical_inventory.chemical_name, safety_ratings.safety_rating FROM chemical_inventory INNER JOIN safety_ratings ON chemical_inventory.chemical_id = safety_ratings.chemical_id;


Question: What is the total quantity of chemical X produced in Q3 2020, for plants located in India?

CREATE TABLE production (plant_id INT, chemical TEXT, quantity INT, quarter INT, year INT); INSERT INTO production (plant_id, chemical, quantity, quarter, year) VALUES (1, 'ChemX', 500, 3, 2020), (2, 'ChemY', 700, 3, 2020), (3, 'ChemX', 450, 3, 2020), (4, 'ChemY', 600, 3, 2020), (5, 'ChemX', 300, 3, 2020), (6, 'ChemX', 800, 4, 2020); CREATE TABLE plants (id INT, name TEXT, location TEXT, PRIMARY KEY (id)); INSERT INTO plants (id, name, location) VALUES (1, 'PlantA', 'IN'), (2, 'PlantB', 'CA'), (3, 'PlantC', 'CN'), (4, 'PlantD', 'AU'), (5, 'PlantE', 'IN'), (6, 'PlantF', 'BR');

SELECT SUM(quantity) FROM production INNER JOIN plants ON production.plant_id = plants.id WHERE chemical = 'ChemX' AND location = 'IN' AND quarter = 3 AND year = 2020;


Question: Generate PostgreSQL SQL for: what is the period if the player is Hashan Tillakaratne?

CREATE TABLE table_26041144_16 (period VARCHAR, player VARCHAR)

SELECT period FROM table_26041144_16 WHERE player = 'Hashan Tillakaratne';


Question: PostgreSQL regression test 'select_into': Write the SELECT query (example 1).

SELECT *
   INTO TABLE sitmp1
   FROM onek
   WHERE onek.unique1 < 2;

Explanation: Regression test for Select Into in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT *
   INTO TABLE sitmp1
   FROM onek
   WHERE onek.unique1 < 2) AS _sub;


Question: Generate PostgreSQL SQL for: What was the tournament that had byron black playing against magnus larsson?

CREATE TABLE table_name_70 (tournament VARCHAR, opponent VARCHAR)

SELECT tournament FROM table_name_70 WHERE opponent = 'magnus larsson';


Question: What's the total revenue generated per visitor who attended the 'Ancient Civilization' exhibition?

CREATE TABLE Transactions (TransactionID INT, VisitorID INT, Amount DECIMAL(10,2));

SELECT AVG(t.Amount) FROM Transactions t JOIN Visitors v ON t.VisitorID = v.VisitorID JOIN Artworks a ON v.VisitorID = a.VisitorID JOIN Exhibitions e ON a.ExhibitionID = e.ExhibitionID WHERE e.ExhibitionName = 'Ancient Civilization';


Question: Which countries have the most vessels in the vessels table?

CREATE TABLE vessels ( id INT, name VARCHAR(255), country VARCHAR(255), capacity INT);

SELECT country, COUNT(*) as vessel_count FROM vessels GROUP BY country ORDER BY vessel_count DESC;


Question: Generate PostgreSQL SQL for: Show each location and the number of cinemas there.

SELECT LOCATION, COUNT(*) FROM cinema GROUP BY LOCATION;


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

CREATE FUNCTION is_valid(ismn)
	RETURNS boolean
	AS 'MODULE_PATHNAME'
	LANGUAGE C
	IMMUTABLE STRICT
	PARALLEL SAFE;


Question: List the wastewater treatment facilities in Texas and their capacities?

CREATE TABLE treatment_facilities (name VARCHAR(50), state VARCHAR(20), capacity INT); INSERT INTO treatment_facilities (name, state, capacity) VALUES ('Facility1', 'Texas', 5000), ('Facility2', 'Texas', 7000);

SELECT name, capacity FROM treatment_facilities WHERE state = 'Texas';


Question: Delete products that have not been restocked in the last 6 months

CREATE TABLE products (product_id INT, product_name VARCHAR(50), restock_date DATE); INSERT INTO products (product_id, product_name, restock_date) VALUES (1, 'Product A', '2021-01-01'), (2, 'Product B', '2021-05-15'), (3, 'Product C', '2020-12-20');

DELETE FROM products WHERE restock_date < DATE_SUB(CURDATE(), INTERVAL 6 MONTH);


Question: Generate PostgreSQL SQL for: How many years had a total earnings amount of 2254598?

CREATE TABLE table_22834834_12 (year VARCHAR, earnings__$_ VARCHAR)

SELECT COUNT(year) FROM table_22834834_12 WHERE earnings__$_ = 2254598;


Question: How many renewable energy projects were completed in 'Texas' in the year 2020?

CREATE TABLE projects (id INT, state VARCHAR(50), year INT, type VARCHAR(50)); INSERT INTO projects (id, state, year, type) VALUES (1, 'Texas', 2020, 'Solar'), (2, 'California', 2021, 'Wind');

SELECT COUNT(*) FROM projects WHERE state = 'Texas' AND year = 2020;


Question: Generate PostgreSQL SQL for: Tell me the opponent for attendance of 68,264

CREATE TABLE table_name_74 (opponent VARCHAR, attendance VARCHAR)

SELECT opponent FROM table_name_74 WHERE attendance = '68,264';


Question: Generate PostgreSQL SQL for: Where was the game held where Hawthorn was the away team?

CREATE TABLE table_name_46 (venue VARCHAR, away_team VARCHAR)

SELECT venue FROM table_name_46 WHERE away_team = 'hawthorn';


Question: What is the average maintenance cost for military equipment in the Pacific region?

CREATE TABLE MilitaryEquipment (Id INT, EquipmentName VARCHAR(50), MaintenanceCost DECIMAL(10,2), Region VARCHAR(50)); INSERT INTO MilitaryEquipment (Id, EquipmentName, MaintenanceCost, Region) VALUES (1, 'Tank', 5000, 'Pacific'), (2, 'Helicopter', 8000, 'Europe');

SELECT AVG(MaintenanceCost) FROM MilitaryEquipment WHERE Region = 'Pacific';


Question: Generate PostgreSQL SQL for: Which Week 13 Nov 23 has a Week 6 Oct 5 of oklahoma state (5-0)?

CREATE TABLE table_name_73 (week_13_nov_23 VARCHAR, week_6_oct_5 VARCHAR)

SELECT week_13_nov_23 FROM table_name_73 WHERE week_6_oct_5 = 'oklahoma state (5-0)';


Question: Delete all records from the 'legal_aid' table where the 'case_value' is less than $5000

CREATE TABLE legal_aid (case_id INT, case_value NUMERIC(10,2));

WITH deleted_records AS (DELETE FROM legal_aid WHERE case_value < 5000 RETURNING *) SELECT * FROM deleted_records;


Question: Delete a specific artifact and its related excavation site

CREATE TABLE ExcavationSites (SiteID int, Name varchar(50), Country varchar(50), StartDate date); INSERT INTO ExcavationSites (SiteID, Name, Country, StartDate) VALUES (7, 'Site H', 'India', '2012-02-02'); CREATE TABLE Artifacts (ArtifactID int, SiteID int, Name varchar(50), Description text, DateFound date); INSERT INTO Artifacts (ArtifactID, SiteID, Name, Description, DateFound) VALUES (6, 7, 'Artifact V', 'An Indian artifact', '2016-04-04');

DELETE es, a FROM ExcavationSites es INNER JOIN Artifacts a ON es.SiteID = a.SiteID WHERE a.ArtifactID = 6;


Question: Generate PostgreSQL SQL for: What was the minimum vertical measurement if the aspect ratio is 16:9 and scanning is interlaced?

CREATE TABLE table_272313_1 (vertical INTEGER, aspect_ratio VARCHAR, scanning VARCHAR)

SELECT MIN(vertical) FROM table_272313_1 WHERE aspect_ratio = '16:9' AND scanning = 'interlaced';


Question: List all policies and claim amounts for policyholders in 'ME' or 'MD' that have a claim amount greater than $5000.

CREATE TABLE Policyholders (PolicyID INT, PolicyholderName TEXT, State TEXT); INSERT INTO Policyholders (PolicyID, PolicyholderName, State) VALUES (1, 'Jose Hernandez', 'ME'), (2, 'Grace Lee', 'MD'); CREATE TABLE Claims (ClaimID INT, PolicyID INT, ClaimAmount INT); INSERT INTO Claims (ClaimID, PolicyID, ClaimAmount) VALUES (1, 1, 10000), (2, 1, 7000), (3, 2, 3000);

SELECT Policyholders.PolicyID, Claims.ClaimAmount FROM Policyholders INNER JOIN Claims ON Policyholders.PolicyID = Claims.PolicyID WHERE Policyholders.State IN ('ME', 'MD') AND Claims.ClaimAmount > 5000;


Question: Generate PostgreSQL SQL for: What time contains the owner of maine chance farm?

CREATE TABLE table_name_55 (time VARCHAR, owner VARCHAR)

SELECT time FROM table_name_55 WHERE owner = 'maine chance farm';


Question: How many players are there in each region?

CREATE TABLE player_info (player_id INT, region VARCHAR(255)); INSERT INTO player_info (player_id, region) VALUES (1, 'North America'), (2, 'Europe'), (3, 'Asia'), (4, 'South America');

SELECT region, COUNT(*) as num_players FROM player_info GROUP BY region;


Question: Write the DDL statement from PostgreSQL regression test 'select_into' (example 50).

CREATE TABLE ctas_ine_tbl AS SELECT 1 / 0; -- error
CREATE TABLE IF NOT EXISTS ctas_ine_tbl AS SELECT 1 / 0; -- ok
CREATE TABLE ctas_ine_tbl AS SELECT 1 / 0 WITH NO DATA; -- error
CREATE TABLE IF NOT EXISTS ctas_ine_tbl AS SELECT 1 / 0 WITH NO DATA; -- ok
EXPLAIN (ANALYZE, COSTS OFF, SUMMARY OFF, TIMING OFF)
  CREATE TABLE ctas_ine_tbl AS SELECT 1 / 0; -- error
EXPLAIN (ANALYZE, COSTS OFF, SUMMARY OFF, TIMING OFF)
  CREATE TABLE IF NOT EXISTS ctas_ine_tbl AS SELECT 1 / 0; -- ok
EXPLAIN (ANALYZE, COSTS OFF, SUMMARY OFF, TIMING OFF)
  CREATE TABLE ctas_ine_tbl AS SELECT 1 / 0 WITH NO DATA; -- error
EXPLAIN (ANALYZE, COSTS OFF, SUMMARY OFF, TIMING OFF)
  CREATE TABLE IF NOT EXISTS ctas_ine_tbl AS SELECT 1 / 0 WITH NO DATA; -- ok
PREPARE ctas_ine_query AS SELECT 1 / 0;

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


Question: Generate PostgreSQL SQL for: Name the title that was written by r. scott gemmill

CREATE TABLE table_17356042_1 (title VARCHAR, written_by VARCHAR)

SELECT title FROM table_17356042_1 WHERE written_by = 'R. Scott Gemmill';


Question: Generate PostgreSQL SQL for: What was the diameter of the feature found in 1997?

CREATE TABLE table_16799784_3 (diameter__km_ VARCHAR, year_named VARCHAR)

SELECT diameter__km_ FROM table_16799784_3 WHERE year_named = 1997;


Question: Show number of labor disputes by union name

CREATE TABLE labor_disputes (id INT, union_name VARCHAR(50), dispute_date DATE, dispute_reason VARCHAR(50)); INSERT INTO labor_disputes (id, union_name, dispute_date, dispute_reason) VALUES (1, 'United Steelworkers', '2019-12-01', 'Wages'), (2, 'Teamsters', '2020-06-15', 'Benefits'), (3, 'Service Employees International Union', '2018-03-03', 'Working conditions');

SELECT union_name, COUNT(*) as total_disputes FROM labor_disputes GROUP BY union_name;


Question: Generate PostgreSQL SQL for: What is the average rating of songs for each language?

CREATE TABLE song (languages VARCHAR, rating INTEGER)

SELECT AVG(rating), languages FROM song GROUP BY languages;


Question: What is the total watch time for videos in the 'investigative journalism' category, grouped by region?

CREATE TABLE videos (id text, category text, region text, watch_time integer); INSERT INTO videos (id, category, region, watch_time) VALUES ('VideoA', 'investigative journalism', 'North America', 3600); INSERT INTO videos (id, category, region, watch_time) VALUES ('VideoB', 'investigative journalism', 'Europe', 4200);

SELECT region, SUM(watch_time) as total_watch_time FROM videos WHERE category = 'investigative journalism' GROUP BY region;


Question: Generate PostgreSQL SQL for: What is the position of the race with a point of test driver?

CREATE TABLE table_name_70 (position VARCHAR, points VARCHAR)

SELECT position FROM table_name_70 WHERE points = 'test driver';


Question: Generate PostgreSQL SQL for: What was the total amount of Value ($M), when the Rank was higher than 6, and the % change on year was -27?

CREATE TABLE table_name_36 (value__ VARCHAR, rank VARCHAR, _percentage_change_on_year VARCHAR)

SELECT COUNT(value__) AS $m_ FROM table_name_36 WHERE rank > 6 AND _percentage_change_on_year = '-27';


Question: Insert a new record into the 'fares' table for 'Zone 2' with an effective date of 2022-01-01 and a fare of $3.00

CREATE TABLE fares (zone TEXT, fare DECIMAL(5,2), effective_date DATE);

INSERT INTO fares (zone, fare, effective_date) VALUES ('Zone 2', 3.00, '2022-01-01');


Question: What is the daily revenue trend for the last quarter?

SELECT date, revenue, ROW_NUMBER() OVER (ORDER BY revenue DESC) as ranking FROM daily_revenue WHERE date >= CURRENT_DATE - INTERVAL '3 months' ORDER BY date;


Question: Which countries have launched satellites using providers other than SpaceTech Inc. and CosmosLaunch?

CREATE TABLE Satellites (country VARCHAR(255), provider VARCHAR(255)); INSERT INTO Satellites (country, provider) VALUES ('Country1', 'SpaceTech Inc.'); INSERT INTO Satellites (country, provider) VALUES ('Country2', 'CosmosLaunch'); INSERT INTO Satellites (country, provider) VALUES ('Country3', 'OtherLaunch');

SELECT country FROM Satellites WHERE provider NOT IN ('SpaceTech Inc.', 'CosmosLaunch');


Question: Generate PostgreSQL SQL for: Who were the opponents during game 30?

CREATE TABLE table_name_82 (opponent VARCHAR, game VARCHAR)

SELECT opponent FROM table_name_82 WHERE game = 30;


Question: What is the minimum number of accommodations provided, per country?

CREATE TABLE Accommodations (ID INT PRIMARY KEY, Country VARCHAR(50), AccommodationType VARCHAR(50), Quantity INT); INSERT INTO Accommodations (ID, Country, AccommodationType, Quantity) VALUES (1, 'USA', 'Sign Language Interpretation', 300), (2, 'Canada', 'Wheelchair Ramp', 250), (3, 'Mexico', 'Assistive Listening Devices', 150);

SELECT Country, MIN(Quantity) as Minimum FROM Accommodations GROUP BY Country;


Question: Determine the average daily production quantity for each well in the Asian region

CREATE TABLE daily_production (well_id INT, date DATE, type VARCHAR(10), quantity INT, region VARCHAR(50)); INSERT INTO daily_production (well_id, date, type, quantity, region) VALUES (1, '2022-01-01', 'Oil', 100, 'Asian'), (1, '2022-01-02', 'Oil', 105, 'Asian'), (2, '2022-01-01', 'Gas', 200, 'Asian'), (2, '2022-01-02', 'Gas', 205, 'Asian');

SELECT well_id, AVG(quantity) as avg_daily_production FROM daily_production WHERE region = 'Asian' GROUP BY well_id;


Question: What is the carbon price in Japanese Yen for each country that has a carbon pricing mechanism?

CREATE TABLE Carbon_Pricing (Country VARCHAR(20), Currency VARCHAR(20), Price DECIMAL(10,2)); INSERT INTO Carbon_Pricing VALUES ('Japan', 'JPY', 3000), ('Canada', 'CAD', 20), ('Sweden', 'SEK', 40);

SELECT Country, Price * (SELECT AVG(Exchange_Rate) FROM Exchange_Rates WHERE Currency_Code = Carbon_Pricing.Currency) AS Price_In_JPY FROM Carbon_Pricing;


Question: Generate PostgreSQL SQL for: What is the population density in Buffalo Lake?

CREATE TABLE table_2500440_1 (population_density__per_km_2__ VARCHAR, name VARCHAR)

SELECT population_density__per_km_2__ FROM table_2500440_1 WHERE name = 'Buffalo Lake';


Question: Generate PostgreSQL SQL for: Who won the Modena circuit?

CREATE TABLE table_1140116_5 (winning_driver VARCHAR, circuit VARCHAR)

SELECT winning_driver FROM table_1140116_5 WHERE circuit = 'Modena';


Question: What is the total production volume of uranium in Canada for the year 2019?

CREATE TABLE production (id INT, mine_id INT, year INT, product TEXT, production_volume INT); INSERT INTO production (id, mine_id, year, product, production_volume) VALUES (1, 1, 2019, 'Uranium', 5000);

SELECT SUM(production_volume) FROM production WHERE year = 2019 AND product = 'Uranium' AND mine_id IN (SELECT id FROM mines WHERE location = 'Canada');


Question: pgTAP test for Resultset (assertion 458).

SELECT * FROM check_test(
    is_empty( 'emptyset', 'whatever' ),
    true,
    'is_empty(prepared, desc)',
    'whatever',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Resultset.


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

SELECT count(*) FROM intervaltmp WHERE a >= '199 days 21:21:23';

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


Question: Generate PostgreSQL SQL for: What was Menato Boffa's grid?

CREATE TABLE table_name_88 (grid VARCHAR, driver VARCHAR)

SELECT grid FROM table_name_88 WHERE driver = 'menato boffa';


Question: Generate PostgreSQL SQL for: How many games have a record of 3-4-0?

CREATE TABLE table_21091162_1 (game INTEGER, record VARCHAR)

SELECT MAX(game) FROM table_21091162_1 WHERE record = '3-4-0';


Question: How many plastic waste recycling facilities are there in China and Indonesia?

CREATE TABLE RecyclingFacilities (facility_id INT, country VARCHAR(50), type VARCHAR(50));

SELECT COUNT(*) FROM RecyclingFacilities WHERE country IN ('China', 'Indonesia') AND type = 'plastic';


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

select jsonb_path_match('[{"a": 1}, {"a": 2}, 3]', 'lax exists($[*].a)', silent => true);

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

SELECT count(*) FROM (select jsonb_path_match('[{"a": 1}, {"a": 2}, 3]', 'lax exists($[*].a)', silent => true)) AS _sub;


Question: Generate PostgreSQL SQL for: What is the match report of the match on 20 August?

CREATE TABLE table_name_12 (match_report VARCHAR, date VARCHAR)

SELECT match_report FROM table_name_12 WHERE date = '20 august';


Question: Generate PostgreSQL SQL for: What name is associated with League 142?

CREATE TABLE table_14962287_2 (name VARCHAR, league VARCHAR)

SELECT name FROM table_14962287_2 WHERE league = 142;


Question: What are the total player scores for each game in a specific region?

CREATE TABLE GameScores (player_id INT, game_id INT, player_score INT, region VARCHAR(255)); INSERT INTO GameScores (player_id, game_id, player_score, region) VALUES (1, 1, 1500, 'North America'), (2, 1, 1800, 'North America'), (3, 2, 2000, 'Asia'), (4, 2, 1900, 'Asia'), (5, 3, 1200, 'Europe'), (6, 3, 1600, 'Europe');

SELECT G.game_name, PS.region, SUM(PS.player_score) as total_score FROM GameScores PS JOIN Games G ON PS.game_id = G.game_id GROUP BY G.game_name, PS.region;


Question: What is the monthly revenue trend for a specific hotel in 2022?

CREATE TABLE hotel_revenue (hotel_name VARCHAR(20), revenue DECIMAL(10,2), revenue_date DATE); INSERT INTO hotel_revenue (hotel_name, revenue, revenue_date) VALUES ('Hotel A', 15000, '2022-01-01'), ('Hotel A', 16000, '2022-02-01'), ('Hotel A', 18000, '2022-03-01');

SELECT revenue_date, SUM(revenue) as monthly_revenue FROM hotel_revenue WHERE hotel_name = 'Hotel A' AND revenue_date BETWEEN '2022-01-01' AND '2022-12-31' GROUP BY EXTRACT(MONTH FROM revenue_date);


Question: What is the difference in the number of visitors between the two exhibitions?

CREATE TABLE Exhibition1 (visitor_id INT, primary key(visitor_id)); INSERT INTO Exhibition1 VALUES (1), (2), (3); CREATE TABLE Exhibition2 (visitor_id INT, primary key(visitor_id)); INSERT INTO Exhibition2 VALUES (4), (5), (6), (7);

SELECT COUNT(Exhibition1.visitor_id) - COUNT(Exhibition2.visitor_id) AS difference FROM Exhibition1 LEFT JOIN Exhibition2 ON Exhibition1.visitor_id = Exhibition2.visitor_id;


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

INSERT INTO t3 VALUES (1, 'sss'), (2, 'ttt'), (3, 'uuu');

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


Question: Generate PostgreSQL SQL for: What is the earliest Year when the City is Peabody?

CREATE TABLE table_name_2 (year INTEGER, city VARCHAR)

SELECT MIN(year) FROM table_name_2 WHERE city = 'peabody';


Question: Generate PostgreSQL SQL for: Which College has Player Mark Brown and a Pick # greater than 195?

CREATE TABLE table_name_63 (college VARCHAR, pick__number VARCHAR, player VARCHAR)

SELECT college FROM table_name_63 WHERE pick__number > 195 AND player = 'mark brown';


Question: What is the average age of artifacts in the 'Ancient_Ceramics' table?

CREATE TABLE Ancient_Ceramics (id INT, artifact_name VARCHAR(50), age INT); INSERT INTO Ancient_Ceramics (id, artifact_name, age) VALUES (1, 'Pottery Shard A', 2000), (2, 'Pottery Shard B', 3000), (3, 'Pottery Shard C', 1500);


Question: What is the count of impact investments in South Asia with a value greater than 10000?

CREATE TABLE impact_investments (id INT, value INT, location VARCHAR(50)); INSERT INTO impact_investments (id, value, location) VALUES (1, 12000, 'South Asia'), (2, 7000, 'East Asia'), (3, 15000, 'South Asia');

SELECT COUNT(*) FROM impact_investments WHERE location = 'South Asia' AND value > 10000;


Question: What is the distribution of case outcomes (won, lost, settled) for attorneys in the 'attorneys_outcomes' table, grouped by attorney age?

CREATE TABLE attorney_age (attorney_id INT, age INT); CREATE TABLE attorneys_outcomes (case_outcome VARCHAR(10), attorney_id INT);

SELECT a.age, o.case_outcome, COUNT(*) AS count FROM attorney_age a JOIN attorneys_outcomes o ON a.attorney_id = o.attorney_id GROUP BY a.age, o.case_outcome;


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

SELECT t1.id1, t1.result, t2.expected
    FROM num_result t1, num_exp_ln t2
    WHERE t1.id1 = t2.id
    AND t1.result != t2.expected;

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

SELECT count(*) FROM (SELECT t1.id1, t1.result, t2.expected
    FROM num_result t1, num_exp_ln t2
    WHERE t1.id1 = t2.id
    AND t1.result != t2.expected) AS _sub;


Question: Update the salary of the council member representing district 3 to $90,000.00.

CREATE TABLE City_Council (council_id INT, council_member VARCHAR(50), district_number INT, salary DECIMAL(10,2), PRIMARY KEY (council_id)); INSERT INTO City_Council (council_id, council_member, district_number, salary) VALUES (1, 'James Smith', 1, 85000.00), (2, 'Katherine Johnson', 2, 85000.00), (3, 'Mohammed Ahmed', 3, 80000.00);

UPDATE City_Council SET salary = 90000.00 WHERE district_number = 3;


Question: Which states have more than 300 wastewater treatment plants?

CREATE TABLE state_plants (state TEXT, num_plants INT); INSERT INTO state_plants (state, num_plants) VALUES ('California', 321), ('Texas', 456), ('New York', 123), ('Florida', 345);

SELECT state FROM state_plants WHERE num_plants > 300;


Question: Generate PostgreSQL SQL for: What was the crowd size for the game where Footscray was the away team?

CREATE TABLE table_name_21 (crowd VARCHAR, away_team VARCHAR)

SELECT COUNT(crowd) FROM table_name_21 WHERE away_team = 'footscray';


Question: How many esports events were held in Japan in 2022?

CREATE TABLE EsportsEvents (EventID INT, Country VARCHAR(20), Year INT); INSERT INTO EsportsEvents (EventID, Country, Year) VALUES (1, 'Japan', 2022);

SELECT COUNT(*) FROM EsportsEvents WHERE Country = 'Japan' AND Year = 2022;


Question: Generate PostgreSQL SQL for: If the total is 6, what is the maximum R?

CREATE TABLE table (r INTEGER, total VARCHAR)

SELECT MAX(r) FROM table WHERE total = 6;


Question: pgTAP test for Ownership (assertion 103).

SELECT * FROM check_test(
    index_owner_is('someschema', 'anothertab', 'idx_name', current_user),
	true,
    'index_owner_is(schema, table, index, user)',
    'Index idx_name ON someschema.anothertab should be owned by ' || quote_ident(current_user),
    ''
);

Explanation: SQL assertion from pgTAP test suite for Ownership.


Question: What is the difference in revenue between the top and bottom album for each artist?

CREATE TABLE AlbumRevenue (AlbumID INT, ArtistID INT, Revenue DECIMAL(10,2)); INSERT INTO AlbumRevenue (AlbumID, ArtistID, Revenue) VALUES (1, 1, 150000.00), (2, 1, 125000.00), (3, 2, 150000.00), (4, 2, 100000.00), (5, 3, 100000.00); CREATE TABLE Artist (ArtistID INT, ArtistName VARCHAR(50)); INSERT INTO Artist (ArtistID, ArtistName) VALUES (1, 'Taylor Swift'), (2, 'BTS'), (3, 'Adele');

SELECT ArtistName, MAX(Revenue) - MIN(Revenue) AS RevenueDifference FROM (SELECT ArtistID, Revenue, ROW_NUMBER() OVER (PARTITION BY ArtistID ORDER BY Revenue DESC) AS Rank FROM AlbumRevenue) AS Subquery JOIN Artist ON Subquery.ArtistID = Artist.ArtistID GROUP BY ArtistName;


Question: pgTAP test for Inheritance (assertion 28).

SELECT * FROM check_test(
    hasnt_inherited_tables( 'child2', 'Gimme inheritance' ),
    true,
    'hasnt_inherited_tables(tab, desc)',
    'Gimme inheritance',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Inheritance.


Question: Delete records in the "renewable_energy" table where the "source" is 'hydro' and the "capacity_mw" is greater than 500

CREATE TABLE renewable_energy ( id INT PRIMARY KEY, source VARCHAR(50), capacity_mw INT ); INSERT INTO renewable_energy (id, source, capacity_mw) VALUES (1, 'hydro', 600), (2, 'solar', 300), (3, 'wind', 400);

DELETE FROM renewable_energy WHERE source = 'hydro' AND capacity_mw > 500;


Question: What is the average account balance for socially responsible lending customers, partitioned by gender?

CREATE TABLE socially_responsible_lending(customer_id INT, name VARCHAR(50), gender VARCHAR(10), account_balance DECIMAL(10, 2)); INSERT INTO socially_responsible_lending VALUES (1, 'John Doe', 'Male', 5000), (2, 'Jane Smith', 'Female', 7000), (3, 'Ali Hassan', 'Male', 6000), (4, 'Fatima Khan', 'Female', 8000);

SELECT gender, AVG(account_balance) avg_balance FROM socially_responsible_lending WINDOW W AS (PARTITION BY gender);


Question: Insert a new professional development course with a unique course_id, course_name, and number of students who have completed the course, and update the corresponding teacher's record accordingly.

CREATE TABLE courses (course_id INT, course_name TEXT, num_completions INT); CREATE TABLE professional_development (pd_id INT, teacher_id INT, course_id INT);

INSERT INTO courses (course_id, course_name, num_completions) VALUES (12345, 'Python for Educators', 50); UPDATE professional_development pd SET pd.course_id = 12345 WHERE EXISTS (SELECT * FROM teachers t JOIN courses c ON t.teacher_id = pd.teacher_id WHERE c.course_id = 12345 AND pd.course_id != 12345);


Question: What is the maximum number of mental health parity cases by state?

CREATE TABLE mental_health_parity (state VARCHAR(255), cases INT); INSERT INTO mental_health_parity (state, cases) VALUES ('California', 500), ('New York', 600), ('Texas', 450), ('Florida', 400);

SELECT state, MAX(cases) FROM mental_health_parity GROUP BY state;


Question: Find the clients who have taken out the most socially responsible loans.

CREATE TABLE socially_responsible_loans(client_id INT, country VARCHAR(25));INSERT INTO socially_responsible_loans(client_id, country) VALUES (1, 'Malaysia'), (2, 'UAE'), (3, 'Indonesia'), (4, 'Saudi Arabia'), (1, 'Malaysia'), (2, 'UAE'), (7, 'Indonesia'), (8, 'Saudi Arabia'), (1, 'Malaysia'), (2, 'UAE');

SELECT client_id, COUNT(*) as num_loans FROM socially_responsible_loans GROUP BY client_id ORDER BY num_loans DESC;


Question: What is the average playtime for each player in the "Shooter" genre?

CREATE TABLE PlayerPlaytime (PlayerID int, PlayerName varchar(50), Game varchar(50), Playtime decimal(10,2));

SELECT PlayerName, AVG(Playtime) OVER(PARTITION BY PlayerID) as AvgPlaytime FROM PlayerPlaytime WHERE Game = 'Shooter';


Question: What is the average training time for creative AI applications?

CREATE TABLE creative_ai_applications_training_times (id INT, application VARCHAR(25), training_time FLOAT); INSERT INTO creative_ai_applications_training_times (id, application, training_time) VALUES (1, 'Art Generation', 2.5), (2, 'Music Composition', 3.2), (3, 'Text Generation', 2.8), (4, 'Image Recognition', 1.5), (5, 'Speech Recognition', 4.2);

SELECT AVG(training_time) as avg_training_time FROM creative_ai_applications_training_times;


Question: Who is the user with the highest number of login attempts in the past month?

SELECT user, COUNT(*) AS login_attempts_count FROM login_attempts WHERE timestamp >= NOW() - INTERVAL '1 month' GROUP BY user ORDER BY login_attempts_count DESC LIMIT 1;


Question: What is the total number of comments on posts related to mental health, published by users in Japan, in the month of February 2022?

CREATE TABLE posts (post_id INT, user_id INT, followers INT, post_date DATE, content TEXT); CREATE TABLE comments (comment_id INT, post_id INT, user_id INT, comment_date DATE, comment_text TEXT);

SELECT SUM(c.comments) FROM posts p JOIN comments c ON p.post_id = c.post_id WHERE p.content LIKE '%mental health%' AND p.country = 'Japan' AND p.post_date >= '2022-02-01' AND p.post_date < '2022-03-01';


Question: Generate PostgreSQL SQL for: Who is the partner at the Tampa tournament?

CREATE TABLE table_name_93 (partner VARCHAR, tournament VARCHAR)

SELECT partner FROM table_name_93 WHERE tournament = 'tampa';


Question: Generate PostgreSQL SQL for: Tell me the competition of 20 august 2008

CREATE TABLE table_name_87 (competition VARCHAR, date VARCHAR)

SELECT competition FROM table_name_87 WHERE date = '20 august 2008';


Question: Which members have the most workout duration in the last month?

CREATE TABLE workout_history (id INT, member_id INT, duration INT, date DATE, type VARCHAR(50)); CREATE VIEW total_duration_by_member AS SELECT member_id, SUM(duration) total_duration FROM workout_history GROUP BY member_id; ALTER TABLE total_duration_by_member ADD COLUMN rank INT; UPDATE total_duration_by_member SET rank = ROW_NUMBER() OVER (ORDER BY total_duration DESC);

SELECT w.name, t.total_duration, t.rank FROM total_duration_by_member t JOIN membership w ON t.member_id = w.id ORDER BY t.rank;


Question: Generate PostgreSQL SQL for: What first class team does sanath jayasuriya play for?

CREATE TABLE table_name_51 (first_class_team VARCHAR, player VARCHAR)

SELECT first_class_team FROM table_name_51 WHERE player = 'sanath jayasuriya';


Question: Generate PostgreSQL SQL for: What is every entry for assists if the player is Lynn Pride?

CREATE TABLE table_25352324_5 (assists VARCHAR, player VARCHAR)

SELECT assists FROM table_25352324_5 WHERE player = 'Lynn Pride';


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

SELECT count(*) FROM (select jsonb_path_query('12345678901234567890', '$.bigint()')) AS _sub;


Question: Generate PostgreSQL SQL for: What was the score when essendon was the home team?

CREATE TABLE table_name_75 (home_team VARCHAR)

SELECT home_team AS score FROM table_name_75 WHERE home_team = 'essendon';


Question: Generate PostgreSQL SQL for: What is the status when the artist is Neil Sedaka?

CREATE TABLE table_name_31 (status VARCHAR, artist VARCHAR)

SELECT status FROM table_name_31 WHERE artist = 'neil sedaka';


Question: What is the total revenue for the month of July?

CREATE TABLE revenue (id INT, month INT, amount DECIMAL(5,2)); INSERT INTO revenue (id, month, amount) VALUES (1, 6, 5000.00), (2, 7, 6000.00), (3, 8, 7000.00), (4, 9, 8000.00);

SELECT SUM(amount) FROM revenue WHERE month = 7;


Question: Which city has the highest number of electric taxi rides in a month?

CREATE TABLE electric_taxis (taxi_id INT, ride_id INT, start_time TIMESTAMP, end_time TIMESTAMP, city VARCHAR(255));

SELECT city, COUNT(*) as num_rides FROM electric_taxis WHERE ride_id BETWEEN 1 AND 100000 GROUP BY city ORDER BY num_rides DESC LIMIT 1;


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

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

SELECT count(*) FROM (select ('123'::jsonb)[0]) AS _sub;


Question: What is the average number of hours worked per week by gender, partitioned by mining operation?

CREATE TABLE mining_operations (id INT, name TEXT, location TEXT, gender TEXT, hours_worked INT); INSERT INTO mining_operations (id, name, location, gender, hours_worked) VALUES (1, 'Operation X', 'Australia-NSW', 'Male', 45), (2, 'Operation Y', 'Australia-QLD', 'Female', 40), (3, 'Operation Z', 'Australia-NSW', 'Non-binary', 35), (4, 'Operation A', 'Australia-QLD', 'Male', 50);

SELECT name, gender, AVG(hours_worked) FROM mining_operations GROUP BY name, gender;


Question: PostgreSQL Plpgsql: show example 68.

CREATE FUNCTION stamp_user(id int, comment text) RETURNS void AS $$ #variable_conflict use_variable DECLARE curtime timestamp := now(); BEGIN UPDATE users SET last_modified = curtime, comment = comment WHERE users.id = id; END; $$ LANGUAGE plpgsql;

Explanation: Example from PostgreSQL documentation on Plpgsql.


Question: Generate PostgreSQL SQL for: What is the least round number for Jon Olinger, who was picked before pick # 24?

CREATE TABLE table_name_3 (round INTEGER, name VARCHAR, pick__number VARCHAR)

SELECT MIN(round) FROM table_name_3 WHERE name = 'jon olinger' AND pick__number < 24;


Question: What is the maximum severity and number of occurrences for each threat type, considering only records reported in the last year?

CREATE TABLE threat_intelligence (threat_id INT, threat_type VARCHAR(255), severity INT, last_reported_date DATE, reported_by VARCHAR(255));

SELECT threat_type, MAX(severity), COUNT(*) FROM threat_intelligence WHERE last_reported_date BETWEEN DATE_SUB(CURDATE(), INTERVAL 1 YEAR) AND CURDATE() GROUP BY threat_type;


Question: Insert a new record into the 'Menu' table with id 4, name 'Fish Tacos', price 8.99, and vegetarian false.

CREATE TABLE Menu (id INT, name VARCHAR(255), price DECIMAL(5,2), vegetarian BOOLEAN); INSERT INTO Menu (id, name, price, vegetarian) VALUES (1, 'Chicken Burger', 7.99, FALSE), (2, 'Veggie Wrap', 6.49, TRUE), (3, 'Chicken Caesar Salad', 9.99, FALSE);

INSERT INTO Menu (id, name, price, vegetarian) VALUES (4, 'Fish Tacos', 8.99, FALSE);


Question: What is the most popular clothing item size in Canada?

CREATE TABLE clothing_inventory (id INT, item_name VARCHAR(255), size VARCHAR(10), quantity INT, country VARCHAR(50));

SELECT item_name, size, SUM(quantity) as total_quantity FROM clothing_inventory WHERE country = 'Canada' GROUP BY item_name, size ORDER BY total_quantity DESC LIMIT 1;


Question: Generate PostgreSQL SQL for: Role of narrator, and a Year larger than 2009, and a Release/Air Date of 7 october 2010 belongs to what author?

CREATE TABLE table_name_62 (author VARCHAR, release_air_date VARCHAR, role VARCHAR, year VARCHAR)

SELECT author FROM table_name_62 WHERE role = 'narrator' AND year > 2009 AND release_air_date = '7 october 2010';


Question: Show all agricultural projects in 'Rural Kenya'

CREATE TABLE agricultural_projects (id INT PRIMARY KEY, name VARCHAR(100), location VARCHAR(50), funding_source VARCHAR(50), start_date DATE, end_date DATE); INSERT INTO agricultural_projects (id, name, location, funding_source, start_date, end_date) VALUES (1, 'Solar Powered Irrigation', 'Rural Kenya', 'World Bank', '2022-01-01', '2023-12-31'), (2, 'Crop Diversification', 'Rural Peru', 'USAID', '2022-06-15', '2024-06-14');

SELECT * FROM agricultural_projects WHERE location = 'Rural Kenya';


Question: What is the most common type of crime committed in the South district?

CREATE TABLE crimes (id INT, district VARCHAR(20), type VARCHAR(20), date DATE); INSERT INTO crimes (id, district, type, date) VALUES (1, 'Downtown', 'Theft', '2022-01-02'); INSERT INTO crimes (id, district, type, date) VALUES (2, 'Uptown', 'Vandalism', '2022-01-03'); INSERT INTO crimes (id, district, type, date) VALUES (3, 'Westside', 'Assault', '2022-01-04'); INSERT INTO crimes (id, district, type, date) VALUES (4, 'East End', 'Theft', '2022-01-05'); INSERT INTO crimes (id, district, type, date) VALUES (5, 'South', 'Theft', '2022-01-06'); INSERT INTO crimes (id, district, type, date) VALUES (6, 'South', 'Vandalism', '2022-01-07');

SELECT type, COUNT(*) AS count FROM crimes WHERE district = 'South' GROUP BY type ORDER BY count DESC LIMIT 1;


Question: Generate PostgreSQL SQL for: What was the rank when then time was 7:52.53?

CREATE TABLE table_name_10 (rank INTEGER, time VARCHAR)

SELECT MIN(rank) FROM table_name_10 WHERE time = '7:52.53';


Question: What is the total aid amount provided by each aid agency?

CREATE TABLE Aid_Agency (id INT PRIMARY KEY, name VARCHAR(50), type VARCHAR(50), donor_id INT, FOREIGN KEY (donor_id) REFERENCES Donor(id)); INSERT INTO Aid_Agency (id, name, type, donor_id) VALUES (1, 'UNHCR', 'Refugee Support', 1); INSERT INTO Aid_Agency (id, name, type, donor_id) VALUES (2, 'WFP', 'Food Security', 2); CREATE TABLE Aid_Distribution (id INT PRIMARY KEY, disaster_id INT, aid_amount FLOAT, aid_agency_id INT, FOREIGN KEY (disaster_id) REFERENCES Disaster(id), FOREIGN KEY (aid_agency_id) REFERENCES Aid_Agency(id)); INSERT INTO Aid_Distribution (id, disaster_id, aid_amount, aid_agency_id) VALUES (1, 1, 100000, 1); INSERT INTO Aid_Distribution (id, disaster_id, aid_amount, aid_agency_id) VALUES (2, 2, 150000, 2);

SELECT a.name as agency_name, SUM(ad.aid_amount) as total_aid FROM Aid_Agency a JOIN Aid_Distribution ad ON a.id = ad.aid_agency_id GROUP BY a.name;


Question: List the unique species and their conservation status in the Arctic region.

CREATE TABLE species (id INT, species_name VARCHAR, conservation_status VARCHAR); INSERT INTO species VALUES (1, 'Polar Bear', 'Vulnerable');

SELECT DISTINCT species_name, conservation_status FROM species;


Question: What is the maximum number of points scored by a player in a single NBA game, and who was the player?

CREATE TABLE games (game_id INT, date DATE, team1 TEXT, team2 TEXT, player TEXT, points INT);


Question: What is the change in temperature for each country between 2019 and 2020 in the 'world_temperature' table?

CREATE TABLE world_temperature (country VARCHAR(255), temperature DECIMAL(5,2), measurement_date DATE); INSERT INTO world_temperature (country, temperature, measurement_date) VALUES ('Canada', 10.5, '2019-01-01'), ('Mexico', 22.3, '2019-01-01'), ('Canada', 12.0, '2020-01-01'), ('Mexico', 25.1, '2020-01-01');

SELECT a.country, (a.temperature - b.temperature) as temperature_change FROM world_temperature a INNER JOIN world_temperature b ON a.country = b.country WHERE YEAR(a.measurement_date) = 2020 AND YEAR(b.measurement_date) = 2019;


Question: Generate PostgreSQL SQL for: What is Winner, when Team is "R.J.MacArthur Onslow", and when Circuit is "Oran Park Raceway"?

CREATE TABLE table_name_29 (winner VARCHAR, team VARCHAR, circuit VARCHAR)

SELECT winner FROM table_name_29 WHERE team = 'r.j.macarthur onslow' AND circuit = 'oran park raceway';


Question: Generate PostgreSQL SQL for: What company collaborated in pre-clinical autoimmune disease and inflammation?

CREATE TABLE table_name_99 (collaboration VARCHAR, status VARCHAR, indication VARCHAR)

SELECT collaboration FROM table_name_99 WHERE status = 'pre-clinical' AND indication = 'autoimmune disease and inflammation';


Question: Generate PostgreSQL SQL for: What are the countries of perpetrators? Show each country and the corresponding number of perpetrators there.

CREATE TABLE perpetrator (Country VARCHAR)

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


Question: What is the minimum property price in accessible neighborhoods in New York?

CREATE TABLE NYC_Neighborhoods (Neighborhood_Name TEXT, Accessibility BOOLEAN); INSERT INTO NYC_Neighborhoods (Neighborhood_Name, Accessibility) VALUES ('Manhattan', true), ('Brooklyn', false), ('Queens', true), ('Bronx', true), ('Staten Island', false); CREATE TABLE NYC_Properties (Neighborhood_Name TEXT, Property_Price INTEGER); INSERT INTO NYC_Properties (Neighborhood_Name, Property_Price) VALUES ('Manhattan', 1000000), ('Brooklyn', 800000), ('Queens', 900000), ('Bronx', 700000), ('Staten Island', 600000);

SELECT MIN(NYC_Properties.Property_Price) FROM NYC_Properties INNER JOIN NYC_Neighborhoods ON NYC_Properties.Neighborhood_Name = NYC_Neighborhoods.Neighborhood_Name WHERE NYC_Neighborhoods.Accessibility = true;


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

INSERT INTO concur_reindex_tab VALUES  (1, 'a');

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


Question: Generate PostgreSQL SQL for: How many total wins with the latest win at the 1999 Italian Grand Prix at a rank of 15?

CREATE TABLE table_name_12 (wins INTEGER, latest_win VARCHAR, rank VARCHAR)

SELECT SUM(wins) FROM table_name_12 WHERE latest_win = '1999 italian grand prix' AND rank > 15;


Question: Find the total size of fish farms in 'oceans' schema where the size is greater than 50.

CREATE SCHEMA oceans; CREATE TABLE fish_farms (id INT, size FLOAT, location VARCHAR(20)); INSERT INTO fish_farms (id, size, location) VALUES (1, 55.2, 'ocean'), (2, 62.5, 'ocean'), (3, 70.3, 'ocean');

SELECT SUM(size) FROM oceans.fish_farms WHERE size > 50;


Question: What is the current landfill capacity in Mumbai, India and the projected capacity for the year 2030?'

CREATE TABLE landfill_capacity (city VARCHAR(20), current_capacity INT, projected_capacity INT); INSERT INTO landfill_capacity (city, current_capacity, projected_capacity) VALUES ('Mumbai', 5000, 7000);

SELECT current_capacity as current_landfill_capacity, projected_capacity as projected_landfill_capacity FROM landfill_capacity WHERE city = 'Mumbai';


Question: What is the ratio of concert ticket prices between Pop and Hip Hop genres?

CREATE TABLE artists (name VARCHAR(50), genre VARCHAR(50)); INSERT INTO artists (name, genre) VALUES ('Beyoncé', 'Pop'), ('Drake', 'Hip Hop'), ('Taylor Swift', 'Country Pop'), ('Kendrick Lamar', 'Hip Hop'); CREATE TABLE concerts (artist_name VARCHAR(50), venue VARCHAR(50), ticket_price DECIMAL(5,2)); INSERT INTO concerts (artist_name, venue, ticket_price) VALUES ('Beyoncé', 'Madison Square Garden', 200.00), ('Beyoncé', 'Staples Center', 180.00), ('Drake', 'Barclays Center', 150.00), ('Taylor Swift', 'MetLife Stadium', 250.00);

SELECT 100.0 * AVG(CASE WHEN genre = 'Pop' THEN ticket_price END) / AVG(CASE WHEN genre = 'Hip Hop' THEN ticket_price END) AS ticket_price_ratio FROM artists JOIN concerts ON artists.name = concerts.artist_name;


Question: Generate PostgreSQL SQL for: What is the translation of chetvert?

CREATE TABLE table_name_81 (translation VARCHAR, unit VARCHAR)

SELECT translation FROM table_name_81 WHERE unit = 'chetvert';


Question: Generate PostgreSQL SQL for: What province is Hamilton part of?

CREATE TABLE table_name_66 (province VARCHAR, city VARCHAR)

SELECT province FROM table_name_66 WHERE city = 'hamilton';


Question: Generate PostgreSQL SQL for: Show the names of companies in the banking or retailing industry?

CREATE TABLE company (Name VARCHAR, Industry VARCHAR)

SELECT Name FROM company WHERE Industry = 'Banking' OR Industry = 'Retailing';


Question: Generate PostgreSQL SQL for: Tell me lived for name of 1994/2003

CREATE TABLE table_name_99 (lived_when___mya__ VARCHAR, discovery___publication_of_name VARCHAR)

SELECT lived_when___mya__ FROM table_name_99 WHERE discovery___publication_of_name = '1994/2003';


Question: Update animal count in 'conservation_program' for Panda

CREATE TABLE conservation_program (id INT PRIMARY KEY, animal_name VARCHAR, num_animals INT); INSERT INTO conservation_program (id, animal_name, num_animals) VALUES (1, 'Tiger', 300), (2, 'Panda', 150), (3, 'Rhino', 70), (4, 'Elephant', 450);

UPDATE conservation_program SET num_animals = 200 WHERE animal_name = 'Panda';


Question: Generate PostgreSQL SQL for: What was the score in Kathmandu?

CREATE TABLE table_name_96 (score VARCHAR, venue VARCHAR)

SELECT score FROM table_name_96 WHERE venue = 'kathmandu';


Question: What is the local economic impact of tourism in London in 2020?

CREATE TABLE tourism_impact (city VARCHAR(100), year INT, local_economic_impact INT); INSERT INTO tourism_impact (city, year, local_economic_impact) VALUES ('Paris', 2020, 12000000); INSERT INTO tourism_impact (city, year, local_economic_impact) VALUES ('London', 2020, 10000000);

SELECT local_economic_impact FROM tourism_impact WHERE city = 'London' AND year = 2020;


Question: Generate PostgreSQL SQL for: What is the sum of Bronze when the rank is 7, and the total is more than 22?

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

SELECT SUM(bronze) FROM table_name_19 WHERE rank = 7 AND total > 22;


Question: What is the combined area of all the habitats where the 'Giant Panda' is found in the 'habitat_animals' table?

CREATE TABLE habitat_animals (id INT, animal_name VARCHAR(50), habitat_name VARCHAR(50), area FLOAT); INSERT INTO habitat_animals (id, animal_name, habitat_name, area) VALUES (1, 'Giant Panda', 'Panda Reserve', 50.0), (2, 'Giant Panda', 'Forest', 100.0), (3, 'Tiger', 'Jungle', 200.0);

SELECT SUM(area) FROM habitat_animals WHERE animal_name = 'Giant Panda';


Question: What is the average home game attendance for the Lakers?

CREATE TABLE teams (team_id INT, team_name VARCHAR(255)); INSERT INTO teams (team_id, team_name) VALUES (1, 'Lakers'); CREATE TABLE venues (venue_id INT, venue_name VARCHAR(255)); INSERT INTO venues (venue_id, venue_name) VALUES (1, 'Staples Center'); CREATE TABLE games (game_id INT, team_id INT, venue_id INT, attendance INT); INSERT INTO games (game_id, team_id, venue_id, attendance) VALUES (1, 1, 1, 10000);

SELECT AVG(games.attendance) FROM games INNER JOIN teams ON games.team_id = teams.team_id INNER JOIN venues ON games.venue_id = venues.venue_id WHERE teams.team_name = 'Lakers' AND venues.venue_name = 'Staples Center';


Question: What is the maximum virtual tour engagement duration in Tokyo, Japan?

CREATE TABLE virtual_tours (tour_id INT, hotel_name VARCHAR(255), city VARCHAR(255), country VARCHAR(255), duration INT); INSERT INTO virtual_tours (tour_id, hotel_name, city, country, duration) VALUES (1, 'Hotel Park Hyatt', 'Tokyo', 'Japan', 240), (2, 'Hotel Imperial', 'Tokyo', 'Japan', 300);

SELECT MAX(duration) FROM virtual_tours WHERE city = 'Tokyo' AND country = 'Japan';


Question: What is the total number of hotels in Brazil that are certified as sustainable?

CREATE TABLE brazil_hotels (name VARCHAR(255), location VARCHAR(255), certification DATE); INSERT INTO brazil_hotels (name, location, certification) VALUES ('Ecohotel Quinta do Buchenau', 'São Paulo, Brazil', '2018-02-14');

SELECT COUNT(*) FROM brazil_hotels WHERE certification IS NOT NULL;


Question: List all employees who have not completed diversity training, along with their hire dates.

CREATE TABLE Employees (EmployeeID INT, HireDate DATETIME, CompletedDiversityTraining BOOLEAN); INSERT INTO Employees (EmployeeID, HireDate, CompletedDiversityTraining) VALUES (1, '2020-01-01', true); INSERT INTO Employees (EmployeeID, HireDate, CompletedDiversityTraining) VALUES (2, '2019-05-15', false);

SELECT EmployeeID, HireDate FROM Employees WHERE CompletedDiversityTraining = false;


Question: Generate PostgreSQL SQL for: What was the result on the wild card?

CREATE TABLE table_name_74 (result VARCHAR, week VARCHAR)

SELECT result FROM table_name_74 WHERE week = 'wild card';


Question: Generate PostgreSQL SQL for: Which years have a Decile of 4, an Authority of state, and a Name of mapiu school?

CREATE TABLE table_name_43 (years VARCHAR, name VARCHAR, decile VARCHAR, authority VARCHAR)

SELECT years FROM table_name_43 WHERE decile = 4 AND authority = 'state' AND name = 'mapiu school';


Question: Generate PostgreSQL SQL for: Which Location has a Method of decision (unanimous), and Res of win x?

CREATE TABLE table_name_99 (location VARCHAR, method VARCHAR, res VARCHAR)

SELECT location FROM table_name_99 WHERE method = 'decision (unanimous)' AND res = 'win x';


Question: What is the maximum number of concerts performed by any artist in a single year?

CREATE TABLE Concerts (ConcertID INT, Title VARCHAR(50), ArtistID INT, Venue VARCHAR(50), Year INT, Revenue INT); INSERT INTO Concerts VALUES (1, 'Jazz Concert', 1, 'New York', 2022, 5000); INSERT INTO Concerts VALUES (2, 'Rock Concert', 2, 'Toronto', 2022, 8000); INSERT INTO Concerts VALUES (3, 'Jazz Concert', 1, 'Chicago', 2022, 6000); INSERT INTO Concerts VALUES (4, 'Pop Concert', 2, 'Montreal', 2021, 7000);

SELECT MAX(C.Performances) FROM (SELECT ArtistID, COUNT(DISTINCT Year) AS Performances FROM Concerts GROUP BY ArtistID) C;


Question: Generate PostgreSQL SQL for: Find all the payment dates for the payments with an amount larger than 10 and the payments handled by a staff person with the first name Elsa.

CREATE TABLE payment (payment_date VARCHAR, staff_id VARCHAR); CREATE TABLE staff (staff_id VARCHAR, first_name VARCHAR); CREATE TABLE payment (payment_date VARCHAR, amount INTEGER)

SELECT payment_date FROM payment WHERE amount > 10 UNION SELECT T1.payment_date FROM payment AS T1 JOIN staff AS T2 ON T1.staff_id = T2.staff_id WHERE T2.first_name = 'Elsa';


Question: What is the moving average of customer orders in the past 7 days?

CREATE TABLE orders(id INT, date DATE, quantity INT); INSERT INTO orders(id, date, quantity) VALUES (1, '2022-05-01', 3), (2, '2022-05-03', 2), (3, '2022-05-05', 5);

SELECT date, AVG(quantity) OVER (ORDER BY date ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) as moving_average FROM orders WHERE date >= CURRENT_DATE - INTERVAL '7 days';


Question: Generate PostgreSQL SQL for: Name the total number of rank for lane 7

CREATE TABLE table_name_69 (rank VARCHAR, lane VARCHAR)

SELECT COUNT(rank) FROM table_name_69 WHERE lane = 7;


Question: Generate PostgreSQL SQL for: What was the nickname of the team in the East Geelong club?

CREATE TABLE table_name_93 (nickname VARCHAR, club VARCHAR)

SELECT nickname FROM table_name_93 WHERE club = 'east geelong';


Question: Generate PostgreSQL SQL for: Show distinct types of artworks that are nominated in festivals in 2007.

CREATE TABLE nomination (Artwork_ID VARCHAR, Festival_ID VARCHAR); CREATE TABLE festival_detail (Festival_ID VARCHAR, Year VARCHAR); CREATE TABLE artwork (Type VARCHAR, Artwork_ID VARCHAR)

SELECT DISTINCT T2.Type FROM nomination AS T1 JOIN artwork AS T2 ON T1.Artwork_ID = T2.Artwork_ID JOIN festival_detail AS T3 ON T1.Festival_ID = T3.Festival_ID WHERE T3.Year = 2007;


Question: What is the average age of construction workers in Texas?

CREATE TABLE construction_workers (id INT, name VARCHAR(50), age INT, state VARCHAR(2)); INSERT INTO construction_workers (id, name, age, state) VALUES (1, 'John Doe', 35, 'Texas'); INSERT INTO construction_workers (id, name, age, state) VALUES (2, 'Jane Smith', 40, 'Texas');

SELECT AVG(age) FROM construction_workers WHERE state = 'Texas';


Question: Generate PostgreSQL SQL for: What is the high lap total for mika salo with a grid greater than 17?

CREATE TABLE table_name_66 (laps INTEGER, driver VARCHAR, grid VARCHAR)

SELECT MAX(laps) FROM table_name_66 WHERE driver = 'mika salo' AND grid > 17;


Question: Generate PostgreSQL SQL for: What was the winning score on Aug 28, 1983?

CREATE TABLE table_name_89 (winning_score VARCHAR, date VARCHAR)

SELECT winning_score FROM table_name_89 WHERE date = 'aug 28, 1983';


Question: pgTAP test for Resultset (assertion 332).

SELECT * FROM check_test(
    bag_has( 'anames', 'subset' ),
    true,
    'bag_has( prepared, subprepared )',
    '',
    ''
);


Question: What is the number of mental health parity violations for each community health worker in the Los Angeles region?

CREATE TABLE community_health_workers (worker_id INT, name TEXT, region TEXT); INSERT INTO community_health_workers (worker_id, name, region) VALUES (1, 'John Doe', 'Los Angeles'), (2, 'Jane Smith', 'New York'); CREATE TABLE mental_health_parity_violations (id INT, worker_id INT, violation_count INT); INSERT INTO mental_health_parity_violations (id, worker_id, violation_count) VALUES (1, 1, 5), (2, 1, 3), (3, 2, 1);

SELECT c.name, m.violation_count FROM community_health_workers c JOIN mental_health_parity_violations m ON c.worker_id = m.worker_id WHERE c.region = 'Los Angeles';


Question: Generate PostgreSQL SQL for: Which episode number in season 5 was viewed by 3.00 million U.S. viziers?

CREATE TABLE table_11820086_1 (no_in_season INTEGER, us_viewers__millions_ VARCHAR)

SELECT MIN(no_in_season) FROM table_11820086_1 WHERE us_viewers__millions_ = '3.00';


Question: pgTAP test for Throwtap (assertion 17).

SELECT * FROM check_test(
    lives_ok( 'EXECUTE livetest'),
    true,
    'lives_ok(execute)'
    '',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Throwtap.


Question: Generate PostgreSQL SQL for: Which 2007 has a 2010 of A?

SELECT 2007 FROM table_name_92 WHERE 2010 = 'a';


Question: Generate PostgreSQL SQL for: Show the most common apartment type code among apartments with more than 1 bathroom.

CREATE TABLE Apartments (apt_type_code VARCHAR, bathroom_count INTEGER)

SELECT apt_type_code FROM Apartments WHERE bathroom_count > 1 GROUP BY apt_type_code ORDER BY COUNT(*) DESC LIMIT 1;


Question: What is the average donation by age group?

CREATE TABLE Donations (ID INT, DonorAge INT, DonationAmount DECIMAL(10,2)); INSERT INTO Donations (ID, DonorAge, DonationAmount) VALUES (1, 25, 50.00), (2, 35, 100.00), (3, 45, 25.00);

SELECT FLOOR(DonorAge/10)*10 AS AgeGroup, AVG(DonationAmount) as AvgDonation FROM Donations GROUP BY AgeGroup;


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

SELECT * FROM test_money WHERE i>='1'::money ORDER BY i;

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


Question: Update the conservation status of the 'Hawaiian monk seal' to 'Endangered' in the 'marine_species' table.

CREATE TABLE marine_species (id INT, name VARCHAR(255), conservation_status VARCHAR(255)); INSERT INTO marine_species (id, name, conservation_status) VALUES (1, 'Pacific salmon', 'Vulnerable'), (2, 'Hawaiian monk seal', 'Threatened'), (3, 'Blue whale', 'Endangered');

UPDATE marine_species SET conservation_status = 'Endangered' WHERE name = 'Hawaisn monk seal';


Question: Update environmental impact score for site 4

CREATE TABLE impact (id INT PRIMARY KEY, site_id INT, impact_score INT);

UPDATE impact SET impact_score = 85 WHERE site_id = 4;


Question: Generate PostgreSQL SQL for: Who was the home team for the match at Stadion pod Vrmcem?

CREATE TABLE table_name_77 (home VARCHAR, venue VARCHAR)

SELECT home FROM table_name_77 WHERE venue = 'stadion pod vrmcem';


Question: List the names of attorneys who have never lost a case.

CREATE TABLE cases (case_id INT, case_outcome VARCHAR(10), attorney_id INT); INSERT INTO cases (case_id, case_outcome, attorney_id) VALUES (1, 'Won', 101), (2, 'Lost', 102), (3, 'Won', 101); CREATE TABLE attorneys (attorney_id INT, attorney_name VARCHAR(20)); INSERT INTO attorneys (attorney_id, attorney_name) VALUES (101, 'Smith'), (102, 'Johnson'), (103, 'Williams');

SELECT a.attorney_name FROM attorneys a LEFT JOIN cases c ON a.attorney_id = c.attorney_id WHERE c.case_outcome IS NULL;


Question: Who are the developers of the smart contract 'Uniswap'?

CREATE TABLE smart_contract_developers (developer_id INT PRIMARY KEY, developer_name TEXT, contract_name TEXT); INSERT INTO smart_contract_developers (developer_id, developer_name, contract_name) VALUES (1, 'Vitalik Buterin', 'Uniswap'), (2, 'Hayden Adams', 'Uniswap');

SELECT developer_name FROM smart_contract_developers WHERE contract_name = 'Uniswap';


Question: Generate PostgreSQL SQL for: How many bronze numbers had a total of more than 4 when the rank is less than four, germany is involved, and there's less than 5 silver?

CREATE TABLE table_name_67 (bronze VARCHAR, silver VARCHAR, nation VARCHAR, total VARCHAR, rank VARCHAR)

SELECT COUNT(bronze) FROM table_name_67 WHERE total > 4 AND rank < 4 AND nation = 'germany' AND silver < 5;


Question: Delete the record with id 1 in the table 'esg_investments'.

CREATE TABLE esg_investments (id INT, country VARCHAR(255), amount FLOAT); INSERT INTO esg_investments (id, country, amount) VALUES (1, 'Canada', 6000000), (2, 'Mexico', 7000000);

DELETE FROM esg_investments WHERE id = 1;


Question: What is the total revenue for each product in the 'seafood_sales' table?

CREATE TABLE seafood_sales (region VARCHAR(255), product VARCHAR(255), revenue DECIMAL(8,2), quantity INT); INSERT INTO seafood_sales (region, product, revenue, quantity) VALUES ('North', 'Tilapia', 1250.00, 500), ('South', 'Salmon', 3500.00, 800), ('North', 'Catfish', 2000.00, 600), ('East', 'Tilapia', 1750.00, 450), ('East', 'Salmon', 3000.00, 700), ('West', 'Tilapia', 2500.00, 550), ('West', 'Catfish', 2200.00, 400), ('South', 'Tilapia', 2750.00, 700);

SELECT product, SUM(revenue) as total_revenue FROM seafood_sales GROUP BY product;


Question: Generate PostgreSQL SQL for: What type was issued in 1964?

CREATE TABLE table_name_1 (type VARCHAR, issued VARCHAR)

SELECT type FROM table_name_1 WHERE issued = 1964;


Question: Generate PostgreSQL SQL for: Name the Player who has a CFL Team of toronto?

CREATE TABLE table_name_24 (player VARCHAR, cfl_team VARCHAR)

SELECT player FROM table_name_24 WHERE cfl_team = 'toronto';


Question: pgTAP test for Ownership (assertion 110).

SELECT * FROM check_test(
    index_owner_is('sometab', 'idx_hey', current_user),
	true,
    'index_owner_is(table, index, user)',
    'Index idx_hey ON sometab should be owned by ' || quote_ident(current_user),
    ''
);


Question: What is the distribution of AI safety incidents by month for the AI subfield of algorithmic fairness in 2021?

CREATE TABLE ai_safety_incidents (incident_id INT, incident_date DATE, ai_subfield TEXT, incident_description TEXT); INSERT INTO ai_safety_incidents (incident_id, incident_date, ai_subfield, incident_description) VALUES (1, '2021-01-05', 'Algorithmic Fairness', 'AI system showed bias against certain groups'); INSERT INTO ai_safety_incidents (incident_id, incident_date, ai_subfield, incident_description) VALUES (2, '2021-03-15', 'Algorithmic Fairness', 'AI system showed disparate impact'); INSERT INTO ai_safety_incidents (incident_id, incident_date, ai_subfield, incident_description) VALUES (3, '2021-04-01', 'Algorithmic Fairness', 'AI system showed bias against certain groups');

SELECT DATE_PART('month', incident_date) as month, COUNT(*) as incidents FROM ai_safety_incidents WHERE incident_date BETWEEN '2021-01-01' AND '2021-12-31' AND ai_subfield = 'Algorithmic Fairness' GROUP BY month;


Question: Generate PostgreSQL SQL for: Who is week 1 if week 3 is Natasha Budhi?

CREATE TABLE table_name_3 (week_1 VARCHAR, week_3 VARCHAR)

SELECT week_1 FROM table_name_3 WHERE week_3 = 'natasha budhi';


Question: Delete all community policing events in district 3 before '2020-01-01'

CREATE TABLE districts (id INT, name VARCHAR(255)); INSERT INTO districts (id, name) VALUES (3, 'Greenhills'); CREATE TABLE community_policing_events (id INT, district_id INT, event_date DATE); INSERT INTO community_policing_events (id, district_id, event_date) VALUES (3001, 3, '2020-01-02'), (3002, 3, '2020-01-03'), (3003, 3, '2019-12-31');

DELETE FROM community_policing_events WHERE event_date < '2020-01-01' AND district_id = 3;


Question: Generate PostgreSQL SQL for: What is Place, when Year is greater than 2006, and when Champion is "Asvel"?

CREATE TABLE table_name_37 (place VARCHAR, year VARCHAR, champion VARCHAR)

SELECT place FROM table_name_37 WHERE year > 2006 AND champion = 'asvel';


Question: List all fans who have not attended any games in the last year

CREATE TABLE fans (fan_id INT, gender VARCHAR(10), last_attended_game DATE); INSERT INTO fans (fan_id, gender, last_attended_game) VALUES (1, 'Male', '2022-02-15'), (2, 'Female', '2022-03-01'), (3, 'Male', '2021-12-31'), (4, 'Female', '2022-01-01'), (5, 'Male', '2022-03-15'), (6, 'Female', NULL);

SELECT * FROM fans WHERE last_attended_game IS NULL;


Question: Generate PostgreSQL SQL for: When did Yugoslavia play a friendly game in Belgrade?

CREATE TABLE table_name_88 (date VARCHAR, city VARCHAR, type_of_game VARCHAR)

SELECT date FROM table_name_88 WHERE city = 'belgrade' AND type_of_game = 'friendly';


Question: List the programs that have a higher total budget compared to the total budget for all programs combined, and their respective budgets.

CREATE TABLE programs(id INT, name TEXT, budget FLOAT);

SELECT programs.name, programs.budget FROM programs WHERE programs.budget > (SELECT SUM(budget) FROM programs) - programs.budget;


Question: How many publications have been made in the Journal of Applied Mathematics by graduate students in the Mathematics department?

CREATE TABLE Students (StudentID INT, FirstName VARCHAR(50), LastName VARCHAR(50), Department VARCHAR(50), Program VARCHAR(50)); CREATE TABLE Publications (PublicationID INT, Title VARCHAR(100), Author VARCHAR(50), Year INT, Journal VARCHAR(50), StudentID INT);

SELECT COUNT(PublicationID) as 'Number of Publications' FROM Publications p JOIN Students s ON p.StudentID = s.StudentID WHERE s.Department = 'Mathematics' AND Journal = 'Journal of Applied Mathematics';


Question: What is the total data usage for postpaid and prepaid customers, sorted by data usage in descending order?

CREATE TABLE mobile_customers (customer_id INT, plan_type VARCHAR(10), data_usage FLOAT, region VARCHAR(20)); INSERT INTO mobile_customers (customer_id, plan_type, data_usage, region) VALUES (1, 'postpaid', 3.5, 'Chicago'), (2, 'prepaid', 2.0, 'Chicago'), (3, 'postpaid', 5.0, 'New York'); CREATE TABLE plan_types (plan_type VARCHAR(10)); INSERT INTO plan_types (plan_type) VALUES ('postpaid'), ('prepaid');

SELECT pt.plan_type, SUM(mc.data_usage) AS total_data_usage FROM mobile_customers mc JOIN plan_types pt ON mc.plan_type = pt.plan_type GROUP BY pt.plan_type ORDER BY total_data_usage DESC;


Question: What is the number of marine species with data on ocean acidification?

CREATE TABLE marine_species (id INT, species_name TEXT, ocean_acidification_data BOOLEAN); INSERT INTO marine_species (id, species_name, ocean_acidification_data) VALUES (1, 'Coral', true); INSERT INTO marine_species (id, species_name, ocean_acidification_data) VALUES (2, 'Humpback Whale', false);

SELECT COUNT(*) FROM marine_species WHERE ocean_acidification_data = true;


Question: Generate PostgreSQL SQL for: Who is the player for south carolina college?

CREATE TABLE table_20871703_1 (player_name VARCHAR, college VARCHAR)

SELECT player_name FROM table_20871703_1 WHERE college = 'South Carolina';


Question: pgTAP test for Ownership (assertion 37).

SELECT * FROM check_test(
    relation_owner_is('__not__apart', current_user, 'mumble'),
	false,
    'relation_owner_is(non-part, user)',
    'mumble',
    '    Relation __not__apart does not exist'
);


Question: What is the total weight of items in the Singapore warehouse?

CREATE TABLE Warehouse (id INT, location VARCHAR(50), quantity INT, weight FLOAT); INSERT INTO Warehouse (id, location, quantity, weight) VALUES (1, 'USA', 300, 12.5), (2, 'Canada', 250, 11.0), (3, 'France', 500, 13.2), (4, 'Germany', 400, 14.7), (5, 'UK', 300, 15.3), (6, 'Japan', 450, 16.1), (7, 'Brazil', 200, 17.5), (8, 'Russia', 600, 18.0), (9, 'Singapore', 150, 20.0);

SELECT SUM(weight) FROM Warehouse WHERE location = 'Singapore';


Question: Generate PostgreSQL SQL for: What is the name of the national final main host when the semi final/heat host shows internal selection in 2011?

CREATE TABLE table_name_83 (national_final_main_host VARCHAR, semi_final_heat_host VARCHAR, year_s_ VARCHAR)

SELECT national_final_main_host FROM table_name_83 WHERE semi_final_heat_host = 'internal selection' AND year_s_ = '2011';


Question: Generate PostgreSQL SQL for: What is the name of the car that was made in the years 1956-1958?

CREATE TABLE table_name_18 (automobile_name VARCHAR, year VARCHAR)

SELECT automobile_name FROM table_name_18 WHERE year = '1956-1958';


Question: Generate PostgreSQL SQL for: What is Geelong's home team score?

CREATE TABLE table_name_89 (home_team VARCHAR)

SELECT home_team AS score FROM table_name_89 WHERE home_team = 'geelong';


Question: Generate PostgreSQL SQL for: What was the earliest year a game was played in Athens?

CREATE TABLE table_name_95 (year INTEGER, location VARCHAR)

SELECT MIN(year) FROM table_name_95 WHERE location = 'athens';


Question: How many public schools in the Education department have a budget over $1,000,000?

CREATE TABLE Education_Dept (ID INT, School_Type VARCHAR(255), Budget FLOAT); INSERT INTO Education_Dept (ID, School_Type, Budget) VALUES (1, 'Public', 1200000), (2, 'Public', 800000), (3, 'Private', 900000);

SELECT COUNT(*) FROM Education_Dept WHERE School_Type = 'Public' AND Budget > 1000000;


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

INSERT INTO result_tbl SELECT * FROM async_pt WHERE b % 100 = 0;

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


Question: Which natural skincare brands in the USA have the highest revenue growth?

CREATE TABLE skincare_revenue (id INT, brand VARCHAR(50), revenue DECIMAL(10,2), year INT, country VARCHAR(50)); INSERT INTO skincare_revenue (id, brand, revenue, year, country) VALUES (1, 'Brand C', 1000.00, 2021, 'USA');

SELECT brand, (revenue - LAG(revenue, 1) OVER (PARTITION BY brand ORDER BY year)) / ABS(LAG(revenue, 1) OVER (PARTITION BY brand ORDER BY year)) * 100.0 AS growth_percentage FROM skincare_revenue WHERE country = 'USA' AND revenue IS NOT NULL GROUP BY brand, revenue, year HAVING growth_percentage IS NOT NULL ORDER BY growth_percentage DESC;


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

CREATE TABLE stxdinh2() INHERITS(stxdinh);

Explanation: DDL from PostgreSQL core regression test for Stats Ext.


Question: Which traditional art types have the most pieces in the database?

CREATE TABLE ArtTypes (ArtTypeID INT, ArtType VARCHAR(50)); CREATE TABLE ArtPieces (ArtPieceID INT, ArtTypeID INT, ArtistID INT, Year INT); INSERT INTO ArtTypes VALUES (1, 'Painting'), (2, 'Sculpture'), (3, 'Textile'), (4, 'Pottery'); INSERT INTO ArtPieces VALUES (1, 1, 1, 2010), (2, 1, 2, 2015), (3, 2, 3, 2005), (4, 2, 4, 2020), (5, 3, 5, 2018), (6, 3, 6, 2021), (7, 4, 7, 2019);

SELECT ArtTypes.ArtType, COUNT(ArtPieces.ArtPieceID) AS ArtPieceCount FROM ArtTypes INNER JOIN ArtPieces ON ArtTypes.ArtTypeID = ArtPieces.ArtTypeID GROUP BY ArtTypes.ArtType ORDER BY ArtPieceCount DESC;


Question: Update the waste generation for plastic in the city of Chicago to 2000 grams in the second quarter of 2021.

CREATE TABLE waste_generation (city VARCHAR(255), quarter INT, material_type VARCHAR(255), generation_grams INT); INSERT INTO waste_generation (city, quarter, material_type, generation_grams) VALUES ('Chicago', 2, 'Plastic', 1800);

UPDATE waste_generation SET generation_grams = 2000 WHERE city = 'Chicago' AND quarter = 2 AND material_type = 'Plastic';


Question: How many solar power projects were implemented in Australia, South Africa, and Egypt between 2016 and 2021?

CREATE TABLE solar_projects_2 (project_id INT, country VARCHAR(50), start_year INT, end_year INT); INSERT INTO solar_projects_2 (project_id, country, start_year, end_year) VALUES (1, 'Australia', 2017, 2021), (2, 'South Africa', 2018, 2020), (3, 'Egypt', 2016, 2019), (4, 'Australia', 2019, 2022), (5, 'South Africa', 2017, 2021), (6, 'Egypt', 2018, 2021), (7, 'Australia', 2016, 2018);

SELECT COUNT(*) FROM solar_projects_2 WHERE country IN ('Australia', 'South Africa', 'Egypt') AND start_year BETWEEN 2016 AND 2021 AND end_year BETWEEN 2016 AND 2021;


Question: Generate PostgreSQL SQL for: what are all the hometown where the average age is 16

CREATE TABLE table_26267849_2 (hometown VARCHAR, age_s_ VARCHAR)

SELECT hometown FROM table_26267849_2 WHERE age_s_ = '16';


Question: Generate PostgreSQL SQL for: How may population figures are given for Settimo Torinese

CREATE TABLE table_1449176_1 (population VARCHAR, common_of VARCHAR)

SELECT COUNT(population) FROM table_1449176_1 WHERE common_of = 'Settimo Torinese';


Question: Generate PostgreSQL SQL for: What was the score of the game with a loss of Maholm (2–4)?

CREATE TABLE table_name_81 (score VARCHAR, loss VARCHAR)

SELECT score FROM table_name_81 WHERE loss = 'maholm (2–4)';


Question: What is the total number of security incidents in the education sector?

CREATE TABLE security_incidents (id INT, sector VARCHAR(20), incident VARCHAR(50)); INSERT INTO security_incidents (id, sector, incident) VALUES (1, 'Education', 'Phishing Attack');

SELECT COUNT(*) FROM security_incidents WHERE sector = 'Education';


Question: PostgreSQL regression test 'box': Write the SELECT query (example 80).

SELECT count(*) FROM quad_box_tbl WHERE b <<| box '((100,200),(300,500))';

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

SELECT count(*) FROM (SELECT count(*) FROM quad_box_tbl WHERE b <<| box '((100,200),(300,500))') AS _sub;


Question: Generate PostgreSQL SQL for: What country was the golfer with a score of 72-72-72=216 representing?

CREATE TABLE table_name_78 (country VARCHAR, score VARCHAR)

SELECT country FROM table_name_78 WHERE score = 72 - 72 - 72 = 216;


Question: Generate PostgreSQL SQL for: Who was the Home captain for the Test match of Australia in England at the Edgbaston Venue?

CREATE TABLE table_name_99 (home_captain VARCHAR, venue VARCHAR)

SELECT home_captain FROM table_name_99 WHERE venue = 'edgbaston';


Question: How many cases were handled by attorneys in the 'New York' office?

CREATE TABLE offices (office_id INT, office_name VARCHAR(20), city VARCHAR(20), state VARCHAR(20)); INSERT INTO offices (office_id, office_name, city, state) VALUES (1, 'Boston', 'Boston', 'MA'), (2, 'New York', 'New York', 'NY'); CREATE TABLE attorneys (attorney_id INT, office_id INT); INSERT INTO attorneys (attorney_id, office_id) VALUES (1, 1), (2, 2); CREATE TABLE cases (case_id INT, attorney_id INT); INSERT INTO cases (case_id, attorney_id) VALUES (1, 1), (2, 2);

SELECT COUNT(*) FROM cases JOIN attorneys ON cases.attorney_id = attorneys.attorney_id JOIN offices ON attorneys.office_id = offices.office_id WHERE offices.city = 'New York';


Question: How many Mars missions were launched by NASA?

CREATE TABLE mars_missions (id INT, name VARCHAR(50), agency VARCHAR(50), year INT); INSERT INTO mars_missions (id, name, agency, year) VALUES (1, 'Mariner 4', 'NASA', 1964); INSERT INTO mars_missions (id, name, agency, year) VALUES (2, 'Viking 1', 'NASA', 1975); INSERT INTO mars_missions (id, name, agency, year) VALUES (3, 'Phoenix', 'NASA', 2007);

SELECT COUNT(*) FROM mars_missions WHERE agency = 'NASA';


Question: Generate PostgreSQL SQL for: How many points does catcat have with more than 2 draws?

CREATE TABLE table_name_21 (points INTEGER, artist VARCHAR, draw VARCHAR)

SELECT AVG(points) FROM table_name_21 WHERE artist = 'catcat' AND draw > 2;


Question: Get the number of items made of recycled materials

CREATE TABLE items (id INT, name VARCHAR(255), material VARCHAR(255)); INSERT INTO items (id, name, material) VALUES (1, 'Jacket', 'recycled polyester'), (2, 'Hat', 'recycled paper'), (3, 'Shirt', 'cotton');

SELECT COUNT(*) FROM items WHERE material LIKE '%recycled%';


Question: What is the total number of electric vehicles by manufacturer, grouped by country, with a count greater than 500?

CREATE TABLE Manufacturers (ManufacturerID INT, ManufacturerName VARCHAR(100), Country VARCHAR(50)); INSERT INTO Manufacturers (ManufacturerID, ManufacturerName, Country) VALUES (1, 'Tesla', 'USA'), (2, 'Nissan', 'Japan'), (3, 'BMW', 'Germany'); CREATE TABLE ElectricVehicles (EVID INT, ManufacturerID INT, Model VARCHAR(50), Year INT); INSERT INTO ElectricVehicles (EVID, ManufacturerID, Model, Year) VALUES (1, 1, 'Model S', 2012), (2, 1, 'Model 3', 2017), (3, 2, 'Leaf', 2010), (4, 3, 'i3', 2013);

SELECT Country, ManufacturerName, COUNT(*) as Total FROM ElectricVehicles EV JOIN Manufacturers M ON EV.ManufacturerID = M.ManufacturerID GROUP BY Country, ManufacturerName HAVING COUNT(*) > 500;


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


Question: Generate PostgreSQL SQL for: Which League from has a Player of louis domingue?

CREATE TABLE table_name_48 (league_from VARCHAR, player VARCHAR)

SELECT league_from FROM table_name_48 WHERE player = 'louis domingue';


Question: List the total number of workouts and unique members who participated in CrossFit classes in the last month.

CREATE TABLE workouts (id INT, member_id INT, workout_type VARCHAR(20), workout_date DATE);

SELECT COUNT(DISTINCT id) as total_members, COUNT(*) as total_workouts FROM workouts WHERE workout_type = 'CrossFit' AND workout_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH);


Question: Which retailers are located in countries that import garments from suppliers located in Africa?

CREATE TABLE supplier_garments (supplier_id INT, garment_id INT); INSERT INTO supplier_garments (supplier_id, garment_id) VALUES (1, 1); INSERT INTO supplier_garments (supplier_id, garment_id) VALUES (2, 2);

SELECT retailers.name FROM retailers JOIN countries ON retailers.country = countries.name JOIN imports ON countries.code = imports.destination_country WHERE imports.source_continent = 'Africa';


Question: What is the number of animals in the 'community_education' table that belong to endangered species?

CREATE TABLE community_education (id INT, animal_name VARCHAR(50)); CREATE TABLE endangered_species (id INT, animal_name VARCHAR(50), endangered_status VARCHAR(50));

SELECT COUNT(*) FROM community_education ce INNER JOIN endangered_species es ON ce.animal_name = es.animal_name WHERE endangered_status = 'Endangered';


Question: Generate PostgreSQL SQL for: Tell me the sum of yards for jason campbell and long less than 23

CREATE TABLE table_name_29 (yards INTEGER, player VARCHAR, long VARCHAR)

SELECT SUM(yards) FROM table_name_29 WHERE player = 'jason campbell' AND long < 23;


Question: Generate PostgreSQL SQL for: Who was the opponent on September 8?

CREATE TABLE table_name_24 (opponent VARCHAR, date VARCHAR)

SELECT opponent FROM table_name_24 WHERE date = 'september 8';


Question: Insert a new record into the design_standards table with the name 'Bridge Building Standard' and description 'Standard for building bridges' for the region 'North America'

CREATE TABLE design_standards (id INT PRIMARY KEY, standard_name VARCHAR(255), description TEXT, region VARCHAR(255)); INSERT INTO design_standards (id, standard_name, description, region) VALUES (1, 'Highway Design Standard', 'Standard for designing highways', 'North America'); INSERT INTO design_standards (id, standard_name, description, region) VALUES (2, 'Railway Design Standard', 'Standard for designing railways', 'Europe');

INSERT INTO design_standards (standard_name, description, region) VALUES ('Bridge Building Standard', 'Standard for building bridges', 'North America');


Question: Generate PostgreSQL SQL for: What is the Week of the game against Green Bay Packers?

CREATE TABLE table_name_71 (week INTEGER, opponent VARCHAR)

SELECT AVG(week) FROM table_name_71 WHERE opponent = 'green bay packers';


Question: Generate PostgreSQL SQL for: What is the current status of the person named Nicholls?

CREATE TABLE table_name_65 (status VARCHAR, name VARCHAR)

SELECT status FROM table_name_65 WHERE name = 'nicholls';


Question: Find the title and genre of the bottom 2 movies with the lowest ratings from studios based in France, ordered by ratings in ascending order.

CREATE TABLE movies (title VARCHAR(255), genre VARCHAR(255), studio VARCHAR(255), rating FLOAT); INSERT INTO movies (title, genre, studio, rating) VALUES ('Movie7', 'Action', 'France Studio1', 6.5), ('Movie8', 'Drama', 'France Studio2', 5.0);

SELECT title, genre FROM (SELECT title, genre, studio, rating, ROW_NUMBER() OVER (PARTITION BY studio ORDER BY rating ASC) as rank FROM movies WHERE studio LIKE '%France%') subquery WHERE rank <= 2 ORDER BY rating ASC;


Question: Generate PostgreSQL SQL for: For engines of Maserati Straight-6 and entrants of H H Gould, what is the latest year?

CREATE TABLE table_name_14 (year INTEGER, engine VARCHAR, entrant VARCHAR)

SELECT MAX(year) FROM table_name_14 WHERE engine = 'maserati straight-6' AND entrant = 'h h gould';


Question: What is the total number of blocks by the Hawks' Trae Young in the 2016-2017 season?

CREATE TABLE teams (team_name VARCHAR(255), season_start_year INT, season_end_year INT); INSERT INTO teams (team_name, season_start_year, season_end_year) VALUES ('Hawks', 2016, 2017); CREATE TABLE players (player_name VARCHAR(255), team_name VARCHAR(255), blocks INT);

SELECT SUM(blocks) FROM players WHERE player_name = 'Trae Young' AND team_name = 'Hawks' AND season_start_year = 2016 AND season_end_year = 2017;


Question: Generate PostgreSQL SQL for: When was Montreal a visitor?

CREATE TABLE table_name_34 (date VARCHAR, visitor VARCHAR)

SELECT date FROM table_name_34 WHERE visitor = 'montreal';


Question: Generate PostgreSQL SQL for: Is the right halfback player a starter?

CREATE TABLE table_25517718_3 (starter VARCHAR, position VARCHAR)

SELECT starter FROM table_25517718_3 WHERE position = 'Right halfback';


Question: List all projects with a start date on or after 2022-07-01

CREATE TABLE project_timeline (project_id INT, start_date DATE, end_date DATE);

SELECT * FROM project_timeline WHERE start_date >= '2022-07-01';


Question: Generate PostgreSQL SQL for: What was the result when Dundee were the Opponent at Venue A on 6 September 1986?

CREATE TABLE table_name_9 (result VARCHAR, date VARCHAR, opponent VARCHAR, venue VARCHAR)

SELECT result FROM table_name_9 WHERE opponent = 'dundee' AND venue = 'a' AND date = '6 september 1986';