Question: What is the total energy production by renewable source in Canada for the month of January 2022?

CREATE TABLE energy_production (id INT, country VARCHAR(50), source VARCHAR(50), production FLOAT, timestamp TIMESTAMP); INSERT INTO energy_production (id, country, source, production, timestamp) VALUES (1, 'Canada', 'Wind', 500.2, '2022-01-01 10:00:00'), (2, 'Canada', 'Solar', 700.3, '2022-01-02 15:00:00');

SELECT source, SUM(production) as total_production FROM energy_production WHERE country = 'Canada' AND timestamp BETWEEN '2022-01-01 00:00:00' AND '2022-01-31 23:59:59' AND source IN ('Wind', 'Solar') GROUP BY source;


Question: Generate PostgreSQL SQL for: What driver won the VII Rand Grand Prix?

CREATE TABLE table_name_26 (winning_driver VARCHAR, race_name VARCHAR)

SELECT winning_driver FROM table_name_26 WHERE race_name = 'vii rand grand prix';


Question: Generate PostgreSQL SQL for: How many tries did the club with a try bonus of correct as of 2 June 2009 have?

CREATE TABLE table_name_45 (tries_for VARCHAR, try_bonus VARCHAR)

SELECT tries_for FROM table_name_45 WHERE try_bonus = 'correct as of 2 june 2009';


Question: What are the names of customers who have invested in the technology sector but not in the healthcare sector?

CREATE TABLE Customers (CustomerID INT, Name VARCHAR(50));CREATE TABLE Investments (CustomerID INT, InvestmentType VARCHAR(10), Sector VARCHAR(10));INSERT INTO Customers VALUES (1,'John Doe'),(2,'Jane Smith'),(3,'Bob Johnson');INSERT INTO Investments VALUES (1,'Stocks','Technology'),(1,'Stocks','Healthcare'),(2,'Stocks','Technology'),(3,'Stocks','Healthcare');

SELECT DISTINCT c.Name FROM Customers c INNER JOIN Investments i ON c.CustomerID = i.CustomerID WHERE i.Sector = 'Technology' AND c.CustomerID NOT IN (SELECT CustomerID FROM Investments WHERE Sector = 'Healthcare');


Question: What is the total quantity of recycled materials in stock?

CREATE TABLE materials (id INT, name TEXT, recycled BOOLEAN); CREATE TABLE inventory (id INT, material_id INT, quantity INT); INSERT INTO materials (id, name, recycled) VALUES (1, 'Material A', true), (2, 'Material B', false), (3, 'Material C', true); INSERT INTO inventory (id, material_id, quantity) VALUES (1, 1, 50), (2, 2, 80), (3, 3, 100);

SELECT SUM(inventory.quantity) FROM inventory INNER JOIN materials ON inventory.material_id = materials.id WHERE materials.recycled = true;


Question: How many local vendors have participated in sustainable events in Spain?

CREATE TABLE LocalVendors (VendorID INT, Country VARCHAR(50), Events INT); INSERT INTO LocalVendors (VendorID, Country, Events) VALUES (1, 'Spain', 3), (2, 'Spain', 2);

SELECT SUM(Events) FROM LocalVendors WHERE Country = 'Spain';


Question: Identify co-owned properties in New York City with sustainable urbanism certifications that were sold in the past six months, and list their names, addresses, and the names of their co-owners.

CREATE TABLE properties (property_id INT, name VARCHAR(255), address VARCHAR(255), city VARCHAR(255), sustainable_urbanism_certified BOOLEAN, sold_date DATE); CREATE TABLE co_owners (property_id INT, owner_name VARCHAR(255)); INSERT INTO properties (property_id, name, address, city, sustainable_urbanism_certified, sold_date) VALUES (1, 'Green Living', '123 Main St', 'New York', true, '2022-03-15'), (2, 'Eco Haven', '456 Oak St', 'New York', false, '2022-01-01'), (3, 'Sustainable Suites', '789 Pine St', 'New York', true, NULL); INSERT INTO co_owners (property_id, owner_name) VALUES (1, 'Alice'), (1, 'Bob'), (2, 'Charlie'), (3, 'Dave');

SELECT p.name, p.address, co.owner_name FROM properties p JOIN co_owners co ON p.property_id = co.property_id WHERE p.city = 'New York' AND p.sustainable_urbanism_certified = true AND p.sold_date >= DATEADD(month, -6, GETDATE());


Question: Generate PostgreSQL SQL for: when points against was 387 what was the lost?

CREATE TABLE table_name_8 (lost VARCHAR, points_against VARCHAR)

SELECT lost FROM table_name_8 WHERE points_against = '387';


Question: What is the average order value per customer by country?

CREATE TABLE Customers (CustomerID INT, CustomerName VARCHAR(50), Country VARCHAR(50)); INSERT INTO Customers VALUES (1, 'John Smith', 'USA'), (2, 'Jane Doe', 'Canada'); CREATE TABLE Orders (OrderID INT, CustomerID INT, OrderValue DECIMAL(10,2)); INSERT INTO Orders VALUES (1, 1, 50.00), (2, 1, 75.00), (3, 2, 100.00);

SELECT Country, AVG(OrderValue) as AvgOrderValue FROM Orders o JOIN Customers c ON o.CustomerID = c.CustomerID GROUP BY Country;


Question: Generate PostgreSQL SQL for: How many bronzes have 1 as the total, with spain (esp) as the nation, and a gold greater than 0?

CREATE TABLE table_name_31 (bronze VARCHAR, gold VARCHAR, total VARCHAR, nation VARCHAR)

SELECT COUNT(bronze) FROM table_name_31 WHERE total = 1 AND nation = 'spain (esp)' AND gold > 0;


Question: What is the total investment in renewable energy sector for the year 2021?

CREATE TABLE investments (id INT PRIMARY KEY, investor_id INT, nonprofit_id INT, amount DECIMAL(10,2), investment_date DATE); INSERT INTO investments (id, investor_id, nonprofit_id, amount, investment_date) VALUES (1, 1, 3, 1500.00, '2021-03-01'), (2, 2, 4, 2000.00, '2021-05-01'), (3, 3, 5, 1000.00, '2021-09-01'), (4, 4, 3, 2500.00, '2021-12-01'); CREATE TABLE nonprofits (id INT PRIMARY KEY, name VARCHAR(255), location VARCHAR(255), sector VARCHAR(255)); INSERT INTO nonprofits (id, name, location, sector) VALUES (3, 'Greenpeace', 'Germany', 'Renewable Energy'), (4, 'SolarAid', 'UK', 'Renewable Energy'), (5, 'WindAid', 'Peru', 'Renewable Energy');

SELECT SUM(amount) FROM investments i JOIN nonprofits n ON i.nonprofit_id = n.id WHERE n.sector = 'Renewable Energy' AND DATE_PART('year', investment_date) = 2021;


Question: Generate PostgreSQL SQL for: What is the highest earnings for the golfer who has more than 37 wins?

CREATE TABLE table_name_90 (earnings___ INTEGER, wins INTEGER)

SELECT MAX(earnings___) AS $__ FROM table_name_90 WHERE wins > 37;


Question: Write the DDL statement from PostgreSQL regression test 'publication' (example 639).

CREATE PUBLICATION pub FOR TABLE sch2.tbl1_part1 WITH (PUBLISH_VIA_PARTITION_ROOT=1);

Explanation: DDL from PostgreSQL core regression test for Publication.


Question: pgTAP test for Resultset (assertion 72).

INSERT INTO names (name) VALUES ('Jack');

Explanation: SQL assertion from pgTAP test suite for Resultset.


Question: What is the average cost of cybersecurity strategies for each sector in 2019?

CREATE TABLE cybersecurity_strategies (id INT PRIMARY KEY, strategy VARCHAR(50), cost INT, sector VARCHAR(50), year INT); INSERT INTO cybersecurity_strategies (id, strategy, cost, sector, year) VALUES (5, 'Encryption', 75000, 'Public', 2019); INSERT INTO cybersecurity_strategies (id, strategy, cost, sector, year) VALUES (6, 'Intrusion Prevention Systems', 120000, 'Private', 2019);

SELECT sector, AVG(cost) as avg_cost FROM cybersecurity_strategies WHERE year = 2019 GROUP BY sector;


Question: Generate PostgreSQL SQL for: What wast the percent cut for the nation with an 80% full gas storage?

CREATE TABLE table_21690339_1 (_percentage_cut VARCHAR, gas_storage VARCHAR)

SELECT _percentage_cut FROM table_21690339_1 WHERE gas_storage = '80% full';


Question: Which species have experienced a decrease in dissolved oxygen levels compared to the previous day in brackish water farms?

CREATE TABLE daily_oxygen_levels_brackish (farm_id INT, date DATE, species VARCHAR(20), dissolved_oxygen FLOAT); INSERT INTO daily_oxygen_levels_brackish (farm_id, date, species, dissolved_oxygen) VALUES (1, '2022-01-01', 'Tilapia', 5.5), (1, '2022-01-02', 'Tilapia', 5.3), (2, '2022-01-01', 'Barramundi', 6.0), (2, '2022-01-02', 'Barramundi', 5.8);

SELECT species, date, dissolved_oxygen, LAG(dissolved_oxygen) OVER (PARTITION BY species ORDER BY date) prev_dissolved_oxygen, dissolved_oxygen - LAG(dissolved_oxygen) OVER (PARTITION BY species ORDER BY date) diff FROM daily_oxygen_levels_brackish WHERE diff < 0;


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

select count(*) from test_range_spgist where ir -|- int4range(100,500);

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

SELECT count(*) FROM (select count(*) from test_range_spgist where ir -|- int4range(100,500)) AS _sub;


Question: Generate PostgreSQL SQL for: Which run 2 with final of 5:24.47?

CREATE TABLE table_name_18 (run_2 VARCHAR, final VARCHAR)

SELECT run_2 FROM table_name_18 WHERE final = '5:24.47';


Question: What is the distribution of article categories by gender?

CREATE TABLE article_categories (title text, category text, author_gender text); INSERT INTO article_categories (title, category, author_gender) VALUES ('Article 7', 'politics', 'Female'); INSERT INTO article_categories (title, category, author_gender) VALUES ('Article 8', 'sports', 'Male');

SELECT author_gender, category, COUNT(*) as count FROM article_categories GROUP BY author_gender, category;


Question: Which mobile devices in the state of Illinois have more than 1000 prepaid subscribers?

CREATE TABLE mobile_devices (device_id INT, device_name VARCHAR(50), mobile_services INT, state VARCHAR(20));

SELECT device_name FROM mobile_devices WHERE state = 'Illinois' AND mobile_services = (SELECT mobile_services FROM mobile_customers WHERE plan_type = 'prepaid' GROUP BY mobile_services HAVING COUNT(*) > 1000) GROUP BY device_name HAVING COUNT(*) > 1000;


Question: Generate PostgreSQL SQL for: Name the total number of party for willis alston (j) 93.9% george e. spruill 6.1%

CREATE TABLE table_2668243_18 (party VARCHAR, candidates VARCHAR)

SELECT COUNT(party) FROM table_2668243_18 WHERE candidates = 'Willis Alston (J) 93.9% George E. Spruill 6.1%';


Question: Generate PostgreSQL SQL for: Which webcast was in Spanish contemporary on xhnoe.com?

CREATE TABLE table_name_86 (webcast VARCHAR, format VARCHAR, website VARCHAR)

SELECT webcast FROM table_name_86 WHERE format = 'spanish contemporary' AND website = 'xhnoe.com';


Question: Which ingredients are used in products that have received a safety violation in the past year and are not cruelty-free certified?

CREATE TABLE products (product_id INT, product_name TEXT, is_cruelty_free BOOLEAN); CREATE TABLE ingredient_sources (ingredient_id INT, product_id INT, source_country TEXT); CREATE TABLE safety_records (record_id INT, product_id INT, violation_date DATE);

SELECT ingredient_sources.ingredient_id FROM ingredient_sources INNER JOIN products ON ingredient_sources.product_id = products.product_id INNER JOIN safety_records ON products.product_id = safety_records.product_id WHERE safety_records.violation_date >= NOW() - INTERVAL '1 year' AND products.is_cruelty_free = FALSE;


Question: Find the maximum loading capacity for vessels in the 'Passenger' category

CREATE TABLE Vessels (VesselID INT, Category VARCHAR(50), LoadingCapacity FLOAT); INSERT INTO Vessels (VesselID, Category, LoadingCapacity) VALUES (1, 'Cargo', 60000), (2, 'Passenger', 3500), (3, 'Cargo', 45000), (4, 'Passenger', 2800);

SELECT MAX(LoadingCapacity) FROM Vessels WHERE Category = 'Passenger';


Question: What is the average number of volunteers per program in H2 2022?

CREATE TABLE Volunteers (id INT, program_id INT, volunteer_date DATE); INSERT INTO Volunteers (id, program_id, volunteer_date) VALUES (1, 601, '2022-07-10'); INSERT INTO Volunteers (id, program_id, volunteer_date) VALUES (2, 602, '2022-10-15'); INSERT INTO Volunteers (id, program_id, volunteer_date) VALUES (3, 601, '2022-09-15');

SELECT AVG(number_of_volunteers) FROM (SELECT program_id, COUNT(DISTINCT user_id) as number_of_volunteers FROM Volunteers WHERE volunteer_date >= '2022-07-01' AND volunteer_date < '2023-01-01' GROUP BY program_id) as subquery;


Question: What is the percentage of accessible technology patents in Europe?

CREATE TABLE tech_patents (location VARCHAR(255), is_accessible BOOLEAN); INSERT INTO tech_patents (location, is_accessible) VALUES ('Germany', true), ('France', false), ('UK', true);

