Question: Generate PostgreSQL SQL for: What AP increase has an AP duration of 0.75?

CREATE TABLE table_name_68 (ap_increase__mv_ VARCHAR, ap_duration__ms_ VARCHAR)

SELECT ap_increase__mv_ FROM table_name_68 WHERE ap_duration__ms_ = '0.75';


Question: Insert new donor records for the first quarter of 2023.

CREATE TABLE Donors (DonorID int, FirstName varchar(50), LastName varchar(50)); INSERT INTO Donors (DonorID, FirstName, LastName) VALUES (1, 'John', 'Doe'), (2, 'Jane', 'Doe');

INSERT INTO Donors (DonorID, FirstName, LastName) VALUES (3, 'Mohammad', 'Ali'), (4, 'Hanako', 'Yamada'), (5, 'Leonel', 'Messi');


Question: Generate PostgreSQL SQL for: What is the height of player James Stanton?

CREATE TABLE table_name_63 (height VARCHAR, name VARCHAR)

SELECT height FROM table_name_63 WHERE name = 'james stanton';


Question: Generate PostgreSQL SQL for: give me names of all compatible browsers and accelerators in the descending order of compatible year

CREATE TABLE accelerator_compatible_browser (browser_id VARCHAR, accelerator_id VARCHAR, compatible_since_year VARCHAR); CREATE TABLE web_client_accelerator (name VARCHAR, id VARCHAR); CREATE TABLE browser (name VARCHAR, id VARCHAR)

SELECT T2.name, T3.name FROM accelerator_compatible_browser AS T1 JOIN browser AS T2 ON T1.browser_id = T2.id JOIN web_client_accelerator AS T3 ON T1.accelerator_id = T3.id ORDER BY T1.compatible_since_year DESC;


Question: How many animals were admitted to the rescue center in the 'Forest' region?;

CREATE TABLE rescue_center (id INT, animal_name VARCHAR(50), date_admitted DATE, region VARCHAR(20)); INSERT INTO rescue_center (id, animal_name, date_admitted, region) VALUES (1, 'Fox', '2021-01-05', 'Mountain'); INSERT INTO rescue_center (id, animal_name, date_admitted, region) VALUES (2, 'Eagle', '2021-06-10', 'Forest'); INSERT INTO rescue_center (id, animal_name, date_admitted, region) VALUES (3, 'Bear', '2021-07-15', 'Mountain');

SELECT COUNT(animal_name) FROM rescue_center WHERE region = 'Forest';


Question: List all network towers in the state of New York that have experienced outages in the past month.

CREATE TABLE network_towers (tower_id INT, location VARCHAR(50), last_outage DATE); INSERT INTO network_towers (tower_id, location, last_outage) VALUES (1, 'New York City', '2022-01-15'); INSERT INTO network_towers (tower_id, location, last_outage) VALUES (2, 'Buffalo', '2022-02-03');

SELECT * FROM network_towers WHERE last_outage >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH) AND state = 'New York';


Question: Insert new records into the 'climate_finance' table with the following details: (1, 'Bilateral', 'Kenya', 25000)

CREATE TABLE climate_finance (id INT, funding_source VARCHAR(255), country VARCHAR(255), amount FLOAT);

INSERT INTO climate_finance (id, funding_source, country, amount) VALUES (1, 'Bilateral', 'Kenya', 25000);


Question: Display the number of marine protected areas and their total size in the Arctic region.

CREATE TABLE marine_protected_areas (id INT, name VARCHAR(50), size FLOAT, ocean VARCHAR(20)); INSERT INTO marine_protected_areas (id, name, size, ocean) VALUES (1, 'Northwest Passage', 123000, 'Arctic'); INSERT INTO marine_protected_areas (id, name, size, ocean) VALUES (2, 'Arctic National Wildlife Refuge', 780000, 'Arctic');

SELECT COUNT(*), SUM(size) FROM marine_protected_areas WHERE ocean = 'Arctic';


Question: Generate PostgreSQL SQL for: What is Release Date, when Format is CD, and when Title is Tsar Wars?

CREATE TABLE table_name_84 (release_date VARCHAR, format VARCHAR, title VARCHAR)

SELECT release_date FROM table_name_84 WHERE format = 'cd' AND title = 'tsar wars';


Question: pgTAP test for Inheritance (assertion 18).

