Question: Generate PostgreSQL SQL for: Show all student ids and the number of hours played.

CREATE TABLE Plays_games (Stuid VARCHAR, hours_played INTEGER)

SELECT Stuid, SUM(hours_played) FROM Plays_games GROUP BY Stuid;


Question: How many new broadband subscribers have signed up in the state of California in the last 30 days?

CREATE TABLE subscribers (id INT, subscriber_type VARCHAR(50), subscribe_date DATE);

SELECT COUNT(*) FROM subscribers WHERE subscriber_type = 'broadband' AND subscribe_date >= CURDATE() - INTERVAL 30 DAY AND subscribe_date < CURDATE() AND state = 'California';


Question: Generate PostgreSQL SQL for: what was the length of the game on may 19

CREATE TABLE table_name_10 (length VARCHAR, date VARCHAR)

SELECT length FROM table_name_10 WHERE date = 'may 19';


Question: Generate PostgreSQL SQL for: What are the number of episodes when the genre is modern drama and the highest average ratings points are 28?

CREATE TABLE table_name_34 (number_of_episodes INTEGER, genre VARCHAR, highest_average_point_ratings VARCHAR)

SELECT AVG(number_of_episodes) FROM table_name_34 WHERE genre = 'modern drama' AND highest_average_point_ratings = 28;


Question: Generate PostgreSQL SQL for: how many player with no being 12

CREATE TABLE table_12962773_5 (player VARCHAR, no VARCHAR)

SELECT COUNT(player) FROM table_12962773_5 WHERE no = 12;


Question: List all the safety protocols for factories located in Ohio or Michigan?

CREATE TABLE factories (factory_id INT, name TEXT, location TEXT); INSERT INTO factories (factory_id, name, location) VALUES (1, 'Factory A', 'Ohio'), (2, 'Factory B', 'Michigan'), (3, 'Factory C', 'California'); CREATE TABLE safety_protocols (protocol_id INT, factory_id INT, protocol TEXT); INSERT INTO safety_protocols (protocol_id, factory_id, protocol) VALUES (1, 1, 'Fire Safety'), (2, 1, 'Emergency Exits'), (3, 2, 'Fire Safety'), (4, 2, 'Chemical Spills'), (5, 3, 'Fire Safety'), (6, 3, 'Hurricane Preparedness');

SELECT s.protocol FROM factories f JOIN safety_protocols s ON f.factory_id = s.factory_id WHERE f.location IN ('Ohio', 'Michigan');


Question: What is the average response time for emergency calls in the 'Mountain' region?

CREATE TABLE emergency_calls (id INT, region VARCHAR(20), response_time INT); INSERT INTO emergency_calls (id, region, response_time) VALUES (1, 'Mountain', 100), (2, 'Mountain', 120), (3, 'Mountain', 85);

SELECT AVG(response_time) FROM emergency_calls WHERE region = 'Mountain';


Question: Generate PostgreSQL SQL for: What is the score on 17 November 1956 when home team is Derby County?

CREATE TABLE table_name_36 (score VARCHAR, date VARCHAR, home_team VARCHAR)

SELECT score FROM table_name_36 WHERE date = '17 november 1956' AND home_team = 'derby county';


Question: Generate PostgreSQL SQL for: Which date has a Home of washington, a Visitor of florida, and a Record of 8-15-2?

CREATE TABLE table_name_78 (date VARCHAR, record VARCHAR, home VARCHAR, visitor VARCHAR)

SELECT date FROM table_name_78 WHERE home = 'washington' AND visitor = 'florida' AND record = '8-15-2';


Question: Generate PostgreSQL SQL for: What was the away team score when the home team was the Brisbane Lions?

CREATE TABLE table_name_83 (away_team VARCHAR, home_team VARCHAR)

SELECT away_team AS score FROM table_name_83 WHERE home_team = 'brisbane lions';


Question: Generate PostgreSQL SQL for: What is the report for the race that Mike Spence won.

CREATE TABLE table_1140099_6 (report VARCHAR, winning_driver VARCHAR)

SELECT report FROM table_1140099_6 WHERE winning_driver = 'Mike Spence';


Question: Generate PostgreSQL SQL for: What score has 15.0% as the 2012?

CREATE TABLE table_name_16 (score VARCHAR)

SELECT score FROM table_name_16 WHERE 2012 = '15.0%';


Question: Generate PostgreSQL SQL for: What was the competition held in 2003?

CREATE TABLE table_name_17 (competition VARCHAR, year VARCHAR)

SELECT competition FROM table_name_17 WHERE year = 2003;


Question: What is the total number of artworks in the modern and contemporary categories?

CREATE TABLE Artworks (category VARCHAR(20), quantity INT); INSERT INTO Artworks (category, quantity) VALUES ('Modern', 1200), ('Modern', 1500), ('Contemporary', 800), ('Contemporary', 900);

SELECT SUM(quantity) FROM Artworks WHERE category IN ('Modern', 'Contemporary');


Question: Generate PostgreSQL SQL for: What was the highest number of goals when 2428 minutes were played?

CREATE TABLE table_name_91 (goals INTEGER, minutes VARCHAR)

SELECT MAX(goals) FROM table_name_91 WHERE minutes = 2428;


Question: What is the average age of soccer players from the UK?

CREATE TABLE Teams (TeamID INT PRIMARY KEY, TeamName VARCHAR(100), Sport VARCHAR(50), Country VARCHAR(50)); INSERT INTO Teams (TeamID, TeamName, Sport, Country) VALUES (1, 'Manchester United', 'Soccer', 'England'); CREATE TABLE Players (PlayerID INT PRIMARY KEY, Name VARCHAR(100), Age INT, Sport VARCHAR(50), Country VARCHAR(50), TeamID INT, FOREIGN KEY (TeamID) REFERENCES Teams(TeamID)); INSERT INTO Players (PlayerID, Name, Age, Sport, Country, TeamID) VALUES (1, 'Alice Johnson', 28, 'Soccer', 'England', 1); INSERT INTO Players (PlayerID, Name, Age, Sport, Country, TeamID) VALUES (2, 'Bob Williams', 31, 'Soccer', 'England', 1);

SELECT AVG(Age) as AvgAge FROM Players WHERE Sport = 'Soccer' AND Country = 'England';


Question: What is the average number of visitors per day for the 'Contemporary Art' exhibition in 2021?

CREATE TABLE Exhibition_Daily_Attendance (exhibition_id INT, visit_date DATE, visitor_count INT); CREATE TABLE Exhibitions (id INT, name VARCHAR(50)); INSERT INTO Exhibitions (id, name) VALUES (1, 'Contemporary Art'); ALTER TABLE Exhibition_Daily_Attendance ADD FOREIGN KEY (exhibition_id) REFERENCES Exhibitions(id);

SELECT AVG(visitor_count) FROM Exhibition_Daily_Attendance WHERE exhibition_id = 1 AND visit_date BETWEEN '2021-01-01' AND '2021-12-31';


Question: Generate PostgreSQL SQL for: Which club has a capacity of 25138?

CREATE TABLE table_name_4 (club VARCHAR, capacity VARCHAR)

SELECT club FROM table_name_4 WHERE capacity = '25138';


Question: What is the total CO2 emissions in Canada, and how does it break down by sector?

CREATE TABLE co2_emissions (id INT, country VARCHAR(255), sector VARCHAR(255), emissions FLOAT);

SELECT sector, SUM(emissions) FROM co2_emissions WHERE country = 'Canada' GROUP BY sector;


Question: What is the number of players who have rated game 1 and game 2?

CREATE TABLE PlayerRatings (PlayerID INT, GameID INT, Rating FLOAT); INSERT INTO PlayerRatings (PlayerID, GameID, Rating) VALUES (1, 1, 8.5), (1, 2, 9.2), (2, 1, 7.8), (2, 2, 8.9), (3, 1, 8.1), (3, 2, 9.0);

SELECT GameID, COUNT(DISTINCT PlayerID) FROM PlayerRatings GROUP BY GameID;


Question: Generate PostgreSQL SQL for: Who was the home team for the match against Arsenal?

CREATE TABLE table_name_2 (home_team VARCHAR, away_team VARCHAR)

SELECT home_team FROM table_name_2 WHERE away_team = 'arsenal';


Question: Write the DDL statement from PostgreSQL regression test 'partition_join' (example 536).

CREATE TABLE plt2_adv_default PARTITION OF plt2_adv DEFAULT;

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


Question: What are the names and locations of marine protected areas that overlap with the ocean floor mapping project?

CREATE TABLE marine_protected_areas (name TEXT, location TEXT, avg_depth REAL); INSERT INTO marine_protected_areas (name, location, avg_depth) VALUES ('Galapagos Marine Reserve', 'Ecuador', 200.0), ('Great Barrier Reef', 'Australia', 35.0); CREATE TABLE ocean_floor_mapping (location TEXT, depth REAL); INSERT INTO ocean_floor_mapping (location, depth) VALUES ('Mariana Trench', 10994.0), ('Sunda Trench', 8047.0);

SELECT name, location FROM marine_protected_areas WHERE location IN (SELECT location FROM ocean_floor_mapping);


Question: Show all records from 'smart_grid_view'

CREATE TABLE smart_grid (id INT PRIMARY KEY, city VARCHAR(50), power_sources VARCHAR(50), renewable_energy_percentage INT); CREATE VIEW smart_grid_view AS SELECT * FROM smart_grid;


Question: Generate PostgreSQL SQL for: Name the percentage which has females of 2

CREATE TABLE table_name_17 (percentage___percentage_ VARCHAR, females VARCHAR)

SELECT percentage___percentage_ FROM table_name_17 WHERE females = '2';


Question: What was the recycling rate in percentage for the region 'Seattle' in 2020?

CREATE TABLE recycling_rates (region VARCHAR(50), year INT, recycling_rate FLOAT); INSERT INTO recycling_rates (region, year, recycling_rate) VALUES ('Seattle', 2020, 35.67);

SELECT recycling_rate FROM recycling_rates WHERE region = 'Seattle' AND year = 2020;


Question: Generate PostgreSQL SQL for: How many gp-gs have 121.70 as an effic and an avg/g less than 218.7?

CREATE TABLE table_name_41 (gp_gs VARCHAR, effic VARCHAR, avg_g VARCHAR)

SELECT COUNT(gp_gs) FROM table_name_41 WHERE effic = '121.70' AND avg_g < 218.7;


Question: What is the average price of non-sustainable materials for each supplier, showing only suppliers with more than 3 products using their materials?

CREATE TABLE supplier (id INT PRIMARY KEY, name VARCHAR(100), country VARCHAR(50), sustainable BOOLEAN); CREATE TABLE material (id INT PRIMARY KEY, name VARCHAR(100), supplier_id INT, price DECIMAL(5,2)); CREATE TABLE product (id INT PRIMARY KEY, name VARCHAR(100), manufacturer_id INT, price DECIMAL(5,2), sustainable BOOLEAN); CREATE TABLE manufacturer (id INT PRIMARY KEY, name VARCHAR(100), country VARCHAR(50), sustainable BOOLEAN); CREATE VIEW sustainable_materials AS SELECT material.id, material.name, material.price, supplier.name as supplier_name FROM material INNER JOIN supplier ON material.supplier_id = supplier.id WHERE supplier.sustainable = TRUE;

SELECT supplier_name, AVG(material.price) as average_price FROM material INNER JOIN product ON material.id = product.material_id INNER JOIN supplier ON material.supplier_id = supplier.id WHERE supplier.sustainable = FALSE GROUP BY supplier.name HAVING COUNT(*) > 3;


Question: What is the age distribution of visitors who attended the "Fauvism" exhibition?

CREATE TABLE visitors (visitor_id INT, age INT, visited_fauvism BOOLEAN); INSERT INTO visitors (visitor_id, age, visited_fauvism) VALUES (123, 45, TRUE), (456, 32, FALSE), (789, 51, TRUE), (111, 64, TRUE), (222, 21, FALSE);

SELECT CASE WHEN age < 30 THEN '18-29' WHEN age < 50 THEN '30-49' ELSE '50+' END AS age_range, COUNT(*) AS visitor_count FROM visitors WHERE visited_fauvism = TRUE GROUP BY age_range;


Question: What is the total cargo weight handled by carriers from Spain?

CREATE TABLE Carrier (CarrierID INT, Name VARCHAR(255), Country VARCHAR(255), HomePort VARCHAR(255)); INSERT INTO Carrier (CarrierID, Name, Country, HomePort) VALUES (2, 'MSC Mediterranean Shipping Company', 'Switzerland', 'Genoa'); INSERT INTO Carrier (CarrierID, Name, Country, HomePort) VALUES (3, 'Maersk', 'Denmark', 'Copenhagen'); INSERT INTO Carrier (CarrierID, Name, Country, HomePort) VALUES (4, 'COSCO Shipping', 'China', 'Shanghai'); INSERT INTO Carrier (CarrierID, Name, Country, HomePort) VALUES (5, 'Hapag-Lloyd', 'Germany', 'Hamburg'); INSERT INTO Carrier (CarrierID, Name, Country, HomePort) VALUES (6, 'Evergreen Marine', 'Taiwan', 'Taipei');

SELECT SUM(Cargo.Weight) FROM Cargo JOIN Vessel ON Cargo.VesselID = Vessel.VesselID JOIN Carrier ON Vessel.CarrierID = Carrier.CarrierID WHERE Carrier.Country = 'Spain';


Question: What is the average dissolved oxygen level for each species in Tank1?

CREATE TABLE Tank1 (species VARCHAR(50), dissolved_oxygen FLOAT); INSERT INTO Tank1 (species, dissolved_oxygen) VALUES ('Salmon', 6.5), ('Trout', 7.2), ('Tilapia', 5.8);

SELECT species, AVG(dissolved_oxygen) FROM Tank1 GROUP BY species;


Question: Generate PostgreSQL SQL for: How many gb's have an iso number of cn-65?

CREATE TABLE table_254234_1 (gb VARCHAR, iso_№ VARCHAR)