SELECT location, COUNT(*) * 100.0 / SUM(COUNT(*)) OVER () as percentage_accessible FROM tech_patents WHERE location LIKE 'Europe%' AND is_accessible = true GROUP BY location;


Question: Generate PostgreSQL SQL for: Where was mlb draft for the player who's school was Carl Albert High School?

CREATE TABLE table_11677100_18 (mlb_draft VARCHAR, school VARCHAR)

SELECT mlb_draft FROM table_11677100_18 WHERE school = 'Carl Albert High school';


Question: Generate PostgreSQL SQL for: When was outgoing manager Zoltán Varga appointed?

CREATE TABLE table_name_77 (date_of_appointment VARCHAR, outgoing_manager VARCHAR)

SELECT date_of_appointment FROM table_name_77 WHERE outgoing_manager = 'zoltán varga';


Question: What is the maximum salary for workers in the 'construction_database' database who are members of a union?

CREATE TABLE builders (id INT, name VARCHAR(50), salary DECIMAL(10, 2), is_union_member BOOLEAN); INSERT INTO builders (id, name, salary, is_union_member) VALUES (1, 'Mia', 80000.00, true), (2, 'Max', 85000.00, true), (3, 'Mel', 90000.00, true);

SELECT MAX(salary) FROM builders WHERE is_union_member = true;


Question: Generate PostgreSQL SQL for: How much does number 26 weigh?

CREATE TABLE table_name_31 (weight VARCHAR, number VARCHAR)

SELECT weight FROM table_name_31 WHERE number = '26';


Question: Delete all records of pollution data in the Mariana Trench.

CREATE TABLE pollution_data (location TEXT, pollution_level INTEGER); INSERT INTO pollution_data (location, pollution_level) VALUES ('Mariana Trench', 3); INSERT INTO pollution_data (location, pollution_level) VALUES ('Atlantic Ocean', 2);

DELETE FROM pollution_data WHERE location = 'Mariana Trench';


Question: What is the total duration of classical music pieces longer than 15 minutes?

CREATE TABLE compositions (id INT, title VARCHAR(255), genre VARCHAR(255), duration INT); INSERT INTO compositions (id, title, genre, duration) VALUES (1, 'Symphony No. 5', 'Classical', 30), (2, 'Piano Concerto No. 21', 'Classical', 25), (3, 'The Four Seasons', 'Classical', 40), (4, 'Requiem Mass in D minor', 'Classical', 90), (5, 'The Planets', 'Classical', 60);

SELECT SUM(duration) FROM compositions WHERE genre = 'Classical' AND duration > 15;


Question: Generate PostgreSQL SQL for: Which date did Chris Duhon (13) receive high assists?

CREATE TABLE table_17060277_6 (date VARCHAR, high_assists VARCHAR)

SELECT date FROM table_17060277_6 WHERE high_assists = 'Chris Duhon (13)';


Question: List the names of all drugs that were approved by the TGA and have a sales figure greater than $50 million.

CREATE TABLE drug (id INT, name TEXT, approval_authority TEXT, sales FLOAT); INSERT INTO drug (id, name, approval_authority, sales) VALUES (1, 'DrugA', 'TGA', 60000000); INSERT INTO drug (id, name, approval_authority, sales) VALUES (2, 'DrugB', 'FDA', 40000000); INSERT INTO drug (id, name, approval_authority, sales) VALUES (3, 'DrugC', 'TGA', 55000000); INSERT INTO drug (id, name, approval_authority, sales) VALUES (4, 'DrugD', 'EMA', 45000000);

SELECT name FROM drug WHERE approval_authority = 'TGA' AND sales > 50000000;


Question: Generate PostgreSQL SQL for: How many companies operates airlines in each airport?

CREATE TABLE airport (id VARCHAR); CREATE TABLE flight (Id VARCHAR); CREATE TABLE operate_company (id VARCHAR)

SELECT T3.id, COUNT(*) FROM operate_company AS T1 JOIN flight AS t2 ON T1.id = T2.company_id JOIN airport AS T3 ON T2.airport_id = T3.id GROUP BY T3.id;


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

SELECT * FROM test_float8 WHERE i<1::float4 ORDER BY i;

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


Question: Generate PostgreSQL SQL for: What was the position in 1999?

CREATE TABLE table_name_58 (position VARCHAR, years VARCHAR)

SELECT position FROM table_name_58 WHERE years = '1999';


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

select jsonb_path_query('true', '$.integer()', silent => true);

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

SELECT count(*) FROM (select jsonb_path_query('true', '$.integer()', silent => true)) AS _sub;


Question: How many animals were admitted to the rehabilitation center in June 2021?

CREATE TABLE rehab_center (animal_id INT, admission_date DATE); INSERT INTO rehab_center (animal_id, admission_date) VALUES (1, '2021-06-01'), (2, '2021-06-15'), (3, '2021-06-27');

SELECT COUNT(*) FROM rehab_center WHERE admission_date BETWEEN '2021-06-01' AND '2021-06-30';


Question: Generate PostgreSQL SQL for: what is the area when the census ranking is 2,290 of 5,008?

CREATE TABLE table_name_49 (area_km_2 VARCHAR, census_ranking VARCHAR)

SELECT area_km_2 FROM table_name_49 WHERE census_ranking = '2,290 of 5,008';


Question: What are the names and launch dates of Mars rovers?

CREATE TABLE mars_rovers(rover_name TEXT, launch_date DATE); INSERT INTO mars_rovers (rover_name, launch_date) VALUES ('Sojourner', '1996-12-04'), ('Spirit', '2003-06-10'), ('Opportunity', '2003-07-07');

SELECT rover_name, launch_date FROM mars_rovers;


Question: Generate PostgreSQL SQL for: What was the date that the st. george-illawarra dragons lost?

CREATE TABLE table_11236195_5 (grand_finaldate VARCHAR, losingteam VARCHAR)

SELECT grand_finaldate FROM table_11236195_5 WHERE losingteam = 'St. George-Illawarra Dragons';


Question: How many renewable energy facilities are located in the Asia-Pacific region, and what is their total capacity in MW?

CREATE TABLE renewable_facilities (region VARCHAR(50), capacity NUMERIC, technology VARCHAR(50)); INSERT INTO renewable_facilities (region, capacity, technology) VALUES ('Asia-Pacific', 500, 'Solar'), ('Asia-Pacific', 600, 'Wind'), ('Europe', 400, 'Hydro'), ('Africa', 300, 'Geothermal');

SELECT region, SUM(capacity) as total_capacity FROM renewable_facilities WHERE region = 'Asia-Pacific' GROUP BY region;


Question: Generate PostgreSQL SQL for: How many episodes directed by ben jones and written by paul dini?

CREATE TABLE table_20360535_3 (no VARCHAR, directed_by VARCHAR, written_by VARCHAR)

SELECT COUNT(no) FROM table_20360535_3 WHERE directed_by = 'Ben Jones' AND written_by = 'Paul Dini';


Question: Generate PostgreSQL SQL for: Which Yards has a Long smaller than 3?

CREATE TABLE table_name_2 (yards INTEGER, long INTEGER)

SELECT AVG(yards) FROM table_name_2 WHERE long < 3;


Question: Generate PostgreSQL SQL for: During what years did the Guard from Oklahoma with a height of 6-6 play for the Rockets?

CREATE TABLE table_name_41 (years_for_rockets VARCHAR, school_club_team_country VARCHAR, height_in_ft VARCHAR, position VARCHAR)

SELECT years_for_rockets FROM table_name_41 WHERE height_in_ft = '6-6' AND position = 'guard' AND school_club_team_country = 'oklahoma';


Question: What is the total budget for each type of infrastructure project in the transportation division?

CREATE TABLE transportation_projects (id INT, name VARCHAR(50), type VARCHAR(50), budget FLOAT); INSERT INTO transportation_projects (id, name, type, budget) VALUES (1, 'Road', 'Construction', 20000000), (2, 'Highway', 'Construction', 50000000), (3, 'Bridge', 'Construction', 35000000), (4, 'Tunnel', 'Construction', 40000000);

SELECT type, SUM(budget) FROM transportation_projects WHERE division = 'Transportation' GROUP BY type;


Question: Generate PostgreSQL SQL for: What number of party had a candidate  resigned when appointed judge democratic hold?

CREATE TABLE table_1342013_31 (party VARCHAR, result VARCHAR)

SELECT COUNT(party) FROM table_1342013_31 WHERE result = 'Resigned when appointed judge Democratic hold';


Question: What is the average claim amount for policies with a duration greater than 1 year?

CREATE TABLE Claims (PolicyID int, ClaimAmount int, PolicyDuration int); INSERT INTO Claims (PolicyID, ClaimAmount, PolicyDuration) VALUES (1, 500, 18), (2, 2000, 3), (3, 800, 24), (4, 1500, 12);

SELECT AVG(ClaimAmount) OVER (ORDER BY ROW_NUMBER() OVER (ORDER BY PolicyDuration DESC)) as AvgClaimAmount FROM Claims WHERE PolicyDuration > 12;


Question: Generate PostgreSQL SQL for: What is the Attendance with a Date that is october 31, 1965?

CREATE TABLE table_name_15 (attendance VARCHAR, date VARCHAR)

SELECT attendance FROM table_name_15 WHERE date = 'october 31, 1965';


Question: Identify the total quantity of dairy products supplied by each supplier in the last month?

CREATE TABLE Suppliers(SupplierID INT, Name VARCHAR(50), Type VARCHAR(50));CREATE TABLE DairyProducts(ProductID INT, SupplierID INT, ProductName VARCHAR(50), Quantity INT, DeliveryDate DATE);INSERT INTO Suppliers VALUES (1, 'Dairy Direct', 'Dairy Supplier'), (2, 'Farm Fresh', 'Dairy Supplier'), (3, 'Fruitful', 'Fruit Supplier');INSERT INTO DairyProducts VALUES (1, 1, 'Milk', 200, '2022-05-15'), (2, 1, 'Cheese', 300, '2022-05-01'), (3, 2, 'Butter', 500, '2022-04-20'), (4, 3, 'Apples', 400, '2022-05-10');

SELECT s.Name, SUM(dp.Quantity) FROM Suppliers s JOIN DairyProducts dp ON s.SupplierID = dp.SupplierID WHERE dp.DeliveryDate >= DATEADD(month, -1, GETDATE()) AND s.Type = 'Dairy Supplier' GROUP BY s.Name;


Question: What is the number of marine species, grouped by conservation status?

CREATE TABLE marine_species (id INT, species VARCHAR(255), conservation_status VARCHAR(255)); INSERT INTO marine_species (id, species, conservation_status) VALUES (1, 'Blue Whale', 'Endangered'); INSERT INTO marine_species (id, species, conservation_status) VALUES (2, 'Green Sea Turtle', 'Vulnerable'); INSERT INTO marine_species (id, species, conservation_status) VALUES (3, 'Clownfish', 'Least Concern');

SELECT conservation_status, COUNT(*) FROM marine_species GROUP BY conservation_status;


Question: What is the minimum capacity of hospitals in the 'global_health' schema?

CREATE SCHEMA global_health; CREATE TABLE hospitals (id INT, name TEXT, location TEXT, capacity INT); INSERT INTO global_health.hospitals (id, name, location, capacity) VALUES (1, 'Hospital A', 'City A', 200), (2, 'Hospital B', 'City B', 300), (3, 'Hospital C', 'City C', 150), (4, 'Hospital D', 'City D', 250), (5, 'Hospital E', 'City E', 400);

SELECT MIN(capacity) FROM global_health.hospitals;


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

SELECT regexp_replace(with_nul, '^caf(.)$', '\1') FROM regress_encoding;

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

SELECT count(*) FROM (SELECT regexp_replace(with_nul, '^caf(.)$', '\1') FROM regress_encoding) AS _sub;


Question: Generate PostgreSQL SQL for: When columbia, south carolina is the hometown what is the lowest age?

CREATE TABLE table_1859855_2 (age INTEGER, hometown VARCHAR)

SELECT MIN(age) FROM table_1859855_2 WHERE hometown = 'Columbia, South Carolina';


Question: Generate PostgreSQL SQL for: What is the FY2008 $mil value associated with a FY2007 $mil value of exactly $120?

CREATE TABLE table_25438110_5 (fy08_$millions VARCHAR, fy07_$millions VARCHAR)

SELECT fy08_$millions FROM table_25438110_5 WHERE fy07_$millions = '$120';


Question: Generate PostgreSQL SQL for: How many different players does the Washington Redskins have?

CREATE TABLE table_27132791_3 (player VARCHAR, nfl_team VARCHAR)

SELECT COUNT(player) FROM table_27132791_3 WHERE nfl_team = 'Washington Redskins';


Question: Find the number of Influenza cases reported in South America in 2020.

CREATE TABLE FluData (Year INT, Region VARCHAR(20), Cases INT); INSERT INTO FluData (Year, Region, Cases) VALUES (2018, 'North America', 5000); INSERT INTO FluData (Year, Region, Cases) VALUES (2020, 'South America', 3000);

SELECT SUM(Cases) FROM FluData WHERE Region = 'South America' AND Year = 2020;


Question: Generate PostgreSQL SQL for: List title of albums have the number of tracks greater than 10.

CREATE TABLE tracks (album_id VARCHAR); CREATE TABLE albums (title VARCHAR, id VARCHAR)

SELECT T1.title FROM albums AS T1 JOIN tracks AS T2 ON T1.id = T2.album_id GROUP BY T1.id HAVING COUNT(T1.id) > 10;


Question: Generate PostgreSQL SQL for: What was Mark Begich polling on October 6, 2008?