SELECT * FROM check_test(
    has_inherited_tables( 'nonesuch', 'Gimme more' ),
    false,
    'has_inherited_tables(nonesuch, desc)',
    'Gimme more',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Inheritance.


Question: Which landfills have a capacity over 100000 tons in 'landfill' table?

CREATE TABLE landfill (name VARCHAR(50), capacity INT);

SELECT * FROM landfill WHERE capacity > 100000;


Question: What is the maximum number of games played by users from Canada?

CREATE TABLE Players (PlayerID INT, PlayerName VARCHAR(50), Country VARCHAR(50), GamesPlayed INT); INSERT INTO Players (PlayerID, PlayerName, Country, GamesPlayed) VALUES (1, 'John Doe', 'USA', 100), (2, 'Jane Smith', 'Canada', 80), (3, 'Taro Yamada', 'Japan', 70), (4, 'Hana Nakamura', 'Japan', 60);

SELECT MAX(GamesPlayed) FROM Players WHERE Country = 'Canada';


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

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


Question: What is the top donor by total donation amount?

CREATE TABLE donors (id INT, donor_name VARCHAR(50), total_donations DECIMAL(10, 2)); INSERT INTO donors (id, donor_name, total_donations) VALUES (1, 'John Doe', 500.00); INSERT INTO donors (id, donor_name, total_donations) VALUES (2, 'Jane Smith', 300.00);

SELECT donor_name, total_donations FROM donors ORDER BY total_donations DESC LIMIT 1;


Question: What is the total number of games played by FC Barcelona?

CREATE TABLE teams (id INT, name TEXT, city TEXT, league TEXT); INSERT INTO teams (id, name, city, league) VALUES (3, 'FC Barcelona', 'Barcelona', 'La Liga'); CREATE TABLE games (id INT, home_team_id INT, away_team_id INT);

SELECT COUNT(*) FROM games WHERE home_team_id = (SELECT id FROM teams WHERE name = 'FC Barcelona' AND city = 'Barcelona') OR away_team_id = (SELECT id FROM teams WHERE name = 'FC Barcelona' AND city = 'Barcelona');


Question: Generate PostgreSQL SQL for: How many schools have some students playing in goalie and mid positions.

CREATE TABLE tryout (cName VARCHAR, pPos VARCHAR)

SELECT COUNT(*) FROM (SELECT cName FROM tryout WHERE pPos = 'goalie' INTERSECT SELECT cName FROM tryout WHERE pPos = 'mid');


Question: List all the co-owned properties in Oakland, CA and their owners.

CREATE TABLE properties (id INT, city VARCHAR(50), price INT); CREATE TABLE co_owners (property_id INT, owner_name VARCHAR(50)); INSERT INTO properties (id, city, price) VALUES (1, 'Oakland', 500000), (2, 'San Francisco', 700000); INSERT INTO co_owners (property_id, owner_name) VALUES (1, 'Alice'), (1, 'Bob'), (2, 'Charlie');

SELECT properties.city, co_owners.owner_name FROM properties INNER JOIN co_owners ON properties.id = co_owners.property_id WHERE properties.city = 'Oakland';


Question: What is the number of donations made by first-time donors from the United Kingdom?

CREATE TABLE Donations (DonationID int, DonorID int, DonationDate date);

SELECT COUNT(*) FROM Donations D INNER JOIN (SELECT DISTINCT DonorID FROM Donations WHERE YEAR(DonationDate) = YEAR(CURRENT_DATE) - 1) FD ON D.DonorID = FD.DonorID WHERE Country = 'UK';


Question: PostgreSQL regression test 'regex': Write the SELECT query (example 24).

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

SELECT count(*) FROM (select regexp_matches('a', 'a(?!b)b*')) AS _sub;


Question: What is the average age of all animals in the 'animal_profiles' table?

CREATE TABLE animal_profiles (id INT, animal_name VARCHAR(50), age INT, species_id INT); INSERT INTO animal_profiles (id, animal_name, age, species_id) VALUES (1, 'Tiger', 5, 1001), (2, 'Polar Bear', 12, 1002), (3, 'Giant Panda', 8, 1003);


Question: Generate PostgreSQL SQL for: What is the venue where the home team is Footscray?

CREATE TABLE table_name_57 (venue VARCHAR, home_team VARCHAR)

SELECT venue FROM table_name_57 WHERE home_team = 'footscray';


Question: Generate PostgreSQL SQL for: What is the percentage where males equal 99?

CREATE TABLE table_name_35 (percentage___percentage_ VARCHAR, males VARCHAR)

SELECT percentage___percentage_ FROM table_name_35 WHERE males = '99';


Question: Generate PostgreSQL SQL for: Which Laps have Points of 29?

CREATE TABLE table_name_23 (laps VARCHAR, points VARCHAR)

SELECT laps FROM table_name_23 WHERE points = 29;


Question: List all countries involved in satellite launches?

CREATE TABLE SatelliteLaunches (id INT, launch_country VARCHAR(50), launch_site VARCHAR(50));  CREATE TABLE Countries (id INT, name VARCHAR(50), code VARCHAR(3));

SELECT DISTINCT SatelliteLaunches.launch_country  FROM SatelliteLaunches  JOIN Countries ON SatelliteLaunches.launch_country = Countries.name;


Question: Generate PostgreSQL SQL for: In what year was 1.35% the average vote per candidate?

CREATE TABLE table_28819393_1 (year VARCHAR, average__percentage_of_vote_per_candidate VARCHAR)

SELECT year FROM table_28819393_1 WHERE average__percentage_of_vote_per_candidate = '1.35';


Question: What is the average yield of crops grown by female farmers?

CREATE TABLE Farmers (id INT, name VARCHAR(50), age INT, gender VARCHAR(10), location VARCHAR(50)); INSERT INTO Farmers (id, name, age, gender, location) VALUES (1, 'John Doe', 35, 'Male', 'USA'); INSERT INTO Farmers (id, name, age, gender, location) VALUES (2, 'Jane Smith', 40, 'Female', 'Canada'); CREATE TABLE Crops (id INT, farmer_id INT, crop_name VARCHAR(50), yield INT, price FLOAT); INSERT INTO Crops (id, farmer_id, crop_name, yield, price) VALUES (1, 1, 'Corn', 120, 2.5); INSERT INTO Crops (id, farmer_id, crop_name, yield, price) VALUES (2, 2, 'Wheat', 150, 3.2);

SELECT AVG(c.yield) AS average_yield FROM Crops c JOIN Farmers f ON c.farmer_id = f.id WHERE f.gender = 'Female';


Question: Generate PostgreSQL SQL for: What nation are carolina hermann / daniel hermann from?

CREATE TABLE table_name_64 (nation VARCHAR, name VARCHAR)

SELECT nation FROM table_name_64 WHERE name = 'carolina hermann / daniel hermann';


Question: Generate PostgreSQL SQL for: What's the date in the United Kingdom having a catalog of reveal50cd/lp?

CREATE TABLE table_name_3 (date VARCHAR, catalog VARCHAR, region VARCHAR)

SELECT date FROM table_name_3 WHERE catalog = 'reveal50cd/lp' AND region = 'united kingdom';


Question: Which dishes have a higher price than their average rating?

CREATE TABLE dishes (id INT, name TEXT, type TEXT, cost FLOAT); INSERT INTO dishes (id, name, type, cost) VALUES (1, 'Quinoa Salad', 'vegetarian', 7.50), (2, 'Chickpea Curry', 'vegetarian', 9.25), (3, 'Beef Stew', 'non-vegetarian', 12.00); CREATE TABLE orders (id INT, dish_id INT, customer_id INT, rating INT); INSERT INTO orders (id, dish_id, customer_id, rating) VALUES (1, 1, 101, 8), (2, 2, 102, 9), (3, 3, 103, 7), (4, 1, 104, 10), (5, 2, 105, 6);

SELECT d.name, d.cost, o.rating FROM dishes d INNER JOIN orders o ON d.id = o.dish_id WHERE d.cost > o.rating;


Question: Generate PostgreSQL SQL for: What Name has a Time of 01:56:52?

CREATE TABLE table_name_46 (name VARCHAR, time VARCHAR)

SELECT name FROM table_name_46 WHERE time = '01:56:52';


Question: Generate PostgreSQL SQL for: What date was the Competition of europe/africa zone, group i, round robin, with a result of loss, in Antalya, and a Score of 1–2?

CREATE TABLE table_name_19 (date VARCHAR, score VARCHAR, location VARCHAR, competition VARCHAR, result VARCHAR)

SELECT date FROM table_name_19 WHERE competition = 'europe/africa zone, group i, round robin' AND result = 'loss' AND location = 'antalya' AND score = '1–2';


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

-- ************************************************************
-- * AFTER UPDATE on PField
-- *	- Let PSlots of this field follow
-- ************************************************************
create function tg_pfield_au() returns trigger as '
begin
    if new.name != old.name then
        update PSlot set pfname = new.name where pfname = old.name;

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


Question: Identify players who experienced a decrease in performance

CREATE TABLE playerperformances (player_id INT, game_id INT, match_date DATE, kills INT, deaths INT); INSERT INTO playerperformances (player_id, game_id, match_date, kills, deaths) VALUES (1, 1001, '2022-01-01', 25, 10);

SELECT player_id, LAG(kills, 1) OVER (PARTITION BY player_id ORDER BY match_date) as prev_kills, deaths, prev_kills - deaths as performance_change FROM playerperformances;


Question: What is the earliest therapy session date?

CREATE TABLE therapy_sessions (id INT, patient_id INT, session_date DATE);

SELECT MIN(session_date) FROM therapy_sessions;


Question: Update the name column in the programs table to set the value to 'Housing Assistance' for the record with id = 2.

CREATE TABLE programs (id INT, name VARCHAR(50)); INSERT INTO programs (id, name) VALUES (1, 'Education Support'), (2, 'Food Assistance'), (3, 'Health Services');

UPDATE programs SET name = 'Housing Assistance' WHERE id = 2;


Question: Generate PostgreSQL SQL for: What is the highest attendance for the opponents Club Brugge in Venue A?

CREATE TABLE table_name_64 (attendance INTEGER, opponent VARCHAR, venue VARCHAR)

SELECT MAX(attendance) FROM table_name_64 WHERE opponent = 'club brugge' AND venue = 'a';


Question: List all healthcare facilities in rural Montana, along with the number of doctors and nurses employed at each facility.

CREATE TABLE healthcare_facilities (id INT, name VARCHAR(100), location VARCHAR(50), num_doctors INT, num_nurses INT); INSERT INTO healthcare_facilities (id, name, location, num_doctors, num_nurses) VALUES (1, 'Rural Clinic', 'Montana', 5, 10);

SELECT healthcare_facilities.name, healthcare_facilities.num_doctors, healthcare_facilities.num_nurses FROM healthcare_facilities WHERE healthcare_facilities.location = 'Montana';


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

select count(*) from test_multirange_gist where mr >> int4range(100,500);

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

SELECT count(*) FROM (select count(*) from test_multirange_gist where mr >> int4range(100,500)) AS _sub;


Question: Generate PostgreSQL SQL for: What Player's To par is −6?

CREATE TABLE table_name_54 (player VARCHAR, to_par VARCHAR)

SELECT player FROM table_name_54 WHERE to_par = '−6';


Question: What is the minimum age of patients diagnosed with anxiety in Germany?

CREATE TABLE patient_diagnosis (patient_id INT, age INT, condition VARCHAR(255), country VARCHAR(255)); INSERT INTO patient_diagnosis (patient_id, age, condition, country) VALUES (1, 25, 'Anxiety', 'Germany'); INSERT INTO patient_diagnosis (patient_id, age, condition, country) VALUES (2, 30, 'Depression', 'Germany');

SELECT MIN(age) FROM patient_diagnosis WHERE condition = 'Anxiety' AND country = 'Germany';


Question: Which public transportation system has the highest ridership in 'New York'?

CREATE TABLE public.public_transit_ridership(id serial PRIMARY KEY, system varchar(255), location varchar(255), ridership int);

SELECT system, MAX(ridership) FROM public.public_transit_ridership WHERE location = 'New York' GROUP BY system;


Question: Generate PostgreSQL SQL for: Name the population in 1931 for lubelskie

CREATE TABLE table_14245_3 (population__1931__in_1 VARCHAR, voivodeship_or_city VARCHAR)

SELECT population__1931__in_1, 000 AS s FROM table_14245_3 WHERE voivodeship_or_city = 'lubelskie';


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

INSERT INTO num_input_test(n1) VALUES ('555.50');

Explanation: DML from PostgreSQL core regression test for Numeric.


Question: What is the wastewater treatment capacity for each state?

CREATE TABLE wastewater_treatment(state VARCHAR(20), treatment_capacity INT); INSERT INTO wastewater_treatment VALUES('New York', 50000), ('Texas', 40000);

SELECT state, treatment_capacity FROM wastewater_treatment;


Question: Add a new marine life research station named 'Station C' in the Indian region.

CREATE TABLE marine_life_research_stations (station_id INT, station_name TEXT, region TEXT);

INSERT INTO marine_life_research_stations (station_id, station_name, region) VALUES ((SELECT MAX(station_id) + 1 FROM marine_life_research_stations), 'Station C', 'Indian');


Question: pgTAP test for Check (assertion 16).

SELECT * FROM check_test(
    col_has_check( 'public', 'sometab', 'id', 'public.sometab.id should have a check' ),
    false,
    'col_has_check( sch, tab, col, desc ) fail',
    'public.sometab.id should have a check',
    '        have: {name}
              {numb,myint}
        want: {id}'
);

Explanation: SQL assertion from pgTAP test suite for Check.


Question: Obtain maintenance activities on specific equipment types

CREATE TABLE equipment_maintenance (equipment_id INT, equipment_type VARCHAR(50), maintenance_date DATE, vendor_name VARCHAR(100), maintenance_type VARCHAR(50)); INSERT INTO equipment_maintenance (equipment_id, equipment_type, maintenance_date, vendor_name, maintenance_type) VALUES (1001, 'Fighter Jet', '2019-12-05', 'DEF Contractors', 'Preventive'); INSERT INTO equipment_maintenance (equipment_id, equipment_type, maintenance_date, vendor_name, maintenance_type) VALUES (1002, 'Tank', '2020-03-20', 'GHI Services', 'Corrective');

SELECT * FROM equipment_maintenance WHERE equipment_type IN ('Fighter Jet', 'Tank');


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

SELECT nummultirange(numrange(8,9)) <@ numrange(1,5);

SELECT count(*) FROM (SELECT nummultirange(numrange(8,9)) <@ numrange(1,5)) AS _sub;


Question: What is the ranking of customer preferences for each cosmetic product?

CREATE TABLE customer_preferences (customer_id INT, product_id INT, preference_score INT); INSERT INTO customer_preferences (customer_id, product_id, preference_score) VALUES (1, 1, 90), (1, 2, 70), (2, 1, 80), (2, 2, 85), (3, 1, 50), (3, 2, 95), (4, 1, 90), (4, 2, 80), (5, 1, 60), (5, 2, 90);

SELECT customer_id, product_id, preference_score, RANK() OVER (PARTITION BY product_id ORDER BY preference_score DESC) as preference_rank FROM customer_preferences;


Question: Which chemical compounds have been used in safety protocols since 2020-01-01?

CREATE TABLE safety_protocols (id INT, compound_name VARCHAR(255), last_use DATE); INSERT INTO safety_protocols (id, compound_name, last_use) VALUES (1, 'Compound A', '2019-12-31'), (2, 'Compound B', '2020-03-05'), (3, 'Compound C', '2018-11-17');

SELECT compound_name FROM safety_protocols WHERE last_use >= '2020-01-01';


Question: How many wells were drilled in 'Nigeria' in the year 2020?

CREATE TABLE OilWells (WellID VARCHAR(10), DrillYear INT, Location VARCHAR(50));

SELECT COUNT(*) FROM OilWells WHERE Location = 'Nigeria' AND DrillYear = 2020;


Question: What is the minimum oxygen level for each depth in the 'oxygen_level' table?

CREATE TABLE oxygen_level (depth INT, level FLOAT); INSERT INTO oxygen_level (depth, level) VALUES (100, 5.5), (200, 4.8);

SELECT depth, MIN(level) as min_level FROM oxygen_level GROUP BY depth;


Question: What is the average population of the regions?

CREATE TABLE regions (id INT PRIMARY KEY, region VARCHAR(50), population INT); INSERT INTO regions (id, region, population) VALUES (1, 'Middle East', 2000), (2, 'Europe', 1500), (3, 'Asia', 800);

SELECT region, AVG(population) as avg_population FROM regions GROUP BY region;


Question: What is the average project timeline for residential buildings in New York?

CREATE TABLE project_timeline (timeline_id INT, project_id INT, building_type VARCHAR(20), city VARCHAR(20), days INT); INSERT INTO project_timeline (timeline_id, project_id, building_type, city, days) VALUES (1, 301, 'Commercial', 'Chicago', 90), (2, 302, 'Residential', 'Chicago', 60), (3, 303, 'Commercial', 'New York', 120), (4, 304, 'Residential', 'New York', 75);

SELECT AVG(days) FROM project_timeline WHERE building_type = 'Residential' AND city = 'New York';


Question: How many explainable AI research papers have been published by each country in the past year, and what is the average number of papers published per country?

CREATE TABLE ExplainableAIPapers (id INT, paper_title VARCHAR(50), country VARCHAR(50), publication_date DATE); INSERT INTO ExplainableAIPapers (id, paper_title, country, publication_date) VALUES (1, 'LIME: A Unified Approach for Explaining Classifier Decisions', 'USA', '2023-01-01'), (2, 'SHAP: A Game Theoretic Approach to Explaining the Predictions of Any Machine Learning Model', 'Canada', '2023-02-01'), (3, 'Anchors: High-Precision Model-Agnostic Explanations', 'Germany', '2023-03-01'), (4, 'TreeExplainer: An Efficient Exact Algorithm for Model Agnostic Explanations', 'France', '2023-04-01'), (5, 'DeepLIFT: A Comprehensible Framework for Model-Agnostic Explanation', 'UK', '2023-05-01');

SELECT country, COUNT(*) as paper_count FROM ExplainableAIPapers WHERE publication_date >= '2022-01-01' GROUP BY country; SELECT AVG(paper_count) as avg_paper_count FROM (SELECT country, COUNT(*) as paper_count FROM ExplainableAIPapers WHERE publication_date >= '2022-01-01' GROUP BY country) as subquery;


Question: What is the number of autonomous driving research papers published each year since 2015 in the 'research_papers' table?

CREATE TABLE research_papers (title VARCHAR(100), author_country VARCHAR(50), publication_year INT);

SELECT publication_year, COUNT(*) FROM research_papers WHERE publication_year >= 2015 GROUP BY publication_year;


Question: Generate PostgreSQL SQL for: What was the day of vacancy for vitória de guimarães?

CREATE TABLE table_name_78 (date_of_vacancy VARCHAR, team VARCHAR)

SELECT date_of_vacancy FROM table_name_78 WHERE team = 'vitória de guimarães';


Question: Generate PostgreSQL SQL for: Which Opponent  has a Score of 3–6, 5–7?

CREATE TABLE table_name_52 (opponent VARCHAR, score VARCHAR)

SELECT opponent FROM table_name_52 WHERE score = '3–6, 5–7';


Question: Retrieve the number of machines of each type

CREATE TABLE machines (id INT PRIMARY KEY, name VARCHAR(255), type VARCHAR(255), status VARCHAR(255)); INSERT INTO machines (id, name, type, status) VALUES (1, 'Machine A', 'CNC', 'Operational'), (2, 'Machine B', 'Robotic Arm', 'Under Maintenance'), (3, 'Machine C', 'CNC', 'Operational'), (4, 'Machine D', 'Robotic Arm', 'Operational'), (5, 'Machine E', 'Conveyor Belt', 'Operational');

SELECT type, COUNT(*) FROM machines GROUP BY type;


Question: Generate PostgreSQL SQL for: What is the low score for the jaguar r3 chasis?

CREATE TABLE table_name_90 (points INTEGER, chassis VARCHAR)

SELECT MIN(points) FROM table_name_90 WHERE chassis = 'jaguar r3';


Question: How many marine conservation organizations were founded in the year 2000?

CREATE TABLE marine_conservation_orgs (org_name TEXT, country TEXT, year_founded INTEGER); INSERT INTO marine_conservation_orgs (org_name, country, year_founded) VALUES ('Ocean Conservancy', 'USA', 1972), ('Marine Conservation Society', 'UK', 1983), ('Coral Reef Alliance', 'USA', 1994);

SELECT COUNT(*) FROM marine_conservation_orgs WHERE year_founded = 2000;


Question: What was the production trend for all countries from 2019 to 2020?

SELECT country, year, amount, LAG(amount, 1) OVER (PARTITION BY country ORDER BY year) AS previous_year_production FROM production;


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

INSERT INTO fract_only VALUES (8, '0.00017');


Question: Delete records of customers who have not paid their bills in the last 60 days from the billing table

CREATE TABLE billing (customer_id INT, bill_amount DECIMAL(5,2), payment_date DATE);

DELETE FROM billing WHERE payment_date < (CURRENT_DATE - INTERVAL '60' DAY);


Question: Generate PostgreSQL SQL for: What year(s) was Duisburg runner-up?

CREATE TABLE table_name_81 (years_runner_up VARCHAR, team VARCHAR)

SELECT years_runner_up FROM table_name_81 WHERE team = 'duisburg';


Question: Generate PostgreSQL SQL for: What is the round for marcus howard?

CREATE TABLE table_name_32 (round INTEGER, name VARCHAR)

SELECT SUM(round) FROM table_name_32 WHERE name = 'marcus howard';


Question: Generate PostgreSQL SQL for: what amount of stations have station code is awy?

CREATE TABLE table_14688744_2 (station VARCHAR, station_code VARCHAR)

SELECT COUNT(station) FROM table_14688744_2 WHERE station_code = 'AWY';


Question: What is the total donation amount by cause in Q1 2022, presented in a pivot table?

CREATE TABLE donations (donor_id INT, donation_amount DECIMAL(10,2), donation_date DATE, cause VARCHAR(255)); INSERT INTO donations (donor_id, donation_amount, donation_date, cause) VALUES (1, 500, '2022-01-01', 'Education'); INSERT INTO donations (donor_id, donation_amount, donation_date, cause) VALUES (2, 250, '2022-01-15', 'Health'); INSERT INTO donations (donor_id, donation_amount, donation_date, cause) VALUES (3, 750, '2022-03-01', 'Environment');

SELECT cause, SUM(donation_amount) AS total_donation_amount FROM donations WHERE donation_date BETWEEN '2022-01-01' AND '2022-03-31' GROUP BY cause WITH ROLLUP;


Question: Generate PostgreSQL SQL for: Which incumbent's democratic candidate was mike carroll?

CREATE TABLE table_name_21 (incumbent VARCHAR, democratic VARCHAR)

SELECT incumbent FROM table_name_21 WHERE democratic = 'mike carroll';


Question: What is the average cargo handling time for 'Port of Santos'?

CREATE TABLE ports (id INT, name TEXT, handling_time INT); INSERT INTO ports (id, name, handling_time) VALUES (1, 'Port of Santos', 120), (2, 'Port of Oakland', 90), (3, 'Port of Singapore', 100);

SELECT AVG(handling_time) FROM ports WHERE name = 'Port of Santos';


Question: What is the total number of digital divide initiatives in Africa and South America?

CREATE TABLE digital_divide_initiatives (id INT, initiative_name VARCHAR(255), location VARCHAR(255), initiative_type VARCHAR(255));

SELECT COUNT(*) FROM digital_divide_initiatives WHERE location IN ('Africa', 'South America') AND initiative_type = 'digital divide';


Question: What are the total expenses for community development programs in Africa?

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

SELECT SUM(budget) FROM programs WHERE program_type = 'Community Development' AND country_code = 'AF';


Question: Which spacecraft has the longest duration in space?

CREATE TABLE spacecraft (id INT, name VARCHAR(255), total_days_in_space INT); INSERT INTO spacecraft (id, name, total_days_in_space) VALUES (1, 'Voyager 1', 43902), (2, 'Voyager 2', 41484), (3, 'Cassini', 13303);

SELECT name, total_days_in_space FROM spacecraft ORDER BY total_days_in_space DESC LIMIT 1;


Question: Generate PostgreSQL SQL for: What is the highest result for Jankovic at Indian Wells and round of SF?

CREATE TABLE table_name_68 (jankovic INTEGER, round VARCHAR, tournament VARCHAR)

SELECT MAX(jankovic) FROM table_name_68 WHERE round = 'sf' AND tournament = 'indian wells';


Question: Write the DML statement from PostgreSQL regression test 'subselect' (example 167).

insert into upsert values(1, 'val') on conflict (key) do update set val = 'seen with subselect ' || (select f1 from int4_tbl where f1 != 0 limit 1)::text;

Explanation: DML from PostgreSQL core regression test for Subselect.


Question: Generate PostgreSQL SQL for: Which country had an interview score of 9.40 and average of 9.44?

CREATE TABLE table_11884814_3 (country VARCHAR, interview VARCHAR, average VARCHAR)

SELECT country FROM table_11884814_3 WHERE interview = '9.40' AND average = '9.44';


Question: Create a table for employee diversity metrics and insert data on gender, race, and veteran status

CREATE TABLE diversity_metrics (id INT, employee_id INT, gender VARCHAR(50), race VARCHAR(50), veteran_status VARCHAR(50));

CREATE TABLE diversity_metrics (id INT, employee_id INT, gender VARCHAR(50), race VARCHAR(50), veteran_status VARCHAR(50)) AS SELECT * FROM (VALUES (1, 123, 'Female', 'Asian', 'No'), (2, 234, 'Male', 'Black', 'Yes'), (3, 345, 'Non-binary', 'White', 'No'), (4, 456, 'Female', 'Latinx', 'No')) AS t(id, employee_id, gender, race, veteran_status);


Question: Generate PostgreSQL SQL for: What is the method of the match in the Road fc 12 at 5:00 with less than 3 rounds, and a loss result?

CREATE TABLE table_name_72 (method VARCHAR, event VARCHAR, res VARCHAR, time VARCHAR, round VARCHAR)

SELECT method FROM table_name_72 WHERE time = '5:00' AND round < 3 AND res = 'loss' AND event = 'road fc 12';


Question: Update the title of the painting with PaintingID 1 to 'The Starry Night'.

CREATE TABLE Paintings (PaintingID INT, Title VARCHAR(50), ArtistID INT, YearCreated INT); INSERT INTO Paintings (PaintingID, Title, ArtistID, YearCreated) VALUES (1, 'Starry Night Sketch', 1, 1889);

UPDATE Paintings SET Title = 'The Starry Night' WHERE PaintingID = 1;


Question: What's the total budget for programs in arts and environment?

CREATE TABLE Programs (ProgramID INT, ProgramName TEXT, Budget DECIMAL(10,2), Category TEXT); INSERT INTO Programs (ProgramID, ProgramName, Budget, Category) VALUES (1, 'Eco Warriors', 8000.00, 'Environment');

SELECT SUM(Budget) FROM Programs WHERE Category IN ('Arts', 'Environment');


Question: Generate PostgreSQL SQL for: What was the attendance for the game where the away team was Stockport County?

CREATE TABLE table_name_1 (attendance VARCHAR, away_team VARCHAR)

SELECT attendance FROM table_name_1 WHERE away_team = 'stockport county';


Question: Generate PostgreSQL SQL for: What Venue held the Olympic games in 2012?

CREATE TABLE table_name_12 (venue VARCHAR, tournament VARCHAR, year VARCHAR)

SELECT venue FROM table_name_12 WHERE tournament = 'olympic games' AND year = 2012;


Question: Generate PostgreSQL SQL for: If seed number is 2, what is the maximum amount of points?

CREATE TABLE table_23501776_18 (points INTEGER, seed VARCHAR)

SELECT MAX(points) FROM table_23501776_18 WHERE seed = 2;


Question: PostgreSQL regression test 'explain': Write the SELECT query (example 22).

select explain_filter_to_json('explain (settings, format json) select * from int8_tbl i8') #> '{0,Settings,plan_cache_mode}';

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

SELECT count(*) FROM (select explain_filter_to_json('explain (settings, format json) select * from int8_tbl i8') #> '{0,Settings,plan_cache_mode}') AS _sub;


Question: What is the minimum assets value for customers in 'North America'?

CREATE TABLE customers (id INT, name VARCHAR(50), region VARCHAR(20), assets DECIMAL(10,2)); INSERT INTO customers (id, name, region, assets) VALUES (1, 'John Doe', 'Southwest', 50000.00), (2, 'Jane Smith', 'Northeast', 75000.00), (3, 'Michael Johnson', 'North America', 30000.00), (4, 'Sarah Lee', 'North America', 40000.00);

SELECT MIN(assets) FROM customers WHERE region = 'North America';


Question: Generate PostgreSQL SQL for: What was the outcome of the final with a partner of Brett Steven?

CREATE TABLE table_name_62 (outcome VARCHAR, partner VARCHAR)

SELECT outcome FROM table_name_62 WHERE partner = 'brett steven';


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

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

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

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


Question: Generate PostgreSQL SQL for: Which record has a time of 0:13?

CREATE TABLE table_name_87 (record VARCHAR, time VARCHAR)

SELECT record FROM table_name_87 WHERE time = '0:13';


Question: Generate PostgreSQL SQL for: Which bridge was completed in 1928?

CREATE TABLE table_name_57 (name VARCHAR, completed VARCHAR)

SELECT name FROM table_name_57 WHERE completed = '1928';


Question: Generate PostgreSQL SQL for: Tell me the competition for half marathon

CREATE TABLE table_name_70 (competition VARCHAR, notes VARCHAR)

SELECT competition FROM table_name_70 WHERE notes = 'half marathon';


Question: Generate PostgreSQL SQL for: Show the different nationalities and the number of journalists of each nationality.

CREATE TABLE journalist (Nationality VARCHAR)

SELECT Nationality, COUNT(*) FROM journalist GROUP BY Nationality;


Question: How many volunteers are there in total?

CREATE TABLE volunteers( id INT PRIMARY KEY NOT NULL, name VARCHAR(50), age INT, city VARCHAR(30), country VARCHAR(30) ); INSERT INTO volunteers (id, name, age, city, country) VALUES (1, 'John Doe', 25, 'New York', 'USA'); INSERT INTO volunteers (id, name, age, city, country) VALUES (2, 'Jane Doe', 30, 'Los Angeles', 'USA');


Question: Who are the traditional artists in Europe?

CREATE TABLE TraditionalArtists (id INT, name VARCHAR(50), country VARCHAR(50), art_form VARCHAR(50)); INSERT INTO TraditionalArtists (id, name, country, art_form) VALUES (1, 'Pablo Picasso', 'Spain', 'Cubism'); INSERT INTO TraditionalArtists (id, name, country, art_form) VALUES (2, 'Vincent van Gogh', 'Netherlands', 'Post-Impressionism');

SELECT TraditionalArtists.name FROM TraditionalArtists WHERE TraditionalArtists.country IN ('Albania', 'Andorra', 'Austria', 'Belarus', 'Belgium', 'Bosnia and Herzegovina', 'Bulgaria', 'Croatia', 'Cyprus', 'Czech Republic', 'Denmark', 'Estonia', 'Finland', 'France', 'Germany', 'Greece', 'Hungary', 'Iceland', 'Ireland', 'Italy', 'Kosovo', 'Latvia', 'Liechtenstein', 'Lithuania', 'Luxembourg', 'Malta', 'Moldova', 'Monaco', 'Montenegro', 'North Macedonia', 'Norway', 'Poland', 'Portugal', 'Romania', 'San Marino', 'Serbia', 'Slovakia', 'Slovenia', 'Spain', 'Sweden', 'Switzerland', 'The Netherlands', 'Turkey', 'Ukraine', 'United Kingdom', 'Vatican City');


Question: Generate PostgreSQL SQL for: What was the tonnage on 12 september 1942?

CREATE TABLE table_name_91 (tonnage VARCHAR, date VARCHAR)

SELECT tonnage FROM table_name_91 WHERE date = '12 september 1942';


Question: Generate PostgreSQL SQL for: WHAT IS THE ATTENDANCE WITH A READING AWAY TEAM?

CREATE TABLE table_name_24 (attendance VARCHAR, away_team VARCHAR)

SELECT attendance FROM table_name_24 WHERE away_team = 'reading';


Question: Update light intensity records for sensor 012 on 2023-03-06 to 10000 lux

CREATE TABLE LightIntensityData (date DATE, intensity INT, sensor_id INT, FOREIGN KEY (sensor_id) REFERENCES SensorData(sensor_id));

UPDATE LightIntensityData SET intensity = 10000 WHERE sensor_id = 12 AND date = '2023-03-06';


Question: What is the total revenue generated from ticket sales for each sport in the 'sales' table?

CREATE TABLE sales (sale_id INT, event VARCHAR(50), sport VARCHAR(20), price DECIMAL(5,2), quantity INT); INSERT INTO sales (sale_id, event, sport, price, quantity) VALUES (1, 'Game 1', 'Basketball', 100.00, 500); INSERT INTO sales (sale_id, event, sport, price, quantity) VALUES (2, 'Game 2', 'Soccer', 75.00, 750);

SELECT sport, SUM(price * quantity) as total_revenue FROM sales GROUP BY sport;


Question: What is the total number of clinical trials conducted by BigPharma Inc. in the United States?

CREATE TABLE clinical_trials (id INT, company VARCHAR(255), country VARCHAR(255), phase VARCHAR(255)); INSERT INTO clinical_trials (id, company, country, phase) VALUES (1, 'BigPharma Inc.', 'United States', 'Phase 3');

SELECT COUNT(*) FROM clinical_trials WHERE company = 'BigPharma Inc.' AND country = 'United States';


Question: What is the total funding received by each program type in Q1 and Q2 for the past two years, grouped by year?

CREATE TABLE programs (program_id INT, program_name VARCHAR(50), program_type VARCHAR(20)); CREATE TABLE funding (funding_id INT, program_id INT, funding_amount DECIMAL(10,2), funding_date DATE); INSERT INTO programs (program_id, program_name, program_type) VALUES (1, 'Art Education', 'Education'), (2, 'Music Education', 'Education'), (3, 'Theater Performance', 'Performance'); INSERT INTO funding (funding_id, program_id, funding_amount, funding_date) VALUES (1, 1, 5000, '2022-01-01'), (2, 2, 3000, '2021-12-01'), (3, 3, 8000, '2020-05-01');

SELECT DATEPART(yy, funding_date) AS year, program_type, SUM(funding_amount) AS total_funding FROM funding f INNER JOIN programs p ON f.program_id = p.program_id WHERE funding_date BETWEEN DATEADD(year, -2, '2022-01-01') AND '2022-06-30' GROUP BY DATEPART(yy, funding_date), program_type;


Question: What is the total amount of resources depleted by each mining site, and which sites have depleted more than 90% of their total resources?

CREATE TABLE mining_sites (id INT, site_name TEXT, total_resources_available INT);CREATE TABLE resources_depleted (site_id INT, amount_depleted INT);

SELECT s.site_name, SUM(r.amount_depleted) as total_depleted, s.total_resources_available FROM mining_sites s JOIN resources_depleted r ON s.id = r.site_id GROUP BY s.site_name HAVING SUM(r.amount_depleted) / s.total_resources_available > 0.9;


Question: Generate PostgreSQL SQL for: List the names and birthdays of the top five players in terms of potential.

CREATE TABLE Player_Attributes (player_api_id VARCHAR); CREATE TABLE Player (player_name VARCHAR, birthday VARCHAR, player_api_id VARCHAR)

SELECT DISTINCT T1.player_name, T1.birthday FROM Player AS T1 JOIN Player_Attributes AS T2 ON T1.player_api_id = T2.player_api_id ORDER BY potential DESC LIMIT 5;


Question: What is the total quantity of electronics transported by vessels that docked at the Port of Los Angeles?

CREATE TABLE Ports (PortID INT, PortName VARCHAR(100), City VARCHAR(100), Country VARCHAR(100)); INSERT INTO Ports (PortID, PortName, City, Country) VALUES (1, 'Port of Los Angeles', 'Los Angeles', 'USA'); INSERT INTO Ports (PortID, PortName, City, Country) VALUES (2, 'Port of Rotterdam', 'Rotterdam', 'Netherlands');   CREATE TABLE Vessels (VesselID INT, VesselName VARCHAR(100), VesselType VARCHAR(100), PortID INT); INSERT INTO Vessels (VesselID, VesselName, VesselType, PortID) VALUES (1, 'Ever Ace', 'Container Ship', 1);   CREATE TABLE Cargo (CargoID INT, CargoName VARCHAR(100), Quantity INT, VesselID INT); INSERT INTO Cargo (CargoID, CargoName, Quantity, VesselID) VALUES (1, 'Electronics', 10000, 1); INSERT INTO Cargo (CargoID, CargoName, Quantity, VesselID) VALUES (2, 'Vehicles', 5000, 2);   CREATE TABLE VesselPorts (VesselID INT, PortID INT); INSERT INTO VesselPorts (VesselID, PortID) VALUES (1, 1);

SELECT SUM(Cargo.Quantity) FROM Cargo INNER JOIN Vessels ON Cargo.VesselID = Vessels.VesselID INNER JOIN VesselPorts ON Vessels.VesselID = VesselPorts.VesselID WHERE VesselPorts.PortID = 1 AND Cargo.CargoName = 'Electronics';


Question: What is the average number of containers handled per day by vessels in the South China Sea in Q2 2020?

CREATE TABLE Vessel_Stats (vessel_name TEXT, location TEXT, handling_date DATE, containers_handled INTEGER); INSERT INTO Vessel_Stats (vessel_name, location, handling_date, containers_handled) VALUES ('VesselA', 'South China Sea', '2020-04-01', 50), ('VesselB', 'South China Sea', '2020-04-02', 75), ('VesselC', 'South China Sea', '2020-05-01', 65), ('VesselD', 'South China Sea', '2020-05-02', 80);

SELECT AVG(containers_handled/30.0) FROM Vessel_Stats WHERE location = 'South China Sea' AND handling_date >= '2020-04-01' AND handling_date <= '2020-06-30';


Question: Insert a new bus route from 'Tokyo' to 'Osaka' with a distance of 500 km and a fare of ¥5000.

CREATE TABLE routes (route_id INT, route_name TEXT); INSERT INTO routes (route_id, route_name) VALUES (101, 'Bus Route 101'), (102, 'Bus Route 102'), (105, 'Bus Route 105'), (501, 'Bus Route 501'), (502, 'Bus Route 502'); CREATE TABLE bus_routes (route_id INT, start_station TEXT, end_station TEXT, distance INT, fare DECIMAL);

INSERT INTO bus_routes (route_id, start_station, end_station, distance, fare) VALUES (501, 'Tokyo', 'Osaka', 500, 5000);


Question: Show an example of PostgreSQL CREATEDB (example 1).

Explanation: PostgreSQL CREATEDB command.


Question: Generate PostgreSQL SQL for: Who constructed the car with a grid over 19 that retired due to suspension?

CREATE TABLE table_name_49 (constructor VARCHAR, grid VARCHAR, time_retired VARCHAR)

SELECT constructor FROM table_name_49 WHERE grid > 19 AND time_retired = 'suspension';


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

select interval '-1 week -2147483648 days';

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

SELECT count(*) FROM (select interval '-1 week -2147483648 days') AS _sub;


Question: What is the total revenue from ticket sales for games with an attendance of more than 5000 people?

CREATE TABLE ticket_prices (ticket_id INT, game_id INT, price DECIMAL(5,2));

SELECT SUM(price * quantity) FROM ticket_sales JOIN ticket_prices ON ticket_sales.ticket_id = ticket_prices.ticket_id WHERE (SELECT COUNT(DISTINCT fan_id) FROM fans WHERE game_id = ticket_sales.game_id) > 5000;


Question: What is the minimum daily water consumption for the water treatment plant with ID 9 in the state of Colorado in 2023?

CREATE TABLE water_treatment_plant (plant_id INT, state VARCHAR(50), year INT, month INT, day INT, water_consumption FLOAT); INSERT INTO water_treatment_plant (plant_id, state, year, month, day, water_consumption) VALUES (9, 'Colorado', 2023, 1, 1, 12345.6), (9, 'Colorado', 2023, 1, 2, 23456.7), (9, 'Colorado', 2023, 1, 3, 34567.8);

SELECT MIN(water_consumption) as min_water_consumption FROM water_treatment_plant WHERE plant_id = 9 AND state = 'Colorado' AND year = 2023;


Question: Generate PostgreSQL SQL for: What is the total of the roll with a Decile of 8, and an Area of hororata?

CREATE TABLE table_name_73 (roll INTEGER, decile VARCHAR, area VARCHAR)

SELECT SUM(roll) FROM table_name_73 WHERE decile = 8 AND area = 'hororata';


Question: What are the total sales for each product category in Q1 of 2022?

CREATE TABLE sales (product_id INT, product_name VARCHAR(100), category VARCHAR(50), sale_date DATE, revenue DECIMAL(10, 2)); INSERT INTO sales (product_id, product_name, category, sale_date, revenue) VALUES (1, 'Lipstick', 'Cosmetics', '2022-01-02', 25.99), (2, 'Foundation', 'Cosmetics', '2022-01-15', 34.99);

SELECT category, SUM(revenue) AS total_sales FROM sales WHERE sale_date BETWEEN '2022-01-01' AND '2022-03-31' GROUP BY category;


Question: Generate PostgreSQL SQL for: what is the class when the quantity perserved is 0 and the quantity made is 5?

CREATE TABLE table_name_78 (class VARCHAR, quantity_preserved VARCHAR, quantity_made VARCHAR)

SELECT class FROM table_name_78 WHERE quantity_preserved = '0' AND quantity_made = '5';


Question: What was the plastic recycling rate in 2019 compared to 2017?

CREATE TABLE recycling_rates (id INT, material VARCHAR(20), year INT, recycling_rate DECIMAL(5,2)); INSERT INTO recycling_rates (id, material, year, recycling_rate) VALUES (1, 'plastic', 2017, 0.25), (2, 'plastic', 2018, 0.28), (3, 'plastic', 2019, 0.31), (4, 'paper', 2017, 0.60), (5, 'paper', 2018, 0.63), (6, 'paper', 2019, 0.66), (7, 'glass', 2017, 0.35), (8, 'glass', 2018, 0.37), (9, 'glass', 2019, 0.39);

SELECT (recycling_rate - (SELECT recycling_rate FROM recycling_rates r2 WHERE r2.material = 'plastic' AND r2.year = 2017)) FROM recycling_rates WHERE material = 'plastic' AND year = 2019;


Question: What is the difference in the average age of players who prefer using VR technology and those who do not?

CREATE TABLE PlayerAges (PlayerID INT, Age INT); INSERT INTO PlayerAges (PlayerID, Age) VALUES (1, 25), (2, 28), (3, 30), (4, 32), (5, 27); CREATE TABLE PlayerPreferences (PlayerID INT, Preference VARCHAR(50)); INSERT INTO PlayerPreferences (PlayerID, Preference) VALUES (1, 'VR'), (2, 'Non-VR'), (3, 'VR'), (4, 'Non-VR'), (5, 'Non-VR');

(SELECT AVG(PlayerAges.Age) FROM PlayerAges JOIN PlayerPreferences ON PlayerAges.PlayerID = PlayerPreferences.PlayerID WHERE PlayerPreferences.Preference = 'VR' EXCEPT SELECT AVG(PlayerAges.Age) FROM PlayerAges JOIN PlayerPreferences ON PlayerAges.PlayerID = PlayerPreferences.PlayerID WHERE PlayerPreferences.Preference = 'Non-VR');


Question: What is the average recycling rate in Mumbai over the last 3 years?

CREATE TABLE recycling_rates (city VARCHAR(50), year INT, recycling_rate DECIMAL(5,2)); INSERT INTO recycling_rates (city, year, recycling_rate) VALUES ('Mumbai', 2019, 0.55), ('Mumbai', 2020, 0.58), ('Mumbai', 2021, 0.62), ('Mumbai', 2022, 0.65);

SELECT AVG(recycling_rate) FROM recycling_rates WHERE city = 'Mumbai' AND year BETWEEN 2019 AND 2022;


Question: What is the total number of transactions and total transaction value for each investment strategy in the last month?

CREATE TABLE investment_strategies (id INT, strategy_name VARCHAR(255), account_id INT, transaction_value DECIMAL(10, 2), transaction_date DATE); INSERT INTO investment_strategies (id, strategy_name, account_id, transaction_value, transaction_date) VALUES (1, 'Conservative', 1, 50, '2022-01-01'), (2, 'Moderate', 1, 100, '2022-01-15'), (3, 'Aggressive', 2, 25, '2022-01-05'), (4, 'Conservative', 2, 75, '2022-01-30'), (5, 'Moderate', 3, 150, '2022-01-20');

SELECT s.strategy_name, COUNT(s.id) AS num_transactions, SUM(s.transaction_value) AS total_transaction_value FROM investment_strategies s WHERE s.transaction_date >= DATE_SUB(CURDATE(), INTERVAL 1 MONTH) GROUP BY s.strategy_name;


Question: What is the total budget allocated for education and healthcare in each city?

CREATE TABLE BudgetAllocation (Id INT, CityId INT, Category VARCHAR(50), Amount DECIMAL(10,2)); INSERT INTO BudgetAllocation (Id, CityId, Category, Amount) VALUES (1, 1, 'Education', 3000000), (2, 1, 'Healthcare', 4000000), (3, 2, 'Education', 6000000), (4, 2, 'Healthcare', 5000000);

SELECT CityId, Category, SUM(Amount) AS TotalBudget FROM BudgetAllocation WHERE Category IN ('Education', 'Healthcare') GROUP BY CityId, Category;


Question: Calculate the percentage of visitors who attended exhibitions in each city.

CREATE TABLE Exhibitions (id INT, city VARCHAR(20), visitor_id INT); CREATE TABLE Visitors (id INT, name VARCHAR(50));

SELECT city, 100.0 * COUNT(DISTINCT Exhibitions.visitor_id) / (SELECT COUNT(DISTINCT Visitors.id) FROM Visitors) AS pct_visitors FROM Exhibitions GROUP BY city;


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

select interval '-2147483648 months -0.1 millennium';

SELECT count(*) FROM (select interval '-2147483648 months -0.1 millennium') AS _sub;


Question: Generate PostgreSQL SQL for: What was the score of the Red Wings game when Vancouver was the home team?

CREATE TABLE table_name_71 (score VARCHAR, home VARCHAR)

SELECT score FROM table_name_71 WHERE home = 'vancouver';


Question: Generate PostgreSQL SQL for: What is the average longitude of stations that never had bike availability more than 10?

CREATE TABLE station (long INTEGER, id VARCHAR, station_id VARCHAR, bikes_available INTEGER); CREATE TABLE status (long INTEGER, id VARCHAR, station_id VARCHAR, bikes_available INTEGER)

SELECT AVG(long) FROM station WHERE NOT id IN (SELECT station_id FROM status GROUP BY station_id HAVING MAX(bikes_available) > 10);


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

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

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


Question: Generate PostgreSQL SQL for: What was the away score when North Melbourne was played?

CREATE TABLE table_name_91 (away_team VARCHAR, home_team VARCHAR)

SELECT away_team AS score FROM table_name_91 WHERE home_team = 'north melbourne';


Question: What is the minimum and maximum word count of articles in the 'article_word_count' table?

CREATE TABLE article_word_count (article_id INT, word_count INT, category VARCHAR(20)); INSERT INTO article_word_count (article_id, word_count, category) VALUES (1, 500, 'Politics'), (2, 800, 'Sports'), (3, 300, 'Politics'), (4, 1200, 'Sports');

SELECT MIN(word_count) as min_word_count, MAX(word_count) as max_word_count FROM article_word_count;


Question: Generate PostgreSQL SQL for: Name the oberliga bayern for sv sandhausen for 1986-87

CREATE TABLE table_14242137_4 (oberliga_bayern VARCHAR, oberliga_baden_württemberg VARCHAR, season VARCHAR)

SELECT oberliga_bayern FROM table_14242137_4 WHERE oberliga_baden_württemberg = 'SV Sandhausen' AND season = '1986-87';


Question: Generate PostgreSQL SQL for: Name the first elected for alabama 3

CREATE TABLE table_25030512_4 (first_elected VARCHAR, district VARCHAR)

SELECT COUNT(first_elected) FROM table_25030512_4 WHERE district = 'Alabama 3';


Question: How many satellites have been launched by each company since 2010?

CREATE TABLE satellites (id INT, company VARCHAR(50), launch_date DATE); INSERT INTO satellites (id, company, launch_date) VALUES (1, 'SpaceX', '2010-01-01'), (2, 'Blue Origin', '2015-04-29'), (3, 'SpaceX', '2018-02-06');

SELECT company, COUNT(*) as total_satellites FROM satellites WHERE YEAR(launch_date) >= 2010 GROUP BY company;


Question: Determine the average wastewater production in cubic meters for the city of Los Angeles in the month of May 2021

CREATE TABLE wastewater_production (id INT, city VARCHAR(50), production FLOAT, date DATE); INSERT INTO wastewater_production (id, city, production, date) VALUES (1, 'Los Angeles', 4500, '2021-05-01'); INSERT INTO wastewater_production (id, city, production, date) VALUES (2, 'Los Angeles', 4800, '2021-05-02');

SELECT AVG(production) FROM wastewater_production WHERE city = 'Los Angeles' AND date >= '2021-05-01' AND date <= '2021-05-31';


Question: What is the total number of startups founded by individuals who identify as LGBTQ+?

CREATE TABLE companies (id INT, name TEXT, founding_year INT, founder_identifies_as_lgbtq BOOLEAN); INSERT INTO companies (id, name, founding_year, founder_identifies_as_lgbtq) VALUES (1, 'Delta Startups', 2020, true); INSERT INTO companies (id, name, founding_year, founder_identifies_as_lgbtq) VALUES (2, 'Epsilon Enterprises', 2018, false);

SELECT COUNT(*) FROM companies WHERE founder_identifies_as_lgbtq = true;


Question: Generate PostgreSQL SQL for: Who won the gold when Kim Hyang-Mi won the bronze?

CREATE TABLE table_name_97 (gold VARCHAR, bronze VARCHAR)

SELECT gold FROM table_name_97 WHERE bronze = 'kim hyang-mi';


Question: Generate PostgreSQL SQL for: What are the goals for a lost of Involuntary suspension of Season (hurricane Rita)?

CREATE TABLE table_name_44 (goals_for VARCHAR, lost VARCHAR)

SELECT goals_for FROM table_name_44 WHERE lost = 'involuntary suspension of season (hurricane rita)';


Question: Generate PostgreSQL SQL for: what is the production in 2010 with rank of 8?

CREATE TABLE table_name_39 (rank VARCHAR)

SELECT 2010 FROM table_name_39 WHERE rank = '8';


Question: Generate PostgreSQL SQL for: What is Winning Score, when Date is 17 Jan 2010?

CREATE TABLE table_name_45 (winning_score VARCHAR, date VARCHAR)

SELECT winning_score FROM table_name_45 WHERE date = '17 jan 2010';


Question: Show the number of wells in the South Pacific that were drilled each year from 2010 to 2020.

CREATE TABLE wells_south_pacific (id INT, location VARCHAR(20), drill_date DATE);

SELECT drill_date, COUNT(*) FROM wells_south_pacific WHERE location LIKE 'South Pacific%' AND drill_date BETWEEN '2010-01-01' AND '2020-12-31' GROUP BY drill_date;


Question: What is the total funding for bioprocess engineering projects in the UK?

CREATE TABLE bioprocess_projects (id INT, project_name VARCHAR(50), location VARCHAR(50), funding_amount INT); INSERT INTO bioprocess_projects (id, project_name, location, funding_amount) VALUES (1, 'Project G', 'UK', 12000000); INSERT INTO bioprocess_projects (id, project_name, location, funding_amount) VALUES (2, 'Project H', 'USA', 10000000);

SELECT SUM(funding_amount) FROM bioprocess_projects WHERE location = 'UK' AND technology = 'Bioprocess Engineering';


Question: What is the total quantity of menu items sold in each country?

CREATE TABLE menus (menu_id INT, item VARCHAR(255), category VARCHAR(255), price DECIMAL(10, 2)); INSERT INTO menus VALUES (1, 'Chicken Wings', 'Appetizers', 12.99); INSERT INTO menus VALUES (2, 'Beef Burger', 'Entrees', 15.99); INSERT INTO menus VALUES (3, 'Chocolate Cake', 'Desserts', 8.99); CREATE TABLE sales (sale_id INT, menu_id INT, quantity INT, country VARCHAR(255));

SELECT s.country, SUM(s.quantity) as total_quantity FROM sales s GROUP BY s.country;


Question: Generate PostgreSQL SQL for: Show all locations which don't have a train station with at least 15 platforms.

CREATE TABLE station (LOCATION VARCHAR, number_of_platforms VARCHAR)

SELECT LOCATION FROM station EXCEPT SELECT LOCATION FROM station WHERE number_of_platforms >= 15;


Question: Generate PostgreSQL SQL for: Which Type has a Builder of avonside engine company, and a Number of 9?

CREATE TABLE table_name_55 (type VARCHAR, builder VARCHAR, number VARCHAR)

SELECT type FROM table_name_55 WHERE builder = 'avonside engine company' AND number = 9;


Question: Generate PostgreSQL SQL for: Name for me the tatsuhito takaiwa for Ryusuke Taguchi of taguchi (14:31)

CREATE TABLE table_name_50 (tatsuhito_takaiwa VARCHAR, ryusuke_taguchi VARCHAR)

SELECT tatsuhito_takaiwa FROM table_name_50 WHERE ryusuke_taguchi = 'taguchi (14:31)';


Question: pgTAP test for Usergroup (assertion 33).

SELECT * FROM check_test(
    is_member_of('meanies', current_user, 'whatever' ),
    true,
    'is_member_of(meanies, current_user, desc)',
    'whatever',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Usergroup.


Question: What is the average price of vegetarian dishes in the lunch category?

CREATE TABLE menu (item_id INT, name TEXT, category TEXT, is_vegetarian BOOLEAN, price FLOAT); INSERT INTO menu (item_id, name, category, is_vegetarian, price) VALUES (1, 'Chickpea Curry', 'Lunch', true, 10.5), (2, 'Chicken Tikka Masala', 'Lunch', false, 13.0), (3, 'Quinoa Salad', 'Starters', true, 7.5);

SELECT AVG(price) as avg_vegetarian_price FROM menu WHERE is_vegetarian = true AND category = 'Lunch';


Question: What is the average amount of climate finance provided by each country for renewable energy projects in 2020?

CREATE TABLE renewable_energy_projects (country VARCHAR(50), finance_amount NUMERIC(10, 2), year INT); INSERT INTO renewable_energy_projects (country, finance_amount, year) VALUES ('USA', 1500000, 2020), ('China', 2000000, 2020), ('India', 1200000, 2020);

SELECT country, AVG(finance_amount) FROM renewable_energy_projects WHERE year = 2020 GROUP BY country;


Question: Update the year of implementation for pollution control initiatives in the Arctic Ocean to 2022 if the year is older than 2010.

CREATE TABLE pollution_control_initiatives (id INT, name TEXT, location TEXT, year INT); INSERT INTO pollution_control_initiatives (id, name, location, year) VALUES (1, 'Ocean Plastic Reduction Project', 'Arctic Ocean', 2006), (2, 'Coral Reef Protection Program', 'Arctic Ocean', 2017), (3, 'Marine Life Restoration Effort', 'Arctic Ocean', 2015);

UPDATE pollution_control_initiatives SET year = 2022 WHERE location = 'Arctic Ocean' AND year < 2010;


Question: PostgreSQL regression test 'timestamp': Write the SELECT query (example 27).

SELECT timestamp 'infinity' = timestamp '+infinity' AS t;

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

SELECT count(*) FROM (SELECT timestamp 'infinity' = timestamp '+infinity' AS t) AS _sub;


Question: Generate PostgreSQL SQL for: In what format was the release from the Nebt068 catalog on April 11, 2005 in?

CREATE TABLE table_name_62 (format VARCHAR, date VARCHAR, catalog VARCHAR)

SELECT format FROM table_name_62 WHERE date = 'april 11, 2005' AND catalog = 'nebt068';


Question: Generate PostgreSQL SQL for: What is the location is the winning driver is Bill Vukovich II?

CREATE TABLE table_22670216_1 (location VARCHAR, winning_driver VARCHAR)

SELECT location FROM table_22670216_1 WHERE winning_driver = 'Bill Vukovich II';


Question: List the names of the cities where waste collection services have improved in the last 2 years based on citizen feedback.

CREATE TABLE Cities(City VARCHAR(25)); CREATE TABLE Feedback(City VARCHAR(25), Year INT, Service VARCHAR(20), Satisfaction FLOAT); INSERT INTO Cities VALUES('CityA'), ('CityB'), ('CityC'); INSERT INTO Feedback VALUES('CityA', 2020, 'Waste Collection', 4.5), ('CityA', 2021, 'Waste Collection', 4.8), ('CityB', 2020, 'Waste Collection', 3.2), ('CityB', 2021, 'Waste Collection', 3.6), ('CityC', 2020, 'Waste Collection', 4.3), ('CityC', 2021, 'Waste Collection', 4.7);

SELECT DISTINCT City FROM Feedback WHERE Service = 'Waste Collection' AND Satisfaction > 4 AND Year IN (2020, 2021) INTERSECT SELECT City FROM Cities;


Question: What is the maximum investment amount for customers in the East region?

CREATE TABLE investments (id INT, customer_id INT, amount FLOAT); INSERT INTO investments (id, customer_id, amount) VALUES (1, 1, 10000), (2, 2, 15000), (3, 3, 8000), (4, 1, 12000); CREATE TABLE customers (id INT, name VARCHAR(50), region VARCHAR(50)); INSERT INTO customers (id, name, region) VALUES (1, 'John Smith', 'East'), (2, 'Jane Doe', 'Northeast'), (3, 'Bob Johnson', 'Southeast'), (4, 'Alex Brown', 'West');

SELECT MAX(amount) FROM investments JOIN customers ON investments.customer_id = customers.id WHERE customers.region = 'East';


Question: Generate PostgreSQL SQL for: Show the document type code with fewer than 3 documents.

CREATE TABLE Documents (document_type_code VARCHAR)

SELECT document_type_code FROM Documents GROUP BY document_type_code HAVING COUNT(*) < 3;


Question: Add the following new rare earth element to the production_data table: Gadolinium with a quantity of 450 from 2020

CREATE TABLE production_data ( id INT PRIMARY KEY, year INT, refined_rare_earth_element TEXT, quantity INT );

INSERT INTO production_data (id, year, refined_rare_earth_element, quantity) VALUES (5, 2020, 'Gadolinium', 450);


Question: Generate PostgreSQL SQL for: When did Final Score of 31-7 happen?

CREATE TABLE table_name_64 (date VARCHAR, final_score VARCHAR)

SELECT date FROM table_name_64 WHERE final_score = '31-7';


Question: Generate PostgreSQL SQL for: What is the maximum, minimum and average market share of the listed browsers?

CREATE TABLE browser (market_share INTEGER)

SELECT MAX(market_share), MIN(market_share), AVG(market_share) FROM browser;


Question: List all aircraft models and their manufacturers, sorted by manufacturer name.

CREATE TABLE aircraft (id INT, model VARCHAR(255)); CREATE TABLE manufacturers (id INT, name VARCHAR(255)); INSERT INTO aircraft (id, model) VALUES (1, '737'), (2, '747'); INSERT INTO manufacturers (id, name) VALUES (1, 'Boeing'), (2, 'Airbus');

SELECT aircraft.model, manufacturers.name FROM aircraft INNER JOIN manufacturers ON aircraft.id = manufacturers.id ORDER BY manufacturers.name;


Question: How many seals are in the Arctic Ocean?

CREATE TABLE Animals (name VARCHAR(50), species VARCHAR(50), location VARCHAR(50)); INSERT INTO Animals (name, species, location) VALUES ('Seal 1', 'Seal', 'Arctic Ocean'), ('Seal 2', 'Seal', 'Arctic Ocean'), ('Walrus 1', 'Walrus', 'Arctic Ocean');

SELECT COUNT(*) FROM Animals WHERE species = 'Seal' AND location = 'Arctic Ocean';


Question: What is the total number of hours spent on open pedagogy projects by students in each gender group?

CREATE TABLE open_pedagogy_gender (student_id INT, gender TEXT, total_open_pedagogy_hours INT); INSERT INTO open_pedagogy_gender (student_id, gender, total_open_pedagogy_hours) VALUES (1, 'Female', 30), (2, 'Male', 45), (3, 'Female', 60);

SELECT gender, SUM(total_open_pedagogy_hours) FROM open_pedagogy_gender GROUP BY gender;


Question: Generate PostgreSQL SQL for: Which City has a Date of may 19, 1976?

CREATE TABLE table_name_23 (city VARCHAR, date VARCHAR)

SELECT city FROM table_name_23 WHERE date = 'may 19, 1976';


Question: Generate PostgreSQL SQL for: Find the name of bank branches that provided some loans.

CREATE TABLE loan (branch_id VARCHAR); CREATE TABLE bank (bname VARCHAR, branch_id VARCHAR)

SELECT DISTINCT T1.bname FROM bank AS T1 JOIN loan AS T2 ON T1.branch_id = T2.branch_id;


Question: Generate PostgreSQL SQL for: How many years was Audi Sport Team Joest in 3rd position?

CREATE TABLE table_name_8 (year VARCHAR, team VARCHAR, pos VARCHAR)

SELECT COUNT(year) FROM table_name_8 WHERE team = 'audi sport team joest' AND pos = '3rd';


Question: How many items were sold in each region in the last month?

CREATE TABLE sales (sale_id INT, product_id INT, quantity INT, sale_date DATE); INSERT INTO sales (sale_id, product_id, quantity, sale_date) VALUES (1, 1, 3, '2022-01-05'), (2, 2, 1, '2022-01-07'); CREATE TABLE product (product_id INT, product_name TEXT, region_id INT); INSERT INTO product (product_id, product_name, region_id) VALUES (1, 'Coca Cola', 1), (2, 'Pizza', 2); CREATE TABLE region (region_id INT, region_name TEXT); INSERT INTO region (region_id, region_name) VALUES (1, 'North'), (2, 'South');

SELECT r.region_name, SUM(s.quantity) as total_sold FROM sales s JOIN product p ON s.product_id = p.product_id JOIN region r ON p.region_id = r.region_id WHERE s.sale_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH) GROUP BY r.region_name;


Question: What is the total donation amount by day for the last week?

CREATE TABLE donations (id INT, donation_amount DECIMAL, donation_date DATE); INSERT INTO donations (id, donation_amount, donation_date) VALUES (1, 100.00, '2022-01-01'), (2, 200.00, '2022-01-05');

SELECT DATE(donation_date) as donation_day, SUM(donation_amount) as total_donations FROM donations WHERE donation_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 WEEK) GROUP BY donation_day ORDER BY donation_day;


Question: How many charging stations are there in Beijing for electric cars?

CREATE TABLE charging_stations(id INT, station_number INT, city VARCHAR(20), charger_type VARCHAR(20), operational BOOLEAN);

SELECT COUNT(*) FROM charging_stations WHERE city = 'Beijing' AND charger_type = 'DC Fast Charger' AND operational = TRUE;


Question: Generate PostgreSQL SQL for: How many courses are offered?

SELECT COUNT(DISTINCT crs_code) FROM CLASS;


Question: How many policyholders live in each state?

CREATE TABLE policyholders (id INT, policyholder_name VARCHAR(50), state VARCHAR(20)); INSERT INTO policyholders (id, policyholder_name, state) VALUES (1, 'John Doe', 'Texas'), (2, 'Jane Smith', 'California'), (3, 'Alice Johnson', 'Texas'), (4, 'Bob Brown', 'New York');

SELECT state, COUNT(*) as policyholder_count FROM policyholders GROUP BY state;


Question: Generate PostgreSQL SQL for: When Kubb is in 9th, who is in 10th?

CREATE TABLE table_17111812_1 (tenth VARCHAR, ninth VARCHAR)

SELECT tenth FROM table_17111812_1 WHERE ninth = 'Kubb';


Question: Generate PostgreSQL SQL for: Show names of actors that have appeared in musical with name "The Phantom of the Opera".

CREATE TABLE actor (Name VARCHAR, Musical_ID VARCHAR); CREATE TABLE musical (Musical_ID VARCHAR, Name VARCHAR)

SELECT T1.Name FROM actor AS T1 JOIN musical AS T2 ON T1.Musical_ID = T2.Musical_ID WHERE T2.Name = 'The Phantom of the Opera';


Question: What is the total quantity of electronics transported by the Ever Ace?

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

SELECT SUM(Cargo.Quantity) FROM Cargo WHERE Cargo.VesselID = 1 AND Cargo.CargoName = 'Electronics';


Question: What is the total number of green buildings in Africa?

CREATE TABLE Green_Buildings (id INT, region VARCHAR(20), number_of_buildings INT); INSERT INTO Green_Buildings (id, region, number_of_buildings) VALUES (1, 'Europe', 5000), (2, 'Asia', 7000), (3, 'Africa', 3000);

SELECT SUM(number_of_buildings) FROM Green_Buildings WHERE region = 'Africa';


Question: Generate PostgreSQL SQL for: What is the Manufacturer with a Fuel Type that is diesel?

CREATE TABLE table_name_9 (manufacturer VARCHAR, fuel_type VARCHAR)

SELECT manufacturer FROM table_name_9 WHERE fuel_type = 'diesel';


Question: What is the total population of vulnerable underwater species by location?

CREATE TABLE Vulnerable_Species(id INT, location VARCHAR(50), species VARCHAR(50), population INT, vulnerable_status VARCHAR(50));

SELECT location, SUM(population) AS Total_Population FROM Vulnerable_Species WHERE vulnerable_status = 'Vulnerable' GROUP BY location;


Question: Generate PostgreSQL SQL for: What date is associated with the Loss of Farrell (6-13)?

CREATE TABLE table_name_20 (date VARCHAR, loss VARCHAR)

SELECT date FROM table_name_20 WHERE loss = 'farrell (6-13)';


Question: Generate PostgreSQL SQL for: What was the score of the game with a loss of Myers (5-6)?

CREATE TABLE table_name_47 (score VARCHAR, loss VARCHAR)

SELECT score FROM table_name_47 WHERE loss = 'myers (5-6)';


Question: Generate PostgreSQL SQL for: in electorate of 83850 what is the minimum s split vote

CREATE TABLE table_15082102_3 (s_spoilt_vote INTEGER, electorate VARCHAR)

SELECT MIN(s_spoilt_vote) FROM table_15082102_3 WHERE electorate = 83850;


Question: What is the number of unique users who streamed each music festival genre?

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

SELECT g.genre, COUNT(DISTINCT u.user_id) as num_users FROM user_streams u JOIN festival_performances f ON u.artist_id = f.artist_id JOIN genre_artist g ON f.artist_id = g.artist_id GROUP BY g.genre;


Question: Generate PostgreSQL SQL for: When was the ship launched when the commissioned or completed(*) is 6 june 1864?

CREATE TABLE table_12592074_1 (launched VARCHAR, commissioned_or_completed_ VARCHAR, _ VARCHAR)

SELECT launched FROM table_12592074_1 WHERE commissioned_or_completed_ * _ = '6 June 1864';


Question: Generate PostgreSQL SQL for: tell me the total number of decile with a roll showing 251.

CREATE TABLE table_name_90 (decile VARCHAR, roll VARCHAR)

SELECT COUNT(decile) FROM table_name_90 WHERE roll = 251;


Question: Generate PostgreSQL SQL for: What is 2004, when 2005 is "Not Tier I"?

SELECT 2004 FROM table_name_31 WHERE 2005 = 'not tier i';


Question: What is the prevalence of diabetes and hypertension among patients in indigenous communities in New Mexico?

CREATE TABLE patients(id INT, name TEXT, community TEXT, diabetes BOOLEAN, hypertension BOOLEAN); INSERT INTO patients(id, name, community, diabetes, hypertension) VALUES (1, 'Patient A', 'New Mexico Indigenous', TRUE, TRUE), (2, 'Patient B', 'New Mexico Indigenous', FALSE, FALSE), (3, 'Patient C', 'California Non-Indigenous', TRUE, FALSE), (4, 'Patient D', 'Florida Non-Indigenous', FALSE, TRUE);

SELECT COUNT(*) as patient_count, diabetes as diabetes_prevalence, hypertension as hypertension_prevalence FROM patients WHERE community = 'New Mexico Indigenous' GROUP BY diabetes, hypertension;


Question: How many community policing events were held in each district in the last year, ordered by the highest number of events?

CREATE TABLE CommunityPolicing (id INT, district VARCHAR(20), event_date DATE);

SELECT district, COUNT(*) as num_events FROM CommunityPolicing WHERE event_date >= DATE_SUB(CURDATE(), INTERVAL 1 YEAR) GROUP BY district ORDER BY num_events DESC;


Question: What is the total resource depletion cost for each mine?

CREATE TABLE mine (id INT, name VARCHAR(50), location VARCHAR(50)); CREATE TABLE cost (mine_id INT, year INT, cost INT);

SELECT mine.name, SUM(cost.cost) FROM cost JOIN mine ON cost.mine_id = mine.id GROUP BY mine.name;


Question: How many artworks were created by female artists in each country?

CREATE TABLE artworks (id INT, name TEXT, artist TEXT, country TEXT); INSERT INTO artworks (id, name, artist, country) VALUES (1, 'Painting', 'Sarah Johnson', 'USA'), (2, 'Sculpture', 'Maria Rodriguez', 'Spain'), (3, 'Installation', 'Yumi Lee', 'South Korea');

SELECT country, COUNT(*) as num_artworks FROM artworks WHERE artist LIKE '%female%' GROUP BY country;


Question: Generate PostgreSQL SQL for: What is the launched date of the destroyer completed 1 July 1936?

CREATE TABLE table_name_28 (launched VARCHAR, completed VARCHAR)

SELECT launched FROM table_name_28 WHERE completed = '1 july 1936';


Question: Insert a new record with permit ID 456, contractor 'Green Construction', and timeline '2022-01-01 - 2022-04-30' in the building_projects table

CREATE TABLE building_projects (permit_id INT, contractor VARCHAR(100), timeline DATE);

INSERT INTO building_projects (permit_id, contractor, timeline) VALUES (456, 'Green Construction', '2022-01-01'::DATE, '2022-04-30'::DATE);


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

CREATE OPERATOR >= (
    LEFTARG    = CITEXT,
    RIGHTARG   = CITEXT,
    NEGATOR    = <,
    COMMUTATOR = <=,
    PROCEDURE  = citext_ge,
    RESTRICT   = scalargtsel,
    JOIN       = scalargtjoinsel
);

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


Question: Generate PostgreSQL SQL for: Show the locations of parties and the names of the party hosts in ascending order of the age of the host.

CREATE TABLE party (Location VARCHAR, Party_ID VARCHAR); CREATE TABLE HOST (Name VARCHAR, Host_ID VARCHAR, Age VARCHAR); CREATE TABLE party_host (Host_ID VARCHAR, Party_ID VARCHAR)

SELECT T3.Location, T2.Name FROM party_host AS T1 JOIN HOST AS T2 ON T1.Host_ID = T2.Host_ID JOIN party AS T3 ON T1.Party_ID = T3.Party_ID ORDER BY T2.Age;


Question: What is the total weight of all satellites launched by Japan in the satellites table?

CREATE TABLE satellites (name TEXT, country TEXT, weight FLOAT); INSERT INTO satellites (name, country, weight) VALUES ('Hayabusa', 'Japan', 500.0);

SELECT SUM(weight) FROM satellites WHERE country = 'Japan';


Question: Generate PostgreSQL SQL for: What is the Aggregate of Bayer Leverkusen opponents?

CREATE TABLE table_name_56 (aggregate VARCHAR, opponents VARCHAR)

SELECT aggregate FROM table_name_56 WHERE opponents = 'bayer leverkusen';


Question: Generate PostgreSQL SQL for: Which location led to a decision and a record of 1-2?

CREATE TABLE table_name_36 (location VARCHAR, method VARCHAR, record VARCHAR)

SELECT location FROM table_name_36 WHERE method = 'decision' AND record = '1-2';


Question: Generate PostgreSQL SQL for: How many different frequencies does the model with part number ado540biaa5do?

CREATE TABLE table_13869651_3 (frequency VARCHAR, part_number_s_ VARCHAR)

SELECT COUNT(frequency) FROM table_13869651_3 WHERE part_number_s_ = 'ADO540BIAA5DO';


Question: What is the average energy efficiency rating of residential buildings in California, grouped by city and construction period?

CREATE TABLE residential_buildings (id INT, city VARCHAR(100), state VARCHAR(50), energy_efficiency_rating FLOAT, construction_period DATE); INSERT INTO residential_buildings (id, city, state, energy_efficiency_rating, construction_period) VALUES (1, 'City A', 'California', 80, '2000-01-01'); INSERT INTO residential_buildings (id, city, state, energy_efficiency_rating, construction_period) VALUES (2, 'City B', 'California', 85, '2005-01-01');

SELECT city, YEAR(construction_period) AS construction_year, AVG(energy_efficiency_rating) AS avg_rating FROM residential_buildings WHERE state = 'California' GROUP BY city, YEAR(construction_period);


Question: Generate PostgreSQL SQL for: What was the original air date of the episode written by michael glassberg?

CREATE TABLE table_26866299_1 (original_airdate VARCHAR, writer VARCHAR)

SELECT original_airdate FROM table_26866299_1 WHERE writer = 'Michael Glassberg';


Question: Update the cost of an existing agricultural innovation project, identified by its id, to the new given cost.

CREATE TABLE agricultural_innovation_projects (id INT, project_name VARCHAR(255), location VARCHAR(255), sector VARCHAR(255), cost FLOAT); INSERT INTO agricultural_innovation_projects (id, project_name, location, sector, cost) VALUES (1, 'Precision Agriculture', 'Country 1', 'Agriculture', 35000.00), (2, 'Drip Irrigation', 'Country 2', 'Agriculture', 28000.00);

UPDATE agricultural_innovation_projects SET cost = 37000.00 WHERE id = 1;


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

SELECT ia1 FROM jsonb_populate_record(NULL::jsbrec, '{"ia1": [1, "2", null, 4]}') q;

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

SELECT count(*) FROM (SELECT ia1 FROM jsonb_populate_record(NULL::jsbrec, '{"ia1": [1, "2", null, 4]}') q) AS _sub;


Question: Generate PostgreSQL SQL for: What is Player, when Previous Team (League) is "Medicine Hat Tigers ( WHL )", and when Year is less than 2002?

CREATE TABLE table_name_90 (player VARCHAR, previous_team__league_ VARCHAR, year VARCHAR)

SELECT player FROM table_name_90 WHERE previous_team__league_ = 'medicine hat tigers ( whl )' AND year < 2002;


Question: Generate PostgreSQL SQL for: Name the opponent for record 10-4

CREATE TABLE table_18894744_5 (opponent VARCHAR, record VARCHAR)

SELECT opponent FROM table_18894744_5 WHERE record = '10-4';


Question: What is the average fare for buses in the 'city' schema, excluding fares less than $1?

CREATE SCHEMA city; CREATE TABLE city.buses (id INT, fare DECIMAL); INSERT INTO city.buses (id, fare) VALUES (1, 2.50), (2, 1.75), (3, 3.00);

SELECT AVG(fare) FROM city.buses WHERE fare > 1;


Question: PostgreSQL regression test 'stats': Write the SELECT query (example 134).

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

SELECT count(*) FROM (SELECT pg_stat_get_live_tuples(:drop_stats_test_xact_oid)) AS _sub;


Question: Generate PostgreSQL SQL for: What was the population in 2011 of banatski karlovac?

CREATE TABLE table_2562572_44 (population__2011_ VARCHAR, settlement VARCHAR)

SELECT population__2011_ FROM table_2562572_44 WHERE settlement = 'Banatski Karlovac';


Question: What was the lowest peacekeeping mission duration for an African country in 2017?

CREATE TABLE african_peacekeeping_missions (country VARCHAR(50), year INT, duration INT); INSERT INTO african_peacekeeping_missions (country, year, duration) VALUES ('Mali', 2017, 120), ('South Sudan', 2017, 150), ('Central African Republic', 2017, 180), ('DRC', 2017, 210), ('Somalia', 2017, 240), ('Western Sahara', 2017, 270);

SELECT MIN(duration) FROM african_peacekeeping_missions WHERE year = 2017;


Question: Generate PostgreSQL SQL for: What time slots have a 6.3 rating

CREATE TABLE table_11244302_1 (time_slot__est_ VARCHAR, rating VARCHAR)

SELECT time_slot__est_ FROM table_11244302_1 WHERE rating = '6.3';


Question: Generate PostgreSQL SQL for: Which Bronze is the lowest one that has a Nation of total, and a Gold smaller than 14?

CREATE TABLE table_name_38 (bronze INTEGER, nation VARCHAR, gold VARCHAR)

SELECT MIN(bronze) FROM table_name_38 WHERE nation = 'total' AND gold < 14;


Question: How many European destinations did Russian tourists visit in 2020?

CREATE TABLE tourism_stats (id INT PRIMARY KEY, year INT, country VARCHAR(255), destination VARCHAR(255));   INSERT INTO tourism_stats (id, year, country, destination) VALUES (1, 2020, 'Russia', 'France'), (2, 2020, 'Russia', 'Italy'), (3, 2020, 'Russia', 'Spain'), (4, 2020, 'Russia', 'Germany');

SELECT COUNT(DISTINCT destination) FROM tourism_stats WHERE country = 'Russia' AND destination LIKE 'Europe%' AND year = 2020;


Question: Generate PostgreSQL SQL for: How many years is ur sulcus listed with a diameter less than 1,145.0?

CREATE TABLE table_name_68 (year_named VARCHAR, name VARCHAR, diameter VARCHAR)

SELECT COUNT(year_named) FROM table_name_68 WHERE name = 'ur sulcus' AND diameter < 1 OFFSET 145.0;


Question: Generate PostgreSQL SQL for: What kind of Tongan has a North Marquesan of /haʔe/?

CREATE TABLE table_name_89 (tongan VARCHAR, north_marquesan VARCHAR)

SELECT tongan FROM table_name_89 WHERE north_marquesan = '/haʔe/';


Question: What is the maximum speed recorded for a shared electric bicycle in Berlin, Germany?

CREATE TABLE shared_ebikes (ebike_id INT, ride_id INT, trip_start_time TIMESTAMP, trip_end_time TIMESTAMP, start_location TEXT, end_location TEXT, city TEXT, max_speed DECIMAL);

SELECT MAX(max_speed) FROM shared_ebikes WHERE city = 'Berlin';


Question: Generate PostgreSQL SQL for: Which Silver has a Total of 7, and a Gold larger than 1?

CREATE TABLE table_name_10 (silver INTEGER, total VARCHAR, gold VARCHAR)

SELECT AVG(silver) FROM table_name_10 WHERE total = 7 AND gold > 1;


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

CREATE TABLE fk_d PARTITION OF fk DEFAULT;

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


Question: Generate PostgreSQL SQL for: What was the date for the Champs Sports Bowl?

CREATE TABLE table_20996923_20 (date VARCHAR, bowl_game VARCHAR)

SELECT date FROM table_20996923_20 WHERE bowl_game = 'Champs Sports Bowl';


Question: Show the total number of ad clicks and the click-through rate (CTR) for each advertising campaign in the last quarter.

CREATE TABLE campaigns (campaign_id INT, campaign_name VARCHAR(255), start_date DATE, end_date DATE); CREATE TABLE ad_impressions (ad_id INT, campaign_id INT, impressions INT, click_date DATE);

SELECT c.campaign_name, SUM(ai.impressions) as total_impressions, SUM(ai.clicks) as total_clicks, SUM(ai.clicks) / SUM(ai.impressions) as ctr FROM campaigns c INNER JOIN ad_impressions ai ON c.campaign_id = ai.campaign_id WHERE ai.click_date BETWEEN DATE_SUB(CURDATE(), INTERVAL 3 MONTH) AND CURDATE() GROUP BY c.campaign_name;


Question: Generate PostgreSQL SQL for: What is the average wins when teams is lions and the percent is more than 0?

CREATE TABLE table_name_31 (wins INTEGER, teams VARCHAR, percent VARCHAR)

SELECT AVG(wins) FROM table_name_31 WHERE teams = 'lions' AND percent > 0;


Question: How many financial capability training sessions were conducted in Brazil in H1 of 2022?

CREATE TABLE financial_capability_training_brazil (id INT, semester INT, year INT, sessions INT);  INSERT INTO financial_capability_training_brazil (id, semester, year, sessions) VALUES (1, 1, 2022, 25), (2, 1, 2022, 30), (3, 2, 2022, 40);

SELECT SUM(sessions) FROM financial_capability_training_brazil WHERE semester IN (1, 2) AND year = 2022 AND country = 'Brazil';


Question: Generate PostgreSQL SQL for: What is the Kickoff Time on January 7, 2002?

CREATE TABLE table_name_72 (kickoff_time VARCHAR, date VARCHAR)

SELECT kickoff_time FROM table_name_72 WHERE date = 'january 7, 2002';


Question: Generate PostgreSQL SQL for: Which Surface has a Partner of galina voskoboeva?

CREATE TABLE table_name_45 (surface VARCHAR, partner VARCHAR)

SELECT surface FROM table_name_45 WHERE partner = 'galina voskoboeva';


Question: What is the total wastewater treatment capacity for each city in India?

CREATE TABLE wastewater_treatment_india(id INT, city VARCHAR(50), treatment_type VARCHAR(50), capacity INT, efficiency FLOAT); INSERT INTO wastewater_treatment_india(id, city, treatment_type, capacity, efficiency) VALUES (1, 'Mumbai', 'Screening', 1200, 0.92);

SELECT city, SUM(capacity) as total_capacity FROM wastewater_treatment_india GROUP BY city;


Question: Generate PostgreSQL SQL for: How many times was performer 3 Kate Robbins?

CREATE TABLE table_14934885_1 (date VARCHAR, performer_3 VARCHAR)

SELECT COUNT(date) FROM table_14934885_1 WHERE performer_3 = 'Kate Robbins';


Question: Write the DDL statement from PostgreSQL regression test 'numeric' (example 1).

CREATE TABLE num_data (id int4, val numeric(210,10));

Explanation: DDL from PostgreSQL core regression test for Numeric.


Question: Write the DML statement from PostgreSQL regression test 'identity' (example 180).

INSERT into pitest2_p1 (f1, f2) VALUES ('2016-07-7', 'from pitest2_p1'); -- error
INSERT into pitest2_p1 (f1, f2, f3) VALUES ('2016-07-7', 'from pitest2_p1', 2000);

Explanation: DML from PostgreSQL core regression test for Identity.


Question: What is the average song_length in the reggae genre?

CREATE TABLE genres (genre VARCHAR(10), song_id INT, song_length FLOAT);   INSERT INTO genres (genre, song_id, song_length) VALUES ('reggae', 16, 210.5), ('reggae', 17, 225.8), ('reggae', 18, 195.4);

SELECT AVG(song_length) FROM genres WHERE genre = 'reggae';


Question: Identify the total count of cases and total billable hours for attorneys in the 'billing' and 'cases' tables, grouped by attorney ethnicity.

CREATE TABLE attorney_ethnicity (attorney_id INT, ethnicity VARCHAR(30)); INSERT INTO attorney_ethnicity VALUES (1, 'Hispanic'), (2, 'Asian'), (3, 'African American'), (4, 'Caucasian'); CREATE TABLE billing (attorney_id INT, hours DECIMAL(5,2)); CREATE TABLE cases (case_id INT, attorney_id INT);

SELECT e.ethnicity, COUNT(c.attorney_id) AS total_cases, SUM(b.hours) AS total_hours FROM attorney_ethnicity e JOIN billing b ON e.attorney_id = b.attorney_id JOIN cases c ON e.attorney_id = c.attorney_id GROUP BY e.ethnicity;


Question: Which public transportation modes have the highest passenger capacity in Berlin, Germany?

CREATE TABLE public_transportation (transport_id INT, type TEXT, capacity INT, in_service BOOLEAN, city TEXT);

SELECT type, MAX(capacity) FROM public_transportation WHERE city = 'Berlin' AND in_service = TRUE GROUP BY type;


Question: What is the distribution of user interactions (like, comment, share) by article?

CREATE TABLE user_interactions_by_article (user_id text, article_id text, interaction text); INSERT INTO user_interactions_by_article (user_id, article_id, interaction) VALUES ('User 7', 'Article 11', 'like'); INSERT INTO user_interactions_by_article (user_id, article_id, interaction) VALUES ('User 8', 'Article 11', 'comment');

SELECT article_id, interaction, COUNT(*) as count FROM user_interactions_by_article GROUP BY article_id, interaction;


Question: Generate PostgreSQL SQL for: What is the result of Saturday that's ថ្ងៃអាទិត្យ [tŋaj ʔaatɨt ] on Sunday?

CREATE TABLE table_name_30 (saturday_shani__saturn_ VARCHAR, sunday_surya__the_sun_ VARCHAR)

SELECT saturday_shani__saturn_ FROM table_name_30 WHERE sunday_surya__the_sun_ = 'ថ្ងៃអាទិត្យ [tŋaj ʔaatɨt ]';


Question: Generate PostgreSQL SQL for: what is the margin of error when the undicided is 8% and other is 4%?

CREATE TABLE table_name_77 (margin_of_error VARCHAR, undecided VARCHAR, other VARCHAR)

SELECT margin_of_error FROM table_name_77 WHERE undecided = '8%' AND other = '4%';


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

SELECT citext_cmp('AARDVARK'::citext, 'AARDVARK'::citext) AS zero;

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


Question: What is the total budget for movies released in 2017 and 2018?

CREATE TABLE Movies (title VARCHAR(255), release_year INT, budget INT); INSERT INTO Movies (title, release_year, budget) VALUES ('Movie1', 2015, 50000000), ('Movie2', 2016, 75000000), ('Movie3', 2017, 60000000), ('Movie4', 2018, 80000000), ('Movie5', 2019, 90000000);

SELECT SUM(budget) FROM Movies WHERE release_year IN (2017, 2018);


Question: What is the minimum number of cases handled by restorative justice programs in Washington D.C. in a single year?

CREATE TABLE restorative_justice_programs (program_id INT, cases_handled INT, year INT, district VARCHAR(20)); INSERT INTO restorative_justice_programs (program_id, cases_handled, year, district) VALUES (1, 100, 2021, 'Washington D.C.'), (2, 200, 2020, 'Washington D.C.'), (3, 150, 2019, 'Washington D.C.'), (4, 250, 2018, 'Washington D.C.'), (5, 300, 2017, 'Washington D.C.');

SELECT MIN(cases_handled) FROM restorative_justice_programs WHERE year >= 2017 AND district = 'Washington D.C.';


Question: List all seafood providers based in California for 'Fresh Catch'?

CREATE TABLE FreshCatch (id INT, provider VARCHAR(30), product VARCHAR(20), state VARCHAR(20)); INSERT INTO FreshCatch (id, provider, product, state) VALUES (1, 'Sea Breeze', 'Tuna', 'California'), (2, 'Pacific Harvest', 'Salmon', 'Oregon');

SELECT DISTINCT provider FROM FreshCatch WHERE state = 'California' AND product LIKE '%seafood%';


Question: What is the maximum length of stay in prison for individuals who have been released in the past year, grouped by their offense type?

CREATE TABLE prison_releases (id INT, offense_type TEXT, release_date DATE, length_of_stay INT);

SELECT offense_type, MAX(length_of_stay) FROM prison_releases WHERE release_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR) GROUP BY offense_type;


