Question: What is the name and location of the rural hospital with the most medical professionals?

CREATE TABLE medical_professionals (id INT, name VARCHAR(50), hospital_id INT); CREATE TABLE hospitals (id INT, name VARCHAR(50), location VARCHAR(50)); INSERT INTO medical_professionals (id, name, hospital_id) VALUES (1, 'Dr. Smith', 1), (2, 'Dr. Johnson', 1), (3, 'Dr. Lee', 2); INSERT INTO hospitals (id, name, location) VALUES (1, 'Hospital A', 'New York'), (2, 'Hospital B', 'New York');

SELECT hospitals.name, hospitals.location FROM hospitals JOIN (SELECT hospital_id, COUNT(*) as num_of_professionals FROM medical_professionals GROUP BY hospital_id ORDER BY num_of_professionals DESC LIMIT 1) AS subquery ON hospitals.id = subquery.hospital_id;


Question: Generate PostgreSQL SQL for: Which occurence has the matrix sim marked as 0.925?

CREATE TABLE table_26708105_2 (occurrence VARCHAR, matrix_sim VARCHAR)

SELECT occurrence FROM table_26708105_2 WHERE matrix_sim = '0.925';


Question: Which threat intelligence sources have provided the most actionable intelligence in the last quarter?

CREATE TABLE threat_intelligence(id INT, source VARCHAR(50), category VARCHAR(50), rating INT, date DATE);

SELECT source, SUM(rating) as total_rating FROM threat_intelligence WHERE date > DATE(NOW()) - INTERVAL 90 DAY AND category = 'actionable' GROUP BY source ORDER BY total_rating DESC;


Question: Regions with the highest percentage of cruelty-free product preferences?

CREATE TABLE user_preferences (user_id INT, region VARCHAR(50), cruelty_free BOOLEAN); INSERT INTO user_preferences (user_id, region, cruelty_free) VALUES (1, 'North America', true), (2, 'Europe', false), (3, 'Asia', true);

SELECT region, AVG(cruelty_free) as cruelty_free_avg FROM user_preferences GROUP BY region ORDER BY cruelty_free_avg DESC;


Question: What is the maximum, minimum, and average accommodation cost for students with cognitive disabilities in each region?

CREATE TABLE AccommodationCostsForCognitiveDisabilities (StudentID INT, Region VARCHAR(50), AccommodationCost DECIMAL(10,2));

SELECT Region, MIN(AccommodationCost) as MinCost, MAX(AccommodationCost) as MaxCost, AVG(AccommodationCost) as AvgCost FROM AccommodationCostsForCognitiveDisabilities WHERE DisabilityType = 'cognitive disability' GROUP BY Region;


Question: Identify the average ESG score for all sectors.

CREATE TABLE companies (id INT, sector VARCHAR(20), ESG_score FLOAT); INSERT INTO companies (id, sector, ESG_score) VALUES (1, 'technology', 78.3), (2, 'finance', 65.2), (3, 'technology', 81.5), (4, 'healthcare', 72.1);

SELECT sector, AVG(ESG_score) FROM companies GROUP BY sector;


Question: Generate PostgreSQL SQL for: Who is the opponent when the record is 3-8?

CREATE TABLE table_name_53 (opponent VARCHAR, record VARCHAR)

SELECT opponent FROM table_name_53 WHERE record = '3-8';


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

SELECT f1 AS nine FROM FLOAT8_TBL
UNION
SELECT f1 FROM INT4_TBL
ORDER BY 1;

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

SELECT count(*) FROM (SELECT f1 AS nine FROM FLOAT8_TBL
UNION
SELECT f1 FROM INT4_TBL
ORDER BY 1) AS _sub;


Question: Generate PostgreSQL SQL for: Tell me the circuit for alfa romeo swedish ice race

CREATE TABLE table_name_5 (circuit VARCHAR, winning_constructor VARCHAR, name VARCHAR)

SELECT circuit FROM table_name_5 WHERE winning_constructor = 'alfa romeo' AND name = 'swedish ice race';


Question: What is the average risk score of vulnerabilities detected in the last 30 days, grouped by software vendor?

CREATE TABLE vulnerabilities (id INT, detection_date DATE, software_vendor VARCHAR(255), risk_score INT); INSERT INTO vulnerabilities (id, detection_date, software_vendor, risk_score) VALUES (1, '2022-01-01', 'VendorA', 7), (2, '2022-01-05', 'VendorB', 5), (3, '2022-01-10', 'VendorA', 9);

SELECT software_vendor, AVG(risk_score) as avg_risk_score FROM vulnerabilities WHERE detection_date >= DATE(NOW()) - INTERVAL 30 DAY GROUP BY software_vendor;


Question: Generate PostgreSQL SQL for: what is the highest pick number of the CFL team, the winnipeg blue bombers?

CREATE TABLE table_name_42 (pick__number INTEGER, cfl_team VARCHAR)

SELECT MAX(pick__number) FROM table_name_42 WHERE cfl_team = 'winnipeg blue bombers';


Question: Generate PostgreSQL SQL for: If the Away Team is Arsenal what is the Score?

CREATE TABLE table_name_47 (score VARCHAR, away_team VARCHAR)

SELECT score FROM table_name_47 WHERE away_team = 'arsenal';


Question: What is the total data usage for each country in the last month?

CREATE TABLE broadband_subscribers (subscriber_id INT, country VARCHAR(50), data_usage INT, subscription_date DATE); INSERT INTO broadband_subscribers (subscriber_id, country, data_usage, subscription_date) VALUES (1, 'India', 50, '2022-03-15'), (2, 'Brazil', 75, '2022-03-10'), (3, 'Indonesia', 100, '2022-03-05'), (4, 'India', 25, '2022-03-20'), (5, 'Brazil', 10, '2022-03-25');

SELECT country, SUM(data_usage) AS total_data_usage FROM broadband_subscribers WHERE subscription_date >= DATE_SUB(CURDATE(), INTERVAL 1 MONTH) GROUP BY country;


Question: What was the total number of cases heard by each judge in the criminal division in 2020?

CREATE TABLE Judges (Name VARCHAR(255), Division VARCHAR(255), CasesHeard INT); INSERT INTO Judges (Name, Division, CasesHeard) VALUES ('Judge 1', 'Criminal', 100), ('Judge 2', 'Civil', 125), ('Judge 3', 'Criminal', 150);

SELECT Division, SUM(CasesHeard) as TotalCasesHeard FROM Judges WHERE Division = 'Criminal' AND YEAR(EventDate) = 2020 GROUP BY Division;


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

create function testpolym(a int) returns table(a int) as $$ select $1;$$ language sql;
select * from testpolym(37);
drop function testpolym(int);

-- test polymorphic params and defaults
create function dfunc(a anyelement, b anyelement = null, flag bool = true)
returns anyelement as $$
  select case when $3 then $1 else $2 end;

Explanation: DDL from PostgreSQL core regression test for Polymorphism.


Question: Generate PostgreSQL SQL for: What is the memory with a socket g1 and a 1/1/6/9 turbo?

CREATE TABLE table_name_93 (memory VARCHAR, socket VARCHAR, turbo VARCHAR)

SELECT memory FROM table_name_93 WHERE socket = 'socket g1' AND turbo = '1/1/6/9';


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

INSERT INTO OID8_TBL(f1) VALUES ('    5d');

Explanation: DML from PostgreSQL core regression test for Oid8.


Question: Generate PostgreSQL SQL for: Which Player had a Long of 5 and Yards of 6?

CREATE TABLE table_name_74 (player VARCHAR, long VARCHAR, yards VARCHAR)

SELECT player FROM table_name_74 WHERE long = '5' AND yards = '6';


Question: Generate PostgreSQL SQL for: What is the nationality of the swimmer with a rank over 2 with a time of 55.77?

CREATE TABLE table_name_47 (nationality VARCHAR, rank VARCHAR, time VARCHAR)

SELECT nationality FROM table_name_47 WHERE rank > 2 AND time = '55.77';


Question: What is the total number of workers represented by unions with headquarters in 'New York'?

CREATE TABLE if not exists union_membership (union_id INT, worker_id INT); CREATE TABLE if not exists unions (union_id INT, union_name TEXT, headquarters_address TEXT, total_workers INT); INSERT INTO union_membership (union_id, worker_id) VALUES (1, 1001), (1, 1002), (1, 1003), (2, 2001), (2, 2002), (3, 3001); INSERT INTO unions (union_id, union_name, headquarters_address, total_workers) VALUES (1, 'United Steelworkers', '60 Boulevard of the Allies, Pittsburgh, PA 15222', 5000), (2, 'Teamsters', '25 Louisiana Ave NW, Washington, DC 20001', 7000), (3, 'UAW', '8000 E Jefferson Ave, Detroit, MI 48214', 6000), (4, 'NYC Labor Council', '275 Seventh Avenue, 18th Floor, New York, NY 10001', 8000);

SELECT SUM(total_workers) FROM unions WHERE headquarters_address LIKE '%New York%';


Question: Generate PostgreSQL SQL for: I want to know the home team for mcg venue

CREATE TABLE table_name_71 (home_team VARCHAR, venue VARCHAR)

SELECT home_team FROM table_name_71 WHERE venue = 'mcg';


Question: List all sustainable building practices with a LEED certification date in the year 2021

CREATE TABLE sustainable_practices (project_id INT, leed_certification_date DATE);

SELECT * FROM sustainable_practices WHERE EXTRACT(YEAR FROM leed_certification_date) = 2021;


Question: Generate PostgreSQL SQL for: who wrote the no 2?

CREATE TABLE table_21726793_1 (written_by VARCHAR, no VARCHAR)

SELECT written_by FROM table_21726793_1 WHERE no = 2;


Question: Generate PostgreSQL SQL for: What is the total number of silver medals for countries of rank 14, with less than 1 total medals?

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

SELECT SUM(silver) FROM table_name_66 WHERE rank = '14' AND total < 1;


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

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

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


Question: Write the DDL statement from PostgreSQL regression test 'copydml' (example 46).

create rule qqq as on delete to copydml_test do instead (insert into copydml_test default values; insert into copydml_test default values);

Explanation: DDL from PostgreSQL core regression test for Copydml.


Question: Calculate the total number of refills for antibiotics prescribed in Q1 2022.

CREATE TABLE medications (id INT, patient_id INT, medication VARCHAR(30), prescription_date DATE, refills INT); INSERT INTO medications (id, patient_id, medication, prescription_date, refills) VALUES (1, 3, 'Amoxicillin', '2022-02-01', 2), (2, 4, 'Ciprofloxacin', '2022-03-15', 1);

SELECT SUM(refills) FROM medications WHERE medication LIKE '%antibiotic%' AND prescription_date BETWEEN '2022-01-01' AND '2022-03-31';


Question: Generate PostgreSQL SQL for: How many values reflect the overall record of the team coached by Frank Beamer?

CREATE TABLE table_28744929_2 (overall_record VARCHAR, head_coach VARCHAR)

SELECT COUNT(overall_record) FROM table_28744929_2 WHERE head_coach = 'Frank Beamer';


Question: What is the total number of 'Zumba' classes offered?

CREATE TABLE Classes (ClassID INT, ClassType VARCHAR(20), ClassDate DATE); INSERT INTO Classes (ClassID, ClassType, ClassDate) VALUES (1, 'Yoga', '2022-01-05'), (2, 'Pilates', '2022-01-07'), (3, 'Zumba', '2022-02-03');

SELECT COUNT(ClassID) FROM Classes WHERE ClassType = 'Zumba';


Question: Which regions had the highest total donations in 2019?

CREATE TABLE donations (donation_id INT, donation_date DATE, amount DECIMAL(10,2), region TEXT); INSERT INTO donations (donation_id, donation_date, amount, region) VALUES (1, '2019-01-01', 1000.00, 'North America'), (2, '2019-02-01', 1500.00, 'Europe'), (3, '2019-03-01', 2000.00, 'Asia');

SELECT region, SUM(amount) as total_donations FROM donations WHERE YEAR(donation_date) = 2019 GROUP BY region ORDER BY total_donations DESC;


Question: What is the maximum number of exhibitions attended by a single visitor?

CREATE TABLE Visitor_Exhibitions (visitor_id INT, exhibition_id INT);

SELECT MAX(Visitor_Exhibitions_agg.visitor_exhibitions) FROM (SELECT COUNT(*) AS visitor_exhibitions FROM Visitor_Exhibitions GROUP BY visitor_id) AS Visitor_Exhibitions_agg;


Question: What is the minimum number of marine species observed in the Andaman Sea?

CREATE TABLE marine_species_count (id INT, location TEXT, species_count INT); INSERT INTO marine_species_count (id, location, species_count) VALUES (1, 'Andaman Sea', 500), (2, 'South China Sea', 700), (3, 'Mediterranean Sea', 600);

SELECT MIN(species_count) FROM marine_species_count WHERE location = 'Andaman Sea';


Question: Who is the oldest blues artist in our database?

CREATE TABLE Artists (ArtistID INT, Name VARCHAR(255), Age INT, Genre VARCHAR(255)); INSERT INTO Artists VALUES (1, 'B.B. King', 92, 'Blues'); INSERT INTO Artists VALUES (2, 'Muddy Waters', 89, 'Blues'); INSERT INTO Artists VALUES (3, 'Buddy Guy', 86, 'Blues');

SELECT Name, MAX(Age) FROM Artists WHERE Genre = 'Blues';


Question: Generate PostgreSQL SQL for: What date was the show's weekly ranking 12?

CREATE TABLE table_27319183_7 (date VARCHAR, weekly_rank VARCHAR)

SELECT date FROM table_27319183_7 WHERE weekly_rank = 12;


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

drop function polyf(x anycompatible, y anycompatible);

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


Question: PostgreSQL regression test 'pg_dependencies': Write the SELECT query (example 61).

