Question: Generate PostgreSQL SQL for: What is the Uyghur Latin with a population of 69,361?

CREATE TABLE table_name_14 (uyghur_latin___uly__ VARCHAR, population__2010_census_ VARCHAR)

SELECT uyghur_latin___uly__ FROM table_name_14 WHERE population__2010_census_ = '69,361';


Question: Insert a new policy record for policy type 'Travel'.

CREATE TABLE Policy (PolicyID INT, PolicyType VARCHAR(50), PolicyHolderName VARCHAR(50), PolicyHolderAddress VARCHAR(50));

INSERT INTO Policy (PolicyID, PolicyType, PolicyHolderName, PolicyHolderAddress) VALUES (4, 'Travel', 'Mark Brown', '321 Pine St');


Question: Generate PostgreSQL SQL for: What's the lowest number of cuts made while the win was less than 0?

CREATE TABLE table_name_65 (cuts_made INTEGER, wins INTEGER)

SELECT MIN(cuts_made) FROM table_name_65 WHERE wins < 0;


Question: How many healthcare workers are there in 'rural_clinics' table per location?

CREATE TABLE rural_clinics (id INT, name TEXT, location TEXT, num_workers INT, avg_age FLOAT); INSERT INTO rural_clinics (id, name, location, num_workers, avg_age) VALUES (1, 'Rural Clinic A', 'Rural Area 1', 10, 45.3), (2, 'Rural Clinic B', 'Rural Area 2', 15, 42.8);

SELECT location, SUM(num_workers) FROM rural_clinics GROUP BY location;


Question: Generate PostgreSQL SQL for: which club is listed when bonus points is bonus points

CREATE TABLE table_20396710_1 (club VARCHAR)

SELECT club FROM table_20396710_1 WHERE "bonus_points" = 'bonus_points';


Question: Generate PostgreSQL SQL for: What was the year when West Manila has a tariff increase of 6.5?

CREATE TABLE table_17302440_1 (year VARCHAR, west_manila VARCHAR)

SELECT year FROM table_17302440_1 WHERE west_manila = '6.5';


Question: List all the national security events related to 'Energy' in the 'NationalSecurity' schema.

CREATE SCHEMA IF NOT EXISTS NationalSecurity; CREATE TABLE IF NOT EXISTS NationalSecurity.National_Security_Events (event_id INT, event_name VARCHAR(255), start_date DATE, end_date DATE, category VARCHAR(255)); INSERT INTO NationalSecurity.National_Security_Events (event_id, event_name, start_date, end_date, category) VALUES (1, 'Energy Crisis', '1973-10-01', '1974-03-18', 'Energy'), (2, 'Fukushima Daiichi Nuclear Disaster', '2011-03-11', '2011-03-15', 'Energy');

SELECT * FROM NationalSecurity.National_Security_Events WHERE category = 'Energy';


Question: Update the carbon sequestration of 'Redwood' species in North America to 15,000,000.

CREATE TABLE regions (id INT PRIMARY KEY, name VARCHAR(255)); INSERT INTO regions (id, name) VALUES (1, 'Europe'); INSERT INTO regions (id, name) VALUES (2, 'North America'); CREATE TABLE species (id INT PRIMARY KEY, name VARCHAR(255)); INSERT INTO species (id, name) VALUES (1, 'Spruce'); INSERT INTO species (id, name) VALUES (2, 'Pine'); INSERT INTO species (id, name) VALUES (3, 'Redwood'); CREATE TABLE carbon_sequestration (region_id INT, species_id INT, sequestration INT); INSERT INTO carbon_sequestration (region_id, species_id, sequestration) VALUES (2, 3, 12000000);

UPDATE carbon_sequestration SET sequestration = 15000000 WHERE region_id = 2 AND species_id = 3;


Question: Generate PostgreSQL SQL for: What School is in the kio kio area?

CREATE TABLE table_name_60 (name VARCHAR, area VARCHAR)

SELECT name FROM table_name_60 WHERE area = 'kio kio';


Question: Generate PostgreSQL SQL for: What is the lowest no. in series?

CREATE TABLE table_17758010_2 (no_in_series INTEGER)

SELECT MIN(no_in_series) FROM table_17758010_2;


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

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

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


Question: Generate PostgreSQL SQL for: What was the total Attendance for Games while Chicago was the visiting Team?

CREATE TABLE table_name_61 (attendance INTEGER, visitor VARCHAR)

SELECT SUM(attendance) FROM table_name_61 WHERE visitor = 'chicago';


Question: Generate PostgreSQL SQL for: What campus is in Brgy. Alangilan, Batangas City?

CREATE TABLE table_name_59 (campus VARCHAR, location VARCHAR)

SELECT campus FROM table_name_59 WHERE location = 'brgy. alangilan, batangas city';


Question: Generate PostgreSQL SQL for: Reported Offenses larger than 216, and a U.S. Rate smaller than 3274, and a Texas Rate smaller than 2688.9, and a Crime of violent crime has what killeen rate?

CREATE TABLE table_name_8 (killeen_rate INTEGER, crime VARCHAR, texas_rate VARCHAR, reported_offenses VARCHAR, us_rate VARCHAR)

SELECT SUM(killeen_rate) FROM table_name_8 WHERE reported_offenses > 216 AND us_rate < 3274 AND texas_rate < 2688.9 AND crime = 'violent crime';


Question: What is the average sourcing distance for a given ingredient?

CREATE TABLE ingredients (ingredient_id INT, product_id INT, sourcing_distance FLOAT); INSERT INTO ingredients VALUES (1, 1, 250.5), (2, 1, 350.2), (3, 2, 150.8), (4, 2, 450.9);

SELECT AVG(sourcing_distance) FROM ingredients WHERE ingredient_id = 1;


Question: Generate PostgreSQL SQL for: Where did the team play and what was the attendance against new jersey?

CREATE TABLE table_13619135_7 (location_attendance VARCHAR, team VARCHAR)

SELECT location_attendance FROM table_13619135_7 WHERE team = 'New Jersey';


Question: Which REEs were produced in 2017?

CREATE TABLE production (year INT, element TEXT, quantity INT); INSERT INTO production (year, element, quantity) VALUES (2015, 'Dysprosium', 100), (2016, 'Dysprosium', 150), (2017, 'Dysprosium', 200), (2018, 'Dysprosium', 250), (2019, 'Dysprosium', 300), (2020, 'Dysprosium', 350), (2015, 'Neodymium', 500), (2016, 'Neodymium', 600), (2017, 'Neodymium', 700), (2018, 'Neodymium', 800), (2019, 'Neodymium', 900), (2020, 'Neodymium', 1000);

SELECT DISTINCT element FROM production WHERE year = 2017;


Question: Generate PostgreSQL SQL for: What is the grid for Jack Brabham with more than 65 laps?

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

SELECT SUM(grid) FROM table_name_34 WHERE driver = 'jack brabham' AND laps > 65;


Question: What is the average severity score of vulnerabilities detected in the healthcare sector?

CREATE TABLE vulnerabilities (id INT, sector VARCHAR(255), severity FLOAT); INSERT INTO vulnerabilities (id, sector, severity) VALUES (1, 'healthcare', 7.5), (2, 'finance', 5.2), (3, 'healthcare', 8.1);

SELECT AVG(severity) FROM vulnerabilities WHERE sector = 'healthcare';


Question: What is the maximum number of security incidents recorded in a single day for each month?

CREATE TABLE Incidents (id INT, incident_date DATE, country VARCHAR(255)); INSERT INTO Incidents (id, incident_date, country) VALUES (1, '2022-03-01', 'India'), (2, '2022-03-15', 'Germany'), (3, '2022-04-01', 'Brazil');

SELECT EXTRACT(MONTH FROM Incidents.incident_date) AS Month, MAX(COUNT(*)) AS Max_Incidents_Per_Day FROM Incidents GROUP BY Month;


Question: pgTAP test for Throwtap (assertion 9).

SELECT * FROM check_test(
    throws_ok( 'mytest', 'P0001'),
    true,
    'prepared statement & errcode',
    'threw P0001'
    ''
);

Explanation: SQL assertion from pgTAP test suite for Throwtap.


Question: How many cases were handled by each judge in the District Court last year?

CREATE TABLE judge_cases (judge_name VARCHAR(20), court_type VARCHAR(20), num_cases INT); INSERT INTO judge_cases (judge_name, court_type, num_cases) VALUES ('Judge 1', 'District Court', 200), ('Judge 2', 'District Court', 300), ('Judge 3', 'District Court', 400);

SELECT judge_name, SUM(num_cases) as total_cases FROM judge_cases WHERE court_type = 'District Court' GROUP BY judge_name;


Question: How many heritage sites are there in Asia, and what are their names?

CREATE TABLE HeritageSites (id INT, name TEXT, location TEXT); INSERT INTO HeritageSites (id, name, location) VALUES (1, 'Taj Mahal', 'India'); CREATE TABLE Locations (id INT, site_id INT, continent TEXT); INSERT INTO Locations (id, site_id, continent) VALUES (1, 1, 'Asia');

SELECT HS.name, COUNT(*) FROM HeritageSites HS INNER JOIN Locations L ON HS.id = L.site_id WHERE L.continent = 'Asia' GROUP BY HS.name;


Question: Write the DDL statement from PostgreSQL regression test 'constraints' (example 86).

CREATE TABLE ATACC2 () INHERITS (ATACC1);

Explanation: DDL from PostgreSQL core regression test for Constraints.


Question: Who is the youngest employee in the Sales department?

CREATE TABLE Employees (Employee_ID INT, First_Name VARCHAR(20), Last_Name VARCHAR(20), Department VARCHAR(20), Salary DECIMAL(10,2), Date_Hired DATE); CREATE VIEW Youngest_Employee AS SELECT Employee_ID, First_Name, Last_Name, Department, Salary, Date_Hired FROM Employees WHERE Date_Hired = (SELECT MIN(Date_Hired) FROM Employees); CREATE VIEW Youngest_Sales_Employee AS SELECT * FROM Youngest_Employee WHERE Department = 'Sales';


Question: What is the minimum donation amount in 'India' for the year 2022?

CREATE TABLE Donations (DonationID int, DonorID int, DonationDate date, DonationAmount decimal(10,2)); INSERT INTO Donations (DonationID, DonorID, DonationDate, DonationAmount) VALUES (1, 1, '2022-01-01', 50.00);

SELECT MIN(DonationAmount) FROM Donations WHERE Country = 'India' AND YEAR(DonationDate) = 2022;


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

SELECT diameter(f1) AS diameter
  FROM CIRCLE_TBL;

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

SELECT count(*) FROM (SELECT diameter(f1) AS diameter
  FROM CIRCLE_TBL) AS _sub;


Question: Generate PostgreSQL SQL for: In what series did Alice Levine Jamie East give a presentation on Saturday?

CREATE TABLE table_name_60 (series VARCHAR, saturday VARCHAR)

SELECT series FROM table_name_60 WHERE saturday = 'alice levine jamie east';


Question: Generate PostgreSQL SQL for: Name the chinese traditional for 美丽人生

CREATE TABLE table_1893815_1 (chinese__traditional_ VARCHAR, chinese__simplified_ VARCHAR)

SELECT chinese__traditional_ FROM table_1893815_1 WHERE chinese__simplified_ = '美丽人生';


Question: Generate PostgreSQL SQL for: What's the official website of Burning Flame 烈火雄心 with 22 episodes?

CREATE TABLE table_name_33 (official_website VARCHAR, number_of_episodes VARCHAR, english_title__chinese_title_ VARCHAR)

SELECT official_website FROM table_name_33 WHERE number_of_episodes > 22 AND english_title__chinese_title_ = 'burning flame 烈火雄心';


Question: Which vessels arrived in the Port of Long Beach more than once in the last month?

CREATE TABLE ports (id INT, name TEXT); INSERT INTO ports (id, name) VALUES (1, 'Port of Long Beach'); CREATE TABLE vessel_arrivals (id INT, port_id INT, vessel_id INT, arrival_date DATE); INSERT INTO vessel_arrivals (id, port_id, vessel_id, arrival_date) VALUES (1, 1, 1, '2022-01-01'), (2, 1, 1, '2022-01-15'), (3, 1, 2, '2022-02-01');

SELECT DISTINCT v.vessel_name  FROM vessel_arrivals va JOIN vessels v ON v.id = va.vessel_id WHERE va.port_id = (SELECT id FROM ports WHERE name = 'Port of Long Beach') AND va.arrival_date BETWEEN DATEADD(day, -30, CURRENT_DATE) AND CURRENT_DATE GROUP BY v.vessel_name HAVING COUNT(v.vessel_name) > 1;


Question: What are the total number of accidents for each company?

CREATE TABLE accidents (id INT PRIMARY KEY, company VARCHAR(50), accident_year INT); INSERT INTO accidents (id, company, accident_year) VALUES (1, 'SpaceX', 2000), (2, 'Rocket Lab', 2005), (3, 'SpaceX', 2010), (4, 'Rocket Lab', 2015);

SELECT company, COUNT(*) FROM accidents GROUP BY company;


Question: Generate PostgreSQL SQL for: What was the title of the episode with a production code of 3x6404?

CREATE TABLE table_27776266_1 (title VARCHAR, production_code VARCHAR)

SELECT title FROM table_27776266_1 WHERE production_code = '3X6404';


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

CREATE FUNCTION gin_extract_query_name(name, internal, int2, internal, internal)
RETURNS internal
AS 'MODULE_PATHNAME'
LANGUAGE C STRICT IMMUTABLE;

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


Question: Generate PostgreSQL SQL for: What is the average attendance at a game held at Firhill for the 5(r) round?

CREATE TABLE table_name_26 (attendance INTEGER, venue VARCHAR, round VARCHAR)

SELECT AVG(attendance) FROM table_name_26 WHERE venue = 'firhill' AND round = '5(r)';


