Question: Generate PostgreSQL SQL for: Name the manner of departure for luis enrique

CREATE TABLE table_27666856_3 (manner_of_departure VARCHAR, outgoing_manager VARCHAR)

SELECT manner_of_departure FROM table_27666856_3 WHERE outgoing_manager = 'Luis Enrique';


Question: Generate PostgreSQL SQL for: What is the score of the game on February 26 with the Chicago black hawks as the home team and the New York Rangers as the visitor team?

CREATE TABLE table_name_59 (score VARCHAR, date VARCHAR, home VARCHAR, visitor VARCHAR)

SELECT score FROM table_name_59 WHERE home = 'chicago black hawks' AND visitor = 'new york rangers' AND date = 'february 26';


Question: How many customers have been served by Shariah-compliant financial institutions in the Middle East offering financial wellbeing products?

CREATE TABLE Customers (CustomerID int, InstitutionID int, Location varchar(50)); INSERT INTO Customers (CustomerID, InstitutionID, Location) VALUES (1, 1, 'Middle East'); CREATE TABLE Institutions (InstitutionID int, Name varchar(50), ShariahCompliant bit, FinancialWellbeing bit); INSERT INTO Institutions (InstitutionID, Name, ShariahCompliant, FinancialWellbeing) VALUES (1, 'Institution A', 1, 1);

SELECT COUNT(*) FROM Customers C INNER JOIN Institutions I ON C.InstitutionID = I.InstitutionID WHERE I.ShariahCompliant = 1 AND I.FinancialWellbeing = 1 AND C.Location = 'Middle East';


Question: What is the difference in mental health visits between consecutive patients, ordered by PatientID?

CREATE TABLE MentalHealthParity (PatientID int, MentalHealthVisits int); INSERT INTO MentalHealthParity (PatientID, MentalHealthVisits) VALUES (1, 5), (2, 3), (3, 6), (4, 4), (5, 8), (6, 7), (7, 6);

SELECT PatientID, MentalHealthVisits, LAG(MentalHealthVisits) OVER (ORDER BY PatientID) AS PreviousVisits, MentalHealthVisits - LAG(MentalHealthVisits) OVER (ORDER BY PatientID) AS VisitDifference FROM MentalHealthParity;


Question: Generate PostgreSQL SQL for: Who drives for the sponsor w.h. bolin?

CREATE TABLE table_name_82 (driver VARCHAR, sponsor VARCHAR)

SELECT driver FROM table_name_82 WHERE sponsor = 'w.h. bolin';


Question: List all sports types

CREATE TABLE sports (id INT PRIMARY KEY, sport_name VARCHAR(100));


Question: Generate PostgreSQL SQL for: What is the earliest quarterfinal week when the genre is dancing and the act is 32?

CREATE TABLE table_27529608_21 (qtr_final__week_ INTEGER, genre VARCHAR, age_s_ VARCHAR)

SELECT MIN(qtr_final__week_) FROM table_27529608_21 WHERE genre = 'Dancing' AND age_s_ = '32';


Question: What is the total value of paintings sold by female artists in Germany?

CREATE TABLE Artists (id INT, name VARCHAR(255), gender VARCHAR(6)); CREATE TABLE ArtWork (id INT, title VARCHAR(255), artist_id INT, price DECIMAL(10,2), type VARCHAR(255)); INSERT INTO Artists (id, name, gender) VALUES (1, 'ArtistX', 'Female'); INSERT INTO ArtWork (id, title, artist_id, price, type) VALUES (1, 'Painting1', 1, 12000, 'Painting');

SELECT SUM(ArtWork.price) FROM ArtWork INNER JOIN Artists ON ArtWork.artist_id = Artists.id WHERE ArtWork.type = 'Painting' AND Artists.gender = 'Female' AND Artists.name LIKE '%Germany%';


Question: Find the number of unique workout activities for members who joined in 2020.

CREATE TABLE members_2020 (id INT, name VARCHAR(50), country VARCHAR(50), joined DATE); INSERT INTO members_2020 (id, name, country, joined) VALUES (6, 'Charlie Davis', 'Canada', '2020-05-10'); CREATE TABLE member_workout (member_id INT, activity VARCHAR(50)); INSERT INTO member_workout (member_id, activity) VALUES (1, 'Running'); INSERT INTO member_workout (member_id, activity) VALUES (1, 'Cycling'); INSERT INTO member_workout (member_id, activity) VALUES (6, 'Swimming'); INSERT INTO member_workout (member_id, activity) VALUES (6, 'Yoga');

SELECT member_id, COUNT(DISTINCT activity) as unique_activities FROM member_workout GROUP BY member_id HAVING joined >= '2020-01-01' AND joined < '2021-01-01';


Question: Insert a new record with species_id 5, species_name 'reindeer', and biomass 180.0 in the 'species_data' table.

CREATE TABLE species_data (species_id INT, species_name VARCHAR(255), biomass FLOAT);

INSERT INTO species_data (species_id, species_name, biomass) VALUES (5, 'reindeer', 180.0);


Question: Which drugs had zero sales in '2019' but not in '2018' and '2020'?

CREATE TABLE sales_yearly_2(year int, drug varchar(10), revenue int); INSERT INTO sales_yearly_2(year, drug, revenue) VALUES(2018, 'DrugM', 500), (2019, 'DrugM', 0), (2020, 'DrugM', 600);

SELECT drug FROM sales_yearly_2 WHERE revenue = 0 AND year = 2019 INTERSECT SELECT drug FROM sales_yearly_2 WHERE year IN (2018, 2020) AND revenue > 0;


Question: Which cruelty-free certified products are most preferred by consumers in the USA?

CREATE TABLE cosmetics_preferences (id INT, consumer_id INT, product_id INT, preference_score INT, country VARCHAR(255)); INSERT INTO cosmetics_preferences (id, consumer_id, product_id, preference_score, country) VALUES (1, 1, 1, 5, 'USA'); CREATE TABLE products (id INT, name VARCHAR(255), is_cruelty_free BOOLEAN); INSERT INTO products (id, name, is_cruelty_free) VALUES (1, 'Natural Glow Foundation', true);

SELECT p.name, cp.preference_score FROM cosmetics_preferences cp INNER JOIN products p ON cp.product_id = p.id WHERE cp.country = 'USA' AND p.is_cruelty_free = true;


Question: Generate PostgreSQL SQL for: Which Model has the GCM (kg) Technical Capacity of 42000?

CREATE TABLE table_name_52 (model VARCHAR, gcm__kg__technical_capacity VARCHAR)

SELECT model FROM table_name_52 WHERE gcm__kg__technical_capacity = '42000';


Question: Generate PostgreSQL SQL for: What party established in 1797 won an election in 2007?

CREATE TABLE table_name_17 (party VARCHAR, established VARCHAR, election VARCHAR)

SELECT party FROM table_name_17 WHERE established > 1797 AND election = 2007;


Question: What is the maximum depth of all deep-sea expeditions in the Pacific Ocean?

CREATE TABLE deep_sea_expeditions (expedition_name VARCHAR(255), depth FLOAT, ocean VARCHAR(255));

SELECT MAX(depth) FROM deep_sea_expeditions WHERE ocean = 'Pacific';


Question: What is the average billing amount for attorneys in the 'billing' table, grouped by their specialty?

CREATE TABLE attorneys (attorney_id INT, specialty VARCHAR(255)); CREATE TABLE billing (bill_id INT, attorney_id INT, amount DECIMAL(10,2));

SELECT a.specialty, AVG(b.amount) FROM attorneys a INNER JOIN billing b ON a.attorney_id = b.attorney_id GROUP BY a.specialty;


Question: Generate PostgreSQL SQL for: Who's the opponent of the game with the record 64-51?

CREATE TABLE table_name_60 (opponent VARCHAR, record VARCHAR)

SELECT opponent FROM table_name_60 WHERE record = '64-51';


Question: Generate PostgreSQL SQL for: Name the number of titles written by adam i. lapidus

CREATE TABLE table_12030612_9 (title VARCHAR, written_by VARCHAR)

SELECT COUNT(title) FROM table_12030612_9 WHERE written_by = 'Adam I. Lapidus';


Question: What are the earliest artifacts in each excavation site?

CREATE TABLE excavation_sites (site_id INT, site_name VARCHAR(255)); CREATE TABLE artifacts (artifact_id INT, site_id INT, artifact_type VARCHAR(255), date_found DATE); INSERT INTO excavation_sites (site_id, site_name) VALUES (1, 'site_a'), (2, 'site_b'), (3, 'site_c'); INSERT INTO artifacts (artifact_id, site_id, artifact_type, date_found) VALUES (1, 1, 'Pottery', '2020-01-01'), (2, 1, 'Bone Fragments', '2019-01-01'), (3, 2, 'Pottery', '2021-01-01'), (4, 2, 'Coins', '2020-01-01'), (5, 3, 'Bone Fragments', '2018-01-01'), (6, 3, 'Bronze Tools', '2019-01-01');

SELECT site_name, MIN(date_found) as earliest_date FROM excavation_sites s JOIN artifacts a ON s.site_id = a.site_id GROUP BY site_name;


Question: Generate PostgreSQL SQL for: what is the number of smallpox when typhoid fever is 293

CREATE TABLE table_1007688_1 (smallpox INTEGER, typhoid_fever VARCHAR)

SELECT MAX(smallpox) FROM table_1007688_1 WHERE typhoid_fever = 293;


Question: What is the maximum safety rating for algorithmic fairness models?

CREATE TABLE fairness_models (model_name TEXT, safety_rating INTEGER); INSERT INTO fairness_models (model_name, safety_rating) VALUES ('Model X', 9), ('Model Y', 8), ('Model Z', 10);

SELECT MAX(safety_rating) FROM fairness_models WHERE model_name LIKE '%fairness%';


Question: What is the total number of cybersecurity incidents and the average severity for each department, partitioned by month and ordered by total number of cybersecurity incidents in descending order?

CREATE TABLE cybersecurity_incident (id INT, department_id INT, severity INT, incident_date DATE); INSERT INTO cybersecurity_incident (id, department_id, severity, incident_date) VALUES (1, 1, 8, '2021-03-15'); INSERT INTO cybersecurity_incident (id, department_id, severity, incident_date) VALUES (2, 2, 5, '2022-01-10'); CREATE TABLE department (id INT, name VARCHAR(255)); INSERT INTO department (id, name) VALUES (1, 'IT'); INSERT INTO department (id, name) VALUES (2, 'Security');

SELECT d.name as department, DATEPART(YEAR, incident_date) as year, DATEPART(MONTH, incident_date) as month, COUNT(ci.id) as total_cybersecurity_incidents, AVG(ci.severity) as avg_severity, ROW_NUMBER() OVER (PARTITION BY d.name ORDER BY COUNT(ci.id) DESC) as rank FROM cybersecurity_incident ci JOIN department d ON ci.department_id = d.id GROUP BY d.name, DATEPART(YEAR, incident_date), DATEPART(MONTH, incident_date) ORDER BY total_cybersecurity_incidents DESC;


Question: What is the number of professional development events attended by teachers in each region, ordered by attendance?

CREATE TABLE teacher_events (teacher_id INT, region VARCHAR(20), event_attended INT); INSERT INTO teacher_events (teacher_id, region, event_attended) VALUES (1, 'North', 2), (2, 'North', 1), (3, 'South', 3), (4, 'South', 0);

SELECT region, SUM(event_attended) as total_events, ROW_NUMBER() OVER (ORDER BY SUM(event_attended) DESC) as rank FROM teacher_events GROUP BY region ORDER BY rank;


Question: What are the total R&D expenditures and sales amounts for each drug, unpivoted and with a total row?

CREATE TABLE RnDExpenditures (drug_name VARCHAR(255), rnd_expenditure DECIMAL(10,2)); INSERT INTO RnDExpenditures (drug_name, rnd_expenditure) VALUES ('DrugD', 60000.00), ('DrugE', 80000.00), ('DrugF', 40000.00); CREATE TABLE SalesData (drug_name VARCHAR(255), sales_quantity INT, sales_amount DECIMAL(10,2)); INSERT INTO SalesData (drug_name, sales_quantity, sales_amount) VALUES ('DrugD', 120, 18000.00), ('DrugE', 150, 22500.00), ('DrugF', 75, 10500.00);

SELECT drug_name, 'rnd_expenditure' as metric, SUM(rnd_expenditure) as value FROM RnDExpenditures GROUP BY drug_name UNION ALL SELECT drug_name, 'sales_amount' as metric, SUM(sales_amount) as value FROM SalesData GROUP BY drug_name UNION ALL SELECT 'Total', SUM(value) as value FROM (SELECT drug_name, 'rnd_expenditure' as metric, SUM(rnd_expenditure) as value FROM RnDExpenditures GROUP BY drug_name UNION ALL SELECT drug_name, 'sales_amount' as metric, SUM(sales_amount) as value FROM SalesData GROUP BY drug_name) sub;


Question: Generate PostgreSQL SQL for: What was the final score of Washington's home game?

CREATE TABLE table_28298589_4 (result VARCHAR, home_team VARCHAR)

SELECT result FROM table_28298589_4 WHERE home_team = 'Washington';


Question: What is the total budget allocated for public transportation in New York City?

CREATE TABLE public_transportation (transport_id INT, transport_name TEXT, city TEXT, state TEXT, budget INT); INSERT INTO public_transportation (transport_id, transport_name, city, state, budget) VALUES (1, 'New York City Subway', 'New York', 'New York', 8000000000); INSERT INTO public_transportation (transport_id, transport_name, city, state, budget) VALUES (2, 'MTA Bus Company', 'New York', 'New York', 500000000); INSERT INTO public_transportation (transport_id, transport_name, city, state, budget) VALUES (3, 'Staten Island Ferry', 'New York', 'New York', 200000000);

