Question: Generate PostgreSQL SQL for: What was Fuzzy Zoeller's score in the United States?

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

SELECT score FROM table_name_82 WHERE country = 'united states' AND player = 'fuzzy zoeller';


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

SELECT * FROM pg_input_error_info('2001-01-01 00:00 Nehwon/Lankhmar', 'timestamptz');

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

SELECT count(*) FROM (SELECT * FROM pg_input_error_info('2001-01-01 00:00 Nehwon/Lankhmar', 'timestamptz')) AS _sub;


Question: Generate PostgreSQL SQL for: Which constructor has a Grid smaller than 18, and a Driver of mika häkkinen?

CREATE TABLE table_name_14 (constructor VARCHAR, grid VARCHAR, driver VARCHAR)

SELECT constructor FROM table_name_14 WHERE grid < 18 AND driver = 'mika häkkinen';


Question: Generate PostgreSQL SQL for: What Engine had a chassis of March 85c?

CREATE TABLE table_name_72 (engine VARCHAR, chassis VARCHAR)

SELECT engine FROM table_name_72 WHERE chassis = 'march 85c';


Question: Generate PostgreSQL SQL for: How many millions of viewers watched the episode directed by Christine Moore?

CREATE TABLE table_23255941_1 (viewers__in_millions_ VARCHAR, directed_by VARCHAR)

SELECT viewers__in_millions_ FROM table_23255941_1 WHERE directed_by = 'Christine Moore';


Question: Delete records in the water_usage table where the usage is less than 100 liters

CREATE TABLE water_usage (id INT, location VARCHAR(50), usage FLOAT);

DELETE FROM water_usage WHERE usage < 100;


Question: What is the average daily ridership for each subway line in Seoul?

CREATE TABLE subway (line_id INT, city VARCHAR(50), daily_ridership INT); INSERT INTO subway (line_id, city, daily_ridership) VALUES (1, 'Tokyo', 300000), (2, 'Tokyo', 450000), (3, 'Tokyo', 400000), (4, 'Tokyo', 500000), (5, 'Seoul', 250000), (6, 'Seoul', 300000);

SELECT line_id, city, AVG(daily_ridership) FROM subway WHERE city = 'Seoul' GROUP BY line_id, city;


Question: How many volunteers engaged in each program, by month?

CREATE TABLE programs (id INT, name VARCHAR(255)); INSERT INTO programs (id, name) VALUES (1, 'Education'), (2, 'Health'), (3, 'Environment'); CREATE TABLE volunteer_hours (id INT, program_id INT, volunteer_date DATE, hours INT); INSERT INTO volunteer_hours (id, program_id, volunteer_date, hours) VALUES (1, 1, '2022-01-01', 5), (2, 1, '2022-01-02', 3), (3, 2, '2022-01-03', 6), (4, 3, '2022-01-04', 4);

SELECT program_id, DATE_TRUNC('month', volunteer_date) AS month, COUNT(*) OVER (PARTITION BY program_id, month) AS volunteers_per_month FROM volunteer_hours;


Question: Generate PostgreSQL SQL for: What was the orginal air date for episodes with production code 2acx12?

CREATE TABLE table_28210383_1 (original_air_date VARCHAR, prod_code VARCHAR)

SELECT original_air_date FROM table_28210383_1 WHERE prod_code = '2ACX12';


Question: Generate PostgreSQL SQL for: Who is the top goalscorer for the season 2010-11?

CREATE TABLE table_2429942_2 (top_goalscorer VARCHAR, season VARCHAR)

SELECT top_goalscorer FROM table_2429942_2 WHERE season = '2010-11';


Question: What is the average depth of all marine protected areas in the Pacific Ocean?"

CREATE TABLE marine_protected_areas (id INT, name TEXT, area_size FLOAT, avg_depth FLOAT, ocean TEXT); INSERT INTO marine_protected_areas (id, name, area_size, avg_depth, ocean) VALUES (1, 'Galapagos Marine Reserve', 133000, 200, 'Pacific');

SELECT AVG(avg_depth) FROM marine_protected_areas WHERE ocean = 'Pacific';


Question: How many car manufacturers are headquartered in South Korea?

CREATE TABLE Manufacturers (Id INT, Name VARCHAR(100), Country VARCHAR(50)); INSERT INTO Manufacturers (Id, Name, Country) VALUES (1, 'Hyundai', 'South Korea'), (2, 'Kia', 'South Korea');

SELECT COUNT(*) FROM Manufacturers WHERE Country = 'South Korea';


Question: List the countries, regions, and mobile towers for regions with an average data usage over 75 among broadband subscribers.

CREATE TABLE countries (country_id INT PRIMARY KEY, country_name VARCHAR(255)); INSERT INTO countries (country_id, country_name) VALUES (1, 'USA'), (2, 'Canada'), (3, 'Mexico'); CREATE TABLE regions (region_id INT PRIMARY KEY, region_name VARCHAR(255), country_id INT); INSERT INTO regions (region_id, region_name, country_id) VALUES (1, 'East', 1), (2, 'West', 1), (3, 'Central', 2), (4, 'North', 3), (5, 'South', 3); CREATE TABLE mobile_towers (tower_id INT PRIMARY KEY, region_id INT); INSERT INTO mobile_towers (tower_id, region_id) VALUES (1, 1), (2, 2), (3, 3), (4, 4), (5, 5); CREATE TABLE broadband_subscribers (subscriber_id INT PRIMARY KEY, region_id INT, data_usage FLOAT); INSERT INTO broadband_subscribers (subscriber_id, region_id, data_usage) VALUES (1, 1, 80.0), (2, 2, 70.0), (3, 3, 90.0), (4, 4, 65.0), (5, 5, 100.0);

SELECT c.country_name, r.region_name, m.tower_id FROM countries c JOIN regions r ON c.country_id = r.country_id JOIN mobile_towers m ON r.region_id = m.region_id JOIN broadband_subscribers b ON r.region_id = b.region_id GROUP BY r.region_id HAVING AVG(b.data_usage) > 75;


Question: How many artworks were added to museums each year?

SELECT year, SUM(quantity) FROM artworks GROUP BY year;


Question: What is the percentage of total donations made by women in 2021?

CREATE TABLE Donors (DonorID int, DonorGender varchar(50), Country varchar(50), AmountDonated numeric(18,2), DonationDate date); INSERT INTO Donors (DonorID, DonorGender, Country, AmountDonated, DonationDate) VALUES (1, 'Female', 'USA', 5000, '2021-01-01'), (2, 'Male', 'Canada', 7000, '2021-02-01'), (3, 'Female', 'Mexico', 8000, '2021-03-01');

SELECT (SUM(CASE WHEN DonorGender = 'Female' THEN AmountDonated ELSE 0 END) / SUM(AmountDonated)) * 100 as Percentage FROM Donors WHERE YEAR(DonationDate) = 2021;


Question: Generate PostgreSQL SQL for: How many Mixed Doubles won when Oliver Pongratz won the Men's Singles?

CREATE TABLE table_12164707_1 (mixed_doubles VARCHAR, mens_singles VARCHAR)

SELECT COUNT(mixed_doubles) FROM table_12164707_1 WHERE mens_singles = 'Oliver Pongratz';


Question: What is the success rate of patients who completed a mindfulness-based stress reduction (MBSR) program, compared to those who did not?

CREATE TABLE patients (patient_id INT, age INT, gender TEXT, state TEXT); INSERT INTO patients (patient_id, age, gender, state) VALUES (1, 35, 'Female', 'California'); INSERT INTO patients (patient_id, age, gender, state) VALUES (2, 45, 'Male', 'Texas'); CREATE TABLE treatments (treatment_id INT, patient_id INT, treatment TEXT, date DATE, completion_date DATE); INSERT INTO treatments (treatment_id, patient_id, treatment, date, completion_date) VALUES (1, 1, 'MBSR', '2021-01-01', '2021-03-01'); INSERT INTO treatments (treatment_id, patient_id, treatment, date) VALUES (2, 2, 'Medication', '2021-01-02');

SELECT AVG(CASE WHEN treatments.completion_date IS NOT NULL THEN 1 ELSE 0 END) AS mbsr_completers_success_rate, AVG(CASE WHEN treatments.completion_date IS NULL THEN 1 ELSE 0 END) AS mbsr_non_completers_success_rate FROM treatments INNER JOIN patients ON treatments.patient_id = patients.patient_id WHERE treatments.treatment = 'MBSR';


Question: Generate PostgreSQL SQL for: What competition had its first match on December 20, 2007?

CREATE TABLE table_name_15 (competition VARCHAR, first_match VARCHAR)

SELECT competition FROM table_name_15 WHERE first_match = 'december 20, 2007';


Question: Show an example of PostgreSQL CREATE SCHEMA (example 4).

CREATE SCHEMA hollywood CREATE TABLE films (title text, release date, awards text[]) CREATE VIEW winners AS SELECT title, release FROM films WHERE awards IS NOT NULL;

Explanation: PostgreSQL CREATE SCHEMA command.


Question: Generate PostgreSQL SQL for: What is the smallest number of episodes in a season?

CREATE TABLE table_2113721_7 (episodes INTEGER)

SELECT MIN(episodes) FROM table_2113721_7;


Question: Generate PostgreSQL SQL for: What was the box score during a home game of the Adelaide 36ers?

CREATE TABLE table_name_39 (Box VARCHAR, home_team VARCHAR)

SELECT Box AS score FROM table_name_39 WHERE home_team = 'adelaide 36ers';


Question: Generate PostgreSQL SQL for: What is the pole position of the Portuguese Grand Prix?

CREATE TABLE table_name_54 (pole_position VARCHAR, grand_prix VARCHAR)

SELECT pole_position FROM table_name_54 WHERE grand_prix = 'portuguese grand prix';


Question: Generate PostgreSQL SQL for: What is Country, when Place is "T8", and when Score is "70-67=137"?

CREATE TABLE table_name_98 (country VARCHAR, place VARCHAR, score VARCHAR)

SELECT country FROM table_name_98 WHERE place = 't8' AND score = 70 - 67 = 137;


Question: How many drugs were approved in 'Asia' in 2021?

CREATE TABLE drug_approval (drug_name TEXT, year INT, region TEXT); INSERT INTO drug_approval (drug_name, year, region) VALUES ('DrugX', 2019, 'Europe'), ('DrugX', 2020, 'Asia'), ('DrugY', 2018, 'Asia'), ('DrugY', 2020, 'Asia'), ('DrugZ', 2021, 'Asia'), ('DrugA', 2021, 'Asia');

SELECT COUNT(DISTINCT drug_name) FROM drug_approval WHERE year = 2021 AND region = 'Asia';


Question: List all campaigns in New York that started after 2018-01-01.

CREATE TABLE campaigns (campaign_id INT, name TEXT, start_date DATE, location TEXT); INSERT INTO campaigns (campaign_id, name, start_date, location) VALUES (1, 'End Stigma', '2017-12-01', 'New York'); INSERT INTO campaigns (campaign_id, name, start_date, location) VALUES (2, 'Mental Health Matters', '2019-06-01', 'California');

SELECT name, start_date FROM campaigns WHERE location = 'New York' AND start_date > '2018-01-01';


Question: Calculate the percentage of community engagement events in each city, ordered by the percentage in descending order.

CREATE TABLE community_events (event_id INT, event_name TEXT, city TEXT, year INT); INSERT INTO community_events (event_id, event_name, city, year) VALUES (1, 'Cultural Festival', 'New York', 2020), (2, 'Traditional Music Concert', 'Los Angeles', 2019);

SELECT city, ROUND(100.0 * COUNT(*) / (SELECT COUNT(*) FROM community_events) , 2) as percentage FROM community_events GROUP BY city ORDER BY percentage DESC;


Question: Generate PostgreSQL SQL for: When was episode 02x02 first broadcast?

CREATE TABLE table_29141354_2 (first_broadcast VARCHAR, episode VARCHAR)

SELECT first_broadcast FROM table_29141354_2 WHERE episode = '02x02';


Question: Generate PostgreSQL SQL for: How many validations are listed for the iin range 36?

CREATE TABLE table_15905399_1 (validation VARCHAR, iin_ranges VARCHAR)

SELECT COUNT(validation) FROM table_15905399_1 WHERE iin_ranges = '36';


Question: Generate PostgreSQL SQL for: What census ranking has an area greater than 578.28 km2?

CREATE TABLE table_name_17 (census_ranking VARCHAR, area_km_2 INTEGER)

SELECT census_ranking FROM table_name_17 WHERE area_km_2 > 578.28;


Question: What is the total revenue generated by indigenous artworks sold in North America, broken down by country?

CREATE TABLE Artists (ArtistID INT, ArtistName VARCHAR(50), Country VARCHAR(50), Ethnicity VARCHAR(50)); CREATE TABLE ArtPieces (ArtPieceID INT, ArtistID INT, Price INT); CREATE TABLE Sales (SaleID INT, ArtPieceID INT, Year INT, Quantity INT); INSERT INTO Artists VALUES (1, 'Artist 1', 'USA', 'Indigenous'), (2, 'Artist 2', 'Canada', 'Indigenous'), (3, 'Artist 3', 'Mexico', 'Indigenous'); INSERT INTO ArtPieces VALUES (1, 1, 5000), (2, 1, 7000), (3, 2, 6000), (4, 2, 8000), (5, 3, 11000), (6, 3, 13000); INSERT INTO Sales VALUES (1, 1, 2021, 2), (2, 2, 2021, 1), (3, 3, 2021, 3), (4, 4, 2021, 2), (5, 5, 2021, 1), (6, 6, 2021, 3);

SELECT A.Country, SUM(AP.Price * S.Quantity) AS TotalRevenue FROM Artists A INNER JOIN ArtPieces AP ON A.ArtistID = AP.ArtistID INNER JOIN Sales S ON AP.ArtPieceID = S.ArtPieceID WHERE A.Ethnicity = 'Indigenous' AND A.Country IN ('USA', 'Canada', 'Mexico') GROUP BY A.Country;


