Question: How many traffic accidents were reported in the state of California in the last 6 months?

CREATE TABLE traffic_accidents (id INT, date DATE, state VARCHAR(255)); INSERT INTO traffic_accidents (id, date, state) VALUES (1, '2022-01-01', 'California'), (2, '2022-01-15', 'California'), (3, '2022-02-01', 'California');

SELECT COUNT(*) FROM traffic_accidents WHERE state = 'California' AND date > DATE_SUB(CURRENT_DATE, INTERVAL 6 MONTH);


Question: Which destination in Mexico had the highest increase in visitors from 2019 to 2022?

CREATE TABLE mexico_tourism (destination VARCHAR(50), year INT, visitors INT); INSERT INTO mexico_tourism (destination, year, visitors) VALUES ('Cancun', 2019, 2000000), ('Cancun', 2022, 2500000), ('Puerto Vallarta', 2019, 1500000), ('Puerto Vallarta', 2022, 2000000);

SELECT destination, MAX(visitors) - MIN(visitors) AS increase FROM mexico_tourism WHERE year IN (2019, 2022) GROUP BY destination ORDER BY increase DESC LIMIT 1;


Question: What is the maximum salary for male employees hired before June 2021?

SELECT MAX(Salary) FROM Employees WHERE Gender = 'Male' AND HireDate < '2021-06-01';


Question: Generate PostgreSQL SQL for: WHich Name origin has a Longitude of 332.5e?

CREATE TABLE table_name_94 (name VARCHAR, longitude VARCHAR)

SELECT name AS origin FROM table_name_94 WHERE longitude = '332.5e';


Question: What is the maximum selling price of natural makeup products in France?

CREATE TABLE MakeupProducts (product_id INT, product_name VARCHAR(255), price DECIMAL(5,2), is_natural BOOLEAN, country VARCHAR(50));

SELECT MAX(price) FROM MakeupProducts WHERE is_natural = TRUE AND country = 'France';


Question: Generate PostgreSQL SQL for: Which organizations were founded in 1972, but became WOSM members until 1977?

CREATE TABLE table_104858_1 (name_of_member_organization VARCHAR, year_member_organization_was_founded VARCHAR, year_current_scouting_organization_joined_wosm VARCHAR)

SELECT name_of_member_organization FROM table_104858_1 WHERE year_member_organization_was_founded = '1972' AND year_current_scouting_organization_joined_wosm = '1977';


Question: Generate PostgreSQL SQL for: Away team Swindon Town had a Tie no listing of Replay with what as an Attendance?

CREATE TABLE table_name_74 (attendance VARCHAR, tie_no VARCHAR, away_team VARCHAR)

SELECT attendance FROM table_name_74 WHERE tie_no = 'replay' AND away_team = 'swindon town';


Question: Write the DDL statement from PostgreSQL regression test 'publication' (example 112).

Explanation: DDL from PostgreSQL core regression test for Publication.


Question: Write the DML statement from PostgreSQL regression test 'rules' (example 541).

INSERT INTO hats VALUES ('h7', 'blue') RETURNING *;

Explanation: DML from PostgreSQL core regression test for Rules.


Question: Find the average mental health score of students in the 'Spring' semester

CREATE TABLE student_mental_health (student_id INT, semester VARCHAR(10), mental_health_score INT); INSERT INTO student_mental_health (student_id, semester, mental_health_score) VALUES (1, 'Spring', 75), (2, 'Spring', 80), (3, 'Fall', 70);

SELECT AVG(mental_health_score) FROM student_mental_health WHERE semester = 'Spring';


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

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


Question: PostgreSQL regression test 'tstypes': Write the SELECT query (example 171).

SELECT ts_delete('base:7 hidden:6 rebel:1 spaceship:2,33A,34B,35C,36D strike:3'::tsvector, ARRAY['spaceshi','rebel']);

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

SELECT count(*) FROM (SELECT ts_delete('base:7 hidden:6 rebel:1 spaceship:2,33A,34B,35C,36D strike:3'::tsvector, ARRAY['spaceshi','rebel'])) AS _sub;


Question: Generate PostgreSQL SQL for: How many years was the pageant miss globe international and delegate was karen loren medrano agustin?

CREATE TABLE table_1825751_14 (year VARCHAR, pageant VARCHAR, delegate VARCHAR)

SELECT COUNT(year) FROM table_1825751_14 WHERE pageant = 'Miss Globe International' AND delegate = 'Karen Loren Medrano Agustin';


Question: What is the average water consumption per household in the city of Seattle?

CREATE TABLE Household (ID INT, City VARCHAR(20), Consumption FLOAT); INSERT INTO Household (ID, City, Consumption) VALUES (1, 'Seattle', 12.3), (2, 'NYC', 10.5), (3, 'Seattle', 13.8);

SELECT AVG(Consumption) FROM Household WHERE City = 'Seattle';


Question: How many individuals have been served by access to justice initiatives in Europe since 2017?

CREATE TABLE initiatives (initiative_id INT, year INT, individuals_served INT); INSERT INTO initiatives (initiative_id, year, individuals_served) VALUES (1, 2017, 2000), (2, 2018, 3000); CREATE TABLE locations (initiative_id INT, region VARCHAR(20)); INSERT INTO locations (initiative_id, region) VALUES (1, 'Europe'), (2, 'North America');

SELECT SUM(initiatives.individuals_served) FROM initiatives INNER JOIN locations ON initiatives.initiative_id = locations.initiative_id WHERE locations.region = 'Europe' AND initiatives.year >= 2017;


Question: Generate PostgreSQL SQL for: How many draws have rumba/tango dance styles?

CREATE TABLE table_name_79 (draw VARCHAR, dance_styles VARCHAR)

SELECT COUNT(draw) FROM table_name_79 WHERE dance_styles = 'rumba/tango';


Question: What is the percentage of female faculty members in the university?

CREATE TABLE university_faculty (id INT, gender VARCHAR(10)); INSERT INTO university_faculty (id, gender) VALUES (1, 'Female'), (2, 'Male'), (3, 'Male'), (4, 'Female'), (5, 'Female');

SELECT ROUND(100.0 * SUM(CASE WHEN gender = 'Female' THEN 1 ELSE 0 END) / COUNT(*), 1) as pct_female_faculty;


Question: Generate PostgreSQL SQL for: What is team 1 if Renova is team 2?

CREATE TABLE table_name_99 (team_1 VARCHAR, team_2 VARCHAR)

SELECT team_1 FROM table_name_99 WHERE team_2 = 'renova';


Question: Generate PostgreSQL SQL for: how many matches did the player that played 23 matches win

CREATE TABLE table_29302711_12 (matches_won INTEGER, matches_played VARCHAR)

SELECT MIN(matches_won) FROM table_29302711_12 WHERE matches_played = 23;


Question: What is the total revenue generated by each product type, sorted by the total revenue in descending order?

CREATE TABLE RevenueByProduct (product VARCHAR(255), revenue DECIMAL(10,2)); INSERT INTO RevenueByProduct (product, revenue) VALUES ('Flower', 50000), ('Concentrates', 35000), ('Edibles', 40000), ('Topicals', 25000);

SELECT product, SUM(revenue) as total_revenue FROM RevenueByProduct GROUP BY product ORDER BY total_revenue DESC;


Question: Generate PostgreSQL SQL for: What is the number of clubs before 2003 with a 4th place winner of Shenzhen Jianlibao?

CREATE TABLE table_name_66 (number_of_clubs INTEGER, fourth_placed VARCHAR, season VARCHAR)

SELECT AVG(number_of_clubs) FROM table_name_66 WHERE fourth_placed = 'shenzhen jianlibao' AND season < 2003;


Question: How many incidents were recorded for Vessel3 between January 1, 2021 and June 30, 2021?

CREATE TABLE VesselIncidents(IncidentID INT, VesselID INT, IncidentType TEXT, IncidentDate DATETIME); INSERT INTO VesselIncidents(IncidentID, VesselID, IncidentType, IncidentDate) VALUES (1, 3, 'Collision', '2021-03-15 14:30:00'), (2, 3, 'Mechanical Failure', '2021-05-02 08:00:00');

SELECT COUNT(*) FROM VesselIncidents WHERE VesselID = 3 AND IncidentDate BETWEEN '2021-01-01' AND '2021-06-30';


Question: Generate PostgreSQL SQL for: What is the average number played of the team with 1 drawn and 24 against?

CREATE TABLE table_name_79 (played INTEGER, drawn VARCHAR, against VARCHAR)

SELECT AVG(played) FROM table_name_79 WHERE drawn = 1 AND against = 24;


Question: Generate PostgreSQL SQL for: What is the product, chromosome and porphyria related to the enzymes which take effect at the location 'Cytosol'?

CREATE TABLE enzyme (product VARCHAR, chromosome VARCHAR, porphyria VARCHAR, LOCATION VARCHAR)

SELECT product, chromosome, porphyria FROM enzyme WHERE LOCATION = 'Cytosol';


Question: What is the total number of players who play games on each platform and in each city?

CREATE TABLE Players (PlayerID INT, City VARCHAR(20), Platform VARCHAR(10)); INSERT INTO Players (PlayerID, City, Platform) VALUES (1, 'Tokyo', 'PC'), (2, 'Los Angeles', 'Console'), (3, 'New York', 'PC'), (4, 'Paris', 'VR'), (5, 'Tokyo', 'Console'), (6, 'Los Angeles', 'PC');

SELECT City, Platform, COUNT(*) AS Count FROM Players GROUP BY City, Platform ORDER BY Count DESC;


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

INSERT INTO f_star (class) VALUES ('f');

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


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

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

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


Question: What is the total donation amount for each preservation project in each location?

CREATE TABLE PreservationProjects (id INT, name VARCHAR(255), location VARCHAR(255), start_date DATE, end_date DATE, donation_amount FLOAT);

SELECT p.location, p.name, SUM(p.donation_amount) FROM PreservationProjects p GROUP BY p.location, p.name;


Question: How many 'high' severity security incidents were recorded in the last month for the 'finance' department?

CREATE TABLE incidents (id INT, department VARCHAR(255), severity VARCHAR(255), incident_date DATE); INSERT INTO incidents (id, department, severity, incident_date) VALUES (1, 'finance', 'high', '2022-04-15'), (2, 'IT', 'medium', '2022-02-20'), (3, 'finance', 'medium', '2022-03-05'); SELECT CURDATE(), DATE_SUB(CURDATE(), INTERVAL 1 MONTH) INTO @current_date, @start_date; SELECT COUNT(*) FROM incidents WHERE department = 'finance' AND severity = 'high' AND incident_date BETWEEN @start_date AND @current_date;

SELECT COUNT(*) FROM incidents WHERE department = 'finance' AND severity = 'high' AND incident_date BETWEEN DATE_SUB(CURDATE(), INTERVAL 1 MONTH) AND CURDATE();


Question: What is the total transaction value for each month of the year 2022?

CREATE TABLE transactions (transaction_id INT, transaction_date DATE, transaction_category VARCHAR(255), transaction_value DECIMAL(10,2)); INSERT INTO transactions (transaction_id, transaction_date, transaction_category, transaction_value) VALUES (1, '2022-01-02', 'Food', 75.00), (2, '2022-02-05', 'Electronics', 350.00), (3, '2022-03-10', 'Clothing', 200.00);

SELECT YEAR(transaction_date) as year, MONTH(transaction_date) as month, SUM(transaction_value) as total_value FROM transactions WHERE transaction_date BETWEEN '2022-01-01' AND '2022-12-31' GROUP BY year, month;


Question: What is the total amount of funding received by 'community_development' table where the 'community_name' is 'peace_village'?

CREATE TABLE community_development (id INT, community_name TEXT, community_size INT, region TEXT, funding FLOAT);

SELECT SUM(funding) FROM community_development WHERE community_name = 'peace_village';


Question: Generate PostgreSQL SQL for: What was the score of the game on November 9 when Atlanta was the visiting team?

CREATE TABLE table_name_73 (score VARCHAR, visitor VARCHAR, date VARCHAR)

SELECT score FROM table_name_73 WHERE visitor = 'atlanta' AND date = 'november 9';


Question: Generate PostgreSQL SQL for: What was the attendance of the bowl game in Gainesville, Fl?

CREATE TABLE table_15190346_2 (attendance VARCHAR, location VARCHAR)

SELECT attendance FROM table_15190346_2 WHERE location = 'Gainesville, FL';


Question: List the names and types of all military technologies that were developed in the last 5 years.

CREATE TABLE military_technology (id INT, name VARCHAR(255), technology_type VARCHAR(255), development_date DATE);INSERT INTO military_technology (id, name, technology_type, development_date) VALUES (1, 'F-35', 'Fighter Jet', '2010-01-01'), (2, 'M1 Abrams', 'Tank', '2005-01-01'), (3, 'Patriot', 'Missile System', '2015-01-01');

SELECT name, technology_type FROM military_technology WHERE YEAR(development_date) >= 2015;


Question: How many packages were shipped from Colombia to Brazil in Q1 2022?

CREATE TABLE packages (package_id INT, origin_country VARCHAR(255), destination_country VARCHAR(255), shipped_qty INT, shipped_quarter INT, shipped_year INT); INSERT INTO packages (package_id, origin_country, destination_country, shipped_qty, shipped_quarter, shipped_year) VALUES (1, 'Colombia', 'Brazil', 250, 1, 2022), (2, 'Brazil', 'Argentina', 300, 1, 2022), (3, 'Chile', 'Brazil', 350, 1, 2022);

SELECT SUM(shipped_qty) as total_shipped FROM packages WHERE origin_country = 'Colombia' AND destination_country = 'Brazil' AND shipped_quarter = 1 AND shipped_year = 2022;


Question: Generate PostgreSQL SQL for: What is the ga date of the t5120 model?

CREATE TABLE table_10818465_1 (ga_date VARCHAR, model VARCHAR)