SELECT COUNT(gb) FROM table_254234_1 WHERE iso_№ = 'CN-65';


Question: Generate PostgreSQL SQL for: Which band serves darwin for commercial purpose?

CREATE TABLE table_name_61 (band VARCHAR, area_served VARCHAR, purpose VARCHAR)

SELECT band FROM table_name_61 WHERE area_served = 'darwin' AND purpose = 'commercial';


Question: Generate PostgreSQL SQL for: What's the diameter of the 2006 equestrian Reverse?

CREATE TABLE table_name_49 (diameter VARCHAR, year VARCHAR, reverse VARCHAR)

SELECT diameter FROM table_name_49 WHERE year = 2006 AND reverse = 'equestrian';


Question: Generate PostgreSQL SQL for: What is the name of the club with 22 points?

CREATE TABLE table_name_2 (club VARCHAR, points VARCHAR)

SELECT club FROM table_name_2 WHERE points = '22';


Question: Find the menu items that have a lower than average revenue for their respective cuisine category.

CREATE TABLE menu_items (menu_item_id INT, restaurant_id INT, name VARCHAR(255), revenue DECIMAL(10, 2), cuisine VARCHAR(255));

SELECT m.name, AVG(o.revenue) OVER (PARTITION BY m.cuisine) AS avg_revenue FROM menu_items m JOIN orders o ON m.menu_item_id = o.menu_item_id WHERE m.revenue < AVG(o.revenue) OVER (PARTITION BY m.cuisine);


Question: Which decentralized applications belong to the 'Finance' category?

CREATE TABLE dapps (id INT, name VARCHAR(255), category VARCHAR(50)); INSERT INTO dapps (id, name, category) VALUES (1, 'DApp1', 'Finance'); INSERT INTO dapps (id, name, category) VALUES (2, 'DApp2', 'Gaming'); INSERT INTO dapps (id, name, category) VALUES (3, 'DApp3', 'Social'); INSERT INTO dapps (id, name, category) VALUES (4, 'DApp4', 'Exchange');

SELECT name FROM dapps WHERE category = 'Finance';


Question: Generate PostgreSQL SQL for: List the all the distinct names of the products with the characteristic name 'warm'.

CREATE TABLE CHARACTERISTICS (characteristic_id VARCHAR, characteristic_name VARCHAR); CREATE TABLE products (product_name VARCHAR, product_id VARCHAR); CREATE TABLE product_characteristics (product_id VARCHAR, characteristic_id VARCHAR)

SELECT DISTINCT t1.product_name FROM products AS t1 JOIN product_characteristics AS t2 ON t1.product_id = t2.product_id JOIN CHARACTERISTICS AS t3 ON t2.characteristic_id = t3.characteristic_id WHERE t3.characteristic_name = 'warm';


Question: Generate PostgreSQL SQL for: What was the purse when Sherri Steinhauer was champion at Woburn Golf and Country Club?

CREATE TABLE table_name_41 (purse___ VARCHAR, champion VARCHAR, venue VARCHAR)

SELECT COUNT(purse___) AS $__ FROM table_name_41 WHERE champion = 'sherri steinhauer' AND venue = 'woburn golf and country club';


Question: Generate PostgreSQL SQL for: What is the total amount of circuts dated 22 april?

CREATE TABLE table_1140105_6 (circuit VARCHAR, date VARCHAR)

SELECT COUNT(circuit) FROM table_1140105_6 WHERE date = '22 April';


Question: Generate PostgreSQL SQL for: For the tournament played on Oct 17, 1982, what was the winning score?

CREATE TABLE table_name_69 (winning_score VARCHAR, date VARCHAR)

SELECT winning_score FROM table_name_69 WHERE date = 'oct 17, 1982';


Question: What percentage of cruelty-free products are also vegan?

CREATE TABLE products (product_id INT, cruelty_free BOOLEAN, vegan BOOLEAN); INSERT INTO products VALUES (1, true, true), (2, false, false), (3, false, true), (4, true, false), (5, true, true), (6, false, true), (7, true, false), (8, false, false), (9, true, true), (10, false, false);

SELECT (COUNT(p.cruelty_free AND p.vegan) * 100.0 / (SELECT COUNT(*) FROM products)) AS vegan_cruelty_free_percentage FROM products p;


Question: What is the average sale value per equipment type?

CREATE TABLE Military_Equipment_Sales(id INT, sale_date DATE, country VARCHAR(50), equipment_type VARCHAR(50), sale_value FLOAT); INSERT INTO Military_Equipment_Sales(id, sale_date, country, equipment_type, sale_value) VALUES (1, '2020-01-01', 'USA', 'Naval', 70000000);

SELECT equipment_type, AVG(sale_value) FROM Military_Equipment_Sales GROUP BY equipment_type;


Question: Delete the artifact with ArtifactID 2 from the database.

CREATE TABLE ExcavationSites (SiteID INT, SiteName TEXT, Country TEXT); INSERT INTO ExcavationSites (SiteID, SiteName, Country) VALUES (1, 'MayanRuins', 'Guatemala'), (3, 'Pompeii', 'Italy'); CREATE TABLE Artifacts (ArtifactID INT, SiteID INT, ArtifactName TEXT, ArtifactType TEXT, Quantity INT); INSERT INTO Artifacts (ArtifactID, SiteID, ArtifactName, ArtifactType, Quantity) VALUES (1, 1, 'Jade Mask', 'Mask', 1), (2, 1, 'Obsidian Knife', 'Knife', 2), (4, 3, 'Roman Coin', 'Coin', 20);

DELETE FROM Artifacts WHERE ArtifactID = 2;


Question: What is the total budget allocated to waste management in Seoul in 2019?

CREATE TABLE Waste (City VARCHAR(20), Year INT, Amount INT); INSERT INTO Waste (City, Year, Amount) VALUES ('Seoul', 2019, 6000);

SELECT SUM(Amount) FROM Waste WHERE City = 'Seoul' AND Year = 2019;


Question: Generate PostgreSQL SQL for: What position is played by the player from the Chicago Cubs?

CREATE TABLE table_name_8 (position VARCHAR, team VARCHAR)

SELECT position FROM table_name_8 WHERE team = 'chicago cubs';


Question: What is the total number of animals in each status category in 'species_status' table?

CREATE TABLE species_status (id INT, species_name VARCHAR(50), status VARCHAR(50)); INSERT INTO species_status VALUES (1, 'Tiger', 'Endangered'), (2, 'Elephant', 'Vulnerable');

SELECT status, COUNT(*) FROM species_status GROUP BY status;


Question: Get the average hourly wage for construction workers in the 10 most populous states for the year 2020

SELECT state, AVG(avg_hourly_wage) FROM labor_statistics WHERE year = 2020 GROUP BY state ORDER BY total_workers DESC LIMIT 10;


Question: Generate PostgreSQL SQL for: What club team is Per Gustafsson play for?

CREATE TABLE table_1013129_11 (college_junior_club_team VARCHAR, player VARCHAR)

SELECT college_junior_club_team FROM table_1013129_11 WHERE player = 'Per Gustafsson';


Question: Generate PostgreSQL SQL for: What ride opened after 2011?

CREATE TABLE table_name_91 (current_name VARCHAR, year_first_opened INTEGER)

SELECT current_name FROM table_name_91 WHERE year_first_opened > 2011;


Question: Calculate the daily revenue for a taxi company in a specific city

CREATE TABLE taxi_trip (trip_id INT, trip_start_time TIMESTAMP, trip_end_time TIMESTAMP, fare DECIMAL(10, 2), city VARCHAR(50));

SELECT DATE(trip_start_time) AS trip_date, SUM(fare) AS daily_revenue FROM taxi_trip WHERE city = 'New York' GROUP BY trip_date;


Question: Generate PostgreSQL SQL for: Show codes and fates of missions, and names of ships involved.

CREATE TABLE mission (Code VARCHAR, Fate VARCHAR, Ship_ID VARCHAR); CREATE TABLE ship (Name VARCHAR, Ship_ID VARCHAR)

SELECT T1.Code, T1.Fate, T2.Name FROM mission AS T1 JOIN ship AS T2 ON T1.Ship_ID = T2.Ship_ID;


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

Explanation: DDL from PostgreSQL core regression test for Rowsecurity.


Question: What is the average rating of hip-hop songs released in 2015?

CREATE TABLE Hip_Hop_Songs (title TEXT, year INTEGER, rating FLOAT); INSERT INTO Hip_Hop_Songs (title, year, rating) VALUES ('Song1', 2013, 7.5), ('Song2', 2014, 8.0), ('Song3', 2015, 8.5), ('Song4', 2016, 9.0), ('Song5', 2017, 9.2), ('Song6', 2018, 9.5);

SELECT AVG(rating) FROM Hip_Hop_Songs WHERE year = 2015;


Question: What is the total number of shelters constructed in "North America" in 2019?

CREATE TABLE shelters (id INT, project_id INT, location VARCHAR(255), construction_date DATE); INSERT INTO shelters (id, project_id, location, construction_date) VALUES (1, 10001, 'USA', '2019-05-01'); INSERT INTO shelters (id, project_id, location, construction_date) VALUES (2, 10002, 'Canada', '2019-02-01');

SELECT COUNT(*) FROM shelters WHERE location = 'North America' AND YEAR(construction_date) = 2019;


Question: What was the average age of attendees for each event in 2022?

CREATE TABLE event_attendance (event_id INT, attendee_age INT, program_id INT, event_date DATE); INSERT INTO event_attendance (event_id, attendee_age, program_id, event_date) VALUES (1, 34, 101, '2022-05-12'); INSERT INTO event_attendance (event_id, attendee_age, program_id, event_date) VALUES (2, 45, 102, '2022-06-20');

SELECT event_id, AVG(attendee_age) as avg_age FROM event_attendance WHERE YEAR(event_date) = 2022 GROUP BY event_id;


Question: List all rural infrastructure projects in Africa, along with their start and end dates, and the number of beneficiaries.

CREATE SCHEMA if not exists rural_dev; use rural_dev; CREATE TABLE if not exists rural_infrastructure_projects (id INT, project_name VARCHAR(255), country VARCHAR(255), start_date DATE, end_date DATE, num_beneficiaries INT, PRIMARY KEY (id));

SELECT project_name, start_date, end_date, num_beneficiaries FROM rural_dev.rural_infrastructure_projects WHERE country LIKE 'Africa%' OR country LIKE 'Algeria' OR country LIKE 'Egypt';


Question: Generate PostgreSQL SQL for: Which nominations was the film 27 Stolen Kisses nominated for?

CREATE TABLE table_10236830_6 (nomination VARCHAR, film_name VARCHAR)

SELECT nomination FROM table_10236830_6 WHERE film_name = '27 Stolen Kisses';


Question: How many community education programs were conducted in '2021' and '2022' in the 'education_programs' table?

CREATE TABLE education_programs (id INT, program_name VARCHAR(50), year INT, attendees INT); INSERT INTO education_programs (id, program_name, year, attendees) VALUES (1, 'Wildlife Conservation', 2021, 250);

SELECT COUNT(*) FROM education_programs WHERE year IN (2021, 2022);


Question: Generate PostgreSQL SQL for: What was the total city area for vehari city with a serial number bigger than 36?

CREATE TABLE table_name_1 (city_area_km_2__ VARCHAR, headquartered_city VARCHAR, serial_no VARCHAR)

SELECT COUNT(city_area_km_2__) FROM table_name_1 WHERE headquartered_city = 'vehari city' AND serial_no > 36;


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

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


Question: What is the total number of military equipment serviced by defense contractors based in Texas?

CREATE TABLE military_equipment (id INT, name VARCHAR(50), company VARCHAR(50), service_frequency INT, company_location VARCHAR(50)); INSERT INTO military_equipment (id, name, company, service_frequency, company_location) VALUES (1, 'M1 Abrams', 'XYZ', 12, 'Texas'); INSERT INTO military_equipment (id, name, company, service_frequency, company_location) VALUES (2, 'F-35', 'ABC', 24, 'New York');

SELECT SUM(service_frequency) FROM military_equipment WHERE company_location = 'Texas';


Question: Generate PostgreSQL SQL for: how many equivalent daily inflation rate with time required for prices to double being 3.7 days

CREATE TABLE table_13681_2 (equivalent_daily_inflation_rate VARCHAR, time_required_for_prices_to_double VARCHAR)

SELECT COUNT(equivalent_daily_inflation_rate) FROM table_13681_2 WHERE time_required_for_prices_to_double = '3.7 days';


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

SELECT * FROM pg_input_error_info('[{"attributes" : [1,2,3,4,5,6,7], "dependency" : 0, "degree": "1.2"}]', 'pg_dependencies');

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

SELECT count(*) FROM (SELECT * FROM pg_input_error_info('[{"attributes" : [1,2,3,4,5,6,7], "dependency" : 0, "degree": "1.2"}]', 'pg_dependencies')) AS _sub;


Question: Update artifact quantities based on their type?

CREATE TABLE Artifacts (ArtifactID INT, ArtifactType VARCHAR(50), Quantity INT); INSERT INTO Artifacts (ArtifactID, ArtifactType, Quantity) VALUES (1, 'Pottery', 25), (2, 'Tools', 12), (3, 'Pottery', 30);

UPDATE Artifacts SET Quantity = CASE ArtifactType WHEN 'Pottery' THEN Quantity * 1.1 WHEN 'Tools' THEN Quantity * 1.2 END;


Question: What is the total carbon emissions (in metric tons) for each industry, ranked from highest to lowest?

CREATE TABLE carbon_emissions (industry VARCHAR(50), emissions FLOAT); INSERT INTO carbon_emissions (industry, emissions) VALUES ('Industry A', 50000, 'Industry B', 60000), ('Industry C', 40000, 'Industry D', 70000);

SELECT industry, emissions, ROW_NUMBER() OVER (ORDER BY emissions DESC) as rank FROM carbon_emissions;


Question: What is the earliest year an artwork was created by each artist?