Question: Find all warehouses located in countries with more than 5 fulfillment centers?

CREATE TABLE Warehouse (WarehouseID INT, WarehouseName TEXT, Country TEXT); INSERT INTO Warehouse (WarehouseID, WarehouseName, Country) VALUES (1, 'Central Warehouse', 'USA'), (2, 'East Coast Warehouse', 'USA'), (3, 'West Coast Warehouse', 'USA'), (4, 'Toronto Warehouse', 'Canada'); CREATE TABLE FulfillmentCenter (FCID INT, FCName TEXT, Country TEXT); INSERT INTO FulfillmentCenter (FCID, FCName, Country) VALUES (1, 'Chicago FC', 'USA'), (2, 'New York FC', 'USA'), (3, 'Los Angeles FC', 'USA'), (4, 'Toronto FC', 'Canada');

SELECT Country FROM Warehouse GROUP BY Country HAVING COUNT(DISTINCT WarehouseID) <= (SELECT COUNT(DISTINCT FCID) FROM FulfillmentCenter GROUP BY Country HAVING COUNT(DISTINCT FCID) > 5);


Question: Show the production quantity, waste produced, and energy consumption for the chemical with the highest safety rating

CREATE TABLE Chemicals_Data (chemical_id INT, safety_rating DECIMAL(3,2), production_quantity INT, waste_amount DECIMAL(5,2), energy_consumption INT);

SELECT cd.chemical_id, cd.production_quantity, cd.waste_amount, cd.energy_consumption FROM Chemicals_Data cd JOIN (SELECT chemical_id, MAX(safety_rating) as max_safety_rating FROM Chemicals_Data GROUP BY chemical_id) ms ON cd.chemical_id = ms.chemical_id AND cd.safety_rating = ms.max_safety_rating;


Question: Generate PostgreSQL SQL for: Who wrote the episode "The Dream Lover", which was viewed by 3.96 million viewers?

CREATE TABLE table_17467578_1 (written_by VARCHAR, us_viewers__million_ VARCHAR)

SELECT written_by FROM table_17467578_1 WHERE us_viewers__million_ = '3.96';


Question: What is the percentage of donations made by first-time donors in the last month?

CREATE TABLE donations (id INT, donor_id INT, is_first_time_donor BOOLEAN, amount DECIMAL(10, 2), donation_date DATE);

SELECT 100.0 * SUM(CASE WHEN is_first_time_donor THEN amount ELSE 0 END) / SUM(amount) as pct_first_time_donors;


Question: Generate PostgreSQL SQL for: Which round has a Kick Off of 1992-10-01 21:15?

CREATE TABLE table_name_42 (round VARCHAR, kick_off VARCHAR)

SELECT round FROM table_name_42 WHERE kick_off = '1992-10-01 21:15';


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

SELECT * FROM hash_page_items(get_raw_page('test_hash_a_idx', 1));

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


Question: What is the maximum safety rating in the 'testing_results' table?

CREATE TABLE testing_results (id INT PRIMARY KEY, vehicle_id INT, safety_rating INT, crash_test_date DATE);

SELECT MAX(safety_rating) FROM testing_results;


Question: How many open data initiatives were launched in California in 2020?

CREATE TABLE open_data_initiatives (id INT, state TEXT, launch_date DATE); INSERT INTO open_data_initiatives (id, state, launch_date) VALUES (1, 'California', '2020-01-01'), (2, 'New York', '2019-12-31'), (3, 'California', '2020-03-15'), (4, 'Texas', '2019-11-25');

SELECT COUNT(*) FROM open_data_initiatives WHERE state = 'California' AND EXTRACT(YEAR FROM launch_date) = 2020;


Question: Insert a new renewable energy source (wind) into the renewables table, and assign it a name, production value, and creation timestamp.

CREATE TABLE renewables (id INT, name VARCHAR(50), type VARCHAR(50), production FLOAT, created_at TIMESTAMP);

INSERT INTO renewables (name, type, production, created_at) VALUES ('Wind Farm 1', 'wind', 5000000, '2022-01-01 00:00:00');


Question: What is the average fare for a train trip in Seoul?

CREATE TABLE train_routes (route_id INT, route_name VARCHAR(255), city VARCHAR(255), fare DECIMAL(5,2));

SELECT AVG(fare) FROM train_routes WHERE city = 'Seoul';


Question: Generate PostgreSQL SQL for: How many receptions were smaller than 7?

CREATE TABLE table_name_12 (reception VARCHAR, long INTEGER)

SELECT COUNT(reception) FROM table_name_12 WHERE long < 7;


Question: Generate PostgreSQL SQL for: What is the Works Number that has a Number of 153 in 1916?

CREATE TABLE table_name_39 (works_number VARCHAR, date VARCHAR, number VARCHAR)

SELECT works_number FROM table_name_39 WHERE date = '1916' AND number = '153';


Question: What is the total number of spacecraft launched by the European Space Agency?

CREATE TABLE Space_Agencies (ID INT, Agency VARCHAR(50), Country VARCHAR(50), Total_Spacecraft INT); INSERT INTO Space_Agencies (ID, Agency, Country, Total_Spacecraft) VALUES (1, 'European Space Agency', 'Europe', 50), (2, 'National Aeronautics and Space Administration', 'USA', 200), (3, 'Roscosmos', 'Russia', 150), (4, 'China National Space Administration', 'China', 100), (5, 'Indian Space Research Organisation', 'India', 75);

SELECT Total_Spacecraft FROM Space_Agencies WHERE Agency = 'European Space Agency';


Question: Show the number of museums and libraries in each borough of New York City from the 'nyc_culture_database'

CREATE TABLE nyc_boroughs (id INT PRIMARY KEY, name VARCHAR(255));CREATE TABLE cultural_institutions (id INT PRIMARY KEY, name VARCHAR(255), type VARCHAR(255), borough_id INT, FOREIGN KEY (borough_id) REFERENCES nyc_boroughs(id)); INSERT INTO nyc_boroughs (id, name) VALUES (1, 'Manhattan'); INSERT INTO nyc_boroughs (id, name) VALUES (2, 'Brooklyn'); INSERT INTO cultural_institutions (id, name, type, borough_id) VALUES (1, 'New York Public Library', 'library', 1); INSERT INTO cultural_institutions (id, name, type, borough_id) VALUES (2, 'Metropolitan Museum of Art', 'museum', 1);

SELECT nyc_boroughs.name as borough_name, COUNT(CASE WHEN cultural_institutions.type = 'museum' THEN 1 ELSE NULL END) as museum_count, COUNT(CASE WHEN cultural_institutions.type = 'library' THEN 1 ELSE NULL END) as library_count FROM nyc_boroughs INNER JOIN cultural_institutions ON nyc_boroughs.id = cultural_institutions.borough_id GROUP BY nyc_boroughs.name;


Question: Generate PostgreSQL SQL for: what is the road numbers when the build year is 1943, the railroad (quantity) is clinchfield railroad (12 new, 6 secondhand)?

CREATE TABLE table_name_33 (road_numbers VARCHAR, build_year VARCHAR, railroad__quantity_ VARCHAR)

SELECT road_numbers FROM table_name_33 WHERE build_year = '1943' AND railroad__quantity_ = 'clinchfield railroad (12 new, 6 secondhand)';


Question: Generate PostgreSQL SQL for: What is the GDP of the nation with 56,210,000 people?

CREATE TABLE table_name_77 (gdp_per_capita__us$_ VARCHAR, population VARCHAR)

SELECT gdp_per_capita__us$_ FROM table_name_77 WHERE population = '56,210,000';


Question: What is the highest capacity prison in the 'prisons' table?

CREATE TABLE prisons (id INT, name VARCHAR(50), location VARCHAR(50), capacity INT, population INT, avg_age FLOAT); INSERT INTO prisons (id, name, location, capacity, population, avg_age) VALUES (1, 'Folsom State Prison', 'California', 2600, 2100, 35.5), (2, 'Sing Sing Correctional Facility', 'New York', 1932, 1585, 42.3);

SELECT name FROM prisons ORDER BY capacity DESC LIMIT 1;


Question: What is the average data usage for mobile customers in each country, segmented by prepaid and postpaid?

CREATE TABLE mobile_customers (customer_id INT, data_usage FLOAT, country VARCHAR(50), postpaid BOOLEAN); INSERT INTO mobile_customers (customer_id, data_usage, country, postpaid) VALUES (1, 2000, 'USA', TRUE), (2, 1500, 'Mexico', FALSE), (3, 3000, 'Canada', TRUE);

SELECT country, postpaid, AVG(data_usage) AS avg_data_usage FROM mobile_customers GROUP BY country, postpaid;


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

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


Question: Generate PostgreSQL SQL for: Atlanta was a visitor on December 8, what was their record?

CREATE TABLE table_name_68 (record VARCHAR, visitor VARCHAR)

SELECT record FROM table_name_68 WHERE visitor = 'atlanta';


Question: Generate PostgreSQL SQL for: What is the city of txdot har?

CREATE TABLE table_name_47 (city_of_license VARCHAR, brand VARCHAR)

SELECT city_of_license FROM table_name_47 WHERE brand = 'txdot har';


Question: How many climate adaptation projects are there in South America with a budget greater than $50,000?

CREATE TABLE climate_adaptation (id INT, project_name TEXT, budget INT, location TEXT); INSERT INTO climate_adaptation (id, project_name, budget, location) VALUES (1, 'Flood Prevention', 75000, 'South America'); INSERT INTO climate_adaptation (id, project_name, budget, location) VALUES (2, 'Drought Resistance', 40000, 'Africa');

SELECT COUNT(*) FROM climate_adaptation WHERE location = 'South America' AND budget > 50000;


Question: Identify the dispensaries in the state of Colorado with the highest average wholesale order quantity for the last 6 months, and their corresponding average wholesale order quantity.

CREATE TABLE dispensaries (id INT PRIMARY KEY, name VARCHAR(255), state VARCHAR(255), location VARCHAR(255)); CREATE TABLE wholesale_orders (id INT PRIMARY KEY, dispensary_id INT, strain_id INT, quantity INT, order_date DATE);

SELECT dispensaries.name, AVG(wholesale_orders.quantity) as avg_quantity FROM dispensaries INNER JOIN wholesale_orders ON dispensaries.id = wholesale_orders.dispensary_id WHERE dispensaries.state = 'Colorado' AND wholesale_orders.order_date BETWEEN DATE_SUB(CURRENT_DATE, INTERVAL 6 MONTH) AND CURRENT_DATE GROUP BY dispensaries.id ORDER BY avg_quantity DESC LIMIT 10;


Question: What is the average accuracy of models trained on fairness_training_data?

CREATE TABLE fairness_training_data (model_name TEXT, accuracy FLOAT);

SELECT AVG(accuracy) FROM fairness_training_data;


Question: What is the minimum salary of athletes in the tennis_players table?

CREATE TABLE tennis_players (player_id INT, name VARCHAR(50), country VARCHAR(50), ranking INT, salary DECIMAL(10, 2)); INSERT INTO tennis_players (player_id, name, country, ranking, salary) VALUES (1, 'Novak Djokovic', 'Serbia', 1, 21000000.00); INSERT INTO tennis_players (player_id, name, country, ranking, salary) VALUES (2, 'Rafael Nadal', 'Spain', 2, 18000000.00);


Question: Add a new virtual tourism attraction to 'attractions' table

CREATE TABLE attractions (id INT PRIMARY KEY, name VARCHAR(255), type VARCHAR(255), country VARCHAR(255));

INSERT INTO attractions (id, name, type, country) VALUES (1, 'Amazon Rainforest Virtual Tour', 'Virtual', 'Brazil');


Question: Write the DDL statement from PostgreSQL regression test 'alter_generic' (example 37).

CREATE SERVER alt_fserv2 FOREIGN DATA WRAPPER alt_fdw2;

Explanation: DDL from PostgreSQL core regression test for Alter Generic.


Question: Display the names of all community development projects in the 'community_development' table, excluding those with a budget over 30000.

CREATE TABLE community_development (name VARCHAR(255), budget INT); INSERT INTO community_development (name, budget) VALUES ('Handicraft Training', 15000), ('Local Business Support', 25000), ('Tourism Development', 30000);

SELECT name FROM community_development WHERE budget <= 30000;


Question: What is the total installed capacity of solar energy projects in the 'renewables' schema?

CREATE SCHEMA if not exists renewables; CREATE TABLE if not exists renewables.solar_projects (project_id int, name varchar(255), location varchar(255), installed_capacity float); INSERT INTO renewables.solar_projects (project_id, name, location, installed_capacity) VALUES (1, 'Solar Project 1', 'Country A', 50.0), (2, 'Solar Project 2', 'Country B', 75.0);

SELECT SUM(installed_capacity) FROM renewables.solar_projects;


Question: Show a SQL definition from the timescaledb project (sort_optimization, item 2).

CREATE INDEX ON order_test(time,device_id);

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


Question: What is the total waste generation by month for the material 'Metal' in 2021?

CREATE TABLE monthly_waste_generation (month VARCHAR(10), year INT, material VARCHAR(20), quantity INT); INSERT INTO monthly_waste_generation (month, year, material, quantity) VALUES ('January', 2021, 'Metal', 500), ('February', 2021, 'Metal', 600), ('March', 2021, 'Metal', 700), ('April', 2021, 'Metal', 800), ('May', 2021, 'Metal', 900);

SELECT STRFTIME('%m', month) as month, SUM(quantity) as total_waste FROM monthly_waste_generation WHERE year = 2021 AND material = 'Metal' GROUP BY STRFTIME('%m', month);


Question: What is the minimum budget for a biosensor technology project in each city?

