Question: Write the DML statement from PostgreSQL regression test 'hash_index' (example 67).

INSERT INTO hash_split_heap SELECT a/2 FROM generate_series(1, 25000) a;

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


Question: What is the total value of all transactions on the Polygon network, grouped by month?

SELECT DATE_FORMAT(tx_time, '%Y-%m') AS month, SUM(value) AS total_value FROM polygon_transactions GROUP BY month;


Question: What is the maximum construction cost of public works projects in the 'Africa' continent?

CREATE TABLE Projects (id INT, name TEXT, country TEXT, cost FLOAT); INSERT INTO Projects (id, name, country, cost) VALUES (1, 'ProjectA', 'CountryX', 2000000.00), (2, 'ProjectB', 'CountryY', 2500500.75), (3, 'ProjectC', 'CountryZ', 1800000.50), (4, 'ProjectD', 'CountryA', 3000000.00); CREATE TABLE Countries (id INT, name TEXT, continent TEXT); INSERT INTO Countries (id, name, continent) VALUES (1, 'CountryX', 'Africa'), (2, 'CountryY', 'Africa'), (3, 'CountryZ', 'Europe'), (4, 'CountryA', 'Africa');

SELECT MAX(cost) FROM Projects INNER JOIN Countries ON Projects.country = Countries.name WHERE Countries.continent = 'Africa';


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

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

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


Question: What is the percentage of menu items that are vegetarian for each cuisine type?

CREATE TABLE restaurants (id INT, name VARCHAR(50), cuisine VARCHAR(50), menu_item_id INT); CREATE TABLE menu_items (id INT, name VARCHAR(50), vegetarian BOOLEAN); INSERT INTO restaurants (id, name, cuisine, menu_item_id) VALUES (1, 'Restaurant A', 'Italian', 1), (2, 'Restaurant B', 'Mexican', 2), (3, 'Restaurant C', 'Chinese', 3); INSERT INTO menu_items (id, name, vegetarian) VALUES (1, 'Pizza Margherita', FALSE), (2, 'Tacos Al Pastor', FALSE), (3, 'Kung Pao Chicken', FALSE), (4, 'Vegetable Stir Fry', TRUE);

SELECT r.cuisine, 100.0 * COUNT(CASE WHEN m.vegetarian THEN 1 END) / COUNT(*) as vegetarian_percentage FROM restaurants r JOIN menu_items m ON r.menu_item_id = m.id GROUP BY r.cuisine;


Question: Generate PostgreSQL SQL for: For which tournament was the margin of victory 7 strokes?

CREATE TABLE table_name_50 (tournament VARCHAR, margin_of_victory VARCHAR)

SELECT tournament FROM table_name_50 WHERE margin_of_victory = '7 strokes';


Question: What is the total number of basketball games played in the 2022 season?

CREATE TABLE games (season TEXT, sport TEXT, total_games INT); INSERT INTO games (season, sport, total_games) VALUES ('2022', 'Basketball', 1230); INSERT INTO games (season, sport, total_games) VALUES ('2022', 'Football', 272);

SELECT SUM(total_games) FROM games WHERE season = '2022' AND sport = 'Basketball';


Question: Find the average renewable energy production of each city in France.

CREATE TABLE renewable_energy_france (id INT, city VARCHAR(255), production FLOAT); INSERT INTO renewable_energy_france (id, city, production) VALUES (1, 'Paris', 2000), (2, 'Lyon', 2500), (3, 'Marseille', 1500);

SELECT city, AVG(production) FROM renewable_energy_france GROUP BY city;


Question: Generate PostgreSQL SQL for: When was the earliest founded university?

CREATE TABLE table_261941_1 (founded INTEGER)

SELECT MIN(founded) FROM table_261941_1;


Question: Generate PostgreSQL SQL for: What was the B.P. of club Halifax?

CREATE TABLE table_19179465_1 (bp VARCHAR, club VARCHAR)

SELECT bp FROM table_19179465_1 WHERE club = 'Halifax';


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

select jsonb_object('{a,b,c,"d e f"}','{1,2,3,"a b c",g}');

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

SELECT count(*) FROM (select jsonb_object('{a,b,c,"d e f"}','{1,2,3,"a b c",g}')) AS _sub;


Question: Generate PostgreSQL SQL for: What are the names of entrepreneurs?

CREATE TABLE people (Name VARCHAR, People_ID VARCHAR); CREATE TABLE entrepreneur (People_ID VARCHAR)

SELECT T2.Name FROM entrepreneur AS T1 JOIN people AS T2 ON T1.People_ID = T2.People_ID;


Question: Generate PostgreSQL SQL for: When the wallington new foresters are in division four what is the season?

CREATE TABLE table_24575253_4 (season VARCHAR, division_four VARCHAR)

SELECT season FROM table_24575253_4 WHERE division_four = 'Wallington New Foresters';


Question: Generate PostgreSQL SQL for: List the rank of the player that left due to right wrist surgery?

CREATE TABLE table_24431264_18 (rank VARCHAR, withdrew_due_to VARCHAR)

SELECT rank FROM table_24431264_18 WHERE withdrew_due_to = 'right wrist surgery';


Question: Generate PostgreSQL SQL for: where did arron oberholser play?

CREATE TABLE table_name_84 (country VARCHAR, player VARCHAR)

SELECT country FROM table_name_84 WHERE player = 'arron oberholser';


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

SELECT name(equipment(hobby_construct(text 'skywalking', text 'mer')));

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

SELECT count(*) FROM (SELECT name(equipment(hobby_construct(text 'skywalking', text 'mer')))) AS _sub;


Question: What is the average temperature required for growing cotton?

CREATE TABLE Crop (id INT, name VARCHAR(255), minimum_temperature INT, maximum_temperature INT); INSERT INTO Crop (id, name, minimum_temperature, maximum_temperature) VALUES (1, 'Cotton', 15, 30), (2, 'Soybean', 10, 35), (3, 'Corn', 5, 30);

SELECT AVG(Crop.minimum_temperature + (Crop.maximum_temperature - Crop.minimum_temperature)/2) FROM Crop WHERE Crop.name = 'Cotton';


Question: Generate PostgreSQL SQL for: What is the highest total with a t12 finish?

CREATE TABLE table_name_61 (total INTEGER, finish VARCHAR)

SELECT MAX(total) FROM table_name_61 WHERE finish = 't12';


Question: What is the total production capacity of all tanks located in the Western region?

CREATE TABLE Production (tank VARCHAR(20), capacity INT, location VARCHAR(20)); INSERT INTO Production (tank, capacity, location) VALUES ('Tank7', 200000, 'Western'), ('Tank8', 250000, 'Western');

SELECT SUM(capacity) FROM Production WHERE location = 'Western';


Question: What is the total investment in network infrastructure for each quarter of the year?

CREATE TABLE infrastructure_investments (investment_date DATE, investment_amount DECIMAL(10,2)); INSERT INTO infrastructure_investments (investment_date, investment_amount) VALUES ('2021-01-01', 250000), ('2021-04-01', 300000), ('2021-07-01', 200000), ('2021-10-01', 350000);

SELECT EXTRACT(QUARTER FROM investment_date) AS quarter, SUM(investment_amount) FROM infrastructure_investments GROUP BY quarter;


Question: What is the total Shariah-compliant loan amount issued per month?

SELECT DATE_FORMAT(loan_date, '%Y-%m') as month, SUM(amount) as total_amount FROM shariah_compliant_loans_over_time GROUP BY month ORDER BY month;


Question: What is the total production quantity (in metric tons) of Holmium from the mine with the ID 1 for the year 2017?

CREATE TABLE production (id INT, mine_id INT, year INT, element TEXT, production_quantity INT); INSERT INTO production (id, mine_id, year, element, production_quantity) VALUES (1, 1, 2017, 'Holmium', 100), (2, 2, 2017, 'Holmium', 150), (3, 3, 2017, 'Holmium', 200), (4, 1, 2017, 'Dysprosium', 200), (5, 2, 2017, 'Dysprosium', 250), (6, 3, 2017, 'Dysprosium', 300);

SELECT SUM(production_quantity) FROM production WHERE mine_id = 1 AND year = 2017 AND element = 'Holmium';


Question: Generate PostgreSQL SQL for: Which Set 2 has a Date of 25 may, and a Set 3 of 21–25?

CREATE TABLE table_name_45 (set_2 VARCHAR, date VARCHAR, set_3 VARCHAR)

SELECT set_2 FROM table_name_45 WHERE date = '25 may' AND set_3 = '21–25';


Question: Generate PostgreSQL SQL for: what's the poles with pts being 81

CREATE TABLE table_14139408_1 (poles VARCHAR, pts VARCHAR)

SELECT poles FROM table_14139408_1 WHERE pts = '81';


Question: PostgreSQL regression test 'join': Write the SELECT query (example 509).

select p.* from
  (parent p left join child c on (p.k = c.k)) join parent x on p.k = x.k
  where p.k = 1 and p.k = 2;

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

SELECT count(*) FROM (select p.* from
  (parent p left join child c on (p.k = c.k)) join parent x on p.k = x.k
  where p.k = 1 and p.k = 2) AS _sub;


Question: Generate PostgreSQL SQL for: What is the to par of the player with a 68-67-75=210?

CREATE TABLE table_name_99 (to_par VARCHAR, score VARCHAR)

SELECT to_par FROM table_name_99 WHERE score = 68 - 67 - 75 = 210;


Question: Generate PostgreSQL SQL for: what is the minimum voted yes where percent no is 68.2

CREATE TABLE table_120778_2 (voted_yes INTEGER, percent_no VARCHAR)

SELECT MIN(voted_yes) FROM table_120778_2 WHERE percent_no = '68.2';


Question: Which train stations have accessibility features?

CREATE TABLE train_stations (station_id INT, station_name TEXT, is_accessible BOOLEAN);  INSERT INTO train_stations (station_id, station_name, is_accessible) VALUES (1, 'Union Station', true), (2, 'City Hall', false), (3, 'Downtown Crossing', true);

SELECT station_id, station_name, is_accessible   FROM train_stations   WHERE is_accessible = true;


Question: Generate PostgreSQL SQL for: HOW MUCH WAS THE OVERALL FOR ERIK KARLSSON?

CREATE TABLE table_11803648_17 (overall INTEGER)

SELECT MIN(overall) FROM table_11803648_17;


Question: Generate PostgreSQL SQL for: What is the rank of Manuel Cortina Martínez?

CREATE TABLE table_name_46 (rank VARCHAR, athletes VARCHAR)

SELECT rank FROM table_name_46 WHERE athletes = 'manuel cortina martínez';


Question: Generate PostgreSQL SQL for: How many episodes had their first air date on March 6, 2008?

CREATE TABLE table_11220799_2 (episode_titles VARCHAR, first_air_date VARCHAR)

SELECT COUNT(episode_titles) FROM table_11220799_2 WHERE first_air_date = 'March 6, 2008';


Question: What is the maximum number of military personnel deployed by African Union in peacekeeping operations?

CREATE SCHEMA if not exists defense; CREATE TABLE if not exists african_union_pk_operations (id INT PRIMARY KEY, year INT, military_personnel INT); INSERT INTO african_union_pk_operations (id, year, military_personnel) VALUES (1, 2018, 3000), (2, 2019, 3500), (3, 2020, 4000), (4, 2021, 4500);

SELECT MAX(military_personnel) FROM defense.african_union_pk_operations;


Question: Which players from the 'players' table have the highest average scores in the 'scores' table, and how many high scores did they achieve?

CREATE TABLE players (player_id INT, name VARCHAR(50)); INSERT INTO players VALUES (1, 'John'); INSERT INTO players VALUES (2, 'Jane'); CREATE TABLE scores (score_id INT, player_id INT, score INT); INSERT INTO scores VALUES (1, 1, 90); INSERT INTO scores VALUES (2, 1, 95); INSERT INTO scores VALUES (3, 2, 85); INSERT INTO scores VALUES (4, 2, 88);

SELECT p.name, AVG(s.score) as avg_score, COUNT(*) as high_scores FROM players p JOIN scores s ON p.player_id = s.player_id WHERE s.score >= (SELECT AVG(score) FROM scores) GROUP BY p.player_id ORDER BY avg_score DESC, high_scores DESC;


Question: What is the average number of green buildings per state in the 'green_buildings' table?

CREATE TABLE green_buildings (state VARCHAR(255), building_type VARCHAR(255));

SELECT state, AVG(cnt) FROM (SELECT state, COUNT(*) AS cnt FROM green_buildings GROUP BY state) AS state_building_counts;


Question: Generate PostgreSQL SQL for: How many people wrote episode number 2 of the season?

CREATE TABLE table_25737761_4 (writer VARCHAR, _number VARCHAR)

SELECT COUNT(writer) FROM table_25737761_4 WHERE _number = 2;


Question: Who are the genetic researchers working on gene editing techniques in the UK?

CREATE SCHEMA if not exists genetics; CREATE TABLE if not exists genetics.researchers (id INT, name VARCHAR(100), country VARCHAR(50), expertise VARCHAR(50)); INSERT INTO genetics.researchers (id, name, country, expertise) VALUES (1, 'John Doe', 'UK', 'CRISPR'); INSERT INTO genetics.researchers (id, name, country, expertise) VALUES (2, 'Jane Smith', 'US', 'CRISPR');

SELECT name FROM genetics.researchers WHERE country = 'UK' AND expertise = 'CRISPR';


Question: Generate PostgreSQL SQL for: How many 2006 subscribers are named Vodafone?

CREATE TABLE table_29395291_2 (subscribers__2006___thousands_ VARCHAR, provider VARCHAR)

SELECT COUNT(subscribers__2006___thousands_) FROM table_29395291_2 WHERE provider = 'Vodafone';