Question: Show a query using PostgreSQL contrib extension 'pg_visibility' (example 63).

select count(*) > 0 from pg_visibility_map('test_partition');

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


Question: Which customers have not made any transactions in the last 3 months for an investment business?

CREATE TABLE customers (customer_id INT, name VARCHAR(255)); CREATE TABLE investment_transactions (transaction_id INT, customer_id INT, amount DECIMAL(10,2), trans_date DATE);

SELECT customers.name FROM customers LEFT JOIN investment_transactions ON customers.customer_id = investment_transactions.customer_id WHERE investment_transactions.trans_date IS NULL OR investment_transactions.trans_date < NOW() - INTERVAL '3 months';


Question: Generate PostgreSQL SQL for: What is the grid total that has a Time/Retired of + 1:33.141, and under 70 laps?

CREATE TABLE table_name_27 (grid INTEGER, time_retired VARCHAR, laps VARCHAR)

SELECT SUM(grid) FROM table_name_27 WHERE time_retired = '+ 1:33.141' AND laps < 70;


Question: Generate PostgreSQL SQL for: What opponent has a loss of McCaskill (9-11)?

CREATE TABLE table_name_10 (opponent VARCHAR, loss VARCHAR)

SELECT opponent FROM table_name_10 WHERE loss = 'mccaskill (9-11)';


