Question: What is the name and gene sequence of patients with illness 'Flu'?

CREATE TABLE patients (id INT PRIMARY KEY, name VARCHAR(255), age INT, gender VARCHAR(10), illness VARCHAR(255)); INSERT INTO patients (id, name, age, gender, illness) VALUES (1, 'Jane Smith', 28, 'Female', 'Flu');

SELECT patients.name, patients.illness FROM patients WHERE patients.illness = 'Flu';


Question: What is the total number of community engagement events in Oceania with more than 500 participants?

CREATE TABLE CommunityEngagement (id INT, name TEXT, region TEXT, participants INT); INSERT INTO CommunityEngagement (id, name, region, participants) VALUES (1, 'Festival 1', 'Oceania', 600), (2, 'Festival 2', 'Oceania', 400), (3, 'Festival 3', 'Europe', 800);

SELECT SUM(*) FROM CommunityEngagement WHERE region = 'Oceania' AND participants > 500;


Question: Update the membership count for the 'United Auto Workers' union in the 'Transportation' industry in New York.

CREATE TABLE unions (id INT, name TEXT, industry TEXT, state TEXT, membership_count INT); INSERT INTO unions (id, name, industry, state, membership_count) VALUES (1, 'United Auto Workers', 'Transportation', 'New York', 5000);

UPDATE unions SET membership_count = 5500 WHERE name = 'United Auto Workers' AND industry = 'Transportation' AND state = 'New York';


Question: Generate PostgreSQL SQL for: How many placed 4th on April 25?

CREATE TABLE table_19317584_2 (date VARCHAR)

SELECT COUNT(4 AS th_placed) FROM table_19317584_2 WHERE date = 'April 25';


Question: Which landfills have reached 75% of their capacity or more?

CREATE TABLE Landfills (LandfillID INT, Capacity INT, Location VARCHAR(50));CREATE TABLE WasteGenerators (GeneratorID INT, WasteType VARCHAR(20), GeneratedTonnes DECIMAL(5,2), LandfillID INT);CREATE VIEW FilledLandfills AS SELECT L.Location, SUM(WG.GeneratedTonnes) AS TotalTonnes FROM Landfills L INNER JOIN WasteGenerators WG ON L.LandfillID = WG.LandfillID GROUP BY L.Location;

SELECT L.Location, (SUM(WG.GeneratedTonnes) / L.Capacity) * 100 AS PercentageFilled FROM FilledLandfills F INNER JOIN Landfills L ON F.Location = L.Location GROUP BY F.Location HAVING PercentageFilled >= 75;


Question: What is the average calorie count for gluten-free meals in Japan?

CREATE TABLE Meals(id INT, name TEXT, calories INT, is_gluten_free BOOLEAN, country TEXT); INSERT INTO Meals(id, name, calories, is_gluten_free, country) VALUES (1, 'Sashimi Salad', 300, TRUE, 'Japan'), (2, 'Rice Bowl', 450, FALSE, 'Japan');

SELECT AVG(calories) FROM Meals WHERE is_gluten_free = TRUE AND country = 'Japan';


Question: Show organizations that provided training in 2023

CREATE TABLE cultural_competency_training (id INT PRIMARY KEY, organization_name VARCHAR(50), training_title TEXT, training_date DATE);

SELECT DISTINCT organization_name FROM cultural_competency_training WHERE training_date >= '2023-01-01';


Question: Generate PostgreSQL SQL for: What is the score of  Tommy Bolt

CREATE TABLE table_name_23 (score INTEGER, player VARCHAR)

SELECT MIN(score) FROM table_name_23 WHERE player = 'tommy bolt';


Question: Generate PostgreSQL SQL for: What is the score when the player is Matt Kuchar?

CREATE TABLE table_28498999_5 (score VARCHAR, player VARCHAR)

SELECT score FROM table_28498999_5 WHERE player = 'Matt Kuchar';


Question: Show the change in ocean pH levels for the Mariana Trench over time, with weekly intervals.

CREATE TABLE OCEAN_PH (LOCATION VARCHAR(20), MEASUREMENT_DATE DATE, PH FLOAT); INSERT INTO OCEAN_PH (LOCATION, MEASUREMENT_DATE, PH) VALUES ('Mariana Trench', '2022-01-01', 7.8), ('Mariana Trench', '2022-01-07', 7.7), ('Mariana Trench', '2022-01-14', 7.6), ('Mariana Trench', '2022-01-21', 7.5), ('Mariana Trench', '2022-01-28', 7.4);

SELECT LOCATION, MEASUREMENT_DATE, PH, LEAD(PH, 1) OVER (PARTITION BY LOCATION ORDER BY MEASUREMENT_DATE) AS NEXT_PH FROM OCEAN_PH WHERE LOCATION = 'Mariana Trench' ORDER BY MEASUREMENT_DATE;


Question: Generate PostgreSQL SQL for: Name the audition city for hyatt regency chicago

CREATE TABLE table_22897967_1 (audition_city VARCHAR, callback_venue VARCHAR)

SELECT audition_city FROM table_22897967_1 WHERE callback_venue = 'Hyatt Regency Chicago';


Question: Generate PostgreSQL SQL for: In italy, when the stolen ends were 10 and blank ends were under 14, what's the lowest ends won?

CREATE TABLE table_name_45 (ends_won INTEGER, blank_ends VARCHAR, stolen_ends VARCHAR, locale VARCHAR)

SELECT MIN(ends_won) FROM table_name_45 WHERE stolen_ends = 10 AND locale = 'italy' AND blank_ends < 14;


Question: Write the DML statement from PostgreSQL regression test 'inet' (example 6).

Explanation: DML from PostgreSQL core regression test for Inet.


Question: What was the total weight of cannabis sold in Oregon in the first quarter of 2021?

CREATE TABLE sales (id INT, state VARCHAR(20), weight DECIMAL(10,2), month INT, year INT);

SELECT SUM(weight) FROM sales WHERE state = 'Oregon' AND month BETWEEN 1 AND 3 AND year = 2021;


Question: List all companies that received funding over $10M in the last 3 years

CREATE TABLE funding (id INT, company_name VARCHAR(30), funding_amount DECIMAL(10,2), funding_date DATE); INSERT INTO funding (id, company_name, funding_amount, funding_date) VALUES (1, 'CompanyA', 5000000.00, '2020-01-01'); INSERT INTO funding (id, company_name, funding_amount, funding_date) VALUES (2, 'CompanyB', 20000000.00, '2019-06-15');

SELECT company_name FROM funding WHERE funding_amount > 10000000 AND funding_date >= DATE_SUB(CURDATE(), INTERVAL 3 YEAR);


Question: Generate PostgreSQL SQL for: What is the date of the Paul Revere 250 race in the Daytona International Speedway circuit?

CREATE TABLE table_name_66 (date VARCHAR, circuit VARCHAR, race VARCHAR)

SELECT date FROM table_name_66 WHERE circuit = 'daytona international speedway' AND race = 'paul revere 250';


Question: pgTAP test for Functap (assertion 304).

-- is_window( NAME, NAME[] )
-- isnt_window( NAME, NAME[] )
SELECT * FROM check_test(
    is_window( 'ntile', ARRAY['int'] ),
    true,
    'is_window(win, arg, desc)',
    'Function ntile(int) should be a window function',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Functap.


Question: Insert environmental impact data for hydrogen peroxide

CREATE TABLE environmental_impact (chemical_name VARCHAR(255), impact_description TEXT);

INSERT INTO environmental_impact (chemical_name, impact_description) VALUES ('hydrogen peroxide', 'Low environmental impact due to its rapid decomposition into water and oxygen.');


Question: Generate PostgreSQL SQL for: What is the sum of Pick #, when Position is Guard, and when Round is greater than 2?

CREATE TABLE table_name_36 (pick__number INTEGER, position VARCHAR, round VARCHAR)

SELECT SUM(pick__number) FROM table_name_36 WHERE position = 'guard' AND round > 2;


Question: PostgreSQL regression test 'domain': Write the SELECT query (example 367).

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

SELECT count(*) FROM (select null::inotnull) AS _sub;


Question: Generate PostgreSQL SQL for: What is the total appearances when the total goals is 289?

CREATE TABLE table_29701419_2 (total_appearances INTEGER, total_goals VARCHAR)

SELECT MIN(total_appearances) FROM table_29701419_2 WHERE total_goals = 289;


Question: Generate PostgreSQL SQL for: List the final tables made and the best finishes of poker players.

CREATE TABLE poker_player (Final_Table_Made VARCHAR, Best_Finish VARCHAR)

SELECT Final_Table_Made, Best_Finish FROM poker_player;


Question: How many compliance violations occurred in the last year in the Atlantic region?

CREATE TABLE compliance_violations (id INT, violation_name VARCHAR(255), violation_date DATE, region VARCHAR(255));

SELECT region, count(*) FROM compliance_violations WHERE violation_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR) AND region = 'Atlantic' GROUP BY region;


Question: Generate PostgreSQL SQL for: How many districts have W. Arthur Winstead as elected official?

CREATE TABLE table_1341930_24 (district VARCHAR, incumbent VARCHAR)

SELECT COUNT(district) FROM table_1341930_24 WHERE incumbent = 'W. Arthur Winstead';


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

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

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


Question: Who is the top scorer among players from Canada in the 2019 season?

CREATE TABLE players (player_id INT, name TEXT, nationality TEXT, points INT, season INT); INSERT INTO players (player_id, name, nationality, points, season) VALUES (1, 'Alice Johnson', 'Canada', 700, 2019), (2, 'Bob Williams', 'Canada', 600, 2019);

SELECT name, MAX(points) FROM players WHERE nationality = 'Canada' AND season = 2019;


Question: pgTAP test for Hastap (assertion 218).

SELECT * FROM check_test(
  hasnt_leftop( 'pg_catalog', '+', 'text', 'bigint'::name ),
  true,
  'hasnt_leftop( schema, name, right, result )',
  'Left operator pg_catalog.+(NONE,text) RETURNS bigint should not exist',
  ''
);

Explanation: SQL assertion from pgTAP test suite for Hastap.


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

CREATE FUNCTION gbt_float4_distance(internal,float4,int2,oid,internal)
RETURNS float8
AS 'MODULE_PATHNAME'
LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;

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


Question: List the names of African countries with more than 5 rural hospitals.

CREATE TABLE hospitals (hospital_id INT, country VARCHAR(20), num_beds INT); INSERT INTO hospitals (hospital_id, country, num_beds) VALUES (1, 'Kenya', 50), (2, 'Tanzania', 75), (3, 'Uganda', 60);

SELECT country FROM hospitals WHERE country IN ('Kenya', 'Tanzania', 'Uganda') GROUP BY country HAVING COUNT(*) > 5;


Question: Identify the EIA reports that have been reviewed and approved, and list the corresponding mine names and report_ids.

CREATE TABLE eia_reports (report_id INT, mine_id INT, report_status TEXT); INSERT INTO eia_reports (report_id, mine_id, report_status) VALUES (1, 1, 'In Progress'), (2, 2, 'Completed'), (3, 3, 'Approved'), (4, 4, 'Rejected'); CREATE TABLE mines (mine_id INT, mine_name TEXT); INSERT INTO mines (mine_id, mine_name) VALUES (1, 'MineA'), (2, 'MineB'), (3, 'MineC'), (4, 'MineD');

SELECT e.report_id, m.mine_name FROM eia_reports e JOIN mines m ON e.mine_id = m.mine_id WHERE e.report_status = 'Approved';


Question: Generate PostgreSQL SQL for: How many nicknames were associated with Milton, Massachusetts?

CREATE TABLE table_1973729_1 (nickname VARCHAR, location VARCHAR)

SELECT COUNT(nickname) FROM table_1973729_1 WHERE location = 'Milton, Massachusetts';


Question: Generate PostgreSQL SQL for: What monarch(s) did Stanley Baldwin (1st ministry) serve?

CREATE TABLE table_name_18 (monarchs_served VARCHAR, name VARCHAR)

SELECT monarchs_served FROM table_name_18 WHERE name = 'stanley baldwin (1st ministry)';


Question: List all circular economy initiatives in 'Asia' from the 'circular_economy_initiatives' table

CREATE TABLE circular_economy_initiatives (id INT, region VARCHAR(50), initiative VARCHAR(100));

SELECT initiative FROM circular_economy_initiatives WHERE region = 'Asia';


Question: Generate PostgreSQL SQL for: Which captain's manager is Joe Royle?

CREATE TABLE table_name_49 (captain VARCHAR, manager VARCHAR)

SELECT captain FROM table_name_49 WHERE manager = 'joe royle';


Question: Generate PostgreSQL SQL for: Which captain has howard wilkinson as the manager?

CREATE TABLE table_name_52 (captain VARCHAR, manager VARCHAR)

SELECT captain FROM table_name_52 WHERE manager = 'howard wilkinson';


Question: Write the DDL statement from PostgreSQL regression test 'object_address' (example 15).

CREATE VIEW addr_nsp.genview AS SELECT * from addr_nsp.gentable;

Explanation: DDL from PostgreSQL core regression test for Object Address.


Question: What is the total revenue for each cuisine type, excluding the Italian cuisine?

CREATE TABLE restaurants (id INT, name TEXT, cuisine TEXT, revenue INT); INSERT INTO restaurants (id, name, cuisine, revenue) VALUES (1, 'Restaurant A', 'Italian', 5000), (2, 'Restaurant B', 'Mexican', 6000), (3, 'Restaurant C', 'Italian', 7000);

SELECT cuisine, SUM(revenue) FROM restaurants WHERE cuisine != 'Italian' GROUP BY cuisine;


Question: Generate PostgreSQL SQL for: What are the first name and last name of Linda Smith's advisor?

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

SELECT T1.fname, T1.lname FROM Faculty AS T1 JOIN Student AS T2 ON T1.FacID = T2.advisor WHERE T2.fname = 'Linda' AND T2.lname = 'Smith';


