Question: What was the total sales revenue for 'DrugE' in the 'Canada' region in Q3 2021?

CREATE TABLE sales_data (drug VARCHAR(50), region VARCHAR(50), quarter INT, year INT, revenue FLOAT); INSERT INTO sales_data (drug, region, quarter, year, revenue) VALUES ('DrugE', 'Canada', 3, 2021, 4000000);

SELECT SUM(revenue) FROM sales_data WHERE drug = 'DrugE' AND region = 'Canada' AND quarter = 3 AND year = 2021;


Question: Generate PostgreSQL SQL for: Name the others % for cleveland

CREATE TABLE table_1733457_1 (others_percentage VARCHAR, county VARCHAR)

SELECT others_percentage FROM table_1733457_1 WHERE county = 'Cleveland';


Question: What is the average preservation cost for each heritage site in Australia, considering the sites with the highest preservation costs?

CREATE TABLE heritage_sites (id INT, name VARCHAR(50), location VARCHAR(50), type VARCHAR(50), PRIMARY KEY(id)); INSERT INTO heritage_sites (id, name, location, type) VALUES (1, 'Sydney Opera House', 'Australia', 'Modern'), (2, 'Uluru', 'Australia', 'Ancient'), (3, 'Port Arthur', 'Australia', 'Historic'); CREATE TABLE preservation_costs (id INT, heritage_site_id INT, cost INT, PRIMARY KEY(id)); INSERT INTO preservation_costs (id, heritage_site_id, cost) VALUES (1, 1, 2000000), (2, 2, 3000000), (3, 3, 1500000);

SELECT hs.name, hs.location, hs.type, AVG(pr.cost) AS avg_cost FROM heritage_sites hs JOIN preservation_costs pr ON hs.id = pr.heritage_site_id WHERE hs.location = 'Australia' GROUP BY hs.name, hs.location, hs.type ORDER BY avg_cost DESC LIMIT 1;


Question: Which sustainable material has the least usage in garment production?

CREATE TABLE Materials (material_id INT PRIMARY KEY, material VARCHAR(50), usage INT); INSERT INTO Materials (material_id, material, usage) VALUES (1, 'Organic Cotton', 500), (2, 'Recycled Polyester', 300), (3, 'Hemp', 100);

SELECT material FROM (SELECT material, ROW_NUMBER() OVER (ORDER BY usage) AS rank FROM Materials) AS ranked_materials WHERE rank = 1;


Question: Generate PostgreSQL SQL for: What is the highest number of laps that also has a finish total of 8?

CREATE TABLE table_name_98 (laps INTEGER, finish VARCHAR)

SELECT MAX(laps) FROM table_name_98 WHERE finish = '8';


Question: Generate PostgreSQL SQL for: Find the distinct last names of all the students who have president votes and whose advisor is not 2192.

CREATE TABLE STUDENT (LName VARCHAR, PRESIDENT_Vote VARCHAR, Advisor VARCHAR); CREATE TABLE STUDENT (LName VARCHAR, StuID VARCHAR); CREATE TABLE VOTING_RECORD (Id VARCHAR)

SELECT DISTINCT T1.LName FROM STUDENT AS T1 JOIN VOTING_RECORD AS T2 ON T1.StuID = PRESIDENT_Vote EXCEPT SELECT DISTINCT LName FROM STUDENT WHERE Advisor = '2192';


Question: What is the total revenue generated from gluten-free dishes?

CREATE TABLE Bakery (bakery_item VARCHAR(50), type VARCHAR(20), price DECIMAL(5,2), revenue DECIMAL(5,2)); INSERT INTO Bakery (bakery_item, type, price, revenue) VALUES ('Almond Croissant', 'Gluten-free', 2.99, 0), ('Chocolate Chip Cookie', 'Gluten-free', 2.49, 0), ('Blueberry Muffin', 'Gluten-free', 3.49, 0);

SELECT SUM(price * revenue) FROM Bakery WHERE type = 'Gluten-free';


Question: Update the record of health equity metric for the county with id 001 to 0.85

CREATE TABLE health_equity_metrics (county_id VARCHAR(255), health_equity_score FLOAT); INSERT INTO health_equity_metrics (county_id, health_equity_score) VALUES ('001', 0.82), ('002', 0.90), ('003', 0.75);

UPDATE health_equity_metrics SET health_equity_score = 0.85 WHERE county_id = '001';


Question: Generate PostgreSQL SQL for: How many clubs have a tries against count of 45 and a losing bonus of 4?

CREATE TABLE table_12886178_5 (tries_for VARCHAR, tries_against VARCHAR, losing_bonus VARCHAR)

SELECT COUNT(tries_for) FROM table_12886178_5 WHERE tries_against = '45' AND losing_bonus = '4';


Question: List all the clients who have invested in Shariah-compliant funds and their total investment amount.

CREATE TABLE clients (client_id INT, name TEXT); CREATE TABLE shariah_compliant_funds (fund_id INT, client_id INT, investment_amount INT); INSERT INTO clients (client_id, name) VALUES (1, 'John Doe'), (2, 'Jane Doe'); INSERT INTO shariah_compliant_funds (fund_id, client_id, investment_amount) VALUES (1, 1, 5000), (2, 1, 7000), (3, 2, 8000);

SELECT clients.name, SUM(shariah_compliant_funds.investment_amount) FROM clients JOIN shariah_compliant_funds ON clients.client_id = shariah_compliant_funds.client_id GROUP BY clients.name;


Question: Which country has the most factories in the 'renewable energy' sector?

CREATE TABLE factories (id INT, name VARCHAR(50), country VARCHAR(50), sector VARCHAR(50)); INSERT INTO factories (id, name, country, sector) VALUES (1, 'Solar Factory', 'Germany', 'renewable energy'), (2, 'Wind Factory', 'China', 'renewable energy'), (3, 'Coal Factory', 'USA', 'non-renewable energy');

SELECT country, COUNT(*) as factory_count FROM factories WHERE sector = 'renewable energy' GROUP BY country ORDER BY factory_count DESC LIMIT 1;


Question: Find the average number of weeks patients with depression are hospitalized in France.

CREATE TABLE patients (patient_id INT, patient_name VARCHAR(50), condition VARCHAR(50), country VARCHAR(50), hospitalization_date DATE, discharge_date DATE); INSERT INTO patients (patient_id, patient_name, condition, country, hospitalization_date, discharge_date) VALUES (1, 'Jean Dupont', 'Depression', 'France', '2021-02-01', '2021-02-14');

SELECT AVG(DATEDIFF(day, patients.hospitalization_date, patients.discharge_date)/7.0) FROM patients WHERE patients.condition = 'Depression' AND patients.country = 'France';


Question: List the exhibitions that have the same city

CREATE TABLE exhibitions (exhibition_id INT PRIMARY KEY, exhibition_name VARCHAR(255), city VARCHAR(255), country VARCHAR(255));

SELECT exhibition_name FROM exhibitions GROUP BY city HAVING COUNT(exhibition_id) > 1;


Question: Show an example of PostgreSQL CREATE COLLATION (example 3).

Explanation: PostgreSQL CREATE COLLATION command.


Question: Generate PostgreSQL SQL for: What is the total number of Total with more than 16 rank for the nation of Romania with more than 0 for silver?

CREATE TABLE table_name_36 (total VARCHAR, silver VARCHAR, rank VARCHAR, nation VARCHAR)

SELECT COUNT(total) FROM table_name_36 WHERE rank > 16 AND nation = 'romania' AND silver > 0;


Question: Generate PostgreSQL SQL for: The person that was born in Sydney died in what year?

CREATE TABLE table_name_47 (born___died VARCHAR, connection_with_australia VARCHAR)

SELECT born___died FROM table_name_47 WHERE connection_with_australia = 'born in sydney';


Question: Generate PostgreSQL SQL for: what is the court surface when the tournament is paris masters?

CREATE TABLE table_name_47 (court_surface VARCHAR, tournament VARCHAR)

SELECT court_surface FROM table_name_47 WHERE tournament = 'paris masters';


Question: Which digital divide initiatives were completed in 2020?

CREATE TABLE Digital_Divide (project_id INT, project_name VARCHAR(100), completion_year INT); INSERT INTO Digital_Divide (project_id, project_name, completion_year) VALUES (1, 'Project X', 2019), (2, 'Project Y', 2020), (3, 'Project Z', 2018);

SELECT project_name FROM Digital_Divide WHERE completion_year = 2020;


Question: What is the minimum pollution level in the Mediterranean Sea?

CREATE TABLE pollution_levels (id INT, location TEXT, pollution_level FLOAT); INSERT INTO pollution_levels (id, location, pollution_level) VALUES (1, 'Mediterranean Sea', 5.0), (2, 'Baltic Sea', 3.0);

SELECT MIN(pollution_level) FROM pollution_levels WHERE location = 'Mediterranean Sea';


Question: List all oil spills that have occurred in the Gulf of Mexico since 2010

CREATE TABLE oil_spills(spill_name VARCHAR(255), location VARCHAR(255), year INT);INSERT INTO oil_spills(spill_name, location, year) VALUES('Deepwater Horizon','Gulf of Mexico',2010),('Ixtoc I','Gulf of Mexico',1979),('Montara','Timor Sea',2009),('Kuwait', 'Persian Gulf', 1991),('Atlantic Empress','Caribbean Sea',1979);

SELECT spill_name FROM oil_spills WHERE location = 'Gulf of Mexico' AND year >= 2010;


Question: Generate PostgreSQL SQL for: What country is Paul Runyan from?

CREATE TABLE table_name_6 (country VARCHAR, name VARCHAR)

SELECT country FROM table_name_6 WHERE name = 'paul runyan';


Question: List the names of organizations that have made social impact investments in Africa.

CREATE TABLE social_impact_investments (investment_id INT, organization_id INT, region VARCHAR(50)); CREATE TABLE organizations (organization_id INT, organization_name VARCHAR(100)); INSERT INTO social_impact_investments (investment_id, organization_id, region) VALUES (1, 1, 'Africa'), (2, 2, 'Europe'), (3, 3, 'Asia'); INSERT INTO organizations (organization_id, organization_name) VALUES (1, 'Global Impact Fund'), (2, 'Renewable Energy Foundation'), (3, 'Community Housing Initiative');

SELECT o.organization_name FROM social_impact_investments i INNER JOIN organizations o ON i.organization_id = o.organization_id WHERE i.region = 'Africa';


Question: Generate PostgreSQL SQL for: What are the market city/market(s) for Rapid City Alternative format?

CREATE TABLE table_134987_3 (target_city__market VARCHAR, city_of_license VARCHAR, format VARCHAR)

SELECT target_city__market FROM table_134987_3 WHERE city_of_license = 'Rapid City' AND format = 'Alternative';


Question: Generate PostgreSQL SQL for: Find the names of the trains that do not pass any station located in London.

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

SELECT T2.name FROM train_station AS T1 JOIN train AS T2 ON T1.train_id = T2.train_id WHERE NOT T1.station_id IN (SELECT T4.station_id FROM train_station AS T3 JOIN station AS T4 ON T3.station_id = T4.station_id WHERE t4.location = 'London');


Question: Generate PostgreSQL SQL for: Which mountain range includes Mount Hubbard?

CREATE TABLE table_name_64 (mountain_range VARCHAR, mountain_peak VARCHAR)

SELECT mountain_range FROM table_name_64 WHERE mountain_peak = 'mount hubbard';


Question: Generate PostgreSQL SQL for: Tell me the date for 2004

CREATE TABLE table_name_35 (date VARCHAR, year VARCHAR)

SELECT date FROM table_name_35 WHERE year = '2004';


Question: Generate PostgreSQL SQL for: What is the name of the site with a CERCLIS ID of prd980512362?

CREATE TABLE table_name_77 (name VARCHAR, cerclis_id VARCHAR)

SELECT name FROM table_name_77 WHERE cerclis_id = 'prd980512362';


Question: Generate PostgreSQL SQL for: What is the Essendon Home Team's venue?

CREATE TABLE table_name_61 (venue VARCHAR, home_team VARCHAR)

SELECT venue FROM table_name_61 WHERE home_team = 'essendon';


Question: Write the DDL statement from PostgreSQL regression test 'rowsecurity' (example 469).

Explanation: DDL from PostgreSQL core regression test for Rowsecurity.


Question: What is the highest daily trading volume for each digital asset category?

CREATE TABLE digital_asset_categories (id INT, name VARCHAR(255)); CREATE TABLE digital_assets (id INT, category_id INT, name VARCHAR(255), daily_trading_volume DECIMAL(10,2)); INSERT INTO digital_asset_categories (id, name) VALUES (1, 'CategoryA'), (2, 'CategoryB'), (3, 'CategoryC'); INSERT INTO digital_assets (id, category_id, name, daily_trading_volume) VALUES (1, 1, 'Asset1', 5000), (2, 1, 'Asset2', 3000), (3, 2, 'Asset3', 2000), (4, 2, 'Asset4', 1000), (5, 3, 'Asset5', 500);

SELECT category_id, MAX(daily_trading_volume) AS Highest_Daily_Trading_Volume FROM digital_assets GROUP BY category_id;


Question: Generate PostgreSQL SQL for: What is the ICAO when the IATA is ika?

CREATE TABLE table_name_19 (icao VARCHAR, iata VARCHAR)

SELECT icao FROM table_name_19 WHERE iata = 'ika';


Question: Write the DDL statement from PostgreSQL regression test 'partition_info' (example 77).

Explanation: DDL from PostgreSQL core regression test for Partition Info.


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

SELECT jsonb_exists_any('{"a":null, "b":"qq"}', ARRAY['b','a']);

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

SELECT count(*) FROM (SELECT jsonb_exists_any('{"a":null, "b":"qq"}', ARRAY['b','a'])) AS _sub;


