Question: PostgreSQL regression test 'int2': Write the SELECT query (example 15).

SELECT * FROM pg_input_error_info('1 asdf', 'int2vector');

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

SELECT count(*) FROM (SELECT * FROM pg_input_error_info('1 asdf', 'int2vector')) AS _sub;


Question: Generate PostgreSQL SQL for: What are the death and injury situations caused by the ship with tonnage 't'?

CREATE TABLE ship (Id VARCHAR); CREATE TABLE death (killed VARCHAR, injured VARCHAR, caused_by_ship_id VARCHAR)

SELECT T1.killed, T1.injured FROM death AS T1 JOIN ship AS t2 ON T1.caused_by_ship_id = T2.id WHERE T2.tonnage = 't';


Question: Generate PostgreSQL SQL for: What is the number for Chauchilla Cemetery Battle with less than 511 pieces?

CREATE TABLE table_name_54 (number INTEGER, pieces VARCHAR, name VARCHAR)

SELECT AVG(number) FROM table_name_54 WHERE pieces < 511 AND name = 'chauchilla cemetery battle';


Question: Find the intersection of open data sets related to diversity in 'state', 'county', and 'city' schemas.

CREATE SCHEMA state; CREATE SCHEMA county; CREATE SCHEMA city; CREATE TABLE state.diversity_data (id INT, name VARCHAR(255), is_open BOOLEAN); CREATE TABLE county.diversity_data (id INT, name VARCHAR(255), is_open BOOLEAN); CREATE TABLE city.diversity_data (id INT, name VARCHAR(255), is_open BOOLEAN); INSERT INTO state.diversity_data (id, name, is_open) VALUES (1, 'population', true), (2, 'workforce', true); INSERT INTO county.diversity_data (id, name, is_open) VALUES (1, 'population', true), (2, 'workforce', true); INSERT INTO city.diversity_data (id, name, is_open) VALUES (1, 'population', true), (2, 'workforce', true), (3, 'elected_officials', true);

SELECT * FROM ( (SELECT * FROM state.diversity_data WHERE is_open = true) INTERSECT (SELECT * FROM county.diversity_data WHERE is_open = true) INTERSECT (SELECT * FROM city.diversity_data WHERE is_open = true) ) AS intersected_data;


Question: Generate PostgreSQL SQL for: What circuit was the British Grand Prix?

CREATE TABLE table_name_92 (circuit VARCHAR, race VARCHAR)

SELECT circuit FROM table_name_92 WHERE race = 'british grand prix';


Question: Generate PostgreSQL SQL for: What number is Fall 06 from the state with 34 for Fall 09?

CREATE TABLE table_name_97 (fall_06 INTEGER, fall_09 VARCHAR)

SELECT AVG(fall_06) FROM table_name_97 WHERE fall_09 = 34;


Question: What is the total carbon sequestration potential for each region in the 'region_sequestration' table?

CREATE TABLE region_sequestration (id INT, region VARCHAR(255), total_sequestration FLOAT); INSERT INTO region_sequestration (id, region, total_sequestration) VALUES (1, 'North', 5000.0), (2, 'South', 6000.0), (3, 'East', 4500.0), (4, 'West', 7000.0);

SELECT region, SUM(total_sequestration) FROM region_sequestration GROUP BY region;


Question: Generate PostgreSQL SQL for: What is the main presenter of bulgaria?

CREATE TABLE table_1053802_1 (main_presenters VARCHAR, region_country VARCHAR)

SELECT main_presenters FROM table_1053802_1 WHERE region_country = 'Bulgaria';


Question: What is the total number of streams and albums sold by artists who have won a Grammy award?

CREATE TABLE Artists (ArtistID INT, ArtistName VARCHAR(100), GrammyWinner BOOLEAN); INSERT INTO Artists (ArtistID, ArtistName, GrammyWinner) VALUES (1, 'Taylor Swift', TRUE), (2, 'Green Day', FALSE); CREATE TABLE MusicStreams (StreamID INT, SongID INT, ArtistID INT); INSERT INTO MusicStreams (StreamID, SongID, ArtistID) VALUES (1, 1, 1), (2, 2, 2); CREATE TABLE Albums (AlbumID INT, AlbumName VARCHAR(100), ArtistID INT); INSERT INTO Albums (AlbumID, AlbumName, ArtistID) VALUES (1, 'Fearless', 1), (2, 'American Idiot', 2);

SELECT COUNT(DISTINCT ms.StreamID) + COUNT(DISTINCT a.AlbumID) AS TotalReleases FROM Artists a JOIN MusicStreams ms ON a.ArtistID = ms.ArtistID JOIN Albums al ON a.ArtistID = al.ArtistID WHERE GrammyWinner = TRUE;


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

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


Question: Generate PostgreSQL SQL for: What is the type for rank 2?

CREATE TABLE table_name_26 (type VARCHAR, rank VARCHAR)

SELECT type FROM table_name_26 WHERE rank = 2;


Question: How many donors live in 'Brazil'?

CREATE TABLE donors (donor_id INT, donor_name TEXT, donation_amount DECIMAL(10,2), country TEXT); INSERT INTO donors (donor_id, donor_name, donation_amount, country) VALUES (1, 'John Doe', 500.00, 'United States'); INSERT INTO donors (donor_id, donor_name, donation_amount, country) VALUES (2, 'Jane Smith', 300.00, 'Canada'); INSERT INTO donors (donor_id, donor_name, donation_amount, country) VALUES (3, 'Jose Garcia', 250.00, 'Brazil');

SELECT COUNT(*) FROM donors WHERE country = 'Brazil';


Question: What is the total number of articles published in 'San Francisco Chronicle' and 'Denver Post' in 2020?

CREATE TABLE SFC_Articles(id INT, title VARCHAR(50), publication DATE, category VARCHAR(20));CREATE TABLE DP_Articles(id INT, title VARCHAR(50), publication DATE, category VARCHAR(20));

SELECT COUNT(*) FROM (SELECT * FROM SFC_Articles WHERE publication BETWEEN '2020-01-01' AND '2020-12-31' UNION ALL SELECT * FROM DP_Articles WHERE publication BETWEEN '2020-01-01' AND '2020-12-31') t;


Question: What is the average budget for humanitarian aid programs in the Middle East?

CREATE TABLE programs (id INT, program_name VARCHAR(50), program_type VARCHAR(20), org_id INT, start_date DATE, end_date DATE, budget DECIMAL(10,2));

SELECT AVG(budget) FROM programs WHERE program_type = 'Humanitarian Aid' AND country_code = 'ME';


Question: Count the number of creative AI applications by type

CREATE TABLE creative_ai (application_name TEXT, application_type TEXT); INSERT INTO creative_ai (application_name, application_type) VALUES ('App1', 'Image Generation'), ('App2', 'Text Generation'), ('App3', 'Music Generation');

SELECT application_type, COUNT(*) FROM creative_ai GROUP BY application_type;


Question: Generate PostgreSQL SQL for: Name the circuit for hertz british grand prix

CREATE TABLE table_27948565_1 (circuit VARCHAR, grand_prix VARCHAR)

SELECT circuit FROM table_27948565_1 WHERE grand_prix = 'Hertz British grand_prix';


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

SELECT * FROM test_name WHERE i>='abc'::text ORDER BY i;

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


Question: What is the minimum salary for data scientists in 'tech_salaries' table?

CREATE TABLE tech_salaries (position VARCHAR(50), employee_name VARCHAR(50), salary INTEGER, company_location VARCHAR(50));

SELECT MIN(salary) FROM tech_salaries WHERE position = 'Data Scientist';


Question: Generate PostgreSQL SQL for: What was the series standing after game 1?

CREATE TABLE table_name_5 (series VARCHAR, game VARCHAR)

SELECT series FROM table_name_5 WHERE game = 1;


Question: Update the artist name 'Eminem' to 'Marshall Mathers' in the MusicArtists table.

CREATE TABLE MusicArtists (artist_id INT, artist_name VARCHAR(50), genre VARCHAR(20));

UPDATE MusicArtists SET artist_name = 'Marshall Mathers' WHERE artist_name = 'Eminem';


Question: Update the rating of 'Breaking Bad' to 4.9.

CREATE TABLE tv_shows (show_id INT, title VARCHAR(100), release_year INT, rating FLOAT); INSERT INTO tv_shows (show_id, title, release_year, rating) VALUES (1, 'Game of Thrones', 2011, 4.1), (2, 'Stranger Things', 2016, 4.6), (3, 'Breaking Bad', 2008, 4.8);

UPDATE tv_shows SET rating = 4.9 WHERE title = 'Breaking Bad';


Question: How many mental health parity violations were reported in California and Texas in 2020 and 2021?

CREATE TABLE MentalHealthParityViolations (Id INT, State VARCHAR(2), Year INT, ViolationCount INT); INSERT INTO MentalHealthParityViolations (Id, State, Year, ViolationCount) VALUES (1, 'CA', 2020, 120), (2, 'TX', 2020, 150), (3, 'CA', 2021, 145), (4, 'TX', 2021, 175), (5, 'NY', 2020, 105), (6, 'FL', 2021, 130);

SELECT State, SUM(ViolationCount) as TotalViolations FROM MentalHealthParityViolations WHERE State IN ('CA', 'TX') AND Year BETWEEN 2020 AND 2021 GROUP BY State;


Question: Which country has the highest revenue in skincare products?

CREATE TABLE CountrySales (country VARCHAR(255), category VARCHAR(255), revenue FLOAT);

SELECT country, MAX(revenue) FROM CountrySales WHERE category = 'Skincare' GROUP BY country;


Question: Generate PostgreSQL SQL for: What is the time for Moscow, Russia?

CREATE TABLE table_name_62 (time VARCHAR, location VARCHAR)

SELECT time FROM table_name_62 WHERE location = 'moscow, russia';


Question: What is the total number of volunteers and total donation amount for each organization in a given year?

CREATE TABLE organization (id INT, name VARCHAR(255)); CREATE TABLE volunteer (id INT, name VARCHAR(255), organization_id INT, volunteer_date DATE); CREATE TABLE donation (id INT, donor_id INT, organization_id INT, amount DECIMAL(10,2), donation_date DATE);

SELECT o.name, COUNT(v.id) as total_volunteers, SUM(d.amount) as total_donations FROM volunteer v JOIN organization o ON v.organization_id = o.id JOIN donation d ON o.id = d.organization_id WHERE YEAR(v.volunteer_date) = 2022 AND YEAR(d.donation_date) = 2022 GROUP BY o.id;


Question: How many cybersecurity incidents were reported by the defense industry in 2020?

CREATE TABLE Cybersecurity_Incidents (id INT, industry VARCHAR(50), year INT, reported_count INT);

SELECT SUM(reported_count) FROM Cybersecurity_Incidents WHERE industry = 'defense' AND year = 2020;


Question: Which social issues have the highest impact scores in projects located in Southeast Asia?

CREATE TABLE social_issues (id INT PRIMARY KEY, name VARCHAR(255), impact_score INT);CREATE TABLE projects (id INT PRIMARY KEY, name VARCHAR(255), location VARCHAR(255), budget DECIMAL(10,2));CREATE TABLE project_issues (project_id INT, issue_id INT, PRIMARY KEY (project_id, issue_id));CREATE VIEW high_impact_issues AS SELECT * FROM social_issues WHERE impact_score >= 75;

SELECT p.name, p.location, si.name as issue, si.impact_score FROM projects p JOIN project_issues pi ON p.id = pi.project_id JOIN social_issues si ON pi.issue_id = si.id WHERE p.location = 'Southeast Asia' AND si.impact_score IN (SELECT impact_score FROM high_impact_issues);


Question: Display the number of threat intelligence records and their source by month

SELECT EXTRACT(MONTH FROM record_date) as month, source, COUNT(*) as records FROM threat_monthly GROUP BY month, source;


Question: Generate PostgreSQL SQL for: What is the quantity when the seats number was 16 and the class was kss 1913?

CREATE TABLE table_name_67 (quantity VARCHAR, seats VARCHAR, class VARCHAR)

SELECT quantity FROM table_name_67 WHERE seats = 16 AND class = 'kss 1913';


Question: What is the percentage of social equity participation for each program in the last year, and the corresponding average participation percentage?

CREATE TABLE dispensaries (id INT PRIMARY KEY, name VARCHAR(255), location VARCHAR(255)); CREATE TABLE social_equity_programs (id INT PRIMARY KEY, dispensary_id INT, program_name VARCHAR(255), start_date DATE); CREATE TABLE social_equity_participation (id INT PRIMARY KEY, dispensary_id INT, year INT, percentage FLOAT);

SELECT program_name, AVG(percentage) as avg_percentage FROM social_equity_programs INNER JOIN social_equity_participation ON social_equity_programs.id = social_equity_participation.dispensary_id WHERE YEAR(social_equity_participation.year) = YEAR(CURRENT_DATE) - 1 GROUP BY program_name;


Question: What is the average price of eco-friendly materials sourced from Latin America?

CREATE TABLE eco_materials (id INT, material VARCHAR(50), source_country VARCHAR(50), price DECIMAL(10,2)); INSERT INTO eco_materials (id, material, source_country, price) VALUES (1, 'organic cotton', 'Peru', 2.50), (2, 'recycled polyester', 'Brazil', 3.20), (3, 'Tencel', 'Brazil', 4.50);

SELECT AVG(price) FROM eco_materials WHERE source_country = 'Brazil' OR source_country = 'Peru';


Question: How many artifacts are made of gold in Peru?