SELECT SUM(budget) FROM public_transportation WHERE city = 'New York' AND state = 'New York';


Question: What was the average sale price for all artworks in the 'Rococo' movement that were sold by the 'Victoria and Albert Museum'?

CREATE TABLE Artworks (artwork_id INT, movement VARCHAR(255), sale_price DECIMAL(10, 2), museum_name VARCHAR(255));

SELECT AVG(sale_price) FROM Artworks WHERE movement = 'Rococo' AND museum_name = 'Victoria and Albert Museum';


Question: Generate PostgreSQL SQL for: what's the winner with tournament value of kroger senior classic

CREATE TABLE table_11621915_1 (winner VARCHAR, tournament VARCHAR)

SELECT winner FROM table_11621915_1 WHERE tournament = 'Kroger Senior Classic';


Question: Delete all records in the 'rural_infrastructure' table where the budget is less than 50000.

CREATE TABLE rural_infrastructure (id INT, project_name VARCHAR(255), budget INT);

DELETE FROM rural_infrastructure WHERE budget < 50000;


Question: Find the number of autonomous shuttles in each city

CREATE TABLE autonomous_vehicles (id INT PRIMARY KEY, make VARCHAR(255), model VARCHAR(255), year INT, city VARCHAR(255));

CREATE VIEW autonmous_shuttles AS SELECT city, COUNT(*) as num_shuttles FROM autonomous_vehicles WHERE make = 'Wayve' AND model = 'Kamino' GROUP BY city;


Question: Generate PostgreSQL SQL for: Is it home or away when opponent is Pride with a W 11-10 result?

CREATE TABLE table_name_49 (home_away VARCHAR, opponent VARCHAR, result VARCHAR)

SELECT home_away FROM table_name_49 WHERE opponent = 'pride' AND result = 'w 11-10';


Question: Generate PostgreSQL SQL for: Which athlete is ranked below 5 and is from China?

CREATE TABLE table_name_62 (athletes VARCHAR, rank VARCHAR, country VARCHAR)

SELECT athletes FROM table_name_62 WHERE rank < 5 AND country = 'china';


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

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


Question: Who are the male actors with more than 5 movies acted?

CREATE TABLE actors (name VARCHAR(255), gender VARCHAR(10), movies INTEGER); INSERT INTO actors (name, gender, movies) VALUES ('ActorA', 'Female', 3), ('ActorB', 'Male', 15), ('ActorC', 'Female', 2), ('ActorD', 'Male', 20), ('ActorE', 'Female', 8), ('ActorF', 'Male', 7), ('ActorG', 'Female', 6), ('ActorH', 'Male', 12);

SELECT name FROM actors WHERE gender = 'Male' AND movies > 5;


Question: How many volunteer hours were recorded for environmental programs in California?

CREATE TABLE VolunteerEvents (EventID INT, EventName TEXT, Location TEXT, EventType TEXT); INSERT INTO VolunteerEvents (EventID, EventName, Location, EventType) VALUES (1, 'Beach Cleanup', 'California', 'Environment'), (2, 'Tree Planting', 'New York', 'Environment');

SELECT SUM(VolunteerHours) FROM VolunteerEvents JOIN VolunteerHours ON VolunteerEvents.EventID = VolunteerHours.EventID WHERE VolunteerEvents.Location = 'California' AND VolunteerEvents.EventType = 'Environment';


Question: Generate PostgreSQL SQL for: What was Geelong's score when they were the away team?

CREATE TABLE table_name_62 (away_team VARCHAR)

SELECT away_team AS score FROM table_name_62 WHERE away_team = 'geelong';


Question: Find the client with the highest account balance in each region.

CREATE TABLE clients (client_id INT, name VARCHAR(50), region VARCHAR(20), account_balance DECIMAL(10,2)); INSERT INTO clients (client_id, name, region, account_balance) VALUES (1, 'John Smith', 'West', 30000.00), (2, 'Jane Doe', 'Northeast', 22000.00), (3, 'Mike Johnson', 'West', 35000.00), (4, 'Sara Jones', 'Southeast', 12000.00), (5, 'William Brown', 'Northeast', 25000.00), (6, 'Emily Davis', 'Southeast', 40000.00);

SELECT client_id, name, region, account_balance FROM (SELECT client_id, name, region, account_balance, DENSE_RANK() OVER (PARTITION BY region ORDER BY account_balance DESC) as rank FROM clients) AS ranked_clients WHERE rank = 1;


Question: Count the number of military equipment maintenance requests for each type of equipment in the state of New York

CREATE TABLE military_equipment (equipment_id INT, name VARCHAR(255), type VARCHAR(255), maintenance_cost DECIMAL(10,2), state VARCHAR(2)); CREATE TABLE maintenance_requests (request_id INT, equipment_id INT, request_date DATE, branch VARCHAR(255));

SELECT equipment_type, COUNT(*) as num_requests FROM military_equipment JOIN maintenance_requests ON military_equipment.equipment_id = maintenance_requests.equipment_id WHERE state = 'New York' GROUP BY equipment_type;


Question: What is the average word count of articles published on politics in the last month, grouped by week?

CREATE TABLE articles (id INT, title VARCHAR(255), word_count INT, publish_date DATE, topic VARCHAR(255)); INSERT INTO articles (id, title, word_count, publish_date, topic) VALUES (1, 'Article 1', 500, '2022-01-01', 'politics'), (2, 'Article 2', 700, '2022-01-05', 'politics');

SELECT AVG(word_count), WEEKOFYEAR(publish_date) AS Week FROM articles WHERE topic = 'politics' AND publish_date >= DATE_SUB(NOW(), INTERVAL 1 MONTH) GROUP BY Week;


Question: Generate PostgreSQL SQL for: Who were the opponents that played on a hard surface on July 13, 2008?

CREATE TABLE table_name_85 (opponents VARCHAR, surface VARCHAR, date VARCHAR)

SELECT opponents FROM table_name_85 WHERE surface = 'hard' AND date = 'july 13, 2008';


Question: Generate PostgreSQL SQL for: How many games were played on october 16?

CREATE TABLE table_27756014_1 (high_points VARCHAR, date VARCHAR)

SELECT COUNT(high_points) FROM table_27756014_1 WHERE date = 'October 16';


Question: Generate PostgreSQL SQL for: Who was the outgoing manager replaced by Marian Bucurescu?

CREATE TABLE table_17115950_2 (outgoing_manager VARCHAR, replaced_by VARCHAR)

SELECT outgoing_manager FROM table_17115950_2 WHERE replaced_by = 'Marian Bucurescu';


Question: Generate PostgreSQL SQL for: In the Western Oval venue, what is the average crowd?

CREATE TABLE table_name_38 (crowd INTEGER, venue VARCHAR)

SELECT AVG(crowd) FROM table_name_38 WHERE venue = 'western oval';


Question: Present the number of cases and their respective outcomes for a given region

CREATE TABLE region_outcomes (region VARCHAR(50) PRIMARY KEY, cases_handled INT, win_rate DECIMAL(5,4));

SELECT region, SUM(cases_handled) FROM region_outcomes GROUP BY region;


Question: Show a SQL definition from the zombodb project (test-xform, item 2).

CREATE VIEW xform_test_view AS
    SELECT xform_test.*,
           users.url,
           users.login,
           users.avatar_url,
           users.gravatar_id,
           users.display_login
      FROM xform_test
      LEFT JOIN users ON xform_test.user_id = users.id;

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


Question: Count the number of accidents for each aircraft.

CREATE TABLE FlightSafety (accident_id INT, aircraft_id INT, accident_date DATE);

SELECT aircraft_id, COUNT(*) FROM FlightSafety GROUP BY aircraft_id;


Question: What is the monthly production volume of sustainable garments in each country?

CREATE TABLE productions (id INT, garment VARCHAR(50), material VARCHAR(50), country VARCHAR(50), production_date DATE); INSERT INTO productions (id, garment, material, country, production_date) VALUES (1, 'T-Shirt', 'Organic Cotton', 'India', '2021-01-15'), (2, 'Hoodie', 'Bamboo Fabric', 'China', '2021-02-20'), (3, 'Jacket', 'Recycled Polyester', 'Bangladesh', '2021-03-10');

SELECT m.country, EXTRACT(MONTH FROM production_date) as month, COUNT(*) as production_volume FROM productions p JOIN materials m ON p.country = m.country WHERE m.type IN ('Organic Cotton', 'Bamboo Fabric', 'Recycled Polyester') GROUP BY m.country, month ORDER BY month;


Question: Generate PostgreSQL SQL for: What was the To par of Jack Nicklaus?

CREATE TABLE table_name_71 (to_par VARCHAR, player VARCHAR)

SELECT to_par FROM table_name_71 WHERE player = 'jack nicklaus';


Question: What is the average production volume of chemical substances in the Europe region for the year 2019?

CREATE TABLE ChemicalSubstances (SubstanceID INT, SubstanceName VARCHAR(50), ProductionVolume INT, Region VARCHAR(50), ProductionDate DATE); INSERT INTO ChemicalSubstances (SubstanceID, SubstanceName, ProductionVolume, Region, ProductionDate) VALUES (1, 'Ethylene', 13000, 'Europe', '2019-01-01'), (2, 'Propylene', 9000, 'Europe', '2019-02-01'), (3, 'Benzenene', 14000, 'Europe', '2019-03-01');

SELECT AVG(ProductionVolume) FROM ChemicalSubstances WHERE Region = 'Europe' AND YEAR(ProductionDate) = 2019;


Question: PostgreSQL regression test 'money': Write the SELECT query (example 106).

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

SELECT count(*) FROM (SELECT '1'::money / 0::int2) AS _sub;


Question: What is the total cost of all road construction projects in Florida?

CREATE TABLE road_construction (project_name TEXT, project_cost INT, project_state TEXT); INSERT INTO road_construction (project_name, project_cost, project_state) VALUES ('RPC1', 5000, 'Florida'), ('RPC2', 7000, 'Florida'), ('RPC3', 8000, 'Florida'), ('RPC4', 6000, 'Florida');

SELECT SUM(project_cost) FROM road_construction WHERE project_state = 'Florida';


Question: List the case numbers, client addresses, and total billing amount for cases with the word 'divorce' in the case name, in the state of New York, ordered by the total billing amount in descending order.

CREATE TABLE Cases (CaseID INT, CaseName VARCHAR(255), ClientAddress VARCHAR(255), AttorneyID INT); INSERT INTO Cases (CaseID, CaseName, ClientAddress, AttorneyID) VALUES (1, 'Smith v. Johnson - Divorce', '123 Main St, New York, NY', 1); CREATE TABLE Billing (BillingID INT, CaseID INT, Amount DECIMAL(10, 2));

SELECT Cases.CaseID, Cases.ClientAddress, SUM(Billing.Amount) FROM Cases INNER JOIN Billing ON Cases.CaseID = Billing.CaseID WHERE Cases.CaseName LIKE '%divorce%' AND Cases.AttorneyID IN (SELECT AttorneyID FROM Attorneys WHERE State = 'New York') GROUP BY Cases.CaseID, Cases.ClientAddress ORDER BY SUM(Billing.Amount) DESC;


Question: Which countries have participated in the community_education program, and what was the total expenditure for each country?

CREATE TABLE community_education (id INT, country VARCHAR(50), participation BOOLEAN, expenditure INT);

SELECT country, SUM(expenditure) FROM community_education WHERE participation = TRUE GROUP BY country;


Question: List eSports teams with the lowest number of players

CREATE TABLE teams (id INT, region VARCHAR(10), players INT); INSERT INTO teams (id, region, players) VALUES (1, 'Europe', 50); INSERT INTO teams (id, region, players) VALUES (2, 'Asia', 75); INSERT INTO teams (id, region, players) VALUES (3, 'America', 100); INSERT INTO teams (id, region, players) VALUES (4, 'Africa', 25);

SELECT id, region, players FROM teams ORDER BY players ASC LIMIT 1;


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

select c2/2, sum(c2) * (c2/2) from ft1 group by c2/2 order by c2/2;

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


Question: What is the total installed capacity of solar plants in the 'solar_plants' table, and what is the average installed capacity of these solar plants, grouped by state?

CREATE TABLE solar_plants (id INT, state VARCHAR(255), name VARCHAR(255), capacity FLOAT, start_date DATE, end_date DATE); INSERT INTO solar_plants (id, state, name, capacity, start_date, end_date) VALUES (6, 'California', 'Solar Plant D', 40.0, '2021-01-01', '2026-12-31'), (7, 'Nevada', 'Solar Plant E', 50.0, '2022-01-01', '2027-12-31');

SELECT state, SUM(capacity) as total_capacity, AVG(capacity) as avg_capacity FROM solar_plants GROUP BY state;


Question: Generate PostgreSQL SQL for: What is the medal named fatuma roba category:articles with hcards for?

CREATE TABLE table_name_73 (medal VARCHAR, name VARCHAR)

SELECT medal FROM table_name_73 WHERE name = 'fatuma roba category:articles with hcards';


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

UPDATE temporal_partitioned_fk_rng2rng SET id = '[4,5)' WHERE id = '[1,2)';

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


Question: Generate PostgreSQL SQL for: What's the series number of the episode with production code 329?

CREATE TABLE table_18055005_1 (no_in_series VARCHAR, prod_code VARCHAR)

SELECT no_in_series FROM table_18055005_1 WHERE prod_code = '329';


Question: Generate PostgreSQL SQL for: What is the address of the restaurant Subway?

CREATE TABLE Restaurant (Address VARCHAR, ResName VARCHAR)

SELECT Address FROM Restaurant WHERE ResName = 'Subway';


Question: Generate PostgreSQL SQL for: How many laps did Ricardo Zonta have?