Question: Generate PostgreSQL SQL for: What is the to par that has ernie els as the player?

CREATE TABLE table_name_43 (to_par VARCHAR, player VARCHAR)

SELECT to_par FROM table_name_43 WHERE player = 'ernie els';


Question: Generate PostgreSQL SQL for: What opponent has euro '84 qualifying as the type and split as the city?

CREATE TABLE table_name_54 (opponent VARCHAR, type_of_game VARCHAR, city VARCHAR)

SELECT opponent FROM table_name_54 WHERE type_of_game = 'euro '84 qualifying' AND city = 'split';


Question: What is the average funding per visual art program, excluding programs with a fundingAmount less than 10000?

CREATE TABLE VisualArtPrograms (programID INT, fundingAmount DECIMAL(10,2)); INSERT INTO VisualArtPrograms (programID, fundingAmount) VALUES (1, 12000.00), (2, 8000.00), (3, 15000.00);

SELECT AVG(fundingAmount) FROM VisualArtPrograms WHERE fundingAmount >= 10000;


Question: Show a query using PostgreSQL contrib extension 'pgcrypto' (example 21).

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


Question: What is the minimum, maximum, and average explainability score of the models developed by different organizations?

CREATE TABLE models_explainability (model_id INT, org_id INT, explainability_score FLOAT); INSERT INTO models_explainability (model_id, org_id, explainability_score) VALUES (101, 1, 0.85), (102, 1, 0.92), (103, 2, 0.88), (104, 2, 0.9), (105, 3, 0.95);

SELECT org_id, MIN(explainability_score) as min_score, MAX(explainability_score) as max_score, AVG(explainability_score) as avg_score FROM models_explainability GROUP BY org_id;


Question: What is the total quantity of eco-friendly fabric used by each textile supplier in the last year?

CREATE TABLE FabricData (FabricID INT, SupplierID INT, FabricType TEXT, Quantity FLOAT, Sustainable BOOLEAN); INSERT INTO FabricData (FabricID, SupplierID, FabricType, Quantity, Sustainable) VALUES (1001, 1, 'Cotton', 500, true), (1002, 1, 'Polyester', 700, false), (1003, 2, 'Hemp', 800, true);

SELECT SupplierID, SUM(Quantity) FROM FabricData WHERE Sustainable = true AND FabricDate >= DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR) GROUP BY SupplierID;


Question: What is the total number of international tourists visiting Canada, grouped by continent of origin?

CREATE TABLE visitors (visitor_country VARCHAR(50), continent VARCHAR(50), total_visits INT); INSERT INTO visitors (visitor_country, continent, total_visits) VALUES ('Canada', 'North America', 25000);

SELECT continent, SUM(total_visits) FROM visitors WHERE visitor_country = 'Canada' GROUP BY continent;


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

SELECT WHERE 1 IN (1, int4(1), int4(2));

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


Question: What is the percentage of students in the "Hillside" school district who did not participate in lifelong learning programs last year?

CREATE TABLE students (student_id INT, district VARCHAR(20), participated_in_llp BOOLEAN, year INT); INSERT INTO students (student_id, district, participated_in_llp, year) VALUES (1, 'Hillside', TRUE, 2021), (2, 'Hillside', FALSE, 2021), (3, 'Townside', TRUE, 2021);

SELECT (COUNT(*) FILTER (WHERE NOT participated_in_llp)) * 100.0 / COUNT(*) FROM students WHERE district = 'Hillside' AND year = 2021;


Question: Show a query using PostgreSQL contrib extension 'cube' (example 199).

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


Question: List the names of rural healthcare centers in India that serve more than 150 patients.

CREATE TABLE healthcare_centers_india_2 (name TEXT, location TEXT, patients_served INT); INSERT INTO healthcare_centers_india_2 (name, location, patients_served) VALUES ('HC A', 'Rural Tamil Nadu', 200), ('HC B', 'Rural Karnataka', 100), ('HC C', 'Rural Andhra Pradesh', 150);

SELECT name FROM healthcare_centers_india_2 WHERE location LIKE 'Rural%' AND patients_served > 150;


Question: Generate PostgreSQL SQL for: What is Illinois 13 District's Party?

CREATE TABLE table_name_59 (party VARCHAR, district VARCHAR)

SELECT party FROM table_name_59 WHERE district = 'illinois 13';


Question: Generate PostgreSQL SQL for: What is the L when the W is 4?

CREATE TABLE table_29565120_2 (l INTEGER, w VARCHAR)

SELECT MIN(l) FROM table_29565120_2 WHERE w = 4;


Question: List all unique departments, ordered from the fewest projects to the most.

CREATE TABLE projects (id INT, engineer_id INT, department VARCHAR(20), cost DECIMAL(10,2)); INSERT INTO projects (id, engineer_id, department, cost) VALUES (1, 1001, 'civil', 5000), (2, 1002, 'civil', 6000), (3, 1003, 'structural', 4000), (4, 1001, 'civil', 7000), (5, 1002, 'civil', 3000), (6, 1003, 'structural', 6000);

SELECT department FROM projects GROUP BY department ORDER BY COUNT(*) ASC;


Question: Find the total number of machines that were added in each year

SELECT YEAR(added_date) AS year, COUNT(*) AS total FROM machines GROUP BY year;


Question: Generate PostgreSQL SQL for: Who are the villains in the episodes where Megan is the storyteller and Lorette LeBlanc is the director?

CREATE TABLE table_10470082_7 (villains VARCHAR, storyteller VARCHAR, director VARCHAR)

SELECT villains FROM table_10470082_7 WHERE storyteller = 'Megan' AND director = 'Lorette LeBlanc';


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

INSERT INTO TIMESTAMPTZ_TBL VALUES ('19970710 173201 America/Does_not_exist');

Explanation: DML from PostgreSQL core regression test for Timestamptz.


Question: List all threat intelligence reports related to 'Cyber Warfare' in the 'Asia-Pacific' region.

CREATE TABLE threat_reports (id INT, report_name TEXT, category TEXT, region TEXT); INSERT INTO threat_reports (id, report_name, category, region) VALUES (1, 'Report A', 'Cyber Warfare', 'Asia-Pacific'), (2, 'Report B', 'Cyber Warfare', 'Europe');

SELECT report_name FROM threat_reports WHERE category = 'Cyber Warfare' AND region = 'Asia-Pacific';


Question: Write the DML statement from PostgreSQL regression test 'matview' (example 2).

Explanation: DML from PostgreSQL core regression test for Matview.


Question: What is the average transaction amount per customer in the 'Retail Banking' division?

CREATE TABLE Customers (CustomerID INT, Division VARCHAR(20)); INSERT INTO Customers (CustomerID, Division) VALUES (1, 'Retail Banking'), (2, 'Retail Banking'), (3, 'Corporate Banking'); CREATE TABLE Transactions (TransactionID INT, CustomerID INT, Amount DECIMAL(10,2)); INSERT INTO Transactions (TransactionID, CustomerID, Amount) VALUES (1, 1, 500.00), (2, 1, 250.00), (3, 2, 750.00), (4, 3, 1500.00);

SELECT AVG(Amount) FROM Transactions INNER JOIN Customers ON Transactions.CustomerID = Customers.CustomerID WHERE Customers.Division = 'Retail Banking';


Question: What is the minimum duration of a song in the pop genre?

CREATE TABLE Song (Title VARCHAR(30), Genre VARCHAR(10), Duration FLOAT); INSERT INTO Song (Title, Genre, Duration) VALUES ('Song1', 'Pop', 3.15), ('Song2', 'Pop', 4.23), ('Song3', 'Pop', 2.87), ('Song4', 'Country', 3.56), ('Song5', 'Rock', 4.55);

SELECT Genre, MIN(Duration) FROM Song WHERE Genre = 'Pop' GROUP BY Genre;


Question: What is the percentage of the population that is obese in each age group in the United States?

CREATE TABLE obesity_rates (id INT, age_group TEXT, obesity_rate DECIMAL(4,2), country TEXT); INSERT INTO obesity_rates (id, age_group, obesity_rate, country) VALUES (1, '0-18', 15.3, 'United States'), (2, '19-34', 27.2, 'United States'), (3, '35-49', 36.6, 'United States'), (4, '50-64', 40.2, 'United States'), (5, '65+', 39.5, 'United States');

SELECT age_group, obesity_rate FROM obesity_rates WHERE country = 'United States';


Question: What is the total mass of spacecraft manufactured by Galactic Inc, grouped by the continent of their origin?

CREATE TABLE SpacecraftManufacturing (Manufacturer VARCHAR(255), Country VARCHAR(255), SpacecraftModel VARCHAR(255), SpacecraftMass INT); INSERT INTO SpacecraftManufacturing (Manufacturer, Country, SpacecraftModel, SpacecraftMass) VALUES ('SpaceTech Corp', 'USA', 'SpaceshipX', 10000), ('SpaceTech Corp', 'USA', 'SpaceshipY', 12000), ('Galactic Inc', 'Canada', 'SpaceshipA', 8000);

SELECT SUM(SpacecraftMass) AS Total_Spacecraft_Mass, CONCAT(SUBSTRING(Country, 1, 2), '%') AS Continent FROM SpacecraftManufacturing WHERE Manufacturer = 'Galactic Inc' GROUP BY Continent;


Question: What are the names and maximum depths for submersibles certified for deep-sea use?

CREATE TABLE submersibles (name VARCHAR(255), manufacturer VARCHAR(255), max_depth INT); INSERT INTO submersibles (name, manufacturer, max_depth) VALUES ('Sub1', 'Manufacturer1', 7000);

SELECT name, max_depth FROM submersibles WHERE max_depth >= 6000;


Question: Generate PostgreSQL SQL for: Which Score in the final has an Outcome of winner, and a Surface of hard (i)?

CREATE TABLE table_name_12 (score_in_the_final VARCHAR, outcome VARCHAR, surface VARCHAR)

SELECT score_in_the_final FROM table_name_12 WHERE outcome = 'winner' AND surface = 'hard (i)';


Question: Generate PostgreSQL SQL for: What is the Home with a Visitor of chicago, and a Series with 3 – 2?

CREATE TABLE table_name_82 (home VARCHAR, visitor VARCHAR, series VARCHAR)

SELECT home FROM table_name_82 WHERE visitor = 'chicago' AND series = '3 – 2';


Question: What is the number of legal aid clinics in each state in the US, and how many clients do they serve on average?

CREATE TABLE us_legal_aid(id INT, state VARCHAR(255), clients_served INT);

SELECT state, AVG(clients_served) AS average_clients_served FROM us_legal_aid GROUP BY state;


Question: Who are the investors who made investments in a specific country?

CREATE TABLE Investments (InvestmentID INT, InvestorID INT, Country VARCHAR(20), Amount INT); INSERT INTO Investments (InvestmentID, InvestorID, Country, Amount) VALUES (1, 1, 'USA', 4000), (2, 1, 'Canada', 3000), (3, 2, 'Mexico', 5000), (4, 2, 'Brazil', 6000), (5, 3, 'USA', 7000), (6, 3, 'Canada', 8000); CREATE TABLE Investors (InvestorID INT, Name VARCHAR(20), Gender VARCHAR(10)); INSERT INTO Investors (InvestorID, Name, Gender) VALUES (1, 'John Doe', 'Male'), (2, 'Jane Smith', 'Female'), (3, 'Jim Brown', 'Male');

SELECT Investors.Name FROM Investors JOIN Investments ON Investors.InvestorID = Investments.InvestorID WHERE Investments.Country = 'USA';


Question: Generate PostgreSQL SQL for: Which week's game was attended by 65,272 people?

CREATE TABLE table_name_18 (week VARCHAR, attendance VARCHAR)

SELECT week FROM table_name_18 WHERE attendance = '65,272';


Question: PostgreSQL Query: show example 5.

INSERT INTO weather (city, temp_lo, temp_hi, prcp, date) VALUES ('San Francisco', 43, 57, 0.0, '1994-11-29');

Explanation: Example from PostgreSQL documentation on Query.


Question: Which countries have the highest hotel rating?

CREATE TABLE Hotels (hotel_id INT, hotel_name TEXT, country TEXT, rating FLOAT); INSERT INTO Hotels (hotel_id, hotel_name, country, rating) VALUES (1, 'Hotel A', 'Spain', 4.3), (2, 'Hotel B', 'Spain', 4.5), (3, 'Hotel C', 'France', 4.7);

SELECT country, MAX(rating) AS max_rating FROM Hotels GROUP BY country;


Question: Generate PostgreSQL SQL for: What position is there when the main contestant is Vishal Singh and the scores are 1 + 7 + 5 = 13?

CREATE TABLE table_name_21 (position VARCHAR, main_contestant VARCHAR, scores_by_each_individual_judge VARCHAR)

SELECT position FROM table_name_21 WHERE main_contestant = 'vishal singh' AND scores_by_each_individual_judge = 1 + 7 + 5 = 13;


Question: Which freight forwarders have handled more than 1000 shipments in total?

CREATE TABLE freight_forwarder (id INT, name VARCHAR(25)); INSERT INTO freight_forwarder (id, name) VALUES (1, 'ABC Freight'), (2, 'XYZ Logistics'), (3, 'Global Shipping'); CREATE TABLE shipment (id INT, forwarder_id INT, weight INT); INSERT INTO shipment (id, forwarder_id, weight) VALUES (1, 1, 500), (2, 1, 800), (3, 2, 300), (4, 3, 1200), (5, 1, 900);

SELECT f.name, COUNT(s.id) FROM freight_forwarder f JOIN shipment s ON f.id = s.forwarder_id GROUP BY f.name HAVING COUNT(s.id) > 1000;


