Question: What is the total quantity of each ingredient used, broken down by day?

CREATE TABLE ingredient_usage (ingredient_name VARCHAR(50), sale_date DATE, quantity INT); INSERT INTO ingredient_usage (ingredient_name, sale_date, quantity) VALUES ('Lettuce', '2023-03-01', 200), ('Tomatoes', '2023-03-01', 300), ('Cheese', '2023-03-01', 400), ('Lettuce', '2023-03-02', 250), ('Tomatoes', '2023-03-02', 350), ('Cheese', '2023-03-02', 450);

SELECT sale_date, ingredient_name, SUM(quantity) FROM ingredient_usage GROUP BY sale_date, ingredient_name;


Question: Generate PostgreSQL SQL for: What was the score of the match that took place in the playoff round?

CREATE TABLE table_name_31 (score VARCHAR, round VARCHAR)

SELECT score FROM table_name_31 WHERE round = 'playoff';


Question: Generate PostgreSQL SQL for: What is Place, when To Par is less than 15, and when Score is 76-72-75-71=294?

CREATE TABLE table_name_59 (place VARCHAR, to_par VARCHAR, score VARCHAR)

SELECT place FROM table_name_59 WHERE to_par < 15 AND score = 76 - 72 - 75 - 71 = 294;


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

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

SELECT count(*) FROM (SELECT to_char('infinity'::interval, 'YYYY')) AS _sub;


Question: What is the count of new hires in the last 3 months, by recruiter and source?

CREATE TABLE Recruitment (RecruiterID int, RecruiterName varchar(50), CandidateSource varchar(50), NewHire bit, HireDate date); INSERT INTO Recruitment (RecruiterID, RecruiterName, CandidateSource, NewHire, HireDate) VALUES (1, 'Alice', 'Job Board', 1, '2022-01-01'), (2, 'Bob', 'Referral', 1, '2022-02-01'), (3, 'Charlie', 'Career Fair', 0, '2022-03-01');

SELECT Recruitment.RecruiterName, Recruitment.CandidateSource, COUNT(CASE WHEN Recruitment.NewHire = 1 AND Recruitment.HireDate >= DATEADD(month, -3, GETDATE()) THEN 1 ELSE NULL END) as Count_of_New_Hires FROM Recruitment GROUP BY Recruitment.RecruiterName, Recruitment.CandidateSource;


Question: Which underwriters have processed fewer than 100 policies in the last month?

CREATE TABLE underwriter (underwriter_id INT, name VARCHAR(50)); CREATE TABLE policy (policy_id INT, underwriter_id INT, processing_date DATE);

SELECT underwriter.name FROM underwriter LEFT JOIN (SELECT underwriter_id, COUNT(*) as policy_count FROM policy WHERE processing_date >= DATEADD(MONTH, -1, GETDATE()) GROUP BY underwriter_id) AS policy_count ON underwriter.underwriter_id = policy_count.underwriter_id WHERE policy_count.policy_count IS NULL OR policy_count.policy_count < 100;


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

select age(timestamp 'infinity', timestamp 'infinity');

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

SELECT count(*) FROM (select age(timestamp 'infinity', timestamp 'infinity')) AS _sub;


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

-- function in subselect
select * from rngfunc2 where f2 in (select f2 from rngfunct(rngfunc2.rngfuncid) z where z.rngfuncid = rngfunc2.rngfuncid) ORDER BY 1,2;

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


Question: What is the total amount of socially responsible loans issued by AltruisticBank in Q1 2021?

CREATE TABLE AltruisticBank (id INT, loan_type VARCHAR(20), loan_amount INT, issue_date DATE); INSERT INTO AltruisticBank (id, loan_type, loan_amount, issue_date) VALUES (1, 'Socially Responsible', 7000, '2021-01-05');

SELECT SUM(loan_amount) FROM AltruisticBank WHERE loan_type = 'Socially Responsible' AND QUARTER(issue_date) = 1 AND YEAR(issue_date) = 2021;


Question: What vehicles passed the 'Pedestrian Safety Test' in the SafetyTesting table?

CREATE TABLE SafetyTesting (Id INT, Vehicle VARCHAR(50), Test VARCHAR(50), Result VARCHAR(50)); INSERT INTO SafetyTesting (Id, Vehicle, Test, Result) VALUES (1, 'Volvo XC60', 'Frontal Crash Test', 'Passed'), (2, 'Nissan Leaf', 'Pedestrian Safety Test', 'Passed');

SELECT Vehicle FROM SafetyTesting WHERE Test = 'Pedestrian Safety Test' AND Result = 'Passed';


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

select jsonb_populate_record_valid(NULL::jsb_ia, '{"a": [1, 2]}');

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

SELECT count(*) FROM (select jsonb_populate_record_valid(NULL::jsb_ia, '{"a": [1, 2]}')) AS _sub;


Question: Generate PostgreSQL SQL for: Show the id, the account name, and other account details for all accounts by the customer with first name 'Meaghan'.

CREATE TABLE Accounts (account_id VARCHAR, date_account_opened VARCHAR, account_name VARCHAR, other_account_details VARCHAR, customer_id VARCHAR); CREATE TABLE Customers (customer_id VARCHAR, customer_first_name VARCHAR)

SELECT T1.account_id, T1.date_account_opened, T1.account_name, T1.other_account_details FROM Accounts AS T1 JOIN Customers AS T2 ON T1.customer_id = T2.customer_id WHERE T2.customer_first_name = 'Meaghan';


Question: How many Arctic fox sightings have been recorded each year for the last 5 years?

CREATE TABLE arctic_fox_sightings (id INT, year INT, sightings INT);

SELECT year, SUM(sightings) FROM arctic_fox_sightings WHERE year BETWEEN (YEAR(CURRENT_DATE) - 5) AND YEAR(CURRENT_DATE) GROUP BY year;


Question: Generate PostgreSQL SQL for: Which Margin has a Dist (f) larger than 10, and a Race of king george vi & queen elizabeth stakes?

CREATE TABLE table_name_33 (margin VARCHAR, dist__f_ VARCHAR, race VARCHAR)

SELECT margin FROM table_name_33 WHERE dist__f_ > 10 AND race = 'king george vi & queen elizabeth stakes';


Question: Insert new record for student 'Sara Lee' with ID 456 and disability 'Physical'

CREATE TABLE Students (StudentID INT PRIMARY KEY, Name VARCHAR(50), Disability VARCHAR(20));

INSERT INTO Students (StudentID, Name, Disability) VALUES (456, 'Sara Lee', 'Physical');


Question: Which mine has the lowest labor productivity?

CREATE TABLE mines (mine_id INT, name TEXT, location TEXT, productivity FLOAT); INSERT INTO mines (mine_id, name, location, productivity) VALUES (1, 'ABC Mine', 'USA', 1200), (2, 'DEF Mine', 'Canada', 800);

SELECT name, MIN(productivity) FROM mines;


Question: What is the average production budget for action movies released between 2000 and 2010?

CREATE TABLE movies (id INT, title VARCHAR(100), genre VARCHAR(50), release_year INT, production_budget INT); INSERT INTO movies (id, title, genre, release_year, production_budget) VALUES (1, 'MovieA', 'Action', 2005, 15000000); INSERT INTO movies (id, title, genre, release_year, production_budget) VALUES (2, 'MovieB', 'Action', 2002, 20000000);

SELECT AVG(production_budget) FROM movies WHERE genre = 'Action' AND release_year BETWEEN 2000 AND 2010;


Question: PL/pgSQL test: Plpython Spi (example 41).

CREATE OR REPLACE FUNCTION plan_composite_args() RETURNS test_composite_type AS $$
plan = plpy.prepare("select $1 as c1", ["test_composite_type"])
res = plpy.execute(plan, [{"a1": 3, "a2": "label"}])
return res[0]["c1"]
$$ LANGUAGE plpython3u;

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


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

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

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


Question: What is the daily revenue for each menu category in the last 30 days?

CREATE TABLE daily_sales (sale_date DATE, menu_category VARCHAR(255), revenue INT);

SELECT sale_date, menu_category, SUM(revenue) as daily_revenue FROM daily_sales WHERE sale_date BETWEEN DATEADD(day, -30, GETDATE()) AND GETDATE() GROUP BY sale_date, menu_category;


Question: What is the most common type of crime in Paris, and how many times did it occur?

CREATE TABLE crimes (id INT, city VARCHAR(255), date DATE, type VARCHAR(255), description TEXT); INSERT INTO crimes (id, city, date, type, description) VALUES (1, 'Paris', '2022-01-01', 'Theft', 'Bicycle theft'), (2, 'Paris', '2022-02-01', 'Vandalism', 'Graffiti');

SELECT type, COUNT(*) FROM crimes WHERE city = 'Paris' GROUP BY type ORDER BY COUNT(*) DESC LIMIT 1;


Question: Generate PostgreSQL SQL for: How many different results are there for the battles?

SELECT COUNT(DISTINCT RESULT) FROM battle;


Question: Generate PostgreSQL SQL for: What location is listed from 2005-2010?

CREATE TABLE table_26476336_2 (location VARCHAR, years VARCHAR)

SELECT location FROM table_26476336_2 WHERE years = '2005-2010';


Question: How many players are in each team?

CREATE TABLE EsportsTeams (TeamID INT, TeamName TEXT, Location TEXT); CREATE TABLE EsportsPlayers (PlayerID INT, PlayerName TEXT, TeamID INT); INSERT INTO EsportsTeams (TeamID, TeamName, Location) VALUES (1, 'TeamA', 'CityA'), (2, 'TeamB', 'CityB'), (3, 'TeamC', 'CityC'); INSERT INTO EsportsPlayers (PlayerID, PlayerName, TeamID) VALUES (1, 'Player1', 1), (2, 'Player2', 1), (3, 'Player3', 2), (4, 'Player4', 3);

SELECT TeamID, COUNT(*) FROM EsportsPlayers GROUP BY TeamID;


Question: Generate PostgreSQL SQL for: What european country had more than 14 goals, and 52 538 avg att?

CREATE TABLE table_name_83 (europe VARCHAR, goals VARCHAR, avgatt VARCHAR)

SELECT europe FROM table_name_83 WHERE goals > 14 AND avgatt = '52 538';


Question: List the states with the most and fewest number of workplaces that have experienced labor disputes in the past year.

CREATE TABLE WorkplaceDisputes (State TEXT, Disputes INT); INSERT INTO WorkplaceDisputes (State, Disputes) VALUES ('California', 150), ('Texas', 100), ('New York', 200), ('Florida', 50);

SELECT State, Disputes FROM WorkplaceDisputes WHERE Disputes = (SELECT MAX(Disputes) FROM WorkplaceDisputes) OR Disputes = (SELECT MIN(Disputes) FROM WorkplaceDisputes);


Question: How many permits were issued for commercial buildings in Los Angeles between 2018 and 2020?

CREATE TABLE building_permits (permit_id INT, building_type VARCHAR(20), city VARCHAR(20), issue_date DATE); INSERT INTO building_permits (permit_id, building_type, city, issue_date) VALUES (4, 'Commercial', 'Los Angeles', '2018-04-01'), (5, 'Residential', 'Los Angeles', '2019-07-15'), (6, 'Commercial', 'Los Angeles', '2020-11-05');

SELECT COUNT(*) FROM building_permits WHERE building_type = 'Commercial' AND city = 'Los Angeles' AND issue_date BETWEEN '2018-01-01' AND '2020-12-31';


Question: What is the minimum and maximum salary for each position in the Mining department?

CREATE TABLE Employees(id INT, name VARCHAR(50), department VARCHAR(50), position VARCHAR(50), salary FLOAT, full_time BOOLEAN, gender VARCHAR(50), start_date DATE);

SELECT position, MIN(salary) AS Min_Salary, MAX(salary) AS Max_Salary FROM Employees WHERE department = 'Mining' GROUP BY position;


Question: Generate PostgreSQL SQL for: What player has the score of 67-72=139?

CREATE TABLE table_name_58 (player VARCHAR, score VARCHAR)

SELECT player FROM table_name_58 WHERE score = 67 - 72 = 139;


Question: Generate PostgreSQL SQL for: What rank was the team from Australia?

CREATE TABLE table_name_77 (rank VARCHAR, country VARCHAR)

SELECT COUNT(rank) FROM table_name_77 WHERE country = 'australia';


Question: Find the digital assets that were launched most recently, along with the country they were launched in, in descending order.

CREATE TABLE DigitalAssets (AssetID int, AssetName varchar(50), LaunchDate date); INSERT INTO DigitalAssets (AssetID, AssetName, LaunchDate) VALUES (1, 'Asset1', '2022-01-01'), (2, 'Asset2', '2022-02-01'), (3, 'Asset3', '2022-03-01');

SELECT AssetName, Country, LaunchDate FROM (SELECT AssetName, Country, LaunchDate, ROW_NUMBER() OVER (ORDER BY LaunchDate DESC) as Rank FROM DigitalAssets) as RankedAssets WHERE Rank = 1;


Question: List the carbon pricing schemes and their corresponding carbon prices for the year 2021, sorted by carbon price in descending order.

CREATE TABLE carbon_pricing (scheme VARCHAR(255), year INT, carbon_price FLOAT); INSERT INTO carbon_pricing (scheme, year, carbon_price) VALUES ('ETS', 2021, 30.56);

SELECT * FROM carbon_pricing WHERE year = 2021 ORDER BY carbon_price DESC;


Question: Generate PostgreSQL SQL for: What was the title of series number 56?

CREATE TABLE table_2468961_4 (title VARCHAR, no_in_series VARCHAR)

SELECT title FROM table_2468961_4 WHERE no_in_series = 56;


Question: What is the maximum number of visitors for an exhibition in Chicago in 2020?