CREATE TABLE table_16751596_13 (democrat VARCHAR, dates_administered VARCHAR)

SELECT democrat AS :_mark_begich FROM table_16751596_13 WHERE dates_administered = 'October 6, 2008';


Question: Generate PostgreSQL SQL for: What is the percentage listed for the team who scored 63 points?

CREATE TABLE table_26200568_16 (percentage VARCHAR, points_for VARCHAR)

SELECT percentage FROM table_26200568_16 WHERE points_for = 63;


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

UPDATE temporal_rng SET valid_at = daterange('2016-01-01', '2016-02-01') WHERE id = '[5,6)';

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


Question: PostgreSQL Plpgsql: show example 26.

CREATE FUNCTION get_userid(username text) RETURNS int AS $$ #print_strict_params on DECLARE userid int; BEGIN SELECT users.userid INTO STRICT userid FROM users WHERE users.username = get_userid.username; RETURN userid; END; $$ LANGUAGE plpgsql;

Explanation: Example from PostgreSQL documentation on Plpgsql.


Question: What is the correlation between the number of social media shares and the length of news articles?

CREATE TABLE articles (id INT, title VARCHAR(100), word_count INT, social_media_shares INT);

SELECT CORR(word_count, social_media_shares) FROM articles;


Question: Generate PostgreSQL SQL for: When itogon, benguet is the city/municipality and 1st class is the income classification how many measurements of population in 2010?

CREATE TABLE table_29289372_1 (population__2010_ VARCHAR, income_classification VARCHAR, city_municipality VARCHAR)

SELECT COUNT(population__2010_) FROM table_29289372_1 WHERE income_classification = '1st Class' AND city_municipality = 'Itogon, Benguet';


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

Explanation: DML from PostgreSQL core regression test for Join.


Question: Find AI safety incidents in South America with a confidence score below 0.8, ordered by incident date.

CREATE TABLE AISafetyIncidents (incident_id INTEGER, confidence FLOAT, incident_date DATE, region TEXT); INSERT INTO AISafetyIncidents (incident_id, confidence, incident_date, region) VALUES (1, 0.75, '2022-01-01', 'South America'), (2, 0.85, '2022-04-01', 'South America');

SELECT * FROM AISafetyIncidents WHERE region = 'South America' AND confidence < 0.8 ORDER BY incident_date;


Question: What is the total amount of climate finance provided to projects in the Pacific region for climate adaptation by the European Investment Bank?

CREATE TABLE european_investment_bank (fund_id INT, project_name VARCHAR(100), country VARCHAR(50), sector VARCHAR(50), amount FLOAT, climate_adaptation_flag BOOLEAN); INSERT INTO european_investment_bank (fund_id, project_name, country, sector, amount, climate_adaptation_flag) VALUES (1, 'Sea Level Rise Protection', 'Tuvalu', 'Infrastructure', 20000000, TRUE);

SELECT SUM(amount) FROM european_investment_bank WHERE country LIKE '%%pacific%%' AND climate_adaptation_flag = TRUE;


Question: Generate PostgreSQL SQL for: How many rounds were fought with opponent Kevin Roddy?

CREATE TABLE table_name_54 (round VARCHAR, opponent VARCHAR)

SELECT COUNT(round) FROM table_name_54 WHERE opponent = 'kevin roddy';


Question: What is the maximum energy efficiency rating for commercial buildings in the "CleanEnergy" schema?

CREATE TABLE CommercialEfficiency (building_id INT, rating FLOAT, city VARCHAR(50), state VARCHAR(50)); INSERT INTO CommercialEfficiency (building_id, rating, city, state) VALUES (1, 85.6, 'LosAngeles', 'CA'), (2, 90.2, 'NewYorkCity', 'NY');

SELECT MAX(rating) FROM CleanEnergy.CommercialEfficiency;


Question: Write the DDL statement from PostgreSQL regression test 'privileges' (example 22).

Explanation: DDL from PostgreSQL core regression test for Privileges.


Question: Which suppliers provide raw materials for the renewable energy sector?

CREATE TABLE suppliers (id INT, name VARCHAR(50), sector VARCHAR(50)); INSERT INTO suppliers (id, name, sector) VALUES (1, 'Supplier X', 'Renewable Energy'), (2, 'Supplier Y', 'Textiles'), (3, 'Supplier Z', 'Renewable Energy');

SELECT name FROM suppliers WHERE sector = 'Renewable Energy';


Question: Generate PostgreSQL SQL for: What streak start has a total less than 79, 22t as the rank, and tampa bay as the teams?

CREATE TABLE table_name_28 (streak_start VARCHAR, teams VARCHAR, total VARCHAR, rank VARCHAR)

SELECT streak_start FROM table_name_28 WHERE total < 79 AND rank = '22t' AND teams = 'tampa bay';


Question: What is the total amount of waste produced by each mining company?

CREATE TABLE CompanyWaste (CompanyID INT, Company VARCHAR(20), Waste INT); INSERT INTO CompanyWaste (CompanyID, Company, Waste) VALUES (1, 'Canada Gold', 1000), (2, 'USA Silver', 2000), (3, 'Mexico Coal', 1500);

SELECT Company, SUM(Waste) FROM CompanyWaste GROUP BY Company;


Question: Update the names of authors with the last name 'Doe' to 'Smith' in the 'authors' table

CREATE TABLE authors (author_id INT PRIMARY KEY, first_name VARCHAR(50), last_name VARCHAR(50));

UPDATE authors SET last_name = 'Smith' WHERE last_name = 'Doe';


Question: What is the average safety rating for creative AI applications in the 'creative_ai' table?

CREATE TABLE creative_ai (app_id INT, app_name TEXT, safety_rating FLOAT);

SELECT AVG(safety_rating) FROM creative_ai;


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

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


Question: Generate PostgreSQL SQL for: What was the publication year ranking l.a. is 1st?

CREATE TABLE table_19948664_2 (year_of_publication VARCHAR, ranking_la__2_ VARCHAR)

SELECT year_of_publication FROM table_19948664_2 WHERE ranking_la__2_ = '1st';


Question: List all the articles published by 'Al Jazeera' that are related to the Middle East.

CREATE TABLE al_jazeera (article_id INT, title TEXT, content TEXT, publisher TEXT); INSERT INTO al_jazeera (article_id, title, content, publisher) VALUES (1, 'Article 1', 'Middle East content', 'Al Jazeera'), (2, 'Article 2', 'Sports content', 'Al Jazeera');

SELECT * FROM al_jazeera WHERE content LIKE '%Middle East%';


Question: What is the total labor hours for all traditional building projects in the state of Washington, Oregon, and California?

CREATE TABLE project (id INT, state VARCHAR(20), type VARCHAR(20), hours INT); INSERT INTO project (id, state, type, hours) VALUES (1, 'Washington', 'Sustainable', 500), (2, 'Oregon', 'Sustainable', 600), (3, 'Seattle', 'Traditional', 300), (4, 'California', 'Traditional', 700);

SELECT SUM(hours) FROM project WHERE state IN ('Washington', 'Oregon', 'California') AND type = 'Traditional';


Question: Generate PostgreSQL SQL for: Album # of 3rd is what chinese title?

CREATE TABLE table_name_57 (chinese_title VARCHAR, album_number VARCHAR)

SELECT chinese_title FROM table_name_57 WHERE album_number = '3rd';


Question: What is the average bioprocess engineering project cost per country, ordered by total cost?

CREATE SCHEMA if not exists bioprocess;CREATE TABLE if not exists bioprocess.projects (id INT PRIMARY KEY, country VARCHAR(50), name VARCHAR(255), cost DECIMAL(10, 2)); INSERT INTO bioprocess.projects (id, country, name, cost) VALUES (1, 'USA', 'ProjectA', 50000.00), (2, 'Canada', 'ProjectB', 75000.00), (3, 'Mexico', 'ProjectC', 35000.00), (4, 'USA', 'ProjectD', 80000.00);

SELECT country, AVG(cost) AS avg_cost FROM bioprocess.projects GROUP BY country ORDER BY avg_cost DESC;


Question: What was the total amount donated by recurring donors in Q3 2021?

CREATE TABLE donors (id INT PRIMARY KEY, donor_type VARCHAR(20), donor_since DATE); INSERT INTO donors (id, donor_type, donor_since) VALUES (1, 'recurring', '2021-07-01'); CREATE TABLE donations (id INT PRIMARY KEY, donor_id INT, donation_amount INT, donation_date DATE); INSERT INTO donations (id, donor_id, donation_amount, donation_date) VALUES (1, 1, 50, '2021-09-01');

SELECT SUM(donation_amount) FROM donations d JOIN donors don ON d.donor_id = don.id WHERE donor_type = 'recurring' AND donation_date BETWEEN '2021-07-01' AND '2021-09-30';


Question: Update the 'resilience_score' of the bridge named 'Chenab Bridge' to 92.5.

CREATE TABLE bridges (id INT, name TEXT, region TEXT, resilience_score FLOAT); INSERT INTO bridges (id, name, region, resilience_score) VALUES (1, 'Golden Gate Bridge', 'West Coast', 85.2), (2, 'Brooklyn Bridge', 'East Coast', 76.3), (3, 'Bay Bridge', 'West Coast', 78.1), (4, 'Chenab Bridge', 'South Asia', 89.6);

UPDATE bridges SET resilience_score = 92.5 WHERE name = 'Chenab Bridge';


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

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

SELECT count(*) FROM (SELECT lowrite(42, 'x')) AS _sub;


Question: Generate PostgreSQL SQL for: Capital of brześć nad bugiem has what area (1930) in 1000skm?

CREATE TABLE table_name_72 (area__1930__in_1 VARCHAR, capital VARCHAR)

SELECT area__1930__in_1, 000 AS skm_2 FROM table_name_72 WHERE capital = 'brześć nad bugiem';


Question: Generate PostgreSQL SQL for: Tell me the revised of mccune reischauer of yŏn (s) ryŏn (n)

CREATE TABLE table_name_48 (revised VARCHAR, mccune_reischauer VARCHAR)

SELECT revised FROM table_name_48 WHERE mccune_reischauer = 'yŏn (s) ryŏn (n)';


Question: Generate PostgreSQL SQL for: Which lowest rank(player) has a rebound average larger than 9, out of 920 rebounds, and who played more than 79 games?

CREATE TABLE table_name_10 (rank INTEGER, games VARCHAR, reb_avg VARCHAR, total_rebounds VARCHAR)

SELECT MIN(rank) FROM table_name_10 WHERE reb_avg > 9 AND total_rebounds = 920 AND games > 79;


Question: Generate PostgreSQL SQL for: What was the record on june 29?

CREATE TABLE table_name_25 (record VARCHAR, date VARCHAR)

SELECT record FROM table_name_25 WHERE date = 'june 29';


Question: Generate PostgreSQL SQL for: What group on the island of Faray has a Height (m) of 32 and a Population of 0?

CREATE TABLE table_name_99 (group VARCHAR, island VARCHAR, height__m_ VARCHAR, population VARCHAR)

SELECT group FROM table_name_99 WHERE height__m_ = 32 AND population = '0' AND island = 'faray';


Question: Generate PostgreSQL SQL for: What is "house", when "four" is "opat"?

CREATE TABLE table_name_89 (house VARCHAR, four VARCHAR)

SELECT house FROM table_name_89 WHERE four = 'opat';


Question: What is the maximum donation amount from Australia?

CREATE TABLE Donors (DonorID INT, DonorName TEXT, DonationAmount DECIMAL(10,2), Country TEXT);

SELECT MAX(DonationAmount) FROM Donors WHERE Country = 'Australia';


Question: What is the total number of members in unions that have collective bargaining agreements?

CREATE TABLE unions (id INT, union_name VARCHAR(255), has_cba BOOLEAN);

SELECT COUNT(*) FROM unions WHERE has_cba = TRUE;


Question: What is the total cost of mental health treatments for patients with anxiety?

CREATE TABLE MentalHealthParity (id INT, patientID INT, condition VARCHAR(50), treatment VARCHAR(50), cost DECIMAL(5,2)); INSERT INTO MentalHealthParity (id, patientID, condition, treatment, cost) VALUES (1, 1001, 'Anxiety', 'Counseling', 80.00), (2, 1002, 'Depression', 'Medication', 100.00);

SELECT patientID, SUM(cost) as 'TotalCost' FROM MentalHealthParity WHERE condition = 'Anxiety';


Question: Provide the number of ocean floor mapping projects by country and year.

CREATE SCHEMA oceans;CREATE TABLE oceans.mapping_projects_by_year (id INT PRIMARY KEY, country VARCHAR(50), year INT, num_projects INT); INSERT INTO oceans.mapping_projects_by_year (id, country, year, num_projects) VALUES (1, 'Canada', 2020, 2), (2, 'Mexico', 2020, 1);

SELECT context.country, context.year, SUM(context.num_projects) FROM oceans.mapping_projects_by_year AS context GROUP BY context.country, context.year;


Question: What is the number of high severity vulnerabilities for each system?

CREATE TABLE vulnerabilities(id INT, system VARCHAR(20), severity VARCHAR(10), date DATE); INSERT INTO vulnerabilities VALUES (1, 'web server', 'high', '2021-01-01'); INSERT INTO vulnerabilities VALUES (2, 'database', 'low', '2021-01-02');

SELECT system, severity, COUNT(*) FROM vulnerabilities WHERE severity = 'high' GROUP BY system;


Question: What is the average duration of space missions for each spacecraft model?

CREATE TABLE Spacecraft (id INT, name TEXT, model TEXT, manufacturer TEXT); CREATE TABLE SpaceMissions (id INT, spacecraft_id INT, mission TEXT, duration INT);