Question: Generate PostgreSQL SQL for: What is the score of the game with a 3-0 record?

CREATE TABLE table_name_67 (score VARCHAR, record VARCHAR)

SELECT score FROM table_name_67 WHERE record = '3-0';


Question: What is the number of clients living in each city?

CREATE TABLE clients (client_id INT, name VARCHAR(50), age INT, city VARCHAR(50)); INSERT INTO clients VALUES (1, 'John Doe', 55, 'New York'), (2, 'Jane Smith', 45, 'Los Angeles'), (3, 'Mike Johnson', 58, 'New York'), (4, 'Alice Davis', 35, 'Chicago'), (5, 'Bob Brown', 40, 'New York');

SELECT city, COUNT(*) FROM clients GROUP BY city;


Question: Generate PostgreSQL SQL for: What is the lowest of the Highest score for the Quickstep Dance and the Lowest score under 16?

CREATE TABLE table_name_72 (highest_score INTEGER, dance VARCHAR, lowest_score VARCHAR)

SELECT MIN(highest_score) FROM table_name_72 WHERE dance = 'quickstep' AND lowest_score < 16;


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

SELECT npoints(f1) AS npoints, f1 AS polygon
   FROM POLYGON_TBL;

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

SELECT count(*) FROM (SELECT npoints(f1) AS npoints, f1 AS polygon
   FROM POLYGON_TBL) AS _sub;


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