CREATE TABLE table_name_69 (laps INTEGER, driver VARCHAR)

SELECT SUM(laps) FROM table_name_69 WHERE driver = 'ricardo zonta';


Question: Generate PostgreSQL SQL for: What is the total number of goals scored of the club with more than 3 draws, more than 1 loses, and less than 26 points?

CREATE TABLE table_name_15 (goals_scored VARCHAR, points VARCHAR, draws VARCHAR, loses VARCHAR)

SELECT COUNT(goals_scored) FROM table_name_15 WHERE draws > 3 AND loses > 1 AND points < 26;


Question: How many community policing events were held in the last month in each district?

CREATE TABLE community_policing (id INT, date DATE, district VARCHAR(20)); INSERT INTO community_policing (id, date, district) VALUES (1, '2022-01-01', 'district1'), (2, '2022-01-02', 'district2');

SELECT district, COUNT(*) FROM community_policing WHERE date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH) GROUP BY district;


Question: How many songs were released per month in 2020?

CREATE TABLE song_release (id INT, title TEXT, release_month INT, release_year INT, genre TEXT); INSERT INTO song_release (id, title, release_month, release_year, genre) VALUES (1, 'Song4', 1, 2020, 'Pop'); INSERT INTO song_release (id, title, release_month, release_year, genre) VALUES (2, 'Song5', 3, 2020, 'Rock'); INSERT INTO song_release (id, title, release_month, release_year, genre) VALUES (3, 'Song6', 12, 2020, 'Jazz');

SELECT release_month, COUNT(*) as songs_released FROM song_release WHERE release_year = 2020 GROUP BY release_month;


Question: Generate PostgreSQL SQL for: What did vijay singh score with a +5 to par?

CREATE TABLE table_name_92 (score VARCHAR, to_par VARCHAR, player VARCHAR)

SELECT score FROM table_name_92 WHERE to_par = '+5' AND player = 'vijay singh';


Question: Generate PostgreSQL SQL for: What score has detroit as the home, and December 9 as the date?

CREATE TABLE table_name_78 (score VARCHAR, home VARCHAR, date VARCHAR)

SELECT score FROM table_name_78 WHERE home = 'detroit' AND date = 'december 9';


Question: Generate PostgreSQL SQL for: What is average December when game is 30?

CREATE TABLE table_name_79 (december INTEGER, game VARCHAR)

SELECT AVG(december) FROM table_name_79 WHERE game = 30;


Question: Generate PostgreSQL SQL for: Name the clas AAAA of school year 2000-01

CREATE TABLE table_name_76 (class_aAAA VARCHAR, school_year VARCHAR)

SELECT class_aAAA FROM table_name_76 WHERE school_year = '2000-01';


Question: Generate PostgreSQL SQL for: What college does Dennis Scott attend?

CREATE TABLE table_name_26 (college VARCHAR, player VARCHAR)

SELECT college FROM table_name_26 WHERE player = 'dennis scott';


Question: Write the DDL statement from PostgreSQL regression test 'foreign_key' (example 924).

CREATE TABLE pk32 (b int, a int NOT NULL);

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


Question: Generate PostgreSQL SQL for: What is the score on February 23, 2005?

CREATE TABLE table_name_81 (score VARCHAR, date VARCHAR)

SELECT score FROM table_name_81 WHERE date = 'february 23, 2005';


Question: What is the highest salary for employees in the finance department?

CREATE TABLE employees (id INT, name VARCHAR(50), department VARCHAR(50), salary FLOAT); INSERT INTO employees (id, name, department, salary) VALUES (1, 'John Doe', 'Marketing', 75000.00), (2, 'Jane Smith', 'Marketing', 80000.00), (3, 'Richard Roe', 'Finance', 90000.00), (4, 'Judy Johnson', 'Finance', 95000.00);

SELECT MAX(salary) FROM employees WHERE department = 'Finance';


Question: Generate PostgreSQL SQL for: What is the average pots of Alfa Romeo v12 after 1983?

CREATE TABLE table_name_44 (pts INTEGER, engine VARCHAR, year VARCHAR)

SELECT AVG(pts) FROM table_name_44 WHERE engine = 'alfa romeo v12' AND year > 1983;


Question: What is the number of military diplomacy events held by Russia with African countries in 2019?

CREATE TABLE military_diplomacy (id INT, country VARCHAR(255), year INT, event_name VARCHAR(255)); INSERT INTO military_diplomacy (id, country, year, event_name) VALUES (1, 'Egypt', 2019, 'Russian-Egyptian Military Cooperation Commission');

SELECT COUNT(*) FROM military_diplomacy WHERE country LIKE 'Africa%' AND year = 2019;


Question: Update the treatment type for patient 001 in the treatments table to "Group Therapy".

CREATE TABLE patients (id TEXT PRIMARY KEY, name TEXT, age INT, gender TEXT); CREATE TABLE treatments (patient_id TEXT, treatment_type TEXT, therapist_id TEXT, start_date DATE, end_date DATE, FOREIGN KEY (patient_id) REFERENCES patients(id));

WITH updated_treatment AS (UPDATE treatments SET treatment_type = 'Group Therapy' WHERE patient_id = '001') SELECT * FROM updated_treatment;


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

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


Question: What is the total revenue for the 'Blue' line since its inception?

CREATE TABLE routes (line VARCHAR(10), start_date DATE); INSERT INTO routes (line, start_date) VALUES ('Blue', '2010-01-01'); CREATE TABLE fares (route VARCHAR(10), revenue DECIMAL(10, 2)); INSERT INTO fares (route, revenue) VALUES ('Blue', 5000), ('Blue', 6000), ('Blue', 7000);

SELECT SUM(revenue) FROM fares WHERE route = (SELECT line FROM routes WHERE start_date <= '2010-01-01' AND line = 'Blue' LIMIT 1);


Question: What is the name and type of all satellites launched by spacecraft from Russia?

CREATE TABLE Spacecraft (id INT, name VARCHAR(50), country VARCHAR(50), launch_date DATE); INSERT INTO Spacecraft (id, name, country, launch_date) VALUES (1, 'Falcon 9', 'USA', '2010-06-04'); INSERT INTO Spacecraft (id, name, country, launch_date) VALUES (2, 'Soyuz-FG', 'Russia', '2001-11-02');   CREATE TABLE Satellites (id INT, name VARCHAR(50), type VARCHAR(50), spacecraft_id INT); INSERT INTO Satellites (id, name, type, spacecraft_id) VALUES (1, 'TESS', 'Observation', 1); INSERT INTO Satellites (id, name, type, spacecraft_id) VALUES (2, 'MetOp-C', 'Weather', 2);

SELECT s.name, s.type FROM Satellites s JOIN Spacecraft sp ON s.spacecraft_id = sp.id WHERE sp.country = 'Russia';


Question: What is the breakdown of the budget allocated for accessibility improvements in each school?

CREATE TABLE AccessibilityImprovements (SchoolName VARCHAR(255), Year INT, Budget DECIMAL(10,2)); INSERT INTO AccessibilityImprovements (SchoolName, Year, Budget) VALUES ('SchoolA', 2020, 50000.00), ('SchoolB', 2020, 75000.00), ('SchoolC', 2019, 60000.00);

SELECT SchoolName, SUM(Budget) as TotalBudget FROM AccessibilityImprovements WHERE SchoolName IN (SELECT SchoolName FROM Schools WHERE Type = 'School') GROUP BY SchoolName;


Question: Insert a new garment with id 3, name 'Jacket', category 'Men', rating 5 and quantity 25 into the database.

CREATE TABLE garments (id INT PRIMARY KEY, name VARCHAR(255), category VARCHAR(255), rating INT); CREATE TABLE inventories (id INT PRIMARY KEY, garment_id INT, quantity INT);

INSERT INTO garments (id, name, category, rating) VALUES (3, 'Jacket', 'Men', 5); INSERT INTO inventories (id, garment_id, quantity) VALUES (3, 3, 25);


Question: What is the total number of accessible technology conferences in South America?

CREATE TABLE tech_conferences (conference_location VARCHAR(255), is_accessible BOOLEAN); INSERT INTO tech_conferences (conference_location, is_accessible) VALUES ('Brazil', true), ('Colombia', false), ('Argentina', true);

SELECT COUNT(*) FROM tech_conferences WHERE conference_location LIKE 'South%' AND is_accessible = true;


Question: Generate PostgreSQL SQL for: What is the High points with a Game that is 56?

CREATE TABLE table_name_31 (high_points VARCHAR, game VARCHAR)

SELECT high_points FROM table_name_31 WHERE game = 56;


Question: Which public transportation systems were added in Q3 2021?

CREATE TABLE schema.public_transportation (system_id INT, system_name VARCHAR(50), system_type VARCHAR(50), implementation_date DATE); INSERT INTO schema.public_transportation (system_id, system_name, system_type, implementation_date) VALUES (1, 'Subway', 'Rail', '2021-04-01'), (2, 'Light Rail', 'Rail', '2021-07-01'), (3, 'Bus Rapid Transit', 'Bus', '2021-10-01');

SELECT system_name FROM schema.public_transportation WHERE implementation_date BETWEEN '2021-07-01' AND '2021-09-30';


Question: What is the average age of visitors who attended the "African Art" exhibition?

CREATE TABLE Exhibitions (ExhibitionID INT, ExhibitionName VARCHAR(255), Age INT); INSERT INTO Exhibitions (ExhibitionID, ExhibitionName, Age) VALUES (1, 'African Art Exhibition', 32), (2, 'Contemporary Art Exhibition', 28);

SELECT AVG(Age) FROM Exhibitions WHERE ExhibitionName = 'African Art Exhibition';


Question: Generate PostgreSQL SQL for: Tell me the wkts for econ of 4.23

CREATE TABLE table_name_13 (wkts VARCHAR, econ VARCHAR)

SELECT wkts FROM table_name_13 WHERE econ = '4.23';


Question: Delete fish farming records with no species information?

CREATE TABLE FishFarming (FarmID INT, Location VARCHAR(50), Date DATE, Species VARCHAR(50));

DELETE FROM FishFarming WHERE Species IS NULL;


Question: Generate PostgreSQL SQL for: What is the USN 2013 ranking with a BW 2013 ranking less than 1000, a Forbes 2011 ranking larger than 17, and a CNN 2011 ranking less than 13?

CREATE TABLE table_name_63 (usn_2013 INTEGER, cnn_2011 VARCHAR, bw_2013 VARCHAR, forbes_2011 VARCHAR)

SELECT SUM(usn_2013) FROM table_name_63 WHERE bw_2013 < 1000 AND forbes_2011 > 17 AND cnn_2011 < 13;


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

SELECT * FROM test_macaddr8 WHERE i<'22:00:5c:08:55:08:01:02'::macaddr8 ORDER BY i;

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


Question: How many graduate students are enrolled in the Mathematics or Physics departments?

CREATE TABLE departments (id INT, name VARCHAR(50)); INSERT INTO departments (id, name) VALUES (1, 'Mathematics'); INSERT INTO departments (id, name) VALUES (2, 'Physics'); CREATE TABLE students (id INT, name VARCHAR(50), department_id INT, level VARCHAR(10)); INSERT INTO students (id, name, department_id, level) VALUES (1, 'John Doe', 1, 'Graduate'); INSERT INTO students (id, name, department_id, level) VALUES (2, 'Jane Smith', 2, 'Graduate');

SELECT COUNT(*) FROM students WHERE department_id IN (SELECT id FROM departments WHERE name IN ('Mathematics', 'Physics')) AND level = 'Graduate';


Question: What is the most common type of crime committed in each borough, in the last month?

CREATE TABLE crimes (id INT, date DATE, borough VARCHAR(50), type VARCHAR(50));

SELECT borough, type, COUNT(*) as count FROM crimes WHERE date >= DATEADD(MONTH, -1, GETDATE()) GROUP BY borough, type ORDER BY borough, count DESC;


Question: Show a SQL definition from the timescaledb project (size_utils, item 24).

-- Get relation size of the chunks of an hypertable
-- hypertable - hypertable to get size of
--
-- Returns:
-- chunk_schema                  - schema name for chunk
-- chunk_name                    - chunk table name
-- table_bytes                   - Disk space used by chunk table
-- index_bytes                   - Disk space used by indexes
-- toast_bytes                   - Disk space of toast tables
-- total_bytes                   - Disk space used in total
-- node_name                     - node on which chunk lives if this is
--                              a distributed hypertable.
CREATE OR REPLACE FUNCTION @extschema@.chunks_detailed_size(
    hypertable              REGCLASS
)
RETURNS TABLE (
               chunk_schema NAME,
               chunk_name NAME,
               table_bytes BIGINT,
               index_bytes BIGINT,
               toast_bytes BIGINT,
               total_bytes BIGINT,
               node_name   NAME)
LANGUAGE PLPGSQL VOLATILE STRICT AS
$BODY$
DECLARE
        table_name       NAME;

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


Question: Generate PostgreSQL SQL for: How many against when losses are 11 and wins are fewer than 5?

CREATE TABLE table_name_24 (against INTEGER, losses VARCHAR, wins VARCHAR)

SELECT AVG(against) FROM table_name_24 WHERE losses = 11 AND wins < 5;


Question: What is the count of startups founded by Latinx individuals in the education sector?

CREATE TABLE company (id INT, name TEXT, industry TEXT, founder_race TEXT); INSERT INTO company (id, name, industry, founder_race) VALUES (1, 'EduBoost', 'Education', 'Latinx'); INSERT INTO company (id, name, industry, founder_race) VALUES (2, 'Shopify', 'E-commerce', 'Asian'); CREATE TABLE funding_round (company_id INT, round_size INT); INSERT INTO funding_round (company_id, round_size) VALUES (1, 5000000); INSERT INTO funding_round (company_id, round_size) VALUES (2, 7000000);