Question: How many artists have released albums in the last 3 years, grouped by genre?

CREATE TABLE AlbumReleases (id INT, year INT, genre VARCHAR(50));

SELECT genre, COUNT(*) FROM AlbumReleases WHERE year BETWEEN (SELECT MAX(year) FROM AlbumReleases) - 2 AND (SELECT MAX(year) FROM AlbumReleases) GROUP BY genre;


Question: Delete a volunteer's record, given their ID

CREATE TABLE Volunteers (id INT, first_name VARCHAR, last_name VARCHAR, email VARCHAR, phone_number VARCHAR, date_joined DATE); INSERT INTO Volunteers (id, first_name, last_name, email, phone_number, date_joined) VALUES (1, 'John', 'Doe', 'john.doe@email.com', '555-123-4567', '2021-05-01'), (2, 'Jane', 'Doe', 'jane.doe@email.com', '555-987-6543', '2021-06-01');


Question: What is the average CO2 emissions of products in each category?

CREATE TABLE products (product_id int, product_category varchar(50), co2_emissions decimal(5,2));

SELECT product_category, AVG(co2_emissions) as avg_co2_emissions FROM products GROUP BY product_category;


Question: Generate PostgreSQL SQL for: What is Beyer Peacock's SR number with a SECR number of 769?

CREATE TABLE table_name_10 (sr_no INTEGER, builder VARCHAR, secr_no VARCHAR)

SELECT AVG(sr_no) FROM table_name_10 WHERE builder = 'beyer peacock' AND secr_no = 769;


Question: Generate PostgreSQL SQL for: What was the name of the project that peaked at 40 and was in the USA?

CREATE TABLE table_name_38 (project_name VARCHAR, peak VARCHAR, country VARCHAR)

SELECT project_name FROM table_name_38 WHERE peak = '40' AND country = 'usa';


Question: Generate PostgreSQL SQL for: Date of 7 september 1996 includes which highest rank athlete?

CREATE TABLE table_name_68 (rank INTEGER, date VARCHAR)

SELECT MAX(rank) FROM table_name_68 WHERE date = '7 september 1996';


Question: update the ticket sales records for a specific game

CREATE TABLE ticket_sales (id INT PRIMARY KEY, game_id INT, number_of_tickets INT, date DATE);

UPDATE ticket_sales SET number_of_tickets = 600 WHERE game_id = 123 AND date = '2022-05-01';


Question: Write the DML statement from PostgreSQL regression test 'insert_conflict' (example 201).

insert into selfconflict values (8,1), (8,2) on conflict(f1) do select returning *;

Explanation: DML from PostgreSQL core regression test for Insert Conflict.


Question: What is the average CO2 emissions in the transportation sector in Germany from 2018 to 2020?

CREATE TABLE co2_emissions_germany (sector VARCHAR(255), year INT, co2_emissions INT); INSERT INTO co2_emissions_germany VALUES ('Transportation', 2018, 800), ('Transportation', 2018, 850), ('Transportation', 2019, 820), ('Transportation', 2019, 870), ('Transportation', 2020, 780), ('Transportation', 2020, 830);

SELECT AVG(co2_emissions) FROM co2_emissions_germany WHERE sector = 'Transportation' AND year BETWEEN 2018 AND 2020;


Question: What is the total quantity of items in warehouses located in 'NJ' and 'MX'?

CREATE TABLE warehouses (id INT, location VARCHAR(10), item VARCHAR(10), quantity INT); INSERT INTO warehouses (id, location, item, quantity) VALUES (1, 'NY', 'A101', 200), (2, 'NJ', 'A101', 300), (3, 'CA', 'B203', 150), (4, 'NY', 'C304', 50), (5, 'MX', 'B203', 250);

SELECT SUM(quantity) FROM warehouses WHERE location IN ('NJ', 'MX');


Question: Generate PostgreSQL SQL for: Which Year(s) won has a Total of 147?

CREATE TABLE table_name_57 (year_s__won VARCHAR, total VARCHAR)

SELECT year_s__won FROM table_name_57 WHERE total = 147;


Question: Generate PostgreSQL SQL for: What is the coverage area of muzik fm station, which has a music genre?

CREATE TABLE table_name_65 (coverage_area VARCHAR, genre VARCHAR, station VARCHAR)

SELECT coverage_area FROM table_name_65 WHERE genre = 'music' AND station = 'muzik fm';


Question: Generate PostgreSQL SQL for: What round was adelaide united the opposition with an attendance of 18,345?

CREATE TABLE table_name_32 (round VARCHAR, opposition VARCHAR, attendance VARCHAR)

SELECT round FROM table_name_32 WHERE opposition = 'adelaide united' AND attendance = '18,345';


Question: Generate PostgreSQL SQL for: What was the result for 10/04/1947?

CREATE TABLE table_name_75 (result VARCHAR, date VARCHAR)

SELECT result FROM table_name_75 WHERE date = '10/04/1947';


Question: Generate PostgreSQL SQL for: How many airlines have the star alliance and are in brazil?

CREATE TABLE table_name_13 (rank VARCHAR, alliance VARCHAR, country VARCHAR)

SELECT COUNT(rank) FROM table_name_13 WHERE alliance = 'star alliance' AND country = 'brazil';


Question: Generate PostgreSQL SQL for: Which Visitor is listed as having a Date of December 17?

CREATE TABLE table_name_13 (visitor VARCHAR, date VARCHAR)

SELECT visitor FROM table_name_13 WHERE date = 'december 17';


Question: Generate PostgreSQL SQL for: What is the average attendance for the date of april 4?

CREATE TABLE table_name_23 (attendance INTEGER, date VARCHAR)

SELECT AVG(attendance) FROM table_name_23 WHERE date = 'april 4';


Question: pgTAP test for Hastap (assertion 260).

SELECT * FROM check_test(
    domain_type_is( 'public', 'integer', 'int', 'whatever'),
    false,
    'domain_type_is(schema, type, type, desc) fail',
    'whatever',
    '   Domain public.integer does not exist'
);


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

CREATE OPERATOR <=> (
	LEFTARG = cube, RIGHTARG = cube, PROCEDURE = distance_chebyshev,
	COMMUTATOR = '<=>'
);


Question: What are the circular economy initiatives by city and their start dates?

CREATE TABLE circular_economy (city VARCHAR(255), initiative VARCHAR(255), start_date DATE); INSERT INTO circular_economy (city, initiative, start_date) VALUES ('CityA', 'Composting', '2018-05-01'), ('CityA', 'Recycling', '2017-12-01'), ('CityB', 'Plastic Reduction', '2019-08-01'), ('CityB', 'E-waste Collection', '2018-09-01');

SELECT city, initiative, start_date FROM circular_economy;


Question: What is the average age of all cheetahs in the 'animal_population' table?

CREATE TABLE animal_population (animal_id INT, animal_type VARCHAR(10), age INT); INSERT INTO animal_population (animal_id, animal_type, age) VALUES (1, 'cheetah', 8); INSERT INTO animal_population (animal_id, animal_type, age) VALUES (2, 'cheetah', 6);

SELECT AVG(age) FROM animal_population WHERE animal_type = 'cheetah';


Question: Generate PostgreSQL SQL for: Which result featured the Indianapolis Colts as opponents?

CREATE TABLE table_name_72 (result VARCHAR, opponent VARCHAR)

SELECT result FROM table_name_72 WHERE opponent = 'indianapolis colts';


Question: Generate PostgreSQL SQL for: Which Tournament in 2010 also has Grand Slam tournaments in 2011

SELECT 2010 FROM table_name_74 WHERE 2011 = 'grand slam tournaments';


Question: Identify the number of rural hospitals in each state with more than 50 employees.

CREATE TABLE hospitals (id INT, name TEXT, state TEXT, num_employees INT);

SELECT state, COUNT(*) FROM hospitals WHERE num_employees > 50 GROUP BY state;


Question: Generate PostgreSQL SQL for: Which province has an elevation of 4550?

CREATE TABLE table_2251578_4 (province VARCHAR, elevation__m_ VARCHAR)

SELECT province FROM table_2251578_4 WHERE elevation__m_ = 4550;


Question: PostgreSQL regression test 'tsearch': Write the SELECT query (example 198).

SELECT * from ts_debug('english', '5aew.werc.ewr:8100/?xx');

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

SELECT count(*) FROM (SELECT * from ts_debug('english', '5aew.werc.ewr:8100/?xx')) AS _sub;


Question: Generate PostgreSQL SQL for: what's the result with candidates being billy tauzin (d) unopposed

CREATE TABLE table_1341586_19 (result VARCHAR, candidates VARCHAR)

SELECT result FROM table_1341586_19 WHERE candidates = 'Billy Tauzin (D) Unopposed';


Question: Generate PostgreSQL SQL for: Name the telephone 052 for area km2  being 5.42

CREATE TABLE table_14465924_1 (telephone__052_ VARCHAR, area__km_2__ VARCHAR)

SELECT telephone__052_ FROM table_14465924_1 WHERE area__km_2__ = '5.42';


Question: What are the unique IP addresses that have sent malicious traffic during the last month, both in and outside the organization?

CREATE TABLE malicious_traffic (ip_address VARCHAR(50), is_internal BOOLEAN, timestamp TIMESTAMP); INSERT INTO malicious_traffic (ip_address, is_internal, timestamp) VALUES ('8.8.8.8', true, '2022-01-01 10:00:00'); INSERT INTO malicious_traffic (ip_address, is_internal, timestamp) VALUES ('192.168.1.1', false, '2022-01-02 15:30:00');

SELECT DISTINCT ip_address FROM malicious_traffic WHERE timestamp >= NOW() - INTERVAL '1 month';


Question: How many healthcare facilities are there in each district?

CREATE TABLE Healthcare (District VARCHAR(255), FacilityType VARCHAR(255), Quantity INT); INSERT INTO Healthcare (District, FacilityType, Quantity) VALUES ('DistrictA', 'Hospital', 2), ('DistrictA', 'Clinic', 5), ('DistrictB', 'Hospital', 3), ('DistrictB', 'Clinic', 4);

SELECT District, FacilityType, SUM(Quantity) FROM Healthcare GROUP BY District, FacilityType;


Question: Determine the average fairness score of algorithms in South America

CREATE TABLE Algorithms (AlgorithmId INT, Name TEXT, FairnessScore FLOAT, Country TEXT); INSERT INTO Algorithms (AlgorithmId, Name, FairnessScore, Country) VALUES (1, 'AlgorithmA', 0.8, 'Brazil'), (2, 'AlgorithmB', 0.9, 'Argentina'), (3, 'AlgorithmC', 0.7, 'Colombia');

SELECT AVG(FairnessScore) FROM Algorithms WHERE Country = 'South America';


Question: How many research grants were awarded to each department?

CREATE TABLE departments (id INT, department_name VARCHAR(255)); CREATE TABLE research_grants (id INT, grant_name VARCHAR(255), grant_amount INT, department_id INT, PRIMARY KEY (id), FOREIGN KEY (department_id) REFERENCES departments(id)); INSERT INTO departments (id, department_name) VALUES (1, 'Computer Science'), (2, 'Mathematics'), (3, 'Physics'); INSERT INTO research_grants (id, grant_name, grant_amount, department_id) VALUES (1, 'Grant1', 50000, 1), (2, 'Grant2', 75000, 2), (3, 'Grant3', 100000, 3);

SELECT d.department_name, COUNT(rg.id) as grant_count FROM departments d JOIN research_grants rg ON d.id = rg.department_id GROUP BY d.department_name;


Question: Generate PostgreSQL SQL for: How many byes were there with an Against of 1655 and more than 10 wins?

CREATE TABLE table_name_51 (byes INTEGER, against VARCHAR, wins VARCHAR)

SELECT MIN(byes) FROM table_name_51 WHERE against = 1655 AND wins > 10;


Question: What is the total sales amount for each sales representative in the North region, ordered by total sales in descending order?

CREATE TABLE sales_representatives (id INT, name TEXT, region TEXT, sales FLOAT); INSERT INTO sales_representatives (id, name, region, sales) VALUES (1, 'Raul Sanchez', 'North', 5000), (2, 'Tanya Patel', 'South', 6000), (3, 'Mohammed Ali', 'East', 7000), (4, 'Emily Wang', 'West', 8000), (5, 'Jose Gonzalez', 'North', 9000), (6, 'Anna Kwon', 'North', 10000);

SELECT name, SUM(sales) as total_sales FROM sales_representatives WHERE region = 'North' GROUP BY name ORDER BY total_sales DESC;


Question: List all environmental impact assessments and their corresponding facilities for the past year.

CREATE TABLE environmental_assessments (id INT, assessment_date DATE, facility TEXT); INSERT INTO environmental_assessments (id, assessment_date, facility) VALUES (1, '2022-01-01', 'Facility1'), (2, '2022-03-15', 'Facility2'), (3, '2022-02-01', 'Facility3');

SELECT * FROM environmental_assessments WHERE assessment_date >= DATEADD(year, -1, CURRENT_DATE);


Question: Generate PostgreSQL SQL for: What Companion (in order from star) has a Semimajor axis (AU) of 0.1886 +0.083 −0.0104?

CREATE TABLE table_name_58 (companion__in_order_from_star_ VARCHAR, semimajor_axis___au__ VARCHAR)

SELECT companion__in_order_from_star_ FROM table_name_58 WHERE semimajor_axis___au__ = '0.1886 +0.083 −0.0104';


Question: List the number of employees hired in each month in 2021 for the marketing department.

CREATE TABLE hiring (id INT, employee_id INT, hire_date DATE); INSERT INTO hiring (id, employee_id, hire_date) VALUES (1, 3, '2021-01-15'), (2, 4, '2021-03-05'), (3, 5, '2021-04-20'), (4, 6, '2021-12-31');