SELECT model, AVG(duration) FROM SpaceMissions JOIN Spacecraft ON SpaceMissions.spacecraft_id = Spacecraft.id GROUP BY model;


Question: Write the DDL statement from PostgreSQL regression test 'create_schema' (example 4).

CREATE SCHEMA AUTHORIZATION regress_create_schema_role
  CREATE VIEW schema_not_existing.view AS SELECT 1;

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


Question: Which satellites were deployed by both SpaceTech Inc. and Orbital Inc.?

CREATE TABLE Satellites (satellite_id INT, name VARCHAR(50), launch_date DATE, manufacturer VARCHAR(50)); INSERT INTO Satellites (satellite_id, name, launch_date, manufacturer) VALUES (1, 'Sat1', '2020-01-01', 'SpaceTech Inc.'), (2, 'Sat2', '2019-05-15', 'Orbital Inc.'), (3, 'Sat3', '2021-03-27', 'SpaceTech Inc.'), (4, 'Sat4', '2018-12-12', 'Orbital Inc.');

SELECT name FROM Satellites WHERE manufacturer IN ('SpaceTech Inc.', 'Orbital Inc.') GROUP BY name HAVING COUNT(DISTINCT manufacturer) = 2;


Question: What is the average playtime for adventure games?

CREATE TABLE Player_Games(player_id INT, game_id INT, playtime INT); INSERT INTO Player_Games(player_id, game_id, playtime) VALUES (1, 1, 50); INSERT INTO Player_Games(player_id, game_id, playtime) VALUES (2, 2, 100); INSERT INTO Player_Games(player_id, game_id, playtime) VALUES (3, 3, 75);

SELECT AVG(playtime) FROM Player_Games JOIN Games ON Player_Games.game_id = Games.game_id WHERE genre = 'Adventure';


Question: Generate PostgreSQL SQL for: What is Updated In Past 30 Days, when Registration is "Open to people 13 and over"?

CREATE TABLE table_name_93 (updated_in_past_30_days VARCHAR, registration VARCHAR)

SELECT updated_in_past_30_days FROM table_name_93 WHERE registration = 'open to people 13 and over';


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

-- function with ORDINALITY
select * from rngfunct(1) with ordinality as z(a,b,ord);

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


Question: What is the total number of trees in the forestry_data schema, excluding trees that are in the no_management_zone table?

CREATE TABLE forestry_data.young_forest (tree_id INT, species VARCHAR(50), age INT, height INT, location VARCHAR(50));CREATE TABLE forestry_data.mature_forest (tree_id INT, species VARCHAR(50), age INT, height INT, location VARCHAR(50));CREATE TABLE forestry_data.protected_zone (tree_id INT, species VARCHAR(50), age INT, height INT, location VARCHAR(50));CREATE TABLE forestry_data.no_management_zone (tree_id INT, species VARCHAR(50), age INT, height INT, location VARCHAR(50));

SELECT COUNT(*) FROM forestry_data.young_forest UNION ALL SELECT COUNT(*) FROM forestry_data.mature_forest EXCEPT SELECT COUNT(*) FROM forestry_data.no_management_zone;


Question: Generate PostgreSQL SQL for: What position does Alexei Lazarenko have?

CREATE TABLE table_name_62 (position VARCHAR, player VARCHAR)

SELECT position FROM table_name_62 WHERE player = 'alexei lazarenko';


Question: Update the 'digital_assets' table to set the 'circulating_supply' to 15000000 for all records where the asset_name is 'Bitcoin'

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

UPDATE digital_assets SET circulating_supply = 15000000 WHERE asset_name = 'Bitcoin';


Question: What are the regulatory frameworks in place for blockchain in the European Union?

CREATE TABLE regulatory_frameworks (framework_id INT, country VARCHAR(100), framework VARCHAR(100)); INSERT INTO regulatory_frameworks (framework_id, country, framework) VALUES (1, 'EU', 'Framework1'), (2, 'EU', 'Framework2'), (3, 'EU', 'Framework3');

SELECT framework FROM regulatory_frameworks WHERE country = 'EU';


Question: What is the change in recycling rates for plastics, paper, and metals from 2020 to 2021 for the country 'USA'?

CREATE TABLE recycling_rates_history (id INT, country VARCHAR(255), year INT, plastics DECIMAL(3,2), paper DECIMAL(3,2), metals DECIMAL(3,2)); INSERT INTO recycling_rates_history (id, country, year, plastics, paper, metals) VALUES (1, 'USA', 2020, 0.30, 0.55, 0.72), (2, 'USA', 2021, 0.33, 0.58, 0.75);

SELECT  (recycling_rates_history.plastics_2021 - recycling_rates_history.plastics_2020) AS plastics_change, (recycling_rates_history.paper_2021 - recycling_rates_history.paper_2020) AS paper_change, (recycling_rates_history.metals_2021 - recycling_rates_history.metals_2020) AS metals_change FROM (SELECT country, plastics AS plastics_2020, paper AS paper_2020, metals AS metals_2020 FROM recycling_rates_history WHERE year = 2020 AND country = 'USA'  UNION ALL SELECT country, plastics AS plastics_2021, paper AS paper_2021, metals AS metals_2021 FROM recycling_rates_history WHERE year = 2021 AND country = 'USA') AS recycling_rates_history;


Question: Find users who have not received any likes on their posts and are from a country other than the US.

CREATE TABLE users (id INT, name VARCHAR(50), country VARCHAR(2), followers INT); INSERT INTO users (id, name, country, followers) VALUES (1, 'Alice', 'US', 1000), (2, 'Bob', 'JP', 500), (3, 'Charlie', 'CA', 1500), (4, 'David', 'MX', 200), (5, 'Eve', 'DE', 800); CREATE TABLE posts (id INT, user_id INT, timestamp DATETIME, likes INT); INSERT INTO posts (id, user_id, timestamp, likes) VALUES (1, 1, '2022-01-01 10:00:00', 0), (2, 1, '2022-01-02 11:00:00', 5), (3, 2, '2022-01-03 12:00:00', 0);

SELECT users.name FROM users LEFT JOIN posts ON users.id = posts.user_id WHERE users.country != 'US' AND posts.likes = 0;


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

SELECT COUNT(id) FROM xmltest WHERE xmlexists('/menu/beers' PASSING BY REF data);

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

SELECT count(*) FROM (SELECT COUNT(id) FROM xmltest WHERE xmlexists('/menu/beers' PASSING BY REF data)) AS _sub;


Question: What is the average environmental impact score for chemical 'D'?

CREATE TABLE environmental_impact (chemical VARCHAR(10), score INT); INSERT INTO environmental_impact VALUES ('D', 25), ('D', 30), ('D', 20), ('E', 35), ('E', 40);

SELECT AVG(score) FROM environmental_impact WHERE chemical = 'D';


Question: What is the average response time for police stations in Atlanta?

CREATE TABLE atlanta_police_responses (id INT, response_time INT, location VARCHAR(20)); INSERT INTO atlanta_police_responses (id, response_time, location) VALUES (1, 150, 'Atlanta'), (2, 120, 'Atlanta');

SELECT AVG(response_time) FROM atlanta_police_responses WHERE location = 'Atlanta';


Question: What is the average number of community health centers per state in the Midwest?

CREATE TABLE community_health_centers (center_id INT, state TEXT, center_type TEXT); INSERT INTO community_health_centers (center_id, state, center_type) VALUES (1, 'Illinois', 'Community Health Center'), (2, 'Indiana', 'Mental Health Center');

SELECT AVG(COUNT(*)) FROM community_health_centers GROUP BY state HAVING state LIKE '%Midwest%';


Question: List all renewable energy types from the renewable_energy_types table in the renewable_energy schema.

CREATE SCHEMA IF NOT EXISTS renewable_energy; CREATE TABLE IF NOT EXISTS renewable_energy.renewable_energy_types (  energy_type_id INT NOT NULL,  energy_type VARCHAR(255) NOT NULL,  PRIMARY KEY (energy_type_id));

SELECT energy_type FROM renewable_energy.renewable_energy_types;


Question: Update the safety_rating of 'Methyl Ethyl Ketone' to 3 in the chemical_table

CREATE TABLE chemical_table (chemical_id INT, chemical_name VARCHAR(50), safety_rating INT);

UPDATE chemical_table SET safety_rating = 3 WHERE chemical_name = 'Methyl Ethyl Ketone';


Question: Generate PostgreSQL SQL for: what's the frequency mhz with city of license being chattanooga, tennessee

CREATE TABLE table_13998897_1 (frequency_mhz VARCHAR, city_of_license VARCHAR)

SELECT frequency_mhz FROM table_13998897_1 WHERE city_of_license = 'Chattanooga, Tennessee';


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

SELECT 'a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11'::citext::uuid = 'a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11'::uuid AS t;

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


Question: How many cases were handled by attorneys in each region?

CREATE TABLE Attorneys (AttorneyID int, Name varchar(50), Region varchar(50)); INSERT INTO Attorneys VALUES (1, 'John Smith', 'Northeast'), (2, 'Jane Doe', 'Southeast'); CREATE TABLE Cases (CaseID int, AttorneyID int); INSERT INTO Cases VALUES (1, 1), (2, 1), (3, 2), (4, 2);

SELECT A.Region, COUNT(C.CaseID) as NumCases FROM Attorneys A JOIN Cases C ON A.AttorneyID = C.AttorneyID GROUP BY A.Region;


Question: What is the success rate of space missions led by private companies?

CREATE TABLE space_missions_by_company (company VARCHAR(255), num_missions INT, num_successful_missions INT); INSERT INTO space_missions_by_company (company, num_missions, num_successful_missions) VALUES ('SpaceX', 105, 98); INSERT INTO space_missions_by_company (company, num_missions, num_successful_missions) VALUES ('Blue Origin', 25, 23);

SELECT company, (num_successful_missions::DECIMAL / num_missions) * 100 AS success_rate FROM space_missions_by_company;


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

SELECT xmltable.* FROM xmldata, LATERAL xmltable('/ROWS/ROW[COUNTRY_NAME="Japan" or COUNTRY_NAME="India"]' PASSING data COLUMNS id int PATH '@id');

SELECT count(*) FROM (SELECT xmltable.* FROM xmldata, LATERAL xmltable('/ROWS/ROW[COUNTRY_NAME="Japan" or COUNTRY_NAME="India"]' PASSING data COLUMNS id int PATH '@id')) AS _sub;


Question: Insert records of new mineral extractions in the 'South America' region.

CREATE TABLE New_Extractions_2 (country TEXT, mineral TEXT, quantity INTEGER, region TEXT);

INSERT INTO New_Extractions_2 (country, mineral, quantity, region) VALUES ('Brazil', 'Diamond', 120, 'South America'); INSERT INTO New_Extractions_2 (country, mineral, quantity, region) VALUES ('Peru', 'Emerald', 90, 'South America');


Question: Generate PostgreSQL SQL for: What district(s) did henry clay represent?

CREATE TABLE table_2668264_8 (district VARCHAR, incumbent VARCHAR)

SELECT district FROM table_2668264_8 WHERE incumbent = 'Henry Clay';


Question: How many tourists from each country visited sustainable destinations?

CREATE TABLE Sustainable_Destinations (id INT, destination_name VARCHAR(50), sustainable BOOLEAN); CREATE TABLE Tourists_Destinations (tourist_id INT, destination_id INT, visit_date DATE); INSERT INTO Sustainable_Destinations VALUES (1, 'Eco Village', true); INSERT INTO Sustainable_Destinations VALUES (2, 'Green City', true); INSERT INTO Tourists_Destinations VALUES (1, 1, '2022-01-01'); INSERT INTO Tourists_Destinations VALUES (2, 2, '2022-01-02'); INSERT INTO Tourists_Destinations VALUES (3, 1, '2022-01-03');

SELECT Tourists.nationality, COUNT(DISTINCT Tourists_Destinations.tourist_id) AS num_tourists FROM Tourists_Destinations INNER JOIN Tourists ON Tourists_Destinations.tourist_id = Tourists.id INNER JOIN Sustainable_Destinations ON Tourists_Destinations.destination_id = Sustainable_Destinations.id WHERE Sustainable_Destinations.sustainable = true GROUP BY Tourists.nationality;


Question: How many Shariah-compliant finance transactions were made in Q1 2022 by gender?

CREATE TABLE shariah_compliant_finance(id INT, transaction_id INT, gender VARCHAR(10), quarter INT, year INT); INSERT INTO shariah_compliant_finance VALUES (1, 301, 'Male', 1, 2022); INSERT INTO shariah_compliant_finance VALUES (2, 302, 'Female', 1, 2022); INSERT INTO shariah_compliant_finance VALUES (3, 303, 'Male', 2, 2022); INSERT INTO shariah_compliant_finance VALUES (4, 304, 'Female', 2, 2022); INSERT INTO shariah_compliant_finance VALUES (5, 305, 'Non-binary', 1, 2022);

SELECT gender, COUNT(transaction_id) FROM shariah_compliant_finance WHERE quarter = 1 AND year = 2022 GROUP BY gender;


Question: What was the minimum investment in agricultural innovation in 'Middle East' up to 2021?

CREATE TABLE agricultural_innovation (innovation_id INT, innovation_name TEXT, region TEXT, investment_amount INT, year INT); INSERT INTO agricultural_innovation (innovation_id, innovation_name, region, investment_amount, year) VALUES (1, 'Drought-Resistant Crops', 'Africa', 2000000, 2020); INSERT INTO agricultural_innovation (innovation_id, innovation_name, region, investment_amount, year) VALUES (2, 'Precision Farming', 'Asia', 3000000, 2021); INSERT INTO agricultural_innovation (innovation_id, innovation_name, region, investment_amount, year) VALUES (3, 'Sustainable Farming', 'Middle East', 2500000, 2019); INSERT INTO agricultural_innovation (innovation_id, innovation_name, region, investment_amount, year) VALUES (4, 'Aquaponics', 'Middle East', 2000000, 2020);