SELECT ga_date FROM table_10818465_1 WHERE model = 'T5120';


Question: Generate PostgreSQL SQL for: How many were written by Peter Winther?

CREATE TABLE table_20704243_3 (written_by VARCHAR, directed_by VARCHAR)

SELECT COUNT(written_by) FROM table_20704243_3 WHERE directed_by = 'Peter Winther';


Question: Generate PostgreSQL SQL for: What is the name of the race on 9 July?

CREATE TABLE table_name_72 (name VARCHAR, date VARCHAR)

SELECT name FROM table_name_72 WHERE date = '9 july';


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

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

SELECT count(*) FROM (SELECT '[1,2]'::jsonb @> '[1,2,2]'::jsonb) AS _sub;


Question: Generate PostgreSQL SQL for: Find the country of the airlines whose name starts with 'Orbit'.

CREATE TABLE airlines (country VARCHAR, name VARCHAR)

SELECT country FROM airlines WHERE name LIKE 'Orbit%';


Question: Generate PostgreSQL SQL for: Which Bronze has a Rank of 4, and a Gold smaller than 0?

CREATE TABLE table_name_7 (bronze INTEGER, rank VARCHAR, gold VARCHAR)

SELECT MAX(bronze) FROM table_name_7 WHERE rank = 4 AND gold < 0;


Question: Generate PostgreSQL SQL for: Who did wilson reis fight against that lasted less than 3 rounds with a time of 1:02?

CREATE TABLE table_name_25 (opponent VARCHAR, round VARCHAR, time VARCHAR)

SELECT opponent FROM table_name_25 WHERE round < 3 AND time = '1:02';


Question: Generate PostgreSQL SQL for: What was the opponent at the game that had a loss of Travers (0–2)?

CREATE TABLE table_name_9 (opponent VARCHAR, loss VARCHAR)

SELECT opponent FROM table_name_9 WHERE loss = 'travers (0–2)';


Question: Generate PostgreSQL SQL for: Which Time/Retired has less than 77 laps, and a Grid of 16?

CREATE TABLE table_name_68 (time_retired VARCHAR, laps VARCHAR, grid VARCHAR)

SELECT time_retired FROM table_name_68 WHERE laps < 77 AND grid = 16;


Question: What is the total amount of climate finance invested in renewable energy in Africa?

CREATE TABLE ClimateFinance (Country TEXT, Sector TEXT, Investment_Amount NUMERIC); INSERT INTO ClimateFinance (Country, Sector, Investment_Amount) VALUES ('South Africa', 'Renewable Energy', 5000000), ('Kenya', 'Renewable Energy', 2000000), ('Nigeria', 'Renewable Energy', 7000000);

SELECT SUM(Investment_Amount) FROM ClimateFinance WHERE Country IN ('South Africa', 'Kenya', 'Nigeria') AND Sector = 'Renewable Energy';


Question: What is the average number of players per multiplayer game in Europe?

CREATE TABLE Games (GameID INT, GameType VARCHAR(255), Multiplayer INT); INSERT INTO Games (GameID, GameType, Multiplayer) VALUES (1, 'Racing', 0); INSERT INTO Games (GameID, GameType, Multiplayer) VALUES (2, 'Shooter', 1); CREATE TABLE Players (PlayerID INT, GameID INT); INSERT INTO Players (PlayerID, GameID) VALUES (1, 1); INSERT INTO Players (PlayerID, GameID) VALUES (1, 2); INSERT INTO Players (PlayerID, GameID) VALUES (2, 2); INSERT INTO Players (PlayerID, GameID) VALUES (3, 2); INSERT INTO Players (PlayerID, GameID) VALUES (4, 2); INSERT INTO Players (PlayerID, GameID) VALUES (5, 2); INSERT INTO Players (PlayerID, GameID) VALUES (6, 2); INSERT INTO Players (PlayerID, GameID) VALUES (7, 2); INSERT INTO Players (PlayerID, GameID) VALUES (8, 2); INSERT INTO Players (PlayerID, GameID) VALUES (9, 2); INSERT INTO Players (PlayerID, GameID) VALUES (10, 2);

SELECT AVG(CountPlayers) FROM (SELECT GameID, COUNT(PlayerID) AS CountPlayers FROM Players INNER JOIN Games ON Players.GameID = Games.GameID WHERE Games.Multiplayer = 1 GROUP BY GameID) AS Subquery WHERE EXISTS (SELECT GameID FROM Games WHERE ReleaseCountry LIKE '%Europe%' AND Games.GameID = Subquery.GameID);


Question: Generate PostgreSQL SQL for: What is the score when the team is milwaukee?

CREATE TABLE table_27734769_8 (score VARCHAR, team VARCHAR)

SELECT score FROM table_27734769_8 WHERE team = 'Milwaukee';


Question: Generate PostgreSQL SQL for: What was the result of the game played on April 16 with Philadelphia as home team?

CREATE TABLE table_name_64 (result VARCHAR, home_team VARCHAR, date VARCHAR)

SELECT result FROM table_name_64 WHERE home_team = 'philadelphia' AND date = 'april 16';


Question: Calculate the percentage of unresolved vulnerabilities by region

CREATE TABLE vulnerabilities (id INT, region VARCHAR(10), status VARCHAR(10)); INSERT INTO vulnerabilities (id, region, status) VALUES (1, 'EMEA', 'Resolved'), (2, 'APAC', 'Unresolved'), (3, 'AMER', 'Resolved'), (4, 'EMEA', 'Resolved'), (5, 'APAC', 'Resolved'), (6, 'AMER', 'Unresolved');

SELECT region, 100.0 * SUM(CASE WHEN status = 'Unresolved' THEN 1 ELSE 0 END) / COUNT(*) as unresolved_percentage FROM vulnerabilities GROUP BY region;


Question: Generate PostgreSQL SQL for: What are the points for ktm-vmc equipment?

CREATE TABLE table_16729457_18 (points VARCHAR, equipment VARCHAR)

SELECT points FROM table_16729457_18 WHERE equipment = 'KTM-VMC';


Question: Identify the menu items that were 86'ed (ran out) before 5pm on a specific day for the 'Gourmet Greens' restaurant.

CREATE TABLE menu_items (id INT, restaurant_id INT, name VARCHAR(50), available INT, available_time TIME); INSERT INTO menu_items (id, restaurant_id, name, available, available_time) VALUES (1, 3, 'Kale Salad', 10, '12:00:00'), (2, 3, 'Beet Burger', 15, '12:00:00'), (3, 3, 'Carrot Fries', 20, '12:00:00'), (4, 3, 'Quinoa Bowl', 30, '12:00:00');

SELECT name FROM menu_items WHERE restaurant_id = 3 AND available_time < '17:00:00' GROUP BY name HAVING SUM(available) = 0;


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

CREATE TABLE t2(time timestamptz, device text, value float) WITH (timescaledb.nonexistent_param = false);

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


Question: Generate PostgreSQL SQL for: For which Game 4 did Michael O'Connor play wing position?

CREATE TABLE table_name_8 (game_4 VARCHAR, position VARCHAR, game_1 VARCHAR)

SELECT game_4 FROM table_name_8 WHERE position = 'wing' AND game_1 = 'michael o'connor';


Question: What is the number of unique users who have streamed music from each genre?

CREATE TABLE user_genre_streams (stream_id int, user_id int, timestamp datetime, genre varchar(255)); INSERT INTO user_genre_streams (stream_id, user_id, timestamp, genre) VALUES (1, 123, '2022-01-01 10:00:00', 'Rock');

SELECT genre, COUNT(DISTINCT user_id) as unique_users FROM user_genre_streams WHERE timestamp BETWEEN '2022-01-01' AND '2022-12-31' GROUP BY genre;


Question: Insert data into the 'auto_show' table

CREATE TABLE auto_show (id INT PRIMARY KEY, show_name VARCHAR(255), location VARCHAR(255), start_date DATE, end_date DATE);

INSERT INTO auto_show (id, show_name, location, start_date, end_date) VALUES (1, 'Paris Motor Show', 'Paris, France', '2023-10-01', '2023-10-15');


Question: Generate PostgreSQL SQL for: What are all the name(namesakes) for the entire chart?

CREATE TABLE table_29860752_11 (name__namesake_ VARCHAR)

SELECT name__namesake_ FROM table_29860752_11;


Question: Generate PostgreSQL SQL for: How many entries are shown for date of successors formal installation where successor is john w. walker (dr)?

CREATE TABLE table_225099_3 (date_of_successors_formal_installation VARCHAR, successor VARCHAR)

SELECT COUNT(date_of_successors_formal_installation) FROM table_225099_3 WHERE successor = 'John W. Walker (DR)';


Question: Generate PostgreSQL SQL for: Tell me the highest total when the horse is spender s

CREATE TABLE table_name_99 (total INTEGER, horse VARCHAR)

SELECT MAX(total) FROM table_name_99 WHERE horse = 'spender s';


Question: Generate PostgreSQL SQL for: Which nation has a Bronze and Silver smaller than 1 and a Gold larger than 1?

CREATE TABLE table_name_87 (nation VARCHAR, gold VARCHAR, bronze VARCHAR, silver VARCHAR)

SELECT nation FROM table_name_87 WHERE bronze < 1 AND silver < 1 AND gold > 1;


Question: Find healthcare providers with low cultural competency scores serving Latinx in FL.

CREATE TABLE healthcare_providers (provider_id INT, name TEXT, state TEXT); INSERT INTO healthcare_providers (provider_id, name, state) VALUES (1, 'Dr. Ana Perez', 'FL'); CREATE TABLE cultural_competency (provider_id INT, score INT, community TEXT);

SELECT h.name, c.score FROM healthcare_providers h INNER JOIN cultural_competency c ON h.provider_id = c.provider_id WHERE h.state = 'FL' AND c.community = 'Latinx' AND c.score < 50;


Question: What is the average order size for each salesperson?

CREATE TABLE salesperson (id INT, name VARCHAR(50), region VARCHAR(50)); INSERT INTO salesperson (id, name, region) VALUES (1, 'John Doe', 'North'), (2, 'Jane Smith', 'South'); CREATE TABLE orders (id INT, salesperson_id INT, size INT); INSERT INTO orders (id, salesperson_id, size) VALUES (1, 1, 10), (2, 1, 15), (3, 2, 20), (4, 2, 25);

SELECT salesperson_id, AVG(size) as avg_order_size FROM orders GROUP BY salesperson_id;


Question: pgTAP test for Valueset (assertion 230).

Explanation: SQL assertion from pgTAP test suite for Valueset.


Question: What is the number of circular economy initiatives for each country in 2020?

CREATE TABLE circular_economy (country VARCHAR(255), year INT, initiatives INT); INSERT INTO circular_economy (country, year, initiatives) VALUES ('USA', 2020, 15), ('Canada', 2020, 10), ('Mexico', 2020, 12);

SELECT c.country, COUNT(c.initiatives) as num_initiatives FROM circular_economy c WHERE c.year = 2020 GROUP BY c.country;


Question: What is the number of food safety violations per category?

CREATE TABLE Menu_Categories (Category_ID INT, Category_Name TEXT); INSERT INTO Menu_Categories (Category_ID, Category_Name) VALUES (1, 'Main Dishes'), (2, 'Sides'); CREATE TABLE Menu_Items (Item_ID INT, Item_Name TEXT, Category_ID INT); INSERT INTO Menu_Items (Item_ID, Item_Name, Category_ID) VALUES (1, 'Burger', 1), (2, 'Pizza', 1), (3, 'Fries', 2), (4, 'Salad', 2); CREATE TABLE Inspections (Inspection_ID INT, Item_ID INT, Violation_Count INT); INSERT INTO Inspections (Inspection_ID, Item_ID, Violation_Count) VALUES (1, 1, 3), (2, 1, 2), (3, 2, 1), (4, 2, 0), (5, 3, 1), (6, 4, 0);

SELECT MC.Category_Name, SUM(I.Violation_Count) as Total_Violations FROM Inspections I JOIN Menu_Items MI ON I.Item_ID = MI.Item_ID JOIN Menu_Categories MC ON MI.Category_ID = MC.Category_ID GROUP BY MC.Category_Name;


Question: Find the total revenue of organic haircare products in the Asian market for the current year.

CREATE TABLE sales(product_id INT, sale_date DATE, revenue DECIMAL(10,2), country VARCHAR(50)); INSERT INTO sales VALUES (11, '2021-06-15', 50.00, 'CN'); INSERT INTO sales VALUES (12, '2021-07-16', 60.00, 'JP'); CREATE TABLE products(product_id INT, product_name VARCHAR(50), is_organic BOOLEAN, product_category VARCHAR(50)); INSERT INTO products VALUES (11, 'Rosemary Shampoo', TRUE, 'Haircare'); INSERT INTO products VALUES (12, 'Lavender Conditioner', TRUE, 'Haircare');

SELECT SUM(sales.revenue) as total_revenue FROM sales JOIN products ON sales.product_id = products.product_id WHERE products.is_organic = TRUE AND sales.country = 'Asia' AND YEAR(sales.sale_date) = YEAR(CURDATE());


Question: Which aircraft has the most accidents in a specific region?

CREATE TABLE aircrafts (aircraft_id INT, model VARCHAR(50), region VARCHAR(50)); INSERT INTO aircrafts (aircraft_id, model, region) VALUES (1, 'Boeing 747', 'North America'), (2, 'Airbus A320', 'Europe'), (3, 'Boeing 737', 'Asia'); CREATE TABLE accidents (accident_id INT, aircraft_id INT, date DATE); INSERT INTO accidents (accident_id, aircraft_id) VALUES (1, 1), (2, 1), (3, 3), (4, 2), (5, 2);

SELECT a.model, COUNT(*) as num_accidents FROM aircrafts a JOIN accidents b ON a.aircraft_id = b.aircraft_id WHERE a.region = 'North America' GROUP BY a.model ORDER BY num_accidents DESC LIMIT 1;


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

