Question: Generate PostgreSQL SQL for: What is the score of the team with the 14-9 record?

CREATE TABLE table_name_43 (score VARCHAR, record VARCHAR)

SELECT score FROM table_name_43 WHERE record = '14-9';


Question: What is the maximum calories burned by a member in a single workout?


Question: Generate PostgreSQL SQL for: Which Second has a Nation of latvia?

CREATE TABLE table_name_16 (second VARCHAR, nation VARCHAR)

SELECT second FROM table_name_16 WHERE nation = 'latvia';


Question: Calculate the average score of user 6 for all games played

CREATE TABLE game_scores (user_id INT, game_name VARCHAR(10), score INT); INSERT INTO game_scores (user_id, game_name, score) VALUES (1, 'A', 50), (2, 'B', 100), (3, 'D', 150), (4, 'C', 200), (4, 'C', 250), (6, 'D', 300), (6, 'A', 350);

SELECT AVG(score) FROM game_scores WHERE user_id = 6;


Question: List all countries, their total production, and the number of active wells in each country, for countries with at least one active well in 2021.

CREATE TABLE countries (country_id INT, country_name TEXT); CREATE TABLE wells (well_id INT, country_id INT, well_name TEXT, production_qty INT, start_date DATE, end_date DATE); INSERT INTO countries (country_id, country_name) VALUES (1, 'Country A'), (2, 'Country B'); INSERT INTO wells (well_id, country_id, well_name, production_qty, start_date, end_date) VALUES (1, 1, 'Well A', 500, '2020-01-01', '2022-02-28'), (2, 1, 'Well B', 700, '2021-01-01', '2023-01-01'), (3, 2, 'Well C', 300, '2022-01-01', '2024-01-01');

SELECT c.country_name, SUM(w.production_qty) AS total_production, COUNT(w.well_id) AS active_wells FROM countries c INNER JOIN wells w ON c.country_id = w.country_id WHERE w.start_date <= '2021-01-01' AND w.end_date >= '2021-01-01' GROUP BY c.country_name;


Question: What is the minimum energy storage utilization rate for the province of Ontario in 2021?

CREATE TABLE energy_storage_utilization (province VARCHAR(20), utilization DECIMAL(4,2), year INT); INSERT INTO energy_storage_utilization (province, utilization, year) VALUES ('Ontario', 80.5, 2021), ('Ontario', 82.3, 2021), ('Ontario', 79.2, 2021);

SELECT MIN(utilization) FROM energy_storage_utilization WHERE province = 'Ontario' AND year = 2021;


Question: What is the total amount of funds spent on refugee support in Africa?

CREATE TABLE funds (id INT, category TEXT, region TEXT, amount DECIMAL(10,2)); INSERT INTO funds (id, category, region, amount) VALUES (1, 'Refugee Support', 'Middle East', 250000.00), (2, 'Disaster Response', 'Asia', 300000.00), (3, 'Community Development', 'Africa', 150000.00), (4, 'Refugee Support', 'Africa', 50000.00), (5, 'Refugee Support', 'Africa', 75000.00);

SELECT SUM(amount) FROM funds WHERE category = 'Refugee Support' AND region = 'Africa';


Question: Generate PostgreSQL SQL for: What is Highest Attendance, when Rank is 90, and when Venue Name is Infineon Raceway?

CREATE TABLE table_name_69 (highest_attendance VARCHAR, rank VARCHAR, venue_name VARCHAR)

SELECT highest_attendance FROM table_name_69 WHERE rank = 90 AND venue_name = 'infineon raceway';


Question: Insert a new rural development project 'AGRI-INNOVATE 3.0' in Rwanda for 2023 with a budget of 5000000.

CREATE TABLE rural_development (project VARCHAR(255), country VARCHAR(255), year INT, budget FLOAT);

INSERT INTO rural_development (project, country, year, budget) VALUES ('AGRI-INNOVATE 3.0', 'Rwanda', 2023, 5000000);


Question: List the community members and their ages who are involved in agricultural innovation and are living in 'rural_area_1' from the 'community_development', 'agriculture_innovation', and 'rural_infrastructure' tables

CREATE TABLE community_development (member_id INT, member_name VARCHAR(50), age INT, area_id INT); CREATE TABLE agriculture_innovation (farmer_id INT, farmer_name VARCHAR(50), member_id INT); CREATE TABLE rural_infrastructure (project_id INT, project_type VARCHAR(50), budget INT, area_id INT);

SELECT c.member_name, c.age FROM community_development c INNER JOIN agriculture_innovation a ON c.member_id = a.member_id INNER JOIN rural_infrastructure r ON c.area_id = r.area_id WHERE c.area_name = 'rural_area_1';


Question: Generate PostgreSQL SQL for: What type has 5 as the quantity?

CREATE TABLE table_name_26 (type VARCHAR, quantity VARCHAR)

SELECT type FROM table_name_26 WHERE quantity = 5;


Question: What is the total installed capacity of renewable energy projects in the state of Florida that involve wind power?

CREATE TABLE renewable_energy (project_id INT, project_name VARCHAR(255), city VARCHAR(255), state VARCHAR(255), technology VARCHAR(255), capacity FLOAT);

SELECT SUM(capacity) FROM renewable_energy WHERE state = 'Florida' AND technology = 'Wind';


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

INSERT INTO temporal_fk_rng2rng (id, valid_at, parent_id) VALUES ('[2,3)', daterange('2018-01-02', '2018-04-01'), '[1,2)');

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


Question: Find the number of transactions involving 'organic' produce in the 'Northeast' region.

CREATE TABLE transactions (id INT, product TEXT, region TEXT, organic BOOLEAN); INSERT INTO transactions (id, product, region, organic) VALUES (1, 'Product 1', 'Northeast', true), (2, 'Product 2', 'Southeast', false);

SELECT COUNT(*) FROM transactions WHERE region = 'Northeast' AND organic = true;


Question: Calculate the total billing amount for cases with a 'Precedential' precedent type, won by attorneys from the 'New York' office?

CREATE TABLE offices (office_id INT, office_name VARCHAR(20)); INSERT INTO offices (office_id, office_name) VALUES (1, 'Boston'), (2, 'New York'), (3, 'Chicago'); CREATE TABLE cases (case_id INT, attorney_id INT, office_id INT, precedent_type VARCHAR(20), billing_amount FLOAT, case_outcome VARCHAR(10)); INSERT INTO cases (case_id, attorney_id, office_id, precedent_type, billing_amount, case_outcome) VALUES (1, 101, 1, 'Precedential', 5000, 'Won'), (2, 102, 1, 'Non-Precedential', 3000, 'Lost'), (3, 103, 1, 'Precedential', 7000, 'Won'), (4, 104, 2, 'Non-Precedential', 2000, 'Won'), (5, 105, 3, 'Precedential', 8000, 'Lost');

SELECT SUM(billing_amount) FROM cases JOIN offices ON cases.office_id = offices.office_id WHERE offices.office_name = 'New York' AND precedent_type = 'Precedential' AND case_outcome = 'Won';


Question: Generate PostgreSQL SQL for: Which away team played against the home team of St Kilda?

CREATE TABLE table_name_66 (away_team VARCHAR, home_team VARCHAR)

SELECT away_team FROM table_name_66 WHERE home_team = 'st kilda';


Question: Generate PostgreSQL SQL for: Chicago fire has a total of a total of how many #s?

CREATE TABLE table_name_5 (pick__number VARCHAR, mls_team VARCHAR)

SELECT COUNT(pick__number) FROM table_name_5 WHERE mls_team = 'chicago fire';


Question: PostgreSQL regression test 'pg_dependencies': Write the SELECT query (example 78).

SELECT '[{"attributes" : [2,3], "dependency" : 4, "dependency": 4, "degree": 1.000}]'::pg_dependencies;

Explanation: Regression test for Pg Dependencies in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT '[{"attributes" : [2,3], "dependency" : 4, "dependency": 4, "degree": 1.000}]'::pg_dependencies) AS _sub;


Question: Generate PostgreSQL SQL for: What is Oklahoma vs. when Current Streak is l 1, and Neutral Site is osu, 7-6?

CREATE TABLE table_name_15 (oklahoma_vs VARCHAR, current_streak VARCHAR, at_neutral_site VARCHAR)

SELECT oklahoma_vs FROM table_name_15 WHERE current_streak = 'l 1' AND at_neutral_site = 'osu, 7-6';


Question: Calculate the average price of ethically made items

CREATE TABLE sales (id INT, item_id INT, price INT, purchase_date DATE); CREATE TABLE standards (id INT, item_id INT, standard VARCHAR(255)); INSERT INTO sales (id, item_id, price, purchase_date) VALUES (1, 1, 100, '2022-01-01'), (2, 2, 75, '2022-01-02'), (3, 1, 120, '2022-01-03'); INSERT INTO standards (id, item_id, standard) VALUES (1, 1, 'ethical'), (2, 2, 'sustainable');

SELECT AVG(price) FROM sales s JOIN standards st ON s.item_id = st.item_id WHERE st.standard = 'ethical';


Question: Generate PostgreSQL SQL for: Who is the opponent in 1992?

CREATE TABLE table_name_17 (opponent VARCHAR, year VARCHAR)

SELECT opponent FROM table_name_17 WHERE year = '1992';


Question: Generate PostgreSQL SQL for: What is the D48 when the D 50 O is d 31?

CREATE TABLE table_name_67 (d_48_√ VARCHAR, d_50_o VARCHAR)

SELECT d_48_√ FROM table_name_67 WHERE d_50_o = 'd 31';


Question: Generate PostgreSQL SQL for: What station was sent on flight up and was launched on 23 July 1980 18:33:03?

CREATE TABLE table_245800_2 (flight_up VARCHAR, launch_date VARCHAR)

SELECT flight_up FROM table_245800_2 WHERE launch_date = '23 July 1980 18:33:03';


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

SELECT * FROM getrngfunc1(1) WITH ORDINALITY AS t1(v,o);

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

SELECT count(*) FROM (SELECT * FROM getrngfunc1(1) WITH ORDINALITY AS t1(v,o)) AS _sub;


Question: Generate PostgreSQL SQL for: what project was initially started before september 20, 1968

CREATE TABLE table_291768_1 (commissioned VARCHAR, launched VARCHAR)

SELECT commissioned FROM table_291768_1 WHERE launched = 'September 20, 1968';


Question: Generate PostgreSQL SQL for: What was Berlin when fk pirmasens was Südwest and westfalia herne was west?

CREATE TABLE table_name_60 (berlin VARCHAR, südwest VARCHAR, west VARCHAR)

SELECT berlin FROM table_name_60 WHERE südwest = 'fk pirmasens' AND west = 'westfalia herne';


Question: Generate PostgreSQL SQL for: List the names of buildings with at least 200 feet of height and with at least 20 floors.

CREATE TABLE building (name VARCHAR, height_feet VARCHAR, floors VARCHAR)

SELECT name FROM building WHERE height_feet >= 200 AND floors >= 20;


Question: List the number of safety incidents for each chemical type, ordered from most to least incidents?

CREATE TABLE safety_incidents (chemical_type VARCHAR(255), incident_date DATE); INSERT INTO safety_incidents (chemical_type, incident_date) VALUES ('Type A', '2020-01-05'), ('Type A', '2020-03-12'), ('Type B', '2020-02-18'), ('Type C', '2020-01-02'), ('Type C', '2020-04-20'), ('Type D', '2020-03-03');

SELECT chemical_type, COUNT(*) as incident_count FROM safety_incidents GROUP BY chemical_type ORDER BY incident_count DESC;


Question: Update the 'workforce' table and set the 'salary' to $60,000 for all workers in the 'mechanical' department

CREATE TABLE workforce (id INT, name VARCHAR(255), department VARCHAR(255), salary DECIMAL(8,2));

UPDATE workforce SET salary = 60000 WHERE department = 'mechanical';


Question: Generate PostgreSQL SQL for: On the date november 24-december 6 what's the winner when the country is united states?

CREATE TABLE table_name_35 (winner VARCHAR, country VARCHAR, date VARCHAR)

SELECT winner FROM table_name_35 WHERE country = 'united states' AND date = 'november 24-december 6';


Question: Generate PostgreSQL SQL for: What is the placement date of the order whose invoice number is 10?

CREATE TABLE orders (date_order_placed VARCHAR, order_id VARCHAR); CREATE TABLE shipments (order_id VARCHAR, invoice_number VARCHAR)

SELECT T1.date_order_placed FROM orders AS T1 JOIN shipments AS T2 ON T1.order_id = T2.order_id WHERE T2.invoice_number = 10;


Question: Write the DML statement from PostgreSQL regression test 'rules' (example 428).

insert into test_2 (name) values ('Test 4');

Explanation: DML from PostgreSQL core regression test for Rules.


Question: Generate PostgreSQL SQL for: What are all the winning records when the result is Scotland won on points table and the Runner-Up result is [[|]] 4 points?

CREATE TABLE table_28601467_1 (winner VARCHAR, result VARCHAR, runner_up VARCHAR)

SELECT winner FROM table_28601467_1 WHERE result = 'Scotland won on points table' AND runner_up = '[[|]] 4 points';


Question: Generate PostgreSQL SQL for: Name the fa cup apps for arthur morton

CREATE TABLE table_19730892_1 (fa_cup_apps VARCHAR, name VARCHAR)

SELECT fa_cup_apps FROM table_19730892_1 WHERE name = 'Arthur Morton';


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

create table fktable2 (
  a int,
  b int,
  very_very_long_column_name_to_exceed_63_characters int,
  foreign key (very_very_long_column_name_to_exceed_63_characters) references pktable1,
  foreign key (a, very_very_long_column_name_to_exceed_63_characters) references pktable2,
  foreign key (a, very_very_long_column_name_to_exceed_63_characters) references pktable2
);

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


Question: What percentage of cosmetics sales in Australia are from eco-friendly packaging?