CREATE TABLE biosensors(id INT, project VARCHAR(50), city VARCHAR(50), budget DECIMAL(10,2)); INSERT INTO biosensors VALUES (1, 'ProjectA', 'LA', 3000000.00), (2, 'ProjectB', 'NYC', 5000000.00), (3, 'ProjectC', 'LA', 4000000.00);

SELECT city, MIN(budget) FROM biosensors GROUP BY city;


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

CREATE FUNCTION sort_desc(_int4)
RETURNS _int4
AS 'MODULE_PATHNAME'
LANGUAGE C STRICT IMMUTABLE PARALLEL SAFE;


Question: pgTAP test for Ruletap (assertion 5).

CREATE RULE upd_me AS ON UPDATE TO public.sometab DO ALSO SELECT now();

Explanation: SQL assertion from pgTAP test suite for Ruletap.


Question: List all facilities along with their waste types

CREATE TABLE WasteTypes (waste_type_id INT PRIMARY KEY, name VARCHAR, description VARCHAR); CREATE TABLE Facilities (facility_id INT PRIMARY KEY, name VARCHAR, location VARCHAR, capacity INT, waste_type_id INT, FOREIGN KEY (waste_type_id) REFERENCES WasteTypes(waste_type_id)); INSERT INTO WasteTypes (waste_type_id, name, description) VALUES (1, 'Recyclable Waste', 'Waste that can be recycled');

SELECT Facilities.name AS facility_name, WasteTypes.name AS waste_type_name FROM Facilities INNER JOIN WasteTypes ON Facilities.waste_type_id = WasteTypes.waste_type_id;


Question: How many vulnerabilities were discovered in the last month, grouped by their severity levels?

CREATE TABLE vulnerabilities (id INT, severity VARCHAR(50), discovered_at TIMESTAMP);

SELECT severity, COUNT(*) as num_vulnerabilities FROM vulnerabilities WHERE discovered_at >= NOW() - INTERVAL '1 month' GROUP BY severity;


Question: What is the average price of garments made with organic cotton, per country?

CREATE TABLE materials (id INT, garment_type VARCHAR(255), material VARCHAR(255), price DECIMAL(10,2)); INSERT INTO materials (id, garment_type, material, price) VALUES (1, 'T-Shirt', 'Organic Cotton', 25.99), (2, 'Pants', 'Organic Cotton', 49.99), (3, 'Jacket', 'Organic Cotton', 79.99);

SELECT material, AVG(price) as avg_price, country FROM materials m JOIN (SELECT garment_type, material, country FROM garments g JOIN country_data cd ON g.manufacturer_id = cd.id) sub ON m.garment_type = sub.garment_type AND m.material = sub.material GROUP BY material, country;


Question: What is the average Gadolinium production by month for 2021 and 2022?

CREATE TABLE mines (id INT, name TEXT, location TEXT, gadolinium_production FLOAT, timestamp DATE); INSERT INTO mines (id, name, location, gadolinium_production, timestamp) VALUES (1, 'Mine A', 'Canada', 120.5, '2021-01-01'), (2, 'Mine B', 'Canada', 150.7, '2021-02-01'), (3, 'Mine C', 'USA', 200.3, '2021-03-01'), (4, 'Mine D', 'Canada', 250.3, '2022-01-01'), (5, 'Mine E', 'USA', 300.3, '2022-02-01');

SELECT MONTH(timestamp), AVG(gadolinium_production) FROM mines WHERE YEAR(timestamp) IN (2021, 2022) GROUP BY MONTH(timestamp);


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

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

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


Question: Delete records of donors who have not donated more than $10000 in the 'donations' table.

DELETE FROM donations WHERE donor_id NOT IN (SELECT donor_id FROM (SELECT donor_id, MAX(donation_amount) AS max_donation FROM donations GROUP BY donor_id) t WHERE max_donation > 10000);


Question: Find the total number of marine species and their observation counts in the Indian Ocean, excluding sharks and rays.

CREATE TABLE indian_marine_species (species VARCHAR(255), count INT); INSERT INTO indian_marine_species (species, count) VALUES ('Turtle', 150), ('Shark', 200), ('Manta Ray', 100), ('Dolphin', 120);

SELECT COUNT(DISTINCT species) AS species_count, SUM(count) AS total_count FROM indian_marine_species WHERE species NOT IN ('Shark', 'Manta Ray');


Question: What are the names and types of military technologies developed in '2019' according to the 'Mil_Tech' table?

CREATE TABLE Mil_Tech (tech_id INT, tech_name VARCHAR(50), tech_year INT, tech_type VARCHAR(50)); INSERT INTO Mil_Tech (tech_id, tech_name, tech_year, tech_type) VALUES (1, 'Stealth Fighter', 2019, 'Aircraft'); INSERT INTO Mil_Tech (tech_id, tech_name, tech_year, tech_type) VALUES (2, 'Carrier Battlegroup', 2017, 'Naval');

SELECT tech_name, tech_type FROM Mil_Tech WHERE tech_year = 2019;


Question: Generate PostgreSQL SQL for: what is the average bronze when the team is northwest territories and gold is more than 34?

CREATE TABLE table_name_23 (bronze INTEGER, team VARCHAR, gold VARCHAR)

SELECT AVG(bronze) FROM table_name_23 WHERE team = 'northwest territories' AND gold > 34;


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

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


Question: Which excavation sites have produced Roman pottery?

CREATE TABLE Sites (SiteID int, SiteName text, Location text, Era text); INSERT INTO Sites (SiteID, SiteName, Location, Era) VALUES (1, 'Pompeii', 'Italy', 'Roman'); CREATE TABLE Artifacts (ArtifactID int, ArtifactName text, SiteID int, Era text); INSERT INTO Artifacts (ArtifactID, ArtifactName, SiteID, Era) VALUES (1, 'Roman Pottery', 1, 'Roman');

SELECT Sites.SiteName FROM Sites INNER JOIN Artifacts ON Sites.SiteID = Artifacts.SiteID WHERE Artifacts.Era = 'Roman' AND Artifacts.ArtifactName = 'Roman Pottery';


Question: Generate PostgreSQL SQL for: How many players hometown was Cincinnati, Ohio?

CREATE TABLE table_11677691_4 (player VARCHAR, hometown VARCHAR)

SELECT COUNT(player) FROM table_11677691_4 WHERE hometown = 'Cincinnati, Ohio';


Question: Generate PostgreSQL SQL for: What Venue had 2 or more Goals in a Friendly Competition?

CREATE TABLE table_name_48 (venue VARCHAR, competition VARCHAR, goal VARCHAR)

SELECT venue FROM table_name_48 WHERE competition = 'friendly' AND goal > 2;


Question: What is the total number of military vehicles sold by ACME Corp to the African region in the year 2022?

CREATE TABLE Military_Equipment_Sales (supplier VARCHAR(255), region VARCHAR(255), equipment VARCHAR(255), quantity INT, sale_year INT);

SELECT SUM(quantity) FROM Military_Equipment_Sales WHERE supplier = 'ACME Corp' AND region = 'Africa' AND sale_year = 2022;


Question: What is the total number of unique donors for each program category, excluding those with a total donation amount below $10,000?

CREATE TABLE donor_category (donor_id INT, program_category VARCHAR(20), donation_amount INT);INSERT INTO donor_category VALUES (1, 'Arts', 5000), (2, 'Arts', 3000), (3, 'Education', 7000), (4, 'Health', 15000), (5, 'Arts', 8000), (6, 'Education', 6000);

SELECT program_category, COUNT(DISTINCT donor_id) FROM donor_category WHERE program_category IN (SELECT program_category FROM donor_category WHERE donation_amount >= 10000) GROUP BY program_category;


Question: What is the minimum rent for units in each building, ordered by building type and then by rent?

CREATE TABLE Buildings (building_id INT, name VARCHAR(50), building_type VARCHAR(50));CREATE TABLE Units (unit_id INT, building_id INT, rent INT);

SELECT b.building_type, b.name, MIN(u.rent) as min_rent FROM Units u JOIN Buildings b ON u.building_id = b.building_id GROUP BY b.building_type, b.name ORDER BY b.building_type, min_rent;


Question: Generate PostgreSQL SQL for: Julio Robledo represents which country?

CREATE TABLE table_name_55 (country VARCHAR, director_s_ VARCHAR)

SELECT country FROM table_name_55 WHERE director_s_ = 'julio robledo';


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

CREATE USER MAPPING FOR current_user SERVER s1;

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


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

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


Question: Generate PostgreSQL SQL for: Which allergy type has most number of allergies?

CREATE TABLE Allergy_type (allergytype VARCHAR)

SELECT allergytype FROM Allergy_type GROUP BY allergytype ORDER BY COUNT(*) DESC LIMIT 1;


Question: Generate PostgreSQL SQL for: What is week 15's result?

CREATE TABLE table_name_24 (result VARCHAR, week VARCHAR)

SELECT result FROM table_name_24 WHERE week = 15;


Question: Generate PostgreSQL SQL for: What result occurs when the round is 4 leg 2?

CREATE TABLE table_name_87 (result VARCHAR, round VARCHAR)

SELECT result FROM table_name_87 WHERE round = '4 leg 2';


Question: Generate PostgreSQL SQL for: How many international builders are there?

CREATE TABLE table_name_84 (total VARCHAR, builder VARCHAR)

SELECT total FROM table_name_84 WHERE builder = 'international';


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

select generate_series(timestamptz '1995-08-06 12:12:12', timestamptz '1996-08-06 12:12:12', interval 'infinity');

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

SELECT count(*) FROM (select generate_series(timestamptz '1995-08-06 12:12:12', timestamptz '1996-08-06 12:12:12', interval 'infinity')) AS _sub;


Question: Find the average age of players who have participated in esports events, segmented by the continent they reside in.

CREATE TABLE Players (PlayerID INT, Name VARCHAR(100), Age INT, Country VARCHAR(50)); INSERT INTO Players VALUES (1, 'John Doe', 25, 'USA'); INSERT INTO Players VALUES (2, 'Jane Smith', 28, 'Canada'); CREATE TABLE Countries (Country VARCHAR(50), Continent VARCHAR(50)); INSERT INTO Countries VALUES ('USA', 'North America'); INSERT INTO Countries VALUES ('Canada', 'North America'); CREATE TABLE EsportsEvents (PlayerID INT, EventName VARCHAR(100)); INSERT INTO EsportsEvents VALUES (1, 'GameX Championship'); INSERT INTO EsportsEvents VALUES (2, 'TournamentY');

SELECT C.Continent, AVG(P.Age) as AvgAge FROM Players P JOIN Countries C ON P.Country = C.Country JOIN EsportsEvents E ON P.PlayerID = E.PlayerID GROUP BY C.Continent;


Question: Which decentralized applications (DApps) are associated with the 'Ethereum' blockchain and what are their names?

CREATE TABLE dapps (dapp_id INT, dapp_name VARCHAR(50), blockchain_id INT); CREATE TABLE blockchains (blockchain_id INT, blockchain_name VARCHAR(50)); INSERT INTO dapps (dapp_id, dapp_name, blockchain_id) VALUES (1, 'Uniswap', 1); INSERT INTO blockchains (blockchain_id, blockchain_name) VALUES (1, 'Ethereum');

SELECT dapps.dapp_name, blockchains.blockchain_name FROM dapps INNER JOIN blockchains ON dapps.blockchain_id = blockchains.blockchain_id WHERE blockchains.blockchain_name = 'Ethereum';


Question: What is the explainability score for each AI safety concern in Europe?

CREATE TABLE AISafety (id INT, concern VARCHAR(255), explainability_score DECIMAL(5,2), region VARCHAR(255)); INSERT INTO AISafety (id, concern, explainability_score, region) VALUES (1, 'Data Privacy', 78.91, 'Europe'), (2, 'Unintended Consequences', 65.23, 'Asia'), (3, 'Bias', 82.34, 'Europe');

SELECT concern, explainability_score FROM AISafety WHERE region = 'Europe';


Question: Generate PostgreSQL SQL for: Against the Houston Oilers after week 14, what was the result of the game?

CREATE TABLE table_name_64 (result VARCHAR, week VARCHAR, opponent VARCHAR)

SELECT result FROM table_name_64 WHERE week > 14 AND opponent = 'houston oilers';


Question: Which regions are facing severe water scarcity in 'WaterScarcity' table?

CREATE TABLE WaterScarcity (region VARCHAR(20), scarcity_level VARCHAR(20)); INSERT INTO WaterScarcity (region, scarcity_level) VALUES ('RegionA', 'Moderate'), ('RegionB', 'Severe'), ('RegionC', 'Critical');

SELECT region FROM WaterScarcity WHERE scarcity_level = 'Severe';


Question: Update the address of the contractor 'BMC' in the 'contractors' table

CREATE TABLE contractors (contractor_id INT, name VARCHAR(50), address VARCHAR(100));

UPDATE contractors SET address = '123 Green Street' WHERE name = 'BMC';


Question: Generate PostgreSQL SQL for: What is the lowest game for a record of 32-12-3?

CREATE TABLE table_name_48 (game INTEGER, record VARCHAR)

SELECT MIN(game) FROM table_name_48 WHERE record = '32-12-3';


Question: Find the average calorie count and total fat for each cuisine type

CREATE TABLE cuisine (id INT, type VARCHAR(255), avg_calories DECIMAL(5,2), total_fat DECIMAL(5,2)); CREATE TABLE dishes (id INT, cuisine_id INT, name VARCHAR(255), calories DECIMAL(5,2), total_fat DECIMAL(5,2)); INSERT INTO cuisine (id, type, avg_calories, total_fat) VALUES (1, 'Italian', NULL, NULL), (2, 'Mexican', NULL, NULL); INSERT INTO dishes (id, cuisine_id, name, calories, total_fat) VALUES (1, 1, 'Pasta', 500, 20), (2, 1, 'Pizza', 800, 35), (3, 2, 'Tacos', 400, 15), (4, 2, 'Burritos', 700, 30);