CREATE TABLE Site (SiteID INT PRIMARY KEY, SiteName VARCHAR(50), Country VARCHAR(50), City VARCHAR(50)); INSERT INTO Site (SiteID, SiteName, Country, City) VALUES (7, 'Machu Picchu', 'Peru', 'Cuzco'); CREATE TABLE Artifact (ArtifactID INT PRIMARY KEY, SiteID INT, ArtifactName VARCHAR(50), Material VARCHAR(50), Era VARCHAR(50)); INSERT INTO Artifact (ArtifactID, SiteID, ArtifactName, Material, Era) VALUES (6, 2, 'Golden Mask', 'Gold', 'Inca'), (7, 7, 'Golden Idol', 'Gold', 'Inca');

SELECT COUNT(*) FROM Artifact WHERE Material = 'Gold' AND SiteID = (SELECT SiteID FROM Site WHERE SiteName = 'Machu Picchu');


Question: Generate PostgreSQL SQL for: What is the finish with 200 laps and a start of 3?

CREATE TABLE table_name_91 (finish VARCHAR, laps VARCHAR, start VARCHAR)

SELECT finish FROM table_name_91 WHERE laps = 200 AND start = '3';


Question: Generate PostgreSQL SQL for: What are all the profits elegance (2007) in which mayor is ma. Ester a. Hamor

CREATE TABLE table_255812_1 (income_class__2007_ VARCHAR, mayor VARCHAR)

SELECT income_class__2007_ FROM table_255812_1 WHERE mayor = 'Ma. Ester A. Hamor';


Question: Generate PostgreSQL SQL for: How many years saw 3 hurricanes wherein the strongest storm was level three?

CREATE TABLE table_2930244_2 (year VARCHAR, number_of_hurricanes VARCHAR, strongest_storm VARCHAR)

SELECT COUNT(year) FROM table_2930244_2 WHERE number_of_hurricanes = 3 AND strongest_storm = 'Three';


Question: Generate PostgreSQL SQL for: How many golds does the nation having a rank of 8, fewer than 5 bronzes and more than 1 silver have?

CREATE TABLE table_name_62 (gold VARCHAR, rank VARCHAR, bronze VARCHAR, silver VARCHAR)

SELECT COUNT(gold) FROM table_name_62 WHERE bronze < 5 AND silver > 1 AND rank > 8;


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

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

SELECT count(*) FROM (SELECT sum2(q1,q2) FROM int8_tbl) AS _sub;


Question: What is the minimum depth of any marine protected area in the Pacific region?

CREATE TABLE marine_protected_areas (name VARCHAR(255), location VARCHAR(255), depth FLOAT); INSERT INTO marine_protected_areas (name, location, depth) VALUES ('MPA 1', 'Pacific', 120.5); INSERT INTO marine_protected_areas (name, location, depth) VALUES ('MPA 2', 'Atlantic', 200.3);

SELECT MIN(depth) FROM marine_protected_areas WHERE location = 'Pacific';


Question: Generate PostgreSQL SQL for: what is the soap opera when the years are 2000–2004, 2005—?

CREATE TABLE table_name_10 (soap_opera VARCHAR, years VARCHAR)

SELECT soap_opera FROM table_name_10 WHERE years = '2000–2004, 2005—';


Question: Generate PostgreSQL SQL for: What Class has 36 Points?

CREATE TABLE table_name_68 (class VARCHAR, points VARCHAR)

SELECT class FROM table_name_68 WHERE points = 36;


Question: How many safety inspections have been conducted on fishing vessels in the past year?

CREATE TABLE vessel (id INT, type VARCHAR(50), name VARCHAR(50));CREATE TABLE safety_inspection (id INT, vessel_id INT, inspection_date DATE);

SELECT COUNT(si.id) as total_inspections FROM vessel v INNER JOIN safety_inspection si ON v.id = si.vessel_id WHERE v.type = 'fishing' AND si.inspection_date >= DATE(NOW(), INTERVAL -1 YEAR);


Question: How many cities in the 'transportation' schema have more than 10000 electric vehicles?

CREATE TABLE city_electric_vehicles (city_name VARCHAR(255), num_electric_vehicles INT); INSERT INTO city_electric_vehicles (city_name, num_electric_vehicles) VALUES ('San Francisco', 15000), ('Los Angeles', 20000), ('New York', 30000);

SELECT COUNT(*) FROM (SELECT city_name FROM city_electric_vehicles WHERE num_electric_vehicles > 10000 GROUP BY city_name) AS subquery;


Question: Generate PostgreSQL SQL for: What is the 2011 when the 2007 is a, and the 2012 is sf?

SELECT 2011 FROM table_name_58 WHERE 2007 = 'a' AND 2012 = 'sf';


Question: What is the maximum response time for emergency calls and fire incidents in the last month in Miami, FL?

CREATE TABLE emergency_calls (id INT, date DATE, response_time INT, city VARCHAR(20), state VARCHAR(20)); INSERT INTO emergency_calls (id, date, response_time, city, state) VALUES (1, '2022-01-01', 10, 'Miami', 'FL'), (2, '2022-01-02', 20, 'Miami', 'FL'); CREATE TABLE fire_incidents (id INT, date DATE, response_time INT, city VARCHAR(20), state VARCHAR(20)); INSERT INTO fire_incidents (id, date, response_time, city, state) VALUES (1, '2022-01-01', 15, 'Miami', 'FL'), (2, '2022-01-02', 25, 'Miami', 'FL');

SELECT 'emergency calls' AS type, MAX(response_time) FROM emergency_calls WHERE date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH) AND city = 'Miami' AND state = 'FL' UNION ALL SELECT 'fire incidents' AS type, MAX(response_time) FROM fire_incidents WHERE date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH) AND city = 'Miami' AND state = 'FL';


Question: Generate PostgreSQL SQL for: What is the earliest year of disaffiliation of a CHCH-TV station, licensed in Hamilton, Ontario?

CREATE TABLE table_name_74 (year_of_disaffiliation INTEGER, city_of_license_market VARCHAR)

SELECT MIN(year_of_disaffiliation) FROM table_name_74 WHERE city_of_license_market = 'hamilton, ontario';


Question: Calculate the total expenditure on community development initiatives in Indonesia for 2021 and 2022.

CREATE TABLE community_initiatives (id INT, country VARCHAR(50), initiative VARCHAR(50), year INT, expenditure DECIMAL(10,2)); INSERT INTO community_initiatives (id, country, initiative, year, expenditure) VALUES (1, 'Indonesia', 'Healthcare Center', 2021, 180000.00), (2, 'Indonesia', 'Education Building', 2022, 220000.00);

SELECT SUM(expenditure) FROM community_initiatives WHERE country = 'Indonesia' AND year IN (2021, 2022);


Question: Generate PostgreSQL SQL for: Name the january when april is courtney rachel culkin

CREATE TABLE table_name_53 (january VARCHAR, april VARCHAR)

SELECT january FROM table_name_53 WHERE april = 'courtney rachel culkin';


Question: Generate PostgreSQL SQL for: What is Notes, when Silver is "Jarkko Huovila"?

CREATE TABLE table_name_3 (notes VARCHAR, silver VARCHAR)

SELECT notes FROM table_name_3 WHERE silver = 'jarkko huovila';


Question: Show a SQL definition from the pg_partman project (pg_partman--4.5.0--4.5.1, item 4).

CREATE OR REPLACE FUNCTION @extschema@.check_epoch_type (p_type text) RETURNS boolean
    LANGUAGE plpgsql IMMUTABLE SECURITY DEFINER
    SET search_path TO pg_catalog, pg_temp
    AS $$
DECLARE
v_result    boolean;
BEGIN
    SELECT p_type IN ('none', 'seconds', 'milliseconds') INTO v_result;
    RETURN v_result;
END
$$;

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


Question: Calculate the total funding for startups founded in each year

CREATE TABLE startups (id INT, name VARCHAR(255), year_founded INT, total_funding INT); INSERT INTO startups (id, name, year_founded, total_funding) VALUES (1, 'Acme Inc', 2010, 5000000), (2, 'Beta Corp', 2012, 8000000), (3, 'Gamma Inc', 2015, 3000000), (4, 'Delta Ltd', 2018, 7000000);

SELECT year_founded AS founded_year, SUM(total_funding) as total_funding FROM startups GROUP BY year_founded;


Question: Generate PostgreSQL SQL for: What is the home team's score for north melbourne?

CREATE TABLE table_name_57 (home_team VARCHAR)

SELECT home_team AS score FROM table_name_57 WHERE home_team = 'north melbourne';


Question: Delete models from Italy with a safety score less than 0.75.

CREATE TABLE models_italy (model_id INT, name VARCHAR(255), country VARCHAR(255), safety_score FLOAT); INSERT INTO models_italy (model_id, name, country, safety_score) VALUES (1, 'ModelA', 'Italy', 0.82), (2, 'ModelB', 'Italy', 0.68), (3, 'ModelC', 'Italy', 0.90);

DELETE FROM models_italy WHERE safety_score < 0.75 AND country = 'Italy';


Question: Generate PostgreSQL SQL for: How much A-League has a Pre-Season larger than 0?

CREATE TABLE table_name_85 (a_league VARCHAR, pre_season INTEGER)

SELECT COUNT(a_league) FROM table_name_85 WHERE pre_season > 0;


Question: Generate PostgreSQL SQL for: What is the name of the airport with an ICAO of ULLI?

CREATE TABLE table_name_40 (airport VARCHAR, icao VARCHAR)

SELECT airport FROM table_name_40 WHERE icao = 'ulli';


Question: Generate PostgreSQL SQL for: What Player is from the College of memphis?

CREATE TABLE table_name_5 (player VARCHAR, college VARCHAR)

SELECT player FROM table_name_5 WHERE college = 'memphis';


Question: Generate PostgreSQL SQL for: Which Partner has a Tournament of catella swedish open?

CREATE TABLE table_name_13 (partner VARCHAR, tournament VARCHAR)

SELECT partner FROM table_name_13 WHERE tournament = 'catella swedish open';


Question: What is the average quantity of 'Organic Silk' used by each brand?

CREATE TABLE Brands (BrandID INT, BrandName VARCHAR(50), Material VARCHAR(50), Quantity INT);INSERT INTO Brands (BrandID, BrandName, Material, Quantity) VALUES (1, 'BrandA', 'Organic Cotton', 3000), (2, 'BrandB', 'Recycled Polyester', 2500), (1, 'BrandA', 'Organic Silk', 1000), (3, 'BrandC', 'Organic Cotton', 2000), (2, 'BrandB', 'Tencel', 1800);

SELECT BrandName, AVG(Quantity) as AvgQuantity FROM Brands WHERE Material = 'Organic Silk' GROUP BY BrandName;


Question: Generate PostgreSQL SQL for: Which party had a Retired Democratic hold?

CREATE TABLE table_name_97 (party VARCHAR, result VARCHAR)

SELECT party FROM table_name_97 WHERE result = 'retired democratic hold';


Question: Find the total number of animals in the 'endangered' status

CREATE TABLE animals (id INT, name VARCHAR(50), status VARCHAR(20)); INSERT INTO animals (id, name, status) VALUES (1, 'Tiger', 'Endangered'); INSERT INTO animals (id, name, status) VALUES (2, 'Elephant', 'Vulnerable');

SELECT COUNT(*) FROM animals WHERE status = 'Endangered';


Question: Show a SQL definition from the citus project (multi_follower_dml, item 8).

CREATE TABLE reference_table (a int, b int, z bigserial);

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


Question: What is the total number of tourists who visited Japan in 2020 from European countries?

CREATE TABLE tourism_data (visitor_country VARCHAR(50), destination_country VARCHAR(50), visit_year INT); INSERT INTO tourism_data (visitor_country, destination_country, visit_year) VALUES ('France', 'Japan', 2020), ('Germany', 'Japan', 2020), ('Italy', 'Japan', 2020);

SELECT SUM(*) FROM tourism_data WHERE visitor_country LIKE 'Europe%' AND visit_year = 2020 AND destination_country = 'Japan';


Question: Generate PostgreSQL SQL for: What years show Model of 2.0 tdi (cr) dpf?

CREATE TABLE table_name_62 (years VARCHAR, model VARCHAR)

SELECT years FROM table_name_62 WHERE model = '2.0 tdi (cr) dpf';


Question: What is the maximum transaction value for the 'Gaming' industry sector in the 'DOGE' digital asset in Q2 2022?

CREATE TABLE transaction_values (industry_sector VARCHAR(10), asset_name VARCHAR(10), quarter INT, max_transaction_value INT); INSERT INTO transaction_values (industry_sector, asset_name, quarter, max_transaction_value) VALUES ('Gaming', 'BTC', 1, 12000), ('Gaming', 'BTC', 2, 15000), ('Gaming', 'BTC', 3, 18000), ('Gaming', 'DOGE', 1, 20000), ('Gaming', 'DOGE', 2, 22000), ('Gaming', 'DOGE', 3, 25000);

SELECT max_transaction_value FROM transaction_values WHERE industry_sector = 'Gaming' AND asset_name = 'DOGE' AND quarter = 2;


Question: Generate PostgreSQL SQL for: Which venues closed in the 1990s?

CREATE TABLE table_name_76 (venue VARCHAR, closed VARCHAR)

SELECT venue FROM table_name_76 WHERE closed = '1990s';


Question: What is the minimum calorie count for meals served at casual dining restaurants?

CREATE TABLE meals (id INT, name TEXT, restaurant_type TEXT); INSERT INTO meals (id, name, restaurant_type) VALUES (1, 'Filet Mignon', 'fine dining'), (2, 'Chicken Caesar', 'casual dining'), (3, 'Tofu Stir Fry', 'fine dining'); CREATE TABLE nutrition (meal_id INT, calorie_count INT); INSERT INTO nutrition (meal_id, calorie_count) VALUES (1, 1200), (2, 800), (3, 900);

SELECT MIN(nutrition.calorie_count) FROM nutrition JOIN meals ON nutrition.meal_id = meals.id WHERE meals.restaurant_type = 'casual dining';


Question: Write the DDL statement from PostgreSQL regression test 'triggers' (example 197).

create table parted_2 partition of parted for values in (2);