CREATE TABLE artists (id INT, name TEXT); INSERT INTO artists (id, name) VALUES (1, 'Artist 1'), (2, 'Artist 2'); CREATE TABLE artworks (id INT, title TEXT, year_created INT, artist_id INT); INSERT INTO artworks (id, title, year_created, artist_id) VALUES (1, 'Artwork 1', 2000, 1), (2, 'Artwork 2', 1990, 1), (3, 'Artwork 3', 2010, 2);

SELECT ar.name, MIN(a.year_created) FROM artists ar INNER JOIN artworks a ON ar.id = a.artist_id GROUP BY ar.name;


Question: What is the count of employees who have completed diversity and inclusion training?

CREATE TABLE Training (EmployeeID INT, TrainingName VARCHAR(50)); INSERT INTO Training (EmployeeID, TrainingName) VALUES (1, 'Diversity and Inclusion Training'), (2, 'Cybersecurity Training'), (3, 'Diversity and Inclusion Training');

SELECT COUNT(DISTINCT EmployeeID) FROM Training WHERE TrainingName = 'Diversity and Inclusion Training';


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

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

SELECT count(*) FROM (select jsonb_path_query('"2023-08-15 12:34:56.789"', '$.timestamp(2.0)')) AS _sub;


Question: What is the total number of community policing events held in the last 30 days, categorized by district and event type?

CREATE TABLE Districts (DistrictID INT, Name VARCHAR(50)); CREATE TABLE CommunityEvents (EventID INT, DistrictID INT, EventType VARCHAR(50), EventDate DATE);

SELECT D.Name, C.EventType, COUNT(*) as EventCount FROM Districts D INNER JOIN CommunityEvents C ON D.DistrictID = C.DistrictID WHERE C.EventDate >= DATEADD(day, -30, GETDATE()) GROUP BY D.Name, C.EventType;


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

SELECT t1."C 1", t2.c1, t3.c1 FROM "S 1"."T 1" t1 left join ft1 t2 full join ft2 t3 on (t2.c1 = t3.c1) on (t3.c1 = t1."C 1") OFFSET 100 LIMIT 10;

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


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

select format('INSERT INTO %I VALUES(%L,%L)', 'mytab', 10, 'Hello');

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

SELECT count(*) FROM (select format('INSERT INTO %I VALUES(%L,%L)', 'mytab', 10, 'Hello')) AS _sub;


Question: Generate PostgreSQL SQL for: what's the cancelable with bubbles being yes

CREATE TABLE table_1507852_5 (cancelable VARCHAR, bubbles VARCHAR)

SELECT cancelable FROM table_1507852_5 WHERE bubbles = 'Yes';


Question: Generate PostgreSQL SQL for: what amount played tried for 60?

CREATE TABLE table_12807904_5 (played VARCHAR, tries_for VARCHAR)

SELECT COUNT(played) FROM table_12807904_5 WHERE tries_for = '60';


Question: Write the DML statement from PostgreSQL regression test 'float4' (example 23).

INSERT INTO FLOAT4_TBL(f1) VALUES ('5 . 0');

Explanation: DML from PostgreSQL core regression test for Float4.


Question: Increase the 'salary' of members in the 'manufacturing' union by 3% who have been part of the union for over 3 years.

CREATE TABLE unions (id INT, name TEXT, industry TEXT);   CREATE TABLE members (id INT, union_id INT, joining_date DATE, salary FLOAT);   CREATE TABLE union_memberships (member_id INT, union_id INT);

UPDATE members SET salary = salary * 1.03 WHERE union_id IN (SELECT id FROM unions WHERE industry = 'manufacturing') AND joining_date <= DATE_SUB(CURRENT_DATE, INTERVAL 3 YEAR);


Question: What traditional arts events are planned for Kyoto in the next 6 months?

CREATE TABLE TraditionalArtsEvents (id INT, city VARCHAR(50), country VARCHAR(50), event_name VARCHAR(100), event_date DATE); INSERT INTO TraditionalArtsEvents (id, city, country, event_name, event_date) VALUES (1, 'Kyoto', 'Japan', 'Kabuki', '2023-04-01'), (2, 'Kyoto', 'Japan', 'Ikebana', '2023-05-15');

SELECT event_name FROM TraditionalArtsEvents WHERE city = 'Kyoto' AND event_date BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 6 MONTH);


Question: Generate PostgreSQL SQL for: Which city has a First season of current spell in Segunda División smaller than 2013?

CREATE TABLE table_name_69 (city VARCHAR, first_season_of_current_spell_in_segunda_división INTEGER)

SELECT city FROM table_name_69 WHERE first_season_of_current_spell_in_segunda_división < 2013;


Question: What is the average rating of hotels in 'Paris' that have a pool?

CREATE TABLE hotels (hotel_id INT, name VARCHAR(50), city VARCHAR(50), rating DECIMAL(2,1), pool BOOLEAN); INSERT INTO hotels (hotel_id, name, city, rating, pool) VALUES (1, 'Hotel Ritz', 'Paris', 4.5, true), (2, 'Hotel de Crillon', 'Paris', 4.7, false);

SELECT AVG(rating) FROM hotels WHERE city = 'Paris' AND pool = true;


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

SELECT count(*) FROM (select jsonb '[]' @@ '$[*]') AS _sub;


Question: pgTAP test for Index (assertion 44).

SELECT * FROM check_test(
    has_index( 'sometab', 'idx_bar', ARRAY['name', 'id'], 'whatever' ),
    false,
    'has_index() invalid no schema',
    'whatever',
    '        have: idx_bar ON sometab(numb, name)
        want: idx_bar ON sometab(name, id)'
);

Explanation: SQL assertion from pgTAP test suite for Index.


Question: What is the total fare collected for a specific train line in Berlin?

CREATE TABLE train_lines (line_id INT, city VARCHAR(50)); INSERT INTO train_lines (line_id, city) VALUES (1, 'Berlin'), (2, 'Berlin'); CREATE TABLE fares_collected (line_id INT, fare DECIMAL(5,2)); INSERT INTO fares_collected (line_id, fare) VALUES (1, 500.00), (1, 750.00), (2, 300.00), (2, 400.00);

SELECT SUM(fare) FROM fares_collected INNER JOIN train_lines ON fares_collected.line_id = train_lines.line_id WHERE city = 'Berlin' AND train_lines.line_id = 1;


Question: Show the total waste generation for each type

CREATE TABLE waste_generation (id INT PRIMARY KEY, waste_type_id INT, generation_rate FLOAT); INSERT INTO waste_generation (id, waste_type_id, generation_rate) VALUES (1, 1, 50.5), (2, 2, 40.3); CREATE TABLE waste_types (id INT PRIMARY KEY, waste_type VARCHAR(255)); INSERT INTO waste_types (id, waste_type) VALUES (1, 'Plastic'), (2, 'Paper');

SELECT waste_types.waste_type, SUM(waste_generation.generation_rate) FROM waste_types INNER JOIN waste_generation ON waste_types.id = waste_generation.waste_type_id GROUP BY waste_types.waste_type;


Question: Generate PostgreSQL SQL for: Which bodyweight has a Total (kg) of 145.0?

CREATE TABLE table_name_18 (bodyweight VARCHAR, total__kg_ VARCHAR)

SELECT bodyweight FROM table_name_18 WHERE total__kg_ = '145.0';


Question: Generate PostgreSQL SQL for: What were the LOA (metres) for the yacht where the skipper was Jez Fanstone?

CREATE TABLE table_25595107_1 (loa__metres_ VARCHAR, skipper VARCHAR)

SELECT loa__metres_ FROM table_25595107_1 WHERE skipper = 'Jez Fanstone';


Question: Generate PostgreSQL SQL for: Who is the captain of the Gloucestershire Gladiators?

CREATE TABLE table_18461635_1 (captain VARCHAR, team VARCHAR)

SELECT captain FROM table_18461635_1 WHERE team = 'Gloucestershire Gladiators';


Question: Generate PostgreSQL SQL for: Who was the outgoing manager who departed due to fc energie cottbus purchased rights?

CREATE TABLE table_name_80 (outgoing_manager VARCHAR, manner_of_departure VARCHAR)

SELECT outgoing_manager FROM table_name_80 WHERE manner_of_departure = 'fc energie cottbus purchased rights';


Question: List all socially responsible lending initiatives by microfinance institutions

CREATE TABLE microfinance_institutions (institution_id INT, institution_name VARCHAR(50));

CREATE TABLE lending_initiatives (initiative_id INT, initiative_name VARCHAR(50), institution_id INT); SELECT institution_name, initiative_name FROM microfinance_institutions;


Question: Generate PostgreSQL SQL for: Name the german voice actor for rafael torres

CREATE TABLE table_14960574_6 (german_voice_actor VARCHAR, spanish_voice_actor VARCHAR)

SELECT german_voice_actor FROM table_14960574_6 WHERE spanish_voice_actor = 'Rafael Torres';


Question: Generate PostgreSQL SQL for: What is the total average for Rank entries where the Lane listed is smaller than 4 and the Nationality listed is San Marino?

CREATE TABLE table_name_7 (rank INTEGER, lane VARCHAR, nationality VARCHAR)

SELECT AVG(rank) FROM table_name_7 WHERE lane < 4 AND nationality = 'san marino';


Question: Generate PostgreSQL SQL for: What points awarded are higher than 6 but smaller than 9

CREATE TABLE table_name_51 (points_awarded__platinum_ INTEGER, points_awarded__gold_ VARCHAR, points_awarded__silver_ VARCHAR)

SELECT MAX(points_awarded__platinum_) FROM table_name_51 WHERE points_awarded__gold_ = 9 AND points_awarded__silver_ > 6;


Question: What is the average speed of vessels that docked in the Port of Oakland in the past month?

CREATE TABLE Vessel_Performance(Vessel_ID INT, Docking_Port VARCHAR(50), Docking_Date DATE, Average_Speed DECIMAL(5,2)); INSERT INTO Vessel_Performance VALUES (1, 'Port of Oakland', '2022-03-15', 15.5), (2, 'Port of Los Angeles', '2022-03-18', 18.3), (3, 'Port of Oakland', '2022-03-22', 14.9);

SELECT AVG(Average_Speed) FROM Vessel_Performance WHERE Docking_Port = 'Port of Oakland' AND Docking_Date >= DATEADD(MONTH, -1, GETDATE());


Question: Generate PostgreSQL SQL for: Who lost that has a score of w 4-3?

CREATE TABLE table_name_25 (loss VARCHAR, score VARCHAR)

SELECT loss FROM table_name_25 WHERE score = 'w 4-3';


Question: What is the success rate of the public defender's office in the city of Chicago?

CREATE TABLE cases (id INT, city VARCHAR(255), office VARCHAR(255), result VARCHAR(255)); INSERT INTO cases (id, city, office, result) VALUES (1, 'Chicago', 'Public Defender', 'Won'), (2, 'Chicago', 'Public Defender', 'Lost'), (3, 'Chicago', 'Prosecutor', 'Won');

SELECT (SUM(CASE WHEN result = 'Won' THEN 1 ELSE 0 END) / COUNT(*)) * 100 AS success_rate FROM cases WHERE city = 'Chicago' AND office = 'Public Defender';


Question: What is the average energy consumption for buildings owned by 'GreenCorp' and 'EcoInnovations'?

CREATE TABLE GreenBuildings (id INT, name TEXT, owner TEXT, energy_consumption FLOAT); INSERT INTO GreenBuildings (id, name, owner, energy_consumption) VALUES (1, 'EcoTower', 'ACME Inc', 1500.0), (2, 'GreenSpire', 'GreenCorp', 1200.0), (3, 'GreenVista', 'ACME Inc', 1300.0), (4, 'GreenPlaza', 'EcoInnovations', 1000.0);

SELECT AVG(energy_consumption) FROM GreenBuildings WHERE owner IN ('GreenCorp', 'EcoInnovations');


Question: Calculate the average waste generation rate per day for each manufacturing plant in the month of February 2022.

CREATE TABLE manufacturing_plants (id INT, name VARCHAR(50));CREATE TABLE waste_generation (plant_id INT, date DATE, amount INT); INSERT INTO manufacturing_plants (id, name) VALUES (1, 'Plant A'), (2, 'Plant B'); INSERT INTO waste_generation (plant_id, date, amount) VALUES (1, '2022-02-01', 100), (1, '2022-02-03', 150), (1, '2022-02-05', 50), (2, '2022-02-02', 200), (2, '2022-02-04', 300), (2, '2022-02-06', 100);

SELECT m.name, AVG(w.amount / 31.0) AS avg_daily_amount FROM manufacturing_plants m INNER JOIN waste_generation w ON m.id = w.plant_id WHERE w.date >= '2022-02-01' AND w.date <= '2022-02-28' GROUP BY m.name;


Question: Generate PostgreSQL SQL for: Which Champion has a Venue of old waverly golf club?

CREATE TABLE table_name_35 (champion VARCHAR, venue VARCHAR)

SELECT champion FROM table_name_35 WHERE venue = 'old waverly golf club';


Question: Write the DDL statement from PostgreSQL regression test 'inet' (example 2).

Explanation: DDL from PostgreSQL core regression test for Inet.


Question: Update the community representation for subscriber 5 to 'Native Hawaiian or Other Pacific Islander'.

CREATE TABLE mobile_subscribers (subscriber_id INT, data_usage FLOAT, community_representation VARCHAR(30)); INSERT INTO mobile_subscribers (subscriber_id, data_usage, community_representation) VALUES (1, 30.5, 'Latinx'), (2, 40.3, 'Black/African American'), (3, 50.2, 'Native American'), (4, 60.1, 'Asian'), (5, 35.6, 'Pacific Islander');

UPDATE mobile_subscribers SET community_representation = 'Native Hawaiian or Other Pacific Islander' WHERE subscriber_id = 5;


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

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

SELECT count(*) FROM (select unnest(array[1,2,3,null,4,null,null,5,6]::text[])) AS _sub;


Question: Generate PostgreSQL SQL for: Which show was nominated for the ITA Milestone Award at the Indian Television Academy Awards?