SELECT MIN(investment_amount) FROM agricultural_innovation WHERE year <= 2021 AND region = 'Middle East';


Question: Get the number of workplaces with safety issues

CREATE TABLE workplaces (id INT, name TEXT, location TEXT, safety_issues INT);

SELECT COUNT(*) FROM workplaces WHERE safety_issues > 0;


Question: Generate PostgreSQL SQL for: How many players have more than 1000 hours of training?

SELECT COUNT(*) FROM Player WHERE HS > 1000;


Question: Who is the leading goal scorer in the history of the English Premier League?

CREATE TABLE epl_goals (player_name VARCHAR(50), goals INT, assists INT); INSERT INTO epl_goals (player_name, goals, assists) VALUES ('Alan Shearer', 260, 64), ('Wayne Rooney', 208, 103);

SELECT player_name, SUM(goals) as total_goals FROM epl_goals GROUP BY player_name ORDER BY total_goals DESC LIMIT 1;


Question: What is the average annual rainfall and temperature for each urban farm in the "urban_farms", "urban_regions", and "weather" tables?

CREATE TABLE urban_farms (id INT, urban_region_id INT); CREATE TABLE urban_regions (id INT, name VARCHAR(50)); CREATE TABLE weather (id INT, region_id INT, year INT, rainfall FLOAT, temperature FLOAT);

SELECT urban_farms.id AS farm_id, urban_regions.name AS region, AVG(weather.rainfall) AS avg_rainfall, AVG(weather.temperature) AS avg_temperature FROM urban_farms INNER JOIN urban_regions ON urban_farms.urban_region_id = urban_regions.id INNER JOIN weather ON urban_regions.id = weather.region_id GROUP BY urban_farms.id;


Question: What is the total amount of loans issued for Shariah-compliant microfinance in India?

CREATE TABLE shariah_microfinance (id INT, loan_type VARCHAR(255), amount DECIMAL(10,2), country VARCHAR(255));

SELECT SUM(amount) FROM shariah_microfinance WHERE loan_type = 'Shariah-compliant microfinance' AND country = 'India';


Question: pgTAP test for Inheritance (assertion 16).