Question: What is the percentage of total complaints for each service category in Quebec in 2021?

CREATE TABLE QuebecComplaints (service VARCHAR(30), complaints INT); INSERT INTO QuebecComplaints (service, complaints) VALUES ('Transportation', 1200), ('Utilities', 900), ('Education', 700), ('Healthcare', 1500);

SELECT service, (complaints * 100.0 / (SELECT SUM(complaints) FROM QuebecComplaints)) AS percentage FROM QuebecComplaints;


Question: Generate PostgreSQL SQL for: How many deciles have a Gender of coed, an Authority of state, and a Name of mount maunganui school?

CREATE TABLE table_name_93 (decile INTEGER, name VARCHAR, gender VARCHAR, authority VARCHAR)

SELECT SUM(decile) FROM table_name_93 WHERE gender = 'coed' AND authority = 'state' AND name = 'mount maunganui school';


Question: Generate PostgreSQL SQL for: When the result is d, who are the opponents?

CREATE TABLE table_name_19 (opponents VARCHAR, result VARCHAR)

SELECT opponents FROM table_name_19 WHERE result = 'd';


Question: Generate PostgreSQL SQL for: How many Joint Music Awards are there when the Total is larger than 18, in a Year after 2007?

CREATE TABLE table_name_32 (joint_music_award VARCHAR, total VARCHAR, year VARCHAR)

SELECT joint_music_award FROM table_name_32 WHERE total > 18 AND year > 2007;


Question: Which sustainable tourism activities in Spain are rated 5?

CREATE TABLE activities (activity_id INT, activity_name VARCHAR(50), country VARCHAR(50), rating INT); INSERT INTO activities (activity_id, activity_name, country, rating) VALUES (1, 'Hiking Adventure', 'Spain', 5), (2, 'Bird Watching', 'Spain', 4), (3, 'Nature Photography', 'Spain', 5), (4, 'Bike Tour', 'Spain', 4);

SELECT activity_name FROM activities WHERE country = 'Spain' AND rating = 5;


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

INSERT INTO UNIQUE_TBL (t) VALUES ('six');

Explanation: DML from PostgreSQL core regression test for Constraints.


Question: Generate PostgreSQL SQL for: What is the to par number of the person who won in 2003?

CREATE TABLE table_name_40 (to_par VARCHAR, year_s__won VARCHAR)

SELECT to_par FROM table_name_40 WHERE year_s__won = '2003';


Question: What is the total number of expeditions for each organization?

CREATE TABLE expedition (org VARCHAR(20), depth INT); INSERT INTO expedition VALUES ('Ocean Explorer', 2500), ('Ocean Explorer', 3000), ('Sea Discoverers', 2000), ('Marine Investigators', 4000), ('Marine Investigators', 4500);

SELECT org, COUNT(*) FROM expedition GROUP BY org;


Question: Generate PostgreSQL SQL for: What is the average total when gold is 0, bronze is 0, and silver is smaller than 1?

CREATE TABLE table_name_54 (total INTEGER, silver VARCHAR, gold VARCHAR, bronze VARCHAR)

SELECT AVG(total) FROM table_name_54 WHERE gold = 0 AND bronze = 0 AND silver < 1;


Question: Generate PostgreSQL SQL for: What is the sum of the lap with a finish of 24?

CREATE TABLE table_name_60 (laps INTEGER, finish VARCHAR)

SELECT SUM(laps) FROM table_name_60 WHERE finish = '24';


Question: What is the minimum number of followers for users who have posted about #veganism in the past week?

CREATE TABLE users (id INT, followers INT, posts TEXT);

SELECT MIN(followers) FROM users WHERE posts LIKE '%#veganism%' AND posts IS NOT NULL AND posts != '';


Question: PostgreSQL regression test 'create_index': Write the SELECT query (example 151).

SELECT * FROM array_index_op_test WHERE t && '{}' ORDER BY seqno;

Explanation: Regression test for Create Index in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT * FROM array_index_op_test WHERE t && '{}' ORDER BY seqno) AS _sub;


Question: Generate PostgreSQL SQL for: What is the highest Kuala Lumpur value with a Durban value less than 1 and a Mar Del Plata value greater than 0?

CREATE TABLE table_name_82 (kuala_lumpur INTEGER, durban VARCHAR, mar_del_plata VARCHAR)

SELECT MAX(kuala_lumpur) FROM table_name_82 WHERE durban < 1 AND mar_del_plata > 0;


Question: What are the names, populations, and regions of species that have been sighted since 2019, excluding species from the Arctic and Antarctic?

CREATE TABLE Species (id INT, name VARCHAR(100), population INT, region VARCHAR(100), last_sighting DATE); INSERT INTO Species (id, name, population, region, last_sighting) VALUES (1, 'Polar Bear', 25000, 'Arctic', '2018-01-01'); INSERT INTO Species (id, name, population, region, last_sighting) VALUES (2, 'Arctic Fox', 30000, 'Arctic', '2020-02-01'); INSERT INTO Species (id, name, population, region, last_sighting) VALUES (3, 'Reindeer', 40000, 'Norway', '2021-01-01'); INSERT INTO Species (id, name, population, region, last_sighting) VALUES (4, 'Penguin', 50000, 'Antarctic', '2019-01-01');

SELECT name, population, region FROM Species WHERE last_sighting >= '2019-01-01' AND region NOT IN ('Arctic', 'Antarctic');


Question: Find the water usage data with the highest usage amount in the water_usage table

CREATE TABLE water_usage ( date DATE, usage_category VARCHAR(20), region VARCHAR(20), usage_amount INT ); INSERT INTO water_usage (date, usage_category, region, usage_amount) VALUES ( '2022-07-01', 'Residential', 'Northeast', 15000), ('2022-07-02', 'Industrial', 'Midwest', 200000), ('2022-07-03', 'Agricultural', 'West', 800000);

SELECT * FROM water_usage WHERE usage_amount = (SELECT MAX(usage_amount) FROM water_usage);


Question: What is the total amount of minerals extracted by each company, considering only environmentally friendly mining methods?

CREATE TABLE mining_companies (company_id INT, company_name TEXT); INSERT INTO mining_companies (company_id, company_name) VALUES (1, 'CompanyX'), (2, 'CompanyY'); CREATE TABLE mining_methods (method_id INT, method_name TEXT, is_environmentally_friendly BOOLEAN); INSERT INTO mining_methods (method_id, method_name, is_environmentally_friendly) VALUES (1, 'Open-pit', true), (2, 'Underground', false), (3, 'In-situ', true); CREATE TABLE extraction_data (company_id INT, method_id INT, amount_extracted INT); INSERT INTO extraction_data (company_id, method_id, amount_extracted) VALUES (1, 1, 500), (1, 3, 300), (2, 1, 700), (2, 3, 400);

SELECT mc.company_name, SUM(ed.amount_extracted) AS total_amount_extracted FROM extraction_data ed JOIN mining_companies mc ON ed.company_id = mc.company_id JOIN mining_methods mm ON ed.method_id = mm.method_id WHERE mm.is_environmentally_friendly = true GROUP BY mc.company_name;


Question: Determine the inventory turnover rate for each ingredient category

CREATE TABLE Ingredients (ingredient_id INT, ingredient_name VARCHAR(255), ingredient_category VARCHAR(255), quantity INT, purchase_price DECIMAL(5,2)); INSERT INTO Ingredients (ingredient_id, ingredient_name, ingredient_category, quantity, purchase_price) VALUES (1, 'Chickpeas', 'Legumes', 50, 1.25), (2, 'Chicken Breast', 'Poultry', 100, 3.50); CREATE TABLE Sales (sales_id INT, ingredient_id INT, quantity INT); INSERT INTO Sales (sales_id, ingredient_id, quantity) VALUES (1, 1, 25), (2, 2, 80);

SELECT ingredient_category, SUM(quantity) AS total_quantity, AVG(quantity) AS avg_quantity_sold, SUM(quantity) / (SELECT SUM(quantity) * purchase_price FROM Ingredients, Sales WHERE Ingredients.ingredient_id = Sales.ingredient_id GROUP BY Ingredients.ingredient_id) AS inventory_turnover_rate FROM Ingredients, Sales WHERE Ingredients.ingredient_id = Sales.ingredient_id GROUP BY ingredient_category;


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

-- test ordered-set aggs using built-in support functions
create aggregate my_percentile_disc(float8 ORDER BY anyelement) (
  stype = internal,
  sfunc = ordered_set_transition,
  finalfunc = percentile_disc_final,
  finalfunc_extra = true,
  finalfunc_modify = read_write
);

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


Question: What is the total number of students and teachers in the 'Education' database?

CREATE TABLE student (student_id INT); INSERT INTO student (student_id) VALUES (1), (2), (3); CREATE TABLE teacher (teacher_id INT); INSERT INTO teacher (teacher_id) VALUES (101), (102), (103);

SELECT COUNT(*) FROM student; SELECT COUNT(*) FROM teacher;


Question: Generate PostgreSQL SQL for: Who is the mix artist for the closing party setlist where artist 1 is Dillinja and Skibadee?

CREATE TABLE table_29264319_1 (mix_artist VARCHAR, setlist VARCHAR, artist_1 VARCHAR)

SELECT mix_artist FROM table_29264319_1 WHERE setlist = 'Closing Party' AND artist_1 = 'Dillinja and Skibadee';


Question: Generate PostgreSQL SQL for: What is the sum of the round of the new york jets NFL club, which has a pick less than 166?

CREATE TABLE table_name_60 (round INTEGER, nfl_club VARCHAR, pick VARCHAR)

SELECT SUM(round) FROM table_name_60 WHERE nfl_club = 'new york jets' AND pick < 166;


Question: Generate PostgreSQL SQL for: What are the names of races held after 12:00:00 or before 09:00:00?

CREATE TABLE races (name VARCHAR, TIME VARCHAR)

SELECT name FROM races WHERE TIME > "12:00:00" OR TIME < "09:00:00";


Question: Find the number of AI safety incidents and their severity, partitioned by incident type, ordered by severity in descending order?

CREATE TABLE ai_safety_incidents (incident_id INT, incident_type VARCHAR(50), severity DECIMAL(3,2)); INSERT INTO ai_safety_incidents (incident_id, incident_type, severity) VALUES (1, 'Cybersecurity', 0.75), (2, 'Data Privacy', 0.85), (3, 'Algorithmic Bias', 0.95), (4, 'Ethical Concerns', 1.00);

SELECT incident_type, COUNT(*) as num_incidents, AVG(severity) as avg_severity FROM ai_safety_incidents GROUP BY incident_type ORDER BY avg_severity DESC;


Question: List all decentralized applications that have had a regulatory action taken against them and their associated smart contracts in the South American region.

CREATE TABLE decentralized_applications (dapp_id INT, dapp_name VARCHAR(50), region VARCHAR(50)); CREATE TABLE smart_contracts (contract_id INT, dapp_id INT, contract_name VARCHAR(50), region VARCHAR(50)); CREATE TABLE regulatory_actions (action_id INT, contract_id INT, action_date DATE);

SELECT d.dapp_name, s.contract_name FROM decentralized_applications d INNER JOIN smart_contracts s ON d.dapp_id = s.dapp_id INNER JOIN regulatory_actions r ON s.contract_id = r.contract_id WHERE d.region = 'South America';


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

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

SELECT count(*) FROM (SELECT var_pop(b) FROM aggtest) AS _sub;


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

$$;

CALL ptest3('b');

SELECT * FROM cp_test;

-- output arguments

CREATE PROCEDURE ptest4a(INOUT a int, INOUT b int)
LANGUAGE SQL
AS $$
SELECT 1, 2;

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


Question: Generate PostgreSQL SQL for: Which Cuts made has a Tournament of totals, and Wins smaller than 11?

CREATE TABLE table_name_25 (cuts_made INTEGER, tournament VARCHAR, wins VARCHAR)

SELECT AVG(cuts_made) FROM table_name_25 WHERE tournament = 'totals' AND wins < 11;


Question: Generate PostgreSQL SQL for: What did the team do in the Open Cup in the 2nd, Northeast season of the USISL D-3 Pro League?

CREATE TABLE table_1939214_1 (open_cup VARCHAR, league VARCHAR, regular_season VARCHAR)

SELECT open_cup FROM table_1939214_1 WHERE league = 'USISL D-3 Pro league' AND regular_season = '2nd, Northeast';


Question: Generate PostgreSQL SQL for: What's Babson College's enrollment?

CREATE TABLE table_1974782_1 (enrollment INTEGER, institution VARCHAR)

SELECT MAX(enrollment) FROM table_1974782_1 WHERE institution = 'Babson College';


Question: Generate PostgreSQL SQL for: What is the Venue on 26 jan 2005

CREATE TABLE table_name_12 (venue VARCHAR, date VARCHAR)

SELECT venue FROM table_name_12 WHERE date = '26 jan 2005';


Question: Generate PostgreSQL SQL for: Where did Konchesky move to?

CREATE TABLE table_name_34 (moving_to VARCHAR, name VARCHAR)

SELECT moving_to FROM table_name_34 WHERE name = 'konchesky';


Question: Generate PostgreSQL SQL for: Which Rank has a Scorer of lee sang-cheol?

CREATE TABLE table_name_69 (rank VARCHAR, scorer VARCHAR)

SELECT rank FROM table_name_69 WHERE scorer = 'lee sang-cheol';


Question: What were the total sales for a specific drug in Q1 2021?

SELECT drug_id, SUM(amount) as total_sales FROM drug_sales WHERE sale_date BETWEEN '2021-01-01' AND '2021-03-31' GROUP BY drug_id;


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

CREATE FUNCTION s.index_this_expr(s.citext, bool) RETURNS s.citext IMMUTABLE
  LANGUAGE SQL AS $$SELECT $1$$;