Question: What is the difference between the average sustainable fabric cost per order for male and female customers?

CREATE TABLE orders (order_id INT, customer_id INT, sustainable_fabric_cost DECIMAL(5,2));CREATE TABLE customers (customer_id INT, gender VARCHAR(10));

SELECT gender, AVG(sustainable_fabric_cost) - LAG(AVG(sustainable_fabric_cost)) OVER (ORDER BY gender) FROM orders INNER JOIN customers ON orders.customer_id = customers.customer_id GROUP BY gender;


Question: Generate PostgreSQL SQL for: What is Draws, when Losses is "Did Not Qualify"?

CREATE TABLE table_name_76 (draws VARCHAR, losses VARCHAR)

SELECT draws FROM table_name_76 WHERE losses = 'did not qualify';


Question: Generate PostgreSQL SQL for: What was the language for the movie "Late Bloomers"?

CREATE TABLE table_22034853_1 (language_s_ VARCHAR, film_title_used_in_nomination VARCHAR)

SELECT language_s_ FROM table_22034853_1 WHERE film_title_used_in_nomination = 'Late Bloomers';


Question: How many wells were drilled in the Gulf of Mexico in 2022?

CREATE TABLE DrillingPlatforms (PlatformID int, PlatformName varchar(50), Location varchar(50), PlatformType varchar(50), NumberOfWells int); INSERT INTO DrillingPlatforms (PlatformID, PlatformName, Location, PlatformType, NumberOfWells) VALUES (1, 'A01', 'North Sea', 'Offshore', 10), (2, 'B02', 'Gulf of Mexico', 'Offshore', 15), (3, 'C03', 'Texas', 'Onshore', 6), (4, 'D04', 'Texas', 'Onshore', 20); CREATE TABLE DrillingLogs (DrillingLogID int, PlatformID int, WellID int, DrillingDate date); INSERT INTO DrillingLogs (DrillingLogID, PlatformID, WellID, DrillingDate) VALUES (1, 2, 101, '2022-01-01'), (2, 2, 102, '2022-01-02'), (3, 5, 201, '2022-01-03'), (4, 5, 202, '2022-01-04');

SELECT COUNT(*) FROM DrillingLogs JOIN DrillingPlatforms ON DrillingLogs.PlatformID = DrillingPlatforms.PlatformID WHERE DrillingPlatforms.Location = 'Gulf of Mexico' AND YEAR(DrillingLogs.DrillingDate) = 2022;


Question: Which mines in California have an environmental impact score above 75?

CREATE TABLE mines (id INT, name TEXT, state TEXT, environmental_score INT); INSERT INTO mines (id, name, state, environmental_score) VALUES (1, 'Delta Mine', 'CA', 85), (2, 'Echo Mine', 'CA', 65), (3, 'Foxtrot Mine', 'CA', 78);

SELECT name, environmental_score FROM mines WHERE state = 'CA' AND environmental_score > 75;


Question: Write the DML statement from PostgreSQL regression test 'vacuum' (example 66).

Explanation: DML from PostgreSQL core regression test for Vacuum.


Question: Generate PostgreSQL SQL for: What's the change over same quarter the previous year in the period when the 89.6% of the trains arrive within 5 minutes of scheduled time (over three months)?

CREATE TABLE table_171748_3 (change_over_same_quarter_the_previous_year VARCHAR, _percentage_trains_arriving_within_5_mins_of_scheduled_time__over_three_months_ VARCHAR)

SELECT change_over_same_quarter_the_previous_year FROM table_171748_3 WHERE _percentage_trains_arriving_within_5_mins_of_scheduled_time__over_three_months_ = '89.6%';


Question: How many female employees work in the 'sustainable_practices' table?

CREATE TABLE sustainable_practices (employee_id INT, first_name VARCHAR(50), last_name VARCHAR(50), gender VARCHAR(10), position VARCHAR(50), hours_worked INT); INSERT INTO sustainable_practices (employee_id, first_name, last_name, gender, position, hours_worked) VALUES (3, 'Alice', 'Johnson', 'Female', 'Analyst', 30); INSERT INTO sustainable_practices (employee_id, first_name, last_name, gender, position, hours_worked) VALUES (4, 'Bob', 'Williams', 'Male', 'Technician', 35); INSERT INTO sustainable_practices (employee_id, first_name, last_name, gender, position, hours_worked) VALUES (8, 'Olga', 'Ivanova', 'Female', 'Technician', 40); INSERT INTO sustainable_practices (employee_id, first_name, last_name, gender, position, hours_worked) VALUES (9, 'Sara', 'Lopez', 'Female', 'Analyst', 35);

SELECT COUNT(*) FROM sustainable_practices WHERE gender = 'Female';


Question: Generate PostgreSQL SQL for: Which Japanese Title has a TV Station of ntv?

CREATE TABLE table_name_19 (japanese_title VARCHAR, tv_station VARCHAR)

SELECT japanese_title FROM table_name_19 WHERE tv_station = 'ntv';


Question: Generate PostgreSQL SQL for: Show the id and star rating of each hotel, ordered by its price from low to high.

CREATE TABLE HOTELS (hotel_id VARCHAR, star_rating_code VARCHAR, price_range VARCHAR)

SELECT hotel_id, star_rating_code FROM HOTELS ORDER BY price_range;


Question: What was the number of disaster response operations in Pakistan in 2018?

CREATE TABLE disaster_response (disaster_name VARCHAR(255), country VARCHAR(255), operation_start_date DATE, operation_end_date DATE); INSERT INTO disaster_response (disaster_name, country, operation_start_date, operation_end_date) VALUES ('Flood', 'Pakistan', '2018-01-01', '2018-04-30'), ('Earthquake', 'Pakistan', '2018-10-01', '2018-12-31');

SELECT COUNT(*) FROM disaster_response WHERE country = 'Pakistan' AND YEAR(operation_start_date) = 2018 AND YEAR(operation_end_date) = 2018;


Question: Write the DML statement from PostgreSQL regression test 'fast_default' (example 34).

Explanation: DML from PostgreSQL core regression test for Fast Default.


Question: What is the total cost of inventory for non-vegetarian menu items in the month of January 2022?

CREATE TABLE Menu (menu_id INT, menu_name VARCHAR(20), is_vegetarian BOOLEAN); CREATE TABLE Inventory (inventory_id INT, menu_id INT, inventory_cost FLOAT); INSERT INTO Menu (menu_id, menu_name, is_vegetarian) VALUES (1, 'Breakfast', FALSE), (2, 'Lunch', FALSE), (3, 'Dinner', TRUE), (4, 'Steak', FALSE); INSERT INTO Inventory (inventory_id, menu_id, inventory_cost) VALUES (1, 1, 5.0), (2, 2, 3.5), (3, 4, 15.0), (4, 1, 8.0), (5, 3, 7.0);

SELECT SUM(Inventory.inventory_cost) FROM Inventory INNER JOIN Menu ON Inventory.menu_id = Menu.menu_id WHERE Menu.is_vegetarian = FALSE AND MONTH(Inventory.inventory_date) = 1 AND YEAR(Inventory.inventory_date) = 2022;


Question: What is the maximum budget allocated for defense diplomacy by countries in Europe in 2018?

CREATE TABLE DefenseDiplomacy (id INT, country VARCHAR(50), budget DECIMAL(10,2), year INT); INSERT INTO DefenseDiplomacy (id, country, budget, year) VALUES (1, 'France', 8000000, 2018), (2, 'Germany', 9000000, 2018), (3, 'Italy', 7000000, 2018);

SELECT MAX(budget) FROM DefenseDiplomacy WHERE country IN ('France', 'Germany', 'Italy') AND year = 2018;


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

SELECT * FROM pg_get_wal_stats('FFFFFFFF/FFFFFFFE', 'FFFFFFFF/FFFFFFFF');

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


Question: Show the gas production of the well with ID 5 in the Eagle Ford region

CREATE TABLE if not exists wells (well_id int, region varchar(50), production_year int, gas_production int);INSERT INTO wells (well_id, region, production_year, gas_production) VALUES (5, 'Eagle Ford', 2019, 550000), (6, 'Eagle Ford', 2020, 600000), (7, 'Marcellus Shale', 2018, 850000);

SELECT gas_production FROM wells WHERE well_id = 5 AND region = 'Eagle Ford';


Question: Show a query using PostgreSQL contrib extension 'pgcrypto' (example 2).

select pgp_pub_decrypt(
		pgp_pub_encrypt('Secret msg', dearmor(pubkey)),
		dearmor(seckey))
from keytbl where keytbl.id=2;


Question: Generate PostgreSQL SQL for: Where was the third bridge over panama canal?

CREATE TABLE table_name_83 (location VARCHAR, name VARCHAR)

SELECT location FROM table_name_83 WHERE name = 'third bridge over panama canal';


Question: Count the number of startups founded by underrepresented minorities each year

CREATE TABLE diversity (company_id INT, founder_minority TEXT); INSERT INTO diversity (company_id, founder_minority) VALUES (1, 'Latinx'); INSERT INTO diversity (company_id, founder_minority) VALUES (2, 'Asian');

SELECT founding_year, COUNT(*) FROM company c INNER JOIN diversity d ON c.id = d.company_id WHERE founder_minority IS NOT NULL GROUP BY founding_year;


Question: What is the average safety score for each AI algorithm in the 'creative_ai' database?

CREATE TABLE creative_ai.ai_algorithms (ai_algorithm_id INT PRIMARY KEY, ai_algorithm VARCHAR(255), safety_score FLOAT); INSERT INTO creative_ai.ai_algorithms (ai_algorithm_id, ai_algorithm, safety_score) VALUES (1, 'Generative Adversarial Networks', 0.75), (2, 'Transformers', 0.85), (3, 'Deep Reinforcement Learning', 0.65);

SELECT ai_algorithm, AVG(safety_score) as avg_safety_score FROM creative_ai.ai_algorithms GROUP BY ai_algorithm;


Question: Show a SQL definition from the pg_partman project (pg_partman--3.2.1--4.0.0, item 47).

CREATE OR REPLACE FUNCTION @extschema@.drop_partition_id(p_parent_table text, p_retention bigint DEFAULT NULL, p_keep_table boolean DEFAULT NULL, p_keep_index boolean DEFAULT NULL, p_retention_schema text DEFAULT NULL) RETURNS int
    LANGUAGE plpgsql
    AS $$
DECLARE

ex_context                  text;
ex_detail                   text;
ex_hint                     text;
ex_message                  text;
v_adv_lock                  boolean;
v_control                   text;
v_control_type              text;
v_count                     int;
v_drop_count                int := 0;
v_index                     record;
v_job_id                    bigint;
v_jobmon                    boolean;
v_jobmon_schema             text;
v_max                       bigint;
v_new_search_path           text := '@extschema@,pg_temp';
v_old_search_path           text;
v_parent_schema             text;
v_parent_tablename          text;
v_partition_interval        bigint;
v_partition_id              bigint;
v_partition_type            text;
v_retention                 bigint;
v_retention_keep_index      boolean;
v_retention_keep_table      boolean;
v_retention_schema          text;
v_row                       record;
v_row_max_id                record;
v_step_id                   bigint;

BEGIN
/*
 * Function to drop child tables from an id-based partition set.
 * Options to move table to different schema, drop only indexes or actually drop the table from the database.
 */

v_adv_lock := pg_try_advisory_xact_lock(hashtext('pg_partman drop_partition_id'));
IF v_adv_lock = 'false' THEN
    RAISE NOTICE 'drop_partition_id already running.';
    RETURN 0;
END IF;

IF p_retention IS NULL THEN
    SELECT
        partition_interval::bigint
        , partition_type
        , control
        , retention::bigint
        , retention_keep_table
        , retention_keep_index
        , retention_schema
        , jobmon
    INTO
        v_partition_interval
        , v_partition_type
        , v_control
        , v_retention
        , v_retention_keep_table
        , v_retention_keep_index
        , v_retention_schema
        , v_jobmon
    FROM @extschema@.part_config
    WHERE parent_table = p_parent_table
    AND retention IS NOT NULL;

    IF v_partition_interval IS NULL THEN
        RAISE EXCEPTION 'Configuration for given parent table with a retention period not found: %', p_parent_table;
    END IF;
ELSE -- Allow override of configuration options
     SELECT
        partition_interval::bigint
        , partition_type
        , control
        , retention_keep_table
        , retention_keep_index
        , retention_schema
        , jobmon
    INTO
        v_partition_interval
        , v_partition_type
        , v_control
        , v_retention_keep_table
        , v_retention_keep_index
        , v_retention_schema
        , v_jobmon
    FROM @extschema@.part_config
    WHERE parent_table = p_parent_table;
    v_retention := p_retention;

    IF v_partition_interval IS NULL THEN
        RAISE EXCEPTION 'Configuration for given parent table not found: %', p_parent_table;
    END IF;
END IF;

SELECT general_type INTO v_control_type FROM @extschema@.check_control_type(v_parent_schema, v_parent_tablename, v_control);
IF v_control_type <> 'id' THEN
    RAISE EXCEPTION 'Data type of control column in given partition set is not an integer type';
END IF;

SELECT current_setting('search_path') INTO v_old_search_path;
IF v_jobmon THEN
    SELECT nspname INTO v_jobmon_schema FROM pg_catalog.pg_namespace n, pg_catalog.pg_extension e WHERE e.extname = 'pg_jobmon'::name AND e.extnamespace = n.oid;
    IF v_jobmon_schema IS NOT NULL THEN
        v_new_search_path := '@extschema@,'||v_jobmon_schema||',pg_temp';
    END IF;
END IF;
EXECUTE format('SELECT set_config(%L, %L, %L)', 'search_path', v_new_search_path, 'false');