SELECT EXTRACT(MONTH FROM hire_date) AS month, COUNT(*) AS hired_count FROM hiring JOIN employees ON hiring.employee_id = employees.id WHERE department = 'Marketing' AND YEAR(hire_date) = 2021 GROUP BY month;


Question: Generate PostgreSQL SQL for: How many bronze medals has a total less than 3 with a silver less than 1 and gold more than 1?

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

SELECT AVG(bronze) FROM table_name_66 WHERE total < 3 AND silver < 1 AND gold > 1;


Question: Determine the average water savings in liters achieved by the implemented water conservation initiatives in 'Beijing' for the month of March 2021

CREATE TABLE savings_data (region VARCHAR(50), date DATE, savings FLOAT); INSERT INTO savings_data (region, date, savings) VALUES ('Beijing', '2021-03-01', 100), ('Beijing', '2021-03-02', 110), ('Beijing', '2021-03-03', 120);

SELECT AVG(savings) FROM savings_data WHERE region = 'Beijing' AND date BETWEEN '2021-03-01' AND '2021-03-31';


Question: What is the average salary of employees who underwent leadership training in the Finance department?

CREATE TABLE EmployeeTrainings (EmployeeID INT, Department TEXT, Salary REAL, Training TEXT); INSERT INTO EmployeeTrainings (EmployeeID, Department, Salary, Training) VALUES (1, 'Finance', 72000, 'Leadership');

SELECT AVG(Salary) FROM EmployeeTrainings WHERE Department = 'Finance' AND Training = 'Leadership';


Question: Generate PostgreSQL SQL for: Show the average, minimum, and maximum ticket prices for exhibitions for all years before 2009.

CREATE TABLE exhibition (ticket_price INTEGER, YEAR INTEGER)

SELECT AVG(ticket_price), MIN(ticket_price), MAX(ticket_price) FROM exhibition WHERE YEAR < 2009;


Question: Create a view of satellites launched by the European Union

CREATE TABLE satellite_deployment (id INT PRIMARY KEY, name VARCHAR(255), country VARCHAR(255), launch_date DATE);

CREATE VIEW eu_satellites AS SELECT * FROM satellite_deployment WHERE country = 'European Union';


Question: Show a SQL definition from the timescaledb project (test_utils, item 1).

\c :TEST_DBNAME :ROLE_SUPERUSER
CREATE OR REPLACE FUNCTION test.condition() RETURNS VOID
    AS :MODULE_PATHNAME, 'ts_test_utils_condition' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;

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


Question: What is the sum of all transaction values (in USD) for Binance Smart Chain in the past week?

CREATE TABLE binance_smart_chain (transaction_time TIMESTAMP, transaction_value DECIMAL(18,2));

SELECT SUM(transaction_value) FROM binance_smart_chain WHERE transaction_time >= NOW() - INTERVAL '1 week';


Question: What is the average population of countries with a GDP less than 1.5 and more than 30 million visitors in the international_visitors table?

CREATE TABLE countries (country_id INT, name VARCHAR(50), population INT, gdp FLOAT); INSERT INTO countries (country_id, name, population, gdp) VALUES (1, 'Brazil', 210147125, 1.432); INSERT INTO countries (country_id, name, population, gdp) VALUES (2, 'Indonesia', 273523615, 1.019);

SELECT AVG(c.population) FROM countries c INNER JOIN (SELECT country_id, SUM(visitors) as total_visitors FROM international_visitors GROUP BY country_id) iv ON c.country_id = iv.country_id WHERE c.gdp < 1.5 AND total_visitors > 30000000;


Question: Identify the total amount of climate finance spent on renewable energy sources in Asia and the number of adaptation projects in the region.

CREATE TABLE climate_finance_re (region VARCHAR(50), source VARCHAR(50), amount NUMERIC(12,2)); INSERT INTO climate_finance_re (region, source, amount) VALUES ('Asia', 'Wind', 1500.00), ('Asia', 'Solar', 2500.00); CREATE TABLE climate_adaptation_re (project_name VARCHAR(50), region VARCHAR(50), status VARCHAR(50)); INSERT INTO climate_adaptation_re (project_name, region, status) VALUES ('Resilient Cities', 'Asia', 'Successful'), ('Green Infrastructure', 'Asia', 'Successful'), ('Coastal Protection', 'Asia', 'Successful');

SELECT SUM(amount) FROM climate_finance_re WHERE region = 'Asia' AND source IN ('Wind', 'Solar'); SELECT COUNT(*) FROM climate_adaptation_re WHERE region = 'Asia';


Question: What is the minimum soil moisture level for each crop type in the past month?

CREATE TABLE crop_soil_moisture (crop_type TEXT, date DATE, soil_moisture INTEGER); INSERT INTO crop_soil_moisture VALUES ('cotton', '2022-06-01', 40), ('rice', '2022-06-01', 50);

SELECT crop_type, MIN(soil_moisture) as min_soil_moisture FROM crop_soil_moisture WHERE date >= CURDATE() - INTERVAL 1 MONTH GROUP BY crop_type;


Question: Generate PostgreSQL SQL for: How much total time was in lane 4?

CREATE TABLE table_name_66 (time VARCHAR, lane VARCHAR)

SELECT COUNT(time) FROM table_name_66 WHERE lane = 4;


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

SELECT * FROM test_timestamptz WHERE i>='2004-10-26 08:55:08'::timestamptz ORDER BY i;

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


Question: Generate PostgreSQL SQL for: Name the most number for air date 2009/12/29

CREATE TABLE table_21002034_7 (_number INTEGER, air_date_netherlands_yyyy_mm_dd VARCHAR)

SELECT MAX(_number) FROM table_21002034_7 WHERE air_date_netherlands_yyyy_mm_dd = '2009/12/29';


Question: Generate PostgreSQL SQL for: What was the lowest ranking rower from Great Britain?

CREATE TABLE table_name_86 (rank INTEGER, country VARCHAR)

SELECT MIN(rank) FROM table_name_86 WHERE country = 'great britain';


Question: What is the average labor rating for factories in each region?

CREATE TABLE regions (region_id INT, name VARCHAR(255)); INSERT INTO regions VALUES (1, 'North America'); INSERT INTO regions VALUES (2, 'Asia'); CREATE TABLE factories (factory_id INT, name VARCHAR(255), location VARCHAR(255), country_id INT, labor_rating INT, region_id INT); INSERT INTO factories VALUES (1, 'Eco-Friendly Factory A', 'New York, NY', 1, 90, 1); INSERT INTO factories VALUES (2, 'Fairtrade Factory B', 'Delhi, India', 2, 85, 2);

SELECT regions.name, AVG(factories.labor_rating) FROM regions JOIN factories ON regions.region_id = factories.region_id GROUP BY regions.name;


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

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


Question: Which province in Canada has the highest energy storage capacity?

CREATE TABLE energy_storage_Canada (province VARCHAR(255), source_type VARCHAR(255), capacity INT); INSERT INTO energy_storage_Canada (province, source_type, capacity) VALUES ('Ontario', 'Batteries', 3000), ('Quebec', 'Batteries', 4000), ('Ontario', 'Pumped Hydro', 8000);

SELECT province, MAX(capacity) FROM energy_storage_Canada GROUP BY province;


Question: How many crimes were reported in District4 of CityR last year?

CREATE TABLE crimes_3 (id INT, city VARCHAR(50), district VARCHAR(50), year INT, crime_count INT); INSERT INTO crimes_3 (id, city, district, year, crime_count) VALUES (1, 'CityR', 'District4', 2021, 39), (2, 'CityR', 'District4', 2020, 30), (3, 'CityS', 'District5', 2021, 55);

SELECT SUM(crime_count) FROM crimes_3 WHERE city = 'CityR' AND district = 'District4' AND year = 2021;


Question: Update the hours volunteered in the 'VolunteerHours' table

CREATE TABLE VolunteerHours (VolunteerHoursID INT PRIMARY KEY, VolunteerID INT, Hours DECIMAL(10, 2), VolunteerDate DATE);

UPDATE VolunteerHours SET Hours = 4.00 WHERE VolunteerHoursID = 401;


Question: PostgreSQL Plpgsql: show example 35.

EXECUTE format('UPDATE tbl SET %I = $1 WHERE key = $2', colname) USING newvalue, keyvalue;

Explanation: Example from PostgreSQL documentation on Plpgsql.


Question: Generate PostgreSQL SQL for: Who was the opponent in the bout that led to a win in a time of 1:21?

CREATE TABLE table_name_47 (opponent VARCHAR, res VARCHAR, time VARCHAR)

SELECT opponent FROM table_name_47 WHERE res = 'win' AND time = '1:21';


Question: Generate PostgreSQL SQL for: Show all allergy types.

CREATE TABLE Allergy_type (allergytype VARCHAR)

SELECT DISTINCT allergytype FROM Allergy_type;


Question: Generate PostgreSQL SQL for: What are the names of the nations with the 3 lowest populations?

CREATE TABLE country (Name VARCHAR, Population VARCHAR)

SELECT Name FROM country ORDER BY Population LIMIT 3;


Question: Generate PostgreSQL SQL for: What is 2011, when 2009 is "A"?

SELECT 2011 FROM table_name_59 WHERE 2009 = 'a';


Question: Generate PostgreSQL SQL for: Who had less than 7 goals, was ranked under 7, and had more than 8 appearances?

CREATE TABLE table_name_86 (name VARCHAR, appearances VARCHAR, goals VARCHAR, rank VARCHAR)

SELECT name FROM table_name_86 WHERE goals < 7 AND rank < 7 AND appearances > 8;


Question: Delete the painting 'Guernica' from the 'Paintings' table.

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

DELETE FROM Paintings WHERE Title = 'Guernica';


Question: Generate PostgreSQL SQL for: Which Mountain Range has a Region of haiti, and a Location of 18.3601°n 71.9764°w?

CREATE TABLE table_name_82 (mountain_range VARCHAR, region VARCHAR, location VARCHAR)

SELECT mountain_range FROM table_name_82 WHERE region = 'haiti' AND location = '18.3601°n 71.9764°w';


Question: What is the average heart rate for each member during 'Yoga' workouts in January 2022?

CREATE TABLE memberships (id INT, member_type VARCHAR(50), region VARCHAR(50)); CREATE TABLE workout_data (member_id INT, workout_type VARCHAR(50), duration INT, heart_rate_avg INT, calories_burned INT, workout_date DATE);

SELECT m.id, AVG(w.heart_rate_avg) as avg_heart_rate FROM memberships m JOIN workout_data w ON m.id = w.member_id WHERE w.workout_type = 'Yoga' AND w.workout_date >= DATE '2022-01-01' AND w.workout_date < DATE '2022-02-01' GROUP BY m.id;


Question: How many fans attended the games of the western conference teams?

CREATE TABLE games (game_id INT, team_id INT, fans_attended INT); INSERT INTO games VALUES (1, 1, 15000), (2, 1, 16000), (3, 2, 17000), (4, 2, 18000), (5, 3, 19000);

SELECT te.conference, SUM(g.fans_attended) as total_fans FROM games g JOIN teams te ON g.team_id = te.team_id WHERE te.conference = 'Western' GROUP BY te.conference;


Question: What is the average response time for emergency calls in the 'downtown' precinct?

CREATE TABLE emergency_calls (id INT, call_time TIMESTAMP, precinct VARCHAR(20)); INSERT INTO emergency_calls (id, call_time, precinct) VALUES (1, '2022-01-01 12:30:00', 'downtown'), (2, '2022-01-01 15:10:00', 'north'), (3, '2022-01-01 09:45:00', 'downtown');

SELECT AVG(EXTRACT(EPOCH FROM call_time - LAG(call_time) OVER (PARTITION BY precinct ORDER BY call_time))) AS avg_response_time FROM emergency_calls WHERE precinct = 'downtown';


Question: What is the total fare collected for metro lines in Paris?

CREATE TABLE metro_lines (line_id INT, city VARCHAR(50)); INSERT INTO metro_lines (line_id, city) VALUES (1, 'Paris'), (2, 'Berlin'); CREATE TABLE fares_collected (line_id INT, fare DECIMAL(5,2)); INSERT INTO fares_collected (line_id, fare) VALUES (1, 500.00), (1, 750.00), (2, 300.00);

SELECT SUM(fare) FROM fares_collected INNER JOIN metro_lines ON fares_collected.line_id = metro_lines.line_id WHERE city = 'Paris';


Question: What is the minimum number of visitors for jazz events in 2021?

CREATE TABLE IF NOT EXISTS events (id INT, name VARCHAR(255), type VARCHAR(255), year INT, visitors INT); INSERT INTO events (id, name, type, year, visitors) VALUES (1, 'EventA', 'Jazz', 2021, 300), (2, 'EventB', 'Jazz', 2021, 450), (3, 'EventC', 'Jazz', 2021, 500);

SELECT MIN(visitors) FROM events WHERE type = 'Jazz' AND year = 2021;


Question: What is the minimum cultural competency score for mental health facilities in New York?

CREATE TABLE mental_health_facilities (id INT, name VARCHAR, state VARCHAR, cultural_competency_score INT); INSERT INTO mental_health_facilities (id, name, state, cultural_competency_score) VALUES (1, 'Facility One', 'New York', 85); INSERT INTO mental_health_facilities (id, name, state, cultural_competency_score) VALUES (2, 'Facility Two', 'New York', 90);

SELECT state, MIN(cultural_competency_score) as min_score FROM mental_health_facilities WHERE state = 'New York' GROUP BY state;


Question: Generate PostgreSQL SQL for: What is the total number of rounds of the player with a pick of 20?

CREATE TABLE table_name_87 (round VARCHAR, pick VARCHAR)

SELECT COUNT(round) FROM table_name_87 WHERE pick = 20;


Question: What is the maximum number of experiments conducted by a single spacecraft, grouped by organization in the astrobiology_experiments and mission_data tables?