SELECT '[{"attributes" : [1, {}], "dependency" : 1, "degree": "1.2"}]'::pg_dependencies;

Explanation: Regression test for Pg Dependencies in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT '[{"attributes" : [1, {}], "dependency" : 1, "degree": "1.2"}]'::pg_dependencies) AS _sub;


Question: Generate PostgreSQL SQL for: what is score of a team with tie of 4?

CREATE TABLE table_name_38 (score VARCHAR, tie_no VARCHAR)

SELECT score FROM table_name_38 WHERE tie_no = '4';


Question: What is the total number of high severity vulnerabilities in the 'vuln_assessments' table?

CREATE TABLE vuln_assessments (id INT, severity VARCHAR(10), description TEXT); INSERT INTO vuln_assessments (id, severity, description) VALUES (1, 'high', 'SQL Injection'), (2, 'medium', 'Cross-Site Scripting'), (3, 'high', 'Privilege Escalation');

SELECT COUNT(*) FROM vuln_assessments WHERE severity = 'high';


Question: Generate PostgreSQL SQL for: For the game with 528 attendance, what was the result?

CREATE TABLE table_name_14 (result VARCHAR, attendance VARCHAR)

SELECT result FROM table_name_14 WHERE attendance = '528';


Question: Generate PostgreSQL SQL for: What is the value of barrel twist when the barrel profile is SFW?

CREATE TABLE table_12834315_8 (barrel_twist VARCHAR, barrel_profile VARCHAR)

SELECT barrel_twist FROM table_12834315_8 WHERE barrel_profile = 'SFW';


Question: Which public works project in 'South' region has the highest construction cost?

CREATE TABLE Projects (id INT, name TEXT, region TEXT, cost FLOAT); INSERT INTO Projects (id, name, region, cost) VALUES (1, 'ProjectA', 'South', 2500000.00), (2, 'ProjectB', 'South', 3000500.75), (3, 'ProjectC', 'South', 2200000.50);

SELECT name, MAX(cost) FROM Projects WHERE region = 'South';


Question: Show all climate communication projects from the 'communication_projects' table

CREATE TABLE communication_projects (id INT PRIMARY KEY, name VARCHAR(255), location VARCHAR(255), description TEXT, start_date DATE, end_date DATE, budget FLOAT); INSERT INTO communication_projects (id, name, location, description, start_date, end_date, budget) VALUES (1, 'Public Awareness Campaign', 'New York', 'Raising awareness of climate change', '2018-01-01', '2018-12-31', 200000);


Question: Generate PostgreSQL SQL for: Which club was in Position 1 in 1959-1960?

CREATE TABLE table_name_59 (clubs VARCHAR, position_in_1959_1960 VARCHAR)

SELECT clubs FROM table_name_59 WHERE position_in_1959_1960 = '1';


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

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


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

SELECT relname, d.* FROM ONLY d, pg_class where d.tableoid = pg_class.oid;

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

SELECT count(*) FROM (SELECT relname, d.* FROM ONLY d, pg_class where d.tableoid = pg_class.oid) AS _sub;


Question: Delete all records related to diversity training programs.

CREATE TABLE TrainingPrograms (ProgramID INT, ProgramName VARCHAR(30), ProgramType VARCHAR(20)); INSERT INTO TrainingPrograms (ProgramID, ProgramName, ProgramType) VALUES (1, 'Diversity Training', 'Diversity'), (2, 'Leadership Training', 'Leadership'), (3, 'Team Building', 'Teamwork');

DELETE FROM TrainingPrograms WHERE ProgramType = 'Diversity';


Question: Generate PostgreSQL SQL for: What is the Class for the ERP W of more than 2 and the call sign of w223au?

CREATE TABLE table_name_50 (class VARCHAR, erp_w VARCHAR, call_sign VARCHAR)

SELECT class FROM table_name_50 WHERE erp_w > 2 AND call_sign = 'w223au';


Question: What is the minimum weight for each type of artifact across all excavation sites?

CREATE TABLE ExcavationSite (SiteID INT, SiteName VARCHAR(50)); INSERT INTO ExcavationSite (SiteID, SiteName) VALUES (1, 'Site A'), (2, 'Site B'), (3, 'Site C'); CREATE TABLE Artifact (ArtifactID INT, SiteID INT, Weight FLOAT, ObjectType VARCHAR(50)); INSERT INTO Artifact (ArtifactID, SiteID, Weight, ObjectType) VALUES (1, 1, 54.3, 'Pottery'), (2, 1, 32.1, 'Tool'), (3, 2, 120.5, 'Statue'), (4, 2, 12.7, 'Bead'), (5, 3, 8.4, 'Bead'), (6, 1, 20.5, 'Bead');

SELECT a.ObjectType, MIN(a.Weight) AS MinWeight FROM Artifact a JOIN ExcavationSite e ON a.SiteID = e.SiteID GROUP BY a.ObjectType;


Question: What is the average donation amount by month in 2022?

CREATE TABLE donations (id INT, donor VARCHAR(50), cause VARCHAR(50), amount DECIMAL(10, 2), donation_date DATE); INSERT INTO donations (id, donor, cause, amount, donation_date) VALUES (1, 'John Doe', 'Education', 500, '2022-04-01'), (2, 'Jane Smith', 'Health', 300, '2022-04-15'), (3, 'Alice Johnson', 'Environment', 700, '2022-05-05');

SELECT EXTRACT(MONTH FROM donation_date) as month, AVG(amount) as avg_donation FROM donations WHERE donation_date BETWEEN '2022-01-01' AND '2022-12-31' GROUP BY month;


Question: What is the maximum energy efficiency (in kWh/m2) of buildings in Canada?

CREATE TABLE Buildings (id INT, country VARCHAR(50), energy_efficiency FLOAT); INSERT INTO Buildings (id, country, energy_efficiency) VALUES (1, 'Canada', 0.45), (2, 'Canada', 0.51), (3, 'USA', 0.42);

SELECT MAX(energy_efficiency) FROM Buildings WHERE country = 'Canada';


Question: Show the total number of users who have engaged with content related to indigenous rights in Canada, for the year 2021.

CREATE TABLE user_interactions (id INT, user_id INT, content_type VARCHAR(50), interaction_date DATE); CREATE TABLE content (id INT, content_type VARCHAR(50), tags VARCHAR(500), country VARCHAR(50));

SELECT COUNT(DISTINCT ui.user_id) as total_users FROM user_interactions ui JOIN content c ON ui.content_type = c.content_type WHERE c.tags LIKE '%indigenous rights%' AND c.country = 'Canada' AND interaction_date >= '2021-01-01' AND interaction_date <= '2021-12-31';


Question: Generate PostgreSQL SQL for: List the players with 1285 new points?

CREATE TABLE table_24431264_18 (player VARCHAR, new_points VARCHAR)

SELECT player FROM table_24431264_18 WHERE new_points = 1285;


Question: What is the distribution of medical risks for astronauts by country?

CREATE TABLE Astronauts (id INT, country TEXT);CREATE TABLE AstronautMedicalData (id INT, astronaut_id INT, medical_risk FLOAT);

SELECT Astronauts.country, AVG(medical_risk) as avg_medical_risk, STDDEV(medical_risk) as stddev_medical_risk FROM Astronauts INNER JOIN AstronautMedicalData ON Astronauts.id = AstronautMedicalData.astronaut_id GROUP BY Astronauts.country;


Question: Generate PostgreSQL SQL for: What was the method used when the opponent was Tyson Griffin?

CREATE TABLE table_name_75 (method VARCHAR, opponent VARCHAR)

SELECT method FROM table_name_75 WHERE opponent = 'tyson griffin';


Question: Generate PostgreSQL SQL for: Gold that has a Rank of 6, and a Bronze larger than 0 had what total number of gold?

CREATE TABLE table_name_46 (gold VARCHAR, rank VARCHAR, bronze VARCHAR)

SELECT COUNT(gold) FROM table_name_46 WHERE rank = '6' AND bronze > 0;


Question: What is the total number of community health workers who have received implicit bias training, broken down by their ethnicity?

CREATE TABLE CommunityHealthWorkers (WorkerID INT, Ethnicity VARCHAR(255), ImplicitBiasTraining DATE); INSERT INTO CommunityHealthWorkers (WorkerID, Ethnicity, ImplicitBiasTraining) VALUES (1, 'Hispanic', '2022-01-10'); INSERT INTO CommunityHealthWorkers (WorkerID, Ethnicity, ImplicitBiasTraining) VALUES (2, 'African American', '2021-12-15'); INSERT INTO CommunityHealthWorkers (WorkerID, Ethnicity, ImplicitBiasTraining) VALUES (3, 'Asian', '2022-02-03'); INSERT INTO CommunityHealthWorkers (WorkerID, Ethnicity, ImplicitBiasTraining) VALUES (4, 'Native American', '2021-08-02');

SELECT Ethnicity, COUNT(*) as Total FROM CommunityHealthWorkers WHERE ImplicitBiasTraining IS NOT NULL GROUP BY Ethnicity;


Question: How many movies and TV shows were released in each month?

CREATE TABLE Movies (id INT, title VARCHAR(255), release_date DATE); CREATE TABLE TVShows (id INT, title VARCHAR(255), release_date DATE);

SELECT DATE_FORMAT(release_date, '%Y-%m') AS Release_Month, COUNT(*) AS Total_Releases FROM Movies GROUP BY Release_Month UNION ALL SELECT DATE_FORMAT(release_date, '%Y-%m') AS Release_Month, COUNT(*) AS Total_Releases FROM TVShows GROUP BY Release_Month;


Question: Generate PostgreSQL SQL for: What is the Outcome when the partner was kristof vliegen?

CREATE TABLE table_name_20 (outcome VARCHAR, partner VARCHAR)

SELECT outcome FROM table_name_20 WHERE partner = 'kristof vliegen';


Question: Generate PostgreSQL SQL for: What was the title of the episode having exactly 9.64 million US viewers?

CREATE TABLE table_24910742_1 (title VARCHAR, us_viewers__millions_ VARCHAR)

SELECT title FROM table_24910742_1 WHERE us_viewers__millions_ = '9.64';


Question: Generate PostgreSQL SQL for: Name the number of episode for phyllo dough

CREATE TABLE table_15187735_3 (episode VARCHAR, segment_c VARCHAR)

SELECT COUNT(episode) FROM table_15187735_3 WHERE segment_c = 'Phyllo Dough';


Question: Generate PostgreSQL SQL for: What Entrepreneurs requested £60,000?

CREATE TABLE table_name_27 (entrepreneur_s_ VARCHAR, money_requested__£_ VARCHAR)

SELECT entrepreneur_s_ FROM table_name_27 WHERE money_requested__£_ = '60,000';


Question: What is the number of people impacted by disasters in each country, sorted by the total number of people impacted, for the last 3 years?

CREATE TABLE disaster (disaster_id INT, name VARCHAR(255), location VARCHAR(255), start_date DATE, people_impacted INT); INSERT INTO disaster VALUES (1, 'Hurricane Katrina', 'USA', '2005-08-29', 100000); INSERT INTO disaster VALUES (2, 'Earthquake', 'Mexico', '2017-09-19', 50000);

SELECT location as country, SUM(people_impacted) as total_people_impacted FROM disaster WHERE start_date >= DATE_SUB(CURRENT_DATE, INTERVAL 3 YEAR) GROUP BY location ORDER BY total_people_impacted DESC;


Question: Generate PostgreSQL SQL for: Who was the away team that played Northampton Town at home with a tie number of replay?

CREATE TABLE table_name_53 (away_team VARCHAR, tie_no VARCHAR, home_team VARCHAR)

SELECT away_team FROM table_name_53 WHERE tie_no = 'replay' AND home_team = 'northampton town';


Question: Generate PostgreSQL SQL for: Tell me the result for week less than 4 and september 7, 1986

CREATE TABLE table_name_46 (result VARCHAR, week VARCHAR, date VARCHAR)

SELECT result FROM table_name_46 WHERE week < 4 AND date = 'september 7, 1986';


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

select x, pg_typeof(x), y, pg_typeof(y)
  from polyf(11, array[1, 2], point(1,2), point(3,4));

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

SELECT count(*) FROM (select x, pg_typeof(x), y, pg_typeof(y)
  from polyf(11, array[1, 2], point(1,2), point(3,4))) AS _sub;


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

SELECT 'tree.awdfg'::ltree @ '!tree | aWdf@*'::ltxtquery;

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


Question: Generate PostgreSQL SQL for: Which role is most common for the staff?

CREATE TABLE Project_Staff (role_code VARCHAR)

SELECT role_code FROM Project_Staff GROUP BY role_code ORDER BY COUNT(*) DESC LIMIT 1;


Question: Generate PostgreSQL SQL for: How many wins were there when the position was 26th?

CREATE TABLE table_1507423_4 (wins VARCHAR, position VARCHAR)

SELECT COUNT(wins) FROM table_1507423_4 WHERE position = '26th';


Question: What is the average population size of marine species in the Pacific Ocean, partitioned by habitat?

CREATE TABLE pacific_species (id INT, species_name VARCHAR(255), population INT, habitat VARCHAR(255), ocean VARCHAR(255)); INSERT INTO pacific_species (id, species_name, population, habitat, ocean) VALUES (1, 'Giant Pacific Octopus', 20000, 'Deep Sea', 'Pacific');

SELECT habitat, AVG(population) AS avg_population FROM pacific_species WHERE ocean = 'Pacific' GROUP BY habitat;


Question: Generate PostgreSQL SQL for: What is the game number that was on November 27?

CREATE TABLE table_22871239_5 (_number VARCHAR, date VARCHAR)

SELECT _number FROM table_22871239_5 WHERE date = 'November 27';


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

update trigger_test_view set v = 'update' where i = 1;

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