IF p_keep_table IS NOT NULL THEN
    v_retention_keep_table = p_keep_table;
END IF;
IF p_keep_index IS NOT NULL THEN
    v_retention_keep_index = p_keep_index;
END IF;
IF p_retention_schema IS NOT NULL THEN
    v_retention_schema = p_retention_schema;
END IF;

SELECT schemaname, tablename INTO v_parent_schema, v_parent_tablename
FROM pg_catalog.pg_tables
WHERE schemaname = split_part(p_parent_table, '.', 1)::name
AND tablename = split_part(p_parent_table, '.', 2)::name;

-- Loop through child tables starting from highest to get current max value in partition set
-- Avoids doing a scan on entire partition set and/or getting any values accidentally in parent.
FOR v_row_max_id IN
    SELECT partition_schemaname, partition_tablename FROM @extschema@.show_partitions(p_parent_table, 'DESC')
LOOP
        EXECUTE format('SELECT max(%I) FROM %I.%I', v_control, v_row_max_id.partition_schemaname, v_row_max_id.partition_tablename) INTO v_max;
        IF v_max IS NOT NULL THEN
            EXIT;
        END IF;
END LOOP;

-- Loop through child tables of the given parent
FOR v_row IN
    SELECT partition_schemaname, partition_tablename FROM @extschema@.show_partitions(p_parent_table, 'ASC')
LOOP
     SELECT child_start_id INTO v_partition_id FROM @extschema@.show_partition_info(v_row.partition_schemaname||'.'||v_row.partition_tablename
        , v_partition_interval::text
        , p_parent_table);

    -- Add one interval since partition names contain the start of the constraint period
    IF v_retention <= (v_max - (v_partition_id + v_partition_interval)) THEN

        -- Do not allow final partition to be dropped
        SELECT count(*) INTO v_count FROM @extschema@.show_partitions(p_parent_table);
        IF v_count = 1 THEN
            RAISE WARNING 'Attempt to drop final partition in partition set % as part of retention policy. Advise reviewing retention policy and/or data entry into the partition set.', p_parent_table;
            CONTINUE;
        END IF;

        -- Only create a jobmon entry if there's actual retention work done
        IF v_jobmon_schema IS NOT NULL AND v_job_id IS NULL THEN
            v_job_id := add_job(format('PARTMAN DROP ID PARTITION: %s', p_parent_table));
        END IF;

        IF v_jobmon_schema IS NOT NULL THEN
            v_step_id := add_step(v_job_id, format('Detach/Uninherit table %s.%s from %s', v_row.partition_schemaname, v_row.partition_tablename, p_parent_table));
        END IF;
        IF v_partition_type = 'native' THEN
            EXECUTE format('ALTER TABLE %I.%I DETACH PARTITION %I.%I'
                , v_parent_schema
                , v_parent_tablename
                , v_row.partition_schemaname
                , v_row.partition_tablename);
        ELSE
            EXECUTE format('ALTER TABLE %I.%I NO INHERIT %I.%I'
                , v_row.partition_schemaname
                , v_row.partition_tablename
                , v_parent_schema
                , v_parent_tablename);
            IF v_jobmon_schema IS NOT NULL THEN
                PERFORM update_step(v_step_id, 'OK', 'Done');
            END IF;
        END IF;
        IF v_retention_schema IS NULL THEN
            IF v_retention_keep_table = false THEN
                IF v_jobmon_schema IS NOT NULL THEN
                    v_step_id := add_step(v_job_id, format('Drop table %s.%s', v_row.partition_schemaname, v_row.partition_tablename));
                END IF;
                EXECUTE format('DROP TABLE %I.%I CASCADE', v_row.partition_schemaname, v_row.partition_tablename);
                IF v_jobmon_schema IS NOT NULL THEN
                    PERFORM update_step(v_step_id, 'OK', 'Done');
                END IF;
            ELSIF v_retention_keep_index = false THEN
                FOR v_index IN
                     WITH child_info AS (
                        SELECT c1.oid
                        FROM pg_catalog.pg_class c1
                        JOIN pg_catalog.pg_namespace n1 ON c1.relnamespace = n1.oid
                        WHERE c1.relname = v_row.partition_tablename::name
                        AND n1.nspname = v_row.partition_schema::name
                    )
                    SELECT c.relname as name
                        , con.conname
                    FROM pg_catalog.pg_index i
                    JOIN pg_catalog.pg_class c ON i.indexrelid = c.oid
                    LEFT JOIN pg_catalog.pg_constraint con ON i.indexrelid = con.conindid
                    JOIN child_info ON i.indrelid = child_info.oid
                LOOP
                    IF v_jobmon_schema IS NOT NULL THEN
                        v_step_id := add_step(v_job_id, format('Drop index %s from %s.%s'
                            , v_index.name
                            , v_row.partition_schemaname
                            , v_row.partition_tablename));
                    END IF;
                    IF v_index.conname IS NOT NULL THEN
                        EXECUTE format('ALTER TABLE %I.%I DROP CONSTRAINT %I', v_row.partition_schemaname, v_row.partition_tablename, v_index.conname);
                    ELSE
                        EXECUTE format('DROP INDEX %I.%I', v_row.partition_schemaname, v_index.name);
                    END IF;
                    IF v_jobmon_schema IS NOT NULL THEN
                        PERFORM update_step(v_step_id, 'OK', 'Done');
                    END IF;
                END LOOP;
            END IF;
        ELSE -- Move to new schema
            IF v_jobmon_schema IS NOT NULL THEN
                v_step_id := add_step(v_job_id, format('Moving table %s.%s to schema %s'
                                                        , v_row.partition_schemaname
                                                        , v_row.partition_tablename
                                                        , v_retention_schema));
            END IF;

            EXECUTE format('ALTER TABLE %I.%I SET SCHEMA %I'
                    , v_row.partition_schemaname
                    , v_row.partition_tablename
                    , v_retention_schema);

            IF v_jobmon_schema IS NOT NULL THEN
                PERFORM update_step(v_step_id, 'OK', 'Done');
            END IF;
        END IF; -- End retention schema if

        -- If child table is a subpartition, remove it from part_config & part_config_sub (should cascade due to FK)
        DELETE FROM @extschema@.part_config WHERE parent_table = v_row.partition_schemaname ||'.'||v_row.partition_tablename;

        v_drop_count := v_drop_count + 1;
    END IF; -- End retention check IF

END LOOP; -- End child table loop

IF v_jobmon_schema IS NOT NULL THEN
    IF v_job_id IS NOT NULL THEN
        v_step_id := add_step(v_job_id, 'Finished partition drop maintenance');
        PERFORM update_step(v_step_id, 'OK', format('%s partitions dropped.', v_drop_count));
        PERFORM close_job(v_job_id);
    END IF;
END IF;

EXECUTE format('SELECT set_config(%L, %L, %L)', 'search_path', v_old_search_path, 'false');

RETURN v_drop_count;

EXCEPTION
    WHEN OTHERS THEN
        GET STACKED DIAGNOSTICS ex_message = MESSAGE_TEXT,
                                ex_context = PG_EXCEPTION_CONTEXT,
                                ex_detail = PG_EXCEPTION_DETAIL,
                                ex_hint = PG_EXCEPTION_HINT;
        IF v_jobmon_schema IS NOT NULL THEN
            IF v_job_id IS NULL THEN
                EXECUTE format('SELECT %I.add_job(''PARTMAN DROP ID PARTITION: %s'')', v_jobmon_schema, p_parent_table) INTO v_job_id;
                EXECUTE format('SELECT %I.add_step(%s, ''EXCEPTION before job logging started'')', v_jobmon_schema, v_job_id, p_parent_table) INTO v_step_id;
            ELSIF v_step_id IS NULL THEN
                EXECUTE format('SELECT %I.add_step(%s, ''EXCEPTION before first step logged'')', v_jobmon_schema, v_job_id) INTO v_step_id;
            END IF;
            EXECUTE format('SELECT %I.update_step(%s, ''CRITICAL'', %L)', v_jobmon_schema, v_step_id, 'ERROR: '||coalesce(SQLERRM,'unknown'));
            EXECUTE format('SELECT %I.fail_job(%s)', v_jobmon_schema, v_job_id);
        END IF;
        RAISE EXCEPTION '%
CONTEXT: %
DETAIL: %
HINT: %', ex_message, ex_context, ex_detail, ex_hint;
END
$$;

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


Question: PostgreSQL regression test 'misc': Write the SELECT query (example 56).

SELECT name(equipment_named_ambiguous_1b(hobby_construct_named(text 'skywalking', text 'mer')));

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

SELECT count(*) FROM (SELECT name(equipment_named_ambiguous_1b(hobby_construct_named(text 'skywalking', text 'mer')))) AS _sub;


Question: What is the maximum number of events attended by a fan?

SELECT MAX(event_count) as max_events FROM (SELECT fan_id, COUNT(*) as event_count FROM events GROUP BY fan_id) as subquery;


Question: Generate PostgreSQL SQL for: How many field goals did Walter Shaw make?

CREATE TABLE table_14342210_14 (field_goals__5_points_ VARCHAR, player VARCHAR)

SELECT COUNT(field_goals__5_points_) FROM table_14342210_14 WHERE player = 'Walter Shaw';


Question: What is the success rate of cases with 'Murphy' as the lead attorney?

CREATE TABLE attorneys (attorney_id INT, name VARCHAR(50)); INSERT INTO attorneys (attorney_id, name) VALUES (1, 'Smith'), (2, 'Johnson'), (3, 'Williams'), (4, 'Murphy'); CREATE TABLE cases (case_id INT, attorney_id INT, is_success BOOLEAN); INSERT INTO cases (case_id, attorney_id, is_success) VALUES (1, 2, TRUE), (2, 1, FALSE), (3, 3, TRUE), (4, 4, TRUE);

SELECT COUNT(*) / (SELECT COUNT(*) FROM cases WHERE cases.attorney_id = attorneys.attorney_id) AS success_rate FROM attorneys INNER JOIN cases ON attorneys.attorney_id = cases.attorney_id WHERE attorneys.name = 'Murphy' AND is_success = TRUE;


Question: What was the total number of visitors to each continent in 2021?

CREATE TABLE if not exists VisitorContinents (Continent VARCHAR(50), Country VARCHAR(50), Visitors INT); INSERT INTO VisitorContinents (Continent, Country, Visitors) VALUES ('Africa', 'Egypt', 120000), ('Asia', 'Japan', 240000), ('Europe', 'France', 300000), ('South America', 'Brazil', 140000), ('North America', 'Canada', 170000), ('Oceania', 'Australia', 270000);

SELECT a.Continent, SUM(a.Visitors) AS TotalVisitors FROM VisitorContinents a WHERE a.Year = 2021 GROUP BY a.Continent;


Question: Find total expenses and income for each month in the 'expenses' and 'income' tables

CREATE TABLE expenses (expense_id INT, expense_amount DECIMAL, expense_date DATE); CREATE TABLE income (income_id INT, income_amount DECIMAL, income_date DATE);

SELECT DATE_FORMAT(expenses.expense_date, '%Y-%m') as month, SUM(expenses.expense_amount) as total_expenses, SUM(income.income_amount) as total_income FROM expenses FULL OUTER JOIN income ON DATE_FORMAT(expenses.expense_date, '%Y-%m') = DATE_FORMAT(income.income_date, '%Y-%m') GROUP BY month;


Question: Generate PostgreSQL SQL for: When the away team was Bolton Wanderers, what was the score?

CREATE TABLE table_name_83 (score VARCHAR, away_team VARCHAR)

SELECT score FROM table_name_83 WHERE away_team = 'bolton wanderers';


Question: Generate PostgreSQL SQL for: What was the constructor of the car that Hermann Lang drove after 1935?

CREATE TABLE table_name_89 (constructor VARCHAR, year VARCHAR, driver VARCHAR)

SELECT constructor FROM table_name_89 WHERE year > 1935 AND driver = 'hermann lang';


Question: What is the average donation amount in Q1 2023 from returning donors in Latin America?

CREATE TABLE Donors (DonorID int, DonorType varchar(50), Country varchar(50), AmountDonated numeric(18,2), DonationDate date, IsReturningDonor bit); INSERT INTO Donors (DonorID, DonorType, Country, AmountDonated, DonationDate, IsReturningDonor) VALUES (1, 'Individual', 'Brazil', 3000, '2023-01-02', 1), (2, 'Organization', 'Argentina', 8000, '2023-01-03', 0);

SELECT AVG(AmountDonated) FROM Donors WHERE DonorType = 'Individual' AND Country LIKE 'Latin America%' AND IsReturningDonor = 1 AND QUARTER(DonationDate) = 1 AND YEAR(DonationDate) = 2023;


Question: Add a new student named "Jamie" with a major in "Computer Science" and a GPA of 3.8 to the "students" table.

CREATE TABLE students (student_id INT, name VARCHAR(255), major VARCHAR(255), gpa DECIMAL(3,2));

INSERT INTO students (name, major, gpa) VALUES ('Jamie', 'Computer Science', 3.8);


Question: What is the minimum budget allocated for any service in Florida?

CREATE TABLE service_budget (state VARCHAR(50), service VARCHAR(50), budget INT); INSERT INTO service_budget (state, service, budget) VALUES ('Florida', 'Education', 5000000), ('Florida', 'Highway Maintenance', 3000000);

SELECT MIN(budget) FROM service_budget WHERE state = 'Florida';


Question: Generate PostgreSQL SQL for: What stake has 16 wards/branches in Arkansas?

CREATE TABLE table_name_97 (stake VARCHAR, wards__branches_in_arkansas VARCHAR)

SELECT stake FROM table_name_97 WHERE wards__branches_in_arkansas = 16;


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

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


Question: Generate PostgreSQL SQL for: What opponent has l 27-7 as the result?