CREATE TABLE astrobiology_experiments (experiment_id INT, name VARCHAR(100), spacecraft VARCHAR(100), launch_date DATE, experiments_conducted INT); CREATE TABLE mission_data (mission_id INT, name VARCHAR(100), organization VARCHAR(100), launch_date DATE, mission_cost FLOAT);

SELECT organization, MAX(experiments_conducted) FROM astrobiology_experiments, mission_data WHERE astrobiology_experiments.launch_date = mission_data.launch_date GROUP BY organization;


Question: Count how many deep-sea expeditions have been conducted by the "Ocean Explorers" organization?

CREATE TABLE deep_sea_expeditions (expedition_id INT, name TEXT, organization TEXT, year INT);

SELECT COUNT(*) FROM deep_sea_expeditions WHERE organization = 'Ocean Explorers';


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

create function polyf(x anyrange) returns anyarray as $$
  select array[lower(x), upper(x)]
$$ language sql;

Explanation: DDL from PostgreSQL core regression test for Polymorphism.


Question: Generate PostgreSQL SQL for: Which date contained Aubrey O'Day as the cover model?

CREATE TABLE table_1566852_10 (date VARCHAR, cover_model VARCHAR)

SELECT date FROM table_1566852_10 WHERE cover_model = 'Aubrey O'Day';


Question: Generate PostgreSQL SQL for: What was the 2009 ranking for Webometrics?

CREATE TABLE table_name_40 (ranking VARCHAR)

SELECT 2009 FROM table_name_40 WHERE ranking = 'webometrics';


Question: Delete companies with no electric vehicles in the ElectricVehicles table.

CREATE TABLE ElectricVehicles (id INT, company VARCHAR(20), vehicle_type VARCHAR(20), num_vehicles INT); INSERT INTO ElectricVehicles (id, company, vehicle_type, num_vehicles) VALUES (1, 'Tesla', 'EV', 1500000), (2, 'Nissan', 'Leaf', 500000), (3, 'Chevrolet', 'Bolt', 300000), (4, 'Ford', 'No EV', 0);

DELETE FROM ElectricVehicles WHERE company NOT IN (SELECT company FROM ElectricVehicles WHERE vehicle_type = 'EV');


Question: What was the total quantity of chemical 'A' produced in Q1 2021?

CREATE TABLE chemical_production (date DATE, chemical VARCHAR(10), quantity INT); INSERT INTO chemical_production VALUES ('2021-01-01', 'A', 500), ('2021-01-05', 'A', 600), ('2021-02-10', 'A', 700), ('2021-03-20', 'A', 800);

SELECT SUM(quantity) FROM chemical_production WHERE chemical = 'A' AND date BETWEEN '2021-01-01' AND '2021-03-31';


Question: Generate PostgreSQL SQL for: What was the time of the bout against Dave Menne?

CREATE TABLE table_name_33 (time VARCHAR, opponent VARCHAR)

SELECT time FROM table_name_33 WHERE opponent = 'dave menne';


Question: Generate PostgreSQL SQL for: Which player is from Joliet Catholic HIgh School?

CREATE TABLE table_11677691_7 (player VARCHAR, school VARCHAR)

SELECT player FROM table_11677691_7 WHERE school = 'Joliet Catholic High school';


Question: What is the maximum number of peacekeeping operations that a single country has been involved in?

CREATE TABLE Peacekeeping_Operations (id INT, country VARCHAR(50), year INT); INSERT INTO Peacekeeping_Operations (id, country, year) VALUES (1, 'United States', 2018), (2, 'United States', 2019), (3, 'United States', 2020), (4, 'United Kingdom', 2018), (5, 'Canada', 2019), (6, 'Australia', 2020), (7, 'France', 2018), (8, 'Germany', 2019), (9, 'Italy', 2020);

SELECT country, MAX(year) FROM Peacekeeping_Operations GROUP BY country HAVING COUNT(year) = (SELECT MAX(pe.cnt) FROM (SELECT COUNT(*) AS cnt FROM Peacekeeping_Operations GROUP BY country) AS pe);


Question: How many citizen feedback records were received in the last week for public safety services?

CREATE TABLE feedback (id INT, service VARCHAR(20), date DATE); INSERT INTO feedback (id, service, date) VALUES (1, 'Public Safety', '2022-01-01'), (2, 'Public Safety', '2022-01-07');

SELECT COUNT(*) FROM feedback WHERE service = 'Public Safety' AND date >= DATE_SUB(CURDATE(), INTERVAL 1 WEEK);


Question: Who are the developers that have created digital assets on the Binance Smart Chain?

CREATE TABLE developers (developer_id INT, name VARCHAR(50), country VARCHAR(50)); CREATE TABLE digital_assets (asset_id INT, name VARCHAR(50), developer_id INT, network VARCHAR(50)); INSERT INTO digital_assets (asset_id, name, developer_id, network) VALUES (1, 'Asset1', 1, 'Ethereum'), (2, 'BSCDApp', 2, 'Binance Smart Chain'); INSERT INTO developers (developer_id, name, country) VALUES (1, 'Alice', 'USA'), (2, 'Bob', 'China');

SELECT developers.name FROM developers INNER JOIN digital_assets ON developers.developer_id = digital_assets.developer_id WHERE digital_assets.network = 'Binance Smart Chain';


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

Explanation: DML from PostgreSQL core regression test for Numeric.


Question: Which council members have not provided any feedback?

CREATE TABLE City_Council (Council_ID INT PRIMARY KEY, Council_Member VARCHAR(50), District_Number INT); CREATE TABLE Policy_Feedback (Feedback_ID INT PRIMARY KEY, Council_ID INT, Policy_Area VARCHAR(30), Feedback VARCHAR(100)); INSERT INTO City_Council (Council_ID, Council_Member, District_Number) VALUES (1, 'Leila Alvarez', 1), (2, 'James Chen', 2), (3, 'Maria Lee', 3), (4, 'Alex Brown', 4); INSERT INTO Policy_Feedback (Feedback_ID, Council_ID, Policy_Area, Feedback) VALUES (1, 1, 'Housing', 'More affordable housing needed'), (2, 2, 'Transportation', 'Improve public transportation'), (3, 3, 'Education', 'Increase funding for schools');

SELECT Council_Member FROM City_Council WHERE Council_ID NOT IN (SELECT Council_ID FROM Policy_Feedback);


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

CREATE TABLE table_name_30 (date VARCHAR, loss VARCHAR)

SELECT date FROM table_name_30 WHERE loss = 'johnson (9-8)';


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

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

SELECT count(*) FROM (select int4range(1, 2, '()')) AS _sub;


Question: Generate PostgreSQL SQL for: What is the catalog number with the date November 16, 2004?

CREATE TABLE table_name_15 (catalog VARCHAR, date VARCHAR)

SELECT catalog FROM table_name_15 WHERE date = 'november 16, 2004';


Question: What is the total number of likes received by users in Germany and the UK?

CREATE TABLE likes (id INT, post_id INT, user_id INT); INSERT INTO likes (id, post_id, user_id) VALUES (1, 1, 1), (2, 1, 2), (3, 2, 1); CREATE TABLE posts (id INT, user_id INT); INSERT INTO posts (id, user_id) VALUES (1, 1), (2, 2), (3, 3); CREATE TABLE users (id INT, country VARCHAR(255)); INSERT INTO users (id, country) VALUES (1, 'Germany'), (2, 'UK'), (3, 'Canada');

SELECT SUM(1) FROM (SELECT * FROM likes INNER JOIN posts ON likes.post_id = posts.id INNER JOIN users ON posts.user_id = users.id WHERE users.country IN ('Germany', 'UK')) AS subquery;


Question: What is the average age of residents in each city, grouped by state, who have participated in public consultations?

CREATE TABLE residents (id INT, age INT, city VARCHAR(50), state VARCHAR(50), participation BOOLEAN); INSERT INTO residents (id, age, city, state, participation) VALUES (1, 34, 'New York', 'NY', true), (2, 55, 'Los Angeles', 'CA', false); CREATE TABLE cities (id INT, name VARCHAR(50), state VARCHAR(50)); INSERT INTO cities (id, name, state) VALUES (1, 'New York', 'NY'), (2, 'Los Angeles', 'CA'); CREATE TABLE public_consultations (id INT, resident_id INT, consultation_topic VARCHAR(50)); INSERT INTO public_consultations (id, resident_id, consultation_topic) VALUES (1, 1, 'Urban Planning');

SELECT state, AVG(age) as avg_age FROM residents r JOIN cities c ON r.city = c.name WHERE participation = true GROUP BY state;


Question: What is the number of professional development courses taken by teachers in each department?

CREATE TABLE teachers (teacher_id INT, teacher_name VARCHAR(50), department VARCHAR(20), course_id INT); INSERT INTO teachers (teacher_id, teacher_name, department, course_id) VALUES (1, 'John Doe', 'Math', 101), (2, 'Jane Smith', 'English', 102), (3, 'Alice Johnson', 'Science', 103), (4, 'Bob Williams', 'Math', 101), (5, 'Charlie Brown', 'English', 102); CREATE TABLE courses (course_id INT, course_name VARCHAR(50), category VARCHAR(20)); INSERT INTO courses (course_id, course_name, category) VALUES (101, 'Algebra I', 'Professional Development'), (102, 'Literature Review', 'Professional Development'), (103, 'Physics Lab', 'Regular Course'), (104, 'Calculus I', 'Professional Development');

SELECT department, COUNT(DISTINCT course_id) FROM teachers t JOIN courses c ON t.course_id = c.course_id WHERE c.category = 'Professional Development' GROUP BY department;


Question: What is the total number of military equipment sales in the Asia-Pacific region?

CREATE TABLE military_equipment_sales(id INT, region VARCHAR(20), equipment_type VARCHAR(20), quantity INT, sale_price FLOAT);

SELECT SUM(quantity * sale_price) FROM military_equipment_sales WHERE region = 'Asia-Pacific';


Question: What is the total revenue for each restaurant location, grouped by state, excluding states with no revenue?

CREATE TABLE restaurants (id INT, name TEXT, state TEXT); CREATE TABLE revenue (restaurant_id INT, location_id INT, amount INT);

SELECT restaurants.state, SUM(revenue.amount) FROM revenue JOIN restaurants ON revenue.restaurant_id = restaurants.id WHERE revenue.amount > 0 GROUP BY restaurants.state;


Question: What is the most popular material based on inventory quantity?

CREATE TABLE trends (id INT, material VARCHAR(255), popularity FLOAT); INSERT INTO trends (id, material, popularity) VALUES (3, 'Hemp', 0.85); INSERT INTO trends (id, material, popularity) VALUES (4, 'Tencel', 0.15);

SELECT t.material, t.popularity FROM trends t JOIN (SELECT material, SUM(quantity) as total_quantity FROM inventory GROUP BY material ORDER BY total_quantity DESC LIMIT 1) i ON t.material = i.material;


Question: Generate PostgreSQL SQL for: During st kilda's home game, what was the number of people in the crowd?

CREATE TABLE table_name_12 (crowd VARCHAR, home_team VARCHAR)

SELECT crowd FROM table_name_12 WHERE home_team = 'st kilda';


Question: Find the number of successful satellite launches by company ABC

CREATE TABLE satellites (id INT, name VARCHAR(50), launch_status VARCHAR(50), manufacturer VARCHAR(50), launch_date DATE);

SELECT COUNT(*) FROM satellites WHERE launch_status = 'Success' AND manufacturer = 'ABC';


Question: PL/pgSQL test: Plpgsql Record (example 69).

end$$;

update mutable set f2 = f2 || ' baz';
table mutable;

--
-- Domains of composite
--

create domain ordered_int8s as two_int8s check((value).q1 <= (value).q2);

create function read_ordered_int8s(p ordered_int8s) returns int8 as $$
begin return p.q1 + p.q2; end
$$ language plpgsql;

select read_ordered_int8s(row(1, 2));
select read_ordered_int8s(row(2, 1));  -- fail

create function build_ordered_int8s(i int8, j int8) returns ordered_int8s as $$
begin return row(i,j); end
$$ language plpgsql;

select build_ordered_int8s(1,2);
select build_ordered_int8s(2,1);  -- fail

create function build_ordered_int8s_2(i int8, j int8) returns ordered_int8s as $$
declare r record; begin r := row(i,j); return r; end
$$ language plpgsql;

select build_ordered_int8s_2(1,2);
select build_ordered_int8s_2(2,1);  -- fail

create function build_ordered_int8s_3(i int8, j int8) returns ordered_int8s as $$
declare r two_int8s; begin r := row(i,j); return r; end
$$ language plpgsql;

select build_ordered_int8s_3(1,2);
select build_ordered_int8s_3(2,1);  -- fail

create function build_ordered_int8s_4(i int8, j int8) returns ordered_int8s as $$
declare r ordered_int8s; begin r := row(i,j); return r; end
$$ language plpgsql;

select build_ordered_int8s_4(1,2);
select build_ordered_int8s_4(2,1);  -- fail

create function build_ordered_int8s_a(i int8, j int8) returns ordered_int8s[] as $$
begin return array[row(i,j), row(i,j+1)]; end
$$ language plpgsql;

select build_ordered_int8s_a(1,2);
select build_ordered_int8s_a(2,1);  -- fail

-- check field assignment
do $$
declare r ordered_int8s;

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


Question: Generate PostgreSQL SQL for: Name the authority for coed gender and chanel college

CREATE TABLE table_name_67 (authority VARCHAR, gender VARCHAR, name VARCHAR)

SELECT authority FROM table_name_67 WHERE gender = 'coed' AND name = 'chanel college';


Question: What was the total revenue for the 'Desserts' menu category in the second quarter of 2021?

CREATE TABLE restaurant_revenue(menu_category VARCHAR(20), revenue DECIMAL(10, 2), order_date DATE); INSERT INTO restaurant_revenue(menu_category, revenue, order_date) VALUES ('Desserts', 1500, '2021-04-01'), ('Desserts', 1800, '2021-05-03'), ('Desserts', 2000, '2021-06-01');