ALTER EXTENSION pgtap ADD FUNCTION is_aggregate( NAME, NAME, NAME[] );


Question: Generate PostgreSQL SQL for: What was the notes of the 400 m event before 2004 with a position of 12th (h)?

CREATE TABLE table_name_69 (notes VARCHAR, position VARCHAR, event VARCHAR, year VARCHAR)

SELECT notes FROM table_name_69 WHERE event = '400 m' AND year < 2004 AND position = '12th (h)';


Question: What is the total value of military equipment sales to the United Kingdom and Canada combined from 2018 to 2021?

CREATE TABLE MilitaryEquipmentSales (id INT PRIMARY KEY, sale_year INT, equipment_type VARCHAR(50), country VARCHAR(50), sale_value FLOAT); INSERT INTO MilitaryEquipmentSales (id, sale_year, equipment_type, country, sale_value) VALUES (1, 2020, 'Aircraft', 'United States', 12000000), (2, 2021, 'Vehicles', 'United States', 8000000), (3, 2018, 'Naval Equipment', 'United Kingdom', 10000000), (4, 2019, 'Radars', 'Canada', 5000000);

SELECT SUM(sale_value) FROM MilitaryEquipmentSales WHERE (country = 'United Kingdom' OR country = 'Canada') AND sale_year BETWEEN 2018 AND 2021;