CREATE TABLE table_name_85 (show VARCHAR, award_ceremony VARCHAR, category VARCHAR)

SELECT show FROM table_name_85 WHERE award_ceremony = 'indian television academy awards' AND category = 'ita milestone award';


Question: Calculate the average distance of freight routes in Germany.

CREATE TABLE routes (id INT, start_location VARCHAR(50), end_location VARCHAR(50), distance INT, country VARCHAR(50)); INSERT INTO routes VALUES (1, 'Location A', 'Location B', 100, 'Germany'), (2, 'Location A', 'Location C', 200, 'France'), (3, 'Location B', 'Location C', 150, 'Germany');

SELECT AVG(distance) as avg_distance FROM routes WHERE country = 'Germany';


Question: Show a SQL definition from the pg_partman project (pg_partman--5.4.0--5.4.1, item 41).

CREATE OR REPLACE PROCEDURE @extschema@.run_analyze(p_skip_locked boolean DEFAULT false, p_quiet boolean DEFAULT false, p_parent_table text DEFAULT NULL)
    LANGUAGE plpgsql
    AS $$
DECLARE

v_adv_lock              boolean;
v_parent_schema         text;
v_parent_tablename      text;
v_row                   record;
v_sql                   text;

BEGIN

v_adv_lock := pg_catalog.pg_try_advisory_lock(hashtext('pg_partman run_analyze'));
IF v_adv_lock = false THEN
    RAISE NOTICE 'Partman analyze already running or another session has not released its advisory lock.';
    RETURN;
END IF;

FOR v_row IN SELECT parent_table FROM @extschema@.part_config
LOOP

    IF p_parent_table IS NOT NULL THEN
        IF p_parent_table != v_row.parent_table THEN
            CONTINUE;
        END IF;
    END IF;

    SELECT n.nspname, c.relname
    INTO v_parent_schema, v_parent_tablename
    FROM pg_catalog.pg_class c
    JOIN pg_catalog.pg_namespace n ON c.relnamespace = n.oid
    WHERE n.nspname = pg_catalog.split_part(v_row.parent_table, '.', 1)::name
    AND c.relname = pg_catalog.split_part(v_row.parent_table, '.', 2)::name;

    v_sql := 'ANALYZE ';
    IF p_skip_locked THEN
        v_sql := v_sql || 'SKIP LOCKED ';
    END IF;
    v_sql := pg_catalog.format('%s %I.%I', v_sql, v_parent_schema, v_parent_tablename);

    IF p_quiet = 'false' THEN
        RAISE NOTICE 'Analyzed partitioned table: %.%', v_parent_schema, v_parent_tablename;
    END IF;
    EXECUTE v_sql;
    COMMIT;

END LOOP;

PERFORM pg_catalog.pg_advisory_unlock(hashtext('pg_partman run_analyze'));
END
$$;

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


Question: Determine the daily revenue for the past week

CREATE TABLE sales (sale_id INT, sale_date DATE, dish_id INT, quantity INT, price DECIMAL(5,2)); INSERT INTO sales (sale_id, sale_date, dish_id, quantity, price) VALUES (1, '2022-01-01', 1, 2, 12.99), (2, '2022-01-01', 2, 1, 15.99), (3, '2022-01-02', 3, 3, 9.99);

SELECT SUM(quantity * price) as daily_revenue FROM sales WHERE sale_date BETWEEN DATE_SUB(CURRENT_DATE, INTERVAL 7 DAY) AND CURRENT_DATE GROUP BY sale_date;


Question: Generate PostgreSQL SQL for: Who is the artist with catalog number ZK 34354?

CREATE TABLE table_name_38 (artist VARCHAR, catalog__number VARCHAR)

SELECT artist FROM table_name_38 WHERE catalog__number = 'zk 34354';


Question: What is the total number of military bases in the Asia-Pacific region?

CREATE TABLE military_bases (id INT, base_name VARCHAR(255), region VARCHAR(255)); INSERT INTO military_bases (id, base_name, region) VALUES (1, 'Base A', 'Asia-Pacific'), (2, 'Base B', 'Europe'), (3, 'Base C', 'Asia-Pacific');

SELECT COUNT(*) FROM military_bases WHERE region = 'Asia-Pacific';


Question: Generate PostgreSQL SQL for: What is the total when the league cup is less than 1, and the fa cup is less than 1?

CREATE TABLE table_name_45 (total INTEGER, league_cup VARCHAR, fa_cup VARCHAR)

SELECT SUM(total) FROM table_name_45 WHERE league_cup < 1 AND fa_cup < 1;


Question: pgTAP test for Valueset (assertion 288).

-- Handle failure due to column count mismatch.
SELECT * FROM check_test(
    set_hasnt( 'VALUES (1), (2)', 'VALUES (''foo'', 1), (''bar'', 2)' ),
    false,
    'set_hasnt((int), (text,int))',
    '',
    '    Columns differ between queries:
        have: (integer)
        want: (text,integer)'
);

Explanation: SQL assertion from pgTAP test suite for Valueset.


Question: Generate PostgreSQL SQL for: What is Player, when Total is "294", and when Year(s) Won is "1955"?

CREATE TABLE table_name_61 (player VARCHAR, total VARCHAR, year_s__won VARCHAR)

SELECT player FROM table_name_61 WHERE total = 294 AND year_s__won = '1955';


Question: How many applicants were there for each job opening, and which openings had more than 50 applicants?

CREATE TABLE JobOpenings (OpeningID INT, Position VARCHAR(50), Department VARCHAR(50), TotalApplicants INT); INSERT INTO JobOpenings (OpeningID, Position, Department, TotalApplicants) VALUES (1, 'Developer', 'IT', 75), (2, 'Manager', 'HR', 30), (3, 'Designer', 'Marketing', 60), (4, 'Analyst', 'Finance', 45);

SELECT OpeningID, Position, Department, TotalApplicants FROM JobOpenings WHERE TotalApplicants > 50;


Question: Generate PostgreSQL SQL for: What is the average unit price of all the tracks?


Question: List all donors, their contact information, and the total amount they have donated to each program, along with program details.

CREATE TABLE donors (id INT, name TEXT, email TEXT); CREATE TABLE donations (id INT, donor_id INT, program_id INT, amount DECIMAL); CREATE TABLE programs (id INT, name TEXT, location TEXT, budget INT);

SELECT donors.name as donor_name, programs.name as program_name, SUM(donations.amount) as total_donation FROM donors INNER JOIN donations ON donors.id = donations.donor_id INNER JOIN programs ON donations.program_id = programs.id GROUP BY donors.id, programs.id;


Question: What is the total budget allocated for each department in 2024?

CREATE TABLE Budget (BudgetID int, DepartmentID int, Amount decimal, StartDate date, EndDate date); INSERT INTO Budget (BudgetID, DepartmentID, Amount, StartDate, EndDate) VALUES (1, 1, 50000, '2024-01-01', '2024-12-31'); INSERT INTO Budget (BudgetID, DepartmentID, Amount, StartDate, EndDate) VALUES (2, 2, 70000, '2024-01-01', '2024-12-31');

SELECT DepartmentID, SUM(Amount) as TotalBudget FROM Budget WHERE YEAR(StartDate) = 2024 AND YEAR(EndDate) = 2024 GROUP BY DepartmentID;


Question: Which artists have their works exhibited in the 'Modern Art Museum'?

CREATE TABLE Artists (ArtistID int, Name varchar(50), Nationality varchar(50)); INSERT INTO Artists (ArtistID, Name, Nationality) VALUES (1, 'Pablo Picasso', 'Spanish'), (2, 'Vincent van Gogh', 'Dutch'); CREATE TABLE Exhibitions (ExhibitionID int, Title varchar(50), Artists varchar(50), Museum varchar(50)); INSERT INTO Exhibitions (ExhibitionID, Title, Artists, Museum) VALUES (1, 'Modern Art Masterpieces', 'Pablo Picasso, Vincent van Gogh', 'Modern Art Museum'), (2, 'Impressionist Icons', 'Claude Monet', 'Metropolitan Museum');

SELECT Artists.Name FROM Artists INNER JOIN Exhibitions ON Artists.ArtistID = Cast(Split_Part(Exhibitions.Artists, ',', 1) AS int) WHERE Exhibitions.Museum = 'Modern Art Museum';


Question: PostgreSQL Advanced: show example 5.

BEGIN; UPDATE accounts SET balance = balance - 100.00 WHERE name = 'Alice'; -- etc etc COMMIT;

Explanation: Example from PostgreSQL documentation on Advanced.


Question: Generate PostgreSQL SQL for: Who wrote the episode that originally aired on March 1, 1998?

CREATE TABLE table_name_42 (written_by VARCHAR, original_airdate VARCHAR)

SELECT written_by FROM table_name_42 WHERE original_airdate = 'march 1, 1998';


Question: Generate PostgreSQL SQL for: What is the total pick number of Virginia Tech?

CREATE TABLE table_name_68 (pick VARCHAR, school VARCHAR)

SELECT COUNT(pick) FROM table_name_68 WHERE school = 'virginia tech';


Question: Find the total number of safety tests passed by US-based automakers in the "safety_testing" table.

CREATE TABLE safety_testing (id INT, automaker VARCHAR(50), country VARCHAR(50), tests_passed INT);

SELECT SUM(tests_passed) FROM safety_testing WHERE country = 'USA';


Question: Generate PostgreSQL SQL for: What is the lowest rank for a nation with 29 total medals, over 5 silvers, and under 16 bronze?

CREATE TABLE table_name_71 (rank INTEGER, bronze VARCHAR, silver VARCHAR, total VARCHAR)

SELECT MIN(rank) FROM table_name_71 WHERE silver > 5 AND total = 29 AND bronze < 16;


Question: Generate PostgreSQL SQL for: How many people attended Junction Oval?

CREATE TABLE table_name_17 (crowd INTEGER, venue VARCHAR)

SELECT SUM(crowd) FROM table_name_17 WHERE venue = 'junction oval';


Question: Generate PostgreSQL SQL for: What was the score of the game that had a loss of Wegman (2-6)?

CREATE TABLE table_name_7 (score VARCHAR, loss VARCHAR)

SELECT score FROM table_name_7 WHERE loss = 'wegman (2-6)';


Question: What is the total number of non-fungible tokens (NFTs) minted on the Flow network?

CREATE TABLE flow_nfts (nft_id INT, mint_timestamp TIMESTAMP);


Question: What is the minimum and maximum funding amount for startups founded by people from underrepresented racial or ethnic backgrounds in the sustainable energy sector?

CREATE TABLE startups(id INT, name TEXT, industry TEXT, foundation_date DATE, founder_race TEXT, funding FLOAT); INSERT INTO startups(id, name, industry, foundation_date, founder_race, funding) VALUES (1, 'GreenPower', 'Sustainable Energy', '2018-01-01', 'Hispanic', 2000000);

SELECT MIN(funding), MAX(funding) FROM startups WHERE industry = 'Sustainable Energy' AND founder_race IN ('African American', 'Hispanic', 'Native American', 'Pacific Islander');


Question: Delete records in the 'FuelingStations' table where 'station_type' is 'Hydrogen'

CREATE TABLE FuelingStations (station_id INT, station_type VARCHAR(10), PRIMARY KEY (station_id));

DELETE FROM FuelingStations WHERE station_type = 'Hydrogen';


Question: Identify the autonomous vehicles with the lowest price per mile in each country

CREATE TABLE autonomous_vehicles (vehicle_id INT, vehicle_name VARCHAR(255), price_per_mile DECIMAL(5,2), country VARCHAR(255));

SELECT vehicle_name, price_per_mile, country FROM (SELECT vehicle_name, price_per_mile, country, ROW_NUMBER() OVER (PARTITION BY country ORDER BY price_per_mile ASC) as rn FROM autonomous_vehicles) t WHERE rn = 1;


Question: Generate PostgreSQL SQL for: List all the names of schools with an endowment amount smaller than or equal to 10.

CREATE TABLE school (school_name VARCHAR, school_id VARCHAR); CREATE TABLE endowment (school_id VARCHAR, amount INTEGER)

SELECT T2.school_name FROM endowment AS T1 JOIN school AS T2 ON T1.school_id = T2.school_id GROUP BY T1.school_id HAVING SUM(T1.amount) <= 10;


Question: Which countries have the least number of impact investing organizations?

CREATE TABLE impact_investing_orgs (name TEXT, country TEXT); INSERT INTO impact_investing_orgs (name, country) VALUES ('Acme Impact', 'USA'), ('GreenTech Initiatives', 'Canada'), ('EcoVentures', 'USA'), ('Global Philanthropic', 'UK'), ('Sustainable Development Foundation', 'Brazil'), ('Green Initiatives', 'India');

SELECT country, COUNT(*) as org_count FROM impact_investing_orgs GROUP BY country ORDER BY org_count ASC;


Question: Generate PostgreSQL SQL for: What is the most lanes used in races with more than 1 heat and a winning mark of 7.25?

CREATE TABLE table_name_60 (lane INTEGER, heat VARCHAR, mark VARCHAR)

SELECT MAX(lane) FROM table_name_60 WHERE heat > 1 AND mark = '7.25';


Question: Generate PostgreSQL SQL for: What is the most bronze when the total is 14, and there are more than 6 gold?

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

SELECT MAX(bronze) FROM table_name_99 WHERE total = 14 AND gold > 6;


Question: Generate PostgreSQL SQL for: What is the height of Anthony Crater?

CREATE TABLE table_29418619_1 (height VARCHAR, name VARCHAR)

SELECT height FROM table_29418619_1 WHERE name = 'Anthony Crater';


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

select jsonb_path_query('[1,2,3]', '$[last ? (@.type() == "string")]');

SELECT count(*) FROM (select jsonb_path_query('[1,2,3]', '$[last ? (@.type() == "string")]')) AS _sub;


Question: What is the average prize pool per game for esports events in North America?