Question: What is the total distance traveled by each route?

CREATE TABLE route (route_id INT, line TEXT);CREATE TABLE trip_distance (distance INT, trip_id INT, route_id INT);

SELECT r.line, SUM(td.distance) FROM route r INNER JOIN trip_distance td ON r.route_id = td.route_id GROUP BY r.line;


Question: Generate PostgreSQL SQL for: What district is Henry Hyde in

CREATE TABLE table_1341423_13 (district VARCHAR, incumbent VARCHAR)

SELECT district FROM table_1341423_13 WHERE incumbent = 'Henry Hyde';


Question: Generate PostgreSQL SQL for: What type of environment is the venue that was built in 2003?

CREATE TABLE table_name_11 (environment VARCHAR, year_built VARCHAR)

SELECT environment FROM table_name_11 WHERE year_built = '2003';


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

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


Question: What is the average fare amount and the number of fares for each route type?

CREATE TABLE route_types (route_type_id INT, route_type_name VARCHAR(50)); CREATE TABLE fares (fare_id INT, route_id INT, fare_amount DECIMAL(5,2), payment_method VARCHAR(50), route_type_id INT);

SELECT rt.route_type_name, f.fare_amount, AVG(f.fare_amount) AS avg_fare_amount, COUNT(f.fare_id) AS fare_count FROM fares f JOIN route_types rt ON f.route_type_id = rt.route_type_id GROUP BY rt.route_type_name, f.fare_amount ORDER BY avg_fare_amount DESC;


Question: Calculate the total sales for each restaurant location

CREATE TABLE restaurants (restaurant_id INT, name VARCHAR(50), location VARCHAR(50)); INSERT INTO restaurants (restaurant_id, name, location) VALUES (1, 'Pizzeria Roma', 'NYC'), (2, 'Pizzeria Roma', 'LA'), (3, 'Taste of India', 'NYC'), (4, 'Taste of India', 'Chicago'); CREATE TABLE sales (sale_id INT, restaurant_id INT, amount DECIMAL); INSERT INTO sales (sale_id, restaurant_id, amount) VALUES (1, 1, 100), (2, 1, 200), (3, 2, 50), (4, 3, 300), (5, 4, 150);

SELECT location, SUM(amount) as total_sales FROM sales JOIN restaurants ON sales.restaurant_id = restaurants.restaurant_id GROUP BY location;


Question: Generate PostgreSQL SQL for: What is the year when the performance is 60.73m and the age (years) is more than 45?

CREATE TABLE table_name_85 (year VARCHAR, performance VARCHAR, age__years_ VARCHAR)

SELECT COUNT(year) FROM table_name_85 WHERE performance = '60.73m' AND age__years_ > 45;


Question: What is the total number of animals in the rescue center from the 'Australian Outback' region?

CREATE TABLE rescue_center_animals (animal_id INT, animal_name VARCHAR(50), region VARCHAR(50)); INSERT INTO rescue_center_animals (animal_id, animal_name, region) VALUES (1, 'Kangaroo', 'Australian Outback'); INSERT INTO rescue_center_animals (animal_id, animal_name, region) VALUES (2, 'Emu', 'Australian Outback');

SELECT COUNT(animal_id) FROM rescue_center_animals WHERE region = 'Australian Outback';


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

CREATE OR REPLACE FUNCTION zdb.bytea_to_json(bytea) RETURNS json
    PARALLEL SAFE IMMUTABLE STRICT
    LANGUAGE sql AS
$$
SELECT to_json(encode($1, 'base64'));
$$;

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


Question: Generate PostgreSQL SQL for: Which week had a result of L 38-21?

CREATE TABLE table_name_91 (week VARCHAR, result VARCHAR)

SELECT week FROM table_name_91 WHERE result = 'l 38-21';


Question: Generate PostgreSQL SQL for: WHAT IS THE GRID OF HONDA, WITH 24 LAPS AND  Time/Retired of +13.997?

CREATE TABLE table_name_22 (grid VARCHAR, time_retired VARCHAR, manufacturer VARCHAR, laps VARCHAR)

SELECT grid FROM table_name_22 WHERE manufacturer = 'honda' AND laps = '24' AND time_retired = '+13.997';


Question: Create a view showing the number of tickets sold per quarter for each sport.

CREATE TABLE Sports (sport_id INT, sport_name VARCHAR(50)); CREATE TABLE Tickets (ticket_id INT, sport_id INT, quantity INT, purchase_date DATE);

CREATE VIEW quarterly_sales AS SELECT sport_id, EXTRACT(QUARTER FROM purchase_date) as quarter, EXTRACT(YEAR FROM purchase_date) as year, SUM(quantity) as total_sales FROM Tickets GROUP BY sport_id, quarter, year;


Question: Generate PostgreSQL SQL for: When playing against Yi Jingqian in the final on a hard surface what was the score?

CREATE TABLE table_name_29 (score VARCHAR, surface VARCHAR, opponent_in_the_final VARCHAR)

SELECT score FROM table_name_29 WHERE surface = 'hard' AND opponent_in_the_final = 'yi jingqian';


Question: What is the number of autonomous vehicle accidents per month?

CREATE TABLE autonomous_accidents (accident_date DATE, is_autonomous BOOLEAN);

SELECT DATE_TRUNC('month', accident_date) as month, COUNT(*) as num_accidents FROM autonomous_accidents WHERE is_autonomous = true GROUP BY month;


Question: Generate PostgreSQL SQL for: Which Lungchang has a Halang of ʒɯ², and a Rera of ʒo²?

CREATE TABLE table_name_85 (lungchang VARCHAR, halang VARCHAR, rera VARCHAR)

SELECT lungchang FROM table_name_85 WHERE halang = 'ʒɯ²' AND rera = 'ʒo²';


Question: Generate PostgreSQL SQL for: Find the average and oldest age for students with different sex.

CREATE TABLE student (sex VARCHAR, age INTEGER)

SELECT AVG(age), MAX(age), sex FROM student GROUP BY sex;


Question: Determine the number of customers who have an account balance greater than the median balance for all accounts.

CREATE TABLE accounts (customer_id INT, account_type VARCHAR(20), balance DECIMAL(10, 2));

SELECT COUNT(DISTINCT customer_id) FROM accounts WHERE balance > PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY balance) OVER ();


Question: Generate PostgreSQL SQL for: What is the Record of the Chicago Black Hawks Home game with the New York Rangers and a Score of 3–2?

CREATE TABLE table_name_28 (record VARCHAR, score VARCHAR, home VARCHAR, visitor VARCHAR)

SELECT record FROM table_name_28 WHERE home = 'chicago black hawks' AND visitor = 'new york rangers' AND score = '3–2';


Question: Generate PostgreSQL SQL for: What are the total number of positions on the Toronto team in 2006-07?

CREATE TABLE table_10015132_9 (position VARCHAR, years_in_toronto VARCHAR)

SELECT COUNT(position) FROM table_10015132_9 WHERE years_in_toronto = '2006-07';


Question: Delete the fashion trend with the lowest popularity.

CREATE TABLE FASHION_TRENDS (trend_id INT PRIMARY KEY, trend_name VARCHAR(50), popularity INT); INSERT INTO FASHION_TRENDS (trend_id, trend_name, popularity) VALUES (1, 'TrendA', 1000), (2, 'TrendB', 800), (3, 'TrendC', 1200), (4, 'TrendD', 500);

DELETE FROM FASHION_TRENDS WHERE trend_name = 'TrendD';


Question: What is the total CO2 emission reduction from recycling programs in Japan and South Korea?

CREATE TABLE recycling_reduction (country VARCHAR(30), reduction FLOAT); INSERT INTO recycling_reduction (country, reduction) VALUES ('Japan', 1.6), ('Japan', 1.8), ('South Korea', 0.9), ('South Korea', 1.2);

SELECT SUM(reduction) FROM recycling_reduction WHERE country IN ('Japan', 'South Korea');


Question: Generate PostgreSQL SQL for: What is the usual attendance for july 2?

CREATE TABLE table_name_6 (attendance INTEGER, date VARCHAR)

SELECT AVG(attendance) FROM table_name_6 WHERE date = 'july 2';


Question: What is the average yield and production cost for each crop variety in the "crops" and "expenses" tables?

CREATE TABLE crops (id INT, crop_name VARCHAR(50), yield INT, revenue INT); CREATE TABLE expenses (id INT, crop_id INT, cost INT);

SELECT crops.crop_name, AVG(crops.yield) AS avg_yield, AVG(expenses.cost) AS avg_cost FROM crops INNER JOIN expenses ON crops.id = expenses.crop_id GROUP BY crops.crop_name;


Question: Generate PostgreSQL SQL for: What party won with a margin of 105731?

CREATE TABLE table_22756549_1 (party VARCHAR, margin VARCHAR)

SELECT party FROM table_22756549_1 WHERE margin = 105731;


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

insert into spgist_text_tbl (id, t)
select g, 'f' || repeat('o', 100) || g from generate_series(1, 10000) g
union all
select g, 'baaaaaaaaaaaaaar' || g from generate_series(1, 1000) g;

Explanation: DML from PostgreSQL core regression test for Spgist.


Question: List all the wastewater treatment plants in Canada and their capacities.

CREATE TABLE wastewater_treatment (plant_name VARCHAR(50), country VARCHAR(20), capacity_m3 INT); INSERT INTO wastewater_treatment (plant_name, country, capacity_m3) VALUES ('Vancouver WWTP', 'Canada', 1500000);

SELECT plant_name, country, capacity_m3 FROM wastewater_treatment WHERE country = 'Canada';


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

SELECT ts_rank_cd(' a:1 sa:2A sb:2D g'::tsvector, 'a <-> s:* <-> sa:A');

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

SELECT count(*) FROM (SELECT ts_rank_cd(' a:1 sa:2A sb:2D g'::tsvector, 'a <-> s:* <-> sa:A')) AS _sub;


Question: Generate PostgreSQL SQL for: size (steps) of 15, and a just (cents) larger than 435.08 is what highest size (cents)?

CREATE TABLE table_name_26 (size__cents_ INTEGER, size__steps_ VARCHAR, just__cents_ VARCHAR)

SELECT MAX(size__cents_) FROM table_name_26 WHERE size__steps_ = 15 AND just__cents_ > 435.08;


Question: Generate PostgreSQL SQL for: What affiliation has an owned since larger than 1991, and also has a channel (tv/rf) of 42?

CREATE TABLE table_name_58 (affiliation VARCHAR, owned_since VARCHAR, channel___tv___rf__ VARCHAR)

SELECT affiliation FROM table_name_58 WHERE owned_since > 1991 AND channel___tv___rf__ = '42';


Question: List all food safety violations for 'Budget Burger' in Q2 2020.

CREATE TABLE Inspections (restaurant_id INT, inspection_date DATE, violation_count INT); INSERT INTO Inspections (restaurant_id, inspection_date, violation_count) VALUES (2, '2020-04-01', 3), (2, '2020-07-15', 2);

SELECT * FROM Inspections WHERE restaurant_id = 2 AND EXTRACT(QUARTER FROM inspection_date) = 2 AND EXTRACT(YEAR FROM inspection_date) = 2020;


Question: Generate PostgreSQL SQL for: Risca RFC has 54 tries for and how many draws?

CREATE TABLE table_13741576_6 (drawn VARCHAR, tries_for VARCHAR)

SELECT drawn FROM table_13741576_6 WHERE tries_for = '54';


Question: How many total units of Lanthanum were produced between 2018 and 2020?

CREATE TABLE production (year INT, element VARCHAR(10), quantity INT); INSERT INTO production (year, element, quantity) VALUES (2015, 'Lanthanum', 1200), (2016, 'Lanthanum', 1400), (2017, 'Lanthanum', 1500), (2018, 'Lanthanum', 1700), (2019, 'Lanthanum', 1800), (2020, 'Lanthanum', 2000), (2021, 'Lanthanum', 2200);

SELECT SUM(quantity) FROM production WHERE element = 'Lanthanum' AND year BETWEEN 2018 AND 2020;


Question: Generate PostgreSQL SQL for: What was the loss of the game that had a record of 3-3?

CREATE TABLE table_name_41 (loss VARCHAR, record VARCHAR)

SELECT loss FROM table_name_41 WHERE record = '3-3';


Question: What is the minimum number of followers for users who have posted more than 50 times in the United States?

SELECT MIN(follower_count) FROM users WHERE id IN (SELECT user_id FROM posts GROUP BY user_id HAVING COUNT(post_date) > 50) AND country = 'USA';


Question: Generate PostgreSQL SQL for: Tell me the average year for my queen

CREATE TABLE table_name_65 (year INTEGER, english_title VARCHAR)

SELECT AVG(year) FROM table_name_65 WHERE english_title = 'my queen';


Question: How many public parks have been created in each borough since 2015?

CREATE TABLE Parks (ParkID INT, ParkName VARCHAR(255), Borough VARCHAR(255), CreationDate DATE); INSERT INTO Parks (ParkID, ParkName, Borough, CreationDate) VALUES (1, 'Central Park', 'Manhattan', '2015-07-01'), (2, 'Prospect Park', 'Brooklyn', '2016-04-01'), (3, 'Van Cortlandt Park', 'Bronx', '2017-08-01');

SELECT COUNT(*), Borough FROM Parks WHERE CreationDate >= '2015-01-01' GROUP BY Borough;


Question: Add a new publication to the publications table for author with ID 5

CREATE TABLE authors (id INT, name VARCHAR(50)); INSERT INTO authors (id, name) VALUES (5, 'John Smith'); CREATE TABLE publications (id INT, title VARCHAR(50), year INT, author_id INT);

INSERT INTO publications (id, title, year, author_id) VALUES (101, 'New Publication', 2022, 5);


Question: What is the maximum salary in each department for employees who have been with the company for more than 10 years?