CREATE TABLE ExhibitionsChicago (id INT, exhibition_name VARCHAR(30), city VARCHAR(20), year INT, visitor_count INT); INSERT INTO ExhibitionsChicago (id, exhibition_name, city, year, visitor_count) VALUES (1, 'Van Gogh in Chicago', 'Chicago', 2020, 100000), (2, 'Impressionism in Motion', 'Chicago', 2020, 85000), (3, 'Ancient Egypt', 'Chicago', 2020, 120000);

SELECT exhibition_name, MAX(visitor_count) FROM ExhibitionsChicago WHERE city = 'Chicago' AND year = 2020;


Question: What is the number of military personnel in each branch of the Chinese military?

CREATE TABLE MilitaryPersonnel (id INT, name VARCHAR(255), branch VARCHAR(255), personnel_count INT); INSERT INTO MilitaryPersonnel (id, name, branch, personnel_count) VALUES (1, 'Li Wei', 'Ground Forces', 800000), (2, 'Zhang Li', 'Air Force', 450000), (3, 'Wang Xiao', 'Navy', 300000);

SELECT branch, personnel_count FROM MilitaryPersonnel WHERE branch IN ('Ground Forces', 'Air Force', 'Navy') GROUP BY branch;


Question: What is the total fare collected for each month?

SELECT EXTRACT(MONTH FROM trip_date) AS month, SUM(fare) AS total_fare FROM trip GROUP BY month;


Question: What is the total number of hours of professional development per instructor per district?

CREATE TABLE development_hours (teacher_id INT, district_id INT, hours_developed INT);

SELECT d.district_id, t.instructor_id, SUM(d.hours_developed) as total_hours FROM development_hours d INNER JOIN teachers t ON d.teacher_id = t.teacher_id GROUP BY d.district_id, t.instructor_id;


Question: What is the average budget allocated for disability support programs per region, ordered by the highest average budget?

CREATE TABLE Disability_Support_Programs (Region VARCHAR(50), Budget NUMERIC(10,2)); INSERT INTO Disability_Support_Programs VALUES ('Northeast', 500000), ('Southeast', 600000), ('Midwest', 400000), ('Southwest', 700000), ('West', 550000);

SELECT Region, AVG(Budget) as Avg_Budget FROM Disability_Support_Programs GROUP BY Region ORDER BY Avg_Budget DESC;


Question: Generate PostgreSQL SQL for: List the opposing team on february 15, 2003.

CREATE TABLE table_26360571_2 (opponent VARCHAR, date VARCHAR)

SELECT opponent FROM table_26360571_2 WHERE date = 'February 15, 2003';


Question: What is the average carbon offset by project?

CREATE TABLE carbon_offsets (project_id INT, carbon_offsets FLOAT); INSERT INTO carbon_offsets (project_id, carbon_offsets) VALUES (1, 1200.5), (2, 1800.75), (3, 2500.33);

SELECT AVG(carbon_offsets) FROM carbon_offsets;


Question: Calculate the total water usage for all mining operations, per month

CREATE TABLE WaterUsage (SiteID INT, UsageDate DATE, AmountUsed INT); INSERT INTO WaterUsage (SiteID, UsageDate, AmountUsed) VALUES (1, '2021-01-01', 500), (1, '2021-01-15', 700);

SELECT DATE_FORMAT(UsageDate, '%Y-%m') as Month, SUM(AmountUsed) as TotalWaterUsage FROM WaterUsage GROUP BY Month;


Question: Generate PostgreSQL SQL for: Name the position with height of 2.09

CREATE TABLE table_name_10 (position VARCHAR, height VARCHAR)

SELECT position FROM table_name_10 WHERE height = 2.09;


Question: Generate PostgreSQL SQL for: Which engine did dr ing f porsche kg use with the porsche rsk (f2) chassis?

CREATE TABLE table_name_77 (engine VARCHAR, entrant VARCHAR, chassis VARCHAR)

SELECT engine FROM table_name_77 WHERE entrant = 'dr ing f porsche kg' AND chassis = 'porsche rsk (f2)';


Question: PL/pgSQL test: Plpython Trigger (example 116).

-- check that using a function as a trigger over two tables works correctly
CREATE FUNCTION trig1234() RETURNS trigger LANGUAGE plpython3u AS $$
    TD["new"]["data"] = '1234'
    return 'MODIFY'
$$;

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


Question: Generate PostgreSQL SQL for: How much Latitude has a Water (sqmi) smaller than 0?

CREATE TABLE table_name_69 (latitude VARCHAR, water__sqmi_ INTEGER)

SELECT COUNT(latitude) FROM table_name_69 WHERE water__sqmi_ < 0;


Question: What is the percentage of policy advocacy efforts focused on mental health in each continent?

CREATE TABLE continent (continent_id INT, continent_name VARCHAR(50), country_code VARCHAR(5)); INSERT INTO continent (continent_id, continent_name, country_code) VALUES (1, 'North America', 'USA'), (2, 'Europe', 'FRA'); CREATE TABLE policy_advocacy (policy_id INT, policy_name VARCHAR(50), continent_id INT, focus_area VARCHAR(50)); INSERT INTO policy_advocacy (policy_id, policy_name, continent_id, focus_area) VALUES (1, 'Mental Health Parity Act', 1, 'Mental Health'), (2, 'Accessibility for Ontarians with Disabilities Act', 2, 'Physical Accessibility');

SELECT C.continent_name, COUNT(PA.policy_id) * 100.0 / (SELECT COUNT(*) FROM policy_advocacy WHERE focus_area = 'Mental Health') as mental_health_percentage FROM policy_advocacy PA JOIN continent C ON PA.continent_id = C.continent_id WHERE PA.focus_area = 'Mental Health' GROUP BY C.continent_name;


Question: Generate PostgreSQL SQL for: When was J.P. Viernes' last performance?

CREATE TABLE table_name_26 (last_performance VARCHAR, name VARCHAR)

SELECT last_performance FROM table_name_26 WHERE name = 'j.p. viernes';


Question: Generate PostgreSQL SQL for: The golfer Jeff Sluman golfs for what country?

CREATE TABLE table_name_13 (country VARCHAR, player VARCHAR)

SELECT country FROM table_name_13 WHERE player = 'jeff sluman';


Question: Generate PostgreSQL SQL for: Who was the runner up before 2007?

CREATE TABLE table_name_93 (runner_up VARCHAR, season INTEGER)

SELECT runner_up FROM table_name_93 WHERE season < 2007;


Question: Generate PostgreSQL SQL for: After 1971, what is the Rank with a Height ft (m) of 19.0 477 (145) and less than 35 Floors?

CREATE TABLE table_name_90 (rank VARCHAR, height_ft__m_ VARCHAR, year VARCHAR, floors VARCHAR)

SELECT rank FROM table_name_90 WHERE year > 1971 AND floors < 35 AND height_ft__m_ = '19.0 477 (145)';


Question: PostgreSQL regression test 'strings': Write the SELECT query (example 181).

SELECT regexp_instr('abcabcabc', 'a.c', 1, 1, -1);

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

SELECT count(*) FROM (SELECT regexp_instr('abcabcabc', 'a.c', 1, 1, -1)) AS _sub;


Question: Generate PostgreSQL SQL for: Party of republican, and a District of 7th is what elected?

CREATE TABLE table_name_81 (elected VARCHAR, party VARCHAR, district VARCHAR)

SELECT elected FROM table_name_81 WHERE party = 'republican' AND district = '7th';


Question: What is the maximum max speed of vessels that have a type of 'Passenger'?

CREATE TABLE Vessel (vessel_id INT, name VARCHAR(255), type VARCHAR(255), max_speed DECIMAL(5,2)); INSERT INTO Vessel (vessel_id, name, type, max_speed) VALUES (1, 'Test Vessel 1', 'Cargo', 20.5), (2, 'Test Vessel 2', 'Tanker', 15.2), (3, 'Test Vessel 3', 'Passenger', 30.7), (4, 'Test Vessel 4', 'Passenger', 35.6);

SELECT MAX(v.max_speed) FROM Vessel v WHERE v.type = 'Passenger';


Question: Show a query using PostgreSQL contrib extension 'postgres_fdw' (example 1224).

SELECT tableoid::regclass, * FROM batch_cp_upd_test ORDER BY 1;

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


Question: How many public schools are there in the capital city?

CREATE TABLE cities (city_id INT, city_name VARCHAR(255), capital_city BOOLEAN); INSERT INTO cities (city_id, city_name, capital_city) VALUES (1, 'Capital City', TRUE), (2, 'Second City', FALSE), (3, 'Third Town', FALSE); CREATE TABLE schools (school_id INT, school_name VARCHAR(255), city_id INT); INSERT INTO schools (school_id, school_name, city_id) VALUES (1, 'Capital High', 1), (2, 'North Secondary', 2), (3, 'East Elementary', 3);

SELECT COUNT(*) FROM schools WHERE city_id = (SELECT city_id FROM cities WHERE capital_city = TRUE);


Question: What is the average cargo handling time in hours for the 'handling_events' table?

CREATE TABLE handling_events (event_id INT, port_id INT, event_time TIME); INSERT INTO handling_events (event_id, port_id, event_time) VALUES (1, 1, '12:30:00'), (2, 2, '10:00:00'), (3, 3, '14:00:00');

SELECT AVG(TIME_TO_SEC(event_time) / 3600) FROM handling_events;


Question: Generate PostgreSQL SQL for: what is the english translation when the artist is ann christine?

CREATE TABLE table_name_10 (english_translation VARCHAR, artist VARCHAR)

SELECT english_translation FROM table_name_10 WHERE artist = 'ann christine';


Question: Generate PostgreSQL SQL for: What is Assembled, when Summoned is "6 October 1297"?

CREATE TABLE table_name_55 (assembled VARCHAR, summoned VARCHAR)

SELECT assembled FROM table_name_55 WHERE summoned = '6 october 1297';


Question: Generate PostgreSQL SQL for: Find the names of all swimmers, sorted by their 100 meter scores in ascending order.

CREATE TABLE swimmer (name VARCHAR, meter_100 VARCHAR)

SELECT name FROM swimmer ORDER BY meter_100;


Question: PL/pgSQL test: Plperl Array (example 27).

select plperl_arrays_inout_l('{{1}, {2}, {3}}');

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


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

SELECT * FROM test_timestamp WHERE i<='infinity'::date ORDER BY i;

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


Question: What is the average sugar content in organic vegan desserts?

CREATE TABLE products (id INT, category TEXT, is_organic BOOLEAN, is_vegan BOOLEAN, sugar_grams FLOAT); INSERT INTO products (id, category, is_organic, is_vegan, sugar_grams) VALUES (1, 'dessert', true, true, 12.5), (2, 'dessert', false, true, 15.0), (3, 'dessert', true, false, 8.0), (4, 'dessert', false, false, 10.0);

SELECT AVG(sugar_grams) FROM products WHERE is_organic = true AND is_vegan = true;


Question: Calculate the percentage of time each type of equipment was in use in the past month.

CREATE TABLE equipment_usage (id INT, equipment_type VARCHAR(255), usage_duration INT, timestamp DATETIME); INSERT INTO equipment_usage (id, equipment_type, usage_duration, timestamp) VALUES (1, 'Tractor', 120, '2022-01-01 10:00:00');

SELECT equipment_type, 100.0 * SUM(usage_duration) / SUM(CASE WHEN equipment_type = 'Tractor' THEN usage_duration ELSE 0 END) as usage_percentage FROM equipment_usage WHERE timestamp >= DATE_SUB(CURRENT_TIMESTAMP(), INTERVAL 1 MONTH) GROUP BY equipment_type;


Question: What is the maximum sea level rise recorded in the Atlantic region?

CREATE TABLE sea_level_data (id INT, region VARCHAR(50), sea_level_rise DECIMAL); INSERT INTO sea_level_data (id, region, sea_level_rise) VALUES (1, 'Pacific', 0.3); INSERT INTO sea_level_data (id, region, sea_level_rise) VALUES (2, 'Atlantic', 0.5);

SELECT MAX(sea_level_rise) FROM sea_level_data WHERE region = 'Atlantic';


Question: What is the total income of clients in the Philippines who are under 35?

CREATE TABLE clients (client_id INT, name VARCHAR(100), age INT, country VARCHAR(50), income DECIMAL(10,2));  INSERT INTO clients (client_id, name, age, country, income) VALUES (7, 'Maria Santos', 30, 'Philippines', 35000);

SELECT SUM(income) FROM clients WHERE country = 'Philippines' AND age < 35;


Question: Generate PostgreSQL SQL for: In what week was the away team Auckland?

CREATE TABLE table_name_92 (week VARCHAR, away_team VARCHAR)

SELECT week FROM table_name_92 WHERE away_team = 'auckland';


Question: pgTAP test for Pgtap--0.94.0--0.95.0 (assertion 42).

-- col_is_unique( scheam, table, column )
CREATE OR REPLACE FUNCTION col_is_unique ( NAME, NAME, NAME )
RETURNS TEXT AS $$
    SELECT col_is_unique( $1, $2, ARRAY[$3], 'Column ' || quote_ident($2) || '(' || quote_ident($3) || ') should have a unique constraint' );
$$ LANGUAGE sql;

Explanation: SQL assertion from pgTAP test suite for Pgtap--0.94.0--0.95.0.


Question: What is the maximum cost of devices for users in urban areas?

CREATE TABLE devices (device_id INT, device_cost FLOAT, user_location VARCHAR(10)); INSERT INTO devices VALUES (1, 300, 'rural'), (2, 500, 'urban'), (3, 400, 'rural');

SELECT MAX(device_cost) FROM devices WHERE user_location = 'urban';


Question: Update the climate finance data to reflect the current inflation rates, using the 'inflation_rates' table.