CREATE TABLE EsportsEvents (EventID INT, EventName VARCHAR(50), Game VARCHAR(50), Location VARCHAR(50), PrizePool DECIMAL(10,2)); INSERT INTO EsportsEvents (EventID, EventName, Game, Location, PrizePool) VALUES (1, 'Fortnite World Cup', 'Fortnite', 'New York, USA', 30000000.00); INSERT INTO EsportsEvents (EventID, EventName, Game, Location, PrizePool) VALUES (2, 'PUBG Global Invitational', 'PUBG', 'Berlin, Germany', 2000000.00); INSERT INTO EsportsEvents (EventID, EventName, Game, Location, PrizePool) VALUES (3, 'The International', 'Dota 2', 'Seattle, USA', 25000000.00); INSERT INTO EsportsEvents (EventID, EventName, Game, Location, PrizePool) VALUES (4, 'League of Legends World Championship', 'League of Legends', 'Paris, France', 6600000.00);

SELECT Game, AVG(PrizePool) AS AvgPrizePool FROM EsportsEvents WHERE Location LIKE '%USA%' GROUP BY Game;


Question: PostgreSQL regression test 'timestamptz': Write the SELECT query (example 298).

SELECT '2011-03-27 01:59:59'::timestamp AT TIME ZONE 'MSK';

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

SELECT count(*) FROM (SELECT '2011-03-27 01:59:59'::timestamp AT TIME ZONE 'MSK') AS _sub;


Question: PostgreSQL regression test 'sqljson': Write the SELECT query (example 103).

SELECT JSON_OBJECT(1: 1, '2': NULL, '3': 1, 4: NULL, '5': 'a' ABSENT ON NULL WITH UNIQUE RETURNING jsonb);

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

SELECT count(*) FROM (SELECT JSON_OBJECT(1: 1, '2': NULL, '3': 1, 4: NULL, '5': 'a' ABSENT ON NULL WITH UNIQUE RETURNING jsonb)) AS _sub;


Question: Delete all records from the marine_conservation_orgs table

CREATE TABLE marine_conservation_orgs (org_name TEXT, country TEXT, year_founded INTEGER);


Question: PostgreSQL regression test 'stats_import': Write the SELECT query (example 71).

SELECT *
FROM pg_stats
WHERE schemaname = 'stats_import'
AND tablename = 'test'
AND inherited = false
AND attname = 'id';

Explanation: Regression test for Stats Import in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT *
FROM pg_stats
WHERE schemaname = 'stats_import'
AND tablename = 'test'
AND inherited = false
AND attname = 'id') AS _sub;


Question: Find the average safety score of AI models created by African researchers since 2020.

CREATE TABLE ModelScores (model_id INT, score FLOAT, dev_region VARCHAR(255), model_year INT); INSERT INTO ModelScores (model_id, score, dev_region, model_year) VALUES (1, 8.5, 'Africa', 2020), (2, 9.2, 'Asia', 2021), (3, 8.8, 'Europe', 2022);

SELECT AVG(score) FROM ModelScores WHERE dev_region = 'Africa' AND model_year >= 2020;


Question: Generate PostgreSQL SQL for: Which To par is the highest one that has a Total smaller than 148?

CREATE TABLE table_name_89 (to_par INTEGER, total INTEGER)

SELECT MAX(to_par) FROM table_name_89 WHERE total < 148;


Question: Generate PostgreSQL SQL for: What Winner had a Prize of zł2,153,999?

CREATE TABLE table_name_22 (winner VARCHAR, prize VARCHAR)

SELECT winner FROM table_name_22 WHERE prize = 'zł2,153,999';


Question: PostgreSQL regression test 'oid8': Write the SELECT query (example 31).

SELECT o.* FROM OID8_TBL o WHERE o.f1 <= '1234';

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

SELECT count(*) FROM (SELECT o.* FROM OID8_TBL o WHERE o.f1 <= '1234') AS _sub;


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

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

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

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


Question: Generate PostgreSQL SQL for: What is the value of the item "Points" when the value of the item "Points against" is 272?

CREATE TABLE table_name_62 (points_for VARCHAR, points_against VARCHAR)

SELECT points_for FROM table_name_62 WHERE points_against = '272';


Question: Delete all records from table cargo_handling with port as 'Seattle'

CREATE TABLE cargo_handling (id INT PRIMARY KEY, cargo_id INT, port VARCHAR(20)); INSERT INTO cargo_handling (id, cargo_id, port) VALUES (1, 101, 'New York'), (2, 102, 'Seattle'), (3, 103, 'Buenos Aires');

DELETE FROM cargo_handling WHERE port = 'Seattle';


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

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


Question: Generate PostgreSQL SQL for: What's the part 3 of the verb in class 5?

CREATE TABLE table_1745843_6 (part_3 VARCHAR, class VARCHAR)

SELECT part_3 FROM table_1745843_6 WHERE class = '5';


Question: Generate PostgreSQL SQL for: What year was the play-by-play for Don Earle?

CREATE TABLE table_name_84 (year VARCHAR, play_by_play VARCHAR)

SELECT year FROM table_name_84 WHERE play_by_play = 'don earle';


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

CREATE TABLE tbl (c1 int,c2 int, c3 int, c4 box,
				UNIQUE(c1,c2) INCLUDE(c3,c4));

Explanation: DDL from PostgreSQL core regression test for Index Including.


Question: List all military equipment types and their corresponding sales revenue for the last quarter

CREATE TABLE equipment_sales (equipment_type VARCHAR(255), sale_date DATE, revenue INT); INSERT INTO equipment_sales (equipment_type, sale_date, revenue) VALUES ('Tank', '2021-04-01', 5000000), ('Tank', '2021-07-01', 6000000), ('Jet', '2021-05-01', 8000000), ('Jet', '2021-08-01', 9000000);

SELECT equipment_type, SUM(revenue) as total_revenue FROM equipment_sales WHERE sale_date BETWEEN DATE_SUB(CURDATE(), INTERVAL 3 MONTH) AND DATE_SUB(CURDATE(), INTERVAL 1 MONTH) GROUP BY equipment_type;


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

CREATE TABLE table_name_3 (date VARCHAR, week VARCHAR)

SELECT date FROM table_name_3 WHERE week = 5;


Question: What is the total salary expense for the company broken down by department?

CREATE TABLE Employees (EmployeeID int, Department varchar(20), Salary numeric(10,2)); INSERT INTO Employees (EmployeeID, Department, Salary) VALUES (1, 'IT', 75000.00), (2, 'IT', 70000.00), (3, 'HR', 60000.00), (4, 'Finance', 80000.00);

SELECT Department, SUM(Salary) FROM Employees GROUP BY Department;


Question: What is the average donation amount for 'international_donors' in the 'global_giving' table?

CREATE TABLE global_giving (donor_type VARCHAR(20), avg_donation DECIMAL(10,2)); INSERT INTO global_giving (donor_type, avg_donation) VALUES ('international_donors', 250.00), ('local_donors', 100.00);

SELECT AVG(avg_donation) FROM global_giving WHERE donor_type = 'international_donors';


Question: What is the maximum cargo weight handled by the port of Rotterdam in a single day, grouped by month?

CREATE TABLE cargo_handling (cargo_handling_id INT, port VARCHAR(255), cargo_weight INT, handling_date DATE);INSERT INTO cargo_handling (cargo_handling_id, port, cargo_weight, handling_date) VALUES (1, 'Rotterdam', 50000, '2022-01-01'), (2, 'Rotterdam', 55000, '2022-01-02');

SELECT EXTRACT(MONTH FROM handling_date) AS month, MAX(cargo_weight) FROM cargo_handling WHERE port = 'Rotterdam' GROUP BY month;


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

insert into rtest_t9 values (19, 'Record should go to rtest_t5 and t7');

Explanation: DML from PostgreSQL core regression test for Rules.


Question: What is the total calorie count of vegan dishes served at 'Plant Power'?

CREATE TABLE Restaurants (name text); INSERT INTO Restaurants (name) VALUES ('Plant Power'); CREATE TABLE Menu (name text, restaurant text, food text, calories integer, diet text); INSERT INTO Menu (name, restaurant, food, calories, diet) VALUES ('Plant Power', 'Vegan Lasagna', 600, 'Vegan'), ('Plant Power', 'Chickpea Salad', 450, 'Vegan');

SELECT SUM(calories) FROM Menu WHERE restaurant = 'Plant Power' AND diet = 'Vegan';


Question: What is the average network investment in the 'Europe' region over the last year?

CREATE TABLE network_investments (id INT, region VARCHAR(20), investment_date DATE, amount DECIMAL(10,2)); INSERT INTO network_investments (id, region, investment_date, amount) VALUES (1, 'Europe', '2022-01-01', 50000.00), (2, 'Asia', '2022-02-01', 75000.00), (3, 'Europe', '2022-03-01', 60000.00), (4, 'Africa', '2022-04-01', 45000.00);

SELECT AVG(amount) FROM network_investments WHERE region = 'Europe' AND investment_date BETWEEN DATE_SUB('2022-04-01', INTERVAL 1 YEAR) AND '2022-04-01';


Question: Generate PostgreSQL SQL for: What is the style for Giuseppe Bausilio?

CREATE TABLE table_name_31 (style VARCHAR, name VARCHAR)

SELECT style FROM table_name_31 WHERE name = 'giuseppe bausilio';


Question: Update the donation amount for donor 'Karen Smith' to $6000.

CREATE TABLE donations_update_2 (donor_id INT, donor_name VARCHAR(255), donation_amount INT); INSERT INTO donations_update_2 (donor_id, donor_name, donation_amount) VALUES (1, 'Karen Smith', 5000), (2, 'Brandon Johnson', 7000), (3, 'Sophia Rodriguez', 8000);

UPDATE donations_update_2 SET donation_amount = 6000 WHERE donor_name = 'Karen Smith';


Question: Generate PostgreSQL SQL for: What are the entry names of catalog with the attribute possessed by most entries.

CREATE TABLE Catalog_Contents_Additional_Attributes (catalog_entry_id VARCHAR, attribute_value VARCHAR); CREATE TABLE Catalog_Contents (catalog_entry_name VARCHAR, catalog_entry_id VARCHAR); CREATE TABLE Catalog_Contents_Additional_Attributes (attribute_value VARCHAR)

SELECT t1.catalog_entry_name FROM Catalog_Contents AS t1 JOIN Catalog_Contents_Additional_Attributes AS t2 ON t1.catalog_entry_id = t2.catalog_entry_id WHERE t2.attribute_value = (SELECT attribute_value FROM Catalog_Contents_Additional_Attributes GROUP BY attribute_value ORDER BY COUNT(*) DESC LIMIT 1);


Question: Insert a new record into the 'habitat_preservation' table with these values: 1, 'Asia', 'Habitat Protection Alliance', '2023-01-01', '2023-12-31'

CREATE TABLE habitat_preservation (id INT PRIMARY KEY, region VARCHAR(20), organization VARCHAR(30), start_date DATE, end_date DATE);

INSERT INTO habitat_preservation (id, region, organization, start_date, end_date) VALUES (1, 'Asia', 'Habitat Protection Alliance', '2023-01-01', '2023-12-31');


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

-- setup of malicious function
CREATE OR REPLACE FUNCTION f_leak(text) RETURNS bool
    COST 0.0000001 LANGUAGE plpgsql
    AS 'BEGIN RAISE NOTICE ''f_leak => %'', $1; RETURN true; END';

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


Question: How many community health workers are culturally competent in each region?

CREATE TABLE CulturalCompetency (CHW_ID INT, Region VARCHAR(50), Competency_Level VARCHAR(50)); INSERT INTO CulturalCompetency (CHW_ID, Region, Competency_Level) VALUES (1, 'North', 'Expert'), (2, 'South', 'Intermediate'), (3, 'East', 'Expert'), (4, 'West', 'Beginner');

SELECT c.Region, COUNT(*) as Competent_CHWs FROM CulturalCompetency c WHERE Competency_Level = 'Expert' GROUP BY c.Region;


Question: What was the total number of donations made in 'Texas' in the year 2020?

CREATE TABLE Donations (donation_id INT, region VARCHAR(20), amount DECIMAL(10,2), donation_year INT); INSERT INTO Donations (donation_id, region, amount, donation_year) VALUES (1, 'Texas', 1000.00, 2020), (2, 'Texas', 2000.00, 2020);

SELECT COUNT(*) FROM Donations WHERE region = 'Texas' AND donation_year = 2020;


Question: Show a query using PostgreSQL contrib extension 'dict_int' (example 28).

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


Question: How many marine species are there in the 'Coral Reef' subcategory?

CREATE TABLE marine_species_categories (species_id INTEGER, species_name VARCHAR(255), category VARCHAR(50), subcategory VARCHAR(50));

SELECT COUNT(species_id) FROM marine_species_categories WHERE subcategory = 'Coral Reef';


Question: List the teams that have not made any ticket sales

CREATE TABLE sports_teams (team_id INT, team_name VARCHAR(50)); INSERT INTO sports_teams (team_id, team_name) VALUES (1, 'TeamA'), (2, 'TeamB'), (3, 'TeamC'); CREATE TABLE ticket_sales (ticket_id INT, team_id INT, price DECIMAL(5,2)); INSERT INTO ticket_sales (ticket_id, team_id, price) VALUES (1, 1, 75.50), (2, 1, 85.20), (3, 2, 65.00), (4, 2, 75.00);

SELECT s.team_name FROM sports_teams s LEFT JOIN ticket_sales t ON s.team_id = t.team_id WHERE t.ticket_id IS NULL;


Question: What is the total number of students who have utilized assistive technology?

CREATE TABLE Assistive_Technology (student_id INT, accommodation VARCHAR(255)); INSERT INTO Assistive_Technology VALUES (1, 'Text-to-Speech');

SELECT COUNT(DISTINCT student_id) FROM Assistive_Technology;


Question: Generate PostgreSQL SQL for: How many games did the team play when they were 1-3?

CREATE TABLE table_13619053_4 (score VARCHAR, record VARCHAR)

SELECT COUNT(score) FROM table_13619053_4 WHERE record = '1-3';