SELECT SUM(revenue) FROM restaurant_revenue WHERE menu_category = 'Desserts' AND order_date >= '2021-04-01' AND order_date <= '2021-06-30';


Question: Generate PostgreSQL SQL for: Name the Pick # which has a Position of lb, and a CFL Team of winnipeg?

CREATE TABLE table_name_74 (pick__number INTEGER, position VARCHAR, cfl_team VARCHAR)

SELECT SUM(pick__number) FROM table_name_74 WHERE position = 'lb' AND cfl_team = 'winnipeg';


Question: Generate PostgreSQL SQL for: What's the type that ends in 2009?

CREATE TABLE table_name_60 (type VARCHAR, ends VARCHAR)

SELECT type FROM table_name_60 WHERE ends = '2009';


Question: What is the total amount donated by each donor in 2021?

CREATE TABLE Donors (DonorID INT, DonorName TEXT, DonationDate DATE, DonationAmount FLOAT); INSERT INTO Donors (DonorID, DonorName, DonationDate, DonationAmount) VALUES (1, 'John Smith', '2021-01-01', 50.00), (2, 'Jane Doe', '2021-02-14', 100.00);

SELECT DonorName, SUM(DonationAmount) as TotalDonation  FROM Donors WHERE YEAR(DonationDate) = 2021 GROUP BY DonorName;


Question: PostgreSQL regression test 'rowsecurity': Write the SELECT query (example 295).

SELECT * FROM rec1;    -- fail, mutual recursion via s.b. views

--
-- recursive RLS and VIEWs in policy
--
SET SESSION AUTHORIZATION regress_rls_alice;

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

SELECT count(*) FROM (SELECT * FROM rec1;    -- fail, mutual recursion via s.b. views

--
-- recursive RLS and VIEWs in policy
--
SET SESSION AUTHORIZATION regress_rls_alice) AS _sub;


Question: Show an example of PostgreSQL ALTER COLLATION (example 2).

Explanation: PostgreSQL ALTER COLLATION command.


Question: Generate PostgreSQL SQL for: What is the Home Team Score at Windy Hill?

CREATE TABLE table_name_64 (home_team VARCHAR, venue VARCHAR)

SELECT home_team AS score FROM table_name_64 WHERE venue = 'windy hill';


Question: Count the number of sustainable textile suppliers, and show only those suppliers that have adopted sustainable practices in the last 5 years.

CREATE TABLE TextileSuppliers (supplier TEXT, sustainable BOOLEAN, last_sustainable_update DATE); INSERT INTO TextileSuppliers (supplier, sustainable, last_sustainable_update) VALUES ('Supplier1', true, '2018-01-01'), ('Supplier2', false, '2015-01-01'), ('Supplier3', true, '2020-01-01'), ('Supplier4', true, '2017-01-01');

SELECT supplier, COUNT(*) as sustainable_suppliers FROM TextileSuppliers WHERE sustainable = true AND last_sustainable_update >= DATE_SUB(CURRENT_DATE, INTERVAL 5 YEAR) GROUP BY supplier HAVING COUNT(*) > 500;


Question: How many marine species have been discovered in the Southern Ocean since 2000?

CREATE TABLE southern_ocean_species (species_name TEXT, year INTEGER, discovered BOOLEAN); INSERT INTO southern_ocean_species (species_name, year, discovered) VALUES ('Antarctic Krill', 2005, TRUE), ('Southern Ocean Squid', 2010, TRUE);

SELECT COUNT(*) FROM southern_ocean_species WHERE year >= 2000 AND discovered = TRUE;


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

SELECT count(*) > 0 AS ok FROM pg_control_recovery();

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

SELECT count(*) FROM (SELECT count(*) > 0 AS ok FROM pg_control_recovery()) AS _sub;


Question: Generate PostgreSQL SQL for: Which College/Junior/Club Team (League) are from sweden?

CREATE TABLE table_name_92 (college_junior_club_team__league_ VARCHAR, nationality VARCHAR)

SELECT college_junior_club_team__league_ FROM table_name_92 WHERE nationality = 'sweden';


Question: What is the percentage of waste generated in the 'East Coast' region that is plastic, paper, or glass?

CREATE TABLE waste_type (waste_type VARCHAR(50)); INSERT INTO waste_type (waste_type) VALUES ('Plastic'), ('Paper'), ('Glass'); CREATE TABLE waste_generation (city_name VARCHAR(50), region VARCHAR(50), waste_type VARCHAR(50), waste_metric INT); INSERT INTO waste_generation (city_name, region, waste_type, waste_metric) VALUES ('New York', 'East Coast', 'Plastic', 500), ('New York', 'East Coast', 'Paper', 600), ('New York', 'East Coast', 'Glass', 400);

SELECT 100.0 * SUM(CASE WHEN waste_type IN ('Plastic', 'Paper', 'Glass') THEN waste_metric ELSE 0 END) / SUM(waste_metric) AS percentage FROM waste_generation WHERE region = 'East Coast';


Question: What is the name and description of the vulnerabilities with a specific severity level in the 'vulnerabilities' table?

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

SELECT name, description FROM vulnerabilities WHERE severity = 'High';


Question: Show a query using PostgreSQL contrib extension 'jsonb_plperl' (example 28).

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


Question: How many users from each state in the USA have a membership?

CREATE TABLE users (id INT, state VARCHAR(50), membership BOOLEAN); INSERT INTO users (id, state, membership) VALUES (1, 'California', TRUE), (2, 'New York', FALSE), (3, 'Texas', TRUE), (4, 'Florida', TRUE);

SELECT state, COUNT(*) as num_members FROM users WHERE state IN ('California', 'New York', 'Texas', 'Florida') AND membership = TRUE GROUP BY state;


Question: What is the total number of yellow cards given to players from Germany?

CREATE TABLE card_stats (id INT, player TEXT, yellow_cards INT, country TEXT); INSERT INTO card_stats (id, player, yellow_cards, country) VALUES (1, 'Klose', 5, 'Germany'), (2, 'Schweinsteiger', 4, 'Germany'), (3, 'Lahm', 3, 'Germany');

SELECT SUM(yellow_cards) FROM card_stats WHERE country = 'Germany';


Question: Update the price of the 'Burrito' menu item to $10.99

CREATE TABLE menu_items (item_name VARCHAR(255), price DECIMAL(10,2)); INSERT INTO menu_items (item_name, price) VALUES ('Pizza', 12.99), ('Burrito', 9.99);

UPDATE menu_items SET price = 10.99 WHERE item_name = 'Burrito';


Question: Generate PostgreSQL SQL for: When the game is listed as 2, what is the score?

CREATE TABLE table_name_81 (score VARCHAR, game VARCHAR)

SELECT score FROM table_name_81 WHERE game = 2;


Question: Insert a new patient record for a 25 year old patient with a diagnosis of PTSD in the US

CREATE SCHEMA mental_health; USE mental_health; CREATE TABLE patients (patient_id INT, diagnosis VARCHAR(50), age INT, country VARCHAR(50));

INSERT INTO patients VALUES (8, 'PTSD', 25, 'US');


Question: Generate PostgreSQL SQL for: What is the Top-25 with an Events of 20, and a Wins larger than 2?

CREATE TABLE table_name_45 (top_25 INTEGER, events VARCHAR, wins VARCHAR)

SELECT AVG(top_25) FROM table_name_45 WHERE events = 20 AND wins > 2;


Question: What is the average production quantity for wells in the 'North Sea' that have a production quantity greater than 1000?

CREATE TABLE wells (id INT, name VARCHAR(255), location VARCHAR(255), production_quantity INT); INSERT INTO wells (id, name, location, production_quantity) VALUES (1, 'Well A', 'North Sea', 1000), (2, 'Well B', 'North Sea', 1200), (3, 'Well C', 'North Sea', 1500);

SELECT AVG(production_quantity) FROM wells WHERE location = 'North Sea' AND production_quantity > 1000;


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

INSERT INTO temporal_partitioned_rng (id, valid_at) VALUES ('[5,6)', daterange('2018-01-01', '2018-02-01'));

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


Question: Find the chemical with the lowest quantity produced in the last 30 days.

CREATE TABLE chemical_production_new2 (id INT PRIMARY KEY, chemical_name VARCHAR(50), quantity INT, production_date DATE);

SELECT chemical_name, MIN(quantity) as min_quantity FROM chemical_production_new2 WHERE production_date > CURDATE() - INTERVAL 30 DAY GROUP BY chemical_name LIMIT 1;


Question: Generate PostgreSQL SQL for: Which modern house title translates to prison?

CREATE TABLE table_name_46 (modern_title_of_house VARCHAR, translation VARCHAR)

SELECT modern_title_of_house FROM table_name_46 WHERE translation = 'prison';


Question: What is the total revenue generated by eco-friendly hotels in Japan?

CREATE TABLE eco_hotels_japan (hotel_id INT, hotel_name TEXT, country TEXT, revenue FLOAT); INSERT INTO eco_hotels_japan (hotel_id, hotel_name, country, revenue) VALUES (1, 'Eco-Hotel Kyoto', 'Japan', 120000), (2, 'Green Tokyo Inn', 'Japan', 150000);

SELECT SUM(revenue) FROM eco_hotels_japan;


Question: Generate PostgreSQL SQL for: What country has a time of 7:28.66 and a rank less than 3?

CREATE TABLE table_name_27 (country VARCHAR, rank VARCHAR, time VARCHAR)

SELECT country FROM table_name_27 WHERE rank < 3 AND time = '7:28.66';


Question: Find customers with multiple claims and 'Renters' policies in Canada.

CREATE TABLE Claims (ClaimID INT, PolicyID INT); CREATE TABLE Policy (PolicyID INT, PolicyType VARCHAR(20), CustomerID INT, CustomerPostalCode VARCHAR(7), Country VARCHAR(20)); INSERT INTO Claims (ClaimID, PolicyID) VALUES (1, 1), (2, 2), (3, 3), (4, 3), (5, 5); INSERT INTO Policy (PolicyID, PolicyType, CustomerID, CustomerPostalCode, Country) VALUES (1, 'Homeowners', 101, 'M1M1M1', 'Canada'), (2, 'Auto', 102, 'A1A1A1', 'Canada'), (3, 'Renters', 103, 'M2M2M2', 'Canada'), (4, 'Life', 104, 'N1N1N1', 'Canada'), (5, 'Renters', 105, 'M2M2M2', 'Canada');

SELECT Policy.CustomerID FROM Policy INNER JOIN Claims ON Policy.PolicyID = Claims.PolicyID WHERE Policy.PolicyType = 'Renters' AND Policy.Country = 'Canada' GROUP BY Policy.CustomerID HAVING COUNT(DISTINCT Claims.ClaimID) > 1;


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

CREATE FUNCTION exists_any(hstore,text[])
RETURNS bool
AS 'MODULE_PATHNAME','hstore_exists_any'
LANGUAGE C STRICT IMMUTABLE PARALLEL SAFE;


Question: Generate PostgreSQL SQL for: Which round was Brian Elder taken in?

CREATE TABLE table_name_15 (round INTEGER, player VARCHAR)

SELECT MIN(round) FROM table_name_15 WHERE player = 'brian elder';


Question: What is the total biomass of all marine species in the Arctic region, grouped by conservation status?"

CREATE TABLE marine_species_biomass (species_name VARCHAR(255), region VARCHAR(255), biomass FLOAT, conservation_status VARCHAR(255)); INSERT INTO marine_species_biomass (species_name, region, biomass, conservation_status) VALUES ('Polar Bear', 'Arctic', 500, 'Fully Protected'), ('Narwhal', 'Arctic', 300, 'Partially Protected'), ('Ringed Seal', 'Arctic', 200, 'Fully Protected');

SELECT conservation_status, SUM(biomass) as total_biomass FROM marine_species_biomass WHERE region = 'Arctic' GROUP BY conservation_status;


Question: What is the average number of heritage sites per country in the Americas?

CREATE TABLE CountriesAmericas (id INT, name TEXT, region TEXT); INSERT INTO CountriesAmericas (id, name, region) VALUES (1, 'United States', 'Americas'), (2, 'Canada', 'Americas'); CREATE TABLE HeritageSitesAmericas (id INT, country_id INT, name TEXT); INSERT INTO HeritageSitesAmericas (id, country_id, name) VALUES (1, 1, 'Statue of Liberty'), (2, 1, 'Grand Canyon'), (3, 2, 'Niagara Falls'), (4, 2, 'CN Tower');

SELECT AVG(site_count) FROM (SELECT COUNT(HeritageSitesAmericas.id) AS site_count FROM HeritageSitesAmericas GROUP BY HeritageSitesAmericas.country_id) AS SiteCountPerCountry;


Question: Generate PostgreSQL SQL for: How many countries had a total freshwater withdrawal (km 3 /yr) where the agricultural use (m 3 /p/yr)(in %) was 428(62%)?

CREATE TABLE table_15909409_2 (total_freshwater_withdrawal__km_3__yr_ VARCHAR, agricultural_use__m_3__p_yr__in__percentage_ VARCHAR)

SELECT COUNT(total_freshwater_withdrawal__km_3__yr_) FROM table_15909409_2 WHERE agricultural_use__m_3__p_yr__in__percentage_ = '428(62%)';


Question: What is the total number of cases handled by attorney 'Alice Smith'?

CREATE TABLE cases (case_id INT, attorney_name TEXT); INSERT INTO cases (case_id, attorney_name) VALUES (1, 'Alice Smith'), (2, 'Bob Johnson'), (3, 'Bob Johnson'), (4, 'Charlie Brown');

SELECT COUNT(*) FROM cases WHERE attorney_name = 'Alice Smith';


