Question: Which food products have been recalled due to contamination in the last 6 months?

CREATE TABLE recalls (id INT, date TEXT, product TEXT, reason TEXT); INSERT INTO recalls (id, date, product, reason) VALUES (1, '2022-01-01', 'Spinach', 'Contamination');

SELECT product, reason FROM recalls WHERE date > DATE_SUB(CURRENT_DATE, INTERVAL 6 MONTH) AND reason = 'Contamination';


Question: Generate PostgreSQL SQL for: what is the goals when the country is wal, the name is smith and apps is more than 0?

CREATE TABLE table_name_83 (goals INTEGER, apps VARCHAR, country VARCHAR, name VARCHAR)

SELECT SUM(goals) FROM table_name_83 WHERE country = 'wal' AND name = 'smith' AND apps > 0;


Question: Generate PostgreSQL SQL for: What is the total number on roll for Shelly Park school?

CREATE TABLE table_name_7 (roll VARCHAR, name VARCHAR)

SELECT COUNT(roll) FROM table_name_7 WHERE name = 'shelly park school';


Question: Generate PostgreSQL SQL for: What was the music video that was from the album High Society, with a length of 3:50?

CREATE TABLE table_name_91 (music_video VARCHAR, album VARCHAR, length VARCHAR)

SELECT music_video FROM table_name_91 WHERE album = 'high society' AND length = '3:50';


Question: Increase the value of military equipment sales by 15% for 'South Asia' in 2023

CREATE TABLE military_sales_11 (id INT, region VARCHAR, year INT, value FLOAT);

UPDATE military_sales_11 SET value = value * 1.15 WHERE region = 'South Asia' AND year = 2023;


Question: Retrieve the total production and reserves for oil fields in the USA.

CREATE TABLE OilFields (FieldID INT, FieldName VARCHAR(50), Country VARCHAR(50), Production INT, Reserves INT); INSERT INTO OilFields (FieldID, FieldName, Country, Production, Reserves) VALUES (1, 'Galaxy', 'USA', 20000, 500000); INSERT INTO OilFields (FieldID, FieldName, Country, Production, Reserves) VALUES (2, 'Apollo', 'Canada', 15000, 400000);

SELECT Country, SUM(Production) AS Total_Production, SUM(Reserves) AS Total_Reserves FROM OilFields WHERE Country = 'USA' GROUP BY Country;


Question: Generate PostgreSQL SQL for: How many steals did jasmine wynne have?

CREATE TABLE table_23346303_4 (steals VARCHAR, player VARCHAR)

SELECT steals FROM table_23346303_4 WHERE player = 'Jasmine Wynne';


Question: Generate PostgreSQL SQL for: Name the torque of the engine is d5244 t5

CREATE TABLE table_1147701_5 (torque__nm VARCHAR, engine_code VARCHAR)

SELECT torque__nm AS @rpm_ FROM table_1147701_5 WHERE engine_code = 'D5244 T5';


Question: Generate PostgreSQL SQL for: Name the date for result loss for duke

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

SELECT date FROM table_21092444_1 WHERE result = 'Loss' AND opponent = 'Duke';


Question: What are the product codes and names for products that share the same suppliers as product 'A101'?

CREATE TABLE Suppliers (product_code TEXT, supplier_id INTEGER); INSERT INTO Suppliers (product_code, supplier_id) VALUES ('A101', 123), ('B203', 123), ('C405', 456), ('A101', 789);

SELECT s2.product_code, p.product_name FROM Suppliers s1 JOIN Suppliers s2 ON s1.supplier_id = s2.supplier_id JOIN Products p ON s2.product_code = p.product_code WHERE s1.product_code = 'A101' AND s1.product_code != s2.product_code;


Question: How many users from the United States have played the virtual reality game "Cybernetic Realms" in the last month?

CREATE TABLE users (id INT, country VARCHAR(50), game VARCHAR(50), last_played DATETIME); INSERT INTO users VALUES (1, 'United States', 'Cybernetic Realms', '2022-02-03 16:20:00'); INSERT INTO users VALUES (2, 'Canada', 'Cybernetic Realms', '2022-02-10 09:35:00');

SELECT COUNT(*) FROM users WHERE country = 'United States' AND game = 'Cybernetic Realms' AND last_played >= DATE_SUB(NOW(), INTERVAL 1 MONTH);


Question: Generate PostgreSQL SQL for: How many judges points did the couple ranked at number 5 have?

CREATE TABLE table_19744915_22 (judges INTEGER, rank VARCHAR)

SELECT MAX(judges) FROM table_19744915_22 WHERE rank = 5;


Question: What is the number of disability support programs offered, partitioned by location and ordered from highest to lowest?

CREATE TABLE Disability_Support_Programs (Location VARCHAR(20), Program VARCHAR(50), Type VARCHAR(20)); INSERT INTO Disability_Support_Programs VALUES ('Campus A', 'Assistive Technology', 'Resource Center'), ('Campus A', 'ASL Interpretation', 'Service'), ('Campus A', 'Mobility Support', 'Service'), ('Campus B', 'Assistive Technology', 'Resource Center'), ('Campus B', 'ASL Interpretation', 'Service'), ('Campus B', 'Mobility Support', 'Service'), ('Campus C', 'Assistive Technology', 'Resource Center'), ('Campus C', 'ASL Interpretation', 'Service');

SELECT Location, COUNT(*) as Number_of_Programs, RANK() OVER (ORDER BY COUNT(*) DESC) as Rank FROM Disability_Support_Programs GROUP BY Location ORDER BY Rank;


Question: Generate PostgreSQL SQL for: Who was Footscray's opponent on June 15th of 1968?

CREATE TABLE table_name_54 (home_team VARCHAR, away_team VARCHAR)

SELECT home_team FROM table_name_54 WHERE away_team = 'footscray';


Question: Generate PostgreSQL SQL for: Which 1st leg has a Team #1 of ummc ekaterinburg?

CREATE TABLE table_name_33 (team__number1 VARCHAR)

SELECT 1 AS st_leg FROM table_name_33 WHERE team__number1 = 'ummc ekaterinburg';


Question: Show a query using PostgreSQL contrib extension 'pgstattuple' (example 62).

select pgstattuple_approx((select reltoastrelid from pg_class where relname = 'test'));

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


Question: Generate PostgreSQL SQL for: Which Home team had attendance 160?

CREATE TABLE table_name_91 (home_team VARCHAR, attendance VARCHAR)

SELECT home_team FROM table_name_91 WHERE attendance = '160';


Question: Generate PostgreSQL SQL for: Who directed the episode with production code 177605?

CREATE TABLE table_26561506_1 (directed_by VARCHAR, production_code VARCHAR)

SELECT directed_by FROM table_26561506_1 WHERE production_code = 177605;


Question: What is the minimum total revenue for the telecom provider in all regions?

CREATE TABLE revenues (revenue FLOAT, region VARCHAR(20)); INSERT INTO revenues (revenue, region) VALUES (120000, 'Southern'), (150000, 'Northern'), (180000, 'Western'), (200000, 'Northern'), (250000, 'Eastern'); CREATE TABLE minimum_revenue (min_revenue FLOAT); INSERT INTO minimum_revenue (min_revenue) VALUES (100000);


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

CREATE VIEW temp_view_test.v2 AS SELECT * FROM base_table;

Explanation: DDL from PostgreSQL core regression test for Create View.


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

CREATE TABLE tableam_parted_a_heap2 PARTITION OF tableam_parted_heap2 FOR VALUES IN ('a');

Explanation: DDL from PostgreSQL core regression test for Create Am.


Question: Add a new record to the "routes" table with the following data: route_id = 5, origin = "Seattle", destination = "New York", distance = 2500, and eta = '2022-07-01'

CREATE TABLE routes (route_id INT, origin VARCHAR(50), destination VARCHAR(50), distance INT, eta DATE);

INSERT INTO routes (route_id, origin, destination, distance, eta) VALUES (5, 'Seattle', 'New York', 2500, '2022-07-01');


Question: Generate PostgreSQL SQL for: What was the outcome when the oppenent was serena williams venus williams and had a hard surface?

CREATE TABLE table_name_60 (outcome VARCHAR, opponents_in_the_final VARCHAR, surface VARCHAR)

SELECT outcome FROM table_name_60 WHERE opponents_in_the_final = 'serena williams venus williams' AND surface = 'hard';


Question: What is the most common treatment type for patients in Germany?

CREATE SCHEMA mental_health; USE mental_health; CREATE TABLE patients (patient_id INT, diagnosis VARCHAR(50), age INT, country VARCHAR(50)); CREATE TABLE treatments (treatment_id INT, patient_id INT, treatment_type VARCHAR(50), treatment_date DATE, country VARCHAR(50)); INSERT INTO treatments VALUES (4, 5, 'psychotherapy', '2021-01-01', 'Germany');

SELECT treatment_type, COUNT(*) FROM treatments JOIN patients ON treatments.patient_id = patients.patient_id WHERE patients.country = 'Germany' GROUP BY treatment_type ORDER BY COUNT(*) DESC LIMIT 1;


Question: What is the minimum budget for all resilience projects in the infrastructure development database?

CREATE TABLE if not exists Projects (id INT, name VARCHAR(50), type VARCHAR(50), budget DECIMAL(10,2)); INSERT INTO Projects (id, name, type, budget) VALUES (1, 'Seawall', 'Resilience', 5000000.00), (2, 'Floodgate', 'Resilience', 3000000.00), (3, 'Bridge', 'Transportation', 8000000.00), (4, 'Highway', 'Transportation', 12000000.00), (5, 'Levee', 'Resilience', 2000000.00), (6, 'Pump Station', 'Resilience', 1500000.00);

SELECT MIN(budget) FROM Projects WHERE type = 'Resilience';


Question: PL/pgSQL test: Plpgsql Domain (example 71).

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


Question: What is the minimum number of visitors to eco-friendly accommodations in North America?

CREATE TABLE accommodations (id INT, name TEXT, continent TEXT, type TEXT, visitors INT); INSERT INTO accommodations (id, name, continent, type, visitors) VALUES (1, 'Eco Lodge', 'North America', 'Eco-friendly', 1500), (2, 'Green Hotel', 'North America', 'Eco-friendly', 1000);

SELECT MIN(visitors) FROM accommodations WHERE continent = 'North America' AND type = 'Eco-friendly';


Question: Generate PostgreSQL SQL for: What was the attendance at the Denver game?

CREATE TABLE table_name_59 (location_attendance VARCHAR, team VARCHAR)

SELECT location_attendance FROM table_name_59 WHERE team = 'denver';


Question: Insert new records into the "humanitarian_aid" table for the following disaster_id, country_name, aid_amount, and aid_date values: (301, 'Bangladesh', 50000, '2021-12-25'), (302, 'Pakistan', 75000, '2021-12-27'), and (303, 'Nepal', 60000, '2021-12-30')

CREATE TABLE humanitarian_aid (disaster_id INT, country_name VARCHAR(50), aid_amount INT, aid_date DATE);


Question: How many graduate students in the Business department have not published any papers in the year 2019?

CREATE TABLE GraduateStudents (StudentID INT, Name VARCHAR(50), Department VARCHAR(50), Publications INT, PublicationYear INT);

SELECT COUNT(StudentID) FROM GraduateStudents WHERE Department = 'Business' AND Publications = 0 AND PublicationYear = 2019;


Question: Generate PostgreSQL SQL for: What day was the score 1-0?

CREATE TABLE table_name_39 (date VARCHAR, score VARCHAR)

SELECT date FROM table_name_39 WHERE score = '1-0';


Question: Generate PostgreSQL SQL for: what is the date when the away team is newport county?

CREATE TABLE table_name_98 (date VARCHAR, away_team VARCHAR)

SELECT date FROM table_name_98 WHERE away_team = 'newport county';


Question: List the total waste generation figures for each region, excluding regions with a population under 500,000.

CREATE TABLE WasteGeneration (id INT, area VARCHAR(10), amount INT, region VARCHAR(10)); INSERT INTO WasteGeneration (id, area, amount, region) VALUES (1, 'Area1', 35000, 'RegionA'), (2, 'Area2', 20000, 'RegionA'), (3, 'Area3', 15000, 'RegionB'), (4, 'Area4', 10000, 'RegionB'); CREATE TABLE Population (id INT, region VARCHAR(10), population INT); INSERT INTO Population (id, region, population) VALUES (1, 'RegionA', 700000), (2, 'RegionB', 600000);

SELECT W.region, SUM(W.amount) FROM WasteGeneration W INNER JOIN Population P ON W.region = P.region WHERE P.population >= 500000 GROUP BY W.region;


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

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

SELECT count(*) FROM (select jsonb_path_query('"10-03-2017"', '$.datetime("dd-mm-yyyy")')) AS _sub;


Question: What is the minimum revenue generated from any sustainable tour in the USA?

CREATE TABLE usa_tours (id INT, type VARCHAR(255), revenue FLOAT); INSERT INTO usa_tours (id, type, revenue) VALUES (1, 'Sustainable', 700.00), (2, 'Cultural', 800.00);

SELECT MIN(revenue) FROM usa_tours WHERE type = 'Sustainable';


Question: What is the maximum range for electric vehicles in the US?

CREATE TABLE EVs (Id INT PRIMARY KEY, Make VARCHAR(50), Model VARCHAR(50), Range INT, Country VARCHAR(50));

SELECT MAX(Range) FROM EVs WHERE Country = 'United States';


Question: Generate PostgreSQL SQL for: With a Tally of 0-14, what is the Rank in Kilkenny County?

CREATE TABLE table_name_3 (rank VARCHAR, county VARCHAR, tally VARCHAR)

SELECT COUNT(rank) FROM table_name_3 WHERE county = 'kilkenny' AND tally = '0-14';


Question: Determine the number of unique garment types present in the 'GarmentProduction' table but not present in the 'GarmentSales' table.