CREATE TABLE cosmetics_sales_australia (id INT, product VARCHAR(50), price DECIMAL(10,2), eco_friendly BOOLEAN, country VARCHAR(50)); INSERT INTO cosmetics_sales_australia (id, product, price, eco_friendly, country) VALUES (1, 'Eco-friendly Mascara', 20.00, TRUE, 'Australia');

SELECT 100.0 * SUM(CASE WHEN eco_friendly THEN price ELSE 0 END) / SUM(price) AS percentage FROM cosmetics_sales_australia WHERE country = 'Australia';


Question: What is the average age of players who play VR games, and how many VR games have been published?

CREATE TABLE Players (PlayerID int, Age int, Gender varchar(10), GamePreference varchar(20)); INSERT INTO Players (PlayerID, Age, Gender, GamePreference) VALUES (1, 25, 'Male', 'VR'); INSERT INTO Players (PlayerID, Age, Gender, GamePreference) VALUES (2, 30, 'Female', 'Non-VR'); CREATE TABLE Games (GameID int, GameName varchar(20), Genre varchar(10), VR boolean); INSERT INTO Games (GameID, GameName, Genre, VR) VALUES (1, 'Game1', 'Action', false); INSERT INTO Games (GameID, GameName, Genre, VR) VALUES (2, 'Game2', 'Adventure', true);

SELECT AVG(Players.Age) AS AvgAge, COUNT(Games.GameID) AS VRGameCount FROM Players INNER JOIN Games ON Players.GamePreference = 'VR' AND Games.VR = true;


Question: What is the name of the latest vulnerability reported in the 'vulnerabilities' table?

CREATE TABLE vulnerabilities (id INT, name VARCHAR(255), description TEXT, severity VARCHAR(50), reported_date DATE);

SELECT name FROM vulnerabilities ORDER BY reported_date DESC LIMIT 1;


Question: What is the total number of fishing vessels in the 'Indian Ocean' that are over 20 years old?'

CREATE TABLE fishing_vessels (name VARCHAR(50), region VARCHAR(20), age INTEGER); INSERT INTO fishing_vessels (name, region, age) VALUES ('Vessel A', 'Indian Ocean', 15), ('Vessel B', 'Indian Ocean', 25), ('Vessel C', 'Atlantic', 10);

SELECT COUNT(*) FROM fishing_vessels WHERE region = 'Indian Ocean' AND age > 20;


Question: PL/pgSQL test: Plperl Trigger (example 19).

CREATE VIEW trigger_test_view AS SELECT * FROM trigger_test;

Explanation: PL/pgSQL example from PostgreSQL source test for Plperl Trigger.


Question: How many art pieces were created by artists from underrepresented communities in the last decade?

CREATE TABLE art_pieces_identity (id INT, year INT, artist_name VARCHAR(50), art_type VARCHAR(50), underrepresented_community VARCHAR(50));

SELECT COUNT(*) as total_art_pieces FROM art_pieces_identity WHERE year >= 2012 AND underrepresented_community IS NOT NULL;


Question: What is the average year when traditional arts were first practiced?

CREATE TABLE traditional_arts (id INT, art_name VARCHAR(255), year INT, country VARCHAR(255)); INSERT INTO traditional_arts (id, art_name, year, country) VALUES (1, 'Ukiyo-e', 1600, 'Japan'), (2, 'Taracea', 1700, 'Mexico');


Question: How many unique subscribers have both mobile and broadband plans?

CREATE TABLE mobile_subscribers (subscriber_id INT, plan_name TEXT); CREATE TABLE broadband_subscribers (subscriber_id INT, plan_name TEXT);

SELECT COUNT(DISTINCT mobile_subscribers.subscriber_id) FROM mobile_subscribers INNER JOIN broadband_subscribers ON mobile_subscribers.subscriber_id = broadband_subscribers.subscriber_id;


Question: Identify the transaction with the largest amount in each quarter for the past two years.

CREATE TABLE transactions (id INT, transaction_date DATE, amount DECIMAL(10, 2)); INSERT INTO transactions (id, transaction_date, amount) VALUES (1, '2022-01-01', 500.00), (2, '2022-02-01', 750.00), (3, '2021-01-01', 1000.00);

SELECT transaction_date, amount FROM (SELECT transaction_date, amount, ROW_NUMBER() OVER (PARTITION BY DATE_TRUNC('quarter', transaction_date) ORDER BY amount DESC) as rn FROM transactions WHERE transaction_date >= (CURRENT_DATE - INTERVAL '2 year')) t WHERE rn = 1;


Question: Generate PostgreSQL SQL for: What is the least obesity rank for the state of Utah?

CREATE TABLE table_18958648_1 (obesity_rank INTEGER, state_and_district_of_columbia VARCHAR)

SELECT MIN(obesity_rank) FROM table_18958648_1 WHERE state_and_district_of_columbia = 'Utah';


Question: What is the total price of all properties in inclusive housing schemes in Oakland?

CREATE TABLE inclusive_housing (property_id INT, city VARCHAR(50), price INT, inclusive_scheme BOOLEAN); INSERT INTO inclusive_housing (property_id, city, price, inclusive_scheme) VALUES (1, 'Oakland', 600000, TRUE), (2, 'Portland', 500000, FALSE), (3, 'Oakland', 700000, TRUE), (4, 'Seattle', 800000, FALSE);

SELECT SUM(price) FROM inclusive_housing WHERE city = 'Oakland' AND inclusive_scheme = TRUE;


Question: Which states have more than 5 disability support programs?

CREATE TABLE states (state_id INT, state_name VARCHAR(50), num_programs INT); INSERT INTO states (state_id, state_name, num_programs) VALUES (1, 'California', 7), (2, 'Texas', 3), (3, 'New York', 6), (4, 'Florida', 4);

SELECT state_name FROM (SELECT state_name, ROW_NUMBER() OVER (ORDER BY num_programs DESC) as rn FROM states) t WHERE rn <= (SELECT COUNT(*) FROM states WHERE num_programs > 5);


Question: What is the average price of cruelty-free products?

CREATE TABLE products (id INT, company VARCHAR(255), price DECIMAL(5,2), cruelty_free BOOLEAN); INSERT INTO products (id, company, price, cruelty_free) VALUES (1, 'ABC', 50.99, TRUE), (2, 'DEF', 35.49, FALSE), (3, 'GHI', 65.99, TRUE), (4, 'JKL', 25.99, TRUE);

SELECT AVG(price) FROM products WHERE cruelty_free = TRUE;


Question: What is the average time between appointments for patients with chronic conditions in rural health clinic B?

CREATE TABLE clinics (clinic_id INT, clinic_name VARCHAR(50)); CREATE TABLE appointments (appointment_id INT, patient_id INT, appointment_date DATE, clinic_id INT, chronic_condition BOOLEAN);

SELECT AVG(DATEDIFF(appointments.appointment_date, LAG(appointments.appointment_date) OVER (PARTITION BY appointments.patient_id ORDER BY appointments.appointment_date))) as avg_time_between_appointments FROM appointments WHERE appointments.clinic_id = (SELECT clinic_id FROM clinics WHERE clinic_name = 'rural health clinic B') AND appointments.chronic_condition = TRUE;


Question: Generate PostgreSQL SQL for: What is the result of nominee, Patricia McGourty, for the drama desk award?

CREATE TABLE table_name_17 (result VARCHAR, award VARCHAR, nominee VARCHAR)

SELECT result FROM table_name_17 WHERE award = 'drama desk award' AND nominee = 'patricia mcgourty';


Question: What are the total waste generation metrics for each city in the region 'West Coast'?

CREATE TABLE cities (city_name VARCHAR(50), region VARCHAR(50)); INSERT INTO cities (city_name, region) VALUES ('San Francisco', 'West Coast'), ('Los Angeles', 'West Coast'), ('Seattle', 'West Coast'); CREATE TABLE waste_generation (city_name VARCHAR(50), waste_metric INT); INSERT INTO waste_generation (city_name, waste_metric) VALUES ('San Francisco', 1200), ('Los Angeles', 1500), ('Seattle', 1800);

SELECT wg.city_name, SUM(waste_metric) as total_waste_metric FROM waste_generation wg JOIN cities c ON wg.city_name = c.city_name WHERE c.region = 'West Coast' GROUP BY wg.city_name;


Question: What is the average duration of virtual tours for each hotel?

CREATE TABLE hotels (hotel_id INT, name VARCHAR(50), category VARCHAR(20), rating DECIMAL(2,1)); INSERT INTO hotels (hotel_id, name, category, rating) VALUES (1, 'The Urban Chic', 'boutique', 4.5), (2, 'The Artistic Boutique', 'boutique', 4.7), (3, 'The Cozy Inn', 'budget', 4.2); CREATE TABLE virtual_tours (tour_id INT, hotel_id INT, title VARCHAR(50), duration INT); INSERT INTO virtual_tours (tour_id, hotel_id, title, duration) VALUES (1, 1, 'Virtual Tour: The Urban Chic Lobby', 15), (2, 1, 'Virtual Tour: The Urban Chic Rooms', 30), (3, 2, 'Virtual Tour: The Artistic Boutique Lobby', 10), (4, 3, 'Virtual Tour: The Cozy Inn Rooms', 20);

SELECT hotel_id, AVG(duration) AS avg_duration FROM virtual_tours GROUP BY hotel_id;


Question: Write the DDL statement from PostgreSQL regression test 'tablespace' (example 146).

CREATE INDEX test_tab_a_idx ON testschema.test_tab (a);

Explanation: DDL from PostgreSQL core regression test for Tablespace.


Question: What is the total number of impact investments made by donors from the United States?

CREATE TABLE donors (donor_id INT, donor_name TEXT, country TEXT); INSERT INTO donors (donor_id, donor_name, country) VALUES (1, 'John Doe', 'United States'); CREATE TABLE impact_investments (investment_id INT, donor_id INT, investment_amount FLOAT); INSERT INTO impact_investments (investment_id, donor_id, investment_amount) VALUES (1, 1, 50000.0);

SELECT SUM(investment_amount) FROM impact_investments JOIN donors ON donors.donor_id = impact_investments.donor_id WHERE donors.country = 'United States';


Question: Generate PostgreSQL SQL for: How many stages did Team Sky lead the teams classification?

CREATE TABLE table_26010857_13 (stage INTEGER, teams_classification VARCHAR)

SELECT MAX(stage) FROM table_26010857_13 WHERE teams_classification = 'Team Sky';


Question: Insert a new space debris record into the "space_debris_monitoring" table for an object launched by India in 2008.

CREATE TABLE space_debris_monitoring (id INT, object_name VARCHAR(50), launch_country VARCHAR(50), launch_date DATE, latitude FLOAT, longitude FLOAT);

INSERT INTO space_debris_monitoring (object_name, launch_country, launch_date, latitude, longitude) VALUES ('Debris_2008_India', 'India', '2008-01-01', 10.123456, 20.123456);


Question: PL/pgSQL test: Plperl Plperlu (example 7).

-- plperlu first
create or replace function bar(text) returns text language plperlu as 'shift';

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


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

select json '{ "a":  "dollar \\u0024 character" }' as not_an_escape;

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

SELECT count(*) FROM (select json '{ "a":  "dollar \\u0024 character" }' as not_an_escape) AS _sub;


Question: Generate PostgreSQL SQL for: How many grand final dual television commentators were there in 1961?

CREATE TABLE table_1368649_9 (grand_final_dual_television_commentator VARCHAR, year_s_ VARCHAR)

SELECT COUNT(grand_final_dual_television_commentator) FROM table_1368649_9 WHERE year_s_ = 1961;


Question: What is the percentage of tenured faculty members in each department?

CREATE TABLE faculty (faculty_id INT, name VARCHAR(50), gender VARCHAR(10), department VARCHAR(50), is_tenured BOOLEAN, position VARCHAR(50)); INSERT INTO faculty VALUES (1, 'John Doe', 'Male', 'Mathematics', TRUE, 'Professor'), (2, 'Jane Smith', 'Female', 'Physics', FALSE, 'Assistant Professor'), (3, 'Alice Johnson', 'Female', 'Mathematics', TRUE, 'Associate Professor');

SELECT department, COUNT(*) * 100.0 / (SELECT COUNT(*) FROM faculty WHERE is_tenured = TRUE) as tenured_percentage FROM faculty WHERE is_tenured = TRUE GROUP BY department;


Question: List all tech companies in 'tech_companies' table located in 'California'.

CREATE TABLE tech_companies (company VARCHAR(50), department VARCHAR(50), employee_name VARCHAR(50), salary INTEGER, company_location VARCHAR(50));

SELECT company FROM tech_companies WHERE company_location = 'California';


Question: What is the total number of security incidents caused by malware in the past week?

CREATE TABLE security_incidents (id INT, type TEXT, timestamp TIMESTAMP); INSERT INTO security_incidents (id, type, timestamp) VALUES (1, 'phishing', '2021-02-01 12:00:00'), (2, 'malware', '2021-02-04 14:30:00'), (3, 'phishing', '2021-02-05 10:15:00'), (4, 'malware', '2021-02-06 16:45:00');

SELECT COUNT(*) FROM security_incidents WHERE type = 'malware' AND timestamp >= NOW() - INTERVAL '1 week';


Question: Generate PostgreSQL SQL for: The community station broadcasting at frequency 0 96.9 is in what band?

CREATE TABLE table_name_87 (band VARCHAR, purpose VARCHAR, frequency VARCHAR)

SELECT band FROM table_name_87 WHERE purpose = 'community' AND frequency = '0 96.9';


Question: Generate PostgreSQL SQL for: Name the most finish for 2006

CREATE TABLE table_name_9 (finish INTEGER, year VARCHAR)

SELECT MAX(finish) FROM table_name_9 WHERE year = 2006;


Question: Generate PostgreSQL SQL for: What is the league goals when the total goals is 179?