REVOKE ALL ON FUNCTION public.setter FROM PUBLIC;
REVOKE ALL ON FUNCTION s.const FROM PUBLIC;
REVOKE ALL ON FUNCTION s.index_this_expr FROM PUBLIC;
-- Even for an empty table, expression planning calls s.const & public.setter.
GRANT EXECUTE ON FUNCTION public.setter TO regress_minimal;
GRANT EXECUTE ON FUNCTION s.const TO regress_minimal;
-- Function for index predicate.
CREATE FUNCTION s.index_row_if(s.citext) RETURNS bool IMMUTABLE
  LANGUAGE SQL AS $$SELECT $1 IS NOT NULL$$;

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


Question: Generate PostgreSQL SQL for: What is the highest Goals Against, when Club is "Pontevedra CF", and when Played is less than 38?

CREATE TABLE table_name_74 (goals_against INTEGER, club VARCHAR, played VARCHAR)

SELECT MAX(goals_against) FROM table_name_74 WHERE club = 'pontevedra cf' AND played < 38;


Question: Delete all menu items with a price over 20 dollars

CREATE TABLE menu_items (item_id INT, item_name VARCHAR(50), price DECIMAL(5,2)); INSERT INTO menu_items (item_id, item_name, price) VALUES (1, 'Steak', 25.99), (2, 'Salad', 12.49), (3, 'Pasta', 18.99);

DELETE FROM menu_items WHERE price > 20.00;


Question: What is the total weight of organic fruits exported to Germany?

CREATE TABLE FruitExport(id INT, name TEXT, weight FLOAT, is_organic BOOLEAN, country TEXT); INSERT INTO FruitExport(id, name, weight, is_organic, country) VALUES (1, 'Bananas', 450.3, TRUE, 'Germany'), (2, 'Apples', 300.2, FALSE, 'Germany');

SELECT SUM(weight) FROM FruitExport WHERE name = 'Bananas' AND is_organic = TRUE AND country = 'Germany';


Question: Generate PostgreSQL SQL for: what is the competition when the date is 1995-08-06?

CREATE TABLE table_name_35 (competition VARCHAR, date VARCHAR)

SELECT competition FROM table_name_35 WHERE date = '1995-08-06';


Question: Generate PostgreSQL SQL for: Visitor of dallas, and a Date of june 12 had what highest attendance?

CREATE TABLE table_name_16 (attendance INTEGER, visitor VARCHAR, date VARCHAR)

SELECT MAX(attendance) FROM table_name_16 WHERE visitor = 'dallas' AND date = 'june 12';


Question: What is the average length of articles written by female authors in Africa?

CREATE TABLE authors (author_id INT, gender VARCHAR(6), country VARCHAR(50)); CREATE TABLE articles (article_id INT, author_id INT, length_words INT); INSERT INTO authors VALUES (1, 'female', 'Nigeria'); INSERT INTO articles VALUES (1, 1, 1200);

SELECT AVG(length_words) FROM authors INNER JOIN articles ON authors.author_id = articles.author_id WHERE authors.gender = 'female' AND country IN ('Nigeria', 'South Africa', 'Egypt');


Question: What is the average sustainable sourcing score for each restaurant category?

CREATE SCHEMA FoodService;CREATE TABLE Sustainability (sustainability_id INT, restaurant_id INT, category VARCHAR(50), score INT); INSERT INTO Sustainability (sustainability_id, restaurant_id, category, score) VALUES (1, 1, 'dining', 85), (2, 1, 'dining', 90), (3, 2, 'takeout', 70), (4, 2, 'takeout', 75);

SELECT category, AVG(score) as avg_score FROM Sustainability GROUP BY category;


Question: List all astronauts who have never been on a space mission

CREATE TABLE Astronauts(ID INT, Name VARCHAR(50), FirstMissionDate DATE);

SELECT Name FROM Astronauts WHERE FirstMissionDate IS NULL;


Question: What is the average number of likes and comments for posts in the past week?

CREATE TABLE posts (id INT PRIMARY KEY, user_id INT, post_date DATETIME, content TEXT, likes INT, comments INT);

SELECT AVG(likes + comments) FROM posts WHERE post_date >= DATEADD(week, -1, GETDATE());


Question: Which locations have had more than 10 marine species observations in a given year, along with the number of observations?

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

SELECT location, COUNT(*) FROM MarineSpeciesObservations GROUP BY location HAVING COUNT(*) > 10;


Question: What is the total number of space missions funded by NASA and ESA?

CREATE TABLE space_missions (id INT, name VARCHAR(50), space_agency VARCHAR(50)); CREATE TABLE space_agencies (id INT, name VARCHAR(50), acronym VARCHAR(50));

SELECT COUNT(*) FROM space_missions WHERE space_agency IN (SELECT name FROM space_agencies WHERE acronym IN ('NASA', 'ESA'));


Question: Show the total visitor count for each department's temporary exhibitions, excluding the "Art" department.

CREATE TABLE DepartmentExhibits (department_name TEXT, exhibit_name TEXT, visitor_count INTEGER); INSERT INTO DepartmentExhibits (department_name, exhibit_name, visitor_count) VALUES ('Art', 'Impressionism', 2000), ('Art', 'Cubism', 1500), ('History', 'Ancient Egypt', 3000); CREATE TABLE DepartmentTotals (department_name TEXT, total_visitors INTEGER); INSERT INTO DepartmentTotals (department_name, total_visitors) SELECT department_name, SUM(visitor_count) FROM DepartmentExhibits WHERE department_name != 'Art' GROUP BY department_name;


Question: Which excavation sites have more artifacts from the Roman period than the Iron Age?

CREATE TABLE SiteArtifacts (SiteID INT, ArtifactID INT, Period TEXT); INSERT INTO SiteArtifacts (SiteID, ArtifactID, Period) VALUES (1, 1, 'Roman'), (1, 2, 'Iron Age'), (2, 3, 'Roman');

SELECT SiteID FROM SiteArtifacts WHERE Period = 'Roman' GROUP BY SiteID HAVING COUNT(*) > (SELECT COUNT(*) FROM SiteArtifacts WHERE SiteID = SiteArtifacts.SiteID AND Period = 'Iron Age');


Question: Which countries in South America have the highest number of eco-friendly accommodations?

CREATE TABLE if NOT EXISTS accommodations (id INT, name TEXT, country TEXT, eco_friendly BOOLEAN); INSERT INTO accommodations (id, name, country, eco_friendly) VALUES (1, 'Eco Lodge', 'Argentina', true), (2, 'Green Retreat', 'Brazil', true), (3, 'Sustainable Hotel', 'Chile', true);

SELECT country, COUNT(*) as count FROM accommodations WHERE eco_friendly = true GROUP BY country ORDER BY count DESC;


Question: What is the total assets under management (AUM) for the 'Value' portfolio as of the last day of the previous quarter?

CREATE TABLE portfolios (portfolio VARCHAR(20), aum DECIMAL(15, 2)); INSERT INTO portfolios (portfolio, aum) VALUES ('Tech Growth', 5000000.00), ('Value', 7000000.00), ('Small Cap', 3000000.00);

SELECT aum FROM portfolios WHERE portfolio = 'Value';


Question: What are the top three mining operations with the highest resource extraction?

CREATE TABLE MiningOperations (OperationID INT, OperationName VARCHAR(20), Location VARCHAR(20), ResourcesExtracted INT, OperationDate DATE);

SELECT OperationName, ResourcesExtracted FROM MiningOperations WHERE ROW_NUMBER() OVER(ORDER BY ResourcesExtracted DESC) <= 3;


Question: List the case IDs and billing amounts for cases that were not billed.

CREATE TABLE Cases (CaseID int, BillingAmount decimal(5,2)); INSERT INTO Cases (CaseID, BillingAmount) VALUES (1, 250.00), (2, NULL), (3, 300.00), (4, 150.00), (5, NULL);

SELECT CaseID, BillingAmount FROM Cases WHERE BillingAmount IS NULL;


Question: Generate PostgreSQL SQL for: What is Record, when Game is 27?

CREATE TABLE table_name_54 (record VARCHAR, game VARCHAR)

SELECT record FROM table_name_54 WHERE game = 27;


Question: How many size 14 jeans were sold in the past month?

CREATE TABLE jeans_sales (id INT PRIMARY KEY, size INT, sale_date DATE); INSERT INTO jeans_sales (id, size, sale_date) VALUES (1, 12, '2021-12-01'), (2, 14, '2021-12-05'), (3, 16, '2021-12-10');

SELECT COUNT(*) FROM jeans_sales WHERE size = 14 AND sale_date >= DATE '2021-11-01' AND sale_date < DATE '2021-12-01';


Question: What is the maximum number of defense contracts signed by a single company in the United States?

CREATE TABLE defense_contracts (dc_id INT, dc_company VARCHAR(50), dc_country VARCHAR(50)); INSERT INTO defense_contracts (dc_id, dc_company, dc_country) VALUES (1, 'Company A', 'United States'), (2, 'Company B', 'United States'), (3, 'Company C', 'Canada');

SELECT MAX(dc_count) FROM (SELECT COUNT(*) AS dc_count FROM defense_contracts WHERE dc_country = 'United States' GROUP BY dc_company) AS subquery;


Question: Generate PostgreSQL SQL for: What are the hometowns of gymnasts and the corresponding number of gymnasts?

CREATE TABLE gymnast (Gymnast_ID VARCHAR); CREATE TABLE people (Hometown VARCHAR, People_ID VARCHAR)

SELECT T2.Hometown, COUNT(*) FROM gymnast AS T1 JOIN people AS T2 ON T1.Gymnast_ID = T2.People_ID GROUP BY T2.Hometown;


Question: What is the total number of organic products in the ORGANIC_PRODUCTS table?

CREATE TABLE ORGANIC_PRODUCTS (id INT, name VARCHAR(50), category VARCHAR(50), quantity INT); INSERT INTO ORGANIC_PRODUCTS (id, name, category, quantity) VALUES (1, 'Quinoa', 'Grains', 50), (2, 'Tofu', 'Proteins', 30);

SELECT SUM(quantity) FROM ORGANIC_PRODUCTS;


Question: Display the research grant amounts for all grants awarded to the 'Physics' department.

CREATE TABLE grants (grant_id INT, dept_name VARCHAR(255), grant_amount FLOAT); INSERT INTO grants (grant_id, dept_name, grant_amount) VALUES (1, 'Physics', 50000), (2, 'Computer_Science', 75000), (3, 'Physics', 60000);

SELECT grant_amount FROM grants WHERE dept_name = 'Physics';


Question: Generate PostgreSQL SQL for: Name the listed owner for mike garvey

CREATE TABLE table_24535095_2 (listed_owner_s_ VARCHAR, crew_chief VARCHAR)

SELECT listed_owner_s_ FROM table_24535095_2 WHERE crew_chief = 'Mike Garvey';


Question: How many threat intelligence reports were generated per month in 2021?

SELECT STR_TO_DATE(Month, '%b-%Y') AS Month, COUNT(*) FROM Reports GROUP BY Month;


Question: Avg. risk rating of sustainable investments in the EU

CREATE TABLE sustainable_investment_risk(investment_id INT, risk_rating INT, investment_type VARCHAR(20));

SELECT AVG(risk_rating) FROM sustainable_investment_risk WHERE investment_type = 'sustainable';


Question: What is the percentage of habitats that are fully protected, by region?

CREATE TABLE habitat_data (habitat_id INT, habitat_type VARCHAR(255), region VARCHAR(255), protection_level VARCHAR(255)); INSERT INTO habitat_data (habitat_id, habitat_type, region, protection_level) VALUES (1, 'Forest', 'North', 'Full'), (2, 'Forest', 'North', 'Partial'), (3, 'Savannah', 'South', 'Full'), (4, 'Savannah', 'South', 'Partial'), (5, 'Wetlands', 'East', 'Full'), (6, 'Wetlands', 'East', 'Full'), (7, 'Mountains', 'West', 'Partial'), (8, 'Mountains', 'West', 'Partial');

SELECT region, (COUNT(CASE WHEN protection_level = 'Full' THEN 1 END)::float/COUNT(habitat_id))*100 AS protection_percentage FROM habitat_data GROUP BY region;


Question: Generate PostgreSQL SQL for: Which Republican ran against the American Labor candidate Matthew J. Merritt?

CREATE TABLE table_name_5 (republican_ticket VARCHAR, american_labor_ticket VARCHAR)

SELECT republican_ticket FROM table_name_5 WHERE american_labor_ticket = 'matthew j. merritt';


Question: Generate PostgreSQL SQL for: Who is the home team when Sheffield United is the away team?

CREATE TABLE table_name_38 (home_team VARCHAR, away_team VARCHAR)

SELECT home_team FROM table_name_38 WHERE away_team = 'sheffield united';


Question: What is the total number of ad impressions in 'advertising_performance' table for the last month?

CREATE TABLE advertising_performance (ad_id INT, user_id INT, ad_impressions INT, ad_date DATE);

SELECT ad_date, SUM(ad_impressions) FROM advertising_performance WHERE ad_date >= CURDATE() - INTERVAL 1 MONTH GROUP BY ad_date;


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

select '$."null \\u0000 escape"'::jsonpath as not_an_escape;

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

SELECT count(*) FROM (select '$."null \\u0000 escape"'::jsonpath as not_an_escape) AS _sub;


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

SELECT test_json -> 2 FROM test_jsonb WHERE json_type = 'object';

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

SELECT count(*) FROM (SELECT test_json -> 2 FROM test_jsonb WHERE json_type = 'object') AS _sub;


Question: Generate PostgreSQL SQL for: What is the venue of the match on 5 April 2000?

CREATE TABLE table_name_45 (venue VARCHAR, date VARCHAR)

SELECT venue FROM table_name_45 WHERE date = '5 april 2000';


Question: What is the average construction labor cost per hour in the state of California?

CREATE TABLE labor_costs (cost_id INT, labor_cost DECIMAL, state TEXT); INSERT INTO labor_costs VALUES (1, 45.5, 'California'), (2, 35.0, 'Texas'), (3, 50.0, 'New York'), (4, 40.0, 'California');