/* skip test if not UTF8 server encoding */
SELECT getdatabaseencoding() <> 'UTF8' AS skip_test \gset
\if :skip_test
\quit
\endif

\getenv libdir PG_LIBDIR
\getenv dlsuffix PG_DLSUFFIX

\set regresslib :libdir '/regress' :dlsuffix

CREATE FUNCTION test_bytea_to_text(bytea) RETURNS text
    AS :'regresslib' LANGUAGE C STRICT;

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


Question: pgTAP test for Resultset (assertion 443).

DECLARE cwant CURSOR FOR SELECT id, name FROM names WHERE name like 'An%' ORDER BY id;

Explanation: SQL assertion from pgTAP test suite for Resultset.


Question: What is the total weight loss in pounds for members who have lost weight since they joined?

CREATE TABLE health_metrics (member_id INT, weight_loss_pounds FLOAT, last_checked DATE); INSERT INTO health_metrics (member_id, weight_loss_pounds, last_checked) VALUES (1, 3, '2021-01-15'), (2, 7, '2022-03-28');

SELECT SUM(weight_loss_pounds) FROM health_metrics JOIN members ON health_metrics.member_id = members.member_id WHERE health_metrics.weight_loss_pounds > 0;


Question: Generate PostgreSQL SQL for: What is the average overall pick number for the USF player who was picked after round 5?

CREATE TABLE table_name_23 (overall INTEGER, college VARCHAR, round VARCHAR)

SELECT AVG(overall) FROM table_name_23 WHERE college = 'usf' AND round > 5;


Question: Generate PostgreSQL SQL for: Who directed the episode written cyrus nowrasteh?

CREATE TABLE table_name_85 (directed_by VARCHAR, written_by VARCHAR)

SELECT directed_by FROM table_name_85 WHERE written_by = 'cyrus nowrasteh';


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

SELECT regexp_matches('foobarbequebaz'::citext, '(bar)(beque)') = ARRAY[ 'bar', 'beque' ] AS t;

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


Question: Generate PostgreSQL SQL for: who is the opponent where tv is abc and game site is tampa stadium

CREATE TABLE table_11406866_2 (opponent VARCHAR, tv VARCHAR, game_site VARCHAR)

SELECT opponent FROM table_11406866_2 WHERE tv = 'ABC' AND game_site = 'Tampa Stadium';


Question: How many local businesses have partnered with hotels in Japan and South Korea?

CREATE TABLE BusinessPartnerships(id INT, business_id INT, hotel_id INT); INSERT INTO BusinessPartnerships(id, business_id, hotel_id) VALUES (1, 1, 1), (2, 2, 2), (3, 3, null), (6, 4, 3), (7, 5, 4); CREATE TABLE LocalBusinesses(id INT, name TEXT, country TEXT); INSERT INTO LocalBusinesses(id, name, country) VALUES (1, 'Surf Shop', 'Japan'), (2, 'Coffee House', 'Japan'), (3, 'Art Gallery', 'Japan'), (4, 'Ramen Shop', 'South Korea'), (5, 'Tea House', 'South Korea'); CREATE TABLE Hotels(id INT, name TEXT, country TEXT); INSERT INTO Hotels(id, name, country) VALUES (1, 'Ocean View', 'Japan'), (2, 'Harbor Inn', 'Japan'), (3, 'Seoul Palace', 'South Korea'), (4, 'Kyoto Garden', 'South Korea');

SELECT COUNT(*) FROM BusinessPartnerships JOIN LocalBusinesses ON BusinessPartnerships.business_id = LocalBusinesses.id JOIN Hotels ON BusinessPartnerships.hotel_id = Hotels.id WHERE LocalBusinesses.country IN ('Japan', 'South Korea') AND Hotels.country IN ('Japan', 'South Korea');


Question: Generate PostgreSQL SQL for: For a team 2 of Al-Faisaly, what was the 2nd leg?

CREATE TABLE table_name_96 (team_2 VARCHAR)

SELECT 2 AS nd_leg FROM table_name_96 WHERE team_2 = 'al-faisaly';


Question: What is the average carbon sequestration value in the 'central_region'?

CREATE TABLE carbon_sequestration (id INT, region VARCHAR(50), value FLOAT); INSERT INTO carbon_sequestration (id, region, value) VALUES (1, 'Central Region', 56.78); INSERT INTO carbon_sequestration (id, region, value) VALUES (2, 'Northern Region', 34.56);

SELECT AVG(value) FROM carbon_sequestration WHERE region = 'Central Region';


Question: Generate PostgreSQL SQL for: What's the lane with a time of 1:00.66?

CREATE TABLE table_name_93 (lane INTEGER, time VARCHAR)

SELECT AVG(lane) FROM table_name_93 WHERE time = '1:00.66';


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

$$ language plpgsql;

select stacked_diagnostics_test();

drop function stacked_diagnostics_test();

-- test variadic functions

create or replace function vari(variadic int[])
returns void as $$
begin
  for i in array_lower($1,1)..array_upper($1,1) loop
    raise notice '%', $1[i];

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


Question: Generate PostgreSQL SQL for: Which To par has a Place in t9 and a Country of Spain?

CREATE TABLE table_name_55 (to_par VARCHAR, place VARCHAR, country VARCHAR)

SELECT to_par FROM table_name_55 WHERE place = 't9' AND country = 'spain';


Question: What is the number of countries in the Latin America and Caribbean region that have reduced their carbon emissions in the last 5 years?

CREATE TABLE country_emissions (name VARCHAR(50), region VARCHAR(50), year INT, carbon_emissions INT); INSERT INTO country_emissions (name, region, year, carbon_emissions) VALUES ('Country 1', 'Latin America and Caribbean', 2017, 10000); INSERT INTO country_emissions (name, region, year, carbon_emissions) VALUES ('Country 1', 'Latin America and Caribbean', 2018, 9000); INSERT INTO country_emissions (name, region, year, carbon_emissions) VALUES ('Country 1', 'Latin America and Caribbean', 2019, 8000); INSERT INTO country_emissions (name, region, year, carbon_emissions) VALUES ('Country 2', 'Latin America and Caribbean', 2017, 15000); INSERT INTO country_emissions (name, region, year, carbon_emissions) VALUES ('Country 2', 'Latin America and Caribbean', 2018, 14000); INSERT INTO country_emissions (name, region, year, carbon_emissions) VALUES ('Country 2', 'Latin America and Caribbean', 2019, 13000);

SELECT region, COUNT(*) FROM country_emissions WHERE region = 'Latin America and Caribbean' AND carbon_emissions < (SELECT carbon_emissions FROM country_emissions WHERE name = 'Country 1' AND year = 2017 AND region = 'Latin America and Caribbean' ORDER BY year DESC LIMIT 1) GROUP BY region HAVING COUNT(*) > 1;


Question: Generate PostgreSQL SQL for: What is McCains percent when Obamas is 39.13%

CREATE TABLE table_20688030_1 (mccain_number VARCHAR, obama_percentage VARCHAR)

SELECT COUNT(mccain_number) FROM table_20688030_1 WHERE obama_percentage = '39.13%';


Question: Generate PostgreSQL SQL for: What is the lowest size of the school with titans as the mascot?

CREATE TABLE table_name_93 (size INTEGER, mascot VARCHAR)

SELECT MIN(size) FROM table_name_93 WHERE mascot = 'titans';


Question: Delete any soil moisture readings that are older than 30 days.

CREATE TABLE Soil_Moisture (ID INT, Moisture FLOAT, Timestamp DATETIME); INSERT INTO Soil_Moisture (ID, Moisture, Timestamp) VALUES (1, 45, '2022-01-01 10:00:00'), (2, 52, '2022-01-15 12:00:00');

DELETE FROM Soil_Moisture WHERE Timestamp < NOW() - INTERVAL '30 days';


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

SELECT btrim('xyxtrimyyx'::citext,    'xy'::text  ) = 'trim' AS t;


Question: Generate PostgreSQL SQL for: What Winning driver has a Winning constructor of talbot?

CREATE TABLE table_name_59 (winning_driver VARCHAR, winning_constructor VARCHAR)

SELECT winning_driver FROM table_name_59 WHERE winning_constructor = 'talbot';


Question: What is the total quantity of recycled materials used by each brand?

CREATE TABLE Brands (BrandID INT, BrandName VARCHAR(50)); INSERT INTO Brands (BrandID, BrandName) VALUES (1, 'BrandX'), (2, 'BrandY'), (3, 'BrandZ'); CREATE TABLE Products (ProductID INT, ProductName VARCHAR(50), BrandID INT, RecycledMaterials INT); INSERT INTO Products (ProductID, ProductName, BrandID, RecycledMaterials) VALUES (1, 'ProductA', 1, 25), (2, 'ProductB', 1, 30), (3, 'ProductC', 2, 15), (4, 'ProductD', 2, 0), (5, 'ProductE', 3, 35), (6, 'ProductF', 3, 40);

SELECT BrandName, SUM(RecycledMaterials) as TotalRecycledMaterials FROM Brands b JOIN Products p ON b.BrandID = p.BrandID GROUP BY BrandName;


Question: What is the average age of patients who identified as LGBTQ+ and have been diagnosed with anxiety?

CREATE TABLE patients (id INT PRIMARY KEY, name VARCHAR(255), age INT, gender VARCHAR(50), ethnicity VARCHAR(255), condition VARCHAR(255)); INSERT INTO patients (id, name, age, gender, ethnicity, condition) VALUES (1, 'Alex Johnson', 30, 'Male', 'Latinx', 'Anxiety');

SELECT AVG(age) as average_age FROM patients WHERE ethnicity LIKE '%LGBTQ+%' AND condition = 'Anxiety';


Question: How many cases were handled by each attorney in the last year?

CREATE TABLE cases (case_id INT, attorney_name VARCHAR(255), case_date DATE); INSERT INTO cases (case_id, attorney_name, case_date) VALUES (1, 'Smith', '2020-01-01'), (2, 'Jones', '2020-05-15'), (3, 'Jones', '2021-07-20'), (4, 'Smith', '2020-12-31'), (5, 'Brown', '2020-06-20');

SELECT attorney_name, COUNT(*) FROM cases WHERE case_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR) GROUP BY attorney_name;


Question: Insert a new product with id 8 from 'Italy'

CREATE TABLE products (id INT PRIMARY KEY, name VARCHAR(100), category VARCHAR(50), price DECIMAL(5,2));

INSERT INTO products (id, name, category, price) VALUES (8, 'Parmigiano Reggiano', 'Cheese', 29.99, 'Italy');


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

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


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

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

SELECT count(*) FROM (SELECT to_timestamp('05121445482000', 'MMDDHH24MISSYYYY')) AS _sub;


Question: Generate PostgreSQL SQL for: How old was the person born 24 September 1851 at the time of disaster?

CREATE TABLE table_name_81 (age_at_time_of_disaster VARCHAR, date_of_birth VARCHAR)

SELECT age_at_time_of_disaster FROM table_name_81 WHERE date_of_birth = '24 september 1851';


Question: Which menu items have a high calorie count and are also bestsellers?

CREATE TABLE MenuItems (id INT, item VARCHAR(30), calories INT, popularity INT); INSERT INTO MenuItems (id, item, calories, popularity) VALUES (1, 'Cheese Burger', 600, 100), (2, 'Garden Salad', 200, 50);

SELECT item, calories FROM MenuItems WHERE popularity > 70 ORDER BY calories DESC;


Question: Generate PostgreSQL SQL for: Which party belongs to district 41, and is delegated by Jill P. Carter?

CREATE TABLE table_name_61 (party VARCHAR, district VARCHAR, delegate VARCHAR)

SELECT party FROM table_name_61 WHERE district = 41 AND delegate = 'jill p. carter';


Question: Generate PostgreSQL SQL for: How much money does the player with a score of 76-70-65-68=279 have?

CREATE TABLE table_name_24 (money___$__ VARCHAR, score VARCHAR)

SELECT money___$__ FROM table_name_24 WHERE score = 76 - 70 - 65 - 68 = 279;


Question: Generate PostgreSQL SQL for: What was the TO par for the player who scored 70-68-74-70=282?

CREATE TABLE table_name_26 (to_par VARCHAR, score VARCHAR)

SELECT to_par FROM table_name_26 WHERE score = 70 - 68 - 74 - 70 = 282;


Question: Generate PostgreSQL SQL for: What is the constructor for the VII Race of Champions?

CREATE TABLE table_name_34 (constructor VARCHAR, race_name VARCHAR)

SELECT constructor FROM table_name_34 WHERE race_name = 'vii race of champions';


Question: Generate PostgreSQL SQL for: Who is the minister with a term end on 10 March 1974?

CREATE TABLE table_name_71 (minister VARCHAR, term_end VARCHAR)

SELECT minister FROM table_name_71 WHERE term_end = '10 march 1974';


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

SELECT * FROM test_float8 WHERE i>1::float8 ORDER BY i;

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


Question: Generate PostgreSQL SQL for: Where was there a result of 4-5 and a score of 1-1?

CREATE TABLE table_name_98 (venue VARCHAR, result VARCHAR, score VARCHAR)

SELECT venue FROM table_name_98 WHERE result = '4-5' AND score = '1-1';


Question: Generate PostgreSQL SQL for: What was zach johnson's score to par?

CREATE TABLE table_275162_1 (to_par VARCHAR, player VARCHAR)

SELECT to_par FROM table_275162_1 WHERE player = 'Zach Johnson';


Question: Generate PostgreSQL SQL for: What is the Date, when the Sport is luge - men's doubles, and when the Record is, "start"?

CREATE TABLE table_name_90 (date VARCHAR, sport VARCHAR, record VARCHAR)

SELECT date FROM table_name_90 WHERE sport = 'luge - men's doubles' AND record = 'start';