SELECT COUNT(*) FROM company WHERE company.founder_race = 'Latinx' AND company.industry = 'Education';


Question: Insert a new record into the 'calibration_data' table with 'algorithm' = 'Deep Learning', 'precision' = 0.8, 'recall' = 0.7

CREATE TABLE calibration_data (id INT, algorithm VARCHAR(20), precision DECIMAL(3,2), recall DECIMAL(3,2)); INSERT INTO calibration_data (id, algorithm, precision, recall) VALUES (1, 'Deep Learning', 0.8, 0.7);

INSERT INTO calibration_data (algorithm, precision, recall) VALUES ('Deep Learning', 0.8, 0.7);


Question: What is the total number of volunteers in organizations that have implemented healthcare projects in Asia since 2018?

CREATE TABLE organizations (id INT, name TEXT, region TEXT); CREATE TABLE projects (id INT, organization_id INT, project_name TEXT, start_date DATE); INSERT INTO organizations (id, name, region) VALUES (1, 'Aid Africa', 'Africa'), (2, 'Asian Aid', 'Asia'), (3, 'Healthcare Hope', 'Asia'); INSERT INTO projects (id, organization_id, project_name, start_date) VALUES (1, 2, 'Healthcare Initiative', '2018-04-01'), (2, 2, 'Education Program', '2017-08-15'), (3, 3, 'Disaster Relief', '2019-12-25');

SELECT COUNT(DISTINCT o.id) FROM organizations o INNER JOIN projects p ON o.id = p.organization_id WHERE o.region = 'Asia' AND p.project_name LIKE '%healthcare%' AND p.start_date >= '2018-01-01';


Question: Generate PostgreSQL SQL for: Which Original title has a Year of 1983, and a Country of italy?

CREATE TABLE table_name_78 (original_title VARCHAR, year VARCHAR, country VARCHAR)

SELECT original_title FROM table_name_78 WHERE year = 1983 AND country = 'italy';


Question: Generate PostgreSQL SQL for: What country has 50 supermarkets?

CREATE TABLE table_name_19 (country VARCHAR, supermarkets VARCHAR)

SELECT country FROM table_name_19 WHERE supermarkets = '50';


Question: Generate PostgreSQL SQL for: Show the name and phone for customers with a mailshot with outcome code 'No Response'.

CREATE TABLE customers (customer_name VARCHAR, customer_phone VARCHAR, customer_id VARCHAR); CREATE TABLE mailshot_customers (customer_id VARCHAR, outcome_code VARCHAR)

SELECT T1.customer_name, T1.customer_phone FROM customers AS T1 JOIN mailshot_customers AS T2 ON T1.customer_id = T2.customer_id WHERE T2.outcome_code = 'No Response';


Question: List all news stories from the 'news_stories' table that have a corresponding entry in the 'ethics_violations' table.

CREATE TABLE news_stories (story_id INT, title VARCHAR(100), description TEXT, reporter_id INT, publish_date DATE); CREATE TABLE ethics_violations (violation_id INT, story_id INT, description TEXT, violation_date DATE);

SELECT news_stories.title FROM news_stories INNER JOIN ethics_violations ON news_stories.story_id = ethics_violations.story_id;


Question: What is the average R&D cost for drugs approved after 2018?

CREATE TABLE r_and_d_expenditures (drug_name VARCHAR(255), r_and_d_cost FLOAT, year INT); INSERT INTO r_and_d_expenditures (drug_name, r_and_d_cost, year) VALUES ('DrugD', 7000000.00, 2019);

SELECT AVG(r_and_d_cost) as avg_r_and_d_cost FROM r_and_d_expenditures e JOIN drug_approvals a ON e.drug_name = a.drug_name WHERE a.approval_date > '2018-12-31';


Question: PostgreSQL Queries: show example 31.

SELECT a + b AS sum, c FROM table1 ORDER BY sum + c; -- wrong;

Explanation: Example from PostgreSQL documentation on Queries.


Question: Generate PostgreSQL SQL for: What was the score of united states player wally armstrong when he had a To par of +1

CREATE TABLE table_name_8 (score VARCHAR, player VARCHAR, country VARCHAR, to_par VARCHAR)

SELECT score FROM table_name_8 WHERE country = 'united states' AND to_par = '+1' AND player = 'wally armstrong';


Question: Generate PostgreSQL SQL for: What is the name of Season #15?

CREATE TABLE table_12564633_1 (title VARCHAR, season__number VARCHAR)

SELECT title FROM table_12564633_1 WHERE season__number = 15;


Question: What was the average energy efficiency rating of appliances sold in Indonesia and Malaysia in 2021?

CREATE TABLE appliance_efficiency (id INT, country VARCHAR(255), year INT, efficiency_rating INT); INSERT INTO appliance_efficiency (id, country, year, efficiency_rating) VALUES (1, 'Indonesia', 2021, 4), (2, 'Malaysia', 2021, 5);

SELECT AVG(efficiency_rating) FROM appliance_efficiency WHERE country IN ('Indonesia', 'Malaysia') AND year = 2021;


Question: What is the maximum number of likes on posts from users aged 18-24, in the 'North America' region, in the past month?

CREATE TABLE users (id INT, age INT, country TEXT, posts TEXT);

SELECT MAX(likes) FROM (SELECT content, MAX(likes) AS likes FROM posts JOIN users ON posts.id = users.id WHERE users.age BETWEEN 18 AND 24 AND users.country IN (SELECT country FROM countries WHERE region = 'North America') AND posts.timestamp BETWEEN DATE_SUB(NOW(), INTERVAL 1 MONTH) AND NOW() GROUP BY content) AS subquery;


Question: Generate PostgreSQL SQL for: Name the location for chattahoochee technical college

CREATE TABLE table_16734640_1 (location VARCHAR, institution VARCHAR)

SELECT location FROM table_16734640_1 WHERE institution = 'Chattahoochee Technical College';


Question: Generate PostgreSQL SQL for: what is the type of vehicle driven by mark higgins

CREATE TABLE table_28046929_2 (car VARCHAR, driver VARCHAR)

SELECT car FROM table_28046929_2 WHERE driver = 'Mark Higgins';


Question: Generate PostgreSQL SQL for: What Tournament has a Partner of tom gorman?

CREATE TABLE table_name_65 (tournament VARCHAR, partner VARCHAR)

SELECT tournament FROM table_name_65 WHERE partner = 'tom gorman';


Question: What is the minimum donation amount in the 'donors' table?

CREATE TABLE donors (id INT, name TEXT, age INT, donation FLOAT); INSERT INTO donors (id, name, age, donation) VALUES (1, 'John Doe', 35, 500.00); INSERT INTO donors (id, name, age, donation) VALUES (2, 'Jane Smith', 45, 750.00); INSERT INTO donors (id, name, age, donation) VALUES (3, 'Bob Johnson', 25, 600.00);


Question: What is the percentage change in sales of each product category in the Asia-Pacific region from 2021 to 2022?

CREATE TABLE sales_data_5 (sale_id INT, product_category VARCHAR(255), region VARCHAR(255), sale_quantity INT, sale_year INT);

SELECT a.product_category, ((a.sale_quantity - b.sale_quantity) * 100.0 / b.sale_quantity) AS sales_percentage_change FROM sales_data_5 a JOIN sales_data_5 b ON a.product_category = b.product_category AND a.region = b.region AND a.sale_year = b.sale_year + 1 WHERE a.region LIKE 'Asia-Pacific%' AND b.sale_year = 2021 GROUP BY a.product_category, a.sale_quantity, b.sale_quantity;


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

CREATE OPERATOR < (
	PROCEDURE = isnlt,
	LEFTARG = ean13,
	RIGHTARG = upc,
	COMMUTATOR = >,
	NEGATOR = >=,
	RESTRICT = scalarltsel,
	JOIN = scalarltjoinsel);

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


Question: Generate PostgreSQL SQL for: What is the number of gold when the silver is 1, bronze is 1, and the nation is Austria?

CREATE TABLE table_name_4 (gold VARCHAR, nation VARCHAR, silver VARCHAR, bronze VARCHAR)

SELECT COUNT(gold) FROM table_name_4 WHERE silver = 1 AND bronze = 1 AND nation = 'austria';


Question: PostgreSQL regression test 'subselect': Write the SELECT query (example 66).

SELECT * FROM foo WHERE id IN
    (SELECT id2 FROM (SELECT id1, id2 FROM bar UNION
                      SELECT id1, id2 FROM bar) AS s);

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

SELECT count(*) FROM (SELECT * FROM foo WHERE id IN
    (SELECT id2 FROM (SELECT id1, id2 FROM bar UNION
                      SELECT id1, id2 FROM bar) AS s)) AS _sub;


Question: Generate PostgreSQL SQL for: What is the upstream for the 100 mbps downstream?

CREATE TABLE table_name_82 (upstream VARCHAR, downstream VARCHAR)

SELECT upstream FROM table_name_82 WHERE downstream = '100 mbps';


Question: What is the most recent mission for each astronaut, partitioned by gender?

CREATE TABLE Astronauts (id INT, name VARCHAR(50), age INT, gender VARCHAR(10), mission_id INT); CREATE TABLE Missions (id INT, name VARCHAR(50), launch_site VARCHAR(50), launch_date DATE);

SELECT a.name, m.name as mission_name, m.launch_date FROM Astronauts a JOIN Missions m ON a.mission_id = m.id JOIN (SELECT mission_id, gender, MAX(launch_date) AS MaxDate FROM Astronauts GROUP BY mission_id, gender) AS MaxDates ON a.mission_id = MaxDates.mission_id AND a.gender = MaxDates.gender AND m.launch_date = MaxDates.MaxDate ORDER BY a.gender, m.launch_date DESC;


Question: How many users have achieved their daily step goal for the past week, and what is the average age of these users?

CREATE TABLE Users (ID INT PRIMARY KEY, Age INT, DailySteps INT, Date DATE);

SELECT AVG(Age), COUNT(*) FROM Users WHERE DailySteps >= (SELECT AVG(DailySteps) FROM Users WHERE Date = (SELECT MAX(Date) FROM Users)) AND Date >= DATEADD(week, -1, GETDATE());


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

CREATE PUBLICATION testpub_forunloggedtbl FOR TABLE testpub_unloggedtbl;

Explanation: DDL from PostgreSQL core regression test for Publication.


Question: What is the maximum number of community engagement events held in a week?

CREATE TABLE Weekly_Community_Engagement (id INT, week_start_date DATE, num_events INT); INSERT INTO Weekly_Community_Engagement (id, week_start_date, num_events) VALUES (1, '2022-02-01', 10), (2, '2022-02-08', 12), (3, '2022-02-15', 15), (4, '2022-02-22', 18), (5, '2022-03-01', 20);

SELECT MAX(num_events) FROM Weekly_Community_Engagement;


Question: Get the names of all players who have played a game designed by a designer from 'Europe'

CREATE TABLE Players_Games (player_id INT, game_id INT); CREATE TABLE Games (id INT, name VARCHAR(50), designer VARCHAR(50), design_region VARCHAR(20)); INSERT INTO Players_Games (player_id, game_id) VALUES (1, 1), (2, 2), (3, 3); INSERT INTO Games (id, name, designer, design_region) VALUES (1, 'Beat Saber', 'Jan Kozlovsky', 'Europe'), (2, 'Job Simulator', 'Alex Schwartz', 'USA'), (3, 'Superhot VR', 'Tomasz Kaczmarczyk', 'Europe');

SELECT Players.name FROM Players_Games JOIN Players ON Players_Games.player_id = Players.id JOIN Games ON Players_Games.game_id = Games.id WHERE Games.design_region = 'Europe';


Question: Generate PostgreSQL SQL for: What is the scored figure when the result is 40-22?

CREATE TABLE table_name_94 (scored INTEGER, result VARCHAR)

SELECT SUM(scored) FROM table_name_94 WHERE result = '40-22';


Question: What is the total revenue for all jazz albums sold on the 'streaming' platform?

CREATE TABLE artists (id INT, name TEXT, genre TEXT); CREATE TABLE albums (id INT, title TEXT, artist_id INT, platform TEXT); CREATE TABLE sales (id INT, album_id INT, quantity INT, revenue DECIMAL); CREATE VIEW jazz_albums AS SELECT a.id, a.title, a.artist_id, a.platform FROM albums a JOIN artists ar ON a.artist_id = ar.id WHERE ar.genre = 'jazz'; CREATE VIEW jazz_sales AS SELECT s.id, sa.album_id, s.quantity, s.revenue FROM sales s JOIN jazz_albums ja ON s.album_id = ja.id;

SELECT SUM(revenue) FROM jazz_sales WHERE platform = 'streaming';


Question: Generate PostgreSQL SQL for: What Social Democratic has a Democratic and Social Centre of 10.0% 22 seats?

CREATE TABLE table_name_33 (social_democratic VARCHAR, democratic_and_social_centre VARCHAR)

SELECT social_democratic FROM table_name_33 WHERE democratic_and_social_centre = '10.0% 22 seats';


Question: Generate PostgreSQL SQL for: What was Craig Stadler's lowest score for United states?

CREATE TABLE table_name_35 (score INTEGER, country VARCHAR, player VARCHAR)

SELECT MIN(score) FROM table_name_35 WHERE country = 'united states' AND player = 'craig stadler';


Question: Generate PostgreSQL SQL for: How many games did they play on january 7?

CREATE TABLE table_27734286_7 (high_points VARCHAR, date VARCHAR)

SELECT COUNT(high_points) FROM table_27734286_7 WHERE date = 'January 7';


Question: Generate PostgreSQL SQL for: When Team 1 is Aalborg BK, what is the 1st Leg?