Question: Generate PostgreSQL SQL for: What type has an unspecified species and less than 367 genes?

CREATE TABLE table_name_65 (type VARCHAR, species VARCHAR, genes VARCHAR)

SELECT type FROM table_name_65 WHERE species = 'unspecified' AND genes < 367;


Question: Generate PostgreSQL SQL for: What is every denomination for the school Seymour college?

CREATE TABLE table_22043925_1 (denomination VARCHAR, school VARCHAR)

SELECT denomination FROM table_22043925_1 WHERE school = 'Seymour College';


Question: Generate PostgreSQL SQL for: Which assets did not incur any fault log? List the asset model.

CREATE TABLE Fault_Log (asset_model VARCHAR, asset_id VARCHAR); CREATE TABLE Assets (asset_model VARCHAR, asset_id VARCHAR)

SELECT asset_model FROM Assets WHERE NOT asset_id IN (SELECT asset_id FROM Fault_Log);


Question: Generate PostgreSQL SQL for: where is the private/presbyterian institute

CREATE TABLE table_1974632_1 (location VARCHAR, type VARCHAR)

SELECT location FROM table_1974632_1 WHERE type = 'Private/Presbyterian';


Question: Generate PostgreSQL SQL for: What was the date of death for a rank below 14 and age of 103 years, 148 days?

CREATE TABLE table_name_61 (death_date VARCHAR, rank VARCHAR, age__as_of_1_february_2014_ VARCHAR)

SELECT death_date FROM table_name_61 WHERE rank < 14 AND age__as_of_1_february_2014_ = '103 years, 148 days';


Question: What is the percentage of successful space missions by continent in 2020?

CREATE TABLE Space_Missions (mission_date DATE, continent VARCHAR(255), success BOOLEAN); INSERT INTO Space_Missions (mission_date, continent, success) VALUES ('2020-01-01', 'North America', TRUE), ('2020-02-01', 'Asia', FALSE), ('2020-03-01', 'Europe', TRUE), ('2020-04-01', 'North America', TRUE), ('2020-05-01', 'Africa', FALSE);

SELECT continent, (COUNT(success) FILTER (WHERE success = TRUE) * 100.0 / COUNT(*)) AS success_percentage FROM Space_Missions WHERE YEAR(mission_date) = 2020 GROUP BY continent;


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

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

SELECT count(*) FROM (SELECT '92233720368547758.07'::money * 2::float8) AS _sub;


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

CREATE FUNCTION isneq(upc, ean13)
	RETURNS boolean
	AS 'int8eq'
	LANGUAGE 'internal'
	IMMUTABLE STRICT
	PARALLEL SAFE;

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


Question: Generate PostgreSQL SQL for: Who took third-place when there were 4 total wins?

CREATE TABLE table_17632217_2 (third_place VARCHAR, total_wins VARCHAR)

SELECT third_place FROM table_17632217_2 WHERE total_wins = 4;


Question: What is the number of mental health campaigns in Rio de Janeiro per month in 2019?

CREATE TABLE campaigns (campaign_id INT, campaign_name TEXT, city TEXT, start_date DATE, end_date DATE); INSERT INTO campaigns (campaign_id, campaign_name, city, start_date, end_date) VALUES (1, 'Healthy Minds', 'Rio de Janeiro', '2019-05-01', '2020-04-30');

SELECT EXTRACT(MONTH FROM start_date) as month, COUNT(*) as num_campaigns FROM campaigns WHERE city = 'Rio de Janeiro' AND EXTRACT(YEAR FROM start_date) = 2019 GROUP BY month ORDER BY month;


Question: What is the total value of all loans issued to customers in London?

CREATE TABLE customers (id INT, name VARCHAR(50), city VARCHAR(50)); INSERT INTO customers (id, name, city) VALUES (1, 'John Doe', 'London'); CREATE TABLE loans (id INT, customer_id INT, product VARCHAR(50), quantity INT, interest_rate DECIMAL(10,2), loaned_at TIMESTAMP); INSERT INTO loans (id, customer_id, product, quantity, interest_rate, loaned_at) VALUES (1, 1, 'Car Loan', 10000, 0.05, NOW());

SELECT SUM(l.quantity * l.interest_rate) as total_value FROM loans l INNER JOIN customers c ON l.customer_id = c.id WHERE c.city = 'London';


Question: Which graduate students have not received any research grants in the past two years?

CREATE TABLE students (student_id INT, name TEXT); INSERT INTO students (student_id, name) VALUES (1, 'Alice Johnson'), (2, 'Bob Brown'), (3, 'Claire White'); CREATE TABLE grants (grant_id INT, student_id INT, year INT, amount INT); INSERT INTO grants (grant_id, student_id, year, amount) VALUES (1, 1, 2021, 5000), (2, 2, 2022, 15000), (3, 1, 2023, 20000);

SELECT s.name FROM students s LEFT JOIN grants g ON s.student_id = g.student_id AND g.year BETWEEN 2021 AND 2023 WHERE g.grant_id IS NULL;


Question: What is the total number of fish for each location, grouped by location, from the 'fish_stock' and 'sustainable_seafood' tables, including those with no records in either table?

CREATE TABLE fish_stock (location VARCHAR(255), num_fish INT); CREATE TABLE sustainable_seafood (location VARCHAR(255), num_fish INT); INSERT INTO fish_stock (location, num_fish) VALUES ('Location A', 500), ('Location B', 600); INSERT INTO sustainable_seafood (location, num_fish) VALUES ('Location A', 450), ('Location B', 650); CREATE TABLE all_locations (location VARCHAR(255)); INSERT INTO all_locations (location) VALUES ('Location A'), ('Location B'), ('Location C');

SELECT coalesce(f.location, l.location) as location, SUM(coalesce(f.num_fish, 0) + coalesce(s.num_fish, 0)) FROM all_locations l LEFT JOIN fish_stock f ON l.location = f.location LEFT JOIN sustainable_seafood s ON l.location = s.location GROUP BY coalesce(f.location, l.location);


Question: Insert a new record into the 'community_education' table with id 4, program 'Wildlife Conservation', and attendance 50.

CREATE TABLE community_education (id INT, program VARCHAR(255), attendance INT); INSERT INTO community_education (id, program, attendance) VALUES (1, 'Biodiversity', 30), (2, 'Climate Change', 40), (3, 'Habitat Restoration', 60);

INSERT INTO community_education (id, program, attendance) VALUES (4, 'Wildlife Conservation', 50);


Question: Generate PostgreSQL SQL for: What was the urban settlement when the city / municipality was kovin?

CREATE TABLE table_2562572_7 (urban_settlement VARCHAR, city___municipality VARCHAR)

SELECT urban_settlement FROM table_2562572_7 WHERE city___municipality = 'Kovin';


Question: Delete all records from the "audience_demographics" table where the "age" is less than 18

CREATE TABLE audience_demographics (id INT PRIMARY KEY, age INT, country VARCHAR(255), gender VARCHAR(255));

DELETE FROM audience_demographics WHERE age < 18;


Question: What is the failure rate for SpaceX missions?

CREATE TABLE space_missions (mission_id INT, mission_year INT, mission_status VARCHAR(10), mission_company VARCHAR(100));

SELECT mission_company, COUNT(*) * 100.0 / (SELECT COUNT(*) FROM space_missions WHERE mission_company = 'SpaceX') AS failure_rate FROM space_missions WHERE mission_status = 'failed' AND mission_company = 'SpaceX' GROUP BY mission_company;


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

INSERT INTO tbl_include_unique2 SELECT 1, 2, 3*x, box('4,4,4,4') FROM generate_series(1,10) AS x;

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


Question: Generate PostgreSQL SQL for: What is the nationality of Shaun Sabol?

CREATE TABLE table_name_94 (nationality VARCHAR, player VARCHAR)

SELECT nationality FROM table_name_94 WHERE player = 'shaun sabol';


Question: Generate PostgreSQL SQL for: Name the tries when tries against were 41, try bonus was 6, and had 317 points.

CREATE TABLE table_name_35 (tries_for VARCHAR, points_against VARCHAR, try_bonus VARCHAR, tries_against VARCHAR)

SELECT tries_for FROM table_name_35 WHERE try_bonus = '6' AND tries_against = '41' AND points_against = '317';


Question: Generate PostgreSQL SQL for: How many games had fewer than 118 opponents and more than 109 net points with an opponent of Washington?

CREATE TABLE table_name_37 (game VARCHAR, opponent VARCHAR, opponents VARCHAR, nets_points VARCHAR)

SELECT COUNT(game) FROM table_name_37 WHERE opponents < 118 AND nets_points > 109 AND opponent = 'washington';


Question: Generate PostgreSQL SQL for: what is the sponsor of motorola

CREATE TABLE table_name_12 (team VARCHAR, sponsor VARCHAR)

SELECT team FROM table_name_12 WHERE sponsor = 'motorola';


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

SELECT '=' ~ '[[:punct:]]' COLLATE PG_C_UTF8; -- symbols are punctuation in posix
SELECT 'a8a' ~ '[[:digit:]]' COLLATE PG_C_UTF8;

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

SELECT count(*) FROM (SELECT '=' ~ '[[:punct:]]' COLLATE PG_C_UTF8; -- symbols are punctuation in posix
SELECT 'a8a' ~ '[[:digit:]]' COLLATE PG_C_UTF8) AS _sub;


Question: Generate PostgreSQL SQL for: What is the highest NFL Draft that has jeff robinson as the player, with an overall pick less than 98?

CREATE TABLE table_name_47 (nfl_draft INTEGER, player VARCHAR, overall_pick VARCHAR)

SELECT MAX(nfl_draft) FROM table_name_47 WHERE player = 'jeff robinson' AND overall_pick < 98;


Question: Generate PostgreSQL SQL for: What are the names of people in ascending alphabetical order?


Question: How many unique countries are represented in the database?

CREATE TABLE artists (id INT, name TEXT, country TEXT); INSERT INTO artists (id, name, country) VALUES (1, 'Eminem', 'USA'), (2, 'The Beatles', 'UK'), (3, 'Rammstein', 'Germany');

SELECT COUNT(DISTINCT country) FROM artists;


Question: PostgreSQL regression test 'float8': Write the SELECT query (example 126).

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

SELECT count(*) FROM (SELECT asinh(float8 'nan')) AS _sub;


Question: How many electronic music tracks were sold through online platforms in Q1 2022?

CREATE TABLE tracks (id INT, title VARCHAR(255), genre VARCHAR(255), platform VARCHAR(255), sales INT); INSERT INTO tracks (id, title, genre, platform, sales) VALUES (1, 'Electricity', 'Electronic', 'iTunes', 150);

SELECT SUM(sales) FROM tracks WHERE genre = 'Electronic' AND platform IN ('iTunes', 'Spotify', 'Google Play') AND YEAR(id) = 2022 AND QUARTER(id) = 1;


Question: Generate PostgreSQL SQL for: What's the title of the episode with series number 36?

CREATE TABLE table_28146944_2 (title VARCHAR, no_in_series VARCHAR)

SELECT title FROM table_28146944_2 WHERE no_in_series = 36;


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

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

SELECT count(*) FROM (select '@ + 1'::jsonpath) AS _sub;


Question: What is the total investment in the 'Technology' industry for projects started on or before 2021?

CREATE TABLE EconomicDiversification (id INT, project_id INT, business_name VARCHAR(50), industry VARCHAR(50), investment DECIMAL(10,2), start_date DATE, end_date DATE); INSERT INTO EconomicDiversification (id, project_id, business_name, industry, investment, start_date, end_date) VALUES (1, 1, 'Green Energy Solutions', 'Renewable Energy', 75000.00, '2021-04-01', '2022-03-31'); INSERT INTO EconomicDiversification (id, project_id, business_name, industry, investment, start_date, end_date) VALUES (2, 2, 'Local Food Market', 'Technology', 35000.00, '2021-01-01', '2023-12-31');

SELECT industry, SUM(investment) FROM EconomicDiversification WHERE start_date <= '2021-12-31' AND industry = 'Technology' GROUP BY industry;


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

select sum(null::numeric) from generate_series(1,3);

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

SELECT count(*) FROM (select sum(null::numeric) from generate_series(1,3)) AS _sub;


Question: Generate PostgreSQL SQL for: Who was the Home team in Tie #23?

CREATE TABLE table_name_80 (home_team VARCHAR, tie_no VARCHAR)

SELECT home_team FROM table_name_80 WHERE tie_no = 23;


Question: What is the maximum energy price for the 'Central' region in April 2022?

CREATE TABLE energy_prices (id INT, region VARCHAR(50), price FLOAT, date DATE); INSERT INTO energy_prices (id, region, price, date) VALUES (1, 'Central', 70.5, '2022-04-01');

SELECT region, MAX(price) AS max_price FROM energy_prices WHERE date BETWEEN '2022-04-01' AND '2022-04-30' AND region = 'Central' GROUP BY region;


Question: Identify the programs with no donations in 2023.

CREATE TABLE Programs (ProgramID INT, ProgramName TEXT, DonationAmount DECIMAL(10,2)); INSERT INTO Programs (ProgramID, ProgramName, DonationAmount) VALUES (1, 'Healthcare', 1000.00), (2, 'Arts & Culture', 500.00), (3, 'Environment', 2000.00), (4, 'Social Services', 750.00); CREATE TABLE Donations (DonationID INT, DonorID INT, ProgramID INT, DonationAmount DECIMAL(10,2), DonationDate DATE); INSERT INTO Donations (DonationID, DonorID, ProgramID, DonationAmount, DonationDate) VALUES (1, 1, 1, 100.00, '2022-01-01'), (2, 2, 2, 10.00, '2022-02-03'), (3, 3, 3, 200.00, '2022-12-25');

SELECT Programs.ProgramID, Programs.ProgramName FROM Programs LEFT JOIN Donations ON Programs.ProgramID = Donations.ProgramID WHERE DATE_FORMAT(DonationDate, '%Y') = '2023' AND Donations.DonationID IS NULL;