CREATE TABLE GarmentProduction (garment_type VARCHAR(50)); INSERT INTO GarmentProduction (garment_type) VALUES ('T-Shirt'), ('Jeans'), ('Hoodie'); CREATE TABLE GarmentSales (garment_type VARCHAR(50)); INSERT INTO GarmentSales (garment_type) VALUES ('T-Shirt'), ('Jackets');

SELECT COUNT(DISTINCT garment_type) FROM GarmentProduction WHERE garment_type NOT IN (SELECT garment_type FROM GarmentSales);


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

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

SELECT count(*) FROM (select daterange('2000-01-10'::date, '2000-01-11'::date, '(]')) AS _sub;


Question: Show a SQL definition from the postgrest project (big_schema, item 28).

CREATE FUNCTION apflora.ap_insert_add_apart() RETURNS trigger
    LANGUAGE plpgsql
    AS $$
BEGIN
  INSERT INTO
    apflora.apart (ap_id, art_id)
  VALUES (NEW.id, NEW.art_id);
  RETURN NEW;
END;
$$;

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


Question: Which teachers have participated in more than 5 professional development courses in the last year?

CREATE TABLE teachers (teacher_id INT, teacher_name VARCHAR(100)); CREATE TABLE professional_development_courses (course_id INT, teacher_id INT, course_name VARCHAR(100), date DATE);

SELECT t.teacher_id, t.teacher_name, COUNT(pdc.course_id) as num_courses FROM teachers t JOIN professional_development_courses pdc ON t.teacher_id = pdc.teacher_id WHERE pdc.date >= DATE_SUB(CURRENT_DATE(), INTERVAL 1 YEAR) GROUP BY t.teacher_id HAVING num_courses > 5;


Question: How many accessible taxi trips were there in the 'east' region in January 2022?

CREATE TABLE taxi_trips (trip_id INT, region_id INT, trip_date DATE, is_accessible BOOLEAN); INSERT INTO taxi_trips (trip_id, region_id, trip_date, is_accessible) VALUES (1, 1, '2022-01-01', true), (2, 2, '2022-01-02', false), (3, 3, '2022-01-03', true), (4, 2, '2022-01-04', false);

SELECT COUNT(*) FROM taxi_trips t WHERE t.region_id = (SELECT region_id FROM regions WHERE region_name = 'east') AND t.trip_date BETWEEN '2022-01-01' AND '2022-01-31' AND t.is_accessible = true;


Question: Generate PostgreSQL SQL for: Which Mountain Peak has a Region of baja california, and a Location of 28.1301°n 115.2206°w?

CREATE TABLE table_name_87 (mountain_peak VARCHAR, region VARCHAR, location VARCHAR)

SELECT mountain_peak FROM table_name_87 WHERE region = 'baja california' AND location = '28.1301°n 115.2206°w';


Question: Generate PostgreSQL SQL for: How much Population density (per km²) has a Name of total northern villages, and a Population (2006) larger than 11414?

CREATE TABLE table_name_98 (population_density__per_km²_ VARCHAR, name VARCHAR, population__2006_ VARCHAR)

SELECT COUNT(population_density__per_km²_) FROM table_name_98 WHERE name = 'total northern villages' AND population__2006_ > 11414;


Question: Generate PostgreSQL SQL for: who was the incoming manager for the 12th position in the table

CREATE TABLE table_26914759_3 (incoming_manager VARCHAR, position_in_table VARCHAR)

SELECT incoming_manager FROM table_26914759_3 WHERE position_in_table = '12th';


Question: List the fair trade certified factories in the factories table.

CREATE TABLE factories (factory_id INT, factory_name TEXT, is_fair_trade_certified BOOLEAN); INSERT INTO factories VALUES (1, 'Green Factory', TRUE); INSERT INTO factories VALUES (2, 'Eco-friendly Solutions', FALSE);

SELECT factory_name FROM factories WHERE is_fair_trade_certified = TRUE;


Question: What is the total number of public works projects completed in 2019 and 2020 for each district?

CREATE TABLE PublicWorks (id INT, district VARCHAR(20), year INT, completed INT); INSERT INTO PublicWorks (id, district, year, completed) VALUES (1, 'Downtown', 2019, 1), (2, 'Uptown', 2020, 1), (3, 'Downtown', 2020, 1);

SELECT district, COUNT(*) as num_projects FROM PublicWorks WHERE year IN (2019, 2020) GROUP BY district;


Question: What is the percentage of total streams for each artist?

CREATE TABLE AlbumStreams (AlbumID int, SongID int, StreamCount int, ArtistID int); INSERT INTO AlbumStreams (AlbumID, SongID, StreamCount, ArtistID) VALUES (1, 1, 1000, 1), (2, 2, 2000, 2), (3, 3, 1500, 3), (4, 4, 2500, 4), (5, 5, 1800, 5);

SELECT Artists.ArtistName, (SUM(AlbumStreams.StreamCount) / (SELECT SUM(StreamCount) FROM AlbumStreams) * 100) as Percentage FROM Artists INNER JOIN AlbumStreams ON Artists.ArtistID = AlbumStreams.ArtistID GROUP BY Artists.ArtistName;


Question: Update the labor cost of factories in Vietnam that use organic cotton to be $1.00 higher than the current value.

CREATE TABLE factory_vietnam (factory VARCHAR(255), country VARCHAR(255), material VARCHAR(255), labor_cost DECIMAL(5,2)); INSERT INTO factory_vietnam (factory, country, material, labor_cost) VALUES ('Factory1', 'Vietnam', 'organic cotton', 5.00), ('Factory2', 'Vietnam', 'conventional cotton', 4.75), ('Factory3', 'Vietnam', 'organic cotton', 5.25);

UPDATE factory_vietnam SET labor_cost = labor_cost + 1.00 WHERE country = 'Vietnam' AND material = 'organic cotton';


Question: Generate PostgreSQL SQL for: What was the final score of the game with 7523 in attendance?

CREATE TABLE table_25331766_3 (final_score VARCHAR, attendance VARCHAR)

SELECT final_score FROM table_25331766_3 WHERE attendance = 7523;


Question: List the countries in Europe with travel advisories and their respective regions, along with the total expenditure by international visitors for the last available year.

CREATE TABLE travel_advisories_europe (id INT, country VARCHAR(50), region VARCHAR(50), travel_warning BOOLEAN, advisory_text TEXT, year INT, continent VARCHAR(10)); INSERT INTO travel_advisories_europe (id, country, region, travel_warning, advisory_text, year, continent) VALUES (1, 'France', 'Europe', true, 'Avoid non-essential travel due to civil unrest.', 2022, 'Europe');

SELECT ta.country, ta.region, t.total_expenditure FROM travel_advisories_europe ta JOIN tourism_spending t ON ta.country = t.country AND t.year = (SELECT MAX(year) FROM tourism_spending WHERE country = ta.country AND continent = ta.continent) WHERE ta.travel_warning = true AND ta.continent = 'Europe';


Question: Find the number of research grants awarded to female faculty members in the Computer Science department

CREATE TABLE faculty(faculty_id INT, name VARCHAR(50), gender VARCHAR(10), department VARCHAR(20)); INSERT INTO faculty VALUES (1, 'Alice', 'Female', 'Computer Science'); INSERT INTO faculty VALUES (2, 'Bob', 'Male', 'Computer Science'); CREATE TABLE research_grants(grant_id INT, faculty_id INT, amount DECIMAL(10, 2)); INSERT INTO research_grants VALUES (1, 1, 50000); INSERT INTO research_grants VALUES (2, 2, 75000);

SELECT COUNT(*) FROM faculty f INNER JOIN research_grants g ON f.faculty_id = g.faculty_id WHERE f.gender = 'Female' AND f.department = 'Computer Science';


Question: Generate PostgreSQL SQL for: Which Record has Points larger than 0, and a Score of 7–3?

CREATE TABLE table_name_96 (record VARCHAR, points VARCHAR, score VARCHAR)

SELECT record FROM table_name_96 WHERE points > 0 AND score = '7–3';


Question: How many public consultations in the environment domain have taken place in the city of Toronto in the last year?

CREATE TABLE consultation (id INT, name VARCHAR(255), domain VARCHAR(255), city VARCHAR(255), start_date DATE); INSERT INTO consultation (id, name, domain, city, start_date) VALUES (1, 'Waste Management', 'Environment', 'Toronto', '2022-02-01'); INSERT INTO consultation (id, name, domain, city, start_date) VALUES (2, 'Park Clean-up', 'Environment', 'Toronto', '2021-12-15');

SELECT COUNT(*) FROM consultation WHERE domain = 'Environment' AND city = 'Toronto' AND start_date >= DATEADD(year, -1, GETDATE());


Question: Generate PostgreSQL SQL for: What music is in the film before 1963?

CREATE TABLE table_name_53 (music VARCHAR, year INTEGER)

SELECT music FROM table_name_53 WHERE year < 1963;


Question: What was the landfill capacity in cubic meters for each state in the USA in 2020?

CREATE TABLE landfill_capacity (state VARCHAR(255), year INT, capacity INT); INSERT INTO landfill_capacity (state, year, capacity) VALUES ('California', 2020, 1500000), ('Texas', 2020, 1600000), ('New York', 2020, 1200000), ('Florida', 2020, 1400000);

SELECT state, capacity FROM landfill_capacity WHERE year = 2020;


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

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

SELECT count(*) FROM (SELECT to_number('5 4 4 4 4 8 . 7 8', '9 9 9 9 9 9 . 9 9')) AS _sub;


Question: Delete all food justice projects in 'California' from the 'food_justice_projects' table.

CREATE TABLE food_justice_projects (id INT, name TEXT, location TEXT); INSERT INTO food_justice_projects (id, name, location) VALUES (1, 'Project A', 'California'), (2, 'Project B', 'New York'), (3, 'Project C', 'California');

DELETE FROM food_justice_projects WHERE location = 'California';


Question: Identify the policy trends in clean energy for countries in the European Union.

CREATE TABLE eu_clean_energy_policy (country VARCHAR(30), policy_date DATE, policy_description TEXT); INSERT INTO eu_clean_energy_policy (country, policy_date, policy_description) VALUES ('Germany', '2022-01-01', 'Implemented a new feed-in tariff for solar energy.'), ('France', '2021-06-15', 'Expanded offshore wind energy capacity.'), ('Spain', '2022-04-20', 'Increased funding for renewable energy research and development.'), ('Italy', '2021-12-10', 'Phased out coal-fired power plants.'), ('Poland', '2022-02-15', 'Introduced a carbon tax on heavy industry.');

SELECT country, policy_description FROM eu_clean_energy_policy WHERE country IN ('Germany', 'France', 'Spain', 'Italy', 'Poland') ORDER BY policy_date DESC;


Question: PostgreSQL regression test 'collate.utf8': Write the SELECT query (example 39).

SELECT 'Δ' ~* '[γ-λ]' COLLATE PG_UNICODE_FAST;

Explanation: Regression test for Collate.Utf8 in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT 'Δ' ~* '[γ-λ]' COLLATE PG_UNICODE_FAST) AS _sub;


Question: Insert new records for a game designer from Japan who has adopted virtual reality technology, and the games they have created with a rating of 9 or higher.

CREATE TABLE GameDesigners (DesignerID INT, Name VARCHAR(30), Country VARCHAR(20), VRAdoption BOOLEAN);CREATE TABLE Games (GameID INT, GameName VARCHAR(30), Rating INT, DesignerID INT);

INSERT INTO GameDesigners (DesignerID, Name, Country, VRAdoption) VALUES (1, 'Hiroshi Tanaka', 'Japan', TRUE);INSERT INTO Games (GameID, GameName, Rating, DesignerID) VALUES (1, 'Samurai Sword', 9, 1), (2, 'Ninja Scroll', 10, 1);


Question: Show the total revenue from football ticket sales in 2021

CREATE TABLE ticket_sales (ticket_id INT, sale_date DATE, event_type VARCHAR(10), revenue DECIMAL(10,2)); INSERT INTO ticket_sales (ticket_id, sale_date, event_type, revenue) VALUES (1, '2021-08-01', 'Football', 50.00), (2, '2022-04-10', 'Football', 75.00), (3, '2021-12-31', 'Football', 60.00);

SELECT SUM(revenue) as total_revenue FROM ticket_sales WHERE event_type = 'Football' AND YEAR(sale_date) = 2021;


Question: List all unique sectors and their corresponding minimum ESG ratings?

CREATE TABLE companies (id INT, sector VARCHAR(20), ESG_rating FLOAT); INSERT INTO companies (id, sector, ESG_rating) VALUES (1, 'technology', 7.5), (2, 'finance', 6.8), (3, 'technology', 8.2), (4, 'renewable_energy', 9.0);

SELECT sector, MIN(ESG_rating) FROM companies GROUP BY sector;


Question: What is the difference in budget between the 'research' and 'development' departments for the year 2019?

CREATE TABLE department_budgets (department TEXT, budget INT, year INT); INSERT INTO department_budgets (department, budget, year) VALUES ('research', 1000000, 2019), ('development', 1200000, 2019), ('research', 1100000, 2020), ('development', 1300000, 2020);

SELECT LAG(budget, 1, 0) OVER (ORDER BY year) as prev_budget, budget, budget - LAG(budget, 1, 0) OVER (ORDER BY year) as budget_diff FROM department_budgets WHERE department IN ('research', 'development') AND year = 2019 AND budget IS NOT NULL;


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

ALTER CONVERSION iso_8859_1_to_utf8 OWNER TO joe;

Explanation: PostgreSQL ALTER CONVERSION command.


Question: PL/pgSQL test: Plpgsql Call (example 18).

-- output arguments

CREATE PROCEDURE test_proc5(INOUT a text)
LANGUAGE plpgsql
AS $$
BEGIN
    a := a || '+' || a;
END;
$$;

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


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

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

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


Question: Calculate the total budget allocated to each department in the "Budget" table, where the department name contains 'Education'.