Question: Generate PostgreSQL SQL for: What is the party where the constituency is 10. Tindivanam?

CREATE TABLE table_22753245_1 (party VARCHAR, constituency VARCHAR)

SELECT party FROM table_22753245_1 WHERE constituency = '10. Tindivanam';


Question: Generate PostgreSQL SQL for: What is Ips-provectus transmittance/contrast ratio?

CREATE TABLE table_name_16 (transmittance__contrast_ratio VARCHAR, name VARCHAR)

SELECT transmittance__contrast_ratio FROM table_name_16 WHERE name = 'ips-provectus';


Question: What is the minimum number of visits for any exhibition?

CREATE TABLE ExhibitionStats (exhibition_id INT, min_visits INT, max_visits INT); INSERT INTO ExhibitionStats (exhibition_id, min_visits, max_visits) VALUES (1, 1000, 2000), (2, 1500, 2500), (3, 2000, 3000);

SELECT MIN(min_visits) FROM ExhibitionStats;


Question: What is the total volume of freight forwarded from Japan to Singapore?

CREATE TABLE Singapore_Freight (id INT, origin_country VARCHAR(50), destination_country VARCHAR(50), volume FLOAT); INSERT INTO Singapore_Freight (id, origin_country, destination_country, volume) VALUES (1, 'Japan', 'Singapore', 123.5), (2, 'Japan', 'Singapore', 234.6), (3, 'Malaysia', 'Singapore', 345.7);

SELECT SUM(volume) FROM Singapore_Freight WHERE origin_country = 'Japan' AND destination_country = 'Singapore';


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

--
-- test SQL string functions
-- E### and T### are feature reference numbers from SQL99
--

-- E021-09 trim function
SELECT TRIM(BOTH FROM '  bunch o blanks  ') = 'bunch o blanks' AS "bunch o blanks";

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


Question: Generate PostgreSQL SQL for: Which Cultural and Educational Panel has a Labour Panel larger than 5, and an Industrial and Commercial Panel larger than 9?

CREATE TABLE table_name_9 (cultural_and_educational_panel VARCHAR, labour_panel VARCHAR, industrial_and_commercial_panel VARCHAR)

SELECT COUNT(cultural_and_educational_panel) FROM table_name_9 WHERE labour_panel > 5 AND industrial_and_commercial_panel > 9;


Question: Generate PostgreSQL SQL for: What is the result for the Green-Communist party when the Left Bloc has 3.0%?

CREATE TABLE table_name_87 (green_communist VARCHAR, left_bloc VARCHAR)

SELECT green_communist FROM table_name_87 WHERE left_bloc = '3.0%';


Question: What is the total recycling rate for each region in the year 2020?

CREATE TABLE RecyclingAmount (region VARCHAR(50), year INT, amount FLOAT); INSERT INTO RecyclingAmount (region, year, amount) VALUES ('Region1', 2018, 600000.0), ('Region1', 2019, 700000.0), ('Region1', 2020, 800000.0), ('Region2', 2018, 500000.0), ('Region2', 2019, 600000.0), ('Region2', 2020, 700000.0);

SELECT r.region, (SUM(r.amount) / (SELECT SUM(wg.amount) FROM WasteGeneration wg WHERE wg.year = 2020 AND EXISTS (SELECT 1 FROM RecyclingCenters rc WHERE rc.region = wg.city)) * 100) FROM RecyclingAmount r WHERE r.year = 2020 GROUP BY r.region;


Question: Generate PostgreSQL SQL for: What are the average points that have december 27?

CREATE TABLE table_name_36 (points INTEGER, december VARCHAR)

SELECT AVG(points) FROM table_name_36 WHERE december = 27;


Question: Which countries in Africa have a carbon pricing (in USD/ton) that is lower than the average for the continent?

CREATE TABLE africa_carbon_pricing (id INT, country VARCHAR(50), price FLOAT); INSERT INTO africa_carbon_pricing (id, country, price) VALUES (1, 'South Africa', 10.5), (2, 'Egypt', 15.2), (3, 'Nigeria', 5.1);

SELECT country, price FROM africa_carbon_pricing WHERE price < (SELECT AVG(price) FROM africa_carbon_pricing);


Question: How many rural hospitals are in the "rural_hospitals_2" table?

CREATE TABLE rural_hospitals_2 (id INT, name TEXT, location TEXT, capacity INT); INSERT INTO rural_hospitals_2 (id, name, location, capacity) VALUES (1, 'Hospital C', 'City3', 75), (2, 'Hospital D', 'City4', 60);


Question: What is the total revenue generated by ticket sales for each month and team?

CREATE TABLE monthly_ticket_sales (ticket_id INT, team_id INT, date DATE, price INT);

SELECT EXTRACT(MONTH FROM date) as month, team_id, SUM(price) as total_revenue FROM monthly_ticket_sales GROUP BY month, team_id;


Question: Generate PostgreSQL SQL for: what is the tries against where points is 60?

CREATE TABLE table_12828723_4 (tries_against VARCHAR, points VARCHAR)

SELECT tries_against FROM table_12828723_4 WHERE points = '60';


Question: Generate PostgreSQL SQL for: What is the minimum laid down?

CREATE TABLE table_12592074_1 (laid_down INTEGER)

SELECT MIN(laid_down) FROM table_12592074_1;


Question: Generate PostgreSQL SQL for: How many states are there?

CREATE TABLE area_code_state (Id VARCHAR)


Question: How many unique fans reside in 'FL' and have an average ticket spending of over $50 in the 'fan_demographics' and 'ticket_sales' tables?

CREATE TABLE fan_demographics (fan_id INT, age INT, state VARCHAR(2)); CREATE TABLE ticket_sales (ticket_id INT, fan_id INT, event_id INT, price DECIMAL(5,2));

SELECT COUNT(DISTINCT fan_id) FROM fan_demographics fd JOIN ticket_sales ts ON fd.fan_id = ts.fan_id WHERE fd.state = 'FL' AND (ts.price / (SELECT COUNT(*) FROM ticket_sales ts2 WHERE ts.fan_id = ts2.fan_id)) > 50;


Question: Generate PostgreSQL SQL for: Where did Footscray play as the away team?

CREATE TABLE table_name_27 (venue VARCHAR, away_team VARCHAR)

SELECT venue FROM table_name_27 WHERE away_team = 'footscray';


Question: Generate PostgreSQL SQL for: The wildcats belong to what school?

CREATE TABLE table_name_38 (school VARCHAR, team VARCHAR)

SELECT school FROM table_name_38 WHERE team = 'wildcats';


Question: What is the oldest chemical still in production?

CREATE TABLE chemical_lifecycle (id INT PRIMARY KEY, chemical_name VARCHAR(255), year_introduced INT, production_status VARCHAR(255)); INSERT INTO chemical_lifecycle (id, chemical_name, year_introduced, production_status) VALUES (1, 'Hydrochloric Acid', 1950, 'Produced'); INSERT INTO chemical_lifecycle (id, chemical_name, year_introduced, production_status) VALUES (2, 'Sodium Hydroxide', 1980, 'Discontinued');

SELECT chemical_name, MIN(year_introduced) AS first_introduced FROM chemical_lifecycle WHERE production_status = 'Produced' GROUP BY chemical_name ORDER BY first_introduced;


Question: Write the DDL statement from PostgreSQL regression test 'spgist' (example 1).

create table spgist_point_tbl(id int4, p point);

Explanation: DDL from PostgreSQL core regression test for Spgist.


Question: Find the average age and total salary of employees in the 'mining_operations' table, for employees with the job_title 'Engineer'?

CREATE TABLE employees (id INT, first_name VARCHAR(50), last_name VARCHAR(50), job_title VARCHAR(50), department VARCHAR(50), age INT, salary DECIMAL(10,2), PRIMARY KEY (id)); INSERT INTO employees (id, first_name, last_name, job_title, department, age, salary) VALUES (1, 'John', 'Doe', 'Engineer', 'Mining', 35, 80000.00), (2, 'Jane', 'Doe', 'Operator', 'Mining', 28, 60000.00), (3, 'Mike', 'Johnson', 'Manager', 'Environment', 45, 90000.00);

SELECT AVG(age), AVG(salary) FROM employees WHERE job_title = 'Engineer';


Question: What is the total quantity of resources depleted in each region for the past 5 years?

SELECT resources.region, SUM(depletions.quantity) FROM resources INNER JOIN depletions ON resources.id = depletions.resource_id WHERE depletions.year BETWEEN 2017 AND 2021 GROUP BY resources.region;


Question: What is the trend in mental health parity violations for each state over the past four years?

SELECT m.state, m.year, m.violations, LAG(m.violations) OVER (PARTITION BY m.state ORDER BY m.year) as prev_year_violations FROM mental_health_parity_trend m;


Question: What is the total energy consumption per mining company, and the average energy consumption per mining operation?

CREATE TABLE mining_companies (company_id INT, company_name TEXT); INSERT INTO mining_companies (company_id, company_name) VALUES (1001, 'Mining Corp A'), (1002, 'Mining Corp B'), (1003, 'Mining Corp C'); CREATE TABLE mining_operations (operation_id INT, operation_name TEXT, country TEXT, energy_consumption FLOAT, company_id INT); INSERT INTO mining_operations (operation_id, operation_name, country, energy_consumption, company_id) VALUES (1, 'Porgera Mine', 'Papua New Guinea', 20000, 1001), (2, 'Cerro Verde Mine', 'Peru', 30000, 1001), (3, 'Gruyere Mine', 'Australia', 40000, 1002), (4, 'Veladero Mine', 'Argentina', 50000, 1002), (5, 'Kidd Mine', 'Canada', 60000, 1003), (6, 'Ducktown Mine', 'USA', 70000, 1003);

SELECT mining_companies.company_name, SUM(mining_operations.energy_consumption) AS total_energy_consumption FROM mining_companies JOIN mining_operations ON mining_companies.company_id = mining_operations.company_id GROUP BY mining_companies.company_name; SELECT AVG(energy_consumption) AS average_energy_consumption FROM mining_operations;


Question: What is the minimum and maximum water pH for each tank in the 'tank_data' table?

CREATE TABLE tank_data (tank_id INT, species VARCHAR(255), water_ph DECIMAL(5,2)); INSERT INTO tank_data (tank_id, species, water_ph) VALUES (1, 'Tilapia', 7.5), (2, 'Salmon', 6.0), (3, 'Tilapia', 7.8), (4, 'Catfish', 7.2), (5, 'Salmon', 6.5);

SELECT tank_id, MIN(water_ph) as min_ph, MAX(water_ph) as max_ph FROM tank_data GROUP BY tank_id;


Question: What is the yearly growth rate in revenue for the "hip-hop" genre in the Asian region?

CREATE TABLE YearlyRevenue(id INT, genre VARCHAR(10), region VARCHAR(10), revenue FLOAT, year INT);

SELECT (SUM(revenue) OVER (PARTITION BY genre ORDER BY year ROWS BETWEEN 1 FOLLOWING AND UNBOUNDED FOLLOWING) - SUM(revenue))/SUM(revenue) OVER (PARTITION BY genre) AS yearly_growth_rate FROM YearlyRevenue WHERE genre = 'hip-hop' AND region = 'Asian';


Question: What is the average sales figure for drugs that were approved by the EMA and contain the word 'Plus' in their name?

CREATE TABLE drug (id INT, name TEXT, approval_authority TEXT, sales FLOAT); INSERT INTO drug (id, name, approval_authority, sales) VALUES (1, 'DrugA Plus', 'EMA', 30000000); INSERT INTO drug (id, name, approval_authority, sales) VALUES (2, 'DrugB', 'EMA', 40000000); INSERT INTO drug (id, name, approval_authority, sales) VALUES (3, 'PlusDrug', 'EMA', 50000000);

SELECT AVG(sales) FROM drug WHERE approval_authority = 'EMA' AND name LIKE '%Plus%';


Question: What is the average CO2 emission of each textile mill, grouped by country and displayed in ascending order based on the emission amount?

CREATE TABLE CO2Emission (mill TEXT, country TEXT, co2_kg FLOAT); INSERT INTO CO2Emission (mill, country, co2_kg) VALUES ('MillA', 'China', 120.5), ('MillB', 'Bangladesh', 80.3), ('MillC', 'Vietnam', 160.1), ('MillD', 'India', 95.6);

SELECT country, AVG(co2_kg) as avg_co2 FROM CO2Emission GROUP BY country ORDER BY avg_co2 ASC;


Question: Generate PostgreSQL SQL for: Name the location that was founded 1798

CREATE TABLE table_2293402_2 (location VARCHAR, founded VARCHAR)

SELECT location FROM table_2293402_2 WHERE founded = 1798;


Question: What is the percentage of Indigenous employees in the Mining department?

CREATE TABLE Employees (EmployeeID INT, Name VARCHAR(50), Department VARCHAR(50), Gender VARCHAR(50), Community VARCHAR(50)); INSERT INTO Employees (EmployeeID, Name, Department, Gender, Community) VALUES (8, 'Emily Brown', 'Mining', 'Female', 'Indigenous'); INSERT INTO Employees (EmployeeID, Name, Department, Gender, Community) VALUES (9, 'Michael White', 'Mining', 'Male', 'Indigenous');

SELECT (COUNT(*) * 100.0 / (SELECT COUNT(*) FROM Employees WHERE Department = 'Mining')) AS Percentage FROM Employees WHERE Department = 'Mining' AND Community = 'Indigenous';


Question: What is the distribution of energy sources in rural areas?

CREATE TABLE energy_sources (location VARCHAR(50), source VARCHAR(50), percentage FLOAT);

SELECT source, SUM(percentage) AS percentage FROM energy_sources WHERE location = 'rural' GROUP BY source;