Question: Generate PostgreSQL SQL for: Who is the opponent with a score of 5–4?

CREATE TABLE table_name_36 (opponent VARCHAR, score VARCHAR)

SELECT opponent FROM table_name_36 WHERE score = '5–4';


Question: Generate PostgreSQL SQL for: Name the high assists for chauncey billups , carmelo anthony (18)

CREATE TABLE table_17355408_4 (high_assists VARCHAR, high_points VARCHAR)

SELECT high_assists FROM table_17355408_4 WHERE high_points = 'Chauncey Billups , Carmelo Anthony (18)';


Question: What is the total length of all tunnels in the state of Texas?

CREATE TABLE Tunnels (id INT, name TEXT, state TEXT, length FLOAT); INSERT INTO Tunnels (id, name, state, length) VALUES (1, 'Houston Tunnel System', 'Texas', 8000.0); INSERT INTO Tunnels (id, name, state, length) VALUES (2, 'Dallas North Tunnel', 'Texas', 3500.0);

SELECT SUM(length) FROM Tunnels WHERE state = 'Texas';


Question: What is the average ticket price for dance events in the city of Chicago?

CREATE TABLE events (name VARCHAR(255), location VARCHAR(255), category VARCHAR(255), price DECIMAL(5,2)); INSERT INTO events (name, location, category, price) VALUES ('Swan Lake', 'Chicago', 'Dance', 95.00), ('The Nutcracker', 'New York', 'Dance', 125.00), ('Hamilton', 'Chicago', 'Theatre', 225.00);

SELECT AVG(price) FROM events WHERE location = 'Chicago' AND category = 'Dance';


Question: Generate PostgreSQL SQL for: What is the tyre when the entrant is sa alfa romeo and the driver is luigi fagioli?

CREATE TABLE table_name_87 (tyre VARCHAR, entrant VARCHAR, driver VARCHAR)

SELECT tyre FROM table_name_87 WHERE entrant = 'sa alfa romeo' AND driver = 'luigi fagioli';


Question: Generate PostgreSQL SQL for: Which Incumbent has a District of California 5?

CREATE TABLE table_name_99 (incumbent VARCHAR, district VARCHAR)

SELECT incumbent FROM table_name_99 WHERE district = 'california 5';


Question: What is the number of volunteers in each age group?

CREATE TABLE Volunteers (id INT, name TEXT, age INT);

SELECT FLOOR(age / 10) * 10 as age_group, COUNT(*) as number_of_volunteers FROM Volunteers GROUP BY age_group;


Question: What is the earliest date an artifact was excavated from 'Site E'?

CREATE TABLE Site (SiteID VARCHAR(10), SiteName VARCHAR(20)); INSERT INTO Site (SiteID, SiteName) VALUES ('E', 'Site E'); CREATE TABLE Excavation (ExcavationID VARCHAR(10), SiteID VARCHAR(10), ExcavationDate DATE); INSERT INTO Excavation (ExcavationID, SiteID, ExcavationDate) VALUES ('1', 'E', '2022-01-01'), ('2', 'E', '2022-02-01'), ('3', 'E', '2022-03-01'), ('4', 'E', '2022-04-01');

SELECT MIN(ExcavationDate) FROM Excavation WHERE SiteID = 'E';


Question: Generate PostgreSQL SQL for: What is the days with rain figure for the city of Santiago de Compostela?

CREATE TABLE table_12837_1 (days_with_rain__year_summer_ VARCHAR, city_town VARCHAR)

SELECT days_with_rain__year_summer_ FROM table_12837_1 WHERE city_town = 'Santiago de Compostela';


Question: Calculate the percentage of emergency incidents in the east region that were responded to within 5 minutes, for each month in the past year.

CREATE TABLE IncidentTimes (id INT, incident_id INT, incident_time TIME); CREATE TABLE EmergencyIncidents (id INT, district_id INT, incident_date DATE, region_id INT); INSERT INTO IncidentTimes (id, incident_id, incident_time) VALUES (1, 1, '12:00:00'), (2, 2, '21:00:00'), (3, 3, '06:00:00'), (4, 4, '18:00:00'); INSERT INTO EmergencyIncidents (id, district_id, incident_date, region_id) VALUES (1, 1, '2021-12-01', 1), (2, 2, '2021-12-02', 1), (3, 3, '2021-12-03', 1), (4, 4, '2021-12-04', 1);

SELECT EXTRACT(MONTH FROM incident_date) as month, region_id, COUNT(*) * 100.0 / SUM(COUNT(*)) OVER (PARTITION BY EXTRACT(MONTH FROM incident_date), region_id) as pct_incidents_within_5_minutes FROM EmergencyIncidents e JOIN IncidentTimes i ON e.id = i.incident_id WHERE incident_time BETWEEN '00:00:00' AND '05:00:00' AND incident_date BETWEEN DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR) AND CURRENT_DATE AND region_id = 2 GROUP BY EXTRACT(MONTH FROM incident_date), region_id;


Question: Generate PostgreSQL SQL for: What was the resting potential with an AP duration of 1.0 and a median giant fiber cell type?

CREATE TABLE table_name_69 (resting_potential__mv_ VARCHAR, ap_duration__ms_ VARCHAR, cell_type VARCHAR)

SELECT resting_potential__mv_ FROM table_name_69 WHERE ap_duration__ms_ = '1.0' AND cell_type = 'median giant fiber';


Question: Insert new records in the satellite_image_analysis table for field 8 with image_quality score 90, taken on 2023-04-01

CREATE TABLE satellite_image_analysis (field_id INT, image_quality INT, image_timestamp DATETIME);

INSERT INTO satellite_image_analysis (field_id, image_quality, image_timestamp) VALUES (8, 90, '2023-04-01');


Question: Generate PostgreSQL SQL for: What is the week 12 nomination that had a week 1 nomination of Maria Maxine and a week 2 nomination of Henri Satu?

CREATE TABLE table_name_1 (week_12 VARCHAR, week_1 VARCHAR, week_2 VARCHAR)

SELECT week_12 FROM table_name_1 WHERE week_1 = 'maria maxine' AND week_2 = 'henri satu';


Question: What was the average donation amount by state in Q1 2022?

CREATE TABLE Donations (id INT, state VARCHAR(2), donation_amount DECIMAL(5,2), donation_date DATE); INSERT INTO Donations (id, state, donation_amount, donation_date) VALUES (1, 'NY', 50.00, '2022-01-01'), (2, 'CA', 100.00, '2022-01-15'), (3, 'TX', 75.00, '2022-03-03');

SELECT AVG(donation_amount) as avg_donation, state FROM Donations WHERE donation_date BETWEEN '2022-01-01' AND '2022-03-31' GROUP BY state;


Question: How many female refugees were assisted by each organization in Africa in 2018?

CREATE TABLE refugees (id INT, organization VARCHAR(255), location VARCHAR(255), assist_date DATE, gender VARCHAR(10), age INT); INSERT INTO refugees (id, organization, location, assist_date, gender, age) VALUES (1, 'UNHCR', 'Africa', '2018-02-12', 'Female', 34), (2, 'Red Cross', 'Africa', '2018-04-01', 'Male', 27), (3, 'Save the Children', 'Africa', '2018-03-21', 'Female', 19), (4, 'World Vision', 'Africa', '2018-05-05', 'Female', 25);

SELECT organization, COUNT(*) as total_female_refugees FROM refugees WHERE location = 'Africa' AND YEAR(assist_date) = 2018 AND gender = 'Female' GROUP BY organization;


Question: Generate PostgreSQL SQL for: How many assists does David Tomlinson have?

CREATE TABLE table_name_71 (assists INTEGER, player VARCHAR)

SELECT SUM(assists) FROM table_name_71 WHERE player = 'david tomlinson';


Question: Generate PostgreSQL SQL for: On what date was the opponent in the final Gwinyai Tongoona?

CREATE TABLE table_name_62 (date VARCHAR, opponent_in_the_final VARCHAR)

SELECT date FROM table_name_62 WHERE opponent_in_the_final = 'gwinyai tongoona';


Question: Generate PostgreSQL SQL for: On what date did the Bills play the Houston Oilers before week 12?

CREATE TABLE table_name_79 (date VARCHAR, week VARCHAR, opponent VARCHAR)

SELECT date FROM table_name_79 WHERE week < 12 AND opponent = 'houston oilers';


Question: What is the percentage of cosmetic products that have a high allergen risk?

CREATE TABLE product_ingredients (product_id INT, allergen_risk TEXT); INSERT INTO product_ingredients (product_id, allergen_risk) VALUES (1, 'low'), (2, 'medium'), (3, 'high'), (4, 'low'), (5, 'medium'), (6, 'high'), (7, 'low'), (8, 'medium'), (9, 'low'), (10, 'high');

SELECT COUNT(*) as total_products, COUNT(*) FILTER (WHERE allergen_risk = 'high') * 100.0 / COUNT(*) as high_risk_percentage FROM product_ingredients;


Question: Generate PostgreSQL SQL for: What is the smallest capacity for Fandok?

CREATE TABLE table_name_84 (capacity INTEGER, team VARCHAR)

SELECT MIN(capacity) FROM table_name_84 WHERE team = 'fandok';


Question: Generate PostgreSQL SQL for: Which club has 16 league goals for a total of 20?

CREATE TABLE table_name_2 (club VARCHAR, league_goals VARCHAR, total VARCHAR)

SELECT club FROM table_name_2 WHERE league_goals = '16' AND total = 20;


Question: What is the landfill capacity for the country of Germany for the year 2025?'

CREATE TABLE country_landfill_capacity (country VARCHAR(20), year INT, capacity INT); INSERT INTO country_landfill_capacity (country, year, capacity) VALUES ('Germany', 2025, 6000000);

SELECT capacity FROM country_landfill_capacity WHERE country = 'Germany' AND year = 2025;


Question: How many electric vehicles are there in each state in the US?

CREATE TABLE us_vehicles (state VARCHAR(20), vehicle_type VARCHAR(20), quantity INT);

SELECT state, vehicle_type, SUM(quantity) AS total_electric_vehicles FROM us_vehicles WHERE vehicle_type = 'electric' GROUP BY state;


Question: Identify the community health workers who speak the same language as their clients, if any.

CREATE TABLE community_health_workers (id INT, name VARCHAR(50), language VARCHAR(20)); INSERT INTO community_health_workers (id, name, language) VALUES (1, 'Jamila Smith', 'English'), (2, 'Pedro Rodriguez', 'Spanish'), (3, 'Thanh Nguyen', 'Vietnamese'); CREATE TABLE clients (id INT, name VARCHAR(50), language VARCHAR(20)); INSERT INTO clients (id, name, language) VALUES (1, 'John Smith', 'English'), (2, 'Maria Garcia', 'Spanish'), (3, 'Tran Nguyen', 'Vietnamese'), (4, 'Alex Johnson', 'Russian');

SELECT chw.name AS worker_name, cl.name AS client_name, chw.language FROM community_health_workers chw, clients cl WHERE chw.language = cl.language;


Question: Generate PostgreSQL SQL for: What is the Atlantic Europe when age is 10,000 years?

CREATE TABLE table_22860_1 (atlantic_europe VARCHAR, age__before_ VARCHAR)

SELECT atlantic_europe FROM table_22860_1 WHERE age__before_ = '10,000 years';


Question: How many public meetings were held by all departments in the month of July for the year 2021?

CREATE TABLE Department (id INT, name VARCHAR(255)); CREATE TABLE Meeting (id INT, department_id INT, datetime DATETIME); INSERT INTO Department (id, name) VALUES (1, 'Education'), (2, 'Healthcare'), (3, 'Transportation'), (4, 'Parks and Recreation'); INSERT INTO Meeting (id, department_id, datetime) VALUES (1, 1, '2021-01-01 10:00:00'), (2, 4, '2021-07-01 14:00:00'), (3, 2, '2021-09-15 09:00:00'), (4, 4, '2021-07-15 11:00:00'), (5, 3, '2021-10-01 16:00:00');

SELECT COUNT(*) FROM Meeting INNER JOIN Department ON Meeting.department_id = Department.id WHERE MONTH(datetime) = 7 AND YEAR(datetime) = 2021;


Question: Generate PostgreSQL SQL for: What is the main use of the structure that was in redfield, arkansas before 2004?

CREATE TABLE table_name_77 (main_use VARCHAR, year VARCHAR, town VARCHAR)

SELECT main_use FROM table_name_77 WHERE year < 2004 AND town = 'redfield, arkansas';


Question: Create a table 'teams' with columns 'name', 'sport', and 'location'

CREATE TABLE athletes (name VARCHAR(100), sport VARCHAR(50), country VARCHAR(50), age INT);

CREATE TABLE teams (name VARCHAR(100), sport VARCHAR(50), location VARCHAR(100));


Question: Generate PostgreSQL SQL for: What is the First Issue date of Bamboo Blade?

CREATE TABLE table_name_89 (first_issue VARCHAR, title VARCHAR)

SELECT first_issue FROM table_name_89 WHERE title = 'bamboo blade';


Question: How much water is conserved in New York through water conservation initiatives?

CREATE TABLE conservation_initiatives (state VARCHAR(20), conservation_amount FLOAT); INSERT INTO conservation_initiatives (state, conservation_amount) VALUES ('New York', 200), ('California', 300), ('Texas', 150);

SELECT conservation_amount FROM conservation_initiatives WHERE state = 'New York';


Question: Generate PostgreSQL SQL for: Which name has notes b and the game of tennis?

CREATE TABLE table_name_13 (name VARCHAR, sport VARCHAR, notes VARCHAR)

SELECT name FROM table_name_13 WHERE sport = 'tennis' AND notes = 'b';


Question: Generate PostgreSQL SQL for: How many draws took place for team Corinthians with more than 5 losses?