CREATE TABLE Budget (id INT, department VARCHAR(50), allocated_budget FLOAT); INSERT INTO Budget (id, department, allocated_budget) VALUES (1, 'Education - Primary', 1000000.0), (2, 'Education - Secondary', 1500000.0), (3, 'Healthcare', 2000000.0), (4, 'Transportation', 1200000.0), (5, 'Education - Higher', 2500000.0);

SELECT department, SUM(allocated_budget) as total_budget FROM Budget WHERE department LIKE '%Education%' GROUP BY department;


Question: Generate PostgreSQL SQL for: Where is the Eastern Nazarene College located?

CREATE TABLE table_1973729_1 (location VARCHAR, institution VARCHAR)

SELECT location FROM table_1973729_1 WHERE institution = 'Eastern Nazarene College';


Question: Generate PostgreSQL SQL for: Which Athlete has a Place of 1, and a Year smaller than 1988, and a Country of gre, and a Time of 21:57:00?

CREATE TABLE table_name_97 (athlete VARCHAR, time VARCHAR, country VARCHAR, place VARCHAR, year VARCHAR)

SELECT athlete FROM table_name_97 WHERE place = 1 AND year < 1988 AND country = 'gre' AND time = '21:57:00';


Question: Update the end date of the 'Habitat Restoration' effort in the 'conservation_efforts' table

CREATE TABLE conservation_efforts (id INT PRIMARY KEY, location VARCHAR(50), start_date DATE, end_date DATE, effort_description VARCHAR(255));

UPDATE conservation_efforts SET end_date = '2023-12-31' WHERE effort_description = 'Habitat Restoration';


Question: Generate PostgreSQL SQL for: What is the mascot with the colors green and navy?

CREATE TABLE table_15873547_1 (mascot VARCHAR, colors VARCHAR)

SELECT mascot FROM table_15873547_1 WHERE colors = 'Green and Navy';


Question: Generate PostgreSQL SQL for: How many losses does Abercarn RFC have?

CREATE TABLE table_name_90 (lost VARCHAR, club VARCHAR)

SELECT lost FROM table_name_90 WHERE club = 'abercarn rfc';


Question: Generate PostgreSQL SQL for: What season was Barcelona ranked higher than 12, had more than 96 goals and had more than 26 apps?

CREATE TABLE table_name_59 (season VARCHAR, rank VARCHAR, goals VARCHAR, apps VARCHAR, club VARCHAR)

SELECT season FROM table_name_59 WHERE apps > 26 AND club = 'barcelona' AND goals > 96 AND rank > 12;


Question: Generate PostgreSQL SQL for: Who had the highest assists on March 18?

CREATE TABLE table_17121262_9 (high_assists VARCHAR, date VARCHAR)

SELECT high_assists FROM table_17121262_9 WHERE date = 'March 18';


Question: Generate PostgreSQL SQL for: How man seasons have the air date of October 2, 2001?

CREATE TABLE table_2219961_2 (season__number VARCHAR, nbc_airdate VARCHAR)

SELECT COUNT(season__number) FROM table_2219961_2 WHERE nbc_airdate = 'October 2, 2001';


Question: Generate PostgreSQL SQL for: what's the party for the first elected in 1980

CREATE TABLE table_1341472_15 (party VARCHAR, first_elected VARCHAR)

SELECT party FROM table_1341472_15 WHERE first_elected = '1980';


Question: Where are the renewable energy projects located with a capacity greater than 700 MW?

CREATE TABLE renewable_energy_projects (id INT, project_name VARCHAR(50), location VARCHAR(50), capacity_mw INT); INSERT INTO renewable_energy_projects (id, project_name, location, capacity_mw) VALUES (1, 'Wind Farm XYZ', 'Texas', 500); INSERT INTO renewable_energy_projects (id, project_name, location, capacity_mw) VALUES (2, 'Solar Park ABC', 'California', 800); INSERT INTO renewable_energy_projects (id, project_name, location, capacity_mw) VALUES (4, 'Hydro Plant DEF', 'Norway', 900);

SELECT location FROM renewable_energy_projects WHERE capacity_mw > 700;


Question: Generate PostgreSQL SQL for: What is the maximum memory for the model discontinued in November 2001?

CREATE TABLE table_10528691_4 (maximum_memory VARCHAR, discontinued VARCHAR)

SELECT maximum_memory FROM table_10528691_4 WHERE discontinued = 'November 2001';


Question: Generate PostgreSQL SQL for: What is the source of the move from Port Vale?

CREATE TABLE table_name_97 (source VARCHAR, moving_from VARCHAR)

SELECT source FROM table_name_97 WHERE moving_from = 'port vale';


Question: What is the total oil production for each country in 2020?

CREATE TABLE production_figures (year INT, country VARCHAR(50), oil_production_mbbl INT);

SELECT country, SUM(oil_production_mbbl) FROM production_figures WHERE year = 2020 GROUP BY country;


Question: What is the average age of players?

SELECT AVG(Age) FROM Player_Demographics;


Question: Generate PostgreSQL SQL for: When the result was l 13-7 ot, who was the opponent?

CREATE TABLE table_name_27 (opponent VARCHAR, result VARCHAR)

SELECT opponent FROM table_name_27 WHERE result = 'l 13-7 ot';


Question: Count the number of publications by graduate students in the Mathematics department in the last 5 years.

CREATE TABLE students (id INT, name VARCHAR(50), department VARCHAR(50), start_year INT); INSERT INTO students (id, name, department, start_year) VALUES (1, 'Charlie', 'Mathematics', 2018); INSERT INTO students (id, name, department, start_year) VALUES (2, 'Dana', 'Computer Science', 2019); CREATE TABLE publications (id INT, student_id INT, year INT, title VARCHAR(100)); INSERT INTO publications (id, student_id, year, title) VALUES (1, 1, 2020, 'Theory of Algebra'); INSERT INTO publications (id, student_id, year, title) VALUES (2, 2, 2021, 'Machine Learning Algorithms');

SELECT COUNT(p.id) FROM publications p JOIN students s ON p.student_id = s.id WHERE s.department = 'Mathematics' AND p.year BETWEEN YEAR(CURRENT_DATE) - 5 AND YEAR(CURRENT_DATE);


Question: What was the minimum ticket price for an exhibition in London before 2020?

CREATE TABLE Exhibitions (id INT, city VARCHAR(50), year INT, ticket_price DECIMAL(5,2));INSERT INTO Exhibitions (id, city, year, ticket_price) VALUES (1, 'London', 2019, 15.00), (2, 'London', 2018, 10.00), (3, 'Paris', 2017, 20.00);

SELECT MIN(ticket_price) FROM Exhibitions WHERE city = 'London' AND year < 2020;


Question: Generate PostgreSQL SQL for: What is Season, when Prize is "$100,000"?

CREATE TABLE table_name_37 (season VARCHAR, prize VARCHAR)

SELECT season FROM table_name_37 WHERE prize = '$100,000';


Question: Generate PostgreSQL SQL for: Name the directed by season # 2

CREATE TABLE table_23286722_1 (directed_by VARCHAR, season__number VARCHAR)

SELECT directed_by FROM table_23286722_1 WHERE season__number = 2;


Question: What is the average disinformation score for content creators in the Middle East, grouped by gender?

CREATE TABLE content_creators (creator_id INT, gender VARCHAR(50), country VARCHAR(50), disinformation_score INT); INSERT INTO content_creators (creator_id, gender, country, disinformation_score) VALUES (1, 'Female', 'Saudi Arabia', 50), (2, 'Male', 'Iran', 45), (3, 'Female', 'Turkey', 55);

SELECT gender, AVG(disinformation_score) as avg_score FROM content_creators WHERE country IN ('Saudi Arabia', 'Iran', 'Turkey', 'United Arab Emirates', 'Israel') GROUP BY gender;


Question: Generate PostgreSQL SQL for: Which English winning song had the winner aris runtuwene?

CREATE TABLE table_name_7 (English VARCHAR, winner VARCHAR)

SELECT WINNING_SONG(English AS Title) FROM table_name_7 WHERE winner = 'aris runtuwene';


Question: Generate PostgreSQL SQL for: What country is player Raymond Floyd from?

CREATE TABLE table_name_35 (country VARCHAR, player VARCHAR)

SELECT country FROM table_name_35 WHERE player = 'raymond floyd';


Question: Generate PostgreSQL SQL for: What is the average day in December of the game with a 8-2-3 record?

CREATE TABLE table_name_25 (december INTEGER, record VARCHAR)

SELECT AVG(december) FROM table_name_25 WHERE record = '8-2-3';


Question: What is the maximum claim amount for policies sold in California?

CREATE TABLE Claims (PolicyID int, ClaimAmount int, SaleState varchar(20)); INSERT INTO Claims (PolicyID, ClaimAmount, SaleState) VALUES (1, 500, 'California'), (2, 2000, 'New York'), (3, 800, 'California');

SELECT MAX(ClaimAmount) OVER (PARTITION BY SaleState) as MaxClaimAmount FROM Claims WHERE SaleState = 'California';


Question: Generate PostgreSQL SQL for: What is the lowest grid for Roberto Rolfo with more than 26 laps?

CREATE TABLE table_name_87 (grid INTEGER, rider VARCHAR, laps VARCHAR)

SELECT MIN(grid) FROM table_name_87 WHERE rider = 'roberto rolfo' AND laps > 26;


Question: Which space agencies have launched missions to Mars?

CREATE TABLE space_mars_missions (agency VARCHAR(50), mission VARCHAR(50), year INTEGER); INSERT INTO space_mars_missions (agency, mission, year) VALUES ('NASA', 'Mars Pathfinder', 1997), ('NASA', 'Mars Global Surveyor', 1997), ('ISAS', 'Nozomi', 1998), ('NASA', 'Mars Climate Orbiter', 1999), ('NASA', 'Mars Polar Lander', 1999), ('NASA', 'Mars Odyssey', 2001), ('ESA', 'Mars Express', 2003), ('Beagle Consortium', 'Beagle 2', 2003), ('NASA', 'Mars Reconnaissance Orbiter', 2006), ('NASA', 'Phoenix', 2008), ('NASA', 'Mars Science Laboratory', 2012), ('NASA', 'Mars Atmosphere and Volatile Evolution', 2013), ('NASA', 'MAVEN', 2014), ('ESA', 'ExoMars Trace Gas Orbiter', 2016), ('NASA', 'InSight', 2018), ('UAE Space Agency', 'Hope Mars Mission', 2021), ('CNSA', 'Tianwen-1', 2021);

SELECT agency FROM space_mars_missions GROUP BY agency;


Question: PostgreSQL regression test 'with': Write the SELECT query (example 100).

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

SELECT count(*) FROM (select pg_get_viewdef('v_cycle1')) AS _sub;


Question: Generate PostgreSQL SQL for: What is the lowest First Title, when All-Time is greater than 1, when Country is "United States (USA)", and when Amateur Era is greater than 17?

CREATE TABLE table_name_13 (first_title INTEGER, amateur_era VARCHAR, all_time VARCHAR, country VARCHAR)

SELECT MIN(first_title) FROM table_name_13 WHERE all_time > 1 AND country = 'united states (usa)' AND amateur_era > 17;


Question: List all authors who have published articles in the 'business' section.

CREATE TABLE articles (id INT, author VARCHAR(255), title VARCHAR(255), section VARCHAR(255), date DATE);

SELECT DISTINCT author FROM articles WHERE section='business';


Question: What are the names of all vessels that are either cargo ships or tankers?

CREATE TABLE Vessels (ID INT, Name VARCHAR(50), Type VARCHAR(50)); INSERT INTO Vessels (ID, Name, Type) VALUES (1, 'MV Pacific', 'Cargo Ship'), (2, 'MV Persian Gulf', 'Tanker');

SELECT Name FROM Vessels WHERE Type IN ('Cargo Ship', 'Tanker');


Question: Generate PostgreSQL SQL for: What is the time for Brazil?

CREATE TABLE table_name_5 (time VARCHAR, country VARCHAR)

SELECT time FROM table_name_5 WHERE country = 'brazil';


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

CREATE FUNCTION test4() RETURNS trigger
LANGUAGE plpython3u
TRANSFORM FOR TYPE hstore
AS $$
assert(TD["new"] == {'a': 1, 'b': {'aa': 'bb', 'cc': None}})
if TD["new"]["a"] == 1:
    TD["new"]["b"] = {'a': 1, 'b': 'boo', 'c': None}

return "MODIFY"
$$;

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


Question: Generate PostgreSQL SQL for: When £337,000 is £ saved what is the percentage of electricity reduction?

CREATE TABLE table_29538735_1 (_percentage_electricity_reduction VARCHAR, £_saved VARCHAR)

SELECT _percentage_electricity_reduction FROM table_29538735_1 WHERE £_saved = '£337,000';


Question: Generate PostgreSQL SQL for: What are the titles of segment c for series episode is 21-08?

CREATE TABLE table_15187735_21 (segment_c VARCHAR, series_ep VARCHAR)

SELECT segment_c FROM table_15187735_21 WHERE series_ep = '21-08';


Question: Generate PostgreSQL SQL for: What is the round number for the date 19/06/2009?

CREATE TABLE table_21311525_1 (round VARCHAR, date VARCHAR)

SELECT round FROM table_21311525_1 WHERE date = '19/06/2009';


Question: Write the DDL statement from PostgreSQL regression test 'create_index' (example 549).

CREATE UNIQUE INDEX CONCURRENTLY concur_reindex_ind5 ON concur_reindex_tab4 (c1);

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


Question: How many fish are there in fish farms located in the Mediterranean Sea with a density greater than 300 fish/m3?

CREATE TABLE fish_farms (id INT, name TEXT, location TEXT, fish_density INT); INSERT INTO fish_farms (id, name, location, fish_density) VALUES (1, 'Farm A', 'Mediterranean Sea', 400), (2, 'Farm B', 'Atlantic Ocean', 200);