SELECT * FROM check_test(
    has_inherited_tables( 'parent', 'Gimme more' ),
    true,
    'has_inherited_tables(tab, desc)',
    'Gimme more',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Inheritance.


Question: Generate PostgreSQL SQL for: What is the margin of victory for the winning score of −10 (71-65-68-70=274)?

CREATE TABLE table_name_78 (margin_of_victory VARCHAR, winning_score VARCHAR)

SELECT margin_of_victory FROM table_name_78 WHERE winning_score = −10(71 - 65 - 68 - 70 = 274);


Question: What are the different mining operations in the Asia-Pacific region?

CREATE TABLE Operations (Company VARCHAR(50), Operation VARCHAR(50), Location VARCHAR(10)); INSERT INTO Operations (Company, Operation, Location) VALUES ('GHI Mines', 'Coal', 'Asia'), ('JKL Mining', 'Gold', 'Australia'), ('MNO Drilling', 'Oil', 'Pacific');

SELECT DISTINCT Operation FROM Operations WHERE Location LIKE 'Asia%' OR Location LIKE 'Pacific%';


Question: What is the total revenue for the 'Chinese' cuisine type in March 2022?

SELECT cuisine, SUM(revenue) as total_revenue FROM restaurant_revenue WHERE date >= '2022-03-01' AND date <= '2022-03-31' AND cuisine = 'Chinese' GROUP BY cuisine;


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

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

SELECT count(*) FROM (select '{(\\,a)}'::textmultirange) AS _sub;


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

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


Question: Generate PostgreSQL SQL for: Which club has 1 cap?

CREATE TABLE table_name_90 (club_province VARCHAR, caps VARCHAR)

SELECT club_province FROM table_name_90 WHERE caps = 1;


Question: List the names of countries with no viewers for any concert?

CREATE TABLE Concerts (id INT, title VARCHAR(255), location VARCHAR(255), viewers INT);

SELECT location FROM Concerts WHERE viewers = 0 GROUP BY location HAVING COUNT(*) = (SELECT COUNT(*) FROM Concerts WHERE Concerts.viewers = 0);


Question: What is the percentage of female and male employees by department?

CREATE TABLE employee_demographics (id INT, employee_id INT, department_id INT, gender VARCHAR(10)); INSERT INTO employee_demographics (id, employee_id, department_id, gender) VALUES (1, 1, 1, 'Female'), (2, 2, 1, 'Male'), (3, 3, 2, 'Female'), (4, 4, 2, 'Non-binary'), (5, 5, 3, 'Male');

SELECT department_id, gender, COUNT(*) * 100.0 / (SELECT COUNT(*) FROM employee_demographics WHERE department_id = departments.id) as percentage FROM employee_demographics JOIN departments ON employee_demographics.department_id = departments.id GROUP BY department_id, gender;


Question: Generate PostgreSQL SQL for: What was the Surface on during 10 November 2006?

CREATE TABLE table_name_41 (surface VARCHAR, date VARCHAR)

SELECT surface FROM table_name_41 WHERE date = '10 november 2006';


Question: Generate PostgreSQL SQL for: What date did they play agains the New York Rangers?

CREATE TABLE table_23308178_4 (date VARCHAR, opponent VARCHAR)

SELECT date FROM table_23308178_4 WHERE opponent = 'New York Rangers';


Question: What is the oldest artist in the 'Famous_Artists' table?

CREATE TABLE Famous_Artists (artist_id INT, artist_name VARCHAR(255), birth_date DATE);

SELECT artist_name FROM Famous_Artists ORDER BY birth_date ASC LIMIT 1;


Question: Add a new satellite project 'Satellite XYZ' launched by 'NASA'

CREATE TABLE satellite_projects (id INT PRIMARY KEY, name VARCHAR(255), organization VARCHAR(255), launch_date DATE);

INSERT INTO satellite_projects (id, name, organization, launch_date) VALUES (1, 'Satellite XYZ', 'NASA', '2025-04-22');


Question: Generate PostgreSQL SQL for: Who are all the runner ups when the score is 9.12 (66) – 5.6 (36)?

CREATE TABLE table_1139835_9 (runner_up VARCHAR, score VARCHAR)

SELECT runner_up FROM table_1139835_9 WHERE score = '9.12 (66) – 5.6 (36)';


Question: List all mines and their environmental impact score, grouped by country

CREATE TABLE mine (id INT, name TEXT, country TEXT, environmental_impact_score INT); INSERT INTO mine VALUES (1, 'Mine A', 'Country A', 60); INSERT INTO mine VALUES (2, 'Mine B', 'Country B', 75); INSERT INTO mine VALUES (3, 'Mine C', 'Country A', 45);

SELECT country, environmental_impact_score, AVG(environmental_impact_score) as avg_score FROM mine GROUP BY country;


Question: What is the total playtime, in hours, for each game, broken down by genre?

CREATE TABLE GamePlaytime (PlayerID INT, PlayerName TEXT, Game TEXT, Genre TEXT, Playtime INT); INSERT INTO GamePlaytime (PlayerID, PlayerName, Game, Genre, Playtime) VALUES (1, 'John Doe', 'Game A', 'Shooter', 50), (2, 'Jane Smith', 'Game B', 'Strategy', 75), (3, 'Bob Johnson', 'Game C', 'Shooter', 100), (4, 'Alice Williams', 'Game D', 'Role-playing', 30), (5, 'Charlie Brown', 'Game A', 'Shooter', 25);

SELECT Genre, SUM(Playtime / 60) AS TotalPlaytime FROM GamePlaytime GROUP BY Genre;


Question: What is the average number of ethical AI courses offered by universities in South America?

CREATE TABLE Ethical_AI_Courses (University VARCHAR(50), Courses INT);

SELECT AVG(Courses) FROM Ethical_AI_Courses WHERE University IN (SELECT University FROM Ethical_AI_Courses WHERE Country IN ('Argentina', 'Brazil', 'Colombia') GROUP BY University HAVING COUNT(*) >= 2);


Question: Write the DML statement from PostgreSQL regression test 'constraints' (example 264).

INSERT INTO circles VALUES('<(20,20), 10>', '<(0,0), 4>')
  ON CONFLICT ON CONSTRAINT circles_c1_c2_excl DO SELECT RETURNING *;

Explanation: DML from PostgreSQL core regression test for Constraints.


Question: Update the community service hours of offenders in California by adding 10 hours to their current total.

CREATE TABLE offenders (id INT, name TEXT, state TEXT, community_service_hours INT); INSERT INTO offenders (id, name, state, community_service_hours) VALUES (1, 'John Doe', 'California', 50); INSERT INTO offenders (id, name, state, community_service_hours) VALUES (2, 'Jane Smith', 'California', 75);

UPDATE offenders SET community_service_hours = community_service_hours + 10 WHERE state = 'California';


Question: Generate PostgreSQL SQL for: What is the amount of 000s from 1996?

CREATE TABLE table_name_20 (total__000s_ INTEGER, year VARCHAR)

SELECT SUM(total__000s_) FROM table_name_20 WHERE year = '1996';


Question: Generate PostgreSQL SQL for: In what rounds did Luigi Fagioli drive for Alfa Romeo SPA?

CREATE TABLE table_name_69 (rounds VARCHAR, entrant VARCHAR, driver VARCHAR)

SELECT rounds FROM table_name_69 WHERE entrant = 'alfa romeo spa' AND driver = 'luigi fagioli';


Question: Generate PostgreSQL SQL for: I want the plaid cymru for 4 may 2011

CREATE TABLE table_name_9 (plaid_cymru VARCHAR, date_s__conducted VARCHAR)

SELECT plaid_cymru FROM table_name_9 WHERE date_s__conducted = '4 may 2011';


Question: Generate PostgreSQL SQL for: Which frequency is located in Davao?

CREATE TABLE table_name_35 (frequency VARCHAR, location VARCHAR)

SELECT frequency FROM table_name_35 WHERE location = 'davao';


Question: Generate PostgreSQL SQL for: Can you tell me the Year(s) Won that has the To par larger than 5, and the Total smaller than 155, and the Country of united states?

CREATE TABLE table_name_18 (year_s__won VARCHAR, country VARCHAR, to_par VARCHAR, total VARCHAR)

SELECT year_s__won FROM table_name_18 WHERE to_par > 5 AND total < 155 AND country = 'united states';


Question: What is the minimum age of artists who have exhibited in galleries located in the Warehouse District?

CREATE TABLE galleries (id INT, name TEXT, location TEXT, city TEXT, state TEXT, zip INT); INSERT INTO galleries (id, name, location, city, state, zip) VALUES (1, 'Gallery X', 'Warehouse District', 'Denver', 'CO', 80202); CREATE TABLE artists (id INT, name TEXT, age INT, gallery_id INT); INSERT INTO artists (id, name, age, gallery_id) VALUES (1, 'Brian', 28, 1);

SELECT MIN(age) FROM artists JOIN galleries ON artists.gallery_id = galleries.id WHERE galleries.location = 'Warehouse District';


Question: What is the total cargo weight handled in the first quarter of 2022 for each country?

CREATE TABLE ports (port_id INT, port_name VARCHAR(255), country VARCHAR(255)); INSERT INTO ports VALUES (1, 'Port of Shanghai', 'China'); CREATE TABLE cargo (cargo_id INT, port_id INT, weight FLOAT, handling_date DATE); INSERT INTO cargo VALUES (1, 1, 5000, '2021-01-01');

SELECT c.country, SUM(c.weight) as total_weight FROM ports p JOIN cargo c ON p.port_id = c.port_id WHERE handling_date >= '2022-01-01' AND handling_date < '2022-04-01' GROUP BY c.country;


Question: Generate PostgreSQL SQL for: How many people attended the score of w 7-6?

CREATE TABLE table_name_15 (crowd VARCHAR, score VARCHAR)

SELECT crowd FROM table_name_15 WHERE score = 'w 7-6';


Question: Delete all records in the 'athletes' table where 'team' is 'Bears'

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

DELETE FROM athletes WHERE team = 'Bears';


Question: List all the defense innovation projects, along with their respective funding amounts, from the 'Innovation' and 'Funding' tables.

CREATE TABLE Innovation (id INT, project VARCHAR(255)); CREATE TABLE Funding (id INT, project VARCHAR(255), amount DECIMAL(10,2));

SELECT Innovation.project, Funding.amount FROM Innovation INNER JOIN Funding ON Innovation.id = Funding.id;


Question: Generate PostgreSQL SQL for: What is the total number of Rating(s), when Weekly Rank is 76/88?

CREATE TABLE table_name_7 (rating VARCHAR, weekly_rank VARCHAR)

SELECT COUNT(rating) FROM table_name_7 WHERE weekly_rank = '76/88';


Question: Find the names of the attendees who have visited both musical and theater events in NY.

CREATE TABLE Events (event_id INT, event_type VARCHAR(50), location VARCHAR(50)); CREATE TABLE Attendance (attendee_id INT, event_id INT); INSERT INTO Events (event_id, event_type, location) VALUES (1, 'Musical', 'New York'), (2, 'Theater', 'Los Angeles'), (3, 'Musical', 'New York'); INSERT INTO Attendance (attendee_id, event_id) VALUES (1, 1), (1, 2), (2, 1), (3, 3);

SELECT attendee_id FROM Attendance A WHERE EXISTS (SELECT 1 FROM Events E WHERE E.event_type = 'Musical' AND E.location = 'New York' AND A.event_id = E.event_id) AND EXISTS (SELECT 1 FROM Events F WHERE F.event_type = 'Theater' AND F.location = 'New York' AND A.event_id = F.event_id);


Question: Generate PostgreSQL SQL for: Which entrant scored less than 8 points and used a Maserati chassis?

CREATE TABLE table_name_91 (entrant VARCHAR, points VARCHAR, chassis VARCHAR)

SELECT entrant FROM table_name_91 WHERE points < 8 AND chassis = 'maserati';


Question: What is the average hire date for employees in the IT department?

CREATE TABLE Employees (EmployeeID INT, FirstName VARCHAR(50), LastName VARCHAR(50), Department VARCHAR(50), Gender VARCHAR(10), HireDate DATE); INSERT INTO Employees (EmployeeID, FirstName, LastName, Department, Gender, HireDate) VALUES (1, 'John', 'Doe', 'IT', 'Male', '2020-01-01'), (2, 'Jane', 'Doe', 'IT', 'Female', '2021-01-01');

SELECT AVG(HireDate) FROM Employees WHERE Department = 'IT';


Question: List all freight forwarding transactions for 'CustomerA' with their corresponding statuses and dates.

CREATE TABLE Customers (CustomerID VARCHAR(20), CustomerName VARCHAR(20)); INSERT INTO Customers (CustomerID, CustomerName) VALUES ('A', 'CustomerA'), ('B', 'CustomerB'); CREATE TABLE FreightForwardingTransactions (TransactionID INT, CustomerID VARCHAR(20), TransactionStatus VARCHAR(20), TransactionDate DATE); INSERT INTO FreightForwardingTransactions (TransactionID, CustomerID, TransactionStatus, TransactionDate) VALUES (1, 'A', 'Created', '2022-01-01'), (2, 'A', 'InProgress', '2022-01-02');

SELECT FreightForwardingTransactions.TransactionID, FreightForwardingTransactions.TransactionStatus, FreightForwardingTransactions.TransactionDate FROM Customers JOIN FreightForwardingTransactions ON Customers.CustomerID = FreightForwardingTransactions.CustomerID WHERE Customers.CustomerName = 'CustomerA';


Question: Maximum fairness score for AI models submitted by women.

CREATE TABLE ai_fairness (model_name TEXT, fairness_score INTEGER, submitter_gender TEXT); INSERT INTO ai_fairness (model_name, fairness_score, submitter_gender) VALUES ('ModelX', 95, 'Female'), ('ModelY', 88, 'Male'), ('ModelZ', 98, 'Female');

SELECT MAX(fairness_score) FROM ai_fairness WHERE submitter_gender = 'Female';


Question: Generate PostgreSQL SQL for: yes or no for the adelaide with no for auckland, yes for melbourne, yes for the gold coast?

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

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


Question: Generate PostgreSQL SQL for: Which distinct source system code includes the substring 'en'?

CREATE TABLE cmi_cross_references (source_system_code VARCHAR)

SELECT DISTINCT source_system_code FROM cmi_cross_references WHERE source_system_code LIKE '%en%';


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

SELECT * FROM test_int8 WHERE i>1::int4 ORDER BY i;


Question: Generate PostgreSQL SQL for: Show all company names and headquarters in the descending order of market value.

CREATE TABLE company (company VARCHAR, headquarters VARCHAR, market_value VARCHAR)

SELECT company, headquarters FROM company ORDER BY market_value DESC;


Question: Update the User_Experience value for the 'Great Wall of China Tour' in the Virtual_Tourism table, adding 150 to the current value.

CREATE TABLE Virtual_Tourism (Experience VARCHAR(50), Platform VARCHAR(50), User_Experience INT); INSERT INTO Virtual_Tourism (Experience, Platform, User_Experience) VALUES ('Great Wall of China Tour', 'Google Arts & Culture', 4800), ('Eiffel Tower Tour', 'AirPano', 3500), ('Vatican City Tour', 'Yandex', 5200);

UPDATE Virtual_Tourism SET User_Experience = User_Experience + 150 WHERE Experience = 'Great Wall of China Tour';


Question: What is the average monthly data usage for prepaid mobile subscribers?

CREATE TABLE data_usage (subscriber_id INT, service VARCHAR(10), start_date DATE, end_date DATE, data_usage INT); INSERT INTO data_usage (subscriber_id, service, start_date, end_date, data_usage) VALUES (1, 'prepaid', '2022-01-01', '2022-01-31', 3000), (2, 'prepaid', '2022-02-01', '2022-02-28', 3500);

SELECT AVG(data_usage) FROM data_usage WHERE service = 'prepaid';


Question: Insert new cultural competency training record for Massachusetts

CREATE TABLE cultural_competency_training (chw_id INT, state VARCHAR(2), year INT, completed BOOLEAN);

INSERT INTO cultural_competency_training (chw_id, state, year, completed) VALUES (789, 'MA', 2022, FALSE);


Question: Identify the wildlife habitats that have a decrease in area between 2018 and 2019, and order them by the largest decrease first.

CREATE TABLE wildlife_habitats (habitat_id INT, habitat_name VARCHAR(50), year INT, area INT); INSERT INTO wildlife_habitats (habitat_id, habitat_name, year, area) VALUES (1, 'Forest', 2018, 1000), (2, 'Wetland', 2018, 2000), (3, 'Grassland', 2018, 3000), (4, 'Forest', 2019, 900), (5, 'Wetland', 2019, 1800), (6, 'Grassland', 2019, 2800);

SELECT habitat_name, (LAG(area, 1) OVER (PARTITION BY habitat_name ORDER BY year)) - area AS area_decrease FROM wildlife_habitats WHERE year = 2019 GROUP BY habitat_name, area ORDER BY area_decrease DESC;


Question: Generate PostgreSQL SQL for: Show the average amount of transactions for different investors.

CREATE TABLE TRANSACTIONS (investor_id VARCHAR, amount_of_transaction INTEGER)

SELECT investor_id, AVG(amount_of_transaction) FROM TRANSACTIONS GROUP BY investor_id;


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

SELECT '42'::float4 / 'Infinity'::float4;

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

SELECT count(*) FROM (SELECT '42'::float4 / 'Infinity'::float4) AS _sub;


Question: what is the number of animals by species in the 'animal_population' table?

CREATE TABLE animal_population (species VARCHAR(50), population INT); INSERT INTO animal_population (species, population) VALUES ('Tiger', 200), ('Lion', 300), ('Elephant', 400);

SELECT species, SUM(population) FROM animal_population GROUP BY species;


Question: PostgreSQL regression test 'tsearch': Write the SELECT query (example 226).

SELECT to_tsquery('english', '(1 <3> 2) <-> a');

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

SELECT count(*) FROM (SELECT to_tsquery('english', '(1 <3> 2) <-> a')) AS _sub;


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

CREATE FUNCTION widget_out(widget)
   RETURNS cstring
   AS :'regresslib'
   LANGUAGE C STRICT IMMUTABLE;

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


Question: Generate PostgreSQL SQL for: Find the name of the students who have more than one advisor?

CREATE TABLE student (name VARCHAR, id VARCHAR); CREATE TABLE advisor (s_id VARCHAR)

SELECT T1.name FROM student AS T1 JOIN advisor AS T2 ON T1.id = T2.s_id GROUP BY T2.s_id HAVING COUNT(*) > 1;


Question: Show a SQL definition from the pg_partman project (test-id-time-subpart-custom-start, item 7).

CREATE TABLE partman_test.id_taptest_table (
    col1 int NOT NULL
    , col2 text DEFAULT 'stuff'
    , col3 timestamptz NOT NULL DEFAULT now())
    PARTITION BY RANGE (col1);

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


Question: Which countries have more than 5 excavation sites?

CREATE TABLE Countries (CountryID INT, CountryName TEXT); INSERT INTO Countries (CountryID, CountryName) VALUES (1, 'Country-X'), (2, 'Country-Y'), (3, 'Country-Z'); CREATE TABLE Sites (SiteID INT, SiteName TEXT, CountryID INT); INSERT INTO Sites (SiteID, SiteName, CountryID) VALUES (1, 'Site-A', 1), (2, 'Site-B', 2), (3, 'Site-C', 3), (4, 'Site-D', 1), (5, 'Site-E', 1), (6, 'Site-F', 2), (7, 'Site-G', 3), (8, 'Site-H', 3), (9, 'Site-I', 3);

SELECT Countries.CountryName, COUNT(DISTINCT Sites.SiteID) AS SiteCount FROM Countries INNER JOIN Sites ON Countries.CountryID = Sites.CountryID GROUP BY Countries.CountryName HAVING SiteCount > 5;


Question: Generate PostgreSQL SQL for: What is the maximum 2010 value for China?

CREATE TABLE table_30133_3 (economy VARCHAR)

SELECT MAX(2010) FROM table_30133_3 WHERE economy = 'China';


Question: Generate PostgreSQL SQL for: How many players received high points where location/attendance was UIC Pavilion 6,304 respectively?

CREATE TABLE table_17118657_7 (high_points VARCHAR, location_attendance VARCHAR)

SELECT COUNT(high_points) FROM table_17118657_7 WHERE location_attendance = 'UIC Pavilion 6,304';


Question: Generate PostgreSQL SQL for: How many people were in attendance when the Washington Nationals had a score of 7-3 and a loss of Worrell (0-1)?

CREATE TABLE table_name_54 (attendance VARCHAR, score VARCHAR, loss VARCHAR)

SELECT COUNT(attendance) FROM table_name_54 WHERE score = '7-3' AND loss = 'worrell (0-1)';


Question: Generate PostgreSQL SQL for: I want the venue for 23 july 1992

CREATE TABLE table_name_64 (venue VARCHAR, date VARCHAR)

SELECT venue FROM table_name_64 WHERE date = '23 july 1992';


Question: Generate PostgreSQL SQL for: What is the time for Sheffield?

CREATE TABLE table_name_15 (time VARCHAR, city VARCHAR)

SELECT time FROM table_name_15 WHERE city = 'sheffield';


Question: What is the average volume of timber produced annually in mangrove forests over the last decade?

CREATE TABLE mangrove_timber (id INT, year INT, volume FLOAT);

SELECT AVG(volume) as avg_annual_volume FROM mangrove_timber WHERE year BETWEEN 2011 AND 2021;


Question: Generate PostgreSQL SQL for: Which name has a percentage of 0.59%?

CREATE TABLE table_name_28 (name VARCHAR, percentage VARCHAR)

SELECT name FROM table_name_28 WHERE percentage = '0.59%';


Question: Generate PostgreSQL SQL for: return the smallest salary for every departments.

CREATE TABLE employees (department_id VARCHAR, salary INTEGER)

SELECT MIN(salary), department_id FROM employees GROUP BY department_id;


Question: How many communities are in the 'Planning' stage for each country?

CREATE TABLE If Not Exists community_development (community_id INT, community_name TEXT, location TEXT, development_stage TEXT); INSERT INTO community_development (community_id, community_name, location, development_stage) VALUES (4, 'Community D', 'Somalia', 'Planning'), (5, 'Community E', 'Sudan', 'Planning');

SELECT location, COUNT(*) as num_communities FROM community_development WHERE development_stage = 'Planning' GROUP BY location;


Question: Generate PostgreSQL SQL for: What ordered has helena as the name?

CREATE TABLE table_name_87 (ordered VARCHAR, name VARCHAR)

SELECT ordered FROM table_name_87 WHERE name = 'helena';


Question: What is the total number of virtual tours in 'Asia' and 'Europe'?

CREATE TABLE VirtualTours (TourID INTEGER, TourName TEXT, Location TEXT); INSERT INTO VirtualTours (TourID, TourName, Location) VALUES (1, 'Virtual Safari', 'Kenya'), (2, 'Virtual Castle Tour', 'Scotland'), (3, 'Virtual Trek', 'Nepal'), (4, 'Virtual Skiing', 'Switzerland'), (5, 'Virtual Temple Tour', 'Japan');

SELECT SUM(CASE WHEN Location IN ('Asia', 'Europe') THEN 1 ELSE 0 END) FROM VirtualTours;


Question: Generate PostgreSQL SQL for: Where is Robert Morris University-Illinois held?

CREATE TABLE table_27361255_1 (location VARCHAR, institution VARCHAR)

SELECT location FROM table_27361255_1 WHERE institution = 'Robert Morris University-Illinois';


Question: What is the total number of volunteers who have joined in each year in the 'Volunteers' table?

CREATE TABLE Volunteers (VolunteerID INT, VolunteerName VARCHAR(50), JoinDate DATE); INSERT INTO Volunteers (VolunteerID, VolunteerName, JoinDate) VALUES (1, 'Sophia Garcia', '2021-05-01'), (2, 'Ali Hassan', '2022-01-15'), (3, 'Lea Kim', '2021-12-31'), (4, 'Han Mehta', '2022-02-28');

SELECT YEAR(JoinDate) as Year, COUNT(*) as TotalVolunteers FROM Volunteers GROUP BY Year;


Question: What is the average size of affordable housing units in the city of Seattle?

CREATE TABLE AffordableHousing (id INT, city VARCHAR(20), size FLOAT);

SELECT AVG(size) FROM AffordableHousing WHERE city = 'Seattle';


Question: Generate PostgreSQL SQL for: Tell me the position in 2012-13 and number of seasons in leigue 1 of 30 with ligue 1 titles of 1

CREATE TABLE table_name_69 (position_in_2012_13 VARCHAR, number_of_seasons_in_ligue_1 VARCHAR, ligue_1_titles VARCHAR)

SELECT position_in_2012_13 FROM table_name_69 WHERE number_of_seasons_in_ligue_1 = 30 AND ligue_1_titles = 1;


Question: Generate PostgreSQL SQL for: what is the color quality when the relay is ✓?

CREATE TABLE table_name_9 (color_quality VARCHAR, relay VARCHAR)

SELECT color_quality FROM table_name_9 WHERE relay = '✓';


Question: Generate PostgreSQL SQL for: What is the silver medal count of the team that finished with 8 bronze medals?

CREATE TABLE table_name_41 (silver INTEGER, bronze VARCHAR)

SELECT SUM(silver) FROM table_name_41 WHERE bronze = 8;


Question: List all waste types

CREATE TABLE waste_types (id INT PRIMARY KEY, waste_type VARCHAR(255)); INSERT INTO waste_types (id, waste_type) VALUES (1, 'Plastic'), (2, 'Paper');


Question: Generate PostgreSQL SQL for: What club has losses greater than 1, 4 for the wins, with points against less than 894?

CREATE TABLE table_name_83 (club VARCHAR, points_against VARCHAR, loses VARCHAR, wins VARCHAR)

SELECT club FROM table_name_83 WHERE loses > 1 AND wins = 4 AND points_against < 894;


Question: What is the average threat intelligence metric score for the Pacific region in the past week?

CREATE TABLE threat_intelligence (threat_id INT, threat_score INT, threat_region VARCHAR(255), threat_date DATE); INSERT INTO threat_intelligence (threat_id, threat_score, threat_region, threat_date) VALUES (1, 7, 'Pacific', '2021-01-01'); INSERT INTO threat_intelligence (threat_id, threat_score, threat_region, threat_date) VALUES (2, 8, 'Atlantic', '2021-02-01'); INSERT INTO threat_intelligence (threat_id, threat_score, threat_region, threat_date) VALUES (3, 9, 'Pacific', '2021-02-02');

SELECT threat_region, AVG(threat_score) as avg_threat_score FROM threat_intelligence WHERE threat_date >= DATEADD(week, -1, GETDATE()) GROUP BY threat_region;


Question: Generate PostgreSQL SQL for: Which exaltation has a domicile of Saturn and a fall of Jupiter?

CREATE TABLE table_name_98 (exaltation VARCHAR, domicile VARCHAR, fall VARCHAR)

SELECT exaltation FROM table_name_98 WHERE domicile = 'saturn' AND fall = 'jupiter';


Question: What is the average production (bbl) per well in the 'Gulf of Mexico'?

CREATE TABLE well_production (well_id INT, region VARCHAR(20), year INT, production INT); INSERT INTO well_production (well_id, region, year, production) VALUES (1, 'Gulf of Mexico', 2020, 100000), (2, 'Gulf of Mexico', 2019, 120000), (3, 'Alaska', 2020, 150000);

SELECT AVG(production) FROM well_production WHERE region = 'Gulf of Mexico';


Question: Count the number of articles published in the 'culture' section with a word count greater than 1000.

CREATE TABLE articles (id INT, title VARCHAR(255), section VARCHAR(64), word_count INT); INSERT INTO articles (id, title, section, word_count) VALUES (1, 'ArticleA', 'culture', 1200), (2, 'ArticleB', 'politics', 800), (3, 'ArticleC', 'culture', 1500);

SELECT COUNT(*) FROM articles WHERE section = 'culture' AND word_count > 1000;


Question: How many fair trade certified factories are there in Vietnam?

CREATE TABLE FairTradeCertification (factory VARCHAR(50), certification VARCHAR(50)); INSERT INTO FairTradeCertification VALUES ('Factory1', 'Fair Trade'), ('Factory2', 'Not Certified'), ('Factory3', 'Fair Trade'), ('Factory4', 'Not Certified');

SELECT COUNT(*) FROM FairTradeCertification WHERE certification = 'Fair Trade';


Question: Generate PostgreSQL SQL for: What's the date of the first airing of the episode with series number 63?

CREATE TABLE table_10718192_2 (original_air_date VARCHAR, no_in_series VARCHAR)

SELECT original_air_date FROM table_10718192_2 WHERE no_in_series = 63;


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

select jsonb_to_tsvector('english', '{"a": "aaa in bbb", "b": 123, "c": 456, "d": true, "f": false, "g": null}'::jsonb, '{}');

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

SELECT count(*) FROM (select jsonb_to_tsvector('english', '{"a": "aaa in bbb", "b": 123, "c": 456, "d": true, "f": false, "g": null}'::jsonb, '{}')) AS _sub;


Question: Generate PostgreSQL SQL for: What is the name of the captain when teh shirt sponsor is n/a?

CREATE TABLE table_27631756_2 (captain VARCHAR, shirt_sponsor VARCHAR)

SELECT captain FROM table_27631756_2 WHERE shirt_sponsor = 'N/A';


Question: pgTAP test for Coltap (assertion 85).

SELECT * FROM check_test(
    col_default_is( 'public', 'sometab', 'myat', 'now()', 'desc' ),
    true,
    'col_default_is( schema, tab, col, expression, desc )',
    'desc',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Coltap.


Question: Generate PostgreSQL SQL for: Which date was for Japan?

CREATE TABLE table_name_66 (date VARCHAR, country VARCHAR)

SELECT date FROM table_name_66 WHERE country = 'japan';


Question: What is the adoption rate of AI-powered chatbots in 'South America' for 'Q2 2021'?

CREATE TABLE ai_adoption (region VARCHAR(20), quarter INT, adoption_rate DECIMAL(5,2)); INSERT INTO ai_adoption (region, quarter, adoption_rate) VALUES ('North America', 2, 68.50), ('South America', 2, 58.20);

SELECT adoption_rate FROM ai_adoption WHERE region = 'South America' AND quarter = 2;


Question: What is the maximum number of players in a multiplayer game?

CREATE TABLE Games (GameID INT, MaxPlayers INT, Players INT); INSERT INTO Games (GameID, MaxPlayers, Players) VALUES (1, 10, 5);


Question: PostgreSQL regression test 'aggregates': Write the SELECT query (example 378).

select percentile_cont(0.5) within group (order by b), sum(b) from aggtest;

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

SELECT count(*) FROM (select percentile_cont(0.5) within group (order by b), sum(b) from aggtest) AS _sub;


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

SELECT * FROM (VALUES (1),(2),(3)) v(r) LEFT JOIN rngfunc_sql(11,13) ON (r+i)<100;

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

SELECT count(*) FROM (SELECT * FROM (VALUES (1),(2),(3)) v(r) LEFT JOIN rngfunc_sql(11,13) ON (r+i)<100) AS _sub;


Question: Find the total number of investments in the healthcare sector with a risk level above 5.

CREATE TABLE investments (id INT, company_id INT, sector VARCHAR(255), risk_level INT); INSERT INTO investments (id, company_id, sector, risk_level) VALUES (1, 4, 'Healthcare', 6), (2, 5, 'Healthcare', 8), (3, 6, 'Healthcare', 7);

SELECT COUNT(*) FROM investments WHERE sector = 'Healthcare' AND risk_level > 5;


Question: Generate PostgreSQL SQL for: Who was Carlton's away team opponents?

CREATE TABLE table_name_16 (away_team VARCHAR, home_team VARCHAR)

SELECT away_team FROM table_name_16 WHERE home_team = 'carlton';


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

CREATE STATISTICS tst ON x, x, y, x, x, y, x, x, y FROM ext_stats_test;

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


Question: Generate PostgreSQL SQL for: Who is the Best dancer with the Worst dancer of Jerry Springer, a Best score of 29, and the Dance was the Quickstep?

CREATE TABLE table_name_47 (best_dancer VARCHAR, dance VARCHAR, worst_dancer VARCHAR, best_score VARCHAR)

SELECT best_dancer FROM table_name_47 WHERE worst_dancer = 'jerry springer' AND best_score = 29 AND dance = 'quickstep';


Question: Show a SQL definition from the pglogical project (pglogical--2.2.1, item 18).

CREATE TABLE pglogical.replication_set (
    set_id oid NOT NULL PRIMARY KEY,
    set_nodeid oid NOT NULL,
    set_name name NOT NULL,
    replicate_insert boolean NOT NULL DEFAULT true,
    replicate_update boolean NOT NULL DEFAULT true,
    replicate_delete boolean NOT NULL DEFAULT true,
    replicate_truncate boolean NOT NULL DEFAULT true,
    UNIQUE (set_nodeid, set_name)
) WITH (user_catalog_table=true);

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


Question: Generate PostgreSQL SQL for: What is the highest tourism arrivals in 2011 in millions with a 3.82 tourism competitiveness in 2011 and more than 1,102 US$ per arrival in 2011 tourism receipts?

CREATE TABLE table_name_92 (tourist_arrivals__2011___millions_ INTEGER, tourism_competitiveness__2011___ttci_ VARCHAR, tourism_receipts__2011___us$_per_arrival_ VARCHAR)

SELECT MAX(tourist_arrivals__2011___millions_) FROM table_name_92 WHERE tourism_competitiveness__2011___ttci_ = '3.82' AND tourism_receipts__2011___us$_per_arrival_ > 1 OFFSET 102;


Question: What is the minimum budget allocation for any service in CityB for the last fiscal year?

CREATE TABLE fiscal_year (fiscal_year INT, start_date DATE, end_date DATE); INSERT INTO fiscal_year VALUES (2022, '2022-01-01', '2022-12-31'), (2023, '2023-01-01', '2023-12-31'); CREATE TABLE budget_allocation (service VARCHAR(20), fiscal_year INT, amount INT); INSERT INTO budget_allocation VALUES ('Healthcare', 2022, 500000), ('Education', 2022, 800000), ('Healthcare', 2023, 600000), ('Education', 2023, 900000); CREATE TABLE cities (id INT, name VARCHAR(20)); INSERT INTO cities VALUES (1, 'CityA'), (2, 'CityB'), (3, 'CityC');

SELECT MIN(amount) FROM budget_allocation WHERE fiscal_year = (SELECT fiscal_year FROM fiscal_year WHERE start_date <= DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR) AND end_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR)) AND city_id = (SELECT id FROM cities WHERE name = 'CityB');