CREATE TABLE table_name_83 (opponent VARCHAR, result VARCHAR)

SELECT opponent FROM table_name_83 WHERE result = 'l 27-7';


Question: Generate PostgreSQL SQL for: Which week was the game on December 14, 1967?

CREATE TABLE table_name_27 (week VARCHAR, date VARCHAR)

SELECT week FROM table_name_27 WHERE date = 'december 14, 1967';


Question: Generate PostgreSQL SQL for: What is the overall draft number for the running back drafted after round 1 from fresno state?

CREATE TABLE table_name_68 (overall INTEGER, college VARCHAR, position VARCHAR, round VARCHAR)

SELECT SUM(overall) FROM table_name_68 WHERE position = 'running back' AND round > 1 AND college = 'fresno state';


Question: What is the minimum and maximum number of art pieces created by artists from the Middle East and North Africa in the last decade?

SELECT MIN(num_pieces), MAX(num_pieces) FROM ArtPieces WHERE artist_region IN ('Middle East', 'North Africa') AND creation_date >= DATEADD(YEAR, -10, GETDATE());


Question: Generate PostgreSQL SQL for: Who did the high points of game 5?

CREATE TABLE table_11960196_3 (high_points VARCHAR, game VARCHAR)

SELECT high_points FROM table_11960196_3 WHERE game = 5;


Question: How many garments were produced in each region using recycled materials?

CREATE TABLE Recycled_Material_Garments (id INT, region VARCHAR, quantity INT);

SELECT region, SUM(quantity) FROM Recycled_Material_Garments GROUP BY region;


Question: Generate PostgreSQL SQL for: When Geelong is the Away team, what did the Home team score?

CREATE TABLE table_name_2 (home_team VARCHAR, away_team VARCHAR)

SELECT home_team AS score FROM table_name_2 WHERE away_team = 'geelong';


Question: Generate PostgreSQL SQL for: What is SECOND, when SIXTH is Victoria?

CREATE TABLE table_name_18 (second VARCHAR, sixth VARCHAR)

SELECT second FROM table_name_18 WHERE sixth = 'victoria';


Question: What are the names and case IDs of all cases that have been resolved in the state of California?

CREATE TABLE court_cases (case_id INT, case_status TEXT, case_state TEXT); INSERT INTO court_cases (case_id, case_status, case_state) VALUES (66666, 'Resolved', 'California');

SELECT case_id, case_status FROM court_cases WHERE case_state = 'California' AND case_status = 'Resolved';


Question: Generate PostgreSQL SQL for: What was the result for the opponent being gerardi rinaldi in 2009?

CREATE TABLE table_name_14 (result VARCHAR, date VARCHAR, opponent VARCHAR)

SELECT result FROM table_name_14 WHERE date = 2009 AND opponent = 'gerardi rinaldi';


Question: What are the endangered languages in South America?

CREATE TABLE EndangeredLanguages (id INT, language VARCHAR(50), status VARCHAR(50), country VARCHAR(50)); INSERT INTO EndangeredLanguages (id, language, status, country) VALUES (1, 'Mapudungun', 'Vulnerable', 'Chile'); INSERT INTO EndangeredLanguages (id, language, status, country) VALUES (2, 'Quechua', 'Vulnerable', 'Peru');

SELECT EndangeredLanguages.language FROM EndangeredLanguages WHERE EndangeredLanguages.status = 'Vulnerable' AND EndangeredLanguages.country IN ('Argentina', 'Bolivia', 'Brazil', 'Chile', 'Colombia', 'Ecuador', 'Guyana', 'Paraguay', 'Peru', 'Suriname', 'Uruguay', 'Venezuela');


Question: What is the average salary of engineers in 'asia_mines'?

CREATE SCHEMA if not exists asia_schema;CREATE TABLE asia_schema.asia_mines (id INT, name VARCHAR, role VARCHAR, salary DECIMAL);INSERT INTO asia_schema.asia_mines (id, name, role, salary) VALUES (1, 'A worker', 'Engineer', 65000.00), (2, 'B engineer', 'Engineer', 72000.00);

SELECT AVG(salary) FROM asia_schema.asia_mines WHERE role = 'Engineer';


Question: What is the average quantity of gold mined per day by each mine?

CREATE TABLE mine (mine_id INT, mine_name TEXT, location TEXT, daily_gold_mined INT); INSERT INTO mine VALUES (1, 'ABC Mine', 'Wyoming, USA', 150), (2, 'DEF Mine', 'West Virginia, USA', 120), (3, 'GHI Mine', 'Kentucky, USA', 80), (4, 'JKL Mine', 'Colorado, USA', 170);

SELECT mine_name, AVG(daily_gold_mined) as avg_daily_gold_mined FROM mine GROUP BY mine_name;


Question: Generate PostgreSQL SQL for: What is the average Industry, when Agriculture is greater than 11?

CREATE TABLE table_name_44 (industry INTEGER, agriculture INTEGER)

SELECT AVG(industry) FROM table_name_44 WHERE agriculture > 11;


Question: Generate PostgreSQL SQL for: What is Result, when Opponent is New England Patriots?

CREATE TABLE table_name_8 (result VARCHAR, opponent VARCHAR)

SELECT result FROM table_name_8 WHERE opponent = 'new england patriots';


Question: List the number of vessels that had a maintenance date in Q3 of 2020 and visited the Port of Shanghai in Q2 of 2019.

CREATE TABLE vessels (vessel_id INT, vessel_name TEXT, last_maintenance_date DATE); INSERT INTO vessels VALUES (1, 'Vessel A', '2020-07-15'), (2, 'Vessel B', '2020-10-10'), (3, 'Vessel C', '2020-09-25'); CREATE TABLE port_visits (visit_id INT, vessel_id INT, port_id INT, visit_date DATE); INSERT INTO port_visits VALUES (1, 1, 8, '2019-04-01'), (2, 2, 8, '2019-05-01'), (3, 3, 8, '2019-06-01');

SELECT COUNT(DISTINCT vessels.vessel_id) FROM vessels JOIN port_visits ON vessels.vessel_id = port_visits.vessel_id WHERE QUARTER(vessels.last_maintenance_date) = 3 AND port_visits.port_id = 8 AND QUARTER(port_visits.visit_date) = 2;


Question: What is the total fare collected on route 101?

CREATE TABLE routes (route_id INT, name VARCHAR(255)); INSERT INTO routes (route_id, name) VALUES (101, 'Route 101'); CREATE TABLE fares (fare_id INT, route_id INT, amount DECIMAL(5,2)); INSERT INTO fares (fare_id, route_id, amount) VALUES (1, 101, 2.50), (2, 101, 3.75);

SELECT SUM(amount) FROM fares WHERE route_id = 101;


Question: Find the total sales for each menu item from the sales_fact table, grouped by menu_item_id.

CREATE TABLE sales_fact (sale_id INT, menu_item_id INT, sale_quantity INT, sale_price DECIMAL, sale_date DATE);

SELECT menu_item_id, SUM(sale_quantity * sale_price) as total_sales FROM sales_fact GROUP BY menu_item_id;


Question: Generate PostgreSQL SQL for: Which Market/Rank is associated with WCRN calls?

CREATE TABLE table_10333757_1 (market_rank VARCHAR, calls VARCHAR)

SELECT market_rank FROM table_10333757_1 WHERE calls = 'WCRN';


Question: What is the distribution of confidence scores for fairness-related predictions made by models 'Fairlearn' and 'AIF360' in the 'model_performance' table?

CREATE TABLE model_performance (model_name VARCHAR(20), prediction VARCHAR(20), confidence FLOAT); INSERT INTO model_performance (model_name, prediction, confidence) VALUES ('Fairlearn', 'fairness', 0.85), ('Fairlearn', 'bias', 0.91), ('AIF360', 'fairness', 0.78), ('AIF360', 'explainability', 0.95);

SELECT model_name, COUNT(*) as count, AVG(confidence) as avg_confidence FROM model_performance WHERE prediction LIKE '%fairness%' GROUP BY model_name;


Question: What is the average playtime, in hours, for players from the United Kingdom, for games in the 'Adventure' genre?

CREATE TABLE games (game_id INT, game_genre VARCHAR(255), player_id INT, playtime_mins INT); CREATE TABLE players (player_id INT, player_country VARCHAR(255));

SELECT AVG(playtime_mins / 60) FROM games JOIN players ON games.player_id = players.player_id WHERE players.player_country = 'United Kingdom' AND game_genre = 'Adventure';


Question: What is the average property price in eco-friendly neighborhoods with more than 5 sustainable urban projects?

CREATE TABLE neighborhoods (neighborhood_id INT, name VARCHAR(255), avg_property_price DECIMAL(10,2), num_sustainable_projects INT); INSERT INTO neighborhoods (neighborhood_id, name, avg_property_price, num_sustainable_projects) VALUES (1, 'Central Park', 850000, 4), (2, 'Soho', 1200000, 2), (3, 'Greenwich Village', 1100000, 6), (4, 'Harlem', 600000, 7);

SELECT avg_property_price FROM neighborhoods WHERE num_sustainable_projects > 5;


Question: Find the autonomous driving research projects that are conducted by companies from the USA and China.

CREATE TABLE AutonomousResearch (project VARCHAR(20), company VARCHAR(20)); INSERT INTO AutonomousResearch (project, company) VALUES ('Tesla Autopilot', 'Tesla'); INSERT INTO AutonomousResearch (project, company) VALUES ('Baidu Apollo', 'Baidu');

SELECT project FROM AutonomousResearch WHERE company IN ('Tesla', 'Baidu');


Question: Generate PostgreSQL SQL for: What is the UK broadcast date of the episode with Ben Okri as the presenter?

CREATE TABLE table_name_87 (uk_broadcast_date VARCHAR, presenter VARCHAR)

SELECT uk_broadcast_date FROM table_name_87 WHERE presenter = 'ben okri';


Question: Find the total number of concerts in each country for the 'Rock' genre.

CREATE TABLE Concerts (ConcertId INT, Venue VARCHAR(255), Country VARCHAR(255), Genre VARCHAR(255), Attendees INT); INSERT INTO Concerts (ConcertId, Venue, Country, Genre, Attendees) VALUES (1, 'Wembley Stadium', 'UK', 'Rock', 50000), (2, 'Stade de France', 'France', 'Rock', 60000), (3, 'MetLife Stadium', 'USA', 'Rock', 40000), (4, 'Estadio Azteca', 'Mexico', 'Rock', 70000), (5, 'ANZ Stadium', 'Australia', 'Rock', 30000);

SELECT Country, Genre, SUM(Attendees) AS TotalConcerts FROM Concerts WHERE Genre = 'Rock' GROUP BY Country;


Question: Generate PostgreSQL SQL for: what is the overall number of times when the calendar showed october 6

CREATE TABLE table_27733909_1 (record VARCHAR, date VARCHAR)

SELECT COUNT(record) FROM table_27733909_1 WHERE date = 'October 6';


Question: PostgreSQL regression test 'arrays': Write the SELECT query (example 134).

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


Question: Generate PostgreSQL SQL for: Name the rating for 3.79 viewers

CREATE TABLE table_22822468_2 (rating VARCHAR, viewers__millions_ VARCHAR)

SELECT rating / SHARE(18 AS –49) FROM table_22822468_2 WHERE viewers__millions_ = '3.79';


Question: What is the percentage of sustainable materials used in production for each item, ordered by the percentage in descending order?

CREATE TABLE Production (item_id INT, material VARCHAR(255), weight DECIMAL(5,2), sustainable BOOLEAN); INSERT INTO Production (item_id, material, weight, sustainable) VALUES (1, 'Organic Cotton', 2.5, true), (2, 'Polyester', 1.5, false), (3, 'Recycled Wool', 3.0, true), (4, 'Polyester', 2.0, false), (5, 'Organic Cotton', 4.0, true);

SELECT item_id, 100.0 * SUM(CASE WHEN sustainable THEN weight ELSE 0 END) / SUM(weight) OVER (PARTITION BY item_id) AS percentage FROM Production ORDER BY percentage DESC;


Question: What is the total number of successful satellite launches by Japanese and Brazilian space programs?

CREATE TABLE Satellite_Launches (launch_date DATE, country VARCHAR(255), success BOOLEAN); INSERT INTO Satellite_Launches (launch_date, country, success) VALUES ('2020-01-01', 'Japan', TRUE), ('2020-02-01', 'Brazil', FALSE), ('2020-03-01', 'Japan', TRUE), ('2020-04-01', 'Brazil', TRUE), ('2020-05-01', 'Japan', FALSE);

SELECT SUM(success) FROM (SELECT success FROM Satellite_Launches WHERE country IN ('Japan', 'Brazil')) AS subquery WHERE success = TRUE;


Question: Generate PostgreSQL SQL for: What year did anna thompson have a 7th place result?

CREATE TABLE table_name_85 (year VARCHAR, result VARCHAR)

SELECT year FROM table_name_85 WHERE result = '7th';


Question: Generate PostgreSQL SQL for: What is the build date of the locomotive with a fa-2 model?

CREATE TABLE table_name_55 (build_date VARCHAR, model VARCHAR)

SELECT build_date FROM table_name_55 WHERE model = 'fa-2';


Question: What is the total revenue generated from ticket sales for the NY Knicks?

CREATE TABLE teams (team_id INT, team_name VARCHAR(50)); INSERT INTO teams (team_id, team_name) VALUES (1, 'NY Knicks'), (2, 'LA Lakers'); CREATE TABLE ticket_sales (id INT, team_id INT, revenue INT);

SELECT SUM(ticket_sales.revenue) FROM ticket_sales JOIN teams ON ticket_sales.team_id = teams.team_id WHERE teams.team_name = 'NY Knicks';