SELECT COUNT(*) FROM fish_farms WHERE location = 'Mediterranean Sea' AND fish_density > 300;


Question: Delete records with a CO2 emission value lower than 100 in the 'emissions' table for the year 2005.

CREATE TABLE emissions (country VARCHAR(255), year INT, co2_emission FLOAT); INSERT INTO emissions (country, year, co2_emission) VALUES ('Canada', 2005, 550.0), ('US', 2005, 520.0), ('Russia', 2005, 190.0), ('Finland', 2005, 60.0), ('Canada', 2005, 80.0);

DELETE FROM emissions WHERE year = 2005 AND co2_emission < 100;


Question: Generate PostgreSQL SQL for: When was the oakachoy covered bridge listed?

CREATE TABLE table_name_34 (listed VARCHAR, name VARCHAR)

SELECT listed FROM table_name_34 WHERE name = 'oakachoy covered bridge';


Question: Generate PostgreSQL SQL for: Who lost the game on May 28?

CREATE TABLE table_name_38 (loss VARCHAR, date VARCHAR)

SELECT loss FROM table_name_38 WHERE date = 'may 28';


Question: Generate PostgreSQL SQL for: Original title of возвращение / vozvrashcheniye had what English title?

CREATE TABLE table_name_79 (english_title VARCHAR, original_title VARCHAR)

SELECT english_title FROM table_name_79 WHERE original_title = 'возвращение / vozvrashcheniye';


Question: Generate PostgreSQL SQL for: Which nation ran a time of 9.69 seconds?

CREATE TABLE table_name_84 (nation VARCHAR, performance VARCHAR)

SELECT nation FROM table_name_84 WHERE performance = '9.69';


Question: What is the total number of salmon farms in Norway and Scotland?

CREATE TABLE salmon_farms (id INT, name TEXT, country TEXT); INSERT INTO salmon_farms (id, name, country) VALUES (1, 'Farm A', 'Norway'); INSERT INTO salmon_farms (id, name, country) VALUES (2, 'Farm B', 'Norway'); INSERT INTO salmon_farms (id, name, country) VALUES (3, 'Farm C', 'Scotland'); INSERT INTO salmon_farms (id, name, country) VALUES (4, 'Farm D', 'Scotland');

SELECT COUNT(*) FROM salmon_farms WHERE country IN ('Norway', 'Scotland');


Question: Generate PostgreSQL SQL for: Which driver for Greenfield Mowers Racing has fewer than 36 points?

CREATE TABLE table_name_82 (driver VARCHAR, points VARCHAR, team VARCHAR)

SELECT driver FROM table_name_82 WHERE points < 36 AND team = 'greenfield mowers racing';


Question: What is the total number of properties in urban areas with co-ownership agreements, and their average price?

CREATE TABLE property (id INT, price INT, area VARCHAR(255), co_ownership BOOLEAN); INSERT INTO property (id, price, area, co_ownership) VALUES (1, 200000, 'urban', true), (2, 300000, 'rural', false);

SELECT SUM(price), AVG(price) FROM property WHERE area = 'urban' AND co_ownership = true;


Question: Generate PostgreSQL SQL for: Tell me the Laps for time/retired of +1:08.491

CREATE TABLE table_name_39 (laps VARCHAR, time_retired VARCHAR)

SELECT laps FROM table_name_39 WHERE time_retired = '+1:08.491';


Question: PostgreSQL regression test 'tidrangescan': Write the SELECT query (example 25).

SELECT ctid FROM tidrangescan WHERE ctid > '(1,4)' AND '(1,7)' >= ctid;

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

SELECT count(*) FROM (SELECT ctid FROM tidrangescan WHERE ctid > '(1,4)' AND '(1,7)' >= ctid) AS _sub;


Question: Generate PostgreSQL SQL for: What are the producers of  磊磊牌嬰幼兒配方乳粉 ?

CREATE TABLE table_18943444_1 (producer VARCHAR, product VARCHAR)

SELECT producer FROM table_18943444_1 WHERE product = '磊磊牌嬰幼兒配方乳粉';


Question: pgTAP test for Resultset (assertion 144).

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

Explanation: SQL assertion from pgTAP test suite for Resultset.


Question: What is the total budget for all education programs in the 'Asia' region?

CREATE TABLE Budget (id INT, program_id INT, amount DECIMAL(10,2)); INSERT INTO Budget (id, program_id, amount) VALUES (1, 1, 10000.00), (2, 2, 20000.00), (3, 3, 30000.00);

SELECT SUM(b.amount) FROM Budget b INNER JOIN EducationPrograms e ON b.program_id = e.id INNER JOIN Coordinators c ON e.coordinator_id = c.id WHERE c.region = 'Asia';


Question: Write the DDL statement from PostgreSQL regression test 'join' (example 283).

Explanation: DDL from PostgreSQL core regression test for Join.


Question: What is the average rating of movies produced in Canada and the USA?

CREATE TABLE movie (id INT, title VARCHAR(255), rating DECIMAL(3,2), country VARCHAR(255)); INSERT INTO movie (id, title, rating, country) VALUES (1, 'Movie1', 7.5, 'Canada'), (2, 'Movie2', 8.2, 'USA'), (3, 'Movie3', 6.9, 'Mexico');

SELECT AVG(rating) FROM movie WHERE country IN ('Canada', 'USA');


Question: How many charging stations are there in South Korea?

CREATE TABLE Charging_Stations_South_Korea (Id INT, Type VARCHAR(50), Location VARCHAR(50)); INSERT INTO Charging_Stations_South_Korea (Id, Type, Location) VALUES (1, 'Public', 'South Korea'), (2, 'Private', 'South Korea'), (3, 'Public', 'Japan');

SELECT COUNT(*) FROM Charging_Stations_South_Korea WHERE Type = 'Public' OR Type = 'Private';


Question: List the names of states that have both healthcare facilities and mental health facilities.

CREATE TABLE healthcare_facilities (id INT, name VARCHAR(50), state VARCHAR(10)); INSERT INTO healthcare_facilities (id, name, state) VALUES (1, 'Facility A', 'State 1'), (2, 'Facility B', 'State 2'), (3, 'Facility C', 'State 3');

SELECT h.state FROM healthcare_facilities h INNER JOIN mental_health_facilities m ON h.state = m.state GROUP BY h.state;


Question: What is the minimum price of non-vegan menu items?

CREATE TABLE MenuItems (menu_item_id INT, name VARCHAR(255), price DECIMAL(5,2), is_vegan BOOLEAN); INSERT INTO MenuItems (menu_item_id, name, price, is_vegan) VALUES (1, 'Burger', 12.99, false), (2, 'Steak', 25.99, false), (3, 'Fries', 3.99, true);

SELECT MIN(price) FROM MenuItems WHERE is_vegan = false;


Question: What is the maximum emission quantity for each emission type in pollution sources that have not been inspected in the last 6 months?

CREATE TABLE PollutionSources (id INT, source_name VARCHAR(255), emission_type VARCHAR(255), emission_quantity INT, last_inspection DATE);

SELECT emission_type, MAX(emission_quantity) FROM PollutionSources WHERE last_inspection <= DATE_SUB(CURRENT_DATE, INTERVAL 6 MONTH) GROUP BY emission_type;


Question: Generate PostgreSQL SQL for: What is the grid average with a +1 lap time and more than 27 laps?

CREATE TABLE table_name_52 (grid INTEGER, time_retired VARCHAR, laps VARCHAR)

SELECT AVG(grid) FROM table_name_52 WHERE time_retired = '+1 lap' AND laps > 27;


Question: How many donations were made in the year 2020?

CREATE TABLE donations (id INT, donor_id INT, amount DECIMAL(10,2), donation_date DATE);

SELECT COUNT(*) FROM donations WHERE YEAR(donation_date) = 2020;


Question: Generate PostgreSQL SQL for: Name the candidates for result of lost renomination democratic loss

CREATE TABLE table_1342149_24 (candidates VARCHAR, result VARCHAR)

SELECT candidates FROM table_1342149_24 WHERE result = 'Lost renomination Democratic loss';


Question: Show the railway stations in Canada

CREATE TABLE Infrastructure (id INT, name VARCHAR(100), type VARCHAR(50), country VARCHAR(50)); INSERT INTO Infrastructure (id, name, type, country) VALUES (9, 'Toronto Union Station', 'Railway Station', 'Canada'), (10, 'Vancouver Pacific Central Station', 'Railway Station', 'Canada');

SELECT name FROM Infrastructure WHERE type = 'Railway Station' AND country = 'Canada';


Question: What is the average assets value for clients in the 'South' region?

CREATE TABLE clients (id INT, name TEXT, region TEXT, assets FLOAT); INSERT INTO clients (id, name, region, assets) VALUES (1, 'María Rodríguez', 'South', 60000.00), (2, 'David Kim', 'North', 90000.00), (3, 'Sophia Chen', 'East', 110000.00), (4, 'Taro Yamada', 'West', 130000.00);

SELECT AVG(assets) FROM clients WHERE region = 'South';


Question: Find the total number of repeat attendees for workshops and lectures, and the number of unique attendees.

CREATE TABLE attendees (id INT, event_id INT, repeat INT); INSERT INTO attendees (id, event_id, repeat) VALUES (1, 1, 0); INSERT INTO attendees (id, event_id, repeat) VALUES (2, 1, 1); INSERT INTO attendees (id, event_id, repeat) VALUES (3, 2, 0); INSERT INTO attendees (id, event_id, repeat) VALUES (4, 3, 0); INSERT INTO attendees (id, event_id, repeat) VALUES (5, 3, 1); INSERT INTO attendees (id, event_id, repeat) VALUES (6, 4, 0); INSERT INTO attendees (id, event_id, repeat) VALUES (7, 5, 1); INSERT INTO attendees (id, event_id, repeat) VALUES (8, 5, 1);

SELECT SUM(repeat), COUNT(DISTINCT id) FROM attendees WHERE event_id IN (SELECT event_id FROM events WHERE type IN ('Workshop', 'Lecture'));


Question: Generate PostgreSQL SQL for: What is the smallest height (ft) of a building in Frankfurt with a height (m) of 257 and less than 55 floors?

CREATE TABLE table_name_24 (height__ft_ INTEGER, floors VARCHAR, city VARCHAR, height__m_ VARCHAR)

SELECT MIN(height__ft_) FROM table_name_24 WHERE city = 'frankfurt' AND height__m_ = 257 AND floors < 55;


Question: What is the count of building permits issued per month in Colorado in 2020?

CREATE TABLE building_permits (id INT, permit_number VARCHAR(20), issue_date DATE, state VARCHAR(10)); INSERT INTO building_permits (id, permit_number, issue_date, state) VALUES (1, '12345', '2020-01-01', 'Colorado'); INSERT INTO building_permits (id, permit_number, issue_date, state) VALUES (2, '67890', '2020-02-15', 'Colorado');

SELECT MONTH(issue_date), COUNT(*) FROM building_permits WHERE state = 'Colorado' AND YEAR(issue_date) = 2020 GROUP BY MONTH(issue_date);


Question: What is the average delivery time for packages shipped via air from each warehouse in Q3 2021?

CREATE TABLE deliveries (id INT, delivery_time FLOAT, warehouse VARCHAR(20), quarter INT, shipment_type VARCHAR(20)); INSERT INTO deliveries (id, delivery_time, warehouse, quarter, shipment_type) VALUES (1, 1.5, 'New York', 3, 'Air'), (2, 5.0, 'Seattle', 1, 'Ground'), (3, 1.2, 'New York', 3, 'Air'); CREATE TABLE warehouses (id INT, name VARCHAR(20)); INSERT INTO warehouses (id, name) VALUES (1, 'New York'), (2, 'Seattle'); CREATE TABLE shipment_types (id INT, type VARCHAR(20)); INSERT INTO shipment_types (id, type) VALUES (1, 'Air'), (2, 'Ground');

SELECT p.warehouse, AVG(d.delivery_time) FROM deliveries d JOIN warehouses w ON d.warehouse = w.name JOIN shipment_types st ON d.shipment_type = st.type WHERE st.type = 'Air' AND d.quarter = 3 GROUP BY p.warehouse;


Question: Generate PostgreSQL SQL for: How many first downs did the bills have when their opponent had 6

CREATE TABLE table_16028459_2 (bills_first_downs INTEGER, opponents VARCHAR)

SELECT MIN(bills_first_downs) FROM table_16028459_2 WHERE opponents = 6;


Question: How many posts were made by each influencer in the last month?

CREATE TABLE influencers (influencer_id INT, influencer_name TEXT);CREATE TABLE posts (post_id INT, post_text TEXT, influencer_id INT, post_date DATE);

SELECT i.influencer_id, i.influencer_name, COUNT(p.post_id) as posts_last_month FROM influencers i JOIN posts p ON i.influencer_id = p.influencer_id WHERE p.post_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH) GROUP BY i.influencer_id;


Question: What is the average engagement time for virtual tours in Mexico and Brazil?

CREATE TABLE virtual_tours_mx_br (id INT, country VARCHAR(50), engagement_time INT); INSERT INTO virtual_tours_mx_br (id, country, engagement_time) VALUES (1, 'Mexico', 400), (2, 'Mexico', 500), (3, 'Brazil', 600), (4, 'Brazil', 700);

SELECT country, AVG(engagement_time) FROM virtual_tours_mx_br WHERE country IN ('Mexico', 'Brazil') GROUP BY country;


Question: Generate PostgreSQL SQL for: Name the game for june 7

CREATE TABLE table_18894744_5 (game VARCHAR, date VARCHAR)

SELECT game FROM table_18894744_5 WHERE date = 'June 7';


Question: Which mobile subscribers have not updated their billing address in the last 6 months?