Question: Which members have a gym membership and a yoga membership?

CREATE TABLE gym_members(member_id INT, name VARCHAR(50), start_date DATE, end_date DATE); INSERT INTO gym_members(member_id, name, start_date, end_date) VALUES (1, 'John Doe', '2021-01-01', '2022-12-31'); INSERT INTO gym_members(member_id, name, start_date, end_date) VALUES (2, 'Jane Smith', '2021-05-15', '2023-05-14'); CREATE TABLE yoga_members(member_id INT, name VARCHAR(50), start_date DATE, end_date DATE); INSERT INTO yoga_members(member_id, name, start_date, end_date) VALUES (1, 'John Doe', '2021-03-01', '2022-02-28'); INSERT INTO yoga_members(member_id, name, start_date, end_date) VALUES (3, 'Alice Johnson', '2021-06-01', '2023-05-31');

SELECT gm.member_id, gm.name FROM gym_members gm INNER JOIN yoga_members ym ON gm.member_id = ym.member_id;


Question: pgTAP test for Resultset (assertion 136).

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

Explanation: SQL assertion from pgTAP test suite for Resultset.


Question: List the total sales for each brand in the "makeup" category for the last quarter.

CREATE TABLE sales_quarterly (id INT, brand VARCHAR(100), category VARCHAR(100), sales_date DATE, revenue FLOAT);

SELECT brand, SUM(revenue) as total_sales FROM sales_quarterly WHERE category = 'makeup' AND sales_date >= DATE_TRUNC('quarter', CURRENT_DATE - INTERVAL '3 months') GROUP BY brand;


Question: What is the total biomass of fish in US farms that are managed by farmers with more than 5 years of experience?

CREATE TABLE us_farms (farmer_id INT, years_of_experience INT, biomass FLOAT); INSERT INTO us_farms (farmer_id, years_of_experience, biomass) VALUES (1, 7, 100.5), (2, 3, 50.2), (3, 6, 120.7);

SELECT SUM(biomass) FROM us_farms WHERE years_of_experience > 5;


Question: Generate PostgreSQL SQL for: What is the greatest lost where played is less than 9?

CREATE TABLE table_name_51 (lost INTEGER, played INTEGER)

SELECT MAX(lost) FROM table_name_51 WHERE played < 9;


Question: Generate PostgreSQL SQL for: What Chassis did Memo Gidley use?

CREATE TABLE table_name_37 (chassis VARCHAR, drivers VARCHAR)

SELECT chassis FROM table_name_37 WHERE drivers = 'memo gidley';


Question: Generate PostgreSQL SQL for: How many integrated allied-related are there?

CREATE TABLE table_11944282_1 (integrated VARCHAR, allied_related VARCHAR)

SELECT integrated FROM table_11944282_1 WHERE allied_related = 'Many';


Question: How many crime incidents occurred in the last week, broken down by day of the week?

CREATE TABLE incidents (iid INT, incident_time TIMESTAMP);

SELECT DATE_FORMAT(i.incident_time, '%W') AS day_of_week, COUNT(i.iid) FROM incidents i WHERE i.incident_time >= DATE_SUB(CURRENT_TIMESTAMP(), INTERVAL 1 WEEK) GROUP BY day_of_week;


Question: Which sustainable material has the highest total revenue in the ethical fashion industry?

CREATE TABLE orders (order_id INT, material VARCHAR(50), revenue DECIMAL(10,2)); INSERT INTO orders (order_id, material, revenue) VALUES (1, 'organic cotton', 100.00), (2, 'recycled polyester', 150.00), (3, 'organic cotton', 200.00);

SELECT material, SUM(revenue) AS total_revenue FROM orders GROUP BY material ORDER BY total_revenue DESC LIMIT 1;


Question: Generate PostgreSQL SQL for: What was Kerry's lowest number of votes where Other received 0.8% and Kerry 70.4%?

CREATE TABLE table_name_65 (kerry__number INTEGER, others__percentage VARCHAR, kerry__percentage VARCHAR)

SELECT MIN(kerry__number) FROM table_name_65 WHERE others__percentage = '0.8%' AND kerry__percentage = '70.4%';


Question: What is the total number of companies founded by people from underrepresented communities in the education sector?

CREATE TABLE Companies (id INT, name TEXT, industry TEXT, founders TEXT, diversity TEXT); INSERT INTO Companies (id, name, industry, founders, diversity) VALUES (1, 'EduForward', 'Education', 'Diverse Team', 'Underrepresented'); INSERT INTO Companies (id, name, industry, founders, diversity) VALUES (2, 'TechBoost', 'Technology', 'Non-Diverse Team', 'Not Underrepresented');

SELECT COUNT(*) FROM Companies WHERE industry = 'Education' AND diversity = 'Underrepresented';


Question: Which destinations had a YoY visitor growth rate above 50% in 2020 compared to 2019?

CREATE TABLE visitor_data (destination VARCHAR(50), year INT, visitors INT);

SELECT destination, ((visitors_2020 / NULLIF(visitors_2019, 0) - 1) * 100) as yoy_growth_rate FROM visitor_data WHERE year IN (2019, 2020) GROUP BY destination HAVING MAX(yoy_growth_rate) > 50;


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

SELECT JSON_QUERY(jsonb 'null', '$Xyz' PASSING 1 AS "Xyz");

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

SELECT count(*) FROM (SELECT JSON_QUERY(jsonb 'null', '$Xyz' PASSING 1 AS "Xyz")) AS _sub;


Question: pgTAP test for Hastap (assertion 175).

Explanation: SQL assertion from pgTAP test suite for Hastap.


Question: How many tour operators in Canada offer eco-friendly tours?

CREATE TABLE tour_operators (id INT, name TEXT, country TEXT, eco_friendly BOOLEAN); INSERT INTO tour_operators (id, name, country, eco_friendly) VALUES (1, 'Eco Tours Canada', 'Canada', true), (2, 'Nature Adventures', 'Canada', false), (3, 'Green Travels', 'Canada', true);

SELECT COUNT(*) FROM tour_operators WHERE country = 'Canada' AND eco_friendly = true;


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

SELECT COUNT(id) FROM xmltest WHERE xpath_exists('/myns:menu/myns:beers',data,ARRAY[ARRAY['myns','http://myns.com']]);

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

SELECT count(*) FROM (SELECT COUNT(id) FROM xmltest WHERE xpath_exists('/myns:menu/myns:beers',data,ARRAY[ARRAY['myns','http://myns.com']])) AS _sub;


Question: Generate PostgreSQL SQL for: What is the D 48 √ with a D 49 √ with r 9?

CREATE TABLE table_name_27 (d_48_√ VARCHAR, d_49_√ VARCHAR)

SELECT d_48_√ FROM table_name_27 WHERE d_49_√ = 'r 9';


Question: What is the number of patients who received group therapy for depression in clinics located in Texas?

CREATE TABLE clinics (clinic_id INT, clinic_name VARCHAR(50), city VARCHAR(50), state VARCHAR(50)); INSERT INTO clinics (clinic_id, clinic_name, city, state) VALUES (1, 'ClinicC', 'Houston', 'TX'), (2, 'ClinicD', 'Austin', 'TX'); CREATE TABLE patients (patient_id INT, patient_name VARCHAR(50), age INT, clinic_id INT, condition_id INT); INSERT INTO patients (patient_id, patient_name, age, clinic_id, condition_id) VALUES (1, 'James Doe', 35, 1, 1), (2, 'Jasmine Smith', 28, 1, 2), (3, 'Alice Johnson', 42, 2, 3); CREATE TABLE conditions (condition_id INT, condition_name VARCHAR(50)); INSERT INTO conditions (condition_id, condition_name) VALUES (1, 'Depression'), (2, 'Anxiety Disorder'), (3, 'Bipolar Disorder'); CREATE TABLE therapies (therapy_id INT, therapy_name VARCHAR(50), patient_id INT, therapy_type VARCHAR(50)); INSERT INTO therapies (therapy_id, therapy_name, patient_id, therapy_type) VALUES (1, 'Group Therapy', 1, 'Group Therapy'), (2, 'Individual Therapy', 2, 'Individual Therapy');

SELECT COUNT(*) FROM patients p JOIN clinics c ON p.clinic_id = c.clinic_id JOIN therapies t ON p.patient_id = t.patient_id JOIN conditions cond ON p.condition_id = cond.condition_id WHERE c.state = 'TX' AND cond.condition_name = 'Depression' AND t.therapy_type = 'Group Therapy';


Question: Update the energy rating of a property in the 'green_buildings' table with id 3 to 80.

CREATE TABLE green_buildings (id INT, square_footage FLOAT, energy_rating INT);

UPDATE green_buildings SET energy_rating = 80 WHERE id = 3;


Question: Identify the number of unique esports events and their types in the last 12 months, excluding 'Exhibition' events.

CREATE TABLE EsportsEvents (EventID INT, EventName TEXT, EventType TEXT, EventDate DATE); INSERT INTO EsportsEvents (EventID, EventName, EventType, EventDate) VALUES (1, 'ELC', 'League', '2022-01-01'), (2, 'DAC', 'Championship', '2022-02-15'), (3, 'GCS', 'Cup', '2021-12-10'), (4, 'WCS', 'Series', '2022-04-20'), (5, 'EPL', 'League', '2022-05-05'), (6, 'IEM', 'Cup', '2022-06-12'), (7, 'EXPO', 'Exhibition', '2022-07-01');

SELECT COUNT(DISTINCT EventID), EventType FROM EsportsEvents WHERE EventDate >= DATEADD(month, -12, GETDATE()) AND EventType != 'Exhibition' GROUP BY EventType;


Question: PostgreSQL Textsearch: show example 64.

SELECT * FROM ts_debug('english', 'Paris'); alias | description | token | dictionaries | dictionary | lexemes -----------+-----------------+-------+----------------+--------------+--------- asciiword | Word, all ASCII | Paris | {english_stem} | english_stem | {pari} CREATE TEXT SEARCH DICTIONARY my_synonym ( TEMPLATE = synonym, SYNONYMS = my_synonyms ); ALTER TEXT SEARCH CONFIGURATION english ALTER MAPPING FOR asciiword WITH my_synonym, english_stem; SELECT * FROM ts_debug('english', 'Paris'); alias | description | token | dictionaries | dictionary | lexemes -----------+-----------------+-------+---------------------------+------------+--------- asciiword | Word, all ASCII | Paris | {my_synonym,english_stem} | my_synonym | {paris};

Explanation: Example from PostgreSQL documentation on Textsearch.


Question: Calculate the total transaction amount for each customer in the "Customers" table, excluding transactions with amounts less than $100.

CREATE TABLE Customers (CustomerID INT, TransactionDate DATE, TransactionAmount DECIMAL(10,2));

SELECT CustomerID, SUM(TransactionAmount) as TotalTransactionAmount FROM Customers WHERE TransactionAmount >= 100 GROUP BY CustomerID;


Question: How many unique countries do players who have played Dota 2 come from?

CREATE TABLE players (id INT, name VARCHAR(50), age INT, game VARCHAR(50), country VARCHAR(50)); INSERT INTO players (id, name, age, game, country) VALUES (1, 'Jane Doe', 22, 'Dota 2', 'USA');

SELECT COUNT(DISTINCT country) AS num_countries FROM players WHERE game = 'Dota 2';


Question: How many satellites were launched by each country in the satellite_launches table?

CREATE TABLE satellite_launches (country VARCHAR(30), launch_year INT, satellites INT); INSERT INTO satellite_launches VALUES ('USA', 1958, 1), ('USSR', 1957, 1), ('USA', 1959, 3), ('USSR', 1960, 4), ('USA', 1961, 4), ('USSR', 1962, 3);

SELECT country, COUNT(satellites) OVER (PARTITION BY country) FROM satellite_launches;


Question: What is the maximum temperature recorded by any spacecraft during a space mission?

CREATE TABLE Spacecraft (SpacecraftID INT, MaximumTemperature FLOAT);

SELECT MAX(MaximumTemperature) FROM Spacecraft;


Question: Generate PostgreSQL SQL for: What was the result of the game on October 6, 1974?

CREATE TABLE table_14954150_1 (result VARCHAR, date VARCHAR)

SELECT result FROM table_14954150_1 WHERE date = 'October 6, 1974';


Question: Generate PostgreSQL SQL for: What College has a Player that is jermaine romans?

CREATE TABLE table_name_79 (college VARCHAR, player VARCHAR)

SELECT college FROM table_name_79 WHERE player = 'jermaine romans';


Question: What is the total number of refugee families supported by each organization in the last 3 months?

CREATE TABLE NGOs (NGOID int, NGOName varchar(50)); INSERT INTO NGOs (NGOID, NGOName) VALUES (1, 'World Vision'), (2, 'Catholic Relief Services'); CREATE TABLE RefugeeSupport (SupportID int, NGOID int, FamilyID int, SupportDate date); INSERT INTO RefugeeSupport (SupportID, NGOID, FamilyID, SupportDate) VALUES (1, 1, 1, '2022-05-01'), (2, 1, 2, '2022-06-01'), (3, 2, 1, '2022-07-01');

SELECT NGOName, COUNT(DISTINCT FamilyID) as SupportedFamilies FROM NGOs INNER JOIN RefugeeSupport ON NGOs.NGOID = RefugeeSupport.NGOID WHERE SupportDate >= DATE_SUB(CURRENT_DATE, INTERVAL 3 MONTH) GROUP BY NGOName;


Question: What are the names and locations of rural infrastructure projects with a budget over 300000?

CREATE TABLE rural_projects (id INT, name TEXT, location TEXT, budget FLOAT); INSERT INTO rural_projects (id, name, location, budget) VALUES (1, 'Water Supply', 'Kenya', 500000.00), (2, 'Electricity Grid', 'Tanzania', 200000.00), (3, 'Road Construction', 'Uganda', 400000.00);

SELECT name, location FROM rural_projects WHERE budget > 300000;


Question: What is the total number of inclusive housing units in Portland and San Francisco?