Question: What is the distribution of genetic research projects by primary investigator gender?

CREATE SCHEMA if not exists genetics;CREATE TABLE if not exists genetics.research_projects (id INT, name VARCHAR(100), primary_investigator VARCHAR(50), primary_investigator_gender VARCHAR(10));INSERT INTO genetics.research_projects (id, name, primary_investigator, primary_investigator_gender) VALUES (1, 'ProjectX', 'Alex Garcia', 'male'), (2, 'ProjectY', 'Taylor Lee', 'non-binary'), (3, 'ProjectZ', 'Claire Kim', 'female');

SELECT primary_investigator_gender, COUNT(*) as total_projects FROM genetics.research_projects GROUP BY primary_investigator_gender;


Question: Write the DML statement from PostgreSQL regression test 'copydml' (example 2).

insert into copydml_test (t) values ('a');

Explanation: DML from PostgreSQL core regression test for Copydml.


Question: Insert a new 'FishHealth' record into the 'FishHealth' table with ID 1, fish ID 2, health score 80, and date entered '2022-07-30 15:00:00'

CREATE TABLE FishHealth (id INT, fish_id INT, health_score INT, date_entered TIMESTAMP);

INSERT INTO FishHealth (id, fish_id, health_score, date_entered) VALUES (1, 2, 80, '2022-07-30 15:00:00');


Question: Retrieve the most recent geopolitical risk rating for India.

CREATE TABLE GeopoliticalRiskAssessments (AssessmentID INT, Country VARCHAR(50), RiskRating VARCHAR(10), AssessmentDate DATE); INSERT INTO GeopoliticalRiskAssessments (AssessmentID, Country, RiskRating, AssessmentDate) VALUES (1, 'Iran', 'High', '2021-06-01'), (2, 'India', 'Medium', '2022-08-12');

SELECT Country, RiskRating FROM GeopoliticalRiskAssessments WHERE AssessmentDate = (SELECT MAX(AssessmentDate) FROM GeopoliticalRiskAssessments WHERE Country = 'India');


Question: Generate PostgreSQL SQL for: what is the mountain peak when the location is 53.1370°n 119.2667°w?

CREATE TABLE table_name_74 (mountain_peak VARCHAR, location VARCHAR)

SELECT mountain_peak FROM table_name_74 WHERE location = '53.1370°n 119.2667°w';


Question: Calculate the average account balance for customers in each city in the USA.

CREATE TABLE customers (id INT, name VARCHAR(100), age INT, gender VARCHAR(10), city VARCHAR(50), state VARCHAR(50), account_balance DECIMAL(10,2));

SELECT city, AVG(account_balance) as avg_balance FROM customers WHERE state = 'USA' GROUP BY city;


Question: Find the average attendance at events in each country.

CREATE TABLE Events (EventID INT, Name TEXT, Attendance INT);CREATE TABLE EventLocations (EventID INT, Country TEXT);

SELECT EventLocations.Country, AVG(Events.Attendance) FROM Events INNER JOIN EventLocations ON Events.EventID = EventLocations.EventID GROUP BY EventLocations.Country;


Question: Generate PostgreSQL SQL for: Which Couple has a Rank by average larger than 3, and an Average larger than 16.5, and a Total smaller than 195, and a Number of dances larger than 3?

CREATE TABLE table_name_20 (couple VARCHAR, number_of_dances VARCHAR, total VARCHAR, rank_by_average VARCHAR, average VARCHAR)

SELECT couple FROM table_name_20 WHERE rank_by_average > 3 AND average > 16.5 AND total < 195 AND number_of_dances > 3;


Question: What is the percentage of games played at home for each team?