SELECT AVG(labor_cost) FROM labor_costs WHERE state = 'California';


Question: Generate PostgreSQL SQL for: Which department has more than 1 head at a time? List the id, name and the number of heads.

CREATE TABLE management (department_id VARCHAR); CREATE TABLE department (department_id VARCHAR, name VARCHAR)

SELECT T1.department_id, T1.name, COUNT(*) FROM management AS T2 JOIN department AS T1 ON T1.department_id = T2.department_id GROUP BY T1.department_id HAVING COUNT(*) > 1;


Question: What is the ratio of male to female healthcare providers in the "rural_clinics_2" table?

CREATE TABLE rural_clinics_2 (id INT, name TEXT, age INT, gender TEXT); INSERT INTO rural_clinics_2 (id, name, age, gender) VALUES (1, 'Clinic C', 50, 'Male'), (2, 'Clinic D', 40, 'Female'), (3, 'Clinic E', 55, 'Male');

SELECT ROUND(COUNT(CASE WHEN gender = 'Male' THEN 1 END)/COUNT(CASE WHEN gender = 'Female' THEN 1 END), 2) FROM rural_clinics_2;


Question: List all the broadband subscribers with their subscription start dates in the Northeast region who have been active for less than 3 months.

CREATE TABLE subscribers(id INT, subscription_start_date DATE, region VARCHAR(10), subscription_type VARCHAR(10)); INSERT INTO subscribers VALUES (1, '2022-08-15', 'Northeast', 'broadband');

SELECT subscribers.id, subscribers.subscription_start_date FROM subscribers WHERE subscribers.region = 'Northeast' AND subscribers.subscription_type = 'broadband' AND DATEDIFF(CURDATE(), subscribers.subscription_start_date) < 90;


Question: Generate PostgreSQL SQL for: How many million u.s. viewers saw the episode that was directed by roger young and written by debra j. fisher?

CREATE TABLE table_28037619_2 (us_viewers__million_ VARCHAR, directed_by VARCHAR, written_by VARCHAR)

SELECT us_viewers__million_ FROM table_28037619_2 WHERE directed_by = 'Roger Young' AND written_by = 'Debra J. Fisher';


Question: What is the average number of families assisted per day by each community center in Q3 of 2021?

CREATE TABLE Community_Centers (cc_name TEXT, families_assisted INTEGER, assist_date DATE); INSERT INTO Community_Centers (cc_name, families_assisted, assist_date) VALUES ('Center A', 10, '2021-07-04'); INSERT INTO Community_Centers (cc_name, families_assisted, assist_date) VALUES ('Center B', 15, '2021-08-18');

SELECT cc_name, AVG(families_assisted/DATEDIFF('2021-10-01', assist_date)) FROM Community_Centers WHERE assist_date BETWEEN '2021-07-01' AND '2021-09-30' GROUP BY cc_name;


Question: Generate PostgreSQL SQL for: Who was perfomer one on 30 January 1988?

CREATE TABLE table_14934885_1 (performer_1 VARCHAR, date VARCHAR)

SELECT performer_1 FROM table_14934885_1 WHERE date = '30 January 1988';


Question: Generate PostgreSQL SQL for: What is the record when the score was 2–0?

CREATE TABLE table_name_45 (record VARCHAR, score VARCHAR)

SELECT record FROM table_name_45 WHERE score = '2–0';


Question: Generate PostgreSQL SQL for: Where was home with a record of 7–5–2?

CREATE TABLE table_name_77 (home VARCHAR, record VARCHAR)

SELECT home FROM table_name_77 WHERE record = '7–5–2';


Question: Generate PostgreSQL SQL for: What was the result when the time was 4:15?

CREATE TABLE table_name_66 (res VARCHAR, time VARCHAR)

SELECT res FROM table_name_66 WHERE time = '4:15';


Question: What is the average operational cost of monitoring stations in the 'monitoring_stations' table, grouped by country?

CREATE TABLE monitoring_stations (station_id INT, station_name VARCHAR(50), country VARCHAR(50), operational_cost FLOAT); INSERT INTO monitoring_stations (station_id, station_name, country, operational_cost) VALUES (1, 'Station A', 'Australia', 50000.0), (2, 'Station B', 'New Zealand', 60000.0), (3, 'Station C', 'Australia', 55000.0);

SELECT country, AVG(operational_cost) FROM monitoring_stations GROUP BY country;


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

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

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


Question: Generate PostgreSQL SQL for: how many geo id with 48.578664 are

CREATE TABLE table_18600760_19 (geo_id VARCHAR, latitude VARCHAR)

SELECT COUNT(geo_id) FROM table_18600760_19 WHERE latitude = '48.578664';


Question: Display the number of unique traditional art forms in each country.

CREATE TABLE Country_Art_Count (country TEXT, art_count INT); INSERT INTO Country_Art_Count (country, art_count) VALUES ('Japan', 2); INSERT INTO Country_Art_Count (country, art_count) VALUES ('India', 3);

SELECT country, COUNT(*) AS unique_art_forms FROM (SELECT DISTINCT name, country FROM Traditional_Arts) AS unique_arts GROUP BY country;


Question: Generate PostgreSQL SQL for: After how many opponents was the overall record 1-0-0?

CREATE TABLE table_20928682_1 (opponents VARCHAR, record VARCHAR)

SELECT COUNT(opponents) FROM table_20928682_1 WHERE record = '1-0-0';


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

INSERT INTO toasted_several(toasted_key) VALUES(repeat('9876543210', 10000));

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


Question: Show a query using PostgreSQL contrib extension 'amcheck' (example 18).

SELECT sum(reads) AS stats_bulkreads_before
  FROM pg_stat_io WHERE context = 'bulkread' \gset
BEGIN;

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


Question: What is the maximum speed of the fastest autonomous vehicle?

CREATE TABLE AutonomousVehicles (Id INT, Name VARCHAR(100), MaxSpeed FLOAT); INSERT INTO AutonomousVehicles (Id, Name, MaxSpeed) VALUES (1, 'Apollo', 240), (2, 'Buddy', 150), (3, 'RoboCar', 180);

SELECT MAX(MaxSpeed) FROM AutonomousVehicles;


Question: Calculate the maximum and minimum salary for each job title in the "employee_data" and "jobs" tables

CREATE TABLE employee_data (id INT, job_title VARCHAR(20), salary DECIMAL(10,2)); INSERT INTO employee_data (id, job_title, salary) VALUES (1, 'Engineer', 80000.00), (2, 'Engineer', 85000.00), (3, 'Technician', 60000.00), (4, 'Technician', 65000.00); CREATE TABLE jobs (id INT, title VARCHAR(20)); INSERT INTO jobs (id, title) VALUES (1, 'Engineer'), (2, 'Technician');

SELECT j.title, MAX(ed.salary) as max_salary, MIN(ed.salary) as min_salary FROM employee_data ed JOIN jobs j ON ed.job_title = j.title GROUP BY j.title;


Question: Generate PostgreSQL SQL for: What is the domestic figure when cargo tonnes equal 25 866?

CREATE TABLE table_name_61 (domestic VARCHAR, cargo__tonnes_ VARCHAR)

SELECT domestic FROM table_name_61 WHERE cargo__tonnes_ = '25 866';


Question: What are the names of the projects in the 'Transportation' table?

CREATE TABLE Transportation (project_id INT, project_name VARCHAR(50), location VARCHAR(50)); INSERT INTO Transportation (project_id, project_name, location) VALUES (1, 'Bridge Replacement', 'Texas'); INSERT INTO Transportation (project_id, project_name, location) VALUES (2, 'Road Construction', 'Florida');

SELECT project_name FROM Transportation;


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

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


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

select * from numrange_test where nr < numrange(0.0, 1.0,'[]');

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

SELECT count(*) FROM (select * from numrange_test where nr < numrange(0.0, 1.0,'[]')) AS _sub;


Question: Identify the number of genetically modified ingredients in dishes served at 'The Green Table'.

CREATE TABLE dishes_gm (dish_id INT, name VARCHAR(50), gm_ingredients INT); INSERT INTO dishes_gm VALUES (1, 'Veggie Burger', 1); INSERT INTO dishes_gm VALUES (2, 'Sweet Potato Fries', 0); CREATE TABLE served_at (dish_id INT, location VARCHAR(50)); INSERT INTO served_at VALUES (1, 'The Green Table'); INSERT INTO served_at VALUES (2, 'The Green Table');

SELECT COUNT(dg.gm_ingredients) FROM dishes_gm dg JOIN served_at sa ON dg.dish_id = sa.dish_id WHERE sa.location = 'The Green Table';


Question: Which organizations received donations from donors located in a specific city, based on the 'donations', 'donors', and 'organizations' tables?

CREATE TABLE organizations (id INT, organization_name TEXT, organization_city TEXT);CREATE TABLE donors (id INT, name TEXT, email TEXT, donor_city TEXT);CREATE TABLE donations (id INT, donor_id INT, organization_id INT, amount DECIMAL(10,2), donation_date DATE);

SELECT organizations.organization_name FROM organizations INNER JOIN donations ON organizations.id = donations.organization_id INNER JOIN donors ON donations.donor_id = donors.id WHERE donors.donor_city = 'San Francisco';


Question: Write the DDL statement from PostgreSQL regression test 'stats_import' (example 126).

CREATE STATISTICS stats_import.test_stat_ndistinct_exprs (ndistinct)
  ON lower(name), upper(name)
  FROM stats_import.test;

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


Question: Show a query using PostgreSQL contrib extension 'jsonb_plpython' (example 30).

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


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

CREATE FUNCTION crosstab(text,text)
RETURNS setof record
AS 'MODULE_PATHNAME','crosstab_hash'
LANGUAGE C STABLE STRICT;

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


Question: Generate PostgreSQL SQL for: Which church was built in 1600?

CREATE TABLE table_name_38 (church_name VARCHAR, year_built VARCHAR)

SELECT church_name FROM table_name_38 WHERE year_built = 1600;


Question: Generate PostgreSQL SQL for: Which Founded  has a League of women's flat track derby association, and a Club of omaha rollergirls?

CREATE TABLE table_name_14 (founded INTEGER, league VARCHAR, club VARCHAR)

SELECT AVG(founded) FROM table_name_14 WHERE league = 'women's flat track derby association' AND club = 'omaha rollergirls';


Question: Generate PostgreSQL SQL for: Andy Roddick is the opponent in the final on what surface?

CREATE TABLE table_26202788_7 (surface VARCHAR, opponent_in_the_final VARCHAR)

SELECT surface FROM table_26202788_7 WHERE opponent_in_the_final = 'Andy Roddick';


Question: Show an example of PostgreSQL SELECT (example 2).

SELECT name FROM distributors ORDER BY code;

Explanation: PostgreSQL SELECT command.


Question: How many cruelty-free ingredients are used in total across all products?

CREATE TABLE Product (id INT, productName VARCHAR(50), price DECIMAL(5,2)); INSERT INTO Product (id, productName, price) VALUES (4, 'Blush', 14.99), (5, 'Foundation', 29.99), (6, 'Lip Liner', 16.99); CREATE TABLE Ingredient (id INT, productId INT, ingredient VARCHAR(50), sourceCountry VARCHAR(50), crueltyFree BOOLEAN); INSERT INTO Ingredient (id, productId, ingredient, sourceCountry, crueltyFree) VALUES (6, 4, 'Shea Butter', 'Ghana', true), (7, 4, 'Rosehip Oil', 'Chile', true), (8, 5, 'Vitamin E', 'Argentina', true), (9, 5, 'Zinc Oxide', 'Australia', true), (10, 6, 'Jojoba Oil', 'Peru', true);

SELECT SUM(I.crueltyFree) as totalCrueltyFreeIngredients FROM Ingredient I;


Question: What is the average age of patients with diabetes in the Northern rural areas of Canada?

CREATE TABLE patients (id INT, age INT, has_diabetes BOOLEAN); INSERT INTO patients (id, age, has_diabetes) VALUES (1, 50, true), (2, 60, false); CREATE TABLE locations (id INT, region VARCHAR, is_rural BOOLEAN); INSERT INTO locations (id, region, is_rural) VALUES (1, 'Northern', true), (2, 'Southern', false);

SELECT AVG(patients.age) FROM patients INNER JOIN locations ON patients.id = locations.id WHERE patients.has_diabetes = true AND locations.region = 'Northern';


Question: Generate PostgreSQL SQL for: What is the rural population percentage in 1979?

CREATE TABLE table_16645_1 (__percentage VARCHAR, rural INTEGER, year__january_ VARCHAR)

SELECT MIN(rural), __percentage FROM table_16645_1 WHERE year__january_ = 1979;


Question: What is the maximum fare for passengers using the 'South' bus route in the last week?

CREATE TABLE Routes (RouteID int, RouteName varchar(255), Region varchar(255)); INSERT INTO Routes (RouteID, RouteName, Region) VALUES (1, 'North', 'East'), (2, 'South', 'Central'), (3, 'West', 'West'), (4, 'Red Line', 'East'), (5, 'Green Line', 'North'), (6, 'Blue Line', 'West'), (7, 'South', 'South'); CREATE TABLE Trips (TripID int, RouteID int, Fare double, TripDateTime datetime);

SELECT MAX(Fare) FROM Routes JOIN Trips ON Routes.RouteID = Trips.RouteID WHERE Routes.RouteName = 'South' AND Trips.TripDateTime >= DATEADD(week, -1, GETDATE());


Question: Generate PostgreSQL SQL for: How many years were there with 348 attempts?

CREATE TABLE table_1037590_1 (yards VARCHAR, attempts VARCHAR)

SELECT COUNT(yards) FROM table_1037590_1 WHERE attempts = 348;


Question: How many unique visitors have attended events at 'Art Gallery' in 2021?