CREATE TABLE Employees (EmployeeID INT, Gender VARCHAR(10), Department VARCHAR(20), Salary DECIMAL(10,2), Tenure INT); INSERT INTO Employees (EmployeeID, Gender, Department, Salary, Tenure) VALUES (1, 'Male', 'IT', 75000.00, 12), (2, 'Female', 'IT', 70000.00, 5), (3, 'Non-binary', 'HR', 60000.00, 8);

SELECT Department, MAX(Salary) FROM Employees WHERE Tenure > 10 GROUP BY Department;


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

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

SELECT count(*) FROM (SELECT '["a","b","c",[1,2],null]'::jsonb -> -5) AS _sub;


Question: What is the average number of public participation events attended by citizens in each district for the year 2021?

SELECT district_id, AVG(total_events) as avg_events FROM (SELECT district_id, event_id, COUNT(*) as total_events FROM participation WHERE date >= '2021-01-01' AND date < '2022-01-01' GROUP BY district_id, event_id) as subquery GROUP BY district_id;


Question: What is the total number of military personnel by branch for each country?

CREATE TABLE MilitaryPersonnel (PersonnelID INT, PersonnelBranch VARCHAR(20), PersonnelCountry VARCHAR(30), PersonnelCount INT); INSERT INTO MilitaryPersonnel (PersonnelID, PersonnelBranch, PersonnelCountry, PersonnelCount) VALUES (1, 'Army', 'USA', 500000), (2, 'Navy', 'USA', 350000), (3, 'Air Force', 'Canada', 20000), (4, 'Marines', 'UK', 25000);

SELECT PersonnelBranch, PersonnelCountry, SUM(PersonnelCount) as Total FROM MilitaryPersonnel GROUP BY PersonnelBranch, PersonnelCountry;


Question: Generate PostgreSQL SQL for: What is the 2007 value with a 2r in 2012 and 1r in 2002?

SELECT 2007 FROM table_name_53 WHERE 2012 = '2r' AND 2002 = '1r';


Question: What is the earliest launch date for each aircraft model?

CREATE TABLE aircrafts (aircraft_id INT, model VARCHAR(50), launch_date DATE); INSERT INTO aircrafts (aircraft_id, model, launch_date) VALUES (1, 'Boeing 747', '2000-01-01'), (2, 'Airbus A320', '2010-01-01'), (3, 'Boeing 737', '1995-01-01'); 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 model, MIN(launch_date) as earliest_launch_date FROM aircrafts WHERE aircraft_id NOT IN (SELECT aircraft_id FROM accidents) GROUP BY model;


Question: Generate PostgreSQL SQL for: What park is Boardwalk Bullet located in?

CREATE TABLE table_2665085_1 (park VARCHAR, name VARCHAR)

SELECT park FROM table_2665085_1 WHERE name = 'Boardwalk Bullet';


Question: What is the number of public libraries in each county in the state of California, including their names and total book collections?

CREATE TABLE counties(id INT, name TEXT, state TEXT); INSERT INTO counties VALUES (1, 'County A', 'California'); INSERT INTO counties VALUES (2, 'County B', 'California'); INSERT INTO counties VALUES (3, 'County C', 'California'); CREATE TABLE libraries(id INT, county_id INT, name TEXT, total_books INT); INSERT INTO libraries VALUES (1, 1, 'Library A', 10000); INSERT INTO libraries VALUES (2, 1, 'Library B', 12000); INSERT INTO libraries VALUES (3, 2, 'Library C', 14000); INSERT INTO libraries VALUES (4, 3, 'Library D', 16000);

SELECT c.name as county_name, l.name as library_name, COUNT(*) as library_count, SUM(l.total_books) as total_books FROM counties c JOIN libraries l ON c.id = l.county_id WHERE c.state = 'California' GROUP BY c.name, l.name;


Question: Generate PostgreSQL SQL for: Who is Wayne Day's crew chief?

CREATE TABLE table_2182170_1 (crew_chief VARCHAR, listed_owner_s_ VARCHAR)

SELECT crew_chief FROM table_2182170_1 WHERE listed_owner_s_ = 'Wayne Day';


Question: Delete the record for 'capacity_building' table, where 'program_name' is 'Youth Mentorship'.

CREATE TABLE capacity_building (id INT, program_name VARCHAR(25)); INSERT INTO capacity_building (id, program_name) VALUES (1, 'Youth Mentorship'), (2, 'Leadership Development');

DELETE FROM capacity_building WHERE program_name = 'Youth Mentorship';


Question: What is the total number of patients diagnosed with Ebola in Democratic Republic of Congo in 2021?

CREATE TABLE Patients (ID INT, Gender VARCHAR(10), Disease VARCHAR(20), Country VARCHAR(30), Diagnosis_Date DATE); INSERT INTO Patients (ID, Gender, Disease, Country, Diagnosis_Date) VALUES (1, 'Male', 'Ebola', 'Democratic Republic of Congo', '2021-01-01');

SELECT COUNT(*) FROM Patients WHERE Disease = 'Ebola' AND Country = 'Democratic Republic of Congo' AND YEAR(Diagnosis_Date) = 2021;


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

-- Look for casts to/from the same type that aren't length coercion functions.
-- (We assume they are length coercions if they take multiple arguments.)
-- Such entries are not necessarily harmful, but they are useless.

SELECT *
FROM pg_cast c
WHERE castsource = casttarget AND castfunc = 0;

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


Question: PostgreSQL Ddl: show example 91.

CREATE TABLE measurement ( city_id int not null, logdate date not null, peaktemp int, unitsales int ) PARTITION BY RANGE (logdate);

Explanation: Example from PostgreSQL documentation on Ddl.


Question: PostgreSQL regression test 'json': Write the SELECT query (example 1).

SELECT '""'::json;				-- OK.
SELECT $$''$$::json;			-- ERROR, single quotes are not allowed
SELECT '"abc"'::json;			-- OK
SELECT '"abc'::json;			-- ERROR, quotes not closed
SELECT '"abc
def"'::json;					-- ERROR, unescaped newline in string constant
SELECT '"\n\"\\"'::json;		-- OK, legal escapes
SELECT '"\v"'::json;			-- ERROR, not a valid JSON escape

-- Check fast path for longer strings (at least 16 bytes long)
SELECT ('"'||repeat('.', 12)||'abc"')::json; -- OK
SELECT ('"'||repeat('.', 12)||'abc\n"')::json; -- OK, legal escapes

-- Test various lengths of strings to validate SIMD processing to escape
-- special chars in the JSON.
SELECT row_to_json(j)::jsonb FROM (
  SELECT left(E'abcdefghijklmnopqrstuv"\twxyz012345678', a) AS a
  FROM generate_series(0,37) a
) j;

-- see json_encoding test for input with unicode escapes

-- Numbers.
SELECT '1'::json;				-- OK
SELECT '0'::json;				-- OK
SELECT '01'::json;				-- ERROR, not valid according to JSON spec
SELECT '0.1'::json;				-- OK
SELECT '9223372036854775808'::json;	-- OK, even though it's too large for int8
SELECT '1e100'::json;			-- OK
SELECT '1.3e100'::json;			-- OK
SELECT '1f2'::json;				-- ERROR
SELECT '0.x1'::json;			-- ERROR
SELECT '1.3ex100'::json;		-- ERROR

-- Arrays.
SELECT '[]'::json;				-- OK
SELECT '[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]'::json;  -- OK
SELECT '[1,2]'::json;			-- OK
SELECT '[1,2,]'::json;			-- ERROR, trailing comma
SELECT '[1,2'::json;			-- ERROR, no closing bracket
SELECT '[1,[2]'::json;			-- ERROR, no closing bracket

-- Objects.
SELECT '{}'::json;				-- OK
SELECT '{"abc"}'::json;			-- ERROR, no value
SELECT '{"abc":1}'::json;		-- OK
SELECT '{1:"abc"}'::json;		-- ERROR, keys must be strings
SELECT '{"abc",1}'::json;		-- ERROR, wrong separator
SELECT '{"abc"=1}'::json;		-- ERROR, totally wrong separator
SELECT '{"abc"::1}'::json;		-- ERROR, another wrong separator
SELECT '{"abc":1,"def":2,"ghi":[3,4],"hij":{"klm":5,"nop":[6]}}'::json; -- OK
SELECT '{"abc":1:2}'::json;		-- ERROR, colon in wrong spot
SELECT '{"abc":1,3}'::json;		-- ERROR, no value

-- Recursion.
SET max_stack_depth = '100kB';
SELECT repeat('[', 10000)::json;
SELECT repeat('{"a":', 10000)::json;
RESET max_stack_depth;

-- Miscellaneous stuff.
SELECT 'true'::json;			-- OK
SELECT 'false'::json;			-- OK
SELECT 'null'::json;			-- OK
SELECT ' true '::json;			-- OK, even with extra whitespace
SELECT 'true false'::json;		-- ERROR, too many values
SELECT 'true, false'::json;		-- ERROR, too many values
SELECT 'truf'::json;			-- ERROR, not a keyword
SELECT 'trues'::json;			-- ERROR, not a keyword
SELECT ''::json;				-- ERROR, no value
SELECT '    '::json;			-- ERROR, no value

-- Multi-line JSON input to check ERROR reporting
SELECT '{
		"one": 1,
		"two":"two",
		"three":
		true}'::json; -- OK
SELECT '{
		"one": 1,
		"two":,"two",  -- ERROR extraneous comma before field "two"
		"three":
		true}'::json;
SELECT '{
		"one": 1,
		"two":"two",
		"averyveryveryveryveryveryveryveryveryverylongfieldname":}'::json;
-- ERROR missing value for last field

-- test non-error-throwing input
select pg_input_is_valid('{"a":true}', 'json');
select pg_input_is_valid('{"a":true', 'json');
select * from pg_input_error_info('{"a":true', 'json');

--constructors
-- array_to_json

SELECT array_to_json(array(select 1 as a));
SELECT array_to_json(array_agg(q),false) from (select x as b, x * 2 as c from generate_series(1,3) x) q;
SELECT array_to_json(array_agg(q),true) from (select x as b, x * 2 as c from generate_series(1,3) x) q;
SELECT array_to_json(array_agg(q),false)
  FROM ( SELECT $$a$$ || x AS b, y AS c,
               ARRAY[ROW(x.*,ARRAY[1,2,3]),
               ROW(y.*,ARRAY[4,5,6])] AS z
         FROM generate_series(1,2) x,
              generate_series(4,5) y) q;

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

SELECT count(*) FROM (SELECT '""'::json;				-- OK.
SELECT $$''$$::json;			-- ERROR, single quotes are not allowed
SELECT '"abc"'::json;			-- OK
SELECT '"abc'::json;			-- ERROR, quotes not closed
SELECT '"abc
def"'::json;					-- ERROR, unescaped newline in string constant
SELECT '"\n\"\\"'::json;		-- OK, legal escapes
SELECT '"\v"'::json;			-- ERROR, not a valid JSON escape

-- Check fast path for longer strings (at least 16 bytes long)
SELECT ('"'||repeat('.', 12)||'abc"')::json; -- OK
SELECT ('"'||repeat('.', 12)||'abc\n"')::json; -- OK, legal escapes

-- Test various lengths of strings to validate SIMD processing to escape
-- special chars in the JSON.
SELECT row_to_json(j)::jsonb FROM (
  SELECT left(E'abcdefghijklmnopqrstuv"\twxyz012345678', a) AS a
  FROM generate_series(0,37) a
) j;

-- see json_encoding test for input with unicode escapes

-- Numbers.
SELECT '1'::json;				-- OK
SELECT '0'::json;				-- OK
SELECT '01'::json;				-- ERROR, not valid according to JSON spec
SELECT '0.1'::json;				-- OK
SELECT '9223372036854775808'::json;	-- OK, even though it's too large for int8
SELECT '1e100'::json;			-- OK
SELECT '1.3e100'::json;			-- OK
SELECT '1f2'::json;				-- ERROR
SELECT '0.x1'::json;			-- ERROR
SELECT '1.3ex100'::json;		-- ERROR

-- Arrays.
SELECT '[]'::json;				-- OK
SELECT '[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]'::json;  -- OK
SELECT '[1,2]'::json;			-- OK
SELECT '[1,2,]'::json;			-- ERROR, trailing comma
SELECT '[1,2'::json;			-- ERROR, no closing bracket
SELECT '[1,[2]'::json;			-- ERROR, no closing bracket

-- Objects.
SELECT '{}'::json;				-- OK
SELECT '{"abc"}'::json;			-- ERROR, no value
SELECT '{"abc":1}'::json;		-- OK
SELECT '{1:"abc"}'::json;		-- ERROR, keys must be strings
SELECT '{"abc",1}'::json;		-- ERROR, wrong separator
SELECT '{"abc"=1}'::json;		-- ERROR, totally wrong separator
SELECT '{"abc"::1}'::json;		-- ERROR, another wrong separator
SELECT '{"abc":1,"def":2,"ghi":[3,4],"hij":{"klm":5,"nop":[6]}}'::json; -- OK
SELECT '{"abc":1:2}'::json;		-- ERROR, colon in wrong spot
SELECT '{"abc":1,3}'::json;		-- ERROR, no value

-- Recursion.
SET max_stack_depth = '100kB';
SELECT repeat('[', 10000)::json;
SELECT repeat('{"a":', 10000)::json;
RESET max_stack_depth;

-- Miscellaneous stuff.
SELECT 'true'::json;			-- OK
SELECT 'false'::json;			-- OK
SELECT 'null'::json;			-- OK
SELECT ' true '::json;			-- OK, even with extra whitespace
SELECT 'true false'::json;		-- ERROR, too many values
SELECT 'true, false'::json;		-- ERROR, too many values
SELECT 'truf'::json;			-- ERROR, not a keyword
SELECT 'trues'::json;			-- ERROR, not a keyword
SELECT ''::json;				-- ERROR, no value
SELECT '    '::json;			-- ERROR, no value

-- Multi-line JSON input to check ERROR reporting
SELECT '{
		"one": 1,
		"two":"two",
		"three":
		true}'::json; -- OK