Question: What is the market share of electric vehicles in India?

CREATE TABLE VehicleSales (Type VARCHAR(50), Country VARCHAR(50), Sales INT); INSERT INTO VehicleSales (Type, Country, Sales) VALUES ('Electric', 'India', 50000), ('Gasoline', 'India', 2000000), ('Diesel', 'India', 1500000);

SELECT (Sales * 100.0 / (SELECT SUM(Sales) FROM VehicleSales WHERE Country = 'India')) FROM VehicleSales WHERE Type = 'Electric' AND Country = 'India';


Question: Generate PostgreSQL SQL for: What is the total sum of 50m splits for josefin lillhage in lanes above 8?

CREATE TABLE table_name_24 (split__50m_ INTEGER, name VARCHAR, lane VARCHAR)

SELECT SUM(split__50m_) FROM table_name_24 WHERE name = 'josefin lillhage' AND lane > 8;


Question: Delete records in the CargoTable that have a weight of zero

CREATE TABLE CargoTable (CargoId INT PRIMARY KEY, VesselId INT, CargoName VARCHAR(50), Weight INT);

DELETE FROM CargoTable WHERE Weight = 0;


Question: Number of public schools in each region of Brazil in 2021.

CREATE TABLE schools (id INT, name VARCHAR(50), region VARCHAR(50), country VARCHAR(50), year INT); INSERT INTO schools (id, name, region, country, year) VALUES (1, 'Escola Estadual', 'Sudeste', 'Brazil', 2021), (2, 'Colégio Municipal', 'Nordeste', 'Brazil', 2021), (3, 'Escola Municipal', 'Centro-Oeste', 'Brazil', 2021), (4, 'Escola Federal', 'Norte', 'Brazil', 2021), (5, 'Escola Particular', 'Sul', 'Brazil', 2021);

SELECT region, COUNT(*) FROM schools WHERE country = 'Brazil' GROUP BY region;


Question: Generate PostgreSQL SQL for: What's the sum of swing to gain with a winning party 2007 of Conservative with a rank smaller than 5?

CREATE TABLE table_name_70 (swing_to_gain INTEGER, winning_party_2007 VARCHAR, rank VARCHAR)

SELECT SUM(swing_to_gain) FROM table_name_70 WHERE winning_party_2007 = 'conservative' AND rank < 5;


Question: Get the total energy storage capacity (MWh) in France

CREATE TABLE energy_storage (id INT, country VARCHAR(50), capacity FLOAT); INSERT INTO energy_storage (id, country, capacity) VALUES (1, 'United Kingdom', 3000), (2, 'Germany', 4000), (3, 'France', 2500);

SELECT SUM(capacity) FROM energy_storage WHERE country = 'France';


Question: Which countries participated in space exploration missions to Venus?

CREATE TABLE Venus_Missions (Mission_ID INT, Mission_Name VARCHAR(50), Country VARCHAR(50), Launch_Year INT, PRIMARY KEY (Mission_ID)); INSERT INTO Venus_Missions (Mission_ID, Mission_Name, Country, Launch_Year) VALUES (1, 'Venera 7', 'Soviet Union', 1970), (2, 'Magellan', 'United States', 1989), (3, 'Akatsuki', 'Japan', 2010);

SELECT DISTINCT Country FROM Venus_Missions;


Question: How many unique customers prefer cruelty-free cosmetics and have made a purchase in the last month?

CREATE TABLE sales (sale_id INT, customer_id INT, product_id INT, sale_date DATE); INSERT INTO sales (sale_id, customer_id, product_id, sale_date) VALUES (1, 1001, 1, '2022-03-05'), (2, 1002, 2, '2022-03-06'), (3, 1003, 3, '2022-03-07'), (4, 1004, 4, '2022-03-08'), (5, 1001, 5, '2022-04-01'), (6, 1005, 1, '2022-04-02'); CREATE TABLE consumer_preferences (preference_id INT, customer_id INT, preference VARCHAR(255)); INSERT INTO consumer_preferences (preference_id, customer_id, preference) VALUES (1, 1001, 'Cruelty-free'), (2, 1002, 'Vegan'), (3, 1003, 'Natural'), (4, 1004, 'Cruelty-free'), (5, 1005, 'Cruelty-free');

SELECT COUNT(DISTINCT sales.customer_id) FROM sales JOIN consumer_preferences ON sales.customer_id = consumer_preferences.customer_id WHERE preference = 'Cruelty-free' AND sale_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH);


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

CREATE CONSTRAINT TRIGGER trig_del_fk_parted AFTER DELETE ON fkpart11.fk_parted INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION fkpart11.print_row();

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


Question: Generate PostgreSQL SQL for: Who was the leading scorer on the game played on February 25?

CREATE TABLE table_name_28 (leading_scorer VARCHAR, date VARCHAR)

SELECT leading_scorer FROM table_name_28 WHERE date = 'february 25';


Question: Which museums have the highest number of modern art pieces?

CREATE TABLE Museums (id INT, name VARCHAR(50), type VARCHAR(50)); INSERT INTO Museums (id, name, type) VALUES (1, 'Metropolitan Museum', 'Art'), (2, 'Natural History Museum', 'Science'); CREATE TABLE ArtPieces (id INT, title VARCHAR(50), museumId INT, artType VARCHAR(50)); INSERT INTO ArtPieces (id, title, museumId, artType) VALUES (1, 'Mona Lisa', 1, 'Modern'), (2, 'Starry Night', 1, 'Modern'), (3, 'Dinosaur Fossil', 2, 'Ancient');

SELECT Museums.name FROM Museums JOIN ArtPieces ON Museums.id = ArtPieces.museumId WHERE ArtPieces.artType = 'Modern' GROUP BY Museums.name ORDER BY COUNT(*) DESC;


Question: Update the genre of the artist 'Selena Gomez' to 'Pop-Folk'

CREATE TABLE Artists (ArtistID INT PRIMARY KEY, ArtistName VARCHAR(100), Genre VARCHAR(50));

UPDATE Artists SET Genre = 'Pop-Folk' WHERE ArtistName = 'Selena Gomez';


Question: List the community education programs that have received more than 500 donations.

CREATE TABLE if NOT EXISTS community_education (program_id INT, program_name VARCHAR(50), donation_count INT); INSERT INTO community_education (program_id, program_name, donation_count) VALUES (1, 'Wildlife Conservation 101', 500); INSERT INTO community_education (program_id, program_name, donation_count) VALUES (2, 'Endangered Species Awareness', 300); INSERT INTO community_education (program_id, program_name, donation_count) VALUES (3, 'Habitat Protection Techniques', 700);

SELECT program_name FROM community_education WHERE donation_count > 500;


Question: Add new mobile_subscribers from historically underrepresented communities.

CREATE TABLE mobile_subscribers (subscriber_id INT, data_usage FLOAT, community_representation VARCHAR(30)); INSERT INTO mobile_subscribers (subscriber_id, data_usage, community_representation) VALUES (5, 35.6, 'Latinx'), (6, 45.7, 'Black/African American'), (7, 55.8, 'Native American'), (8, 65.9, 'Asian');

INSERT INTO mobile_subscribers (subscriber_id, data_usage, community_representation) VALUES (9, 75.1, 'Pacific Islander'), (10, 85.2, 'Two or More Races'), (11, 95.3, 'Decline to State'), (12, 105.4, 'Not Hispanic or Latino');


Question: Create a table named 'sales_tax' with columns 'region' and 'tax_percentage'

CREATE TABLE sales_tax (region VARCHAR(50), tax_percentage DECIMAL(5,2));


Question: Add a new autonomous bus to the public transportation fleet in Vancouver.

CREATE TABLE public_transportation (transport_id INT, type VARCHAR(20), city VARCHAR(20)); INSERT INTO public_transportation (transport_id, type, city) VALUES (1, 'Bus', 'Vancouver'), (2, 'Tram', 'Vancouver'), (3, 'Train', 'Vancouver');

INSERT INTO public_transportation (transport_id, type, city) VALUES (4, 'Autonomous Bus', 'Vancouver');


Question: Generate PostgreSQL SQL for: Which CFL team did the player from British Columbia get drafted to

CREATE TABLE table_16441561_5 (cfl_team VARCHAR, college VARCHAR)

SELECT cfl_team FROM table_16441561_5 WHERE college = 'British Columbia';


Question: Generate PostgreSQL SQL for: What is the sum of bronzes for teams with more than 0 silver and a total under 1?

CREATE TABLE table_name_22 (bronze INTEGER, silver VARCHAR, total VARCHAR)

SELECT SUM(bronze) FROM table_name_22 WHERE silver > 0 AND total < 1;


Question: Generate PostgreSQL SQL for: Where does CF Pachuca play?

CREATE TABLE table_name_64 (game_site VARCHAR, opponent VARCHAR)

SELECT game_site FROM table_name_64 WHERE opponent = 'cf pachuca';


Question: Generate PostgreSQL SQL for: What is the order for a red list of 7 in the didelphidae family?

CREATE TABLE table_name_91 (order VARCHAR, red_list VARCHAR, family VARCHAR)

SELECT order FROM table_name_91 WHERE red_list = 7 AND family = 'didelphidae';


Question: Show the number of workers in each department by gender for the past month.

SELECT Department, Gender, COUNT(*) as Number_of_Workers FROM Workforce WHERE HireDate >= DATEADD(MONTH, -1, GETDATE()) GROUP BY Department, Gender;


Question: What are the names of all chemical compounds that have been used in the production of a hazardous product in the past 6 months?

CREATE TABLE chemical_compounds (compound_id INT, name TEXT); CREATE TABLE product_compounds (compound_id INT, product_id INT); CREATE TABLE products (product_id INT, hazardous_flag BOOLEAN, production_date DATE);

SELECT chemical_compounds.name FROM chemical_compounds INNER JOIN product_compounds ON chemical_compounds.compound_id = product_compounds.compound_id INNER JOIN products ON product_compounds.product_id = products.product_id WHERE products.hazardous_flag = TRUE AND products.production_date > DATEADD(month, -6, GETDATE());


Question: List all exploration projects in the 'Asia-Pacific' region, along with their start dates.

CREATE TABLE exploration_projects (project_id INT, project_name VARCHAR(50), region VARCHAR(50), start_date DATE); INSERT INTO exploration_projects (project_id, project_name, region, start_date) VALUES (1, 'Project X', 'Asia-Pacific', '2020-01-01');

SELECT project_name, start_date FROM exploration_projects WHERE region = 'Asia-Pacific';


Question: What is the total water consumption by all sectors in 2015 and 2016?

CREATE TABLE total_consumption (year INT, sector TEXT, consumption FLOAT); INSERT INTO total_consumption (year, sector, consumption) VALUES (2015, 'residential', 123.5), (2015, 'commercial', 234.6), (2016, 'residential', 130.2), (2016, 'commercial', 240.1);

SELECT consumption FROM total_consumption WHERE year IN (2015, 2016);


Question: Generate PostgreSQL SQL for: What is the Site when the Result was w52-0?

CREATE TABLE table_name_92 (site VARCHAR, result VARCHAR)

SELECT site FROM table_name_92 WHERE result = 'w52-0';


Question: What is the total CO2 emissions for each mining operation in the past 6 months, ordered by the most emitting operation?

CREATE TABLE mining_operations (id INT, name TEXT, co2_emissions INT, operation_date DATE); INSERT INTO mining_operations (id, name, co2_emissions, operation_date) VALUES (1, 'Operation X', 12000, '2021-07-01'), (2, 'Operation Y', 15000, '2021-07-01'), (3, 'Operation Z', 18000, '2021-07-01');

SELECT name, SUM(co2_emissions) FROM mining_operations WHERE operation_date >= DATEADD(month, -6, GETDATE()) GROUP BY name ORDER BY SUM(co2_emissions) DESC;


Question: Generate PostgreSQL SQL for: What is the highest overall pick that has c as the position, with an NFL Draft greater than 1977?

CREATE TABLE table_name_27 (overall_pick INTEGER, position VARCHAR, nfl_draft VARCHAR)

SELECT MAX(overall_pick) FROM table_name_27 WHERE position = 'c' AND nfl_draft > 1977;


Question: List the mining sites in the 'Asia-Pacific' region with environmental impact scores above 85.

CREATE TABLE mining_sites (id INT, site_name VARCHAR(50), location VARCHAR(50), environmental_score FLOAT); INSERT INTO mining_sites (id, site_name, location, environmental_score) VALUES (1, 'Site A', 'Australia', 82.50);

SELECT site_name, environmental_score FROM mining_sites WHERE location LIKE 'Asia-Pacific' AND environmental_score > 85.00;


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

INSERT INTO temporal_mltrng (id, valid_at) VALUES ('[2,3)', datemultirange(daterange('2005-01-01', '2006-01-01'))) ON CONFLICT DO NOTHING;

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


Question: Generate PostgreSQL SQL for: What is the name of team 1 that was after the 2005 season and with a 4-2 score?

CREATE TABLE table_name_11 (team_1 VARCHAR, season VARCHAR, score VARCHAR)

SELECT team_1 FROM table_name_11 WHERE season > 2005 AND score = '4-2';


Question: Generate PostgreSQL SQL for: What team was he on when he finished in 11th position?

CREATE TABLE table_24491017_1 (team VARCHAR, position VARCHAR)

SELECT team FROM table_24491017_1 WHERE position = '11th';


Question: Generate PostgreSQL SQL for: What To par scored 72-71-68=211?

CREATE TABLE table_name_29 (to_par VARCHAR, score VARCHAR)

SELECT to_par FROM table_name_29 WHERE score = 72 - 71 - 68 = 211;


Question: How many deep-sea expeditions were conducted by country?'

CREATE TABLE deep_sea_expeditions (expedition_id INT, country VARCHAR(50), year INT);