Explanation: DDL from PostgreSQL core regression test for Triggers.


Question: What is the maximum production capacity of any tank in the Eastern region?

CREATE TABLE Production (tank VARCHAR(20), capacity INT, location VARCHAR(20)); INSERT INTO Production (tank, capacity, location) VALUES ('Tank3', 100000, 'Eastern'), ('Tank4', 150000, 'Western');

SELECT MAX(capacity) FROM Production WHERE location = 'Eastern';


Question: Generate PostgreSQL SQL for: What is the Away team score for Away team North Melbourne?

CREATE TABLE table_name_13 (away_team VARCHAR)

SELECT away_team AS score FROM table_name_13 WHERE away_team = 'north melbourne';


Question: Generate PostgreSQL SQL for: Who has less than 3 lanes for France?

CREATE TABLE table_name_88 (name VARCHAR, nationality VARCHAR, lane VARCHAR)

SELECT name FROM table_name_88 WHERE nationality = 'france' AND lane < 3;


Question: Which countries have mining companies with the highest labor productivity?

CREATE TABLE Companies (CompanyID INT, CompanyName VARCHAR(50), Country VARCHAR(50), LaborProductivity DECIMAL(5,2)); INSERT INTO Companies (CompanyID, CompanyName, Country, LaborProductivity) VALUES (1, 'ACME Mining', 'Canada', 15.5), (2, 'BIG Excavations', 'South Africa', 12.3), (3, 'Giga Drilling', 'Australia', 18.7), (4, 'Mega Quarrying', 'Brazil', 10.1);

SELECT Country FROM Companies WHERE LaborProductivity IN (SELECT MAX(LaborProductivity) FROM Companies);


Question: What is the total number of concert tickets sold in each city for artists from the Pop genre?

CREATE TABLE Concerts (id INT, city VARCHAR(255), tickets_sold INT); CREATE TABLE Artists (id INT, genre VARCHAR(255));

SELECT city, SUM(tickets_sold) as total_tickets_sold FROM Concerts INNER JOIN Artists ON Concerts.id = Artists.id WHERE genre = 'Pop' GROUP BY city;


Question: What is the total number of articles published in "The Washington Post" that mention "climate change" in the title or content?

CREATE TABLE articles (id INT, title TEXT, content TEXT, publication_date DATE, newspaper TEXT);

SELECT COUNT(*) FROM articles WHERE (title LIKE '%climate change%' OR content LIKE '%climate change%') AND newspaper = 'The Washington Post';


Question: What is the maximum production volume for zinc mines in South Africa?

CREATE TABLE mines (id INT, name TEXT, location TEXT, production_volume INT); INSERT INTO mines (id, name, location, production_volume) VALUES (1, 'South African Zinc Mine 1', 'South Africa', 11000); INSERT INTO mines (id, name, location, production_volume) VALUES (2, 'South African Zinc Mine 2', 'South Africa', 9000);

SELECT MAX(production_volume) FROM mines WHERE location = 'South Africa' AND mineral = 'zinc';


Question: Calculate the average REE market trends for each year since 2017, excluding China.

CREATE TABLE market_trends (year INT, market_trend VARCHAR(255), country VARCHAR(255)); INSERT INTO market_trends (year, market_trend, country) VALUES (2017, 'Increase', 'China'), (2017, 'Decrease', 'USA'), (2018, 'Stable', 'China'), (2018, 'Increase', 'USA'), (2019, 'Decrease', 'China'), (2019, 'Stable', 'USA');

SELECT AVG(market_trend = 'Increase') AS avg_increase, AVG(market_trend = 'Decrease') AS avg_decrease, AVG(market_trend = 'Stable') AS avg_stable FROM market_trends WHERE year >= 2017 AND country != 'China';


Question: Find mining operations that have higher than average emission factors

CREATE TABLE operation_emission_factors (id INT, operation VARCHAR(255), emission_factor DECIMAL(10,2));

SELECT operation FROM operation_emission_factors WHERE emission_factor > (SELECT AVG(emission_factor) FROM operation_emission_factors);


Question: Count of active platforms in the South China Sea.

CREATE TABLE platforms (id INT, location VARCHAR(50), status VARCHAR(50)); INSERT INTO platforms (id, location, status) VALUES (1, 'South China Sea', 'Active');

SELECT COUNT(*) FROM platforms WHERE location = 'South China Sea' AND status = 'Active';


Question: What is the total number of union members in workplaces with more than 1000 total employees?

CREATE TABLE workplaces (id INT, name TEXT, location TEXT, sector TEXT, total_employees INT, union_members INT, successful_cb BOOLEAN, cb_year INT); CREATE TABLE union_members (id INT, workplace_id INT, member_name TEXT, member_join_date DATE, member_status TEXT); INSERT INTO workplaces (id, name, location, sector, total_employees, union_members, successful_cb, cb_year) VALUES (1, 'School A', 'City X', 'education', 50, 30, true, 2020), (2, 'University B', 'City Y', 'education', 3000, 1500, true, 2019), (3, 'Factory C', 'City Z', 'manufacturing', 1200, 900, true, 2018); INSERT INTO union_members (id, workplace_id, member_name, member_join_date, member_status) VALUES (1, 1, 'John Doe', '2018-01-01', 'active'), (2, 1, 'Jane Smith', '2019-05-15', 'active'), (3, 2, 'Mike Johnson', '2020-03-01', 'active'), (4, 3, 'Sara Connor', '2017-09-01', 'active');

SELECT SUM(um.member_status = 'active'::INTEGER) FROM union_members um JOIN workplaces w ON um.workplace_id = w.id WHERE w.total_employees > 1000;


Question: Write the DDL statement from PostgreSQL regression test 'alter_table' (example 261).

create text search parser alter1.prs(start = prsd_start, gettoken = prsd_nexttoken, end = prsd_end, lextypes = prsd_lextype);

Explanation: DDL from PostgreSQL core regression test for Alter Table.


Question: What is the average years of experience for teachers who teach Math?

CREATE TABLE teachers (id INT, name VARCHAR(50), subject VARCHAR(50), years_experience INT); INSERT INTO teachers (id, name, subject, years_experience) VALUES (1, 'Alice Brown', 'Math', 10); INSERT INTO teachers (id, name, subject, years_experience) VALUES (2, 'Bob Johnson', 'Science', 15); INSERT INTO teachers (id, name, subject, years_experience) VALUES (3, 'Charlie Smith', 'Math', 12);

SELECT AVG(years_experience) FROM teachers WHERE subject = 'Math';


Question: Find the number of policies issued in 'Illinois' having a claim amount less than $500 and issued after '2020-01-01'.

CREATE TABLE policyholders (id INT, name TEXT, state TEXT); CREATE TABLE policies (id INT, policyholder_id INT, issue_date DATE, claim_amount FLOAT); INSERT INTO policyholders (id, name, state) VALUES (1, 'Mike Brown', 'IL'); INSERT INTO policies (id, policyholder_id, issue_date, claim_amount) VALUES (1, 1, '2020-02-01', 400.00);

SELECT COUNT(policies.id) FROM policies INNER JOIN policyholders ON policies.policyholder_id = policyholders.id WHERE policies.claim_amount < 500 AND policies.issue_date > '2020-01-01' AND policyholders.state = 'IL';


Question: Write the DML statement from PostgreSQL regression test 'numeric_big' (example 381).

Explanation: DML from PostgreSQL core regression test for Numeric Big.


Question: Generate PostgreSQL SQL for: How many points against have a lose of 13?

CREATE TABLE table_17510803_2 (points_against VARCHAR, lost VARCHAR)

SELECT points_against FROM table_17510803_2 WHERE lost = '13';


Question: Generate PostgreSQL SQL for: I want the lowest points for tries of 39 and goals more than 0

CREATE TABLE table_name_1 (points INTEGER, tries VARCHAR, goals VARCHAR)

SELECT MIN(points) FROM table_name_1 WHERE tries = 39 AND goals > 0;


Question: What is the average funding for marine conservation per year?

CREATE TABLE marine_conservation_funding (year INT, funding INT); INSERT INTO marine_conservation_funding (year, funding) VALUES (2020, 5000000), (2021, 5500000), (2022, 6000000);

SELECT AVG(funding) FROM marine_conservation_funding;


Question: Generate PostgreSQL SQL for: Which Krypton has a Physical property of critical pressure (atm)?

CREATE TABLE table_name_36 (krypton VARCHAR, physical_property VARCHAR)

SELECT krypton FROM table_name_36 WHERE physical_property = 'critical pressure (atm)';


Question: pgTAP test for Proctap (assertion 52).

SELECT * FROM check_test(
    isnt_procedure( 'nonesuch', '{}'::name[], 'whatever' ),
    false,
    'isnt_procedure(noproc, noargs, desc)',
    'whatever',
    '    Function nonesuch() does not exist'
);

Explanation: SQL assertion from pgTAP test suite for Proctap.


Question: Update 'athlete_wellbeing' table to set 'wellbeing_score' to 70 where 'athlete_id' is 3

CREATE TABLE athlete_wellbeing (athlete_id INT, wellbeing_score INT); INSERT INTO athlete_wellbeing (athlete_id, wellbeing_score) VALUES (1, 75), (2, 60), (3, 45), (4, 80);

UPDATE athlete_wellbeing SET wellbeing_score = 70 WHERE athlete_id = 3;


Question: List all wastewater treatment plants in India with their treatment capacities for the year 2020.

CREATE TABLE wastewater_plants (id INT, country VARCHAR(50), year INT, capacity FLOAT); INSERT INTO wastewater_plants (id, country, year, capacity) VALUES (1, 'India', 2020, 80.0), (2, 'India', 2019, 85.0), (3, 'India', 2018, 90.0), (4, 'United States', 2020, 95.0), (5, 'United States', 2019, 100.0), (6, 'United States', 2018, 105.0);

SELECT capacity FROM wastewater_plants WHERE country = 'India' AND year = 2020;


Question: Identify the restaurants with the lowest food safety scores in each region.

CREATE TABLE Restaurants (RestaurantID INT, RestaurantName VARCHAR(255), Region VARCHAR(255), FoodSafetyScore INT); INSERT INTO Restaurants VALUES (1,'Restaurant A','North',90),(2,'Restaurant B','North',85),(3,'Restaurant C','South',80),(4,'Restaurant D','South',82),(5,'Restaurant E','East',95),(6,'Restaurant F','East',93),(7,'Restaurant G','West',75),(8,'Restaurant H','West',88);

SELECT Restaurants.RestaurantName, Restaurants.Region, Restaurants.FoodSafetyScore FROM Restaurants WHERE Restaurants.FoodSafetyScore = (SELECT MIN(FoodSafetyScore) FROM Restaurants AS T WHERE T.Region = Restaurants.Region) GROUP BY Restaurants.Region;


Question: Generate PostgreSQL SQL for: Can you tell me the sum of FLap that has the Pole larger than 0, and the Podiums of 6?

CREATE TABLE table_name_40 (flap INTEGER, pole VARCHAR, podiums VARCHAR)

SELECT SUM(flap) FROM table_name_40 WHERE pole > 0 AND podiums = 6;


Question: Who is the top scorer for each team in a tournament?

CREATE TABLE Player (PlayerID int, PlayerName varchar(50), TeamID int); CREATE TABLE Goal (GoalID int, PlayerID int, Goals int, MatchDate date, TournamentID int);  INSERT INTO Player (PlayerID, PlayerName, TeamID) VALUES (1, 'James Rodriguez', 1), (2, 'Radamel Falcao', 1), (3, 'Thomas Muller', 2), (4, 'Miroslav Klose', 2); INSERT INTO Goal (GoalID, PlayerID, Goals, MatchDate, TournamentID) VALUES (1, 1, 2, '2022-06-01', 1), (2, 1, 3, '2022-06-05', 1), (3, 2, 1, '2022-06-01', 1), (4, 2, 2, '2022-06-05', 1), (5, 3, 4, '2022-06-01', 1), (6, 3, 5, '2022-06-05', 1), (7, 4, 2, '2022-06-01', 1), (8, 4, 3, '2022-06-05', 1);

SELECT p.TeamID, p.PlayerName, SUM(g.Goals) AS TotalGoals, ROW_NUMBER() OVER (PARTITION BY p.TeamID ORDER BY SUM(g.Goals) DESC) AS Ranking FROM Player p JOIN Goal g ON p.PlayerID = g.PlayerID WHERE g.TournamentID = 1 GROUP BY p.TeamID, p.PlayerName HAVING Ranking <= 1;


Question: Who are the regulators for the 'Securities and Exchange Commission Act' and 'Digital Asset Business Act'?

CREATE TABLE Regulatory_Frameworks (Framework_Name VARCHAR(100), Country VARCHAR(50), Regulatory_Body VARCHAR(100)); INSERT INTO Regulatory_Frameworks (Framework_Name, Country, Regulatory_Body) VALUES ('Digital Asset Business Act', 'Bermuda', 'Bermuda Monetary Authority'); INSERT INTO Regulatory_Frameworks (Framework_Name, Country, Regulatory_Body) VALUES ('Securities and Exchange Commission Act', 'United States', 'Securities and Exchange Commission');

SELECT Regulatory_Body FROM Regulatory_Frameworks WHERE Framework_Name IN ('Securities and Exchange Commission Act', 'Digital Asset Business Act');


Question: Generate PostgreSQL SQL for: What is the Borough for the Seward listing on 1977-11-23?

CREATE TABLE table_name_54 (borough VARCHAR, location VARCHAR, listed VARCHAR)

SELECT borough FROM table_name_54 WHERE location = 'seward' AND listed = '1977-11-23';


Question: What is the total number of streams for each artist, for artists who have performed at music festivals in the last year?

CREATE TABLE artist_genre (artist_id INT, genre VARCHAR(255));

