Question: What are the names of the 2 most recent marine conservation projects?

CREATE TABLE marine_conservation_projects (project_name TEXT, start_date DATE); INSERT INTO marine_conservation_projects (project_name, start_date) VALUES ('Coral Reef Restoration', '2022-03-01'), ('Seagrass Protection', '2021-09-15'), ('Mangrove Forest Expansion', '2020-05-01');

SELECT project_name FROM marine_conservation_projects ORDER BY start_date DESC LIMIT 2;


Question: What is the average phosphorus concentration (in µg/L) for each species in 2024, ordered by the average value?

CREATE TABLE species_phosphorus (species VARCHAR(255), year INT, avg_phosphorus FLOAT); INSERT INTO species_phosphorus (species, year, avg_phosphorus) VALUES ('Salmon', 2024, 12.0), ('Tilapia', 2024, 7.5), ('Catfish', 2024, 6.0), ('Trout', 2024, 10.5), ('Shrimp', 2024, 14.0), ('Lobster', 2024, 15.0);

SELECT species, AVG(avg_phosphorus) as avg_phosphorus_ug_l FROM species_phosphorus WHERE year = 2024 GROUP BY species ORDER BY avg_phosphorus_ug_l;


Question: Generate PostgreSQL SQL for: What is the represent province for the contestant whose hometown is Woerden?

CREATE TABLE table_27946889_2 (represent_province VARCHAR, hometown VARCHAR)

SELECT represent_province FROM table_27946889_2 WHERE hometown = 'Woerden';


Question: Generate PostgreSQL SQL for: Who had a second qualification time of 1:01.777?

CREATE TABLE table_name_9 (name VARCHAR, qual_2 VARCHAR)

SELECT name FROM table_name_9 WHERE qual_2 = '1:01.777';


Question: pgTAP test for Hastap (assertion 290).

SELECT * FROM check_test(
    hasnt_relation( '__SDFSDFD__', 'lol' ),
    true,
    'hasnt_relation(non-existent schema, tab)',
    'lol',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Hastap.


Question: Generate PostgreSQL SQL for: What is the power at Baguio where the frequency is 102.3mhz?

CREATE TABLE table_name_59 (power__kw_ VARCHAR, frequency VARCHAR, location VARCHAR)

SELECT power__kw_ FROM table_name_59 WHERE frequency = '102.3mhz' AND location = 'baguio';


Question: Generate PostgreSQL SQL for: When 380 g/mi (236 g/km) is the dirty electric grid rocky mountains (denver) what is the u.s national average electric mix?

CREATE TABLE table_24620684_2 (us_national_average_electric_mix VARCHAR, dirty_electric_grid_rocky_mountains__denver_ VARCHAR)

SELECT us_national_average_electric_mix FROM table_24620684_2 WHERE dirty_electric_grid_rocky_mountains__denver_ = '380 g/mi (236 g/km)';


Question: Identify artworks that have been exhibited in both London and Tokyo.

CREATE TABLE Exhibitions (ExhibitionID INT PRIMARY KEY, Title VARCHAR(100), City VARCHAR(100), StartDate DATE, EndDate DATE, ArtWorkID INT, FOREIGN KEY (ArtWorkID) REFERENCES ArtWorks(ArtWorkID)); INSERT INTO Exhibitions (ExhibitionID, Title, City, StartDate, EndDate, ArtWorkID) VALUES (1, 'Artistic Revolutions', 'London', '2020-01-01', '2020-03-31', 1); INSERT INTO Exhibitions (ExhibitionID, Title, City, StartDate, EndDate, ArtWorkID) VALUES (2, 'Artistic Revolutions', 'Tokyo', '2020-04-01', '2020-06-30', 1); CREATE TABLE ArtWorks (ArtWorkID INT PRIMARY KEY, Title VARCHAR(100)); INSERT INTO ArtWorks (ArtWorkID, Title) VALUES (1, 'The Persistence of Memory');

SELECT ArtWorks.Title FROM ArtWorks INNER JOIN Exhibitions ON ArtWorks.ArtWorkID = Exhibitions.ArtWorkID WHERE Exhibitions.City IN ('London', 'Tokyo') GROUP BY ArtWorks.Title HAVING COUNT(DISTINCT Exhibitions.City) = 2;


Question: What is the number of eco-certified accommodations in Tokyo?

CREATE TABLE accommodations (accommodation_id INT, name TEXT, city TEXT, eco_certified INT); INSERT INTO accommodations (accommodation_id, name, city, eco_certified) VALUES (1, 'Eco Lodge A', 'Tokyo', 1), (2, 'Hotel B', 'Tokyo', 0), (3, 'Inn C', 'Tokyo', 1);

SELECT COUNT(*) FROM accommodations WHERE city = 'Tokyo' AND eco_certified = 1;


Question: Generate PostgreSQL SQL for: Find the name of the courses that do not have any prerequisite?

CREATE TABLE prereq (title VARCHAR, course_id VARCHAR); CREATE TABLE course (title VARCHAR, course_id VARCHAR)

SELECT title FROM course WHERE NOT course_id IN (SELECT course_id FROM prereq);


Question: What is the average flight safety score for flights operated by SpaceAirlines in the last 2 years?

CREATE TABLE flights (flight_id INT, airline VARCHAR(255), flight_date DATE, safety_score INT); INSERT INTO flights (flight_id, airline, flight_date, safety_score) VALUES (1, 'SpaceAirlines', '2020-02-03', 95), (2, 'SpaceAirlines', '2020-06-15', 92), (3, 'SpaceAirlines', '2019-11-18', 97), (4, 'SpaceAirlines', '2021-03-25', 93), (5, 'SpaceAirlines', '2018-09-01', 96);

SELECT AVG(safety_score) FROM flights WHERE airline = 'SpaceAirlines' AND flight_date >= DATEADD(year, -2, CURRENT_DATE);


Question: What is the total number of employees from underrepresented communities in the 'mining_operations' table, grouped by their departments?

CREATE TABLE mining_operations (id INT, name VARCHAR(50), job_title VARCHAR(50), department VARCHAR(50), community VARCHAR(50)); INSERT INTO mining_operations (id, name, job_title, department, community) VALUES (1, 'John Doe', 'Mining Engineer', 'Operations', 'Underrepresented'); INSERT INTO mining_operations (id, name, job_title, department, community) VALUES (2, 'Jane Smith', 'Geologist', 'Exploration', 'Underrepresented'); INSERT INTO mining_operations (id, name, job_title, department, community) VALUES (3, 'Maria Garcia', 'Mining Engineer', 'Operations', 'Not Underrepresented');

SELECT department, COUNT(*) as total_employees FROM mining_operations WHERE community = 'Underrepresented' GROUP BY department;


Question: How many movies were produced in Italy each year?

CREATE TABLE movies (id INT, title VARCHAR(255), rating FLOAT, release_year INT, country VARCHAR(50)); INSERT INTO movies (id, title, rating, release_year, country) VALUES (1, 'Movie1', 7.5, 2010, 'Italy'), (2, 'Movie2', 8.2, 2012, 'Italy'), (3, 'Movie3', 6.8, 2015, 'Italy'), (4, 'Movie4', 8.1, 2011, 'Italy'), (5, 'Movie5', 7.2, 2013, 'Italy');

SELECT release_year, COUNT(*) FROM movies WHERE country = 'Italy' GROUP BY release_year;


Question: What is the average weight of ingredients for all products sold in the US region?

CREATE TABLE product (product_id INT, product_name TEXT); CREATE TABLE ingredient (ingredient_id INT, product_id INT, weight FLOAT, country TEXT); CREATE TABLE purchase (purchase_id INT, product_id INT, purchase_date DATE, region TEXT); INSERT INTO product VALUES (1, 'Lipstick'), (2, 'Moisturizer'); INSERT INTO ingredient VALUES (1, 1, 50.0, 'CA'), (2, 1, 25.0, 'US'), (3, 2, 30.0, 'CA'); INSERT INTO purchase VALUES (1, 1, '2022-01-10', 'US'), (2, 2, '2022-01-15', 'CA');

SELECT AVG(weight) FROM ingredient i JOIN product p ON i.product_id = p.product_id JOIN purchase pu ON p.product_id = pu.product_id WHERE pu.region = 'US';


Question: Generate PostgreSQL SQL for: What is the name of the zhou jinsong's hometown?

CREATE TABLE table_28180840_15 (hometown VARCHAR, name_name_of_act VARCHAR)

SELECT hometown FROM table_28180840_15 WHERE name_name_of_act = 'Zhou Jinsong';


Question: Generate PostgreSQL SQL for: What date was the game at Dowdy-Ficklen stadium • Greenville, NC, with 27,321 in attendance?

CREATE TABLE table_name_96 (date VARCHAR, site VARCHAR, attendance VARCHAR)

SELECT date FROM table_name_96 WHERE site = 'dowdy-ficklen stadium • greenville, nc' AND attendance = '27,321';


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

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

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


Question: What was the highest score in League Y?

CREATE TABLE League_Y (match_id INT, score INT); INSERT INTO League_Y (match_id, score) VALUES (1, 100), (2, 90), (3, 110);


Question: What is the total amount of Shariah-compliant loans issued by financial institutions in the United States, broken down by state, for the year 2020?

CREATE TABLE financial_institutions (institution_id INT, institution_name VARCHAR(255), state VARCHAR(255)); INSERT INTO financial_institutions (institution_id, institution_name, state) VALUES (1, 'Institution A', 'New York'), (2, 'Institution B', 'California'); CREATE TABLE shariah_compliant_loans (loan_id INT, institution_id INT, loan_amount DECIMAL(10, 2), loan_date DATE);

SELECT f.state, SUM(s.loan_amount) as total_loan_amount FROM shariah_compliant_loans s JOIN financial_institutions f ON s.institution_id = f.institution_id WHERE YEAR(loan_date) = 2020 GROUP BY f.state;


Question: Generate PostgreSQL SQL for: When was the last final lost of the club with a last win in 1959?

CREATE TABLE table_name_70 (last_final_lost VARCHAR, last_win VARCHAR)

SELECT last_final_lost FROM table_name_70 WHERE last_win = '1959';


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

INSERT INTO covering_index_heap VALUES(1,2,'BBB');

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


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

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

SELECT count(*) FROM (SELECT 2 * m FROM money_data) AS _sub;


Question: Generate PostgreSQL SQL for: Tell me the year built for number built of 10

CREATE TABLE table_name_14 (year_built__converted VARCHAR, _ VARCHAR, no_built__converted VARCHAR)

SELECT year_built__converted * _ FROM table_name_14 WHERE no_built__converted * _ = '10';


Question: How many investments have been made with a risk assessment score greater than 80?

CREATE TABLE investments (id INT, sector VARCHAR(255), risk_assessment_score INT); INSERT INTO investments (id, sector, risk_assessment_score) VALUES (1, 'Technology', 80), (2, 'Healthcare', 70), (3, 'Social Impact Investing', 90);

SELECT COUNT(*) FROM investments WHERE risk_assessment_score > 80;


Question: Generate PostgreSQL SQL for: What is the attendance when oadby town is away?

CREATE TABLE table_name_37 (attendance VARCHAR, away_team VARCHAR)

SELECT attendance FROM table_name_37 WHERE away_team = 'oadby town';


Question: Calculate the average age of visitors who participated in offline events in Australia.

CREATE TABLE EventParticipants (event_id INT, country VARCHAR(20), participant_age INT, event_type VARCHAR(10)); INSERT INTO EventParticipants (event_id, country, participant_age, event_type) VALUES (1, 'Australia', 25, 'Offline'), (2, 'Australia', 30, 'Online'), (3, 'New Zealand', 35, 'Offline');

SELECT AVG(participant_age) FROM EventParticipants WHERE country = 'Australia' AND event_type = 'Offline';


Question: What is the average environmental factor score for projects in the education sector with an investment amount greater than $700,000?

CREATE TABLE impact_investments (id INT, project VARCHAR(50), location VARCHAR(50), investment_amount DECIMAL(10,2), impact_score INT, primary_sector VARCHAR(50)); INSERT INTO impact_investments (id, project, location, investment_amount, impact_score, primary_sector) VALUES (1, 'School Construction', 'Nigeria', 750000.00, 85, 'Education');

SELECT AVG(e.environmental_factor) as avg_env_factor FROM esg_factors e JOIN impact_investments i ON e.investment_id = i.id WHERE i.primary_sector = 'Education' AND i.investment_amount > 700000;


Question: Generate PostgreSQL SQL for: Name the Milan – San Remo which has a Liège–Bastogne–Liège of danilo di luca ( ita )?

CREATE TABLE table_name_81 (milan___san_remo VARCHAR, liège_bastogne_liège VARCHAR)

SELECT milan___san_remo FROM table_name_81 WHERE liège_bastogne_liège = 'danilo di luca ( ita )';


Question: Write the DML statement from PostgreSQL regression test 'merge' (example 115).

Explanation: DML from PostgreSQL core regression test for Merge.


Question: Generate PostgreSQL SQL for: What is the Company Name, when the Accreditation Level is Joyn Hot Fixes, and when the Accreditation Status is Approved (Awarded 17.05.13)?

CREATE TABLE table_name_13 (company_name VARCHAR, accreditation_level VARCHAR, accreditation_status VARCHAR)

SELECT company_name FROM table_name_13 WHERE accreditation_level = 'joyn hot fixes' AND accreditation_status = 'approved (awarded 17.05.13)';


Question: Generate PostgreSQL SQL for: What is the English title of 餓狼伝説バトルアーカイブズ２?

CREATE TABLE table_name_95 (english_title VARCHAR, japanese_title VARCHAR)

SELECT english_title FROM table_name_95 WHERE japanese_title = '餓狼伝説バトルアーカイブズ２';


Question: Generate PostgreSQL SQL for: What is the highest Total when Georgia is the nation with less than 11 rank?

CREATE TABLE table_name_46 (total INTEGER, nation VARCHAR, rank VARCHAR)

SELECT MAX(total) FROM table_name_46 WHERE nation = 'georgia' AND rank < 11;


Question: PostgreSQL regression test 'misc_functions': Write the SELECT query (example 76).

select count(*) = 1 as dot_found
  from pg_ls_dir('.', false, false) as ls where ls = '.';

Explanation: Regression test for Misc Functions in PostgreSQL core test suite.

SELECT count(*) FROM (select count(*) = 1 as dot_found
  from pg_ls_dir('.', false, false) as ls where ls = '.') AS _sub;


Question: How many news articles were published about climate change in the last year, for publications in the United States?

CREATE TABLE news_articles (id INT, title VARCHAR(100), publication_date DATE, topic VARCHAR(50), publication_country VARCHAR(50)); INSERT INTO news_articles (id, title, publication_date, topic, publication_country) VALUES (1, 'Climate Change: A Growing Crisis', '2022-02-12', 'Climate Change', 'United States'), (2, 'Political Turmoil in Europe', '2022-02-13', 'Politics', 'United Kingdom');

SELECT COUNT(*) FROM news_articles WHERE topic = 'Climate Change' AND publication_country = 'United States' AND publication_date >= DATEADD(year, -1, GETDATE());


Question: What is the minimum height of players in the basketball team 'Los Angeles Lakers'?

CREATE TABLE players (player_name TEXT, team TEXT, height FLOAT); INSERT INTO players (player_name, team, height) VALUES ('Charlie Davis', 'Los Angeles Lakers', 200.66); INSERT INTO players (player_name, team, height) VALUES ('Diana Williams', 'Los Angeles Lakers', 192.02);

SELECT MIN(height) FROM players WHERE team = 'Los Angeles Lakers';


Question: How many occurrences of pests were there for each pest type on farms in the West region, owned by farmers over 50 years old?

CREATE TABLE pests (id INT, date DATE, name VARCHAR(50), count INT, farm_id INT, FOREIGN KEY (farm_id) REFERENCES farmers(id)); INSERT INTO pests (id, date, name, count, farm_id) VALUES (1, '2022-01-01', 'Aphids', 10, 1), (2, '2022-01-02', 'Spider mites', 8, 2), (3, '2022-01-03', 'Thrips', 12, 5), (4, '2022-01-04', 'Whiteflies', 7, 6); INSERT INTO farmers (id, name, region, age) VALUES (1, 'James', 'West', 53), (2, 'Sophia', 'South', 40), (3, 'Mason', 'West', 57), (4, 'Lily', 'East', 55), (5, 'Olivia', 'West', 60), (6, 'Benjamin', 'East', 48);

SELECT p.name, COUNT(p.count) as total_occurrences FROM pests p JOIN farmers f ON p.farm_id = f.id WHERE f.region = 'West' AND f.age > 50 GROUP BY p.name;


Question: Generate PostgreSQL SQL for: Which tier is for football at Tianhe Stadium?

CREATE TABLE table_name_62 (tier VARCHAR, sport VARCHAR, stadium VARCHAR)

SELECT tier FROM table_name_62 WHERE sport = 'football' AND stadium = 'tianhe stadium';


Question: What is the average ticket price for TeamA's home games?

CREATE TABLE tickets (id INT, team VARCHAR(50), location VARCHAR(50), price DECIMAL(5, 2)); INSERT INTO tickets (id, team, location, price) VALUES (1, 'TeamA', 'Home', 100.00), (2, 'TeamA', 'Away', 75.00), (3, 'TeamB', 'Home', 120.00), (4, 'TeamB', 'Away', 80.00);

SELECT AVG(price) FROM tickets WHERE team = 'TeamA' AND location = 'Home';


Question: What is the average time between train breakdowns for trains in the 'South' district?

CREATE TABLE TrainBreakdowns (BreakdownID INT, BreakdownDate DATE, District VARCHAR(20)); INSERT INTO TrainBreakdowns (BreakdownID, BreakdownDate, District) VALUES (1, '2022-01-02', 'North'), (2, '2022-01-05', 'South'), (3, '2022-01-07', 'East'), (4, '2022-01-10', 'South'), (5, '2022-01-12', 'West'); CREATE TABLE TrainEvents (EventID INT, EventDate DATE, EventType VARCHAR(20), TrainID INT); INSERT INTO TrainEvents (EventID, EventDate, EventType, TrainID) VALUES (1, '2022-01-01', 'Start of Service', 1001), (2, '2022-01-02', 'Breakdown', 1001), (3, '2022-01-05', 'Breakdown', 1002), (4, '2022-01-06', 'End of Service', 1002), (5, '2022-01-07', 'Start of Service', 1003), (6, '2022-01-07', 'Breakdown', 1003);

SELECT AVG(DATEDIFF(day, EventDate, LEAD(EventDate) OVER (PARTITION BY TrainID ORDER BY EventDate))) FROM TrainEvents WHERE EventType = 'Breakdown' AND District = 'South';


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

SELECT citext_pattern_ge('A'::citext, 'b'::citext) AS false;

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


Question: Which policies were implemented in 'Delhi' or 'Mumbai' between 2018 and 2021?

CREATE TABLE City (id INT, name VARCHAR(50)); INSERT INTO City (id, name) VALUES (1, 'New York'); INSERT INTO City (id, name) VALUES (2, 'Los Angeles'); INSERT INTO City (id, name) VALUES (3, 'Delhi'); INSERT INTO City (id, name) VALUES (4, 'Mumbai'); INSERT INTO City (id, name) VALUES (5, 'Tokyo'); CREATE TABLE Policy (id INT, name VARCHAR(50), city_id INT, category VARCHAR(50), budget DECIMAL(10,2), start_date DATE, end_date DATE); INSERT INTO Policy (id, name, city_id, category, budget, start_date, end_date) VALUES (1, 'Education', 3, 'Education', 1200000, '2021-01-01', '2023-12-31'); INSERT INTO Policy (id, name, city_id, category, budget, start_date, end_date) VALUES (2, 'Healthcare', 3, 'Healthcare', 1500000, '2020-01-01', '2022-12-31'); INSERT INTO Policy (id, name, city_id, category, budget, start_date, end_date) VALUES (3, 'Transportation', 4, 'Transportation', 2000000, '2019-01-01', '2024-12-31'); INSERT INTO Policy (id, name, city_id, category, budget, start_date, end_date) VALUES (4, 'Education', 4, 'Education', 1800000, '2020-01-01', '2023-12-31');

SELECT name, start_date FROM Policy JOIN City ON Policy.city_id = City.id WHERE City.name IN ('Delhi', 'Mumbai') AND YEAR(start_date) BETWEEN 2018 AND 2021;


Question: PostgreSQL regression test 'select_distinct_on': Write the SELECT query (example 17).

SELECT DISTINCT ON (y, x) x, y FROM (SELECT * FROM distinct_on_tbl ORDER BY x) s;

Explanation: Regression test for Select Distinct On in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT DISTINCT ON (y, x) x, y FROM (SELECT * FROM distinct_on_tbl ORDER BY x) s) AS _sub;