SELECT '{
		"one": 1,
		"two":,"two",  -- ERROR extraneous comma before field "two"
		"three":
		true}'::json;
SELECT '{
		"one": 1,
		"two":"two",
		"averyveryveryveryveryveryveryveryveryverylongfieldname":}'::json;
-- ERROR missing value for last field

-- test non-error-throwing input
select pg_input_is_valid('{"a":true}', 'json');
select pg_input_is_valid('{"a":true', 'json');
select * from pg_input_error_info('{"a":true', 'json');

--constructors
-- array_to_json

SELECT array_to_json(array(select 1 as a));
SELECT array_to_json(array_agg(q),false) from (select x as b, x * 2 as c from generate_series(1,3) x) q;
SELECT array_to_json(array_agg(q),true) from (select x as b, x * 2 as c from generate_series(1,3) x) q;
SELECT array_to_json(array_agg(q),false)
  FROM ( SELECT $$a$$ || x AS b, y AS c,
               ARRAY[ROW(x.*,ARRAY[1,2,3]),
               ROW(y.*,ARRAY[4,5,6])] AS z
         FROM generate_series(1,2) x,
              generate_series(4,5) y) q) AS _sub;


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

Explanation: DML from PostgreSQL core regression test for Numeric.


Question: Generate PostgreSQL SQL for: What was the date of the premiere that had a 20.9 rating?

CREATE TABLE table_name_38 (premiere VARCHAR, rating VARCHAR)

SELECT premiere FROM table_name_38 WHERE rating = '20.9';


Question: Get the total energy consumption for each production site and the average energy consumption per chemical per site

CREATE TABLE Production_Sites (site_id INT, site_name VARCHAR(50), energy_consumption INT); CREATE TABLE Production_Chemicals (site_id INT, chemical_id INT, energy_consumption INT);

SELECT ps.site_name, SUM(ps.energy_consumption) as total_energy, AVG(pc.energy_consumption/cnt.chemical_count) as avg_energy_per_chemical FROM Production_Sites ps JOIN Production_Chemicals pc ON ps.site_id = pc.site_id JOIN (SELECT site_id, COUNT(DISTINCT chemical_id) as chemical_count FROM Production_Chemicals GROUP BY site_id) cnt ON ps.site_id = cnt.site_id GROUP BY ps.site_name;


Question: What is the average number of algorithmic fairness assessments conducted per month in India in 2022?

CREATE TABLE fairness_assessments (assessment_id INT, assessment_date DATE, country TEXT); INSERT INTO fairness_assessments (assessment_id, assessment_date, country) VALUES (1, '2022-01-02', 'India'), (2, '2022-02-15', 'India'), (3, '2022-03-27', 'India');

SELECT AVG(num_assessments) as avg_assessments_per_month FROM (SELECT COUNT(*) as num_assessments, EXTRACT(MONTH FROM assessment_date) as month FROM fairness_assessments WHERE country = 'India' AND assessment_date BETWEEN '2022-01-01' AND '2022-12-31' GROUP BY month) as subquery;


Question: List all climate mitigation initiatives in Africa in 2020 and their corresponding funding amounts.

CREATE TABLE climate_mitigation (year INT, country VARCHAR(50), initiative VARCHAR(50), amount FLOAT); INSERT INTO climate_mitigation (year, country, initiative, amount) VALUES (2020, 'Country X', 'Mitigation Initiative 1', 200000);

SELECT initiative, amount FROM climate_mitigation WHERE year = 2020 AND country = 'Africa';


Question: Update equipment status in 'equipment_maintenance' table

CREATE TABLE equipment_maintenance (equipment_id INTEGER PRIMARY KEY, last_maintenance_date DATE, next_maintenance_date DATE, completed_maintenance BOOLEAN, status TEXT);

UPDATE equipment_maintenance SET status = 'Operational' WHERE equipment_id = 1 AND completed_maintenance = TRUE;


Question: Generate PostgreSQL SQL for: What's the Bulgarian word for september?

CREATE TABLE table_name_56 (bulgarian_name VARCHAR, english_name VARCHAR)

SELECT bulgarian_name FROM table_name_56 WHERE english_name = 'september';


Question: Generate PostgreSQL SQL for: when the population was 1599, what was the census ranking?

CREATE TABLE table_170961_2 (census_ranking VARCHAR, population VARCHAR)

SELECT census_ranking FROM table_170961_2 WHERE population = 1599;


Question: What is the percentage of donors who donated more than $1000 in the year 2021 compared to the total number of donors in that year?

CREATE TABLE Donors (DonorID INT, DonorName TEXT, Amount DECIMAL(10,2), Year INT); INSERT INTO Donors (DonorID, DonorName, Amount, Year) VALUES (1, 'John Doe', 500.00, 2021), (2, 'Jane Smith', 1500.00, 2021), (3, 'Bob Johnson', 750.00, 2021);

SELECT (COUNT(DonorID) * 100.00 / (SELECT COUNT(DonorID) FROM Donors WHERE Year = 2021)) FROM Donors WHERE Amount > 1000 AND Year = 2021;


Question: How many mobile devices were sold in each state of the United States, for the month of July, 2022?

CREATE TABLE sales (sale_id INT, sale_date DATE, quantity INT, state VARCHAR(50));

SELECT EXTRACT(MONTH FROM sale_date) AS month, state, SUM(quantity) AS total_sales FROM sales WHERE YEAR(sale_date) = 2022 AND MONTH(sale_date) = 7 GROUP BY month, state;


Question: Generate PostgreSQL SQL for: Votes of 27,391 has which quotient?

CREATE TABLE table_name_10 (quotient VARCHAR, votes VARCHAR)

SELECT quotient FROM table_name_10 WHERE votes = '27,391';


Question: What is the maximum number of military bases in African countries?

CREATE TABLE military_bases (country VARCHAR(50), num_bases INT); INSERT INTO military_bases (country, num_bases) VALUES ('Egypt', 12), ('Algeria', 15), ('South Africa', 10), ('Morocco', 14), ('Sudan', 11), ('Libya', 8);

SELECT MAX(num_bases) FROM military_bases WHERE country IN ('Egypt', 'Algeria', 'South Africa', 'Morocco', 'Sudan', 'Libya');


Question: List all regions with network investments greater than $5000.

CREATE TABLE network_investments (region TEXT, investment_amount FLOAT);

SELECT region FROM network_investments WHERE investment_amount > 5000;


Question: Show a query using PostgreSQL contrib extension 'intarray' (example 26).

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


Question: How many schools are there in 'CityF' as of 2021?

CREATE TABLE Schools (City VARCHAR(20), Year INT, Number INT); INSERT INTO Schools (City, Year, Number) VALUES ('CityF', 2021, 30);

SELECT Number FROM Schools WHERE City = 'CityF' AND Year = 2021;


Question: Which fashion brands have the highest and lowest diversity scores for their product sizes?

CREATE TABLE DiversityScores (BrandID INT, DiversityScore INT);

SELECT FB.BrandName, DS.DiversityScore FROM FashionBrands FB INNER JOIN DiversityScores DS ON FB.BrandID = DS.BrandID ORDER BY DS.DiversityScore ASC, FB.BrandName ASC;


Question: Generate PostgreSQL SQL for: When did Kim Thompson win with 278 score?

CREATE TABLE table_name_87 (year INTEGER, score VARCHAR, champion VARCHAR)

SELECT SUM(year) FROM table_name_87 WHERE score = '278' AND champion = 'kim thompson';


Question: Delete all records from the 'surveys' table where 'survey_date' is in the year 2005

CREATE TABLE surveys (id INT PRIMARY KEY, mine_id VARCHAR(10), survey_date DATE); INSERT INTO surveys (id, mine_id, survey_date) VALUES (1, 'Mine_001', '2005-01-01'); INSERT INTO surveys (id, mine_id, survey_date) VALUES (2, 'Mine_002', '2006-01-01'); INSERT INTO surveys (id, mine_id, survey_date) VALUES (3, 'Mine_001', '2004-01-01');

DELETE FROM surveys WHERE YEAR(survey_date) = 2005;


Question: Show a SQL definition from the citus project (multi_sql_function, item 17).

-- test router executor parameterized sql functions
CREATE TABLE temp_table (
	key int,
	value int
);

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


Question: Generate PostgreSQL SQL for: When November is 153 what is the March number?

CREATE TABLE table_25235489_2 (march_27_29 VARCHAR, november_3 VARCHAR)

SELECT march_27_29 FROM table_25235489_2 WHERE november_3 = '153';


Question: How many size 30 jeans were sold in the last month?

SELECT COUNT(*) FROM sales_data WHERE jean_size = 30 AND sale_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH);


Question: What is the total number of emergency calls and crimes reported during natural disasters?

CREATE TABLE disasters (disaster_id INT, disaster_name VARCHAR(255), disaster_date DATE);CREATE TABLE emergency_calls (id INT, disaster_id INT, call_type VARCHAR(255), call_date DATE);CREATE TABLE crimes (id INT, disaster_id INT, crime_type VARCHAR(255), crime_date DATE);

SELECT 'Total emergency calls' AS metric, COUNT(ec.id) AS count FROM emergency_calls ec JOIN disasters d ON ec.disaster_id = d.disaster_id UNION ALL SELECT 'Total crimes' AS metric, COUNT(c.id) AS count FROM crimes c JOIN disasters d ON c.disaster_id = d.disaster_id;


Question: Generate PostgreSQL SQL for: How many Lanes have a Country of jamaica, and a Name of kerron stewart, and a Time larger than 22?

CREATE TABLE table_name_46 (lane INTEGER, time VARCHAR, country VARCHAR, name VARCHAR)

SELECT SUM(lane) FROM table_name_46 WHERE country = 'jamaica' AND name = 'kerron stewart' AND time > 22;


Question: Generate PostgreSQL SQL for: Name the released for pat mills

CREATE TABLE table_1620397_2 (released VARCHAR, author VARCHAR)

SELECT released FROM table_1620397_2 WHERE author = 'Pat Mills';


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

ALTER TABLESPACE index_space OWNER TO mary;

Explanation: PostgreSQL ALTER TABLESPACE command.


Question: Generate PostgreSQL SQL for: How many viewers are the when the draw is 3?

CREATE TABLE table_27994983_8 (viewers INTEGER, draw VARCHAR)

SELECT MAX(viewers) FROM table_27994983_8 WHERE draw = 3;


Question: List the ports that have been visited by vessels with a maximum cargo capacity of over 15000 tons.

CREATE TABLE Port_Visits (id INT, vessel VARCHAR(255), capacity INT, port VARCHAR(255), time DATETIME); INSERT INTO Port_Visits (id, vessel, capacity, port, time) VALUES (1, 'Sea Titan', 20000, 'Singapore', '2020-01-01 10:00:00'), (2, 'Ocean Wave', 12000, 'Sydney', '2020-02-15 15:30:00');

SELECT DISTINCT port FROM Port_Visits PV JOIN (SELECT vessel, capacity FROM Vessels WHERE capacity > 15000) V ON PV.vessel = V.vessel;


Question: Generate PostgreSQL SQL for: What city was the game held in when the opponent was Towson?

CREATE TABLE table_name_93 (city VARCHAR, opponent VARCHAR)

SELECT city FROM table_name_93 WHERE opponent = 'towson';


Question: Generate PostgreSQL SQL for: Which player is from Tampa, Florida?

CREATE TABLE table_name_68 (player VARCHAR, hometown VARCHAR)

SELECT player FROM table_name_68 WHERE hometown = 'tampa, florida';


Question: What is the total number of natural ingredients sourced from South America?

CREATE TABLE Ingredient_Sourcing (SupplierID INT, ProductID INT, Natural BOOLEAN, Region VARCHAR(50)); INSERT INTO Ingredient_Sourcing (SupplierID, ProductID, Natural, Region) VALUES (3001, 101, TRUE, 'South America'), (3002, 102, FALSE, 'South America'), (3003, 101, TRUE, 'South America'), (3004, 103, FALSE, 'South America'), (3005, 102, TRUE, 'South America');

SELECT SUM(Natural) as TotalNatural FROM Ingredient_Sourcing WHERE Region = 'South America';


Question: Generate PostgreSQL SQL for: What is the Name of the Space Telescope Terminated on March 1993?

CREATE TABLE table_name_31 (name VARCHAR, terminated VARCHAR)

SELECT name FROM table_name_31 WHERE terminated = 'march 1993';


Question: Generate PostgreSQL SQL for: What is the frequency of the station located in polangui, albay?

CREATE TABLE table_27588823_2 (frequency VARCHAR, location VARCHAR)

SELECT frequency FROM table_27588823_2 WHERE location = 'Polangui, Albay';


Question: Generate PostgreSQL SQL for: Which bullet has a Shoulder of 10.92 (.430)?

CREATE TABLE table_name_25 (bullet VARCHAR, shoulder VARCHAR)

SELECT bullet FROM table_name_25 WHERE shoulder = '10.92 (.430)';


Question: Generate PostgreSQL SQL for: Which Lost has Games larger than 7?

CREATE TABLE table_name_54 (lost INTEGER, games INTEGER)

SELECT AVG(lost) FROM table_name_54 WHERE games > 7;


Question: Generate PostgreSQL SQL for: What date was parliament assembled when John rudhale was first member?

CREATE TABLE table_15451122_2 (assembled VARCHAR, first_member VARCHAR)

SELECT assembled FROM table_15451122_2 WHERE first_member = 'John Rudhale';


Question: What are the bioprocess engineering companies that have received funding?