SELECT a.artist_id, SUM(s.streams) as total_streams FROM artist_streams s JOIN festival_performances f ON s.artist_id = f.artist_id JOIN artist_genre g ON s.artist_id = g.artist_id WHERE f.performance_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR) GROUP BY a.artist_id;


Question: What is the suicide rate in Japan?

CREATE TABLE Suicide (Country TEXT, Suicides INT, Population INT); INSERT INTO Suicide (Country, Suicides, Population) VALUES ('Japan', 15000, 120000000), ('Japan', 16000, 120000000);

SELECT (Suicides / Population) * 100000 FROM Suicide WHERE Country = 'Japan';


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

ALTER EXTENSION pgtap ADD FUNCTION types_are ( NAME[] );

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


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

SELECT nummultirange(numrange(null,null)) @> numrange(2,null);

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

SELECT count(*) FROM (SELECT nummultirange(numrange(null,null)) @> numrange(2,null)) AS _sub;


Question: Generate PostgreSQL SQL for: How many number of series have the production code of 1.11?

CREATE TABLE table_2226817_2 (no_in_series INTEGER, production_code VARCHAR)

SELECT MAX(no_in_series) FROM table_2226817_2 WHERE production_code = '1.11';


Question: What are the total production quantities of Gadolinium in 2019 and 2020 from the 'mining' and 'recycling' sources?

CREATE TABLE mining (year INT, element VARCHAR(10), quantity INT); INSERT INTO mining VALUES (2019, 'Gadolinium', 1400), (2020, 'Gadolinium', 1600); CREATE TABLE recycling (year INT, element VARCHAR(10), quantity INT); INSERT INTO recycling VALUES (2019, 'Gadolinium', 1000), (2020, 'Gadolinium', 1200);

SELECT year, SUM(quantity) FROM (SELECT year, quantity FROM mining WHERE element = 'Gadolinium' UNION ALL SELECT year, quantity FROM recycling WHERE element = 'Gadolinium') AS total_sources GROUP BY year HAVING year IN (2019, 2020);


Question: Generate PostgreSQL SQL for: Which Points against has a Lost of lost?

CREATE TABLE table_name_97 (points_against VARCHAR)

SELECT points_against FROM table_name_97 WHERE "lost" = 'lost';


Question: Generate PostgreSQL SQL for: What's Trina Gulliver's high checkout?

CREATE TABLE table_20351295_2 (high_checkout VARCHAR, player VARCHAR)

SELECT high_checkout FROM table_20351295_2 WHERE player = 'Trina Gulliver';


Question: pgTAP test for Privs (assertion 66).

-- Try nonexistent user.
SELECT * FROM check_test(
    language_privs_are( 'plpgsql', '__noone', '{USAGE}', 'whatever' ),
    false,
    'language_privs_are(lang, non-role, privs, desc)',
    'whatever',
    '    Role __noone does not exist'
);

Explanation: SQL assertion from pgTAP test suite for Privs.


Question: PostgreSQL regression test 'join': Write the SELECT query (example 422).

select 1 from
  text_tbl as tt1
  inner join text_tbl as tt2 on (tt1.f1 = 'foo')
  left join text_tbl as tt3 on (tt3.f1 = 'foo')
  left join text_tbl as tt4 on (tt3.f1 = tt4.f1),
  lateral (select tt4.f1 as c0 from text_tbl as tt5 limit 1) as ss1
where tt1.f1 = ss1.c0;

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

SELECT count(*) FROM (select 1 from
  text_tbl as tt1
  inner join text_tbl as tt2 on (tt1.f1 = 'foo')
  left join text_tbl as tt3 on (tt3.f1 = 'foo')
  left join text_tbl as tt4 on (tt3.f1 = tt4.f1),
  lateral (select tt4.f1 as c0 from text_tbl as tt5 limit 1) as ss1
where tt1.f1 = ss1.c0) AS _sub;


Question: Generate PostgreSQL SQL for: Who is the player from the United States with a score of 71-72=143?

CREATE TABLE table_name_38 (player VARCHAR, country VARCHAR, score VARCHAR)

SELECT player FROM table_name_38 WHERE country = 'united states' AND score = 71 - 72 = 143;


Question: Remove all clients with the last name 'Patel' from the 'clients' table

CREATE TABLE clients (client_id INT PRIMARY KEY, client_first_name VARCHAR(50), client_last_name VARCHAR(50)); INSERT INTO clients (client_id, client_first_name, client_last_name) VALUES (1, 'Ravi', 'Patel'), (2, 'Kalpana', 'Patel'), (3, 'Raj', 'Singh'), (4, 'Simran', 'Kaur');

DELETE FROM clients WHERE client_last_name = 'Patel';


Question: List all the menu items that have a 'Halal' certification

CREATE TABLE menu_items (id INT, name VARCHAR(50), category VARCHAR(50), certification VARCHAR(50), price DECIMAL(5,2)); INSERT INTO menu_items (id, name, category, certification, price) VALUES (101, 'Beef Shawarma', 'Middle Eastern', 'Halal', 7.99), (102, 'Chicken Tikka Masala', 'Indian', 'Halal', 10.99), (103, 'Veggie Burger', 'American', NULL, 6.99);

SELECT name FROM menu_items WHERE certification = 'Halal';


Question: Generate PostgreSQL SQL for: What's the total of Rank for the County of Galway and has a Total that's larger than 13?

CREATE TABLE table_name_60 (rank INTEGER, county VARCHAR, total VARCHAR)

SELECT SUM(rank) FROM table_name_60 WHERE county = 'galway' AND total > 13;


Question: What is the total number of vaccinations administered to indigenous people in Canada?

CREATE TABLE Vaccinations (VaccinationID INT, PatientID INT, Age INT, Ethnicity VARCHAR(30), VaccineType VARCHAR(20), Date DATE); INSERT INTO Vaccinations (VaccinationID, PatientID, Age, Ethnicity, VaccineType, Date) VALUES (1, 7, 45, 'Indigenous', 'Pfizer', '2021-01-10'); INSERT INTO Vaccinations (VaccinationID, PatientID, Age, Ethnicity, VaccineType, Date) VALUES (2, 8, 50, 'Non-Indigenous', 'Moderna', '2021-01-12');

SELECT COUNT(*) FROM Vaccinations WHERE Ethnicity = 'Indigenous' AND Country = 'Canada';


Question: How many restaurants in California offer vegan options on their menu?

CREATE TABLE restaurants (id INT, name TEXT, location TEXT, type TEXT); INSERT INTO restaurants (id, name, location, type) VALUES (1, 'Restaurant A', 'California', 'Italian'), (2, 'Restaurant B', 'California', 'Vegan'), (3, 'Restaurant C', 'Texas', 'Mexican'), (4, 'Restaurant D', 'California', 'Chinese'); CREATE TABLE menu_items (id INT, name TEXT, is_vegan BOOLEAN, restaurant_id INT); INSERT INTO menu_items (id, name, is_vegan, restaurant_id) VALUES (1, 'Margherita Pizza', FALSE, 1), (2, 'Spaghetti Aglio e Olio', FALSE, 1), (3, 'Vegan Burger', TRUE, 2), (4, 'Garden Salad', TRUE, 2), (5, 'Tacos', FALSE, 3), (6, 'Vegan Sushi', TRUE, 4);

SELECT COUNT(*) FROM restaurants INNER JOIN menu_items ON restaurants.id = menu_items.restaurant_id WHERE is_vegan = TRUE AND location = 'California';


Question: Generate PostgreSQL SQL for: For week 15, what was the total number of attendance recorded?

CREATE TABLE table_name_66 (attendance VARCHAR, week VARCHAR)

SELECT COUNT(attendance) FROM table_name_66 WHERE week = 15;


Question: Generate PostgreSQL SQL for: What is the Galician (reintegrationist) word of the Galician (Official) is bo día / bos días?

CREATE TABLE table_26614365_5 (galician___reintegrationist__ VARCHAR, galician___official__ VARCHAR)

SELECT galician___reintegrationist__ FROM table_26614365_5 WHERE galician___official__ = 'Bo día / Bos días';


Question: What is the maximum data usage in GB for postpaid mobile customers in each region?

CREATE TABLE customers (id INT, type VARCHAR(10), region VARCHAR(10)); INSERT INTO customers (id, type, region) VALUES (1, 'postpaid', 'North'), (2, 'prepaid', 'North'), (3, 'postpaid', 'South'), (4, 'prepaid', 'South'); CREATE TABLE usage (customer_id INT, data_usage FLOAT); INSERT INTO usage (customer_id, data_usage) VALUES (1, 3.5), (2, 2.2), (3, 4.7), (4, 1.8);

SELECT customers.region, MAX(usage.data_usage) FROM usage JOIN customers ON usage.customer_id = customers.id WHERE customers.type = 'postpaid' GROUP BY customers.region;


Question: PostgreSQL regression test 'timetz': Write the SELECT query (example 37).

SELECT EXTRACT(EPOCH       FROM TIME WITH TIME ZONE '2020-05-26 13:30:25.575401-04');

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

SELECT count(*) FROM (SELECT EXTRACT(EPOCH       FROM TIME WITH TIME ZONE '2020-05-26 13:30:25.575401-04')) AS _sub;


Question: Generate PostgreSQL SQL for: What is the least place when the couple is Keiron & Brianne?

CREATE TABLE table_26375386_28 (place INTEGER, couple VARCHAR)

SELECT MIN(place) FROM table_26375386_28 WHERE couple = 'Keiron & Brianne';


Question: Generate PostgreSQL SQL for: What is the score of the match won by Willie Hunter at the Royal Liverpool Golf Club?

CREATE TABLE table_name_21 (score VARCHAR, venue VARCHAR, champion VARCHAR)

SELECT score FROM table_name_21 WHERE venue = 'royal liverpool golf club' AND champion = 'willie hunter';


Question: Generate PostgreSQL SQL for: What Song has a Draw of less than 4 with a Percentage of 32.22%?

CREATE TABLE table_name_72 (song VARCHAR, draw VARCHAR, percentage VARCHAR)

SELECT song FROM table_name_72 WHERE draw < 4 AND percentage = '32.22%';


Question: Generate PostgreSQL SQL for: What was the 2nd leg that had the Estudiantes La Plata home for the 2nd leg?

CREATE TABLE table_name_41 (home__2nd_leg_ VARCHAR)

SELECT 2 AS nd_leg FROM table_name_41 WHERE home__2nd_leg_ = 'estudiantes la plata';


Question: Which circular supply chain initiatives have been implemented by suppliers in the USA?

CREATE TABLE Suppliers (SupplierID int, Name varchar(50), Country varchar(50), CircularSupplyChainInitiatives bool); INSERT INTO Suppliers (SupplierID, Name, Country, CircularSupplyChainInitiatives) VALUES (1, 'Supplier A', 'USA', true), (2, 'Supplier B', 'Canada', false), (3, 'Supplier C', 'USA', true), (4, 'Supplier D', 'Mexico', false);

SELECT Name FROM Suppliers WHERE Country = 'USA' AND CircularSupplyChainInitiatives = true;


Question: Write the DML statement from PostgreSQL regression test 'insert' (example 155).

insert into list_parted (a) values ('aA');

Explanation: DML from PostgreSQL core regression test for Insert.


Question: Generate PostgreSQL SQL for: What shows for 2002 when the 1991 is w?

SELECT 2002 FROM table_name_46 WHERE 1991 = 'w';


Question: Generate PostgreSQL SQL for: What is the least number of penalties he got when his point total was over 1419 in more than 98 games?

CREATE TABLE table_name_45 (penalties INTEGER, points_total VARCHAR, played VARCHAR)

SELECT MIN(penalties) FROM table_name_45 WHERE points_total = 1419 AND played > 98;


Question: Display the average voyage duration for each vessel type in the 'voyage_log' table

CREATE TABLE voyage_log (id INT, vessel_type VARCHAR(50), voyage_duration INT);

SELECT vessel_type, AVG(voyage_duration) FROM voyage_log GROUP BY vessel_type;


Question: Generate PostgreSQL SQL for: Which Overall is the highest one that has a Pick # smaller than 9, and a Name of mike pearson?

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

SELECT MAX(overall) FROM table_name_3 WHERE pick__number < 9 AND name = 'mike pearson';


Question: Generate PostgreSQL SQL for: What is Country, when Player is "Billy Maxwell"?

CREATE TABLE table_name_77 (country VARCHAR, player VARCHAR)

SELECT country FROM table_name_77 WHERE player = 'billy maxwell';


Question: What is the average square footage of co-owned properties in Seattle?

CREATE TABLE properties (id INT, city VARCHAR(20), square_footage INT, co_owned BOOLEAN); INSERT INTO properties (id, city, square_footage, co_owned) VALUES (1, 'Seattle', 1800, true); INSERT INTO properties (id, city, square_footage, co_owned) VALUES (2, 'Seattle', 1500, false);

SELECT AVG(square_footage) FROM properties WHERE city = 'Seattle' AND co_owned = true;


Question: Generate PostgreSQL SQL for: Who was the partner of the winner after 2012?

CREATE TABLE table_name_12 (partner VARCHAR, year VARCHAR, outcome VARCHAR)

SELECT partner FROM table_name_12 WHERE year > 2012 AND outcome = 'winner';


Question: Generate PostgreSQL SQL for: What championship after 1997 was the score 1–6, 4–6, 7–5, 5–7?

CREATE TABLE table_name_3 (championship VARCHAR, year VARCHAR, score VARCHAR)

SELECT championship FROM table_name_3 WHERE year > 1997 AND score = '1–6, 4–6, 7–5, 5–7';


Question: What is the distribution of investments by sector for Red Fund?

CREATE TABLE investments (id INT, fund_name VARCHAR(255), sector VARCHAR(255), investment_amount FLOAT);

SELECT sector, COUNT(*) as num_investments, SUM(investment_amount) as total_invested FROM investments WHERE fund_name = 'Red Fund' GROUP BY sector;


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