SELECT country, COUNT(expedition_id) AS num_expeditions   FROM deep_sea_expeditions   GROUP BY country;


Question: How many fans attended football games in Los Angeles during 2022?

CREATE TABLE games (team VARCHAR(255), city VARCHAR(255), date DATE, attendance INT); INSERT INTO games (team, city, date, attendance) VALUES ('LA Rams', 'Los Angeles', '2022-09-08', 70000), ('LA Chargers', 'Los Angeles', '2022-09-11', 65000);

SELECT SUM(attendance) FROM games WHERE city = 'Los Angeles' AND YEAR(date) = 2022 AND sport = 'Football';


Question: How many 'public' investors have made investments in the 'healthcare' sector?

CREATE TABLE investors (investor_id INT, investor_name VARCHAR(30), investor_type VARCHAR(20)); CREATE TABLE investments (investment_id INT, investor_id INT, sector_id INT);

SELECT COUNT(*) FROM investments i INNER JOIN investors j ON i.investor_id = j.investor_id WHERE j.investor_type = 'public' AND i.sector_id IN (SELECT sector_id FROM sectors WHERE sector_name = 'healthcare');


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

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

SELECT count(*) FROM (select format('Hello %%')) AS _sub;


Question: Generate PostgreSQL SQL for: What was the score when the away team was norwich city?

CREATE TABLE table_24887326_8 (score_1 VARCHAR, away_team VARCHAR)

SELECT score_1 FROM table_24887326_8 WHERE away_team = 'Norwich City';


Question: Generate PostgreSQL SQL for: What was the result of the game from September 10, 2000?

CREATE TABLE table_name_68 (result VARCHAR, date VARCHAR)

SELECT result FROM table_name_68 WHERE date = 'september 10, 2000';


Question: What is the average distance traveled per day by all electric vehicles in the city of Seattle?

CREATE TABLE ElectricVehicles (id INT, make VARCHAR(50), model VARCHAR(50), daily_distance FLOAT, city VARCHAR(50)); INSERT INTO ElectricVehicles (id, make, model, daily_distance, city) VALUES (1, 'Tesla', 'Model 3', 45.6, 'Seattle'); INSERT INTO ElectricVehicles (id, make, model, daily_distance, city) VALUES (2, 'Chevrolet', 'Bolt', 38.2, 'Seattle');

SELECT AVG(daily_distance) FROM ElectricVehicles WHERE city = 'Seattle';


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

CREATE OPERATOR <> (
	PROCEDURE = isnne,
	LEFTARG = ismn,
	RIGHTARG = ismn13,
	COMMUTATOR = <>,
	NEGATOR = =,
	RESTRICT = neqsel,
	JOIN = neqjoinsel);

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


Question: Which team won the most titles in the NFL?

CREATE TABLE nfl_titles (team VARCHAR(50), titles INT); INSERT INTO nfl_titles (team, titles) VALUES ('Pittsburgh Steelers', 6), ('New England Patriots', 6), ('Dallas Cowboys', 5);

SELECT team, MAX(titles) AS most_titles FROM nfl_titles;


Question: What is the minimum ocean acidification level in the Pacific Ocean?

CREATE TABLE ocean_acidification (location TEXT, value FLOAT); INSERT INTO ocean_acidification (location, value) VALUES ('Pacific Ocean', 8.1), ('Atlantic Ocean', 8.0);

SELECT MIN(value) FROM ocean_acidification WHERE location = 'Pacific Ocean';


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

CREATE FUNCTION hs_contains(hstore,hstore)
RETURNS bool
AS 'MODULE_PATHNAME','hstore_contains'
LANGUAGE C STRICT IMMUTABLE PARALLEL SAFE;


Question: Calculate the total population of all animals in Australian conservation programs

CREATE TABLE conservation_programs (id INT, program_name VARCHAR(255), location VARCHAR(255)); CREATE TABLE animal_populations (id INT, program_id INT, animal_type VARCHAR(255), population INT); INSERT INTO conservation_programs (id, program_name, location) VALUES (1, 'Australian Wildlife Conservancy', 'Australia'), (2, 'Taronga Conservation Society', 'Australia'); INSERT INTO animal_populations (id, program_id, animal_type, population) VALUES (1, 1, 'Kangaroo', 10000), (2, 1, 'Wallaby', 5000), (3, 2, 'Koala', 8000), (4, 2, 'Wombat', 2000);

SELECT SUM(animal_populations.population) FROM conservation_programs INNER JOIN animal_populations ON conservation_programs.id = animal_populations.program_id WHERE conservation_programs.location = 'Australia';


Question: Delete diversity_metrics records for company_id 102

CREATE TABLE diversity_metrics (id INT PRIMARY KEY, company_id INT, gender VARCHAR(50), diversity_score DECIMAL(3,2));

DELETE FROM diversity_metrics WHERE company_id = 102;


Question: Generate PostgreSQL SQL for: Name the date for attendance more than 20,268

CREATE TABLE table_name_47 (date VARCHAR, attendance INTEGER)

SELECT date FROM table_name_47 WHERE attendance > 20 OFFSET 268;


Question: Generate PostgreSQL SQL for: What is the lane for notes Q, SB and time less than 11.22?

CREATE TABLE table_name_31 (lane INTEGER, notes VARCHAR, time___sec__ VARCHAR)

SELECT SUM(lane) FROM table_name_31 WHERE notes = 'q, sb' AND time___sec__ < 11.22;


Question: Generate PostgreSQL SQL for: What player has 14 wins?

CREATE TABLE table_name_83 (player VARCHAR, wins VARCHAR)

SELECT player FROM table_name_83 WHERE wins = 14;


Question: Write the DDL statement from PostgreSQL regression test 'partition_prune' (example 9).

create table lp_null partition of lp for values in (null);

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


Question: Generate PostgreSQL SQL for: What year and the corresponding ceremony was the english titled movie "time out" submitted?

CREATE TABLE table_22102732_1 (year__ceremony_ VARCHAR, english_title VARCHAR)

SELECT year__ceremony_ FROM table_22102732_1 WHERE english_title = 'Time Out';


Question: Generate PostgreSQL SQL for: When dayton is the team what is the record?

CREATE TABLE table_29556461_8 (record VARCHAR, team VARCHAR)

SELECT record FROM table_29556461_8 WHERE team = 'Dayton';


Question: Generate PostgreSQL SQL for: What is the highest November that has a game less than 12, and @ detroit red wings as the opponent?

CREATE TABLE table_name_57 (november INTEGER, game VARCHAR, opponent VARCHAR)

SELECT MAX(november) FROM table_name_57 WHERE game < 12 AND opponent = '@ detroit red wings';


Question: What percentage of faculty members in the Physics department are female?

CREATE TABLE faculty (id INT, faculty_name VARCHAR(255), department VARCHAR(255), gender VARCHAR(255)); INSERT INTO faculty (id, faculty_name, department, gender) VALUES (1, 'Faculty1', 'Physics', 'Male'), (2, 'Faculty2', 'Physics', 'Female'), (3, 'Faculty3', 'Physics', 'Male'), (4, 'Faculty4', 'Mathematics', 'Female'), (5, 'Faculty5', 'Mathematics', 'Male');

SELECT (COUNT(*) FILTER (WHERE gender = 'Female')) * 100.0 / COUNT(*) as percentage FROM faculty WHERE department = 'Physics';


Question: PostgreSQL regression test 'window': Write the SELECT query (example 75).

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

SELECT count(*) FROM (SELECT * FROM v_window) AS _sub;


Question: What is the average checking account balance in the Boston branch?

CREATE TABLE accounts (customer_id INT, account_type VARCHAR(20), branch VARCHAR(20), balance DECIMAL(10,2)); INSERT INTO accounts (customer_id, account_type, branch, balance) VALUES (1, 'Savings', 'New York', 5000.00), (2, 'Checking', 'New York', 7000.00), (3, 'Checking', 'Boston', 8000.00), (4, 'Savings', 'Boston', 4000.00);

SELECT AVG(balance) FROM accounts WHERE account_type = 'Checking' AND branch = 'Boston';


Question: Find the number of sustainable tourism activities in each country.

CREATE TABLE SustainableTourismActivities (activity_id INT, activity_name TEXT, country TEXT, local_economic_impact FLOAT); INSERT INTO SustainableTourismActivities (activity_id, activity_name, country, local_economic_impact) VALUES (1, 'Biking Tour', 'Portugal', 12000.0), (2, 'Hiking Adventure', 'Portugal', 15000.0), (3, 'Surfing Lesson', 'Australia', 8000.0);

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


Question: Generate PostgreSQL SQL for: What primary sponsor has the owner Rick Hendrick and their crew chief is Alan Gustafson?

CREATE TABLE table_name_50 (primary_sponsor_s_ VARCHAR, owner_s_ VARCHAR, crew_chief VARCHAR)

SELECT primary_sponsor_s_ FROM table_name_50 WHERE owner_s_ = 'rick hendrick' AND crew_chief = 'alan gustafson';


Question: What is the maximum cargo weight transported by any vessel for each destination?

CREATE TABLE cargo_data(id INT, vessel_name VARCHAR(50), destination VARCHAR(50), cargo_weight DECIMAL(5,2)); INSERT INTO cargo_data(id, vessel_name, destination, cargo_weight) VALUES (1, 'Vessel A', 'Port A', 200.0), (2, 'Vessel B', 'Port A', 250.0);

SELECT destination, MAX(cargo_weight) FROM cargo_data GROUP BY destination;


Question: Generate PostgreSQL SQL for: What title runs for 3:22?

CREATE TABLE table_name_5 (title VARCHAR, time VARCHAR)

SELECT title FROM table_name_5 WHERE time = '3:22';


Question: Generate PostgreSQL SQL for: What country has a score less than 68, and paul casey as the player?

CREATE TABLE table_name_95 (country VARCHAR, score VARCHAR, player VARCHAR)

SELECT country FROM table_name_95 WHERE score < 68 AND player = 'paul casey';


Question: Which programs have the highest average donation in the 'Programs' and 'Donations' tables?

CREATE TABLE Programs (ProgramID INT, ProgramName VARCHAR(50)); CREATE TABLE Donations (DonorID INT, ProgramID INT, Amount DECIMAL(10, 2)); INSERT INTO Programs (ProgramID, ProgramName) VALUES (1, 'Youth Mentoring'), (2, 'Food Bank'), (3, 'Climate Action'); INSERT INTO Donations (DonorID, ProgramID, Amount) VALUES (1, 1, 500.00), (2, 2, 250.00), (3, 1, 1000.00), (4, 3, 750.00);

SELECT Programs.ProgramName, AVG(Donations.Amount) as AverageDonation FROM Programs INNER JOIN Donations ON Programs.ProgramID = Donations.ProgramID GROUP BY Programs.ProgramID ORDER BY AverageDonation DESC LIMIT 1;


Question: Generate PostgreSQL SQL for: Which team had a qualifying 2 time of 1:01.093?

CREATE TABLE table_name_11 (team VARCHAR, qual_2 VARCHAR)

SELECT team FROM table_name_11 WHERE qual_2 = '1:01.093';


Question: Generate PostgreSQL SQL for: What is the coronie with a 0.7% nickerie?

CREATE TABLE table_name_92 (coronie VARCHAR, nickerie VARCHAR)

SELECT coronie FROM table_name_92 WHERE nickerie = '0.7%';


Question: What is the total number of healthcare providers in the 'rural_clinic' table who are specialized in cardiology?

CREATE TABLE rural_clinic (id INT, name VARCHAR(50), specialty VARCHAR(50)); INSERT INTO rural_clinic (id, name, specialty) VALUES (1, 'John Doe', 'Cardiology'), (2, 'Jane Smith', 'Pediatrics'), (3, 'Michael Brown', 'Cardiology');

SELECT COUNT(*) FROM rural_clinic WHERE specialty = 'Cardiology';


Question: What is the name and capacity of each sports stadium in the state of Florida?

CREATE TABLE states (id INT, name VARCHAR(255)); CREATE TABLE stadiums (id INT, state_id INT, name VARCHAR(255), capacity INT);

SELECT name, capacity FROM stadiums WHERE state_id = (SELECT id FROM states WHERE name = 'Florida');


Question: Which AI system has the lowest explainability rating in the legal domain?

CREATE TABLE explainability_domain (ai_system TEXT, domain TEXT, rating FLOAT); INSERT INTO explainability_domain (ai_system, domain, rating) VALUES ('AI Judge', 'Legal', 0.50), ('Legal Analytics Tool', 'Legal', 0.85), ('AI Contract Review', 'Legal', 0.75);

SELECT ai_system, MIN(rating) FROM explainability_domain WHERE domain = 'Legal';


Question: What is the total number of military technology patents filed by Asian countries?

CREATE TABLE MilitaryPatents (id INT PRIMARY KEY, country VARCHAR(50), technology VARCHAR(50), date DATE); INSERT INTO MilitaryPatents (id, country, technology, date) VALUES (1, 'China', 'Stealth Technology', '2020-01-01'), (2, 'Japan', 'Artificial Intelligence', '2019-12-15'), (3, 'South Korea', 'Cyber Security', '2020-03-02');

SELECT country, COUNT(*) as total_patents FROM MilitaryPatents WHERE country IN ('China', 'Japan', 'South Korea') GROUP BY country;


Question: Generate PostgreSQL SQL for: How many goals when the points 1 is 38 and the played number is less than 42?

CREATE TABLE table_name_24 (goals_for INTEGER, points_1 VARCHAR, played VARCHAR)

SELECT SUM(goals_for) FROM table_name_24 WHERE points_1 = 38 AND played < 42;


Question: Generate PostgreSQL SQL for: Which current venues location is Mason, Ohio?