CREATE TABLE company (id INT, name VARCHAR(50), industry VARCHAR(50), location VARCHAR(50)); INSERT INTO company (id, name, industry, location) VALUES (1, 'GenTech', 'Genetic Research', 'San Francisco'); INSERT INTO company (id, name, industry, location) VALUES (2, 'BioEngineer', 'Bioprocess Engineering', 'Boston'); INSERT INTO company (id, name, industry, location) VALUES (3, 'BioSolutions', 'Bioprocess Engineering', 'Seattle'); CREATE TABLE funding (company_id INT, round VARCHAR(50), amount FLOAT); INSERT INTO funding (company_id, round, amount) VALUES (2, 'Seed', 3000000); INSERT INTO funding (company_id, round, amount) VALUES (3, 'Series A', 8000000);

SELECT c.name FROM company c JOIN funding f ON c.id = f.company_id WHERE c.industry = 'Bioprocess Engineering';


Question: Show a SQL definition from the citus project (multi_behavioral_analytics_create_table, item 43).

CREATE INDEX is_index3 ON users_table(value_1);


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

DELETE FROM foo WHERE f1 = 5
  RETURNING (SELECT max(old.f4 + x) FROM generate_series(1, 10) x) old_max,
            (SELECT max(new.f4 + x) FROM generate_series(1, 10) x) new_max;

Explanation: DML from PostgreSQL core regression test for Returning.


Question: Show the number of patients treated by 'Dr. Jane' and their respective conditions.

CREATE TABLE treatment (treatment_id INT, patient_id INT, condition VARCHAR(50), provider VARCHAR(50), date DATE); INSERT INTO treatment (treatment_id, patient_id, condition, provider, date) VALUES (1, 1, 'Anxiety Disorder', 'Dr. Jane', '2021-01-01'); INSERT INTO treatment (treatment_id, patient_id, condition, provider, date) VALUES (2, 1, 'PTSD', 'Dr. Bob', '2021-02-01');

SELECT COUNT(patient_id), condition FROM treatment WHERE provider = 'Dr. Jane' GROUP BY condition;


Question: What is the average number of military personnel in humanitarian assistance operations by country, for countries with more than 200 personnel?

CREATE TABLE HumanitarianAssistanceOperations (id INT, country VARCHAR(50), military_personnel INT);

SELECT country, AVG(military_personnel) FROM HumanitarianAssistanceOperations GROUP BY country HAVING COUNT(*) > 200;


Question: Show a SQL definition from the timescaledb project (bookend, item 6).

CREATE OR REPLACE FUNCTION _timescaledb_functions.bookend_serializefunc(internal)
RETURNS bytea
AS '@MODULE_PATHNAME@', 'ts_bookend_serializefunc'
LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;

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


Question: Find the average price of garments in each category in the garments table

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

SELECT category, AVG(price) as avg_price FROM garments GROUP BY category;


Question: Generate PostgreSQL SQL for: What is the sum of Points, when Year is after 1959, and when Class is 250cc?

CREATE TABLE table_name_42 (points INTEGER, year VARCHAR, class VARCHAR)

SELECT SUM(points) FROM table_name_42 WHERE year > 1959 AND class = '250cc';


Question: Delete records of donations and investments from the 'donations' and 'investments' tables with a value over 100000 for the 'amount' column.

CREATE TABLE donations (donation_id INT, donor_id INT, cause_id INT, amount DECIMAL(10, 2)); CREATE TABLE investments (investment_id INT, investor_id INT, sector_id INT, amount DECIMAL(10, 2));

DELETE FROM donations WHERE amount > 100000; DELETE FROM investments WHERE amount > 100000;


Question: What are the unique technology accessibility concerns for people with visual impairments in the accessibility table?

CREATE TABLE accessibility (id INT, disability VARCHAR(255), concern VARCHAR(255));

SELECT DISTINCT concern FROM accessibility WHERE disability = 'people with visual impairments';


Question: What is the maximum conservation status level for marine species in the Pacific Ocean?

CREATE TABLE Pacific_Species (species_name TEXT, location TEXT, conservation_status TEXT); INSERT INTO Pacific_Species (species_name, location, conservation_status) VALUES ('Hawaiian Monk Seal', 'Pacific Ocean', 'Endangered'), ('Green Sea Turtle', 'Pacific Ocean', 'Threatened');

SELECT MAX(conservation_status) FROM Pacific_Species;


Question: What is the maximum ESG score for investments in the education sector, broken down by year?

SELECT EXTRACT(YEAR FROM investment_date) as year, MAX(esg_score) as max_esg_score FROM investments WHERE sector = 'Education' GROUP BY year ORDER BY year ASC;


Question: Show a SQL definition from the postgrest project (jwt, item 8).

CREATE OR REPLACE FUNCTION jwt.algorithm_sign(signables text, secret text, algorithm text)
RETURNS text LANGUAGE sql AS $$
WITH
  alg AS (
    SELECT CASE
      WHEN algorithm = 'HS256' THEN 'sha256'
      WHEN algorithm = 'HS384' THEN 'sha384'
      WHEN algorithm = 'HS512' THEN 'sha512'
      ELSE '' END)  -- hmac throws error
SELECT jwt.url_encode(public.hmac(signables, secret, (select * FROM alg)));
$$;

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


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

CREATE TABLE table_name_60 (country VARCHAR, year_s__won VARCHAR)

SELECT country FROM table_name_60 WHERE year_s__won = '1977';


Question: How many animals are in the 'conservation_program' table?

CREATE TABLE conservation_program (id INT PRIMARY KEY, animal_name VARCHAR, num_animals INT);

SELECT SUM(num_animals) FROM conservation_program;


Question: How many halal-certified makeup products were sold in the last quarter?

CREATE TABLE Sales (id INT, product_id INT, sale_date DATE); CREATE TABLE Products (id INT, category TEXT, is_halal_certified BOOLEAN); INSERT INTO Sales (id, product_id, sale_date) VALUES (1, 1, '2022-01-05'), (2, 2, '2022-04-17'); INSERT INTO Products (id, category, is_halal_certified) VALUES (1, 'Makeup', true), (2, 'Skincare', false);

SELECT COUNT(*) FROM Sales JOIN Products ON Sales.product_id = Products.id WHERE is_halal_certified = true AND category = 'Makeup' AND sale_date >= '2022-01-01' AND sale_date <= '2022-03-31';


Question: What is the total number of electric vehicles sold in California and New York in 2020?

CREATE TABLE EVSales (Id INT PRIMARY KEY, Model VARCHAR(100), Year INT, State VARCHAR(2), UnitsSold INT); INSERT INTO EVSales (Id, Model, Year, State, UnitsSold) VALUES (1, 'Tesla Model 3', 2020, 'CA', 50000), (2, 'Tesla Model Y', 2020, 'CA', 45000), (3, 'Tesla Model S', 2020, 'CA', 15000), (4, 'Tesla Model X', 2020, 'CA', 12000), (5, 'Chevrolet Bolt', 2020, 'CA', 8000), (6, 'Nissan Leaf', 2020, 'CA', 7000), (7, 'Tesla Model 3', 2020, 'NY', 25000), (8, 'Tesla Model Y', 2020, 'NY', 20000), (9, 'Tesla Model S', 2020, 'NY', 5000), (10, 'Tesla Model X', 2020, 'NY', 4000), (11, 'Chevrolet Bolt', 2020, 'NY', 3000), (12, 'Nissan Leaf', 2020, 'NY', 2000);

SELECT SUM(UnitsSold) FROM EVSales WHERE Year = 2020 AND State IN ('CA', 'NY');


Question: Write the DDL statement from PostgreSQL regression test 'update' (example 47).

CREATE TABLE upsert_test_1 PARTITION OF upsert_test FOR VALUES IN (1);

Explanation: DDL from PostgreSQL core regression test for Update.


Question: What is the maximum number of games played by any player from South America?

CREATE TABLE Players (PlayerID INT, PlayerName VARCHAR(50), Age INT, Country VARCHAR(50), GamesPlayed INT); INSERT INTO Players (PlayerID, PlayerName, Age, Country, GamesPlayed) VALUES (1, 'John Doe', 25, 'USA', 100); INSERT INTO Players (PlayerID, PlayerName, Age, Country, GamesPlayed) VALUES (2, 'Jane Smith', 30, 'Canada', 200); INSERT INTO Players (PlayerID, PlayerName, Age, Country, GamesPlayed) VALUES (3, 'Pedro Alvarez', 35, 'Brazil', 300);

SELECT MAX(GamesPlayed) FROM Players WHERE Country IN ('Brazil', 'Argentina', 'Colombia');


Question: Generate PostgreSQL SQL for: What round was a player from Indiana picked?

CREATE TABLE table_name_71 (round VARCHAR, college VARCHAR)

SELECT round FROM table_name_71 WHERE college = 'indiana';


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

-- now create the partitions
CREATE TABLE date_partition_2006 PARTITION OF date_partitioned_table FOR VALUES FROM ('2006-01-01') TO ('2007-01-01');


Question: Write the DML statement from PostgreSQL regression test 'updatable_views' (example 3).

INSERT INTO base_tbl SELECT i, 'Row ' || i FROM generate_series(-2, 2) g(i);

Explanation: DML from PostgreSQL core regression test for Updatable Views.


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

CREATE TABLE Policyholders (ID INT, Name VARCHAR(50), Age INT, Gender VARCHAR(10), City VARCHAR(50), State VARCHAR(20), ZipCode VARCHAR(10)); CREATE TABLE Claims (ID INT, PolicyholderID INT, ClaimAmount DECIMAL(10,2), ClaimDate DATE);

SELECT AVG(Claims.ClaimAmount) FROM Claims JOIN Policyholders ON Claims.PolicyholderID = Policyholders.ID WHERE Policyholders.State = 'California';


Question: Generate PostgreSQL SQL for: Who was the away team on 10 January 1979 who had a tie no of 17?

CREATE TABLE table_name_82 (away_team VARCHAR, date VARCHAR, tie_no VARCHAR)

SELECT away_team FROM table_name_82 WHERE date = '10 january 1979' AND tie_no = '17';


Question: What is the total length of highways in India?

CREATE TABLE Highway (id INT, name VARCHAR(50), length FLOAT, country VARCHAR(50)); INSERT INTO Highway (id, name, length, country) VALUES (1, 'Golden Quadrilateral', 5846, 'India');

SELECT SUM(length) FROM Highway WHERE country = 'India';


Question: Generate PostgreSQL SQL for: What is the Rank of Qi Hui?

CREATE TABLE table_name_52 (rank VARCHAR, name VARCHAR)

SELECT COUNT(rank) FROM table_name_52 WHERE name = 'qi hui';


Question: Which teacher professional development courses were taken by teachers in district 101?

CREATE TABLE teacher_pd_courses (teacher_id INT, course_id INT, district_id INT); INSERT INTO teacher_pd_courses (teacher_id, course_id, district_id) VALUES (1, 1001, 101), (2, 1002, 101), (3, 1003, 101), (4, 1004, 102), (5, 1005, 103); CREATE TABLE courses (course_id INT, course_name VARCHAR(255)); INSERT INTO courses (course_id, course_name) VALUES (1001, 'Course 1'), (1002, 'Course 2'), (1003, 'Course 3'), (1004, 'Course 4'), (1005, 'Course 5');

SELECT c.course_name FROM teacher_pd_courses t JOIN courses c ON t.course_id = c.course_id WHERE t.district_id = 101;


Question: Update the gender of multiple players

CREATE TABLE Players (PlayerID INT PRIMARY KEY, Name VARCHAR(50), Age INT, Gender VARCHAR(10)); INSERT INTO Players (PlayerID, Name, Age, Gender) VALUES (1, 'John Doe', 25, 'Male'); INSERT INTO Players (PlayerID, Name, Age, Gender) VALUES (2, 'Jane Doe', 30, 'Female'); INSERT INTO Players (PlayerID, Name, Age, Gender) VALUES (3, 'Alex Smith', 22, 'Male');

UPDATE Players SET Gender = 'Non-binary' WHERE PlayerID IN (1, 3);


Question: What is the total number of comments on posts in the 'beauty' category on Instagram?

CREATE TABLE post_data (post_id INT, category VARCHAR(50), platform VARCHAR(20)); INSERT INTO post_data (post_id, category, platform) VALUES (1, 'beauty', 'Instagram'), (2, 'fashion', 'Instagram'); CREATE TABLE post_comments (comment_id INT, post_id INT, platform VARCHAR(20)); INSERT INTO post_comments (comment_id, post_id, platform) VALUES (1, 1, 'Instagram'), (2, 1, 'Instagram'), (3, 2, 'Instagram');

SELECT SUM(comment_id) FROM post_comments INNER JOIN post_data ON post_comments.post_id = post_data.post_id WHERE post_data.category = 'beauty' AND post_data.platform = 'Instagram';


Question: Find the number of unique artifact types per excavation site?

CREATE TABLE Sites (SiteID INT, SiteName TEXT); INSERT INTO Sites (SiteID, SiteName) VALUES (1, 'Site-A'), (2, 'Site-B'), (3, 'Site-C'); CREATE TABLE Artifacts (ArtifactID INT, ArtifactName TEXT, SiteID INT, ArtifactType TEXT); INSERT INTO Artifacts (ArtifactID, ArtifactName, SiteID, ArtifactType) VALUES (1, 'Pottery Shard', 1, 'Ceramic'), (2, 'Bronze Arrowhead', 2, 'Metal'), (3, 'Flint Tool', 3, 'Stone'), (4, 'Ancient Coin', 1, 'Metal'), (5, 'Stone Hammer', 2, 'Stone');

SELECT Sites.SiteName, COUNT(DISTINCT Artifacts.ArtifactType) AS UniqueArtifactTypes FROM Sites INNER JOIN Artifacts ON Sites.SiteID = Artifacts.SiteID GROUP BY Sites.SiteName;