CREATE TABLE if not exists venue (id INT, name VARCHAR(50)); CREATE TABLE if not exists event_calendar (id INT, venue_id INT, event_date DATE); INSERT INTO venue (id, name) VALUES (1, 'Art Gallery'); INSERT INTO event_calendar (id, venue_id, event_date) VALUES (1, 1, '2021-01-01'), (2, 1, '2021-03-12'), (3, 1, '2022-05-28');

SELECT COUNT(DISTINCT e.id) FROM event_calendar ec JOIN (SELECT DISTINCT id FROM event_attendees) e ON ec.id = e.id WHERE ec.venue_id = (SELECT id FROM venue WHERE name = 'Art Gallery') AND ec.event_date BETWEEN '2021-01-01' AND '2021-12-31';


Question: Show a SQL definition from the citus project (merge_repartition2, item 19).

CREATE OR REPLACE FUNCTION setup_data() RETURNS VOID SET search_path TO merge_repartition2_schema AS $$
    INSERT INTO pg_source SELECT i, i+1, 1 FROM generate_series(1, 100000) i;
    INSERT INTO pg_target SELECT i, 1 FROM generate_series(50001, 100000) i;
    INSERT INTO citus_source SELECT i, i+1, 1 FROM generate_series(1, 100000) i;
    INSERT INTO citus_target SELECT i, 1 FROM generate_series(50001, 100000) i;
$$
LANGUAGE SQL;

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


Question: Write the DML statement from PostgreSQL regression test 'inherit' (example 16).

Explanation: DML from PostgreSQL core regression test for Inherit.


Question: Generate PostgreSQL SQL for: What is the number of points when the draws are more than 1?

CREATE TABLE table_name_57 (points VARCHAR, draw INTEGER)

SELECT COUNT(points) FROM table_name_57 WHERE draw > 1;


Question: Generate PostgreSQL SQL for: Which Opposition has a Year smaller than 1977, and a City of manchester?

CREATE TABLE table_name_53 (opposition VARCHAR, year VARCHAR, city VARCHAR)

SELECT opposition FROM table_name_53 WHERE year < 1977 AND city = 'manchester';


Question: Add a new teacher with a unique teacher_id, teacher_name, and assignment to a school, updating the corresponding school record accordingly.

CREATE TABLE schools (school_id INT, school_name TEXT); CREATE TABLE teachers (teacher_id INT, teacher_name TEXT, school_id INT);

INSERT INTO teachers (teacher_id, teacher_name, school_id) VALUES (98765, 'Mx. Lopez', 4321); UPDATE schools s SET s.teacher_id = 98765 WHERE EXISTS (SELECT * FROM teachers t WHERE t.school_id = s.school_id AND s.teacher_id != 98765);


Question: Insert new records for 5 users who joined in the past week.

CREATE TABLE users (id INT, name TEXT, signup_date DATE);   INSERT INTO users (id, name, signup_date) VALUES (1, 'Alice', '2022-01-01'), (2, 'Bob', '2022-01-02'), (3, 'Charlie', '2022-01-03');


Question: Delete the concert with ID 1.

CREATE TABLE Concerts (ConcertID INT, ArtistID INT, Venue VARCHAR(100), TicketsSold INT); INSERT INTO Concerts (ConcertID, ArtistID, Venue, TicketsSold) VALUES (1, 1, 'New York', 5000); INSERT INTO Concerts (ConcertID, ArtistID, Venue, TicketsSold) VALUES (2, 5, 'Seoul', 8000);

DELETE FROM Concerts WHERE ConcertID = 1;


Question: What is the total budget allocated for policy advocacy in the last quarter?

CREATE TABLE PolicyAdvocacy (PolicyAdvocacyID INT, PolicyName VARCHAR(50), Budget DECIMAL(5,2)); INSERT INTO PolicyAdvocacy (PolicyAdvocacyID, PolicyName, Budget) VALUES (1, 'Accessibility Laws', 5000.00); INSERT INTO PolicyAdvocacy (PolicyAdvocacyID, PolicyName, Budget) VALUES (2, 'Inclusion Programs', 7000.00);

SELECT SUM(Budget) as TotalBudget FROM PolicyAdvocacy WHERE Date BETWEEN DATEADD(quarter, -1, GETDATE()) AND GETDATE();


Question: What is the total weight of shipments to a given country from all continents?

CREATE TABLE shipments (id INT, origin_continent VARCHAR(255), destination_country VARCHAR(255), weight FLOAT); INSERT INTO shipments (id, origin_continent, destination_country, weight) VALUES (1, 'Asia', 'Australia', 700.0), (2, 'Africa', 'Australia', 800.0);

SELECT destination_country, SUM(weight) as total_weight FROM shipments GROUP BY destination_country;


Question: Generate PostgreSQL SQL for: What is the location of Blanca Peak?

CREATE TABLE table_name_77 (location VARCHAR, mountain_peak VARCHAR)

SELECT location FROM table_name_77 WHERE mountain_peak = 'blanca peak';


Question: What is the average horsepower of vehicles manufactured in Japan?

CREATE TABLE Vehicles (id INT, make VARCHAR(50), model VARCHAR(50), horsepower INT, country VARCHAR(50)); INSERT INTO Vehicles (id, make, model, horsepower, country) VALUES (1, 'Toyota', 'Corolla', 139, 'Japan');

SELECT AVG(horsepower) FROM Vehicles WHERE country = 'Japan';


Question: Insert new virtual tours that recently became available.

CREATE TABLE virtual_tours (tour_id INT, tour_name TEXT, location TEXT, price DECIMAL(5,2)); INSERT INTO virtual_tours (tour_id, tour_name, location, price) VALUES (1, 'Louvre VR Experience', 'Paris', 24.99), (2, 'Gondola Tour in Venice', 'Venice', 19.99), (3, 'Great Wall of China Virtual Walk', 'China', 29.99);

INSERT INTO virtual_tours (tour_id, tour_name, location, price) VALUES (4, 'Petra Virtual Tour', 'Jordan', 22.99), (5, 'Galapagos Islands Virtual Experience', 'Ecuador', 34.99), (6, 'Angkor Wat Virtual Reality Tour', 'Cambodia', 27.99);


Question: Generate PostgreSQL SQL for: What's  the voltage of the model with part number TT80503300?

CREATE TABLE table_24096813_15 (voltage VARCHAR, part_number_s_ VARCHAR)

SELECT voltage FROM table_24096813_15 WHERE part_number_s_ = 'TT80503300';


Question: Generate PostgreSQL SQL for: what was the score of the Championship match played in Estoril, Portugal?

CREATE TABLE table_name_92 (score_in_the_final VARCHAR, championship VARCHAR)

SELECT score_in_the_final FROM table_name_92 WHERE championship = 'estoril, portugal';


Question: What percentage of total donations went towards education initiatives in 2019?

CREATE TABLE donors (id INT, name TEXT);CREATE TABLE donations (id INT, donor_id INT, amount DECIMAL, donation_date DATE, initiative_category TEXT);

SELECT (SUM(CASE WHEN initiative_category = 'education' THEN donations.amount ELSE 0 END) / SUM(donations.amount)) * 100 as education_percentage FROM donations WHERE YEAR(donation_date) = 2019;


Question: What is the total horsepower of vehicles released in 2017?

CREATE TABLE VehicleData (Id INT, Name VARCHAR(50), Year INT, Horsepower INT); INSERT INTO VehicleData (Id, Name, Year, Horsepower) VALUES (1, 'Corvette', 2017, 460), (2, '911 Turbo', 2017, 540), (3, 'M4 GTS', 2016, 493);

SELECT SUM(Horsepower) FROM VehicleData WHERE Year = 2017;


Question: List all underwater volcanoes near the Mariana Trench.

CREATE TABLE underwater_volcanoes (id INT, name TEXT, lat FLOAT, lon FLOAT, depth INT); INSERT INTO underwater_volcanoes (id, name, lat, lon, depth) VALUES (1, 'NW Rota-1', 14.05, 145.75, 5367), (2, 'Ferdinand De Lesseps', 11.87, 142.33, 4000); CREATE TABLE mariana_trench (id INT, point TEXT, lat FLOAT, lon FLOAT); INSERT INTO mariana_trench (id, point, lat, lon) VALUES (1, 'Challenger Deep', 11.23, 142.19), (2, 'Sirena Deep', 11.20, 142.15);

SELECT uv.name FROM underwater_volcanoes uv INNER JOIN mariana_trench mt ON uv.lat BETWEEN mt.lat - 1 AND mt.lat + 1 AND uv.lon BETWEEN mt.lon - 1 AND mt.lon + 1;


Question: Which countries have the most female film directors?

CREATE TABLE country (country_id INT, country_name VARCHAR(50)); INSERT INTO country (country_id, country_name) VALUES (1, 'United States'), (2, 'Canada'), (3, 'France'); CREATE TABLE film_director (director_id INT, director_name VARCHAR(50), country_id INT); INSERT INTO film_director (director_id, director_name, country_id) VALUES (1, 'Ava DuVernay', 1), (2, 'Xavier Dolan', 2), (3, 'Celine Sciamma', 3);

SELECT country_name, COUNT(*) as num_female_directors FROM film_director fd JOIN country c ON fd.country_id = c.country_id WHERE director_name = 'Ava DuVernay' OR director_name = 'Celine Sciamma' GROUP BY country_name ORDER BY num_female_directors DESC;


Question: Generate PostgreSQL SQL for: Which player has less than 201 games, is ranked 2, and played between 2007-2012?

CREATE TABLE table_name_74 (player VARCHAR, years VARCHAR, games VARCHAR, rank VARCHAR)

SELECT player FROM table_name_74 WHERE games < 201 AND rank = 2 AND years = '2007-2012';


Question: What is the total budget allocated for transportation services in Brazil in 2019?

CREATE SCHEMA br_schema;CREATE TABLE br_schema.transportation_budget (year INT, service VARCHAR(20), amount INT);INSERT INTO br_schema.transportation_budget (year, service, amount) VALUES (2019, 'Transportation', 20000000);

SELECT amount FROM br_schema.transportation_budget WHERE year = 2019 AND service = 'Transportation';


Question: Generate PostgreSQL SQL for: How many total medals for the nation with 1 gold and 6 bronzes?

CREATE TABLE table_name_52 (total VARCHAR, gold VARCHAR, bronze VARCHAR)

SELECT COUNT(total) FROM table_name_52 WHERE gold = 1 AND bronze = 6;


Question: Generate PostgreSQL SQL for: Which network has model nForce Professional 3400 MCP?

CREATE TABLE table_name_29 (network VARCHAR, model VARCHAR)

SELECT network FROM table_name_29 WHERE model = 'nforce professional 3400 mcp';


Question: Generate PostgreSQL SQL for: What is the Score of the Tournament with Opponent in the final of Martin Spottl?

CREATE TABLE table_name_70 (score VARCHAR, opponent_in_the_final VARCHAR)

SELECT score FROM table_name_70 WHERE opponent_in_the_final = 'martin spottl';


Question: Generate PostgreSQL SQL for: What name is in the number 2 spot when Ethan is in the number 6 spot and Mason is in the number 3 spot?

CREATE TABLE table_name_7 (no_2 VARCHAR, no_6 VARCHAR, no_3 VARCHAR)

SELECT no_2 FROM table_name_7 WHERE no_6 = 'ethan' AND no_3 = 'mason';


Question: Generate PostgreSQL SQL for: How many new points were earned by rk 26?

CREATE TABLE table_27615896_18 (new_points VARCHAR, rk VARCHAR)

SELECT new_points FROM table_27615896_18 WHERE rk = 26;


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

CREATE FUNCTION plsample_call_handler() RETURNS language_handler AS '$libdir/plsample' LANGUAGE C; CREATE LANGUAGE plsample HANDLER plsample_call_handler;

Explanation: PostgreSQL CREATE LANGUAGE command.


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

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

SELECT count(*) FROM (SELECT ts_lexize('hunspell_num', 'unbooking')) AS _sub;


Question: Generate PostgreSQL SQL for: Which Catalog has a Date of july 15, 2011?

CREATE TABLE table_name_73 (catalog INTEGER, date VARCHAR)

SELECT AVG(catalog) FROM table_name_73 WHERE date = 'july 15, 2011';


Question: What is the average carbon sequestration for each forest type?

CREATE TABLE forests (forest_type VARCHAR(255), year INT, carbon_sequestration INT); INSERT INTO forests (forest_type, year, carbon_sequestration) VALUES ('Temperate', 2018, 500), ('Temperate', 2019, 550), ('Temperate', 2020, 600), ('Temperate', 2021, 650), ('Boreal', 2018, 700), ('Boreal', 2019, 750), ('Boreal', 2020, 800), ('Boreal', 2021, 850), ('Tropical', 2018, 900), ('Tropical', 2019, 950), ('Tropical', 2020, 1000), ('Tropical', 2021, 1050);

SELECT forest_type, AVG(carbon_sequestration) as avg_carbon_sequestration FROM forests GROUP BY forest_type;


Question: What is the minimum salinity in the Pacific Ocean?

CREATE TABLE location (location_id INT, location_name TEXT); INSERT INTO location (location_id, location_name) VALUES (1, 'Pacific Ocean'); CREATE TABLE salinity (salinity_id INT, location_id INT, salinity FLOAT); INSERT INTO salinity (salinity_id, location_id, salinity) VALUES (1, 1, 34.5), (2, 1, 34.6), (3, 1, 34.7), (4, 1, 34.8), (5, 1, 34.9);

SELECT MIN(salinity) FROM salinity WHERE location_id = (SELECT location_id FROM location WHERE location_name = 'Pacific Ocean');


Question: What is the total number of articles published by female authors in the 'articles' table?

CREATE TABLE articles (title VARCHAR(255), author_name VARCHAR(255), author_gender VARCHAR(10), publication_date DATE);

SELECT COUNT(*) FROM articles WHERE author_gender = 'female';


Question: Generate PostgreSQL SQL for: How many points were scored against the club that drew 3 and scored 50 points?

CREATE TABLE table_name_60 (points_against VARCHAR, drawn VARCHAR, points VARCHAR)