CREATE TABLE table_name_53 (team_1 VARCHAR)

SELECT 1 AS st_leg FROM table_name_53 WHERE team_1 = 'aalborg bk';


Question: Generate PostgreSQL SQL for: What are the male Bounder books?

CREATE TABLE table_name_23 (books VARCHAR, gender VARCHAR, animal_name VARCHAR)

SELECT books FROM table_name_23 WHERE gender = 'male' AND animal_name = 'bounder';


Question: Generate PostgreSQL SQL for: When 6 is the rank what is the time for Tuesday August 25th?

CREATE TABLE table_23465864_3 (tues_25_aug VARCHAR, rank VARCHAR)

SELECT tues_25_aug FROM table_23465864_3 WHERE rank = 6;


Question: What is the total number of marine species researched and their respective researchers?

CREATE TABLE MarineSpecies (id INT PRIMARY KEY, species VARCHAR(255), researcher VARCHAR(255));

SELECT species, researcher, COUNT(*) as total FROM MarineSpecies GROUP BY species, researcher;


Question: Show biosensor technology development data for optical sensors from the biosensor_development table

CREATE TABLE biosensor_development (id INT, sensor_type VARCHAR(50), data TEXT, date DATE); INSERT INTO biosensor_development (id, sensor_type, data, date) VALUES (1, 'optical', 'Sensor data 1', '2022-01-01'); INSERT INTO biosensor_development (id, sensor_type, data, date) VALUES (2, 'electrochemical', 'Sensor data 2', '2022-02-01');

SELECT * FROM biosensor_development WHERE sensor_type = 'optical';


Question: Compare labor productivity and accident rates in Mexican mining operations between 2017 and 2019.

CREATE TABLE mx_mine_productivity (year INT, productivity FLOAT); INSERT INTO mx_mine_productivity (year, productivity) VALUES (2017, 1.7), (2018, 1.9), (2019, 2.1); CREATE TABLE mx_mine_safety (year INT, accident_rate FLOAT); INSERT INTO mx_mine_safety (year, accident_rate) VALUES (2017, 0.02), (2018, 0.018), (2019, 0.016);

SELECT mx_mine_productivity.year, mx_mine_productivity.productivity, mx_mine_safety.accident_rate FROM mx_mine_productivity INNER JOIN mx_mine_safety ON mx_mine_productivity.year = mx_mine_safety.year WHERE mx_mine_productivity.year BETWEEN 2017 AND 2019;


Question: What is the total number of properties in sustainable urban areas?

CREATE TABLE sustainable_urban (area_id INT, property_id INT); INSERT INTO sustainable_urban (area_id, property_id) VALUES (1, 101), (1, 102), (1, 103), (2, 201), (2, 202), (3, 301);

SELECT COUNT(DISTINCT property_id) FROM sustainable_urban;


Question: Which community health workers have the most experience?

CREATE TABLE community_health_workers (id INT, name VARCHAR(50), race VARCHAR(50), ethnicity VARCHAR(50), years_of_experience INT); INSERT INTO community_health_workers (id, name, race, ethnicity, years_of_experience) VALUES (1, 'John Doe', 'White', 'Not Hispanic or Latino', 5), (2, 'Jane Smith', 'Black or African American', 'Not Hispanic or Latino', 10);

SELECT name, years_of_experience, RANK() OVER (ORDER BY years_of_experience DESC) as rank FROM community_health_workers;


Question: What is the policy type and effective date of policies with a risk score less than 700 and that have a claim in 2021?

CREATE TABLE Policy (PolicyID int, PolicyType varchar(50), EffectiveDate date, RiskScore int); CREATE TABLE Claim (ClaimID int, PolicyID int, ClaimDate date, ClaimAmount int, State varchar(50)); INSERT INTO Policy (PolicyID, PolicyType, EffectiveDate, RiskScore) VALUES (1, 'Auto', '2020-01-01', 700), (2, 'Home', '2019-05-05', 900), (3, 'Life', '2021-08-01', 850); INSERT INTO Claim (ClaimID, PolicyID, ClaimDate, ClaimAmount, State) VALUES (1, 1, '2020-03-15', 2000, 'Texas'), (2, 2, '2019-12-27', 3000, 'California'), (3, 3, '2021-01-05', 1500, 'Texas');

SELECT Policy.PolicyType, Policy.EffectiveDate FROM Policy INNER JOIN Claim ON Policy.PolicyID = Claim.PolicyID WHERE Policy.RiskScore < 700 AND Claim.ClaimDate BETWEEN '2021-01-01' AND '2021-12-31';


Question: Generate PostgreSQL SQL for: What was the last round the team drafted?

CREATE TABLE table_14999879_2 (round INTEGER)

SELECT MAX(round) FROM table_14999879_2;


Question: Write the DML statement from PostgreSQL regression test 'multirangetypes' (example 387).

insert into test_multirange_gist select int4multirange(int4range(g, g+10),int4range(g+20, g+30),int4range(g+40, g+50)) from generate_series(1,2000) g;

Explanation: DML from PostgreSQL core regression test for Multirangetypes.


Question: Generate PostgreSQL SQL for: Which claimant's rank is 200?

CREATE TABLE table_name_7 (claimant VARCHAR, rank VARCHAR)

SELECT claimant FROM table_name_7 WHERE rank = 200;


Question: What is the average obesity rate in Sydney, Australia in 2020?

CREATE TABLE ObesityRates (ID INT, Rate FLOAT, City VARCHAR(50), Year INT); INSERT INTO ObesityRates (ID, Rate, City, Year) VALUES (1, 25.3, 'Sydney', 2020); INSERT INTO ObesityRates (ID, Rate, City, Year) VALUES (2, 27.1, 'Sydney', 2020);

SELECT AVG(Rate) FROM ObesityRates WHERE City = 'Sydney' AND Year = 2020;


Question: What is the total number of public transportation users in Sydney?

CREATE TABLE public_transportation (id INT, users INT, city VARCHAR(20)); INSERT INTO public_transportation (id, users, city) VALUES (1, 200000, 'Sydney');

SELECT SUM(users) FROM public_transportation WHERE city = 'Sydney';


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

SELECT * FROM test_float4 WHERE i<='NaN'::float8 ORDER BY i;


Question: What is the total landfill capacity for regions with a population density above 5000 people per square kilometer?

CREATE TABLE region (name TEXT, population INT, area FLOAT, landfill_capacity FLOAT); INSERT INTO region (name, population, area, landfill_capacity) VALUES ('Region A', 500000, 100, 600), ('Region B', 600000, 120, 800), ('Region C', 400000, 80, 500);

SELECT SUM(landfill_capacity) FROM region WHERE population/area > 5000;


Question: Generate PostgreSQL SQL for: What is the name of the subject who ran in the general election for Queen Anne's County State's Attorney?

CREATE TABLE table_name_63 (subject VARCHAR, election VARCHAR, office VARCHAR)

SELECT subject FROM table_name_63 WHERE election = 'general' AND office = 'queen anne's county state's attorney';


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

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


Question: How many space missions were led by astronauts from the UK?

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', 'James Smith', 'UK', 150), ('Mars Exploration', 'Oliver Lee', 'UK', 250);

SELECT COUNT(*) FROM SpaceMissionRecords WHERE country = 'UK';


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

UPDATE trunc_stats_test1 SET id = id + 100;

Explanation: DML from PostgreSQL core regression test for Stats.


Question: Generate PostgreSQL SQL for: what are all the result for New York 7 district

CREATE TABLE table_1341395_33 (result VARCHAR, district VARCHAR)

SELECT result FROM table_1341395_33 WHERE district = 'New York 7';


Question: Find the number of chemical products produced by each manufacturer and the total safety protocol number for each manufacturer.

CREATE TABLE manufacturer_products (manufacturer INT, product INT, safety_protocol INT); INSERT INTO manufacturer_products (manufacturer, product, safety_protocol) VALUES (1001, 1, 650), (1002, 2, 300), (1003, 3, 700), (1001, 4, 800), (1002, 5, 900);

SELECT manufacturer, COUNT(DISTINCT product) as num_products, SUM(safety_protocol) as total_safety_protocol FROM manufacturer_products GROUP BY manufacturer;


Question: Delete records from the 'oil_platforms' table where the platform_name = 'Bering Sea Rig 1'

CREATE TABLE oil_platforms (platform_id INT PRIMARY KEY, platform_name VARCHAR(255), water_depth_ft INT, operational_status VARCHAR(50));

DELETE FROM oil_platforms WHERE platform_name = 'Bering Sea Rig 1';


Question: Display the AI safety incidents in Asia with costs greater than $6000.

CREATE TABLE ai_safety_incidents (incident_id INTEGER, incident_cost FLOAT, region TEXT); INSERT INTO ai_safety_incidents (incident_id, incident_cost, region) VALUES (11, 6500, 'Asia'), (12, 5000, 'Asia'), (13, 7000, 'Europe');

SELECT incident_id, incident_cost FROM ai_safety_incidents WHERE region = 'Asia' AND incident_cost > 6000;


Question: Generate PostgreSQL SQL for: What is the Canada singles in 1979 with a US A.C. of 24?

CREATE TABLE table_name_75 (canada_singles VARCHAR, year VARCHAR, us_ac VARCHAR)

SELECT canada_singles FROM table_name_75 WHERE year = 1979 AND us_ac = '24';


Question: Generate PostgreSQL SQL for: Who was the opponent in week 3?

CREATE TABLE table_name_34 (opponent VARCHAR, week VARCHAR)

SELECT opponent FROM table_name_34 WHERE week = 3;


Question: What is the total number of visitors by age group for all art exhibitions?

CREATE TABLE art_exhibitions (exhibition_id INT, exhibition_name VARCHAR(50), visitor_count INT, age_group VARCHAR(20));

SELECT age_group, SUM(visitor_count) as total_visitors FROM art_exhibitions GROUP BY age_group;


Question: What is the total quantity of gold extracted by each company?

CREATE TABLE company (id INT, name VARCHAR(50));CREATE TABLE extraction (company_id INT, mineral VARCHAR(10), quantity INT); INSERT INTO company (id, name) VALUES (1, 'ABC Mining'), (2, 'XYZ Corp'); INSERT INTO extraction (company_id, mineral, quantity) VALUES (1, 'gold', 500), (1, 'silver', 300), (2, 'gold', 800), (2, 'copper', 700);

SELECT e.company_id, c.name, SUM(e.quantity) AS total_gold_quantity FROM extraction e JOIN company c ON e.company_id = c.id WHERE e.mineral = 'gold' GROUP BY e.company_id, c.name;


Question: What is the total number of heritage sites in the Oceania region?

CREATE TABLE HeritageSites (SiteID INT, SiteName VARCHAR(100), Location VARCHAR(100), Visits INT); INSERT INTO HeritageSites (SiteID, SiteName, Location, Visits) VALUES (1, 'Sydney Opera House', 'Australia', 8000000);

SELECT COUNT(*) FROM HeritageSites WHERE Location LIKE 'Oceania%';


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

INSERT INTO num_exp_div VALUES (8,0,'NaN');

Explanation: DML from PostgreSQL core regression test for Numeric.


Question: What is the total waste quantity generated and the total number of circular economy initiatives, for each location and material, for the year 2023?

CREATE TABLE WasteGeneration (Date date, Location text, Material text, Quantity integer);CREATE TABLE CircularEconomyInitiatives (Location text, Initiative text, StartDate date);

SELECT wg.Location, wg.Material, SUM(wg.Quantity) as TotalWasteQuantity, COUNT(DISTINCT cei.Initiative) as NumberOfInitiatives FROM WasteGeneration wg LEFT JOIN CircularEconomyInitiatives cei ON wg.Location = cei.Location WHERE wg.Date >= '2023-01-01' AND wg.Date < '2024-01-01' GROUP BY wg.Location, wg.Material;


Question: Show the number of drought impacts for each severity

CREATE TABLE drought_impact (location VARCHAR(255), year INT, severity VARCHAR(255));

SELECT severity, COUNT(*) as num_impacts FROM drought_impact GROUP BY severity;


Question: How many art pieces were created by artists from Asia in the 'painting' medium?

CREATE TABLE art_pieces (id INT, title TEXT, artist_name TEXT, medium TEXT, region TEXT); INSERT INTO art_pieces (id, title, artist_name, medium, region) VALUES (1, 'Mount Fuji', 'Hokusai', 'painting', 'Asia');

SELECT COUNT(*) FROM art_pieces WHERE medium = 'painting' AND region = 'Asia';


Question: List all financial institutions offering Shariah-compliant loans in Asia within the last 2 years.

CREATE TABLE financial_institutions (id INT, name TEXT, location TEXT, last_shariah_activity DATE);

SELECT name FROM financial_institutions WHERE location LIKE 'Asia%' AND last_shariah_activity BETWEEN DATE_SUB(CURRENT_DATE, INTERVAL 2 YEAR) AND CURRENT_DATE AND offering_shariah_loans = TRUE;


Question: Generate PostgreSQL SQL for: What Player has a To par of +1 and a Score of 73-71-71=217?

CREATE TABLE table_name_24 (player VARCHAR, to_par VARCHAR, score VARCHAR)

SELECT player FROM table_name_24 WHERE to_par = '+1' AND score = 73 - 71 - 71 = 217;


Question: Show the number of unique vehicle makes and models in the 'vehicle_info' table, grouped by 'vehicle_type'.

CREATE TABLE vehicle_info (id INT, vehicle_make VARCHAR, vehicle_model VARCHAR, vehicle_type VARCHAR);

SELECT vehicle_type, COUNT(DISTINCT CONCAT(vehicle_make, '_', vehicle_model)) AS unique_vehicles FROM vehicle_info GROUP BY vehicle_type;