Question: What is the maximum property price in sustainable neighborhoods with co-ownership agreements?

CREATE TABLE property (id INT, price INT, sustainability_rating INT, co_ownership BOOLEAN); INSERT INTO property (id, price, sustainability_rating, co_ownership) VALUES (1, 500000, 5, true), (2, 400000, 3, false);

SELECT MAX(price) FROM property WHERE sustainability_rating >= 4 AND co_ownership = true;


Question: Generate PostgreSQL SQL for: What was the title of the episode with production code 2J5515?

CREATE TABLE table_28582091_2 (title VARCHAR, production_code VARCHAR)

SELECT title FROM table_28582091_2 WHERE production_code = '2J5515';


Question: Generate PostgreSQL SQL for: How many places have yamaha as the machine, and 89.85mph as the speed?

CREATE TABLE table_name_30 (place INTEGER, machine VARCHAR, speed VARCHAR)

SELECT SUM(place) FROM table_name_30 WHERE machine = 'yamaha' AND speed = '89.85mph';


Question: Generate PostgreSQL SQL for: What is the best finish record for Sean O'hair?

CREATE TABLE table_29504351_2 (best_finish VARCHAR, player VARCHAR)

SELECT best_finish FROM table_29504351_2 WHERE player = 'Sean O'Hair';


Question: How many players from India play games that are available in the 'Action' category?

CREATE TABLE Players (PlayerID INT, Age INT, Country VARCHAR(50)); INSERT INTO Players (PlayerID, Age, Country) VALUES (1, 25, 'India'), (2, 30, 'Canada'), (3, 22, 'Germany'), (4, 35, 'Japan'); CREATE TABLE GameLibrary (GameID INT, GameName VARCHAR(50), GameType VARCHAR(50), Category VARCHAR(50)); INSERT INTO GameLibrary (GameID, GameName, GameType, Category) VALUES (1, 'GameA', 'VR', 'Action'), (2, 'GameB', 'Non-VR', 'Strategy'), (3, 'GameC', 'VR', 'Action'); CREATE TABLE PlayerGameLibrary (PlayerID INT, GameID INT); INSERT INTO PlayerGameLibrary (PlayerID, GameID) VALUES (1, 1), (2, 2), (3, 1), (4, 3);

SELECT COUNT(Players.PlayerID) FROM Players JOIN PlayerGameLibrary ON Players.PlayerID = PlayerGameLibrary.PlayerID JOIN GameLibrary ON PlayerGameLibrary.GameID = GameLibrary.GameID WHERE Players.Country = 'India' AND GameLibrary.Category = 'Action';


Question: Generate PostgreSQL SQL for: What is the Score, when the Year is after 2007, and when the Country is England?

CREATE TABLE table_name_5 (score VARCHAR, year VARCHAR, country VARCHAR)

SELECT score FROM table_name_5 WHERE year > 2007 AND country = 'england';


Question: What is the total mass of spacecraft manufactured by 'Cosmic Corp.' in 2022?

CREATE TABLE spacecraft(id INT, name VARCHAR(50), manufacturer VARCHAR(50), mass FLOAT, manufacture_year INT); INSERT INTO spacecraft VALUES(1, 'Artemis 1', 'Cosmic Corp.', 25000., 2022), (2, 'Artemis 2', 'Cosmic Corp.', 26000., 2023);

SELECT SUM(mass) FROM spacecraft WHERE manufacturer = 'Cosmic Corp.' AND manufacture_year = 2022;


Question: What is the total calorie count for meals served by each vendor?

CREATE TABLE Meals (MealID INT, MealName VARCHAR(50), Vendor VARCHAR(50), Calories INT); INSERT INTO Meals (MealID, MealName, Vendor, Calories) VALUES (1, 'Spaghetti Bolognese', 'Pasta Palace', 650), (2, 'Chicken Tikka Masala', 'Curry House', 850);

SELECT Vendor, SUM(Calories) as TotalCalories FROM Meals GROUP BY Vendor;


Question: What is the percentage of patients in Chicago who have not received the flu vaccine this year?

CREATE TABLE patient (patient_id INT, age INT, gender VARCHAR(10), city VARCHAR(20)); INSERT INTO patient (patient_id, age, gender, city) VALUES (1, 5, 'Female', 'Chicago'); INSERT INTO patient (patient_id, age, gender, city) VALUES (2, 10, 'Male', 'Chicago');