CREATE TABLE table_29701419_2 (league_goals INTEGER, total_goals VARCHAR)

SELECT MAX(league_goals) FROM table_29701419_2 WHERE total_goals = 179;


Question: Which natural ingredient is most commonly used in skincare products?

CREATE TABLE product_ingredients (product_id INT, product_category VARCHAR(50), ingredient VARCHAR(50)); INSERT INTO product_ingredients (product_id, product_category, ingredient) VALUES (1009, 'skincare', 'aloe vera'), (1010, 'skincare', 'lavender oil'), (1011, 'haircare', 'coconut oil'), (1012, 'skincare', 'jojoba oil'), (1013, 'makeup', 'talc');

SELECT ingredient, COUNT(*) AS ingredient_count FROM product_ingredients WHERE product_category = 'skincare' GROUP BY ingredient ORDER BY ingredient_count DESC LIMIT 1;


Question: Find the number of grants awarded to each department in the College of Social Sciences.

CREATE TABLE departments (id INT, name VARCHAR(50)); CREATE TABLE grants (id INT, department_id INT, amount INT); INSERT INTO departments VALUES (1, 'Psychology'), (2, 'Sociology'), (3, 'Anthropology'); INSERT INTO grants VALUES (1, 1, 5000), (2, 1, 7000), (3, 2, 6000), (4, 3, 4000);

SELECT department_id, COUNT(*) AS grant_count FROM grants GROUP BY department_id;


Question: Show a SQL definition from the citus project (multi_behavioral_analytics_create_table, item 47).

-- Create composite type to use in subquery pushdown
CREATE TYPE user_composite_type AS
(
    tenant_id BIGINT,
    user_id BIGINT
);

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


Question: List the number of wind farms in Canada, Brazil, and Argentina, as of 2020.

CREATE TABLE wind_farms (country VARCHAR(50), operational BOOLEAN, year INT); INSERT INTO wind_farms (country, operational, year) VALUES ('Canada', true, 2020), ('Brazil', true, 2020), ('Argentina', true, 2020), ('Mexico', false, 2020);

SELECT country, COUNT(*) FROM wind_farms WHERE country IN ('Canada', 'Brazil', 'Argentina') AND operational = true GROUP BY country;


Question: Total sales of drugs manufactured by ManuE

CREATE TABLE sales (sale_id INT, drug_name TEXT, manufacturer TEXT, sales_figure DECIMAL); INSERT INTO sales (sale_id, drug_name, manufacturer, sales_figure) VALUES (1, 'DrugO', 'ManuE', 3000000), (2, 'DrugP', 'ManuF', 4000000);

SELECT SUM(sales_figure) FROM sales WHERE manufacturer = 'ManuE';


Question: List the total budget for rural infrastructure projects by project type and project status, and calculate the average budget per project in the 'rural_infrastructure_projects' table.

CREATE TABLE rural_infrastructure_projects (project_type VARCHAR(255), project_status VARCHAR(255), budget INT); INSERT INTO rural_infrastructure_projects (project_type, project_status, budget) VALUES ('Bridge', 'Under Construction', 2000000), ('Road', 'Completed', 1500000);

SELECT project_type, project_status, SUM(budget) AS total_budget, AVG(budget) AS average_budget_per_project FROM rural_infrastructure_projects GROUP BY project_type, project_status;


Question: Generate PostgreSQL SQL for: What game has 28 points, and tampa bay lightning as the opponent?

CREATE TABLE table_name_50 (game VARCHAR, points VARCHAR, opponent VARCHAR)

SELECT game FROM table_name_50 WHERE points = 28 AND opponent = 'tampa bay lightning';


Question: Generate PostgreSQL SQL for: What is the total number of opponents played against the bears in game 4?

CREATE TABLE table_21035326_1 (opponents VARCHAR, game VARCHAR)

SELECT COUNT(opponents) FROM table_21035326_1 WHERE game = 4;


Question: Generate PostgreSQL SQL for: When the assets are 2,550, what is the Market Value?

CREATE TABLE table_1682026_2 (market_value__billion_$_ VARCHAR, assets__billion_$_ VARCHAR)

SELECT market_value__billion_$_ FROM table_1682026_2 WHERE assets__billion_$_ = '2,550';


Question: Write the DML statement from PostgreSQL regression test 'arrays' (example 94).

update arrtest1 set i[-7:-6] = array[-17,null], t[-7:-6] = array['m17',null];

Explanation: DML from PostgreSQL core regression test for Arrays.


Question: Write the DML statement from PostgreSQL regression test 'join' (example 13).

INSERT INTO J1_TBL VALUES (NULL, 0, 'zero');

Explanation: DML from PostgreSQL core regression test for Join.


Question: Generate PostgreSQL SQL for: What away team played against Footscray as the home team?

CREATE TABLE table_name_50 (away_team VARCHAR, home_team VARCHAR)

SELECT away_team FROM table_name_50 WHERE home_team = 'footscray';


Question: Find the average gold and silver production quantities for each mine, excluding mines with missing data.

CREATE TABLE mine (name VARCHAR(255), location VARCHAR(255)); CREATE TABLE gold_mine_production (mine_name VARCHAR(255), quantity INT); CREATE TABLE silver_mine_production (mine_name VARCHAR(255), quantity INT);

SELECT gold_mine_production.mine_name, AVG(gold_mine_production.quantity) AS avg_gold_quantity, AVG(silver_mine_production.quantity) AS avg_silver_quantity FROM gold_mine_production INNER JOIN silver_mine_production ON gold_mine_production.mine_name = silver_mine_production.mine_name GROUP BY gold_mine_production.mine_name HAVING COUNT(*) = 2;


Question: What is the average daily revenue for hotels in the 'EMEA' region for the year 2022?

CREATE TABLE daily_revenue (id INT, hotel_id INT, region TEXT, calendar DATE, revenue FLOAT);

SELECT region, AVG(revenue) FROM daily_revenue WHERE region = 'EMEA' AND YEAR(calendar) = 2022 GROUP BY region;


Question: What is the percentage of cases that were resolved through restorative justice practices for each year?

CREATE TABLE cases (case_id INT, resolution_type VARCHAR(50), resolution_year INT); INSERT INTO cases (case_id, resolution_type, resolution_year) VALUES (1, 'restorative_justice', 2020); INSERT INTO cases (case_id, resolution_type, resolution_year) VALUES (2, 'prosecution', 2020); INSERT INTO cases (case_id, resolution_type, resolution_year) VALUES (3, 'restorative_justice', 2021);

SELECT resolution_year, resolution_type, COUNT(*) * 100.0 / SUM(COUNT(*)) OVER (PARTITION BY resolution_year) as percentage FROM cases WHERE resolution_type = 'restorative_justice' GROUP BY resolution_year, resolution_type;


Question: How many students have participated in open pedagogy projects, and what are the average and total project costs?

CREATE TABLE project (project_id INT, project_name VARCHAR(50), num_students INT, avg_cost DECIMAL(5,2), total_cost DECIMAL(10,2), PRIMARY KEY(project_id)); INSERT INTO project (project_id, project_name, num_students, avg_cost, total_cost) VALUES (1, 'Open Source Software Development', 15, 500, 7500), (2, 'Data Journalism', 10, 300, 3000), (3, 'Digital Citizenship', 20, 250, 5000);

SELECT num_students, AVG(avg_cost) as avg_project_cost, SUM(total_cost) as total_project_cost FROM project;


Question: Generate PostgreSQL SQL for: What is the location of the b.c. open?

CREATE TABLE table_name_81 (location VARCHAR, tournament VARCHAR)

SELECT location FROM table_name_81 WHERE tournament = 'b.c. open';


Question: Update the price of 'Solar-Powered Lamps' to $29.99 in stores located in 'New York' and 'Texas'

CREATE TABLE Stores (store_id INT, store_name VARCHAR(50), state VARCHAR(50)); INSERT INTO Stores (store_id, store_name, state) VALUES (1, 'Eco-Market', 'New York'), (2, 'Green Vista', 'Texas'); CREATE TABLE Inventory (product_id INT, product_name VARCHAR(50), store_id INT, price DECIMAL(5, 2)); INSERT INTO Inventory (product_id, product_name, store_id, price) VALUES (1, 'Solar-Powered Lamps', 1, 24.99), (2, 'Bamboo Toothbrushes', 2, 9.99);

UPDATE Inventory SET price = 29.99 WHERE product_name = 'Solar-Powered Lamps' AND store_id IN (SELECT store_id FROM Stores WHERE state IN ('New York', 'Texas'));


Question: Generate PostgreSQL SQL for: Which record has Katsuomi Inagaki as an opponent?

CREATE TABLE table_name_51 (record VARCHAR, opponent VARCHAR)

SELECT record FROM table_name_51 WHERE opponent = 'katsuomi inagaki';


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

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

SELECT count(*) FROM (SELECT to_char('100'::numeric, 'f"ool\"999')) AS _sub;


Question: What is the average energy efficiency rating for appliances in the European Union?

CREATE TABLE eu_appliances (id INT, country VARCHAR(255), name VARCHAR(255), energy_efficiency_rating FLOAT); INSERT INTO eu_appliances (id, country, name, energy_efficiency_rating) VALUES (1, 'France', 'Appliance A', 3.5), (2, 'Germany', 'Appliance B', 4.2), (3, 'Italy', 'Appliance C', 3.9);

SELECT AVG(energy_efficiency_rating) FROM eu_appliances WHERE country IN (SELECT name FROM countries WHERE region = 'European Union');


Question: Delete records in the wildlife table where the animal_type is 'Bird' and region is 'Asia'

CREATE TABLE wildlife (id INT PRIMARY KEY, animal_type TEXT, region TEXT, conservation_status TEXT); INSERT INTO wildlife (id, animal_type, region, conservation_status) VALUES (1, 'Bird', 'Asia', 'Vulnerable');

DELETE FROM wildlife WHERE animal_type = 'Bird' AND region = 'Asia';


Question: Generate PostgreSQL SQL for: Tell me the year built for withdrawn of 1983

CREATE TABLE table_name_19 (year_built__converted VARCHAR, _ VARCHAR, withdrawn VARCHAR)

SELECT year_built__converted * _ FROM table_name_19 WHERE withdrawn = 1983;


Question: Generate PostgreSQL SQL for: When the engine Ford Cosworth DFV 3.0 v8 has a chassis of m23 and in rounds 14-15, what is its Tyre?

CREATE TABLE table_name_51 (tyre VARCHAR, chassis VARCHAR, rounds VARCHAR, engine VARCHAR)

SELECT tyre FROM table_name_51 WHERE rounds = '14-15' AND engine = 'ford cosworth dfv 3.0 v8' AND chassis = 'm23';


Question: Generate PostgreSQL SQL for: Which route has 21 stations?

CREATE TABLE table_name_31 (route VARCHAR, stations VARCHAR)

SELECT route FROM table_name_31 WHERE stations = 21;


Question: Generate PostgreSQL SQL for: What is the 2012 population for the state whose capital is Santa Fe?

CREATE TABLE table_name_61 (population_est__2012_ VARCHAR, capital VARCHAR)

SELECT population_est__2012_ FROM table_name_61 WHERE capital = 'santa fe';


Question: Generate PostgreSQL SQL for: What are the ids of the movies that are not reviewed by Brittany Harris.

CREATE TABLE Reviewer (rID VARCHAR, name VARCHAR); CREATE TABLE Rating (mID VARCHAR); CREATE TABLE Rating (mID VARCHAR, rID VARCHAR)

SELECT mID FROM Rating EXCEPT SELECT T1.mID FROM Rating AS T1 JOIN Reviewer AS T2 ON T1.rID = T2.rID WHERE T2.name = 'Brittany Harris';


Question: Determine the number of public events held in the city of Los Angeles in each month of the year 2021

CREATE TABLE public_events (event_id INT, city VARCHAR(20), year INT, month INT, events_held INT); INSERT INTO public_events (event_id, city, year, month, events_held) VALUES (1, 'Los Angeles', 2021, 1, 10);

SELECT month, SUM(events_held) FROM public_events WHERE city = 'Los Angeles' AND year = 2021 GROUP BY month;


Question: How many students have enrolled in each course offering, and what is the average mental health rating for each course?

CREATE TABLE course_offerings (course_id INT, offering_id INT, enrollment INT); INSERT INTO course_offerings (course_id, offering_id, enrollment) VALUES (1, 1, 30), (1, 2, 25), (2, 1, 20), (2, 2, 22), (3, 1, 40), (3, 2, 38), (4, 1, 35), (4, 2, 33); CREATE TABLE courses (course_id INT, mental_health_rating FLOAT); INSERT INTO courses (course_id, mental_health_rating) VALUES (1, 4.5), (2, 3.8), (3, 4.7), (4, 2.5);

SELECT co.offering_id, c.course_id, AVG(c.mental_health_rating) AS avg_rating, SUM(co.enrollment) AS total_enrollment FROM course_offerings co JOIN courses c ON co.course_id = c.course_id GROUP BY co.offering_id, c.course_id;


Question: Update the region of donors who have donated more than $5000 in the 'asia' region to 'emerging_market'.

CREATE TABLE donors (id INT, name TEXT, region TEXT, donation_amount FLOAT); INSERT INTO donors (id, name, region, donation_amount) VALUES (1, 'John Doe', 'Asia', 5000.00), (2, 'Jane Smith', 'Europe', 3000.00);

UPDATE donors SET region = 'Emerging_Market' WHERE region = 'Asia' AND donation_amount > 5000;


Question: What is the increase in the number of local vendors participating in sustainable events in Mexico?

CREATE TABLE VendorParticipation (ParticipationID INT, Country VARCHAR(50), Vendors INT); INSERT INTO VendorParticipation (ParticipationID, Country, Vendors) VALUES (1, 'Mexico', 50), (2, 'Mexico', 60);