Question: What is the total revenue of factories in the renewable energy sector?

CREATE TABLE renewable_energy_factories (id INT, factory_name VARCHAR(100), location VARCHAR(50), revenue DECIMAL(10, 2)); INSERT INTO renewable_energy_factories (id, factory_name, location, revenue) VALUES (1, 'EcoPower', 'USA', 10000000); INSERT INTO renewable_energy_factories (id, factory_name, location, revenue) VALUES (2, 'GreenTech', 'Canada', 15000000);

SELECT SUM(ref.revenue) as total_revenue FROM renewable_energy_factories ref;


Question: Count the number of marine mammals in 'ocean_mammals' table.

CREATE TABLE ocean_mammals (id INT, species VARCHAR(255), population INT);

SELECT COUNT(*) FROM ocean_mammals WHERE species LIKE '%mammal%';


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

SELECT cube_enlarge('(2),(-2)'::cube, 0, 4);

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


Question: What is the total revenue from Spotify streams for Taylor Swift in 2020?

CREATE TABLE SpotifyStreams (artist VARCHAR(255), year INT, revenue FLOAT);

SELECT SUM(revenue) FROM SpotifyStreams WHERE artist = 'Taylor Swift' AND year = 2020;


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

INSERT INTO temporal_mltrng3 (id, valid_at) VALUES ('[1,2)', datemultirange(daterange('2010-01-01', '2020-01-01'))) ON CONFLICT (id, valid_at) DO NOTHING;


Question: Generate PostgreSQL SQL for: What is the former school of the player from Detroit, MI?

CREATE TABLE table_29418619_1 (former_school VARCHAR, hometown VARCHAR)

SELECT former_school FROM table_29418619_1 WHERE hometown = 'Detroit, MI';


Question: Generate PostgreSQL SQL for: What is the average point count for tristan gommendy?

CREATE TABLE table_name_30 (points INTEGER, driver VARCHAR)

SELECT AVG(points) FROM table_name_30 WHERE driver = 'tristan gommendy';


Question: PostgreSQL regression test 'rowtypes': Write the SELECT query (example 21).

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

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


Question: PostgreSQL regression test 'money': Write the SELECT query (example 60).

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

SELECT count(*) FROM (SELECT '9223372036854775807'::money) AS _sub;


Question: List the water consumption for the agriculture industry in California in 2019, 2020, and 2021.

CREATE TABLE industrial_water_usage (state VARCHAR(20), year INT, sector VARCHAR(30), usage FLOAT); INSERT INTO industrial_water_usage (state, year, sector, usage) VALUES ('California', 2019, 'Agriculture', 12345.6), ('California', 2020, 'Agriculture', 23456.7), ('California', 2021, 'Agriculture', 34567.8);

SELECT year, usage FROM industrial_water_usage WHERE state = 'California' AND sector = 'Agriculture';


Question: What is the minimum billing amount for each case in the 'billing' table, grouped by case type?

CREATE TABLE cases (case_id INT, case_type VARCHAR(255)); INSERT INTO cases (case_id, case_type) VALUES (1, 'Criminal'), (2, 'Family'), (3, 'Personal Injury'), (4, 'Criminal'), (5, 'Family'); CREATE TABLE billing (bill_id INT, case_id INT, amount DECIMAL(10,2)); INSERT INTO billing (bill_id, case_id, amount) VALUES (1, 1, 500.00), (2, 1, 750.00), (3, 2, 600.00), (4, 3, 800.00), (5, 3, 900.00), (6, 4, 1000.00), (7, 4, 1200.00), (8, 5, 1500.00);

SELECT cases.case_type, MIN(billing.amount) FROM billing JOIN cases ON billing.case_id = cases.case_id GROUP BY cases.case_type;


Question: Generate PostgreSQL SQL for: Name the date for rio de janeiro

CREATE TABLE table_name_55 (date VARCHAR, city VARCHAR)

SELECT date FROM table_name_55 WHERE city = 'rio de janeiro';


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

CREATE TABLE part_a_1_a_10 PARTITION OF range_parted FOR VALUES FROM ('a', 1) TO ('a', 10);

Explanation: DDL from PostgreSQL core regression test for Update.


Question: Insert a new record into the DefenseContractNegotiations table

CREATE TABLE DefenseContractNegotiations (id INT, company_name VARCHAR(50), contract_value INT, negotiation_date DATE);

INSERT INTO DefenseContractNegotiations (id, company_name, contract_value, negotiation_date) VALUES (1, 'ABC Corp', 1500000, '2021-03-01');


Question: Generate PostgreSQL SQL for: What is the league of the third baseman player before 1973?

CREATE TABLE table_name_79 (league VARCHAR, year VARCHAR, position VARCHAR)

SELECT league FROM table_name_79 WHERE year < 1973 AND position = 'third baseman';


Question: PostgreSQL regression test 'rowsecurity': Write the SELECT query (example 583).

SELECT * FROM rls_view; --fail - permission denied.
EXPLAIN (COSTS OFF) SELECT * FROM rls_view; --fail - permission denied.

-- Query as role that is not the owner of the table or view with permissions.
SET SESSION AUTHORIZATION regress_rls_alice;

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

SELECT count(*) FROM (SELECT * FROM rls_view; --fail - permission denied.
EXPLAIN (COSTS OFF) SELECT * FROM rls_view; --fail - permission denied.

-- Query as role that is not the owner of the table or view with permissions.
SET SESSION AUTHORIZATION regress_rls_alice) AS _sub;


Question: What is the percentage of upcycled clothing items in our inventory in Mexico?

CREATE TABLE clothing_inventory (id INT, item_name VARCHAR(50), item_type VARCHAR(50), upcycled BOOLEAN, country_of_sale VARCHAR(50)); INSERT INTO clothing_inventory (id, item_name, item_type, upcycled, country_of_sale) VALUES (1, 'Upcycled Sweater', 'Clothing', true, 'Mexico'), (2, 'Vintage Dress', 'Clothing', false, 'Mexico'), (3, 'Recycled T-Shirt', 'Clothing', true, 'USA');

SELECT (COUNT(*) FILTER (WHERE upcycled = true) * 100.0 / COUNT(*)) FROM clothing_inventory WHERE country_of_sale = 'Mexico';


Question: Generate PostgreSQL SQL for: Name the circuit for 13 july

CREATE TABLE table_25322130_3 (circuit VARCHAR, date VARCHAR)

SELECT circuit FROM table_25322130_3 WHERE date = '13 July';


Question: Which users have posted the most in the last 3 days?

SELECT user_id, COUNT(*) AS num_posts FROM posts WHERE post_date >= DATEADD(day, -3, GETDATE()) GROUP BY user_id ORDER BY num_posts DESC;


Question: Generate PostgreSQL SQL for: What is the total avge of John Hall, who has less than 63 goals?

CREATE TABLE table_name_25 (avge VARCHAR, name VARCHAR, goals VARCHAR)

SELECT COUNT(avge) FROM table_name_25 WHERE name = 'john hall' AND goals < 63;


Question: What are the unique resilience metrics for 'Transportation' systems?

CREATE TABLE ResilienceMetrics (id INT, system_type TEXT, metric_number TEXT, description TEXT); INSERT INTO ResilienceMetrics (id, system_type, metric_number, description) VALUES (1, 'Power Grid', 'Metric123', 'Power outage duration'); INSERT INTO ResilienceMetrics (id, system_type, metric_number, description) VALUES (2, 'Transportation', 'Metric456', 'Road closure duration'); INSERT INTO ResilienceMetrics (id, system_type, metric_number, description) VALUES (3, 'Power Grid', 'Metric789', 'Restoration time'); INSERT INTO ResilienceMetrics (id, system_type, metric_number, description) VALUES (4, 'Transportation', 'Metric012', 'Bridge closure duration');

SELECT DISTINCT metric_number, description FROM ResilienceMetrics WHERE system_type = 'Transportation';


Question: Alter the 'waste_generation_metrics' table to add a new column 'region'

CREATE TABLE waste_generation_metrics ( country VARCHAR(50), year INT, generation_metric INT);

ALTER TABLE waste_generation_metrics ADD COLUMN region VARCHAR(50);


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

SELECT count(*) AS One FROM TIMESTAMPTZ_TBL WHERE d1 = timestamp with time zone 'tomorrow zulu';

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

SELECT count(*) FROM (SELECT count(*) AS One FROM TIMESTAMPTZ_TBL WHERE d1 = timestamp with time zone 'tomorrow zulu') AS _sub;


Question: What is the minimum salary for employees who identify as Native Hawaiian or Pacific Islander?

CREATE TABLE Employees (EmployeeID INT, EmployeeName VARCHAR(50), Department VARCHAR(50), Salary DECIMAL(10,2), Ethnicity VARCHAR(50)); INSERT INTO Employees (EmployeeID, EmployeeName, Department, Salary, Ethnicity) VALUES (1, 'John Doe', 'IT', 75000.00, 'Asian'), (2, 'Jane Smith', 'IT', 80000.00, 'White'), (3, 'Mike Johnson', 'IT', 78000.00, 'Hispanic'), (4, 'Alice Williams', 'HR', 65000.00, 'Black'), (5, 'Bob Brown', 'Finance', 90000.00, 'Native Hawaiian or Pacific Islander'), (6, 'Charlie Davis', 'Finance', 95000.00, 'Asian');

SELECT MIN(Salary) FROM Employees WHERE Ethnicity = 'Native Hawaiian or Pacific Islander';


Question: Generate PostgreSQL SQL for: What party was Lane Evans?

CREATE TABLE table_1341568_14 (party VARCHAR, incumbent VARCHAR)

SELECT party FROM table_1341568_14 WHERE incumbent = 'Lane Evans';


Question: Generate PostgreSQL SQL for: What is the lowest number of losses for a team with more than 0 wins?

CREATE TABLE table_name_53 (losses INTEGER, wins INTEGER)

SELECT MIN(losses) FROM table_name_53 WHERE wins > 0;


Question: What are the total installed capacities of renewable energy projects for each country, sorted by the highest capacity first?

CREATE TABLE Country (CountryID INT, CountryName VARCHAR(100)); INSERT INTO Country VALUES (1, 'Canada'), (2, 'USA'), (3, 'Mexico'); CREATE TABLE Project (ProjectID INT, ProjectName VARCHAR(100), CountryID INT); INSERT INTO Project VALUES (1, 'Solar Farm A', 1), (2, 'Wind Farm B', 2), (3, 'Hydro Plant C', 3); CREATE TABLE Capacity (CapacityID INT, ProjectID INT, Capacity FLOAT); INSERT INTO Capacity VALUES (1, 1, 100.5), (2, 2, 200.3), (3, 3, 300.1);

SELECT CountryName, SUM(Capacity) AS TotalCapacity FROM Country JOIN Project ON Country.CountryID = Project.CountryID JOIN Capacity ON Project.ProjectID = Capacity.ProjectID GROUP BY CountryName ORDER BY TotalCapacity DESC;


Question: Generate PostgreSQL SQL for: What was the title of the episode that martin worth wrote the story for?

CREATE TABLE table_name_55 (title VARCHAR, story VARCHAR)

SELECT title FROM table_name_55 WHERE story = 'martin worth';


Question: What is the average time between vehicle maintenance events for each maintenance type?

CREATE TABLE VehicleMaintenanceEvents (EventID int, VehicleID int, MaintenanceTypeID int, EventDateTime datetime); INSERT INTO VehicleMaintenanceEvents VALUES (1, 1, 1, '2022-01-01 08:00:00'), (2, 1, 2, '2022-01-01 10:00:00'), (3, 3, 1, '2022-01-01 09:00:00');

SELECT M.MaintenanceType, AVG(DATEDIFF(minute, VME1.EventDateTime, VME2.EventDateTime)) as AvgTimeBetweenEvents FROM VehicleMaintenanceEvents VME1 INNER JOIN VehicleMaintenanceEvents VME2 ON VME1.VehicleID = VME2.VehicleID AND VME1.MaintenanceTypeID = VME2.MaintenanceTypeID AND VME1.EventID < VME2.EventID INNER JOIN MaintenanceTypes M ON VME1.MaintenanceTypeID = M.MaintenanceTypeID GROUP BY M.MaintenanceType;


Question: What is the count of visitors from India who attended exhibitions in 2022?

CREATE TABLE Visitors (visitor_id INT, visitor_name VARCHAR(50), country VARCHAR(50)); INSERT INTO Visitors (visitor_id, visitor_name, country) VALUES (1, 'John Doe', 'USA'), (2, 'Sita Patel', 'India'); CREATE TABLE Exhibitions (exhibition_id INT, exhibition_name VARCHAR(50), exhibition_year INT); INSERT INTO Exhibitions (exhibition_id, exhibition_name, exhibition_year) VALUES (1, 'Art of the 20th Century', 2022); CREATE TABLE Attendance (attendance_id INT, visitor_id INT, exhibition_id INT, attendance_date DATE); INSERT INTO Attendance (attendance_id, visitor_id, exhibition_id, attendance_date) VALUES (1, 1, 1, '2022-06-01'), (2, 2, 1, '2022-07-01');

SELECT COUNT(*) FROM Visitors v JOIN Attendance a ON v.visitor_id = a.visitor_id JOIN Exhibitions e ON a.exhibition_id = e.exhibition_id WHERE v.country = 'India' AND e.exhibition_year = 2022;


Question: How many female and male employees are there in the company?

CREATE TABLE Employees (EmployeeID INT, Name VARCHAR(50), Gender VARCHAR(50)); INSERT INTO Employees (EmployeeID, Name, Gender) VALUES (1, 'John Doe', 'Male'), (2, 'Jane Smith', 'Female'), (3, 'Mike Johnson', 'Male');

SELECT Gender, COUNT(*) FROM Employees GROUP BY Gender;