SELECT 100.0 * SUM(CASE WHEN flu_vaccine_date IS NULL THEN 1 ELSE 0 END) OVER (PARTITION BY city ORDER BY patient_id DESC ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) / COUNT(*) OVER (PARTITION BY city ORDER BY patient_id DESC ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS percentage FROM patient WHERE city = 'Chicago';


Question: What is the minimum sea level, grouped by month?

CREATE TABLE sea_level (id INT, month INT, level FLOAT); INSERT INTO sea_level (id, month, level) VALUES (1, 1, 20); INSERT INTO sea_level (id, month, level) VALUES (2, 2, 19); INSERT INTO sea_level (id, month, level) VALUES (3, 3, 18);

SELECT month, MIN(level) FROM sea_level GROUP BY month;


Question: Generate PostgreSQL SQL for: Which District is Constituency number 22?

CREATE TABLE table_name_43 (district VARCHAR, constituency_number VARCHAR)

SELECT district FROM table_name_43 WHERE constituency_number = '22';


Question: Generate PostgreSQL SQL for: What is the surface made of if the year is 1979 and the championship is US Open?

CREATE TABLE table_22597626_2 (surface VARCHAR, championship VARCHAR, year VARCHAR)

SELECT surface FROM table_22597626_2 WHERE championship = 'US Open' AND year = 1979;


Question: How many languages are spoken in each country?

CREATE TABLE Countries (CountryID INT, CountryName VARCHAR(50)); CREATE TABLE Languages (LanguageID INT, CountryID INT, Spoken VARCHAR(50)); INSERT INTO Countries VALUES (1, 'CountryA'), (2, 'CountryB'), (3, 'CountryC'); INSERT INTO Languages VALUES (1, 1, 'LanguageX'), (2, 1, 'LanguageY'), (3, 2, 'LanguageY'), (4, 3, 'LanguageZ'), (5, 3, 'LanguageW');

SELECT C.CountryName, COUNT(L.LanguageID) AS LanguagesSpoken FROM Countries C JOIN Languages L ON C.CountryID = L.CountryID GROUP BY C.CountryName;


Question: Write the DML statement from PostgreSQL regression test 'case' (example 7).

Explanation: DML from PostgreSQL core regression test for Case.


Question: Generate PostgreSQL SQL for: Show the name of the party that has the most delegates.

CREATE TABLE election (Party VARCHAR); CREATE TABLE party (Party VARCHAR, Party_ID VARCHAR)

SELECT T2.Party FROM election AS T1 JOIN party AS T2 ON T1.Party = T2.Party_ID GROUP BY T1.Party ORDER BY COUNT(*) DESC LIMIT 1;


Question: Determine the difference in average transaction amounts between customers from 'North America' and 'Asia'.

CREATE TABLE transaction_amounts (customer_id INT, region VARCHAR(20), transaction_amount NUMERIC(12,2)); INSERT INTO transaction_amounts (customer_id, region, transaction_amount) VALUES (1, 'Asia', 1000), (2, 'Europe', 1500), (3, 'Africa', 750), (4, 'North America', 2000), (5, 'South America', 1200), (6, 'Australia', 1750), (7, 'Asia', 1500), (8, 'Europe', 2000), (9, 'Africa', 1000), (10, 'North America', 2500);

SELECT AVG(transaction_amount) as avg_asia FROM transaction_amounts WHERE region = 'Asia' INTERSECT SELECT AVG(transaction_amount) as avg_north_america FROM transaction_amounts WHERE region = 'North America';


Question: List the names of all startups that have received funding and have diverse founding teams (more than one founder with different genders).

CREATE TABLE startups (id INT, name TEXT, founder1 TEXT, founder2 TEXT, funding FLOAT); INSERT INTO startups (id, name, founder1, founder2, funding) VALUES (1, 'Acme', 'John Doe', 'Jane Smith', 500000.00); INSERT INTO startups (id, name, founder1, founder2, funding) VALUES (2, 'Beta Corp', 'Jane Smith', 'John Doe', 750000.00); INSERT INTO startups (id, name, founder1, founder2, funding) VALUES (3, 'Gamma Inc', 'Alice', NULL, 300000.00);

SELECT name FROM startups WHERE (founder1 != founder2) AND (founder1 IS NOT NULL AND founder2 IS NOT NULL);


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

CREATE FUNCTION pgstatindex(IN relname text,
    OUT version INT,
    OUT tree_level INT,
    OUT index_size BIGINT,
    OUT root_block_no BIGINT,
    OUT internal_pages BIGINT,
    OUT leaf_pages BIGINT,
    OUT empty_pages BIGINT,
    OUT deleted_pages BIGINT,
    OUT avg_leaf_density FLOAT8,
    OUT leaf_fragmentation FLOAT8)
AS 'MODULE_PATHNAME', 'pgstatindex'
LANGUAGE C STRICT PARALLEL SAFE;

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


Question: How many esports events were held in total in 2021?

CREATE TABLE esports_events (id INT, year INT, location VARCHAR(20)); INSERT INTO esports_events (id, year, location) VALUES (1, 2022, 'USA'), (2, 2022, 'Germany'), (3, 2021, 'France');

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


Question: Which waste types are not included in the circular economy initiatives?

CREATE TABLE waste_types (type TEXT, id INTEGER); INSERT INTO waste_types (type, id) VALUES ('Plastic', 1), ('Paper', 2), ('Glass', 3), ('Metal', 4); CREATE TABLE circular_economy_initiatives (waste_type_id INTEGER); INSERT INTO circular_economy_initiatives (waste_type_id) VALUES (1), (2), (3);

SELECT wt.type FROM waste_types wt LEFT JOIN circular_economy_initiatives cei ON wt.id = cei.waste_type_id WHERE cei.waste_type_id IS NULL;


Question: Generate PostgreSQL SQL for: What is the attendance date of the game home team Shrewsbury Town played?

CREATE TABLE table_name_48 (attendance VARCHAR, home_team VARCHAR)

SELECT attendance FROM table_name_48 WHERE home_team = 'shrewsbury town';


Question: Generate PostgreSQL SQL for: What was the date of the game that had a loss of Rojas (9–8)?

CREATE TABLE table_name_74 (date VARCHAR, loss VARCHAR)

SELECT date FROM table_name_74 WHERE loss = 'rojas (9–8)';


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

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


Question: Write the DML statement from PostgreSQL regression test 'publication' (example 605).

Explanation: DML from PostgreSQL core regression test for Publication.


Question: Generate PostgreSQL SQL for: Is Jasper being producted?

CREATE TABLE table_name_66 (in_production VARCHAR, codename VARCHAR)

SELECT in_production FROM table_name_66 WHERE codename = 'jasper';


Question: Delete player records from the "players" table who have not played any game

CREATE TABLE players (player_id INT, name VARCHAR(255), country VARCHAR(255), date_registered DATE); CREATE TABLE player_scores (player_id INT, game_name VARCHAR(255), score INT, date DATE);

DELETE FROM players WHERE player_id NOT IN (SELECT player_id FROM player_scores);


Question: Generate PostgreSQL SQL for: Name the publication date when the fictional date is 2112

CREATE TABLE table_name_25 (publication_date VARCHAR, fictional_date VARCHAR)

SELECT publication_date FROM table_name_25 WHERE fictional_date = '2112';


Question: Which regulatory frameworks were adopted in 2022?

CREATE TABLE regulatory_frameworks (framework_id INT PRIMARY KEY, country VARCHAR(255), name VARCHAR(255), framework TEXT, adoption_date TIMESTAMP); INSERT INTO regulatory_frameworks (framework_id, country, name, framework, adoption_date) VALUES (3, 'Japan', 'JFSA Guidelines', 'Blockchain regulations in Japan', '2022-04-01');

SELECT country, name, framework FROM regulatory_frameworks WHERE adoption_date BETWEEN '2022-01-01' AND '2022-12-31';


Question: What are the unique IP addresses that have been associated with 'APT35' threat actor?

SELECT DISTINCT ip_address FROM actor_ip WHERE threat_actor = 'APT35';


Question: Write the DDL statement from PostgreSQL regression test 'polymorphism' (example 125).

CREATE AGGREGATE myaggn15b(BASETYPE = anyelement, SFUNC = tfnp,
  STYPE = anyarray, INITCOND = '{}');

Explanation: DDL from PostgreSQL core regression test for Polymorphism.


Question: Generate PostgreSQL SQL for: How many candidates won the election in the district whose incumbent is Bud Shuster?

CREATE TABLE table_1341604_39 (candidates VARCHAR, incumbent VARCHAR)

SELECT COUNT(candidates) FROM table_1341604_39 WHERE incumbent = 'Bud Shuster';


Question: Generate PostgreSQL SQL for: How many times does the  rebuilt data contain cannot handle non-empty timestamp argument! 1929 and scrapped data contain cannot handle non-empty timestamp argument! 1954?

CREATE TABLE table_12113888_1 (number VARCHAR, rebuilt VARCHAR, scrapped_sold VARCHAR)

SELECT COUNT(number) FROM table_12113888_1 WHERE rebuilt = 'Cannot handle non-empty timestamp argument! 1929' AND scrapped_sold = 'Cannot handle non-empty timestamp argument! 1954';


Question: What is the total salary expense for each department in 2021?

CREATE TABLE departments (id INT, name VARCHAR(255));CREATE TABLE employees (id INT, department_id INT, salary INT, hire_date DATE);

SELECT d.name, SUM(e.salary) AS salary_expense  FROM departments d  INNER JOIN employees e ON d.id = e.department_id  WHERE e.hire_date >= '2021-01-01' AND e.hire_date < '2022-01-01'  GROUP BY d.name;


Question: What is the maximum distance for routes that originate from 'City C'?

CREATE TABLE Routes (id INT, origin_city VARCHAR(255), destination_city VARCHAR(255), distance INT, eta INT); INSERT INTO Routes (id, origin_city, destination_city, distance, eta) VALUES (1, 'City A', 'City C', 200, 2); INSERT INTO Routes (id, origin_city, destination_city, distance, eta) VALUES (2, 'City B', 'City D', 250, 3); INSERT INTO Routes (id, origin_city, destination_city, distance, eta) VALUES (3, 'City C', 'City E', 300, 4);

SELECT origin_city, MAX(distance) FROM Routes WHERE origin_city = 'City C' GROUP BY origin_city;


Question: What is the total number of hospitals and total number of beds for each city?

CREATE TABLE hospitals (id INT, name TEXT, city TEXT, state TEXT, beds INT); INSERT INTO hospitals (id, name, city, state, beds) VALUES (1, 'General Hospital', 'Miami', 'Florida', 500); INSERT INTO hospitals (id, name, city, state, beds) VALUES (2, 'Memorial Hospital', 'Boston', 'Massachusetts', 600);

SELECT city, COUNT(*) as hospital_count, SUM(beds) as total_beds FROM hospitals GROUP BY city;


Question: pgTAP test for Aretap (assertion 171).

SELECT * FROM check_test(
    columns_are( 'fou', ARRAY['id', 'name', 'numb', 'myInt'], 'whatever' ),
    true,
    'columns_are(table, columns, desc)',
    'whatever',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Aretap.


Question: Generate PostgreSQL SQL for: Show the name and the nationality of the oldest host.

CREATE TABLE HOST (Name VARCHAR, Nationality VARCHAR, Age VARCHAR)

SELECT Name, Nationality FROM HOST ORDER BY Age DESC LIMIT 1;


Question: Generate PostgreSQL SQL for: What was the number of viewers in millions for the broadcast from 2010?

CREATE TABLE table_24212608_1 (viewers__millions_ VARCHAR, broadcast_date VARCHAR)

SELECT viewers__millions_ FROM table_24212608_1 WHERE broadcast_date = 2010;


Question: Update the hours_served column in the volunteers table to set the value to 35.00 for the record with id = 4.

CREATE TABLE volunteers (id INT, name VARCHAR(50), hours_served FLOAT); INSERT INTO volunteers (id, name, hours_served) VALUES (4, 'Olivia Thompson', 25.00);

UPDATE volunteers SET hours_served = 35.00 WHERE id = 4;


Question: How many technology accessibility patents were granted to women in tech in 2019?

CREATE TABLE tech_accessibility_patents (id INT, year INT, community VARCHAR(255), type VARCHAR(255)); INSERT INTO tech_accessibility_patents (id, year, community, type) VALUES (1, 2019, 'Women in Tech', 'Technology Accessibility'); INSERT INTO tech_accessibility_patents (id, year, community, type) VALUES (2, 2020, 'Minority Tech Group', 'AI for Good');

SELECT COUNT(*) FROM tech_accessibility_patents WHERE year = 2019 AND community = 'Women in Tech';


Question: Generate PostgreSQL SQL for: How many matches were 44?

CREATE TABLE table_24039597_26 (dismissals VARCHAR, matches VARCHAR)

SELECT COUNT(dismissals) FROM table_24039597_26 WHERE matches = 44;


Question: What is the number of new users who signed up from each country, in the last month?

CREATE TABLE users (user_id INT, user_name TEXT, user_country TEXT, user_signup_date DATE);

SELECT user_country, COUNT(DISTINCT user_id) as new_users FROM users WHERE user_signup_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH) GROUP BY user_country;


Question: Generate PostgreSQL SQL for: What is the score when november 15 is the date?

CREATE TABLE table_name_86 (score VARCHAR, date VARCHAR)

SELECT score FROM table_name_86 WHERE date = 'november 15';


Question: Generate PostgreSQL SQL for: What Winning team has 22 July as a Date?

CREATE TABLE table_name_79 (winning_team VARCHAR, date VARCHAR)

SELECT winning_team FROM table_name_79 WHERE date = '22 july';


Question: Rank the water treatment plants in India by the amount of wastewater treated daily in descending order.

CREATE TABLE india_wastewater_treatment (id INT, plant_name VARCHAR(50), daily_wastewater_treated FLOAT); INSERT INTO india_wastewater_treatment (id, plant_name, daily_wastewater_treated) VALUES (1, 'Bangalore Plant', 500), (2, 'Mumbai Plant', 600), (3, 'Delhi Plant', 400), (4, 'Chennai Plant', 450);

SELECT plant_name, daily_wastewater_treated, RANK() OVER (ORDER BY daily_wastewater_treated DESC) as rank FROM india_wastewater_treatment;


Question: Find the 'total area' of 'coniferous' forests in '2021'.

CREATE TABLE forests (id INT, biome VARCHAR(50), area FLOAT, year INT); INSERT INTO forests (id, biome, area, year) VALUES (1, 'coniferous', 5000.0, 2021);

SELECT SUM(area) FROM forests WHERE biome = 'coniferous' AND year = 2021;


Question: Generate PostgreSQL SQL for: What is the round where winners from the previous round totals 8?

CREATE TABLE table_18328569_1 (round VARCHAR, winners_from_previous_round VARCHAR)

SELECT round FROM table_18328569_1 WHERE winners_from_previous_round = '8';


Question: Update security policies' category

CREATE TABLE security_policies (id INT, policy_id VARCHAR(255), policy_name VARCHAR(255), category VARCHAR(255), last_updated DATETIME); INSERT INTO security_policies (id, policy_id, policy_name, category, last_updated) VALUES (1, 'POL-002', 'Incident Response', 'Detection', '2021-07-01 11:00:00');

UPDATE security_policies SET category = 'Monitoring' WHERE policy_id = 'POL-002';


Question: List members who did yoga or zumba workouts and their total workouts.

CREATE TABLE membership_data (member_id INT, join_date DATE); CREATE TABLE workout_data (workout_id INT, member_id INT, workout_type VARCHAR(20), workout_date DATE);

SELECT m.member_id, m.join_date, COUNT(w.workout_id) as total_workouts FROM membership_data m JOIN workout_data w ON m.member_id = w.member_id WHERE w.workout_type IN ('yoga', 'zumba') GROUP BY m.member_id;


Question: Generate PostgreSQL SQL for: What is Date, when Label is Jugoton?

CREATE TABLE table_name_48 (date VARCHAR, label VARCHAR)

SELECT date FROM table_name_48 WHERE label = 'jugoton';


Question: Show an example of PostgreSQL CREATE FUNCTION (example 1).

CREATE FUNCTION foo(int) ... CREATE FUNCTION foo(int, OUT text) ...;

Explanation: PostgreSQL CREATE FUNCTION command.


Question: What was the total revenue for lipsticks sold in the USA in Q1 2022?

CREATE TABLE cosmetics_sales(product_type VARCHAR(255), country VARCHAR(255), sales_quantity INT, sales_revenue DECIMAL(10,2));

SELECT SUM(sales_revenue) FROM cosmetics_sales WHERE product_type = 'lipstick' AND country = 'USA' AND sales_date BETWEEN '2022-01-01' AND '2022-03-31';


Question: Delete all records in the ProductIngredients table with organic ingredients.

CREATE TABLE ProductIngredients (productID INT, ingredient VARCHAR(50), organic BOOLEAN); INSERT INTO ProductIngredients (productID, ingredient, organic) VALUES (1, 'Aloe Vera', true), (2, 'Chamomile', true), (3, 'Retinol', false), (4, 'Hyaluronic Acid', false);

DELETE FROM ProductIngredients WHERE organic = true;


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

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

SELECT count(*) FROM (SELECT to_char(val, '9999999999999999.999999999999999PR')
	FROM num_data) AS _sub;


Question: Generate PostgreSQL SQL for: What is the value for 2009 when the value for 2011 is 138?

SELECT 2009 FROM table_name_87 WHERE 2011 = '138';


Question: Generate PostgreSQL SQL for: Find the id and weight of all pets whose age is older than 1.

CREATE TABLE pets (petid VARCHAR, weight VARCHAR, pet_age INTEGER)

SELECT petid, weight FROM pets WHERE pet_age > 1;


Question: What are the mines with labor turnover rates higher than 0.08?

CREATE TABLE labor_force (mine_name VARCHAR(255), employee_count INT, turnover_rate FLOAT); INSERT INTO labor_force (mine_name, employee_count, turnover_rate) VALUES ('Green Valley', 250, 0.09); INSERT INTO labor_force (mine_name, employee_count, turnover_rate) VALUES ('Blue Hills', 300, 0.07);

SELECT mine_name FROM labor_force WHERE turnover_rate > 0.08;


Question: Generate PostgreSQL SQL for: Who were the runners-up in the game that was won by Cork City F.C. on 10/05/1998?

CREATE TABLE table_name_48 (runners_up VARCHAR, winners VARCHAR, date VARCHAR)

SELECT runners_up FROM table_name_48 WHERE winners = 'cork city f.c.' AND date = '10/05/1998';


Question: Generate PostgreSQL SQL for: WHAT PLAYER HAS UPLAND HIGH SCHOOL?

CREATE TABLE table_name_88 (player VARCHAR, hometown_school VARCHAR)

SELECT player FROM table_name_88 WHERE hometown_school = 'upland high school';


Question: Generate PostgreSQL SQL for: Who was the Europe/Africa group i's opponent?

CREATE TABLE table_name_61 (opponent VARCHAR, zone VARCHAR)

SELECT opponent FROM table_name_61 WHERE zone = 'europe/africa group i';


Question: What is the maximum response time for any emergency in Miami-Dade County in 2021?

CREATE TABLE emergency_responses (id INT, incident_id INT, response_time INT, city VARCHAR(255), state VARCHAR(255), county VARCHAR(255)); INSERT INTO emergency_responses (id, incident_id, response_time, city, state, county) VALUES (1, 1, 15, 'Miami', 'Florida', 'Miami-Dade County'); INSERT INTO emergency_responses (id, incident_id, response_time, city, state, county) VALUES (2, 2, 8, 'Miami Beach', 'Florida', 'Miami-Dade County');

SELECT MAX(response_time) FROM emergency_responses WHERE county = 'Miami-Dade County' AND reported_date >= '2021-01-01' AND reported_date < '2022-01-01';


Question: How many unique mineral types are there in the 'mineral_survey' table?

CREATE TABLE mineral_survey (id INT, mine_name VARCHAR, mineral VARCHAR, percentage_composition DECIMAL); INSERT INTO mineral_survey (id, mine_name, mineral, percentage_composition) VALUES (1, 'Crystal Mine', 'Quartz', 45.00), (2, 'Gemstone Gulch', 'Emerald', 75.00), (3, 'Ore Mountain', 'Gold', 90.00), (4, 'Granite Grove', 'Granite', 100.00);

SELECT COUNT(DISTINCT mineral) FROM mineral_survey;


Question: What is the total production volume for each region, and what is the percentage of the total production volume accounted for by each region?

CREATE TABLE production_volume (volume_id INT, well_id INT, production_year INT, production_volume FLOAT, region VARCHAR(50)); INSERT INTO production_volume (volume_id, well_id, production_year, production_volume, region) VALUES (3, 3, 2022, 220.0, 'Asia-Pacific'); INSERT INTO production_volume (volume_id, well_id, production_year, production_volume, region) VALUES (4, 4, 2023, 180.5, 'Africa');

SELECT region, SUM(production_volume) as total_volume, PERCENTAGE_RANK() OVER (ORDER BY SUM(production_volume) DESC) as percentage_of_total FROM production_volume GROUP BY region;


Question: PL/pgSQL test: Plpython Record (example 65).

SELECT * FROM test_type_record_error2();

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


Question: Generate PostgreSQL SQL for: How many were in the Kargahar (vidhan sabha constituency)?

CREATE TABLE table_29785324_5 (constituency_no INTEGER, vidhan_sabha_constituency VARCHAR)

SELECT MIN(constituency_no) FROM table_29785324_5 WHERE vidhan_sabha_constituency = 'Kargahar (Vidhan Sabha constituency)';


Question: Generate PostgreSQL SQL for: Who wrote the episodes that had a viewership of 7.14?

CREATE TABLE table_24910737_1 (written_by VARCHAR, us_viewers__millions_ VARCHAR)

SELECT written_by FROM table_24910737_1 WHERE us_viewers__millions_ = '7.14';


Question: Count the number of public transportation trips taken in New York City for the month of January in the year 2022.

CREATE TABLE trips (trip_id INT, trip_date DATE, trip_type VARCHAR(50), city VARCHAR(50)); INSERT INTO trips (trip_id, trip_date, trip_type, city) VALUES (1, '2022-01-01', 'Public Transportation', 'New York City'), (2, '2022-01-05', 'Taxi', 'New York City'), (3, '2022-01-10', 'Public Transportation', 'New York City');

SELECT COUNT(*) FROM trips WHERE trip_type = 'Public Transportation' AND EXTRACT(MONTH FROM trip_date) = 1 AND EXTRACT(YEAR FROM trip_date) = 2022 AND city = 'New York City';


Question: Update the country for volunteer 'Bob' to Canada.

CREATE TABLE Volunteers (id INT, name VARCHAR(255), country VARCHAR(255)); INSERT INTO Volunteers (id, name, country) VALUES (1, 'Alice', 'United States'), (2, 'Bob', 'United States');

UPDATE Volunteers SET country = 'Canada' WHERE name = 'Bob';


Question: What is the minimum score obtained in the game 'Quantum Quest'?

CREATE TABLE Game_Scores (Player_ID INT, Player_Name VARCHAR(50), Game_Name VARCHAR(50), Score INT); INSERT INTO Game_Scores (Player_ID, Player_Name, Game_Name, Score) VALUES (1, 'Olga Petrova', 'Ukraine', 400), (2, 'Ricardo Gonzales', 'Argentina', 700), (3, 'Elif Yilmaz', 'Turkey', 500), (4, 'Jordan Bennett', 'Australia', 600), (5, 'Nina Jensen', 'Norway', 800);

SELECT MIN(Score) FROM Game_Scores WHERE Game_Name = 'Quantum Quest';


Question: Generate PostgreSQL SQL for: Who is the team captain of the team that Lübzer is the shirt sponsor for?

CREATE TABLE table_name_88 (team VARCHAR, shirt_sponsor VARCHAR)

SELECT team AS captain FROM table_name_88 WHERE shirt_sponsor = 'lübzer';


Question: How many students participated in each support program?

CREATE TABLE Students(student_id INT, name TEXT);CREATE TABLE Programs(program_id INT, program_name TEXT);CREATE TABLE Student_Programs(student_id INT, program_id INT);

SELECT p.program_name, COUNT(sp.student_id) FROM Programs p INNER JOIN Student_Programs sp ON p.program_id = sp.program_id GROUP BY p.program_name;


Question: Generate PostgreSQL SQL for: What is the name on the Socialist ticket when the Democratic ticket is george k. shuler?

CREATE TABLE table_name_6 (socialist_ticket VARCHAR, democratic_ticket VARCHAR)

SELECT socialist_ticket FROM table_name_6 WHERE democratic_ticket = 'george k. shuler';


Question: What are the names and locations of climate finance projects that received more funding than any project in Europe?

CREATE TABLE climate_finance_projects ( id INT, name VARCHAR(255), location VARCHAR(255), funding FLOAT ); INSERT INTO climate_finance_projects (id, name, location, funding) VALUES (1, 'Project P', 'Europe', 6000000); INSERT INTO climate_finance_projects (id, name, location, funding) VALUES (2, 'Project Q', 'Europe', 8000000);

SELECT name, location FROM climate_finance_projects WHERE funding > (SELECT MAX(funding) FROM climate_finance_projects WHERE location = 'Europe');


Question: What is the total number of certified sustainable tourism businesses in Italy?

CREATE TABLE sustainable_tourism (id INT, name TEXT, country TEXT, is_certified BOOLEAN); INSERT INTO sustainable_tourism (id, name, country, is_certified) VALUES (1, 'Eco Hotel', 'Italy', true), (2, 'Green Tourism', 'Italy', true), (3, 'Sustainable Travel Italy', 'Italy', false);

SELECT COUNT(*) FROM sustainable_tourism WHERE country = 'Italy' AND is_certified = true;


Question: How many members have a gym membership starting in January?

CREATE TABLE gym_memberships(member_id INT, start_date DATE); INSERT INTO gym_memberships(member_id, start_date) VALUES (1, '2022-01-01'); INSERT INTO gym_memberships(member_id, start_date) VALUES (2, '2022-02-01'); INSERT INTO gym_memberships(member_id, start_date) VALUES (3, '2021-12-15'); INSERT INTO gym_memberships(member_id, start_date) VALUES (4, '2022-01-15');

SELECT COUNT(member_id) FROM gym_memberships WHERE MONTH(start_date) = 1;


Question: Generate PostgreSQL SQL for: How many opponents played 1 game with a result win?

CREATE TABLE table_18207285_2 (opponents INTEGER, result VARCHAR, game VARCHAR)

SELECT MAX(opponents) FROM table_18207285_2 WHERE result = 'Win' AND game = 1;


Question: What is the total number of sustainable tour packages sold by vendors from Oceania?

CREATE TABLE Vendors (VendorID INT, VendorName VARCHAR(50), Country VARCHAR(50)); INSERT INTO Vendors (VendorID, VendorName, Country) VALUES (1, 'GreenVacations', 'Australia'), (2, 'EcoTours', 'New Zealand'), (3, 'SustainableJourneys', 'Fiji'), (4, 'BluePlanetTours', 'USA'); CREATE TABLE Packages (PackageID INT, VendorID INT, PackageType VARCHAR(20), Sales INT); INSERT INTO Packages (PackageID, VendorID, PackageType, Sales) VALUES (1, 1, 'Sustainable', 500), (2, 1, 'Virtual', 300), (3, 2, 'Sustainable', 700), (4, 2, 'Virtual', 600), (5, 3, 'Sustainable', 800), (6, 3, 'Virtual', 400), (7, 4, 'Sustainable', 50), (8, 4, 'Virtual', 60);

SELECT V.Country, SUM(P.Sales) as TotalSales FROM Vendors V INNER JOIN Packages P ON V.VendorID = P.VendorID WHERE V.Country LIKE 'Oceania%' AND P.PackageType = 'Sustainable' GROUP BY V.Country;


Question: Generate PostgreSQL SQL for: What is the largest caps value for Glen Moss?

CREATE TABLE table_name_50 (caps INTEGER, player VARCHAR)

SELECT MAX(caps) FROM table_name_50 WHERE player = 'glen moss';


Question: Add a new soil moisture reading of 42 for sensor S102

CREATE TABLE soil_moisture_sensors (sensor_id VARCHAR(10), moisture_level INT);

INSERT INTO soil_moisture_sensors (sensor_id, moisture_level) VALUES ('S102', 42);


Question: Generate PostgreSQL SQL for: What was the name of the tournament played on Jun 17, 1973?

CREATE TABLE table_name_3 (tournament VARCHAR, date VARCHAR)

SELECT tournament FROM table_name_3 WHERE date = 'jun 17, 1973';


Question: Generate PostgreSQL SQL for: What is the venue of the 1990 Asian games?

CREATE TABLE table_name_77 (venue VARCHAR, competition VARCHAR)

SELECT venue FROM table_name_77 WHERE competition = '1990 asian games';


Question: Generate PostgreSQL SQL for: What is the 1st leg of Team 2 PSV Eindhoven?

CREATE TABLE table_name_21 (team_2 VARCHAR)

SELECT 1 AS st_leg FROM table_name_21 WHERE team_2 = 'psv eindhoven';


Question: What is the total plastic waste generation per capita by state in the USA in 2021?

CREATE TABLE waste_generation (id INT, state VARCHAR(50), waste_amount FLOAT, waste_type VARCHAR(50), year INT); INSERT INTO waste_generation (id, state, waste_amount, waste_type, year) VALUES (1, 'California', 120000, 'plastic', 2021), (2, 'Texas', 100000, 'plastic', 2021), (3, 'New York', 90000, 'plastic', 2021);

SELECT state, SUM(waste_amount) / (SELECT SUM(population) FROM populations WHERE populations.state = state AND populations.year = 2021) as per_capita FROM waste_generation WHERE waste_type = 'plastic' AND year = 2021 GROUP BY state ORDER BY per_capita DESC;


Question: Generate PostgreSQL SQL for: What date did season 12 premiere?

CREATE TABLE table_2655016_4 (original_air_date VARCHAR, season__number VARCHAR)

SELECT original_air_date FROM table_2655016_4 WHERE season__number = 12;


Question: Generate PostgreSQL SQL for: What are all the school years where class AAAA is in Gregory-Portland?

CREATE TABLE table_14603212_5 (school_year VARCHAR, class_aAAA VARCHAR, Gregory VARCHAR, Portland VARCHAR)

SELECT school_year FROM table_14603212_5 WHERE class_aAAA = Gregory - Portland;


Question: Generate PostgreSQL SQL for: What was the result on September 20?

CREATE TABLE table_name_99 (result VARCHAR, date VARCHAR)

SELECT result FROM table_name_99 WHERE date = 'september 20';


Question: What is the average sustainability score of manufacturers who produce products in the 'accessories' category?

CREATE TABLE manufacturers (id INT PRIMARY KEY, name TEXT, location TEXT, sustainability_score INT); CREATE TABLE products (id INT PRIMARY KEY, name TEXT, category TEXT, price DECIMAL, manufacturer_id INT, FOREIGN KEY (manufacturer_id) REFERENCES manufacturers(id));

SELECT AVG(m.sustainability_score)  FROM manufacturers m  JOIN products p ON m.id = p.manufacturer_id  WHERE p.category = 'accessories';


Question: Who are the suppliers located in India?

CREATE TABLE suppliers (id INT, name VARCHAR(255), location VARCHAR(255), sustainable_practices BOOLEAN); CREATE TABLE garments (id INT, name VARCHAR(255), category VARCHAR(255), price DECIMAL(5,2), quantity INT, supplier_id INT); CREATE TABLE manufacturing_costs (id INT, garment_id INT, labor_cost DECIMAL(5,2), material_cost DECIMAL(5,2), manufacturing_time INT); INSERT INTO suppliers (id, name, location, sustainable_practices) VALUES (3, 'Supplier C', 'India', true); INSERT INTO garments (id, name, category, price, quantity, supplier_id) VALUES (3, 'Garment Z', 'Bottoms', 45.99, 25, 3); INSERT INTO manufacturing_costs (id, garment_id, labor_cost, material_cost, manufacturing_time) VALUES (3, 3, 22.50, 21.25, 40);

SELECT suppliers.name FROM suppliers WHERE suppliers.location = 'India';


Question: Generate PostgreSQL SQL for: How many different municipal mayors were there in the municipality with an area of 42.66 km2?

CREATE TABLE table_216776_2 (municipal_mayor VARCHAR, area__km²_ VARCHAR)

SELECT COUNT(municipal_mayor) FROM table_216776_2 WHERE area__km²_ = '42.66';


Question: List the total number of claims and total claim amount for each product type.

CREATE TABLE Claim (ClaimID INT, PolicyholderID INT, ClaimDate DATE, Product VARCHAR(10), ClaimAmount DECIMAL(10,2)); INSERT INTO Claim (ClaimID, PolicyholderID, ClaimDate, Product, ClaimAmount) VALUES (1, 1, '2020-01-01', 'Auto', 500), (2, 1, '2021-01-01', 'Auto', 1000), (3, 2, '2020-01-01', 'Home', 2000), (4, 3, '2018-01-01', 'Auto', 1500);

SELECT Product, COUNT(*) AS TotalClaims, SUM(ClaimAmount) AS TotalClaimAmount FROM Claim GROUP BY Product;


Question: What is the most popular game genre among players in the EU region?

CREATE TABLE PlayerGenre (PlayerID INT PRIMARY KEY, Region VARCHAR(10), GameType VARCHAR(20)); INSERT INTO PlayerGenre (PlayerID, Region, GameType) VALUES (1, 'EU', 'Strategy'); INSERT INTO PlayerGenre (PlayerID, Region, GameType) VALUES (2, 'NA', 'FPS'); INSERT INTO PlayerGenre (PlayerID, Region, GameType) VALUES (3, 'EU', 'RPG');

SELECT GameType, COUNT(*) AS Count FROM PlayerGenre WHERE Region = 'EU' GROUP BY GameType ORDER BY Count DESC LIMIT 1;


Question: Delete all records in the 'military_equipment' table where 'equipment_type' is 'aircraft'

CREATE TABLE military_equipment (equipment_id INT PRIMARY KEY, equipment_type VARCHAR(20), country VARCHAR(20), in_service BOOLEAN);

DELETE FROM military_equipment WHERE equipment_type = 'aircraft';


Question: What is the average duration of virtual tours in Colombia?

CREATE TABLE virtual_tours_co (tour_id INT, tour_name VARCHAR(255), country VARCHAR(255), duration INT); INSERT INTO virtual_tours_co (tour_id, tour_name, country, duration) VALUES (1, 'Virtual Tour Bogota', 'Colombia', 60); INSERT INTO virtual_tours_co (tour_id, tour_name, country, duration) VALUES (2, 'Virtual Tour Medellin', 'Colombia', 75); INSERT INTO virtual_tours_co (tour_id, tour_name, country, duration) VALUES (3, 'Virtual Tour Cartagena', 'Colombia', 90);

SELECT country, AVG(duration) FROM virtual_tours_co WHERE country = 'Colombia';


Question: List all military equipment maintenance activities performed on aircraft in the Asia-Pacific region in the last 6 months.

CREATE TABLE equipment_maintenance (maintenance_id INT, maintenance_date DATE, equipment_type VARCHAR(255), region VARCHAR(255)); INSERT INTO equipment_maintenance (maintenance_id, maintenance_date, equipment_type, region) VALUES (1, '2021-12-31', 'aircraft', 'Asia-Pacific'), (2, '2022-04-04', 'tank', 'Europe'), (3, '2022-06-15', 'aircraft', 'Asia-Pacific');

SELECT * FROM equipment_maintenance WHERE equipment_type = 'aircraft' AND region = 'Asia-Pacific' AND maintenance_date >= DATE_SUB(CURRENT_DATE, INTERVAL 6 MONTH);


Question: How many TV shows were released per year in the 'Drama' genre and their average IMDb ratings?

CREATE TABLE TVShows (ShowID INT, Title VARCHAR(255), ReleaseYear INT, Genre VARCHAR(50), IMDbRating DECIMAL(3,2));

SELECT ReleaseYear, Genre, COUNT(Title) AS Number_Of_Shows, AVG(IMDbRating) AS Avg_Rating FROM TVShows WHERE Genre = 'Drama' GROUP BY ReleaseYear, Genre;


Question: Generate PostgreSQL SQL for: What method was used in the match that went to round 1, and had a 6-3-1 record?

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

SELECT method FROM table_name_13 WHERE round = 1 AND record = '6-3-1';


Question: What is the running total of 'online_time' for each user, for the 'online_learning' database, ordered by user_id and date?

CREATE TABLE online_learning (id INT, user_id INT, online_date DATE, online_time INT); INSERT INTO online_learning (id, user_id, online_date, online_time) VALUES (1, 1001, '2022-01-01', 60); INSERT INTO online_learning (id, user_id, online_date, online_time) VALUES (2, 1001, '2022-01-03', 90); INSERT INTO online_learning (id, user_id, online_date, online_time) VALUES (3, 1002, '2022-01-02', 45);

SELECT user_id, online_date, online_time, SUM(online_time) OVER (PARTITION BY user_id ORDER BY online_date) as running_total FROM online_learning;


Question: Generate PostgreSQL SQL for: When was the score l 111–122 (ot)?

CREATE TABLE table_name_84 (date VARCHAR, score VARCHAR)

SELECT date FROM table_name_84 WHERE score = 'l 111–122 (ot)';


Question: What is the rank of the total number of labor hours worked by each construction trade for each state?

CREATE TABLE labor_hours_by_state (state TEXT, trade TEXT, hours INT); INSERT INTO labor_hours_by_state (state, trade, hours) VALUES ('California', 'Carpentry', 9000), ('California', 'Electrical', 11000), ('California', 'Plumbing', 8000), ('Texas', 'Carpentry', 7000), ('Texas', 'Electrical', 9000), ('Texas', 'Plumbing', 10000);

SELECT state, trade, RANK() OVER (PARTITION BY state ORDER BY hours DESC) FROM labor_hours_by_state;


Question: Insert new product 'Eco-friendly Product4' with is_organic = TRUE in 'FarmersMarket' view

CREATE VIEW FarmersMarket AS SELECT * FROM Products WHERE is_organic = TRUE; INSERT INTO Products (id, name, is_organic) VALUES (1, 'Product1', TRUE), (2, 'Product2', FALSE), (3, 'Product3', TRUE);

INSERT INTO Products (id, name, is_organic) VALUES ((SELECT COALESCE(MAX(id), 0) + 1 FROM Products), 'Eco-friendly Product4', TRUE); INSERT INTO FarmersMarket SELECT * FROM Products WHERE is_organic = TRUE;


Question: Generate PostgreSQL SQL for: What % has 4 RLng?

CREATE TABLE table_name_80 (int_percentage VARCHAR, rlng VARCHAR)

SELECT int_percentage FROM table_name_80 WHERE rlng = '4';


Question: Generate PostgreSQL SQL for: What was the high rebounds from the date of April 14?

CREATE TABLE table_name_29 (high_rebounds VARCHAR, date VARCHAR)

SELECT high_rebounds FROM table_name_29 WHERE date = 'april 14';


Question: Generate PostgreSQL SQL for: What is the grid value which has Time/Retired value of accident?

CREATE TABLE table_name_57 (grid VARCHAR, time_retired VARCHAR)

SELECT grid FROM table_name_57 WHERE time_retired = 'accident';


Question: Find the maximum weight of containers handled daily by a single crane in 'Cairo'.

CREATE TABLE port (port_id INT, name TEXT);CREATE TABLE crane (crane_id INT, port_id INT, name TEXT);CREATE TABLE container (container_id INT, crane_id INT, weight INT, handled_at DATETIME);INSERT INTO port VALUES (11, 'Cairo');

SELECT crane.name, DATE(container.handled_at) AS handling_date, MAX(container.weight) AS heaviest_weight FROM crane JOIN port ON crane.port_id = port.port_id JOIN container ON crane.crane_id = container.crane_id WHERE port.name = 'Cairo' GROUP BY crane.name, handling_date;


Question: Which customers have the highest transaction amounts?

CREATE TABLE customers (customer_id INT, customer_name VARCHAR(20), transaction_id INT); INSERT INTO customers (customer_id, customer_name, transaction_id) VALUES (1, 'John Doe', 1), (2, 'Jane Smith', 2), (3, 'Bob Johnson', 3);

SELECT c.customer_name, SUM(t.amount) as total_amount FROM customers c JOIN transactions t ON c.transaction_id = t.transaction_id GROUP BY c.customer_name ORDER BY total_amount DESC;


Question: Show all intelligence agencies in the 'Africa' schema.

CREATE SCHEMA Africa; CREATE TABLE IntelligenceAgencies (id INT, name VARCHAR(255), location VARCHAR(255), date DATE); INSERT INTO IntelligenceAgencies (id, name, location, date) VALUES (1, 'NISA', 'Nigeria', '2013-08-01'); INSERT INTO IntelligenceAgencies (id, name, location, date) VALUES (2, 'DGSE', 'Algeria', '1989-12-12');

SELECT * FROM Africa.IntelligenceAgencies;


Question: Generate PostgreSQL SQL for: What is the total for set 2 17-25?

CREATE TABLE table_name_80 (total VARCHAR, set_2 VARCHAR)

SELECT total FROM table_name_80 WHERE set_2 = '17-25';


Question: What is the maximum number of sustainable clothing items sold in a single transaction?

CREATE TABLE Transactions (id INT, customer_id INT, items_sold INT); INSERT INTO Transactions (id, customer_id, items_sold) VALUES (1, 1, 3), (2, 2, 1), (3, 3, 2), (4, 4, 4), (5, 5, 5), (6, 6, 1);

SELECT MAX(items_sold) FROM Transactions WHERE EXISTS (SELECT 1 FROM Sales WHERE Transactions.customer_id = Sales.id AND material IN ('Organic Cotton', 'Hemp', 'Recycled Polyester', 'Tencel', 'Bamboo'));


Question: Generate PostgreSQL SQL for: When did the episode first air that had a production code of 102?

CREATE TABLE table_18335117_2 (original_air_date VARCHAR, production_code VARCHAR)

SELECT original_air_date FROM table_18335117_2 WHERE production_code = 102;


Question: How many players play games on mobile devices?

CREATE TABLE PlayerDevice (PlayerID INT, Age INT, Device VARCHAR(20)); INSERT INTO PlayerDevice (PlayerID, Age, Device) VALUES (1, 15, 'PC'), (2, 20, 'Mobile'), (3, 18, 'Tablet');

SELECT COUNT(*) FROM PlayerDevice WHERE Device = 'Mobile';


Question: Generate PostgreSQL SQL for: For each account type, find the average account balance of customers with credit score lower than 50.

CREATE TABLE customer (acc_type VARCHAR, acc_bal INTEGER, credit_score INTEGER)

SELECT AVG(acc_bal), acc_type FROM customer WHERE credit_score < 50 GROUP BY acc_type;


Question: What is the total cargo weight transported by each vessel that visited Australian ports?

CREATE TABLE cargo (id INT, vessel_name VARCHAR(255), cargo_weight INT, port VARCHAR(255), unload_date DATE); INSERT INTO cargo (id, vessel_name, cargo_weight, port, unload_date) VALUES (1, 'VesselA', 12000, 'Sydney', '2021-12-20');

SELECT vessel_name, SUM(cargo_weight) as total_weight FROM cargo WHERE port IN ('Sydney', 'Melbourne', 'Brisbane', 'Perth', 'Adelaide') GROUP BY vessel_name;


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

INSERT INTO test_io_vac_strategy SELECT i, i from generate_series(1, 4500)i;

Explanation: DML from PostgreSQL core regression test for Stats.


Question: How many farms are there in each country?

CREATE TABLE FarmCount (country VARCHAR(50), num_farms INT); INSERT INTO FarmCount (country, num_farms) VALUES ('USA', 5000), ('Canada', 4000), ('Mexico', 3000);

SELECT country, num_farms FROM FarmCount;


Question: Show production figures for wells in the Gulf of Mexico.

CREATE TABLE wells (well_id INT, country VARCHAR(50), production FLOAT); INSERT INTO wells (well_id, country, production) VALUES (1, 'USA - Gulf of Mexico', 1000), (2, 'Canada', 1500), (3, 'Norway', 800);

SELECT production FROM wells WHERE country LIKE '%Gulf of Mexico%';


Question: Which countries have the most diverse set of authors?

CREATE TABLE Authors (id INT, name TEXT, country TEXT); INSERT INTO Authors (id, name, country) VALUES (1, 'Author 1', 'United States'), (2, 'Author 2', 'Canada'), (3, 'Author 3', 'United States');

SELECT country, COUNT(DISTINCT name) as unique_authors FROM Authors GROUP BY country ORDER BY unique_authors DESC;


Question: Find the number of players for each game genre.

CREATE TABLE PlayerCount (GameID int, GameName varchar(100), Genre varchar(50), PlayerCount int); INSERT INTO PlayerCount VALUES (1, 'GameA', 'Action', 100000), (2, 'GameB', 'RPG', 120000), (3, 'GameC', 'Action', 150000), (4, 'GameD', 'Simulation', 110000);

SELECT Genre, SUM(PlayerCount) as TotalPlayers FROM PlayerCount GROUP BY Genre;


Question: Calculate the year-over-year production change for each oil field

CREATE TABLE production (id INT, field_name VARCHAR(50), year INT, qty FLOAT); INSERT INTO production (id, field_name, year, qty) VALUES (1, 'Galkynysh', 2018, 100000); INSERT INTO production (id, field_name, year, qty) VALUES (2, 'Galkynysh', 2019, 120000); INSERT INTO production (id, field_name, year, qty) VALUES (3, 'Samotlor', 2018, 110000); INSERT INTO production (id, field_name, year, qty) VALUES (4, 'Samotlor', 2019, 105000);

SELECT a.field_name, (b.qty - a.qty) / a.qty as yoy_change FROM production a JOIN production b ON a.field_name = b.field_name WHERE a.year = (YEAR(CURRENT_DATE) - 1) AND b.year = YEAR(CURRENT_DATE);


Question: What is the maximum score achieved by a student in each district?

CREATE TABLE student_mental_health (student_id INT, district_id INT, score INT); INSERT INTO student_mental_health (student_id, district_id, score) VALUES (1, 101, 80), (2, 101, 75), (3, 102, 85), (4, 102, 90), (5, 103, 65);

SELECT district_id, MAX(score) as max_score FROM student_mental_health GROUP BY district_id;


Question: Generate PostgreSQL SQL for: what is the year for the game dead space 2?

CREATE TABLE table_name_53 (year VARCHAR, game VARCHAR)

SELECT year FROM table_name_53 WHERE game = 'dead space 2';


Question: Generate PostgreSQL SQL for: What Loss had an Attendance of 17,675?

CREATE TABLE table_name_27 (loss VARCHAR, attendance VARCHAR)

SELECT loss FROM table_name_27 WHERE attendance = '17,675';


Question: What is the total number of digital assets in circulation in India as of 2022-02-01?

CREATE TABLE digital_assets (asset_name TEXT, in_circulation INTEGER, circulation_date DATE); INSERT INTO digital_assets (asset_name, in_circulation, circulation_date) VALUES ('Bitcoin', 18750000, '2022-02-01'), ('Ethereum', 115500000, '2022-02-01');

SELECT SUM(in_circulation) FROM digital_assets WHERE circulation_date = '2022-02-01' AND asset_name IN ('Bitcoin', 'Ethereum');


Question: Generate PostgreSQL SQL for: What engine has 2 points?

CREATE TABLE table_name_41 (engine_s_ VARCHAR, points VARCHAR)

SELECT engine_s_ FROM table_name_41 WHERE points = '2';


Question: Generate PostgreSQL SQL for: How many Airspeed Fleet Shadower aircraft are retired?

CREATE TABLE table_13605170_2 (retired VARCHAR, aircraft_type VARCHAR)

SELECT retired FROM table_13605170_2 WHERE aircraft_type = 'Airspeed Fleet Shadower';


Question: Generate PostgreSQL SQL for: How many games did they play in 1905?

CREATE TABLE table_name_83 (played INTEGER, years VARCHAR)

SELECT AVG(played) FROM table_name_83 WHERE years = '1905';


Question: Generate PostgreSQL SQL for: Name the home for detroit visitor and date of february 29

CREATE TABLE table_name_25 (home VARCHAR, visitor VARCHAR, date VARCHAR)

SELECT home FROM table_name_25 WHERE visitor = 'detroit' AND date = 'february 29';


Question: What is the average production rate per well for wells in the Bakken formation?

CREATE TABLE wells (well_id INT, well_name VARCHAR(255), well_type VARCHAR(255), location VARCHAR(255)); INSERT INTO wells VALUES (1, 'Well A', 'Onshore', 'Bakken Formation'); INSERT INTO wells VALUES (2, 'Well B', 'Onshore', 'Utica Shale');

SELECT AVG(production_rate) FROM (SELECT well_id, production_rate FROM well_production WHERE location LIKE 'Bakken%' ORDER BY production_rate DESC) WHERE row_number() OVER (ORDER BY production_rate DESC) <= 10;


Question: Write the DDL statement from PostgreSQL regression test 'generated_stored' (example 134).

CREATE TABLE gtest11 (a int PRIMARY KEY, b int, c int GENERATED ALWAYS AS (b * 2) STORED);

Explanation: DDL from PostgreSQL core regression test for Generated Stored.


Question: Generate PostgreSQL SQL for: Who was the constructor of the car that had a Q1 pos of less than 8 and a Q1 time of 1:15.038?

CREATE TABLE table_name_84 (constructor VARCHAR, q1_pos VARCHAR, q1_time VARCHAR)

SELECT constructor FROM table_name_84 WHERE q1_pos < 8 AND q1_time = '1:15.038';


Question: pgTAP test for Enumtap (assertion 37).

SELECT * FROM check_test(
    enums_are( array_append(___myenum('bug_status'), 'fredy') ),
    false,
    'enums_are(enums) fail',
    'Search path ' || pg_catalog.current_setting('search_path') || ' should have the correct enums',
    '    Extra types:
        bug_status
    Missing types:
        fredy'
);

Explanation: SQL assertion from pgTAP test suite for Enumtap.


Question: What is the total number of multimodal trips taken in New York City?

CREATE TABLE multimodal_trips (id INT, trips INT, city VARCHAR(50));

SELECT SUM(trips) FROM multimodal_trips WHERE city = 'New York City';


Question: Update the sustainability_score for all organic produce suppliers in the suppliers table to 90.

CREATE TABLE suppliers (id INT, name VARCHAR(255), category VARCHAR(255), sustainability_score INT);

UPDATE suppliers SET sustainability_score = 90 WHERE category = 'organic produce';


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

select jsonb_path_query('1', 'strict $.*', silent => true);

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

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


Question: Generate PostgreSQL SQL for: Who are the opponents in district California 9?

CREATE TABLE table_1341568_6 (opponent VARCHAR, district VARCHAR)

SELECT opponent FROM table_1341568_6 WHERE district = 'California 9';


Question: What is the average safety rating for vehicles manufactured in Italy and Spain?

CREATE TABLE Vehicles (ID INT, Manufacturer VARCHAR(255), SafetyRating FLOAT); INSERT INTO Vehicles (ID, Manufacturer, SafetyRating) VALUES (1, 'Ferrari', 4.5), (2, 'Lamborghini', 4.3), (3, 'Seat', 4.1), (4, 'Skoda', 4.2);

SELECT AVG(SafetyRating) FROM Vehicles WHERE Manufacturer IN ('Italy', 'Spain');


Question: Generate PostgreSQL SQL for: Of all the contestants who got voted, what is the contestant number and name of the contestant who got least votes?

CREATE TABLE votes (contestant_number VARCHAR); CREATE TABLE contestants (contestant_number VARCHAR, contestant_name VARCHAR)

SELECT T1.contestant_number, T1.contestant_name FROM contestants AS T1 JOIN votes AS T2 ON T1.contestant_number = T2.contestant_number GROUP BY T1.contestant_number ORDER BY COUNT(*) LIMIT 1;


Question: Generate PostgreSQL SQL for: Who is the opponent in the final of the Tournament of Blenheim?

CREATE TABLE table_name_42 (opponent_in_the_final VARCHAR, tournament VARCHAR)

SELECT opponent_in_the_final FROM table_name_42 WHERE tournament = 'blenheim';


Question: Create a table named 'player_achievements'

CREATE TABLE player_achievements (player_id INT, achievement_name VARCHAR(255), achievement_date DATE);


Question: What is the total installed capacity (in MW) of renewable energy projects in the state of California?

CREATE TABLE Projects (project_id INT, project_name VARCHAR(100), state VARCHAR(100), installed_capacity FLOAT);

SELECT SUM(installed_capacity) FROM Projects WHERE state = 'California';


Question: What is the average distance traveled by astrophysics research on Mars?

CREATE TABLE astrophysics_research (research_id INT, location VARCHAR(50), distance FLOAT); INSERT INTO astrophysics_research (research_id, location, distance) VALUES (1, 'Mars', 50.3), (2, 'Venus', 10.2), (3, 'Mars', 40.1), (4, 'Jupiter', 70.5), (5, 'Mars', 60.0);

SELECT AVG(distance) FROM astrophysics_research WHERE location = 'Mars';


Question: What is the total number of unsuccessful cybersecurity incidents handled by the 'Cybersecurity Response Team' in the last decade?

CREATE TABLE cybersecurity_incidents (id INT, team VARCHAR(255), success BOOLEAN, incident_date DATE);

SELECT COUNT(*) as total_unsuccessful_incidents FROM cybersecurity_incidents WHERE team = 'Cybersecurity Response Team' AND success = FALSE AND incident_date >= DATE_SUB(CURRENT_DATE, INTERVAL 10 YEAR);


Question: Find the number of unique origins for freight with a cost greater than 500.

CREATE TABLE Freight (id INT PRIMARY KEY, shipment_id INT, origin VARCHAR(50), destination VARCHAR(50), distance INT, cost FLOAT); INSERT INTO Freight (id, shipment_id, origin, destination, distance, cost) VALUES (1, 1, 'Mumbai', 'Delhi', 1400, 7200.5), (2, 2, 'Tokyo', 'Seoul', 2100, 1050.3), (3, 3, 'São Paulo', 'Buenos Aires', 1084, 542.7), (4, 4, 'Toronto', 'Montreal', 543, 271.5), (5, 5, 'Delhi', 'Mumbai', 1400, 7250.8), (6, 6, 'Mumbai', 'Kolkata', 1520, 810.9);

SELECT COUNT(DISTINCT origin) FROM Freight WHERE cost > 500;


Question: Generate PostgreSQL SQL for: Which Events is the highest one that has a Top-5 larger than 5, and a Top-10 larger than 28?

CREATE TABLE table_name_93 (events INTEGER, top_5 VARCHAR, top_10 VARCHAR)

SELECT MAX(events) FROM table_name_93 WHERE top_5 > 5 AND top_10 > 28;


Question: What is the total number of green buildings in the city of Vancouver, and what is their total floor area?

CREATE TABLE green_buildings (id INT, name VARCHAR(255), city VARCHAR(255), floor_area FLOAT, certification_date DATE);

SELECT COUNT(*) AS total_buildings, SUM(floor_area) AS total_floor_area FROM green_buildings WHERE city = 'Vancouver';


Question: What is the total number of digital assets issued by companies based in North America?

CREATE TABLE Companies (id INT, name VARCHAR(255), region VARCHAR(255)); INSERT INTO Companies (id, name, region) VALUES (1, 'CompanyA', 'North America'), (2, 'CompanyB', 'Europe');

SELECT COUNT(*) FROM Companies WHERE region = 'North America' JOIN DigitalAssets ON Companies.id = DigitalAssets.company_id;


Question: Write the DML statement from PostgreSQL regression test 'predicate' (example 36).

INSERT INTO pred_tab_notnull VALUES (3, 3);

Explanation: DML from PostgreSQL core regression test for Predicate.


Question: What is the maximum transaction amount in Florida?

CREATE TABLE clients (id INT, name TEXT, age INT, state TEXT, transaction_amount DECIMAL(10,2)); INSERT INTO clients (id, name, age, state, transaction_amount) VALUES (1, 'John Doe', 35, 'Florida', 700.00); INSERT INTO clients (id, name, age, state, transaction_amount) VALUES (2, 'Jane Smith', 40, 'Florida', 650.50);

SELECT MAX(transaction_amount) FROM clients WHERE state = 'Florida';


Question: Generate PostgreSQL SQL for: What is Competition, when Date is "January 11, 1996", when Venue is "San Diego , United States"?

CREATE TABLE table_name_72 (competition VARCHAR, date VARCHAR, venue VARCHAR)

SELECT competition FROM table_name_72 WHERE date = 'january 11, 1996' AND venue = 'san diego , united states';


Question: What is the average CO2 emission per material?

CREATE TABLE CO2Emissions (EmissionID INT, Material VARCHAR(50), CO2 DECIMAL(5,2)); INSERT INTO CO2Emissions (EmissionID, Material, CO2) VALUES (1, 'Organic Cotton', 3.50), (2, 'Hemp', 2.80), (3, 'Recycled Polyester', 4.20), (4, 'Tencel', 3.10);

SELECT Material, AVG(CO2) AS AvgCO2Emission FROM CO2Emissions GROUP BY Material;


Question: Display the total claim amount for each policy type in the month of December

CREATE TABLE claims (claim_id INT, policy_id INT, claim_amount DECIMAL(10,2), claim_date DATE, policy_type VARCHAR(20));

SELECT policy_type, SUM(claim_amount) FROM claims WHERE MONTH(claim_date) = 12 GROUP BY policy_type;


Question: Which container ships have had their capacity updated in the last month?

CREATE TABLE ship_updates (update_id INT, ship_name VARCHAR(50), capacity INT, update_date DATE); INSERT INTO ship_updates VALUES (1, 'MSC Maya', 19224, '2022-03-15'); INSERT INTO ship_updates VALUES (2, 'OOCL Hong Kong', 21413, '2022-02-20'); INSERT INTO ship_updates VALUES (3, 'Ever Given', 20000, '2022-03-08');

SELECT ship_name, update_date FROM ship_updates WHERE update_date > DATEADD(MONTH, -1, GETDATE());


Question: Find the total energy production (in MWh) from renewable energy sources for each state in the renewable_energy_production table.

CREATE TABLE renewable_energy_production (state VARCHAR(50), year INT, energy_production FLOAT, energy_source VARCHAR(50));

SELECT state, SUM(energy_production) as total_renewable_energy FROM renewable_energy_production WHERE energy_source = 'Wind' OR energy_source = 'Solar' GROUP BY state;


Question: For cases with an outcome of 'settled', find the client's first and last name, state, and the difference between the case closing date and the case opening date, in descending order by the difference.

CREATE TABLE Cases (CaseID INT, ClientFirstName VARCHAR(50), ClientLastName VARCHAR(50), State VARCHAR(2), CaseOutcome VARCHAR(20), OpenDate DATE, CloseDate DATE); INSERT INTO Cases (CaseID, ClientFirstName, ClientLastName, State, CaseOutcome, OpenDate, CloseDate) VALUES (1, 'John', 'Doe', 'NY', 'settled', '2020-01-01', '2020-06-01'), (2, 'Jane', 'Smith', 'CA', 'won', '2019-01-01', '2019-12-31');

SELECT ClientFirstName, ClientLastName, State, DATEDIFF(CloseDate, OpenDate) AS DaysOpen FROM Cases WHERE CaseOutcome = 'settled' ORDER BY DaysOpen DESC;


Question: Generate PostgreSQL SQL for: How many episodes in the series are from season 12?

CREATE TABLE table_2226817_8 (no_in_series VARCHAR, no_in_season VARCHAR)

SELECT no_in_series FROM table_2226817_8 WHERE no_in_season = 12;


Question: What is the total size of green buildings in the 'green_buildings' table?

CREATE TABLE green_buildings (id INT, size FLOAT, certification VARCHAR(255), PRIMARY KEY (id)); INSERT INTO green_buildings (id, size, certification) VALUES (1, 1200.0, 'LEED'), (2, 800.0, 'BREEAM'), (3, 1500.0, 'WELL');

SELECT SUM(size) FROM green_buildings WHERE certification IS NOT NULL;


Question: List all marine species that are found at a depth greater than 500 meters.

CREATE TABLE marine_species (id INT, name VARCHAR(255), habitat_depth INT); INSERT INTO marine_species (id, name, habitat_depth) VALUES (1, 'Clownfish', 20), (2, 'Blue Whale', 1000);

SELECT name FROM marine_species WHERE habitat_depth > 500;


Question: PostgreSQL regression test 'interval': Write the SELECT query (example 379).

SELECT interval '0 days' * 'infinity'::float;

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

SELECT count(*) FROM (SELECT interval '0 days' * 'infinity'::float) AS _sub;


Question: Create a table named 'workforce_training'

CREATE TABLE workforce_training (id INT PRIMARY KEY, employee_name VARCHAR(255), training_topic VARCHAR(255), training_hours INT, training_completion_date DATE);


Question: What was the total quantity of refrigerated cargo unloaded at the port of Long Beach in August 2021, grouped by cargo type?

CREATE TABLE ports (id INT, name VARCHAR(50)); INSERT INTO ports (id, name) VALUES (1, 'Oakland'), (2, 'Long Beach'), (3, 'Los Angeles'); CREATE TABLE cargo (id INT, port_id INT, cargo_type VARCHAR(50), temperature_type VARCHAR(50), quantity INT); INSERT INTO cargo (id, port_id, cargo_type, temperature_type, quantity) VALUES (1, 1, 'Frozen Food', 'Refrigerated', 500), (2, 1, 'Electronics', 'Non-Refrigerated', 800), (3, 2, 'Furniture', 'Non-Refrigerated', 700), (4, 2, 'Seafood', 'Refrigerated', 900), (5, 3, 'Vegetables', 'Refrigerated', 1000);

SELECT cargo_type, SUM(quantity) as total_quantity FROM cargo WHERE port_id = 2 AND temperature_type = 'Refrigerated' AND MONTH(date) = 8 GROUP BY cargo_type;


Question: What is the total population of all birds in the savannah habitat?

CREATE TABLE animals (id INT, name VARCHAR(50), species VARCHAR(50), population INT, habitat VARCHAR(50)); INSERT INTO animals (id, name, species, population, habitat) VALUES (7, 'Eagle', 'Bird', 30, 'Savannah'); INSERT INTO animals (id, name, species, population, habitat) VALUES (8, 'Ostrich', 'Bird', 50, 'Savannah');

SELECT SUM(population) FROM animals WHERE species LIKE '%Bird' AND habitat = 'Savannah';


Question: What is the total timber production for each country in 2022?

CREATE TABLE timber_production (country_code CHAR(3), year INT, volume INT); INSERT INTO timber_production (country_code, year, volume) VALUES ('IDN', 2022, 12000), ('IDN', 2021, 11000), ('JPN', 2022, 15000), ('JPN', 2021, 13000);

SELECT c.country_name, SUM(tp.volume) as total_volume FROM timber_production tp INNER JOIN country c ON tp.country_code = c.country_code WHERE tp.year = 2022 GROUP BY c.country_name;


Question: Generate PostgreSQL SQL for: How much Played has an Against larger than 11, and a Team of botafogo, and a Position smaller than 2?

CREATE TABLE table_name_57 (played VARCHAR, position VARCHAR, against VARCHAR, team VARCHAR)

SELECT COUNT(played) FROM table_name_57 WHERE against > 11 AND team = 'botafogo' AND position < 2;


Question: What is the percentage of fair trade products by manufacturer?

CREATE TABLE ManufacturerProducts (manufacturer_id INT, manufacturer_name VARCHAR(255), product_type VARCHAR(255), is_fair_trade BOOLEAN); INSERT INTO ManufacturerProducts (manufacturer_id, manufacturer_name, product_type, is_fair_trade) VALUES (1, 'EcoPure', 'Clothing', true), (2, 'GreenYarn', 'Yarn', false), (3, 'SustainableTimber', 'Furniture', true), (4, 'EthicalMinerals', 'Electronics', true), (5, 'FairTradeFabrics', 'Textiles', true), (6, 'EcoDyes', 'Dyes', false), (7, 'EcoPaints', 'Paint', true), (8, 'GreenBuilding', 'Building Materials', false);

SELECT manufacturer_name, ROUND(COUNT(*) FILTER (WHERE is_fair_trade = true) * 100.0 / COUNT(*), 2) as fair_trade_percentage FROM ManufacturerProducts GROUP BY manufacturer_name;


Question: Generate PostgreSQL SQL for: What is the Panthers' Division Record?

CREATE TABLE table_name_48 (division_record VARCHAR, team VARCHAR)

SELECT division_record FROM table_name_48 WHERE team = 'panthers';


Question: pgTAP test for Coltap (assertion 61).

SELECT * FROM check_test(
    col_has_default( 'sometab', '__asdfasdfs__', 'desc' ),
    false,
    'col_has_default( tab, col, desc )',
    'desc',
    '    Column sometab.__asdfasdfs__ does not exist'
);

Explanation: SQL assertion from pgTAP test suite for Coltap.


Question: What is the average cost of Mars rovers?

CREATE TABLE MarsRovers (name TEXT, launch_date DATE, cost INTEGER);INSERT INTO MarsRovers (name, launch_date, cost) VALUES ('Sojourner', '1996-12-04', 250000000); INSERT INTO MarsRovers (name, launch_date, cost) VALUES ('Spirit', '2003-06-10', 400000000);


Question: Generate PostgreSQL SQL for: Which Driver and passenger have a bike number of less than 4 with zabel -vmc equipment?

CREATE TABLE table_name_9 (driver___passenger VARCHAR, bike_no VARCHAR, equipment VARCHAR)

SELECT driver___passenger FROM table_name_9 WHERE bike_no < 4 AND equipment = 'zabel -vmc';


Question: Generate PostgreSQL SQL for: what is the time/retired when the laps is less than 54 and the driver is mark donohue?

CREATE TABLE table_name_35 (time_retired VARCHAR, laps VARCHAR, driver VARCHAR)

SELECT time_retired FROM table_name_35 WHERE laps < 54 AND driver = 'mark donohue';


Question: Write the DDL statement from PostgreSQL regression test 'foreign_data' (example 140).

CREATE USER MAPPING FOR public SERVER s8;

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


Question: Generate PostgreSQL SQL for: Which long version was remixed in 1986?

CREATE TABLE table_name_51 (remixed_by VARCHAR, year VARCHAR, version VARCHAR)

SELECT remixed_by FROM table_name_51 WHERE year = 1986 AND version = 'long version';


Question: How many cases were won by attorneys from the law firm 'Smith & Jones' in the last 3 years?

CREATE TABLE attorneys (attorney_id INT, law_firm VARCHAR(50), joined_date DATE); INSERT INTO attorneys (attorney_id, law_firm, joined_date) VALUES (1, 'Smith & Jones', '2015-01-01'); CREATE TABLE cases (case_id INT, attorney_id INT, case_outcome VARCHAR(10), case_date DATE); INSERT INTO cases (case_id, attorney_id, case_outcome, case_date) VALUES (1, 1, 'Won', '2020-05-01'), (2, 1, 'Lost', '2019-08-15');

SELECT COUNT(*) FROM cases JOIN attorneys ON cases.attorney_id = attorneys.attorney_id WHERE attorneys.law_firm = 'Smith & Jones' AND cases.case_date >= DATE_SUB(CURDATE(), INTERVAL 3 YEAR) AND cases.case_outcome = 'Won';


Question: What is the minimum budget for an ethical AI project?

CREATE TABLE ethical_ai_projects (id INT, project_name VARCHAR(50), budget INT); INSERT INTO ethical_ai_projects (id, project_name, budget) VALUES (1, 'Ethical AI Guidelines Development', 50000), (2, 'AI Ethics Training Program', 25000), (3, 'AI Auditing Framework Design', 75000);

SELECT MIN(budget) FROM ethical_ai_projects;


Question: How many animals are in the 'habitat_preservation' table?

CREATE TABLE habitat_preservation (id INT, habitat_name VARCHAR(50), acres FLOAT); INSERT INTO habitat_preservation (id, habitat_name, acres) VALUES (1, 'Forest', 500.5), (2, 'Wetlands', 300.2), (3, 'Grasslands', 700.1);

SELECT COUNT(*) FROM habitat_preservation;


Question: What is the average fare for buses and trains in the NYC subway system?

CREATE TABLE nyc_subway (route_type VARCHAR(10), fare DECIMAL(5,2)); INSERT INTO nyc_subway (route_type, fare) VALUES ('Bus', 2.75), ('Train', 3);

SELECT AVG(fare) FROM nyc_subway WHERE route_type IN ('Bus', 'Train');


Question: Update the water usage for California in 2020 to 10000.

CREATE TABLE water_usage(state VARCHAR(20), year INT, usage FLOAT);

UPDATE water_usage SET usage=10000 WHERE state='California' AND year=2020;


Question: Generate PostgreSQL SQL for: Who was eliminated on Banana Night?

CREATE TABLE table_name_33 (name VARCHAR, eliminated VARCHAR)

SELECT name FROM table_name_33 WHERE eliminated = 'banana night';


Question: How many members have a recorded heart rate measurement greater than 120 in September?

CREATE TABLE Members (Id INT, Age INT, Gender VARCHAR(10)); CREATE TABLE Measurements (Id INT, MemberId INT, HeartRate INT, Date DATE); INSERT INTO Members (Id, Age, Gender) VALUES (1, 25, 'Female'), (2, 32, 'Male'), (3, 45, 'Female'), (4, 28, 'Non-binary'); INSERT INTO Measurements (Id, MemberId, HeartRate, Date) VALUES (1, 1, 130, '2022-09-01'), (2, 1, 125, '2022-09-15'), (3, 2, 90, '2022-08-30'), (4, 3, 70, '2022-09-03'), (5, 4, 126, '2022-09-05');

SELECT COUNT(DISTINCT MemberId) FROM Measurements INNER JOIN Members ON Measurements.MemberId = Members.Id WHERE DATE_FORMAT(Date, '%Y-%m') = '2022-09' AND HeartRate > 120;


Question: Generate PostgreSQL SQL for: Which Rating has a Centre of helsinki?

CREATE TABLE table_name_88 (rating INTEGER, centre VARCHAR)

SELECT SUM(rating) FROM table_name_88 WHERE centre = 'helsinki';


Question: What is the total number of heritage sites and associated artifacts in each continent?

CREATE TABLE Site (SiteID INT, SiteName VARCHAR(50), Continent VARCHAR(50)); INSERT INTO Site (SiteID, SiteName, Continent) VALUES (1, 'Great Wall', 'Asia'), (2, 'Machu Picchu', 'South America'), (3, 'Easter Island', 'South America'); CREATE TABLE Artifact (ArtifactID INT, ArtifactName VARCHAR(50), SiteID INT); INSERT INTO Artifact (ArtifactID, ArtifactName, SiteID) VALUES (1, 'Watchtower', 1), (2, 'Temple of the Sun', 1), (3, 'Temple of the Moon', 1), (4, 'Llama Figurine', 2);

SELECT Continent, COUNT(DISTINCT SiteID) as SiteCount, (SELECT COUNT(*) FROM Artifact WHERE EXISTS (SELECT 1 FROM Site WHERE Site.SiteID = Artifact.SiteID AND Site.Continent = Site.Continent)) as ArtifactCount FROM Site GROUP BY Continent;


Question: What is the total assets value for customers from the USA?

CREATE TABLE customers (id INT, name TEXT, age INT, country TEXT, assets FLOAT); INSERT INTO customers (id, name, age, country, assets) VALUES (1, 'John Doe', 45, 'USA', 250000.00); INSERT INTO customers (id, name, age, country, assets) VALUES (2, 'Jane Smith', 34, 'Canada', 320000.00);

SELECT SUM(assets) FROM customers WHERE country = 'USA';


Question: Generate PostgreSQL SQL for: What is the Film title used in nomination of Cilvēka Bērns?

CREATE TABLE table_name_91 (film_title_used_in_nomination VARCHAR, original_title VARCHAR)

SELECT film_title_used_in_nomination FROM table_name_91 WHERE original_title = 'cilvēka bērns';


Question: Delete a department from the "departments" table

CREATE TABLE departments (id INT, department VARCHAR(50), manager VARCHAR(50));

DELETE FROM departments WHERE department = 'Marketing';


Question: Generate PostgreSQL SQL for: What is the highest Counties when Mitt Romney was the candidate with less than 0 delegates?

CREATE TABLE table_name_62 (counties INTEGER, candidate VARCHAR, delegates VARCHAR)

SELECT MAX(counties) FROM table_name_62 WHERE candidate = 'mitt romney' AND delegates < 0;


Question: What is the average depth at which sharks have been recorded in the Arctic Ocean?

CREATE TABLE shark_sightings (id INT, name TEXT, location TEXT, depth INT); INSERT INTO shark_sightings (id, name, location, depth) VALUES (1, 'Greenland Shark', 'Arctic Ocean', 2000), (2, 'Pacific Sleeper Shark', 'Arctic Ocean', 2500), (3, 'Basking Shark', 'Atlantic Ocean', 1000);

SELECT AVG(depth) FROM shark_sightings WHERE location = 'Arctic Ocean';


Question: Generate PostgreSQL SQL for: What is the High rebounds of a Game with 56?

CREATE TABLE table_name_70 (high_rebounds VARCHAR, game VARCHAR)

SELECT high_rebounds FROM table_name_70 WHERE game = 56;


Question: Generate PostgreSQL SQL for: List the dates of enrollment and completion of the student with personal name "Karson".

CREATE TABLE Student_Course_Enrolment (date_of_enrolment VARCHAR, date_of_completion VARCHAR, student_id VARCHAR); CREATE TABLE Students (student_id VARCHAR, personal_name VARCHAR)

SELECT T1.date_of_enrolment, T1.date_of_completion FROM Student_Course_Enrolment AS T1 JOIN Students AS T2 ON T1.student_id = T2.student_id WHERE T2.personal_name = 'Karson';


Question: What is the minimum speed recorded for vessels arriving in South Korea in August 2022?

CREATE TABLE vessel_performance (id INT, name TEXT, speed DECIMAL(5,2), arrived_date DATE, country TEXT); INSERT INTO vessel_performance (id, name, speed, arrived_date, country) VALUES (1, 'Vessel P', 12.8, '2022-08-02', 'South Korea'), (2, 'Vessel Q', 14.5, '2022-08-15', 'South Korea'), (3, 'Vessel R', 11.9, '2022-08-26', 'South Korea');

SELECT MIN(speed) FROM vessel_performance WHERE YEAR(arrived_date) = 2022 AND MONTH(arrived_date) = 8 AND country = 'South Korea';


Question: What is the total number of public meetings for each department?

CREATE TABLE PublicMeetings ( MeetingId INT, MeetingDate DATE, Department VARCHAR(255) ); INSERT INTO PublicMeetings (MeetingId, MeetingDate, Department) VALUES (1, '2021-01-01', 'Transportation'), (2, '2021-02-01', 'Education'), (3, '2021-03-01', 'Healthcare');

SELECT Department, COUNT(*) OVER (PARTITION BY Department) as TotalMeetings FROM PublicMeetings;


Question: Generate PostgreSQL SQL for: The man who received 87,676 votes in Queens won what percentage of the total for the election?

CREATE TABLE table_1108394_47 (_percentage VARCHAR, queens VARCHAR)

SELECT _percentage FROM table_1108394_47 WHERE queens = '87,676';


Question: What is the adoption rate of electric scooters in Madrid?

CREATE TABLE scooter_adoption (id INT, city VARCHAR(20), adoption_rate FLOAT); INSERT INTO scooter_adoption (id, city, adoption_rate) VALUES (1, 'Madrid', 0.2), (2, 'Barcelona', 0.15);

SELECT adoption_rate FROM scooter_adoption WHERE city = 'Madrid';


Question: Get the average number of employees for startups that have had an exit

CREATE TABLE company (id INT, name TEXT, number_of_employees INT, has_exited BOOLEAN); CREATE TABLE exit_strategies (id INT, company_id INT, exit_year INT, exit_amount INT);

SELECT AVG(number_of_employees) FROM company c INNER JOIN exit_strategies es ON c.id = es.company_id WHERE has_exited = true;


Question: Calculate veteran employment rates by state, for the past 6 months

CREATE TABLE veteran_employment (veteran_id INT, veteran_state VARCHAR(2), employment_status VARCHAR(255), employment_date DATE);

SELECT veteran_state, AVG(CASE WHEN employment_status = 'Employed' THEN 100 ELSE 0 END) as employment_rate FROM veteran_employment WHERE employment_date >= DATEADD(month, -6, CURRENT_DATE) GROUP BY veteran_state;


Question: Generate PostgreSQL SQL for: What place is South Africa?

CREATE TABLE table_name_99 (place VARCHAR, country VARCHAR)

SELECT place FROM table_name_99 WHERE country = 'south africa';


Question: Update labor_statistics table and set hourly_wage = 30.50 for all records where job_category is 'Carpentry'

CREATE TABLE labor_statistics (id INT, job_category VARCHAR(20), hourly_wage DECIMAL(5,2));

UPDATE labor_statistics SET hourly_wage = 30.50 WHERE job_category = 'Carpentry';


Question: Generate PostgreSQL SQL for: Find all the rooms that have a price higher than 160 and can accommodate more than 2 people. Report room names and ids.

CREATE TABLE Rooms (roomName VARCHAR, RoomId VARCHAR, basePrice VARCHAR, maxOccupancy VARCHAR)

SELECT roomName, RoomId FROM Rooms WHERE basePrice > 160 AND maxOccupancy > 2;


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

SELECT nummultirange(numrange(1,2)) + nummultirange();

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

SELECT count(*) FROM (SELECT nummultirange(numrange(1,2)) + nummultirange()) AS _sub;


Question: PostgreSQL regression test 'oid8': Write the SELECT query (example 36).

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

SELECT count(*) FROM (SELECT 1::int4::oid8) AS _sub;


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

INSERT INTO num_exp_mul VALUES (3,0,'0');

Explanation: DML from PostgreSQL core regression test for Numeric.


Question: List all countries with their respective number of marine species in danger.

CREATE TABLE countries (country_name TEXT, country_code TEXT); CREATE TABLE marine_species (species_name TEXT, country_code TEXT, status TEXT); INSERT INTO countries (country_name, country_code) VALUES ('Australia', 'AU'), ('Brazil', 'BR'), ('Indonesia', 'ID'); INSERT INTO marine_species (species_name, country_code, status) VALUES ('Clownfish', 'AU', 'endangered'), ('Seahorse', 'BR', 'endangered'), ('Manta Ray', 'ID', 'endangered');

SELECT countries.country_name, COUNT(marine_species.species_name) FROM countries INNER JOIN marine_species ON countries.country_code = marine_species.country_code WHERE marine_species.status = 'endangered' GROUP BY countries.country_name;


Question: Generate PostgreSQL SQL for: What is the company from Greece with author Aeschylus?

CREATE TABLE table_name_45 (company VARCHAR, country VARCHAR, author VARCHAR)

SELECT company FROM table_name_45 WHERE country = 'greece' AND author = 'aeschylus';


Question: What is the total number of marine species observed in the Pacific and Atlantic oceans, grouped by year?

CREATE TABLE MarineSpeciesObservations (observation_id INT, species VARCHAR(255), location VARCHAR(255), year INT); INSERT INTO MarineSpeciesObservations (observation_id, species, location, year) VALUES (1, 'Dolphin', 'Pacific Ocean', 2020); INSERT INTO MarineSpeciesObservations (observation_id, species, location, year) VALUES (2, 'Shark', 'Atlantic Ocean', 2019);

SELECT year, COUNT(*) FROM MarineSpeciesObservations WHERE location IN ('Pacific Ocean', 'Atlantic Ocean') GROUP BY year;


Question: How many broadband customers does the Tokyo regional office have?

CREATE TABLE broadband_subscribers (subscriber_id INT, regional_office VARCHAR(20)); INSERT INTO broadband_subscribers (subscriber_id, regional_office) VALUES (1, 'Boston'), (2, 'Boston'), (3, 'Tokyo'), (4, 'NYC'), (5, 'Tokyo');

SELECT COUNT(*) FROM broadband_subscribers WHERE regional_office = 'Tokyo';


Question: Generate PostgreSQL SQL for: What is the number of points for the maserati straight-4 engine, later than 1959?

CREATE TABLE table_name_94 (points VARCHAR, engine VARCHAR, year VARCHAR)

SELECT COUNT(points) FROM table_name_94 WHERE engine = 'maserati straight-4' AND year > 1959;


Question: Generate PostgreSQL SQL for: Show all advisors who have at least two students.

SELECT advisor FROM Student GROUP BY advisor HAVING COUNT(*) >= 2;


Question: Create a table named 'routes' with columns 'route_id', 'name', 'type'

CREATE TABLE routes (route_id INT, name VARCHAR(255), type VARCHAR(255));


Question: Generate PostgreSQL SQL for: what is the sum of games played when the losses is less than 7, the wins is 6 and the goals for is more than 76?

CREATE TABLE table_name_31 (games_played INTEGER, goals_for VARCHAR, losses VARCHAR, wins VARCHAR)

SELECT SUM(games_played) FROM table_name_31 WHERE losses < 7 AND wins = 6 AND goals_for > 76;


Question: List all environmental impact assessments from 2019.

CREATE TABLE environmental_assessments (assessment_id INT, assessment_date DATE); INSERT INTO environmental_assessments VALUES (1, '2019-04-01'); INSERT INTO environmental_assessments VALUES (2, '2018-09-20'); INSERT INTO environmental_assessments VALUES (3, '2020-12-15');

SELECT * FROM environmental_assessments WHERE assessment_date >= '2019-01-01' AND assessment_date < '2020-01-01';


Question: Generate PostgreSQL SQL for: What is the average Total, when Nation is Soviet Union, and when Gold is greater than 9?

CREATE TABLE table_name_33 (total INTEGER, nation VARCHAR, gold VARCHAR)

SELECT AVG(total) FROM table_name_33 WHERE nation = 'soviet union' AND gold > 9;


Question: Which autonomous driving research projects received funding from the US government in 2021 and 2022?

CREATE TABLE Research_Project (id INT, name VARCHAR(50), type VARCHAR(20), country VARCHAR(10), start_year INT, end_year INT); INSERT INTO Research_Project (id, name, type, country, start_year, end_year) VALUES (1, 'Project A', 'Autonomous Driving', 'USA', 2021, 2023), (2, 'Project B', 'Electric Vehicles', 'China', 2020, 2022), (3, 'Project C', 'Autonomous Driving', 'Germany', 2022, 2025);

SELECT name FROM Research_Project WHERE type = 'Autonomous Driving' AND country = 'USA' AND start_year BETWEEN 2021 AND 2022;


Question: Generate PostgreSQL SQL for: What is the format for the album under the label, luaka bop, that had a catalog number of 3645 and dated after 1981?

CREATE TABLE table_name_15 (format VARCHAR, label VARCHAR, catalog VARCHAR, date VARCHAR)

SELECT format FROM table_name_15 WHERE catalog = '3645' AND date > 1981 AND label = 'luaka bop';


Question: Generate PostgreSQL SQL for: What is the draw when the tries against was 69?

CREATE TABLE table_name_75 (drawn VARCHAR, tries_against VARCHAR)

SELECT drawn FROM table_name_75 WHERE tries_against = '69';


Question: Show a query using PostgreSQL contrib extension 'ltree' (example 177).

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


Question: Show a SQL definition from the timescaledb project (compat, item 13).

CREATE OR REPLACE FUNCTION _timescaledb_internal.create_compressed_chunk(chunk regclass,chunk_table regclass,uncompressed_heap_size bigint,uncompressed_toast_size bigint,uncompressed_index_size bigint,compressed_heap_size bigint,compressed_toast_size bigint,compressed_index_size bigint,numrows_pre_compression bigint,numrows_post_compression bigint) RETURNS regclass LANGUAGE PLPGSQL AS $$
BEGIN
  IF current_setting('timescaledb.enable_deprecation_warnings', true)::bool THEN
    RAISE WARNING 'function _timescaledb_internal.create_compressed_chunk(regclass,regclass,bigint,bigint,bigint,bigint,bigint,bigint,bigint,bigint) is deprecated and has been moved to _timescaledb_functions schema. this compatibility function will be removed in a future version.';
  END IF;
  RETURN _timescaledb_functions.create_compressed_chunk($1,$2,$3,$4,$5,$6,$7,$8,$9,$10);
END$$
SET search_path TO pg_catalog,pg_temp;

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


Question: PL/pgSQL test: Plperlu--1.0 (example 4).

CREATE LANGUAGE plperlu
  HANDLER plperlu_call_handler
  INLINE plperlu_inline_handler
  VALIDATOR plperlu_validator;

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


Question: What is the average volume of timber harvested per year, per species?

SELECT species, AVG(volume) as avg_volume FROM forests GROUP BY species;


Question: What is the total carbon sequestration of all the trees in the Trees table, if each tree sequesters 48.19 pounds of carbon per year on average?

CREATE TABLE Trees (id INT, species VARCHAR(255), age INT); INSERT INTO Trees (id, species, age) VALUES (1, 'Oak', 50), (2, 'Pine', 30), (3, 'Maple', 40);