Question: Find the number of Mars rovers with a mass greater than 500 kg

CREATE TABLE rovers (id INT, name VARCHAR(50), mass INT, manufacturer VARCHAR(50));

SELECT COUNT(*) FROM rovers WHERE mass > 500 AND planet = 'Mars';


Question: Generate PostgreSQL SQL for: What is the total top-25 of the U.S. Open, which has less than 7 cuts?

CREATE TABLE table_name_84 (top_25 INTEGER, tournament VARCHAR, cuts_made VARCHAR)

SELECT SUM(top_25) FROM table_name_84 WHERE tournament = 'u.s. open' AND cuts_made < 7;


Question: Generate PostgreSQL SQL for: How many different titles does the representative whose mission was terminated on August 5, 1984 have?

CREATE TABLE table_20065425_1 (title VARCHAR, termination_of_mission VARCHAR)

SELECT COUNT(title) FROM table_20065425_1 WHERE termination_of_mission = 'August 5, 1984';


Question: Generate PostgreSQL SQL for: What are the distinct positions of the players from a country whose capital is Dublin?

CREATE TABLE country (Country_id VARCHAR, Capital VARCHAR); CREATE TABLE match_season (Position VARCHAR, Country VARCHAR)

SELECT DISTINCT T2.Position FROM country AS T1 JOIN match_season AS T2 ON T1.Country_id = T2.Country WHERE T1.Capital = 'Dublin';


Question: List all rural infrastructure projects in India and their respective start dates.

CREATE TABLE rural_infrastructure_projects (id INT, project_name VARCHAR(50), country VARCHAR(50), start_date DATE); INSERT INTO rural_infrastructure_projects (id, project_name, country, start_date) VALUES (1, 'Rajiv Gandhi Rural Electrification Program', 'India', '2010-04-01'), (2, 'BharatNet Rural Broadband Initiative', 'India', '2015-07-26');

SELECT project_name, start_date FROM rural_infrastructure_projects WHERE country = 'India';


Question: List broadband subscribers who joined after mobile subscribers with the same region_id.

SELECT b.* FROM broadband_subscribers b INNER JOIN mobile_subscribers m ON b.region_id = m.region_id WHERE b.join_date > m.join_date;


Question: What is the count of unique accommodations for 'MobilityAssistanceDog' in the 'ServiceAnimalAccommodations' table?

CREATE TABLE ServiceAnimalAccommodations (service_animal_id INT, accommodation_type VARCHAR(255)); INSERT INTO ServiceAnimalAccommodations (service_animal_id, accommodation_type) VALUES (1001, 'VisualAssistanceDog'), (1002, 'HearingDog'), (1003, 'MobilityAssistanceDog'), (1004, 'MobilityAssistanceDog'), (1005, 'VisualAssistanceDog');

SELECT COUNT(DISTINCT accommodation_type) FROM ServiceAnimalAccommodations WHERE accommodation_type = 'MobilityAssistanceDog';


Question: Generate PostgreSQL SQL for: What is the Location for the jiu-jitsu vs martial arts?

CREATE TABLE table_name_36 (location VARCHAR, event VARCHAR)

SELECT location FROM table_name_36 WHERE event = 'jiu-jitsu vs martial arts';


Question: Generate PostgreSQL SQL for: What's the Proto-Germanic when the German is /t/?

CREATE TABLE table_name_48 (proto_germanic VARCHAR, german VARCHAR)

SELECT proto_germanic FROM table_name_48 WHERE german = '/t/';


Question: How many circular economy initiatives were launched in Osaka in 2020?

CREATE TABLE circular_economy_initiatives(location VARCHAR(20), launch_date DATE); INSERT INTO circular_economy_initiatives VALUES('Osaka', '2020-01-01'), ('Osaka', '2020-03-15'), ('Tokyo', '2019-12-31');

SELECT COUNT(*) as initiatives FROM circular_economy_initiatives WHERE location = 'Osaka' AND YEAR(launch_date) = 2020;


Question: What is the total number of fish in each farm in the aquaculture facility?

CREATE TABLE salmon_farms (id INT, name TEXT, location TEXT, size INT);CREATE TABLE fish_population (id INT, farm_id INT, species TEXT, population INT, biomass FLOAT, date DATE);

SELECT farm_id, SUM(population) FROM fish_population GROUP BY farm_id;


Question: Show a SQL definition from the timescaledb project (plain, item 12).

CREATE TABLE z (b TEXT, PRIMARY KEY(aa, b)) inherits (a);


Question: What is the total number of workers from historically underrepresented communities in the Operations department?

CREATE TABLE departments (id INT, name VARCHAR(255), diversity_stats VARCHAR(255)); INSERT INTO departments (id, name, diversity_stats) VALUES (1, 'HR', '{"total_employees":50, "underrepresented":20}'), (2, 'Operations', '{"total_employees":75, "underrepresented":15}'), (3, 'Finance', '{"total_employees":60, "underrepresented":10}');

SELECT d.name AS department, JSON_EXTRACT(d.diversity_stats, '$.underrepresented') AS underrepresented_count FROM departments d WHERE d.name = 'Operations';


Question: What was the total donation amount for the year 2020 in the 'Great Lakes' region?

CREATE TABLE Donations (donation_id INT, region VARCHAR(20), amount DECIMAL(10,2), donation_year INT); INSERT INTO Donations (donation_id, region, amount, donation_year) VALUES (1, 'Great Lakes', 5000.00, 2020), (2, 'Southeast', 3000.00, 2020);

SELECT SUM(amount) FROM Donations WHERE region = 'Great Lakes' AND donation_year = 2020;


Question: What was the total budget for criminal justice systems before 2018?

CREATE TABLE public.criminal_justice (id serial PRIMARY KEY, name text, type text, budget integer, year integer); INSERT INTO public.criminal_justice (name, type, budget, year) VALUES ('Prison System', 'Corrections', 85000000, 2020), ('Police Department', 'Law Enforcement', 150000000, 2018);

SELECT name, type, budget, year, (SELECT SUM(budget) FROM public.criminal_justice cj2 WHERE cj2.year < cj.year AND cj2.id <> cj.id) as total_budget_before FROM public.criminal_justice cj WHERE year < 2018;


Question: Which urban farms in Oakland, CA have the highest yield per acre?

CREATE TABLE urban_farms (name TEXT, city TEXT, state TEXT, acres NUMERIC, yield NUMERIC); INSERT INTO urban_farms (name, city, state, acres, yield) VALUES ('Groundwork', 'Oakland', 'CA', 2.5, 15000), ('City Slicker Farms', 'Oakland', 'CA', 3.2, 12000), ('Kinderfarms', 'Oakland', 'CA', 1.9, 8000);

SELECT name, acres, yield, ROW_NUMBER() OVER (ORDER BY yield/acres DESC) as rank FROM urban_farms WHERE city = 'Oakland' AND state = 'CA';


Question: How many articles were published per day in January 2020?

CREATE TABLE articles (id INT, title VARCHAR(100), content TEXT, publish_date DATE); INSERT INTO articles (id, title, content, publish_date) VALUES (1, 'Article 1', 'Content 1', '2020-01-01'), (2, 'Article 2', 'Content 2', '2020-01-02'), (3, 'Article 3', 'Content 3', '2020-01-03');

SELECT DATE_FORMAT(publish_date, '%Y-%m-%d') AS day, COUNT(*) as articles_per_day FROM articles WHERE YEAR(publish_date) = 2020 AND MONTH(publish_date) = 1 GROUP BY day;


Question: Generate PostgreSQL SQL for: Name the number of season number for jeff truman

CREATE TABLE table_15838081_3 (season__number VARCHAR, writer_s_ VARCHAR)

SELECT COUNT(season__number) FROM table_15838081_3 WHERE writer_s_ = 'Jeff Truman';


Question: Generate PostgreSQL SQL for: Which highschool has senior (rs) for the year?

CREATE TABLE table_22496344_1 (high_school VARCHAR, year VARCHAR)

SELECT high_school FROM table_22496344_1 WHERE year = 'Senior (RS)';


Question: pgTAP test for Functap (assertion 184).