SELECT nummultirange() -|- 'empty'::numrange;

SELECT count(*) FROM (SELECT nummultirange() -|- 'empty'::numrange) AS _sub;


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

CREATE TABLE table_name_70 (away_team VARCHAR, home_team VARCHAR)

SELECT away_team FROM table_name_70 WHERE home_team = 'south melbourne';


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

ALTER EXTENSION pgtap ADD FUNCTION runtests( );


Question: What is the latest launch date for each country in the satellites table?

CREATE TABLE satellites (id INT, name VARCHAR(50), launch_country VARCHAR(50), launch_date DATE); INSERT INTO satellites VALUES (1, 'Sputnik 1', 'Russia', '1957-10-04'); INSERT INTO satellites VALUES (2, 'Explorer 1', 'USA', '1958-01-31'); INSERT INTO satellites VALUES (3, 'Echo 1', 'USA', '1960-08-12'); INSERT INTO satellites VALUES (4, 'Cosmos 1', 'Russia', '1962-04-16');

SELECT launch_country, MAX(launch_date) as latest_launch FROM satellites GROUP BY launch_country;


Question: Generate PostgreSQL SQL for: When was successor David Atwood (R) seated?

CREATE TABLE table_2417345_4 (date_successor_seated VARCHAR, successor VARCHAR)

SELECT date_successor_seated FROM table_2417345_4 WHERE successor = 'David Atwood (R)';


Question: Generate PostgreSQL SQL for: What team had a race time of 2:53:57?

CREATE TABLE table_2268216_1 (team VARCHAR, race_time VARCHAR)

SELECT team FROM table_2268216_1 WHERE race_time = '2:53:57';


Question: Generate PostgreSQL SQL for: How many episodes have the Netflix episode number S08E04?

CREATE TABLE table_15187735_15 (episode VARCHAR, netflix VARCHAR)

SELECT COUNT(episode) FROM table_15187735_15 WHERE netflix = 'S08E04';


Question: What is the quantity of item 'D01' in all warehouses?

CREATE TABLE inventory (item_code varchar(5), warehouse_id varchar(5), quantity int); INSERT INTO inventory (item_code, warehouse_id, quantity) VALUES ('D01', 'LHR', 800), ('D01', 'MAD', 900);

SELECT SUM(quantity) FROM inventory WHERE item_code = 'D01';


Question: What is the total number of tickets sold for music concerts in Los Angeles by recurring customers?

CREATE TABLE tickets (ticket_id INT, customer_id INT, event_type VARCHAR(50), price DECIMAL(10,2), city VARCHAR(50)); CREATE TABLE customers (customer_id INT, name VARCHAR(50), is_recurring BOOLEAN); INSERT INTO customers (customer_id, name, is_recurring) VALUES (1, 'Michael Johnson', TRUE), (2, 'Sarah Lee', FALSE); INSERT INTO tickets (ticket_id, customer_id, event_type, price, city) VALUES (1, 1, 'Music Concert', 50.00, 'Los Angeles'), (2, 2, 'Music Concert', 75.00, 'Los Angeles');

SELECT SUM(t.price) AS total_sales FROM tickets t JOIN customers c ON t.customer_id = c.customer_id WHERE c.city = 'Los Angeles' AND c.is_recurring = TRUE AND t.event_type = 'Music Concert';


Question: Who are the property owners in the 'prop_owners' table that have a 'property_id' matching with any record in the 'property2' table?

CREATE TABLE prop_owners (id INT, owner VARCHAR(20), property_id INT); INSERT INTO prop_owners (id, owner, property_id) VALUES (1, 'Oliver', 201), (2, 'Sophia', 202), (3, 'Jacob', 203); CREATE TABLE property2 (id INT, city VARCHAR(20), price INT); INSERT INTO property2 (id, city, price) VALUES (201, 'Phoenix', 700000), (202, 'Denver', 500000);

SELECT prop_owners.owner FROM prop_owners INNER JOIN property2 ON prop_owners.property_id = property2.id;


Question: Generate PostgreSQL SQL for: What is the term for hometown Ester Creek?

CREATE TABLE table_name_55 (term VARCHAR, hometown VARCHAR)

SELECT term FROM table_name_55 WHERE hometown = 'ester creek';


Question: Which fields have had a decrease in soil moisture in the past week?

CREATE TABLE field (id INT, name VARCHAR(20)); CREATE TABLE soil_moisture (id INT, field_id INT, value INT, timestamp TIMESTAMP);

SELECT f.name FROM field f INNER JOIN soil_moisture sm1 ON f.id = sm1.field_id INNER JOIN soil_moisture sm2 ON f.id = sm2.field_id AND sm2.timestamp = sm1.timestamp - INTERVAL '1 day' WHERE sm1.value > sm2.value;


Question: Generate PostgreSQL SQL for: What label has the netherlands as the region, and magik muzik 802-1 as the catalog?

CREATE TABLE table_name_83 (label VARCHAR, region VARCHAR, catalog VARCHAR)

SELECT label FROM table_name_83 WHERE region = 'netherlands' AND catalog = 'magik muzik 802-1';


Question: What is the name and number of crimes for each police department in the state of Texas?

CREATE TABLE states (id INT, name VARCHAR(255)); CREATE TABLE police_departments (id INT, state_id INT, name VARCHAR(255)); CREATE TABLE crimes (id INT, department_id INT, name VARCHAR(255), number INT);

SELECT pd.name, c.name, c.number FROM police_departments pd JOIN crimes c ON pd.id = c.department_id WHERE pd.state_id = (SELECT id FROM states WHERE name = 'Texas');


Question: Generate PostgreSQL SQL for: 4tab of commercial broadcaster Radio Tab broadcasts at what frequency?

CREATE TABLE table_name_75 (frequency VARCHAR, callsign VARCHAR, purpose VARCHAR, on_air_id VARCHAR)

SELECT frequency FROM table_name_75 WHERE purpose = 'commercial' AND on_air_id = 'radio tab' AND callsign = '4tab';


Question: PostgreSQL regression test 'int4': Write the SELECT query (example 56).

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

SELECT count(*) FROM (SELECT (-2147483648)::int4 / (-1)::int4) AS _sub;


Question: Generate PostgreSQL SQL for: Which wicket had a 100 (45) Runs (balls) amount?

CREATE TABLE table_name_43 (wicket VARCHAR, runs__balls_ VARCHAR)

SELECT wicket FROM table_name_43 WHERE runs__balls_ = '100 (45)';


Question: Generate PostgreSQL SQL for: What's the volume:issue of Sheryl Crow with 3 weeks on top?

CREATE TABLE table_name_7 (volume VARCHAR, weeks_on_top VARCHAR, artist VARCHAR)

SELECT volume AS :issue FROM table_name_7 WHERE weeks_on_top = '3' AND artist = 'sheryl crow';


Question: How many vessels transported liquefied natural gas in the Caribbean Sea in each month of 2021?

CREATE TABLE VesselTypes (id INT, vessel_type VARCHAR(50), capacity INT); CREATE TABLE CargoTransports (id INT, vessel_id INT, transport_weight INT, transport_time TIMESTAMP);

SELECT EXTRACT(MONTH FROM CT.transport_time) as month, COUNT(DISTINCT CT.vessel_id) as vessels_count FROM CargoTransports CT JOIN VesselTypes VT ON CT.vessel_id = VT.id WHERE VT.vessel_type = 'Liquefied Natural Gas Carrier' AND CT.transport_time > '2021-01-01' AND CT.transport_time < '2022-01-01' AND CT.latitude BETWEEN 10 AND 25 AND CT.longitude BETWEEN -90 AND -55 GROUP BY month;


Question: Generate PostgreSQL SQL for: Which episode had viewership of 0.296 million?

CREATE TABLE table_27987623_3 (episode VARCHAR, viewers__millions_ VARCHAR)

SELECT episode FROM table_27987623_3 WHERE viewers__millions_ = '0.296';


Question: Generate PostgreSQL SQL for: What venue has an attendance of 30824 at Essendon in 1984?

CREATE TABLE table_1139835_9 (venue VARCHAR, premier VARCHAR, attendance VARCHAR)

SELECT venue FROM table_1139835_9 WHERE premier = 'Essendon' AND attendance = 30824;


Question: Generate PostgreSQL SQL for: what is the largest city where the population is 6620100?

CREATE TABLE table_17416221_1 (largest_city VARCHAR, population__2013_ VARCHAR)

SELECT largest_city FROM table_17416221_1 WHERE population__2013_ = 6620100;


Question: What is the maximum number of reviews for eco-friendly hotels in India?

CREATE TABLE eco_hotels (hotel_id INT, hotel_name TEXT, reviews INT, country TEXT); INSERT INTO eco_hotels (hotel_id, hotel_name, reviews, country) VALUES (1, 'Eco Lodge Jaipur', 100, 'India'), (2, 'Green Hotel New Delhi', 150, 'India');

SELECT MAX(reviews) FROM eco_hotels WHERE country = 'India';


Question: Insert a new record into the volunteers table with the following information: id = 5, name = 'Liam Brown', hours_served = 30.00.

CREATE TABLE volunteers (id INT, name VARCHAR(50), hours_served FLOAT);

INSERT INTO volunteers (id, name, hours_served) VALUES (5, 'Liam Brown', 30.00);


Question: Generate PostgreSQL SQL for: What's the HR Number when the LMS number is 14757 and has a built of 9/1915?

CREATE TABLE table_name_75 (hr_no VARCHAR, built VARCHAR, lms_no VARCHAR)

SELECT hr_no FROM table_name_75 WHERE built = '9/1915' AND lms_no = 14757;


Question: What is the number of orders that were shipped using carbon-neutral methods in the ethical fashion marketplace?

CREATE TABLE shipments (shipment_id INT, carbon_neutral BOOLEAN); INSERT INTO shipments (shipment_id, carbon_neutral) VALUES (1, true), (2, false), (3, true);

SELECT COUNT(*) FROM shipments WHERE carbon_neutral = true;


Question: Generate PostgreSQL SQL for: how many times is the country united states and the score 72-71-73-73=289?

CREATE TABLE table_name_93 (to_par VARCHAR, country VARCHAR, score VARCHAR)

SELECT COUNT(to_par) FROM table_name_93 WHERE country = 'united states' AND score = 72 - 71 - 73 - 73 = 289;


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

SELECT * FROM crosstab2('SELECT rowid, attribute, val FROM ct where rowclass = ''group2'' and (attribute = ''att1'' or attribute = ''att2'') ORDER BY 1,2;');

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


Question: How many renewable energy projects have been implemented in the Asia Pacific region?

CREATE TABLE renewable_energy (id INT, project_name VARCHAR(50), location VARCHAR(50)); INSERT INTO renewable_energy (id, project_name, location) VALUES (1, 'SolarFarm AP', 'Asia Pacific'), (2, 'WindFarm EU', 'Europe'), (3, 'HydroAP', 'Asia Pacific'), (4, 'GeoThermal NA', 'North America');

SELECT COUNT(*) FROM renewable_energy WHERE location = 'Asia Pacific';


Question: Generate PostgreSQL SQL for: What is the region 1 date for series 4

CREATE TABLE table_15823956_1 (region_1 VARCHAR, series VARCHAR)

SELECT region_1 FROM table_15823956_1 WHERE series = '4';


Question: Insert new student records for 'Oregon' and 'Washington' who have completed their mental health counseling

CREATE TABLE NewStudents (StudentID INT, State VARCHAR(10), Counseling VARCHAR(10)); INSERT INTO NewStudents (StudentID, State, Counseling) VALUES (1, 'OR', 'Completed'), (2, 'WA', 'Completed');

INSERT INTO NewStudents (StudentID, State, Counseling) VALUES (3, 'Oregon', 'Completed'), (4, 'Washington', 'Completed');


Question: Generate PostgreSQL SQL for: Which states have renewable electricity equal to 9667 (gw×h)?

CREATE TABLE table_25244412_1 (state VARCHAR, renewable_electricity__gw•h_ VARCHAR)

SELECT state FROM table_25244412_1 WHERE renewable_electricity__gw•h_ = 9667;


Question: Generate PostgreSQL SQL for: Which Lost has a Position of 4, and a Drawn smaller than 3?

CREATE TABLE table_name_4 (lost INTEGER, position VARCHAR, drawn VARCHAR)

SELECT AVG(lost) FROM table_name_4 WHERE position = 4 AND drawn < 3;


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

INSERT INTO num_exp_add VALUES (0,7,'-83028485');

Explanation: DML from PostgreSQL core regression test for Numeric.


Question: What are the three rural areas with the highest obesity rate in Canada?

CREATE TABLE areas_canada (id INT, name VARCHAR(255), rural_designation VARCHAR(50)); INSERT INTO areas_canada (id, name, rural_designation) VALUES (1, 'Area X', 'Rural'); CREATE TABLE obesity_rates (id INT, area_id INT, obesity_rate FLOAT); INSERT INTO obesity_rates (id, area_id, obesity_rate) VALUES (1, 1, 30.5);

SELECT a.name, ob.obesity_rate FROM areas_canada a JOIN obesity_rates ob ON a.id = ob.area_id WHERE a.rural_designation = 'Rural' ORDER BY ob.obesity_rate DESC LIMIT 3;


Question: Generate PostgreSQL SQL for: What was the time for the event in which Tony Mendoza was the opponent?

CREATE TABLE table_name_22 (time VARCHAR, opponent VARCHAR)

SELECT time FROM table_name_22 WHERE opponent = 'tony mendoza';


Question: Generate PostgreSQL SQL for: what game had a doubles round in 1979

CREATE TABLE table_name_92 (mixed_doubles VARCHAR, year VARCHAR)

SELECT mixed_doubles FROM table_name_92 WHERE year = 1979;


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

INSERT INTO fract_only VALUES (9, 'NaN');