SELECT c.type, AVG(d.calories) AS avg_calories, SUM(d.total_fat) AS total_fat FROM cuisine c JOIN dishes d ON c.id = d.cuisine_id GROUP BY c.id;


Question: How many disaster response volunteers are there in 'regions' table and what are their names?

CREATE TABLE regions (region_id INT, volunteer_name VARCHAR(50), is_disaster_response BOOLEAN); INSERT INTO regions (region_id, volunteer_name, is_disaster_response) VALUES (1, 'John Doe', true), (2, 'Jane Smith', false), (3, 'Alice Johnson', true), (4, 'Bob Brown', true), (5, 'Charlie Davis', false);

SELECT COUNT(*), volunteer_name FROM regions WHERE is_disaster_response = true;


Question: What are the total number of articles and videos in the 'media_library'?

CREATE TABLE media_library (id INT, type VARCHAR(10), title VARCHAR(50), length FLOAT, source VARCHAR(50)); INSERT INTO media_library (id, type, title, length, source) VALUES (1, 'article', 'Sample Article 1', 5.5, 'BBC'); INSERT INTO media_library (id, type, title, length, source) VALUES (2, 'video', 'Sample Video 1', 12.3, 'CNN');

SELECT COUNT(*) FROM media_library WHERE type IN ('article', 'video');


Question: What is the percentage of the population that has received the flu vaccine by disability status?

CREATE TABLE population (person_id INT, disability_status VARCHAR(10)); CREATE TABLE flu_vaccinations (vaccination_id INT, person_id INT, vaccination_date DATE);

SELECT p.disability_status, COUNT(DISTINCT p.person_id) * 100.0 / (SELECT COUNT(DISTINCT p.person_id) FROM population p) AS percentage FROM population p JOIN flu_vaccinations fv ON p.person_id = fv.person_id GROUP BY p.disability_status;


Question: Generate PostgreSQL SQL for: What is the length of the Panther Chameleon?

CREATE TABLE table_name_15 (length__female_ VARCHAR, common_name VARCHAR)

SELECT length__female_ FROM table_name_15 WHERE common_name = 'panther chameleon';


Question: What is the total number of wells drilled in the Gulf of Mexico between 2017 and 2020, and what is the sum of their daily production rates of gas?

CREATE TABLE gulf_of_mexico (id INT, well_name VARCHAR(255), drill_date DATE, daily_production_gas FLOAT);

SELECT COUNT(*) as total_wells, SUM(daily_production_gas) as total_daily_production_gas FROM gulf_of_mexico WHERE drill_date BETWEEN '2017-01-01' AND '2020-12-31';


Question: What is the maximum number of daily transactions for each blockchain network?

CREATE TABLE blockchains (blockchain_id INT, blockchain_name VARCHAR(50), daily_transactions INT); INSERT INTO blockchains (blockchain_id, blockchain_name, daily_transactions) VALUES (1, 'Ethereum', 50000); INSERT INTO blockchains (blockchain_id, blockchain_name, daily_transactions) VALUES (2, 'Solana', 100000);

SELECT blockchain_name, MAX(daily_transactions) FROM blockchains GROUP BY blockchain_name;


Question: Generate PostgreSQL SQL for: What are the different cities listed?

CREATE TABLE manufacturers (headquarter VARCHAR)

SELECT DISTINCT headquarter FROM manufacturers;


Question: What is the total trading volume for digital assets issued in the Asian region?

CREATE TABLE digital_assets (asset_id INT, asset_name VARCHAR(50), region VARCHAR(50), trading_volume DECIMAL(18,2)); INSERT INTO digital_assets (asset_id, asset_name, region, trading_volume) VALUES (1, 'Bitcoin', 'Asia', 15000000), (2, 'Ethereum', 'Asia', 8000000);

SELECT SUM(trading_volume) FROM digital_assets WHERE region = 'Asia';


Question: Generate PostgreSQL SQL for: What was the location of the game with a score of 113-106?

CREATE TABLE table_name_13 (location_attendance VARCHAR, score VARCHAR)

SELECT location_attendance FROM table_name_13 WHERE score = '113-106';


Question: Generate PostgreSQL SQL for: What were the matches where the teams finished in the first group stage, in 1998?

CREATE TABLE table_name_95 (matches VARCHAR, result VARCHAR, year VARCHAR)

SELECT matches FROM table_name_95 WHERE result = 'first group stage' AND year = '1998';


Question: Generate PostgreSQL SQL for: What's the total appeared that has an RR Rate less than 0.17?

CREATE TABLE table_name_95 (appeared INTEGER, rr_w_rate INTEGER)

SELECT SUM(appeared) FROM table_name_95 WHERE rr_w_rate < 0.17;


Question: What is the minimum budget allocated for language preservation in 'North America'?

CREATE TABLE LanguagePreservationNA (ProjectID INT PRIMARY KEY, ProjectName VARCHAR(50), Location VARCHAR(50), Budget DECIMAL(10,2)); INSERT INTO LanguagePreservationNA (ProjectID, ProjectName, Location, Budget) VALUES (1, 'Navajo Language', 'United States', 150000.00), (2, 'Inuit Language', 'Canada', 200000.00);

SELECT MIN(Budget) FROM LanguagePreservationNA WHERE Location LIKE '%North America%';


Question: What is the total number of algorithmic fairness incidents in each region for the AI Writer application?

CREATE TABLE IncidentByApp (id INT, app VARCHAR(255), region VARCHAR(255), incident_count INT); INSERT INTO IncidentByApp (id, app, region, incident_count) VALUES (1, 'AI Writer', 'North America', 12), (2, 'AI Artist', 'Europe', 15), (3, 'AI Composer', 'Asia', 8), (4, 'AI Writer', 'South America', 5), (5, 'AI Artist', 'Africa', 2), (6, 'AI Composer', 'North America', 10), (7, 'AI Writer', 'Europe', 18), (8, 'AI Writer', 'Asia', 9), (9, 'AI Writer', 'Africa', 7);

SELECT region, SUM(incident_count) as total_incidents FROM IncidentByApp WHERE app = 'AI Writer' GROUP BY region;


Question: Update the carbon offset initiative records for project 'Urban Forest' to have a total offset of 5000 tons.

CREATE TABLE carbon_offset_initiatives ( id INT PRIMARY KEY, project_name VARCHAR(255), total_offset INT );

UPDATE carbon_offset_initiatives SET total_offset = 5000 WHERE project_name = 'Urban Forest';


Question: List all astronauts who have participated in space missions and their medical records.

CREATE TABLE Astronauts (id INT, name VARCHAR(255), age INT); CREATE TABLE SpaceMissions (id INT, astronaut_id INT, mission VARCHAR(255)); CREATE TABLE MedicalRecords (id INT, astronaut_id INT, medical_condition VARCHAR(255));

SELECT Astronauts.name, SpaceMissions.mission, MedicalRecords.medical_condition FROM Astronauts INNER JOIN SpaceMissions ON Astronauts.id = SpaceMissions.astronaut_id INNER JOIN MedicalRecords ON Astronauts.id = MedicalRecords.astronaut_id;


Question: Generate PostgreSQL SQL for: Who earned the save in the game against the Sinon Bulls when Jeriome Robertson took the loss?

CREATE TABLE table_name_32 (save VARCHAR, opponent VARCHAR, loss VARCHAR)

SELECT save FROM table_name_32 WHERE opponent = 'sinon bulls' AND loss = 'jeriome robertson';


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

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


Question: Generate PostgreSQL SQL for: What is the title of the episode number 11 of the season?

CREATE TABLE table_27833469_1 (title VARCHAR, season__number VARCHAR)

SELECT title FROM table_27833469_1 WHERE season__number = '11';


Question: Avg. ticket sales for concerts in 2022

CREATE TABLE concerts (id INT, concert_date DATE, ticket_sales INT); INSERT INTO concerts (id, concert_date, ticket_sales) VALUES (1, '2022-01-01', 5000);

SELECT AVG(ticket_sales) AS avg_ticket_sales FROM concerts WHERE YEAR(concert_date) = 2022;


Question: Find the number of sustainable seafood certifications by country.

CREATE TABLE seafood_certifications (id INT, country VARCHAR(50), certification VARCHAR(50)); INSERT INTO seafood_certifications (id, country, certification) VALUES (1, 'Norway', 'MSC'), (2, 'Norway', 'ASC'), (3, 'Canada', 'MSC');

SELECT country, COUNT(DISTINCT certification) FROM seafood_certifications GROUP BY country;


Question: How many civil cases were handled by attorneys from the 'Downtown' office location?

CREATE TABLE Attorneys (AttorneyID INT, OfficeLocation VARCHAR(255)); INSERT INTO Attorneys (AttorneyID, OfficeLocation) VALUES (1, 'Downtown'), (2, 'Uptown'), (3, 'Downtown'), (4, 'Suburbs'); CREATE TABLE Cases (CaseID INT, AttorneyID INT, CaseType VARCHAR(255)); INSERT INTO Cases (CaseID, AttorneyID, CaseType) VALUES (1, 1, 'Civil'), (2, 1, 'Criminal'), (3, 2, 'Civil'), (4, 3, 'Civil'), (5, 4, 'Criminal');

SELECT COUNT(*) FROM Cases JOIN Attorneys ON Cases.AttorneyID = Attorneys.AttorneyID WHERE OfficeLocation = 'Downtown' AND CaseType = 'Civil';


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

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


Question: What is the average valuation of companies in the renewable energy sector that have received funding from a specific investor?

CREATE TABLE valuations (id INT, company_id INT, valuation INT); INSERT INTO valuations (id, company_id, valuation) VALUES (1, 1, 10000000), (2, 2, 20000000), (3, 3, 30000000);

SELECT AVG(valuations.valuation) FROM valuations JOIN investment_rounds ON valuations.company_id = investment_rounds.company_id JOIN investors ON investment_rounds.investor_id = investors.id JOIN companies ON investment_rounds.company_id = companies.id WHERE companies.industry = 'Renewable Energy' AND investors.name = 'GreenTech Ventures';


Question: What is the total number of volunteers for each organization by year in the 'volunteers' table?

CREATE TABLE volunteers (volunteer_id INT, org_id INT, volunteer_year INT, num_volunteers INT);

SELECT org_id, volunteer_year, SUM(num_volunteers) FROM volunteers GROUP BY org_id, volunteer_year;


Question: How many exoplanets have been discovered by the Kepler Space Telescope by the end of 2022?

CREATE TABLE exoplanets(id INT, name VARCHAR(255), discovery_date DATE, discovery_method VARCHAR(255), telescope VARCHAR(255)); INSERT INTO exoplanets VALUES (1, 'Kepler-10b', '2010-01-04', 'Transit Method', 'Kepler Space Telescope'); INSERT INTO exoplanets VALUES (2, 'Kepler-11b', '2011-02-02', 'Transit Method', 'Kepler Space Telescope'); INSERT INTO exoplanets VALUES (3, 'Kepler-12b', '2011-12-20', 'Transit Method', 'Kepler Space Telescope');

SELECT COUNT(*) FROM exoplanets WHERE telescope = 'Kepler Space Telescope' AND discovery_date <= '2022-12-31';


Question: Generate PostgreSQL SQL for: Which school left in 1968 and has the team name of Panthers?

CREATE TABLE table_name_81 (school VARCHAR, team_name VARCHAR, year_left VARCHAR)

SELECT school FROM table_name_81 WHERE team_name = 'panthers' AND year_left = '1968';


Question: What's the name, AI topic, and country of AI researchers who have published more than 10 papers in the last 2 years?

CREATE TABLE ais (id INT, name VARCHAR(255), country VARCHAR(255), topic VARCHAR(255), publications INT, publication_date DATE);

SELECT ais.name, ais.topic, ais.country FROM ais INNER JOIN (SELECT id, COUNT(*) as num_publications FROM ais WHERE publication_date >= DATE_SUB(CURRENT_DATE(), INTERVAL 2 YEAR) GROUP BY id) AS recent_publications ON ais.id = recent_publications.id WHERE recent_publications.num_publications > 10;


Question: Generate PostgreSQL SQL for: The Home team of Sydney had which ground?

CREATE TABLE table_name_1 (ground VARCHAR, home_team VARCHAR)

SELECT ground FROM table_name_1 WHERE home_team = 'sydney';


Question: Generate PostgreSQL SQL for: What is dma?

CREATE TABLE table_19131921_1 (dma INTEGER)


Question: Generate PostgreSQL SQL for: Which party had an incumbent of W. Jasper Talbert?

CREATE TABLE table_name_70 (party VARCHAR, incumbent VARCHAR)

SELECT party FROM table_name_70 WHERE incumbent = 'w. jasper talbert';


Question: How many mining accidents were reported in Asia in the last 5 years?

CREATE TABLE Accidents (AccidentID INT, CompanyID INT, AccidentDate DATE); INSERT INTO Accidents (AccidentID, CompanyID, AccidentDate) VALUES (1, 1, '2020-01-01'), (2, 2, '2019-12-15'), (3, 3, '2018-05-23'), (4, 4, '2017-09-04'), (5, 1, '2016-02-10');

SELECT COUNT(*) FROM Accidents WHERE YEAR(AccidentDate) >= YEAR(CURRENT_DATE) - 5 AND Country IN ('China', 'India', 'Indonesia');


Question: Generate PostgreSQL SQL for: Sort employee names by their age in ascending order.

CREATE TABLE employee (name VARCHAR, age VARCHAR)


Question: How many unique health conditions were reported in total in Vancouver during 2019?

CREATE TABLE reports (id INT, patient_id INT, condition TEXT, city TEXT, date DATE); INSERT INTO reports (id, patient_id, condition, city, date) VALUES (1, 1, 'Flu', 'Vancouver', '2019-01-01'); INSERT INTO reports (id, patient_id, condition, city, date) VALUES (2, 2, 'Cold', 'Vancouver', '2019-02-01');