SELECT points_against FROM table_name_60 WHERE drawn = '3' AND points = '50';


Question: Generate PostgreSQL SQL for: What is the Date of the match with Opponent in the final Kenneth Carlsen?

CREATE TABLE table_name_41 (date VARCHAR, opponent_in_the_final VARCHAR)

SELECT date FROM table_name_41 WHERE opponent_in_the_final = 'kenneth carlsen';


Question: Create a new table named 'tournaments' with columns 'id', 'name', 'location', 'start_date', 'end_date'

CREATE TABLE gaming.tournaments (id INT, name VARCHAR(100), location VARCHAR(100), start_date DATE, end_date DATE);


Question: Generate PostgreSQL SQL for: What is the highest number of silver when there is 1 bronze and less than 4 golds?

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

SELECT MAX(silver) FROM table_name_38 WHERE bronze = 1 AND gold < 4;


Question: Generate PostgreSQL SQL for: Please give me a list of cities whose regional population is over 10000000.

CREATE TABLE city (city VARCHAR, regional_population INTEGER)

SELECT city FROM city WHERE regional_population > 10000000;


Question: Update the response time to 45 minutes for all emergencies in the 'Eastside' district.

CREATE TABLE districts (district_id INT, district_name TEXT);CREATE TABLE emergencies (emergency_id INT, district_id INT, response_time INT);

UPDATE emergencies SET response_time = 45 WHERE district_id = (SELECT district_id FROM districts WHERE district_name = 'Eastside');


Question: Which departments have a budget allocation below the average budget?

CREATE TABLE dept_budget (dept VARCHAR(50), budget INT); INSERT INTO dept_budget (dept, budget) VALUES ('Infrastructure', 800000), ('Education', 700000), ('Health', 900000);

SELECT dept FROM dept_budget WHERE budget < (SELECT AVG(budget) FROM dept_budget);


Question: Generate PostgreSQL SQL for: what was the result on 01x06

CREATE TABLE table_29141354_1 (scores VARCHAR, episode VARCHAR)

SELECT scores FROM table_29141354_1 WHERE episode = '01x06';


Question: What is the average yield of potato crops across different countries?

CREATE TABLE Country (id INT, name VARCHAR(255)); INSERT INTO Country (id, name) VALUES (1, 'Canada'), (2, 'Mexico'), (3, 'Brazil'); CREATE TABLE Crop (id INT, name VARCHAR(255), yield INT); INSERT INTO Crop (id, name, yield) VALUES (1, 'Potato', 25), (2, 'Corn', 75), (3, 'Potato', 15);

SELECT AVG(Crop.yield) FROM Crop INNER JOIN Country ON Crop.id = Country.id WHERE Crop.name = 'Potato';


Question: Generate PostgreSQL SQL for: How many genes are in species burkholderia pseudomallei with 4,126,292 base pairs?

CREATE TABLE table_name_13 (genes VARCHAR, species VARCHAR, base_pairs VARCHAR)

SELECT genes FROM table_name_13 WHERE species = 'burkholderia pseudomallei' AND base_pairs = '4,126,292';


Question: PostgreSQL regression test 'xmlmap': Write the SELECT query (example 26).

SELECT cursor_to_xml('xc'::refcursor, 5, false, true, '');

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

SELECT count(*) FROM (SELECT cursor_to_xml('xc'::refcursor, 5, false, true, '')) AS _sub;


Question: What is the average response time for emergency calls in the state of Illinois, excluding calls that took more than 20 minutes to respond?

CREATE TABLE emergency_calls (id INT, state VARCHAR(20), response_time INT);

SELECT AVG(response_time) FROM emergency_calls WHERE state = 'Illinois' AND response_time < 20*60;


Question: What is the number of art pieces created by artists from different countries in the oil painting medium?

CREATE SCHEMA art; CREATE TABLE art_pieces (art_id INT, art_name VARCHAR(255), artist_name VARCHAR(255), artist_country VARCHAR(50), medium VARCHAR(50), creation_date DATE); INSERT INTO art.art_pieces (art_id, art_name, artist_name, artist_country, medium, creation_date) VALUES (1, 'Painting', 'Sarah Johnson', 'USA', 'Oil', '2018-01-01'), (2, 'Sculpture', 'Mia Kim', 'South Korea', 'Bronze', '2019-05-15'), (3, 'Print', 'Jamie Lee', 'Canada', 'Woodcut', '2020-12-31'), (4, 'Installation', 'David Park', 'Mexico', 'Mixed Media', '2020-06-01'), (5, 'Painting', 'David Park', 'Brazil', 'Watercolor', '2019-12-31');

SELECT artist_country, COUNT(*) as count FROM art.art_pieces WHERE medium = 'Oil' GROUP BY artist_country;


Question: What is the total number of accessible technology projects, and how many of those are in Africa?

CREATE TABLE accessible_tech_projects (id INT, country VARCHAR(2), project_accessibility VARCHAR(10)); INSERT INTO accessible_tech_projects (id, country, project_accessibility) VALUES (1, 'US', 'yes'), (2, 'CA', 'no'), (3, 'MX', 'yes'), (4, 'BR', 'yes'), (5, 'AR', 'no'), (6, 'NG', 'yes'), (7, 'EG', 'no'), (8, 'ZA', 'yes'), (9, 'ET', 'no'), (10, 'GH', 'yes');

SELECT COUNT(*) FROM accessible_tech_projects WHERE project_accessibility = 'yes' AND country IN ('NG', 'EG', 'ZA', 'ET', 'GH');


Question: What is the total quantity of sustainable ingredients used in each dish, categorized by restaurant location?

CREATE TABLE Restaurants (RestaurantID INT, Location VARCHAR(50), OpenDate DATETIME); CREATE TABLE Menu (MenuID INT, RestaurantID INT, Name VARCHAR(50), Price DECIMAL(5,2), IsSustainable BOOLEAN); CREATE TABLE Ingredients (IngredientID INT, MenuID INT, Name VARCHAR(50), Quantity INT, IsSustainable BOOLEAN);

SELECT Restaurants.Location, SUM(CASE WHEN Ingredients.IsSustainable THEN Ingredients.Quantity ELSE 0 END) as TotalSustainableQuantity FROM Restaurants JOIN Menu ON Restaurants.RestaurantID = Menu.RestaurantID JOIN Ingredients ON Menu.MenuID = Ingredients.MenuID GROUP BY Restaurants.Location;


Question: What is the average speed of shared electric scooters in Portland, OR?

CREATE TABLE shared_scooters (scooter_id INT, ride_id INT, trip_start_time TIMESTAMP, trip_end_time TIMESTAMP, start_location TEXT, end_location TEXT, city TEXT, vehicle_type TEXT, avg_speed DECIMAL);

SELECT AVG(avg_speed) FROM shared_scooters WHERE city = 'Portland' AND vehicle_type = 'electric scooter';


Question: List the unique neighborhoods where both 'Burglary' and 'Theft' occurred in the last month, excluding neighborhoods with fewer than 2 total crimes.

CREATE TABLE Crimes (crime_id INT, crime_type VARCHAR(10), neighborhood VARCHAR(20), date DATE); INSERT INTO Crimes VALUES (1, 'Burglary', 'Parkside', '2022-01-01'), (2, 'Theft', 'Parkside', '2022-01-03'), (3, 'Burglary', 'Downtown', '2022-01-05'), (4, 'Theft', 'Downtown', '2022-01-07'), (5, 'Assault', 'Parkside', '2022-01-09'), (6, 'Assault', 'Downtown', '2022-01-11');

SELECT neighborhood FROM Crimes WHERE crime_type IN ('Burglary', 'Theft') AND date >= DATEADD(month, -1, CURRENT_TIMESTAMP) GROUP BY neighborhood HAVING COUNT(DISTINCT crime_type) = 2 AND COUNT(*) >= 2;


Question: Generate PostgreSQL SQL for: What is the average against that has a drawn less than 7, points greater than 22, and 19 for the played?

CREATE TABLE table_name_66 (against INTEGER, played VARCHAR, drawn VARCHAR, points VARCHAR)

SELECT AVG(against) FROM table_name_66 WHERE drawn < 7 AND points > 22 AND played = 19;


Question: Generate PostgreSQL SQL for: Who is the Shirt Back Sponsor if the Shorts Sponsor is Telestet?

CREATE TABLE table_name_69 (shirt_back_sponsor VARCHAR, shorts_sponsor VARCHAR)

SELECT shirt_back_sponsor FROM table_name_69 WHERE shorts_sponsor = 'telestet';


Question: Generate PostgreSQL SQL for: What is the series number for the episode directed by  jay sandrich that aired October 23, 1986?

CREATE TABLE table_2818164_4 (no_in_series INTEGER, directed_by VARCHAR, original_air_date VARCHAR)

SELECT MIN(no_in_series) FROM table_2818164_4 WHERE directed_by = 'Jay Sandrich' AND original_air_date = 'October 23, 1986';


Question: Which users have posted on consecutive days?

SELECT user_id FROM (SELECT user_id, post_date, DATEDIFF(day, LAG(post_date) OVER (PARTITION BY user_id ORDER BY post_date), post_date) AS gap FROM posts) AS t WHERE gap = 1 GROUP BY user_id;


Question: Generate PostgreSQL SQL for: During the Tournament in which Jiří Novák was absent(A) in 1995, absent(A) in 1997, and made it to the 3rd round (3R) in 2003, how did he do in 2006?

SELECT 2006 FROM table_name_31 WHERE 1995 = 'a' AND 1997 = 'a' AND 2003 = '3r';


Question: What is the average ticket price for concerts in the 'concert_tours' table?

CREATE TABLE concert_tours (concert_id INT, concert_name TEXT, artist_id INT, location TEXT, date DATE, price DECIMAL(5,2));


Question: Delete all satellites deployed before 2010

DELETE FROM satellites WHERE launch_date < '2010-01-01';


Question: What is the number of projects and their total budget for each type of project?

CREATE TABLE projects_4 (id INT, name VARCHAR, type VARCHAR, budget FLOAT); INSERT INTO projects_4 (id, name, type, budget) VALUES (1, 'AI for good', 'AI', 100000), (2, 'Accessible software development', 'Accessibility', 150000), (3, 'Digital divide reduction', 'Digital divide', 200000);

SELECT projects_4.type, COUNT(*), SUM(projects_4.budget) FROM projects_4 GROUP BY projects_4.type;


Question: Find the average temperature (in Celsius) and humidity (in percentage) for the past 30 days from IoT sensors in the 'Field1'

CREATE TABLE iot_sensors (id INT, field VARCHAR(50), temperature FLOAT, humidity FLOAT, timestamp DATETIME); INSERT INTO iot_sensors (id, field, temperature, humidity, timestamp) VALUES (1, 'Field1', 22.5, 60.0, '2022-01-01 10:00:00'), (2, 'Field1', 25.0, 55.0, '2022-01-02 10:00:00');

SELECT AVG(temperature) as avg_temperature, AVG(humidity) as avg_humidity FROM iot_sensors WHERE timestamp BETWEEN DATE_SUB(CURRENT_TIMESTAMP, INTERVAL 30 DAY) AND CURRENT_TIMESTAMP AND field = 'Field1';


Question: How many unique cities hosted basketball games in 2020?

CREATE TABLE cities (id INT, name VARCHAR(255), games_hosted INT); INSERT INTO cities (id, name, games_hosted) VALUES (1, 'City1', 5); INSERT INTO cities (id, name, games_hosted) VALUES (2, 'City2', 3);

SELECT COUNT(DISTINCT name) FROM cities WHERE games_hosted > 0 AND EXTRACT(YEAR FROM games_hosted_date) = 2020 AND name IN (SELECT city FROM games WHERE sport = 'Basketball');


Question: Generate PostgreSQL SQL for: In which Tournament was Mansour Bahrami Eric Winogradsky

CREATE TABLE table_name_9 (tournament VARCHAR, opponent_in_final VARCHAR)

SELECT tournament FROM table_name_9 WHERE opponent_in_final = 'mansour bahrami eric winogradsky';


Question: What is the minimum number of accommodations provided to a single student with a mobility impairment in the art department?

CREATE TABLE students (id INT, mobility_impairment BOOLEAN, department VARCHAR(255)); INSERT INTO students (id, mobility_impairment, department) VALUES (1, true, 'art'), (2, false, 'engineering'), (3, true, 'art'), (4, true, 'mathematics'), (5, false, 'art'), (6, true, 'art'); CREATE TABLE accommodations (id INT, student_id INT, year INT); INSERT INTO accommodations (id, student_id, year) VALUES (1, 1, 2018), (2, 1, 2019), (3, 3, 2018), (4, 3, 2019), (5, 3, 2020), (6, 4, 2020), (7, 5, 2018), (8, 5, 2019), (9, 5, 2020), (10, 5, 2021), (11, 6, 2018), (12, 6, 2019), (13, 6, 2020), (14, 6, 2021);

SELECT MIN(accommodations) FROM (SELECT student_id, COUNT(*) as accommodations FROM accommodations GROUP BY student_id) as subquery WHERE student_id IN (SELECT id FROM students WHERE mobility_impairment = true AND department = 'art');


Question: List all collaborations between artists of different genres in the last year.

CREATE TABLE Collaborations (CollaborationId INT, Artist1 VARCHAR(255), Genre1 VARCHAR(255), Artist2 VARCHAR(255), Genre2 VARCHAR(255), CollaborationDate DATE); INSERT INTO Collaborations (CollaborationId, Artist1, Genre1, Artist2, Genre2, CollaborationDate) VALUES (1, 'Drake', 'Hip Hop', 'Ariana Grande', 'Pop', '2021-03-26'), (2, 'Post Malone', 'Rap Rock', 'Swae Lee', 'R&B', '2021-06-12'), (3, 'Justin Bieber', 'Pop', 'Chance the Rapper', 'Hip Hop', '2022-01-15'), (4, 'Lady Gaga', 'Pop', 'Tony Bennett', 'Jazz', '2021-10-01'), (5, 'Kendrick Lamar', 'Hip Hop', 'Sia', 'Pop', '2022-02-20');