Question: Show a SQL definition from the pgaudit project (pgaudit, item 45).

CREATE VIEW vw_test3 AS
SELECT *
  FROM test3;

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


Question: Generate PostgreSQL SQL for: What was the score of the March 14 game?

CREATE TABLE table_name_95 (score VARCHAR, date VARCHAR)

SELECT score FROM table_name_95 WHERE date = 'march 14';


Question: Generate PostgreSQL SQL for: Show the name of the conductor that has conducted the most number of orchestras.

CREATE TABLE orchestra (Conductor_ID VARCHAR); CREATE TABLE conductor (Name VARCHAR, Conductor_ID VARCHAR)

SELECT T1.Name FROM conductor AS T1 JOIN orchestra AS T2 ON T1.Conductor_ID = T2.Conductor_ID GROUP BY T2.Conductor_ID ORDER BY COUNT(*) DESC LIMIT 1;


Question: What is the moving average of sales for the last 3 months?

SELECT sale_date, AVG(units_sold) OVER (ORDER BY sale_date ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) as moving_average FROM sales_data;


Question: How many tickets were sold for the 'Homecoming' event in the 'tickets' table?

CREATE TABLE tickets (ticket_id INT, event VARCHAR(50), price DECIMAL(5,2), quantity INT); INSERT INTO tickets (ticket_id, event, price, quantity) VALUES (1, 'Homecoming', 50.00, 1000); INSERT INTO tickets (ticket_id, event, price, quantity) VALUES (2, 'Season Finale', 75.00, 500);

SELECT SUM(quantity) FROM tickets WHERE event = 'Homecoming';


Question: Generate PostgreSQL SQL for: What years did the Utah Jazz Player from Southern Methodist, Play?

CREATE TABLE table_name_52 (years_for_jazz VARCHAR, school_club_team VARCHAR)

SELECT years_for_jazz FROM table_name_52 WHERE school_club_team = 'southern methodist';


Question: Write the DDL statement from PostgreSQL regression test 'matview' (example 91).

CREATE MATERIALIZED VIEW mvtest_boxmv AS SELECT * FROM mvtest_boxes;

Explanation: DDL from PostgreSQL core regression test for Matview.


Question: What is the maximum duration of space missions led by Canadian astronauts?

CREATE TABLE SpaceMissionRecords (mission_name VARCHAR(30), astronaut_name VARCHAR(30), country VARCHAR(20), mission_duration INT); INSERT INTO SpaceMissionRecords (mission_name, astronaut_name, country, mission_duration) VALUES ('Moon Landing', 'Jacob Johnson', 'Canada', 120), ('Mars Exploration', 'Emily Brown', 'Canada', 180);

SELECT MAX(mission_duration) FROM SpaceMissionRecords WHERE country = 'Canada';


Question: Generate PostgreSQL SQL for: Which premiere had languages in danish?

CREATE TABLE table_11323532_2 (premiere VARCHAR, languages VARCHAR)

SELECT premiere FROM table_11323532_2 WHERE languages = 'Danish';


Question: How many polar bears are there in Canada and Russia?

CREATE TABLE polar_bear_population (country VARCHAR(255), year INT, population INT);

SELECT SUM(population) FROM polar_bear_population WHERE country IN ('Canada', 'Russia');


Question: PostgreSQL regression test 'window': Write the SELECT query (example 55).

SELECT sum(unique1) over (rows between 2 preceding and 2 following exclude no others),
	unique1, four
FROM tenk1 WHERE unique1 < 10;

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

SELECT count(*) FROM (SELECT sum(unique1) over (rows between 2 preceding and 2 following exclude no others),
	unique1, four
FROM tenk1 WHERE unique1 < 10) AS _sub;


Question: pgTAP test for Hastap (assertion 88).