Question: Generate PostgreSQL SQL for: What was the result of the December 15, 2002 game?

CREATE TABLE table_name_66 (result VARCHAR, date VARCHAR)

SELECT result FROM table_name_66 WHERE date = 'december 15, 2002';


Question: Generate PostgreSQL SQL for: Which Date has a Surface of clay, and a Score of 6–3, 5–7, 2–6?

CREATE TABLE table_name_89 (date VARCHAR, surface VARCHAR, score VARCHAR)

SELECT date FROM table_name_89 WHERE surface = 'clay' AND score = '6–3, 5–7, 2–6';


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

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

SELECT count(*) FROM (SELECT 1 AS one WHERE 1 IN (SELECT 1)) AS _sub;


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

-- Create the operator class
CREATE OPERATOR CLASS gist_bytea_ops
DEFAULT FOR TYPE bytea USING gist
AS
	OPERATOR	1	<  ,
	OPERATOR	2	<= ,
	OPERATOR	3	=  ,
	OPERATOR	4	>= ,
	OPERATOR	5	>  ,
	OPERATOR	6	<> ,
	FUNCTION	1	gbt_bytea_consistent (internal, bytea, int2, oid, internal),
	FUNCTION	2	gbt_bytea_union (internal, internal),
	FUNCTION	3	gbt_bytea_compress (internal),
	FUNCTION	4	gbt_var_decompress (internal),
	FUNCTION	5	gbt_bytea_penalty (internal, internal, internal),
	FUNCTION	6	gbt_bytea_picksplit (internal, internal),
	FUNCTION	7	gbt_bytea_same (gbtreekey_var, gbtreekey_var, internal),
	FUNCTION	9	gbt_var_fetch (internal),
	FUNCTION	11	gbt_bytea_sortsupport (internal),
	FUNCTION	12 ("any", "any") gist_translate_cmptype_btree (int),
	STORAGE			gbtreekey_var;

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


Question: What is the maximum ticket price for an art exhibit in Paris?

CREATE TABLE Exhibits (exhibit_id INT, city VARCHAR(50), price DECIMAL(5,2)); INSERT INTO Exhibits (exhibit_id, city, price) VALUES (1, 'Paris', 45.99), (2, 'London', 32.49), (3, 'Berlin', 50.00);

SELECT MAX(price) FROM Exhibits WHERE city = 'Paris';


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

-- test hypertable classification when query is in an inlineable function

\set PREFIX 'EXPLAIN (buffers off, costs off)'

CREATE TABLE test (a int, b bigint NOT NULL);


Question: Which cetacean species have been sighted in the same location more than once in the Survey table?

CREATE TABLE Survey ( id INT PRIMARY KEY, species_id INT, location VARCHAR(255), sighted_date DATE); CREATE TABLE Species ( id INT PRIMARY KEY, name VARCHAR(255), family VARCHAR(255), population INT);

SELECT Survey.location, Species.name FROM Survey JOIN Species ON Survey.species_id = Species.id GROUP BY Survey.location, Species.name HAVING COUNT(Survey.id) > 1 WHERE Species.family = 'Cetacean';


Question: What was the average monthly CO2 emission for each manufacturing facility in 2021?

CREATE TABLE co2_emissions (facility_id INT, facility_name VARCHAR(255), emission_date DATE, co2_emission DECIMAL(10,2)); INSERT INTO co2_emissions (facility_id, facility_name, emission_date, co2_emission) VALUES (1, 'Facility A', '2021-01-01', 500.00), (2, 'Facility B', '2021-02-01', 700.00), (3, 'Facility C', '2021-03-01', 800.00);

SELECT facility_name, AVG(co2_emission) as avg_monthly_emission FROM co2_emissions WHERE emission_date BETWEEN '2021-01-01' AND '2021-12-31' GROUP BY facility_name;


Question: Generate PostgreSQL SQL for: I want the tyres for hans binder

CREATE TABLE table_name_46 (tyres VARCHAR, driver VARCHAR)

SELECT tyres FROM table_name_46 WHERE driver = 'hans binder';


Question: How many 'safety_incidents' were reported in 'Site B' in the 'SafetyIncidents' table for '2022'?

CREATE TABLE SafetyIncidents (id INT, site VARCHAR(255), year INT, safety_incidents INT); INSERT INTO SafetyIncidents (id, site, year, safety_incidents) VALUES (1, 'Site A', 2021, 2), (2, 'Site B', 2022, 3), (3, 'Site A', 2022, 1);

SELECT SUM(safety_incidents) FROM SafetyIncidents WHERE site = 'Site B' AND year = 2022;


Question: Provide the total area of plantations in the Northern region.

CREATE TABLE plantations (id INT, name VARCHAR(255), acres FLOAT, region VARCHAR(255)); INSERT INTO plantations (id, name, acres, region) VALUES (1, 'Maplewood', 500.3, 'North'); INSERT INTO plantations (id, name, acres, region) VALUES (2, 'Pinehill', 700.5, 'South');

SELECT SUM(acres) FROM plantations WHERE region = 'North';


Question: Generate PostgreSQL SQL for: What is the Date for the Away team University?

CREATE TABLE table_name_73 (date VARCHAR, away_team VARCHAR)

SELECT date FROM table_name_73 WHERE away_team = 'university';


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

select interval '-9223372036854775808 microseconds -0.1 days';

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

SELECT count(*) FROM (select interval '-9223372036854775808 microseconds -0.1 days') AS _sub;


Question: List the names and launch dates of satellites manufactured by Japanese companies.

CREATE TABLE Manufacturer (name VARCHAR(50), country VARCHAR(50), domain VARCHAR(20)); INSERT INTO Manufacturer (name, country, domain) VALUES ('Mitsubishi Heavy Industries', 'Japan', 'Aerospace'); INSERT INTO Manufacturer (name, country, domain) VALUES ('Nissan Space Agency', 'Japan', 'Aerospace');

SELECT s.name, s.launch_date FROM Satellite s INNER JOIN Manufacturer m ON s.manufacturer = m.name WHERE m.country = 'Japan';


Question: How many walruses are in the Arctic Ocean?

CREATE TABLE Animals (name VARCHAR(50), species VARCHAR(50), location VARCHAR(50)); INSERT INTO Animals (name, species, location) VALUES ('Seal 1', 'Seal', 'Arctic Ocean'), ('Seal 2', 'Seal', 'Arctic Ocean'), ('Walrus 1', 'Walrus', 'Arctic Ocean');

SELECT COUNT(*) FROM Animals WHERE species = 'Walrus' AND location = 'Arctic Ocean';


Question: Generate PostgreSQL SQL for: what's the report with rnd being 4

CREATE TABLE table_1140074_2 (report VARCHAR, rnd VARCHAR)

SELECT report FROM table_1140074_2 WHERE rnd = 4;


Question: Generate PostgreSQL SQL for: which countries did participated in both Friendly and Tournament type competitions.

CREATE TABLE competition (country VARCHAR, competition_type VARCHAR)

SELECT country FROM competition WHERE competition_type = 'Friendly' INTERSECT SELECT country FROM competition WHERE competition_type = 'Tournament';


Question: Delete the existing high-speed train route from Rome to Milan

CREATE TABLE high_speed_rail_routes (id INT PRIMARY KEY, route_name VARCHAR(255), departure_city VARCHAR(255), destination_city VARCHAR(255), distance INT, avg_speed INT);

DELETE FROM high_speed_rail_routes WHERE route_name = 'Rome-Milan Express';


Question: Generate PostgreSQL SQL for: Which event has Philadelphia, PA as the location and 41 days held?

CREATE TABLE table_name_39 (event VARCHAR, location VARCHAR, days_held VARCHAR)

SELECT event FROM table_name_39 WHERE location = 'philadelphia, pa' AND days_held = 41;


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

/* AttributeError at toplevel used to give segfaults with the traceback
*/
CREATE FUNCTION toplevel_attribute_error() RETURNS void AS
$$
plpy.nonexistent
$$ LANGUAGE plpython3u;

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


Question: Generate PostgreSQL SQL for: What is the top attendance for weeks past 2 on october 29, 1961?

CREATE TABLE table_name_57 (attendance INTEGER, week VARCHAR, date VARCHAR)

SELECT MAX(attendance) FROM table_name_57 WHERE week > 2 AND date = 'october 29, 1961';


Question: What is the maximum speed reached by a shared bike in New York City?

CREATE TABLE shared_bikes (bike_id INT, max_speed FLOAT, registration_date TIMESTAMP, city VARCHAR(50)); INSERT INTO shared_bikes (bike_id, max_speed, registration_date, city) VALUES (1, 30.0, '2021-01-01', 'New York City'), (2, 35.0, '2021-01-02', 'New York City');

SELECT MAX(max_speed) FROM shared_bikes WHERE city = 'New York City';


Question: Generate PostgreSQL SQL for: I want the control trailers for 1931 with builder of grcw

CREATE TABLE table_name_45 (Control VARCHAR, year VARCHAR, builder VARCHAR)

SELECT Control AS trailers FROM table_name_45 WHERE year = '1931' AND builder = 'grcw';


Question: Compare the CO2 emissions of the transportation sector in Japan and South Africa.

CREATE TABLE co2_emissions (country VARCHAR(20), sector VARCHAR(20), co2_emissions INT); INSERT INTO co2_emissions (country, sector, co2_emissions) VALUES ('Japan', 'transportation', 240000), ('South Africa', 'transportation', 180000);

SELECT co2_emissions FROM co2_emissions WHERE country = 'Japan' INTERSECT SELECT co2_emissions FROM co2_emissions WHERE country = 'South Africa';


Question: Generate PostgreSQL SQL for: What position did Garion Weller hold in 2012?

CREATE TABLE table_name_23 (position VARCHAR)

SELECT position FROM table_name_23 WHERE 2012 = 'garion weller';


Question: What was the average speed of Vessel A?

CREATE TABLE Vessels (ID VARCHAR(10), Name VARCHAR(20), Type VARCHAR(20), Max_Speed FLOAT); INSERT INTO Vessels (ID, Name, Type, Max_Speed) VALUES ('1', 'Vessel A', 'Cargo', 20.5);

SELECT AVG(Max_Speed) FROM Vessels WHERE Name = 'Vessel A';


Question: Delete all routes associated with vessels that have a license_number of a captain who is under 30 years old.

CREATE TABLE Vessel (id INT, name VARCHAR(50), type VARCHAR(50), length FLOAT); CREATE TABLE Captain (id INT, name VARCHAR(50), age INT, license_number VARCHAR(50), VesselId INT); CREATE TABLE Route (id INT, departure_port VARCHAR(50), arrival_port VARCHAR(50), distance FLOAT, VesselId INT);

DELETE FROM Route WHERE VesselId IN (SELECT VesselId FROM Captain WHERE age < 30);


Question: How many lawyers are in the 'lawyers' table?

CREATE TABLE lawyers (id INT, name VARCHAR(50), is_pro_bono BOOLEAN); INSERT INTO lawyers (id, name, is_pro_bono) VALUES (1, 'John Smith', FALSE), (2, 'Jane Doe', TRUE), (3, 'Michael Lee', FALSE);


Question: Create a table for health equity metrics by race

CREATE TABLE health_equity_race (id INT PRIMARY KEY, state VARCHAR(2), year INT, race VARCHAR(20), disparity_rate FLOAT);

CREATE TABLE if not exists health_equity_race_new AS SELECT * FROM health_equity_race WHERE FALSE;


Question: Generate PostgreSQL SQL for: List the total number of years that have a score of 3–6, 4–6, 2–6.

CREATE TABLE table_2201724_1 (year VARCHAR, score_in_the_final VARCHAR)

SELECT COUNT(year) FROM table_2201724_1 WHERE score_in_the_final = '3–6, 4–6, 2–6';


Question: Generate PostgreSQL SQL for: How many fatalities does Italy have?

CREATE TABLE table_name_50 (fatalities VARCHAR, country VARCHAR)

SELECT fatalities FROM table_name_50 WHERE country = 'italy';


Question: Generate PostgreSQL SQL for: I want the average pages for  ISBN of 978-0-9766580-5-4

CREATE TABLE table_name_77 (pages INTEGER, isbn VARCHAR)

SELECT AVG(pages) FROM table_name_77 WHERE isbn = '978-0-9766580-5-4';


Question: Which investment strategies have had a total transaction value of over 50000 in the past month in an asset management firm?

CREATE TABLE investment_strategies (strategy_id INT, name VARCHAR(255)); CREATE TABLE asset_management_transactions (transaction_id INT, strategy_id INT, amount DECIMAL(10,2), trans_date DATE);

SELECT investment_strategies.name FROM investment_strategies INNER JOIN asset_management_transactions ON investment_strategies.strategy_id = asset_management_transactions.strategy_id WHERE asset_management_transactions.trans_date >= NOW() - INTERVAL '1 month' GROUP BY investment_strategies.name HAVING SUM(asset_management_transactions.amount) > 50000;


Question: Which energy efficiency projects have type 'Insulation'?

CREATE TABLE efficiency_type (name TEXT, location TEXT, type TEXT); INSERT INTO efficiency_type (name, location, type) VALUES ('Project A', 'Country O', 'Lighting'), ('Project B', 'Country P', 'Insulation'), ('Project C', 'Country Q', 'HVAC');

SELECT * FROM efficiency_type WHERE type = 'Insulation';


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

SELECT 'hawkeye' NOT LIKE 'H%' AS "true";

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

SELECT count(*) FROM (SELECT 'hawkeye' NOT LIKE 'H%' AS "true") AS _sub;


Question: What is the total production of indigenous food systems in each continent?