SELECT * FROM check_test(
    isnt_normal_function( 'tap_accum', ARRAY[etype()], 'whatever' ),
    true,
    'isnt_normal_function(func, agg, desc)',
    'whatever',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Functap.


Question: PostgreSQL Rules: show example 31.

INSERT INTO shoelace_log VALUES ( new.sl_name, new.sl_avail, current_user, current_timestamp ) FROM shoelace_data new, shoelace_data old, shoelace_data shoelace_data WHERE new.sl_avail <> old.sl_avail ;

Explanation: Example from PostgreSQL documentation on Rules.


Question: What is the minimum mental health score of students who identify as Indigenous, grouped by their ethnicity?

CREATE TABLE students (student_id INT, ethnicity VARCHAR(255), mental_health_score INT); INSERT INTO students (student_id, ethnicity, mental_health_score) VALUES (1, 'Native American', 80), (2, 'Latino', 70), (3, 'Indigenous Australian', 90);

SELECT ethnicity, MIN(mental_health_score) as min_score FROM students WHERE ethnicity LIKE '%Indigenous%' GROUP BY ethnicity;


Question: Generate PostgreSQL SQL for: What was the attendance for july 18?

CREATE TABLE table_name_84 (attendance VARCHAR, date VARCHAR)

SELECT COUNT(attendance) FROM table_name_84 WHERE date = 'july 18';


Question: Generate PostgreSQL SQL for: Where has a Rules of thai boxing, and a Round of n/a, and an Opponent of everton crawford?

CREATE TABLE table_name_99 (location VARCHAR, opponent VARCHAR, rules VARCHAR, round VARCHAR)

SELECT location FROM table_name_99 WHERE rules = 'thai boxing' AND round = 'n/a' AND opponent = 'everton crawford';


Question: What is the average fare for bus routes serving low-income neighborhoods?

CREATE TABLE bus_routes (route_id INT, neighborhood VARCHAR(255), fare DECIMAL(5,2)); INSERT INTO bus_routes (route_id, neighborhood, fare) VALUES (1, 'Westwood', 1.50), (2, 'Downtown', 2.50), (3, 'Eastside', 0.75);

SELECT AVG(fare) FROM bus_routes WHERE neighborhood IN (SELECT neighborhood FROM low_income_neighborhoods);


Question: What is the average duration of peacekeeping operations for each country?

CREATE TABLE Peacekeeping_Operations (Operation_ID INT, Country_Name VARCHAR(50), Start_Date DATE, End_Date DATE); INSERT INTO Peacekeeping_Operations (Operation_ID, Country_Name, Start_Date, End_Date) VALUES (1, 'Bangladesh', '2005-01-01', '2007-12-31');

SELECT Country_Name, AVG(DATEDIFF(End_Date, Start_Date)) as Average_Duration FROM Peacekeeping_Operations GROUP BY Country_Name;


Question: Generate PostgreSQL SQL for: Who is the player when the pick is 22 and the year [A] is after 1979?

CREATE TABLE table_name_5 (player_name VARCHAR, pick VARCHAR, year_ VARCHAR, a_ VARCHAR)

SELECT player_name FROM table_name_5 WHERE pick = '22' AND year_[a_] > 1979;


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

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

SELECT count(*) FROM (select '[2]={1,7}'::int[]) AS _sub;


Question: Generate PostgreSQL SQL for: How many draft copies does the document with id 2 have?

CREATE TABLE Draft_Copies (document_id VARCHAR)

SELECT COUNT(*) FROM Draft_Copies WHERE document_id = 2;


Question: Insert records into the 'user_demographics' table

CREATE TABLE user_demographics (user_id INT, age INT, gender VARCHAR(10), occupation VARCHAR(255));

INSERT INTO user_demographics (user_id, age, gender, occupation) VALUES (1, 35, 'male', 'software engineer');


Question: What is the maximum number of sessions attended by a patient in Spain for any therapy?

CREATE TABLE therapy_attendance (id INT, patient_id INT, session_name TEXT, num_sessions INT, country TEXT);

SELECT MAX(num_sessions) FROM therapy_attendance WHERE country = 'Spain';


Question: What is the total revenue of sales in the last quarter for ethical clothing produced in factories with fair labor practices?

CREATE TABLE Factories (factory_id INT, name VARCHAR(100), location VARCHAR(100), num_workers INT, has_fair_labor BOOLEAN); CREATE TABLE Products (product_id INT, name VARCHAR(100), factory_id INT, price DECIMAL(5,2)); CREATE TABLE Sales (sale_id INT, product_id INT, quantity INT, sale_date DATE); INSERT INTO Factories VALUES (1,'Factory A','New York',200,TRUE),(2,'Factory B','Mumbai',350,FALSE),(3,'Factory C','Dhaka',500,TRUE),(4,'Factory D','São Paulo',400,FALSE); INSERT INTO Products VALUES (1,'Eco T-Shirt',1,20.00),(2,'Fair Trade Blouse',2,30.00),(3,'Sustainable Skirt',3,40.00),(4,'Organic Cotton Jeans',3,50.00); INSERT INTO Sales VALUES (1,1,10,DATE '2022-01-01'),(2,2,15,DATE '2022-02-15'),(3,3,20,DATE '2022-03-30'),(4,4,25,DATE '2022-04-15');

SELECT SUM(Products.price * Sales.quantity) FROM Factories JOIN Products ON Factories.factory_id = Products.factory_id JOIN Sales ON Products.product_id = Sales.product_id WHERE Factories.has_fair_labor = TRUE AND Sales.sale_date >= DATE '2022-01-01' AND Sales.sale_date < DATE '2022-04-01';


Question: Generate PostgreSQL SQL for: What is Player, when Pick is less than 161, and when College is "Auburn University"?

CREATE TABLE table_name_58 (player VARCHAR, pick VARCHAR, college VARCHAR)

SELECT player FROM table_name_58 WHERE pick < 161 AND college = 'auburn university';


Question: What is the average age of aircraft manufactured by Boeing?

CREATE TABLE Manufacturers (Id INT, Name VARCHAR(50)); INSERT INTO Manufacturers (Id, Name) VALUES (1, 'Boeing'), (2, 'Airbus'); CREATE TABLE Aircraft (Id INT, Name VARCHAR(50), Age INT, ManufacturerId INT); INSERT INTO Aircraft (Id, Name, Age, ManufacturerId) VALUES (1, '747', 50, 1), (2, '777', 25, 1), (3, 'A320', 10, 2), (4, 'A350', 5, 2);

SELECT AVG(Aircraft.Age) FROM Aircraft JOIN Manufacturers ON Aircraft.ManufacturerId = Manufacturers.Id WHERE Manufacturers.Name = 'Boeing';


Question: What is the maximum safety rating in the 'workplace_safety' table for workplaces with a union membership size greater than 100 in the 'labor_rights' table?

CREATE TABLE workplace_safety (safety_rating INT, workplace_id INT); CREATE TABLE labor_rights (workplace_id INT, union_membership_size INT);

SELECT MAX(workplace_safety.safety_rating) FROM workplace_safety INNER JOIN labor_rights ON workplace_safety.workplace_id = labor_rights.workplace_id WHERE labor_rights.union_membership_size > 100;


Question: Write the DDL statement from PostgreSQL regression test 'publication' (example 108).

CREATE TABLE testpub_rf_tbl2 (c text, d integer);

Explanation: DDL from PostgreSQL core regression test for Publication.


Question: Find the number of genetic research participants by project.

CREATE TABLE research_participants (id INT, project_id INT, participant_id INT, date DATE);

SELECT project_id, COUNT(DISTINCT participant_id) FROM research_participants GROUP BY project_id;


Question: What is the maximum depth of the ocean?

CREATE TABLE ocean_depth (location TEXT, depth INTEGER);


Question: Find the number of visitors who attended exhibitions in Tokyo or New York.

CREATE TABLE Visitors (id INT, city VARCHAR(20)); INSERT INTO Visitors (id, city) VALUES (1, 'Tokyo'), (2, 'Paris'), (3, 'New York'), (4, 'Berlin');

SELECT COUNT(*) FROM Visitors WHERE city IN ('Tokyo', 'New York');


Question: How many water sources were offline for more than a month in the 'WaterSources' table?

CREATE TABLE WaterSources (ID INT, SourceID INT, Status VARCHAR(10), LastOnline DATE); INSERT INTO WaterSources (ID, SourceID, Status, LastOnline) VALUES (1, 1, 'Online', '2022-01-01'); INSERT INTO WaterSources (ID, SourceID, Status, LastOnline) VALUES (2, 2, 'Offline', '2022-06-15');

SELECT COUNT(*) FROM WaterSources WHERE Status = 'Offline' AND DATEDIFF(day, LastOnline, GETDATE()) > 30;


Question: Generate PostgreSQL SQL for: Which Attendance has a Result of l 26–16?

CREATE TABLE table_name_47 (attendance VARCHAR, result VARCHAR)

SELECT attendance FROM table_name_47 WHERE result = 'l 26–16';


Question: What were the total sales of each drug in the Southeast region in Q2 2021?

CREATE TABLE drugs (drug_id INT, drug_name VARCHAR(255)); INSERT INTO drugs (drug_id, drug_name) VALUES (1, 'DrugA'), (2, 'DrugB'); CREATE TABLE sales (sale_id INT, drug_id INT, region VARCHAR(255), sales_amount DECIMAL(10, 2), quarter INT, year INT); INSERT INTO sales (sale_id, drug_id, region, sales_amount, quarter, year) VALUES (1, 1, 'Southeast', 15000, 2, 2021), (2, 2, 'Southeast', 20000, 2, 2021);

SELECT d.drug_name, SUM(s.sales_amount) as total_sales FROM drugs d JOIN sales s ON d.drug_id = s.drug_id WHERE s.region = 'Southeast' AND s.quarter = 2 AND s.year = 2021 GROUP BY d.drug_name;


Question: Which community has the highest obesity rate in the US?

CREATE TABLE Community (Name TEXT, State TEXT, ObesityRate FLOAT); INSERT INTO Community (Name, State, ObesityRate) VALUES ('Community A', 'California', 20.0); INSERT INTO Community (Name, State, ObesityRate) VALUES ('Community B', 'Texas', 25.0);

SELECT Name, ObesityRate FROM Community WHERE State = 'US' ORDER BY ObesityRate DESC LIMIT 1;


Question: What was the total number of volunteers registered in 'New York' and 'Florida'?

CREATE TABLE Volunteers (volunteer_id INT, registration_date DATE, state VARCHAR(20)); INSERT INTO Volunteers (volunteer_id, registration_date, state) VALUES (1, '2022-01-01', 'New York'), (2, '2022-01-02', 'Florida');

SELECT SUM(state = 'New York') + SUM(state = 'Florida') FROM Volunteers;


Question: What is the total investment in companies with a high ESG rating (greater than 80)?

CREATE TABLE investments (investment_id INT, company_id INT, investment_amount FLOAT); INSERT INTO investments (investment_id, company_id, investment_amount) VALUES (1, 1, 150000), (2, 2, 200000), (3, 3, 120000), (4, 5, 250000); CREATE TABLE companies (company_id INT, ESG_rating FLOAT); INSERT INTO companies (company_id, ESG_rating) VALUES (1, 85.2), (2, 78.1), (3, 88.5), (4, 65.3), (5, 82.7);

SELECT SUM(investment_amount) FROM investments JOIN companies ON investments.company_id = companies.company_id WHERE companies.ESG_rating > 80;


Question: What is the total number of customers who have made at least one transaction in the last week?

CREATE TABLE customers (customer_id INT, name VARCHAR(50), last_transaction_date DATE); INSERT INTO customers (customer_id, name, last_transaction_date) VALUES (1, 'John Doe', '2022-02-05'), (2, 'Jane Smith', NULL), (3, 'Bob Johnson', '2022-02-02');

SELECT COUNT(DISTINCT customer_id) FROM customers WHERE last_transaction_date >= DATE_SUB(CURDATE(), INTERVAL 1 WEEK);


Question: Generate PostgreSQL SQL for: How long did it take to ride when the laps were 23 and the grid of 13?

CREATE TABLE table_name_65 (time VARCHAR, laps VARCHAR, grid VARCHAR)

SELECT time FROM table_name_65 WHERE laps = 23 AND grid = 13;


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

select t1.ten, sum(x) from
  tenk1 t1 left join lateral (
    select t1.ten + t2.ten as x, t2.fivethous from tenk1 t2
  ) ss on t1.unique1 = ss.fivethous
group by t1.ten
order by t1.ten;

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

SELECT count(*) FROM (select t1.ten, sum(x) from
  tenk1 t1 left join lateral (
    select t1.ten + t2.ten as x, t2.fivethous from tenk1 t2
  ) ss on t1.unique1 = ss.fivethous
group by t1.ten
order by t1.ten) AS _sub;


Question: How many mental health parity consultations were conducted by community health workers in California?

CREATE TABLE community_health_workers (id INT, name TEXT, zip TEXT, consultations INT); INSERT INTO community_health_workers (id, name, zip, consultations) VALUES (1, 'John Doe', '90001', 30), (2, 'Jane Smith', '94117', 45);

SELECT SUM(consultations) FROM community_health_workers WHERE zip BETWEEN '90001' AND '96162';


Question: Generate PostgreSQL SQL for: Name the landesliga mitte sv türk gücü münchen

CREATE TABLE table_20181270_3 (landesliga_mitte VARCHAR, bayernliga VARCHAR)

SELECT landesliga_mitte FROM table_20181270_3 WHERE bayernliga = 'SV Türk Gücü München';


Question: What is the maximum financial capability score for individuals in India, grouped by gender?

CREATE TABLE individuals (id INT, country VARCHAR(255), gender VARCHAR(255), financial_capability_score INT);

SELECT gender, MAX(financial_capability_score) FROM individuals WHERE country = 'India' GROUP BY gender;


Question: What is the count of students who received accommodations for 'Extended Testing Time' in the 'StudentAccommodations' table?

CREATE TABLE StudentAccommodations (student_id INT, accommodation_type VARCHAR(255)); INSERT INTO StudentAccommodations (student_id, accommodation_type) VALUES (1, 'Sign Language Interpreter'), (2, 'Assistive Technology'), (3, 'Extended Testing Time'), (4, 'Extended Testing Time');

SELECT COUNT(*) FROM StudentAccommodations WHERE accommodation_type = 'Extended Testing Time';


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

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


Question: Generate PostgreSQL SQL for: Where was the game held that was played on 2002-03-07?

CREATE TABLE table_name_36 (venue VARCHAR, date VARCHAR)

SELECT venue FROM table_name_36 WHERE date = '2002-03-07';


Question: Identify unique authors who have written for 'The Hindu' and 'NDTV' in May 2021.

CREATE TABLE hindu (author_id INT, author_name VARCHAR(50), article_date DATE); INSERT INTO hindu (author_id, author_name, article_date) VALUES (1, 'Rajesh Patel', '2021-05-01'), (2, 'Priya Gupta', '2021-05-02'); CREATE TABLE ndtv (author_id INT, author_name VARCHAR(50), article_date DATE); INSERT INTO ndtv (author_id, author_name, article_date) VALUES (3, 'Meera Kapoor', '2021-05-01'), (4, 'Rajesh Patel', '2021-05-03');

SELECT author_name FROM hindu WHERE article_date BETWEEN '2021-05-01' AND '2021-05-31' INTERSECT SELECT author_name FROM ndtv WHERE article_date BETWEEN '2021-05-01' AND '2021-05-31';


Question: Generate PostgreSQL SQL for: what is the react when the country is sweden and the lane is higher than 6?

CREATE TABLE table_name_65 (react INTEGER, country VARCHAR, lane VARCHAR)

SELECT SUM(react) FROM table_name_65 WHERE country = 'sweden' AND lane > 6;


Question: Which vessels have been inspected in the last month?

CREATE TABLE Vessel (vessel_id INT, name VARCHAR(255), type VARCHAR(255), max_speed DECIMAL(5,2)); CREATE TABLE Inspection (inspection_id INT, vessel_id INT, inspection_time TIMESTAMP); INSERT INTO Vessel (vessel_id, name, type, max_speed) VALUES (1, 'Test Vessel 1', 'Cargo', 20.5), (2, 'Test Vessel 2', 'Tanker', 15.2); INSERT INTO Inspection (inspection_id, vessel_id, inspection_time) VALUES (1, 1, '2022-01-01 12:00:00'), (2, 2, '2022-01-15 10:00:00'), (3, 1, '2022-02-01 09:00:00');

SELECT v.vessel_id, v.name FROM Vessel v INNER JOIN Inspection i ON v.vessel_id = i.vessel_id WHERE i.inspection_time >= NOW() - INTERVAL '1 month';


Question: What is the minimum cargo weight handled by port 'Busan' and 'Incheon'?

CREATE TABLE ports (port_id INT, port_name VARCHAR(255)); INSERT INTO ports (port_id, port_name) VALUES (1, 'Busan'), (2, 'Incheon'), (3, 'Daegu'); CREATE TABLE cargo (cargo_id INT, port_id INT, weight FLOAT); INSERT INTO cargo (cargo_id, port_id, weight) VALUES (1, 1, 1000), (2, 1, 1500), (3, 2, 800), (4, 3, 1200);

SELECT MIN(weight) FROM cargo WHERE port_name IN ('Busan', 'Incheon');


Question: List all unique medical conditions of astronauts from Brazil.

CREATE TABLE AstronautMedical (id INT, astronaut_id INT, nationality VARCHAR(50), medical_condition VARCHAR(50)); INSERT INTO AstronautMedical (id, astronaut_id, nationality, medical_condition) VALUES (1, 121, 'Brazil', 'Hypercalcemia'); INSERT INTO AstronautMedical (id, astronaut_id, nationality, medical_condition) VALUES (2, 122, 'Brazil', 'Urinary Tract Infection'); INSERT INTO AstronautMedical (id, astronaut_id, nationality, medical_condition) VALUES (3, 123, 'Brazil', 'Nausea');

SELECT DISTINCT medical_condition FROM AstronautMedical WHERE nationality = 'Brazil';


Question: What is the total investment in economic diversification projects in Indonesia, Malaysia, and the Philippines, including only manufacturing and tourism projects?

CREATE TABLE eco_diversification (id INT, name TEXT, location TEXT, investment FLOAT, project_type TEXT); INSERT INTO eco_diversification (id, name, location, investment, project_type) VALUES (1, 'Renewable Energy', 'Indonesia', 700000.00, 'Energy'), (2, 'Tourism Infrastructure', 'Malaysia', 600000.00, 'Tourism'), (3, 'Manufacturing Zone', 'Philippines', 800000.00, 'Manufacturing'), (4, 'Mining Concession', 'Indonesia', 900000.00, 'Mining');

SELECT SUM(investment) FROM eco_diversification WHERE location IN ('Indonesia', 'Malaysia', 'Philippines') AND project_type IN ('Manufacturing', 'Tourism');


Question: Show an example of PostgreSQL SELECT (example 10).

SELECT * FROM distributors ORDER BY name; SELECT * FROM distributors ORDER BY 2; did | name -----+------------------ 109 | 20th Century Fox 110 | Bavaria Atelier 101 | British Lion 107 | Columbia 102 | Jean Luc Godard 113 | Luso films 104 | Mosfilm 103 | Paramount 106 | Toho 105 | United Artists 111 | Walt Disney 112 | Warner Bros. 108 | Westward;

Explanation: PostgreSQL SELECT command.


Question: Generate PostgreSQL SQL for: In which colleges is the NFL Team New York Giants and with the position defensive back?

CREATE TABLE table_2508633_11 (college VARCHAR, nfl_team VARCHAR, position VARCHAR)

SELECT college FROM table_2508633_11 WHERE nfl_team = 'New York Giants' AND position = 'Defensive back';


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

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


Question: Generate PostgreSQL SQL for: What is the production number directed by Robert McKimson in series mm titled People Are Bunny?

CREATE TABLE table_name_18 (production_number INTEGER, title VARCHAR, director VARCHAR, series VARCHAR)

SELECT SUM(production_number) FROM table_name_18 WHERE director = 'robert mckimson' AND series = 'mm' AND title = 'people are bunny';


Question: What is the total number of streams by country?

CREATE TABLE Countries (CountryID int, CountryName varchar(255)); INSERT INTO Countries (CountryID, CountryName) VALUES (1, 'USA'), (2, 'UK'), (3, 'France'); CREATE TABLE StreamsByCountry (StreamID int, CountryID int, StreamCount int); INSERT INTO StreamsByCountry (StreamID, CountryID, StreamCount) VALUES (1, 1, 1000), (2, 2, 2000), (3, 1, 1500);

SELECT Countries.CountryName, SUM(StreamsByCountry.StreamCount) as TotalStreams FROM Countries INNER JOIN StreamsByCountry ON Countries.CountryID = StreamsByCountry.CountryID GROUP BY Countries.CountryName;


Question: Update the ocean_name for species_id 1 to 'Indian Ocean'.

CREATE TABLE marine_species (species_id INT, species_name VARCHAR(50), ocean_name VARCHAR(50));

UPDATE marine_species SET ocean_name = 'Indian Ocean' WHERE species_id = 1;


Question: Generate PostgreSQL SQL for: What is the average Position with less than 57 against and the team is Juventus?

CREATE TABLE table_name_19 (position INTEGER, against VARCHAR, team VARCHAR)

SELECT AVG(position) FROM table_name_19 WHERE against < 57 AND team = 'juventus';


Question: What is the total number of citizen feedback records for public services in the city of Los Angeles?

CREATE TABLE citizen_feedback (city VARCHAR(20), service VARCHAR(20)); INSERT INTO citizen_feedback (city, service) VALUES ('Los Angeles', 'public transportation'); INSERT INTO citizen_feedback (city, service) VALUES ('Los Angeles', 'public transportation'); INSERT INTO citizen_feedback (city, service) VALUES ('Los Angeles', 'public parks'); INSERT INTO citizen_feedback (city, service) VALUES ('San Diego', 'public libraries');

SELECT COUNT(*) FROM citizen_feedback WHERE city = 'Los Angeles';


Question: What is the total number of crimes committed in each city in the last 3 months?

CREATE TABLE cities (id INT, name TEXT);CREATE TABLE crimes (id INT, city_id INT, date DATE);

SELECT c.name, COUNT(cr.id) FROM cities c JOIN crimes cr ON c.id = cr.city_id WHERE cr.date >= DATEADD(month, -3, GETDATE()) GROUP BY c.id;


Question: Generate PostgreSQL SQL for: If the national trophy/rookie is Simone Iaquinta, what is the season total number?

CREATE TABLE table_25563779_4 (season VARCHAR, national_trophy_rookie VARCHAR)

SELECT COUNT(season) FROM table_25563779_4 WHERE national_trophy_rookie = 'Simone Iaquinta';


Question: Generate PostgreSQL SQL for: Who was the candidate when the result - % was 0.4%?

CREATE TABLE table_25818630_2 (candidate VARCHAR, result____percentage VARCHAR)

SELECT candidate FROM table_25818630_2 WHERE result____percentage = '0.4%';


Question: Generate PostgreSQL SQL for: Which name has a Kanji of 朧?

CREATE TABLE table_name_77 (name VARCHAR, kanji VARCHAR)

SELECT name FROM table_name_77 WHERE kanji = '朧';


Question: Generate PostgreSQL SQL for: What's the latest episode in a season where the U.S. viewers totaled 14.37 million?

CREATE TABLE table_10842344_1 (no_in_season INTEGER, us_viewers__millions_ VARCHAR)

SELECT MAX(no_in_season) FROM table_10842344_1 WHERE us_viewers__millions_ = '14.37';


Question: What is the total number of professional development courses completed by teachers in each school, grouped by course type?

CREATE TABLE teacher_pd (teacher_id INT, school_id INT, course_id INT, course_type VARCHAR(255)); CREATE TABLE courses (course_id INT, course_name VARCHAR(255), course_type VARCHAR(255)); CREATE TABLE schools (school_id INT, school_name VARCHAR(255));

SELECT s.school_name, c.course_type, COUNT(DISTINCT t.teacher_id, t.course_id) as num_courses FROM teacher_pd t INNER JOIN schools s ON t.school_id = s.school_id INNER JOIN courses c ON t.course_id = c.course_id GROUP BY s.school_name, c.course_type;


Question: Calculate the average fuel consumption per hour for the vessel 'Blue Whale' in the 'Tankers' fleet in the past week.

CREATE TABLE Vessels (id INT, name VARCHAR(255)); INSERT INTO Vessels (id, name) VALUES (1, 'Blue Whale'); CREATE TABLE FuelConsumption (vessel_id INT, fuel_consumption INT, timestamp TIMESTAMP); INSERT INTO FuelConsumption (vessel_id, fuel_consumption, timestamp) VALUES (1, 500, '2022-07-01 10:00:00'), (1, 800, '2022-07-01 22:00:00');

SELECT AVG(fuel_consumption / DATEDIFF(HOUR, LAG(timestamp) OVER (PARTITION BY vessel_id ORDER BY timestamp), timestamp)) as avg_fuel_consumption_per_hour FROM FuelConsumption WHERE vessel_id = 1 AND timestamp >= DATEADD(week, -1, GETDATE());


Question: Generate PostgreSQL SQL for: Which Date has a Catalog of 887 195-2, and a Format of cd maxi?

CREATE TABLE table_name_63 (date VARCHAR, catalog VARCHAR, format VARCHAR)

SELECT date FROM table_name_63 WHERE catalog = '887 195-2' AND format = 'cd maxi';


Question: Generate PostgreSQL SQL for: When 55 is the tries for what is the lost?

CREATE TABLE table_17941032_1 (lost VARCHAR, tries_for VARCHAR)

SELECT lost FROM table_17941032_1 WHERE tries_for = '55';


Question: Generate PostgreSQL SQL for: What does American have if Australia has əʉ?

CREATE TABLE table_name_65 (american VARCHAR, australian VARCHAR)

SELECT american FROM table_name_65 WHERE australian = 'əʉ';


Question: Write the DDL statement from PostgreSQL regression test 'copy' (example 43).

create table parted_copytest_a1 (c text, b int, a int);

Explanation: DDL from PostgreSQL core regression test for Copy.


Question: Generate PostgreSQL SQL for: What was the finish for England?

CREATE TABLE table_name_76 (finish VARCHAR, country VARCHAR)

SELECT finish FROM table_name_76 WHERE country = 'england';


Question: List all public transportation routes with more than 50% hybrid bus usage in London.

CREATE TABLE public_transportation (route_id INT, route_name TEXT, vehicle_type TEXT, is_hybrid BOOLEAN, passengers INT);

SELECT route_name FROM public_transportation WHERE vehicle_type = 'Bus' AND is_hybrid = TRUE GROUP BY route_name HAVING COUNT(*) FILTER (WHERE is_hybrid = TRUE) / COUNT(*) > 0.5 AND route_name LIKE 'London%';


Question: Generate PostgreSQL SQL for: Where is Adam Gilchrist from?

CREATE TABLE table_11303072_9 (nationality VARCHAR, player VARCHAR)

SELECT nationality FROM table_11303072_9 WHERE player = 'Adam Gilchrist';


Question: What are the total earnings of each eSports team in the last year?

CREATE TABLE eSportsTeams (TeamID INT, TeamName VARCHAR(100), Earnings FLOAT, LastUpdated DATE); INSERT INTO eSportsTeams (TeamID, TeamName, Earnings, LastUpdated) VALUES (1, 'TeamA', 1000000, '2020-01-01'), (2, 'TeamB', 1200000, '2020-02-01'), (3, 'TeamC', 1100000, '2020-03-01');

SELECT TeamName, SUM(Earnings) as TotalEarnings FROM eSportsTeams WHERE LastUpdated >= DATEADD(year, -1, GETDATE()) GROUP BY TeamName;


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

CREATE FUNCTION nested_call_three(a text) RETURNS text
	AS
'return a'
	LANGUAGE plpython3u ;

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


Question: What is the total number of defense diplomacy events held in 'canada' between 2019 and 2021?

CREATE TABLE defense_diplomacy (country VARCHAR(50), year INT, events INT); INSERT INTO defense_diplomacy (country, year, events) VALUES ('Canada', 2019, 15), ('Canada', 2020, 12), ('Canada', 2021, 18);

SELECT country, SUM(events) as total_events FROM defense_diplomacy WHERE country = 'Canada' AND year BETWEEN 2019 AND 2021 GROUP BY country;


Question: Generate PostgreSQL SQL for: What is the Akira when Prince Devitt is Devitt (7:20)?

CREATE TABLE table_name_99 (akira VARCHAR, prince_devitt VARCHAR)

SELECT akira FROM table_name_99 WHERE prince_devitt = 'devitt (7:20)';


Question: List the faculty members who have not published any papers, in alphabetical order.

CREATE TABLE faculties (faculty_id INT, name VARCHAR(255), dept_id INT, num_publications INT);

SELECT name FROM faculties WHERE num_publications = 0 ORDER BY name ASC;


Question: What is the average revenue per concert by country?

CREATE TABLE concerts (id INT, artist_id INT, city VARCHAR(50), country VARCHAR(50), revenue FLOAT); INSERT INTO concerts (id, artist_id, city, country, revenue) VALUES (1, 1, 'Los Angeles', 'USA', 500000), (2, 1, 'New York', 'USA', 700000), (3, 2, 'Seoul', 'South Korea', 800000), (4, 2, 'Tokyo', 'Japan', 900000), (5, 3, 'Paris', 'France', 1000000), (6, 4, 'Osaka', 'Japan', 850000), (7, 1, 'London', 'UK', 600000);

SELECT country, AVG(revenue) as avg_revenue FROM concerts GROUP BY country;


Question: Generate PostgreSQL SQL for: When the Vancouver Canucks were visiting, what was the record when the score was 4-2?

CREATE TABLE table_name_6 (record VARCHAR, score VARCHAR, visitor VARCHAR)

SELECT record FROM table_name_6 WHERE score = '4-2' AND visitor = 'vancouver canucks';


Question: Generate PostgreSQL SQL for: Which English has Dutch of tong?

CREATE TABLE table_name_26 (english VARCHAR, dutch VARCHAR)

SELECT english FROM table_name_26 WHERE dutch = 'tong';


Question: Add a new record to the historical_sites table

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

INSERT INTO historical_sites (id, name, country, type) VALUES (1, 'Machu Picchu', 'Peru', 'cultural_heritage');


Question: Generate PostgreSQL SQL for: What is the result when team 1 is ICL Pakistan?

CREATE TABLE table_17103566_1 (result VARCHAR, team_1 VARCHAR)

SELECT result FROM table_17103566_1 WHERE team_1 = 'ICL Pakistan';


Question: Generate PostgreSQL SQL for: Who won the mens singles in 2009?

CREATE TABLE table_12204717_1 (mens_singles VARCHAR, year VARCHAR)

SELECT mens_singles FROM table_12204717_1 WHERE year = 2009;


Question: Insert a new record into the "resources" table for a new gold mine in "Peru" with ID 901 and reserves of 5000 tons

CREATE TABLE resources (id INT, mine_type VARCHAR(50), country VARCHAR(50), reserve_tons INT);

INSERT INTO resources (id, mine_type, country, reserve_tons) VALUES (901, 'gold', 'Peru', 5000);


Question: What's the total transaction volume for digital assets in the last month?

CREATE TABLE digital_assets (id INT, name VARCHAR(255), transaction_volume DECIMAL(10, 2)); INSERT INTO digital_assets (id, name, transaction_volume) VALUES (1, 'Asset 1', 1000.50), (2, 'Asset 2', 1500.25), (3, 'Asset 3', 2000.00); CREATE TABLE transactions (id INT, digital_asset_id INT, transaction_date DATE); INSERT INTO transactions (id, digital_asset_id, transaction_date) VALUES (1, 1, '2022-01-01'), (2, 2, '2022-01-05'), (3, 3, '2022-01-10');

SELECT SUM(transaction_volume) FROM digital_assets JOIN transactions ON digital_assets.id = transactions.digital_asset_id WHERE transaction_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH);