CREATE TABLE housing (id INT, units INT, city VARCHAR(20), inclusive BOOLEAN); INSERT INTO housing (id, units, city, inclusive) VALUES (1, 50, 'Portland', TRUE), (2, 75, 'San Francisco', TRUE), (3, 100, 'NYC', FALSE);

SELECT SUM(units) FROM housing WHERE inclusive = TRUE AND city IN ('Portland', 'San Francisco');


Question: List the donors who have donated more than $10,000 in total, and their corresponding donation dates.

CREATE TABLE Donors (DonorID int, DonorName varchar(50), Country varchar(50), AmountDonated float); INSERT INTO Donors (DonorID, DonorName, Country, AmountDonated) VALUES (1, 'John Doe', 'USA', 15000.00), (2, 'Jane Smith', 'Canada', 20000.00);

SELECT DonorName, DonationDate FROM Donors D JOIN Donations DON ON D.DonorID = DON.DonorID WHERE D.DonorID IN (SELECT DonorID FROM Donors WHERE AmountDonated > 10000.00);


Question: List all the unique investment products and their associated asset classes.

CREATE TABLE investment_products (id INT, name VARCHAR(50), asset_class VARCHAR(50)); INSERT INTO investment_products (id, name, asset_class) VALUES (1, 'Stock A', 'Equities'), (2, 'Bond B', 'Fixed Income'), (3, 'Mutual Fund C', 'Equities'), (4, 'ETF D', 'Commodities');

SELECT DISTINCT name, asset_class FROM investment_products;


Question: Generate PostgreSQL SQL for: What is the position with an overall less than 128 for Brigham Young college?

CREATE TABLE table_name_87 (position VARCHAR, overall VARCHAR, college VARCHAR)

SELECT position FROM table_name_87 WHERE overall < 128 AND college = 'brigham young';


Question: Generate PostgreSQL SQL for: What was Melbourne's score as the home team?

CREATE TABLE table_name_16 (home_team VARCHAR)

SELECT home_team AS score FROM table_name_16 WHERE home_team = 'melbourne';


Question: Show the number of new donors per month in 2022.

SELECT DATE_FORMAT(donation_date, '%Y-%m') as month, COUNT(DISTINCT id) as new_donors FROM donors WHERE YEAR(donation_date) = 2022 GROUP BY month;


Question: Determine the number of unique IP addresses associated with each threat category in the last 90 days.

SELECT Threat, COUNT(DISTINCT IP) as IPCount FROM ThreatIPs WHERE Timestamp >= DATE_SUB(CURRENT_TIMESTAMP, INTERVAL 90 DAY) GROUP BY Threat;


Question: What was the average funding received per community development initiative in Ghana from 2016 to 2018?

CREATE TABLE community_funding (initiative_id INT, country TEXT, funding INT, year INT); INSERT INTO community_funding (initiative_id, country, funding, year) VALUES (1, 'Ghana', 50000, 2016), (2, 'Ghana', 55000, 2017), (3, 'Ghana', 60000, 2018), (4, 'Ghana', 65000, 2019);

SELECT AVG(funding) FROM community_funding WHERE country = 'Ghana' AND year BETWEEN 2016 AND 2018;


Question: Generate PostgreSQL SQL for: Name the 20 questions when centerfold model is cherie witter

CREATE TABLE table_1566848_6 (centerfold_model VARCHAR)

SELECT 20 AS _questions FROM table_1566848_6 WHERE centerfold_model = 'Cherie Witter';


Question: How many units of each product type were sold in Michigan dispensaries in the past month?

CREATE TABLE ProductTypes (ProductTypeID INT, ProductType VARCHAR(100)); CREATE TABLE DispensaryTransactions (TransactionID INT, ProductTypeID INT, QuantitySold INT, TransactionDate DATE, DispensaryID INT);

SELECT PT.ProductType, SUM(DT.QuantitySold) as TotalQuantitySold FROM ProductTypes PT JOIN DispensaryTransactions DT ON PT.ProductTypeID = DT.ProductTypeID WHERE DT.TransactionDate >= DATEADD(month, -1, GETDATE()) AND DT.DispensaryID IN (SELECT DispensaryID FROM Dispensaries WHERE State = 'Michigan') GROUP BY PT.ProductType;


Question: Generate PostgreSQL SQL for: Which college have both players with position midfielder and players with position defender?

CREATE TABLE match_season (College VARCHAR, POSITION VARCHAR)

SELECT College FROM match_season WHERE POSITION = 'Midfielder' INTERSECT SELECT College FROM match_season WHERE POSITION = 'Defender';


Question: Generate PostgreSQL SQL for: What was the total number of games on January 20?

CREATE TABLE table_name_75 (game VARCHAR, january VARCHAR)

SELECT COUNT(game) FROM table_name_75 WHERE january = 20;


Question: Generate PostgreSQL SQL for: What source of wealth has a value of £5726m?

CREATE TABLE table_name_51 (source_of_wealth VARCHAR, value VARCHAR)

SELECT source_of_wealth FROM table_name_51 WHERE value = '£5726m';


Question: What was the total weight of minerals extracted by age group in the given dataset?

CREATE TABLE labor (employee_id INT, age_group VARCHAR(50), material VARCHAR(50), weight FLOAT); INSERT INTO labor (employee_id, age_group, material, weight) VALUES (1, '18-24', 'Iron', 500), (2, '25-34', 'Iron', 450), (3, '35-44', 'Iron', 400), (4, '45-54', 'Iron', 350), (5, '55-64', 'Iron', 300);

SELECT age_group, SUM(weight) as total_weight FROM labor GROUP BY age_group;


Question: Generate PostgreSQL SQL for: How much did the home team Hawthorn score?

CREATE TABLE table_name_5 (home_team VARCHAR)

SELECT home_team AS score FROM table_name_5 WHERE home_team = 'hawthorn';


Question: Generate PostgreSQL SQL for: What was round 7's lowest overall?

CREATE TABLE table_name_72 (overall INTEGER, round VARCHAR)

SELECT MIN(overall) FROM table_name_72 WHERE round = 7;


Question: Get the names of schools with accessibility ratings below 3.

CREATE TABLE schools (id INT, name VARCHAR(255), accessibility_rating INT);

SELECT name FROM schools WHERE accessibility_rating < 3;


Question: pgTAP test for Resultset (assertion 465).

SELECT * FROM check_test(
    isnt_empty( 'SELECT 1' ),
    true,
    'isnt_empty(sql)',
    '',
    ''
);


Question: What is the average horsepower of electric vehicles in the 2022 Detroit Auto Show?

CREATE TABLE AutoShow (Id INT, VehicleType VARCHAR(50), Event VARCHAR(100), Horsepower FLOAT); INSERT INTO AutoShow (Id, VehicleType, Event, Horsepower) VALUES (1, 'Electric', '2022 Detroit Auto Show', 350), (2, 'Hybrid', '2022 Detroit Auto Show', 250), (3, 'Gasoline', '2022 Detroit Auto Show', 200), (4, 'Electric', '2022 Shanghai Auto Show', 400), (5, 'Hybrid', '2022 Shanghai Auto Show', 300);

SELECT AVG(Horsepower) FROM AutoShow WHERE VehicleType = 'Electric' AND Event LIKE '%2022 Detroit Auto Show%';


Question: Generate PostgreSQL SQL for: What was the score of the game with 96 points?

CREATE TABLE table_name_85 (score VARCHAR, points VARCHAR)

SELECT score FROM table_name_85 WHERE points = 96;


Question: Which crop has the highest yield in 'crop_comparison' table?

CREATE TABLE crop_comparison (farmer VARCHAR(50), crop VARCHAR(50), yield INT); INSERT INTO crop_comparison (farmer, crop, yield) VALUES ('FarmerA', 'corn', 100), ('FarmerA', 'wheat', 80), ('FarmerB', 'corn', 110), ('FarmerB', 'wheat', 90), ('FarmerC', 'corn', 95), ('FarmerC', 'wheat', 75);

SELECT crop, MAX(yield) as highest_yield FROM crop_comparison GROUP BY crop;


Question: Get all aircraft with the engine 'CFM56'

CREATE TABLE aircraft (id INT PRIMARY KEY, model VARCHAR(50), engine VARCHAR(50)); INSERT INTO aircraft (id, model, engine) VALUES (101, '747', 'CFM56'), (102, 'A320', 'IAE V2500'), (103, 'A350', 'Rolls-Royce Trent XWB'), (104, '787', 'GE GEnx'), (105, '737', 'CFM56');

SELECT * FROM aircraft WHERE engine = 'CFM56';


Question: List all electric vehicle adoption statistics for France, including the year and the number of electric vehicles sold.

CREATE TABLE Adoption (Year INT, Country VARCHAR(255), EVsSold INT); INSERT INTO Adoption (Year, Country, EVsSold) VALUES (2018, 'France', 120000), (2019, 'France', 150000), (2020, 'France', 200000);

SELECT Year, EVsSold FROM Adoption WHERE Country = 'France';


Question: How many marine species are threatened with extinction?

CREATE TABLE marine_species_status (species TEXT, status TEXT);

SELECT COUNT(*) FROM marine_species_status WHERE status = 'Threatened';


Question: Generate PostgreSQL SQL for: What is the unformatted capacity per side if the size is 8in?

CREATE TABLE table_name_42 (unformatted_capacity_per_side VARCHAR, size VARCHAR)

SELECT unformatted_capacity_per_side FROM table_name_42 WHERE size = '8in';


Question: Generate PostgreSQL SQL for: What was the placing when the weight in kg was 58.0?

CREATE TABLE table_24915874_1 (placing VARCHAR, weight__kg_ VARCHAR)

SELECT placing FROM table_24915874_1 WHERE weight__kg_ = '58.0';


Question: Generate PostgreSQL SQL for: Who has a DCSF number of 3373?

CREATE TABLE table_name_19 (name VARCHAR, dcsf_number VARCHAR)

SELECT name FROM table_name_19 WHERE dcsf_number = 3373;


Question: What is the maximum price of organic cosmetics sourced from the United States?

CREATE TABLE products (product_id INT, name TEXT, is_organic BOOLEAN, price DECIMAL, source_country TEXT); INSERT INTO products (product_id, name, is_organic, price, source_country) VALUES (1, 'Lipstick', TRUE, 25.99, 'USA'); INSERT INTO products (product_id, name, is_organic, price, source_country) VALUES (2, 'Eye Shadow', FALSE, 23.49, 'Mexico');

SELECT MAX(price) FROM products WHERE is_organic = TRUE AND source_country = 'USA';


Question: pgTAP test for Unique (assertion 15).

SELECT * FROM check_test(
    col_is_unique( 'public', 'sometab', 'name'::name ),
    true,
    'col_is_unique( schema, table, column )',
    'Column sometab(name) should have a unique constraint',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Unique.


Question: Delete all records of non-vegan products in the 'haircare' category.

CREATE TABLE products (id INT, name VARCHAR(255), category VARCHAR(255), price DECIMAL(5,2), vegan BOOLEAN); INSERT INTO products (id, name, category, price, vegan) VALUES (1, 'Shampoo', 'haircare', 12.99, false), (2, 'Conditioner', 'haircare', 14.99, true), (3, 'Hair Spray', 'haircare', 7.99, false);

DELETE FROM products WHERE category = 'haircare' AND vegan = false;


Question: PostgreSQL regression test 'stats': Write the SELECT query (example 268).

SELECT stats_reset > :'wal_reset_ts'::timestamptz FROM pg_stat_wal;

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

SELECT count(*) FROM (SELECT stats_reset > :'wal_reset_ts'::timestamptz FROM pg_stat_wal) AS _sub;


Question: Generate PostgreSQL SQL for: How many platinum points were awarded when 70 silver points were awarded?

CREATE TABLE table_11254821_2 (points_awarded__platinum_ VARCHAR, points_awarded__silver_ VARCHAR)

SELECT points_awarded__platinum_ FROM table_11254821_2 WHERE points_awarded__silver_ = 70;


Question: What is the total number of sustainable tourism awards?

CREATE TABLE Destinations (destination_id INT, destination_name TEXT, country TEXT, awards INT); INSERT INTO Destinations (destination_id, destination_name, country, awards) VALUES (1, 'City A', 'Germany', 3), (2, 'City B', 'Switzerland', 5), (3, 'City C', 'Norway', 2);

SELECT SUM(awards) AS total_awards FROM Destinations;


Question: Generate PostgreSQL SQL for: What was the crowd when the away team was hawthorn?

CREATE TABLE table_name_72 (crowd INTEGER, away_team VARCHAR)

SELECT MIN(crowd) FROM table_name_72 WHERE away_team = 'hawthorn';


Question: Delete the record for the donor from Canada.

CREATE TABLE donors (id INT, name TEXT, country TEXT, amount_donated DECIMAL(10,2)); INSERT INTO donors (id, name, country, amount_donated) VALUES (1, 'Alice', 'United States', 5000.00), (2, 'Bob', 'Canada', 6000.00);

DELETE FROM donors WHERE country = 'Canada';


Question: Generate PostgreSQL SQL for: Which players made exactly 8 cuts?

CREATE TABLE table_20590020_2 (player VARCHAR, cuts_made VARCHAR)

SELECT player FROM table_20590020_2 WHERE cuts_made = 8;


Question: Write the DDL statement from PostgreSQL regression test 'create_table_like' (example 36).

CREATE TABLE test_like_4d (LIKE test_like_4 INCLUDING DEFAULTS INCLUDING GENERATED);

Explanation: DDL from PostgreSQL core regression test for Create Table Like.


Question: How many military bases are present in Germany?

CREATE TABLE MilitaryBases (ID INT, Country VARCHAR(20), Quantity INT); INSERT INTO MilitaryBases (ID, Country, Quantity) VALUES (1, 'Germany', 31);

SELECT Quantity FROM MilitaryBases WHERE Country = 'Germany';


Question: Show the names and costs of all military technologies in the 'communication' category.

CREATE TABLE military_tech (tech_name TEXT, category TEXT, cost INTEGER); INSERT INTO military_tech (tech_name, category, cost) VALUES ('UAV', 'Surveillance', 10000), ('Satellite', 'Communication', 15000), ('AI System', 'intelligence operations', 20000);

SELECT tech_name, cost FROM military_tech WHERE category = 'Communication';


Question: Insert a new rural healthcare worker into the "healthcare_workers" table.

CREATE TABLE healthcare_workers (id INT, name TEXT, age INT, position TEXT, hospital_id INT); CREATE TABLE rural_hospitals (id INT, name TEXT, location TEXT, state TEXT);

INSERT INTO healthcare_workers (id, name, age, position, hospital_id) VALUES (3, 'Maria Garcia', 35, 'Nurse', 3);


Question: Generate PostgreSQL SQL for: What is the lowest number conceded for the team that had less than 8 wins, scored 21, and had less than 23 points?

CREATE TABLE table_name_77 (conceded INTEGER, points VARCHAR, wins VARCHAR, scored VARCHAR)

SELECT MIN(conceded) FROM table_name_77 WHERE wins < 8 AND scored = 21 AND points < 23;


Question: Generate PostgreSQL SQL for: What is the highest Rank for Jason Kreis, with less than 305 matches?

CREATE TABLE table_name_67 (rank INTEGER, name VARCHAR, matches VARCHAR)

SELECT MAX(rank) FROM table_name_67 WHERE name = 'jason kreis' AND matches < 305;


Question: Generate PostgreSQL SQL for: For short patent type of protections, what type of PCT route is available?

CREATE TABLE table_2279413_1 (pct_route_available VARCHAR, type_of_protection VARCHAR)

SELECT pct_route_available FROM table_2279413_1 WHERE type_of_protection = 'short patent';


Question: Update the price of concert records for the artist 'Adele' to 150 in the 'concerts' table.

CREATE TABLE concerts (id INT, artist VARCHAR(255), city VARCHAR(255), tickets_sold INT, price DECIMAL(10,2));

UPDATE concerts SET price = 150 WHERE artist = 'Adele';


Question: Generate PostgreSQL SQL for: What is the division for the division semifinals playoffs?

CREATE TABLE table_1087659_2 (division VARCHAR, playoffs VARCHAR)

SELECT division FROM table_1087659_2 WHERE playoffs = 'division Semifinals';


Question: Generate PostgreSQL SQL for: What is the total bodyweight of everyone that has a Snatch of 153.0?

CREATE TABLE table_name_98 (bodyweight INTEGER, snatch VARCHAR)

SELECT SUM(bodyweight) FROM table_name_98 WHERE snatch = '153.0';


Question: Generate PostgreSQL SQL for: What's the number of the horse whose trainer is Kim Bailey?

CREATE TABLE table_20095300_1 (number INTEGER, trainer VARCHAR)

SELECT MAX(number) FROM table_20095300_1 WHERE trainer = 'Kim Bailey';


Question: PostgreSQL regression test 'compression_lz4': Write the SELECT query (example 42).

SELECT pg_column_compression(f1) FROM cmpart2;

Explanation: Regression test for Compression Lz4 in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT pg_column_compression(f1) FROM cmpart2) AS _sub;