Question: Generate PostgreSQL SQL for: When the socket is bga956 and processor is penryn-3m, what is the tdp?

CREATE TABLE table_24100843_1 (tdp VARCHAR, socket VARCHAR, processor VARCHAR)

SELECT tdp FROM table_24100843_1 WHERE socket = 'BGA956' AND processor = 'Penryn-3M';


Question: How many labor accidents occurred in mining sites located in the Amazon rainforest in 2021?

CREATE TABLE MiningSites (SiteID int, SiteName varchar(50), Location varchar(50)); INSERT INTO MiningSites VALUES (1, 'SiteA', 'Amazon Rainforest'), (2, 'SiteB', 'Andes Mountains'), (3, 'SiteC', 'Sahara Desert'); CREATE TABLE AccidentData (SiteID int, AccidentDate date); INSERT INTO AccidentData VALUES (1, '2021-03-15'), (1, '2021-06-27'), (3, '2021-09-04'), (2, '2021-12-18'), (1, '2021-11-29');

SELECT COUNT(*) as LaborAccidents FROM AccidentData ad JOIN MiningSites ms ON ad.SiteID = ms.SiteID WHERE ms.Location = 'Amazon Rainforest' AND ad.AccidentDate BETWEEN '2021-01-01' AND '2021-12-31';


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