Question: PostgreSQL regression test 'regproc': Write the SELECT query (example 13).

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

SELECT count(*) FROM (SELECT to_regclass('pg_class')) AS _sub;


Question: What is the average age of patients who received therapy from counselors named "James" or "Michelle"?

CREATE TABLE counselors (counselor_id INT, name TEXT, age INT); INSERT INTO counselors (counselor_id, name, age) VALUES (1, 'James', 35), (2, 'Michelle', 40); CREATE TABLE patients (patient_id INT, counselor_id INT, age INT); INSERT INTO patients (patient_id, counselor_id, age) VALUES (1, 1, 25), (2, 1, 30), (3, 2, 45), (4, 2, 50);

SELECT AVG(patients.age) FROM patients JOIN counselors ON patients.counselor_id = counselors.counselor_id WHERE counselors.name IN ('James', 'Michelle');


Question: What is the average distance of space debris generated by NASA from the Earth's center?

CREATE TABLE space_debris (id INT, name VARCHAR(50), type VARCHAR(50), source VARCHAR(50), location POINT);

SELECT AVG(DISTANCE(location, POINT(0, 0))) as average_distance FROM space_debris WHERE source = 'NASA';


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

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

SELECT count(*) FROM (select '$ ? (@.a < +.1e-1)'::jsonpath) AS _sub;