CREATE TABLE climate_finance (project VARCHAR(50), country VARCHAR(50), amount FLOAT, date DATE); CREATE TABLE inflation_rates (country VARCHAR(50), rate FLOAT, date DATE); INSERT INTO climate_finance (project, country, amount, date) VALUES ('Green City', 'USA', 5000000, '2020-01-01'); INSERT INTO inflation_rates (country, rate, date) VALUES ('USA', 1.02, '2020-01-01');

UPDATE climate_finance SET amount = amount * (SELECT rate FROM inflation_rates WHERE climate_finance.country = inflation_rates.country AND climate_finance.date = inflation_rates.date);


Question: Select names of all sustainable suppliers

CREATE TABLE supplier_info (id INT PRIMARY KEY, name VARCHAR(255), country VARCHAR(255), sustainable_practices BOOLEAN); CREATE VIEW sustainable_suppliers AS SELECT * FROM supplier_info WHERE sustainable_practices = TRUE;


Question: PostgreSQL regression test 'date': Write the SELECT query (example 196).

SELECT EXTRACT(TIMEZONE_M    FROM DATE '2020-08-11');

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

SELECT count(*) FROM (SELECT EXTRACT(TIMEZONE_M    FROM DATE '2020-08-11')) AS _sub;


Question: Generate PostgreSQL SQL for: Which week was the team's bye week?

CREATE TABLE table_name_78 (week INTEGER, attendance VARCHAR)

SELECT MAX(week) FROM table_name_78 WHERE attendance = 'bye';


Question: Generate PostgreSQL SQL for: Which translation was published in 1986?

CREATE TABLE table_name_78 (translation VARCHAR, date VARCHAR)

SELECT translation FROM table_name_78 WHERE date = 1986;


Question: What is the total number of 'recycling' facilities in 'Japan'?

CREATE TABLE facilities (id INT, name TEXT, type TEXT, location TEXT); INSERT INTO facilities (id, name, type, location) VALUES (1, 'recycling plant', 'recycling', 'Japan'), (2, 'waste treatment plant', 'waste', 'Japan'), (3, 'recycling plant', 'recycling', 'China');

SELECT COUNT(*) FROM facilities WHERE type = 'recycling' AND location = 'Japan';


Question: What is the total number of shipments for each warehouse, excluding cancelled shipments?

CREATE TABLE shipments (shipment_id INT, warehouse_id VARCHAR(5), quantity INT, cancelled BOOLEAN); CREATE TABLE warehouses (warehouse_id VARCHAR(5), city VARCHAR(5), state VARCHAR(3)); INSERT INTO shipments VALUES (1, 'LAX', 200, FALSE), (2, 'NYC', 300, TRUE), (3, 'LAX', 100, FALSE), (4, 'JFK', 50, FALSE); INSERT INTO warehouses VALUES ('LAX', 'Los', ' Angeles'), ('NYC', 'New', ' York'), ('JFK', 'New', ' York');

SELECT warehouses.warehouse_id, COUNT(shipments.shipment_id) FROM warehouses LEFT JOIN shipments ON warehouses.warehouse_id = shipments.warehouse_id WHERE NOT shipments.cancelled GROUP BY warehouses.warehouse_id;


Question: Show the total number of vehicles in 'Tokyo', 'Delhi', and 'Sao Paulo'

CREATE TABLE public.vehicles (id INT, type VARCHAR(20), city VARCHAR(20)); INSERT INTO public.vehicles (id, type, city) VALUES (1, 'electric_car', 'Tokyo'), (2, 'conventional_car', 'Tokyo'), (3, 'autonomous_bus', 'Delhi'), (4, 'conventional_car', 'Delhi'), (5, 'electric_bus', 'Sao Paulo'), (6, 'conventional_bus', 'Sao Paulo');

SELECT SUM(cnt) FROM (SELECT city, COUNT(*) AS cnt FROM public.vehicles WHERE city IN ('Tokyo', 'Delhi', 'Sao Paulo') GROUP BY city) AS subquery;


Question: Generate PostgreSQL SQL for: What event had 1 round and a record of 6-2?

CREATE TABLE table_name_9 (event VARCHAR, round VARCHAR, record VARCHAR)

SELECT event FROM table_name_9 WHERE round = 1 AND record = '6-2';


Question: Generate PostgreSQL SQL for: What lane did the swimmer with a time of 52.84 have?

CREATE TABLE table_name_43 (lane INTEGER, time VARCHAR)

SELECT MAX(lane) FROM table_name_43 WHERE time = 52.84;


Question: Generate PostgreSQL SQL for: What is the sum of year with the local host Sai?

CREATE TABLE table_name_37 (year INTEGER, local_host_s_ VARCHAR)

SELECT SUM(year) FROM table_name_37 WHERE local_host_s_ = 'sai';


Question: Generate PostgreSQL SQL for: What is Hungary's highest Rank?

CREATE TABLE table_name_38 (rank INTEGER, country VARCHAR)

SELECT MAX(rank) FROM table_name_38 WHERE country = 'hungary';


Question: Insert a new record into the customers table

CREATE TABLE customers (customer_id INT, first_name VARCHAR(50), last_name VARCHAR(50), email VARCHAR(100), phone_number VARCHAR(15), created_at TIMESTAMP);

INSERT INTO customers (customer_id, first_name, last_name, email, phone_number, created_at) VALUES (1001, 'Jamal', 'Lewis', 'jamal.lewis@mail.com', '5551234567', '2022-01-01 10:30:00');


Question: Generate PostgreSQL SQL for: What is the latest year joined with a Conference championships of 5, and an Institution of university of north carolina?

CREATE TABLE table_name_84 (joined INTEGER, conference_championships VARCHAR, institution VARCHAR)

SELECT MAX(joined) FROM table_name_84 WHERE conference_championships = 5 AND institution = 'university of north carolina';


Question: Show the number of customer complaints regarding mobile and broadband services, pivoted by the service type and month.

CREATE TABLE customer_complaints (complaint_id INT, complaint_date DATE, service_type VARCHAR(50)); INSERT INTO customer_complaints (complaint_id, complaint_date, service_type) VALUES (1, '2022-01-01', 'Mobile'), (2, '2022-02-01', 'Broadband'), (3, '2022-01-01', 'Broadband');

SELECT EXTRACT(MONTH FROM complaint_date) as month, service_type, COUNT(*) as complaints FROM customer_complaints GROUP BY month, service_type;


Question: Find the maximum number of attendees in virtual tours across Asian countries, in the last 6 months.

CREATE TABLE virtual_tours (id INT, location TEXT, attendees INT, tour_date DATE); INSERT INTO virtual_tours (id, location, attendees, tour_date) VALUES (1, 'Tokyo', 25, '2022-01-01'), (2, 'Seoul', 30, '2022-02-10');

SELECT MAX(attendees) FROM virtual_tours WHERE location LIKE '%Asia%' AND tour_date >= DATE_SUB(NOW(), INTERVAL 6 MONTH);


Question: Generate PostgreSQL SQL for: Result of win, and a Score of 33-22 involved what event?

CREATE TABLE table_name_4 (event VARCHAR, result VARCHAR, score VARCHAR)

SELECT event FROM table_name_4 WHERE result = 'win' AND score = '33-22';


Question: What is the total number of eco-certified destinations in Oceania?

CREATE TABLE destinations (destination_id INT, name VARCHAR(50), country_id INT, is_eco_certified BOOLEAN); INSERT INTO destinations (destination_id, name, country_id, is_eco_certified) VALUES (11, 'Great Barrier Reef', 14, true); INSERT INTO destinations (destination_id, name, country_id, is_eco_certified) VALUES (12, 'Fiordland National Park', 15, true);

SELECT COUNT(*) FROM destinations d WHERE d.is_eco_certified = true AND d.country_id IN (SELECT country_id FROM countries WHERE continent = 'Oceania');


Question: Update the R&D expenditure for 'DrugB' to $2,500,000 in Q3 2019.

CREATE TABLE rd_expenditure (drug_name TEXT, quarter INTEGER, year INTEGER, amount INTEGER); INSERT INTO rd_expenditure (drug_name, quarter, year, amount) VALUES ('DrugB', 3, 2019, 2000000);

UPDATE rd_expenditure SET amount = 2500000 WHERE drug_name = 'DrugB' AND quarter = 3 AND year = 2019;


Question: What is the total number of defense diplomacy events in the diplomacy_2020 table, grouped by region?

CREATE TABLE diplomacy_2020 (id INT, region VARCHAR(255), event VARCHAR(255)); INSERT INTO diplomacy_2020 VALUES (1, 'Asia', 'Summit A'), (2, 'Africa', 'Summit B'), (3, 'Asia', 'Summit C');

SELECT region, COUNT(*) FROM diplomacy_2020 GROUP BY region;


Question: Generate PostgreSQL SQL for: name the team for 36-29 record

CREATE TABLE table_27902171_8 (team VARCHAR, record VARCHAR)

SELECT team FROM table_27902171_8 WHERE record = '36-29';


Question: Generate PostgreSQL SQL for: What is the country that has a place of T6, a socre of 69-69=138, and where Niclas Fasth played?

CREATE TABLE table_name_17 (country VARCHAR, player VARCHAR, place VARCHAR, score VARCHAR)

SELECT country FROM table_name_17 WHERE place = 't6' AND score = 69 - 69 = 138 AND player = 'niclas fasth';


Question: pgTAP test for Proctap (assertion 72).