CREATE TABLE indigenous_production (continent VARCHAR(255), production INT); INSERT INTO indigenous_production (continent, production) VALUES ('Continent1', 2500), ('Continent2', 3200), ('Continent3', 1800); CREATE VIEW indigenous_systems_view AS SELECT * FROM indigenous_production WHERE production > 1500;

SELECT continent FROM indigenous_systems_view;


Question: Generate PostgreSQL SQL for: What is the name of the country with less than 9.033 for swimsuit, 8.611 for interview and preliminary is less than 8.87?

CREATE TABLE table_name_50 (country VARCHAR, preliminary VARCHAR, swimsuit VARCHAR, interview VARCHAR)

SELECT country FROM table_name_50 WHERE swimsuit < 9.033 AND interview = 8.611 AND preliminary < 8.87;


Question: What is the number of articles about immigration published in "El País" in the first quarter of 2021?

CREATE TABLE articles (id INT, title TEXT, publication TEXT, year INT, month INT, day INT, topic TEXT); INSERT INTO articles (id, title, publication, year, month, day, topic) VALUES (1, 'Article 1', 'El País', 2021, 1, 1, 'Immigration'); INSERT INTO articles (id, title, publication, year, month, day, topic) VALUES (2, 'Article 2', 'El País', 2021, 1, 2, 'Immigration'); INSERT INTO articles (id, title, publication, year, month, day, topic) VALUES (3, 'Article 3', 'El País', 2021, 2, 1, 'Politics');

SELECT COUNT(*) FROM articles WHERE publication = 'El País' AND topic = 'Immigration' AND year = 2021 AND month BETWEEN 1 AND 3;


Question: Generate PostgreSQL SQL for: Can you tell me the Out of that has the Source of united nations, and the Rank larger than 47, and the Year smaller than 2003?

CREATE TABLE table_name_31 (out_of VARCHAR, year VARCHAR, source VARCHAR, rank VARCHAR)

SELECT out_of FROM table_name_31 WHERE source = 'united nations' AND rank > 47 AND year < 2003;


Question: What is the total production volume of Samarium in Canada and the USA combined?

CREATE TABLE Samarium_Production (id INT, year INT, country VARCHAR(20), production_volume INT);

SELECT SUM(production_volume) FROM Samarium_Production WHERE country IN ('Canada', 'USA');


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

CREATE OPERATOR <= (
    LEFTARG    = CITEXT,
    RIGHTARG   = CITEXT,
    NEGATOR    = >,
    COMMUTATOR = >=,
    PROCEDURE  = citext_le,
    RESTRICT   = scalarltsel,
    JOIN       = scalarltjoinsel
);


Question: Delete all records from the 'weapons' table where the 'origin' is 'Russia'

CREATE TABLE weapons (id INT PRIMARY KEY, name VARCHAR(255), origin VARCHAR(255)); INSERT INTO weapons (id, name, origin) VALUES (1, 'AK-47', 'Russia'), (2, 'RPG-7', 'Russia'), (3, 'Mig-29', 'Russia');

DELETE FROM weapons WHERE origin = 'Russia';


Question: What is the minimum water consumption in the public sector in Alberta?

CREATE TABLE public_sector (id INT, province VARCHAR(20), water_consumption FLOAT); INSERT INTO public_sector (id, province, water_consumption) VALUES (1, 'Alberta', 100000000), (2, 'Alberta', 90000000), (3, 'Alberta', 80000000);

SELECT MIN(water_consumption) FROM public_sector WHERE province = 'Alberta';


Question: Generate PostgreSQL SQL for: What is the Weight of the player with a Block larger than 328, Spike greater than 375 and Height larger than 207?

CREATE TABLE table_name_28 (weight VARCHAR, spike VARCHAR, block VARCHAR, height VARCHAR)

SELECT COUNT(weight) FROM table_name_28 WHERE block > 328 AND height > 207 AND spike > 375;


Question: What is the mortality rate for each infectious disease in Africa?

CREATE TABLE MortalityRates (Disease VARCHAR(255), Continent VARCHAR(255), MortalityRate FLOAT); INSERT INTO MortalityRates (Disease, Continent, MortalityRate) VALUES ('Malaria', 'Africa', 0.6), ('Tuberculosis', 'Africa', 0.3), ('HIV/AIDS', 'Africa', 0.7), ('Hepatitis', 'Africa', 0.1), ('Influenza', 'Africa', 0.01);

SELECT Disease, MortalityRate FROM MortalityRates WHERE Continent = 'Africa';


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

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


Question: Generate PostgreSQL SQL for: Show different carriers of phones together with the number of phones with each carrier.

SELECT Carrier, COUNT(*) FROM phone GROUP BY Carrier;


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

-- Unicode variant

CREATE FUNCTION stupid7u() RETURNS trigger
AS $$
    TD["new"] = {'v': 'foo', 'a': 'bar'}
    return "MODIFY"
$$ LANGUAGE plpython3u;

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


Question: Generate PostgreSQL SQL for: What is the Catalog Number is for the Japan region?

CREATE TABLE table_name_59 (catalog VARCHAR, region VARCHAR)

SELECT catalog FROM table_name_59 WHERE region = 'japan';


Question: List the employees who have a higher salary than the average salary in the Sales department.

CREATE TABLE Employees (EmployeeID INT, Salary DECIMAL(10,2), Department VARCHAR(50)); INSERT INTO Employees (EmployeeID, Salary, Department) VALUES (1, 90000.00, 'Sales'), (2, 80000.00, 'Sales');

SELECT * FROM Employees WHERE Salary > (SELECT AVG(Salary) FROM Employees WHERE Department = 'Sales');


Question: Update the location of a heritage site in the 'heritage_sites' table

CREATE TABLE heritage_sites (id INT PRIMARY KEY, name VARCHAR(255), location VARCHAR(255), year INT);

UPDATE heritage_sites SET location = 'Scotland' WHERE id = 1;


Question: Generate PostgreSQL SQL for: how many for christer tornell where the total is 30?

CREATE TABLE table_28677723_11 (christer_tornell VARCHAR, total VARCHAR)

SELECT COUNT(christer_tornell) FROM table_28677723_11 WHERE total = 30;


Question: What is the total number of research stations in the Arctic region?

CREATE TABLE ResearchStations (station_name varchar(50), region varchar(50), operational_status varchar(50));

SELECT COUNT(DISTINCT station_name) AS total_stations FROM ResearchStations WHERE region LIKE '%Arctic%';


Question: Generate PostgreSQL SQL for: What is the result of the International Friendly competition on May 15, 1966?

CREATE TABLE table_name_89 (result VARCHAR, competition VARCHAR, date VARCHAR)

SELECT result FROM table_name_89 WHERE competition = 'international friendly' AND date = 'may 15, 1966';


Question: Identify the economic diversification efforts in West Africa with an investment of over 5 million USD.

CREATE TABLE DiversificationEfforts (id INT, effort_name TEXT, location TEXT, investment FLOAT); INSERT INTO DiversificationEfforts (id, effort_name, location, investment) VALUES (1, 'Renewable Energy West Africa', 'West Africa', 5500000); INSERT INTO DiversificationEfforts (id, effort_name, location, investment) VALUES (2, 'Tourism Development West Africa', 'West Africa', 4000000); INSERT INTO DiversificationEfforts (id, effort_name, location, investment) VALUES (3, 'Mining West Africa', 'West Africa', 3500000);

SELECT effort_name, location FROM DiversificationEfforts WHERE investment > 5000000 AND location LIKE '%West Africa%';


Question: List the number of community development projects in 'rural_development' database, grouped by region and project type.

CREATE TABLE projects (id INT, region TEXT, project_type TEXT, start_date DATE, end_date DATE);

SELECT region, project_type, COUNT(*) FROM projects GROUP BY region, project_type;


Question: Generate PostgreSQL SQL for: where was the abbas family and the pickering family located

CREATE TABLE table_19897294_9 (location_s_ VARCHAR, family_families VARCHAR)

SELECT location_s_ FROM table_19897294_9 WHERE family_families = 'The Abbas Family and The Pickering Family';


Question: Delete size records for customers not fitting standard sizes

CREATE TABLE CustomerSizes (CustomerID INT, Size TEXT); INSERT INTO CustomerSizes (CustomerID, Size) VALUES (1, 'XS'), (2, 'S'), (3, 'M');

DELETE FROM CustomerSizes WHERE Size NOT IN ('XS', 'S', 'M');


Question: Generate PostgreSQL SQL for: What are McCain's Percent when Obama has 36.47%?

CREATE TABLE table_20688030_1 (mccain_percentage VARCHAR, obama_percentage VARCHAR)

SELECT mccain_percentage FROM table_20688030_1 WHERE obama_percentage = '36.47%';


Question: pgTAP test for Runtests (assertion 7).

CREATE OR REPLACE FUNCTION whatever.setup() RETURNS SETOF TEXT AS $$
    SELECT collect_tap(ARRAY[
        pass('setup'),
        (SELECT is( MAX(id), NULL, 'Should be nothing in the test table') FROM whatever.foo)
    ]);
$$ LANGUAGE SQL;

Explanation: SQL assertion from pgTAP test suite for Runtests.


Question: What is the number of customers with financial capability in South America?

CREATE TABLE financial_capability_south_america (id INT, customer_id INT, country VARCHAR(255), capable BOOLEAN); INSERT INTO financial_capability_south_america (id, customer_id, country, capable) VALUES (1, 6001, 'Brazil', true), (2, 6002, 'Argentina', false), (3, 6003, 'Colombia', true);

SELECT COUNT(*) FROM financial_capability_south_america WHERE capable = true AND country IN ('Brazil', 'Argentina', 'Colombia');


Question: Generate PostgreSQL SQL for: Which country is dated October 20, 1976?

CREATE TABLE table_name_83 (country VARCHAR, date VARCHAR)

SELECT country FROM table_name_83 WHERE date = 'october 20, 1976';


Question: Calculate the average food safety inspection score for restaurants in a particular city in 2020.

CREATE TABLE restaurant (restaurant_id INT, name TEXT, city TEXT, inspection_score INT); INSERT INTO restaurant (restaurant_id, name, city, inspection_score) VALUES (1, 'Restaurant A', 'San Francisco', 90), (2, 'Restaurant B', 'New York', 85), (3, 'Restaurant C', 'San Francisco', 80), (4, 'Restaurant D', 'Chicago', 95), (5, 'Restaurant E', 'New York', 88);

SELECT city, AVG(inspection_score) AS avg_inspection_score FROM restaurant WHERE city = 'San Francisco' AND EXTRACT(YEAR FROM last_inspection_date) = 2020 GROUP BY city;


Question: Calculate the landfill capacity utilization for the city of Los Angeles in 2020

CREATE TABLE landfill_capacity (city VARCHAR(20), year INT, landfill_capacity FLOAT, waste_generated FLOAT);INSERT INTO landfill_capacity (city, year, landfill_capacity, waste_generated) VALUES ('Los Angeles', 2019, 5000000, 3000000), ('Los Angeles', 2020, 5000000, 3200000), ('Los Angeles', 2021, 5000000, 3400000), ('San Diego', 2019, 4000000, 2500000), ('San Diego', 2020, 4000000, 2700000), ('San Diego', 2021, 4000000, 2900000);

SELECT (waste_generated / landfill_capacity) * 100 FROM landfill_capacity WHERE city = 'Los Angeles' AND year = 2020;


Question: Generate PostgreSQL SQL for: I want the time/retired for Grid of 13

CREATE TABLE table_name_59 (time_retired VARCHAR, grid VARCHAR)

SELECT time_retired FROM table_name_59 WHERE grid = 13;


Question: What is the average revenue per day for a specific restaurant?

CREATE TABLE daily_revenue (restaurant_id INT, revenue FLOAT, date DATE); INSERT INTO daily_revenue (restaurant_id, revenue, date) VALUES (1, 5000.00, '2022-01-01'), (1, 6000.00, '2022-01-02'), (1, 4000.00, '2022-01-03');

SELECT AVG(revenue) as avg_daily_revenue FROM daily_revenue WHERE restaurant_id = 1;


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

select interval '1 year 2 mons 3 days 04:05:06.699999';

SELECT count(*) FROM (select interval '1 year 2 mons 3 days 04:05:06.699999') AS _sub;


Question: pgTAP test for Inheritance (assertion 90).

-- test is_descendent_of
SELECT * FROM check_test(
    is_descendent_of( 'hide', 'h_child1', 'hide', 'h_parent', 1, 'Lookie' ),
    true,
    'is_descendent_of(csch, ctab, psch, ptab, 1, desc)',
    'Lookie',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Inheritance.


Question: Generate PostgreSQL SQL for: Name the location when control is private and founded is 1870

CREATE TABLE table_15851155_1 (location VARCHAR, control VARCHAR, founded VARCHAR)

SELECT location FROM table_15851155_1 WHERE control = 'Private' AND founded = 1870;


Question: Generate PostgreSQL SQL for: Name the least week for  l 26–42

CREATE TABLE table_26401898_2 (week INTEGER, final_score VARCHAR)

SELECT MIN(week) FROM table_26401898_2 WHERE final_score = 'L 26–42';


Question: Which community development initiatives were completed in '2021'?

CREATE TABLE community_development (id INT, initiative_name VARCHAR(50), sector VARCHAR(50), start_date DATE, end_date DATE, budget FLOAT); INSERT INTO community_development (id, initiative_name, sector, start_date, end_date, budget) VALUES (1, 'Youth Empowerment Program', 'Community Development', '2019-01-01', '2020-12-31', 250000);

SELECT initiative_name FROM community_development WHERE YEAR(end_date) = 2021;


Question: Generate PostgreSQL SQL for: What was the location that led to a record of 9-0-0?

CREATE TABLE table_name_95 (location VARCHAR, record VARCHAR)

SELECT location FROM table_name_95 WHERE record = '9-0-0';