CREATE TABLE mobile_subscribers (subscriber_id INT, first_name VARCHAR(50), last_name VARCHAR(50), billing_address VARCHAR(100), last_updated_date DATE);

SELECT subscriber_id, first_name, last_name, billing_address FROM mobile_subscribers WHERE last_updated_date < DATE_SUB(CURRENT_DATE, INTERVAL 6 MONTH);


Question: pgTAP test for Resultset (assertion 348).

SELECT * FROM check_test(
    set_hasnt( 'anames', 'others' ),
    true,
    'set_hasnt( prepared, prepared, description )',
    '',
    ''
);


Question: Generate PostgreSQL SQL for: What grid did the team racing professionals race on?

CREATE TABLE table_name_84 (grid VARCHAR, team VARCHAR)

SELECT grid FROM table_name_84 WHERE team = 'racing professionals';


Question: Generate PostgreSQL SQL for: What was the result of the game on august 30, 1968?

CREATE TABLE table_name_69 (result VARCHAR, date VARCHAR)

SELECT result FROM table_name_69 WHERE date = 'august 30, 1968';


Question: Which ethical manufacturing certifications have been awarded to factories in the Asia-Pacific region?

CREATE TABLE factories (factory_id INT, name TEXT, location TEXT); CREATE TABLE certifications (certification_id INT, name TEXT, factory_id INT, region TEXT); INSERT INTO factories (factory_id, name, location) VALUES (1, 'Flex Factory', 'Japan'), (2, 'GreenTech Plant', 'Germany'), (3, 'Smart Manufacturing Co.', 'China'); INSERT INTO certifications (certification_id, name, factory_id, region) VALUES (1, 'Fair Trade', 1, 'Asia-Pacific'), (2, 'SA8000', 3, 'Asia-Pacific'), (3, 'BSCI', 2, 'Europe');

SELECT factories.name, certifications.name FROM factories INNER JOIN certifications ON factories.factory_id = certifications.factory_id WHERE certifications.region = 'Asia-Pacific' AND certifications.name IN ('Fair Trade', 'SA8000', 'BSCI');


Question: PostgreSQL regression test 'tsrf': Write the SELECT query (example 40).

SELECT dataa, datab b, generate_series(1,2) g, count(*) FROM few GROUP BY CUBE(dataa, datab, g);

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

SELECT count(*) FROM (SELECT dataa, datab b, generate_series(1,2) g, count(*) FROM few GROUP BY CUBE(dataa, datab, g)) AS _sub;


Question: Which mobile subscribers have not updated their billing information in the last 6 months?

CREATE TABLE mobile_subscribers (subscriber_id INT, name VARCHAR(50), billing_updated_date DATE); INSERT INTO mobile_subscribers (subscriber_id, name, billing_updated_date) VALUES (1, 'John Doe', '2021-01-15'); INSERT INTO mobile_subscribers (subscriber_id, name, billing_updated_date) VALUES (2, 'Jane Smith', '2021-07-22');

SELECT * FROM mobile_subscribers WHERE billing_updated_date <= DATE_SUB(CURRENT_DATE, INTERVAL 6 MONTH);


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

ALTER EXTENSION pgtap ADD VIEW pg_all_foreign_keys;


Question: What is the total value of assets under management for each risk level as of the last day of the previous quarter?

CREATE TABLE portfolios (portfolio_id INT, customer_id INT, risk_level VARCHAR(10), assets_value DECIMAL(10, 2), portfolio_date DATE); INSERT INTO portfolios (portfolio_id, customer_id, risk_level, assets_value, portfolio_date) VALUES (1, 1, 'low', 10000, '2021-01-01'), (2, 2, 'high', 50000, '2021-02-01'), (3, 3, 'medium', 25000, '2021-03-01'), (4, 4, 'low', 15000, '2021-04-01');

SELECT risk_level, SUM(assets_value) FROM portfolios WHERE portfolio_date = LAST_DAY(DATE_SUB(CURDATE(), INTERVAL 3 MONTH)) GROUP BY risk_level;


Question: Generate PostgreSQL SQL for: what is the nation when the world rank is 6 and the birth date is 1971-07-31?

CREATE TABLE table_name_88 (nation VARCHAR, world_rank VARCHAR, birth_date VARCHAR)

SELECT nation FROM table_name_88 WHERE world_rank = '6' AND birth_date = '1971-07-31';


Question: Generate PostgreSQL SQL for: Which text has a date of c. 1180?

CREATE TABLE table_name_13 (text VARCHAR, date__ce_ VARCHAR)

SELECT text FROM table_name_13 WHERE date__ce_ = 'c. 1180';


Question: Generate PostgreSQL SQL for: Name the competition for australia 13, new zealand 40, drawn 3

CREATE TABLE table_20251343_4 (competition VARCHAR, head_to_head VARCHAR)

SELECT competition FROM table_20251343_4 WHERE head_to_head = 'Australia 13, New Zealand 40, Drawn 3';


Question: Write the DDL statement from PostgreSQL regression test 'brin_bloom' (example 6).

CREATE INDEX brinidx_bloom ON brintest_bloom USING brin (
	byteacol bytea_bloom_ops(false_positive_rate = 0.26)
);

Explanation: DDL from PostgreSQL core regression test for Brin Bloom.


Question: Display data from 'top_sustainable_suppliers' view

CREATE TABLE suppliers( supplier_id INT PRIMARY KEY, name VARCHAR(255), location VARCHAR(255), sustainability_score INT); INSERT INTO suppliers (supplier_id, name, location, sustainability_score) VALUES (1, 'Supplier A', 'City A', 80), (2, 'Supplier B', 'City B', 85), (3, 'Supplier C', 'City C', 90), (4, 'Supplier D', 'City D', 95), (5, 'Supplier E', 'City E', 100); CREATE VIEW top_sustainable_suppliers AS SELECT * FROM suppliers WHERE sustainability_score >= 90; SELECT * FROM top_sustainable_suppliers;


Question: Generate PostgreSQL SQL for: What was the sum of league goals where the toal was 8 and league cup goals were larger than 0?

CREATE TABLE table_name_80 (league_goals INTEGER, total_goals VARCHAR, league_cup_goals VARCHAR)

SELECT SUM(league_goals) FROM table_name_80 WHERE total_goals = 8 AND league_cup_goals > 0;


Question: Find the total sales of cruelty-free cosmetics in the first half of 2021, grouped by region.

CREATE TABLE products (product_id INT, product_name VARCHAR(100), is_cruelty_free BOOLEAN, region VARCHAR(50), sales INT, launch_year INT, launch_quarter INT); INSERT INTO products (product_id, product_name, is_cruelty_free, region, sales, launch_year, launch_quarter) VALUES (1, 'Lipstick', true, 'USA', 500, 2021, 1), (2, 'Mascara', false, 'Canada', 700, 2020, 4), (3, 'Foundation', true, 'USA', 800, 2021, 2), (4, 'Eyeshadow', true, 'USA', 600, 2020, 3), (5, 'Blush', false, 'Canada', 400, 2021, 1);

SELECT region, SUM(sales) FROM products WHERE is_cruelty_free = true AND launch_year = 2021 AND launch_quarter BETWEEN 1 AND 2 GROUP BY region;


Question: Generate PostgreSQL SQL for: What is the score for Jock Hutchison?

CREATE TABLE table_name_89 (score VARCHAR, player VARCHAR)

SELECT score FROM table_name_89 WHERE player = 'jock hutchison';


Question: Insert new contract records for contracts awarded in Q4 2021

CREATE TABLE Contracts (ID INT, Vendor TEXT, Amount DECIMAL(10,2), Quarter INT); INSERT INTO Contracts (ID, Vendor, Amount, Quarter) VALUES (1, 'Vendor A', 150000.00, 4), (2, 'Vendor B', 250000.00, 4);

INSERT INTO Contracts (ID, Vendor, Amount, Quarter) VALUES (3, 'Vendor C', 300000.00, 4), (4, 'Vendor D', 100000.00, 4);


Question: Generate PostgreSQL SQL for: Which Network has 16.0 million Viewers?

CREATE TABLE table_name_67 (network VARCHAR, viewers VARCHAR)

SELECT network FROM table_name_67 WHERE viewers = '16.0 million';


Question: Generate PostgreSQL SQL for: Which release had 6 DVDs?

CREATE TABLE table_25721_4 (release VARCHAR, _number_of_discs VARCHAR)

SELECT release FROM table_25721_4 WHERE _number_of_discs = 6;


Question: Generate PostgreSQL SQL for: Which mm × mm has an in × in of 11 × 17?

CREATE TABLE table_name_7 (mm_×_mm VARCHAR, in_×_in VARCHAR)

SELECT mm_×_mm FROM table_name_7 WHERE in_×_in = '11 × 17';


Question: Generate PostgreSQL SQL for: Which Long has redshirt for its Avg/G?

CREATE TABLE table_name_97 (long VARCHAR, avg_g VARCHAR)

SELECT long FROM table_name_97 WHERE avg_g = 'redshirt';


Question: Delete all sales records with a quantity of 200 from the 'sales_data' table.

CREATE TABLE sales_data (sales_id INT, drug_name VARCHAR(255), quantity_sold INT, sales_date DATE, region VARCHAR(255));

DELETE FROM sales_data WHERE quantity_sold = 200;


Question: What is the average water usage per person in the Northeast region, grouped by state?

CREATE TABLE northeast_water_usage(state VARCHAR(20), usage NUMERIC(10,2), population NUMERIC(10,2)); INSERT INTO northeast_water_usage VALUES ('Maine', 50.67, 1345678), ('New Hampshire', 60.78, 1456789), ('Vermont', 70.89, 1567890), ('Massachusetts', 80.90, 1678901), ('Rhode Island', 90.10, 1789012), ('Connecticut', 100.20, 1890123);

SELECT state, AVG(usage) FROM northeast_water_usage GROUP BY state;


Question: Get creative AI applications using the 'Deep Learning' technology

CREATE TABLE creative_apps_2 (id INT, name VARCHAR(255), type VARCHAR(255), technology VARCHAR(255)); INSERT INTO creative_apps_2 (id, name, type, technology) VALUES (1, 'DeepArt', 'Art Generation', 'Deep Learning'), (2, 'DeepSpeech', 'Speech Recognition', 'Deep Learning');

SELECT * FROM creative_apps_2 WHERE technology = 'Deep Learning';


Question: Generate PostgreSQL SQL for: how many new managers replaced  manager(s) who resigned?

CREATE TABLE table_28164986_4 (incoming_manager VARCHAR, manner_of_departure VARCHAR)

SELECT COUNT(incoming_manager) FROM table_28164986_4 WHERE manner_of_departure = 'Resigned';


Question: How many unique strains are available in TX dispensaries with organic in their name?

CREATE TABLE strains (id INT, name TEXT, dispensary_id INT); INSERT INTO strains (id, name, dispensary_id) VALUES (1, 'Strain A', 1), (2, 'Strain B', 2), (3, 'Strain C', 3); CREATE TABLE dispensaries (id INT, name TEXT, state TEXT); INSERT INTO dispensaries (id, name, state) VALUES (1, 'Organic Dispensary', 'Texas'), (2, 'Dispensary X', 'Texas'), (3, 'Dispensary Y', 'Texas');

SELECT COUNT(DISTINCT s.name)  FROM strains s  JOIN dispensaries d ON s.dispensary_id = d.id  WHERE d.state = 'Texas' AND d.name LIKE '%organic%';


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

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


Question: What is the total number of water wells dug in "Latin America" since 2018?

CREATE TABLE water_wells (id INT, project_id INT, location VARCHAR(255), construction_date DATE); INSERT INTO water_wells (id, project_id, location, construction_date) VALUES (1, 4001, 'Colombia', '2019-05-01'); INSERT INTO water_wells (id, project_id, location, construction_date) VALUES (2, 4002, 'Peru', '2018-02-01');

SELECT COUNT(*) FROM water_wells WHERE location = 'Latin America' AND YEAR(construction_date) >= 2018;


Question: How many players registered in 2022 play multiplayer online battle arena (MOBA) games on PC?

CREATE TABLE players (player_id INT, name VARCHAR(30), age INT, gender VARCHAR(10), country VARCHAR(30), registration_date DATE, platform VARCHAR(20));

SELECT COUNT(*) FROM players WHERE YEAR(registration_date) = 2022 AND genre = 'MOBA' AND platform = 'PC';


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

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


Question: What is the total number of exhibitions in each city?

CREATE TABLE Exhibitions (id INT, city VARCHAR(20), visitors INT); INSERT INTO Exhibitions (id, city, visitors) VALUES (1, 'Paris', 3000), (2, 'London', 4000), (3, 'New York', 5000), (4, 'Paris', 2000), (5, 'London', 1000), (6, 'New York', 3000), (7, 'Tokyo', 4000), (8, 'Berlin', 5000), (9, 'Rome', 2000), (10, 'Tokyo', 3000);

SELECT city, COUNT(id) FROM Exhibitions GROUP BY city;


Question: Generate PostgreSQL SQL for: Which Office has a Party of dem, and a First Elected of 1991†?

CREATE TABLE table_name_2 (office VARCHAR, party VARCHAR, first_elected VARCHAR)

SELECT office FROM table_name_2 WHERE party = 'dem' AND first_elected = '1991†';


Question: Which region has the highest number of donors?

CREATE TABLE donors (donor_id INT, donor_name VARCHAR(255), region VARCHAR(255)); INSERT INTO donors (donor_id, donor_name, region) VALUES (1001, 'John Smith', 'North America'), (1002, 'Marie Johnson', 'Europe'), (1003, 'Mario Rodriguez', 'South America'), (1004, 'Nguyen Tran', 'Asia');

SELECT region, COUNT(*) as num_donors FROM donors GROUP BY region ORDER BY num_donors DESC LIMIT 1;


Question: Generate PostgreSQL SQL for: What is the highest league goals that have barry endean as the name, wirh FA cup apps greater than 0?