Question: What is the total number of animal species in the 'animal_species' table grouped by region?

CREATE TABLE animal_species_regions (species_id INT, species_name VARCHAR(50), region VARCHAR(50)); INSERT INTO animal_species_regions (species_id, species_name, region) VALUES (1, 'Deer', 'North'), (2, 'Bear', 'South'), (3, 'Wolf', 'North'), (4, 'Eagle', 'South');

SELECT region, COUNT(*) as total_species_per_region FROM animal_species_regions GROUP BY region;


Question: How many volunteers signed up in H1 and H2 of 2023?

CREATE TABLE VolunteerSignups (VolunteerSignupID INT, VolunteerID INT, SignUpDate DATE); INSERT INTO VolunteerSignups (VolunteerSignupID, VolunteerID, SignUpDate) VALUES (1, 1, '2023-01-05'), (2, 2, '2023-04-10'), (3, 3, '2023-07-20');

SELECT CONCAT('H', FLOOR(MONTH(SignUpDate) / 6)) AS Half, COUNT(*) as VolunteerCount FROM VolunteerSignups WHERE YEAR(SignUpDate) = 2023 GROUP BY Half;


Question: List the number of offshore platforms in each country in the South China Sea

CREATE TABLE offshore_platforms (country VARCHAR(255), region VARCHAR(255), num_platforms INT); INSERT INTO offshore_platforms (country, region, num_platforms) VALUES ('Vietnam', 'South China Sea', 25), ('China', 'South China Sea', 30), ('Malaysia', 'South China Sea', 12);

SELECT country, SUM(num_platforms) FROM offshore_platforms WHERE region = 'South China Sea' GROUP BY country;


Question: How many artifacts were analyzed in 2015?

CREATE TABLE artifact_analysis (id INT, excavation_site_id INT, date DATE); INSERT INTO artifact_analysis (id, excavation_site_id, date) VALUES (1, 1, '2015-01-01'), (2, 1, '2015-02-01');

SELECT COUNT(*) FROM artifact_analysis WHERE YEAR(date) = 2015;


Question: List the organizations that have received donations from donors located in 'California', but have not received donations from donors located in 'New York'.

CREATE TABLE donors (id INT, name TEXT, state TEXT); INSERT INTO donors (id, name, state) VALUES (1, 'John Doe', 'California'); CREATE TABLE donations (id INT, donor_id INT, org_id INT, donation_amount DECIMAL(10,2)); INSERT INTO donations (id, donor_id, org_id, donation_amount) VALUES (1, 1, 1, 100.00);

SELECT organizations.name FROM organizations WHERE organizations.id IN (SELECT donations.org_id FROM donations JOIN donors ON donations.donor_id = donors.id WHERE donors.state = 'California') AND organizations.id NOT IN (SELECT donations.org_id FROM donations JOIN donors ON donations.donor_id = donors.id WHERE donors.state = 'New York');


Question: List the number of offshore drilling platforms in the Arabian Sea as of 2019.

CREATE TABLE arabian_sea_platforms (year INT, region VARCHAR(20), num_platforms INT); INSERT INTO arabian_sea_platforms (year, region, num_platforms) VALUES (2015, 'Arabian Sea', 2500), (2016, 'Arabian Sea', 2600), (2017, 'Arabian Sea', 2700), (2018, 'Arabian Sea', 2800), (2019, 'Arabian Sea', 2900), (2020, 'Arabian Sea', 3000);

SELECT num_platforms FROM arabian_sea_platforms WHERE year = 2019 AND region = 'Arabian Sea';


Question: List all excavation sites and the number of artifacts associated with each site.

CREATE TABLE excavation_sites (id INT, site_name VARCHAR(50), location VARCHAR(50), num_artifacts INT); INSERT INTO excavation_sites (id, site_name, location, num_artifacts) VALUES (1, 'Site A', 'USA', 30), (2, 'Site B', 'Mexico', 45), (3, 'Site C', 'Canada', 25);

SELECT site_name, num_artifacts FROM excavation_sites;


Question: Update the 'OceanFloorMapping' table to correct the depth for the 'Tonga Trench' to 10820 meters

CREATE TABLE OceanFloorMapping (id INT, location VARCHAR(50), depth INT); INSERT INTO OceanFloorMapping (id, location, depth) VALUES (1, 'Mariana Trench', 10000), (2, 'Sunda Trench', 8000), (3, 'Philippine Trench', 6500), (4, 'Kermadec Trench', 10000), (5, 'Tonga Trench', 10800);

UPDATE OceanFloorMapping SET depth = 10820 WHERE location = 'Tonga Trench';


Question: Identify the vehicle models with the highest and lowest safety ratings in the 'safety_test_results' table.

CREATE TABLE safety_test_results (id INT, vehicle_model VARCHAR, safety_rating DECIMAL(3,2));

SELECT vehicle_model, safety_rating, RANK() OVER (PARTITION BY safety_rating ORDER BY safety_rating DESC) as rank FROM safety_test_results WHERE rank = 1 OR rank = (SELECT COUNT(*) FROM safety_test_results WHERE safety_rating = max_safety_rating) ORDER BY safety_rating;


Question: What are the product names and their origins for all clothing items in the inventory?

CREATE TABLE ClothingInventory (product_id INT, product_name TEXT, origin TEXT); INSERT INTO ClothingInventory (product_id, product_name, origin) VALUES (1, 'Organic Cotton T-Shirt', 'India'), (2, 'Hemp Pants', 'China');

SELECT product_name, origin FROM ClothingInventory;


Question: What is the total REE production by mine name for 2020?

CREATE TABLE mines (id INT, name TEXT, location TEXT, annual_production INT); INSERT INTO mines (id, name, location, annual_production) VALUES (1, 'Mine A', 'Country X', 1500), (2, 'Mine B', 'Country Y', 2000), (3, 'Mine C', 'Country Z', 1750);

SELECT name, SUM(annual_production) as total_production FROM mines WHERE YEAR(timestamp) = 2020 GROUP BY name;


Question: Generate PostgreSQL SQL for: What date was the away team from Adelaide?

CREATE TABLE table_name_37 (date VARCHAR, away_team VARCHAR)

SELECT date FROM table_name_37 WHERE away_team = 'adelaide';


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

SELECT sum(unique1) over (order by four range between 2::int8 preceding and 1::int2 preceding 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 (order by four range between 2::int8 preceding and 1::int2 preceding exclude no others),
	unique1, four
FROM tenk1 WHERE unique1 < 10) AS _sub;


Question: Identify the number of mental health parity violations by region?

CREATE TABLE mental_health_parity_violations (id INT, region VARCHAR(50), violation_count INT); INSERT INTO mental_health_parity_violations (id, region, violation_count) VALUES (1, 'Northeast', 10), (2, 'Southeast', 5), (3, 'Midwest', 15);

SELECT region, SUM(violation_count) as total_violations FROM mental_health_parity_violations GROUP BY region;


Question: What is the total installed renewable energy capacity for the 'renewable_energy_capacity' table by country?

CREATE TABLE renewable_energy_capacity (country VARCHAR(50), wind_capacity NUMERIC(5,2), solar_capacity NUMERIC(5,2)); INSERT INTO renewable_energy_capacity (country, wind_capacity, solar_capacity) VALUES ('Germany', 30.0, 20.0), ('France', 40.0, 30.0), ('Canada', 50.0, 40.0);

SELECT SUM(wind_capacity + solar_capacity) FROM renewable_energy_capacity;


Question: How many shipwrecks have been recorded in the Caribbean Sea?

CREATE TABLE caribbean_sea (id INT, year INT, shipwreck TEXT); INSERT INTO caribbean_sea (id, year, shipwreck) VALUES (1, 1650, 'Santa Maria');

SELECT COUNT(shipwreck) FROM caribbean_sea;


Question: Generate PostgreSQL SQL for: What is the clock multiplier if the voltage range (v) is 3.3 - 3.6; input clock (mhz) is 33 x 3 / 50 x 2; and part number is a80486dx4-100?

CREATE TABLE table_15261_1 (clock_multiplier VARCHAR, part_number VARCHAR, voltage_range__v_ VARCHAR, input_clock__mhz_ VARCHAR)

SELECT clock_multiplier FROM table_15261_1 WHERE voltage_range__v_ = '3.3 - 3.6' AND input_clock__mhz_ = '33 X 3 / 50 X 2' AND part_number = 'A80486DX4-100';


Question: What is the total number of sensors in the Antarctic?

CREATE TABLE sensors ( id INT PRIMARY KEY, location VARCHAR(255), type VARCHAR(255), value DECIMAL(10,2), timestamp TIMESTAMP); INSERT INTO sensors (id, location, type, value, timestamp) VALUES (1, 'Arctic', 'Temperature', 25.5, '2022-01-01 12:00:00'); INSERT INTO sensors (id, location, type, value, timestamp) VALUES (2, 'Antarctic', 'Humidity', 60.0, '2022-01-01 12:00:00');

SELECT COUNT(*) FROM sensors WHERE location = 'Antarctic';


Question: Generate PostgreSQL SQL for: How many years have HMOs been 27% and POS plans 18%?

CREATE TABLE table_name_54 (year VARCHAR, hmos VARCHAR, pos_plans VARCHAR)

SELECT COUNT(year) FROM table_name_54 WHERE hmos = '27%' AND pos_plans = '18%';


Question: Generate PostgreSQL SQL for: What is the lowest number of f/laps in the 5th position?

CREATE TABLE table_name_17 (f_laps INTEGER, position VARCHAR)

SELECT MIN(f_laps) FROM table_name_17 WHERE position = '5th';


Question: Generate PostgreSQL SQL for: What is the sanskrit word if the transcription is wan athit?

CREATE TABLE table_180802_3 (sanskrit_word VARCHAR, transcription VARCHAR)

SELECT sanskrit_word FROM table_180802_3 WHERE transcription = 'wan athit';


Question: Generate PostgreSQL SQL for: Find the number of distinct type of pets.

SELECT COUNT(DISTINCT pettype) FROM pets;


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

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

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


Question: Generate PostgreSQL SQL for: WHAT PERCENTAGE OF GLOBAL TOTAL EMISSIONS DID INDIA PRODUCE?

CREATE TABLE table_11251601_2 (percentage_of_global_total VARCHAR, country VARCHAR)

SELECT percentage_of_global_total FROM table_11251601_2 WHERE country = 'India';


Question: Generate PostgreSQL SQL for: What are the names of poker players?

CREATE TABLE poker_player (People_ID VARCHAR); CREATE TABLE people (Name VARCHAR, People_ID VARCHAR)

SELECT T1.Name FROM people AS T1 JOIN poker_player AS T2 ON T1.People_ID = T2.People_ID;


Question: Delete a record with Id 123 from the "Vessels" table

CREATE TABLE Vessels (Id INT PRIMARY KEY, Name VARCHAR(100), Type VARCHAR(50), Year INT);


Question: Generate PostgreSQL SQL for: What record has the score 111-89?

CREATE TABLE table_name_75 (record VARCHAR, score VARCHAR)

SELECT record FROM table_name_75 WHERE score = '111-89';


Question: Generate PostgreSQL SQL for: What is the H/A on 5 August 1990?

CREATE TABLE table_name_46 (h___a VARCHAR, date VARCHAR)

SELECT h___a FROM table_name_46 WHERE date = '5 august 1990';


Question: What is the difference in total points scored between the first and second halves of each NBA game?

CREATE TABLE games (game_id INT, first_half_points INT, second_half_points INT);

SELECT game_id, first_half_points - second_half_points AS point_difference FROM games;


Question: Generate PostgreSQL SQL for: What is Dave Rummells's to par?

CREATE TABLE table_name_22 (to_par VARCHAR, player VARCHAR)

SELECT to_par FROM table_name_22 WHERE player = 'dave rummells';


Question: Delete records of recycling rates for 2019 in California.

CREATE TABLE recycling_rates(year INT, state VARCHAR(255), plastic_recycling FLOAT, paper_recycling FLOAT, glass_recycling FLOAT); INSERT INTO recycling_rates VALUES (2019, 'California', 0.6, 0.7, 0.5), (2020, 'California', 0.7, 0.8, 0.6);

DELETE FROM recycling_rates WHERE year = 2019 AND state = 'California';


Question: What is the average age of volunteers with engineering expertise?

CREATE TABLE volunteers (volunteer_id INTEGER, name TEXT, age INTEGER, expertise TEXT); INSERT INTO volunteers (volunteer_id, name, age, expertise) VALUES (1, 'Alice', 25, 'Medical'), (2, 'Bob', 30, 'Engineering'), (3, 'Charlie', 35, 'Medical');

SELECT AVG(v.age) FROM volunteers v WHERE v.expertise = 'Engineering';


Question: pgTAP test for Ownership (assertion 56).

Explanation: SQL assertion from pgTAP test suite for Ownership.


Question: What is the average market access time for drugs in Africa?

CREATE TABLE market_access (access_id INT, drug_name TEXT, access_time INT, region TEXT); INSERT INTO market_access (access_id, drug_name, access_time, region) VALUES (1, 'DrugI', 365, 'Africa'), (2, 'DrugJ', 420, 'Africa');

SELECT region, AVG(access_time) as avg_access_time FROM market_access WHERE region = 'Africa';


Question: Insert a new record for a company with the name 'LMN Inc.' and an ESG rating of 'A-' into the companies table.

CREATE TABLE companies (id INT, name VARCHAR(50), esg_rating VARCHAR(2)); INSERT INTO companies (id, name, esg_rating) VALUES (1, 'ABC Inc.', 'A'); INSERT INTO companies (id, name, esg_rating) VALUES (2, 'DEF Inc.', 'B'); INSERT INTO companies (id, name, esg_rating) VALUES (3, 'XYZ Inc.', 'C');