CREATE TABLE table_14903081_1 (current_venue VARCHAR, location VARCHAR)

SELECT current_venue FROM table_14903081_1 WHERE location = 'Mason, Ohio';


Question: What is the total number of climate mitigation projects in Asia that were completed before 2015?

CREATE TABLE climate_mitigation_projects (project_id INT, project_name TEXT, location TEXT, project_type TEXT, start_date DATE, end_date DATE);

SELECT COUNT(project_id) FROM climate_mitigation_projects WHERE location LIKE '%Asia%' AND end_date < '2015-01-01';


Question: Insert a new record for a donation of $500 made by a corporate donor named "ABC Corp" on March 15, 2022.

CREATE TABLE donations (id INT, donor_id INT, donation_date DATE, amount_donated DECIMAL(10,2)); CREATE TABLE donors (id INT, name TEXT, donor_type TEXT);

INSERT INTO donations (id, donor_id, donation_date, amount_donated) VALUES (1, (SELECT id FROM donors WHERE name = 'ABC Corp' AND donor_type = 'Corporate' LIMIT 1), '2022-03-15', 500); INSERT INTO donors (id, name, donor_type) VALUES (1, 'ABC Corp', 'Corporate') ON DUPLICATE KEY UPDATE id = id;


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

select encrypt('foo', '01234589', 'des');

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


Question: Which drugs were tested in clinical trials and approved, grouped by approval status?

CREATE TABLE ClinicalTrials (trial_id INT, drug_name VARCHAR(255), trial_status VARCHAR(255)); INSERT INTO ClinicalTrials (trial_id, drug_name, trial_status) VALUES (1, 'DrugD', 'Completed'), (2, 'DrugD', 'Failed'), (3, 'DrugE', 'Completed'), (4, 'DrugF', 'In Progress'); CREATE TABLE DrugApproval (drug_name VARCHAR(255), approval_date DATE); INSERT INTO DrugApproval (drug_name, approval_date) VALUES ('DrugD', '2021-03-10'), ('DrugE', '2020-11-25');

SELECT ct.trial_status, ct.drug_name FROM ClinicalTrials ct JOIN DrugApproval da ON ct.drug_name = da.drug_name GROUP BY ct.trial_status, ct.drug_name;


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

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

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


Question: Show teacher_id, training_type, and completed_date from the teacher_training table

CREATE TABLE teacher_training (id INT PRIMARY KEY, teacher_id INT, training_type VARCHAR(255), completed_date DATE);

SELECT teacher_id, training_type, completed_date FROM teacher_training;


Question: Generate PostgreSQL SQL for: What is the name of the tournament played 13 November 2000?

CREATE TABLE table_name_35 (tournament VARCHAR, date VARCHAR)

SELECT tournament FROM table_name_35 WHERE date = '13 november 2000';


Question: Generate PostgreSQL SQL for: From what country is the player with a score of 68-71-76=215?

CREATE TABLE table_name_70 (country VARCHAR, score VARCHAR)

SELECT country FROM table_name_70 WHERE score = 68 - 71 - 76 = 215;


Question: How many solar energy projects are there in Canada with a commissioned date after 2015?

CREATE TABLE solar_energy (project_id INT, project_name VARCHAR(255), country VARCHAR(255), commissioned_date DATE);

SELECT COUNT(*) FROM solar_energy WHERE country = 'Canada' AND commissioned_date > '2015-12-31';


Question: Generate PostgreSQL SQL for: Which Visitor played on January 17?

CREATE TABLE table_name_67 (visitor VARCHAR, date VARCHAR)

SELECT visitor FROM table_name_67 WHERE date = 'january 17';


Question: Generate PostgreSQL SQL for: What is the 54 holes for The Open Championship (4)?

CREATE TABLE table_name_7 (championship VARCHAR)

SELECT 54 AS _holes FROM table_name_7 WHERE championship = 'the open championship (4)';


Question: PostgreSQL regression test 'indexing': Write the SELECT query (example 230).

select c.relname, pg_get_indexdef(indexrelid)
  from pg_class c join pg_index i on c.oid = i.indexrelid
  where indrelid::regclass::text like 'idxpart%'
  order by indexrelid::regclass::text collate "C";

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

SELECT count(*) FROM (select c.relname, pg_get_indexdef(indexrelid)
  from pg_class c join pg_index i on c.oid = i.indexrelid
  where indrelid::regclass::text like 'idxpart%'
  order by indexrelid::regclass::text collate "C") AS _sub;


Question: What are the names of all satellites launched by India?

CREATE TABLE Satellites (Id INT, Name VARCHAR(50), LaunchYear INT, Country VARCHAR(50)); INSERT INTO Satellites (Id, Name, LaunchYear, Country) VALUES (1, 'Sat1', 2018, 'USA'), (2, 'Sat2', 2019, 'USA'), (3, 'Sat3', 2020, 'USA'), (4, 'Sat4', 2020, 'China'), (5, 'Sat5', 2020, 'Russia'), (6, 'Sat6', 2018, 'Germany'), (7, 'Sat7', 2019, 'India'), (8, 'Sat8', 2020, 'India'), (9, 'Sat9', 2020, 'India');

SELECT Name FROM Satellites WHERE Country = 'India';


Question: What is the average salary of workers in the manufacturing industry, grouped by their job role and location?

CREATE TABLE salaries (worker_id INT, job_role VARCHAR(255), location VARCHAR(255), salary FLOAT);

SELECT location, job_role, AVG(salary) FROM salaries GROUP BY location, job_role;


Question: What is the average age of astronauts at their first space mission?

CREATE TABLE astronauts(id INT, name VARCHAR(50), age INT, first_mission_year INT); INSERT INTO astronauts VALUES(1, 'Yang Liwei', 38, 2003), (2, 'Valentina Tereshkova', 26, 1963);

SELECT AVG(age - first_mission_year) FROM astronauts;


Question: PostgreSQL regression test 'horology': Write the SELECT query (example 131).

SELECT (timestamp without time zone 'tomorrow' > 'now') as "True";

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

SELECT count(*) FROM (SELECT (timestamp without time zone 'tomorrow' > 'now') as "True") AS _sub;


Question: Generate PostgreSQL SQL for: Name the high points for record 9-4

CREATE TABLE table_22654073_6 (high_points VARCHAR, record VARCHAR)

SELECT high_points FROM table_22654073_6 WHERE record = '9-4';


Question: Generate PostgreSQL SQL for: Name the score in the final for runner-up and hard surface with opponents being michaël llodra nenad zimonjić

CREATE TABLE table_name_1 (score_in_the_final VARCHAR, opponents_in_the_final VARCHAR, outcome VARCHAR, surface VARCHAR)

SELECT score_in_the_final FROM table_name_1 WHERE outcome = 'runner-up' AND surface = 'hard' AND opponents_in_the_final = 'michaël llodra nenad zimonjić';


Question: Insert a new product with an ID of 5, a department of 'home_decor', and a price of 14.99.

CREATE TABLE products (product_id INT, department VARCHAR(20), price DECIMAL(5,2));

INSERT INTO products (product_id, department, price) VALUES (5, 'home_decor', 14.99);


Question: What is the number of donors and total donation amount for each program?

CREATE TABLE donations (donor_id INT, program_id VARCHAR(20), amount DECIMAL(10,2)); INSERT INTO donations (donor_id, program_id, amount) VALUES (1, 'Education', 500.00), (2, 'Health', 300.00), (3, 'Education', 250.00);

SELECT program_id, COUNT(DISTINCT donor_id) AS num_donors, SUM(amount) AS total_donations FROM donations GROUP BY program_id;


Question: Generate PostgreSQL SQL for: How many FA cups for the player with under 5 champs, 0 league cups, and over 3 total?

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

SELECT SUM(fa_cup) FROM table_name_13 WHERE championship < 5 AND league_cup = 0 AND total > 3;


Question: Show me the cybersecurity policies that were dropped in the last week.

CREATE TABLE cybersecurity_policies (id INT, name VARCHAR(50), description TEXT, date DATE); INSERT INTO cybersecurity_policies (id, name, description, date) VALUES (1, 'Incident response policy', 'Outlines the process for responding to security incidents', '2022-04-15'), (2, 'Access control policy', 'Defines who has access to what resources', '2022-05-05'), (3, 'Password policy', 'Defines password complexity and length requirements', '2022-05-12');

SELECT * FROM cybersecurity_policies WHERE date >= DATEADD(week, -1, GETDATE()) AND name = 'Password policy';


Question: Which country has the most exploration projects?

CREATE TABLE exploration_projects (project_id INT, project_name VARCHAR(50), country VARCHAR(50)); INSERT INTO exploration_projects (project_id, project_name, country) VALUES (1, 'Project X', 'Brazil'), (2, 'Project Y', 'Nigeria'), (3, 'Project Z', 'Brazil');

SELECT countries.country_name, COUNT(exploration_projects.project_id) FROM exploration_projects INNER JOIN countries ON exploration_projects.country = countries.country_name GROUP BY countries.country_name ORDER BY COUNT(exploration_projects.project_id) DESC LIMIT 1;


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

SELECT * FROM pg_split_walfile_name('invalid');

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

SELECT count(*) FROM (SELECT * FROM pg_split_walfile_name('invalid')) AS _sub;


Question: Generate PostgreSQL SQL for: What is the lowest cuts made that had a Top-25 less than 6 and wins greater than 0?

CREATE TABLE table_name_63 (cuts_made INTEGER, top_25 VARCHAR, wins VARCHAR)

SELECT MIN(cuts_made) FROM table_name_63 WHERE top_25 < 6 AND wins < 0;


Question: What is the percentage of employees from underrepresented racial or ethnic groups, by department, for the entire company?

CREATE TABLE employees (id INT, name VARCHAR(50), department VARCHAR(50), race VARCHAR(50)); INSERT INTO employees (id, name, department, race) VALUES (1, 'John Doe', 'IT', 'Caucasian'); INSERT INTO employees (id, name, department, race) VALUES (2, 'Jane Smith', 'HR', 'African American');

SELECT department, SUM(CASE WHEN race IN ('African American', 'Hispanic', 'Native American', 'Asian', 'Pacific Islander') THEN 1 ELSE 0 END) / COUNT(*) * 100 AS pct_underrepresented FROM employees GROUP BY department;


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

Explanation: Regression test for Hash Func in PostgreSQL core test suite.


Question: Generate PostgreSQL SQL for: In the tournament that has 15 events, and less than 6 top-25's, how many top-5's did he have?

CREATE TABLE table_name_76 (top_5 INTEGER, events VARCHAR, top_25 VARCHAR)

SELECT SUM(top_5) FROM table_name_76 WHERE events = 15 AND top_25 < 6;


Question: Generate PostgreSQL SQL for: What is the average rank of the province alborz, which had more than 14526 in 1956?

CREATE TABLE table_name_95 (rank INTEGER, province VARCHAR)

SELECT AVG(rank) FROM table_name_95 WHERE province = 'alborz' AND 1956 > 14526;


Question: pgTAP test for Partitions (assertion 38).