SELECT COUNT(DISTINCT condition) FROM reports WHERE city = 'Vancouver' AND date BETWEEN '2019-01-01' AND '2019-12-31';


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

select count(*) from test_multirange_gist where mr &> 'empty'::int4range;

SELECT count(*) FROM (select count(*) from test_multirange_gist where mr &> 'empty'::int4range) AS _sub;


Question: What is the average claim amount and number of claims for policyholders who are male and have a policy type of 'Auto'?

CREATE TABLE Policyholders (Id INT PRIMARY KEY, FirstName VARCHAR(50), LastName VARCHAR(50), Age INT, Gender VARCHAR(10)); CREATE TABLE Policies (Id INT PRIMARY KEY, PolicyholderId INT, PolicyType VARCHAR(50), CoverageAmount DECIMAL(10,2), FOREIGN KEY (PolicyholderId) REFERENCES Policyholders(Id)); CREATE TABLE Claims (Id INT PRIMARY KEY, PolicyId INT, ClaimAmount DECIMAL(10,2), ClaimDate DATE, FOREIGN KEY (PolicyId) REFERENCES Policies(Id));

SELECT P.Gender, PL.PolicyType, AVG(C.ClaimAmount) as AverageClaimAmount, COUNT(C.Id) as NumberOfClaims FROM Policyholders P JOIN Policies PL ON P.Id = PL.PolicyholderId JOIN Claims C ON PL.Id = C.PolicyId WHERE P.Gender = 'Male' AND PL.PolicyType = 'Auto' GROUP BY P.Gender, PL.PolicyType ORDER BY AverageClaimAmount DESC;


Question: Create a table named 'soil_moisture' with sensor_id, timestamp, and moisture

CREATE TABLE farm_sensors (sensor_id INT, timestamp TIMESTAMP, temperature INT); CREATE TABLE crop_temperature (crop_id INT, crop_type VARCHAR(50), timestamp TIMESTAMP, temperature INT);

CREATE TABLE soil_moisture (sensor_id INT, timestamp TIMESTAMP, moisture INT);


Question: Generate PostgreSQL SQL for: Show the product ids and the number of unique orders containing each product.

CREATE TABLE Order_items (product_id VARCHAR, order_id VARCHAR)

SELECT product_id, COUNT(DISTINCT order_id) FROM Order_items GROUP BY product_id;


Question: Generate PostgreSQL SQL for: what measurement does the contestant from sindelfingen have?

CREATE TABLE table_26427332_17 (measurements__in_cm_ VARCHAR, city VARCHAR)

SELECT measurements__in_cm_ FROM table_26427332_17 WHERE city = 'Sindelfingen';


Question: What is the average price of vegetarian dishes offered by restaurants in New York?

CREATE TABLE restaurants (id INT, name TEXT, city TEXT, state TEXT); INSERT INTO restaurants (id, name, city, state) VALUES (1, 'Restaurant A', 'New York', 'NY'), (2, 'Restaurant B', 'New York', 'NY'); CREATE TABLE dishes (id INT, name TEXT, price DECIMAL, restaurant_id INT, vegetarian BOOLEAN); INSERT INTO dishes (id, name, price, restaurant_id, vegetarian) VALUES (1, 'Veggie Burger', 12.50, 1, true), (2, 'Pasta Primavera', 16.00, 1, true), (3, 'Cheeseburger', 10.50, 1, false), (4, 'Fish and Chips', 15.00, 2, false);

SELECT AVG(price) FROM dishes WHERE vegetarian = true AND restaurant_id IN (SELECT id FROM restaurants WHERE city = 'New York');


Question: What is the maximum amount of funding received by a company founded by a founder from Oceania?

CREATE TABLE company (id INT, name TEXT, founding_date DATE, industry TEXT, headquarters TEXT, oceania_founder BOOLEAN); CREATE TABLE funding_rounds (id INT, company_id INT, funding_amount INT, round_type TEXT, date DATE);

SELECT MAX(funding_amount) FROM funding_rounds JOIN company ON funding_rounds.company_id = company.id WHERE oceania_founder = TRUE;


Question: Show a SQL definition from the pglogical project (node_origin_cascade, item 26).

-- Table that replicates from top level provider to mid-level pglogical node.
SELECT pglogical.replicate_ddl_command($$
	CREATE TABLE public.mid_level_tbl (
		id serial primary key,
		other integer,
		data text,
		something interval
	);
$$);

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


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

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

SELECT count(*) FROM (SELECT pg_lsn('NaN'::numeric)) AS _sub;


Question: Generate PostgreSQL SQL for: what's the party with first elected being 1926

CREATE TABLE table_1342256_6 (party VARCHAR, first_elected VARCHAR)

SELECT party FROM table_1342256_6 WHERE first_elected = '1926';


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

insert into idxpart (b, a) values ('one', 142857), ('two', 285714);

Explanation: DML from PostgreSQL core regression test for Indexing.


Question: Generate PostgreSQL SQL for: What venue did the game on september 5, 1998 take place at?

CREATE TABLE table_name_71 (venue VARCHAR, date VARCHAR)

SELECT venue FROM table_name_71 WHERE date = 'september 5, 1998';


Question: What is the maximum cargo weight for each port?

CREATE TABLE port_cargo_weight (port_id INT, port_name VARCHAR(50), cargo_weight INT); INSERT INTO port_cargo_weight VALUES (1, 'PortF', 2000), (2, 'PortF', 2200), (3, 'PortG', 2500), (4, 'PortG', 2800);

SELECT port_name, MAX(cargo_weight) FROM port_cargo_weight GROUP BY port_name;


Question: Generate PostgreSQL SQL for: When was Henry Daniel first elected?

CREATE TABLE table_2668243_8 (first_elected VARCHAR, incumbent VARCHAR)

SELECT first_elected FROM table_2668243_8 WHERE incumbent = 'Henry Daniel';


Question: What is the total number of machines in the 'machine_1' and 'machine_2' categories?

CREATE TABLE machines (id INT, name VARCHAR(50), category VARCHAR(20)); INSERT INTO machines (id, name, category) VALUES (1, 'Machine 1', 'machine_1'), (2, 'Machine 2', 'machine_2'), (3, 'Machine 3', 'machine_3');

SELECT COUNT(*) FROM machines WHERE category IN ('machine_1', 'machine_2');


Question: Generate PostgreSQL SQL for: What farm has a capacity of 70 and is operational?

CREATE TABLE table_26387382_1 (name VARCHAR, capacity__mw_ VARCHAR, status VARCHAR)

SELECT name FROM table_26387382_1 WHERE capacity__mw_ = '70' AND status = 'Operational';


Question: What is the maximum membership duration in the 'retail' sector?

CREATE TABLE union_members (member_id INT, sector VARCHAR(20), membership_duration INT); INSERT INTO union_members (member_id, sector, membership_duration) VALUES (1, 'Retail', 10), (2, 'Retail', 12), (3, 'Healthcare', 8);

SELECT MAX(membership_duration) FROM union_members WHERE sector = 'Retail';


Question: What is the total revenue from concert ticket sales for artists from the United States?

CREATE TABLE Artists (artist_id INT, artist_name TEXT, country TEXT); CREATE TABLE Concerts (concert_id INT, artist_id INT, ticket_sales_revenue FLOAT);

SELECT SUM(Concerts.ticket_sales_revenue) FROM Concerts INNER JOIN Artists ON Concerts.artist_id = Artists.artist_id WHERE Artists.country = 'United States';


Question: What is the engagement rate (likes + comments) for posts in the fashion category?

CREATE TABLE post_stats (post_id INT, category VARCHAR(50), likes INT, comments INT);  INSERT INTO post_stats (post_id, category, likes, comments) VALUES (1, 'fashion', 100, 25), (2, 'fashion', 200, 50), (3, 'beauty', 150, 75);

SELECT post_id, (likes + comments) AS engagement_rate FROM post_stats WHERE category = 'fashion';


Question: What are the names of all bioprocess engineering projects funded by venture capitalists located in the US?

CREATE TABLE bioprocess_engineering (project_name VARCHAR(255), location VARCHAR(255), funder VARCHAR(255)); INSERT INTO bioprocess_engineering (project_name, location, funder) VALUES ('ProjX', 'USA', 'Venture Capital X');

SELECT project_name FROM bioprocess_engineering WHERE location = 'USA' AND funder LIKE '%Venture Capital%';


Question: pgTAP test for Inheritance (assertion 62).