SELECT SUM(Vendors) FROM VendorParticipation WHERE Country = 'Mexico';


Question: What is the average playtime for players who have played games with a price greater than 50, by gender?

CREATE TABLE Players (PlayerID INT, Age INT, Gender VARCHAR(10), Country VARCHAR(50)); INSERT INTO Players (PlayerID, Age, Gender, Country) VALUES (1, 25, 'Male', 'USA'), (2, 30, 'Female', 'Canada'), (3, 22, 'Male', 'Mexico'); CREATE TABLE GamePlay (PlayerID INT, Playtime INT, GamePrice DECIMAL(5, 2)); INSERT INTO GamePlay (PlayerID, Playtime, GamePrice) VALUES (1, 120, 60.00), (2, 90, 45.00), (3, 150, 55.00), (4, 100, 70.00), (5, 80, 75.00);

SELECT Gender, AVG(Playtime) FROM Players INNER JOIN GamePlay ON Players.PlayerID = GamePlay.PlayerID WHERE GamePrice > 50 GROUP BY Gender;


Question: Generate PostgreSQL SQL for: What is Scott Gomez's biggest weight?

CREATE TABLE table_name_57 (weight__kg_ INTEGER, name VARCHAR)

SELECT MAX(weight__kg_) FROM table_name_57 WHERE name = 'scott gomez';


Question: Generate PostgreSQL SQL for: Name the team classification for stage of 6

CREATE TABLE table_name_47 (team_classification VARCHAR, stage VARCHAR)

SELECT team_classification FROM table_name_47 WHERE stage = '6';


Question: What is the total number of mining accidents in each province in Canada?

CREATE TABLE accidents (id INT, province VARCHAR(50), industry VARCHAR(50), num_accidents INT); INSERT INTO accidents (id, province, industry, num_accidents) VALUES (1, 'Ontario', 'mining', 50); INSERT INTO accidents (id, province, industry, num_accidents) VALUES (2, 'Quebec', 'mining', 30); INSERT INTO accidents (id, province, industry, num_accidents) VALUES (3, 'Alberta', 'oil', 20);

SELECT province, SUM(num_accidents) FROM accidents WHERE industry = 'mining' GROUP BY province;


Question: What is the percentage of employees from underrepresented racial groups in the mining industry?

CREATE TABLE workforce (id INT, name VARCHAR(50), ethnicity VARCHAR(50), position VARCHAR(50), department VARCHAR(50)); INSERT INTO workforce (id, name, ethnicity, position, department) VALUES (1, 'John Doe', 'Caucasian', 'Engineer', 'Mining'), (2, 'Jane Smith', 'African American', 'Technician', 'Environment'), (3, 'Alice Johnson', 'Hispanic', 'Manager', 'Operations');

SELECT (COUNT(CASE WHEN ethnicity IN ('African American', 'Hispanic', 'Native American', 'Asian', 'Pacific Islander') THEN 1 ELSE 0 END) * 100.0 / COUNT(*)) as underrepresented_percentage FROM workforce;


Question: Generate PostgreSQL SQL for: Which location has 101,119 as the capacity?

CREATE TABLE table_name_72 (location VARCHAR, capacity VARCHAR)

SELECT location FROM table_name_72 WHERE capacity = '101,119';


Question: PostgreSQL regression test 'collate.utf8': Write the SELECT query (example 38).

SELECT 'xAb' !~* '[c-d]' COLLATE PG_UNICODE_FAST;

Explanation: Regression test for Collate.Utf8 in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT 'xAb' !~* '[c-d]' COLLATE PG_UNICODE_FAST) AS _sub;


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

SELECT 'sad'::mood::citext = 'sad' AS t;

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


Question: Generate PostgreSQL SQL for: What is the total crowd count for the venue Princes Park?

CREATE TABLE table_name_23 (crowd INTEGER, venue VARCHAR)

SELECT SUM(crowd) FROM table_name_23 WHERE venue = 'princes park';


Question: What is the total amount of water saved through conservation initiatives in the year 2020?

CREATE TABLE savings (id INT, amount FLOAT, year INT); INSERT INTO savings (id, amount, year) VALUES (1, 1000, 2020), (2, 1500, 2019), (3, 2000, 2018);

SELECT SUM(amount) FROM savings WHERE year = 2020;


Question: What is the average age of all volunteers who have led community education programs?

CREATE TABLE volunteers (volunteer_id INT, age INT, has_led_program BOOLEAN);

SELECT AVG(age) FROM volunteers WHERE has_led_program = TRUE;


Question: List all oceanographic studies in 'Atlantic Ocean' since 2010.

CREATE TABLE if not exists oceanographic_studies (id INT, name TEXT, location TEXT, year INT);

SELECT * FROM oceanographic_studies WHERE location = 'Atlantic Ocean' AND year >= 2010;


Question: Generate PostgreSQL SQL for: What is Score, when Game is "19"?

CREATE TABLE table_name_11 (score VARCHAR, game VARCHAR)

SELECT score FROM table_name_11 WHERE game = 19;


Question: What is the average ESG score for companies based in the United States?

CREATE TABLE companies (company_id INT, country VARCHAR(50), esg_score FLOAT); INSERT INTO companies (company_id, country, esg_score) VALUES (1, 'United States', 75.0), (2, 'Canada', 82.3), (3, 'United States', 68.9);

SELECT AVG(esg_score) FROM companies WHERE country = 'United States';


Question: What is the average severity rating of all vulnerabilities in the 'network' category?

CREATE TABLE vulnerabilities (id INT, category VARCHAR(255), severity INT); INSERT INTO vulnerabilities (id, category, severity) VALUES (1, 'network', 8), (2, 'malware', 5);

SELECT AVG(severity) FROM vulnerabilities WHERE category = 'network';


Question: Generate PostgreSQL SQL for: How many starts have a year prior to 2012, and team penske as the team, with a finish greater than 27?

CREATE TABLE table_name_35 (start INTEGER, finish VARCHAR, year VARCHAR, team VARCHAR)

SELECT SUM(start) FROM table_name_35 WHERE year < 2012 AND team = 'team penske' AND finish > 27;


Question: Generate PostgreSQL SQL for: What is the title of every song, and how many weeks was each song at #1 for One Direction?

CREATE TABLE table_19542477_9 (song_s__—_weeks VARCHAR, artist_s_ VARCHAR)

SELECT song_s__—_weeks FROM table_19542477_9 WHERE artist_s_ = 'One Direction';


Question: Generate PostgreSQL SQL for: Find the name of the dorm with the largest capacity.

CREATE TABLE dorm (dorm_name VARCHAR, student_capacity VARCHAR)

SELECT dorm_name FROM dorm ORDER BY student_capacity DESC LIMIT 1;


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

CREATE FUNCTION gbt_cash_compress(internal)
RETURNS internal
AS 'MODULE_PATHNAME'
LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;

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


Question: Identify artists in the 'ArtistsDemographics' table who are older than 40 and from the 'American' nationality.

CREATE TABLE ArtistsDemographics (ArtistID INT, Age INT, Gender VARCHAR(10), Nationality VARCHAR(50)); INSERT INTO ArtistsDemographics (ArtistID, Age, Gender, Nationality) VALUES (1, 45, 'Male', 'American'), (2, 34, 'Female', 'Canadian'), (3, 50, 'Male', 'British'), (4, 35, 'Female', 'Mexican'), (5, 40, 'Non-binary', 'Australian');

SELECT * FROM ArtistsDemographics WHERE Age > 40 AND Nationality = 'American';


Question: What is the average manufacturing cost for aircraft components?

CREATE TABLE AircraftComponents (id INT, component_name VARCHAR(50), manufacturing_cost FLOAT);  CREATE VIEW ComponentManufacturingCosts AS SELECT component_name, AVG(manufacturing_cost) as avg_cost FROM AircraftComponents GROUP BY component_name;

SELECT ComponentManufacturingCosts.component_name, ComponentManufacturingCosts.avg_cost  FROM ComponentManufacturingCosts;


Question: Generate PostgreSQL SQL for: List the brands of lenses that took both a picture of mountains with range 'Toubkal Atlas' and a picture of mountains with range 'Lasta Massif'

CREATE TABLE mountain (id VARCHAR, range VARCHAR); CREATE TABLE photos (mountain_id VARCHAR, camera_lens_id VARCHAR); CREATE TABLE camera_lens (brand VARCHAR, id VARCHAR)

SELECT T3.brand FROM mountain AS T1 JOIN photos AS T2 ON T1.id = T2.mountain_id JOIN camera_lens AS T3 ON T2.camera_lens_id = T3.id WHERE T1.range = 'Toubkal Atlas' INTERSECT SELECT T3.brand FROM mountain AS T1 JOIN photos AS T2 ON T1.id = T2.mountain_id JOIN camera_lens AS T3 ON T2.camera_lens_id = T3.id WHERE T1.range = 'Lasta Massif';


Question: Generate PostgreSQL SQL for: How many females speak Ukrainian?

CREATE TABLE table_name_11 (females VARCHAR, language VARCHAR)

SELECT females FROM table_name_11 WHERE language = 'ukrainian';


Question: What is the average network investment per day for the past year?

CREATE TABLE network_investments (investment_id INT, investment_amount DECIMAL(10,2), investment_date DATE); INSERT INTO network_investments (investment_id, investment_amount, investment_date) VALUES (1, 25000.00, '2021-12-25'), (2, 30000.00, '2022-01-07'), (3, 15000.00, '2022-02-01');

SELECT AVG(investment_amount) FROM network_investments WHERE investment_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR);


Question: Generate PostgreSQL SQL for: Which Date has an Opposing Pitcher of jack morris, and an Inning of 4th?

CREATE TABLE table_name_88 (date VARCHAR, opposing_pitcher VARCHAR, inning VARCHAR)

SELECT date FROM table_name_88 WHERE opposing_pitcher = 'jack morris' AND inning = '4th';


Question: Which employees have completed the most cultural competency training hours?

CREATE TABLE CulturalCompetencyTraining (ID INT PRIMARY KEY, EmployeeID INT, TrainingType VARCHAR(20), Hours INT, Date DATE);

SELECT EmployeeID, SUM(Hours) as TotalHours FROM CulturalCompetencyTraining GROUP BY EmployeeID ORDER BY TotalHours DESC LIMIT 5;


Question: Generate PostgreSQL SQL for: Tell me the category of na director

CREATE TABLE table_name_75 (category VARCHAR, director VARCHAR)

SELECT category FROM table_name_75 WHERE director = 'na';


Question: Generate PostgreSQL SQL for: When was there an attendance of 51,342?

CREATE TABLE table_name_6 (date VARCHAR, attendance VARCHAR)

SELECT date FROM table_name_6 WHERE attendance = '51,342';


Question: What is the average carbon emission for mining operations in Africa?

CREATE TABLE MiningOperations (OperationID INT, MineName VARCHAR(50), Location VARCHAR(50), CarbonEmissions INT); INSERT INTO MiningOperations (OperationID, MineName, Location, CarbonEmissions) VALUES (1, 'Platinum Mine', 'South Africa', 100), (2, 'Gold Mine', 'Ghana', 120), (3, 'Diamond Mine', 'Botswana', 150);

SELECT AVG(CarbonEmissions) FROM MiningOperations WHERE Location LIKE 'Africa%';


Question: Generate PostgreSQL SQL for: Who directed the film Antonio's Breakfast?

CREATE TABLE table_name_44 (director_s_ VARCHAR, film VARCHAR)

SELECT director_s_ FROM table_name_44 WHERE film = 'antonio's breakfast';


Question: Maximum CO2 emissions from a single industrial process

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

SELECT MAX(co2_emissions) FROM industrial_processes;


Question: What is the total CO2 emissions for all mines located in Canada?

CREATE TABLE EnvironmentalImpact (ImpactID INT, MineSite VARCHAR(50), Country VARCHAR(50), CO2Emissions INT); INSERT INTO EnvironmentalImpact (ImpactID, MineSite, Country, CO2Emissions) VALUES (1, 'Site A', 'Canada', 500);

SELECT SUM(CO2Emissions) FROM EnvironmentalImpact WHERE Country = 'Canada';


Question: What is the maximum score achieved in a single game session?

CREATE TABLE game_sessions (session_id INT, player_id INT, score INT); INSERT INTO game_sessions (session_id, player_id, score) VALUES (1, 1, 300), (2, 2, 400), (3, 3, 250);


Question: Generate PostgreSQL SQL for: What is the Operator with a Peak that is 55?

CREATE TABLE table_name_47 (operator VARCHAR, peak VARCHAR)

SELECT operator FROM table_name_47 WHERE peak = '55';


Question: Show a query using PostgreSQL contrib extension 'btree_gist' (example 10).

SELECT count(*) FROM varbittmp WHERE a <   '1110100111010'::varbit;

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


Question: What is the minimum age of players from Japan who have played more than 50 games?

CREATE TABLE Players (PlayerID INT, PlayerName VARCHAR(50), Age INT, Country VARCHAR(50), GamesPlayed INT); INSERT INTO Players (PlayerID, PlayerName, Age, Country, GamesPlayed) VALUES (1, 'John Doe', 25, 'USA', 100); INSERT INTO Players (PlayerID, PlayerName, Age, Country, GamesPlayed) VALUES (2, 'Jane Smith', 30, 'Canada', 200); INSERT INTO Players (PlayerID, PlayerName, Age, Country, GamesPlayed) VALUES (3, 'Taro Yamada', 24, 'Japan', 75); INSERT INTO Players (PlayerID, PlayerName, Age, Country, GamesPlayed) VALUES (4, 'Sachiko Tanaka', 28, 'Japan', 150);

SELECT MIN(Age) FROM Players WHERE Country = 'Japan' AND GamesPlayed > 50;


Question: What is the number of trains that require maintenance in the Berlin S-Bahn network?