Question: List the virtual tours that are available in Spanish and have a cultural heritage focus, along with their average user rating.

CREATE TABLE virtual_tour (id INT PRIMARY KEY, name VARCHAR(255), language VARCHAR(255), focus VARCHAR(255), user_rating DECIMAL(3,2)); INSERT INTO virtual_tour (id, name, language, focus, user_rating) VALUES (1, 'Tour of the Alhambra', 'Spanish', 'Cultural Heritage', 4.5);

SELECT vt.name, vt.language, vt.focus, AVG(vt.user_rating) as avg_rating FROM virtual_tour vt WHERE vt.language = 'Spanish' AND vt.focus = 'Cultural Heritage' GROUP BY vt.name, vt.language, vt.focus;


Question: Who are the volunteers that signed up in January and June of 2022?

CREATE TABLE volunteers (volunteer_id INT, signup_date DATE); INSERT INTO volunteers (volunteer_id, signup_date) VALUES (1, '2022-01-05'), (2, '2022-03-30'), (3, '2022-04-15'), (4, '2022-06-10');

SELECT volunteer_id, signup_date FROM volunteers WHERE (MONTH(signup_date) = 1 AND YEAR(signup_date) = 2022) OR (MONTH(signup_date) = 6 AND YEAR(signup_date) = 2022);


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

SELECT count(*) FROM (SELECT to_timestamp('2016-02-29 15:50:55', 'YYYY-MM-DD HH24:MI:SS');  -- ok
SELECT to_timestamp('2015-02-29 15:50:55', 'YYYY-MM-DD HH24:MI:SS')) AS _sub;


Question: Generate PostgreSQL SQL for: What is the Date of Week 2?

CREATE TABLE table_name_47 (date VARCHAR, week VARCHAR)

SELECT date FROM table_name_47 WHERE week = 2;


Question: Generate PostgreSQL SQL for: who is the constructor when the tyre is d, the engine is talbot 23cv 4.5 l6, the chassis is talbot-lago t26c and the entrant is ecurie belge?

CREATE TABLE table_name_75 (constructor VARCHAR, entrant VARCHAR, chassis VARCHAR, tyre VARCHAR, engine VARCHAR)

SELECT constructor FROM table_name_75 WHERE tyre = 'd' AND engine = 'talbot 23cv 4.5 l6' AND chassis = 'talbot-lago t26c' AND entrant = 'ecurie belge';


Question: How many 'Eco-Friendly' garments were sold in 'Australia' retail stores in Q1 of 2022?

CREATE TABLE SalesStore (id INT PRIMARY KEY, store_name VARCHAR(50), location VARCHAR(50), garment_type VARCHAR(50), is_eco_friendly BOOLEAN, quantity INT, sale_date DATE); INSERT INTO SalesStore (id, store_name, location, garment_type, is_eco_friendly, quantity, sale_date) VALUES (1, 'Store D', 'Australia', 'Eco-Friendly T-Shirt', true, 30, '2022-01-15');

SELECT SUM(quantity) as total_quantity FROM SalesStore WHERE location = 'Australia' AND is_eco_friendly = true AND sale_date BETWEEN '2022-01-01' AND '2022-03-31';


Question: What is the number of cases with a female judge and male defendant?

CREATE TABLE cases (id INT, judge_gender VARCHAR(6), defendant_gender VARCHAR(6)); INSERT INTO cases (id, judge_gender, defendant_gender) VALUES (1, 'Female', 'Male'), (2, 'Male', 'Female'), (3, 'Female', 'Male');

SELECT COUNT(*) FROM cases WHERE judge_gender = 'Female' AND defendant_gender = 'Male';


Question: Generate PostgreSQL SQL for: What is the highest swimsuit a contestant from Kansas with an average larger than 8.48, an interview higher than 8.58, and an evening gown higher than 8.82 has?

CREATE TABLE table_name_69 (swimsuit INTEGER, state VARCHAR, evening_gown VARCHAR, average VARCHAR, interview VARCHAR)

SELECT MAX(swimsuit) FROM table_name_69 WHERE average > 8.48 AND interview > 8.58 AND evening_gown > 8.82 AND state = 'kansas';


Question: Generate PostgreSQL SQL for: Find the name of all the cities and states.

CREATE TABLE addresses (town_city VARCHAR, state_province_county VARCHAR)

SELECT town_city FROM addresses UNION SELECT state_province_county FROM addresses;


Question: Generate PostgreSQL SQL for: What is the enrollment at delaware valley college?

CREATE TABLE table_261906_2 (joined_mac INTEGER, institution VARCHAR)

SELECT MAX(joined_mac) FROM table_261906_2 WHERE institution = 'Delaware Valley College';


Question: Generate PostgreSQL SQL for: What is the area of Tuscany?

CREATE TABLE table_14532_1 (area__km²_ INTEGER, region VARCHAR)

SELECT MAX(area__km²_) FROM table_14532_1 WHERE region = 'Tuscany';


Question: What was the waste generation in Bangkok in 2019?

CREATE TABLE waste_generation_bangkok (year INT, total_waste INT); INSERT INTO waste_generation_bangkok (year, total_waste) VALUES (2018, 150000), (2019, 170000), (2020, 185000);

SELECT total_waste FROM waste_generation_bangkok WHERE year = 2019;


Question: Which destinations in Canada have the highest increase in visitors from 2019 to 2022?

CREATE TABLE canada_tourism (destination VARCHAR(50), year INT, visitors INT); INSERT INTO canada_tourism (destination, year, visitors) VALUES ('Banff', 2019, 500000), ('Banff', 2022, 700000), ('Whistler', 2019, 300000), ('Whistler', 2022, 500000);

SELECT destination, MAX(visitors) - MIN(visitors) AS increase FROM canada_tourism WHERE year IN (2019, 2022) GROUP BY destination ORDER BY increase DESC;


Question: Generate PostgreSQL SQL for: Which position from the Cherkassy Monkeys' club was born after 1978?

CREATE TABLE table_name_10 (position VARCHAR, year_born VARCHAR, current_club VARCHAR)

SELECT position FROM table_name_10 WHERE year_born > 1978 AND current_club = 'cherkassy monkeys';


Question: Delete all records from the 'readers' table where 'country' is 'United States'

CREATE TABLE readers (id INT, name VARCHAR(50), country VARCHAR(50)); INSERT INTO readers (id, name, country) VALUES (1, 'Alice Johnson', 'United States'); INSERT INTO readers (id, name, country) VALUES (2, 'Bob Williams', 'Canada');

DELETE FROM readers WHERE country = 'United States';


Question: What is the average number of fouls committed by players from Argentina in the 'World Cup'?

CREATE TABLE players (player_id INT, name TEXT, country TEXT); INSERT INTO players (player_id, name, country) VALUES (1, 'Messi', 'Argentina'), (2, 'Di Maria', 'Argentina'), (3, 'Kane', 'England'); CREATE TABLE fouls (foul_id INT, player_id INT, fouls INT); INSERT INTO fouls (foul_id, player_id, fouls) VALUES (1, 1, 2), (2, 1, 3), (3, 2, 1), (4, 3, 5); CREATE TABLE games (game_id INT, player_id INT, tournament TEXT); INSERT INTO games (game_id, player_id, tournament) VALUES (1, 1, 'World Cup'), (2, 1, 'World Cup'), (3, 2, 'World Cup'), (4, 3, 'World Cup');

SELECT AVG(fouls) FROM fouls JOIN games ON fouls.player_id = games.player_id JOIN players ON fouls.player_id = players.player_id WHERE players.country = 'Argentina' AND games.tournament = 'World Cup';


Question: pgTAP test for Index (assertion 75).