-- test isnt_ancestor_of
SELECT * FROM check_test(
    isnt_ancestor_of( 'hide', 'h_parent', 'hide', 'h_child1', 1, 'Lookie' ),
    false,
    'isnt_ancestor_of(psch, ptab, csch, ctab, 1, desc)',
    'Lookie',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Inheritance.


Question: List all timber production sites located in 'Asia' or 'Africa' regions.

CREATE TABLE timber_production (id INT, name VARCHAR(50), region VARCHAR(50)); INSERT INTO timber_production (id, name, region) VALUES (1, 'Timber Inc.', 'Asia'), (2, 'WoodCo', 'Africa'), (3, 'Forest Ltd.', 'North America');

SELECT name FROM timber_production WHERE region IN ('Asia', 'Africa');


Question: Generate PostgreSQL SQL for: Can you tell me the lowest Crowd that has the Away team of melbourne tigers?

CREATE TABLE table_name_24 (crowd INTEGER, away_team VARCHAR)

SELECT MIN(crowd) FROM table_name_24 WHERE away_team = 'melbourne tigers';


Question: Generate PostgreSQL SQL for: Which Class Pos has a Year larger than 1997, a Team of corvette racing, a Class of gt1, and 327 laps?

CREATE TABLE table_name_25 (class VARCHAR, laps VARCHAR, year VARCHAR, team VARCHAR)

SELECT class AS pos FROM table_name_25 WHERE year > 1997 AND team = 'corvette racing' AND class = 'gt1' AND laps = 327;


Question: Generate PostgreSQL SQL for: What year is the Grim Fandango with a windows platform?

CREATE TABLE table_name_36 (year VARCHAR, platform_s_ VARCHAR, game VARCHAR)

SELECT year FROM table_name_36 WHERE platform_s_ = 'windows' AND game = 'grim fandango';


Question: What is the average donation amount for each program in 2022?

CREATE TABLE Programs (ProgramID INT, ProgramName VARCHAR(50)); CREATE TABLE Donations (DonationID INT, ProgramID INT, DonationAmount DECIMAL(10, 2), DonationDate DATE); INSERT INTO Programs (ProgramID, ProgramName) VALUES (1, 'Art Education'), (2, 'Theater Production'), (3, 'Music Conservatory'); INSERT INTO Donations (DonationID, ProgramID, DonationAmount, DonationDate) VALUES (1, 1, 100, '2022-01-05'), (2, 1, 150, '2022-02-10'), (3, 2, 200, '2022-03-20');

SELECT p.ProgramName, AVG(d.DonationAmount) as AvgDonationAmount FROM Donations d INNER JOIN Programs p ON d.ProgramID = p.ProgramID WHERE d.DonationDate >= '2022-01-01' AND d.DonationDate < '2023-01-01' GROUP BY p.ProgramName;


Question: pgTAP test for Usergroup (assertion 18).

SELECT * FROM check_test(
    has_group('meanies', 'whatever'),
    true,
    'has_group(group, desc)',
    'whatever',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Usergroup.


Question: What is the total number of streams for each artist in Canada and Germany?

CREATE TABLE streams (id INT, artist VARCHAR(255), country VARCHAR(255), streams INT); INSERT INTO streams (id, artist, country, streams) VALUES (1, 'Artist1', 'Canada', 1000000), (2, 'Artist2', 'Germany', 800000), (3, 'Artist1', 'Canada', 1200000), (4, 'Artist3', 'Germany', 900000);

SELECT artist, SUM(streams) AS total_streams FROM streams WHERE country IN ('Canada', 'Germany') GROUP BY artist;


Question: Generate PostgreSQL SQL for: What is the lowest bronze a team with 9 silvers, a total larger than 13, and more than 13 gold medals has?

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

SELECT MIN(bronze) FROM table_name_58 WHERE silver = 9 AND total > 13 AND gold > 13;


Question: Generate PostgreSQL SQL for: If the position is 9th, what is the total podiums number?

CREATE TABLE table_21795846_1 (podiums VARCHAR, position VARCHAR)

SELECT COUNT(podiums) FROM table_21795846_1 WHERE position = '9th';


Question: Generate PostgreSQL SQL for: What Winning Jockey ran in the Tampa Bay Downs Track on Winning Horse Barkley Sound?

CREATE TABLE table_name_86 (winning_jockey VARCHAR, track VARCHAR, winning_horse VARCHAR)

SELECT winning_jockey FROM table_name_86 WHERE track = 'tampa bay downs' AND winning_horse = 'barkley sound';


Question: Generate PostgreSQL SQL for: What is the charity of the celebrity with the background reality star?

CREATE TABLE table_12286195_1 (charity VARCHAR, background VARCHAR)

SELECT charity FROM table_12286195_1 WHERE background = 'Reality Star';


Question: Generate PostgreSQL SQL for: What is the game number played on April 3?

CREATE TABLE table_27723526_13 (game INTEGER, date VARCHAR)

SELECT MAX(game) FROM table_27723526_13 WHERE date = 'April 3';


Question: Generate PostgreSQL SQL for: For delegate is gaines, tawanna p. tawanna gaines, please specify all the party.

CREATE TABLE table_27050336_7 (party VARCHAR, delegate VARCHAR)

SELECT party FROM table_27050336_7 WHERE delegate = 'Gaines, Tawanna P. Tawanna Gaines';


Question: What is the total number of recipients in the 'community_development' schema, grouped by gender?

CREATE TABLE community_development.recipients_grouped (recipient_gender VARCHAR(10), recipient_count INT); INSERT INTO community_development.recipients_grouped (recipient_gender, recipient_count) VALUES ('Male', 50), ('Female', 75), ('Non-binary', 10);

SELECT * FROM community_development.recipients_grouped;


Question: Find the top ten chemical reactions with the highest energy consumption.

CREATE TABLE chemical_reactions (reaction_id INT, energy_consumption FLOAT, reaction_type VARCHAR(50)); INSERT INTO chemical_reactions (reaction_id, energy_consumption, reaction_type) VALUES (1, 1000, 'synthesis'); INSERT INTO chemical_reactions (reaction_id, energy_consumption, reaction_type) VALUES (2, 1200, 'decomposition');

SELECT reaction_id, energy_consumption FROM (SELECT reaction_id, energy_consumption, RANK() OVER (ORDER BY energy_consumption DESC) as rank FROM chemical_reactions) as subquery WHERE rank <= 10;


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

UPDATE temporal_mltrng SET valid_at = datemultirange(daterange('2018-01-15', '2018-03-01'))
  WHERE id = '[1,2)' AND valid_at @> '2018-01-15'::date;

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


Question: Generate PostgreSQL SQL for: What country has a silver medal in the boxing, heavyweight event?

CREATE TABLE table_name_77 (country VARCHAR, medal VARCHAR, event VARCHAR)

SELECT country FROM table_name_77 WHERE medal = 'silver' AND event = 'boxing, heavyweight';


Question: Generate PostgreSQL SQL for: What team is from Lake Oval?

CREATE TABLE table_name_93 (home_team VARCHAR, venue VARCHAR)

SELECT home_team FROM table_name_93 WHERE venue = 'lake oval';


Question: What is the average lifespan of artists who have exhibited their works in both the 'Metropolitan Museum of Art' and the 'Tate Modern'?

CREATE TABLE Galleries (GalleryID INT PRIMARY KEY, Name VARCHAR(50), City VARCHAR(50), Country VARCHAR(50)); INSERT INTO Galleries (GalleryID, Name, City, Country) VALUES (16, 'Metropolitan Museum of Art', 'New York', 'USA'), (17, 'Tate Modern', 'London', 'UK');

SELECT AVG(DeathYear - BirthYear) FROM Artists WHERE ArtistID IN (SELECT ArtistID FROM Exhibitions WHERE GalleryID IN (16, 17) GROUP BY ArtistID HAVING COUNT(DISTINCT GalleryID) = 2);


Question: Generate PostgreSQL SQL for: display the full name (first and last), hire date, salary, and department number for those employees whose first name does not containing the letter M.

CREATE TABLE employees (first_name VARCHAR, last_name VARCHAR, hire_date VARCHAR, salary VARCHAR, department_id VARCHAR)

SELECT first_name, last_name, hire_date, salary, department_id FROM employees WHERE NOT first_name LIKE '%M%';


Question: What is the maximum CO2 emission per garment in factories located in the 'Seoul' region?

CREATE TABLE factories (id INT PRIMARY KEY, name VARCHAR(255), location VARCHAR(255), co2_emission_per_year INT);

SELECT MAX(co2_emission_per_garment) FROM (SELECT (co2_emission_per_year / quantity_manufactured) as co2_emission_per_garment FROM factories WHERE location LIKE 'Seoul%') as subquery;


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

SELECT
    t, lower(t), initcap(t), upper(t),
    length(convert_to(t, 'UTF8')) AS t_bytes,
    length(convert_to(lower(t), 'UTF8')) AS lower_t_bytes,
    length(convert_to(initcap(t), 'UTF8')) AS initcap_t_bytes,
    length(convert_to(upper(t), 'UTF8')) AS upper_t_bytes
  FROM test_pg_unicode_fast;

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

SELECT count(*) FROM (SELECT
    t, lower(t), initcap(t), upper(t),
    length(convert_to(t, 'UTF8')) AS t_bytes,
    length(convert_to(lower(t), 'UTF8')) AS lower_t_bytes,
    length(convert_to(initcap(t), 'UTF8')) AS initcap_t_bytes,
    length(convert_to(upper(t), 'UTF8')) AS upper_t_bytes
  FROM test_pg_unicode_fast) AS _sub;


Question: What is the total quantity of minerals extracted (in kg) for all mining projects in Oceania that have a reported environmental impact?

CREATE TABLE productivity (project_id INT, region TEXT, mineral TEXT, quantity INT, environmental_impact TEXT); INSERT INTO productivity (project_id, region, mineral, quantity, environmental_impact) VALUES (1, 'Oceania', 'gold', 1200, 'high'), (2, 'Oceania', 'copper', 1500, 'low');

SELECT SUM(quantity) FROM productivity WHERE region = 'Oceania' AND environmental_impact IS NOT NULL;


Question: What is the filing date of the oldest case in the 'court_cases' table?

CREATE TABLE court_cases (id INT, case_number INT, filing_date DATE, case_type VARCHAR(50), case_status VARCHAR(50)); INSERT INTO court_cases (id, case_number, filing_date, case_type, case_status) VALUES (1, 2021001, '2021-01-01', 'Civil', 'Open'), (2, 2021002, '2021-02-01', 'Criminal', 'Closed'), (3, 2021003, '2021-03-01', 'Civil', 'Open');

SELECT filing_date FROM court_cases ORDER BY filing_date LIMIT 1;


Question: Calculate the average funding for companies founded by veterans in the renewable energy industry

CREATE TABLE diversity (id INT, company_id INT, founder_veteran BOOLEAN); CREATE TABLE companies (id INT, industry VARCHAR(255), founding_date DATE); CREATE TABLE funding (company_id INT, amount INT); INSERT INTO diversity SELECT 1, 1, true; INSERT INTO diversity SELECT 2, 2, false; INSERT INTO diversity SELECT 3, 3, true; INSERT INTO companies (id, industry, founding_date) SELECT 2, 'Finance', '2012-01-01'; INSERT INTO companies (id, industry, founding_date) SELECT 3, 'Renewable Energy', '2016-01-01'; INSERT INTO companies (id, industry, founding_date) SELECT 4, 'Retail', '2021-01-01'; INSERT INTO funding (company_id, amount) SELECT 2, 1250000; INSERT INTO funding (company_id, amount) SELECT 3, 1750000; INSERT INTO funding (company_id, amount) SELECT 4, 2250000;

SELECT AVG(funding.amount) FROM funding JOIN companies ON funding.company_id = companies.id JOIN diversity ON companies.id = diversity.company_id WHERE companies.industry = 'Renewable Energy' AND diversity.founder_veteran = true;


Question: Generate PostgreSQL SQL for: What is the rank for less than 6 plays?

CREATE TABLE table_name_47 (rank INTEGER, played INTEGER)

SELECT SUM(rank) FROM table_name_47 WHERE played < 6;


Question: Generate PostgreSQL SQL for: What is the score of the game with 39,592 attendance?

CREATE TABLE table_name_19 (score VARCHAR, attendance VARCHAR)

SELECT score FROM table_name_19 WHERE attendance = '39,592';


Question: Generate PostgreSQL SQL for: What is the total population with less than 789 males?

CREATE TABLE table_name_12 (total_population VARCHAR, male INTEGER)

SELECT COUNT(total_population) FROM table_name_12 WHERE male < 789;


Question: List all companies in the 'social_impact' sector.

CREATE TABLE companies (id INT, name TEXT, sector TEXT); INSERT INTO companies (id, name, sector) VALUES (1, 'SocialCo', 'social_impact'), (2, 'ImpactInc', 'social_impact'), (3, 'ChangeOrg', 'non-profit'), (4, 'GreenCorp', 'renewable_energy');

SELECT * FROM companies WHERE sector = 'social_impact';


Question: Generate PostgreSQL SQL for: who is the opponent on november 24?

CREATE TABLE table_name_68 (opponent VARCHAR, november VARCHAR)

SELECT opponent FROM table_name_68 WHERE november = 24;


Question: Generate PostgreSQL SQL for: What is the Elector with a Faction of roman, and an Elevated with 1244, may 28?

CREATE TABLE table_name_56 (elector VARCHAR, faction VARCHAR, elevated VARCHAR)

SELECT elector FROM table_name_56 WHERE faction = 'roman' AND elevated = '1244, may 28';


Question: Generate PostgreSQL SQL for: How many tree species are in the kitechura reserve?

CREATE TABLE table_16577990_1 (tree_species VARCHAR, central_forest_reserve VARCHAR)

SELECT tree_species FROM table_16577990_1 WHERE central_forest_reserve = 'Kitechura';


Question: Count the number of diamond mines in Russia that have not had inspections in the past year.

CREATE TABLE diamond_mines (id INT, name TEXT, location TEXT, labor_disputes INT, inspections INT, violations INT); INSERT INTO diamond_mines (id, name, location, labor_disputes, inspections, violations) VALUES (1, 'Russian Diamond Mine', 'Russia', 1, 0, 0); INSERT INTO diamond_mines (id, name, location, labor_disputes, inspections, violations) VALUES (2, 'Siberian Diamond Mine', 'Russia', 0, 2, 1);

SELECT COUNT(*) FROM diamond_mines WHERE location = 'Russia' AND inspections = 0;


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

SELECT xmlserialize(DOCUMENT '<?xml version="1.0" encoding="UTF-8"?><foo><bar><val>73</val></bar></foo>' AS text INDENT);

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

SELECT count(*) FROM (SELECT xmlserialize(DOCUMENT '<?xml version="1.0" encoding="UTF-8"?><foo><bar><val>73</val></bar></foo>' AS text INDENT)) AS _sub;


Question: What is the average response time for each city, considering the previous two records in addition to the current one, ordered by date?

SELECT City, AVG(Time) OVER (PARTITION BY City ORDER BY Date ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS AvgResponseTime FROM ResponseTimes;


Question: List all companies that have not yet had an exit event

CREATE TABLE company_founding(id INT PRIMARY KEY, company_name VARCHAR(100)); CREATE TABLE exit_strategies(id INT PRIMARY KEY, company_id INT, exit_type VARCHAR(50)); INSERT INTO company_founding VALUES (1, 'Acme Inc'); INSERT INTO company_founding VALUES (2, 'Beta Corp'); INSERT INTO exit_strategies VALUES (1, 1, 'Acquisition');

SELECT cf.company_name FROM company_founding cf LEFT JOIN exit_strategies es ON cf.id = es.company_id WHERE es.company_id IS NULL;


Question: Generate PostgreSQL SQL for: What is the status of the unit with a net capacity of 1212 MW?

CREATE TABLE table_name_50 (status VARCHAR, net_capacity VARCHAR)

SELECT status FROM table_name_50 WHERE net_capacity = '1212 mw';


Question: Generate PostgreSQL SQL for: What is the latest year that has more than 5 points and a renault ef15 1.5 v6 t engine?

CREATE TABLE table_name_20 (year INTEGER, engine VARCHAR, points VARCHAR)

SELECT MAX(year) FROM table_name_20 WHERE engine = 'renault ef15 1.5 v6 t' AND points > 5;


Question: What is the average rating for nonprofits that have received donations in the last month?

CREATE TABLE donations (id INT, nonprofit_id INT, amount FLOAT, donation_date DATE); INSERT INTO donations (id, nonprofit_id, amount, donation_date) VALUES (1, 1, 500, '2022-03-15'), (2, 2, 1000, '2022-03-20'), (3, 1, 750, '2022-03-25'); CREATE TABLE nonprofit_ratings (id INT, nonprofit_id INT, rating INT); INSERT INTO nonprofit_ratings (id, nonprofit_id, rating) VALUES (1, 1, 4), (2, 1, 5), (3, 2, 3);

SELECT nonprofit_id, AVG(rating) FROM nonprofit_ratings JOIN (SELECT nonprofit_id FROM donations WHERE donation_date BETWEEN DATEADD(day, -30, GETDATE()) AND GETDATE() GROUP BY nonprofit_id) AS last_month_donors ON nonprofit_ratings.nonprofit_id = last_month_donors.nonprofit_id GROUP BY nonprofit_id;


Question: Generate PostgreSQL SQL for: On February 10, what was the location attendance?

CREATE TABLE table_name_49 (location_attendance VARCHAR, date VARCHAR)

SELECT location_attendance FROM table_name_49 WHERE date = 'february 10';


Question: Generate PostgreSQL SQL for: What is Motherwell Team's manner of departure?

CREATE TABLE table_name_57 (manner_of_departure VARCHAR, team VARCHAR)

SELECT manner_of_departure FROM table_name_57 WHERE team = 'motherwell';


Question: How many community events were held in London, including both online and offline events?

CREATE TABLE CommunityEvents (id INT, city VARCHAR(20), event_type VARCHAR(10), participation INT); INSERT INTO CommunityEvents (id, city, event_type, participation) VALUES (1, 'London', 'Online', 50), (2, 'London', 'Offline', 20), (3, 'Paris', 'Online', 30);

SELECT COUNT(*) FROM CommunityEvents WHERE city = 'London' AND event_type IN ('Online', 'Offline');


Question: Update "union_members" table where the "id" is 2

CREATE TABLE union_members (id INT, name VARCHAR(50), state VARCHAR(2), city VARCHAR(20), occupation VARCHAR(20)); INSERT INTO union_members (id, name, state, city, occupation) VALUES (1, 'John Doe', 'NY', 'New York', 'Engineer'); INSERT INTO union_members (id, name, state, city, occupation) VALUES (2, 'Jane Smith', 'CA', 'Los Angeles', 'Teacher');

UPDATE union_members SET state = 'WA', city = 'Seattle' WHERE id = 2;


Question: Generate PostgreSQL SQL for: when was the premiere when a 3.3 millions of North American watched the episode whose writer was Rob Wright?

CREATE TABLE table_21313498_1 (original_air_date VARCHAR, us_viewers__millions_ VARCHAR, written_by VARCHAR)

SELECT original_air_date FROM table_21313498_1 WHERE us_viewers__millions_ = '3.3' AND written_by = 'Rob Wright';


Question: Generate PostgreSQL SQL for: How many titles are listed with 8.44 million viewers?

CREATE TABLE table_24910733_1 (title VARCHAR, us_viewers__millions_ VARCHAR)

SELECT COUNT(title) FROM table_24910733_1 WHERE us_viewers__millions_ = '8.44';


Question: What is the total number of hospital beds in rural hospitals in Central America?

CREATE TABLE rural_hospitals_beds_2 (hospital_id INT, region VARCHAR(10), num_of_beds INT); INSERT INTO rural_hospitals_beds_2 (hospital_id, region, num_of_beds) VALUES (1, 'Central America', 150), (2, 'Middle East', 170), (3, 'Central America', 160), (4, 'Eastern Europe', 140);

SELECT SUM(num_of_beds) FROM rural_hospitals_beds_2 WHERE region = 'Central America';


Question: What is the average water usage and extraction cost for companies in the mining industry?

CREATE TABLE Water_Usage (Company VARCHAR(255), Year INT, Water_Consumption FLOAT); INSERT INTO Water_Usage (Company, Year, Water_Consumption) VALUES ('JKL Mining', 2019, 567.8), ('MNO Mining', 2020, 678.9); CREATE TABLE Mineral_Extraction (Company VARCHAR(255), Year INT, Extraction_Cost FLOAT); INSERT INTO Mineral_Extraction (Company, Year, Extraction_Cost) VALUES ('JKL Mining', 2019, 800.5), ('MNO Mining', 2020, 850.6);

SELECT W.Company, AVG(W.Water_Consumption) AS Average_Water_Usage, M.Extraction_Cost FROM Water_Usage W JOIN Mineral_Extraction M ON W.Company = M.Company WHERE W.Year = M.Year GROUP BY W.Company, M.Extraction_Cost;


Question: What is the total landfill capacity for European countries?

CREATE TABLE LandfillCapacities (country VARCHAR(50), capacity INT); INSERT INTO LandfillCapacities (country, capacity) VALUES ('Germany', 120000), ('France', 90000), ('UK', 80000);

SELECT SUM(capacity) FROM LandfillCapacities WHERE country IN ('Germany', 'France', 'UK', 'Italy', 'Spain');


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

INSERT INTO tr_sub(path) VALUES ('3-top-2-2-#1');

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


Question: Generate PostgreSQL SQL for: What is the Player with a Pick that is 6?

CREATE TABLE table_name_15 (player VARCHAR, pick VARCHAR)

SELECT player FROM table_name_15 WHERE pick = 6;


Question: What is the average citizen feedback score for each service provided in urban and rural areas?

CREATE TABLE CitizenFeedback (AreaType VARCHAR(50), Service VARCHAR(50), Score INT); INSERT INTO CitizenFeedback (AreaType, Service, Score) VALUES ('Urban', 'Waste Collection', 8), ('Urban', 'Street Lighting', 9), ('Rural', 'Water Supply', 7), ('Rural', 'Road Maintenance', 6);

SELECT AreaType, Service, AVG(Score) OVER(PARTITION BY AreaType, Service) as AvgScore FROM CitizenFeedback;


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

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

Explanation: DML from PostgreSQL core regression test for Numeric.


Question: PostgreSQL regression test 'partition_join': Write the SELECT query (example 209).

SELECT t1.a, t1.c, t2.b, t2.c FROM (SELECT * FROM prt1_l WHERE prt1_l.b = 0) t1 FULL JOIN (SELECT * FROM prt2_l WHERE prt2_l.a = 0) t2 ON (t1.a = t2.b AND t1.c = t2.c) ORDER BY t1.a, t2.b;

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

SELECT count(*) FROM (SELECT t1.a, t1.c, t2.b, t2.c FROM (SELECT * FROM prt1_l WHERE prt1_l.b = 0) t1 FULL JOIN (SELECT * FROM prt2_l WHERE prt2_l.a = 0) t2 ON (t1.a = t2.b AND t1.c = t2.c) ORDER BY t1.a, t2.b) AS _sub;


Question: What is the maximum amount of funding received by a startup with a female founder in the healthcare sector?

CREATE TABLE funding(startup_id INT, funding_amount INT); INSERT INTO funding (startup_id, funding_amount) VALUES (1, 5000000); INSERT INTO funding (startup_id, funding_amount) VALUES (2, 7000000);

SELECT MAX(funding_amount) FROM funding JOIN startups ON startups.id = funding.startup_id WHERE startups.founder_gender = 'Female' AND startups.industry = 'Healthcare';


Question: Show the policy details of policies starting with 'P' and ending with 'Y'?

CREATE TABLE Policies (PolicyID TEXT, PolicyHolder TEXT, Premium INT); INSERT INTO Policies (PolicyID, PolicyHolder, Premium) VALUES ('P123', 'John Doe', 1000); INSERT INTO Policies (PolicyID, PolicyHolder, Premium) VALUES ('Y456', 'Jane Smith', 2000);

SELECT * FROM Policies WHERE PolicyID LIKE 'P%' AND PolicyID LIKE '%Y';


Question: Generate PostgreSQL SQL for: What is the Australian equivalent to i /ɪ/?

CREATE TABLE table_name_79 (australian VARCHAR, letter VARCHAR)

SELECT australian FROM table_name_79 WHERE letter = 'i /ɪ/';


Question: Generate PostgreSQL SQL for: In rounds 7-13 what engine was featured?

CREATE TABLE table_name_58 (engine VARCHAR, rounds VARCHAR)

SELECT engine FROM table_name_58 WHERE rounds = '7-13';


Question: What is the average yield per hectare for corn in the 'rural_development' database?

CREATE TABLE crop_yield (id INT, crop VARCHAR(255), yield_per_hectare FLOAT); INSERT INTO crop_yield (id, crop, yield_per_hectare) VALUES (1, 'corn', 5.6), (2, 'wheat', 3.2);

SELECT AVG(yield_per_hectare) FROM crop_yield WHERE crop = 'corn';


Question: Generate PostgreSQL SQL for: What was the location and attendance for game 60?

CREATE TABLE table_17121262_9 (location_attendance VARCHAR, game VARCHAR)

SELECT location_attendance FROM table_17121262_9 WHERE game = 60;


Question: What is the average temperature change in each continent from 1950 to 2000?

CREATE TABLE temperature (year INT, continent TEXT, temperature FLOAT); INSERT INTO temperature (year, continent, temperature) VALUES (1950, 'Africa', 22.3), (1950, 'Asia', 23.1), (1950, 'Europe', 10.3), (1950, 'North America', 8.9), (1950, 'South America', 21.4), (1950, 'Oceania', 18.2), (2000, 'Africa', 22.7), (2000, 'Asia', 24.0), (2000, 'Europe', 10.8), (2000, 'North America', 9.5), (2000, 'South America', 21.8), (2000, 'Oceania', 18.8);

SELECT continent, AVG(temperature) FROM temperature WHERE year BETWEEN 1950 AND 2000 GROUP BY continent;


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

SELECT count(*) FROM (select 0.5678 ^ (-85)) AS _sub;


Question: Generate PostgreSQL SQL for: In what year was Lindenwood University founded?

CREATE TABLE table_10082596_1 (founded INTEGER, school VARCHAR)

SELECT MIN(founded) FROM table_10082596_1 WHERE school = 'Lindenwood University';


Question: Generate PostgreSQL SQL for: Name the realization for 'to be, to do'

CREATE TABLE table_name_71 (realization VARCHAR, gloss VARCHAR)

SELECT realization FROM table_name_71 WHERE gloss = ''to be, to do'';


Question: Generate PostgreSQL SQL for: What is the 2011 population if the headquarters is Chittorgarh?

CREATE TABLE table_2168295_1 (population__2011_ VARCHAR, headquarters VARCHAR)

SELECT population__2011_ FROM table_2168295_1 WHERE headquarters = 'Chittorgarh';


Question: PostgreSQL regression test 'stats_ext': Write the SELECT query (example 307).

SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE a IN (1, 26, 51, 76) AND b IN (''1'', ''26'') AND c = 1');

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

SELECT count(*) FROM (SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE a IN (1, 26, 51, 76) AND b IN (''1'', ''26'') AND c = 1')) AS _sub;


Question: Generate PostgreSQL SQL for: What film did abdelatif hwidar direct that was in the short film 2007 prix uip category?

CREATE TABLE table_name_93 (film VARCHAR, category VARCHAR, director_s_ VARCHAR)

SELECT film FROM table_name_93 WHERE category = 'short film 2007 prix uip' AND director_s_ = 'abdelatif hwidar';


Question: What is the name of the company with the most employees in the year 2021 in the Education industry?

CREATE TABLE company_info (id INT, name VARCHAR(50), industry VARCHAR(50), employees INT, year INT); INSERT INTO company_info (id, name, industry, employees, year) VALUES (1, 'EdTech Solutions', 'Education', 500, 2021); INSERT INTO company_info (id, name, industry, employees, year) VALUES (2, 'Green Energy Solutions', 'Environment', 200, 2021); INSERT INTO company_info (id, name, industry, employees, year) VALUES (3, 'SmartCare Inc', 'Healthcare', 300, 2021);

SELECT name FROM company_info WHERE year = 2021 AND industry = 'Education' AND employees = (SELECT MAX(employees) FROM company_info WHERE year = 2021 AND industry = 'Education');


Question: Rank nonprofits based in Washington by the number of donations received

CREATE TABLE donations (id INT PRIMARY KEY, donor_id INT, donation_amount DECIMAL(10,2), donation_date DATE, nonprofit_id INT); CREATE TABLE nonprofits (id INT PRIMARY KEY, name VARCHAR(100), city VARCHAR(50), mission VARCHAR(200)); INSERT INTO donations (id, donor_id, donation_amount, donation_date, nonprofit_id) VALUES (1, 1, 500, '2022-01-01', 1); INSERT INTO donations (id, donor_id, donation_amount, donation_date, nonprofit_id) VALUES (2, 2, 750, '2022-02-15', 2); INSERT INTO nonprofits (id, name, city, mission) VALUES (1, 'Save the Children', 'Washington', 'Improving the lives of children through better education, health care, and economic opportunities.'); INSERT INTO nonprofits (id, name, city, mission) VALUES (2, 'Greenpeace', 'San Francisco', 'Dedicated to preserving the environment and promoting peace.');

SELECT nonprofits.name, ROW_NUMBER() OVER (PARTITION BY nonprofits.city ORDER BY COUNT(donations.id) DESC) as ranking FROM nonprofits INNER JOIN donations ON nonprofits.id = donations.nonprofit_id WHERE nonprofits.city = 'Washington' GROUP BY nonprofits.name;


Question: Generate PostgreSQL SQL for: what is the average tries for the season 2008 warrington wolves with an appearance more than 7?

CREATE TABLE table_name_55 (tries INTEGER, season VARCHAR, appearance VARCHAR)

SELECT AVG(tries) FROM table_name_55 WHERE season = '2008 warrington wolves' AND appearance > 7;


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

INSERT INTO num_exp_sub VALUES (4,1,'7799461.4119');


Question: Generate PostgreSQL SQL for: What is the competition that had a win result and a score of 3-1?

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

SELECT competition FROM table_name_19 WHERE result = 'win' AND score = '3-1';


Question: What is the total waste generated by the 'Acme Chemicals' plant located in 'San Francisco'?

CREATE TABLE plants (id INT, name TEXT, city TEXT, state TEXT); INSERT INTO plants (id, name, city, state) VALUES (1, 'Acme Chemicals', 'San Francisco', 'CA'); CREATE TABLE wastes (id INT, plant_id INT, amount INT); INSERT INTO wastes (id, plant_id, amount) VALUES (1, 1, 500), (2, 1, 300), (3, 1, 700);

SELECT SUM(wastes.amount) FROM wastes JOIN plants ON wastes.plant_id = plants.id WHERE plants.name = 'Acme Chemicals' AND plants.city = 'San Francisco';


Question: Find policy types with more than one policyholder living in 'FL'.

CREATE TABLE policyholders (id INT, name TEXT, state TEXT, policy_type TEXT, premium FLOAT); INSERT INTO policyholders (id, name, state, policy_type, premium) VALUES (1, 'John Doe', 'FL', 'Auto', 1200.00), (2, 'Jane Smith', 'FL', 'Auto', 1200.00), (3, 'Jim Brown', 'CA', 'Home', 2500.00);

SELECT policy_type, COUNT(DISTINCT name) as num_policyholders FROM policyholders WHERE state = 'FL' GROUP BY policy_type HAVING num_policyholders > 1;


Question: What is the total number of cases in 'justice_cases' table, resolved through mediation?

CREATE TABLE justice_cases (id INT, case_type TEXT, resolution_method TEXT); INSERT INTO justice_cases (id, case_type, resolution_method) VALUES (1, 'Violent Crime', 'Restorative Justice'), (2, 'Property Crime', 'Mediation'), (3, 'Violent Crime', 'Mediation');

SELECT COUNT(*) FROM justice_cases WHERE resolution_method = 'Mediation';


Question: Generate PostgreSQL SQL for: What is the average length in feet of the bridges?

CREATE TABLE bridge (length_feet INTEGER)


Question: What is the average speed of vessels for each port?

CREATE TABLE port_vessels (id INT, port VARCHAR(50), vessel_id INT, name VARCHAR(50), speed DECIMAL(5,2)); INSERT INTO port_vessels VALUES (1, 'PortA', 1, 'Vessel1', 25.6), (2, 'PortA', 2, 'Vessel2', 27.3), (3, 'PortB', 3, 'Vessel3', 24.5);

SELECT port, AVG(speed) FROM port_vessels GROUP BY port;


Question: What is the maximum price of dysprosium in China in the last 3 years?

CREATE TABLE dysprosium_prices (year INT, country TEXT, price FLOAT); INSERT INTO dysprosium_prices (year, country, price) VALUES (2019, 'China', 126.3), (2020, 'China', 135.2), (2021, 'China', 142.9), (2022, 'China', 150.1);

SELECT MAX(price) FROM dysprosium_prices WHERE country = 'China' AND year >= 2019 AND year <= 2021;


Question: Calculate average donation per donor

CREATE TABLE financial_donations (id INT, donor_id INT, amount INT); INSERT INTO financial_donations VALUES (1, 1, 500)

SELECT AVG(fd.amount) / COUNT(DISTINCT fd.donor_id) AS avg_donation_per_donor FROM financial_donations fd;


Question: Generate PostgreSQL SQL for: Which Release date has a Required OS of windows, a Type of 2d, and a Developer(s) of zeonix?

CREATE TABLE table_name_59 (release_date VARCHAR, developer_s_ VARCHAR, required_os VARCHAR, type VARCHAR)

SELECT release_date FROM table_name_59 WHERE required_os = 'windows' AND type = '2d' AND developer_s_ = 'zeonix';


Question: Generate PostgreSQL SQL for: Name the title that was directed  by john terlesky

CREATE TABLE table_24222929_2 (title VARCHAR, directed_by VARCHAR)

SELECT title FROM table_24222929_2 WHERE directed_by = 'John Terlesky';


Question: What is the maximum smart city technology adoption rate in cities in the US, in the last 5 years?

CREATE TABLE city_tech (id INT, city VARCHAR(20), country VARCHAR(20), adoption_rate FLOAT, year INT); INSERT INTO city_tech (id, city, country, adoption_rate, year) VALUES (1, 'San Francisco', 'USA', 0.75, 2018), (2, 'Portland', 'USA', 0.68, 2019), (3, 'Vancouver', 'Canada', 0.55, 2020);

SELECT MAX(adoption_rate) FROM city_tech WHERE country = 'USA' AND year BETWEEN 2016 AND 2021;


Question: Generate PostgreSQL SQL for: List all countries of markets in ascending alphabetical order.

SELECT Country FROM market ORDER BY Country;


Question: What is the total cost of projects with a completion date in 2021?

CREATE TABLE Infrastructure (id INT, category VARCHAR(20), cost FLOAT, completed DATE); INSERT INTO Infrastructure (id, category, cost, completed) VALUES (1, 'Transportation', 5000000, '2020-01-01'), (2, 'WaterSupply', 3000000, '2019-01-01'), (3, 'Transportation', 7000000, '2021-01-01');

SELECT SUM(cost) FROM Infrastructure WHERE YEAR(completed) = 2021;


Question: What is the total sales revenue for a given region in a given year?

SELECT SUM(sale_price) FROM sales WHERE sale_date BETWEEN '2022-01-01' AND '2022-12-31' AND region = 'Europe';


Question: Generate PostgreSQL SQL for: What is the value in 2012 if it is 2R in 2013, 1R in 2005, and 1R in 2008?

SELECT 2012 FROM table_name_84 WHERE 2013 = '2r' AND 2005 = '1r' AND 2008 = '1r';


Question: How many volunteers engaged in each program, having more than 20 participants?

CREATE TABLE Volunteers (id INT, volunteer_name TEXT, program TEXT, participation_date DATE); INSERT INTO Volunteers (id, volunteer_name, program, participation_date) VALUES (1, 'Alice', 'Feed the Hungry', '2022-01-01'), (2, 'Bob', 'Tutor Kids', '2022-01-02');

SELECT program, COUNT(*) FROM Volunteers GROUP BY program HAVING COUNT(*) > 20;


Question: What is the population size of 'Birds' species in 'Habitat 5'?

CREATE TABLE Habitat5(animal_id INT, species VARCHAR(20), population INT, habitat VARCHAR(20)); INSERT INTO Habitat5 VALUES (1, 'Eagle', 50, 'Habitat5'), (2, 'Hawk', 60, 'Habitat5'), (3, 'Osprey', 70, 'Habitat5');

SELECT SUM(population) FROM Habitat5 WHERE species IN (SELECT species FROM AnimalData3 WHERE order_class = 'Birds') AND habitat = 'Habitat5';


Question: Generate PostgreSQL SQL for: Who had the high assists on the date December 12?

CREATE TABLE table_11960944_4 (high_assists VARCHAR, date VARCHAR)

SELECT high_assists FROM table_11960944_4 WHERE date = 'December 12';


Question: What is the average rating of games released in the past year, grouped by genre and platform?

CREATE TABLE games (id INT, title VARCHAR(50), release_date DATE, rating INT, genre VARCHAR(20), platform VARCHAR(20));

SELECT g.genre, g.platform, AVG(g.rating) FROM games g WHERE g.release_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR) GROUP BY g.genre, g.platform;


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

$$;

CALL ptest7(least('a', 'b'), 'a');

-- empty body
CREATE PROCEDURE ptest8(x text)
BEGIN ATOMIC
END;

\df ptest8
SELECT pg_get_functiondef('ptest8'::regproc);
CALL ptest8('');

-- OUT parameters

CREATE PROCEDURE ptest9(OUT a int)
LANGUAGE SQL
AS $$
INSERT INTO cp_test VALUES (1, 'a');

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


Question: What is the total cargo weight transported by vessels from India to Australia in the last year, excluding liquefied gas carriers?

CREATE TABLE Ports (id INT, name VARCHAR(50), country VARCHAR(50)); CREATE TABLE CargoTransports (id INT, vessel_id INT, weight INT, transport_time TIMESTAMP, source_port_id INT, destination_port_id INT);

SELECT SUM(weight) FROM CargoTransports WHERE transport_time > NOW() - INTERVAL '1 year' AND source_port_id IN (SELECT id FROM Ports WHERE country = 'India') AND destination_port_id IN (SELECT id FROM Ports WHERE country = 'Australia') AND (SELECT vessel_type FROM Vessels WHERE id = CargoTransports.vessel_id) != 'Liquefied Gas Carrier';


Question: Generate PostgreSQL SQL for: What Constructor has 56 Laps?

CREATE TABLE table_name_13 (constructor VARCHAR, laps VARCHAR)

SELECT constructor FROM table_name_13 WHERE laps = 56;


Question: Generate PostgreSQL SQL for: What is the total when gold is 1, and rank is more than 4, and bronze is 0?

CREATE TABLE table_name_1 (total VARCHAR, bronze VARCHAR, gold VARCHAR, rank VARCHAR)

SELECT COUNT(total) FROM table_name_1 WHERE gold = 1 AND rank > 4 AND bronze = 0;


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

/* contrib/dblink/dblink--1.0--1.1.sql */

-- complain if script is sourced in psql, rather than via ALTER EXTENSION
\echo Use "ALTER EXTENSION dblink UPDATE TO '1.1'" to load this file. \quit

CREATE FUNCTION dblink_fdw_validator(
    options text[],
    catalog oid
)
RETURNS void
AS 'MODULE_PATHNAME', 'dblink_fdw_validator'
LANGUAGE C STRICT;

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


Question: What is the total number of Shariah-compliant finance accounts in all regions?

CREATE TABLE all_regions (region VARCHAR(20), account_type VARCHAR(30)); INSERT INTO all_regions (region, account_type) VALUES ('Northeast', 'Shariah-compliant Finance'), ('Northeast', 'Traditional Finance'), ('Southeast', 'Shariah-compliant Finance'), ('Southeast', 'Traditional Finance'), ('Midwest', 'Shariah-compliant Finance'), ('Midwest', 'Traditional Finance'), ('Western', 'Shariah-compliant Finance'), ('Western', 'Traditional Finance');

SELECT COUNT(*) FROM all_regions WHERE account_type = 'Shariah-compliant Finance';


Question: Find the total revenue and average sustainability rating for each city with restaurants.

CREATE TABLE Restaurants (RestaurantID int, RestaurantName varchar(50), City varchar(50), AnnualRevenue numeric(10, 2)); INSERT INTO Restaurants (RestaurantID, RestaurantName, City, AnnualRevenue) VALUES (1, 'The Green Garden', 'San Francisco', 50000); INSERT INTO Restaurants (RestaurantID, RestaurantName, City, AnnualRevenue) VALUES (2, 'Healthy Bites', 'Los Angeles', 70000); CREATE TABLE MenuItems (MenuItemID int, RestaurantID int, MenuItemName varchar(50), SaleAmount numeric(10, 2), SustainabilityRating int); INSERT INTO MenuItems (MenuItemID, RestaurantID, MenuItemName, SaleAmount, SustainabilityRating) VALUES (1, 1, 'Quinoa Salad', 2000, 5); INSERT INTO MenuItems (MenuItemID, RestaurantID, MenuItemName, SaleAmount, SustainabilityRating) VALUES (2, 1, 'Chickpea Curry', 3000, 4); INSERT INTO MenuItems (MenuItemID, RestaurantID, MenuItemName, SaleAmount, SustainabilityRating) VALUES (3, 2, 'Tofu Stir Fry', 4000, 5); INSERT INTO MenuItems (MenuItemID, RestaurantID, MenuItemName, SaleAmount, SustainabilityRating) VALUES (4, 2, 'Vegetable Sushi', 1000, 3);

SELECT R.City, SUM(M.SaleAmount) AS TotalRevenue, AVG(M.SustainabilityRating) AS AvgSustainabilityRating FROM Restaurants R JOIN MenuItems M ON R.RestaurantID = M.RestaurantID GROUP BY R.City;


Question: How many carbon offset initiatives have been launched by the city government of Paris in the last 2 years?

CREATE TABLE carbon_offset_initiatives (initiative_id INT, initiative_name VARCHAR(100), launch_date DATE, city VARCHAR(100)); INSERT INTO carbon_offset_initiatives (initiative_id, initiative_name, launch_date, city) VALUES (1, 'Tree Planting', '2022-01-01', 'Paris'), (2, 'Bicycle Sharing Expansion', '2021-07-01', 'Paris');

SELECT COUNT(*) FROM carbon_offset_initiatives WHERE city = 'Paris' AND launch_date >= DATE_SUB(CURRENT_DATE, INTERVAL 2 YEAR);


Question: Generate PostgreSQL SQL for: Show the distinct apartment numbers of the apartments that have bookings with status code "Confirmed".

CREATE TABLE Apartments (apt_number VARCHAR, apt_id VARCHAR); CREATE TABLE Apartment_Bookings (apt_id VARCHAR, booking_status_code VARCHAR)

SELECT DISTINCT T2.apt_number FROM Apartment_Bookings AS T1 JOIN Apartments AS T2 ON T1.apt_id = T2.apt_id WHERE T1.booking_status_code = 'Confirmed';


Question: Generate PostgreSQL SQL for: What was the result of the Competition of friendly?

CREATE TABLE table_name_61 (result VARCHAR, competition VARCHAR)

SELECT result FROM table_name_61 WHERE competition = 'friendly';


Question: What is the daily sales trend for each product category in the last month?

CREATE TABLE Product (id INT, name VARCHAR(255), category VARCHAR(255), revenue FLOAT, sale_date DATE);

SELECT category, sale_date, SUM(revenue) as daily_sales FROM Product WHERE sale_date >= (CURRENT_DATE - INTERVAL '1 month') GROUP BY ROLLUP(category, sale_date) ORDER BY category, sale_date DESC;


Question: What is the maximum permit issuance fee for projects in the Southeast?

CREATE TABLE Permits (id INT, region VARCHAR(255), issuance_fee FLOAT); INSERT INTO Permits (id, region, issuance_fee) VALUES (1, 'Southeast', 500.0), (2, 'Northwest', 700.0), (3, 'Southeast', 600.0);

SELECT MAX(issuance_fee) FROM Permits WHERE region = 'Southeast';


Question: What is the average budget of transportation projects in African nations that have been completed?

CREATE TABLE transportation_projects (id INT, project_budget INT, project_status TEXT, country TEXT); INSERT INTO transportation_projects (id, project_budget, project_status, country) VALUES (1, 50000, 'completed', 'Nigeria'), (2, 75000, 'in_progress', 'Kenya'), (3, 30000, 'completed', 'Egypt');

SELECT AVG(project_budget) FROM transportation_projects WHERE project_status = 'completed' AND country IN ('Africa');


Question: Generate PostgreSQL SQL for: Who was the 2007 actor from Moscow for the voyage of Varenka Bakunin?

CREATE TABLE table_name_91 (actor_in_moscow VARCHAR, _2007 VARCHAR, voyage VARCHAR)

SELECT actor_in_moscow, _2007 FROM table_name_91 WHERE voyage = 'varenka bakunin';


Question: Generate PostgreSQL SQL for: Who won the runner-up in 1999?

CREATE TABLE table_name_26 (runner_up VARCHAR, year VARCHAR)

SELECT runner_up FROM table_name_26 WHERE year = 1999;


Question: Generate PostgreSQL SQL for: What is the snatch for the Clean & jerk of 145.0, and a Bodyweight larger than 76.22?

CREATE TABLE table_name_50 (snatch INTEGER, bodyweight VARCHAR, clean_ VARCHAR, _jerk VARCHAR)

SELECT AVG(snatch) FROM table_name_50 WHERE clean_ & _jerk = '145.0' AND bodyweight > 76.22;


Question: Generate PostgreSQL SQL for: If a radius is 10, what  is the lowest possible mass?

CREATE TABLE table_10432351_1 (mass__m___ INTEGER, radius__r___ VARCHAR)

SELECT MIN(mass__m___) FROM table_10432351_1 WHERE radius__r___ = 10;