CREATE TABLE table_name_71 (champion VARCHAR, year VARCHAR, finalist VARCHAR)

SELECT champion FROM table_name_71 WHERE year > 2007 AND finalist = 'asvel';


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

SELECT b.relname,
       CASE WHEN a.relfilenode = b.relfilenode THEN 'relfilenode is unchanged'
       ELSE 'relfilenode has changed' END AS filenode,
       CASE WHEN a.reltablespace = b.reltablespace THEN 'reltablespace is unchanged'
       ELSE 'reltablespace has changed' END AS tbspace
  FROM reindex_temp_before b JOIN pg_class a ON b.relname = a.relname
  ORDER BY 1;

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

SELECT count(*) FROM (SELECT b.relname,
       CASE WHEN a.relfilenode = b.relfilenode THEN 'relfilenode is unchanged'
       ELSE 'relfilenode has changed' END AS filenode,
       CASE WHEN a.reltablespace = b.reltablespace THEN 'reltablespace is unchanged'
       ELSE 'reltablespace has changed' END AS tbspace
  FROM reindex_temp_before b JOIN pg_class a ON b.relname = a.relname
  ORDER BY 1) AS _sub;


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

-- Ensure all these functions made it into the catalog
SELECT aggfnoid, aggtransfn, aggcombinefn, aggtranstype::regtype,
       aggserialfn, aggdeserialfn, aggfinalmodify