SELECT Artist1, Genre1, Artist2, Genre2 FROM Collaborations WHERE CollaborationDate >= DATE_SUB(CURDATE(), INTERVAL 1 YEAR) AND Genre1 <> Genre2;


Question: Generate PostgreSQL SQL for: What is the total round of the 129 pick?

CREATE TABLE table_name_49 (round VARCHAR, pick__number VARCHAR)

SELECT COUNT(round) FROM table_name_49 WHERE pick__number = 129;


Question: PL/pgSQL test: Plpython Composite (example 83).

SELECT * FROM return_record_2('v4') AS (v1 int, v4 int, v2 int);

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


Question: Generate PostgreSQL SQL for: What is the average births that had a death rate of 0.4

CREATE TABLE table_name_38 (births__000s_ INTEGER, deaths VARCHAR)

SELECT AVG(births__000s_) FROM table_name_38 WHERE deaths = 0.4;


Question: Write the DDL statement from PostgreSQL regression test 'hash_index' (example 21).

create unique index hash_f8_index_3 on hash_f8_heap(random) where seqno > 1000;

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


Question: Generate PostgreSQL SQL for: What was their record on Wed. Dec. 5, when they played in Boston Garden?

CREATE TABLE table_name_11 (record VARCHAR, location VARCHAR, date VARCHAR)

SELECT record FROM table_name_11 WHERE location = 'boston garden' AND date = 'wed. dec. 5';


Question: Generate PostgreSQL SQL for: What was the career duration of the bowler who played 60 matches?

CREATE TABLE table_18914438_1 (career VARCHAR, matches VARCHAR)

SELECT career FROM table_18914438_1 WHERE matches = 60;


Question: Update the automation trend for May 5, 2022

CREATE TABLE automation_trends (date DATETIME, trend_data VARCHAR(500));

UPDATE automation_trends SET trend_data = '...' WHERE date = '2022-05-05';


Question: How many co-owned properties are there in Austin, TX?

CREATE TABLE properties (id INT, city VARCHAR(50), co_ownership BOOLEAN); INSERT INTO properties (id, city, co_ownership) VALUES (1, 'Austin', true), (2, 'Dallas', false);

SELECT COUNT(*) FROM properties WHERE city = 'Austin' AND co_ownership = true;


Question: Generate PostgreSQL SQL for: Name the transfer wind for giuly

CREATE TABLE table_name_15 (transfer_window VARCHAR, name VARCHAR)

SELECT transfer_window FROM table_name_15 WHERE name = 'giuly';


Question: Generate PostgreSQL SQL for: Tell me the Hindu with Jewish of source: uk 2001 census

CREATE TABLE table_name_87 (hindu VARCHAR, jewish VARCHAR)

SELECT hindu FROM table_name_87 WHERE jewish = 'source: uk 2001 census';


Question: Generate PostgreSQL SQL for: Where is the Westfield State University located?

CREATE TABLE table_1974545_2 (location VARCHAR, institution VARCHAR)

SELECT location FROM table_1974545_2 WHERE institution = 'Westfield State University';


Question: Generate PostgreSQL SQL for: What is the upstream for the internet 100 plans?

CREATE TABLE table_name_42 (upstream VARCHAR, internet_plan VARCHAR)

SELECT upstream FROM table_name_42 WHERE internet_plan = 'internet 100';


Question: Find the number of players who have played "Fighting Game F" and identify their gender.

CREATE TABLE Fighting_Game_F (player_id INT, name VARCHAR(50), age INT, gender VARCHAR(10)); INSERT INTO Fighting_Game_F (player_id, name, age, gender) VALUES (2, 'Jane Smith', 24, 'Female'), (4, 'Bob Brown', 30, 'Male'), (11, 'Oliver Lee', 26, 'Male');

SELECT COUNT(*), gender FROM Fighting_Game_F GROUP BY gender;


Question: What is the total catch weight for fish in the 'South Atlantic' region?

CREATE TABLE fish_species (id INT, species TEXT, region TEXT); INSERT INTO fish_species (id, species, region) VALUES (1, 'Tuna', 'South Atlantic'), (2, 'Sardines', 'South Atlantic'), (3, 'Mackerel', 'North Atlantic'); CREATE TABLE catch_data (id INT, species TEXT, weight FLOAT); INSERT INTO catch_data (id, species, weight) VALUES (1, 'Tuna', 400), (2, 'Sardines', 600), (3, 'Mackerel', 350);

SELECT SUM(catch_data.weight) FROM catch_data INNER JOIN fish_species ON catch_data.species = fish_species.species WHERE fish_species.region = 'South Atlantic';


Question: Show the total production volume for each mine and year in the "mine_production", "mines", and "calendar" tables

CREATE TABLE mines (id INT, name VARCHAR(20)); INSERT INTO mines (id, name) VALUES (1, 'Golden Mine'), (2, 'Silver Mine'); CREATE TABLE calendar (year INT); INSERT INTO calendar (year) VALUES (2020), (2021), (2022); CREATE TABLE mine_production (mine_id INT, year INT, volume INT); INSERT INTO mine_production (mine_id, year, volume) VALUES (1, 2020, 1000), (1, 2021, 1200), (2, 2022, 1500);

SELECT m.name, c.year, SUM(mp.volume) as total_volume FROM mines m JOIN mine_production mp ON m.id = mp.mine_id JOIN calendar c ON mp.year = c.year GROUP BY m.name, c.year;


Question: What is the percentage of people with access to clean water in Egypt?

CREATE TABLE Water (ID INT, Country VARCHAR(100), Year INT, CleanWaterPercentage FLOAT); INSERT INTO Water (ID, Country, Year, CleanWaterPercentage) VALUES (1, 'Egypt', 2020, 98);

SELECT CleanWaterPercentage FROM Water WHERE Country = 'Egypt' AND Year = 2020;


Question: Create a table for traditional art forms by country.

CREATE TABLE Country_Arts (id INT, country TEXT, art_name TEXT); INSERT INTO Country_Arts (id, country, art_name) VALUES (1, 'Nigeria', 'Uli'); INSERT INTO Country_Arts (id, country, art_name) VALUES (2, 'India', 'Madhubani');


Question: What is the total number of military bases in the 'US_Military_Bases' table?

CREATE SCHEMA IF NOT EXISTS defense_security;CREATE TABLE IF NOT EXISTS defense_security.US_Military_Bases (id INT PRIMARY KEY, base_name VARCHAR(255), location VARCHAR(255), type VARCHAR(255));INSERT INTO defense_security.US_Military_Bases (id, base_name, location, type) VALUES (1, 'Fort Bragg', 'North Carolina', 'Army Base');

SELECT COUNT(*) FROM defense_security.US_Military_Bases;


Question: Generate PostgreSQL SQL for: Which Blagojevich (D) happened on october 16, 2006?

CREATE TABLE table_name_77 (blagojevich__d_ VARCHAR, date VARCHAR)

SELECT blagojevich__d_ FROM table_name_77 WHERE date = 'october 16, 2006';


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

SELECT JSON_SERIALIZE(JSON('{ "a" : 1 } '));

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

SELECT count(*) FROM (SELECT JSON_SERIALIZE(JSON('{ "a" : 1 } '))) AS _sub;


Question: Generate PostgreSQL SQL for: What season shows podium 7?

CREATE TABLE table_29471472_1 (season INTEGER, podiums VARCHAR)

SELECT MIN(season) FROM table_29471472_1 WHERE podiums = 7;


Question: Find the projects that have been completed in both the 'rural_development' and 'urban_development' databases.

CREATE TABLE RuralDevelopment_InfrastructureProjects (id INT PRIMARY KEY, name VARCHAR(100), status VARCHAR(20), evaluation_date DATE); INSERT INTO RuralDevelopment_InfrastructureProjects (id, name, status, evaluation_date) VALUES (1, 'Water Treatment Plant', 'completed', NULL), (2, 'Renewable Energy Center', 'in_progress', '2023-02-28'), (3, 'Rural Connectivity', 'completed', '2022-09-15'); CREATE TABLE UrbanDevelopment_InfrastructureProjects (id INT PRIMARY KEY, name VARCHAR(100), status VARCHAR(20), evaluation_date DATE); INSERT INTO UrbanDevelopment_InfrastructureProjects (id, name, status, evaluation_date) VALUES (1, 'Water Treatment Plant', 'completed', '2022-08-10'), (2, 'Urban Connectivity', 'completed', '2022-07-01'), (3, 'Transportation Center', 'in_progress', '2023-02-28');

SELECT RuralDevelopment_InfrastructureProjects.name FROM RuralDevelopment_InfrastructureProjects INNER JOIN UrbanDevelopment_InfrastructureProjects ON RuralDevelopment_InfrastructureProjects.name = UrbanDevelopment_InfrastructureProjects.name WHERE RuralDevelopment_InfrastructureProjects.status = 'completed' AND UrbanDevelopment_InfrastructureProjects.status = 'completed';


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

CREATE OPERATOR <% (
        LEFTARG = text,
        RIGHTARG = text,
        PROCEDURE = word_similarity_op,
        COMMUTATOR = '%>',
        RESTRICT = contsel,
        JOIN = contjoinsel
);


Question: Generate PostgreSQL SQL for: What round was on 11/11/1992?

CREATE TABLE table_name_91 (round VARCHAR, date VARCHAR)

SELECT round FROM table_name_91 WHERE date = '11/11/1992';


Question: PostgreSQL regression test 'partition_prune': Write the SELECT query (example 135).

select * from boolpart where not a = false;

Explanation: Regression test for Partition Prune in PostgreSQL core test suite.

SELECT count(*) FROM (select * from boolpart where not a = false) AS _sub;


Question: What is the distribution of student mental health scores by grade level, for students who identify as Indigenous or Native Hawaiian?

CREATE TABLE student_mental_health_scores (score_id INT, student_id INT, grade_level INT, mental_health_score INT, student_ethnicity VARCHAR(50));

SELECT grade_level, student_ethnicity, AVG(mental_health_score) FROM student_mental_health_scores WHERE student_ethnicity IN ('Indigenous', 'Native Hawaiian') GROUP BY grade_level, student_ethnicity;


Question: Find dishes with the highest sales per day and their average CO2 emissions.

CREATE TABLE dishes (dish_name VARCHAR(255), daily_sales INT, co2_emissions INT);

SELECT d.dish_name, AVG(d.co2_emissions) as avg_co2, MAX(d.daily_sales) as max_sales FROM dishes d GROUP BY d.dish_name ORDER BY max_sales DESC LIMIT 10;


Question: Generate PostgreSQL SQL for: Name the number of pinyin where simplified is 河西区

CREATE TABLE table_1638437_2 (pinyin VARCHAR, simplified VARCHAR)

SELECT COUNT(pinyin) FROM table_1638437_2 WHERE simplified = '河西区';


Question: Generate PostgreSQL SQL for: Which country has Weerawila Airport?

CREATE TABLE table_name_76 (country VARCHAR, airport VARCHAR)

SELECT country FROM table_name_76 WHERE airport = 'weerawila airport';


Question: What is the total number of donors from Japan and Brazil combined?

CREATE TABLE donors (donor_id INT, donor_name TEXT, donor_country TEXT); INSERT INTO donors (donor_id, donor_name, donor_country) VALUES (1, 'John Doe', 'Japan'), (2, 'Jane Smith', 'USA'), (3, 'Alice Johnson', 'Canada'), (4, 'Carlos Alvarez', 'Brazil'), (5, 'Elizabeth Brown', 'UK');

SELECT COUNT(DISTINCT donor_country) as total_donors FROM donors WHERE donor_country IN ('Japan', 'Brazil');


Question: Which brands offer the most vegan-friendly products?

CREATE TABLE brands (brand_id INT PRIMARY KEY, brand_name VARCHAR(50)); CREATE TABLE products (product_id INT, brand_id INT, PRIMARY KEY (product_id, brand_id), FOREIGN KEY (brand_id) REFERENCES brands(brand_id)); CREATE TABLE vegan_products (product_id INT, brand_id INT, PRIMARY KEY (product_id, brand_id), FOREIGN KEY (product_id) REFERENCES products(product_id), FOREIGN KEY (brand_id) REFERENCES brands(brand_id)); INSERT INTO brands (brand_id, brand_name) VALUES (1, 'Kat Von D'), (2, 'LUSH'), (3, 'The Body Shop'); INSERT INTO products (product_id, brand_id) VALUES (1, 1), (2, 1), (3, 2), (4, 2), (5, 3), (6, 3); INSERT INTO vegan_products (product_id, brand_id) VALUES (1, 1), (2, 1), (3, 2), (5, 3);

SELECT brand_name, COUNT(*) as product_count FROM vegan_products JOIN brands ON vegan_products.brand_id = brands.brand_id GROUP BY brand_id ORDER BY product_count DESC;


Question: List all technology initiatives focused on social good in Pacific Asian countries.

CREATE TABLE TechInitiatives (InitiativeID INT, InitiativeName TEXT, Country TEXT, Focus TEXT); INSERT INTO TechInitiatives (InitiativeID, InitiativeName, Country, Focus) VALUES (1, 'Initiative A', 'Japan', 'Social Good'); INSERT INTO TechInitiatives (InitiativeID, InitiativeName, Country, Focus) VALUES (2, 'Initiative B', 'South Korea', 'Healthcare'); INSERT INTO TechInitiatives (InitiativeID, InitiativeName, Country, Focus) VALUES (3, 'Initiative C', 'Singapore', 'Social Good');

SELECT InitiativeName, Country FROM TechInitiatives WHERE Country IN ('Japan', 'South Korea', 'Singapore') AND Focus = 'Social Good';


Question: Update the collective bargaining agreement expiration date for a specific union affiliation.