Question: Generate PostgreSQL SQL for: Who had the most laps led in monterey, california when scott rarick won the race?

CREATE TABLE table_25668203_2 (most_laps_led VARCHAR, location VARCHAR, winning_driver VARCHAR)

SELECT most_laps_led FROM table_25668203_2 WHERE location = 'Monterey, California' AND winning_driver = 'Scott Rarick';


Question: Write the DML statement from PostgreSQL regression test 'triggers' (example 90).

UPDATE city_table SET city_name = NEW.city_name,
                              population = NEW.population,
                              country_id = ctry_id
            WHERE city_id = OLD.city_id;

Explanation: DML from PostgreSQL core regression test for Triggers.


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

CREATE TABLE People (Name VARCHAR, Height VARCHAR)

SELECT Name FROM People ORDER BY Height;


Question: What is the total quantity of product 4 in the circular supply chain?

CREATE TABLE circular_supply_chain (product_id INT, supplier_id INT, retailer_id INT, quantity INT); INSERT INTO circular_supply_chain (product_id, supplier_id, retailer_id, quantity) VALUES (4, 4, 4, 120);

SELECT SUM(quantity) AS total_quantity FROM circular_supply_chain WHERE product_id = 4;


Question: List the programs with a budget over $5000 but no volunteers.

CREATE TABLE Programs (ProgramID INT, Name TEXT, Budget DECIMAL); CREATE TABLE Volunteers (VolunteerID INT, ProgramID INT); INSERT INTO Programs (ProgramID, Name, Budget) VALUES (1, 'Education', 6000.00), (2, 'Health', 4000.00), (3, 'Environment', 7000.00); INSERT INTO Volunteers (VolunteerID, ProgramID) VALUES (1, 1), (2, 2);

SELECT Programs.Name FROM Programs LEFT JOIN Volunteers ON Programs.ProgramID = Volunteers.ProgramID WHERE Programs.Budget > 5000 AND Volunteers.ProgramID IS NULL;


Question: What is the maximum number of artifacts found in a single excavation session?

SELECT MAX(total_artifacts) FROM excavation_sessions;


Question: Generate PostgreSQL SQL for: What college picked someone from The Episcopal Academy?

CREATE TABLE table_name_47 (college VARCHAR, school VARCHAR)

SELECT college FROM table_name_47 WHERE school = 'episcopal academy';


Question: Generate PostgreSQL SQL for: What is the highest Attendance, when Date is "Oct. 26"?

CREATE TABLE table_name_25 (attendance INTEGER, date VARCHAR)

SELECT MAX(attendance) FROM table_name_25 WHERE date = 'oct. 26';


Question: Generate PostgreSQL SQL for: How many roller coasters are there?

CREATE TABLE roller_coaster (Id VARCHAR)


Question: What is the property size of the smallest co-owned property in London?

CREATE TABLE properties (id INT, size FLOAT, co_owned BOOLEAN, city VARCHAR(20)); INSERT INTO properties (id, size, co_owned, city) VALUES (1, 1500, TRUE, 'London'), (2, 2000, FALSE, 'London'), (3, 1000, TRUE, 'London');

SELECT size FROM properties WHERE city = 'London' AND co_owned = TRUE ORDER BY size ASC LIMIT 1;


Question: Compare the wastewater treatment capacities in New York and Florida.

CREATE TABLE wastewater_treatment_capacities(state VARCHAR(20), capacity INT); INSERT INTO wastewater_treatment_capacities(state, capacity) VALUES ('New York', 5000000), ('Florida', 3000000);

SELECT capacity FROM wastewater_treatment_capacities WHERE state IN ('New York', 'Florida') ORDER BY capacity DESC;


Question: Generate PostgreSQL SQL for: what's the party with district being alabama 3

CREATE TABLE table_1342292_2 (party VARCHAR, district VARCHAR)

SELECT party FROM table_1342292_2 WHERE district = 'Alabama 3';


Question: Insert a new record of equipment maintenance for a Jeep on Apr 30, 2021 with labor cost 200 and parts cost 100.

CREATE TABLE Maintenance (id INT, equipment VARCHAR(255), date DATE, labor INT, parts INT);

INSERT INTO Maintenance (equipment, date, labor, parts) VALUES ('Jeep', '2021-04-30', 200, 100);


Question: What was the average number of strikeouts per game for Team G in the 2018 season?

CREATE TABLE games (id INT, team TEXT, location TEXT, strikeouts INT); INSERT INTO games (id, team, location, strikeouts) VALUES (1, 'Team G', 'Home', 12), (2, 'Team G', 'Away', 15);

SELECT AVG(strikeouts) FROM games WHERE team = 'Team G' AND year = 2018;


Question: Generate PostgreSQL SQL for: What is the highest top-25 with more than 9 top-10 but less than 29 events?

CREATE TABLE table_name_17 (top_25 INTEGER, top_10 VARCHAR, events VARCHAR)

SELECT MAX(top_25) FROM table_name_17 WHERE top_10 > 9 AND events < 29;


Question: Generate PostgreSQL SQL for: How many long range shots did tonya edwards make.

CREATE TABLE table_24906653_5 (field_goals VARCHAR, player VARCHAR)

SELECT COUNT(field_goals) FROM table_24906653_5 WHERE player = 'Tonya Edwards';


Question: Which menu items have the highest cost?

CREATE TABLE menu_items (menu_item_id INT, item_name VARCHAR(255), category VARCHAR(255), price INT); INSERT INTO menu_items (menu_item_id, item_name, category, price) VALUES (1, 'Steak', 'Entree', 25), (2, 'Fries', 'Side', 5), (3, 'Burger', 'Entree', 15), (4, 'Salad', 'Side', 8);

SELECT item_name, price FROM menu_items ORDER BY price DESC LIMIT 2;


Question: Identify the number of spacecraft missions per day, and rank them in descending order?

CREATE TABLE spacecraft_missions (spacecraft_name TEXT, mission_date DATE);

SELECT DATE_TRUNC('day', mission_date) as mission_day, COUNT(*) as mission_count, RANK() OVER (ORDER BY COUNT(*) DESC) as mission_rank FROM spacecraft_missions GROUP BY mission_day ORDER BY mission_rank;


Question: Generate PostgreSQL SQL for: What team defeated the Capital City Giants?

CREATE TABLE table_name_11 (team VARCHAR, runner_up VARCHAR)

SELECT team FROM table_name_11 WHERE runner_up = 'capital city giants';


Question: What is the total quantity of each product in the Sydney warehouse?

CREATE TABLE Warehouses (WarehouseID int, WarehouseName varchar(255), City varchar(255), Country varchar(255)); INSERT INTO Warehouses (WarehouseID, WarehouseName, City, Country) VALUES (4, 'Sydney Warehouse', 'Sydney', 'Australia'); CREATE TABLE Inventory (InventoryID int, WarehouseID int, ProductName varchar(255), Quantity int); INSERT INTO Inventory (InventoryID, WarehouseID, ProductName, Quantity) VALUES (4, 4, 'Pears', 100);

SELECT ProductName, SUM(Quantity) AS TotalQuantity FROM Inventory WHERE WarehouseID = 4 GROUP BY ProductName;


Question: What is the average calorie count per dish for dishes that have more than 5 reviews?

CREATE TABLE dishes (dish_id INT, name VARCHAR(255), calories INT, reviews INT); INSERT INTO dishes (dish_id, name, calories, reviews) VALUES (1, 'Pizza', 300, 7), (2, 'Pasta', 400, 3), (3, 'Salad', 200, 8), (4, 'Burger', 500, 10);

SELECT AVG(calories) FROM (SELECT calories, ROW_NUMBER() OVER (PARTITION BY name ORDER BY reviews DESC) rn FROM dishes) t WHERE t.rn > 1;


Question: Generate PostgreSQL SQL for: How many wins does the club with 565 points for have?

CREATE TABLE table_1676073_13 (won VARCHAR, points_for VARCHAR)

SELECT won FROM table_1676073_13 WHERE points_for = '565';


Question: What is the total quantity of vegetarian items sold per store?

CREATE TABLE Stores (StoreID INT, StoreName VARCHAR(50)); INSERT INTO Stores (StoreID, StoreName) VALUES (1, 'Store A'), (2, 'Store B'); CREATE TABLE Menu (MenuID INT, MenuItem VARCHAR(50), Type VARCHAR(20), StoreID INT); INSERT INTO Menu (MenuID, MenuItem, Type, StoreID) VALUES (1, 'Falafel', 'Vegetarian', 1), (2, 'Chicken Shawarma', 'Non-Vegetarian', 1), (3, 'Vegetable Curry', 'Vegetarian', 2), (4, 'Steak Platter', 'Non-Vegetarian', 2); CREATE TABLE Sales (SaleID INT, MenuID INT, Quantity INT, OrderDate DATE); INSERT INTO Sales (SaleID, MenuID, Quantity, OrderDate) VALUES (1, 1, 25, '2022-01-01'), (2, 2, 15, '2022-01-01'), (3, 3, 30, '2022-01-02'), (4, 4, 10, '2022-01-02');

SELECT StoreID, SUM(Quantity) as TotalQuantity FROM Sales s JOIN Menu m ON s.MenuID = m.MenuID WHERE Type = 'Vegetarian' GROUP BY StoreID;


Question: pgTAP test for Roletap (assertion 5).