SELECT * FROM check_test(
    isnt_procedure( 'argpubfunc' ),
    true,
    'isnt_procedure(func)',
    'Function argpubfunc() should not be a procedure',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Proctap.


Question: What is the circular economy initiative in the city of London?

CREATE TABLE circular_economy (city VARCHAR(255), initiative VARCHAR(255)); INSERT INTO circular_economy (city, initiative) VALUES ('London', 'Waste to Wealth');

SELECT initiative FROM circular_economy WHERE city = 'London';


Question: Generate PostgreSQL SQL for: What was the Rd. Time for October 3, 2009?

CREATE TABLE table_name_86 (rd VARCHAR, _time VARCHAR, date VARCHAR)

SELECT rd, _time FROM table_name_86 WHERE date = 'october 3, 2009';


Question: PostgreSQL Rules: show example 35.

INSERT INTO shoelace_log VALUES ( shoelace_data.sl_name, 6, current_user, current_timestamp ) FROM shoelace_data WHERE 6 <> shoelace_data.sl_avail AND shoelace_data.sl_name = 'sl7'; UPDATE shoelace_data SET sl_avail = 6 WHERE sl_name = 'sl7';

Explanation: Example from PostgreSQL documentation on Rules.


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

Explanation: DML from PostgreSQL core regression test for Numeric.


Question: What is the total number of mobile and broadband subscribers for each technology type?

CREATE TABLE mobile_subscribers (subscriber_id INT, technology VARCHAR(20)); CREATE TABLE broadband_subscribers (subscriber_id INT, technology VARCHAR(20)); INSERT INTO mobile_subscribers (subscriber_id, technology) VALUES (1, '4G'), (2, '5G'), (3, '3G'); INSERT INTO broadband_subscribers (subscriber_id, technology) VALUES (4, 'Fiber'), (5, 'Cable'), (6, 'DSL');

SELECT 'Mobile' as source, technology, COUNT(*) as total FROM mobile_subscribers GROUP BY technology UNION ALL SELECT 'Broadband' as source, technology, COUNT(*) as total FROM broadband_subscribers GROUP BY technology;


Question: Show the number of dams in each state

CREATE TABLE Dams (id INT, state VARCHAR(50)); INSERT INTO Dams (id, state) VALUES (1, 'California'), (2, 'Texas');

SELECT state, COUNT(*) FROM Dams GROUP BY state;


Question: Generate PostgreSQL SQL for: What is the highest numbered event?

CREATE TABLE table_30060356_3 (event INTEGER)

SELECT MAX(event) FROM table_30060356_3;


Question: What is the average time taken for cases to be resolved for each ethnicity of judges?

CREATE TABLE public.judges (id SERIAL PRIMARY KEY, name VARCHAR(255), age INT, ethnicity VARCHAR(255), appointment_date DATE); CREATE TABLE public.cases (id SERIAL PRIMARY KEY, judge_id INT, case_number VARCHAR(255), case_date DATE, case_type VARCHAR(255), court_location VARCHAR(255));

SELECT j.ethnicity, AVG(c.case_date - j.appointment_date) as average_time_to_resolve FROM public.judges j JOIN public.cases c ON j.id = c.judge_id GROUP BY j.ethnicity;


Question: Identify the agricultural innovation metrics that have the lowest average score in Central America and the Caribbean.

CREATE TABLE innovation_metrics (id INT, name TEXT, score INT, region TEXT); INSERT INTO innovation_metrics (id, name, score, region) VALUES (1, 'Soil Monitoring', 7, 'Central America'), (2, 'Irrigation', 6, 'Caribbean'), (3, 'Crop Yield', 8, 'Central America'), (4, 'Livestock Management', 9, 'Caribbean');

SELECT name, AVG(score) as avg_score FROM innovation_metrics WHERE region IN ('Central America', 'Caribbean') GROUP BY name ORDER BY avg_score LIMIT 1;


Question: What was the total donation amount by individuals in Canada in Q1 2021?

CREATE TABLE Donations (id INT, donor_name VARCHAR(255), donation_amount DECIMAL(10,2), donation_date DATE); INSERT INTO Donations (id, donor_name, donation_amount, donation_date) VALUES (1, 'John Smith', 50.00, '2021-01-10'), (2, 'Emily Johnson', 75.00, '2021-03-15');

SELECT SUM(donation_amount) FROM Donations WHERE donor_name NOT LIKE '%org%' AND donation_date BETWEEN '2021-01-01' AND '2021-03-31';


Question: What is the number of unique donors per country, for countries that have received donations?

CREATE TABLE donors (id INT, name TEXT, organization TEXT, country TEXT);CREATE TABLE donations (id INT, donor_id INT, amount DECIMAL(10,2)); INSERT INTO donors (id, name, organization, country) VALUES (1, 'Donor A', 'Organization 1', 'Country A'), (2, 'Donor B', 'Organization 2', 'Country A'), (3, 'Donor C', 'Organization 3', 'Country B'), (4, 'Donor D', 'Organization 4', 'Country C'); INSERT INTO donations (id, donor_id, amount) VALUES (1, 1, 500.00), (2, 1, 750.00), (3, 2, 300.00), (4, 3, 1000.00), (5, 4, 250.00);

SELECT donors.country, COUNT(DISTINCT donors.id) FROM donors INNER JOIN donations ON donors.id = donations.donor_id GROUP BY donors.country;


Question: Generate PostgreSQL SQL for: Show party names and the number of events for each party.

CREATE TABLE party (party_name VARCHAR, party_id VARCHAR); CREATE TABLE party_events (party_id VARCHAR)

SELECT T2.party_name, COUNT(*) FROM party_events AS T1 JOIN party AS T2 ON T1.party_id = T2.party_id GROUP BY T1.party_id;


Question: Which classical models were developed for explainable AI?

CREATE TABLE Explainable_Models (Model_Type VARCHAR(20), Model_Name VARCHAR(30)); INSERT INTO Explainable_Models (Model_Type, Model_Name) VALUES ('Classical', 'Decision Trees'), ('Classical', 'Logistic Regression');

SELECT Model_Name FROM Explainable_Models WHERE Model_Type = 'Classical';


Question: pgTAP test for Functap (assertion 39).

SELECT * FROM check_test(
    hasnt_function( 'pg_catalog', 'now', 'whatever' ),
    false,
    'simple schema.func with desc',
    'whatever',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Functap.


Question: Which restorative justice programs have the highest participant satisfaction rates by facilitator?

CREATE TABLE participants (participant_id INT, participant_satisfaction INT, program_id INT); CREATE TABLE programs (program_id INT, facilitator_id INT, program_type VARCHAR(255));

SELECT facilitator_name, MAX(AVG(participant_satisfaction)) as avg_satisfaction FROM participants JOIN programs ON programs.program_id = participants.program_id JOIN facilitators ON programs.facilitator_id = facilitators.facilitator_id GROUP BY facilitator_name HAVING program_type = 'Restorative Justice';


Question: PL/pgSQL test: Pltcl Queries (example 14).

-- test some error cases
create function tcl_error(out a int, out b int) as $$returm 1$$ language pltcl;
select tcl_error();

create function bad_record(out a text, out b text) as $$return [list a]$$ language pltcl;

Explanation: PL/pgSQL example from PostgreSQL source test for Pltcl Queries.


Question: Generate PostgreSQL SQL for: What is the week 12 opponent for the year that had a week 3 opponent of South Florida (3-0)?

CREATE TABLE table_name_6 (week_12_nov_16 VARCHAR, week_3_sept_14 VARCHAR)

SELECT week_12_nov_16 FROM table_name_6 WHERE week_3_sept_14 = 'south florida (3-0)';


Question: What is the maximum age of players who have played VR games?

CREATE TABLE Players (PlayerID INT, Age INT, Gender VARCHAR(10), HasPlayedVR BOOLEAN); INSERT INTO Players (PlayerID, Age, Gender, HasPlayedVR) VALUES (1, 25, 'Male', true), (2, 30, 'Female', false), (3, 22, 'Male', true);

SELECT MAX(Age) FROM Players WHERE HasPlayedVR = true;


Question: Delete the 'peacekeeping_view' view

CREATE VIEW peacekeeping_view AS SELECT operation_id, name, location FROM peacekeeping_operations


Question: Generate PostgreSQL SQL for: What player that has a position of middle blocker, a Nationality of Turkey, and shirt no is 8?

CREATE TABLE table_name_36 (player VARCHAR, shirt_no VARCHAR, position VARCHAR, nationality VARCHAR)

SELECT player FROM table_name_36 WHERE position = 'middle blocker' AND nationality = 'turkey' AND shirt_no = 8;


Question: Generate PostgreSQL SQL for: What is Result, when Date is "June 11, 1994", and when Venue is "Miami, United States"?

CREATE TABLE table_name_58 (result VARCHAR, date VARCHAR, venue VARCHAR)

SELECT result FROM table_name_58 WHERE date = 'june 11, 1994' AND venue = 'miami, united states';


Question: Get the number of volleyball games played in 2022

CREATE TABLE volleyball_games (game_date DATE, team1 VARCHAR(255), team2 VARCHAR(255)); INSERT INTO volleyball_games (game_date, team1, team2) VALUES ('2022-01-01', 'Brazil', 'Russia'); INSERT INTO volleyball_games (game_date, team1, team2) VALUES ('2022-01-02', 'Italy', 'USA');

SELECT COUNT(*) FROM volleyball_games WHERE YEAR(game_date) = 2022;


Question: Generate PostgreSQL SQL for: Which Year is the highest one that has a Bronze of south korea, and a Silver of philippines?

CREATE TABLE table_name_27 (year INTEGER, bronze VARCHAR, silver VARCHAR)

SELECT MAX(year) FROM table_name_27 WHERE bronze = 'south korea' AND silver = 'philippines';


Question: Generate PostgreSQL SQL for: What Away team had an Attendance of 3,395?

CREATE TABLE table_name_68 (away_team VARCHAR, attendance VARCHAR)

SELECT away_team FROM table_name_68 WHERE attendance = '3,395';


Question: Generate PostgreSQL SQL for: Who was the away team playing against collingwood?

CREATE TABLE table_name_15 (away_team VARCHAR, home_team VARCHAR)

SELECT away_team FROM table_name_15 WHERE home_team = 'collingwood';


Question: Generate PostgreSQL SQL for: Phil Mickelson has what  To par?

CREATE TABLE table_name_47 (to_par VARCHAR, player VARCHAR)

SELECT to_par FROM table_name_47 WHERE player = 'phil mickelson';


Question: Generate PostgreSQL SQL for: What type of surface was played on when the score was 2–6, 6–1, [10–5]?

CREATE TABLE table_name_7 (surface VARCHAR, score VARCHAR)

SELECT surface FROM table_name_7 WHERE score = '2–6, 6–1, [10–5]';


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

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


Question: How many customers from each country have an account balance greater than 10000?

CREATE TABLE customers (id INT, name VARCHAR(255), country VARCHAR(255)); INSERT INTO customers (id, name, country) VALUES (1, 'John Doe', 'USA'), (2, 'Jane Smith', 'Canada'), (3, 'Marie Lee', 'France'); CREATE TABLE accounts (id INT, customer_id INT, balance DECIMAL(10, 2)); INSERT INTO accounts (id, customer_id, balance) VALUES (1, 1, 12000.00), (2, 1, 18000.00), (3, 2, 6000.00), (4, 3, 1500.00);

SELECT customers.country, COUNT(DISTINCT customers.id) FROM customers INNER JOIN accounts ON customers.id = accounts.customer_id WHERE accounts.balance > 10000 GROUP BY customers.country;


Question: Update the price of a menu item

CREATE TABLE menu_items (item_id INT, item_name VARCHAR(255), price DECIMAL(5,2));

UPDATE menu_items SET price = 15.99 WHERE item_id = 678;


Question: Generate PostgreSQL SQL for: What was the score for the team with a time of 2:44?

CREATE TABLE table_name_8 (score VARCHAR, time VARCHAR)

SELECT score FROM table_name_8 WHERE time = '2:44';


Question: What is the minimum number of accommodations provided, by accommodation type, for each region?

CREATE TABLE Accommodations (ID INT PRIMARY KEY, Region VARCHAR(50), AccommodationType VARCHAR(50), Quantity INT); INSERT INTO Accommodations (ID, Region, AccommodationType, Quantity) VALUES (1, 'North America', 'Sign Language Interpretation', 300), (2, 'North America', 'Wheelchair Ramp', 250), (3, 'South America', 'Assistive Listening Devices', 150), (4, 'Asia', 'Mobility Assistance', 200), (5, 'Europe', 'Sign Language Interpretation', 400), (6, 'Africa', 'Wheelchair Ramp', 100);

SELECT Region, AccommodationType, MIN(Quantity) as Minimum FROM Accommodations GROUP BY Region, AccommodationType;


Question: Update the total donation amount for donor 'Pedro Garcia' to $4500.

CREATE TABLE donors (donor_id INT, donor_name TEXT, country TEXT, total_donation_amount FLOAT); INSERT INTO donors (donor_id, donor_name, country, total_donation_amount) VALUES (1, 'Juan Rodriguez', 'Mexico', 4000.00), (2, 'Natalia Ivanova', 'Russia', 5000.00), (3, 'Pedro Garcia', 'Brazil', 2500.00);

WITH updated_pedro_garcia AS (UPDATE donors SET total_donation_amount = 4500.00 WHERE donor_name = 'Pedro Garcia' AND country = 'Brazil' RETURNING *) SELECT * FROM updated_pedro_garcia;


Question: Generate PostgreSQL SQL for: What is the English word for twie?

CREATE TABLE table_name_43 (english VARCHAR, twie VARCHAR, Limburgish VARCHAR)

SELECT english FROM table_name_43 WHERE DUTCH(Limburgish) = twie;


Question: Who are the construction workers in Washington with a salary higher than the average salary?

CREATE TABLE construction_workers (id INT, name VARCHAR(50), salary DECIMAL(10, 2), state VARCHAR(10)); INSERT INTO construction_workers (id, name, salary, state) VALUES (1, 'John Doe', 60000, 'Washington'); INSERT INTO construction_workers (id, name, salary, state) VALUES (2, 'Jane Smith', 55000, 'Washington');

SELECT * FROM construction_workers WHERE state = 'Washington' AND salary > (SELECT AVG(salary) FROM construction_workers WHERE state = 'Washington');


Question: What is the minimum depth of marine protected areas in the Arctic Ocean region?

CREATE TABLE arctic_marine_protected_areas (id INT, name TEXT, region TEXT, min_depth FLOAT); INSERT INTO arctic_marine_protected_areas (id, name, region, min_depth) VALUES (1, 'Norwegian Trench', 'Arctic', 3000.0), (2, 'Fram Strait', 'Arctic', 2500.0);

SELECT MIN(min_depth) FROM arctic_marine_protected_areas WHERE region = 'Arctic';


Question: Which regions have the highest and lowest donation amounts?

SELECT region, amount FROM Donations ORDER BY amount DESC LIMIT 1;


Question: Generate PostgreSQL SQL for: What is the name of the Representative Work in a year later than 2005 with a Result of nominated, and an Award of best variety show host?

CREATE TABLE table_name_20 (representative_work VARCHAR, award VARCHAR, year VARCHAR, result VARCHAR)

SELECT representative_work FROM table_name_20 WHERE year > 2005 AND result = 'nominated' AND award = 'best variety show host';


Question: Show a query using PostgreSQL contrib extension 'pg_stat_statements' (example 43).

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


Question: Insert new records into the museum_operations table for a new exhibit.

CREATE TABLE museum_operations (exhibit_id INT, exhibit_name TEXT, start_date DATE, end_date DATE, daily_visitors INT);

INSERT INTO museum_operations (exhibit_id, exhibit_name, start_date, end_date, daily_visitors) VALUES (1001, 'Contemporary Art from Japan', '2023-03-01', '2023-05-31', 500);


Question: Write the DML statement from PostgreSQL regression test 'box' (example 8).

INSERT INTO BOX_TBL (f1) VALUES ('[1, 2, 3, 4)');

Explanation: DML from PostgreSQL core regression test for Box.


Question: Update the temperature records for Svalbard with the new measurements.

CREATE TABLE arctic_regions (region_id INT, region_name VARCHAR(50)); CREATE TABLE weather (weather_id INT, region_id INT, measurement_date DATE, temperature DECIMAL(5,2)); INSERT INTO arctic_regions (region_id, region_name) VALUES (1, 'Alaska'), (2, 'Greenland'), (3, 'Svalbard'); INSERT INTO weather (weather_id, region_id, measurement_date, temperature) VALUES (1, 1, '2017-01-01', -10.5), (2, 1, '2017-12-31', 15.2), (3, 2, '2017-01-01', -25.6), (4, 2, '2017-12-31', -5.2), (5, 3, '2017-01-01', -12.2);

UPDATE weather SET temperature = -3.0 WHERE region_id = (SELECT region_id FROM arctic_regions WHERE region_name = 'Svalbard') AND measurement_date = '2017-01-01'; UPDATE weather SET temperature = -4.2 WHERE region_id = (SELECT region_id FROM arctic_regions WHERE region_name = 'Svalbard') AND measurement_date = '2017-12-31';


Question: List all military technologies that were used in the last 2 military conflicts, including the technology type and conflict date.

CREATE TABLE military_tech_usage (id INT, tech_type TEXT, tech_usage_date DATE, conflict TEXT); INSERT INTO military_tech_usage (id, tech_type, tech_usage_date, conflict) VALUES (1, 'Drones', '2020-02-01', 'Conflict A'), (2, 'Armored Vehicles', '2019-11-15', 'Conflict B');

SELECT mt.tech_type, mt.tech_usage_date FROM military_tech_usage mt WHERE mt.tech_usage_date >= '2019-01-01';


Question: Generate PostgreSQL SQL for: What country has a loan as the type?

CREATE TABLE table_name_6 (country VARCHAR, type VARCHAR)

SELECT country FROM table_name_6 WHERE type = 'loan';


Question: Generate PostgreSQL SQL for: How many players had a best winning average of 20?

CREATE TABLE table_27533947_1 (games_won VARCHAR, best_winning_average VARCHAR)

SELECT COUNT(games_won) FROM table_27533947_1 WHERE best_winning_average = '20';


Question: Generate PostgreSQL SQL for: What is the Date of Tie no 3?

CREATE TABLE table_name_67 (date VARCHAR, tie_no VARCHAR)

SELECT date FROM table_name_67 WHERE tie_no = '3';


Question: Determine the monthly sales growth of eco-friendly makeup products in the last year.

CREATE TABLE MakeupSales (ProductID INT, ProductType VARCHAR(20), IsEcoFriendly BOOLEAN, Revenue DECIMAL(10,2), SaleDate DATE); INSERT INTO MakeupSales (ProductID, ProductType, IsEcoFriendly, Revenue, SaleDate) VALUES (1, 'Lipstick', TRUE, 50.00, '2022-01-15'); INSERT INTO MakeupSales (ProductID, ProductType, IsEcoFriendly, Revenue, SaleDate) VALUES (2, 'Eyeshadow', TRUE, 75.00, '2022-02-20'); INSERT INTO MakeupSales (ProductID, ProductType, IsEcoFriendly, Revenue, SaleDate) VALUES (3, 'Foundation', TRUE, 60.00, '2022-03-05'); INSERT INTO MakeupSales (ProductID, ProductType, IsEcoFriendly, Revenue, SaleDate) VALUES (4, 'Blush', TRUE, 80.00, '2022-04-10');

SELECT EXTRACT(MONTH FROM SaleDate) AS Month, AVG(Revenue) AS AverageRevenue, LAG(AVG(Revenue)) OVER (ORDER BY EXTRACT(MONTH FROM SaleDate)) AS PreviousMonthAverage FROM MakeupSales WHERE ProductType = 'Makeup' AND IsEcoFriendly = TRUE GROUP BY EXTRACT(MONTH FROM SaleDate) ORDER BY EXTRACT(MONTH FROM SaleDate);


Question: Generate PostgreSQL SQL for: What season had an acquisition of free agency, and was higher than 9?

CREATE TABLE table_name_89 (season VARCHAR, acquisition_via VARCHAR, number VARCHAR)

SELECT season FROM table_name_89 WHERE acquisition_via = 'free agency' AND number > 9;


Question: What is the total number of factories in the workforce development sector that have implemented workforce diversity initiatives and have a workforce size above 500?

CREATE TABLE factories (factory_id INT, sector VARCHAR(255), has_workforce_diversity_initiatives BOOLEAN, workforce_size INT); INSERT INTO factories (factory_id, sector, has_workforce_diversity_initiatives, workforce_size) VALUES (1, 'Workforce Development', TRUE, 600), (2, 'Workforce Development', TRUE, 400), (3, 'Workforce Development', FALSE, 500);

SELECT COUNT(*) FROM factories WHERE sector = 'Workforce Development' AND has_workforce_diversity_initiatives = TRUE AND workforce_size > 500;


Question: Write the DDL statement from PostgreSQL regression test 'eager_aggregate' (example 3).

CREATE TABLE eager_agg_t3 (a int, b int, c double precision);

Explanation: DDL from PostgreSQL core regression test for Eager Aggregate.


Question: What was the average price per gram of cannabis flower sold by each dispensary in the city of Toronto in the month of February 2022?

CREATE TABLE Dispensaries (id INT, name VARCHAR(255), city VARCHAR(255), state VARCHAR(255));CREATE TABLE Inventory (id INT, dispensary_id INT, price DECIMAL(10, 2), product_type VARCHAR(255), grams INT, month INT, year INT);INSERT INTO Dispensaries (id, name, city, state) VALUES (1, 'CannaCorp', 'Toronto', 'ON');INSERT INTO Inventory (id, dispensary_id, price, product_type, grams, month, year) VALUES (1, 1, 20, 'flower', 3.5, 2, 2022);

SELECT d.name, AVG(i.price/i.grams) as avg_price_per_gram FROM Dispensaries d JOIN Inventory i ON d.id = i.dispensary_id WHERE d.city = 'Toronto' AND i.product_type = 'flower' AND i.month = 2 AND i.year = 2022 GROUP BY d.name;


Question: What is the minimum travel time for an autonomous ride-hailing service in Singapore?

CREATE TABLE autonomous_ride_hailing (ride_id INT, travel_time FLOAT, city VARCHAR(50));

SELECT MIN(travel_time) FROM autonomous_ride_hailing WHERE city = 'Singapore';


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

-- create the operator class for gist
CREATE OPERATOR CLASS gist_trgm_ops
FOR TYPE text USING gist
AS
        OPERATOR        1       % (text, text),
        FUNCTION        1       gtrgm_consistent (internal, text, smallint, oid, internal),
        FUNCTION        2       gtrgm_union (internal, internal),
        FUNCTION        3       gtrgm_compress (internal),
        FUNCTION        4       gtrgm_decompress (internal),
        FUNCTION        5       gtrgm_penalty (internal, internal, internal),
        FUNCTION        6       gtrgm_picksplit (internal, internal),
        FUNCTION        7       gtrgm_same (gtrgm, gtrgm, internal),
        STORAGE         gtrgm;

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


Question: Write the DML statement from PostgreSQL regression test 'timestamptz' (example 39).

INSERT INTO TIMESTAMPTZ_TBL VALUES ('1997-02-10 17:32:01-0800');

Explanation: DML from PostgreSQL core regression test for Timestamptz.


Question: What is the total revenue for each restaurant, including the sum of sales for all menu items and additional charges?

CREATE TABLE Restaurants (RestaurantID int, RestaurantName varchar(255)); CREATE TABLE MenuItems (MenuID int, MenuName varchar(255), RestaurantID int, Sales int); CREATE TABLE AdditionalCharges (ChargeID int, ChargeName varchar(255), RestaurantID int, ChargeAmt int);

SELECT R.RestaurantName, SUM(M.Sales + AC.ChargeAmt) as TotalRevenue FROM Restaurants R INNER JOIN MenuItems M ON R.RestaurantID = M.RestaurantID INNER JOIN AdditionalCharges AC ON R.RestaurantID = AC.RestaurantID GROUP BY R.RestaurantName;


Question: What is the average budget allocated per public service in the education sector?

CREATE TABLE EducationBudget (ID INT, Service VARCHAR(255), Budget INT); INSERT INTO EducationBudget (ID, Service, Budget) VALUES (1, 'Primary Education', 5000000), (2, 'Secondary Education', 6000000), (3, 'Tertiary Education', 8000000);

SELECT AVG(Budget) FROM EducationBudget WHERE Service LIKE 'Education%';


Question: Generate PostgreSQL SQL for: How many parties is the incumbent Bob Brady a member of?

CREATE TABLE table_1341423_38 (party VARCHAR, incumbent VARCHAR)

SELECT COUNT(party) FROM table_1341423_38 WHERE incumbent = 'Bob Brady';


Question: What is the change in monthly water usage for each household in Austin from 2020 to 2021?

CREATE TABLE Household_Water_Usage (ID INT, Household VARCHAR(20), Year INT, Month INT, Usage FLOAT);

SELECT h20_21.Household, AVG(h20_21.Usage - h20_20.Usage) as Avg_Change FROM Household_Water_Usage h20_21, Household_Water_Usage h20_20 WHERE h20_21.Household = h20_20.Household AND h20_20.Year = 2020 AND h20_21.Year = 2021 GROUP BY h20_21.Household;


Question: Insert a new artifact 'Roman Coin' with ArtifactID 4, type 'Coin', quantity 20, and belonging to site 'Pompeii' (SiteID 3).

CREATE TABLE ExcavationSites (SiteID INT, SiteName TEXT, Country TEXT); CREATE TABLE Artifacts (ArtifactID INT, SiteID INT, ArtifactName TEXT, ArtifactType TEXT, Quantity INT);

INSERT INTO Artifacts (ArtifactID, SiteID, ArtifactName, ArtifactType, Quantity) VALUES (4, 3, 'Roman Coin', 'Coin', 20);


Question: Present the types of military equipment from the USA

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

SELECT type FROM military_equipment WHERE country = 'USA';


Question: Generate PostgreSQL SQL for: How many ends were won where the blank ends are smaller than 3.0?

CREATE TABLE table_25718552_2 (Ends VARCHAR, blank_ends INTEGER)

SELECT Ends AS won FROM table_25718552_2 WHERE blank_ends < 3.0;


Question: Generate PostgreSQL SQL for: Who was the opponent when the record was 11-6-2?

CREATE TABLE table_name_25 (opponent VARCHAR, record VARCHAR)

SELECT opponent FROM table_name_25 WHERE record = '11-6-2';


Question: Generate PostgreSQL SQL for: What is the Branding with a Callsign DWLL?

CREATE TABLE table_name_99 (branding VARCHAR, callsign VARCHAR)

SELECT branding FROM table_name_99 WHERE callsign = 'dwll';


Question: What are the crops planted by farmers aged 40 or older?

CREATE TABLE farmers (id INT PRIMARY KEY, name VARCHAR(50), age INT, location VARCHAR(50)); INSERT INTO farmers (id, name, age, location) VALUES (1, 'John Doe', 35, 'New York'); INSERT INTO farmers (id, name, age, location) VALUES (2, 'Jane Smith', 40, 'Los Angeles'); CREATE TABLE crops (id INT PRIMARY KEY, name VARCHAR(50), growth_season VARCHAR(50), planted_by INT, FOREIGN KEY (planted_by) REFERENCES farmers(id)); INSERT INTO crops (id, name, growth_season, planted_by) VALUES (1, 'Corn', 'Summer', 1); INSERT INTO crops (id, name, growth_season, planted_by) VALUES (2, 'Carrots', 'Winter', 2);

SELECT crops.name FROM crops INNER JOIN farmers ON crops.planted_by = farmers.id WHERE farmers.age >= 40;


Question: Generate PostgreSQL SQL for: When vp8 ( webm ) is 4.4, how much is vp9 ( webm )

CREATE TABLE table_26099252_1 (vp9___webm__ VARCHAR, vp8___webm__ VARCHAR)

SELECT vp9___webm__ FROM table_26099252_1 WHERE vp8___webm__ = '4.4';


Question: What's the minimum donation amount made by donors from California in the year 2021?

CREATE TABLE Donors (DonorID INT, DonorName VARCHAR(100), DonationAmount DECIMAL(10,2), DonationDate DATE, DonorState VARCHAR(50));

SELECT MIN(DonationAmount) FROM Donors WHERE DonorState = 'California' AND YEAR(DonationDate) = 2021;


Question: Generate PostgreSQL SQL for: Show the station name with at least two trains.

CREATE TABLE station (name VARCHAR, station_id VARCHAR); CREATE TABLE train_station (station_id VARCHAR)

SELECT T2.name FROM train_station AS T1 JOIN station AS T2 ON T1.station_id = T2.station_id GROUP BY T1.station_id HAVING COUNT(*) >= 2;


Question: Show a query using PostgreSQL contrib extension 'dblink' (example 24).

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


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

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

SELECT count(*) FROM (select '[{"b": "c"}, {"b": "cc"}]'::jsonb #> array['1','b']) AS _sub;


Question: Count the number of unique esports events where at least one player from Asia participated, and the number of unique FPS games played in these events.

CREATE TABLE EsportsEvents (EventID INT, EventName VARCHAR(50)); CREATE TABLE Players (PlayerID INT, Age INT, Gender VARCHAR(10), Region VARCHAR(20)); CREATE TABLE PlayerEvent (PlayerID INT, EventID INT); CREATE TABLE Games (GameID INT, GameName VARCHAR(50), Genre VARCHAR(20)); CREATE TABLE GameEvent (GameID INT, EventID INT, GameType VARCHAR(10)); CREATE TABLE VR_Games (GameID INT, IsVR INT);

SELECT COUNT(DISTINCT EsportsEvents.EventID), COUNT(DISTINCT Games.GameID) FROM EsportsEvents INNER JOIN PlayerEvent ON EsportsEvents.EventID = PlayerEvent.EventID INNER JOIN Players ON PlayerEvent.PlayerID = Players.PlayerID INNER JOIN Games ON GameEvent.GameID = Games.GameID INNER JOIN GameEvent ON EsportsEvents.EventID = GameEvent.EventID INNER JOIN VR_Games ON Games.GameID = VR_Games.GameID WHERE Players.Region = 'Asia' AND Games.Genre = 'FPS';


Question: Delete all artifacts related to a specific excavation site

CREATE TABLE ExcavationSites (SiteID int, Name varchar(50), Country varchar(50), StartDate date); INSERT INTO ExcavationSites (SiteID, Name, Country, StartDate) VALUES (5, 'Site E', 'Egypt', '2013-11-11'); CREATE TABLE Artifacts (ArtifactID int, SiteID int, Name varchar(50), Description text, DateFound date); INSERT INTO Artifacts (ArtifactID, SiteID, Name, Description, DateFound) VALUES (4, 5, 'Artifact W', 'An Egyptian artifact', '2017-07-07');


Question: Number of patients who did not show improvement after dialectical behavior therapy (DBT) treatment in the USA.

CREATE TABLE patients (patient_id INT, country VARCHAR(50)); INSERT INTO patients (patient_id, country) VALUES (1, 'USA'), (2, 'Canada'), (3, 'USA'); CREATE TABLE treatments (patient_id INT, treatment VARCHAR(10), improvement BOOLEAN); INSERT INTO treatments (patient_id, treatment, improvement) VALUES (1, 'DBT', FALSE), (2, 'DBT', TRUE), (3, 'CBT', TRUE);

SELECT COUNT(patients.patient_id) FROM patients INNER JOIN treatments ON patients.patient_id = treatments.patient_id WHERE treatments.treatment = 'DBT' AND patients.country = 'USA' AND treatments.improvement = FALSE;


Question: Generate PostgreSQL SQL for: Which season did the Minnesota Kicks lose 13 games and scored 156 points?

CREATE TABLE table_name_34 (season VARCHAR, lost VARCHAR, points VARCHAR)

SELECT COUNT(season) FROM table_name_34 WHERE lost = 13 AND points = 156;


Question: List all historical sites in Spain with over 1000 virtual tours, ordered by the number of virtual tours in descending order.

CREATE TABLE historical_sites(site_id INT, site_name TEXT, country TEXT, num_virtual_tours INT); INSERT INTO historical_sites(site_id, site_name, country, num_virtual_tours) VALUES (1, 'Alhambra', 'Spain', 1500), (2, 'Sagrada Familia', 'Spain', 1200), (3, 'Mosque of Cordoba', 'Spain', 800);

SELECT site_id, site_name, num_virtual_tours FROM historical_sites WHERE country = 'Spain' AND num_virtual_tours > 1000 ORDER BY num_virtual_tours DESC;


Question: Find the percentage of visitors that engaged with online exhibitions from North America and Europe combined.

CREATE TABLE Online_Interaction (id INT, user_id INT, interaction_date DATE, country VARCHAR(50)); INSERT INTO Online_Interaction (id, user_id, interaction_date, country) VALUES (1, 1, '2022-05-01', 'USA'), (2, 3, '2022-05-15', 'Canada'), (3, 5, '2022-04-20', 'France'), (4, 7, '2022-03-25', 'UK');

SELECT (COUNT(DISTINCT CASE WHEN country IN ('USA', 'Canada', 'France', 'UK') THEN Online_Interaction.user_id END) * 100.0 / COUNT(DISTINCT Online_Interaction.user_id)) as percentage FROM Online_Interaction;


Question: What is the total number of patients that have completed their treatment for each condition?

CREATE TABLE TreatmentOutcomes (TreatmentID int, ConditionID int, Completed int); INSERT INTO TreatmentOutcomes (TreatmentID, ConditionID, Completed) VALUES (1, 1, 1), (2, 1, 0), (3, 2, 1);

SELECT Conditions.Condition, SUM(TreatmentOutcomes.Completed) FROM TreatmentOutcomes JOIN Conditions ON TreatmentOutcomes.ConditionID = Conditions.ConditionID GROUP BY Conditions.Condition;


Question: PL/pgSQL test: Pltcl Queries (example 64).


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

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


Question: What is the average distance each marathoner ran in the Olympics?

CREATE TABLE olympic_marathon (athlete VARCHAR(50), distance INT); INSERT INTO olympic_marathon (athlete, distance) VALUES ('Eliud Kipchoge', 42195), ('Feyisa Lilesa', 42320), ('Galen Rupp', 42200);

SELECT AVG(distance) AS avg_distance FROM olympic_marathon;


Question: Write the DML statement from PostgreSQL regression test 'create_misc' (example 43).

INSERT INTO f_star (class, a, c, f)
   VALUES ('f', 21, 'hi marcel'::name, '(11,44),(22,55),(33,66)'::polygon);

Explanation: DML from PostgreSQL core regression test for Create Misc.


Question: What is the average lead time for each fabric supplier in the Asia-Pacific region?

CREATE TABLE suppliers (supplier_id INT, supplier_name VARCHAR(50), location VARCHAR(50), lead_time INT);

SELECT location, AVG(lead_time) as avg_lead_time FROM suppliers WHERE location LIKE '%Asia-Pacific%' GROUP BY location;


Question: Generate PostgreSQL SQL for: What is the sum avg/g with an effic of 858.4?

CREATE TABLE table_name_61 (avg_g INTEGER, effic VARCHAR)

SELECT SUM(avg_g) FROM table_name_61 WHERE effic = 858.4;


Question: PostgreSQL regression test 'subselect': Write the SELECT query (example 214).

select * from exists_tbl t1
  where (exists(select 1 from exists_tbl t2 where t1.c1 = t2.c2) or c3 < 0);

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

SELECT count(*) FROM (select * from exists_tbl t1
  where (exists(select 1 from exists_tbl t2 where t1.c1 = t2.c2) or c3 < 0)) AS _sub;


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

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


Question: Generate PostgreSQL SQL for: Name the score for game for 25

CREATE TABLE table_17103729_8 (score VARCHAR, game VARCHAR)

SELECT score FROM table_17103729_8 WHERE game = 25;


Question: PL/pgSQL test: Plperl (example 61).

CREATE OR REPLACE FUNCTION foo_good() RETURNS SETOF footype AS $$
return [
    {x => 1, y => 2},
    {x => 3, y => 4}
];
$$ LANGUAGE plperl;

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


Question: What is the average number of training hours for employees in the 'Marketing' department who have completed diversity and inclusion training?

CREATE TABLE Employee_Training (Employee_ID INT, Employee_Name VARCHAR(50), Department VARCHAR(50), Training_Type VARCHAR(50), Hours_Spent DECIMAL(5,2)); INSERT INTO Employee_Training (Employee_ID, Employee_Name, Department, Training_Type, Hours_Spent) VALUES (6, 'Alex Johnson', 'Marketing', 'Diversity and Inclusion', 5.00), (7, 'Taylor Lee', 'Marketing', 'Diversity and Inclusion', 4.00), (8, 'Jasmine Brown', 'Marketing', 'Cybersecurity', 7.00);

SELECT AVG(Hours_Spent) FROM Employee_Training WHERE Department = 'Marketing' AND Training_Type = 'Diversity and Inclusion';


Question: Write the DML statement from PostgreSQL regression test 'select_implicit' (example 10).

INSERT INTO test_missing_target VALUES (8, 4, 'CCCC', 'I');

Explanation: DML from PostgreSQL core regression test for Select Implicit.


Question: What is the percentage of climate finance that went to climate adaptation projects in South America between 2010 and 2015?

CREATE TABLE climate_finance (region VARCHAR(255), year INT, project_type VARCHAR(255), amount FLOAT);

SELECT (SUM(CASE WHEN project_type = 'climate adaptation' THEN amount ELSE 0 END) / SUM(amount)) * 100 AS adaptation_percentage FROM climate_finance WHERE year BETWEEN 2010 AND 2015 AND region = 'South America';


Question: What is the maximum property price in each neighborhood in San Francisco?

CREATE TABLE sf_neighborhoods (id INT, name VARCHAR(50)); INSERT INTO sf_neighborhoods (id, name) VALUES (1, 'Mission'), (2, 'Castro'), (3, 'Haight-Ashbury'); CREATE TABLE properties (id INT, neighborhood_id INT, price INT); INSERT INTO properties (id, neighborhood_id, price) VALUES (1, 1, 500000), (2, 2, 400000), (3, 1, 600000);

SELECT properties.neighborhood_id, MAX(properties.price) FROM properties GROUP BY properties.neighborhood_id;


Question: What is the minimum installed capacity of wind turbines for all renewable energy projects in Germany?

CREATE TABLE renewable_energy (project_name VARCHAR(50), country VARCHAR(50), wind_capacity INT); INSERT INTO renewable_energy (project_name, country, wind_capacity) VALUES ('Project1', 'Germany', 5000), ('Project2', 'Germany', 12000), ('Project3', 'Germany', 8000);

SELECT MIN(wind_capacity) FROM renewable_energy WHERE country = 'Germany';


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

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

SELECT count(*) FROM (select jsonb_path_query('0', '$.boolean()')) AS _sub;


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

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

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


Question: Generate PostgreSQL SQL for: Who is the opponent in the final on 24 November 2008?

CREATE TABLE table_name_43 (opponent_in_the_final VARCHAR, date VARCHAR)

SELECT opponent_in_the_final FROM table_name_43 WHERE date = '24 november 2008';


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

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

Explanation: DML from PostgreSQL core regression test for Numeric.


Question: What is the total number of military personnel involved in cybersecurity operations in Asia?

CREATE TABLE MilitaryCyberOps (Id INT, Region VARCHAR(50), Personnel INT, Year INT); INSERT INTO MilitaryCyberOps (Id, Region, Personnel, Year) VALUES (1, 'Asia', 200, 2021); INSERT INTO MilitaryCyberOps (Id, Region, Personnel, Year) VALUES (2, 'Europe', 300, 2021);

SELECT SUM(Personnel) FROM MilitaryCyberOps WHERE Region = 'Asia';


Question: What is the total amount donated and number of donations for each quarter in the 'donations' table?

CREATE TABLE donations (donation_id INT, donation_date DATE, donation_amount FLOAT); INSERT INTO donations (donation_id, donation_date, donation_amount) VALUES (1, '2022-01-01', 50.00), (2, '2022-02-01', 100.00), (3, '2022-03-01', 150.00);

SELECT DATE_TRUNC('quarter', donation_date) as quarter, SUM(donation_amount) as total_donation, COUNT(donation_id) as num_donations FROM donations GROUP BY quarter ORDER BY quarter;


Question: List the names of investors who have invested in companies that have a female founder.

CREATE TABLE Companies (id INT, name TEXT, founder_gender TEXT); INSERT INTO Companies (id, name, founder_gender) VALUES (1, 'Daisy Enterprise', 'Female'); INSERT INTO Companies (id, name, founder_gender) VALUES (2, 'Bright Star Corp', 'Male'); CREATE TABLE Investors (id INT, name TEXT); INSERT INTO Investors (id, name) VALUES (1, 'Venture Capital 3'); INSERT INTO Investors (id, name) VALUES (2, 'Angel Investor 3');

SELECT Investors.name FROM Companies INNER JOIN Investors ON TRUE WHERE Companies.founder_gender = 'Female';


Question: Write the DML statement from PostgreSQL regression test 'generated_stored' (example 54).

INSERT INTO gtest1v VALUES (4, 8);  -- error
INSERT INTO gtest1v VALUES (5, DEFAULT);  -- ok
INSERT INTO gtest1v VALUES (6, 66), (7, 77);  -- error
INSERT INTO gtest1v VALUES (6, DEFAULT), (7, 77);  -- error
INSERT INTO gtest1v VALUES (6, 66), (7, DEFAULT);  -- error
INSERT INTO gtest1v VALUES (6, DEFAULT), (7, DEFAULT);  -- ok

ALTER VIEW gtest1v ALTER COLUMN b SET DEFAULT 100;

Explanation: DML from PostgreSQL core regression test for Generated Stored.


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

SELECT xmlroot(xml '<foo/>', version no value, standalone no value);

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

SELECT count(*) FROM (SELECT xmlroot(xml '<foo/>', version no value, standalone no value)) AS _sub;


Question: pgTAP test for Hastap (assertion 48).

SELECT * FROM check_test(
    has_view( '__SDFSDFD__', 'howdy' ),
    false,
    'has_view(non-existent view, desc)',
    'howdy',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Hastap.


Question: What is the total number of virtual tour views for hotels in Miami?

CREATE TABLE cultural_heritage (site_id INT, hotel_id INT, attendance INT); INSERT INTO cultural_heritage (site_id, hotel_id, attendance) VALUES (1, 1, 500), (2, 2, 300);

SELECT SUM(vt.num_views) FROM virtual_tours vt INNER JOIN hotel_info hi ON vt.hotel_id = hi.hotel_id WHERE hi.city = 'Miami';


Question: Which teams have the highest and lowest average ticket prices for regular seats?

CREATE TABLE Teams (TeamID INT, TeamName VARCHAR(50), AvgRegularTicketPrice DECIMAL(5,2));

SELECT TeamName FROM Teams WHERE AvgRegularTicketPrice = (SELECT MAX(AvgRegularTicketPrice) FROM Teams) OR AvgRegularTicketPrice = (SELECT MIN(AvgRegularTicketPrice) FROM Teams);


Question: Generate PostgreSQL SQL for: What kind of Entrant has a Maserati Straight-6 Engine, built in the year 1958 or early, and has a Maserati 250f Chassis with points less than 4?

CREATE TABLE table_name_95 (entrant VARCHAR, points VARCHAR, chassis VARCHAR, engine VARCHAR, year VARCHAR)

SELECT entrant FROM table_name_95 WHERE engine = 'maserati straight-6' AND year < 1958 AND chassis = 'maserati 250f' AND points < 4;


Question: Show an example of PostgreSQL ALTER INDEX (example 4).

CREATE INDEX coord_idx ON measured (x, y, (z + t)); ALTER INDEX coord_idx ALTER COLUMN 3 SET STATISTICS 1000;

Explanation: PostgreSQL ALTER INDEX command.


Question: Show a SQL definition from the timescaledb project (create_table_with, item 25).

CREATE TABLE t7(time timestamptz, device text, value float) WITH (timescaledb.hypertable,tsdb.partition_column='time');

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


Question: Generate PostgreSQL SQL for: When did they win 7 races?

CREATE TABLE table_24937583_1 (seasons VARCHAR, wins VARCHAR)

SELECT seasons FROM table_24937583_1 WHERE wins = 7;


Question: Show a SQL definition from the citus project (multi_partitioning_utils, item 44).

CREATE TABLE partition_child_1_schema.child_1 (id int NOT NULL, time date );

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


Question: Generate PostgreSQL SQL for: Name the least frequency Mhz with call sign of k202ag

CREATE TABLE table_name_24 (frequency_mhz INTEGER, call_sign VARCHAR)

SELECT MIN(frequency_mhz) FROM table_name_24 WHERE call_sign = 'k202ag';


Question: Generate PostgreSQL SQL for: I want to know the tie for drawn of 47

CREATE TABLE table_name_46 (tied VARCHAR, drawn VARCHAR)

SELECT tied FROM table_name_46 WHERE drawn = '47';


Question: What is the average rating for each product, and the number of ratings for each product, ordered by the average rating in descending order?

CREATE TABLE product (product_id INT, name VARCHAR(50), rating DECIMAL(3,2), num_ratings INT); INSERT INTO product VALUES (1, 'Product A', 4.5, 100), (2, 'Product B', 3.5, 200), (3, 'Product C', 5.0, 50);

SELECT name, AVG(rating) as avg_rating, num_ratings FROM product GROUP BY name ORDER BY avg_rating DESC, num_ratings DESC;


Question: Generate PostgreSQL SQL for: List the order dates of all the bookings.

CREATE TABLE BOOKINGS (Order_Date VARCHAR)


Question: Update a record with community health statistic for a specific community type

CREATE TABLE community_health_statistics_v2 (id INT, community_type VARCHAR(20), statistic_value INT);

UPDATE community_health_statistics_v2 SET statistic_value = 110 WHERE community_type = 'Urban';


Question: Show a SQL definition from the timescaledb project (compat, item 26).

CREATE OR REPLACE FUNCTION _timescaledb_internal.policy_compression_check(config jsonb) RETURNS void LANGUAGE PLPGSQL AS $$
BEGIN
  IF current_setting('timescaledb.enable_deprecation_warnings', true)::bool THEN
    RAISE WARNING 'function _timescaledb_internal.policy_compression_check(jsonb) is deprecated and has been moved to _timescaledb_functions schema. this compatibility function will be removed in a future version.';
  END IF;
  PERFORM _timescaledb_functions.policy_compression_check($1);
END$$
SET search_path TO pg_catalog,pg_temp;


Question: Generate PostgreSQL SQL for: What is the rank of the arch with a length in meters of 75/55?

CREATE TABLE table_name_29 (rank VARCHAR, length___m__ VARCHAR)

SELECT rank FROM table_name_29 WHERE length___m__ = '75/55';


Question: pgTAP test for Valueset (assertion 274).

-- Make sure that dupes are not ignored.
SELECT * FROM check_test(
    bag_has( 'anames', 'VALUES (44, ''Anna''), (44, ''Anna'')' ),
    false,
    'bag_has( prepared, dupes )',
    '',
    '    Missing records:
        (44,Anna)'
);

Explanation: SQL assertion from pgTAP test suite for Valueset.


Question: List all wells that were drilled in the 'Haynesville' shale play and had production greater than 2000 in any quarter.

CREATE TABLE wells (well_id INT, well_name VARCHAR(50), shale_play VARCHAR(50), production_q1 FLOAT, production_q2 FLOAT, production_q3 FLOAT, production_q4 FLOAT); INSERT INTO wells (well_id, well_name, shale_play, production_q1, production_q2, production_q3, production_q4) VALUES (1, 'Well M', 'Haynesville', 2200, 2400, 2600, 2800), (2, 'Well N', 'Barnett', 1900, 2150, 2400, 2650);

SELECT well_name FROM wells WHERE shale_play = 'Haynesville' AND (production_q1 > 2000 OR production_q2 > 2000 OR production_q3 > 2000 OR production_q4 > 2000);


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

SELECT count(*) FROM (SELECT '{"a":"b", "b":1, "c":null}'::jsonb @> '{"g":null}') AS _sub;


Question: Generate PostgreSQL SQL for: Championship larger than 3, and a FA Cup smaller than 3, and a Total smaller than 6 involves what highest league cup?

CREATE TABLE table_name_27 (league_cup INTEGER, total VARCHAR, championship VARCHAR, fa_cup VARCHAR)

SELECT MAX(league_cup) FROM table_name_27 WHERE championship > 3 AND fa_cup < 3 AND total < 6;


Question: Update team names to uppercase in the 'esports_teams' table

CREATE TABLE esports_teams (team_id INT, team_name VARCHAR(50));

UPDATE esports_teams SET team_name = UPPER(team_name);


Question: Generate PostgreSQL SQL for: What is the lowest number of silver medals with a rank of 4 and total medals greater than 1?

CREATE TABLE table_name_68 (silver INTEGER, rank VARCHAR, total VARCHAR)

SELECT MIN(silver) FROM table_name_68 WHERE rank = 4 AND total > 1;


Question: Generate PostgreSQL SQL for: What was the call sign for ERP W of 99?

CREATE TABLE table_name_68 (call_sign VARCHAR, erp_w VARCHAR)

SELECT call_sign FROM table_name_68 WHERE erp_w = 99;


Question: What is the maximum depth reached by a marine species in the Southern Ocean, along with its habitat and species name?

CREATE TABLE southern_ocean_depths (id INT, species_name VARCHAR(255), depth FLOAT, habitat VARCHAR(255)); INSERT INTO southern_ocean_depths (id, species_name, depth, habitat) VALUES (1, 'Southern Right Whale', 300, 'Coastal');

SELECT species_name, depth, habitat FROM (SELECT species_name, depth, habitat, MAX(depth) OVER (PARTITION BY ocean) AS max_depth FROM southern_ocean_depths WHERE ocean = 'Southern Ocean') t WHERE depth = max_depth;


Question: What is the maximum ESG score for companies in the energy sector in Q4 2020?

CREATE TABLE if not exists companies (company_id INT, sector VARCHAR(50), esg_score DECIMAL(3,2), quarter INT, year INT); INSERT INTO companies (company_id, sector, esg_score, quarter, year) VALUES (1, 'Energy', 8.4, 4, 2020), (2, 'Energy', 9.2, 4, 2020), (3, 'Energy', 8.9, 4, 2020);

SELECT MAX(esg_score) FROM companies WHERE sector = 'Energy' AND quarter = 4 AND year = 2020;


Question: List all organizations in the 'environment' category along with the total donation amount they received.

CREATE TABLE organizations (id INT, name VARCHAR(255), category VARCHAR(255)); INSERT INTO organizations (id, name, category) VALUES (1, 'Greenpeace', 'environment'), (2, 'Climate Action', 'environment'), (3, 'Education Alliance', 'education'); CREATE TABLE donations (id INT, organization_id INT, amount DECIMAL(10, 2)); INSERT INTO donations (id, organization_id, amount) VALUES (1, 1, 1000), (2, 1, 2000), (3, 2, 500), (4, 2, 1500), (5, 3, 3000);

SELECT organizations.name, SUM(donations.amount) AS total_donation FROM organizations INNER JOIN donations ON organizations.id = donations.organization_id WHERE organizations.category = 'environment' GROUP BY organizations.name;


Question: What is the average age of language speakers in the 'community_engagement' table?

CREATE TABLE community_engagement (id INT, name VARCHAR(50), language VARCHAR(50), age INT); INSERT INTO community_engagement (id, name, language, age) VALUES (1, 'John Doe', 'English', 45), (2, 'Jane Smith', 'Spanish', 32);

SELECT AVG(age) FROM community_engagement WHERE language IS NOT NULL;


Question: Generate PostgreSQL SQL for: display the job title of jobs which minimum salary is greater than 9000.

CREATE TABLE jobs (job_title VARCHAR, min_salary INTEGER)

SELECT job_title FROM jobs WHERE min_salary > 9000;


Question: Generate PostgreSQL SQL for: What Competition in Main Article of Bradford Bulls 1997 have Robbie Paul as Captain with less than 5 Lost?

CREATE TABLE table_name_54 (competition VARCHAR, main_article VARCHAR, captain VARCHAR, lost VARCHAR)

SELECT competition FROM table_name_54 WHERE captain = 'robbie paul' AND lost < 5 AND main_article = 'bradford bulls 1997';


Question: Which cruelty-free certified products are not vegan-friendly?

CREATE TABLE product (id INT, name VARCHAR(50), is_cruelty_free BOOLEAN, is_vegan BOOLEAN); INSERT INTO product (id, name, is_cruelty_free, is_vegan) VALUES (1, 'Lipstick A', true, false), (2, 'Eye Shadow B', true, true);

SELECT name FROM product WHERE is_cruelty_free = true AND is_vegan = false;


Question: How many vessels with flag_state 'Panama' were active in the last month?

CREATE TABLE vessel_activity (id INT, vessel_name VARCHAR(50), flag_state VARCHAR(50), activity_date DATE); INSERT INTO vessel_activity (id, vessel_name, flag_state, activity_date) VALUES (1, 'Panama Titan', 'Panama', '2022-03-20'), (2, 'Panama Titan', 'Panama', '2022-03-23');

SELECT COUNT(DISTINCT vessel_name) FROM vessel_activity WHERE flag_state = 'Panama' AND activity_date BETWEEN DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH) AND CURRENT_DATE;


Question: Generate PostgreSQL SQL for: What was the final score for the game in which Carmelo Anthony (26) was the high points scorer?

CREATE TABLE table_name_78 (score VARCHAR, high_points VARCHAR)

SELECT score FROM table_name_78 WHERE high_points = 'carmelo anthony (26)';


Question: How many times has a specific IP address been associated with phishing attacks in the last month?

CREATE TABLE phishing_attacks (id INT, ip_address VARCHAR(255), date DATE);

SELECT COUNT(*) FROM phishing_attacks WHERE ip_address = '192.168.1.1' AND date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH);


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

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


Question: Generate PostgreSQL SQL for: List the creation year, name and budget of each department.

CREATE TABLE department (creation VARCHAR, name VARCHAR, budget_in_billions VARCHAR)

SELECT creation, name, budget_in_billions FROM department;


Question: pgTAP test for Resultset (assertion 222).

SELECT is(
    _temptable( '"something cool"', '__spacenames__' ),
    '__spacenames__',
    'Should create a temp table for a prepared statement with space'
);

Explanation: SQL assertion from pgTAP test suite for Resultset.


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

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


Question: What is the average horsepower of electric vehicles in the vehicle_safety_testing table?

CREATE TABLE vehicle_safety_testing (vehicle_id INT, vehicle_name VARCHAR(50), horsepower INT, safety_rating FLOAT);

SELECT AVG(horsepower) FROM vehicle_safety_testing WHERE vehicle_type = 'Electric';


Question: Generate PostgreSQL SQL for: what is the year when the location is san diego, california and defeated is houston baptist (texas)?

CREATE TABLE table_name_96 (year VARCHAR, location VARCHAR, defeated VARCHAR)

SELECT COUNT(year) FROM table_name_96 WHERE location = 'san diego, california' AND defeated = 'houston baptist (texas)';


Question: pgTAP test for Ownership (assertion 40).

SELECT * FROM check_test(
    relation_owner_is('__not__public', 'someseq', current_user, 'mumble'),
	false,
    'relation_owner_is(non-sch, seq, user)',
    'mumble',
    '    Relation __not__public.someseq does not exist'
);

Explanation: SQL assertion from pgTAP test suite for Ownership.


Question: What is the number of employees working in each mining operation type?

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

SELECT operation_type, COUNT(*) as num_employees FROM workforce GROUP BY operation_type;


Question: What is the total revenue of organic products sold by vendors with a high ethical labor score?

CREATE TABLE vendors (vendor_id INT, ethical_score INT); INSERT INTO vendors (vendor_id, ethical_score) VALUES (1, 90), (2, 75), (3, 85); CREATE TABLE products (product_id INT, organic BOOLEAN); INSERT INTO products (product_id, organic) VALUES (101, TRUE), (102, FALSE), (103, TRUE); CREATE TABLE sales (sale_id INT, vendor_id INT, product_id INT, revenue INT); INSERT INTO sales (sale_id, vendor_id, product_id, revenue) VALUES (1, 1, 101, 500), (2, 1, 102, 300), (3, 2, 101, 400), (4, 3, 103, 600);

SELECT SUM(sales.revenue) FROM sales JOIN vendors ON sales.vendor_id = vendors.vendor_id JOIN products ON sales.product_id = products.product_id WHERE products.organic = TRUE AND vendors.ethical_score >= 80;


Question: Find the difference in transaction amount between the first and last transaction for each customer.

CREATE TABLE customer_transactions (transaction_date DATE, customer_id INT, transaction_amt DECIMAL(10, 2)); INSERT INTO customer_transactions (transaction_date, customer_id, transaction_amt) VALUES ('2022-01-01', 1, 200.00), ('2022-01-05', 1, 300.00), ('2022-01-01', 2, 100.00);

SELECT customer_id, FIRST_VALUE(transaction_amt) OVER (PARTITION BY customer_id ORDER BY transaction_date) AS first_transaction_amt, LAST_VALUE(transaction_amt) OVER (PARTITION BY customer_id ORDER BY transaction_date ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS last_transaction_amt, last_transaction_amt - first_transaction_amt AS transaction_diff FROM customer_transactions;


Question: What is the number of workers involved in fair trade and living wage practices?

CREATE TABLE labor_practices (id INT, supplier VARCHAR(255), practice VARCHAR(255), num_workers INT); INSERT INTO labor_practices (id, supplier, practice, num_workers) VALUES (1, 'Supplier A', 'Fair Trade', 50), (2, 'Supplier B', 'Living Wage', 75), (3, 'Supplier C', 'Fair Trade', 100), (4, 'Supplier D', 'Living Wage', 125), (5, 'Supplier E', 'Fair Trade', 150);

SELECT practice, SUM(num_workers) FROM labor_practices WHERE practice IN ('Fair Trade', 'Living Wage') GROUP BY practice;


Question: Find the total number of indigenous communities in the 'Arctic_Communities' table that have a population size greater than any community in the 'Antarctic_Communities' table.

CREATE TABLE Arctic_Communities (name TEXT, population INTEGER); CREATE TABLE Antarctic_Communities (name TEXT, population INTEGER);

SELECT COUNT(*) FROM Arctic_Communities WHERE Arctic_Communities.population > (SELECT MAX(population) FROM Antarctic_Communities);


Question: How many hybrid cars and hybrid trucks are in the fleet_inventory table?

CREATE TABLE fleet_inventory (id INT, ev_type VARCHAR(20), quantity INT); INSERT INTO fleet_inventory (id, ev_type, quantity) VALUES (1, 'electric_car', 50), (2, 'hybrid_car', 30), (3, 'electric_truck', 10), (4, 'hybrid_truck', 20);

SELECT SUM(quantity) FROM fleet_inventory WHERE ev_type LIKE 'hybrid%';


Question: What's the total revenue of Marvel movies released in 2019?

CREATE TABLE movies (id INT, title VARCHAR(255), release_year INT, production_budget INT, revenue INT); INSERT INTO movies (id, title, release_year, production_budget, revenue) VALUES (1, 'Avengers: Endgame', 2019, 356000000, 27978000000), (2, 'Captain Marvel', 2019, 153000000, 11285000000);

SELECT SUM(revenue) FROM movies WHERE release_year = 2019 AND title IN ('Avengers: Endgame', 'Captain Marvel');


Question: What is the name and location of all heritage sites with no community engagement events?

CREATE TABLE events (id INT, name VARCHAR, site_id INT); INSERT INTO events (id, name, site_id) VALUES (1, 'Event A', 1), (2, 'Event B', 2); CREATE TABLE heritage_sites (id INT, name VARCHAR, location VARCHAR); INSERT INTO heritage_sites (id, name, location) VALUES (1, 'Heritage Site A', 'City A'), (2, 'Heritage Site B', 'City B'), (3, 'Heritage Site C', 'City C');

SELECT heritage_sites.name, heritage_sites.location FROM heritage_sites LEFT JOIN events ON heritage_sites.id = events.site_id WHERE events.id IS NULL;


Question: Find the maximum altitude reached by 'Boeing' and 'Airbus' aircraft models.

CREATE TABLE Flight_Altitude (aircraft_model VARCHAR(255), altitude INT); INSERT INTO Flight_Altitude (aircraft_model, altitude) VALUES ('B737', 40000), ('A320', 41000), ('B747', 43000), ('B787', 44000), ('A350', 45000), ('A380', 46000), ('Boeing', 47000), ('Airbus', 48000);

SELECT aircraft_model, altitude FROM Flight_Altitude WHERE aircraft_model IN ('Boeing', 'Airbus') AND altitude = (SELECT MAX(altitude) FROM Flight_Altitude WHERE aircraft_model IN ('Boeing', 'Airbus'));


Question: Generate PostgreSQL SQL for: What chassis has the year 1987?

CREATE TABLE table_name_87 (chassis VARCHAR, year VARCHAR)

SELECT chassis FROM table_name_87 WHERE year = 1987;


Question: Generate PostgreSQL SQL for: What is Points Against, when Drawn is "2", and when Points Of is "32"?

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

SELECT points_against FROM table_name_80 WHERE drawn = '2' AND points = '32';


Question: What are the unique threat_actors that have been involved in both 'Network Intrusions' and 'Data Exfiltration' incidents?

CREATE TABLE incidents (id INT, threat_actor VARCHAR(255), incident_type VARCHAR(255)); INSERT INTO incidents (id, threat_actor, incident_type) VALUES (1, 'APT28', 'Network Intrusion'), (2, 'APT33', 'Data Exfiltration'), (3, 'APT34', 'Network Intrusion'), (4, 'APT29', 'Data Exfiltration'), (5, 'APT35', 'Network Intrusion'), (6, 'APT28', 'Data Exfiltration');

SELECT threat_actor FROM incidents WHERE incident_type = 'Network Intrusion' INTERSECT SELECT threat_actor FROM incidents WHERE incident_type = 'Data Exfiltration';


Question: How many military equipment maintenance requests were there in Q2 2020?

CREATE TABLE maintenance_requests (request_id INT, date DATE, type VARCHAR(255)); INSERT INTO maintenance_requests (request_id, date, type) VALUES (1, '2020-01-01', 'equipment'); INSERT INTO maintenance_requests (request_id, date, type) VALUES (2, '2020-01-15', 'facility');

SELECT COUNT(*) FROM maintenance_requests WHERE date BETWEEN '2020-04-01' AND '2020-06-30' AND type = 'equipment';


Question: Generate PostgreSQL SQL for: What is the Away with a Time that is 14:00?

CREATE TABLE table_name_28 (away VARCHAR, time VARCHAR)

SELECT away FROM table_name_28 WHERE time = '14:00';


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

INSERT INTO t4 VALUES (1, 'mmm'), (2, 'nnn'), (3, 'ooo');

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


Question: Generate PostgreSQL SQL for: What is the location for the game on October 20 with it's corresponding attendance?

CREATE TABLE table_28768469_2 (location_attendance VARCHAR, date VARCHAR)

SELECT location_attendance FROM table_28768469_2 WHERE date = 'October 20';


Question: Generate PostgreSQL SQL for: What is the sum of Runners-Up, when Champions is greater than 5?

CREATE TABLE table_name_2 (runners_up INTEGER, champions INTEGER)

SELECT SUM(runners_up) FROM table_name_2 WHERE champions > 5;


Question: What is the total revenue for the 'Burger' category?

CREATE TABLE restaurant_revenue (item_category VARCHAR(20), daily_revenue DECIMAL(10,2)); INSERT INTO restaurant_revenue (item_category, daily_revenue) VALUES ('Burger', 1500.00), ('Pizza', 1200.00), ('Salad', 800.00);

SELECT SUM(daily_revenue) FROM restaurant_revenue WHERE item_category = 'Burger';


Question: What was the total amount of funds spent by UN agencies in Syria in 2017?

CREATE TABLE un_agencies (agency_name VARCHAR(255), country VARCHAR(255), funds_spent DECIMAL(10,2), funds_date DATE); INSERT INTO un_agencies (agency_name, country, funds_spent, funds_date) VALUES ('UND', 'Syria', 90000, '2017-02-25'), ('UNE', 'Syria', 100000, '2017-08-17'), ('UNF', 'Syria', 110000, '2017-11-29');

SELECT SUM(funds_spent) FROM un_agencies WHERE country = 'Syria' AND YEAR(funds_date) = 2017;


Question: Generate PostgreSQL SQL for: Who did the fastest lap when pole position was damon hill and the location was magny-cours?

CREATE TABLE table_name_33 (fastest_lap VARCHAR, pole_position VARCHAR, location VARCHAR)

SELECT fastest_lap FROM table_name_33 WHERE pole_position = 'damon hill' AND location = 'magny-cours';


Question: Generate PostgreSQL SQL for: How many times did outgoing manager Bart de Roover vacated a position?

CREATE TABLE table_27374004_4 (date_of_vacancy VARCHAR, outgoing_manager VARCHAR)

SELECT COUNT(date_of_vacancy) FROM table_27374004_4 WHERE outgoing_manager = 'Bart De Roover';


Question: What is the total data usage for the month of March?

CREATE TABLE data_usage (id INT, subscriber_id INT, usage FLOAT, month TEXT); INSERT INTO data_usage (id, subscriber_id, usage, month) VALUES (1, 1, 15.0, 'March'); INSERT INTO data_usage (id, subscriber_id, usage, month) VALUES (2, 2, 20.0, 'March'); INSERT INTO data_usage (id, subscriber_id, usage, month) VALUES (3, 3, 10.0, 'March'); INSERT INTO data_usage (id, subscriber_id, usage, month) VALUES (4, 1, 20.0, 'April');

SELECT SUM(usage) FROM data_usage WHERE month = 'March';


Question: Generate PostgreSQL SQL for: What are the names of reviewers who had rated 3 star and 4 star?

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

SELECT T2.name FROM Rating AS T1 JOIN Reviewer AS T2 ON T1.rID = T2.rID WHERE T1.stars = 3 INTERSECT SELECT T2.name FROM Rating AS T1 JOIN Reviewer AS T2 ON T1.rID = T2.rID WHERE T1.stars = 4;


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

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

SELECT count(*) FROM (SELECT pg_size_bytes('-.kb')) AS _sub;


Question: Generate PostgreSQL SQL for: Find the number of female students (with F sex) living in Smith Hall

CREATE TABLE lives_in (stuid VARCHAR, dormid VARCHAR); CREATE TABLE student (stuid VARCHAR, sex VARCHAR); CREATE TABLE dorm (dormid VARCHAR, dorm_name VARCHAR)

SELECT COUNT(*) FROM student AS T1 JOIN lives_in AS T2 ON T1.stuid = T2.stuid JOIN dorm AS T3 ON T3.dormid = T2.dormid WHERE T3.dorm_name = 'Smith Hall' AND T1.sex = 'F';


Question: Generate PostgreSQL SQL for: What is the Round din Ullevaal?

CREATE TABLE table_name_23 (round VARCHAR, venue VARCHAR)

SELECT round FROM table_name_23 WHERE venue = 'ullevaal';


Question: What is the distribution of genres in our movie database?

CREATE TABLE Movies (id INT, title VARCHAR(255), genre VARCHAR(255));

SELECT genre, COUNT(*) AS count FROM Movies GROUP BY genre;


Question: Find the circular economy initiatives that have the highest recycling rates.

CREATE TABLE Initiatives (InitiativeID INT, InitiativeName VARCHAR(50), RecyclingRate FLOAT); INSERT INTO Initiatives VALUES (1, 'Initiative1', 0.7), (2, 'Initiative2', 0.6), (3, 'Initiative3', 0.8), (4, 'Initiative4', 0.5);

SELECT InitiativeName, RecyclingRate FROM Initiatives WHERE RecyclingRate = (SELECT MAX(RecyclingRate) FROM Initiatives);


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

-- B-tree support

CREATE OPERATOR CLASS ltree_ops
    DEFAULT FOR TYPE ltree USING btree AS
        OPERATOR        1       < ,
        OPERATOR        2       <= ,
        OPERATOR        3       = ,
        OPERATOR        4       >= ,
        OPERATOR        5       > ,
        FUNCTION        1       ltree_cmp(ltree, ltree);

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


Question: What is the total cost of fair trade coffee products in the last 6 months?

CREATE TABLE Dates (date DATE); CREATE TABLE Sales (sale_id INT, date DATE, product_id INT, quantity INT, cost INT); CREATE TABLE Products (product_id INT, product_name VARCHAR(255), is_fair_trade BOOLEAN);

SELECT SUM(s.cost) as total_cost FROM Sales s JOIN Dates d ON s.date = d.date JOIN Products p ON s.product_id = p.product_id WHERE d.date >= DATE(NOW()) - INTERVAL 6 MONTH AND p.is_fair_trade = TRUE;


Question: What is the average safety score for each AI algorithm, partitioned by algorithm type, ordered by score in descending order?

CREATE TABLE ai_algorithms (algorithm_id INT, algorithm_name VARCHAR(50), safety_score DECIMAL(5,2)); INSERT INTO ai_algorithms (algorithm_id, algorithm_name, safety_score) VALUES (1, 'DeepQA', 85.34), (2, 'Random Forest', 91.23), (3, 'Support Vector Machine', 89.11), (4, 'Neural Network', 87.54);

SELECT algorithm_name, AVG(safety_score) as avg_safety_score FROM ai_algorithms GROUP BY algorithm_name ORDER BY avg_safety_score DESC;


Question: What is the average number of employees for each sector in the ai_companies table?

CREATE TABLE ai_companies (id INT, name VARCHAR(20), location VARCHAR(20), sector VARCHAR(20), employees INT, ethical_ai BOOLEAN); INSERT INTO ai_companies (id, name, location, sector, employees, ethical_ai) VALUES (4, 'GHI Tech', 'USA', 'Robotics', 60, false);

SELECT sector, AVG(employees) as avg_employees FROM ai_companies GROUP BY sector;


Question: What is the average financial wellbeing score for clients in urban areas?

CREATE TABLE clients(id INT, name TEXT, location TEXT, financial_wellbeing_score INT);

SELECT AVG(c.financial_wellbeing_score) FROM clients c WHERE c.location LIKE '%urban%';


Question: Generate PostgreSQL SQL for: What was the record for the Argonauts on September 7?

CREATE TABLE table_24136814_3 (record VARCHAR, date VARCHAR)

SELECT record FROM table_24136814_3 WHERE date = 'September 7';


Question: Generate PostgreSQL SQL for: tries against is 88, played is 22, what is the lost?

CREATE TABLE table_name_57 (lost VARCHAR, played VARCHAR, tries_against VARCHAR)

SELECT lost FROM table_name_57 WHERE played = '22' AND tries_against = '88';


Question: What is the average temperature for all regions growing 'Corn'?

CREATE TABLE farm (id INT PRIMARY KEY, name VARCHAR(50), region_id INT, avg_temp DECIMAL(5,2)); CREATE TABLE region (id INT PRIMARY KEY, name VARCHAR(50)); INSERT INTO region (id, name) VALUES (1, 'Midwest'), (2, 'South'); INSERT INTO farm (id, name, region_id, avg_temp) VALUES (1, 'Smith Farm', 1, 15.5), (2, 'Jones Farm', 1, 16.3), (3, 'Brown Farm', 2, 20.2);

SELECT AVG(f.avg_temp) FROM farm f INNER JOIN region r ON f.region_id = r.id WHERE r.name IN (SELECT name FROM region WHERE id IN (SELECT region_id FROM farm WHERE name = 'Corn'));


Question: Generate PostgreSQL SQL for: What was the largest number of people in attendance of the game with a W 14-3 result after week 10?

CREATE TABLE table_name_10 (attendance INTEGER, result VARCHAR, week VARCHAR)

SELECT MAX(attendance) FROM table_name_10 WHERE result = 'w 14-3' AND week > 10;