SELECT * FROM check_test(
    partitions_are( 'public', 'parted', '{part1,part2,hide.part3}'::name[] ),
    true,
    'partitions_are( sch, tab, parts )',
    'Table public.parted should have the correct partitions',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Partitions.


Question: Generate PostgreSQL SQL for: When did the king who entered office in 1012 leave office?

CREATE TABLE table_name_34 (left_office VARCHAR, entered_office VARCHAR)

SELECT left_office FROM table_name_34 WHERE entered_office = '1012';


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

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


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

SELECT * FROM test_timestamp WHERE i<'2004-10-27'::date ORDER BY i;

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


Question: Obtain threat intelligence metrics related to cyber attacks on defense networks

CREATE TABLE threat_intelligence (threat_id INT, threat_source VARCHAR(50), attack_vector VARCHAR(50), network_impact FLOAT, date DATE); INSERT INTO threat_intelligence (threat_id, threat_source, attack_vector, network_impact, date) VALUES (1, 'APT10', 'Phishing', 75, '2020-01-05'); INSERT INTO threat_intelligence (threat_id, threat_source, attack_vector, network_impact, date) VALUES (2, 'APT28', 'Malware', 90, '2020-04-10');

SELECT threat_source, attack_vector, network_impact, date FROM threat_intelligence;


Question: Generate PostgreSQL SQL for: Bronze of 2, and a Silver smaller than 0 then what is the sum of the gold?

CREATE TABLE table_name_99 (gold INTEGER, bronze VARCHAR, silver VARCHAR)

SELECT SUM(gold) FROM table_name_99 WHERE bronze = 2 AND silver < 0;


Question: Generate PostgreSQL SQL for: How many bullet tips colors had other features of a blue band on case base?

CREATE TABLE table_1036189_1 (bullet_tip_color VARCHAR, other_features VARCHAR)

SELECT COUNT(bullet_tip_color) FROM table_1036189_1 WHERE other_features = 'Blue band on case base';


Question: Generate PostgreSQL SQL for: How many different jockeys ran on 17 Feb 2007?

CREATE TABLE table_14981555_3 (jockey VARCHAR, date VARCHAR)

SELECT COUNT(jockey) FROM table_14981555_3 WHERE date = '17 Feb 2007';


Question: Generate PostgreSQL SQL for: how many county with per capita income being $20,101

CREATE TABLE table_1350350_2 (county VARCHAR, per_capita_income VARCHAR)

SELECT COUNT(county) FROM table_1350350_2 WHERE per_capita_income = '$20,101';


Question: Which biosensor samples have expression levels higher than 5 for gene 'XYZ'?

CREATE SCHEMA if not exists biosensor; USE biosensor; CREATE TABLE if not exists gene_expression (sample_id INT, gene_name VARCHAR(255), expression DECIMAL(5,2)); INSERT INTO gene_expression (sample_id, gene_name, expression) VALUES (1, 'ABC', 3.45), (2, 'ABC', 3.56), (3, 'XYZ', 5.12), (4, 'DEF', 2.98), (5, 'XYZ', 6.25), (6, 'GHI', 4.02);

SELECT sample_id, gene_name, expression FROM biosensor.gene_expression WHERE gene_name = 'XYZ' AND expression > 5;


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

CREATE TABLE tbl1 (c) AS VALUES ('bar'::text);

Explanation: DDL from PostgreSQL core regression test for Rowsecurity.


Question: Generate PostgreSQL SQL for: What is the Gecko value for the item that has a Prince XML value of 'no' and a KHTML value of 'yes'?

CREATE TABLE table_name_6 (gecko VARCHAR, prince_xml VARCHAR, khtml VARCHAR)

SELECT gecko FROM table_name_6 WHERE prince_xml = 'yes' AND khtml = 'yes';


Question: Generate PostgreSQL SQL for: Name the season for runner up of judean rebels

CREATE TABLE table_name_56 (season VARCHAR, runner_up VARCHAR)

SELECT season FROM table_name_56 WHERE runner_up = 'judean rebels';


Question: Generate PostgreSQL SQL for: Who was in lane 6 with a mark of 2:05.58 SB?

CREATE TABLE table_name_84 (name VARCHAR, lane VARCHAR, mark VARCHAR)

SELECT name FROM table_name_84 WHERE lane = 6 AND mark = '2:05.58 sb';


Question: Generate PostgreSQL SQL for: What is the Runner-up on April 11?

CREATE TABLE table_name_36 (runner_up VARCHAR, week VARCHAR)

SELECT runner_up FROM table_name_36 WHERE week = 'april 11';


Question: Generate PostgreSQL SQL for: Who did the Blue Jays play against on April 11?

CREATE TABLE table_name_52 (opponent VARCHAR, date VARCHAR)

SELECT opponent FROM table_name_52 WHERE date = 'april 11';


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

SELECT * FROM brin_revmap_data(get_raw_page('test1_a_idx', 0)) LIMIT 5;


Question: Generate PostgreSQL SQL for: Who is the Winnning driver in which lorenzo bandini has the fastest lap as well as the Pole position?

CREATE TABLE table_name_21 (winning_driver VARCHAR, fastest_lap VARCHAR, pole_position VARCHAR)

SELECT winning_driver FROM table_name_21 WHERE fastest_lap = 'lorenzo bandini' AND pole_position = 'lorenzo bandini';


Question: Generate PostgreSQL SQL for: What was the rank of the park that had a value of 5,040,000 in 2010?

CREATE TABLE table_name_30 (rank VARCHAR)

SELECT rank FROM table_name_30 WHERE 2010 = '5,040,000';


Question: How many public meetings have taken place in the Finance department since 2016?

CREATE TABLE meetings (id INT, department TEXT, date DATE); INSERT INTO meetings (id, department, date) VALUES (1, 'Education', '2015-01-01'); INSERT INTO meetings (id, department, date) VALUES (2, 'Education', '2016-01-01'); INSERT INTO meetings (id, department, date) VALUES (3, 'Finance', '2015-01-01');

SELECT COUNT(*) FROM meetings WHERE department = 'Finance' AND date >= '2016-01-01';


Question: How many network infrastructure investments were made in a specific country in the last year?

CREATE TABLE network_investments (investment_id INT, investment_date DATE, country VARCHAR(50), investment_amount INT);

SELECT country, COUNT(investment_id) FROM network_investments WHERE investment_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR) GROUP BY country;


Question: PostgreSQL regression test 'join': Write the SELECT query (example 36).

SELECT tx.ii, tx.jj, tx.kk
  FROM (J1_TBL t1 (a, b, c) CROSS JOIN J2_TBL t2 (d, e))
    AS tx (ii, jj, tt, ii2, kk);

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

SELECT count(*) FROM (SELECT tx.ii, tx.jj, tx.kk
  FROM (J1_TBL t1 (a, b, c) CROSS JOIN J2_TBL t2 (d, e))
    AS tx (ii, jj, tt, ii2, kk)) AS _sub;


Question: What is the maximum recorded depth for a marine species habitat?

CREATE TABLE marine_species (id INT, name VARCHAR(255), habitat_type VARCHAR(255), average_depth FLOAT); INSERT INTO marine_species (id, name, habitat_type, average_depth) VALUES (1, 'Clownfish', 'Coral Reef', 20.0); INSERT INTO marine_species (id, name, habitat_type, average_depth) VALUES (2, 'Blue Whale', 'Open Ocean', 200.0); CREATE TABLE ocean_depths (location VARCHAR(255), depth FLOAT); INSERT INTO ocean_depths (location, depth) VALUES ('Mariana Trench', 10994.0); INSERT INTO ocean_depths (location, depth) VALUES ('Sierra Leone Rise', 5791.0);

SELECT MAX(od.depth) as max_depth FROM marine_species ms JOIN ocean_depths od ON ms.habitat_type = od.location;


Question: How many geopolitical risk assessments were conducted for Brazil in 2019 and 2020?

CREATE TABLE Geopolitical_Risk_Assessments (assessment_id INT, assessment_date DATE, country VARCHAR(50)); INSERT INTO Geopolitical_Risk_Assessments (assessment_id, assessment_date, country) VALUES (1, '2019-05-12', 'Brazil'), (2, '2020-07-03', 'Brazil'), (3, '2021-11-28', 'Brazil');

SELECT COUNT(assessment_id) FROM Geopolitical_Risk_Assessments WHERE country = 'Brazil' AND YEAR(assessment_date) IN (2019, 2020);


Question: Generate PostgreSQL SQL for: What country is David Graham from?

CREATE TABLE table_name_94 (country VARCHAR, player VARCHAR)

SELECT country FROM table_name_94 WHERE player = 'david graham';


Question: Generate PostgreSQL SQL for: What is the average number of goals conceded where more than 19 goals were scored, the team had 31 points, and more than 7 draws?

CREATE TABLE table_name_80 (goals_conceded__gc_ INTEGER, draw__pe_ VARCHAR, goals_scored__gf_ VARCHAR, points__pts_ VARCHAR)

SELECT AVG(goals_conceded__gc_) FROM table_name_80 WHERE goals_scored__gf_ > 19 AND points__pts_ = 31 AND draw__pe_ > 7;


Question: Show a SQL definition from the postgrest project (schema, item 49).

create function change_role_statement_timeout(timeout text) returns void as $_$
begin
  execute format($$
    alter role current_user set statement_timeout = %L;
  $$, timeout);

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


Question: Write the DML statement from PostgreSQL regression test 'oid' (example 17).

INSERT INTO OID_TBL(f1) VALUES (' - 500');

Explanation: DML from PostgreSQL core regression test for Oid.


Question: Which counties in 'voting_data' table have less than 10,000 registered voters?

CREATE TABLE voting_data (county VARCHAR(255), num_voters INT);

SELECT county FROM voting_data WHERE num_voters < 10000;


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

Explanation: DML from PostgreSQL core regression test for Join.


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

SELECT * FROM unnest((JSON_QUERY(jsonb '{"jsa":  [{"a": 1, "b": ["foo"]}, {"a": 2, "c": {}}, 123]}', '$' RETURNING sqljsonb_rec)).jsa);

Explanation: Regression test for Sqljson Queryfuncs in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT * FROM unnest((JSON_QUERY(jsonb '{"jsa":  [{"a": 1, "b": ["foo"]}, {"a": 2, "c": {}}, 123]}', '$' RETURNING sqljsonb_rec)).jsa)) AS _sub;


Question: Generate PostgreSQL SQL for: Which team was the opponent on December 30?

CREATE TABLE table_name_17 (team VARCHAR, date VARCHAR)

SELECT team FROM table_name_17 WHERE date = 'december 30';


Question: Generate PostgreSQL SQL for: How many times did  li ju win the womens singles and wang liqin win the mens singles?

CREATE TABLE table_28138035_6 (womens_doubles VARCHAR, womens_singles VARCHAR, mens_singles VARCHAR)

SELECT COUNT(womens_doubles) FROM table_28138035_6 WHERE womens_singles = 'Li Ju' AND mens_singles = 'Wang Liqin';


Question: What is the maximum calorie burn during 'Cardio' workouts for members residing in 'California'?

CREATE TABLE Workouts (MemberID INT, State VARCHAR(20), WorkoutType VARCHAR(20), CaloriesBurned INT); INSERT INTO Workouts (MemberID, State, WorkoutType, CaloriesBurned) VALUES (1, 'California', 'Cardio', 300), (2, 'New York', 'Strength', 250), (3, 'California', 'Cardio', 350);

SELECT MAX(CaloriesBurned) FROM Workouts WHERE State = 'California' AND WorkoutType = 'Cardio';


Question: Generate PostgreSQL SQL for: For the game ending with a score of 28-43, what is the listed as the final record?

CREATE TABLE table_name_86 (record VARCHAR, score VARCHAR)

SELECT record FROM table_name_86 WHERE score = '28-43';


Question: Create a view named "health_trends" with columns "metric_name", "latest_value", and "one_year_ago_value". Only include metrics with measurement dates within the last year.

CREATE TABLE ocean_health_metrics (metric_id INT PRIMARY KEY, metric_name VARCHAR(255), metric_value FLOAT, measurement_date DATE); INSERT INTO ocean_health_metrics (metric_id, metric_name, metric_value, measurement_date) VALUES (1, 'Dissolved oxygen', 6.5, '2022-01-01'), (2, 'pH', 8.1, '2022-01-02'), (3, 'Temperature', 15.2, '2022-01-03'), (4, 'Salinity', 34.8, '2022-01-04');

CREATE VIEW health_trends AS SELECT metric_name, MAX(metric_value) AS latest_value, (SELECT metric_value FROM ocean_health_metrics ohm2 WHERE ohm2.metric_name = ohm.metric_name AND ohm2.measurement_date = DATE_SUB(CURDATE(), INTERVAL 1 YEAR)) AS one_year_ago_value FROM ocean_health_metrics ohm WHERE measurement_date >= DATE_SUB(CURDATE(), INTERVAL 1 YEAR) GROUP BY metric_name;


Question: What is the total installed capacity (in kW) of renewable energy projects for each city?

CREATE TABLE renewable_projects (id INT, project_name VARCHAR(255), city VARCHAR(255), installed_capacity FLOAT);

SELECT city, SUM(installed_capacity) FROM renewable_projects GROUP BY city;


Question: Generate PostgreSQL SQL for: What is the sum of gold medals for the United States with silver medal count greater than 3?

CREATE TABLE table_name_26 (gold INTEGER, nation VARCHAR, silver VARCHAR)

SELECT SUM(gold) FROM table_name_26 WHERE nation = 'united states' AND silver > 3;


Question: How many dispensaries exist in Colorado with a valid license in 2023?

CREATE TABLE dispensaries (id INT, name TEXT, state TEXT, license_expiry DATE); INSERT INTO dispensaries (id, name, state, license_expiry) VALUES (1, 'Dispensary C', 'Colorado', '2023-05-01');

SELECT COUNT(*) as num_dispensaries FROM dispensaries WHERE state = 'Colorado' AND license_expiry >= '2023-01-01';


Question: What is the percentage change in water consumption for households in Tokyo from 2017 to 2018?

CREATE TABLE Household_Water_Usage (Household_ID INT, City VARCHAR(20), Year INT, Water_Consumption FLOAT); INSERT INTO Household_Water_Usage (Household_ID, City, Year, Water_Consumption) VALUES (1, 'Tokyo', 2017, 120.5), (2, 'Tokyo', 2018, 110.2);

SELECT (COUNT(*) * 100.0 / (SELECT COUNT(*) FROM Household_Water_Usage WHERE City = 'Tokyo' AND Year = 2017)) - 100.0 AS Percentage_Change FROM Household_Water_Usage WHERE City = 'Tokyo' AND Year = 2018;


Question: Generate PostgreSQL SQL for: What college did the player for the Hamilton Tiger-Cats go to?

CREATE TABLE table_21321804_3 (college VARCHAR, cfl_team VARCHAR)

SELECT college FROM table_21321804_3 WHERE cfl_team = 'Hamilton Tiger-Cats';


Question: Generate PostgreSQL SQL for: What is the Cover Date of the Story Title Spacehikers (Part 2)?

CREATE TABLE table_name_59 (cover_date VARCHAR, story_title VARCHAR)

SELECT cover_date FROM table_name_59 WHERE story_title = 'spacehikers (part 2)';


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

CREATE TABLE uaccount (
    pguser      name primary key,
    seclv       int
);


Question: How many donors have donated to each cause?

CREATE TABLE Donors (DonorID INT, DonorName VARCHAR(50), DonationAmount DECIMAL(10,2), CauseID INT);CREATE TABLE Causes (CauseID INT, CauseName VARCHAR(50));

SELECT C.CauseName, COUNT(D.DonorID) FROM Donors D JOIN Causes C ON D.CauseID = C.CauseID GROUP BY C.CauseName;


Question: Generate PostgreSQL SQL for: How many countries were sampled for the index in 2nd place in the LA ranking and 23rd in the world ranking?

CREATE TABLE table_19948664_1 (countries_sampled VARCHAR, ranking_la__2_ VARCHAR, world_ranking__1_ VARCHAR)

SELECT countries_sampled FROM table_19948664_1 WHERE ranking_la__2_ = '2nd' AND world_ranking__1_ = '23rd';


Question: What is the number of disaster preparedness workshops held in Houston and their respective attendance?"

CREATE TABLE houston_disaster_preparedness (id INT, workshop_name VARCHAR(255), city VARCHAR(255), attendance INT); INSERT INTO houston_disaster_preparedness (id, workshop_name, city, attendance) VALUES (1, 'Hurricane Preparedness', 'Houston', 30);