SELECT * FROM check_test(
    index_is_primary( 'idx_baz' ),
    false,
    'index_is_primary() fail index only',
    'Index idx_baz should be on a primary key',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Index.


Question: How many local businesses in Spain have benefited from sustainable tourism initiatives?

CREATE TABLE local_businesses (business_id INT, business_name TEXT, country TEXT, sustainable_initiative BOOLEAN); INSERT INTO local_businesses (business_id, business_name, country, sustainable_initiative) VALUES (1, 'La Ribera Market', 'Spain', TRUE); INSERT INTO local_businesses (business_id, business_name, country, sustainable_initiative) VALUES (2, 'Gothic Quarter Shops', 'Spain', TRUE); INSERT INTO local_businesses (business_id, business_name, country, sustainable_initiative) VALUES (3, 'Barceloneta Fish Market', 'Spain', FALSE);

SELECT COUNT(*) FROM local_businesses WHERE country = 'Spain' AND sustainable_initiative = TRUE;


Question: Generate PostgreSQL SQL for: What are the goals for 8/4/04?

CREATE TABLE table_name_70 (goals VARCHAR, date VARCHAR)

SELECT goals FROM table_name_70 WHERE date = '8/4/04';


Question: What is the total amount of donations made by donors from Palestine in the year 2019?

CREATE TABLE donations (id INT, donor_id INT, donor_country TEXT, donation_date DATE, donation_amount DECIMAL); INSERT INTO donations (id, donor_id, donor_country, donation_date, donation_amount) VALUES (1, 1, 'Palestine', '2019-01-01', 50.00), (2, 2, 'Palestine', '2019-06-01', 100.00), (3, 3, 'Palestine', '2019-12-31', 25.00);

SELECT SUM(donation_amount) FROM donations WHERE donor_country = 'Palestine' AND YEAR(donation_date) = 2019;


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

Explanation: DDL from PostgreSQL core regression test for Rowsecurity.


Question: What is the average product price for each category in the 'sustainable_products' table?

CREATE TABLE sustainable_products (product_id INT, category VARCHAR(255), price DECIMAL(10,2));

SELECT category, AVG(price) FROM sustainable_products GROUP BY category;


Question: Generate PostgreSQL SQL for: What is every Gregorian month when the season in Tamil is இளவேனில்?

CREATE TABLE table_1740431_3 (gregorian_months VARCHAR, season_in_tamil VARCHAR)

SELECT gregorian_months FROM table_1740431_3 WHERE season_in_tamil = 'இளவேனில்';


Question: Generate PostgreSQL SQL for: What's the population with a code more than 90902 and an area less than 1,335.47?

CREATE TABLE table_name_19 (population INTEGER, code VARCHAR, area__km_2__ VARCHAR)

SELECT MIN(population) FROM table_name_19 WHERE code > 90902 AND area__km_2__ < 1 OFFSET 335.47;


Question: Display the total quantity of sustainable materials used by ethical fashion brands in the last quarter.

CREATE TABLE Dates (date_id INT, date DATE); INSERT INTO Dates (date_id, date) VALUES (1, '2022-01-01'), (2, '2022-04-01'), (3, '2022-07-01'), (4, '2022-10-01'); CREATE TABLE SustainableBrands (brand_id INT, material_id INT, quantity INT, date_id INT); INSERT INTO SustainableBrands (brand_id, material_id, quantity, date_id) VALUES (1, 1, 500, 4), (1, 2, 300, 4), (2, 3, 700, 4), (3, 1, 400, 4);

SELECT SUM(quantity) FROM SustainableBrands INNER JOIN Dates ON SustainableBrands.date_id = Dates.date_id WHERE date >= DATE_SUB(CURRENT_DATE, INTERVAL 3 MONTH) AND EXISTS (SELECT * FROM Brands WHERE Brands.brand_id = SustainableBrands.brand_id AND location = 'Europe');


Question: Generate PostgreSQL SQL for: Who is the champion of the 1994 season?

CREATE TABLE table_2527617_1 (champion VARCHAR, season VARCHAR)

SELECT champion FROM table_2527617_1 WHERE season = 1994;


Question: Generate PostgreSQL SQL for: Which Country has a Score of 70-68-70-68=276?

CREATE TABLE table_name_43 (country VARCHAR, score VARCHAR)

SELECT country FROM table_name_43 WHERE score = 70 - 68 - 70 - 68 = 276;


Question: Generate PostgreSQL SQL for: What is the last 10 meetings that have 11/26/1988 as the lasr meeting?

CREATE TABLE table_name_32 (last_10_meetings VARCHAR, last_meeting VARCHAR)

SELECT last_10_meetings FROM table_name_32 WHERE last_meeting = '11/26/1988';


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

ALTER EXTENSION pgtap ADD FUNCTION _ikeys( NAME, NAME, NAME);

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


Question: Generate PostgreSQL SQL for: List ids for all student who are on scholarship.

CREATE TABLE Sportsinfo (StuID VARCHAR, onscholarship VARCHAR)

SELECT StuID FROM Sportsinfo WHERE onscholarship = 'Y';


Question: List the total number of pollution control initiatives implemented in the Atlantic and Arctic regions.

CREATE TABLE PollutionControl (id INT, initiative VARCHAR(50), region VARCHAR(20)); INSERT INTO PollutionControl (id, initiative, region) VALUES (1, 'Ocean Cleanup', 'Arctic'), (2, 'Plastic Reduction', 'Atlantic'), (3, 'Carbon Capture', 'Global');

SELECT region, COUNT(*) as total_initiatives FROM PollutionControl WHERE region IN ('Atlantic', 'Arctic') GROUP BY region;


Question: Generate PostgreSQL SQL for: What was the score of the 3-0 Win result?

CREATE TABLE table_name_91 (score VARCHAR, result VARCHAR)

SELECT score FROM table_name_91 WHERE result = '3-0 win';


Question: Generate PostgreSQL SQL for: The station located in Albuquerque has been owned since what year?

CREATE TABLE table_11147852_1 (owned_since VARCHAR, city_of_license_market VARCHAR)

SELECT owned_since FROM table_11147852_1 WHERE city_of_license_market = 'Albuquerque';


Question: What is the average salary by department for employees who have been trained?

CREATE TABLE Employees (EmployeeID INT, Department VARCHAR(20), Salary FLOAT, Trained BOOLEAN); INSERT INTO Employees (EmployeeID, Department, Salary, Trained) VALUES (1, 'IT', 75000.0, 1), (2, 'HR', 65000.0, 0), (3, 'IT', 80000.0, 1);

SELECT Department, AVG(Salary) FROM Employees WHERE Trained = 1 GROUP BY Department;


Question: List all tables and views in the 'telecom' schema

CREATE SCHEMA telecom; CREATE TABLE mobile_subscribers (id INT, name TEXT, data_plan TEXT); CREATE VIEW broadband_subscribers AS SELECT * FROM subscribers WHERE type = 'broadband'; CREATE TABLE network_investments (year INT, amount FLOAT); CREATE TABLE compliance_reports (quarter INT, filed BOOLEAN);

SELECT * FROM information_schema.tables WHERE table_schema = 'telecom';


Question: Generate PostgreSQL SQL for: What was the score when they played the Boston Patriots?

CREATE TABLE table_name_91 (result VARCHAR, opponent VARCHAR)

SELECT result FROM table_name_91 WHERE opponent = 'boston patriots';


Question: List the rural infrastructure projects and their budgets for 'rural_area_1' from the 'rural_infrastructure' and 'community_development' tables

CREATE TABLE rural_infrastructure (project_id INT, project_type VARCHAR(50), budget INT, area_id INT); CREATE TABLE community_development (area_id INT, area_name VARCHAR(50));

SELECT r.project_type, r.budget FROM rural_infrastructure r INNER JOIN community_development c ON r.area_id = c.area_id WHERE c.area_name = 'rural_area_1';


Question: Show the total installed capacity of renewable energy projects for each location

CREATE TABLE renewable_energy ( id INT PRIMARY KEY, location VARCHAR(255), project_name VARCHAR(255), installed_capacity INT ); INSERT INTO renewable_energy (id, location, project_name, installed_capacity) VALUES (1, 'Germany', 'Solarpark Finow Tower', 45000); INSERT INTO renewable_energy (id, location, project_name, installed_capacity) VALUES (2, 'France', 'La Plaine Wind Farm', 60000);

SELECT location, SUM(installed_capacity) FROM renewable_energy GROUP BY location;


Question: List all countries with their respective number of podcasts and the total duration of those podcasts.

CREATE TABLE podcasts (id INT, name VARCHAR(255), country VARCHAR(255), duration INT); INSERT INTO podcasts (id, name, country, duration) VALUES (1, 'Podcast1', 'USA', 100), (2, 'Podcast2', 'UK', 200);

SELECT country, COUNT(*) as num_podcasts, SUM(duration) as total_duration FROM podcasts GROUP BY country;


Question: Generate PostgreSQL SQL for: When was the WC 1974 Qualifying game?

CREATE TABLE table_name_94 (date VARCHAR, type_of_game VARCHAR)

SELECT date FROM table_name_94 WHERE type_of_game = 'wc 1974 qualifying';


Question: PL/pgSQL test: Plpython Subtransaction (example 31).

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


Question: List all volunteers who worked on 'Food Security' program in 'Asia'

CREATE TABLE Volunteers (VolunteerID INT, VolunteerName TEXT, Country TEXT); INSERT INTO Volunteers (VolunteerID, VolunteerName, Country) VALUES (1, 'Anna Lee', 'Korea'); INSERT INTO Volunteers (VolunteerID, VolunteerName, Country) VALUES (2, 'Ravi Patel', 'India'); CREATE TABLE VolunteerHours (VolunteerID INT, Program TEXT, Hours DECIMAL); INSERT INTO VolunteerHours (VolunteerID, Program, Hours) VALUES (1, 'Food Security', 20); INSERT INTO VolunteerHours (VolunteerID, Program, Hours) VALUES (2, 'Food Security', 30);

SELECT Volunteers.VolunteerName FROM Volunteers INNER JOIN VolunteerHours ON Volunteers.VolunteerID = VolunteerHours.VolunteerID WHERE VolunteerHours.Program = 'Food Security' AND Volunteers.Country = 'Asia';


Question: Generate PostgreSQL SQL for: what are all the positions of players who's hometown is concord, california

CREATE TABLE table_11677691_12 (position VARCHAR, hometown VARCHAR)

SELECT position FROM table_11677691_12 WHERE hometown = 'Concord, California';


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

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


Question: Identify users who have posted more than 50 posts in the 'social_media' table.

CREATE TABLE social_media (user_id INT, posts_count INT);

SELECT user_id FROM social_media WHERE posts_count > 50;


Question: Generate PostgreSQL SQL for: How many points did the Falcons score when the record was 4-4?

CREATE TABLE table_16710971_2 (falcons_points VARCHAR, record VARCHAR)

SELECT falcons_points FROM table_16710971_2 WHERE record = '4-4';


Question: How many countries in Europe have been promoting sustainable tourism since 2019?

CREATE TABLE Sustainable_Practices ( id INT PRIMARY KEY, country_id INT, certification_date DATE, FOREIGN KEY (country_id) REFERENCES Countries(id) ); INSERT INTO Sustainable_Practices (id, country_id, certification_date) VALUES (1, 7, '2019-07-01'); INSERT INTO Sustainable_Practices (id, country_id, certification_date) VALUES (2, 8, '2020-03-01');

SELECT COUNT(DISTINCT c.id) as country_count FROM Countries c INNER JOIN Sustainable_Practices sp ON c.id = sp.country_id WHERE c.continent = 'Europe' AND sp.certification_date >= '2019-01-01';


Question: What is the maximum duration of a space mission to Mars in days?

CREATE TABLE SpaceMissions (MissionID INT, Name VARCHAR(50), LaunchDate DATE, Duration INT); INSERT INTO SpaceMissions VALUES (1, 'Curiosity', '2012-11-26', 669), (2, 'Perseverance', '2020-07-30', 342), (3, 'InSight', '2018-05-05', 913);

SELECT MAX(Duration) FROM SpaceMissions WHERE Destination = 'Mars';


Question: Count the number of esports events in 2022

CREATE TABLE Esports_Events (id INT, name VARCHAR(50), event_date DATE); INSERT INTO Esports_Events (id, name, event_date) VALUES (1, 'Dreamhack', '2022-01-01'), (2, 'ESL One', '2021-01-01'), (3, 'IEM', '2022-03-01');

SELECT COUNT(*) FROM Esports_Events WHERE event_date BETWEEN '2022-01-01' AND '2022-12-31';


Question: Find the number of founders who are women

CREATE TABLE startup (id INT, name TEXT, founding_year INT, founder_gender TEXT);

SELECT COUNT(*) FROM startup WHERE founder_gender = 'woman';


Question: PL/pgSQL test: Plpgsql Transaction (example 23).

$$;

CALL transaction_test5();

-- SECURITY DEFINER currently disallow transaction statements
CREATE PROCEDURE transaction_test5b()
LANGUAGE plpgsql
SECURITY DEFINER
AS $$
BEGIN
    COMMIT;

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


Question: How many astronauts are there in total from India and Japan?

CREATE TABLE Astronauts (astronaut_id INT, name VARCHAR(255), country VARCHAR(255)); INSERT INTO Astronauts (astronaut_id, name, country) VALUES (1001, 'Rakesh Sharma', 'India'), (1002, 'Kalpana Chawla', 'US'), (1003, 'Sunita Williams', 'US'), (2001, 'Takao Doi', 'Japan'), (2002, 'Naoko Yamazaki', 'Japan');

SELECT COUNT(*) FROM Astronauts WHERE country = 'India' OR country = 'Japan';


Question: Which vessels have a compliance score below 70 and have traveled to the Arctic Ocean?

CREATE TABLE vessels (id INT, name TEXT, type TEXT, compliance_score INT);CREATE TABLE routes (id INT, vessel_id INT, destination TEXT, date DATE); INSERT INTO vessels (id, name, type, compliance_score) VALUES (1, 'VesselF', 'Cargo', 65); INSERT INTO routes (id, vessel_id, destination, date) VALUES (1, 1, 'Arctic', '2022-02-15');

SELECT v.name FROM vessels v JOIN routes r ON v.id = r.vessel_id WHERE v.compliance_score < 70 AND r.destination = 'Arctic';


Question: What is the maximum billing amount for each attorney in the 'billing' table, grouped by their specialty?

CREATE TABLE attorney (attorney_id INT, specialty VARCHAR(255)); INSERT INTO attorney (attorney_id, specialty) VALUES (1, 'Criminal Law'), (2, 'Family Law'), (3, 'Personal Injury'); CREATE TABLE billing (bill_id INT, attorney_id INT, amount DECIMAL(10,2)); INSERT INTO billing (bill_id, attorney_id, amount) VALUES (1, 1, 500.00), (2, 1, 750.00), (3, 2, 600.00), (4, 3, 800.00), (5, 3, 900.00);

SELECT specialty, MAX(amount) FROM billing JOIN attorney ON billing.attorney_id = attorney.attorney_id GROUP BY specialty;


Question: pgTAP test for Hastap (assertion 103).

SELECT * FROM check_test(
    hasnt_type( 'public'::name, '__foobarbaz__'::name ),
    true,
    'hasnt_type(scheam, type)',
    'Type public.__foobarbaz__ should not exist',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Hastap.


Question: Generate PostgreSQL SQL for: What duration is listed for Christian de la Fuente?

CREATE TABLE table_11210576_3 (duration VARCHAR, actor VARCHAR)

SELECT duration FROM table_11210576_3 WHERE actor = 'Christian de la Fuente';


Question: Generate PostgreSQL SQL for: What is the location code with the most documents?

CREATE TABLE Document_locations (location_code VARCHAR)

SELECT location_code FROM Document_locations GROUP BY location_code ORDER BY COUNT(*) DESC LIMIT 1;


Question: How many marine species are endangered in the Indian Ocean?

CREATE TABLE marine_species (name TEXT, region TEXT, endangered BOOLEAN); INSERT INTO marine_species (name, region, endangered) VALUES ('Whale Shark', 'Indian Ocean', TRUE), ('Dugong', 'Indian Ocean', TRUE);

SELECT COUNT(*) FROM marine_species WHERE region = 'Indian Ocean' AND endangered = TRUE;


Question: Generate PostgreSQL SQL for: What is Fiji's lowest total?

CREATE TABLE table_name_63 (total INTEGER, country VARCHAR)

SELECT MIN(total) FROM table_name_63 WHERE country = 'fiji';


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


Question: Get the total area of the ocean floor mapped by region

CREATE TABLE ocean_floor_mapping (mapping_id INT, region VARCHAR(255), area INT);

SELECT region, SUM(area) FROM ocean_floor_mapping GROUP BY region;


Question: What is the total number of employees working in the 'manufacturing' department, excluding any employees who also appear in the 'training' table?

CREATE TABLE companies (company_id INT, department VARCHAR(20)); INSERT INTO companies (company_id, department) VALUES (1, 'manufacturing'), (2, 'HR'), (3, 'manufacturing'); CREATE TABLE employees (employee_id INT, company_id INT); CREATE TABLE training (employee_id INT, training VARCHAR(20)); INSERT INTO employees (employee_id, company_id) VALUES (1, 1), (2, 1), (3, 2); INSERT INTO training (employee_id, training) VALUES (1, 'welding'), (2, 'safety'), (3, 'safety');

SELECT COUNT(*) FROM companies INNER JOIN employees ON companies.company_id = employees.company_id WHERE companies.department = 'manufacturing' AND employees.employee_id NOT IN (SELECT employee_id FROM training);


Question: Generate PostgreSQL SQL for: What was the score of the game played in the 2012 Africa Cup of Nations?

CREATE TABLE table_name_90 (score VARCHAR, competition VARCHAR)

SELECT score FROM table_name_90 WHERE competition = '2012 africa cup of nations';


Question: Generate PostgreSQL SQL for: What date was the score 3–3, and away team was Barnet?

CREATE TABLE table_name_96 (date VARCHAR, score VARCHAR, away_team VARCHAR)

SELECT date FROM table_name_96 WHERE score = '3–3' AND away_team = 'barnet';


Question: Write the DDL statement from PostgreSQL regression test 'stats_ext' (example 759).

CREATE STATISTICS s_expr ON mod(id, 2), lower(col) FROM stats_ext_tbl;

Explanation: DDL from PostgreSQL core regression test for Stats Ext.


Question: Generate PostgreSQL SQL for: What year was the startup for the Project Named of taq taq ph 2?

CREATE TABLE table_name_51 (year_startup VARCHAR, project_name VARCHAR)

SELECT year_startup FROM table_name_51 WHERE project_name = 'taq taq ph 2';


Question: What is the maximum number of cases handled in a year by any mediation center?

CREATE TABLE AnnualCasesHandled (ID INT, MediationCenter VARCHAR(50), Year INT, Cases INT); INSERT INTO AnnualCasesHandled (ID, MediationCenter, Year, Cases) VALUES (1, 'PeaceBuilders', 2005, 120), (2, 'CommunityHealers', 2010, 150), (3, 'HarmonyKeepers', 2008, 210), (4, 'UnityCreators', 2015, 200);

SELECT MAX(Cases) FROM AnnualCasesHandled;


Question: Generate PostgreSQL SQL for: What date has a margin of victory of 1 stroke over Greg Kraft?

CREATE TABLE table_name_21 (date VARCHAR, margin_of_victory VARCHAR, runner_s__up VARCHAR)

SELECT date FROM table_name_21 WHERE margin_of_victory = '1 stroke' AND runner_s__up = 'greg kraft';


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

SELECT * FROM test_bpchar WHERE i<='abc' ORDER BY i;

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


Question: Write the DML statement from PostgreSQL regression test 'returning' (example 47).

DELETE FROM foo WHERE f2 = 'zit' RETURNING *;

Explanation: DML from PostgreSQL core regression test for Returning.