SELECT * FROM check_test(
    has_role('aoijaoisjfaoidfjaisjdfosjf', 'desc'),
    false,
    'has_role(nonexistent role, desc)',
    'desc',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Roletap.


Question: Delete transactions over $1000 for customers with 'Gold' status

CREATE TABLE transactions (id INT PRIMARY KEY, customer_id INT, amount DECIMAL(10,2), transaction_date DATE, customer_status VARCHAR(50)); INSERT INTO transactions (id, customer_id, amount, transaction_date, customer_status) VALUES (1, 1, 500.00, '2022-01-01', 'Gold'); INSERT INTO transactions (id, customer_id, amount, transaction_date, customer_status) VALUES (2, 2, 750.00, '2022-01-02', 'Silver');

DELETE t FROM transactions t WHERE t.amount > 1000 AND t.customer_status = 'Gold';


Question: pgTAP test for Inheritance (assertion 94).

SELECT * FROM check_test(
    is_descendent_of( 'hide', 'h_child1', 'hide', 'h_parent', 1 ),
    true,
    'is_descendent_of(csch, ctab, psch, ptab, 1)',
    'Table hide.h_child1 should be descendent 1 from hide.h_parent',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Inheritance.


Question: What is the total CO2 emissions from manufacturing cosmetics in the last 12 months?

CREATE TABLE manufacturing_emissions (emission_id INT, product_id INT, co2_emissions FLOAT, emission_date DATE);

SELECT SUM(co2_emissions) FROM manufacturing_emissions WHERE emission_date BETWEEN DATE_SUB(CURRENT_DATE, INTERVAL 12 MONTH) AND CURRENT_DATE;


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

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

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


Question: Generate PostgreSQL SQL for: What points for have 30 as the game, and 73 as the total points?

CREATE TABLE table_name_92 (points_for VARCHAR, games VARCHAR, total_points VARCHAR)

SELECT points_for FROM table_name_92 WHERE games = '30' AND total_points = '73';


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

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

SELECT count(*) FROM (select array[1,2]::orderedpair) AS _sub;


Question: What is the average number of satellites launched per year by each country, ordered by the country with the highest average?

CREATE TABLE SatelliteMissions (MissionID INT, Name VARCHAR(50), LaunchCountry VARCHAR(50), LaunchDate DATE); INSERT INTO SatelliteMissions VALUES (1, 'GSAT-12', 'India', '2011-07-15'); INSERT INTO SatelliteMissions VALUES (2, 'GSAT-11', 'India', '2018-12-04');

SELECT LaunchCountry, AVG(DATEDIFF(YEAR, LaunchDate, LEAD(LaunchDate) OVER (PARTITION BY LaunchCountry ORDER BY LaunchDate))) as avg_launches_per_year FROM SatelliteMissions GROUP BY LaunchCountry ORDER BY avg_launches_per_year DESC;


Question: Generate PostgreSQL SQL for: Which 2007 has a Tournament of grand slam sr?

CREATE TABLE table_name_32 (tournament VARCHAR)

SELECT 2007 FROM table_name_32 WHERE tournament = 'grand slam sr';


Question: Generate PostgreSQL SQL for: Which charts had debut sales of of more than 339333.011497678?

CREATE TABLE table_23180638_1 (oricon_albums_chart VARCHAR, debut_sales__copies_ INTEGER)

SELECT oricon_albums_chart FROM table_23180638_1 WHERE debut_sales__copies_ > 339333.011497678;


Question: What is the minimum number of reviews for hotels in Canada?

CREATE TABLE hotels (id INT, name TEXT, country TEXT, reviews INT); INSERT INTO hotels (id, name, country, reviews) VALUES (1, 'Hotel A', 'Canada', 120), (2, 'Hotel B', 'Canada', 80), (3, 'Hotel C', 'Canada', 50);

SELECT MIN(reviews) FROM hotels WHERE country = 'Canada';


Question: Generate PostgreSQL SQL for: What is the highest number listed?

CREATE TABLE table_12113888_1 (number INTEGER)

SELECT MAX(number) FROM table_12113888_1;


Question: How many workplaces in Canada have no labor rights violations?

CREATE TABLE workplaces (id INT, country VARCHAR(50), has_lrv BOOLEAN); INSERT INTO workplaces (id, country, has_lrv) VALUES (1, 'Canada', true), (2, 'Canada', false), (3, 'Canada', false);

SELECT COUNT(*) FROM workplaces WHERE country = 'Canada' AND has_lrv = false;


Question: How many size 14 dresses were sold in the last 3 months?

CREATE TABLE sales (sale_id INTEGER, product_id INTEGER, size INTEGER, date DATE); INSERT INTO sales (sale_id, product_id, size, date) VALUES (1, 1001, 12, '2022-01-05'), (2, 1002, 8, '2022-02-10'), (3, 1003, 14, '2022-03-20');

SELECT COUNT(*) FROM sales WHERE size = 14 AND date >= DATEADD(month, -3, CURRENT_DATE);


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

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

SELECT count(*) FROM (SELECT jsonb_array_length('[]')) AS _sub;


Question: PL/pgSQL test: Plpython Error (example 49).

/* raising plpy.spiexception.* from python code should preserve sqlstate
 */
CREATE FUNCTION plpy_raise_spiexception() RETURNS void AS $$
raise plpy.spiexceptions.DivisionByZero()
$$ LANGUAGE plpython3u;

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


Question: Delete all records of ticket sales for a specific salesperson, identified by their salesperson ID.

CREATE TABLE salesperson (salesperson_id INT, name VARCHAR(50), position VARCHAR(50)); CREATE TABLE tickets (ticket_id INT, salesperson_id INT, event_id INT, price DECIMAL(5,2), quantity INT); INSERT INTO salesperson VALUES (1, 'John Doe', 'Senior Salesperson'); INSERT INTO tickets VALUES (1, 1, 1, 50, 100);

DELETE t FROM tickets t WHERE t.salesperson_id = 1;


Question: Create a view to display the job titles and departments of applicants

CREATE TABLE TalentAcquisition (ApplicantID INT PRIMARY KEY, JobTitle VARCHAR(30), Department VARCHAR(20), ApplicationDate DATE);

CREATE VIEW JobTitlesDepartments AS SELECT JobTitle, Department FROM TalentAcquisition;


Question: Find the number of movies released each year, by studios located in California, that have a runtime of over 2 hours.

CREATE TABLE movies (id INT, title VARCHAR(255), release_year INT, runtime INT, studio_location VARCHAR(255));

SELECT release_year, COUNT(*) as num_movies FROM movies WHERE studio_location = 'California' AND runtime > 120 GROUP BY release_year;


Question: Generate PostgreSQL SQL for: Which episode is number 3 in the season?

CREATE TABLE table_29960651_5 (episode VARCHAR, no_for_season VARCHAR)

SELECT episode FROM table_29960651_5 WHERE no_for_season = 3;


Question: Show a SQL definition from the zombodb project (test-analyzers, item 3).

CREATE INDEX idxanalyzers_test ON analyzers_test USING zombodb ((analyzers_test));

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


Question: What is the total sales of all drugs in India?

CREATE TABLE sales (drug_id VARCHAR(10), country VARCHAR(10), sales_amount NUMERIC(12,2));

SELECT SUM(sales_amount) FROM sales WHERE country = 'India';


Question: Generate PostgreSQL SQL for: How many records were there when opponents were 9?

CREATE TABLE table_22815265_1 (record VARCHAR, opponents VARCHAR)

SELECT COUNT(record) FROM table_22815265_1 WHERE opponents = 9;


Question: Generate PostgreSQL SQL for: What is the 1999 tournament that has a Q1 in 2003 and a Q3 in 2002?

SELECT 1999 FROM table_name_2 WHERE 2003 = 'q1' AND 2002 = 'q3';


Question: Write the DDL statement from PostgreSQL regression test 'privileges' (example 20).

Explanation: DDL from PostgreSQL core regression test for Privileges.


Question: What is the average age of patients with diabetes in rural Texas who are male?

CREATE TABLE patients (id INT, name VARCHAR(50), age INT, gender VARCHAR(10), diagnosis VARCHAR(50), location VARCHAR(50)); INSERT INTO patients (id, name, age, gender, diagnosis, location) VALUES (1, 'Jane Doe', 65, 'Female', 'Diabetes', 'Texas'), (2, 'John Doe', 45, 'Male', 'Diabetes', 'Texas'), (3, 'Jim Brown', 55, 'Male', 'Diabetes', 'Texas');

SELECT AVG(age) FROM patients WHERE diagnosis = 'Diabetes' AND gender = 'Male' AND location = 'Texas';


Question: Delete a customer record from the 'customers' table

CREATE TABLE customers (customer_id INT, first_name VARCHAR(255), last_name VARCHAR(255), email VARCHAR(255), address VARCHAR(255));

DELETE FROM customers WHERE customer_id = 1001;


Question: What is the average media literacy score for users in each country who have completed at least one disinformation detection course?

CREATE TABLE users (id INT, country VARCHAR(50), media_literacy_score INT, courses_completed INT);

SELECT country, AVG(media_literacy_score) FROM users WHERE courses_completed > 0 GROUP BY country;


Question: Find the number of attendees by age group and program type in 2021

CREATE TABLE attendee_program_info (id INT, attendee_age INT, program_type VARCHAR(255), visit_year INT);

SELECT attendee_age, program_type, COUNT(*) OVER (PARTITION BY attendee_age, program_type) AS attendees_by_age_and_program  FROM attendee_program_info WHERE visit_year = 2021 ORDER BY attendee_age, program_type;


Question: Which biotech startups received funding in Canada and have a female founder?

CREATE TABLE funding(startup VARCHAR(50), country VARCHAR(20), founder_gender VARCHAR(10));INSERT INTO funding(startup, country, founder_gender) VALUES('StartupA', 'Canada', 'Female'), ('StartupB', 'US', 'Male'), ('StartupC', 'Canada', 'Female');

SELECT startup FROM funding WHERE country = 'Canada' AND founder_gender = 'Female';


Question: How many cultural heritage sites are there in Japan, and what is the average number of virtual tours per site?

CREATE TABLE cultural_sites(site_id INT, site_name TEXT, country TEXT, num_virtual_tours INT); INSERT INTO cultural_sites(site_id, site_name, country, num_virtual_tours) VALUES (1, 'Temple Mount', 'Japan', 3), (2, 'Kinkaku-ji', 'Japan', 5), (3, 'Himeji Castle', 'Japan', 4);

SELECT COUNT(*), AVG(num_virtual_tours) FROM cultural_sites WHERE country = 'Japan';


Question: Generate PostgreSQL SQL for: What is the D 48 √ with a D 46 √ with r 33 o?

CREATE TABLE table_name_87 (d_48_√ VARCHAR, d_46_√ VARCHAR)

SELECT d_48_√ FROM table_name_87 WHERE d_46_√ = 'r 33 o';


Question: Calculate the average home value for socially responsible loans in New York

CREATE TABLE socially_responsible_loans (id INT, home_value FLOAT, state VARCHAR(255)); CREATE TABLE states (id INT, state VARCHAR(255), region VARCHAR(255));

SELECT AVG(home_value) FROM socially_responsible_loans INNER JOIN states ON socially_responsible_loans.state = states.state WHERE states.state = 'New York';


Question: Generate PostgreSQL SQL for: Which biggest interview score had an evening gown stat of 9.286?

CREATE TABLE table_name_56 (interview INTEGER, evening_gown VARCHAR)

SELECT MAX(interview) FROM table_name_56 WHERE evening_gown = 9.286;


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

select count(*) from test_range_gist where ir && int4range(10,20);

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

SELECT count(*) FROM (select count(*) from test_range_gist where ir && int4range(10,20)) AS _sub;


Question: Generate PostgreSQL SQL for: What state is 25% Democrats has a ratio of 6/2 of Republicans to Democrats?

CREATE TABLE table_name_66 (state_ranked_in_partisan_order VARCHAR, percentage_democrats VARCHAR, republican__democratic VARCHAR)

SELECT state_ranked_in_partisan_order FROM table_name_66 WHERE percentage_democrats = '25%' AND republican__democratic = '6/2';


Question: How many public libraries were opened in each year from 2018 to 2021?

CREATE TABLE Facilities (Year INT, FacilityType TEXT); INSERT INTO Facilities (Year, FacilityType) VALUES (2018, 'PublicLibrary'), (2019, 'PublicLibrary'), (2020, 'PublicLibrary'), (2021, 'PublicLibrary');

SELECT Year, COUNT(*) FROM Facilities WHERE FacilityType = 'PublicLibrary' GROUP BY Year;


Question: Calculate the total waste generated by each manufacturer in the North American region

CREATE TABLE Manufacturers (manufacturer_id INT, manufacturer_name VARCHAR(50), region VARCHAR(50)); INSERT INTO Manufacturers (manufacturer_id, manufacturer_name, region) VALUES (1, 'ManufacturerA', 'North America'), (2, 'ManufacturerB', 'Europe'); CREATE TABLE WasteData (manufacturer_id INT, waste_quantity INT); INSERT INTO WasteData (manufacturer_id, waste_quantity) VALUES (1, 120), (1, 150), (2, 80);

SELECT m.manufacturer_name, SUM(wd.waste_quantity) AS total_waste FROM Manufacturers m INNER JOIN WasteData wd ON m.manufacturer_id = wd.manufacturer_id WHERE m.region = 'North America' GROUP BY m.manufacturer_name;


Question: Update the sustainability_score of the supplier with supplier_id 2 to 4.5

UPDATE suppliers SET sustainability_score = 4.5 WHERE supplier_id = 2;


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

CREATE AGGREGATE alt_agg2 (
  sfunc1 = int4mi, basetype = int4, stype1 = int4, initcond = 0
);

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


Question: What is the success rate of therapy as a treatment approach for patients with anxiety in Japan?

CREATE TABLE treatments (id INT, patient_id INT, approach VARCHAR(255), success BOOLEAN); INSERT INTO treatments (id, patient_id, approach, success) VALUES (1, 1, 'Medication', TRUE), (2, 2, 'Therapy', FALSE), (3, 3, 'Therapy', TRUE), (4, 4, 'Meditation', TRUE); INSERT INTO patients (id, age, condition, country) VALUES (1, 35, 'Anxiety', 'Japan'), (2, 42, 'Depression', 'Canada'), (3, 28, 'Anxiety', 'Japan'), (4, 31, 'Bipolar', 'Mexico');

SELECT AVG(treatments.success) FROM treatments JOIN patients ON treatments.patient_id = patients.id WHERE patients.condition = 'Anxiety' AND patients.country = 'Japan' AND treatments.approach = 'Therapy';


Question: Generate PostgreSQL SQL for: On what day was game 2 played?

CREATE TABLE table_name_56 (date VARCHAR, game VARCHAR)

SELECT date FROM table_name_56 WHERE game = 2;


Question: What is the minimum production rate for wells in the Marcellus Shale?

CREATE TABLE well_prod (well_name VARCHAR(50), location VARCHAR(50), rate FLOAT); INSERT INTO well_prod (well_name, location, rate) VALUES ('Well A', 'Marcellus Shale', 1200), ('Well B', 'Marcellus Shale', 1800);

SELECT MIN(rate) FROM well_prod WHERE location = 'Marcellus Shale';


Question: pgTAP test for Resultset (assertion 53).

INSERT INTO names (name) VALUES ('Taylor');

Explanation: SQL assertion from pgTAP test suite for Resultset.


Question: Generate PostgreSQL SQL for: What years was Lebanon the nationality?

CREATE TABLE table_name_82 (years_in_orlando VARCHAR, nationality VARCHAR)

SELECT years_in_orlando FROM table_name_82 WHERE nationality = 'lebanon';


Question: Generate PostgreSQL SQL for: Name the seasons and winners that airs 28 january 2007

CREATE TABLE table_16884579_1 (seasons_and_winners VARCHAR, premiere VARCHAR)

SELECT seasons_and_winners FROM table_16884579_1 WHERE premiere = '28 January 2007';


Question: Generate PostgreSQL SQL for: Which game did New Jersey Devils played in?

CREATE TABLE table_name_54 (game VARCHAR, opponent VARCHAR)

SELECT game FROM table_name_54 WHERE opponent = 'new jersey devils';


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

SELECT citext_smaller( 'aardvark'::citext, 'Aaba'::citext ) = 'Aaba' AS t;

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


Question: What was the minimum donation amount from individual donors in the West region in 2020?

CREATE TABLE DonorContributions (donor_id INT, donation_amount DECIMAL(10,2), donation_date DATE, region VARCHAR(50)); INSERT INTO DonorContributions (donor_id, donation_amount, donation_date, region) VALUES (4, 300, '2020-01-01', 'West'), (5, 400, '2020-02-01', 'West'), (6, 200, '2020-03-01', 'East');

SELECT MIN(donation_amount) FROM DonorContributions WHERE region = 'West' AND YEAR(donation_date) = 2020 AND donor_id NOT IN (SELECT donor_id FROM DonorContributions WHERE donation_type = 'Corporate');


Question: Write the DML statement from PostgreSQL regression test 'merge' (example 471).

INSERT INTO cj_source1 VALUES (3, 10, 400);

Explanation: DML from PostgreSQL core regression test for Merge.


Question: Show the total revenue for the "classical" genre from all platforms, excluding any platforms that have a revenue lower than $10,000 for that genre.

CREATE TABLE platformA (genre TEXT, revenue INT); CREATE TABLE platformB (genre TEXT, revenue INT); CREATE TABLE platformC (genre TEXT, revenue INT);

SELECT genre, SUM(revenue) FROM (SELECT genre, revenue FROM platformA WHERE genre = 'classical' AND revenue >= 10000 UNION ALL SELECT genre, revenue FROM platformB WHERE genre = 'classical' AND revenue >= 10000 UNION ALL SELECT genre, revenue FROM platformC WHERE genre = 'classical' AND revenue >= 10000) AS combined_platforms GROUP BY genre;


Question: List all sculptures from the 20th century with their material and the name of the museum they are exhibited in, if available, sorted by the sculpture's creation date. If no museum is available, order by material.

CREATE TABLE Sculptures (SculptureID INT, Title VARCHAR(50), CreationDate DATE, Material VARCHAR(50), MuseumID INT); CREATE TABLE Museums (MuseumID INT, Name VARCHAR(50)); INSERT INTO Sculptures VALUES (1, 'Bird in Space', '1923', 'Bronze', 1); INSERT INTO Museums VALUES (1, 'Museum of Modern Art');

SELECT s.Title, s.CreationDate, s.Material, m.Name FROM Sculptures s LEFT JOIN Museums m ON s.MuseumID = m.MuseumID WHERE YEAR(s.CreationDate) >= 1900 ORDER BY s.CreationDate, s.Material;


Question: Generate PostgreSQL SQL for: How many counties have people before profit as the party, and a borough greater than 0?

CREATE TABLE table_name_16 (county INTEGER, party VARCHAR, borough VARCHAR)

SELECT SUM(county) FROM table_name_16 WHERE party = 'people before profit' AND borough > 0;


Question: Count the number of streams for Latin songs in Spain during 2021.

CREATE TABLE Streaming (country VARCHAR(50), genre VARCHAR(50), year INT, streams INT); INSERT INTO Streaming (country, genre, year, streams) VALUES ('Spain', 'Latin', 2021, 1500000); INSERT INTO Streaming (country, genre, year, streams) VALUES ('Spain', 'Latin', 2021, 1600000);

SELECT COUNT(streams) FROM Streaming WHERE country = 'Spain' AND genre = 'Latin' AND year = 2021;


Question: Generate PostgreSQL SQL for: what is the metlink code that opened in 1908?

CREATE TABLE table_3005450_1 (metlink_code VARCHAR, opened VARCHAR)

SELECT metlink_code FROM table_3005450_1 WHERE opened = '1908';


Question: Get the carrier_name and count of shipments for each warehouse_id from the shipment table where the shipped_date is between '2021-01-01' and '2021-12-31' grouped by carrier_name and warehouse_id

CREATE TABLE shipment (shipment_id VARCHAR(10), status VARCHAR(20), warehouse_id VARCHAR(10), carrier_name VARCHAR(30), shipped_date DATE);

SELECT carrier_name, warehouse_id, COUNT(*) as count FROM shipment WHERE shipped_date BETWEEN '2021-01-01' AND '2021-12-31' GROUP BY carrier_name, warehouse_id;


Question: Which minerals were extracted in quantities greater than 1000 tons by companies that have mining operations in South America?

CREATE TABLE company (id INT, name VARCHAR(255), country VARCHAR(255));CREATE TABLE extraction (company_id INT, mineral VARCHAR(255), amount INT);

SELECT DISTINCT e.mineral FROM extraction e JOIN company c ON e.company_id = c.id WHERE c.country LIKE '%South America%' AND e.amount > 1000;


Question: Generate PostgreSQL SQL for: What are the Notes of the Country of finland?

CREATE TABLE table_name_16 (notes VARCHAR, country VARCHAR)

SELECT notes FROM table_name_16 WHERE country = 'finland';


Question: Generate PostgreSQL SQL for: What is the Total when the Set 3 was 25-15?

CREATE TABLE table_name_68 (total VARCHAR, set_3 VARCHAR)

SELECT total FROM table_name_68 WHERE set_3 = '25-15';


Question: Generate PostgreSQL SQL for: In which district is the residence Dublin?

CREATE TABLE table_26131768_4 (district VARCHAR, residence VARCHAR)

SELECT district FROM table_26131768_4 WHERE residence = 'Dublin';


Question: pgTAP test for Pgtap--0.91.0--0.92.0 (assertion 76).

CREATE OR REPLACE FUNCTION has_index ( NAME, NAME, NAME, text )
RETURNS TEXT AS $$
    SELECT CASE WHEN _is_schema( $1 ) THEN
        -- Looking for schema.table index.
            ok ( _have_index( $1, $2, $3 ), $4)
        ELSE
        -- Looking for particular columns.
            has_index( $1, $2, ARRAY[$3], $4 )
      END;
$$ LANGUAGE sql;

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


Question: What is the total billable hours for cases opened in the last year?

CREATE TABLE TimeEntries (EntryID INT, CaseID INT, Hours DECIMAL(10,2)); INSERT INTO TimeEntries (EntryID, CaseID, Hours) VALUES (1, 1, 5.00), (2, 2, 7.50);

SELECT SUM(Hours) FROM TimeEntries INNER JOIN Cases ON TimeEntries.CaseID = Cases.CaseID WHERE OpenDate >= DATEADD(year, -1, GETDATE());


Question: Generate PostgreSQL SQL for: How many items withdrawn had numbers over 5?

CREATE TABLE table_name_93 (withdrawn VARCHAR, number INTEGER)

SELECT COUNT(withdrawn) FROM table_name_93 WHERE number > 5;


Question: Generate PostgreSQL SQL for: What player from South Africa had a total less than 284?

CREATE TABLE table_name_93 (player VARCHAR, total VARCHAR, country VARCHAR)

SELECT player FROM table_name_93 WHERE total < 284 AND country = 'south africa';


Question: Generate PostgreSQL SQL for: How many picks did Jay Bruchak have?

CREATE TABLE table_name_31 (pick VARCHAR, player VARCHAR)

SELECT COUNT(pick) FROM table_name_31 WHERE player = 'jay bruchak';


Question: Generate PostgreSQL SQL for: What is the sum of Year, when Result is 9th?

CREATE TABLE table_name_10 (year INTEGER, result VARCHAR)

SELECT SUM(year) FROM table_name_10 WHERE result = '9th';


Question: What is the name and location of all airports in the state of Texas with more than 100,000 annual passengers?

CREATE TABLE Airports (id INT, name VARCHAR(100), location VARCHAR(100), annual_passengers INT, state VARCHAR(50)); INSERT INTO Airports (id, name, location, annual_passengers, state) VALUES (1, 'Dallas/Fort Worth International Airport', 'DFW', 69000000, 'Texas');

SELECT name, location FROM Airports WHERE state = 'Texas' AND annual_passengers > 100000;


Question: Show a query using PostgreSQL contrib extension 'earthdistance' (example 42).

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


Question: What is the total energy consumption for each mining site in Q2 2022, ordered by the highest consumption?

CREATE TABLE mining_sites (site_id INT, site_name VARCHAR(50), energy_consumption INT); INSERT INTO mining_sites (site_id, site_name, energy_consumption) VALUES (1, 'Site D', 4000), (2, 'Site E', 6000), (3, 'Site F', 3000);

SELECT site_name, SUM(energy_consumption) as total_energy_consumption FROM mining_sites WHERE energy_consumption >= 0 AND consumption_date >= '2022-04-01' AND consumption_date <= '2022-06-30' GROUP BY site_name ORDER BY total_energy_consumption DESC;


Question: List the number of factories in each state

CREATE TABLE factories_state (id INT, name VARCHAR(50), state VARCHAR(50)); INSERT INTO factories_state (id, name, state) VALUES (1, 'Factory A', 'New York'), (2, 'Factory B', 'California'), (3, 'Factory C', 'Texas'), (4, 'Factory D', 'New York'), (5, 'Factory E', 'California');

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


Question: What is the total revenue generated from upcycling initiatives in Q1 2021?

CREATE TABLE sales (sale_id INT, initiative_type TEXT, initiative_region TEXT, revenue DECIMAL, sale_date DATE); INSERT INTO sales (sale_id, initiative_type, initiative_region, revenue, sale_date) VALUES (1, 'Upcycling', 'Europe', 500, '2021-01-01'), (2, 'Recycling', 'North America', 1000, '2021-01-02'), (3, 'Donation', 'Asia', 250, '2021-01-03'), (4, 'Upcycling', 'Europe', 750, '2021-04-01');

SELECT SUM(revenue) FROM sales WHERE initiative_type = 'Upcycling' AND initiative_region = 'Europe' AND sale_date BETWEEN '2021-01-01' AND '2021-03-31';


Question: What is the average speed of vessels arriving from Japan to the US west coast?

CREATE TABLE vessels(id INT, name VARCHAR(50), country VARCHAR(50), speed FLOAT); INSERT INTO vessels(id, name, country, speed) VALUES (1, 'Vessel1', 'Japan', 25.3); INSERT INTO vessels(id, name, country, speed) VALUES (2, 'Vessel2', 'Japan', 27.1);

SELECT AVG(speed) FROM vessels WHERE country = 'Japan' AND name IN ('Vessel1', 'Vessel2');


Question: Generate PostgreSQL SQL for: Which To par has a Score larger than 68?

CREATE TABLE table_name_42 (to_par VARCHAR, score INTEGER)

SELECT to_par FROM table_name_42 WHERE score > 68;


Question: Generate PostgreSQL SQL for: how many series have production code 8acx05

CREATE TABLE table_26259391_1 (no_in_series VARCHAR, production_code VARCHAR)

SELECT no_in_series FROM table_26259391_1 WHERE production_code = '8ACX05';


Question: Update the price of the Veggie Burger to $13.00 in the menu_items table

CREATE TABLE menu_items (menu_item_id INT, name VARCHAR(255), description TEXT, price DECIMAL(5,2), category VARCHAR(255), sustainability_rating INT);

UPDATE menu_items SET price = 13.00 WHERE name = 'Veggie Burger';


Question: What is the average time to resolve a security incident for each incident type?

CREATE TABLE security_incidents (id INT, incident_type VARCHAR(50), resolution_time INT); INSERT INTO security_incidents (id, incident_type, resolution_time) VALUES (1, 'Malware', 120), (2, 'Phishing', 180);

SELECT incident_type, AVG(resolution_time) as avg_resolution_time FROM security_incidents GROUP BY incident_type;


Question: Show the agroecology farmers' details and their offered produce in Asian regions.

CREATE TABLE Agroecology_Farmers_4 (id INT PRIMARY KEY, name VARCHAR(50), age INT, location VARCHAR(50), sustainable_practices BOOLEAN); INSERT INTO Agroecology_Farmers_4 (id, name, age, location, sustainable_practices) VALUES (1, 'Hiroshi Tanaka', 45, 'Japanese Alps', true); INSERT INTO Agroecology_Farmers_4 (id, name, age, location, sustainable_practices) VALUES (2, 'Mei-Ling Chen', 50, 'Taiwan Highlands', true); CREATE TABLE Agroecology_Produce_4 (id INT PRIMARY KEY, product_name VARCHAR(50), price DECIMAL(5,2), farmer_id INT, location VARCHAR(50)); INSERT INTO Agroecology_Produce_4 (id, product_name, price, farmer_id, location) VALUES (1, 'Rice', 0.50, 1, 'Japanese Alps'); INSERT INTO Agroecology_Produce_4 (id, product_name, price, farmer_id, location) VALUES (2, 'Tea', 1.00, 2, 'Taiwan Highlands');

SELECT af.name, af.location, ap.product_name, ap.price FROM Agroecology_Farmers_4 af INNER JOIN Agroecology_Produce_4 ap ON af.id = ap.farmer_id WHERE af.location IN ('Japanese Alps', 'Taiwan Highlands');


Question: What is the number of marine protected areas in each country in the 'marine_protected_areas' and 'countries' tables?"

CREATE TABLE marine_protected_areas (area_name VARCHAR(50), country_name VARCHAR(50)); CREATE TABLE countries (country_name VARCHAR(50), population INT);

SELECT mpa.country_name, COUNT(*) as num_areas FROM marine_protected_areas mpa JOIN countries c ON mpa.country_name = c.country_name GROUP BY mpa.country_name;


Question: Generate PostgreSQL SQL for: What is the total rank of team roanne, which has less than 14 games?

CREATE TABLE table_name_58 (rank VARCHAR, team VARCHAR, games VARCHAR)

SELECT COUNT(rank) FROM table_name_58 WHERE team = 'roanne' AND games < 14;


Question: How many students have increased their mental health score by more than 10% in the last 6 months?

CREATE TABLE student_mental_health_history (student_id INT, score INT, date DATE); INSERT INTO student_mental_health_history VALUES (1, 60, '2022-01-01'), (1, 66, '2022-07-01'), (2, 80, '2022-01-01'), (2, 88, '2022-07-01');

SELECT COUNT(*) FROM (SELECT student_id, (score - LAG(score) OVER(PARTITION BY student_id ORDER BY date)) / LAG(score) OVER(PARTITION BY student_id ORDER BY date) * 100.0 as increase_percentage FROM student_mental_health_history WHERE date >= DATEADD(month, -6, GETDATE())) t WHERE increase_percentage > 10;


Question: List the total number of patients with diabetes in rural hospitals, grouped by hospital location state.

CREATE TABLE patients (patient_id INT, age INT, gender TEXT, rural BOOLEAN, disease TEXT, hospital_id INT); INSERT INTO patients (patient_id, age, gender, rural, disease, hospital_id) VALUES (1, 50, 'Female', true, 'Diabetes', 1); CREATE TABLE hospitals (hospital_id INT, hospital_name TEXT, beds INT, rural BOOLEAN, state_id INT); INSERT INTO hospitals (hospital_id, hospital_name, beds, rural, state_id) VALUES (1, 'Hospital A', 100, true, 1); CREATE TABLE states (state_id INT, state TEXT); INSERT INTO states (state_id, state) VALUES (1, 'Alabama'), (2, 'Alaska');

SELECT states.state, SUM(CASE WHEN patients.disease = 'Diabetes' THEN 1 ELSE 0 END) patient_count FROM patients JOIN hospitals ON patients.hospital_id = hospitals.hospital_id JOIN states ON hospitals.state_id = states.state_id WHERE hospitals.rural = true GROUP BY states.state;


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

Explanation: DML from PostgreSQL core regression test for Numeric.