CREATE TABLE train_maintenance (train_id INT, network VARCHAR(50), needs_maintenance BOOLEAN); INSERT INTO train_maintenance (train_id, network, needs_maintenance) VALUES (1, 'S-Bahn', true), (2, 'S-Bahn', false), (3, 'U-Bahn', false);

SELECT COUNT(*) FROM train_maintenance WHERE network = 'S-Bahn' AND needs_maintenance = true;


Question: Generate PostgreSQL SQL for: What is the date of birth for the player from Ulster and plays at Centre position?

CREATE TABLE table_name_26 (date_of_birth__age_ VARCHAR, club_province VARCHAR, position VARCHAR)

SELECT date_of_birth__age_ FROM table_name_26 WHERE club_province = 'ulster' AND position = 'centre';


Question: Generate PostgreSQL SQL for: Which team had 1 race, 1 F/lap and in the series 24 hours of Nurburgring?

CREATE TABLE table_name_44 (team VARCHAR, series VARCHAR, races VARCHAR, f_laps VARCHAR)

SELECT team FROM table_name_44 WHERE races = '1' AND f_laps = '1' AND series = '24 hours of nurburgring';


Question: Generate PostgreSQL SQL for: What is the platform for the latest release 5.0.3?

CREATE TABLE table_name_53 (platform VARCHAR, latest_stable_release VARCHAR)

SELECT platform FROM table_name_53 WHERE latest_stable_release = '5.0.3';


Question: Generate PostgreSQL SQL for: When sylvania, oh is the location what is the team nickname?

CREATE TABLE table_28211213_2 (team_nickname VARCHAR, location VARCHAR)

SELECT team_nickname FROM table_28211213_2 WHERE location = 'Sylvania, OH';


Question: PostgreSQL regression test 'create_view': Write the SELECT query (example 197).

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

SELECT count(*) FROM (select pg_get_viewdef('vv4', true)) AS _sub;


Question: Generate PostgreSQL SQL for: In the match where fitzroy was the away team, where was the venue?

CREATE TABLE table_name_47 (venue VARCHAR, away_team VARCHAR)

SELECT venue FROM table_name_47 WHERE away_team = 'fitzroy';


Question: Generate PostgreSQL SQL for: What was the attendance at the Billericay Town home game?

CREATE TABLE table_name_51 (attendance VARCHAR, home_team VARCHAR)

SELECT attendance FROM table_name_51 WHERE home_team = 'billericay town';


Question: Generate PostgreSQL SQL for: What are toranosuke takagi's average laps?

CREATE TABLE table_name_14 (laps INTEGER, driver VARCHAR)

SELECT AVG(laps) FROM table_name_14 WHERE driver = 'toranosuke takagi';


Question: Generate PostgreSQL SQL for: What season did he have 7 appearances?

CREATE TABLE table_name_91 (season VARCHAR, apps VARCHAR)

SELECT season FROM table_name_91 WHERE apps = 7;


Question: Insert a new record into the marine_life table for the 'Shark' species with a population of 1000 in the indian_ocean region.

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

INSERT INTO marine_life (id, species, population, region) VALUES ((SELECT COALESCE(MAX(id), 0) + 1 FROM marine_life), 'Shark', 1000, 'indian_ocean');


Question: Generate PostgreSQL SQL for: Which African countries have a smaller population than that of any country in Asia?

CREATE TABLE country (Name VARCHAR, Continent VARCHAR, population INTEGER)

SELECT Name FROM country WHERE Continent = 'Africa' AND population < (SELECT MIN(population) FROM country WHERE Continent = 'Asia');


Question: Generate PostgreSQL SQL for: What is the number of clubs when Dalian Shide won and Sichuan Quanxing won 4th?

CREATE TABLE table_name_35 (number_of_clubs INTEGER, winners VARCHAR, fourth_placed VARCHAR)

SELECT AVG(number_of_clubs) FROM table_name_35 WHERE winners = 'dalian shide' AND fourth_placed = 'sichuan quanxing';


Question: Generate PostgreSQL SQL for: How many picks does Matt Moran have altogether after round 6?

CREATE TABLE table_name_72 (pick VARCHAR, name VARCHAR, round VARCHAR)

SELECT COUNT(pick) FROM table_name_72 WHERE name = 'matt moran' AND round > 6;


Question: Identify policyholders who have never made a claim in Michigan

CREATE TABLE claims (policyholder_id INT, claim_number INT, state VARCHAR(2)); INSERT INTO claims (policyholder_id, claim_number, state) VALUES (1, 1, 'MI'), (2, 1, 'MI'), (3, 1, 'OH');

SELECT policyholder_id FROM claims WHERE state = 'MI' GROUP BY policyholder_id HAVING COUNT(claim_number) = 1;


Question: Write the DML statement from PostgreSQL regression test 'rowsecurity' (example 379).

DELETE FROM bv1 WHERE a = 6 AND f_leak(b);

Explanation: DML from PostgreSQL core regression test for Rowsecurity.


Question: List all smart contracts in the 'Tezos' network that have a name starting with 'Con'.

CREATE TABLE tezos_smart_contracts (id INT, name VARCHAR(255), network VARCHAR(255)); INSERT INTO tezos_smart_contracts (id, name, network) VALUES (1, 'Con1', 'tezos'), (2, 'SC2', 'tezos');

SELECT * FROM tezos_smart_contracts WHERE network = 'tezos' AND name LIKE 'Con%';


Question: Update the caloric information of product X to 350.

CREATE TABLE Food (FoodID varchar(10), FoodName varchar(20), Calories int); INSERT INTO Food VALUES ('X', 'Product X', 400);

UPDATE Food SET Calories = 350 WHERE FoodID = 'X';


Question: What is the average age of fans by country?

CREATE TABLE fans (fan_id INT, fan_name VARCHAR(50), country VARCHAR(50), age INT);

SELECT f.country, AVG(f.age) as avg_age FROM fans f GROUP BY f.country;


Question: Generate PostgreSQL SQL for: What is the total number of losses against 1412, and Byes less than 2?

CREATE TABLE table_name_4 (losses VARCHAR, against VARCHAR, byes VARCHAR)

SELECT COUNT(losses) FROM table_name_4 WHERE against = 1412 AND byes < 2;


Question: Which agricultural innovations were implemented in Mexico between 2017 and 2020?

CREATE TABLE agricultural_innovations (innovation_id INT, country TEXT, innovation TEXT, implementation_year INT); INSERT INTO agricultural_innovations (innovation_id, country, innovation, implementation_year) VALUES (1, 'Mexico', 'Precision agriculture', 2017), (2, 'Mexico', 'Drip irrigation', 2018), (3, 'Mexico', 'Vertical farming', 2019), (4, 'Mexico', 'Automated harvesting', 2020);

SELECT innovation FROM agricultural_innovations WHERE country = 'Mexico' AND implementation_year BETWEEN 2017 AND 2020;


Question: Generate PostgreSQL SQL for: What is the highest to par with a place of t8 and West Germany as the country?

CREATE TABLE table_name_37 (to_par INTEGER, place VARCHAR, country VARCHAR)

SELECT MAX(to_par) FROM table_name_37 WHERE place = 't8' AND country = 'west germany';


Question: Generate PostgreSQL SQL for: Which Season 7 has a Season 6 of jim treliving?

CREATE TABLE table_name_98 (season_7 VARCHAR, season_6 VARCHAR)

SELECT season_7 FROM table_name_98 WHERE season_6 = 'jim treliving';


Question: Insert records of companies with female founders and their investments.

CREATE TABLE Companies (id INT, name TEXT, founder_gender TEXT); INSERT INTO Companies (id, name, founder_gender) VALUES (1, 'Women in Power', 'Female'), (2, 'Green Innovations', 'Male'); CREATE TABLE Investment_Rounds (id INT, company_name TEXT, round_amount INT, round_type TEXT, date DATE);

INSERT INTO Companies (id, name, founder_gender) VALUES (3, 'Code for Equality', 'Female'), (4, 'Sustainable Futures', 'Female'); INSERT INTO Investment_Rounds (id, company_name, round_amount, round_type, date) VALUES (1, 'Women in Power', 2000000, 'Series A', '2021-09-01'), (2, 'Green Innovations', 1500000, 'Seed', '2022-01-10'), (3, 'Code for Equality', 3000000, 'Series B', '2022-03-15'), (4, 'Sustainable Futures', 2500000, 'Seed', '2022-02-22');


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

SELECT count(*) FROM timestamptztmp WHERE a >  '2018-12-18 10:59:54 GMT+3';


Question: How many mental health parity cases were reported in each region?

CREATE TABLE MentalHealthParity (CaseID INT, Region VARCHAR(25)); INSERT INTO MentalHealthParity (CaseID, Region) VALUES (1, 'Northeast'), (2, 'Midwest'), (3, 'South'), (4, 'Northeast'), (5, 'West');

SELECT Region, COUNT(*) as NumCases FROM MentalHealthParity GROUP BY Region;


Question: What is the average calorie count for organic products in our inventory?

CREATE TABLE Inventory (product_id INT, product_name VARCHAR(100), is_organic BOOLEAN, calorie_count INT); INSERT INTO Inventory (product_id, product_name, is_organic, calorie_count) VALUES (1, 'Apple', true, 95), (2, 'Banana', true, 105), (3, 'Chips', false, 150);

SELECT AVG(calorie_count) FROM Inventory WHERE is_organic = true;


Question: What is the number of vessels in the fleet of Oceanic Lines that were built before 2010?

CREATE TABLE vessels (id INT, name VARCHAR(50), company VARCHAR(50), build_year INT); INSERT INTO vessels (id, name, company, build_year) VALUES (1, 'MV Orion', 'Oceanic Lines', 2005), (2, 'MV Pegasus', 'Oceanic Lines', 2012), (3, 'MV Neptune', 'Oceanic Lines', 2008);

SELECT COUNT(*) FROM vessels WHERE company = 'Oceanic Lines' AND build_year < 2010;


Question: Show the total amount spent on raw materials for each product in the past quarter.

CREATE TABLE raw_materials (material_id INT, product_id INT, amount DECIMAL(10,2)); INSERT INTO raw_materials VALUES (1, 1, 5000), (2, 1, 6000), (3, 2, 7000), (4, 2, 8000), (5, 3, 9000), (6, 3, 10000), (7, 1, 4000), (8, 2, 5000), (9, 3, 6000); CREATE TABLE products (product_id INT, name TEXT); INSERT INTO products VALUES (1, 'Product A'), (2, 'Product B'), (3, 'Product C');

SELECT products.name, SUM(raw_materials.amount) AS total_spent FROM raw_materials JOIN products ON raw_materials.product_id = products.product_id WHERE raw_materials.material_id > (SELECT MAX(material_id) - 3 FROM raw_materials) GROUP BY products.name;


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

CREATE FUNCTION gin_compare_prefix_timetz(timetz, timetz, int2, internal)
RETURNS int4
AS 'MODULE_PATHNAME'
LANGUAGE C STRICT IMMUTABLE;


Question: Write the DML statement from PostgreSQL regression test 'indexing' (example 472).

Explanation: DML from PostgreSQL core regression test for Indexing.


Question: Generate PostgreSQL SQL for: What's the school that has an enrollment more than 441 with chargers as their mascot?

CREATE TABLE table_name_35 (school VARCHAR, enrollment VARCHAR, mascot VARCHAR)

SELECT school FROM table_name_35 WHERE enrollment > 441 AND mascot = 'chargers';


Question: Generate PostgreSQL SQL for: what is the number where the player was jimmy demaret

CREATE TABLE table_262383_1 (runner_s__up VARCHAR)

SELECT 54 AS _holes FROM table_262383_1 WHERE runner_s__up = 'Jimmy Demaret';


Question: What is the total population in Africa with access to clean water?

CREATE TABLE WaterAccess (country_name TEXT, continent TEXT, population INTEGER, clean_water_access BOOLEAN); INSERT INTO WaterAccess (country_name, continent, population, clean_water_access) VALUES ('Algeria', 'Africa', 43073003, true), ('Angola', 'Africa', 32898569, false), ('Benin', 'Africa', 12131338, true), ('Botswana', 'Africa', 2359373, true), ('Burkina Faso', 'Africa', 20807289, false), ('Burundi', 'Africa', 11526794, false), ('Cameroon', 'Africa', 25678974, true);

SELECT SUM(population) FROM WaterAccess WHERE clean_water_access = true AND continent = 'Africa';


Question: Generate PostgreSQL SQL for: What is High Rebounds, when High Assists is "Jason Kidd (13)"?

CREATE TABLE table_name_50 (high_rebounds VARCHAR, high_assists VARCHAR)

SELECT high_rebounds FROM table_name_50 WHERE high_assists = 'jason kidd (13)';


Question: What is the average year that each country formed a military alliance?

CREATE TABLE MilitaryAlliances (id INT PRIMARY KEY, name VARCHAR(50), country VARCHAR(50), year_formed INT); INSERT INTO MilitaryAlliances (id, name, country, year_formed) VALUES (1, 'NATO', 'USA', 1949); INSERT INTO MilitaryAlliances (id, name, country, year_formed) VALUES (2, 'Warsaw Pact', 'USSR', 1955);

SELECT country, AVG(year_formed) FROM MilitaryAlliances GROUP BY country;


Question: What is the total budget for initiatives that are related to "public_safety" and were submitted after 2019-01-01 in the "initiatives" table?

CREATE TABLE initiatives (id INT, title TEXT, budget INT, category TEXT, submit_date DATE);

SELECT SUM(budget) FROM initiatives WHERE category = 'public_safety' AND submit_date > '2019-01-01';


Question: Generate PostgreSQL SQL for: what is the highest ANSI code with a latitude more than 47.623288 and a geo id more than 3805508060 with land (sqmi) more than 35.66 and a longitude less than -102.054248

CREATE TABLE table_name_98 (ansi_code INTEGER, longitude VARCHAR, land___sqmi__ VARCHAR, latitude VARCHAR, geo_id VARCHAR)