Question: Generate PostgreSQL SQL for: What is the name of series episode 11-02's segment c?

CREATE TABLE table_15187735_11 (segment_c VARCHAR, series_ep VARCHAR)

SELECT segment_c FROM table_15187735_11 WHERE series_ep = '11-02';


Question: Generate PostgreSQL SQL for: What is the Award name with a Team name that is cougar robotics team?

CREATE TABLE table_name_53 (award_name VARCHAR, team_name VARCHAR)

SELECT award_name FROM table_name_53 WHERE team_name = 'cougar robotics team';


Question: How many sharks are there in the 'sharks' table?

CREATE TABLE sharks (id INT, name VARCHAR(255), location VARCHAR(255), status VARCHAR(255));

SELECT COUNT(*) FROM sharks WHERE status = 'alive';


Question: Generate PostgreSQL SQL for: What are the first names of all the students?


Question: Generate PostgreSQL SQL for: Tell me the total number of Bronze for futsal

CREATE TABLE table_name_67 (bronze VARCHAR, sport VARCHAR)

SELECT COUNT(bronze) FROM table_name_67 WHERE sport = 'futsal';


Question: Show a query using PostgreSQL contrib extension 'jsonb_plperl' (example 33).

SELECT roundtrip('[["string1", "string2"]]', 'ARRAY');

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


Question: Generate PostgreSQL SQL for: Which To par is of thomas aiken?

CREATE TABLE table_name_77 (to_par VARCHAR, player VARCHAR)

SELECT to_par FROM table_name_77 WHERE player = 'thomas aiken';


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

SELECT count(*) FROM float4tmp WHERE a >= -179.0;

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


Question: Generate PostgreSQL SQL for: What is the lowest finish that has a start greater than 27, with a year after 1985?

CREATE TABLE table_name_62 (finish INTEGER, start VARCHAR, year VARCHAR)

SELECT MIN(finish) FROM table_name_62 WHERE start > 27 AND year > 1985;


Question: What is the average explainability score for AI algorithms, by algorithm type, in the Middle Eastern region?

CREATE TABLE ai_algorithms (algorithm_id INT, algorithm_name VARCHAR(50), algorithm_type VARCHAR(50), region VARCHAR(50), explainability_score FLOAT); INSERT INTO ai_algorithms (algorithm_id, algorithm_name, algorithm_type, region, explainability_score) VALUES (1, 'AlgoO', 'Deep Learning', 'Middle East', 0.75), (2, 'AlgoP', 'Computer Vision', 'Middle East', 0.82), (3, 'AlgoQ', 'Deep Learning', 'Middle East', 0.80), (4, 'AlgoR', 'Rule-based', 'Middle East', 0.85);

SELECT algorithm_type, region, AVG(explainability_score) AS avg_explainability_score FROM ai_algorithms WHERE region = 'Middle East' GROUP BY algorithm_type, region;


Question: Generate PostgreSQL SQL for: How many gold medals for bellbrook HS with less than 1 silver?

CREATE TABLE table_name_73 (gold_medals VARCHAR, ensemble VARCHAR, silver_medals VARCHAR)

SELECT COUNT(gold_medals) FROM table_name_73 WHERE ensemble = 'bellbrook hs' AND silver_medals < 1;


Question: Generate PostgreSQL SQL for: What's the lowest rank of the United States with a time less than 24.63?

CREATE TABLE table_name_74 (rank INTEGER, nationality VARCHAR, time VARCHAR)

SELECT MIN(rank) FROM table_name_74 WHERE nationality = 'united states' AND time < 24.63;


Question: What is the total number of books, by genre, published by presses in India and Nigeria?

CREATE TABLE books (id INT, title VARCHAR(255), genre VARCHAR(255), press_location VARCHAR(255)); INSERT INTO books (id, title, genre, press_location) VALUES (1, 'Book1', 'Fiction', 'India'), (2, 'Book2', 'Non-fiction', 'Nigeria'); CREATE TABLE presses (id INT, name VARCHAR(255), location VARCHAR(255)); INSERT INTO presses (id, name, location) VALUES (1, 'Press1', 'India'), (2, 'Press2', 'Nigeria');

SELECT genre, COUNT(*) as total FROM books JOIN presses ON books.press_location = presses.location WHERE presses.location IN ('India', 'Nigeria') GROUP BY genre;


Question: What is the total amount donated to each organization type?

CREATE TABLE Donations (DonationID int, Amount decimal, OrganizationType text); INSERT INTO Donations (DonationID, Amount, OrganizationType) VALUES (1, 5000, 'Environment'); INSERT INTO Donations (DonationID, Amount, OrganizationType) VALUES (2, 7000, 'Health'); INSERT INTO Donations (DonationID, Amount, OrganizationType) VALUES (3, 3000, 'Education'); INSERT INTO Donations (DonationID, Amount, OrganizationType) VALUES (4, 2000, 'Environment'); CREATE TABLE OrganizationTypes (OrganizationTypeID int, OrganizationType text); INSERT INTO OrganizationTypes (OrganizationTypeID, OrganizationType) VALUES (1, 'Environment'); INSERT INTO OrganizationTypes (OrganizationTypeID, OrganizationType) VALUES (2, 'Health'); INSERT INTO OrganizationTypes (OrganizationTypeID, OrganizationType) VALUES (3, 'Education');

SELECT OrganizationType, SUM(Amount) as TotalDonation FROM Donations JOIN OrganizationTypes ON Donations.OrganizationType = OrganizationTypes.OrganizationType GROUP BY OrganizationType;


Question: Generate PostgreSQL SQL for: What was the score with a goal of 16?

CREATE TABLE table_name_93 (score VARCHAR, goal VARCHAR)

SELECT score FROM table_name_93 WHERE goal = 16;


Question: Generate PostgreSQL SQL for: What did Steve Stricker score?

CREATE TABLE table_name_54 (score VARCHAR, player VARCHAR)

SELECT score FROM table_name_54 WHERE player = 'steve stricker';


Question: Find the number of players who achieved level 10 or above in 'PuzzleGame' in 'SA' region.

CREATE TABLE PuzzleGame (playerID INT, region VARCHAR(5), level INT); INSERT INTO PuzzleGame (playerID, region, level) VALUES (1, 'SA', 12), (2, 'SA', 15), (3, 'SA', 8), (4, 'EU', 20);

SELECT COUNT(*) FROM PuzzleGame WHERE region = 'SA' AND level >= 10;


Question: Identify the community development initiatives in India with the highest expenditure in 2021.

CREATE TABLE community_initiatives (id INT, country VARCHAR(50), initiative VARCHAR(50), year INT, expenditure DECIMAL(10,2)); INSERT INTO community_initiatives (id, country, initiative, year, expenditure) VALUES (1, 'India', 'Healthcare Center', 2021, 200000.00), (2, 'India', 'Education Building', 2021, 250000.00);

SELECT initiative, SUM(expenditure) AS total_expenditure FROM community_initiatives WHERE country = 'India' AND year = 2021 GROUP BY initiative ORDER BY total_expenditure DESC LIMIT 1;


Question: Generate PostgreSQL SQL for: Which Start has a 0 Conv, 0 Pens and 8 Tries?

CREATE TABLE table_name_54 (start VARCHAR, tries VARCHAR, conv VARCHAR, pens VARCHAR)

SELECT start FROM table_name_54 WHERE conv = '0' AND pens = '0' AND tries = '8';


Question: What is the total weight of cruelty-free ingredients for each product?

CREATE TABLE product (product_id INT, product_name TEXT); CREATE TABLE ingredient (ingredient_id INT, product_id INT, weight FLOAT, cruelty_free BOOLEAN); INSERT INTO product VALUES (1, 'Lipstick'), (2, 'Moisturizer'); INSERT INTO ingredient VALUES (1, 1, 50.0, true), (2, 1, 25.0, false), (3, 2, 30.0, true);

SELECT p.product_name, SUM(i.weight) FROM product p JOIN ingredient i ON p.product_id = i.product_id WHERE i.cruelty_free = true GROUP BY p.product_name;


Question: Generate PostgreSQL SQL for: Average total for jim furyk?

CREATE TABLE table_name_33 (total INTEGER, player VARCHAR)

SELECT AVG(total) FROM table_name_33 WHERE player = 'jim furyk';


Question: Get the details of the defense contract with the second highest value

CREATE TABLE second_highest_contracts (id INT, contract_type VARCHAR(255), contract_value INT); INSERT INTO second_highest_contracts (id, contract_type, contract_value) VALUES (1, 'Service', 5000000), (2, 'Supply', 7000000), (3, 'Research', 6000000);

SELECT * FROM second_highest_contracts WHERE contract_value = (SELECT MAX(contract_value) FROM second_highest_contracts WHERE contract_value < (SELECT MAX(contract_value) FROM second_highest_contracts));


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

CREATE TABLE eager_agg_tab_ml_p3 PARTITION OF eager_agg_tab_ml FOR VALUES FROM (20) TO (30) PARTITION BY RANGE(x);

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


Question: Generate PostgreSQL SQL for: What is the Date with a Score with 86–108?

CREATE TABLE table_name_7 (date VARCHAR, score VARCHAR)

SELECT date FROM table_name_7 WHERE score = '86–108';


Question: What is the average depth of the 'Indian Ocean' in the ocean_floor_mapping table?

CREATE TABLE ocean_floor_mapping (location TEXT, depth INTEGER); INSERT INTO ocean_floor_mapping (location, depth) VALUES ('Challenger Deep', 10994), ('Mariana Trench', 10972), ('Tonga Trench', 10823), ('Indian Ocean', 4665);

SELECT AVG(depth) FROM ocean_floor_mapping WHERE location = 'Indian Ocean';


Question: Generate PostgreSQL SQL for: What is the rank of the player who got 58179 in yardage?

CREATE TABLE table_18686317_1 (rank VARCHAR, yardage VARCHAR)

SELECT rank FROM table_18686317_1 WHERE yardage = 58179;


Question: List all factories in regions with a low percentage of sustainable textile sourcing, ordered alphabetically by factory name.

CREATE TABLE Factories (FactoryID int, FactoryName varchar(50), Region varchar(50)); INSERT INTO Factories (FactoryID, FactoryName, Region) VALUES (1, 'EcoFactory', 'Asia'); INSERT INTO Factories (FactoryID, FactoryName, Region) VALUES (2, 'GreenManufacturing', 'Europe'); CREATE TABLE Sourcing (FactoryID int, SustainableSourcePercentage decimal(5,2)); INSERT INTO Sourcing (FactoryID, SustainableSourcePercentage) VALUES (1, 0.60); INSERT INTO Sourcing (FactoryID, SustainableSourcePercentage) VALUES (2, 0.70);

SELECT f.FactoryName FROM Factories f INNER JOIN Sourcing s ON f.FactoryID = s.FactoryID WHERE s.SustainableSourcePercentage < 0.75 GROUP BY f.FactoryName ORDER BY f.FactoryName ASC;