SELECT workshop_name, SUM(attendance) as total_attendance FROM houston_disaster_preparedness WHERE city = 'Houston' GROUP BY workshop_name;


Question: What is the minimum energy storage capacity of pumped hydro storage plants in Japan?

CREATE TABLE pumped_hydro_storage (id INT, name TEXT, country TEXT, capacity FLOAT); INSERT INTO pumped_hydro_storage (id, name, country, capacity) VALUES (1, 'Kannagawa', 'Japan', 245), (2, 'Okuyoshino', 'Japan', 270), (3, 'Shimizu', 'Japan', 300), (4, 'Okutataragi', 'Japan', 336);

SELECT MIN(capacity) FROM pumped_hydro_storage WHERE country = 'Japan';


Question: What is the maximum labor practice rating for products in each category, by brand?

CREATE TABLE Brands (id INT, brand VARCHAR(255)); INSERT INTO Brands (id, brand) VALUES (1, 'BrandA'), (2, 'BrandB'), (3, 'BrandC'); CREATE TABLE Products (id INT, product VARCHAR(255), category VARCHAR(255), brand_id INT, labor_practice_rating DECIMAL(3, 2)); INSERT INTO Products (id, product, category, brand_id, labor_practice_rating) VALUES (1, 'Product1', 'CategoryA', 1, 4.50), (2, 'Product2', 'CategoryA', 1, 4.75), (3, 'Product3', 'CategoryB', 2, 3.25), (4, 'Product4', 'CategoryB', 2, 3.50), (5, 'Product5', 'CategoryC', 3, 4.00), (6, 'Product6', 'CategoryC', 3, 4.25);

SELECT b.brand, p.category, MAX(p.labor_practice_rating) AS max_rating FROM Products p JOIN Brands b ON p.brand_id = b.id GROUP BY b.brand, p.category;


Question: What is the average years of experience for investigative journalists in the "investigative_journalists" table who are from India?

CREATE TABLE investigative_journalists (id INT, name VARCHAR(50), country VARCHAR(50), years_of_experience INT); INSERT INTO investigative_journalists (id, name, country, years_of_experience) VALUES (1, 'John Doe', 'USA', 10), (2, 'Jane Smith', 'Canada', 12), (3, 'Pedro Martinez', 'Mexico', 8), (4, 'Rajesh Patel', 'India', 15), (5, 'Anna Lee', 'India', 20);

SELECT AVG(years_of_experience) FROM investigative_journalists WHERE country = 'India';


Question: What is the average CO2 emission reduction (in metric tons) per green building in the 'green_buildings' and 'carbon_offset' schemas, grouped by city?

CREATE TABLE green_buildings.green_buildings_data (city VARCHAR(20), green_building BOOLEAN); CREATE TABLE carbon_offset.offset_initiatives (city VARCHAR(20), co2_reduction_tons INT);

SELECT city, AVG(co2_reduction_tons / (SELECT COUNT(*) FROM green_buildings.green_buildings_data WHERE green_building = TRUE)) AS avg_co2_reduction_per_green_building FROM carbon_offset.offset_initiatives WHERE green_building = TRUE GROUP BY city;


Question: What is the average amount of socially responsible loans issued by financial institutions in Africa?

CREATE TABLE financial_institutions (institution_id INT, institution_name TEXT, region TEXT);CREATE TABLE loans (loan_id INT, institution_id INT, loan_amount DECIMAL, is_socially_responsible BOOLEAN);

SELECT AVG(loan_amount) FROM loans JOIN financial_institutions ON loans.institution_id = financial_institutions.institution_id WHERE is_socially_responsible = TRUE AND region = 'Africa';


Question: What is the average water temperature in January for all salmon farms in Norway?

CREATE TABLE salmon_farms (id INT, name TEXT, country TEXT, latitude DECIMAL(9,6), longitude DECIMAL(9,6)); INSERT INTO salmon_farms (id, name, country, latitude, longitude) VALUES (1, 'Farm A', 'Norway', 60.123456, 7.123456), (2, 'Farm B', 'Norway', 62.123456, 8.123456); CREATE TABLE temperature_readings (id INT, farm_id INT, date DATE, temperature DECIMAL(5,2)); INSERT INTO temperature_readings (id, farm_id, date, temperature) VALUES (1, 1, '2022-01-01', 8.5), (2, 1, '2022-01-02', 9.0), (3, 2, '2022-01-01', 7.0), (4, 2, '2022-01-02', 7.5);

SELECT AVG(temperature) FROM temperature_readings tr JOIN salmon_farms sf ON tr.farm_id = sf.id WHERE sf.country = 'Norway' AND MONTH(tr.date) = 1;


Question: What is the average price of cotton textiles sourced from India?

CREATE TABLE textile_sourcing (id INT, material VARCHAR(20), country VARCHAR(20), price DECIMAL(5,2)); INSERT INTO textile_sourcing (id, material, country, price) VALUES (1, 'cotton', 'India', 3.50), (2, 'silk', 'China', 15.00), (3, 'wool', 'Australia', 12.00);

SELECT AVG(price) FROM textile_sourcing WHERE material = 'cotton' AND country = 'India';


Question: How many different types of crops were grown in each region over the past 5 years?

CREATE TABLE Crops (date DATE, crop_type VARCHAR(20), region VARCHAR(20));

SELECT region, COUNT(DISTINCT crop_type) OVER(PARTITION BY region ORDER BY region ROWS BETWEEN 5 PRECEDING AND CURRENT ROW) as crop_types FROM Crops;


Question: What is the total number of police officers and firefighters in each city district?

CREATE TABLE districts (did INT, name VARCHAR(255)); CREATE TABLE police_officers (oid INT, did INT, rank VARCHAR(255)); CREATE TABLE firefighters (fid INT, did INT, rank VARCHAR(255)); INSERT INTO districts VALUES (1, 'Downtown'), (2, 'Uptown'); INSERT INTO police_officers VALUES (1, 1, 'Captain'), (2, 2, 'Lieutenant'); INSERT INTO firefighters VALUES (1, 1, 'Captain'), (2, 2, 'Lieutenant');

SELECT d.name, COUNT(po.oid) + COUNT(f.fid) as total_employees FROM districts d LEFT JOIN police_officers po ON d.did = po.did LEFT JOIN firefighters f ON d.did = f.did GROUP BY d.did;


Question: What was the average cost of vegetarian menu items?

CREATE TABLE menu_items (item VARCHAR(50), type VARCHAR(15), cost DECIMAL(10,2)); INSERT INTO menu_items (item, type, cost) VALUES ('Pizza Margherita', 'Vegetarian', 30.00), ('Caesar Salad', 'Vegetarian', 15.00); CREATE VIEW veg_menu_items AS SELECT item, cost FROM menu_items WHERE type = 'Vegetarian';


Question: pgTAP test for Cmpok (assertion 10).

SELECT * FROM check_test(
    isa_ok( ''::text, 'text', 'an empty string' ),
    true,
    'isa_ok("", text, desc)',
    'an empty string isa text',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Cmpok.


Question: What is the total waste quantity generated and the total number of circular economy initiatives, for each location and material, for the fourth quarter of 2024?

CREATE TABLE WasteGeneration (Date date, Location text, Material text, Quantity integer);CREATE TABLE CircularEconomyInitiatives (Location text, Initiative text, StartDate date);

SELECT wg.Location, wg.Material, SUM(wg.Quantity) as TotalWasteQuantity, COUNT(DISTINCT cei.Initiative) as NumberOfInitiatives FROM WasteGeneration wg LEFT JOIN CircularEconomyInitiatives cei ON wg.Location = cei.Location WHERE wg.Date >= '2024-10-01' AND wg.Date < '2025-01-01' GROUP BY wg.Location, wg.Material;


Question: Generate PostgreSQL SQL for: What is the home team on March 7?

CREATE TABLE table_name_61 (home VARCHAR, date VARCHAR)

SELECT home FROM table_name_61 WHERE date = 'march 7';


Question: What is the maximum number of followers for users from India?

CREATE TABLE users (id INT, name VARCHAR(50), country VARCHAR(2), followers INT); INSERT INTO users (id, name, country, followers) VALUES (1, 'Alice', 'US', 1000), (2, 'Bob', 'IN', 2000), (3, 'Charlie', 'CA', 1500);

SELECT MAX(users.followers) as max_followers FROM users WHERE users.country = 'IN';


Question: Generate PostgreSQL SQL for: Which Points have an Opponent of vancouver canucks, and a November smaller than 11?

CREATE TABLE table_name_42 (points INTEGER, opponent VARCHAR, november VARCHAR)

SELECT AVG(points) FROM table_name_42 WHERE opponent = 'vancouver canucks' AND november < 11;


Question: Generate PostgreSQL SQL for: What is the party of the youngest people?

CREATE TABLE people (Party VARCHAR, Age VARCHAR)

SELECT Party FROM people ORDER BY Age LIMIT 1;


Question: Generate PostgreSQL SQL for: Which location includes Coast Mountains with a rank less than 18 at Skihist Mountain?

CREATE TABLE table_name_41 (location VARCHAR, mountain_peak VARCHAR, mountain_range VARCHAR, rank VARCHAR)

SELECT location FROM table_name_41 WHERE mountain_range = 'coast mountains' AND rank < 18 AND mountain_peak = 'skihist mountain';


Question: Add a new rural healthcare facility to the 'rural_facilities' table

CREATE TABLE rural_facilities (id INT PRIMARY KEY, name VARCHAR(255), type VARCHAR(50), capacity INT, location VARCHAR(255));

INSERT INTO rural_facilities (id, name, type, capacity, location) VALUES (1, 'Rural Health Clinic', 'Clinic', 20, '789 Elm St, Ruralville, CA 93420');


Question: Generate PostgreSQL SQL for: Tell me the date for dinah pfizenmaier anna zaja and winner

CREATE TABLE table_name_46 (date VARCHAR, outcome VARCHAR, opponents VARCHAR)

SELECT date FROM table_name_46 WHERE outcome = 'winner' AND opponents = 'dinah pfizenmaier anna zaja';


Question: What is the total number of space missions launched before 1999?

CREATE TABLE Missions (id INT, name VARCHAR(50), launch_year INT); INSERT INTO Missions (id, name, launch_year) VALUES (1, 'Mission1', 2000), (2, 'Mission2', 1999), (3, 'Mission3', 2001);

SELECT COUNT(*) FROM Missions WHERE launch_year < 1999;


Question: Generate PostgreSQL SQL for: Who won the bronze medal in Hiroshima?

CREATE TABLE table_name_90 (bronze VARCHAR, location VARCHAR)

SELECT bronze FROM table_name_90 WHERE location = 'hiroshima';


Question: What is the total number of orders placed by customers in the 'extra-large' size range?

CREATE TABLE customer_size(customer_id INT, size VARCHAR(10)); INSERT INTO customer_size(customer_id, size) VALUES(1, 'large'), (2, 'medium'), (3, 'extra-large'), (4, 'small');

SELECT COUNT(*) FROM customer_size WHERE size = 'extra-large';


Question: Delete all records in the 'digital_divide_stats' table where the 'year' is before 2010

CREATE TABLE digital_divide_stats (id INT PRIMARY KEY, country VARCHAR(255), year INT, internet_users INT, total_population INT);

WITH deleted_data AS (DELETE FROM digital_divide_stats WHERE year < 2010 RETURNING *) SELECT * FROM deleted_data;


Question: Generate PostgreSQL SQL for: Name the  President who has a Treasurer of james davidson, and a Season of 2006–2007?

CREATE TABLE table_name_26 (president VARCHAR, treasurer VARCHAR, season VARCHAR)

SELECT president FROM table_name_26 WHERE treasurer = 'james davidson' AND season = '2006–2007';


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

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

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


Question: Write the DDL statement from PostgreSQL regression test 'matview' (example 64).

CREATE VIEW mvtest_vt2 AS SELECT moo, 2*moo FROM mvtest_vt1 UNION ALL SELECT moo, 3*moo FROM mvtest_vt1;

Explanation: DDL from PostgreSQL core regression test for Matview.


Question: What is the capacity of landfills that serve cities with a population above 500,000?

CREATE TABLE Cities (CityID INT, CityName VARCHAR(50), Population INT, LandfillID INT); INSERT INTO Cities VALUES (1, 'CityA', 600000, 1), (2, 'CityB', 800000, 2), (3, 'CityC', 550000, 3); CREATE TABLE Landfills (LandfillID INT, LandfillName VARCHAR(50), Capacity FLOAT); INSERT INTO Landfills VALUES (1, 'Landfill1', 2000000), (2, 'Landfill2', 3000000), (3, 'Landfill3', 2500000);

SELECT LandfillName, Capacity FROM Landfills WHERE LandfillID IN (SELECT Cities.LandfillID FROM Cities WHERE Population > 500000);


Question: Generate PostgreSQL SQL for: What is the L2 cache of the microprocessor with model number pentium dual-core t3400?

CREATE TABLE table_name_91 (l2_cache VARCHAR, model_number VARCHAR)

SELECT l2_cache FROM table_name_91 WHERE model_number = 'pentium dual-core t3400';


Question: Generate PostgreSQL SQL for: What are the processors supported by a ddr2 memory and the nforce 550 model?

CREATE TABLE table_name_91 (processors_supported VARCHAR, memory VARCHAR, model VARCHAR)

SELECT processors_supported FROM table_name_91 WHERE memory = 'ddr2' AND model = 'nforce 550';


Question: List the unique medical conditions of astronauts who have participated in space missions longer than 30 days.

CREATE TABLE Astronaut_Medical (Astronaut_ID INT, Medical_Condition VARCHAR(50), Mission_Duration INT); INSERT INTO Astronaut_Medical (Astronaut_ID, Medical_Condition, Mission_Duration) VALUES (1, 'Motion Sickness', 300); INSERT INTO Astronaut_Medical (Astronaut_ID, Medical_Condition, Mission_Duration) VALUES (2, 'Space Adaptation Syndrome', 35); INSERT INTO Astronaut_Medical (Astronaut_ID, Medical_Condition, Mission_Duration) VALUES (3, 'Back Pain', 250);

SELECT DISTINCT Medical_Condition FROM Astronaut_Medical WHERE Mission_Duration > 30;


Question: Generate PostgreSQL SQL for: What was Stockholm's score when Malmo scored 2?

CREATE TABLE table_name_54 (stockholm VARCHAR, malmö VARCHAR)

SELECT stockholm FROM table_name_54 WHERE malmö = '2';


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

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


Question: Generate PostgreSQL SQL for: Who owned winner Blueeyesintherein after 2009?

CREATE TABLE table_name_75 (owner VARCHAR, year VARCHAR, winner VARCHAR)

SELECT owner FROM table_name_75 WHERE year > 2009 AND winner = 'blueeyesintherein';


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

select jsonb_path_query('1', 'strict $[1]');

SELECT count(*) FROM (select jsonb_path_query('1', 'strict $[1]')) AS _sub;


Question: How many operators were hired in the last month in each factory?

CREATE TABLE factories(id INT, name TEXT, location TEXT);CREATE TABLE operators(id INT, factory_id INT, hire_date DATE);INSERT INTO factories(id, name, location) VALUES (1, 'Factory A', 'Location A'), (2, 'Factory B', 'Location B'); INSERT INTO operators(id, factory_id, hire_date) VALUES (1, 1, '2021-04-01'), (2, 1, '2021-05-01'), (3, 2, '2021-03-15');

SELECT factory_id, COUNT(*) as new_hires FROM operators WHERE hire_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH) GROUP BY factory_id;


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