FROM pg_aggregate
WHERE aggfnoid = 'myavg'::REGPROC;

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


Question: What is the total revenue generated from domestic shipments?

CREATE TABLE shipments (id INT, shipment_type VARCHAR(10), revenue DECIMAL(10,2)); INSERT INTO shipments (id, shipment_type, revenue) VALUES (1, 'domestic', 500.00), (2, 'international', 800.00);

SELECT SUM(revenue) FROM shipments WHERE shipment_type = 'domestic';


Question: What is the average word count of articles in each country, for articles published in the 'politics' category?

CREATE TABLE countries (id INT, name TEXT); CREATE TABLE categories (id INT, name TEXT); CREATE TABLE articles (id INT, title TEXT, content TEXT, category_id INT, country_id INT); INSERT INTO countries (id, name) VALUES (1, 'USA'), (2, 'Canada'), (3, 'Mexico'); INSERT INTO categories (id, name) VALUES (1, 'Politics'), (2, 'Technology'), (3, 'Sports'); INSERT INTO articles (id, title, content, category_id, country_id) VALUES (1, 'Article 1', 'Content 1', 1, 1), (2, 'Article 2', 'Content 2', 2, 2), (3, 'Article 3', 'Content 3', 1, 3), (4, 'Article 4', 'Content 4', 1, 1), (5, 'Article 5', 'Content 5', 3, 2);

SELECT countries.name, AVG(LENGTH(articles.content) - LENGTH(REPLACE(articles.content, ' ', '')) + 1) as avg_word_count FROM articles INNER JOIN countries ON articles.country_id = countries.id INNER JOIN categories ON articles.category_id = categories.id WHERE categories.name = 'Politics' GROUP BY countries.name;


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

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


Question: Generate PostgreSQL SQL for: What is the region 1 (Canada) date associated with a region 2 (UK) date of May 18, 2009?

CREATE TABLE table_240936_2 (region_1__can_ VARCHAR, region_2__uk_ VARCHAR)

SELECT region_1__can_ FROM table_240936_2 WHERE region_2__uk_ = 'May 18, 2009';


Question: How many electric vehicles are there in Canada and Australia?

CREATE TABLE electric_vehicles (id INT, country VARCHAR(255), name VARCHAR(255), quantity INT); INSERT INTO electric_vehicles (id, country, name, quantity) VALUES (1, 'Canada', 'EV A', 5000), (2, 'Australia', 'EV B', 7000), (3, 'USA', 'EV C', 12000);

SELECT SUM(quantity) FROM electric_vehicles WHERE country IN ('Canada', 'Australia');


Question: What is the average transaction value (in USD) for the Bitcoin network in the last week?

CREATE TABLE BitcoinTransactions (id INT, txid VARCHAR(100), value DECIMAL(20,2), timestamp BIGINT); INSERT INTO BitcoinTransactions (id, txid, value, timestamp) VALUES (1, '...', 100, 1643324480), (2, '...', 200, 1643410880);

SELECT AVG(value * (SELECT rate FROM ExchangeRates WHERE currency = 'BTC' AND timestamp = tx.timestamp)) as avg_value_usd FROM BitcoinTransactions tx WHERE timestamp >= UNIX_TIMESTAMP(DATE_SUB(CURRENT_DATE, INTERVAL 1 WEEK)) * 1000;


Question: Generate PostgreSQL SQL for: What is the largest frequency owned by multicultural broadcasting with a Format of vietnamese?

CREATE TABLE table_name_40 (frequency INTEGER, status VARCHAR, format VARCHAR)

SELECT MAX(frequency) FROM table_name_40 WHERE status = 'owned by multicultural broadcasting' AND format = 'vietnamese';


Question: Generate PostgreSQL SQL for: How many sound engineers were there for law hakon '3er leek?

CREATE TABLE table_28005100_1 (sound_engineer VARCHAR, title VARCHAR)

SELECT COUNT(sound_engineer) FROM table_28005100_1 WHERE title = 'Law Hakon '3er Leek';


Question: PostgreSQL regression test 'sqljson': Write the SELECT query (example 63).

SELECT JSON_OBJECT(RETURNING bytea FORMAT JSON ENCODING UTF32);

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

SELECT count(*) FROM (SELECT JSON_OBJECT(RETURNING bytea FORMAT JSON ENCODING UTF32)) AS _sub;


Question: Generate PostgreSQL SQL for: Game site of shea stadium, and a Week smaller than 10, and a Opponent of baltimore colts happened on what date?

CREATE TABLE table_name_13 (date VARCHAR, opponent VARCHAR, game_site VARCHAR, week VARCHAR)

SELECT date FROM table_name_13 WHERE game_site = 'shea stadium' AND week < 10 AND opponent = 'baltimore colts';


Question: Generate PostgreSQL SQL for: What spacecrafts had 22 orbital flights?

CREATE TABLE table_179174_2 (spacecraft VARCHAR, flights VARCHAR)

SELECT spacecraft FROM table_179174_2 WHERE flights = '22 Orbital';


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

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


Question: What is the average age of community health workers by their ethnicity?

CREATE TABLE CommunityHealthWorkers (WorkerID INT, Age INT, Ethnicity VARCHAR(255)); INSERT INTO CommunityHealthWorkers (WorkerID, Age, Ethnicity) VALUES (1, 45, 'Hispanic'), (2, 34, 'African American'), (3, 50, 'Asian'), (4, 40, 'Caucasian');

SELECT Ethnicity, AVG(Age) as AvgAge FROM CommunityHealthWorkers GROUP BY Ethnicity;


Question: List all the auto shows with more than 500 exhibitors in Japan.

CREATE TABLE Auto_Shows (id INT, name TEXT, exhibitors INT, country TEXT); INSERT INTO Auto_Shows (id, name, exhibitors, country) VALUES (1, 'Tokyo Auto Show', 600, 'Japan'); INSERT INTO Auto_Shows (id, name, exhibitors, country) VALUES (2, 'Osaka Auto Show', 400, 'Japan');

SELECT name FROM Auto_Shows WHERE exhibitors > 500 AND country = 'Japan';


Question: Generate PostgreSQL SQL for: What is the lowest tie with less than 100 points and 277 goals?

CREATE TABLE table_name_57 (tied INTEGER, points VARCHAR, goals_for VARCHAR)

SELECT MIN(tied) FROM table_name_57 WHERE points < 100 AND goals_for = 277;


Question: Write the DML statement from PostgreSQL regression test 'foreign_key' (example 1030).

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


Question: What is the maximum number of likes received by a post in each content type in the past week?

CREATE TABLE post_likes (post_id INT, content_type VARCHAR(20), likes INT); INSERT INTO post_likes (post_id, content_type, likes) VALUES (1, 'photo', 100), (2, 'video', 200), (3, 'link', 150), (4, 'photo', 250), (5, 'video', 300);

SELECT content_type, MAX(likes) AS max_likes FROM post_likes WHERE date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 WEEK) GROUP BY content_type;


Question: What is the total revenue for the Pop genre in 2021?

CREATE TABLE music_sales (sale_id INT, genre VARCHAR(10), year INT, revenue FLOAT); INSERT INTO music_sales (sale_id, genre, year, revenue) VALUES (1, 'Pop', 2021, 50000.00), (2, 'Rock', 2021, 45000.00), (3, 'Pop', 2020, 40000.00); CREATE VIEW genre_sales AS SELECT genre, SUM(revenue) as total_revenue FROM music_sales GROUP BY genre;

SELECT total_revenue FROM genre_sales WHERE genre = 'Pop';


Question: How many employees work in the 'Risk Management' department in the 'New York' office?

CREATE TABLE office (office_id INT, city VARCHAR(50), state VARCHAR(50)); CREATE TABLE department (department_id INT, department_name VARCHAR(50), office_id INT); CREATE TABLE employee (employee_id INT, employee_name VARCHAR(100), department_id INT); INSERT INTO office (office_id, city, state) VALUES (1, 'New York', 'NY'), (2, 'Toronto', 'ON'); INSERT INTO department (department_id, department_name, office_id) VALUES (1, 'Risk Management', 1), (2, 'IT', 1); INSERT INTO employee (employee_id, employee_name, department_id) VALUES (1, 'Bob Brown', 1), (2, 'Sara Green', 2);

SELECT COUNT(*) FROM employee JOIN department ON employee.department_id = department.department_id JOIN office ON department.office_id = office.office_id WHERE office.city = 'New York' AND department.department_name = 'Risk Management';


Question: Generate PostgreSQL SQL for: What is the average number of audience for festivals?

CREATE TABLE festival_detail (Num_of_Audience INTEGER)

SELECT AVG(Num_of_Audience) FROM festival_detail;


Question: Determine the percentage of female founders in each country

CREATE TABLE founders (id INT, name VARCHAR(255), gender VARCHAR(10), country VARCHAR(255)); INSERT INTO founders (id, name, gender, country) VALUES (1, 'John Doe', 'Male', 'USA'), (2, 'Jane Smith', 'Female', 'USA'), (3, 'Mike Johnson', 'Male', 'Canada'), (4, 'Alice Williams', 'Female', 'Canada'), (5, 'Bob Brown', 'Male', 'UK'), (6, 'Claire Johnson', 'Female', 'UK'), (7, 'Suresh Patel', 'Male', 'India'), (8, 'Priya Gupta', 'Female', 'India');

SELECT country, gender, COUNT(*) as head_count, ROUND(COUNT(*)*100.0/SUM(COUNT(*)) OVER (PARTITION BY country), 2) as gender_percentage FROM founders GROUP BY country, gender;