SELECT MAX(ansi_code) FROM table_name_98 WHERE latitude > 47.623288 AND geo_id > 3805508060 AND land___sqmi__ > 35.66 AND longitude < -102.054248;


Question: Who are the volunteers for the 'disaster_relief' program and when did they last volunteer?

CREATE TABLE program (id INT, name VARCHAR(255)); CREATE TABLE volunteer (id INT, program_id INT, name VARCHAR(255), last_volunteered DATE); INSERT INTO program (id, name) VALUES (1, 'youth_mentoring'), (2, 'disaster_relief'); INSERT INTO volunteer (id, program_id, name, last_volunteered) VALUES (1, 1, 'Alice', '2022-01-01'), (2, 2, 'Bob', '2022-02-15'), (3, 2, 'Charlie', '2022-03-05'), (4, 2, 'David', '2022-03-20'), (5, 1, 'Eve', '2022-04-01');

SELECT * FROM volunteer WHERE program_id = (SELECT id FROM program WHERE name = 'disaster_relief');


Question: What is the distribution of articles by topic in 2020?

CREATE TABLE articles (id INT, title VARCHAR(255), topic VARCHAR(50), publication_year INT); INSERT INTO articles (id, title, topic, publication_year) VALUES (1, 'Article1', 'Culture', 2020), (2, 'Article2', 'Politics', 2019), (3, 'Article3', 'Culture', 2018), (4, 'Article4', 'Science', 2020), (5, 'Article5', 'Culture', 2020);

SELECT topic, COUNT(*) as count FROM articles WHERE publication_year = 2020 GROUP BY topic ORDER BY count DESC;


Question: PostgreSQL regression test 'regproc': Write the SELECT query (example 124).

SELECT * FROM pg_input_error_info('-', 'regoper');

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

SELECT count(*) FROM (SELECT * FROM pg_input_error_info('-', 'regoper')) AS _sub;


Question: Generate PostgreSQL SQL for: What season was the Formula BMW USA in?

CREATE TABLE table_name_87 (season VARCHAR, series VARCHAR)

SELECT season FROM table_name_87 WHERE series = 'formula bmw usa';


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

select pg_column_size('aa=>1, b=>2'::hstore || ''::hstore)
         = pg_column_size('aa=>1, b=>2'::hstore);

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


Question: Generate PostgreSQL SQL for: What is the Nord in 1952, when tennis borussia berlin was Berlin?

CREATE TABLE table_name_3 (nord VARCHAR, berlin VARCHAR, year VARCHAR)

SELECT nord FROM table_name_3 WHERE berlin = 'tennis borussia berlin' AND year = 1952;


Question: Which organic products were sold in Europe?

CREATE TABLE products (product_id INT, product_name VARCHAR(50), is_organic BOOLEAN); INSERT INTO products VALUES (1, 'Lipstick 101', true), (2, 'Eye Shadow 202', false); CREATE TABLE sales (sale_id INT, product_id INT, sale_date DATE, region VARCHAR(50)); INSERT INTO sales VALUES (1, 1, '2022-01-05', 'Europe'), (2, 2, '2022-02-10', 'Asia'), (3, 1, '2022-03-20', 'Europe');

SELECT products.product_name FROM products INNER JOIN sales ON products.product_id = sales.product_id WHERE products.is_organic = true AND sales.region = 'Europe';


Question: Generate PostgreSQL SQL for: WHAT IS THE BUDGET FOR THE INCREDIBLES?

CREATE TABLE table_name_28 (budget VARCHAR, film VARCHAR)

SELECT budget FROM table_name_28 WHERE film = 'the incredibles';


Question: Who are the female founders that have received funding from Indian venture capital firms in the last 5 years?

CREATE TABLE investor (id INT, name VARCHAR(50), type VARCHAR(50), total_investments INT, total_assets FLOAT); CREATE TABLE investment (id INT, investor_id INT, company_id INT, round VARCHAR(50), invested_amount FLOAT, investment_date DATE); CREATE TABLE company (id INT, name VARCHAR(50), founding_year INT, industry VARCHAR(50), ceo_id INT, gender VARCHAR(10));

SELECT c.name, i.name FROM company c INNER JOIN investment inv ON c.id = inv.company_id INNER JOIN investor i ON inv.investor_id = i.id WHERE c.gender = 'Female' AND i.type = 'Venture Capital' AND investment_date >= DATEADD(year, -5, GETDATE()) AND inv.investor_id IN (SELECT id FROM investor WHERE location = 'India');


Question: Generate PostgreSQL SQL for: Which the lowest Score-Fina has a Rank-Final of 7 and a Year larger than 2009?

CREATE TABLE table_name_26 (score_final INTEGER, rank_final VARCHAR, year VARCHAR)

SELECT MIN(score_final) FROM table_name_26 WHERE rank_final = 7 AND year > 2009;


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

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

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


Question: Generate PostgreSQL SQL for: Which Club or province has a caps larger than 15 and has Chris Cusiter playing for them?

CREATE TABLE table_name_88 (club_province VARCHAR, caps VARCHAR, player VARCHAR)

SELECT club_province FROM table_name_88 WHERE caps > 15 AND player = 'chris cusiter';


Question: pgTAP test for Resultset (assertion 309).