CREATE TABLE table_name_46 (league_goals INTEGER, name VARCHAR, fa_cup_apps VARCHAR)

SELECT MAX(league_goals) FROM table_name_46 WHERE name = 'barry endean' AND fa_cup_apps > 0;


Question: Generate PostgreSQL SQL for: What is Incumbent, when District is "Louisiana 4"?

CREATE TABLE table_name_7 (incumbent VARCHAR, district VARCHAR)

SELECT incumbent FROM table_name_7 WHERE district = 'louisiana 4';


Question: List all unique attorney last names who have billed for cases in the 'Immigration' case type, in descending order based on the number of cases they handled.

CREATE TABLE ImmigrationCases (CaseID INT, CaseType VARCHAR(20), AttorneyLastName VARCHAR(20), BillingAmount DECIMAL(10,2)); INSERT INTO ImmigrationCases (CaseID, CaseType, AttorneyLastName, BillingAmount) VALUES (1, 'Immigration', 'Garcia', 5000.00), (2, 'Immigration', 'Rodriguez', 3000.00), (3, 'Immigration', 'Garcia', 2000.00);

SELECT DISTINCT AttorneyLastName, COUNT(*) AS CaseCount FROM ImmigrationCases WHERE CaseType = 'Immigration' GROUP BY AttorneyLastName ORDER BY CaseCount DESC;


Question: Generate PostgreSQL SQL for: What is the score for set 2 when the time is 18:00 and the score of set 1 is 18–25?

CREATE TABLE table_name_48 (set_2 VARCHAR, time VARCHAR, set_1 VARCHAR)

SELECT set_2 FROM table_name_48 WHERE time = '18:00' AND set_1 = '18–25';


Question: Generate PostgreSQL SQL for: What season was played at Safeco Field, against the Boston Red Sox, with a decision of L?

CREATE TABLE table_name_60 (season VARCHAR, opponent VARCHAR, location VARCHAR, decision VARCHAR)

SELECT season FROM table_name_60 WHERE location = 'safeco field' AND decision = 'l' AND opponent = 'boston red sox';


Question: What is the average water temperature in fish farms located in the Mediterranean and Aegean seas?

CREATE TABLE Farm(id INT, location VARCHAR(50), temperature FLOAT); INSERT INTO Farm(id, location, temperature) VALUES (1, 'Mediterranean Sea', 22.5), (2, 'Aegean Sea', 21.3);

SELECT AVG(temperature) FROM Farm WHERE location LIKE '%Mediterranean Sea%' OR location LIKE '%Aegean Sea%';


Question: Generate PostgreSQL SQL for: How many dominant religions were in the settlement that had a population of 17105?

CREATE TABLE table_2562572_53 (dominant_religion__2002_ VARCHAR, population__2011_ VARCHAR)

SELECT COUNT(dominant_religion__2002_) FROM table_2562572_53 WHERE population__2011_ = 17105;


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

SELECT count(*) FROM inettmp WHERE a >  '89.225.196.191'::inet;

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


Question: Generate PostgreSQL SQL for: Who was the manufacturer for Matt Kenseth on March 7?

CREATE TABLE table_2196127_1 (manufacturer VARCHAR, driver VARCHAR, date VARCHAR)

SELECT manufacturer FROM table_2196127_1 WHERE driver = 'Matt Kenseth' AND date = 'March 7';


Question: PostgreSQL regression test 'aggregates': Write the SELECT query (example 80).

SELECT covar_pop(b, a), covar_samp(b, a) FROM aggtest;

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

SELECT count(*) FROM (SELECT covar_pop(b, a), covar_samp(b, a) FROM aggtest) AS _sub;


Question: What is the maximum number of infectious disease cases reported in a month in rural areas?

CREATE TABLE infectious_disease_tracking (id INT, location TEXT, cases_per_month INT, month TEXT); INSERT INTO infectious_disease_tracking (id, location, cases_per_month, month) VALUES (1, 'Rural A', 10, 'January'), (2, 'Rural B', 15, 'February'), (3, 'Rural A', 20, 'March');

SELECT MAX(cases_per_month) FROM infectious_disease_tracking WHERE location = 'rural';


Question: Generate PostgreSQL SQL for: How often does a train leave sealdah?

CREATE TABLE table_12095519_1 (frequency VARCHAR, origin VARCHAR)

SELECT frequency FROM table_12095519_1 WHERE origin = 'Sealdah';


Question: Generate PostgreSQL SQL for: What was the mintage when the theme was Santa Claus?

CREATE TABLE table_name_15 (mintage VARCHAR, theme VARCHAR)

SELECT mintage FROM table_name_15 WHERE theme = 'santa claus';


Question: PostgreSQL regression test 'matview': Write the SELECT query (example 108).

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

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


Question: List all peacekeeping operations in Africa with more than 5,000 personnel.

CREATE TABLE peacekeeping_operations (operation_id INT, name TEXT, location TEXT, personnel INT); INSERT INTO peacekeeping_operations (operation_id, name, location, personnel) VALUES (1, 'MINUSCA', 'Central African Republic', 12000), (2, 'MONUSCO', 'Democratic Republic of the Congo', 16000);

SELECT name FROM peacekeeping_operations WHERE location LIKE 'Africa%' AND personnel > 5000;


Question: Generate PostgreSQL SQL for: What was the venue where Chuck Klein played?

CREATE TABLE table_name_85 (venue VARCHAR, player VARCHAR)

SELECT venue FROM table_name_85 WHERE player = 'chuck klein';


Question: List diversity metrics for companies with a patent count greater than 2.

CREATE TABLE company_demographics (company_id INT, patent_count INT, female_percent FLOAT, minority_percent FLOAT); INSERT INTO company_demographics (company_id, patent_count, female_percent, minority_percent) VALUES (1, 3, 0.4, 0.3), (2, 1, 0.5, 0.2), (3, 2, 0.35, 0.45), (4, 4, 0.6, 0.1), (5, 0, 0.7, 0.2);

SELECT patent_count, female_percent, minority_percent FROM company_demographics WHERE patent_count > 2;


Question: Generate PostgreSQL SQL for: Which College/junior/club team has a Pick # of 1?

CREATE TABLE table_name_27 (college_junior_club_team VARCHAR, pick__number VARCHAR)

SELECT college_junior_club_team FROM table_name_27 WHERE pick__number = '1';


Question: What is the average income in the city of 'San Francisco'?

CREATE TABLE city (name VARCHAR(255), income FLOAT); INSERT INTO city (name, income) VALUES ('San Francisco', 96000), ('Oakland', 72000);

SELECT AVG(income) FROM city WHERE name = 'San Francisco';


Question: Update the type of disaster for disaster with ID 1 to 'Super Typhoon'

CREATE TABLE disasters (id INT PRIMARY KEY, name VARCHAR(50), location VARCHAR(50), type VARCHAR(50), start_date DATE, end_date DATE);

UPDATE disasters SET type = 'Super Typhoon' WHERE id = 1;


Question: Minimum risk rating of investments in LATAM for a given fund?

CREATE TABLE fund_investment_risks(fund_id INT, investment_id INT, risk_rating INT, region VARCHAR(10));

SELECT MIN(risk_rating) FROM fund_investment_risks WHERE fund_id = 1 AND region = 'LATAM';


Question: What is the maximum amount of shelter support provided to a single household in Iraq?

CREATE TABLE shelter_support (id INT, country VARCHAR(255), household_id INT, amount FLOAT); INSERT INTO shelter_support (id, country, household_id, amount) VALUES (1, 'Iraq', 1001, 500), (2, 'Iraq', 1002, 800), (3, 'Syria', 1003, 900);

SELECT MAX(amount) FROM shelter_support WHERE country = 'Iraq';


Question: Show all tables related to algorithmic fairness.

CREATE TABLE algorithmic_fairness (table_name VARCHAR(255)); INSERT INTO algorithmic_fairness (table_name) VALUES ('disparate_impact'), ('equal_opportunity'), ('demographic_parity');

SELECT table_name FROM algorithmic_fairness;


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

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

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


Question: Generate PostgreSQL SQL for: Which Loses has Points smaller than 6?

CREATE TABLE table_name_38 (loses INTEGER, points INTEGER)

SELECT AVG(loses) FROM table_name_38 WHERE points < 6;


Question: Generate PostgreSQL SQL for: What the number of matches when the BBI is 3/27?

CREATE TABLE table_28846752_9 (matches INTEGER, bbi VARCHAR)

SELECT MIN(matches) FROM table_28846752_9 WHERE bbi = '3/27';


Question: What is the total sales revenue for each pharmaceutical company in Brazil for the year 2019?

CREATE TABLE SalesRevenue (Company VARCHAR(50), Country VARCHAR(50), Revenue INT, Year INT); INSERT INTO SalesRevenue (Company, Country, Revenue, Year) VALUES ('Eurofarma', 'Brazil', 1000000, 2019), ('Aché', 'Brazil', 1200000, 2019), ('Hypera', 'Brazil', 1500000, 2019), ('Grupo Sanofi', 'Brazil', 1800000, 2019);

SELECT Company, SUM(Revenue) FROM SalesRevenue WHERE Country = 'Brazil' AND Year = 2019 GROUP BY Company;


Question: How many users from each country are there in the users table?

CREATE TABLE users (id INT, name VARCHAR(20), country VARCHAR(20), last_login TIMESTAMP); INSERT INTO users (id, name, country, last_login) VALUES (3, 'Bob', 'UK', '2021-01-04 10:00:00');

SELECT country, COUNT(*) as users FROM users GROUP BY country;


Question: Generate PostgreSQL SQL for: How many points did Corbari Italia earn in 1985?

CREATE TABLE table_name_90 (points VARCHAR, entrant VARCHAR, year VARCHAR)

SELECT points FROM table_name_90 WHERE entrant = 'corbari italia' AND year = 1985;


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

CREATE ROLE regress_encrypted_password ENCRYPTED PASSWORD 'foo';

Explanation: DDL from PostgreSQL core regression test for Create Role.


Question: What is the number of open pedagogy projects completed by students in each department in the last 6 months?

CREATE TABLE op_projects (project_id INT, department_id INT, completed BOOLEAN, completion_date DATE); INSERT INTO op_projects (project_id, department_id, completed, completion_date) VALUES (1, 501, true, '2022-01-01'), (2, 501, false, '2021-01-01'), (3, 502, true, '2022-03-01'), (4, 502, false, '2021-04-01');

SELECT department_id, COUNT(project_id) as num_projects_completed FROM op_projects WHERE completion_date >= DATEADD(month, -6, CURRENT_TIMESTAMP) AND completed = true GROUP BY department_id;


Question: What is the total number of artworks in the 'Artworks' table for each year?

CREATE TABLE Artworks (id INT, art_category VARCHAR(255), artist_name VARCHAR(255), year INT, art_medium VARCHAR(255), price DECIMAL(10,2));

SELECT year, COUNT(*) as total FROM Artworks GROUP BY year;


Question: Show countries involved in more than 5 military technologies

CREATE TABLE CountryMilitary (Country VARCHAR(50) PRIMARY KEY, Technology VARCHAR(50));

SELECT Country FROM CountryMilitary GROUP BY Country HAVING COUNT(*) > 5;


Question: Generate PostgreSQL SQL for: What is the average Silver with a Total that is smaller than 1?

CREATE TABLE table_name_97 (silver INTEGER, total INTEGER)

SELECT AVG(silver) FROM table_name_97 WHERE total < 1;


Question: Show all reservoirs with capacity > 1000

CREATE TABLE oil_reservoirs (reservoir_id INT, reservoir_name VARCHAR(100), location VARCHAR(100), oil_capacity FLOAT); INSERT INTO oil_reservoirs (reservoir_id, reservoir_name, location, oil_capacity) VALUES (1, 'Girassol', 'Angola', 800), (2, 'Jazireh-e-Jafar', 'Iran', 1500), (3, 'Thunder Horse', 'Gulf of Mexico', 1200), (4, 'Kashagan', 'Caspian Sea', 1100);

SELECT * FROM oil_reservoirs WHERE oil_capacity > 1000;


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

Explanation: DML from PostgreSQL core regression test for Rules.


Question: Delete all TV shows with a runtime less than 30 minutes.

CREATE TABLE shows (id INT, title TEXT, runtime INT); INSERT INTO shows (id, title, runtime) VALUES (1, 'Show 1', 60); CREATE TABLE tv_shows (id INT, show_id INT, episodes INT); INSERT INTO tv_shows (id, show_id, episodes) VALUES (1, 1, 10);

DELETE FROM shows WHERE id IN (SELECT s.id FROM shows s INNER JOIN tv_shows t ON s.id = t.show_id WHERE s.runtime < 30);


Question: What is the total number of orders shipped to the United States that contain eco-friendly materials?

CREATE TABLE orders (id INT, order_value DECIMAL(10,2), eco_friendly BOOLEAN, country VARCHAR(50)); INSERT INTO orders (id, order_value, eco_friendly, country) VALUES (1, 150.50, TRUE, 'USA'), (2, 75.20, FALSE, 'Canada'), (3, 225.00, TRUE, 'USA');

SELECT COUNT(*) FROM orders WHERE eco_friendly = TRUE AND country = 'USA';


Question: Generate PostgreSQL SQL for: Which team was the away team when home team was essendon?

CREATE TABLE table_29090919_1 (away_team VARCHAR, home_team VARCHAR)

SELECT away_team FROM table_29090919_1 WHERE home_team = 'Essendon';


Question: Find the average funding amount for startups founded by individuals from underrepresented countries

CREATE TABLE underrepresented_countries (company_name VARCHAR(100), founder_country VARCHAR(50), founding_year INT, funding_amount INT);

SELECT AVG(funding_amount) FROM underrepresented_countries;


Question: List the names of games that are not played by any player and their respective game IDs.

SELECT GameTitle, GameID FROM GameDesign WHERE GameID NOT IN (SELECT GameID FROM GameLibrary);