SELECT * FROM check_test(
    has_type( 'sometype', 'mydesc' ),
    true,
    'has_type(type, desc)',
    'mydesc',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Hastap.


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

CREATE INDEX concur_reindex_part_index ON ONLY concur_reindex_part (c1);

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


Question: How many electric vehicles were sold in each city in 2020?

CREATE TABLE cities (id INT, name VARCHAR(50), population INT); INSERT INTO cities (id, name, population) VALUES (1, 'San Francisco', 874000); INSERT INTO cities (id, name, population) VALUES (2, 'New York', 8601000); CREATE TABLE electric_vehicles (id INT, city_id INT, make VARCHAR(50), model VARCHAR(50), year INT, sales INT); INSERT INTO electric_vehicles (id, city_id, make, model, year, sales) VALUES (1, 1, 'Tesla', 'Model S', 2020, 5000); INSERT INTO electric_vehicles (id, city_id, make, model, year, sales) VALUES (2, 1, 'Tesla', 'Model 3', 2020, 8000); INSERT INTO electric_vehicles (id, city_id, make, model, year, sales) VALUES (3, 2, 'Chevrolet', 'Bolt', 2020, 3000);

SELECT cities.name, electric_vehicles.year, SUM(electric_vehicles.sales) as total_sales FROM cities JOIN electric_vehicles ON cities.id = electric_vehicles.city_id GROUP BY cities.name, electric_vehicles.year HAVING electric_vehicles.year = 2020;


Question: Generate PostgreSQL SQL for: What company is the kit manufacturer that Gareth Southgate belongs to?

CREATE TABLE table_name_50 (kit_manufacturer VARCHAR, captain VARCHAR)

SELECT kit_manufacturer FROM table_name_50 WHERE captain = 'gareth southgate';


Question: What is the maximum number of habitat preservation projects in South America, focusing on 'Rainforest Conservation'?

CREATE TABLE HabitatProjects (ProjectID INT, Project VARCHAR(50), Maximum INT, Location VARCHAR(50)); INSERT INTO HabitatProjects (ProjectID, Project, Maximum, Location) VALUES (1, 'Rainforest Conservation', 100, 'South America'); INSERT INTO HabitatProjects (ProjectID, Project, Maximum, Location) VALUES (2, 'Ocean Preservation', 80, 'South America');

SELECT MAX(Maximum) FROM HabitatProjects WHERE Project = 'Rainforest Conservation' AND Location = 'South America';


Question: What is the average weight of chemical substances manufactured in the US that were produced in the last 5 years, grouped by their respective categories?

CREATE TABLE chemicals (id INT, name VARCHAR(255), weight FLOAT, manufacturer_country VARCHAR(255), category VARCHAR(255), production_date DATE);

SELECT category, AVG(weight) as avg_weight FROM chemicals WHERE manufacturer_country = 'USA' AND production_date > DATE_SUB(CURDATE(), INTERVAL 5 YEAR) GROUP BY category;


Question: Insert a new record into the animals table with a species of 'Lion', population of 300, and status of 'Threatened'

CREATE TABLE animals (species VARCHAR(50), population INT, status VARCHAR(20));

INSERT INTO animals (species, population, status) VALUES ('Lion', 300, 'Threatened');


Question: What is the total production of Terbium in Africa from 2017 to 2020?

CREATE TABLE terbium_production (id INT, country TEXT, year INT, terbium_prod FLOAT); INSERT INTO terbium_production (id, country, year, terbium_prod) VALUES (1, 'South Africa', 2017, 120.0), (2, 'South Africa', 2018, 150.0), (3, 'South Africa', 2019, 180.0), (4, 'South Africa', 2020, 200.0), (5, 'Egypt', 2017, 50.0), (6, 'Egypt', 2018, 55.0), (7, 'Egypt', 2019, 60.0), (8, 'Egypt', 2020, 65.0);

SELECT SUM(terbium_prod) as total_terbium_prod FROM terbium_production WHERE year BETWEEN 2017 AND 2020 AND country = 'South Africa' OR country = 'Egypt';


Question: Generate PostgreSQL SQL for: How many episodes had 4.44m viewers?

CREATE TABLE table_27039190_3 (episode VARCHAR, viewers VARCHAR)

SELECT COUNT(episode) FROM table_27039190_3 WHERE viewers = '4.44m';


Question: Generate PostgreSQL SQL for: How many games were against Furman?

CREATE TABLE table_20745444_1 (game INTEGER, opponent VARCHAR)

SELECT MAX(game) FROM table_20745444_1 WHERE opponent = 'Furman';


Question: Calculate the percentage of veterans employed in the defense industry

CREATE TABLE veteran_employment (employee_id INT, industry VARCHAR(20));

SELECT (COUNT(*) FILTER (WHERE industry = 'Defense')) * 100.0 / COUNT(*) as defense_industry_percentage FROM veteran_employment;


Question: Show a SQL definition from the zombodb project (_cat-api, item 10).

CREATE OR REPLACE VIEW zdb.cat_nodeattrs AS
SELECT
    url,
    (response->>'node') AS "node",
    (response->>'host') AS "host",
    (response->>'ip')::inet AS "ip",
    (response->>'attr') AS "attr",
    (response->>'value') AS "value"
FROM zdb._all_indices_cat_request('nodeattrs');

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


Question: Determine the dishes that have not been sold in the last 30 days

CREATE TABLE sales_data (sale_id INT, dish_id INT, sale_date DATE); INSERT INTO sales_data (sale_id, dish_id, sale_date) VALUES (1, 1, '2022-01-01'), (2, 2, '2022-01-05'), (3, 1, '2022-01-10'); CREATE TABLE menu (dish_id INT, dish_name VARCHAR(255), dish_type VARCHAR(255)); INSERT INTO menu (dish_id, dish_name, dish_type) VALUES (1, 'Quinoa Salad', 'Vegetarian'), (2, 'Chicken Sandwich', 'Non-Vegetarian');

SELECT m.dish_id, m.dish_name FROM menu m LEFT JOIN sales_data s ON m.dish_id = s.dish_id WHERE s.sale_date < DATE_SUB(CURDATE(), INTERVAL 30 DAY) IS NULL;


Question: Generate PostgreSQL SQL for: Who was the losing team with a total of 24 when the winning team was Sydney Roosters?

CREATE TABLE table_name_44 (losing_team VARCHAR, total VARCHAR, winning_team VARCHAR)

SELECT losing_team FROM table_name_44 WHERE total = 24 AND winning_team = 'sydney roosters';


Question: PostgreSQL regression test 'arrays': Write the SELECT query (example 423).

select unnest(array(select '11 22 33'::oidvector from generate_series(1,5)));

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

SELECT count(*) FROM (select unnest(array(select '11 22 33'::oidvector from generate_series(1,5)))) AS _sub;


Question: Write the DML statement from PostgreSQL regression test 'numeric_big' (example 297).

Explanation: DML from PostgreSQL core regression test for Numeric Big.


Question: Generate PostgreSQL SQL for: Name the name for company d

CREATE TABLE table_25794010_1 (name VARCHAR, company VARCHAR)

SELECT name FROM table_25794010_1 WHERE company = 'company D';


Question: Generate PostgreSQL SQL for: Which Commercial Operation has both a Gross Capacity of 417 mw and an Electricity Grid 27.12.1971?

CREATE TABLE table_name_48 (commercial_operation VARCHAR, gross_capacity VARCHAR, electricity_grid VARCHAR)

SELECT commercial_operation FROM table_name_48 WHERE gross_capacity = '417 mw' AND electricity_grid = '27.12.1971';


Question: What is the average number of lifelong learning courses completed by teachers in each institution?

CREATE TABLE teacher_lifelong_learning (teacher_id INT, institution_id INT, course_count INT);

SELECT institution_id, AVG(course_count) as avg_courses FROM teacher_lifelong_learning GROUP BY institution_id;


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

select hstore 'a=>NULL, b=>qq' ?| ARRAY['a','b'];

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


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

Explanation: DML from PostgreSQL core regression test for Polymorphism.


Question: Generate PostgreSQL SQL for: Who are the away teams when subiaco oval was the grounds?

CREATE TABLE table_16388506_1 (away_team VARCHAR, ground VARCHAR)

SELECT away_team FROM table_16388506_1 WHERE ground = 'Subiaco Oval';


Question: How many cases were handled by each restorative justice program?

CREATE TABLE restorative_justice (id INT, program_name VARCHAR(255), cases_handled INT); INSERT INTO restorative_justice (id, program_name, cases_handled) VALUES (1, 'Victim-Offender Mediation', 35), (2, 'Restorative Circles', 47), (3, 'Community Conferencing', 29);

SELECT program_name, SUM(cases_handled) FROM restorative_justice GROUP BY program_name;


Question: Generate PostgreSQL SQL for: Which days have a stage of ss11?

CREATE TABLE table_21536557_2 (day VARCHAR, stage VARCHAR)

SELECT day FROM table_21536557_2 WHERE stage = 'SS11';


Question: What is the total quantity of goods transported by container ships?

CREATE TABLE Vessels (VesselID INT, VesselName VARCHAR(100), VesselType VARCHAR(100), PortID INT); INSERT INTO Vessels (VesselID, VesselName, VesselType, PortID) VALUES (1, 'Ever Ace', 'Container Ship', 1); INSERT INTO Vessels (VesselID, VesselName, VesselType, PortID) VALUES (2, 'Algeciras', 'Ro-Ro Ship', 2);   CREATE TABLE Cargo (CargoID INT, CargoName VARCHAR(100), Quantity INT, VesselID INT); INSERT INTO Cargo (CargoID, CargoName, Quantity, VesselID) VALUES (1, 'Electronics', 10000, 1); INSERT INTO Cargo (CargoID, CargoName, Quantity, VesselID) VALUES (2, 'Vehicles', 5000, 2);

SELECT SUM(Cargo.Quantity) FROM Cargo INNER JOIN Vessels ON Cargo.VesselID = Vessels.VesselID WHERE Vessels.VesselType = 'Container Ship';


Question: What is the total budget allocated for education programs in the "GovernmentBudget" table, for each department, where the budget was over $100,000?

CREATE TABLE GovernmentBudget (id INT, department VARCHAR(50), program VARCHAR(50), budget DECIMAL(10,2)); INSERT INTO GovernmentBudget (id, department, program, budget) VALUES (1, 'Education', 'Elementary School', 50000), (2, 'Education', 'High School', 120000), (3, 'Education', 'College', 200000), (4, 'Healthcare', 'Hospital', 300000);

SELECT department, SUM(budget) as total_budget FROM GovernmentBudget WHERE budget > 100000 AND program LIKE '%Education%' GROUP BY department;


Question: Generate PostgreSQL SQL for: What is the height of the delegate whose hometown is Renton, WA?

CREATE TABLE table_name_69 (height VARCHAR, hometown VARCHAR)

SELECT height FROM table_name_69 WHERE hometown = 'renton, wa';


Question: Generate PostgreSQL SQL for: What is Points, when Tries For is "correct as of 00:00 11 June 2008"?

CREATE TABLE table_name_90 (points VARCHAR, tries_for VARCHAR)

SELECT points FROM table_name_90 WHERE tries_for = 'correct as of 00:00 11 june 2008';


Question: What is the average quantity of products sold in stores located in urban areas?

CREATE TABLE stores (store_id INT, location VARCHAR(20), quantity INT); INSERT INTO stores (store_id, location, quantity) VALUES (1, 'urban', 100), (2, 'rural', 50), (3, 'urban', 150), (4, 'suburban', 75);

SELECT AVG(quantity) FROM stores WHERE location = 'urban';


Question: Generate PostgreSQL SQL for: Name the represents for los alcarrizos

CREATE TABLE table_26301697_2 (represents VARCHAR, hometown VARCHAR)

SELECT represents FROM table_26301697_2 WHERE hometown = 'Los Alcarrizos';


Question: What is the average age of patients with diabetes in indigenous communities, and what is the total population in those communities?

CREATE TABLE patients (id INT, name TEXT, age INT, is_indigenous BOOLEAN, has_diabetes BOOLEAN); INSERT INTO patients (id, name, age, is_indigenous, has_diabetes) VALUES (1, 'Juanita Flores', 50, true, true), (2, 'Brian White', 45, false, false), (3, 'Nia Brown', 60, true, true);

SELECT AVG(patients.age), COUNT(patients.id) FROM patients WHERE patients.is_indigenous = true AND patients.has_diabetes = true;


Question: Generate PostgreSQL SQL for: Name who wrote the episode by lawrence trilling

CREATE TABLE table_27504682_1 (written_by VARCHAR, directed_by VARCHAR)

SELECT written_by FROM table_27504682_1 WHERE directed_by = 'Lawrence Trilling';


Question: Generate PostgreSQL SQL for: Name the rank for thomas morgenstern

CREATE TABLE table_24489942_10 (rank VARCHAR, name VARCHAR)

SELECT rank FROM table_24489942_10 WHERE name = 'Thomas Morgenstern';


Question: Generate PostgreSQL SQL for: What date did the Green-Communists receive 5.7%?

CREATE TABLE table_1881642_1 (date_released VARCHAR, green_communist VARCHAR)

SELECT date_released FROM table_1881642_1 WHERE green_communist = '5.7%';


Question: Which countries have the highest military budgets in the Asia-Pacific region, excluding China?

CREATE TABLE military_budget (country VARCHAR(50), budget INT); INSERT INTO military_budget (country, budget) VALUES ('United States', 7050000000), ('China', 22800000000), ('Japan', 4936000000), ('India', 5574000000), ('South Korea', 4370000000);

SELECT country, budget FROM military_budget WHERE country != 'China' AND country IN ('United States', 'Japan', 'India', 'South Korea') ORDER BY budget DESC;


Question: What was the total waste generation in kg for each city in the year 2020?

CREATE TABLE waste_generation(city VARCHAR(255), year INT, amount FLOAT); INSERT INTO waste_generation(city, year, amount) VALUES('CityA', 2020, 123.45), ('CityB', 2020, 678.90);

SELECT city, SUM(amount) FROM waste_generation WHERE year = 2020 GROUP BY city;


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

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

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


Question: pgTAP test for Privs (assertion 89).

Explanation: SQL assertion from pgTAP test suite for Privs.


Question: Generate PostgreSQL SQL for: what is the total number o production code where us viewers is 2.76?

CREATE TABLE table_21726793_1 (production_code VARCHAR, us_viewers__million_ VARCHAR)

SELECT COUNT(production_code) FROM table_21726793_1 WHERE us_viewers__million_ = '2.76';


Question: Generate PostgreSQL SQL for: Find the title of the course that is offered by more than one department.

SELECT title FROM course GROUP BY title HAVING COUNT(*) > 1;


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

SELECT count(*) >= 0 AS ok FROM pg_ls_replslotdir('not_existing_slot'); -- fails

-- permanent slot has survived
SELECT pg_drop_replication_slot('regression_slot_p');

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


Question: Generate PostgreSQL SQL for: when first elected was 1898 what was the party?

CREATE TABLE table_name_9 (party VARCHAR, first_elected VARCHAR)

SELECT party FROM table_name_9 WHERE first_elected = '1898';


Question: What is the total biomass of seals in the Canadian Arctic?

CREATE TABLE SealData (species VARCHAR(50), location VARCHAR(50), biomass FLOAT); INSERT INTO SealData (species, location, biomass) VALUES ('Hooded Seal', 'Canadian Arctic', 250.0), ('Ringed Seal', 'Canadian Arctic', 300.0), ('Bearded Seal', 'Canadian Arctic', 350.0);

SELECT location, SUM(biomass) FROM SealData WHERE species IN ('Hooded Seal', 'Ringed Seal', 'Bearded Seal') GROUP BY location;


Question: Count the number of clinics in rural New Mexico that have a capacity greater than 50.

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

SELECT COUNT(clinics.id) FROM clinics WHERE clinics.region = 'Rural New Mexico' AND clinics.capacity > 50;


Question: PostgreSQL regression test 'conversion': Write the SELECT query (example 62).

select description, inbytes, (test_conv(inbytes, 'mule_internal', 'iso8859-5')).* from mic_inputs;

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

SELECT count(*) FROM (select description, inbytes, (test_conv(inbytes, 'mule_internal', 'iso8859-5')).* from mic_inputs) AS _sub;


Question: What is the average runtime of movies by genre?

CREATE TABLE movie_data (title VARCHAR(255), runtime INT, genre VARCHAR(255)); INSERT INTO movie_data (title, runtime, genre) VALUES ('Die Hard', 132, 'Action'), ('The Shawshank Redemption', 142, 'Drama');

SELECT genre, AVG(runtime) FROM movie_data GROUP BY genre;


Question: What is the minimum explainability score for models developed in Africa?

CREATE TABLE explainability_scores (id INT, model_id INT, score FLOAT); INSERT INTO explainability_scores (id, model_id, score) VALUES (1, 1, 0.75), (2, 2, 0.91), (3, 3, 0.68); CREATE TABLE models (id INT, name TEXT, country TEXT); INSERT INTO models (id, name, country) VALUES (1, 'ModelA', 'Africa'), (2, 'ModelB', 'Canada'), (3, 'ModelC', 'Africa');

SELECT MIN(score) FROM explainability_scores JOIN models ON explainability_scores.model_id = models.id WHERE country = 'Africa';


Question: What is the average number of weapons for each naval vessel?

CREATE TABLE NavalVessels (ID INT, Name VARCHAR(50), NumWeapons INT);

SELECT AVG(NumWeapons) FROM NavalVessels;


Question: What is the minimum credit score of clients who have made an investment in the past month?

SELECT MIN(credit_score) FROM clients c JOIN investments i ON c.id = i.client_id WHERE i.investment_date >= c.registered_date + INTERVAL '1 month';


Question: Generate PostgreSQL SQL for: Who were the Opponents in the match on a Hard Surface with Catherine Suire as Partner and Outcome of runner-up?

CREATE TABLE table_name_6 (opponents VARCHAR, partner VARCHAR, outcome VARCHAR, surface VARCHAR)

SELECT opponents FROM table_name_6 WHERE outcome = 'runner-up' AND surface = 'hard' AND partner = 'catherine suire';


Question: Which player from Africa has the highest score in the 'all_time_high_scores' table?

CREATE TABLE all_time_high_scores (player_id INT, player_name TEXT, score INT, country TEXT);

SELECT player_name, MAX(score) as high_score FROM all_time_high_scores WHERE country = 'Africa' GROUP BY player_name ORDER BY high_score DESC LIMIT 1;


Question: What is the total quantity of items shipped from the USA to Canada?

CREATE TABLE Warehouse (id INT, location VARCHAR(50), quantity INT); INSERT INTO Warehouse (id, location, quantity) VALUES (1, 'USA', 300), (2, 'Canada', 250);

SELECT SUM(quantity) FROM Warehouse WHERE location = 'USA';


Question: Which country in 'South America' has the most organic farms?

CREATE TABLE organic_farms (id INT, country VARCHAR(50), region VARCHAR(50), no_farms INT); INSERT INTO organic_farms (id, country, region, no_farms) VALUES (1, 'Brazil', 'South America', 2000); INSERT INTO organic_farms (id, country, region, no_farms) VALUES (2, 'Argentina', 'South America', 3000); INSERT INTO organic_farms (id, country, region, no_farms) VALUES (3, 'Colombia', 'South America', 1500);

SELECT country, MAX(no_farms) FROM organic_farms WHERE region = 'South America';


Question: Generate PostgreSQL SQL for: How many epsidode(s) had 3.63 million viewers?

CREATE TABLE table_22353769_3 (episode__number VARCHAR, viewers__millions_ VARCHAR)

SELECT COUNT(episode__number) FROM table_22353769_3 WHERE viewers__millions_ = '3.63';


Question: Generate PostgreSQL SQL for: what are the numbers of episodes that had 0.79 million US views?

CREATE TABLE table_28348757_6 (_number VARCHAR, us_viewers__million_ VARCHAR)

SELECT _number FROM table_28348757_6 WHERE us_viewers__million_ = '0.79';


Question: Generate PostgreSQL SQL for: Who is the player from La Costa Canyon High School?

CREATE TABLE table_name_79 (player VARCHAR, school VARCHAR)

SELECT player FROM table_name_79 WHERE school = 'la costa canyon high school';


Question: Generate PostgreSQL SQL for: how many have times of 6

CREATE TABLE table_13512105_3 (fastest_lap VARCHAR, rnd VARCHAR)

SELECT COUNT(fastest_lap) FROM table_13512105_3 WHERE rnd = 6;


Question: PostgreSQL regression test 'timestamptz': Write the SELECT query (example 228).

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

SELECT count(*) FROM (SELECT make_timestamptz(1973, 07, 15, 08, 15, 55.33, '+2')) AS _sub;


Question: Generate PostgreSQL SQL for: What is the Outcome of the game against Frederic Jeanclaude?

CREATE TABLE table_name_55 (outcome VARCHAR, opponent VARCHAR)

SELECT outcome FROM table_name_55 WHERE opponent = 'frederic jeanclaude';


Question: Generate PostgreSQL SQL for: List the name of albums that are released by aritist whose name has 'Led'

CREATE TABLE artists (id VARCHAR, name VARCHAR); CREATE TABLE albums (title VARCHAR, artist_id VARCHAR)

SELECT T2.title FROM artists AS T1 JOIN albums AS T2 ON T1.id = T2.artist_id WHERE T1.name LIKE '%Led%';


Question: Generate PostgreSQL SQL for: Who was the pilot of max altitude of 55.9 miles?

CREATE TABLE table_221315_3 (pilot VARCHAR, max_altitude__miles_ VARCHAR)

SELECT pilot FROM table_221315_3 WHERE max_altitude__miles_ = '55.9';


Question: How many articles were written by each author from underrepresented communities in the 'news_articles' table?

CREATE TABLE news_articles (article_id INT, author VARCHAR(50), title VARCHAR(100), publication_date DATE, category VARCHAR(20), community_represented BOOLEAN); INSERT INTO news_articles (article_id, author, title, publication_date, category, community_represented) VALUES (1, 'Aisha Jones', 'Article 1', '2022-01-01', 'Politics', true), (2, 'Brian Chen', 'Article 2', '2022-01-02', 'Sports', false);

SELECT author, SUM(community_represented) as articles_for_underrepresented FROM news_articles GROUP BY author;


Question: Generate PostgreSQL SQL for: What chassis does the shadow built car use?

CREATE TABLE table_name_36 (chassis VARCHAR, constructor VARCHAR)

SELECT chassis FROM table_name_36 WHERE constructor = 'shadow';


Question: Calculate the risk score of clients who have made more than 10 transactions in the past month

CREATE TABLE clients (client_id INT PRIMARY KEY, name VARCHAR(100)); CREATE TABLE client_transactions (transaction_id INT PRIMARY KEY, client_id INT, transaction_date DATE);

SELECT c.name, AVG(r.risk_score) AS avg_risk_score FROM clients c JOIN (SELECT client_id, risk_score FROM client_risk_scores WHERE client_id IN (SELECT client_id FROM client_transactions WHERE transaction_date >= DATE_SUB(NOW(), INTERVAL 1 MONTH) GROUP BY client_id HAVING COUNT(*) > 10)) r ON c.client_id = r.client_id GROUP BY c.client_id;


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

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


Question: Show a query using PostgreSQL contrib extension 'pgcrypto' (example 7).

INSERT INTO ctest VALUES ('password', '', '');

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


Question: What's the total amount of coal reserves for each mining region?

CREATE TABLE coal_mines(id INT, region VARCHAR, reserves FLOAT); INSERT INTO coal_mines(id, region, reserves) VALUES (1, 'Appalachia', 1234.56), (2, 'Powder River', 789.10);

SELECT region, SUM(reserves) FROM coal_mines GROUP BY region;


Question: Find the number of wells drilled by each company in the Bakken Formation.

CREATE TABLE wells_by_company (company VARCHAR(255), formation VARCHAR(255), num_wells INT);

SELECT company, formation, COUNT(*) AS num_wells FROM wells_by_company WHERE formation = 'Bakken Formation' GROUP BY company;


Question: Update the geopolitical risk assessment of 'Project E' to medium

CREATE TABLE geopolitical_risk (project_name VARCHAR(255), risk_level VARCHAR(255)); INSERT INTO geopolitical_risk (project_name, risk_level) VALUES ('Project A', 'medium'), ('Project B', 'low'), ('Project E', 'high');

UPDATE geopolitical_risk SET risk_level = 'medium' WHERE project_name = 'Project E';


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

CREATE INDEX CONCURRENTLY concur_index5 on concur_heap(f2) WHERE f1='x';


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

SELECT 'a | ff' < 'b & c'::tsquery as "false";

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

SELECT count(*) FROM (SELECT 'a | ff' < 'b & c'::tsquery as "false") AS _sub;


Question: Generate PostgreSQL SQL for: What was the score for game 18?

CREATE TABLE table_name_87 (score VARCHAR, game VARCHAR)

SELECT score FROM table_name_87 WHERE game = 18;


Question: What is the maximum revenue earned by restaurants serving 'Halal' dishes?

CREATE TABLE restaurants (restaurant_id INT, name VARCHAR(50), cuisine VARCHAR(50), diet VARCHAR(50), revenue INT); INSERT INTO restaurants VALUES (1, 'Asian Fusion', 'Asian', 'Non-Halal', 5000), (2, 'Tuscan Bistro', 'Italian', 'Non-Halal', 7000), (3, 'Baja Coast', 'Mexican', 'Non-Halal', 4000), (4, 'Sushi House', 'Asian', 'Halal', 8000), (5, 'Pizzeria Rustica', 'Italian', 'Halal', 6000), (6, 'Taqueria El Paso', 'Mexican', 'Halal', 4500), (7, 'Mexican Grill', 'Mexican', 'Halal', 5500), (8, 'Halal Bistro', 'Middle Eastern', 'Halal', 9000);

SELECT diet, MAX(revenue) FROM restaurants WHERE diet = 'Halal';


Question: Generate PostgreSQL SQL for: What is the date of the game with an attendance larger than 62,491?

CREATE TABLE table_name_55 (date VARCHAR, attendance INTEGER)

SELECT date FROM table_name_55 WHERE attendance > 62 OFFSET 491;


Question: How many projects were completed in 'public_works' and 'civil_projects' between 2019-01-01 and 2021-12-31?

CREATE TABLE public_works (id INT, project_name VARCHAR(50), location VARCHAR(50), start_date DATE, end_date DATE, total_cost FLOAT); INSERT INTO public_works (id, project_name, location, start_date, end_date, total_cost) VALUES (1, 'Road Repaving', 'New York', '2020-01-01', '2020-12-31', 500000.00), (2, 'Bridge Construction', 'California', '2019-05-01', '2021-03-31', 2000000.00); CREATE TABLE civil_projects (id INT, project_name VARCHAR(50), location VARCHAR(50), start_date DATE, end_date DATE, total_cost FLOAT); INSERT INTO civil_projects (id, project_name, location, start_date, end_date, total_cost) VALUES (1, 'Dam Construction', 'Texas', '2018-05-01', '2020-01-15', 1500000.00), (2, 'Water Treatment Plant Upgrade', 'Florida', '2019-06-01', '2021-03-31', 800000.00);

SELECT COUNT(*) FROM (SELECT * FROM public_works WHERE start_date >= '2019-01-01' AND end_date <= '2021-12-31' UNION ALL SELECT * FROM civil_projects WHERE start_date >= '2019-01-01' AND end_date <= '2021-12-31') AS completed_projects;


Question: List the electric vehicle models and their adoption rates in the US.

CREATE TABLE ElectricVehicleAdoption (Model VARCHAR(20), Country VARCHAR(10), AdoptionRate FLOAT);

SELECT Model, AdoptionRate FROM ElectricVehicleAdoption WHERE Country = 'US';


Question: Show a SQL definition from the zombodb project (issue-295, item 1).

CREATE TABLE rvs (
  id                BIGSERIAL NOT NULL    CONSTRAINT pk_rvs PRIMARY KEY,
  txt               TEXT
);


Question: Generate PostgreSQL SQL for: Where did the player loaned out on 27 november 2008 move to ?

CREATE TABLE table_name_65 (moving_to VARCHAR, date_from VARCHAR)

SELECT moving_to FROM table_name_65 WHERE date_from = '27 november 2008';


Question: Generate PostgreSQL SQL for: Which outgoing manager was replaced by Jafar Fatahi?

CREATE TABLE table_22297140_3 (outgoing_manager VARCHAR, replaced_by VARCHAR)

SELECT outgoing_manager FROM table_22297140_3 WHERE replaced_by = 'Jafar Fatahi';


Question: Generate PostgreSQL SQL for: what are all the location where station number is c11

CREATE TABLE table_11934032_1 (location VARCHAR, station_number VARCHAR)

SELECT location FROM table_11934032_1 WHERE station_number = 'C11';


Question: Generate PostgreSQL SQL for: What team has a yamaha constructor with all rounds?

CREATE TABLE table_name_60 (team VARCHAR, rounds VARCHAR, constructor VARCHAR)

SELECT team FROM table_name_60 WHERE rounds = 'all' AND constructor = 'yamaha';


Question: Which OTAs in Australia have the highest number of hotel listings with AI-powered services?

CREATE TABLE ota_hotel (ota_id INT, ota_name TEXT, region TEXT, ai_powered TEXT, hotel_listings INT); INSERT INTO ota_hotel (ota_id, ota_name, region, ai_powered, hotel_listings) VALUES (1, 'TravelEase', 'Australia', 'yes', 1000), (2, 'VoyagePlus', 'Australia', 'no', 800), (3, 'ExploreNow', 'Australia', 'yes', 1200);

SELECT ota_name, MAX(hotel_listings) FROM ota_hotel WHERE region = 'Australia' AND ai_powered = 'yes' GROUP BY ota_name;


Question: What is the average emergency room wait time for patients in rural Brazil, and how many nurses are available per patient in the emergency room?

CREATE TABLE patients (patient_id INT, age INT, emergency_room_wait_time INT, location VARCHAR(255)); INSERT INTO patients (patient_id, age, emergency_room_wait_time, location) VALUES (12, 32, 60, 'rural Brazil'); INSERT INTO patients (patient_id, age, emergency_room_wait_time, location) VALUES (13, 50, 90, 'rural Brazil'); CREATE TABLE nurses (nurse_id INT, location VARCHAR(255)); INSERT INTO nurses (nurse_id, location) VALUES (120, 'rural Brazil'); INSERT INTO nurses (nurse_id, location) VALUES (121, 'rural Brazil');

SELECT AVG(emergency_room_wait_time) AS avg_wait_time, COUNT(nurses.nurse_id) / COUNT(DISTINCT patients.patient_id) AS nurses_per_patient FROM patients INNER JOIN nurses ON patients.location = nurses.location WHERE patients.location LIKE 'rural% Brazil';


Question: Generate PostgreSQL SQL for: Which player from the 2004 CFL draft attended Wilfrid Laurier?

CREATE TABLE table_10975034_2 (player VARCHAR, college VARCHAR)

SELECT player FROM table_10975034_2 WHERE college = 'Wilfrid Laurier';


Question: Generate PostgreSQL SQL for: When did Austin Austin TX get the third place?

CREATE TABLE table_2011349_2 (year VARCHAR, third_place VARCHAR)

SELECT year FROM table_2011349_2 WHERE third_place = 'Austin Austin TX';


Question: Generate PostgreSQL SQL for: Which McIntosh has a Stuart of bass, and a Linda McCartney of keyboards or drum?

CREATE TABLE table_name_78 (mcintosh VARCHAR, stuart VARCHAR, linda_mccartney VARCHAR)

SELECT mcintosh FROM table_name_78 WHERE stuart = 'bass' AND linda_mccartney = 'keyboards or drum';


Question: What is the percentage of donations made in each year compared to the total donations?

SELECT DonationYear, SUM(DonationAmount) AS TotalDonation, SUM(DonationAmount) OVER () AS TotalDonations, (SUM(DonationAmount) / SUM(DonationAmount) OVER ()) * 100.0 AS DonationPercentage FROM Donations GROUP BY DonationYear;


Question: Identify space debris mitigation initiatives by ESA and NASA

CREATE TABLE debris_mitigation (initiative VARCHAR(50), agency VARCHAR(50)); INSERT INTO debris_mitigation (initiative, agency) VALUES ('Active Debris Removal', 'ESA'), ('Passive Debris Removal', 'ESA'), ('Space Debris Sensor', 'NASA'), ('Orbital Debris Observatory', 'NASA');

SELECT initiative FROM debris_mitigation WHERE agency IN ('ESA', 'NASA');


Question: Increase the yield of crop 'moringa' in farm 'Sustainable Grove' by 30 in 2023

CREATE TABLE farms (id INT, name TEXT, location TEXT, size FLOAT); INSERT INTO farms (id, name, location, size) VALUES (1, 'Sustainable Grove', 'India', 180.0); CREATE TABLE crops (id INT, farm_id INT, crop TEXT, yield INT, year INT); INSERT INTO crops (id, farm_id, crop, yield, year) VALUES (1, 1, 'moringa', 100, 2023);

UPDATE crops SET yield = yield + 30 WHERE farm_id = (SELECT id FROM farms WHERE name = 'Sustainable Grove') AND crop = 'moringa' AND year = 2023;


Question: What percentage of products in each segment are certified cruelty-free?

CREATE TABLE products (product_id INT, segment VARCHAR(20), certified_cruelty_free BOOLEAN); INSERT INTO products (product_id, segment, certified_cruelty_free) VALUES (1, 'Natural', true), (2, 'Organic', false), (3, 'Natural', true); CREATE TABLE segments (segment VARCHAR(20), num_products INT); INSERT INTO segments (segment, num_products) VALUES ('Natural', 3), ('Organic', 2);

SELECT segment, COUNT(*) * 100.0 / num_products AS percentage FROM products INNER JOIN segments ON products.segment = segments.segment WHERE certified_cruelty_free = true GROUP BY segment;


Question: Generate PostgreSQL SQL for: Which Home Team has an Attendance of 1,859?

CREATE TABLE table_name_14 (home_team VARCHAR, attendance VARCHAR)

SELECT home_team FROM table_name_14 WHERE attendance = '1,859';


Question: PostgreSQL Json: show example 7.

SELECT doc->'site_name' FROM websites WHERE doc @> '{"tags":[{"term":"paris"}, {"term":"food"}]}';

Explanation: Example from PostgreSQL documentation on Json.


Question: What is the total value of military equipment sold to Canada by Lockheed Martin in 2020?

CREATE TABLE MilitaryEquipmentSales (seller VARCHAR(255), buyer VARCHAR(255), equipment VARCHAR(255), sale_value FLOAT, sale_date DATE); INSERT INTO MilitaryEquipmentSales (seller, buyer, equipment, sale_value, sale_date) VALUES ('Lockheed Martin', 'Canada', 'F-35 Fighter Jet', 90000000, '2020-03-15');

SELECT SUM(sale_value) FROM MilitaryEquipmentSales WHERE seller = 'Lockheed Martin' AND buyer = 'Canada' AND sale_date BETWEEN '2020-01-01' AND '2020-12-31';


Question: PostgreSQL regression test 'nls': Write the SELECT query (example 4).

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

SELECT count(*) FROM (SELECT test_translation()) AS _sub;


Question: What is the total network infrastructure investment in Texas for the last 3 years?

CREATE TABLE infrastructure_investments (id INT, year INT, investment DECIMAL(10,2), state VARCHAR(50)); INSERT INTO infrastructure_investments (id, year, investment, state) VALUES (1, 2020, 500000, 'TX'); INSERT INTO infrastructure_investments (id, year, investment, state) VALUES (2, 2019, 600000, 'TX'); INSERT INTO infrastructure_investments (id, year, investment, state) VALUES (3, 2018, 700000, 'TX');

SELECT SUM(investment) FROM infrastructure_investments WHERE state = 'TX' AND year BETWEEN 2018 AND 2020;


Question: What is the percentage of garments made from sustainable materials in each category?

CREATE TABLE garments (garment_id INT, garment_name VARCHAR(255), category VARCHAR(255), is_sustainable_material BOOLEAN);

SELECT category, 100.0 * AVG(CASE WHEN is_sustainable_material THEN 1.0 ELSE 0.0 END) AS percentage FROM garments GROUP BY category;


Question: Generate PostgreSQL SQL for: Name the year model for 1.3

CREATE TABLE table_1444201_1 (year_model VARCHAR, model VARCHAR)

SELECT year_model FROM table_1444201_1 WHERE model = '1.3';


Question: Insert a new record in the 'cities' table with name 'Yountville', state 'CA', and population 3000

CREATE TABLE cities (id INT, name VARCHAR(50), state VARCHAR(2), population INT);

INSERT INTO cities (name, state, population) VALUES ('Yountville', 'CA', 3000);


Question: PL/pgSQL test: Plpgsql Call (example 26).

-- recursive with output arguments

CREATE PROCEDURE test_proc7(x int, INOUT a int, INOUT b numeric)
LANGUAGE plpgsql
AS $$
BEGIN
IF x > 1 THEN
    a := x / 10;
    b := x / 2;
    CALL test_proc7(b::int, a, b);
END IF;
END;
$$;

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


Question: Generate PostgreSQL SQL for: The boat named Agamemnon has what status?

CREATE TABLE table_name_94 (status VARCHAR, name VARCHAR)

SELECT status FROM table_name_94 WHERE name = 'agamemnon';