SELECT * FROM check_test(
    results_eq( 'cwant'::refcursor, 'chave'::refcursor ),
    true,
    'results_eq(cursor, cursor)',
    '',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Resultset.


Question: Provide the average safety test scores for vehicles from each manufacturer

CREATE TABLE vehicle_safety_testing (id INT PRIMARY KEY, manufacturer VARCHAR(255), model VARCHAR(255), test_score INT);

SELECT manufacturer, AVG(test_score) as avg_score FROM vehicle_safety_testing GROUP BY manufacturer;


Question: Which mobile plans have more than 500 subscribers?

CREATE TABLE subscriber_data (subscriber_id INT, plan_id INT, age INT); INSERT INTO subscriber_data (subscriber_id, plan_id, age) VALUES (1, 1, 25), (2, 2, 35), (3, 3, 45), (4, 1, 30), (5, 2, 40), (6, 3, 50);

SELECT plan_id, COUNT(*) AS subscriber_count FROM subscriber_data GROUP BY plan_id HAVING subscriber_count > 500;


Question: Generate PostgreSQL SQL for: Find the players' first name and last name who won award both in 1960 and in 1961.

CREATE TABLE player (name_first VARCHAR, name_last VARCHAR); CREATE TABLE player_award (year VARCHAR)

SELECT T1.name_first, T1.name_last FROM player AS T1 JOIN player_award AS T2 WHERE T2.year = 1960 INTERSECT SELECT T1.name_first, T1.name_last FROM player AS T1 JOIN player_award AS T2 WHERE T2.year = 1961;


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

Explanation: DML from PostgreSQL core regression test for Numeric.


Question: How many graduate students in the Physics department have a GPA of at least 3.5?

CREATE SCHEMA if not exists higher_ed;CREATE TABLE if not exists higher_ed.students(id INT, name VARCHAR(255), department VARCHAR(255), gpa DECIMAL(3,2));

SELECT COUNT(*) FROM higher_ed.students WHERE department = 'Physics' AND gpa >= 3.5;


Question: How many users are from Germany in the Workout table?

CREATE TABLE Workout (user_id INT, workout_duration INT, country VARCHAR(50)); INSERT INTO Workout (user_id, workout_duration, country) VALUES (1, 30, 'Germany'), (2, 40, 'USA'), (3, 50, 'Germany');

SELECT COUNT(*) FROM Workout WHERE country = 'Germany';


Question: pgTAP test for Hastap (assertion 203).

SELECT * FROM check_test(
  has_leftop( '+', 'bigint', 'desc' ),
  true,
  'has_leftop( name, right, desc )',
  'desc',
  ''
);

Explanation: SQL assertion from pgTAP test suite for Hastap.


Question: What is the total revenue for each game?

CREATE TABLE Game (GameID INT, GameName VARCHAR(100), Genre VARCHAR(50), Price DECIMAL(5, 2)); INSERT INTO Game (GameID, GameName, Genre, Price) VALUES (1, 'GameA', 'Shooter', 50.00), (2, 'GameB', 'Strategy', 60.00), (3, 'GameC', 'RPG', 40.00); CREATE TABLE Sales (SaleID INT, GameID INT, Quantity INT); INSERT INTO Sales (SaleID, GameID, Quantity) VALUES (1, 1, 100), (2, 2, 150), (3, 1, 50), (4, 3, 200);

SELECT GameID, SUM(Price * Quantity) FROM Game G JOIN Sales S ON G.GameID = S.GameID GROUP BY GameID;


Question: Generate PostgreSQL SQL for: What was the Attendance on September 26, 1971?

CREATE TABLE table_name_86 (attendance INTEGER, date VARCHAR)

SELECT AVG(attendance) FROM table_name_86 WHERE date = 'september 26, 1971';


Question: What is the name of the defense diplomacy events held by India with ASEAN countries in 2018?

CREATE TABLE defense_diplomacy (id INT, country VARCHAR(255), year INT, event_name VARCHAR(255)); INSERT INTO defense_diplomacy (id, country, year, event_name) VALUES (1, 'Indonesia', 2018, 'India-Indonesia Defense Cooperation Dialogue');

SELECT DISTINCT event_name FROM defense_diplomacy WHERE country LIKE 'ASEAN%' AND year = 2018;


Question: What was the total budget allocated for environmental services in 2020, 2021, and 2022?

CREATE TABLE EnvBudget (Year INT, Amount INT); INSERT INTO EnvBudget (Year, Amount) VALUES (2020, 1200000), (2021, 1300000), (2022, 1400000);

SELECT Year, SUM(Amount) FROM EnvBudget GROUP BY Year;


Question: What is the percentage change in the number of public hospitals in each region between 2018 and 2021?

CREATE TABLE regions (region_name VARCHAR(50), year INT, num_hospitals INT); INSERT INTO regions VALUES ('Region 1', 2018, 50); INSERT INTO regions VALUES ('Region 1', 2019, 52); INSERT INTO regions VALUES ('Region 1', 2020, 54); INSERT INTO regions VALUES ('Region 1', 2021, 56); INSERT INTO regions VALUES ('Region 2', 2018, 40); INSERT INTO regions VALUES ('Region 2', 2019, 43); INSERT INTO regions VALUES ('Region 2', 2020, 45); INSERT INTO regions VALUES ('Region 2', 2021, 47);

SELECT region_name, (LAG(num_hospitals, 3) OVER (PARTITION BY region_name ORDER BY year) - num_hospitals) * 100.0 / NULLIF(LAG(num_hospitals, 3) OVER (PARTITION BY region_name ORDER BY year), 0) as percentage_change FROM regions;


Question: Generate PostgreSQL SQL for: Show the document id with paragraph text 'Brazil' and 'Ireland'.

CREATE TABLE Paragraphs (document_id VARCHAR, paragraph_text VARCHAR)

SELECT document_id FROM Paragraphs WHERE paragraph_text = 'Brazil' INTERSECT SELECT document_id FROM Paragraphs WHERE paragraph_text = 'Ireland';


Question: List the names of all graduate students who have not published an academic paper.

CREATE TABLE paper (id INT, student_id INT); INSERT INTO paper (id, student_id) VALUES (1, 1), (2, 2), (3, 3); CREATE TABLE student (id INT, name TEXT); INSERT INTO student (id, name) VALUES (1, 'Alice'), (2, 'Bob'), (3, 'Charlie'), (4, 'Diana');

SELECT name FROM student WHERE id NOT IN (SELECT student_id FROM paper);


Question: What is the maximum number of points scored in a volleyball game?

CREATE TABLE games (id INT, team1 VARCHAR(50), team2 VARCHAR(50), points_team1 INT, points_team2 INT);

SELECT MAX(GREATEST(points_team1, points_team2)) FROM games;


Question: Which neighborhood in Austin has the most affordable housing?

CREATE TABLE housing_units (id INT, neighborhood TEXT, city TEXT, state TEXT, price FLOAT, is_affordable BOOLEAN);

SELECT neighborhood, COUNT(*) as total_affordable FROM housing_units WHERE city = 'Austin' AND is_affordable = TRUE GROUP BY 1 HAVING total_affordable > (SELECT AVG(total_affordable) FROM (SELECT COUNT(*) as total_affordable FROM housing_units WHERE city = 'Austin' AND is_affordable = TRUE GROUP BY neighborhood) as subquery);


Question: Generate PostgreSQL SQL for: Name the winning driver for round 7

CREATE TABLE table_name_24 (winning_driver VARCHAR, round VARCHAR)

SELECT winning_driver FROM table_name_24 WHERE round = 7;


Question: What is the total number of points scored by the 'Warriors' in the NBA since the year 2015?

CREATE TABLE games (game_id INT, team1 VARCHAR(50), team2 VARCHAR(50), league VARCHAR(50), season INT, year INT, points1 INT, points2 INT); INSERT INTO games (game_id, team1, team2, league, season, year, points1, points2) VALUES (1, 'Warriors', 'Cavaliers', 'NBA', 2015, 2015, 104, 91);

SELECT SUM(points1) FROM games WHERE team1 = 'Warriors' AND year >= 2015;


Question: Generate PostgreSQL SQL for: What are the notes for the shirt that said Pavv before 2005?

CREATE TABLE table_name_57 (notes VARCHAR, shirt_printing VARCHAR, year VARCHAR)

SELECT notes FROM table_name_57 WHERE shirt_printing = 'pavv' AND year < 2005;


Question: How many animals of each species are there in 'Nature's Guardians'?

CREATE TABLE Nature_s_Guardians (Animal_ID INT, Animal_Name VARCHAR(50), Species VARCHAR(50), Age INT); INSERT INTO Nature_s_Guardians VALUES (1, 'Bambi', 'Deer', 3); INSERT INTO Nature_s_Guardians VALUES (2, 'Fiona', 'Turtle', 10); INSERT INTO Nature_s_Guardians VALUES (3, 'Chirpy', 'Eagle', 5); INSERT INTO Nature_s_Guardians VALUES (4, 'Whiskers', 'Raccoon', 2); INSERT INTO Nature_s_Guardians VALUES (5, 'Bella', 'Deer', 4);

SELECT Species, COUNT(*) AS Number_of_Animals FROM Nature_s_Guardians GROUP BY Species;


Question: What is the average life expectancy for individuals in urban areas compared to rural areas?

CREATE TABLE population_data (id INT, name VARCHAR(50), location VARCHAR(50), life_expectancy FLOAT); INSERT INTO population_data VALUES (1, 'John Doe', 'Urban', 78.5), (2, 'Jane Smith', 'Rural', 75.3), (3, 'Jim Brown', 'Urban', 79.2), (4, 'Jake White', 'Rural', 74.8);

SELECT AVG(life_expectancy) AS avg_life_expectancy, location FROM population_data GROUP BY location;


Question: Generate PostgreSQL SQL for: What is the highest played when there was less than 74 goals against and points 1 of 36 2?

CREATE TABLE table_name_30 (played INTEGER, points_1 VARCHAR, goals_against VARCHAR)

SELECT MAX(played) FROM table_name_30 WHERE points_1 = '36 2' AND goals_against < 74;


Question: What is the percentage of smart city projects completed in each quarter?

CREATE TABLE smart_city_projects (project_name TEXT, completion_date DATE); INSERT INTO smart_city_projects VALUES ('Project1', '2022-01-15'), ('Project2', '2022-02-20'), ('Project3', '2022-03-05'), ('Project4', '2022-04-10');

SELECT DATE_TRUNC('quarter', completion_date) AS quarter, COUNT(project_name) AS projects, COUNT(project_name) * 100.0 / (SELECT COUNT(project_name) FROM smart_city_projects) AS percentage FROM smart_city_projects GROUP BY quarter;


Question: Find the average speed of vessels per trip

VESSEL(vessel_id, voyage_id, max_speed); TRIP(voyage_id, avg_speed)

SELECT v.vessel_id, AVG(t.avg_speed) AS avg_speed_per_vessel FROM VESSEL v JOIN TRIP t ON v.voyage_id = t.voyage_id GROUP BY v.vessel_id;


Question: How many renewable energy projects are there in total for each country?

CREATE TABLE projects (name TEXT, type TEXT, country TEXT); INSERT INTO projects (name, type, country) VALUES ('Project 1', 'Wind', 'USA'), ('Project 2', 'Solar', 'Germany'), ('Project 3', 'Wind', 'France');

SELECT country, COUNT(*) FROM projects GROUP BY country;


Question: PostgreSQL regression test 'boolean': Write the SELECT query (example 85).

SELECT isfalse OR isfalse OR isnul FROM booltbl4;

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

SELECT count(*) FROM (SELECT isfalse OR isfalse OR isnul FROM booltbl4) AS _sub;


Question: Generate PostgreSQL SQL for: How many results do Ellery and Frankie have?

CREATE TABLE table_19744915_15 (result VARCHAR, couple VARCHAR)

SELECT COUNT(result) FROM table_19744915_15 WHERE couple = 'Ellery and Frankie';


Question: Generate PostgreSQL SQL for: Where was the game when Police S.A. was the opponent?

CREATE TABLE table_name_78 (location VARCHAR, opponent_team VARCHAR)

SELECT location FROM table_name_78 WHERE opponent_team = 'police s.a.';


Question: What is the number of sustainable seafood certifications in Japan and the United States?

CREATE TABLE Certifications (country VARCHAR(20), certification_type VARCHAR(20), is_sustainable BOOLEAN); INSERT INTO Certifications (country, certification_type, is_sustainable) VALUES ('Japan', 'MSC', TRUE); INSERT INTO Certifications (country, certification_type, is_sustainable) VALUES ('Japan', 'ASC', FALSE); INSERT INTO Certifications (country, certification_type, is_sustainable) VALUES ('United States', 'MSC', TRUE); INSERT INTO Certifications (country, certification_type, is_sustainable) VALUES ('United States', 'ASC', TRUE);

SELECT COUNT(*) FROM Certifications WHERE country IN ('Japan', 'United States') AND is_sustainable = TRUE;


Question: Generate PostgreSQL SQL for: What are the names and scores of wines that are made of white color grapes?

CREATE TABLE GRAPES (Grape VARCHAR, Color VARCHAR); CREATE TABLE WINE (Name VARCHAR, Score VARCHAR, Grape VARCHAR)

SELECT T2.Name, T2.Score FROM GRAPES AS T1 JOIN WINE AS T2 ON T1.Grape = T2.Grape WHERE T1.Color = 'White';


Question: What is the maximum and minimum number of attendees at cultural events in each state, grouped by state?

CREATE TABLE cultural_events (id INT, name VARCHAR(255), state VARCHAR(255), attendance INT);

SELECT state, MAX(attendance) AS max_attendance, MIN(attendance) AS min_attendance FROM cultural_events GROUP BY state;


Question: What is the maximum duration (in days) of completed missions?

CREATE TABLE mission_duration (mission_name VARCHAR(50), mission_status VARCHAR(50), duration INT);

SELECT mission_status, MAX(duration) as max_duration FROM mission_duration WHERE mission_status = 'completed' GROUP BY mission_status;


Question: Generate PostgreSQL SQL for: What is the rank for the city of sewri?

CREATE TABLE table_name_46 (rank VARCHAR, city VARCHAR)

SELECT COUNT(rank) FROM table_name_46 WHERE city = 'sewri';


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

SELECT * FROM INT8_TBL WHERE q2 < 4567890123456789;

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

SELECT count(*) FROM (SELECT * FROM INT8_TBL WHERE q2 < 4567890123456789) AS _sub;


Question: PL/pgSQL test: Plpython Import (example 8).

-- test import and simple argument handling
--
SELECT import_test_one('sha hash of this string');

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


Question: Generate PostgreSQL SQL for: How many people did Mayor Olav Martin Vik preside over?

CREATE TABLE table_name_87 (innhabitants INTEGER, mayor VARCHAR)

SELECT AVG(innhabitants) FROM table_name_87 WHERE mayor = 'olav martin vik';


Question: Insert a new record of a whale sighting in the Atlantic Ocean

CREATE TABLE whale_sightings (id INT PRIMARY KEY, species VARCHAR(255), location VARCHAR(255), sighting_date DATE);

INSERT INTO whale_sightings (id, species, location, sighting_date) VALUES (1, 'Blue Whale', 'Atlantic Ocean', '2023-03-12');


Question: Generate PostgreSQL SQL for: What was the match points score for the match won by Connacht?

CREATE TABLE table_28068063_2 (match_points VARCHAR, winners VARCHAR)

SELECT match_points FROM table_28068063_2 WHERE winners = 'Connacht';


Question: What are the drug approval dates for each drug in the 'DrugApproval' table, grouped by drug name?

CREATE TABLE DrugApproval (drug_name VARCHAR(255), approval_date DATE); INSERT INTO DrugApproval (drug_name, approval_date) VALUES ('DrugA', '2020-01-01'), ('DrugB', '2019-05-15'), ('DrugC', '2018-12-31');

SELECT drug_name, MIN(approval_date) as first_approval_date FROM DrugApproval GROUP BY drug_name;


Question: Generate PostgreSQL SQL for: I want the ends for transfer fee of free and goals being 0 for roy carroll

CREATE TABLE table_name_53 (ends VARCHAR, name VARCHAR, transfer_fee VARCHAR, goals VARCHAR)

SELECT ends FROM table_name_53 WHERE transfer_fee = 'free' AND goals = 0 AND name = 'roy carroll';


Question: Generate PostgreSQL SQL for: What are the African countries that have a  population less than any country in Asia?

CREATE TABLE country (Name VARCHAR, Continent VARCHAR, population INTEGER)

SELECT Name FROM country WHERE Continent = 'Africa' AND population < (SELECT MAX(population) FROM country WHERE Continent = 'Asia');


Question: Generate PostgreSQL SQL for: what is the location when the year is after 1974 and the date is september 19?

CREATE TABLE table_name_36 (location VARCHAR, year VARCHAR, date VARCHAR)

SELECT location FROM table_name_36 WHERE year > 1974 AND date = 'september 19';


Question: Generate PostgreSQL SQL for: Which Position has a Round smaller than 14, and a College of illinois?

CREATE TABLE table_name_88 (position VARCHAR, round VARCHAR, college VARCHAR)

SELECT position FROM table_name_88 WHERE round < 14 AND college = 'illinois';


Question: What is the total number of community health workers by gender in the United States?

CREATE TABLE Genders (gender_id INT, gender_name TEXT); CREATE TABLE CommunityHealthWorkers (worker_id INT, worker_gender INT, country_id INT);

SELECT COUNT(*) as total_workers, g.gender_name FROM CommunityHealthWorkers chw JOIN Genders g ON chw.worker_gender = g.gender_id WHERE country_id = 1 GROUP BY chw.worker_gender;


Question: PostgreSQL regression test 'jsonpath': Write the SELECT query (example 104).

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

SELECT count(*) FROM (select '($)'::jsonpath) AS _sub;


Question: What is the average water consumption of factories in each country?

CREATE TABLE Factories (id INT, name TEXT, country TEXT, water_consumption DECIMAL(5,2)); INSERT INTO Factories (id, name, country, water_consumption) VALUES (1, 'Factory A', 'USA', 12000.00), (2, 'Factory B', 'Mexico', 15000.00), (3, 'Factory C', 'India', 8000.00), (4, 'Factory D', 'Bangladesh', 10000.00), (5, 'Factory E', 'China', 13000.00);

SELECT country, AVG(water_consumption) FROM Factories GROUP BY country;


Question: How many users have a heart rate above 150 during evening workouts?

CREATE TABLE workouts (id INT, user_id INT, heart_rate INT, workout_time TIME); INSERT INTO workouts (id, user_id, heart_rate, workout_time) VALUES (1, 1, 160, '18:00:00');

SELECT COUNT(*) FROM workouts WHERE heart_rate > 150 AND workout_time BETWEEN '18:00:00' AND '23:59:59';


Question: Generate PostgreSQL SQL for: Name the district for tim lee hall

CREATE TABLE table_1341672_14 (district VARCHAR, incumbent VARCHAR)

SELECT district FROM table_1341672_14 WHERE incumbent = 'Tim Lee Hall';


Question: Generate PostgreSQL SQL for: What was the score when 43,746 attended?

CREATE TABLE table_name_50 (score VARCHAR, attendance VARCHAR)

SELECT score FROM table_name_50 WHERE attendance = '43,746';


Question: Generate PostgreSQL SQL for: When the apparent magnitude is 10.5, what is the right ascension?

CREATE TABLE table_name_71 (right_ascension___j2000__ VARCHAR, apparent_magnitude VARCHAR)

SELECT right_ascension___j2000__ FROM table_name_71 WHERE apparent_magnitude = 10.5;


Question: Generate PostgreSQL SQL for: Name the rufus guest for episode 1x07

CREATE TABLE table_19930660_1 (rufus_guest VARCHAR, episode VARCHAR)

SELECT rufus_guest FROM table_19930660_1 WHERE episode = '1x07';


Question: Insert new soil moisture data for field ID 67890.

CREATE TABLE soil_moisture (field_id INT, date DATE, moisture DECIMAL(5,2));


Question: Generate PostgreSQL SQL for: How many years has 1 run?

CREATE TABLE table_name_53 (year VARCHAR, score VARCHAR)

SELECT COUNT(year) FROM table_name_53 WHERE score = '1 run';


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


Question: pgTAP test for Resultset (assertion 324).

-- Try an empty set in the second arg.
SELECT * FROM check_test(
    set_has( 'anames', 'SELECT id, name FROM annames WHERE false' ),
    true,
    'set_has( prepared, empty )',
    '',
    ''
);


Question: Generate PostgreSQL SQL for: How many schools did Bubba Starling attend?

CREATE TABLE table_11677100_17 (school VARCHAR, player VARCHAR)

SELECT COUNT(school) FROM table_11677100_17 WHERE player = 'Bubba Starling';


Question: Generate PostgreSQL SQL for: What district is Joseph Lecompte in office in?

CREATE TABLE table_2668243_8 (district VARCHAR, incumbent VARCHAR)

SELECT district FROM table_2668243_8 WHERE incumbent = 'Joseph Lecompte';


Question: Generate PostgreSQL SQL for: What is the genre for the hot fm station?

CREATE TABLE table_1601792_3 (genre VARCHAR, station VARCHAR)

SELECT genre FROM table_1601792_3 WHERE station = 'Hot FM';


Question: What is the average weight of pottery artifacts?

CREATE TABLE ArtifactTypes (id INT, name VARCHAR(255), category VARCHAR(255)); INSERT INTO ArtifactTypes (id, name, category) VALUES (1, 'Pottery', 'Artifact'); CREATE TABLE Artifacts (id INT, artifactTypeId INT, name VARCHAR(255), weight FLOAT); INSERT INTO Artifacts (id, artifactTypeId, weight) VALUES (1, 1, 1.5), (2, 1, 2.2), (3, 1, 1.8);

SELECT AVG(weight) FROM Artifacts WHERE artifactTypeId = (SELECT id FROM ArtifactTypes WHERE name = 'Pottery');


Question: What is the minimum depth of any ocean floor mapping project site in the 'Ocean' schema?

CREATE SCHEMA Ocean; CREATE TABLE Mapping (site_id INT, depth FLOAT); INSERT INTO Mapping (site_id, depth) VALUES (1, 5000.2), (2, 4000.3), (3, 3000.4), (4, 2000.5), (5, 1000.6);


Question: What is the number of building permits issued for each type of building in the city of Chicago?

CREATE TABLE permit (id INT, city VARCHAR(20), type VARCHAR(20), permit_number INT); INSERT INTO permit (id, city, type, permit_number) VALUES (1, 'Chicago', 'Residential', 100), (2, 'Chicago', 'Commercial', 150), (3, 'LA', 'Residential', 80);

SELECT type, COUNT(permit_number) FROM permit WHERE city = 'Chicago' GROUP BY type;


Question: Generate PostgreSQL SQL for: Who was the opponent at the game with a result of W 13–12?

CREATE TABLE table_name_83 (opponent VARCHAR, result VARCHAR)

SELECT opponent FROM table_name_83 WHERE result = 'w 13–12';


Question: Identify the total biomass of fish in farms located in the Mediterranean sea?

CREATE TABLE fish_farms (id INT, name TEXT, country TEXT, biomass FLOAT); INSERT INTO fish_farms (id, name, country) VALUES (1, 'Farm C', 'Italy'); INSERT INTO fish_farms (id, name, country) VALUES (2, 'Farm D', 'Spain'); CREATE TABLE biomass_data (farm_id INT, biomass FLOAT); INSERT INTO biomass_data (farm_id, biomass) VALUES (1, 500.3); INSERT INTO biomass_data (farm_id, biomass) VALUES (2, 600.5);

SELECT SUM(bd.biomass) FROM fish_farms ff JOIN biomass_data bd ON ff.id = bd.farm_id WHERE ff.country LIKE '%Mediterranean%';


Question: Generate PostgreSQL SQL for: What position was the player who was drafted by the Washington Capitals?

CREATE TABLE table_2850912_10 (position VARCHAR, nhl_team VARCHAR)

SELECT position FROM table_2850912_10 WHERE nhl_team = 'Washington Capitals';


Question: What is the total waste produced per production line per week?

create table ProductionWaste (ProductionLine varchar(255), Waste int, Timestamp datetime); insert into ProductionWaste values ('ProductionLine1', 10, '2022-01-01 00:00:00'), ('ProductionLine2', 15, '2022-01-01 01:00:00'), ('ProductionLine1', 12, '2022-01-08 02:00:00');

select ProductionLine, DATE_PART('week', Timestamp) as Week, SUM(Waste) as TotalWaste from ProductionWaste group by ProductionLine, Week;


Question: Generate PostgreSQL SQL for: What is the earliest term limit for the senator who resides in Coshocton?

CREATE TABLE table_26129220_2 (term_limited INTEGER, residence VARCHAR)

SELECT MIN(term_limited) FROM table_26129220_2 WHERE residence = 'Coshocton';


Question: Find the regulatory frameworks that were implemented after the regulatory framework with ID 5.

SELECT * FROM regulatory_frameworks WHERE implementation_date > (SELECT implementation_date FROM regulatory_frameworks WHERE id = 5);


Question: What is the minimum monthly bill for broadband subscribers in the city of San Francisco?

CREATE TABLE broadband_subscribers (subscriber_id INT, monthly_bill FLOAT, city VARCHAR(20)); INSERT INTO broadband_subscribers (subscriber_id, monthly_bill, city) VALUES (1, 60.5, 'San Francisco'), (2, 70.3, 'Houston'), (3, 55.7, 'San Francisco');

SELECT MIN(monthly_bill) FROM broadband_subscribers WHERE city = 'San Francisco';


Question: What is the average number of visitors for natural destinations in each country?

CREATE TABLE Destinations (id INT PRIMARY KEY, country_id INT, name VARCHAR(255), type VARCHAR(255)); INSERT INTO Destinations (id, country_id, name, type) VALUES (1, 1, 'Sydney Opera House', 'Cultural'); INSERT INTO Destinations (id, country_id, name, type) VALUES (2, 1, 'Great Barrier Reef', 'Natural'); INSERT INTO Destinations (id, country_id, name, type) VALUES (3, 2, 'Niagara Falls', 'Natural'); INSERT INTO Destinations (id, country_id, name, type) VALUES (4, 2, 'CN Tower', 'Architectural');

SELECT country_id, AVG(visitors) FROM Tourists t JOIN Destinations d ON t.country_id = d.country_id WHERE d.type = 'Natural' GROUP BY country_id;


Question: Generate PostgreSQL SQL for: How many womens singles entries are there when womens doubles is li xiaodan wen jia?

CREATE TABLE table_28138035_27 (womens_singles VARCHAR, womens_doubles VARCHAR)

SELECT COUNT(womens_singles) FROM table_28138035_27 WHERE womens_doubles = 'Li Xiaodan Wen Jia';


Question: Generate PostgreSQL SQL for: What is the score for set 2 when the score of set 1 is 19–25?

CREATE TABLE table_name_70 (set_2 VARCHAR, set_1 VARCHAR)

SELECT set_2 FROM table_name_70 WHERE set_1 = '19–25';


Question: Generate PostgreSQL SQL for: How many dogs have an age below the average?

SELECT COUNT(*) FROM Dogs WHERE age < (SELECT AVG(age) FROM Dogs);


Question: PostgreSQL regression test 'partition_merge': Write the SELECT query (example 165).

SELECT * FROM sales_list WHERE salesperson_name = 'Ivanov';

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

SELECT count(*) FROM (SELECT * FROM sales_list WHERE salesperson_name = 'Ivanov') AS _sub;


Question: Generate PostgreSQL SQL for: When maker is the model what is the nupowr 167?

CREATE TABLE table_3002894_4 (nupowr_167 VARCHAR, model VARCHAR)

SELECT nupowr_167 FROM table_3002894_4 WHERE model = 'Maker';


Question: Generate PostgreSQL SQL for: Which Venue has an Away team of south melbourne?

CREATE TABLE table_name_89 (venue VARCHAR, away_team VARCHAR)

SELECT venue FROM table_name_89 WHERE away_team = 'south melbourne';


Question: What is the total number of community education programs in each country?

CREATE TABLE education_programs (id INT, name VARCHAR(50), country VARCHAR(50), programs INT); INSERT INTO education_programs (id, name, country, programs) VALUES (1, 'Wildlife Awareness', 'Brazil', 10), (2, 'Habitat Conservation', 'Kenya', 5), (3, 'Biodiversity Education', 'Indonesia', 15);

SELECT country, SUM(programs) FROM education_programs GROUP BY country;


Question: Generate PostgreSQL SQL for: When the driver richard attwood has a constructor of brm, what is the number of laps?

CREATE TABLE table_name_87 (laps VARCHAR, constructor VARCHAR, driver VARCHAR)

SELECT laps FROM table_name_87 WHERE constructor = 'brm' AND driver = 'richard attwood';


Question: Generate PostgreSQL SQL for: If the vehicle category is multi-axle vehicle, what is the till aligarh?

CREATE TABLE table_19787093_1 (till_aligarh INTEGER, vehicle_category VARCHAR)

SELECT MIN(till_aligarh) FROM table_19787093_1 WHERE vehicle_category = 'Multi-axle Vehicle';


Question: Generate PostgreSQL SQL for: What was the score at 3:27?

CREATE TABLE table_name_8 (score VARCHAR, time VARCHAR)

SELECT score FROM table_name_8 WHERE time = '3:27';


Question: Generate PostgreSQL SQL for: Which Score has an Outcome of runner-up, and a Tournament of johannesburg?

CREATE TABLE table_name_69 (score VARCHAR, outcome VARCHAR, tournament VARCHAR)

SELECT score FROM table_name_69 WHERE outcome = 'runner-up' AND tournament = 'johannesburg';


Question: Generate PostgreSQL SQL for: What are the average and minimum price (in Euro) of all products?

CREATE TABLE catalog_contents (price_in_euros INTEGER)

SELECT AVG(price_in_euros), MIN(price_in_euros) FROM catalog_contents;


Question: What is the average age of fans who have attended at least one home game for the NY Knicks and live in New York?

CREATE TABLE fans (fan_id INT, age INT, city VARCHAR(20)); CREATE TABLE tickets (ticket_id INT, fan_id INT, team_id INT); CREATE TABLE teams (team_id INT, team_name VARCHAR(20)); INSERT INTO teams (team_id, team_name) VALUES (1, 'NY Knicks'); INSERT INTO fans (fan_id, age, city) VALUES (1, 30, 'New York'); INSERT INTO tickets (ticket_id, fan_id, team_id) VALUES (1, 1, 1);

SELECT AVG(fans.age) FROM fans INNER JOIN tickets ON fans.fan_id = tickets.fan_id INNER JOIN teams ON tickets.team_id = teams.team_id WHERE teams.team_name = 'NY Knicks' AND fans.city = 'New York' GROUP BY fans.age HAVING COUNT(fans.fan_id) >= 1;


Question: Generate PostgreSQL SQL for: WHich Record has a Visitor of quebec nordiques with a Score of 7–5?

CREATE TABLE table_name_37 (record VARCHAR, visitor VARCHAR, score VARCHAR)

SELECT record FROM table_name_37 WHERE visitor = 'quebec nordiques' AND score = '7–5';


Question: What is the most popular game genre among female players?

CREATE TABLE PlayerDemographics (PlayerID INT, Gender VARCHAR(10)); INSERT INTO PlayerDemographics (PlayerID, Gender) VALUES (1, 'Male'); INSERT INTO PlayerDemographics (PlayerID, Gender) VALUES (2, 'Female');

SELECT g.Genre, COUNT(*) AS Popularity FROM Games g JOIN PlayerDemographics pd ON 1 = 1 JOIN GameSales gs ON g.GameID = gs.GameID GROUP BY g.Genre HAVING SUM(CASE WHEN pd.Gender = 'Female' THEN 1 ELSE 0 END) / COUNT(*) > 0.5;


Question: What is the distribution of funding amounts by round type?

CREATE TABLE funding_rounds (company_id INT, round_amount DECIMAL(10,2), round_type VARCHAR(20), year INT); INSERT INTO funding_rounds (company_id, round_amount, round_type, year) VALUES (1, 2000000, 'Seed', 2016), (2, 5000000, 'Series A', 2017), (3, 3000000, 'Seed', 2018), (4, 6000000, 'Series B', 2019);

SELECT f.round_type, AVG(f.round_amount), STDDEV(f.round_amount), MIN(f.round_amount), MAX(f.round_amount) FROM funding_rounds f GROUP BY f.round_type;


Question: What is the percentage of faculty members in the Humanities department who identify as underrepresented minorities?

CREATE TABLE faculty (id INT, name VARCHAR(50), department VARCHAR(50), minority VARCHAR(10)); INSERT INTO faculty (id, name, department, minority) VALUES (1, 'Judy', 'Humanities', 'Yes'); INSERT INTO faculty (id, name, department, minority) VALUES (2, 'Kevin', 'Engineering', 'No');

SELECT f.department, ROUND(100.0 * COUNT(CASE WHEN f.minority = 'Yes' THEN 1 END) / COUNT(*), 2) AS pct_minority_faculty FROM faculty f GROUP BY f.department;


Question: What is the total number of violations for each ethical fashion brand?

CREATE TABLE Violations (violation_id INT, brand_id INT, violation_count INT); CREATE TABLE Brands (brand_id INT, brand_name VARCHAR(50), ethical BOOLEAN);

SELECT B.brand_name, SUM(violation_count) FROM Violations V INNER JOIN Brands B ON V.brand_id = B.brand_id WHERE B.ethical = TRUE GROUP BY B.brand_name;


Question: Delete records of artists who have not received any funding.

CREATE TABLE Artists (artist_id INT, artist_name VARCHAR(255), community_identifier VARCHAR(255)); CREATE TABLE Funding (funding_id INT, artist_id INT, funding_amount DECIMAL(10,2));

DELETE FROM Artists WHERE artist_id NOT IN (SELECT artist_id FROM Funding);


Question: What is the total cost of materials sourced from local suppliers by each manufacturer?

CREATE TABLE manufacturers (id INT, name TEXT); INSERT INTO manufacturers (id, name) VALUES (1, 'MNO'), (2, 'PQR'); CREATE TABLE local_suppliers (id INT, manufacturer_id INT, cost FLOAT); INSERT INTO local_suppliers (id, manufacturer_id, cost) VALUES (1, 1, 5000.00), (2, 1, 7000.00), (3, 2, 8000.00); CREATE TABLE materials (id INT, local_supplier_id INT, quantity INT); INSERT INTO materials (id, local_supplier_id, quantity) VALUES (1, 1, 100), (2, 2, 150), (3, 3, 200);

SELECT m.name, SUM(l.cost * m.quantity) FROM manufacturers m JOIN local_suppliers l ON m.id = l.manufacturer_id JOIN materials m ON l.id = m.local_supplier_id GROUP BY m.name;


Question: Determine the maximum pressure (in bar) for any chemical storage unit in Mexico during the first week of October.

CREATE TABLE StorageUnits (id INT, location VARCHAR(50), pressure FLOAT, day INT); INSERT INTO StorageUnits (id, location, pressure, day) VALUES (1, 'Mexico', 10.5, 3), (2, 'Mexico', 11.2, 5), (3, 'Mexico', 9.8, 7);

SELECT MAX(pressure) FROM StorageUnits WHERE location = 'Mexico' AND day BETWEEN 1 AND 7 AND EXTRACT(MONTH FROM DATE '2022-10-01' + INTERVAL (day-1) DAY) = 10;


Question: How many wastewater treatment plants are in Canada and the United States combined?

CREATE TABLE WastewaterTreatmentPlants (country VARCHAR(20), num_plants INT);

SELECT COUNT(*) FROM WastewaterTreatmentPlants WHERE country IN ('Canada', 'United States');


Question: Generate PostgreSQL SQL for: What is the class of facility ID 150935?

CREATE TABLE table_name_21 (class VARCHAR, facility_id VARCHAR)

SELECT class FROM table_name_21 WHERE facility_id = 150935;