CREATE TABLE table_name_81 (drawn VARCHAR, team VARCHAR, lost VARCHAR)

SELECT COUNT(drawn) FROM table_name_81 WHERE team = 'corinthians' AND lost > 5;


Question: Show a query using PostgreSQL contrib extension 'unaccent' (example 14).

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


Question: Generate PostgreSQL SQL for: Who took the winning slot at the Vojens venue?

CREATE TABLE table_name_29 (winners VARCHAR, venue VARCHAR)

SELECT winners FROM table_name_29 WHERE venue = 'vojens';


Question: Calculate the average salinity level in the Pacific and Atlantic oceans.

CREATE TABLE salinity (location VARCHAR(255), year INT, avg_salinity FLOAT);

SELECT location, AVG(avg_salinity) FROM salinity WHERE location IN ('Pacific Ocean', 'Atlantic Ocean') GROUP BY location;


Question: What is the average recycling rate (%) for urban areas in 2019?

CREATE TABLE recycling_rates(region VARCHAR(255), year INT, recycling_rate FLOAT);

SELECT AVG(recycling_rate) FROM recycling_rates WHERE region LIKE '%urban%' AND year = 2019;


Question: Which countries have the most excavation sites?

CREATE TABLE Sites (SiteID INT, Country VARCHAR(50), Type VARCHAR(50)); INSERT INTO Sites (SiteID, Country, Type) VALUES (1, 'Egypt', 'Ancient Ruins'); INSERT INTO Sites (SiteID, Country, Type) VALUES (2, 'Mexico', 'Mayan Temples'); INSERT INTO Sites (SiteID, Country, Type) VALUES (3, 'Peru', 'Incan Fortress'); INSERT INTO Sites (SiteID, Country, Type) VALUES (4, 'Egypt', 'Pyramid'); INSERT INTO Sites (SiteID, Country, Type) VALUES (5, 'Mexico', 'Aztec City'); CREATE TABLE Excavations (ExcavationID INT, Site VARCHAR(50)); INSERT INTO Excavations (ExcavationID, Site) VALUES (1, 'Ancient Ruins'); INSERT INTO Excavations (ExcavationID, Site) VALUES (2, 'Mayan Temples'); INSERT INTO Excavations (ExcavationID, Site) VALUES (3, 'Incan Fortress'); INSERT INTO Excavations (ExcavationID, Site) VALUES (4, 'Pyramid'); INSERT INTO Excavations (ExcavationID, Site) VALUES (5, 'Aztec City');

SELECT S.Country, COUNT(E.Site) AS Excavation_Count FROM Sites S INNER JOIN Excavations E ON S.Site = E.Site GROUP BY S.Country;


Question: What is the average area of land used for farming by indigenous farmers?

CREATE TABLE farmer (id INT PRIMARY KEY, name VARCHAR(50), gender VARCHAR(10), is_indigenous BOOLEAN, area_in_hectares INT); INSERT INTO farmer (id, name, gender, is_indigenous, area_in_hectares) VALUES (1, 'Jamal', 'Male', FALSE, 3000), (2, 'Aisha', 'Female', FALSE, 2500), (3, 'Samir', 'Male', FALSE, 2000), (4, 'Nina', 'Female', TRUE, 5000);

SELECT gender, AVG(area_in_hectares) FROM farmer WHERE is_indigenous = TRUE GROUP BY gender;


Question: Generate PostgreSQL SQL for: WHAT ARE THE RACES WHEN FLAPS ARE ZERO, PODIUMS ARE LARGER THAN 0, SEASON IS 2008, AND POLE SMALLER THAN 1?

CREATE TABLE table_name_93 (races INTEGER, pole VARCHAR, season VARCHAR, flaps VARCHAR, podiums VARCHAR)

SELECT SUM(races) FROM table_name_93 WHERE flaps = 0 AND podiums > 0 AND season = '2008' AND pole < 1;


Question: What is the average number of emergencies handled per day by police stations in districts with low crime rates?

CREATE TABLE district_crime_rates (did INT, rate INT, PRIMARY KEY(did)); CREATE TABLE station_emergencies (eid INT, sid INT, time TIMESTAMP, PRIMARY KEY(eid), FOREIGN KEY(sid) REFERENCES stations(sid));

SELECT AVG(COUNT(se.eid) / TIMESTAMPDIFF(DAY, (SELECT MIN(time) FROM station_emergencies se2 WHERE se2.sid = se.sid), (SELECT MAX(time) FROM station_emergencies se3 WHERE se3.sid = se.sid))) FROM station_emergencies se JOIN districts d ON se.sid IN (SELECT sid FROM stations WHERE did = d.did) WHERE d.rate < (SELECT AVG(rate) FROM district_crime_rates);


Question: What was the total revenue for the state of Colorado in the second quarter of 2022?

CREATE TABLE sales (id INT, state VARCHAR(50), quarter INT, revenue FLOAT); INSERT INTO sales (id, state, quarter, revenue) VALUES (1, 'California', 1, 25000.0), (2, 'California', 2, 30000.0), (3, 'Colorado', 1, 20000.0), (4, 'Colorado', 2, 28000.0);

SELECT SUM(revenue) FROM sales WHERE state = 'Colorado' AND quarter = 2;


Question: What is the average age of patients who received therapy sessions in the state of California?

CREATE TABLE patients (patient_id INT, age INT, gender VARCHAR(20), state VARCHAR(20)); INSERT INTO patients (patient_id, age, gender, state) VALUES (1, 35, 'Female', 'California'); INSERT INTO patients (patient_id, age, gender, state) VALUES (2, 42, 'Male', 'Texas'); CREATE TABLE therapy_sessions (session_id INT, patient_id INT, therapist_id INT, session_date DATE); INSERT INTO therapy_sessions (session_id, patient_id, therapist_id, session_date) VALUES (1, 1, 3, '2021-03-15');

SELECT AVG(patients.age) FROM patients INNER JOIN therapy_sessions ON patients.patient_id = therapy_sessions.patient_id WHERE patients.state = 'California';


Question: pgTAP test for Pgtap--1.1.0--1.2.0 (assertion 67).

-- isnt_normal_function( schema, function )
CREATE OR REPLACE FUNCTION isnt_normal_function( NAME, NAME )
RETURNS TEXT AS $$
    SELECT _func_compare(
        $1, $2, NOT _type_func('f', $1, $2),
        'Function ' || quote_ident($1) || '.' || quote_ident($2) || '() should not be a normal function'
    );
$$ LANGUAGE sql;

Explanation: SQL assertion from pgTAP test suite for Pgtap--1.1.0--1.2.0.


Question: List all clinical trials conducted for oncology drugs in Mexico, along with their approval status and completion date.

CREATE TABLE clinical_trials (id INT, drug_name VARCHAR(255), trial_location VARCHAR(255), trial_status VARCHAR(255), completion_date DATE); INSERT INTO clinical_trials (id, drug_name, trial_location, trial_status, completion_date) VALUES (1, 'DrugB', 'Mexico', 'Approved', '2018-12-31'); INSERT INTO clinical_trials (id, drug_name, trial_location, trial_status, completion_date) VALUES (2, 'DrugC', 'Mexico', 'Pending', '2021-03-01');

SELECT * FROM clinical_trials WHERE trial_location = 'Mexico' AND drug_name LIKE '%oncology%' AND (trial_status = 'Approved' OR trial_status = 'Pending');


Question: Generate PostgreSQL SQL for: What is the type of the match with a win result and Michael Gomez as the opponent?

CREATE TABLE table_name_79 (type VARCHAR, res VARCHAR, opponent VARCHAR)

SELECT type FROM table_name_79 WHERE res = 'win' AND opponent = 'michael gomez';


Question: Find the number of new threat intelligence reports created per day in the last week.

CREATE TABLE threat_intelligence (report_id INT, creation_date DATE); INSERT INTO threat_intelligence VALUES (1, '2021-07-01'), (2, '2021-07-02'), (3, '2021-07-02');

SELECT creation_date, COUNT(*) OVER (PARTITION BY creation_date) FROM threat_intelligence WHERE creation_date >= CURRENT_DATE - INTERVAL '7 days';


Question: What is the maximum donation amount received from a single donor in the last month?

CREATE TABLE Donations (donorID INT, donationDate DATE, donationAmount DECIMAL(10,2)); INSERT INTO Donations (donorID, donationDate, donationAmount) VALUES (1, '2022-03-02', 150.50), (2, '2022-03-15', 200.00), (3, '2022-03-27', 125.75);

SELECT MAX(donationAmount) FROM Donations WHERE donationDate >= '2022-03-01' AND donationDate <= '2022-03-31';


Question: Generate PostgreSQL SQL for: What was the highest grid for Patrick Carpentier?

CREATE TABLE table_name_77 (grid INTEGER, driver VARCHAR)

SELECT MAX(grid) FROM table_name_77 WHERE driver = 'patrick carpentier';


Question: What is the average claim amount for policyholders living in 'California'?

CREATE TABLE policyholders (id INT, name TEXT, state TEXT); INSERT INTO policyholders (id, name, state) VALUES (1, 'John Doe', 'California'); INSERT INTO policyholders (id, name, state) VALUES (2, 'Jane Smith', 'Texas');   CREATE TABLE claims (id INT, policyholder_id INT, amount INT); INSERT INTO claims (id, policyholder_id, amount) VALUES (1, 1, 5000); INSERT INTO claims (id, policyholder_id, amount) VALUES (2, 1, 2000); INSERT INTO claims (id, policyholder_id, amount) VALUES (3, 2, 3000);

SELECT AVG(amount) FROM claims JOIN policyholders ON claims.policyholder_id = policyholders.id WHERE policyholders.state = 'California';


Question: List the names of countries that have both eco-friendly hotels and cultural heritage sites, but no virtual tours.

CREATE TABLE eco_hotels (hotel_id INT, country VARCHAR(20), name VARCHAR(50)); INSERT INTO eco_hotels (hotel_id, country, name) VALUES (1, 'Germany', 'Green Hotel'), (2, 'Portugal', 'Eco Lodge'), (3, 'France', 'Sustainable Suites'); CREATE TABLE cultural_sites (site_id INT, country VARCHAR(20), type VARCHAR(20)); INSERT INTO cultural_sites (site_id, country, type) VALUES (1, 'Germany', 'heritage'), (2, 'Portugal', 'heritage'), (3, 'France', 'heritage'); CREATE TABLE virtual_tours (tour_id INT, country VARCHAR(20), type VARCHAR(20)); INSERT INTO virtual_tours (tour_id, country, type) VALUES (1, 'Germany', 'virtual'), (2, 'Portugal', 'virtual');

(SELECT country FROM eco_hotels WHERE name IS NOT NULL) INTERSECT (SELECT country FROM cultural_sites WHERE type = 'heritage') EXCEPT (SELECT country FROM virtual_tours WHERE type = 'virtual');


Question: Generate PostgreSQL SQL for: What was the location when the stolen ends is 12 and shot pct is 77%?

CREATE TABLE table_1543845_63 (locale VARCHAR, stolen_ends VARCHAR, shot_pct VARCHAR)

SELECT locale FROM table_1543845_63 WHERE stolen_ends = 12 AND shot_pct = '77%';


Question: List all space missions that have involved international collaboration, along with the participating countries.

CREATE TABLE space_missions (id INT, mission_name VARCHAR(50), launch_date DATE, country_of_origin VARCHAR(50)); INSERT INTO space_missions (id, mission_name, launch_date, country_of_origin) VALUES (1, 'Artemis I', '2022-08-29', 'USA'); INSERT INTO space_missions (id, mission_name, launch_date, country_of_origin) VALUES (2, 'ExoMars', '2016-03-14', 'Europe');

SELECT mission_name, country_of_origin FROM space_missions WHERE country_of_origin <> 'USA' AND country_of_origin <> (SELECT country_of_origin FROM space_missions WHERE mission_name = 'Artemis I');


Question: Find the average rating of movies directed by female directors.

CREATE TABLE movies (id INT, title VARCHAR(255), release_year INT, director_gender VARCHAR(10), rating DECIMAL(2,1)); INSERT INTO movies (id, title, release_year, director_gender, rating) VALUES (1, 'Movie1', 2020, 'Female', 8.2), (2, 'Movie2', 2019, 'Male', 7.1), (3, 'Movie3', 2018, 'Female', 9.0);

SELECT AVG(rating) FROM movies WHERE director_gender = 'Female';


Question: Generate PostgreSQL SQL for: What was the 1st leg that had a 4-2 aggregate?

CREATE TABLE table_name_33 (aggregate VARCHAR)

SELECT 1 AS st_leg FROM table_name_33 WHERE aggregate = '4-2';


Question: Generate PostgreSQL SQL for: What was the course type on 22 May?

CREATE TABLE table_name_13 (type VARCHAR, date VARCHAR)

SELECT type FROM table_name_13 WHERE date = '22 may';


Question: Generate PostgreSQL SQL for: What kind of Replaced has a Outgoing manager of guillermo sanguinetti?

CREATE TABLE table_name_95 (replaced_by VARCHAR, outgoing_manager VARCHAR)

SELECT replaced_by FROM table_name_95 WHERE outgoing_manager = 'guillermo sanguinetti';


Question: Identify customers who have made transactions in both the 'Stocks' and 'Bonds' categories.

CREATE TABLE transactions (id INT, customer_id INT, category VARCHAR(50), amount DECIMAL(10,2)); INSERT INTO transactions (id, customer_id, category, amount) VALUES (1, 101, 'Stocks', 500.00), (2, 102, 'Bonds', 350.00), (3, 103, 'Stocks', 700.00), (4, 104, 'Bonds', 600.00), (5, 105, 'Stocks', 400.00), (6, 105, 'Bonds', 800.00);

SELECT customer_id FROM transactions WHERE category = 'Stocks' INTERSECT SELECT customer_id FROM transactions WHERE category = 'Bonds';