INSERT INTO companies (name, esg_rating) VALUES ('LMN Inc.', 'A-');


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

INSERT INTO temporal_mltrng (id, valid_at) VALUES ('[1,2)', datemultirange(daterange('2018-03-03', '2018-04-04')));

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


Question: Generate PostgreSQL SQL for: Which winner has a P stage?

CREATE TABLE table_name_48 (winner VARCHAR, stage VARCHAR)

SELECT winner FROM table_name_48 WHERE stage = 'p';


Question: How many users purchased a monthly pass in the last quarter?

CREATE TABLE user_profiles (user_id INT, user_name VARCHAR(255), pass_type VARCHAR(255), purchase_date DATE); INSERT INTO user_profiles (user_id, user_name, pass_type, purchase_date) VALUES (1, 'Alice', 'Monthly', '2022-03-01'), (2, 'Bob', 'Weekly', '2022-03-02'), (3, 'Charlie', 'Monthly', '2022-01-01');

SELECT COUNT(*) FROM user_profiles WHERE pass_type = 'Monthly' AND purchase_date >= DATE_SUB(CURRENT_DATE, INTERVAL 3 MONTH);


Question: Generate PostgreSQL SQL for: What department has an m.phil (physics) qualification?

CREATE TABLE table_name_25 (department VARCHAR, qualification VARCHAR)

SELECT department FROM table_name_25 WHERE qualification = 'm.phil (physics)';


Question: Generate PostgreSQL SQL for: What is the average number of weeks that the opponent was the Denver Broncos?

CREATE TABLE table_name_78 (week INTEGER, opponent VARCHAR)

SELECT AVG(week) FROM table_name_78 WHERE opponent = 'denver broncos';


Question: Generate PostgreSQL SQL for: What is the average game number that was on october 19?

CREATE TABLE table_name_4 (game INTEGER, october VARCHAR)

SELECT AVG(game) FROM table_name_4 WHERE october = 19;


Question: Which indigenous communities have experienced relocation due to coastal erosion?

CREATE TABLE Relocations (community TEXT, year INT, reason TEXT); INSERT INTO Relocations (community, year, reason) VALUES ('Inuit', 1995, 'Erosion'), ('Inuit', 2005, 'Flooding'), ('Sami', 2010, 'Thawing Permafrost'), ('Gwich’in', 2015, 'Thawing Permafrost'), ('Yupik', 2020, 'Coastal Erosion'), ('Aleut', 2018, 'Coastal Erosion');

SELECT community FROM Relocations WHERE reason = 'Coastal Erosion' GROUP BY community;


Question: Generate PostgreSQL SQL for: What points has 18 for the played and bala rfc as the club?

CREATE TABLE table_name_31 (points_for VARCHAR, played VARCHAR, club VARCHAR)

SELECT points_for FROM table_name_31 WHERE played = '18' AND club = 'bala rfc';


Question: Generate PostgreSQL SQL for: When was the result 0–3?

CREATE TABLE table_name_48 (date VARCHAR, result VARCHAR)

SELECT date FROM table_name_48 WHERE result = '0–3';


Question: Show an example of PostgreSQL ALTER PROCEDURE (example 5).

ALTER PROCEDURE check_password(text) SET search_path = admin, pg_temp;

Explanation: PostgreSQL ALTER PROCEDURE command.


Question: What is the total number of tourists who visited eco-friendly accommodations in Scandinavia and the Caribbean?

CREATE TABLE scandinavia_accommodations (id INT, country TEXT, eco_visitors INT, year INT); INSERT INTO scandinavia_accommodations VALUES (1, 'Norway', 500, 2022), (2, 'Sweden', 600, 2022); CREATE TABLE caribbean_accommodations (id INT, country TEXT, eco_visitors INT, year INT); INSERT INTO caribbean_accommodations VALUES (1, 'Bahamas', 700, 2022), (2, 'Jamaica', 800, 2022);

SELECT SUM(eco_visitors) FROM scandinavia_accommodations WHERE year = 2022 UNION ALL SELECT SUM(eco_visitors) FROM caribbean_accommodations WHERE year = 2022;


Question: Generate PostgreSQL SQL for: What is the Location of the 10th Iteration?

CREATE TABLE table_name_40 (location VARCHAR, iteration VARCHAR)

SELECT location FROM table_name_40 WHERE iteration = '10th';


Question: Which tree species have the highest carbon sequestration rate in the tropical region?

CREATE TABLE tree_carbon_sequestration (tree_id INT, species_id INT, region_id INT, sequestration_rate DECIMAL(5,2)); INSERT INTO tree_carbon_sequestration (tree_id, species_id, region_id, sequestration_rate) VALUES (1, 1, 1, 20.5), (2, 2, 1, 19.3), (3, 3, 2, 25.0), (4, 4, 2, 23.6); CREATE TABLE regions (region_id INT, region_name VARCHAR(100)); INSERT INTO regions (region_id, region_name) VALUES (1, 'Tropical'), (2, 'Temperate'); CREATE TABLE tree_species (species_id INT, species_name VARCHAR(100)); INSERT INTO tree_species (species_id, species_name) VALUES (1, 'Mahogany'), (2, 'Teak'), (3, 'Ebony'), (4, 'Rosewood');

SELECT ts.species_name, tcs.sequestration_rate FROM tree_carbon_sequestration tcs JOIN regions r ON tcs.region_id = r.region_id JOIN tree_species ts ON tcs.species_id = ts.species_id WHERE r.region_name = 'Tropical' ORDER BY tcs.sequestration_rate DESC LIMIT 1;


Question: What is the average age of players in the basketball_teams table?

CREATE TABLE basketball_teams (team_id INT, team_name VARCHAR(100), player_name VARCHAR(100), player_age INT);

SELECT AVG(player_age) FROM basketball_teams;


Question: Generate PostgreSQL SQL for: What party did the re-elected incumbent of the Texas 11 district belong to?

CREATE TABLE table_1342149_43 (party VARCHAR, result VARCHAR, district VARCHAR)

SELECT party FROM table_1342149_43 WHERE result = 'Re-elected' AND district = 'Texas 11';


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

ALTER EXTENSION pgtap ADD FUNCTION os_name();

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


Question: What is the average square footage of LEED-certified buildings in New York City, partitioned by their construction types?

CREATE TABLE leed_buildings (id INT, building_name VARCHAR(50), square_footage FLOAT, construction_type VARCHAR(50), city VARCHAR(50), state VARCHAR(50)); INSERT INTO leed_buildings (id, building_name, square_footage, construction_type, city, state) VALUES (1, 'GreenHQ', 120000, 'Steel', 'New York', 'NY'), (2, 'EcoTower', 200000, 'Concrete', 'New York', 'NY'), (3, 'SustainableSpire', 180000, 'Wood', 'New York', 'NY');

SELECT construction_type, AVG(square_footage) as avg_square_footage FROM leed_buildings WHERE city = 'New York' AND state = 'NY' AND construction_type IN ('Steel', 'Concrete', 'Wood') GROUP BY construction_type;


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

SELECT name FROM srt WHERE name !~~ '%B%' ORDER BY name;

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


Question: Generate PostgreSQL SQL for: Which Away team has a Venue of arden street oval?

CREATE TABLE table_name_32 (away_team VARCHAR, venue VARCHAR)

SELECT away_team FROM table_name_32 WHERE venue = 'arden street oval';


Question: What is the average number of hours volunteered per volunteer in 2021?

CREATE TABLE VolunteerHours (VolunteerID INT, Hours INT, VolunteerDate DATE); INSERT INTO VolunteerHours VALUES (1, 4, '2021-01-01'), (1, 6, '2021-02-01'), (2, 8, '2021-03-01');

SELECT AVG(Hours) FROM VolunteerHours WHERE YEAR(VolunteerDate) = 2021;


Question: Get the total spending on military innovation by each country for the year 2019

CREATE TABLE military_innovation (id INT, weapon_system VARCHAR(255), country VARCHAR(255), year INT);

SELECT country, SUM(year) FROM military_innovation WHERE year = 2019 GROUP BY country;


Question: Delete all records from the 'equipment_inventory' table where the quantity is 0.

CREATE TABLE equipment_inventory (id INT, type VARCHAR(50), quantity INT); INSERT INTO equipment_inventory (id, type, quantity) VALUES (1, 'Drilling Machine', 15); INSERT INTO equipment_inventory (id, type, quantity) VALUES (2, 'Excavator', 8); INSERT INTO equipment_inventory (id, type, quantity) VALUES (3, 'Bulldozer', 5); INSERT INTO equipment_inventory (id, type, quantity) VALUES (4, 'Dump Truck', 0);

DELETE FROM equipment_inventory WHERE quantity = 0;


Question: Generate PostgreSQL SQL for: What type of game was held against France with the results of 3:1?

CREATE TABLE table_name_20 (type_of_game VARCHAR, results¹ VARCHAR, opponent VARCHAR)

SELECT type_of_game FROM table_name_20 WHERE results¹ = '3:1' AND opponent = 'france';


Question: Generate PostgreSQL SQL for: What was the winning score for the tournament played on Jul 14, 1973?

CREATE TABLE table_name_96 (winning_score VARCHAR, date VARCHAR)

SELECT winning_score FROM table_name_96 WHERE date = 'jul 14, 1973';


Question: PostgreSQL regression test 'horology': Write the SELECT query (example 284).

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

SELECT count(*) FROM (SELECT to_timestamp('2011-12-18 11:38 +05:20', 'YYYY-MM-DD HH12:MI TZH:TZM')) AS _sub;


Question: Generate PostgreSQL SQL for: What is the greatest B score when the A score was less than 6.5?

CREATE TABLE table_name_4 (b_score INTEGER, a_score INTEGER)

SELECT MAX(b_score) FROM table_name_4 WHERE a_score < 6.5;


Question: pgTAP test for Privs (assertion 21).

Explanation: SQL assertion from pgTAP test suite for Privs.


Question: Generate PostgreSQL SQL for: Tell me the result for green bay packers

CREATE TABLE table_name_77 (result VARCHAR, opponent VARCHAR)

SELECT result FROM table_name_77 WHERE opponent = 'green bay packers';


Question: Generate PostgreSQL SQL for: What is the location/state of the Launceston race?

CREATE TABLE table_name_60 (location___state VARCHAR, race_title VARCHAR)

SELECT location___state FROM table_name_60 WHERE race_title = 'launceston';


Question: How many visitors identified as BIPOC attended the last three exhibitions at the local museum?

CREATE TABLE museum_visitors (id INT, exhibition_date DATE, is_bipoc BOOLEAN); INSERT INTO museum_visitors (id, exhibition_date, is_bipoc) VALUES (1, '2022-05-01', TRUE), (2, '2022-05-01', FALSE), (3, '2022-05-02', TRUE);

SELECT COUNT(*) FROM (SELECT * FROM museum_visitors WHERE exhibition_date IN ('2022-04-30', '2022-05-01', '2022-05-02') AND is_bipoc = TRUE) AS subquery;


Question: List the names, roles, and years of experience of all male mining engineers.

CREATE TABLE mine_operators (id INT PRIMARY KEY, name VARCHAR(50), role VARCHAR(50), gender VARCHAR(10), years_of_experience INT); INSERT INTO mine_operators (id, name, role, gender, years_of_experience) VALUES (1, 'John Doe', 'Mining Engineer', 'Male', 7), (2, 'Maria', 'Mining Engineer', 'Female', 5);

SELECT name, role, years_of_experience FROM mine_operators WHERE gender = 'Male';


Question: Generate PostgreSQL SQL for: What is the 1.93 that is 2.05 in height?

CREATE TABLE table_name_77 (height VARCHAR)

SELECT 193 FROM table_name_77 WHERE height = 2.05;


Question: Identify AI models with low performance scores and their sectors.

CREATE TABLE ai_models (model_name TEXT, performance_score INTEGER, sector TEXT); INSERT INTO ai_models (model_name, performance_score, sector) VALUES ('Model1', 75, 'Finance'), ('Model2', 85, 'Healthcare'), ('Model3', 60, 'Finance'), ('Model4', 90, 'Healthcare');

SELECT sector, model_name, performance_score FROM ai_models WHERE performance_score < 70;


Question: Generate PostgreSQL SQL for: On what day was the score of 1–6 6–1 3–6 achieved?

CREATE TABLE table_name_12 (date VARCHAR, score VARCHAR)

SELECT date FROM table_name_12 WHERE score = '1–6 6–1 3–6';


Question: Insert data into the archaeologist table

CREATE TABLE Archaeologists (ArchaeologistID INT PRIMARY KEY, FirstName VARCHAR(255), LastName VARCHAR(255), Specialty TEXT, Country VARCHAR(255)); INSERT INTO Archaeologists (ArchaeologistID, FirstName, LastName, Specialty, Country) VALUES (1, 'Howard', 'Carter', 'Egyptology', 'England');


Question: Generate PostgreSQL SQL for: What is the average drawn of the team with a difference of 4 and more than 13 losses?

CREATE TABLE table_name_30 (drawn INTEGER, difference VARCHAR, lost VARCHAR)

SELECT AVG(drawn) FROM table_name_30 WHERE difference = '4' AND lost > 13;


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

SELECT xmlserialize(CONTENT  '<foo><bar><val x="y">42</val></bar></foo>' AS text) = xmlserialize(CONTENT '<foo><bar><val x="y">42</val></bar></foo>' AS text NO INDENT);

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

SELECT count(*) FROM (SELECT xmlserialize(CONTENT  '<foo><bar><val x="y">42</val></bar></foo>' AS text) = xmlserialize(CONTENT '<foo><bar><val x="y">42</val></bar></foo>' AS text NO INDENT)) AS _sub;