Question: Generate PostgreSQL SQL for: what is the to par for retief goosen?

CREATE TABLE table_name_93 (to_par VARCHAR, player VARCHAR)

SELECT to_par FROM table_name_93 WHERE player = 'retief goosen';


Question: Generate PostgreSQL SQL for: What is the Traditional Chinese of 国殇 which is over 9?

CREATE TABLE table_name_14 (traditional_chinese VARCHAR, standard_order VARCHAR, simplified_chinese VARCHAR)

SELECT traditional_chinese FROM table_name_14 WHERE standard_order > 9 AND simplified_chinese = '国殇';


Question: Delete all records of expeditions that reached a depth greater than 6000 meters?

CREATE TABLE Expeditions(ExpeditionID INT, LeaderName VARCHAR(20), MaxDepth INT); INSERT INTO Expeditions(ExpeditionID, LeaderName, MaxDepth) VALUES (1, 'Alice', 6500), (2, 'Bob', 4200), (3, 'Charlie', 2100), (4, 'Dana', 5100), (5, 'Eve', 7000);

DELETE FROM Expeditions WHERE MaxDepth > 6000;


Question: PostgreSQL regression test 'money': Write the SELECT query (example 108).

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

SELECT count(*) FROM (SELECT '42'::money * '-inf'::float8) AS _sub;


Question: What is the average weight of chemicals produced in the Asia Pacific region, grouped by chemical category?

CREATE TABLE chemicals (id INT, name VARCHAR(255), weight FLOAT, region VARCHAR(255));

SELECT category, AVG(weight) as avg_weight FROM (SELECT chemicals.name as category, AVG(weight) as weight FROM chemicals WHERE region = 'Asia Pacific' GROUP BY chemicals.name) as subquery GROUP BY category;


Question: Show an example of PostgreSQL RELEASE SAVEPOINT (example 1).

BEGIN; INSERT INTO table1 VALUES (3); SAVEPOINT my_savepoint; INSERT INTO table1 VALUES (4); RELEASE SAVEPOINT my_savepoint; COMMIT;

Explanation: PostgreSQL RELEASE SAVEPOINT command.


Question: Generate PostgreSQL SQL for: What is the car # of the Chevrolet that complete 363 laps?

CREATE TABLE table_name_68 (car__number VARCHAR, make VARCHAR, laps VARCHAR)

SELECT COUNT(car__number) FROM table_name_68 WHERE make = 'chevrolet' AND laps = 363;


Question: Generate PostgreSQL SQL for: what is the Frequency that has a fairview City of license

CREATE TABLE table_name_32 (frequency VARCHAR, city_of_license VARCHAR)

SELECT frequency FROM table_name_32 WHERE city_of_license = 'fairview';


Question: Generate PostgreSQL SQL for: What episode number in the series was directed by John Behring?

CREATE TABLE table_21164557_1 (no_in_series INTEGER, directed_by VARCHAR)

SELECT MAX(no_in_series) FROM table_21164557_1 WHERE directed_by = 'John Behring';


Question: PostgreSQL regression test 'stats_rewrite': Write the SELECT query (example 88).

SELECT last_analyze AS last_vacuum_analyze
  FROM pg_stat_all_tables WHERE relname = 'test_timestamp' \gset
ALTER TABLE test_timestamp ALTER COLUMN a TYPE bigint;

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

SELECT count(*) FROM (SELECT last_analyze AS last_vacuum_analyze
  FROM pg_stat_all_tables WHERE relname = 'test_timestamp' \gset
ALTER TABLE test_timestamp ALTER COLUMN a TYPE bigint) AS _sub;


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

SELECT name FROM srt WHERE name !~ 'A$' ORDER BY name;

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


Question: Update the name of the founder of the company with id 3 to 'Alex'

CREATE TABLE founder (id INT, name TEXT);

UPDATE company SET founder_gender = 'Other' WHERE id = 3; UPDATE founder SET name = 'Alex' WHERE id = 3;


Question: Find the total number of games played in NHL where the home team won, for the 2021-2022 season.

CREATE TABLE NHL_Matches (Season VARCHAR(50), HomeTeam VARCHAR(50), AwayTeam VARCHAR(50), HomeTeamScore INT, AwayTeamScore INT); INSERT INTO NHL_Matches (Season, HomeTeam, AwayTeam, HomeTeamScore, AwayTeamScore) VALUES ('2021-2022', 'Toronto Maple Leafs', 'Montreal Canadiens', 4, 2);

SELECT SUM(HomeTeamScore > AwayTeamScore) FROM NHL_Matches WHERE Season = '2021-2022';


Question: What is the second-deepest marine trench?

CREATE TABLE marine_trenches (name TEXT, depth FLOAT); INSERT INTO marine_trenches (name, depth) VALUES ('Mariana Trench', 36000); INSERT INTO marine_trenches (name, depth) VALUES ('Tonga Trench', 35000); INSERT INTO marine_trenches (name, depth) VALUES ('Kermadec Trench', 32000); INSERT INTO marine_trenches (name, depth) VALUES ('Sunda Trench', 31000);

SELECT name, depth FROM (SELECT name, depth, ROW_NUMBER() OVER (ORDER BY depth DESC) AS rn FROM marine_trenches) AS sub WHERE rn = 2;


Question: What is the total number of songs produced by artists from the United States?

CREATE TABLE artists (id INT, name TEXT, country TEXT); INSERT INTO artists (id, name, country) VALUES (1, 'Taylor Swift', 'United States'), (2, 'Eminem', 'United States'); CREATE TABLE songs (id INT, title TEXT, artist_id INT); INSERT INTO songs (id, title, artist_id) VALUES (1, 'Shake it Off', 1), (2, 'Lose Yourself', 2);

SELECT COUNT(*) FROM songs JOIN artists ON songs.artist_id = artists.id WHERE artists.country = 'United States';


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

CREATE FUNCTION latitude(earth)
RETURNS float8
LANGUAGE SQL
IMMUTABLE STRICT
PARALLEL SAFE
AS 'SELECT CASE WHEN cube_ll_coord($1, 3)/earth() < -1 THEN -90::float8 WHEN cube_ll_coord($1, 3)/earth() > 1 THEN 90::float8 ELSE degrees(asin(cube_ll_coord($1, 3)/earth())) END';

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


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

CREATE FUNCTION inline_eq(foodomain, foodomain) returns boolean as
  'SELECT CASE $2::text WHEN $1::text THEN true ELSE false END' language sql;

Explanation: DDL from PostgreSQL core regression test for Case.


Question: Display the number of underwater volcanoes in the Atlantic Ocean.

CREATE TABLE underwater_volcanoes (name TEXT, location TEXT, depth INT); INSERT INTO underwater_volcanoes (name, location, depth) VALUES ('Volcano 1', 'Atlantic Ocean', '3000'), ('Volcano 2', 'Pacific Ocean', '4000');

SELECT COUNT(*) FROM underwater_volcanoes WHERE location = 'Atlantic Ocean';


Question: Generate PostgreSQL SQL for: What is the to par for the score 72-69-68=209?

CREATE TABLE table_name_11 (to_par VARCHAR, score VARCHAR)

SELECT to_par FROM table_name_11 WHERE score = 72 - 69 - 68 = 209;


Question: Generate PostgreSQL SQL for: What was the original air date of the episode directed by frederick e. o. toye?

CREATE TABLE table_25923164_1 (original_air_date VARCHAR, directed_by VARCHAR)

SELECT original_air_date FROM table_25923164_1 WHERE directed_by = 'Frederick E. O. Toye';


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

Explanation: DDL from PostgreSQL core regression test for Publication.


Question: What are the total sales for vintage garments at each retail store?

CREATE TABLE sales_vintage (id INT, garment VARCHAR(255), retail_store VARCHAR(255), sale_date DATE, quantity INT, sales_price DECIMAL(5,2)); INSERT INTO sales_vintage (id, garment, retail_store, sale_date, quantity, sales_price) VALUES (1, 'vintage_t-shirt', 'London Fashion', '2021-03-01', 20, 25.99); INSERT INTO sales_vintage (id, garment, retail_store, sale_date, quantity, sales_price) VALUES (2, 'vintage_jeans', 'Los Angeles Boutique', '2021-04-01', 12, 49.99);

SELECT retail_store, SUM(quantity * sales_price) as total_sales FROM sales_vintage WHERE garment LIKE '%vintage%' GROUP BY retail_store;


Question: What is the total number of electric vehicle charging stations by country and state?

CREATE TABLE ElectricVehicleChargingStationsByRegion(Country VARCHAR(50), State VARCHAR(50), Stations INT);

SELECT Country, State, SUM(Stations) FROM ElectricVehicleChargingStationsByRegion GROUP BY Country, State;


Question: Get the names of publishers who have never published an article on 'Sunday'.

CREATE TABLE articles (id INT, title TEXT, publication_day TEXT, publisher TEXT);

SELECT DISTINCT publisher FROM articles WHERE publication_day != 'Sunday';


Question: What is the average water usage per capita in drought-impacted areas since 2015?

CREATE TABLE drought_impact (id INT, area VARCHAR(50), year INT, PRIMARY KEY(id, year)); INSERT INTO drought_impact (id, area, year) VALUES (1, 'California', 2015), (1, 'California', 2016), (1, 'California', 2017), (2, 'Texas', 2015), (2, 'Texas', 2016), (2, 'Texas', 2017), (3, 'Australia', 2015), (3, 'Australia', 2016), (3, 'Australia', 2017); CREATE TABLE water_usage (id INT, area VARCHAR(50), year INT, usage FLOAT, PRIMARY KEY(id, year), FOREIGN KEY (id) REFERENCES drought_impact(id)); INSERT INTO water_usage (id, area, year, usage) VALUES (1, 'California', 2015, 150), (1, 'California', 2016, 140), (1, 'California', 2017, 130), (2, 'Texas', 2015, 200), (2, 'Texas', 2016, 210), (2, 'Texas', 2017, 220), (3, 'Australia', 2015, 300), (3, 'Australia', 2016, 310), (3, 'Australia', 2017, 320);

SELECT AVG(wu.usage) as avg_usage FROM drought_impact di JOIN water_usage wu ON di.id = wu.id WHERE di.year >= 2015;


Question: Calculate the average fare for each public transportation mode

CREATE TABLE fare (fare_id INT, mode VARCHAR(10), fare DECIMAL(10, 2));

SELECT mode, AVG(fare) AS avg_fare FROM fare GROUP BY mode;


Question: Generate PostgreSQL SQL for: What is the lowest year for stage 12, category 1?

CREATE TABLE table_name_33 (year INTEGER, category VARCHAR, stage VARCHAR)

SELECT MIN(year) FROM table_name_33 WHERE category = '1' AND stage = 12;


Question: Find the average depth of all marine life research sites

CREATE TABLE marine_sites (site_id INT, site_name VARCHAR(255), longitude DECIMAL(9,6), latitude DECIMAL(9,6), depth DECIMAL(5,2));


Question: Generate PostgreSQL SQL for: What is the lowest against when the draws are more than 0 and the losses are less than 3?

CREATE TABLE table_name_74 (against INTEGER, losses VARCHAR, draws VARCHAR)

SELECT MIN(against) FROM table_name_74 WHERE losses < 3 AND draws > 0;


Question: Which animal has the lowest population?

CREATE TABLE animal_population (id INT, animal_name VARCHAR(50), population INT); INSERT INTO animal_population (id, animal_name, population) VALUES (1, 'Tiger', 2500), (2, 'Elephant', 5000), (3, 'Lion', 3000);

SELECT animal_name, MIN(population) FROM animal_population;


Question: Generate PostgreSQL SQL for: Loss of postponed (rain) rescheduled for may 10 had what record?

CREATE TABLE table_name_60 (record VARCHAR, loss VARCHAR)

SELECT record FROM table_name_60 WHERE loss = 'postponed (rain) rescheduled for may 10';


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

select pgp_sym_decrypt(
	pgp_sym_encrypt('Secret.', 'key', 'sess-key=1, cipher-algo=aes192'),
	'key', 'expect-sess-key=1, expect-cipher-algo=aes192');

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


Question: Generate PostgreSQL SQL for: What is the name of the soccer stadium in NL providence?

CREATE TABLE table_27369069_1 (soccer_stadium VARCHAR, province VARCHAR)

SELECT soccer_stadium FROM table_27369069_1 WHERE province = 'NL';


Question: What is the average emergency response time in Houston?

CREATE TABLE houston_emergency_responses (id INT, response_time INT, location VARCHAR(20)); INSERT INTO houston_emergency_responses (id, response_time, location) VALUES (1, 120, 'Houston'), (2, 90, 'Houston');

SELECT AVG(response_time) FROM houston_emergency_responses WHERE location = 'Houston';


Question: Calculate the median age of members who have participated in yoga workouts.

CREATE TABLE MemberWorkout (member_id INT, workout_id INT); INSERT INTO MemberWorkout (member_id, workout_id) VALUES (1001, 3001);

SELECT AVG(DATEDIFF('day', dob, CURDATE()))/365 as median_age FROM Member m JOIN MemberWorkout mw ON m.id = mw.member_id JOIN WorkoutType wt ON mw.workout_id = wt.id WHERE wt.workout_name = 'Yoga' GROUP BY m.id ORDER BY median_age;


Question: What was the total budget allocated for each department in 2021?

CREATE TABLE Budget (id INT, department VARCHAR(50), budget_amount DECIMAL(10,2), allocation_date DATE); INSERT INTO Budget (id, department, budget_amount, allocation_date) VALUES (1, 'Education', 50000, '2021-01-01'), (2, 'Health', 75000, '2021-04-15'), (3, 'Education', 60000, '2021-07-03'), (4, 'Health', 80000, '2021-10-17');

SELECT department, SUM(budget_amount) as total_budget FROM Budget WHERE YEAR(allocation_date) = 2021 GROUP BY department;