\d fk_notpartitioned_pk

-- Check the existing FK trigger
SELECT conname, tgrelid::regclass as tgrel, regexp_replace(tgname, '[0-9]+', 'N') as tgname, tgtype
FROM pg_trigger t JOIN pg_constraint c ON (t.tgconstraint = c.oid)
WHERE tgrelid IN (SELECT relid FROM pg_partition_tree('fk_partitioned_fk'::regclass)
				  UNION ALL SELECT 'fk_notpartitioned_pk'::regclass)
ORDER BY tgrelid, tgtype;

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


Question: Which organizations have a location in 'Australia' and are of type 'Government'?

CREATE TABLE organizations (id INT PRIMARY KEY, name VARCHAR(50), type VARCHAR(50), location VARCHAR(50)); INSERT INTO organizations (id, name, type, location) VALUES (1, 'Australian Renewable Energy Agency', 'Government', 'Australia'); INSERT INTO organizations (id, name, type, location) VALUES (2, 'Sustainable Energy Authority of Ireland', 'Government', 'Ireland');

SELECT organizations.name, organizations.type, organizations.location FROM organizations WHERE organizations.location = 'Australia' AND organizations.type = 'Government';


Question: What was the average price of electric vehicle charging in Paris per kWh in Q2 2022?

CREATE TABLE EV_Charging_Prices (city VARCHAR(20), quarter INT, year INT, avg_price DECIMAL(5,2)); INSERT INTO EV_Charging_Prices (city, quarter, year, avg_price) VALUES ('Paris', 2, 2022, 0.25), ('Paris', 3, 2022, 0.26), ('Berlin', 2, 2022, 0.28), ('Berlin', 3, 2022, 0.29);

SELECT AVG(avg_price) FROM EV_Charging_Prices WHERE city = 'Paris' AND quarter = 2 AND year = 2022;


Question: Generate PostgreSQL SQL for: What is the A330 for A310 B10?

CREATE TABLE table_name_62 (a330 VARCHAR, a310 VARCHAR)

SELECT a330 FROM table_name_62 WHERE a310 = 'b10';


Question: How many investments were made in total in Q2 2021?

CREATE TABLE investments (id INT, region VARCHAR(20), date DATE); INSERT INTO investments (id, region, date) VALUES (1, 'Asia-Pacific', '2021-01-05'), (2, 'Europe', '2021-02-10'), (3, 'Asia-Pacific', '2021-03-25'), (4, 'Africa', '2021-04-15'), (5, 'Europe', '2021-06-01');

SELECT COUNT(*) FROM investments WHERE date BETWEEN '2021-04-01' AND '2021-06-30';


Question: Generate PostgreSQL SQL for: What is the tier IV year for the tournament held in Tampa?

CREATE TABLE table_20630462_1 (tier_iv_in VARCHAR, tournament VARCHAR)

SELECT tier_iv_in FROM table_20630462_1 WHERE tournament = 'Tampa';


Question: What is the total area of sustainable forests in square kilometers?

CREATE TABLE forest (id INT, name TEXT, area_sqkm FLOAT, is_sustainable BOOLEAN);

SELECT SUM(area_sqkm) FROM forest WHERE is_sustainable = TRUE;


Question: What are the regulatory frameworks for 'Country4' and 'Country5'?

CREATE TABLE countries (id INT, name VARCHAR(255)); INSERT INTO countries (id, name) VALUES (1, 'Country1'); INSERT INTO countries (id, name) VALUES (2, 'Country2'); INSERT INTO countries (id, name) VALUES (3, 'Country3'); INSERT INTO countries (id, name) VALUES (4, 'Country4'); INSERT INTO countries (id, name) VALUES (5, 'Country5'); CREATE TABLE regulatory_frameworks (id INT, country_id INT, name VARCHAR(255)); INSERT INTO regulatory_frameworks (id, country_id, name) VALUES (1, 1, 'Framework1'); INSERT INTO regulatory_frameworks (id, country_id, name) VALUES (2, 1, 'Framework2'); INSERT INTO regulatory_frameworks (id, country_id, name) VALUES (3, 2, 'Framework3'); INSERT INTO regulatory_frameworks (id, country_id, name) VALUES (4, 4, 'Framework4'); INSERT INTO regulatory_frameworks (id, country_id, name) VALUES (5, 4, 'Framework5'); INSERT INTO regulatory_frameworks (id, country_id, name) VALUES (6, 5, 'Framework6');

SELECT name FROM regulatory_frameworks WHERE country_id IN (4, 5);


Question: List the banks with the lowest number of financial capability programs offered in Q2 2022, in ascending order?

CREATE TABLE FINANCIAL_CAPABILITY_PROGRAMS (BANK_NAME VARCHAR(50), PROGRAM_NAME VARCHAR(50), START_DATE DATE); INSERT INTO FINANCIAL_CAPABILITY_PROGRAMS VALUES ('Bank F', 'Program I', '2022-04-15'); INSERT INTO FINANCIAL_CAPABILITY_PROGRAMS VALUES ('Bank G', 'Program J', '2022-05-20'); INSERT INTO FINANCIAL_CAPABILITY_PROGRAMS VALUES ('Bank F', 'Program K', '2022-06-05'); INSERT INTO FINANCIAL_CAPABILITY_PROGRAMS VALUES ('Bank H', 'Program L', '2022-04-01');

SELECT BANK_NAME, COUNT(*) TOTAL_PROGRAMS FROM FINANCIAL_CAPABILITY_PROGRAMS WHERE START_DATE >= '2022-04-01' AND START_DATE < '2022-07-01' GROUP BY BANK_NAME ORDER BY TOTAL_PROGRAMS ASC;


Question: Generate PostgreSQL SQL for: Which League showed 7,975 for an average attendance?

CREATE TABLE table_name_20 (league VARCHAR, attendance_average VARCHAR)

SELECT league FROM table_name_20 WHERE attendance_average = '7,975';


Question: What is the total number of public transportation users in New York, London, and Paris in 2020?

CREATE TABLE CityTransport (city VARCHAR(30), users INT, year INT); INSERT INTO CityTransport (city, users, year) VALUES ('New York', 1000000, 2020), ('London', 1200000, 2020), ('Paris', 1100000, 2020);

SELECT SUM(users) FROM CityTransport WHERE city IN ('New York', 'London', 'Paris') AND year = 2020;


Question: What is the minimum fare for a trolleybus in the 'Delhi' region?

CREATE TABLE trolleybuses (id INT, region VARCHAR(20), fare DECIMAL(5,2)); INSERT INTO trolleybuses (id, region, fare) VALUES (1, 'Delhi', 15.00), (2, 'Delhi', 20.00), (3, 'Mumbai', 12.00);

SELECT MIN(fare) FROM trolleybuses WHERE region = 'Delhi';


Question: What is the average number of games played by players from the United States?

CREATE TABLE Players (PlayerID INT, PlayerName VARCHAR(50), Age INT, Country VARCHAR(50)); INSERT INTO Players (PlayerID, PlayerName, Age, Country) VALUES (1, 'John Doe', 25, 'USA'); INSERT INTO Players (PlayerID, PlayerName, Age, Country) VALUES (2, 'Jane Smith', 30, 'Canada');

SELECT AVG(Age) FROM Players WHERE Country = 'USA';


Question: How many matches did each player participate in during the 2020 tennis season?

CREATE TABLE tennis (player VARCHAR(255), match_id INT); INSERT INTO tennis (player, match_id) VALUES ('Federer', 1), ('Federer', 2), ('Federer', 3), ('Djokovic', 4), ('Djokovic', 5);

SELECT player, COUNT(*) FROM tennis GROUP BY player;


Question: What is the average fine for each violation in 'regulatory_compliance' table?

CREATE TABLE regulatory_compliance (id INT, dispensary VARCHAR(255), fine FLOAT, violation DATE);

SELECT violation, AVG(fine) as avg_fine FROM regulatory_compliance GROUP BY violation;


Question: List all managers and their respective departments who have not completed diversity and inclusion training.

CREATE TABLE Employees (EmployeeID INT, FirstName VARCHAR(50), LastName VARCHAR(50), Department VARCHAR(50), Position VARCHAR(50)); CREATE TABLE DiversityTraining (EmployeeID INT, TrainingID INT, Completed DATE); INSERT INTO Employees (EmployeeID, FirstName, LastName, Department, Position) VALUES (1, 'John', 'Doe', 'IT', 'Manager'), (2, 'Jane', 'Smith', 'HR', 'Manager'); INSERT INTO DiversityTraining (EmployeeID, TrainingID, Completed) VALUES (1, 1, '2021-06-01');

SELECT Employees.FirstName, Employees.LastName, Employees.Department FROM Employees LEFT JOIN DiversityTraining ON Employees.EmployeeID = DiversityTraining.EmployeeID WHERE Employees.Position = 'Manager' AND DiversityTraining.Completed IS NULL;


Question: Which department has the highest number of security incidents in the 'security_incidents' table?

CREATE TABLE security_incidents (id INT, department VARCHAR(50), date DATE);

SELECT department, COUNT(*) as incident_count FROM security_incidents GROUP BY department ORDER BY incident_count DESC LIMIT 1;


Question: PostgreSQL regression test 'without_overlaps': Write the SELECT query (example 233).

SELECT * FROM tp1 ORDER BY id, valid_at;

Explanation: Regression test for Without Overlaps in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT * FROM tp1 ORDER BY id, valid_at) AS _sub;


Question: What are the product names and their ratings for products with a rating greater than 4.5?

CREATE TABLE products (product_id INT, product_name TEXT, rating FLOAT); INSERT INTO products (product_id, product_name, rating) VALUES (1, 'Product A', 4.5), (2, 'Product B', 4.2), (3, 'Product C', 4.8);

SELECT product_name, rating FROM products WHERE rating > 4.5;


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

SELECT ''::ltree || 'Top.Child1.Child2'::ltree;

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


Question: What was the average project timeline for sustainable building projects in New York?

CREATE TABLE project_timelines (id INT PRIMARY KEY, project_name VARCHAR(255), state VARCHAR(255), start_date DATE, end_date DATE, sustainable VARCHAR(5));

SELECT AVG(DATEDIFF(end_date, start_date)) FROM project_timelines WHERE state = 'New York' AND sustainable = 'yes';


Question: How many inclusive housing units are in New York and Los Angeles combined?

CREATE TABLE inclusive_housing (units INT, city VARCHAR(20));

SELECT SUM(units) FROM inclusive_housing WHERE city IN ('New York', 'Los Angeles');


Question: Generate PostgreSQL SQL for: What team had the record asscoiated with the 9th inning?

CREATE TABLE table_name_54 (team VARCHAR, inn VARCHAR)

SELECT team FROM table_name_54 WHERE inn = '9th';


Question: Generate PostgreSQL SQL for: Which province has evening gown score of 7.61

CREATE TABLE table_15081939_4 (province VARCHAR, evening_gown VARCHAR)

SELECT province FROM table_15081939_4 WHERE evening_gown = '7.61';


Question: Generate PostgreSQL SQL for: What is the average Goals/Games for Rummenigge, Karl-Heinz, with Goals less than 162?

CREATE TABLE table_name_66 (games VARCHAR, goals INTEGER, name VARCHAR)

SELECT AVG(goals) / games FROM table_name_66 WHERE name = 'rummenigge, karl-heinz' AND goals < 162;


Question: Which countries have no renewable energy projects in the renewable_projects table?

CREATE TABLE renewable_projects (id INT, project_name VARCHAR(100), country VARCHAR(50)); INSERT INTO renewable_projects (id, project_name, country) VALUES (1, 'Renewable Project 1', 'Germany'), (2, 'Renewable Project 2', 'Sweden');

SELECT rp.country FROM renewable_projects rp GROUP BY rp.country HAVING COUNT(*) = 0;