CREATE TABLE teams (team_id INT, team_name TEXT, city TEXT); CREATE TABLE games (game_id INT, team_id INT, home BOOLEAN);

SELECT t.team_name, (SUM(g.home) * 100.0 / COUNT(g.game_id)) as home_percentage FROM games g JOIN teams t ON g.team_id = t.team_id GROUP BY t.team_name;


Question: How many users signed up for the 'Elite' membership in the last quarter?

CREATE TABLE memberships (membership_id INT, membership_type VARCHAR(50), signup_date DATE); INSERT INTO memberships (membership_id, membership_type, signup_date) VALUES (1, 'Basic', '2022-01-10'), (2, 'Premium', '2022-02-15'), (3, 'Elite', '2022-03-20'), (4, 'Basic', '2022-04-05');

SELECT membership_type, COUNT(membership_id) as new_members FROM memberships WHERE membership_type = 'Elite' AND signup_date >= DATEADD(quarter, -1, CURRENT_DATE) GROUP BY membership_type;


Question: Generate PostgreSQL SQL for: What is the first date of election for the incumbent that was re-elected in the South Carolina 1 district?

CREATE TABLE table_name_45 (first_elected VARCHAR, result VARCHAR, district VARCHAR)

SELECT first_elected FROM table_name_45 WHERE result = 're-elected' AND district = 'south carolina 1';


Question: Generate PostgreSQL SQL for: What is the party of re-elected, incumbent Charles H. Grosvenor, who was first elected before 1894?

CREATE TABLE table_name_3 (party VARCHAR, incumbent VARCHAR, result VARCHAR, first_elected VARCHAR)

SELECT party FROM table_name_3 WHERE result = 're-elected' AND first_elected < 1894 AND incumbent = 'charles h. grosvenor';


Question: What was the maximum price of kids' garments in Australia?

CREATE TABLE Categories (category_id INT, category VARCHAR(50), PRIMARY KEY (category_id)); INSERT INTO Categories (category_id, category) VALUES (1, 'Kids'), (2, 'Adults');

SELECT MAX(price) as max_price FROM Products JOIN Categories ON Products.category = Categories.category WHERE Categories.category = 'Kids' AND Products.country = 'Australia';


Question: Generate PostgreSQL SQL for: Name the number of points for field goals being 1

CREATE TABLE table_14342480_6 (points VARCHAR, field_goals VARCHAR)

SELECT COUNT(points) FROM table_14342480_6 WHERE field_goals = 1;


Question: Generate PostgreSQL SQL for: What is the comp for games less than 2?

CREATE TABLE table_name_63 (comp VARCHAR, games INTEGER)

SELECT comp FROM table_name_63 WHERE games < 2;


Question: What is the minimum R&D expenditure for drugs approved in 2017?

CREATE TABLE rd_expenditure (drug_id VARCHAR(10), approval_year INT, expenditure NUMERIC(12,2));

SELECT MIN(expenditure) FROM rd_expenditure WHERE approval_year = 2017;


Question: List the unique types of healthcare facilities in 'rural' areas, excluding pharmacies.

CREATE TABLE healthcare_facilities (id INT, name TEXT, location TEXT, type TEXT); INSERT INTO healthcare_facilities (id, name, location, type) VALUES (1, 'Hospital A', 'rural', 'hospital'); INSERT INTO healthcare_facilities (id, name, location, type) VALUES (2, 'Clinic A', 'rural', 'clinic'); INSERT INTO healthcare_facilities (id, name, location, type) VALUES (3, 'Pharmacy A', 'rural', 'pharmacy');

SELECT DISTINCT type FROM healthcare_facilities WHERE location = 'rural' AND type != 'pharmacy';


Question: How many circular supply chain vendors are there in each region?

CREATE TABLE vendors (vendor_id INT, vendor_name TEXT, region TEXT); INSERT INTO vendors (vendor_id, vendor_name, region) VALUES (1, 'Green Vendors', 'Northeast'); INSERT INTO vendors (vendor_id, vendor_name, region) VALUES (2, 'Eco-Friendly Vendors', 'West');

SELECT region, COUNT(*) FROM vendors GROUP BY region;


Question: Generate PostgreSQL SQL for: The match against Paul-Henri Mathieu had what outcome?

CREATE TABLE table_name_92 (outcome VARCHAR, opponent VARCHAR)

SELECT outcome FROM table_name_92 WHERE opponent = 'paul-henri mathieu';


Question: Generate PostgreSQL SQL for: Which university hosted in Long Beach?

CREATE TABLE table_name_12 (host VARCHAR, city VARCHAR)

SELECT host FROM table_name_12 WHERE city = 'long beach';


Question: What is the total number of military aircraft in the 'Military_Aircraft' table?

CREATE SCHEMA IF NOT EXISTS defense_security;CREATE TABLE IF NOT EXISTS defense_security.Military_Aircraft (id INT PRIMARY KEY, aircraft_name VARCHAR(255), type VARCHAR(255), quantity INT);INSERT INTO defense_security.Military_Aircraft (id, aircraft_name, type, quantity) VALUES (1, 'F-16 Fighting Falcon', 'Fighter', 1000), (2, 'B-52 Stratofortress', 'Bomber', 76);

SELECT SUM(quantity) FROM defense_security.Military_Aircraft;


Question: What are the names of all rural infrastructure projects in the 'rural_infrastructure_2' table?

CREATE TABLE rural_infrastructure_2 (id INT, project_name VARCHAR(50), sector VARCHAR(50)); INSERT INTO rural_infrastructure_2 (id, project_name, sector) VALUES (3, 'Smart Irrigation', 'Rural Infrastructure'), (4, 'Rural Connectivity', 'Rural Infrastructure');

SELECT project_name FROM rural_infrastructure_2 WHERE sector = 'Rural Infrastructure';


Question: What is the minimum budget allocated for technology for social good projects in Oceania countries?

CREATE TABLE SocialGoodBudget (Country VARCHAR(50), Budget DECIMAL(10,2)); INSERT INTO SocialGoodBudget (Country, Budget) VALUES ('Australia', 1200000.00), ('New Zealand', 1500000.00); CREATE TABLE Countries (Country VARCHAR(50), Continent VARCHAR(50)); INSERT INTO Countries (Country, Continent) VALUES ('Australia', 'Oceania'), ('New Zealand', 'Oceania');

SELECT MIN(SocialGoodBudget.Budget) AS MinBudget FROM SocialGoodBudget INNER JOIN Countries ON SocialGoodBudget.Country = Countries.Country WHERE Countries.Continent = 'Oceania';


Question: What was the average revenue per shipment for the month of January 2022?

CREATE TABLE shipments (shipment_id INT, shipment_date DATE, revenue DECIMAL(10,2)); INSERT INTO shipments (shipment_id, shipment_date, revenue) VALUES (1, '2022-01-01', 1000), (2, '2022-01-05', 2000), (3, '2022-02-03', 3000);

SELECT AVG(revenue) FROM shipments WHERE shipment_date BETWEEN '2022-01-01' AND '2022-01-31';


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


Question: Delete the records in the expedition_researchers table for the expedition 'Expedition2'.

CREATE TABLE expeditions (id INT PRIMARY KEY, name VARCHAR(50), location VARCHAR(50), start_date DATE, end_date DATE); CREATE TABLE researchers (id INT PRIMARY KEY, name VARCHAR(50), affiliation VARCHAR(50)); CREATE TABLE expedition_researchers AS SELECT NULL id, e.name AS expedition, r.name AS researcher FROM expeditions e JOIN researchers r ON TRUE WHERE e.location = r.affiliation;

DELETE FROM expedition_researchers WHERE expedition = 'Expedition2';


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

SELECT count(*) FROM (SELECT min(row(a,b)) FROM aggtest) AS _sub;


Question: What is the total cost of all lifelong learning programs offered in the region of Paris?

CREATE TABLE regions (region_name VARCHAR(255), region_id INT); CREATE TABLE lifelong_learning_programs (program_id INT, program_name VARCHAR(255), region_id INT, program_cost DECIMAL(10,2), PRIMARY KEY (program_id), FOREIGN KEY (region_id) REFERENCES regions(region_id));

SELECT SUM(lifelong_learning_programs.program_cost) FROM lifelong_learning_programs INNER JOIN regions ON lifelong_learning_programs.region_id = regions.region_id WHERE regions.region_name = 'Paris';


Question: What is the total cargo weight handled by container ships built before 2010, grouped by ship builder?

CREATE TABLE container_ships (ship_id INT, ship_name VARCHAR(255), ship_builder VARCHAR(255), year INT, cargo_weight INT);INSERT INTO container_ships (ship_id, ship_name, ship_builder, year, cargo_weight) VALUES (1, 'Ever Given', 'Baosteel', 2010, 210000), (2, 'CMA CGM Marco Polo', 'Daewoo Shipbuilding & Marine Engineering', 2008, 165000);

SELECT ship_builder, SUM(cargo_weight) FROM container_ships WHERE year < 2010 GROUP BY ship_builder;


Question: What is the total number of military innovation projects and their average budget in Europe?

CREATE TABLE MilitaryInnovationEurope (id INT, project VARCHAR(50), country VARCHAR(50), budget INT); INSERT INTO MilitaryInnovationEurope (id, project, country, budget) VALUES (1, 'Stealth Technology', 'UK', 12000000), (2, 'Cyber Warfare', 'Germany', 9000000), (3, 'Artificial Intelligence', 'France', 11000000);

SELECT COUNT(*) AS total_projects, AVG(budget) AS avg_budget FROM MilitaryInnovationEurope;


Question: Generate PostgreSQL SQL for: Give me the name and year of opening of the manufacturers that have either less than 10 factories or more than 10 shops.

CREATE TABLE manufacturer (name VARCHAR, open_year VARCHAR, num_of_shops VARCHAR, Num_of_Factories VARCHAR)

SELECT name, open_year FROM manufacturer WHERE num_of_shops > 10 OR Num_of_Factories < 10;


Question: Generate PostgreSQL SQL for: Who was the home team of the game at the time of 14:00?

CREATE TABLE table_name_53 (home VARCHAR, time VARCHAR)

SELECT home FROM table_name_53 WHERE time = '14:00';


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

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


Question: Write the DML statement from PostgreSQL regression test 'sqljson_queryfuncs' (example 202).

INSERT INTO test_jsonb_constraints VALUES ('{"a": 1}', 1);

Explanation: DML from PostgreSQL core regression test for Sqljson Queryfuncs.


Question: Find the total area of all buildings in the 'green_buildings' table

CREATE TABLE green_buildings (id INT, name VARCHAR(50), location VARCHAR(50), area FLOAT, sustainability_rating INT);


Question: List the number of healthcare providers in each county, for counties with more than 50 providers.

CREATE TABLE healthcare_providers (id INT, county VARCHAR(10), count INT); INSERT INTO healthcare_providers (id, county, count) VALUES (1, 'County 1', 120), (2, 'County 2', 80), (3, 'County 3', 150), (4, 'County 4', 70), (5, 'County 5', 110);

SELECT county, count FROM healthcare_providers WHERE count > 50 GROUP BY county;


Question: What is the total revenue generated by the Louvre from Impressionist paintings between 1950 and 1970?

CREATE TABLE Artworks (artwork_id INT, name VARCHAR(255), artist_id INT, date_sold DATE, price DECIMAL(10,2), museum_id INT); CREATE TABLE Artists (artist_id INT, name VARCHAR(255), nationality VARCHAR(255), gender VARCHAR(255)); CREATE TABLE Museums (museum_id INT, name VARCHAR(255));

SELECT SUM(Artworks.price) FROM Artworks INNER JOIN Artists ON Artworks.artist_id = Artists.artist_id INNER JOIN Museums ON Artworks.museum_id = Museums.museum_id WHERE Artists.nationality = 'Impressionist' AND Museums.name = 'The Louvre' AND YEAR(Artworks.date_sold) BETWEEN 1950 AND 1970;


Question: Generate PostgreSQL SQL for: What is the Score of the Competition with a Result of 5-0?

CREATE TABLE table_name_7 (score VARCHAR, result VARCHAR)

SELECT score FROM table_name_7 WHERE result = '5-0';


Question: Generate PostgreSQL SQL for: Where does Essendon play their home games?

CREATE TABLE table_name_38 (venue VARCHAR, home_team VARCHAR)

SELECT venue FROM table_name_38 WHERE home_team = 'essendon';


Question: Find the energy efficiency rating for a specific appliance model.

CREATE TABLE appliance_ratings (appliance_model VARCHAR(255), energy_efficiency_rating FLOAT); INSERT INTO appliance_ratings VALUES ('Model A', 4.5), ('Model B', 3.8), ('Model C', 5.0), ('Model D', 4.2), ('Model E', 4.8);

SELECT energy_efficiency_rating FROM appliance_ratings WHERE appliance_model = 'Model C';


Question: What is the total carbon emissions reduction achieved by clean energy projects in the US since 2015?

CREATE TABLE projects (id INT, country VARCHAR(255), name VARCHAR(255), carbon_emissions_reduction INT, start_year INT); INSERT INTO projects (id, country, name, carbon_emissions_reduction, start_year) VALUES (1, 'US', 'Project1', 1500, 2015), (2, 'US', 'Project2', 2000, 2017), (3, 'US', 'Project3', 1000, 2016);

SELECT SUM(carbon_emissions_reduction) FROM projects WHERE country = 'US' AND start_year >= 2015;


Question: pgTAP test for Aretap (assertion 43).

SELECT * FROM check_test(
    tables_are( ARRAY['fou', 'foo'] ),
    true,
    'tables_are(tables)',
    'Search path ' || pg_catalog.current_setting('search_path') || ' should have the correct tables',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Aretap.