Question: Generate PostgreSQL SQL for: What is the greatest draw that has 4th for place?

CREATE TABLE table_name_62 (draw INTEGER, place VARCHAR)

SELECT MAX(draw) FROM table_name_62 WHERE place = '4th';


Question: What is the average budget for renewable energy projects in each country, excluding projects with a budget greater than 8000000?

CREATE TABLE Renewable_Energy_Projects (id INT, project_name VARCHAR(50), budget FLOAT, country VARCHAR(50)); INSERT INTO Renewable_Energy_Projects (id, project_name, budget, country) VALUES (1, 'Solar Farm', 5000000, 'USA'), (2, 'Wind Farm', 7000000, 'Canada'), (3, 'Hydroelectric Plant', 6000000, 'Mexico'), (4, 'Geothermal Plant', 4000000, 'USA'), (5, 'Tidal Energy', 3000000, 'Canada');

SELECT country, AVG(budget) FROM Renewable_Energy_Projects WHERE budget <= 8000000 GROUP BY country;


Question: PL/pgSQL test: Plperl (example 116).

CREATE OR REPLACE FUNCTION perl_spi_prepared_row(footype) RETURNS footype AS $$
   my $footype = shift;
   my $x = spi_prepare('select $1 AS a', 'footype');
   my $q = spi_exec_prepared( $x, {}, $footype );
   spi_freeplan($x);
return $q->{rows}->[0]->{a};
$$ LANGUAGE plperl;

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


Question: Which vendors have a recycling program in place and are reducing waste?

CREATE TABLE sustainability (id INT, vendor VARCHAR(50), recycling_program BOOLEAN, waste_reduction BOOLEAN); INSERT INTO sustainability (id, vendor, recycling_program, waste_reduction) VALUES (4, 'Local Produce', true, true), (5, 'Farm Fresh', false, true), (6, 'Organic Harvest', true, false);

SELECT vendor, CASE WHEN recycling_program THEN 'Yes' ELSE 'No' END as recycling_program, CASE WHEN waste_reduction THEN 'Yes' ELSE 'No' END as waste_reduction FROM sustainability WHERE recycling_program = 'True' AND waste_reduction = 'True';


Question: Generate PostgreSQL SQL for: Find the name of customer who has the lowest credit score.

CREATE TABLE customer (cust_name VARCHAR, credit_score VARCHAR)

SELECT cust_name FROM customer ORDER BY credit_score LIMIT 1;


Question: What is the total budget for successful community development initiatives in the 'community_development' table?

CREATE TABLE community_development (id INT, initiative VARCHAR(50), budget FLOAT, status VARCHAR(20));

SELECT SUM(budget) FROM community_development WHERE status = 'successful';


Question: Generate PostgreSQL SQL for: What horse has a 65.863 result?

CREATE TABLE table_name_18 (horse VARCHAR, result VARCHAR)

SELECT horse FROM table_name_18 WHERE result = '65.863';


Question: Identify the top two community health workers with the most unique patients served who identify as Hispanic or Latino, along with the number of patients they have served.

CREATE TABLE CommunityHealthWorker (ID INT, Name TEXT); INSERT INTO CommunityHealthWorker (ID, Name) VALUES (1, 'Maria Rodriguez'); INSERT INTO CommunityHealthWorker (ID, Name) VALUES (2, 'Jose Hernandez'); INSERT INTO CommunityHealthWorker (ID, Name) VALUES (3, 'Fatima Khan'); CREATE TABLE PatientCommunityHealthWorker (PatientID INT, CommunityHealthWorkerID INT, Ethnicity TEXT);

SELECT CommunityHealthWorkerID, COUNT(DISTINCT PatientID) as PatientsServed FROM PatientCommunityHealthWorker WHERE Ethnicity = 'Hispanic or Latino' GROUP BY CommunityHealthWorkerID ORDER BY PatientsServed DESC LIMIT 2;


Question: How many broadband subscribers does the company have in 'Suburban' areas?

CREATE TABLE subscribers (id INT, subscriber_type VARCHAR(20), location VARCHAR(20)); INSERT INTO subscribers (id, subscriber_type, location) VALUES (1, 'Broadband', 'Suburban');

SELECT COUNT(*) FROM subscribers WHERE subscriber_type = 'Broadband' AND location = 'Suburban';


Question: Generate PostgreSQL SQL for: Which Transfer window has a Name of tofas?

CREATE TABLE table_name_27 (transfer_window VARCHAR, name VARCHAR)

SELECT transfer_window FROM table_name_27 WHERE name = 'tofas';


Question: What is the minimum revenue generated by a restaurant in the "asian" cuisine type?

CREATE TABLE restaurants (id INT, name TEXT, cuisine TEXT, revenue FLOAT); INSERT INTO restaurants (id, name, cuisine, revenue) VALUES (1, 'Restaurant A', 'asian', 40000.00), (2, 'Restaurant B', 'italian', 50000.00), (3, 'Restaurant C', 'asian', 35000.00);

SELECT MIN(revenue) FROM restaurants WHERE cuisine = 'asian';


Question: Generate PostgreSQL SQL for: Which ZX Spectrum has a Year larger than 1984, and a Genre of arcade/strategy?

CREATE TABLE table_name_92 (zx_spectrum VARCHAR, year VARCHAR, genre VARCHAR)

SELECT zx_spectrum FROM table_name_92 WHERE year > 1984 AND genre = 'arcade/strategy';


Question: Generate PostgreSQL SQL for: What was the score and game outcome when High Points was andre miller (17)?

CREATE TABLE table_17323042_11 (score VARCHAR, high_points VARCHAR)

SELECT score FROM table_17323042_11 WHERE high_points = 'Andre Miller (17)';


Question: List defense projects with their start dates and contractors from the 'projects' and 'contractors' tables

CREATE TABLE projects (id INT, project_name VARCHAR(255), start_date DATE, end_date DATE); CREATE TABLE contractors (id INT, contractor VARCHAR(255)); INSERT INTO projects (id, project_name, start_date, end_date) VALUES (1, 'Stealth Fighter Development', '2017-04-01', '2022-12-31'); INSERT INTO projects (id, project_name, start_date, end_date) VALUES (2, 'Missile Shield Upgrade', '2018-09-15', '2023-06-30'); INSERT INTO contractors (id, contractor) VALUES (1, 'Lockheed Martin'); INSERT INTO contractors (id, contractor) VALUES (2, 'Raytheon');

SELECT projects.project_name, projects.start_date, contractors.contractor FROM projects INNER JOIN contractors ON projects.id = contractors.id;


Question: How many troops were deployed in peacekeeping missions in the first half of the years 2018 to 2020?

CREATE TABLE peacekeeping_missions (id INT, year INT, quarter INT, troops INT); INSERT INTO peacekeeping_missions (id, year, quarter, troops) VALUES (1, 2018, 1, 4000), (2, 2018, 2, 5000), (3, 2019, 1, 5500), (4, 2019, 2, 6000), (5, 2020, 1, 6500), (6, 2020, 2, 7000);

SELECT SUM(troops) FROM peacekeeping_missions WHERE quarter <= 2 AND year BETWEEN 2018 AND 2020;


Question: Select the names and games of players who have a score higher than the average score in game A, and update their score to be 100 points higher.

CREATE TABLE Players (PlayerID INT, Name VARCHAR(50), Game VARCHAR(50), Score INT); INSERT INTO Players (PlayerID, Name, Game, Score) VALUES (1, 'John Doe', 'GameA', 1000); INSERT INTO Players (PlayerID, Name, Game, Score) VALUES (2, 'Jane Doe', 'GameB', 2000); INSERT INTO Players (PlayerID, Name, Game, Score) VALUES (3, 'Alice', 'GameA', 1500); INSERT INTO Players (PlayerID, Name, Game, Score) VALUES (4, 'Bob', 'GameA', 1200);

UPDATE Players SET Score = Score + 100 WHERE Game = 'GameA' AND Score > (SELECT AVG(Score) FROM Players WHERE Game = 'GameA'); SELECT Name, Game, Score FROM Players WHERE Game = 'GameA' AND Score > (SELECT AVG(Score) FROM Players WHERE Game = 'GameA');


Question: Generate PostgreSQL SQL for: What's the lowest bits precision when the total bits are less than 16?

CREATE TABLE table_name_32 (bits_precision INTEGER, total_bits INTEGER)

SELECT MIN(bits_precision) FROM table_name_32 WHERE total_bits < 16;


Question: Generate PostgreSQL SQL for: Who does pregame analysts for TSN2 network when Taylor Twellman is the color commentator?

CREATE TABLE table_name_74 (pregame_analysts VARCHAR, color_commentator VARCHAR, network VARCHAR)

SELECT pregame_analysts FROM table_name_74 WHERE color_commentator = 'taylor twellman' AND network = 'tsn2';


Question: How many ships were inspected in the 'Mediterranean' sea in the year 2019, and what was the total tonnage of those ships?

CREATE TABLE ship_inspections (id INT, inspection_date DATE, region TEXT, tonnage INT); INSERT INTO ship_inspections (id, inspection_date, region, tonnage) VALUES (1, '2019-01-01', 'Mediterranean', 10000), (2, '2019-02-01', 'Mediterranean', 15000), (3, '2018-01-01', 'Mediterranean', 12000);

SELECT COUNT(*), SUM(tonnage) FROM ship_inspections WHERE region = 'Mediterranean' AND inspection_date BETWEEN '2019-01-01' AND '2019-12-31';


Question: What is the minimum cost of electrical substation projects in the Europe region?

CREATE TABLE InfrastructureProjects (id INT, name VARCHAR(100), region VARCHAR(50), project_type VARCHAR(50), cost FLOAT); INSERT INTO InfrastructureProjects (id, name, region, project_type, cost) VALUES (1, 'Paris Electrical Substation', 'Europe', 'electrical substation', 15000000);

SELECT MIN(cost) FROM InfrastructureProjects WHERE region = 'Europe' AND project_type = 'electrical substation';


Question: Display the total number of marine species in the Pacific Ocean.

CREATE TABLE marine_species_2 (name TEXT, location TEXT, num_individuals INT); INSERT INTO marine_species_2 (name, location, num_individuals) VALUES ('Clownfish', 'Indian Ocean', '10000'), ('Dolphin', 'Pacific Ocean', '20000');

SELECT SUM(num_individuals) FROM marine_species_2 WHERE location = 'Pacific Ocean';


Question: What is the minimum maintenance cost for military equipment of type XYZ?

CREATE TABLE military_equipment_cost (id INT, equipment_type VARCHAR(50), maintenance_cost FLOAT); INSERT INTO military_equipment_cost (id, equipment_type, maintenance_cost) VALUES (1, 'XYZ', 100000); INSERT INTO military_equipment_cost (id, equipment_type, maintenance_cost) VALUES (2, 'ABC', 200000);

SELECT MIN(maintenance_cost) FROM military_equipment_cost WHERE equipment_type = 'XYZ';


Question: Generate PostgreSQL SQL for: What team belongs to Delmar?

CREATE TABLE table_name_36 (team VARCHAR, school VARCHAR)

SELECT team FROM table_name_36 WHERE school = 'delmar';


Question: Generate PostgreSQL SQL for: Name the total number of goals which have played more than 44

CREATE TABLE table_name_13 (goals_for VARCHAR, played INTEGER)

SELECT COUNT(goals_for) FROM table_name_13 WHERE played > 44;


Question: What is the total number of assistive technology items provided to students with hearing impairments?

CREATE TABLE Assistive_Technology (Student_ID INT, Student_Name TEXT, Disability_Type TEXT, Assistive_Tech_Item TEXT); INSERT INTO Assistive_Technology (Student_ID, Student_Name, Disability_Type, Assistive_Tech_Item) VALUES (1, 'John Doe', 'Visual Impairment', 'Screen Reader'), (2, 'Jane Smith', 'Hearing Impairment', 'Hearing Aid'), (3, 'Michael Brown', 'ADHD', 'None');

SELECT SUM(CASE WHEN Disability_Type = 'Hearing Impairment' THEN 1 ELSE 0 END) FROM Assistive_Technology WHERE Assistive_Tech_Item IS NOT NULL;


Question: Generate PostgreSQL SQL for: How many times did the team lose who had a goal difference of +2, 52 goals for, and less than 9 draws?

CREATE TABLE table_name_97 (lost INTEGER, drawn VARCHAR, goal_difference VARCHAR, goals_for VARCHAR)

SELECT MIN(lost) FROM table_name_97 WHERE goal_difference = '+2' AND goals_for = 52 AND drawn < 9;


Question: List all records from the 'PlayerData' table where 'Age' is greater than 25

CREATE TABLE PlayerData (PlayerID INT, Name VARCHAR(50), Age INT, Country VARCHAR(50)); INSERT INTO PlayerData (PlayerID, Name, Age, Country) VALUES ('1', 'John Doe', '25', 'USA'), ('2', 'Jane Smith', '30', 'Canada'), ('3', 'Mike Johnson', '22', 'USA'), ('4', 'Sarah Lee', '28', 'Canada'), ('5', 'Lucas Martinez', '35', 'Mexico');

SELECT * FROM PlayerData WHERE Age > 25;


Question: Generate PostgreSQL SQL for: What yacht did Andrew Saies sail on?

CREATE TABLE table_25561560_3 (yacht VARCHAR, skipper VARCHAR)

SELECT yacht FROM table_25561560_3 WHERE skipper = 'Andrew Saies';


Question: What is the total number of cases in the 'restorative_justice' table?

CREATE TABLE restorative_justice (id INT, case_id INT, case_type VARCHAR(50), participant_count INT); INSERT INTO restorative_justice (id, case_id, case_type, participant_count) VALUES (1, 1001, 'Mediation', 3), (2, 1002, 'Restorative Circle', 5), (3, 1003, 'Victim Offender Conference', 4);

SELECT COUNT(*) FROM restorative_justice;