CREATE TABLE union_info (id INT, union_affiliation TEXT, collective_bargaining_agreement_expiration DATE); INSERT INTO union_info (id, union_affiliation, collective_bargaining_agreement_expiration) VALUES (1, 'Union A', '2022-12-31'), (2, 'Union B', '2023-06-30'), (3, 'Union C', '2024-01-31');

UPDATE union_info SET collective_bargaining_agreement_expiration = '2025-01-31' WHERE union_affiliation = 'Union A';


Question: Local economic impact of sustainable tourism in each province?

CREATE TABLE local_economy_extended_2 (province TEXT, impact FLOAT, year INT); INSERT INTO local_economy_extended_2 (province, impact, year) VALUES ('Ontario', 50000.0, 2021), ('British Columbia', 75000.0, 2021), ('Quebec', 60000.0, 2021);

SELECT province, impact FROM local_economy_extended_2 WHERE year = 2021 GROUP BY province;


Question: Compute the percentage of renewable energy used for transportation in the European Union, for each country, in the last 5 years.

CREATE TABLE EU_Transportation (country VARCHAR(255), year INT, renewable_energy INT); INSERT INTO EU_Transportation (country, year, renewable_energy) VALUES ('Germany', 2018, 10), ('France', 2018, 15), ('Italy', 2018, 12), ('Spain', 2018, 14), ('Germany', 2019, 12), ('France', 2019, 16), ('Italy', 2019, 13), ('Spain', 2019, 15);

SELECT country, (SUM(renewable_energy) FILTER (WHERE year BETWEEN 2018 AND 2022) OVER (PARTITION BY country)::DECIMAL / SUM(renewable_energy) OVER (PARTITION BY country)) * 100 AS pct_renewable_transport FROM EU_Transportation;


Question: How many workers were involved in each construction project in the 'Projects' and 'Workforce' tables?

CREATE TABLE Projects (projectID INT, projectName VARCHAR(50));CREATE TABLE Workforce (workerID INT, workerStartDate DATE, workerEndDate DATE, projectID INT);

SELECT P.projectName, COUNT(W.workerID) AS Workers FROM Projects P INNER JOIN Workforce W ON P.projectID = W.projectID GROUP BY P.projectName;


Question: Generate PostgreSQL SQL for: How many debates are there?


Question: Generate PostgreSQL SQL for: What is the average total with a Rank larger than 11, a Nation of switzerland, and a Silver smaller than 0?

CREATE TABLE table_name_85 (total INTEGER, silver VARCHAR, rank VARCHAR, nation VARCHAR)

SELECT AVG(total) FROM table_name_85 WHERE rank > 11 AND nation = 'switzerland' AND silver < 0;


Question: Generate PostgreSQL SQL for: Available in 2-CD format, what is the title of story number 026?

CREATE TABLE table_name_83 (title VARCHAR, format VARCHAR, story__number VARCHAR)

SELECT title FROM table_name_83 WHERE format = '2-cd' AND story__number = '026';


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

CREATE UNIQUE INDEX concur_exprs_index_pred_2
  ON concur_exprs_tab ((1 / c1))
  WHERE ('-H') >= (c2::TEXT) COLLATE "C";

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


Question: Generate PostgreSQL SQL for: Where was the hometown for the player that attended Shanley High School?

CREATE TABLE table_11677691_4 (hometown VARCHAR, school VARCHAR)

SELECT hometown FROM table_11677691_4 WHERE school = 'Shanley High school';


Question: How many 'Sustainable Material' garments are produced in 'South America'?

CREATE TABLE sustainable_garments(garment VARCHAR(20), material VARCHAR(20), region VARCHAR(20)); INSERT INTO sustainable_garments VALUES('Skirts', 'Sustainable Material', 'South America');

SELECT COUNT(*) FROM sustainable_garments WHERE material = 'Sustainable Material' AND region = 'South America';


Question: Generate PostgreSQL SQL for: Show ids for the faculty members who don't advise any student.

CREATE TABLE Faculty (FacID VARCHAR, advisor VARCHAR); CREATE TABLE Student (FacID VARCHAR, advisor VARCHAR)

SELECT FacID FROM Faculty EXCEPT SELECT advisor FROM Student;


Question: Generate PostgreSQL SQL for: What is the IHSAA class for the school where the mascot is the Rebels?

CREATE TABLE table_name_80 (ihsaa_class VARCHAR, mascot VARCHAR)

SELECT ihsaa_class FROM table_name_80 WHERE mascot = 'rebels';


Question: Generate PostgreSQL SQL for: A plural abbreviation of pp. is used for what singular word?

CREATE TABLE table_name_82 (singular_word VARCHAR, plural_abbreviation VARCHAR)

SELECT singular_word FROM table_name_82 WHERE plural_abbreviation = 'pp.';


Question: List the names and total points scored by football players in the 'football_matches' table, sorted by total points in descending order.

CREATE TABLE football_teams (team_id INT, team_name VARCHAR(50));CREATE VIEW football_matches AS SELECT player_id, team_id, SUM(points) AS total_points FROM football_player_scores GROUP BY player_id, team_id;

SELECT football_teams.team_name, football_matches.total_points, basketball_players.name FROM football_teams INNER JOIN football_matches ON football_teams.team_id = football_matches.team_id INNER JOIN basketball_players ON basketball_players.player_id = football_matches.player_id ORDER BY football_matches.total_points DESC;


Question: CO2 emissions of the transportation sector in 2018

CREATE TABLE co2_emissions (id INT, sector VARCHAR(255), year INT, co2_emissions FLOAT);

SELECT sector, SUM(co2_emissions) FROM co2_emissions WHERE sector = 'Transportation' AND year = 2018 GROUP BY sector;


Question: Generate PostgreSQL SQL for: What episode in the season was directed by Jeff Melman?

CREATE TABLE table_11058032_1 (no_in_season INTEGER, directed_by VARCHAR)

SELECT MIN(no_in_season) FROM table_11058032_1 WHERE directed_by = 'Jeff Melman';


Question: What was the average energy efficiency rating for commercial buildings in Texas in 2018?

CREATE TABLE building_energy_efficiency (state VARCHAR(20), year INT, building_type VARCHAR(20), energy_efficiency_rating FLOAT);

SELECT AVG(energy_efficiency_rating) FROM building_energy_efficiency WHERE state = 'Texas' AND year = 2018 AND building_type = 'Commercial';


Question: What is the maximum price of artworks created by Mexican artists?

CREATE TABLE Artists (artist_id INT, artist_name VARCHAR(50), birth_date DATE, country VARCHAR(50)); INSERT INTO Artists (artist_id, artist_name, birth_date, country) VALUES (1, 'Clara Peeters', '1594-01-15', 'Netherlands'); ; CREATE TABLE Artworks (artwork_id INT, title VARCHAR(50), year_made INT, artist_id INT, price FLOAT); INSERT INTO Artworks (artwork_id, title, year_made, artist_id, price) VALUES (1, 'Still Life with Flowers', 1612, 1, 1000.0); ;

SELECT MAX(Artworks.price) FROM Artworks INNER JOIN Artists ON Artworks.artist_id = Artists.artist_id WHERE Artists.country = 'Mexico';


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

--
-- pgp_pub_decrypt(data, key, psw)
--
CREATE FUNCTION pgp_pub_decrypt(bytea, bytea, text)
RETURNS text
AS 'MODULE_PATHNAME', 'pgp_pub_decrypt_text'
LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;


Question: Generate PostgreSQL SQL for: WHAT IS THE SUM PLAYED WITH POINTS 1 OF 53, AND POSITION LARGER THAN 3?

CREATE TABLE table_name_81 (played INTEGER, points_1 VARCHAR, position VARCHAR)

SELECT SUM(played) FROM table_name_81 WHERE points_1 = '53' AND position > 3;


Question: Insert new records of workplaces, including safety violations and union affiliations.

CREATE TABLE workplaces (id INT, name TEXT, safety_violation BOOLEAN, union_affiliation TEXT);

INSERT INTO workplaces (id, name, safety_violation, union_affiliation) VALUES (5, 'RST Industries', TRUE, 'Union C'), (6, 'UVW Corporation', FALSE, 'Union D');


Question: What is the total weight of each strain type sold in California dispensaries in March 2022?

CREATE TABLE sales (id INT, strain_id INT, weight DECIMAL(5,2), date DATE); INSERT INTO sales (id, strain_id, weight, date) VALUES (1, 1, 5.5, '2022-03-01'), (2, 2, 7.3, '2022-03-02');

SELECT strain_id, type, SUM(weight) as total_weight FROM sales s JOIN strains st ON s.strain_id = st.id WHERE st.state = 'California' AND date BETWEEN '2022-03-01' AND '2022-03-31' GROUP BY strain_id, type;


Question: Show a SQL definition from the zombodb project (test-es-only-fields, item 1).

CREATE TABLE es_only (
    id serial8 not null primary key,
    first_name varchar(25),
    last_name varchar(64)
);

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


Question: Calculate total revenue for all exhibitions

CREATE TABLE Exhibitions (id INT, name VARCHAR(255), entry_fee DECIMAL(5,2)); CREATE TABLE Tickets (id INT, visitor_id INT, exhibition_id INT, price DECIMAL(5,2));

SELECT SUM(Tickets.price) FROM Tickets JOIN Exhibitions ON Tickets.exhibition_id = Exhibitions.id;


Question: Generate PostgreSQL SQL for: What is raymond floyd's lowest $?

CREATE TABLE table_name_77 (money___ INTEGER, player VARCHAR)

SELECT MIN(money___) AS $__ FROM table_name_77 WHERE player = 'raymond floyd';


Question: What is the total cost of all the astrobiology missions that have been launched by private companies?

CREATE TABLE missions (mission_id INT, mission_name VARCHAR(50), agency_type VARCHAR(50), cost INT); INSERT INTO missions (mission_id, mission_name, agency_type, cost) VALUES (1, 'Mission1', 'Private', 1000000), (2, 'Mission2', 'Government', 2000000), (3, 'Mission3', 'Private', 1500000);

SELECT SUM(cost) FROM missions WHERE agency_type = 'Private' AND mission_name LIKE '%astrobiology%';


Question: Generate PostgreSQL SQL for: Name the district for matthew clay

CREATE TABLE table_2668387_18 (district VARCHAR, incumbent VARCHAR)

SELECT district FROM table_2668387_18 WHERE incumbent = 'Matthew Clay';


Question: Generate PostgreSQL SQL for: What was the lowest draw for Beathoven when the place was smaller than 16?

CREATE TABLE table_name_55 (draw INTEGER, artist VARCHAR, place VARCHAR)

SELECT MIN(draw) FROM table_name_55 WHERE artist = 'beathoven' AND place < 16;


Question: Generate PostgreSQL SQL for: What is the total for the person with 73.28 bodyweight and fewer snatches than 75?

CREATE TABLE table_name_22 (total__kg_ INTEGER, bodyweight VARCHAR, snatch VARCHAR)

SELECT AVG(total__kg_) FROM table_name_22 WHERE bodyweight = 73.28 AND snatch < 75;


Question: Generate PostgreSQL SQL for: what is the grid when the driver is louis rosier and the laps is more than 78?

CREATE TABLE table_name_39 (grid INTEGER, driver VARCHAR, laps VARCHAR)

SELECT MIN(grid) FROM table_name_39 WHERE driver = 'louis rosier' AND laps > 78;


Question: Find the vessel with the highest average speed that arrived in the Netherlands ports?

CREATE TABLE VesselArrivals (ID INT, VesselName VARCHAR(50), ArrivalPort VARCHAR(50), ArrivalDate DATE, AverageSpeed DECIMAL(5,2)); INSERT INTO VesselArrivals (ID, VesselName, ArrivalPort, ArrivalDate, AverageSpeed) VALUES (1, 'Test Vessel 1', 'Amsterdam', '2022-01-01', 15.5), (2, 'Test Vessel 2', 'Rotterdam', '2022-01-02', 20.3), (3, 'Test Vessel 3', 'Utrecht', '2022-01-03', 18.5);

SELECT VesselName, MAX(AverageSpeed) FROM VesselArrivals WHERE ArrivalPort LIKE 'Netherlands%' GROUP BY VesselName;


Question: Which forests have an average tree height over 45 meters?

CREATE TABLE forests (id INT, name VARCHAR(255), hectares FLOAT, country VARCHAR(255)); INSERT INTO forests (id, name, hectares, country) VALUES (1, 'Boreal Forest', 1200000.0, 'Canada'), (2, 'Amazon Rainforest', 5500000.0, 'Brazil'), (3, 'Daintree Rainforest', 120000.0, 'Australia'); CREATE TABLE trees (id INT, species VARCHAR(255), height FLOAT, forest_id INT); INSERT INTO trees (id, species, height, forest_id) VALUES (1, 'White Spruce', 42.0, 1), (2, 'Rainforest Gum', 30.0, 2), (3, 'Southern Silky Oak', 70.0, 3); CREATE VIEW avg_tree_height AS SELECT forest_id, AVG(height) as avg_height FROM trees GROUP BY forest_id;

SELECT forests.name FROM forests INNER JOIN avg_tree_height ON forests.id = avg_tree_height.forest_id WHERE avg_tree_height.avg_height > 45;


Question: Generate PostgreSQL SQL for: What is the time for a lane less than 6, and a heat less than 4 for Joanne Malar?

CREATE TABLE table_name_19 (time VARCHAR, name VARCHAR, lane VARCHAR, heat VARCHAR)

SELECT time FROM table_name_19 WHERE lane < 6 AND heat < 4 AND name = 'joanne malar';


Question: Generate PostgreSQL SQL for: how many categories fall under the category of britons?

CREATE TABLE table_261895_1 (type VARCHAR, nickname VARCHAR)

SELECT COUNT(type) FROM table_261895_1 WHERE nickname = 'Britons';


Question: Generate PostgreSQL SQL for: Name the 2009 for wta premier mandatory tournaments

CREATE TABLE table_name_99 (tournament VARCHAR)

SELECT 2009 FROM table_name_99 WHERE tournament = 'wta premier mandatory tournaments';