Question: What is the total weight of cannabis flowers produced by each cultivation site in Colorado in the last 6 months?

CREATE TABLE cultivation_sites (id INT, state TEXT, site_name TEXT);CREATE TABLE cultivation (id INT, site_id INT, plant_weight DECIMAL, plant_type TEXT, cultivation_date DATE);

SELECT cs.site_name, SUM(c.plant_weight) as total_weight FROM cultivation_sites cs INNER JOIN cultivation c ON cs.id = c.site_id WHERE cs.state = 'Colorado' AND c.plant_type = 'flowers' AND c.cultivation_date >= DATE_SUB(CURRENT_DATE, INTERVAL 6 MONTH) GROUP BY cs.site_name;


Question: What is the total quantity of cargo handled by ports in each region, excluding the African region?

CREATE TABLE ports_cargo_region (port_id INT, port_name TEXT, region TEXT, cargo_quantity INT); INSERT INTO ports_cargo_region VALUES (1, 'Port I', 'Africa', 2000), (2, 'Port J', 'Europe', 1800), (3, 'Port K', 'Asia Pacific', 2200);

SELECT ports_cargo_region.region, SUM(ports_cargo_region.cargo_quantity) FROM ports_cargo_region WHERE ports_cargo_region.region != 'Africa' GROUP BY ports_cargo_region.region;


Question: Delete records with humidity levels below 40 for the 'USA' in the month of January from the humidity table.

DELETE FROM humidity WHERE sensor_id IN (SELECT sensor_id FROM humidity WHERE country = 'USA' AND EXTRACT(MONTH FROM timestamp) = 1 AND humidity < 40) AND EXTRACT(MONTH FROM timestamp) = 1;


Question: What is the average credit score for clients who have a Shariah-compliant personal loan?

CREATE TABLE shariah_compliant_personal_loans (client_id INT, credit_score INT); INSERT INTO shariah_compliant_personal_loans (client_id, credit_score) VALUES (1, 700), (2, 750), (3, 650); CREATE TABLE shariah_compliant_loans (loan_id INT, client_id INT); INSERT INTO shariah_compliant_loans (loan_id, client_id) VALUES (101, 1), (102, 2), (103, 3);

SELECT AVG(scpl.credit_score) FROM shariah_compliant_personal_loans scpl JOIN shariah_compliant_loans scl ON scpl.client_id = scl.client_id;


Question: Show the total number of affordable housing units in Oakland and Boston.

CREATE TABLE oakland_housing(id INT, type VARCHAR(20), price INT); INSERT INTO oakland_housing VALUES (1, 'affordable', 300000); CREATE TABLE boston_housing(id INT, type VARCHAR(20), price INT); INSERT INTO boston_housing VALUES (1, 'affordable', 400000);

SELECT COUNT(*) FROM oakland_housing WHERE type = 'affordable' UNION ALL SELECT COUNT(*) FROM boston_housing WHERE type = 'affordable';


Question: Generate PostgreSQL SQL for: What is the African Spoonbill when the Ostrich is Brown-hooded Kingfisher?

CREATE TABLE table_20042805_2 (african_spoonbill VARCHAR, ostrich VARCHAR)

SELECT african_spoonbill FROM table_20042805_2 WHERE ostrich = 'Brown-hooded Kingfisher';


Question: What is the average wellbeing score for athletes on the Golden State Warriors?

CREATE TABLE athletes (athlete_id INT, wellbeing_score INT, team_id INT); CREATE TABLE teams (team_id INT, team_name VARCHAR(20)); INSERT INTO teams (team_id, team_name) VALUES (4, 'Golden State Warriors'); INSERT INTO athletes (athlete_id, wellbeing_score, team_id) VALUES (4, 80, 4);

SELECT AVG(athletes.wellbeing_score) FROM athletes INNER JOIN teams ON athletes.team_id = teams.team_id WHERE teams.team_name = 'Golden State Warriors';


Question: Write the DML statement from PostgreSQL regression test 'merge' (example 445).

INSERT INTO pa_target SELECT '2017-01-31', id, id * 100, 'initial' FROM generate_series(1,9,3) AS id;

Explanation: DML from PostgreSQL core regression test for Merge.


Question: Generate PostgreSQL SQL for: Tell me the scoring average for year less than 1998 and wins more than 3

CREATE TABLE table_name_92 (scoring_average VARCHAR, year VARCHAR, wins VARCHAR)

SELECT scoring_average FROM table_name_92 WHERE year < 1998 AND wins > 3;


Question: What is the total amount of funding received from the "Government" source?

CREATE TABLE Funding (FundingID INT, FundingSource TEXT, Amount DECIMAL); INSERT INTO Funding (FundingID, FundingSource, Amount) VALUES (1, 'Government', 5000.00), (2, 'Private', 3000.00);

SELECT SUM(Amount) FROM Funding WHERE FundingSource = 'Government';


Question: What is the total donation amount by volunteers in Mexico, for each program, in the fiscal year 2022?

CREATE TABLE donations (id INT, donor_name VARCHAR(50), donation_amount DECIMAL(10,2), donation_date DATE, is_volunteer BOOLEAN, program_name VARCHAR(50)); INSERT INTO donations (id, donor_name, donation_amount, donation_date, is_volunteer, program_name) VALUES (1, 'Carlos Hernandez', 100.00, '2022-04-01', true, 'Program A'), (2, 'Ana Garcia', 200.00, '2022-07-01', true, 'Program B'), (3, 'Luis Rodriguez', 150.00, '2022-10-01', false, 'Program C'), (4, 'Mariana Sanchez', 50.00, '2022-01-01', true, 'Program A'); CREATE TABLE programs (id INT, program_name VARCHAR(50)); INSERT INTO programs (id, program_name) VALUES (1, 'Program A'), (2, 'Program B'), (3, 'Program C');

SELECT p.program_name, DATE_FORMAT(d.donation_date, '%Y-%V') AS fiscal_year, SUM(d.donation_amount) FROM donations d JOIN programs p ON d.program_name = p.program_name WHERE d.is_volunteer = true AND d.donor_country = 'Mexico' GROUP BY p.program_name, fiscal_year;


Question: Generate PostgreSQL SQL for: What is the location of the Durfee Mill No. 1, built before 1872 ?

CREATE TABLE table_name_7 (location VARCHAR, built VARCHAR, name VARCHAR)

SELECT location FROM table_name_7 WHERE built < 1872 AND name = 'durfee mill no. 1';


Question: What was the average sustainability score for the 'Spring 2022' collection?

CREATE TABLE garment_data_3 (garment_id INT, collection VARCHAR(20), sustainability_score FLOAT); INSERT INTO garment_data_3 (garment_id, collection, sustainability_score) VALUES (1, 'Spring 2022', 8.2), (2, 'Summer 2022', 8.7), (3, 'Autumn 2022', 9.0);

SELECT AVG(sustainability_score) FROM garment_data_3 WHERE collection = 'Spring 2022';


Question: List all artifacts with their respective analysis results, excluding those from 'Site13'.

CREATE TABLE Artifacts (ArtifactName VARCHAR(50), SiteName VARCHAR(50), AnalysisResult VARCHAR(50)); INSERT INTO Artifacts (ArtifactName, SiteName, AnalysisResult) VALUES ('ArtifactC1', 'Site13', 'ResultC1'), ('ArtifactC2', 'Site14', 'ResultC2'), ('ArtifactD1', 'Site15', 'ResultD1');

SELECT ArtifactName, AnalysisResult FROM Artifacts WHERE SiteName != 'Site13';


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

select jsonb_to_tsvector('english', '{"a": "aaa in bbb", "b": 123, "c": 456, "d": true, "f": false, "g": null}'::jsonb, '["all", null]');

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

SELECT count(*) FROM (select jsonb_to_tsvector('english', '{"a": "aaa in bbb", "b": 123, "c": 456, "d": true, "f": false, "g": null}'::jsonb, '["all", null]')) AS _sub;


Question: What is the average cultural competency score for hospitals in each state?

CREATE TABLE HospitalsCulturalCompetency (HospitalID INT, State VARCHAR(255), CulturalCompetencyScore INT); INSERT INTO HospitalsCulturalCompetency (HospitalID, State, CulturalCompetencyScore) VALUES (1, 'California', 85), (2, 'New York', 90), (3, 'Florida', 75), (4, 'Texas', 80), (5, 'Pennsylvania', 95);

SELECT State, AVG(CulturalCompetencyScore) as AvgCulturalCompetencyScore FROM HospitalsCulturalCompetency GROUP BY State;


Question: How many mobile and broadband customers are there in each region?

CREATE TABLE mobile_customers (customer_id INT, region VARCHAR(20)); CREATE TABLE broadband_customers (customer_id INT, region VARCHAR(20)); INSERT INTO mobile_customers (customer_id, region) VALUES (1, 'NE'), (2, 'SE'), (3, 'NW'); INSERT INTO broadband_customers (customer_id, region) VALUES (4, 'NE'), (5, 'SW'), (6, 'NE');

SELECT 'mobile' as service, region, COUNT(*) as num_customers FROM mobile_customers GROUP BY region UNION ALL SELECT 'broadband', region, COUNT(*) FROM broadband_customers GROUP BY region;


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

CREATE TABLE fkpart13_t2 (
  part_id int PRIMARY KEY,
  column_to_drop int,
  FOREIGN KEY (part_id) REFERENCES fkpart13_t1 ON UPDATE CASCADE ON DELETE CASCADE
) PARTITION BY LIST (part_id);

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


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

select sum(salary) over (order by enroll_date range between '1 year'::interval preceding and '1 year'::interval following
	exclude group), salary, enroll_date from empsalary;

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

SELECT count(*) FROM (select sum(salary) over (order by enroll_date range between '1 year'::interval preceding and '1 year'::interval following
	exclude group), salary, enroll_date from empsalary) AS _sub;


Question: Find the minimum price of plus size clothing

CREATE TABLE products (id INT, category VARCHAR(50), subcategory VARCHAR(50), is_plus_size BOOLEAN, price DECIMAL(5,2)); INSERT INTO products (id, category, subcategory, is_plus_size, price) VALUES (1, 'Clothing', 'Tops', FALSE, 19.99), (2, 'Clothing', 'Pants', TRUE, 49.99), (3, 'Clothing', 'Dresses', FALSE, 69.99), (4, 'Clothing', 'Jackets', TRUE, 89.99), (5, 'Clothing', 'Skirts', FALSE, 39.99);

SELECT MIN(price) FROM products WHERE category = 'Clothing' AND is_plus_size = TRUE;


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

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


Question: What is the minimum age of patients diagnosed with HIV in Florida?

CREATE TABLE Patients (ID INT, Age INT, Disease VARCHAR(20), State VARCHAR(20)); INSERT INTO Patients (ID, Age, Disease, State) VALUES (1, 34, 'Tuberculosis', 'California'); INSERT INTO Patients (ID, Age, Disease, State) VALUES (2, 28, 'HIV', 'Florida');

SELECT MIN(Age) FROM Patients WHERE Disease = 'HIV' AND State = 'Florida';


Question: What is the number of teachers who have completed professional development in data science, by school district?

CREATE TABLE districts (district_id INT, district_name VARCHAR(255)); CREATE TABLE teachers (teacher_id INT, district_id INT, years_of_experience INT); CREATE TABLE workshops (workshop_id INT, district_id INT, workshop_topic VARCHAR(255), teacher_id INT); INSERT INTO districts (district_id, district_name) VALUES (1, 'Downtown'), (2, 'Uptown'); INSERT INTO teachers (teacher_id, district_id, years_of_experience) VALUES (1, 1, 5), (2, 1, 10), (3, 2, 3), (4, 2, 8); INSERT INTO workshops (workshop_id, district_id, workshop_topic, teacher_id) VALUES (1, 1, 'Data Science', 1), (2, 1, 'Data Science', 2), (3, 2, 'Data Science', 3), (4, 2, 'Data Science', 4);

SELECT sd.district_name, COUNT(w.teacher_id) as num_teachers FROM districts sd JOIN workshops w ON sd.district_id = w.district_id WHERE w.workshop_topic = 'Data Science' GROUP BY sd.district_name;


Question: Generate PostgreSQL SQL for: What is the only city name with a population density of 200?

CREATE TABLE table_21284653_1 (name VARCHAR, population_density VARCHAR)

SELECT name FROM table_21284653_1 WHERE population_density = '200';


Question: Generate PostgreSQL SQL for: What is the highest tonnage for a ship from Great Britain named Newton Ash?

CREATE TABLE table_name_13 (tonnage INTEGER, nationality VARCHAR, ship VARCHAR)

SELECT MAX(tonnage) FROM table_name_13 WHERE nationality = 'great britain' AND ship = 'newton ash';


Question: What was the total revenue for each team's merchandise sales by month in 2022?

CREATE TABLE teams (id INT, name VARCHAR(255)); INSERT INTO teams (id, name) VALUES (1, 'TeamA'), (2, 'TeamB'), (3, 'TeamC'); CREATE TABLE merchandise_sales (team_id INT, year INT, month INT, revenue DECIMAL(10,2));

SELECT t.name, m.month, SUM(m.revenue) as total_revenue FROM merchandise_sales m JOIN teams t ON m.team_id = t.id WHERE m.year = 2022 GROUP BY t.name, m.month;


Question: Generate PostgreSQL SQL for: Find the patient who has the most recent undergoing treatment?

CREATE TABLE undergoes (patient VARCHAR, dateundergoes VARCHAR)

SELECT patient FROM undergoes ORDER BY dateundergoes LIMIT 1;


Question: Generate PostgreSQL SQL for: How many CFL teams drafted someone from mount allison college?

CREATE TABLE table_26996293_3 (cfl_team VARCHAR, college VARCHAR)

SELECT COUNT(cfl_team) FROM table_26996293_3 WHERE college = 'Mount Allison';


Question: PostgreSQL Json: show example 4.

-- Simple scalar/primitive values contain only the identical value: SELECT '"foo"'::jsonb @> '"foo"'::jsonb; -- The array on the right side is contained within the one on the left: SELECT '[1, 2, 3]'::jsonb @> '[1, 3]'::jsonb; -- Order of array elements is not significant, so this is also true: SELECT '[1, 2, 3]'::jsonb @> '[3, 1]'::jsonb; -- Duplicate array elements don't matter either: SELECT '[1, 2, 3]'::jsonb @> '[1, 2, 2]'::jsonb; -- The object with a single pair on the right side is contained -- within the object on the left side: SELECT '{"product": "PostgreSQL", "version": 9.4, "jsonb": true}'::jsonb @> '{"version": 9.4}'::jsonb; -- The array on the right side is not considered contained within the -- array on the left, even though a similar array is nested within it: SELECT '[1, 2, [1, 3]]'::jsonb @> '[1, 3]'::jsonb; -- yields false -- But with a layer of nesting, it is contained: SELECT '[1, 2, [1, 3]]'::jsonb @> '[[1, 3]]'::jsonb; -- Similarly, containment is not reported here: SELECT '{"foo": {"bar": "baz"}}'::jsonb @> '{"bar": "baz"}'::jsonb; -- yields false -- A top-level key and an empty object is contained: SELECT '{"foo": {"bar": "baz"}}'::jsonb @> '{"foo": {}}'::jsonb;

Explanation: Example from PostgreSQL documentation on Json.


Question: What is the total number of inclusive housing units in the state of Florida?

CREATE TABLE housing (id INT, state VARCHAR(20), inclusive BOOLEAN); INSERT INTO housing (id, state, inclusive) VALUES (1, 'Florida', TRUE), (2, 'Florida', FALSE), (3, 'Florida', TRUE);

SELECT COUNT(*) FROM housing WHERE state = 'Florida' AND inclusive = TRUE;


Question: How many employees in each department have been promoted in the past year?

CREATE TABLE Employees (EmployeeID INT, Department VARCHAR(25), Salary DECIMAL(10, 2), PromotionDate DATE); INSERT INTO Employees (EmployeeID, Department, Salary, PromotionDate) VALUES (1, 'Marketing', 60000, '2021-12-01'), (2, 'IT', 70000, NULL), (3, 'Marketing', 65000, NULL), (4, 'IT', 75000, '2022-02-01');

SELECT Department, COUNT(*) FROM Employees WHERE PromotionDate >= DATEADD(year, -1, GETDATE()) GROUP BY Department;


Question: Generate PostgreSQL SQL for: What's the track for 1978?

CREATE TABLE table_name_47 (track VARCHAR, year VARCHAR)

SELECT track FROM table_name_47 WHERE year = 1978;


Question: pgTAP test for Aretap (assertion 66).

SELECT * FROM check_test(
    sequences_are( ARRAY['sumeseq', 'someseq', 'bar'] ),
    false,
    'sequences_are(sequences) missing',
    'Search path ' || pg_catalog.current_setting('search_path') || ' should have the correct sequences',
    '    Missing sequences:
        bar'
);

Explanation: SQL assertion from pgTAP test suite for Aretap.


Question: Update all records in the 'ingredient' table where the 'origin' column is 'China'

CREATE TABLE ingredient (product_id INT, ingredient TEXT, origin TEXT);

UPDATE ingredient SET origin = 'Taiwan' WHERE origin = 'China';


Question: Insert a new record in the 'state_facts' table with data for the state of 'TX': capital 'Austin', population 29_527_941, and area 268_596 sq miles

CREATE TABLE state_facts (state VARCHAR(2), capital VARCHAR(50), population INT, area_sq_miles INT);

INSERT INTO state_facts (state, capital, population, area_sq_miles) VALUES ('TX', 'Austin', 29527941, 268596);


Question: Generate PostgreSQL SQL for: What year was she on a 350cc class bike, ranked 16th, with over 0 wins?

CREATE TABLE table_name_85 (year INTEGER, wins VARCHAR, class VARCHAR, rank VARCHAR)

SELECT SUM(year) FROM table_name_85 WHERE class = '350cc' AND rank = '16th' AND wins > 0;


Question: Identify the number of unique volunteers who participated in events in NYC in 2020 and the average number of hours they contributed.

CREATE TABLE Volunteers (VolunteerID int, EventID int, Hours decimal(5,2)); INSERT INTO Volunteers (VolunteerID, EventID, Hours) VALUES (1, 100, 5.5), (2, 101, 7.2), (3, 100, 3.8), (4, 102, 6.5), (5, 101, 8.0);

SELECT COUNT(DISTINCT VolunteerID), AVG(Hours) FROM Volunteers INNER JOIN (SELECT EventID FROM Events WHERE City = 'NYC') AS EventLocations ON Volunteers.EventID = EventLocations.EventID WHERE EXTRACT(YEAR FROM EventDate) = 2020;


Question: Generate PostgreSQL SQL for: what is the current version of the project64 with gpl v2 license?

CREATE TABLE table_name_38 (current_version VARCHAR, license VARCHAR, name VARCHAR)

SELECT current_version FROM table_name_38 WHERE license = 'gpl v2' AND name = 'project64';


Question: What are the production figures for the 'Troll' field for the years 2018 and 2019

CREATE TABLE field_production (field VARCHAR(50), year INT, oil_production FLOAT, gas_production FLOAT); INSERT INTO field_production (field, year, oil_production, gas_production) VALUES ('Troll', 2018, 1234.5, 678.9); INSERT INTO field_production (field, year, oil_production, gas_production) VALUES ('Troll', 2019, 2345.6, 789.0);

SELECT year, oil_production, gas_production FROM field_production WHERE field = 'Troll';


Question: Create a view named "affordable_properties" that contains all properties with a sustainability rating of at least 80

CREATE TABLE properties (property_id INT, property_name VARCHAR(255), location VARCHAR(255), sustainability_rating INT); INSERT INTO properties (property_id, property_name, location, sustainability_rating) VALUES (1, 'Green Heights', 'Brooklyn', 85), (2, 'Sunrise Village', 'Seattle', 70), (3, 'EcoHaven', 'Austin', 88);

CREATE VIEW affordable_properties AS SELECT * FROM properties WHERE sustainability_rating >= 80;


Question: What is the average production rate of chemical X in the last 3 months?

CREATE TABLE Chemical_Production (Chemical_Name VARCHAR(255), Production_Date DATE, Production_Rate INT); INSERT INTO Chemical_Production (Chemical_Name, Production_Date, Production_Rate) VALUES ('Chemical X', '2022-01-01', 500), ('Chemical X', '2022-02-01', 600), ('Chemical X', '2022-03-01', 700);

SELECT AVG(Production_Rate) FROM Chemical_Production WHERE Chemical_Name = 'Chemical X' AND Production_Date >= DATE_SUB(CURDATE(), INTERVAL 3 MONTH);


Question: Generate PostgreSQL SQL for: what is the name when the lane is less than 4 and mark is 52.64?

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

SELECT name FROM table_name_37 WHERE lane < 4 AND mark = '52.64';


Question: Add a new record to the "sustainable_practices" table with an ID of 6, a description of 'Recycling initiatives in housekeeping', and a category of 'Waste'

CREATE TABLE sustainable_practices (practice_id INT, description TEXT, category VARCHAR(20));

INSERT INTO sustainable_practices (practice_id, description, category) VALUES (6, 'Recycling initiatives in housekeeping', 'Waste');


Question: Which decentralized applications were developed by Stellar's development team?

CREATE TABLE decentralized_apps (app_name VARCHAR(255), developer VARCHAR(255)); INSERT INTO decentralized_apps (app_name, developer) VALUES ('StellarPort', 'Stellar Devs'); INSERT INTO decentralized_apps (app_name, developer) VALUES ('Smartlands', 'Stellar Devs');

SELECT app_name FROM decentralized_apps WHERE developer = 'Stellar Devs';


Question: Generate PostgreSQL SQL for: Find the year which offers the largest number of courses.

SELECT YEAR FROM SECTION GROUP BY YEAR ORDER BY COUNT(*) DESC LIMIT 1;


Question: Generate PostgreSQL SQL for: What is the type for EU Council Presidency of UK and John Major as President-in-Office?

CREATE TABLE table_name_27 (type VARCHAR, eu_council_presidency VARCHAR, president_in_office VARCHAR)

SELECT type FROM table_name_27 WHERE eu_council_presidency = 'uk' AND president_in_office = 'john major';


Question: Generate PostgreSQL SQL for: What were the blocks per game in the selection where the field goal percentage was .594 (2nd)?

CREATE TABLE table_25774493_3 (blocks_per_game VARCHAR, field_goal_percentage VARCHAR)

SELECT blocks_per_game FROM table_25774493_3 WHERE field_goal_percentage = '.594 (2nd)';


Question: What is the total budget allocated for infrastructure projects in the 'StateData' schema's 'StateInfrastructure' table, for services provided by private contractors in 2024?

CREATE SCHEMA StateData; CREATE TABLE StateInfrastructure (Service varchar(255), Year int, Budget int, Contractor varchar(255)); INSERT INTO StateInfrastructure (Service, Year, Budget, Contractor) VALUES ('Roads', 2024, 300000, 'Public'), ('Roads', 2024, 700000, 'Private'), ('Bridges', 2024, 500000, 'Public');

SELECT SUM(Budget) FROM StateData.StateInfrastructure WHERE Year = 2024 AND Contractor = 'Private';


Question: What is the maximum duration of 'Deep Space' missions?

CREATE TABLE MissionData (name VARCHAR(50), type VARCHAR(15), duration INT); INSERT INTO MissionData (name, type, duration) VALUES ('Ares 1', 'Low Earth Orbit', 150), ('Artemis 1', 'Deep Space', 300), ('Apollo 11', 'Low Earth Orbit', 200), ('Voyager 1', 'Deep Space', 400);

SELECT MAX(duration) FROM MissionData WHERE type = 'Deep Space';


Question: Find the total donation amount for each donor

CREATE TABLE DonationAmounts (DonationID INT, DonorID INT, DonationDate DATE, DonationAmount DECIMAL(10,2));

SELECT DonorID, SUM(DonationAmount) FROM DonationAmounts GROUP BY DonorID;


Question: What is the maximum number of articles published in a day by "Al Jazeera" in 2022?

CREATE TABLE articles (id INT, title TEXT, publication TEXT, published_at DATE); INSERT INTO articles (id, title, publication, published_at) VALUES (1, 'Article 1', 'Al Jazeera', '2022-01-01'); INSERT INTO articles (id, title, publication, published_at) VALUES (2, 'Article 2', 'Al Jazeera', '2022-01-02'); INSERT INTO articles (id, title, publication, published_at) VALUES (3, 'Article 3', 'Al Jazeera', '2022-01-02');

SELECT MAX(cnt) FROM (SELECT published_at, COUNT(*) as cnt FROM articles WHERE publication = 'Al Jazeera' AND YEAR(published_at) = 2022 GROUP BY published_at) as t;


Question: Generate PostgreSQL SQL for: What is the Place of the Player with a To par of –1?

CREATE TABLE table_name_61 (place VARCHAR, to_par VARCHAR)

SELECT place FROM table_name_61 WHERE to_par = '–1';


Question: How many hours did each volunteer contribute in the first quarter of 2024, including any partial hours?

CREATE TABLE VolunteerHours (HourID INT, VolunteerID INT, Hours DECIMAL(10,2), HourDate DATE);

SELECT V.Name, SUM(VH.Hours) as TotalHours  FROM VolunteerHours VH JOIN Volunteers V ON VH.VolunteerID = Volunteers.VolunteerID WHERE VH.HourDate BETWEEN '2024-01-01' AND '2024-03-31' GROUP BY V.VolunteerID, V.Name;


Question: Generate PostgreSQL SQL for: What is the 1st(m) score for the Person who had a total points of 272.7

CREATE TABLE table_14407512_9 (points VARCHAR)

SELECT 1 AS st__m_ FROM table_14407512_9 WHERE points = '272.7';


Question: Generate PostgreSQL SQL for: Which incumbent was in the 24th district?

CREATE TABLE table_name_60 (incumbent VARCHAR, district VARCHAR)

SELECT incumbent FROM table_name_60 WHERE district = '24th';


Question: PostgreSQL regression test 'brin_multi': Write the SELECT query (example 96).

SELECT COUNT(*) FROM brin_test_multi_1 WHERE a <= 25;

Explanation: Regression test for Brin Multi in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT COUNT(*) FROM brin_test_multi_1 WHERE a <= 25) AS _sub;


Question: Generate PostgreSQL SQL for: Candidate of riikka manner has how many votes?

CREATE TABLE table_name_41 (votes VARCHAR, candidate VARCHAR)

SELECT votes FROM table_name_41 WHERE candidate = 'riikka manner';


Question: Generate PostgreSQL SQL for: What was the film title nominated from the Netherlands?

CREATE TABLE table_name_18 (film_title_used_in_nomination VARCHAR, country VARCHAR)

SELECT film_title_used_in_nomination FROM table_name_18 WHERE country = 'netherlands';


Question: Generate PostgreSQL SQL for: How many total gold medals did India receive?

CREATE TABLE table_name_10 (gold VARCHAR, nation VARCHAR)

SELECT gold FROM table_name_10 WHERE nation = 'india';


Question: Generate PostgreSQL SQL for: What date was Rodger Ward the winning driver?

CREATE TABLE table_name_48 (date VARCHAR, winning_driver VARCHAR)

SELECT date FROM table_name_48 WHERE winning_driver = 'rodger ward';


Question: Delete all records of a specific type of intelligence operation in the "intelligence_ops" table

CREATE TABLE intelligence_ops (id INT, year INT, location VARCHAR(255), type VARCHAR(255), result VARCHAR(255)); INSERT INTO intelligence_ops (id, year, location, type, result) VALUES (1, 2015, 'Russia', 'Surveillance', 'Success'), (2, 2015, 'Germany', 'Infiltration', 'Failure');

DELETE FROM intelligence_ops WHERE type = 'Infiltration';


Question: What is the minimum pH level in brackish water shrimp farms in India?

CREATE TABLE water_params (id INT, farm_id INT, country TEXT, water_type TEXT, pH DECIMAL(4,2)); INSERT INTO water_params (id, farm_id, country, water_type, pH) VALUES (1, 1, 'India', 'Brackish', 7.8); INSERT INTO water_params (id, farm_id, country, water_type, pH) VALUES (2, 2, 'India', 'Brackish', 7.6); INSERT INTO water_params (id, farm_id, country, water_type, pH) VALUES (3, 3, 'India', 'Freshwater', 7.9);

SELECT MIN(pH) FROM water_params WHERE country = 'India' AND water_type = 'Brackish';


Question: Generate PostgreSQL SQL for: What frequency does Chihuahua Sinaloa Durango cover?

CREATE TABLE table_14670060_1 (frequency VARCHAR, coverage VARCHAR)

SELECT frequency FROM table_14670060_1 WHERE coverage = 'Chihuahua Sinaloa Durango';


Question: What is the average annual temperature change in the last 5 years for the Arctic region?

CREATE TABLE arctic_temperatures (location VARCHAR(50), year INTEGER, temperature FLOAT); INSERT INTO arctic_temperatures (location, year, temperature) VALUES ('Arctic', 2016, -23.4), ('Arctic', 2017, -23.2), ('Arctic', 2018, -23.0), ('Arctic', 2019, -22.8), ('Arctic', 2020, -22.6), ('Arctic', 2021, -22.4);

SELECT AVG(temperature - LAG(temperature) OVER (ORDER BY year)) AS avg_annual_temp_change  FROM arctic_temperatures WHERE location = 'Arctic' AND year BETWEEN 2016 AND 2021;


Question: What is the percentage of players who have completed a given achievement, broken down by platform?

CREATE TABLE GameAchievements (PlayerID INT, PlayerName TEXT, Platform TEXT, Achievement TEXT, Completed BOOLEAN); INSERT INTO GameAchievements (PlayerID, PlayerName, Platform, Achievement, Completed) VALUES (1, 'Alice', 'PC', 'Achievement 1', TRUE), (2, 'Bob', 'PC', 'Achievement 1', FALSE), (3, 'Charlie', 'Console', 'Achievement 1', TRUE), (4, 'David', 'Console', 'Achievement 1', TRUE), (5, 'Eve', 'PC', 'Achievement 1', FALSE);

SELECT Platform, (COUNT(*) FILTER (WHERE Completed = TRUE)) * 100.0 / COUNT(*) AS PercentageCompleted FROM GameAchievements GROUP BY Platform;


Question: Generate PostgreSQL SQL for: What title had a remark of #21 us [riaa certified gold january 3, 1990]?

CREATE TABLE table_name_61 (title VARCHAR, remark VARCHAR)

SELECT title FROM table_name_61 WHERE remark = '#21 us [riaa certified gold january 3, 1990]';


Question: Add a new department 'research' and insert an employee named 'Eli' into it with the 'employee' role and an id of 5.

CREATE TABLE departments (id INT, department VARCHAR(50)); CREATE TABLE employees (id INT, name VARCHAR(50), department VARCHAR(50), role VARCHAR(50)); INSERT INTO departments (id, department) VALUES (1, 'hr'), (2, 'operations'), (3, 'it'), (4, 'marketing'), (5, 'research');

INSERT INTO employees (id, name, department, role) VALUES (5, 'Eli', 'research', 'employee');


Question: What is the maximum altitude reached by space probes?

CREATE TABLE Space_Probes (probe_name TEXT, max_altitude FLOAT); INSERT INTO Space_Probes (probe_name, max_altitude) VALUES ('Voyager 1', 21384000000), ('New Horizons', 12670000000), ('Pioneer 10', 12670000000), ('Voyager 2', 11620000000), ('Pioneer 11', 10500000000);

SELECT max_altitude as max_altitude_reached FROM Space_Probes ORDER BY max_altitude DESC LIMIT 1;


Question: Generate PostgreSQL SQL for: What is the lowest number of points for Drivers that have raced in more than 16 Races?

CREATE TABLE table_name_35 (points INTEGER, races INTEGER)

SELECT MIN(points) FROM table_name_35 WHERE races > 16;


Question: Delete the volunteer with ID 2

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

DELETE FROM volunteers WHERE volunteer_id = 2;


Question: What is the maximum number of stories in buildings in Brazil and Argentina?

CREATE TABLE buildings (id INT, country VARCHAR(255), building_name VARCHAR(255), number_of_stories INT); INSERT INTO buildings (id, country, building_name, number_of_stories) VALUES (1, 'Brazil', 'Edifício Copan', 38), (2, 'Brazil', 'Museum of Tomorrow', 14), (3, 'Argentina', 'Alvear Tower', 54), (4, 'Argentina', 'Kavanagh', 33);

SELECT country, MAX(number_of_stories) FROM buildings GROUP BY country;


Question: Generate PostgreSQL SQL for: What is the Nominee from the Category that is best costume design?

CREATE TABLE table_name_64 (nominee VARCHAR, category VARCHAR)

SELECT nominee FROM table_name_64 WHERE category = 'best costume design';


Question: What is the number of patients treated by gender?

CREATE TABLE Patients (PatientID int, Gender varchar(10)); INSERT INTO Patients (PatientID, Gender) VALUES (1, 'Male'), (2, 'Female');

SELECT Gender, COUNT(*) FROM Patients GROUP BY Gender;


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

$$;

CREATE TRIGGER city_delete_trig INSTEAD OF DELETE ON city_view
FOR EACH ROW EXECUTE PROCEDURE city_delete();

CREATE FUNCTION city_update() RETURNS trigger LANGUAGE plpgsql AS $$
declare
    ctry_id int;

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


Question: What is the total number of military personnel and military spending for each country involved in defense diplomacy?

CREATE TABLE defense_diplomacy (id INT, country VARCHAR, military_personnel INT, military_spending FLOAT);

SELECT country, SUM(military_personnel) AS total_military_personnel, SUM(military_spending) AS total_military_spending FROM defense_diplomacy GROUP BY country;


Question: Generate PostgreSQL SQL for: What is the earliest round where the gt winning car is max angelelli?

CREATE TABLE table_28490105_1 (rnd INTEGER, gt_winning_car VARCHAR)

SELECT MIN(rnd) FROM table_28490105_1 WHERE gt_winning_car = 'Max Angelelli';


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

SELECT crypt('the minimum number is still observed', '$6$rounds=10$roundstoolow')
           = '$6$rounds=1000$roundstoolow$kUMsbe306n21p9R.FRkW3IGn.S9NPN0x50YhH1xhLsPuWGsUSklZt58jaTfF4ZEQpyUNGc0dqbpBYYBaHHrsX.' AS result;

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


Question: Generate PostgreSQL SQL for: Which overall pick number went to college at Youngstown State?

CREATE TABLE table_10360823_1 (overall INTEGER, college VARCHAR)

SELECT MIN(overall) FROM table_10360823_1 WHERE college = 'Youngstown State';


Question: What is the total number of hotels in each country?

CREATE TABLE hotels_geo (id INT PRIMARY KEY, hotel_id INT, country VARCHAR(255));

SELECT h.country, COUNT(DISTINCT hg.hotel_id) FROM hotels h JOIN hotels_geo hg ON h.id = hg.hotel_id GROUP BY h.country;


Question: Find the total number of open data sets related to transparency in 'city', 'county', and 'state' schemas.

CREATE SCHEMA city; CREATE SCHEMA county; CREATE SCHEMA state; CREATE TABLE city.transparency_data (id INT, name VARCHAR(255), is_open BOOLEAN); CREATE TABLE county.transparency_data (id INT, name VARCHAR(255), is_open BOOLEAN); CREATE TABLE state.transparency_data (id INT, name VARCHAR(255), is_open BOOLEAN); INSERT INTO city.transparency_data (id, name, is_open) VALUES (1, 'budget', true), (2, 'council_meetings', true); INSERT INTO county.transparency_data (id, name, is_open) VALUES (1, 'budget', false), (2, 'council_meetings', true); INSERT INTO state.transparency_data (id, name, is_open) VALUES (1, 'budget', true), (2, 'council_meetings', false);

SELECT COUNT(*) FROM ( (SELECT * FROM city.transparency_data WHERE is_open = true) UNION (SELECT * FROM county.transparency_data WHERE is_open = true) UNION (SELECT * FROM state.transparency_data WHERE is_open = true) ) AS combined_transparency_data;


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

CREATE EXTENSION IF NOT EXISTS plpgsql WITH SCHEMA pg_catalog;

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


Question: Generate PostgreSQL SQL for: What was the place for player John Merrick?

CREATE TABLE table_name_52 (place VARCHAR, player VARCHAR)

SELECT place FROM table_name_52 WHERE player = 'john merrick';


Question: Generate PostgreSQL SQL for: Which Location has a Competition of Group Stage, a Lineup of Start and a Date of 2000-09-17?

CREATE TABLE table_name_67 (location VARCHAR, date VARCHAR, competition VARCHAR, lineup VARCHAR)

SELECT location FROM table_name_67 WHERE competition = 'group stage' AND lineup = 'start' AND date = '2000-09-17';


Question: What is the average budget for ocean floor mapping projects in each region?

CREATE TABLE ocean_floor_map (id INT, project_name VARCHAR(255), region VARCHAR(255), budget FLOAT);

SELECT region, avg(budget) FROM ocean_floor_map GROUP BY region;


Question: Find the total revenue of TV shows produced by Green Studios.

CREATE TABLE studio (studio_id INT, name VARCHAR(100)); INSERT INTO studio (studio_id, name) VALUES (1, 'Green Studios'); CREATE TABLE tv_show (tv_show_id INT, title VARCHAR(100), studio_id INT, revenue INT);

SELECT SUM(tv_show.revenue) FROM tv_show WHERE tv_show.studio_id = 1;


Question: What is the maximum account balance for customers in each region?

CREATE TABLE customer_data_2 (customer_id INT, account_balance DECIMAL(10, 2), region VARCHAR(20)); INSERT INTO customer_data_2 (customer_id, account_balance, region) VALUES (1, 5000, 'Latin America'), (2, 7000, 'North America'), (3, 6000, 'Latin America'), (4, 8000, 'Europe'), (5, 9000, 'Asia'); CREATE VIEW customer_data_view AS SELECT region, MAX(account_balance) as max_balance FROM customer_data_2 GROUP BY region;

SELECT region, max_balance FROM customer_data_view;


Question: Generate PostgreSQL SQL for: How many points are in the scored category for the team that played less than 18 games?

CREATE TABLE table_name_41 (scored INTEGER, played INTEGER)

SELECT SUM(scored) FROM table_name_41 WHERE played < 18;


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

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


Question: Generate PostgreSQL SQL for: In the region where Roskilde is the largest city, what is the seat of administration?

CREATE TABLE table_16278602_1 (seat_of_administration VARCHAR, largest_city VARCHAR)

SELECT seat_of_administration FROM table_16278602_1 WHERE largest_city = 'Roskilde';


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

select format('%2$s, %1$s', variadic array['first', 'second']);

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

SELECT count(*) FROM (select format('%2$s, %1$s', variadic array['first', 'second'])) AS _sub;


Question: How many sustainable building projects were completed in New York in 2021?

CREATE TABLE sustainable_projects (id INT, project_name TEXT, state TEXT, completion_year INT, is_sustainable BOOLEAN); INSERT INTO sustainable_projects (id, project_name, state, completion_year, is_sustainable) VALUES (1, 'Solar Park', 'New York', 2021, true), (2, 'Wind Farm', 'California', 2020, true), (3, 'Green Apartments', 'New York', 2021, true), (4, 'Eco-Hotel', 'Florida', 2020, false);

SELECT COUNT(*) FROM sustainable_projects WHERE state = 'New York' AND completion_year = 2021 AND is_sustainable = true;


Question: Generate PostgreSQL SQL for: Which Circuit did Johnny Wakefield win?

CREATE TABLE table_name_3 (circuit VARCHAR, winning_driver VARCHAR)

SELECT circuit FROM table_name_3 WHERE winning_driver = 'johnny wakefield';


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

SELECT ts_filter('base hidden rebel spaceship strike'::tsvector, '{a,b,NULL}');

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

SELECT count(*) FROM (SELECT ts_filter('base hidden rebel spaceship strike'::tsvector, '{a,b,NULL}')) AS _sub;


Question: Determine the number of wind turbines installed in Germany

CREATE TABLE WindTurbines (id INT, name TEXT, height INT, location TEXT); INSERT INTO WindTurbines (id, name, height, location) VALUES (1, 'Enercon E-126', 198, 'Germany'); INSERT INTO WindTurbines (id, name, height, location) VALUES (2, 'Vestas V164', 220, 'Denmark');

SELECT COUNT(*) FROM WindTurbines WHERE location = 'Germany';


Question: Delete records for strains sold in Michigan dispensaries with sales amounts less than 500.

CREATE TABLE OldDispensary (StrainName VARCHAR(255), SalesAmount DECIMAL(10,2), State VARCHAR(255));

DELETE FROM OldDispensary WHERE SalesAmount < 500 AND State = 'Michigan';


Question: List all unique fields from the 'geology' and 'drilling' tables.

CREATE TABLE geology (well_id INT, rock_type VARCHAR(50)); CREATE TABLE drilling (well_id INT, drill_depth INT);

SELECT field FROM (SELECT 'geology' as table_name, column_name as field FROM information_schema.columns WHERE table_name = 'geology' UNION ALL SELECT 'drilling' as table_name, column_name as field FROM information_schema.columns WHERE table_name = 'drilling') as subquery;


Question: List the tree species with their respective average timber volume in the private_lands schema, in descending order.

CREATE TABLE private_lands.timber_volume (species VARCHAR(255), volume DECIMAL(5,2));

SELECT species, AVG(volume) AS avg_volume FROM private_lands.timber_volume GROUP BY species ORDER BY avg_volume DESC;


Question: What is the minimum age of readers who prefer opinion pieces in the 'Latin America' region?

CREATE TABLE readers (id INT, name TEXT, age INT, region TEXT, interest TEXT); INSERT INTO readers (id, name, age, region, interest) VALUES (1, 'Juan Garcia', 28, 'Latin America', 'opinion');

SELECT MIN(age) FROM readers WHERE interest = 'opinion' AND region = 'Latin America';


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

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

SELECT count(*) FROM (select * from float8range_test) AS _sub;


Question: What is the maximum salary of female employees in the Finance department?

CREATE TABLE Employees (EmployeeID INT, Department VARCHAR(20), Gender VARCHAR(10), Salary FLOAT); INSERT INTO Employees (EmployeeID, Department, Gender, Salary) VALUES (1, 'IT', 'Male', 70000), (2, 'HR', 'Female', 60000), (3, 'IT', 'Female', 75000), (4, 'IT', 'Male', 78000), (5, 'Finance', 'Male', 85000), (6, 'Finance', 'Female', 90000), (7, 'HR', 'Male', 65000);

SELECT MAX(Salary) FROM Employees WHERE Department = 'Finance' AND Gender = 'Female';


Question: What is the maximum number of mental health parity complaints filed in the last 6 months for the Native Hawaiian or Other Pacific Islander race?

CREATE TABLE mental_health_parity_complaints (complaint_id INT, complaint_date DATE, race VARCHAR(20)); INSERT INTO mental_health_parity_complaints (complaint_id, complaint_date, race) VALUES (1, '2021-07-01', 'Asian'), (2, '2021-03-15', 'Black'), (3, '2021-01-01', 'Native Hawaiian or Other Pacific Islander');

SELECT MAX(complaint_count) as max_complaints FROM (SELECT COUNT(*) as complaint_count FROM mental_health_parity_complaints WHERE complaint_date >= DATE_SUB(CURRENT_DATE, INTERVAL 6 MONTH) AND race = 'Native Hawaiian or Other Pacific Islander' GROUP BY complaint_date) as subquery;


Question: Generate PostgreSQL SQL for: Which challenge loser has a Challenge Winner of roseny?

CREATE TABLE table_name_81 (challenge_loser VARCHAR, challenge_winner VARCHAR)

SELECT challenge_loser FROM table_name_81 WHERE challenge_winner = 'roseny';


Question: pgTAP test for Pg73 (assertion 21).

select is('a'::char, 'a'::char, 'a=a char');

Explanation: SQL assertion from pgTAP test suite for Pg73.


Question: Generate PostgreSQL SQL for: What is the average of lost for place less than 10, less than 23 points, and goals conceded less than 26 for the Chorrillo team?

CREATE TABLE table_name_21 (lost INTEGER, goals_conceded VARCHAR, team VARCHAR, place VARCHAR, points VARCHAR)

SELECT AVG(lost) FROM table_name_21 WHERE place < 10 AND points < 23 AND team = 'chorrillo' AND goals_conceded < 26;


Question: Generate PostgreSQL SQL for: Name the record for december 6

CREATE TABLE table_17058151_6 (record VARCHAR, date VARCHAR)

SELECT record FROM table_17058151_6 WHERE date = 'December 6';


Question: Which tennis player won the most matches in the 'wins' table?

CREATE TABLE wins (win_id INT, player_id INT, match_id INT, team_id INT, wins INT); INSERT INTO wins (win_id, player_id, match_id, team_id, wins) VALUES (1, 13, 14, 715, 10);


Question: Generate PostgreSQL SQL for: WHEN has a Result of w 23–17?

CREATE TABLE table_name_96 (date VARCHAR, result VARCHAR)

SELECT date FROM table_name_96 WHERE result = 'w 23–17';


Question: Generate PostgreSQL SQL for: Which railway was built in 1909?

CREATE TABLE table_name_63 (railway VARCHAR, built VARCHAR)

SELECT railway FROM table_name_63 WHERE built = '1909';


Question: Generate PostgreSQL SQL for: What is the number of production codes for episode #73?

CREATE TABLE table_2623498_5 (prod_code VARCHAR, episode__number VARCHAR)

SELECT COUNT(prod_code) FROM table_2623498_5 WHERE episode__number = '73';


Question: Generate PostgreSQL SQL for: What are the actual delivery dates of orders with quantity 1?

CREATE TABLE Customer_Orders (Actual_Delivery_Date VARCHAR, Order_ID VARCHAR); CREATE TABLE ORDER_ITEMS (Order_ID VARCHAR, Order_Quantity VARCHAR)

SELECT T1.Actual_Delivery_Date FROM Customer_Orders AS T1 JOIN ORDER_ITEMS AS T2 ON T1.Order_ID = T2.Order_ID WHERE T2.Order_Quantity = 1;


Question: What is the average speed of each cyclist in the 2022 Tour de France?

CREATE TABLE cyclists (cyclist_id INT, cyclist_name VARCHAR(50), avg_speed DECIMAL(5,2)); INSERT INTO cyclists (cyclist_id, cyclist_name, avg_speed) VALUES (1, 'Tadej Pogacar', 40.2), (2, 'Jonas Vingegaard', 39.8), (3, 'Richard Carapaz', 39.3), (4, 'Geraint Thomas', 39.1), (5, 'Primož Roglič', 38.9);

SELECT AVG(avg_speed) as avg_speed FROM cyclists;


Question: Find the donors who have donated in the last month and their respective donation amounts.

SELECT donor_id, donation_amount FROM donor_history WHERE donation_date >= DATEADD(month, -1, CURRENT_DATE) ORDER BY donor_id;


Question: Generate PostgreSQL SQL for: What was the final score of the game on November 24 with the visiting team the Indianapolis Colts?

CREATE TABLE table_name_23 (final_score VARCHAR, visiting_team VARCHAR, date VARCHAR)

SELECT final_score FROM table_name_23 WHERE visiting_team = 'indianapolis colts' AND date = 'november 24';


Question: Generate PostgreSQL SQL for: What is the production code for the episode with 5.5 million u.s. viewers?

CREATE TABLE table_28195898_1 (production_code VARCHAR, us_viewers__millions_ VARCHAR)

SELECT production_code FROM table_28195898_1 WHERE us_viewers__millions_ = '5.5';


Question: Generate PostgreSQL SQL for: what is the location when the year is before 1979 and the result is 19-17?

CREATE TABLE table_name_68 (location VARCHAR, year VARCHAR, result VARCHAR)

SELECT location FROM table_name_68 WHERE year < 1979 AND result = '19-17';


Question: What is the number of juvenile offenders in the 'juvenile_justice' table?

CREATE TABLE juvenile_justice (offender_id INT, age INT, offense VARCHAR(50), disposition VARCHAR(30), processing_date DATE);

SELECT COUNT(*) FROM juvenile_justice WHERE age < 18;


Question: What is the average revenue per user (ARPU) for each game genre?

CREATE TABLE games (id INT, genre VARCHAR(255), revenue INT); INSERT INTO games (id, genre, revenue) VALUES (1, 'FPS', 100000), (2, 'RPG', 200000), (3, 'FPS', 150000);

SELECT genre, AVG(revenue) OVER (PARTITION BY genre) AS ARPU FROM games ORDER BY ARPU DESC;


Question: Insert a new organization focused on animal rights and effective altruism with id 5.

CREATE TABLE organizations (id INT, name VARCHAR(255), focus VARCHAR(255)); INSERT INTO organizations (id, name, focus) VALUES (3, 'Climate Foundation', 'Climate Change');

INSERT INTO organizations (id, name, focus) VALUES (5, 'Animal Rights Effective Altruism', 'Animal Rights, Effective Altruism');


Question: Generate PostgreSQL SQL for: What's the power output for channel tv-29?

CREATE TABLE table_2523809_1 (power__kw_ VARCHAR, channel VARCHAR)

SELECT power__kw_ FROM table_2523809_1 WHERE channel = 'TV-29';


Question: Generate PostgreSQL SQL for: Which Opponent has a Surface of hard on 28 august 1993?

CREATE TABLE table_name_46 (opponent VARCHAR, surface VARCHAR, date VARCHAR)

SELECT opponent FROM table_name_46 WHERE surface = 'hard' AND date = '28 august 1993';


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

SELECT * FROM test_timetz WHERE i<'08:55:08 GMT+2'::timetz ORDER BY i;

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


Question: What is the total biomass of cod in the Barents Sea?

CREATE TABLE FishData (species VARCHAR(50), location VARCHAR(50), biomass FLOAT); INSERT INTO FishData (species, location, biomass) VALUES ('Atlantic Cod', 'Barents Sea', 1200000), ('Herring', 'Barents Sea', 800000);

SELECT location, SUM(biomass) FROM FishData WHERE species = 'Atlantic Cod' GROUP BY location;


Question: Identify vessels with a rising number of violations.

CREATE TABLE VesselInspections (ID INT, Vessel VARCHAR(50), InspectionDate DATE, ViolationCount INT); INSERT INTO VesselInspections (ID, Vessel, InspectionDate, ViolationCount) VALUES (1, 'SS Freedom', '2020-01-01', 3), (2, 'SS Liberty', '2020-01-02', 2), (3, 'SS Eagle', '2020-01-03', 4), (4, 'SS Freedom', '2020-01-04', 4);

SELECT Vessel, ViolationCount, LEAD(ViolationCount) OVER (PARTITION BY Vessel ORDER BY InspectionDate) as NextViolationCount FROM VesselInspections;


Question: Generate PostgreSQL SQL for: Which Week has Attendance of 51,558?

CREATE TABLE table_name_71 (week INTEGER, attendance VARCHAR)

SELECT MIN(week) FROM table_name_71 WHERE attendance = 51 OFFSET 558;


Question: Update the "depth" column to 4000 for all records in the "oceanography" table where the "ocean_name" is "Pacific Ocean"

CREATE TABLE oceanography (id INT PRIMARY KEY, ocean_name VARCHAR(255), depth FLOAT); INSERT INTO oceanography (id, ocean_name, depth) VALUES (1, 'Pacific Ocean', 3970); INSERT INTO oceanography (id, ocean_name, depth) VALUES (2, 'Indian Ocean', 3960);

UPDATE oceanography SET depth = 4000 WHERE ocean_name = 'Pacific Ocean';


Question: How many users have engaged with 'Facebook' or 'LinkedIn' posts about data privacy in the last month?

CREATE TABLE Facebook(id INT, user_id INT, post_time TIMESTAMP, content TEXT, privacy_topic BOOLEAN); CREATE TABLE LinkedIn(id INT, user_id INT, post_time TIMESTAMP, content TEXT, privacy_topic BOOLEAN);

SELECT COUNT(DISTINCT user_id) FROM (SELECT user_id FROM Facebook WHERE post_time >= NOW() - INTERVAL '1 month' AND privacy_topic = TRUE UNION ALL SELECT user_id FROM LinkedIn WHERE post_time >= NOW() - INTERVAL '1 month' AND privacy_topic = TRUE) AS total_users;


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

SELECT proname, proargtypes, pronamespace
   FROM pg_proc
   WHERE proname >= 'abs' AND (proname, proargtypes) < ('abs', NULL)
ORDER BY proname, proargtypes, pronamespace;

Explanation: Regression test for Btree Index in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT proname, proargtypes, pronamespace
   FROM pg_proc
   WHERE proname >= 'abs' AND (proname, proargtypes) < ('abs', NULL)
ORDER BY proname, proargtypes, pronamespace) AS _sub;


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

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

SELECT count(*) FROM (SELECT power('-inf'::numeric, '-2')) AS _sub;


Question: PL/pgSQL test: Plpython Types (example 108).

SELECT * FROM test_type_conversion_array_text(ARRAY['foo', 'bar']);

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


Question: Generate PostgreSQL SQL for: Show the id, name of each festival and the number of artworks it has nominated.

CREATE TABLE nomination (Festival_ID VARCHAR, Artwork_ID VARCHAR); CREATE TABLE festival_detail (Festival_Name VARCHAR, Festival_ID VARCHAR); CREATE TABLE artwork (Artwork_ID VARCHAR)

SELECT T1.Festival_ID, T3.Festival_Name, COUNT(*) FROM nomination AS T1 JOIN artwork AS T2 ON T1.Artwork_ID = T2.Artwork_ID JOIN festival_detail AS T3 ON T1.Festival_ID = T3.Festival_ID GROUP BY T1.Festival_ID;


Question: What is the total number of criminal cases and their clearance rate by state?

CREATE TABLE states (state_id INT PRIMARY KEY, state_name VARCHAR(50)); CREATE TABLE cases (case_id INT PRIMARY KEY, state_id INT, case_type VARCHAR(50), cleared INT); INSERT INTO states VALUES (1, 'California'), (2, 'Texas'), (3, 'New York'); INSERT INTO cases VALUES (1, 1, 'Murder', 1), (2, 1, 'Theft', 0), (3, 2, 'Murder', 1), (4, 2, 'Theft', 1), (5, 3, 'Murder', 0), (6, 3, 'Theft', 1);

SELECT s.state_name, COUNT(c.case_id) AS total_cases, SUM(c.cleared) / COUNT(c.case_id) * 100 AS clearance_rate FROM states s JOIN cases c ON s.state_id = c.state_id GROUP BY s.state_id;


Question: What is the average funding for projects in the digital divide category?

CREATE TABLE projects (id INT, name TEXT, category TEXT, funding FLOAT); INSERT INTO projects (id, name, category, funding) VALUES (1, 'ProjA', 'DigitalDivide', 50000), (2, 'ProjB', 'SocialGood', 35000), (3, 'ProjC', 'DigitalDivide', 75000);

SELECT AVG(funding) FROM projects WHERE category = 'DigitalDivide';


Question: Write the DDL statement from PostgreSQL regression test 'create_table' (example 149).

CREATE TABLE fail_part PARTITION OF temp_parted FOR VALUES IN ('a');

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


Question: Generate PostgreSQL SQL for: what is the time/retired when the grid is less than 3 and 45 laps?

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

SELECT time_retired FROM table_name_95 WHERE grid < 3 AND laps = 45;


Question: Calculate the total revenue for the last 3 cricket world cups

CREATE TABLE events (id INT, name VARCHAR(50), sport VARCHAR(20), start_date DATE, end_date DATE, ticket_price INT);

SELECT SUM(DATEDIFF(end_date, start_date) + 1) * ticket_price FROM events WHERE sport = 'Cricket' AND name LIKE '%World Cup%' AND start_date >= DATE_SUB(CURDATE(), INTERVAL 3 YEAR);


Question: What is the maximum diameter at breast height (DBH) for trees in the tropical rainforest biome?

CREATE TABLE biomes (biome_id INT PRIMARY KEY, name VARCHAR(50), area_km2 FLOAT); INSERT INTO biomes (biome_id, name, area_km2) VALUES (1, 'Tropical Rainforest', 15000000.0), (2, 'Temperate Rainforest', 250000.0), (3, 'Boreal Forest', 12000000.0); CREATE TABLE trees (tree_id INT PRIMARY KEY, species VARCHAR(50), biome_id INT, dbh FLOAT, FOREIGN KEY (biome_id) REFERENCES biomes(biome_id)); INSERT INTO trees (tree_id, species, biome_id, dbh) VALUES (1, 'Rubber Tree', 1, 80.0), (2, 'Mahogany', 1, 60.0), (3, 'Cacao', 1, 30.0);

SELECT MAX(dbh) FROM trees WHERE biomes.name = 'Tropical Rainforest';


Question: How many collective bargaining agreements were signed in the 'Education' sector between 2015 and 2018?

CREATE TABLE CollectiveBargaining (AgreementID INT, Sector VARCHAR(20), SignDate DATE); INSERT INTO CollectiveBargaining (AgreementID, Sector, SignDate) VALUES (1, 'Education', '2015-05-01'), (2, 'Education', '2016-09-15'), (3, 'Healthcare', '2017-03-25');

SELECT COUNT(*) FROM CollectiveBargaining WHERE Sector = 'Education' AND SignDate BETWEEN '2015-01-01' AND '2018-12-31';


Question: Generate PostgreSQL SQL for: What is the home team score of the game with Adelaide as the away team?

CREATE TABLE table_name_90 (home_team VARCHAR, away_team VARCHAR)

SELECT home_team AS score FROM table_name_90 WHERE away_team = 'adelaide';


Question: Generate PostgreSQL SQL for: Show the average price range of hotels that have 5 star ratings and allow pets.

CREATE TABLE HOTELS (price_range INTEGER, star_rating_code VARCHAR, pets_allowed_yn VARCHAR)

SELECT AVG(price_range) FROM HOTELS WHERE star_rating_code = '5' AND pets_allowed_yn = 1;


Question: Update the donation amount for 'Jane Doe' to $500 for her donation made on 2022-05-15.

CREATE TABLE Donors (donor_id INT, donor_name TEXT, donation_amount DECIMAL, donation_date DATE);

UPDATE Donors SET Donors.donation_amount = 500 WHERE Donors.donor_name = 'Jane Doe' AND Donors.donation_date = '2022-05-15';


Question: Generate PostgreSQL SQL for: Whose origin of Programming offers a general genre, a network of ntv bangla and a service of cogeco cable?

CREATE TABLE table_name_12 (origin_of_programming VARCHAR, service VARCHAR, genre VARCHAR, network VARCHAR)

SELECT origin_of_programming FROM table_name_12 WHERE genre = 'general' AND network = 'ntv bangla' AND service = 'cogeco cable';


Question: What is the average number of employees for companies founded by veterans?

CREATE TABLE company (id INT, name TEXT, founding_year INT, founder_veteran BOOLEAN); INSERT INTO company (id, name, founding_year, founder_veteran) VALUES (1, 'Acme Inc', 2010, true); INSERT INTO company (id, name, founding_year, founder_veteran) VALUES (2, 'Beta Corp', 2015, false);

SELECT AVG(num_employees) FROM company_data INNER JOIN company ON company_data.company_id = company.id WHERE company.founder_veteran = true;


Question: Generate PostgreSQL SQL for: Who is fourth when Anders Martinson USA is second?

CREATE TABLE table_name_98 (fourth VARCHAR, second VARCHAR)

SELECT fourth FROM table_name_98 WHERE second = 'anders martinson usa';


Question: Delete records with a budget over 100000 in the 'community_development' table

CREATE TABLE community_development (id INT, project_name VARCHAR(255), budget INT, country VARCHAR(255));

DELETE FROM community_development WHERE budget > 100000;


Question: Generate PostgreSQL SQL for: Please show the team that has the most number of technicians.

SELECT Team FROM technician GROUP BY Team ORDER BY COUNT(*) DESC LIMIT 1;


Question: Generate PostgreSQL SQL for: What was the earliest aired show that's returning on September 13?

CREATE TABLE table_name_1 (last_aired INTEGER, returning VARCHAR)

SELECT MIN(last_aired) FROM table_name_1 WHERE returning = 'september 13';


Question: What is the total CO2 emissions reduction for each carbon offset project?

CREATE TABLE carbon_offset_projects (project_id INT, name VARCHAR(100), co2_reduction INT); INSERT INTO carbon_offset_projects (project_id, name, co2_reduction) VALUES (1, 'Forest Conservation', 10000);

SELECT name, SUM(co2_reduction) as total_co2_reduction FROM carbon_offset_projects GROUP BY name;


Question: Generate PostgreSQL SQL for: What is the total number of playoffs held in exactly 2006?

CREATE TABLE table_1999350_1 (playoffs VARCHAR, year VARCHAR)

SELECT COUNT(playoffs) FROM table_1999350_1 WHERE year = 2006;


Question: What is the average monthly salary of workers in the 'Labor Rights Union'?

CREATE TABLE union_members (member_id INT, member_name VARCHAR(255), union_id INT, monthly_salary DECIMAL(10,2)); CREATE TABLE unions (union_id INT, union_name VARCHAR(255)); INSERT INTO unions (union_id, union_name) VALUES (123, 'United Workers Union'); INSERT INTO unions (union_id, union_name) VALUES (456, 'Labor Rights Union'); INSERT INTO union_members (member_id, member_name, union_id, monthly_salary) VALUES (1, 'John Doe', 456, 3500.50); INSERT INTO union_members (member_id, member_name, union_id, monthly_salary) VALUES (2, 'Jane Doe', 123, 3200.25);

SELECT AVG(monthly_salary) FROM union_members WHERE union_id = (SELECT union_id FROM unions WHERE union_name = 'Labor Rights Union');


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

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

SELECT count(*) FROM (select jsonb_insert('{"a": [0,1,2]}', '{a, -1}', '"new_value"', true)) AS _sub;


Question: list all astronauts with more than 5 space missions

CREATE TABLE Astronauts(astronaut_id INT, name VARCHAR(50), country VARCHAR(50), missions INT);

SELECT name FROM Astronauts WHERE missions > 5;


Question: Generate PostgreSQL SQL for: What is the Opponent on Week 11?

CREATE TABLE table_name_28 (opponent VARCHAR, week VARCHAR)

SELECT opponent FROM table_name_28 WHERE week = 11;


Question: Generate PostgreSQL SQL for: What is the name of the team with a qual 1 time of 1:17.481?

CREATE TABLE table_name_77 (team VARCHAR, qual_1 VARCHAR)

SELECT team FROM table_name_77 WHERE qual_1 = '1:17.481';


Question: Insert a new artist 'Maria Fernandes' in the 'Artists' table

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

INSERT INTO Artists (ArtistID, ArtistName) VALUES (101, 'Maria Fernandes');


Question: Generate PostgreSQL SQL for: Who is the  pärnu manager?

CREATE TABLE table_27409644_1 (manager VARCHAR, club VARCHAR)

SELECT manager FROM table_27409644_1 WHERE club = 'Pärnu';


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

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


Question: How many graduate students are enrolled in STEM programs and have published at least one paper?

CREATE TABLE students (id INT, name VARCHAR(50), gender VARCHAR(10), program VARCHAR(50), publications INT); INSERT INTO students (id, name, gender, program, publications) VALUES (1, 'Charlie', 'Non-binary', 'Mathematics', 2), (2, 'Dana', 'Female', 'Physics', 0), (3, 'Eli', 'Male', 'Engineering', 1);

SELECT COUNT(*) FROM students WHERE program LIKE 'STEM%' AND publications > 0;


Question: Generate PostgreSQL SQL for: Which April has a Game of 84

CREATE TABLE table_name_54 (april INTEGER, game VARCHAR)

SELECT MAX(april) FROM table_name_54 WHERE game = 84;


Question: What is the name and efficiency of the solar panel with the highest efficiency in Japan?

CREATE TABLE solar_panels (id INT, name VARCHAR(255), efficiency FLOAT); INSERT INTO solar_panels (id, name, efficiency) VALUES (1, 'SolarPanel A', 18.5), (2, 'SolarPanel B', 20.3), (3, 'SolarPanel C', 21.0), (4, 'SolarPanel D', 19.1);

SELECT name, MAX(efficiency) FROM solar_panels WHERE country = 'Japan';


Question: What is the total number of marine life species observed in the Atlantic Ocean that are not sharks?

CREATE TABLE Oceans (id INT, name VARCHAR(20)); INSERT INTO Oceans (id, name) VALUES (1, 'Pacific'), (2, 'Atlantic'); CREATE TABLE SpeciesObservations (id INT, ocean_id INT, species VARCHAR(50), count INT); INSERT INTO SpeciesObservations (id, ocean_id, species, count) VALUES (1, 1, 'Shark', 500), (2, 1, 'Whale', 300), (3, 2, 'Shark', 700), (4, 2, 'Dolphin', 600);

SELECT SUM(SpeciesObservations.count) FROM SpeciesObservations JOIN Oceans ON SpeciesObservations.ocean_id = Oceans.id WHERE Oceans.name = 'Atlantic' AND SpeciesObservations.species != 'Shark';


Question: Generate PostgreSQL SQL for: Tell me the naame of Investigation of thrombus imaging

CREATE TABLE table_name_19 (name VARCHAR, investigation VARCHAR)

SELECT name FROM table_name_19 WHERE investigation = 'thrombus imaging';


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

ALTER EXTENSION pgtap ADD FUNCTION throws_ok ( TEXT, int4, TEXT );

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


Question: What is the maximum number of publications by a faculty member in a single year?

CREATE TABLE Publications(PubID INT, FacultyID INT, Year INT, NumArticles INT); INSERT INTO Publications(PubID, FacultyID, Year, NumArticles) VALUES (1, 1, 2019, 3), (2, 1, 2020, 5), (3, 2, 2018, 2), (4, 2, 2019, 4);

SELECT FacultyID, MAX(NumArticles) FROM Publications GROUP BY FacultyID;


Question: Generate PostgreSQL SQL for: What finish has +21 as the to par?

CREATE TABLE table_name_35 (finish VARCHAR, to_par VARCHAR)

SELECT finish FROM table_name_35 WHERE to_par = '+21';


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

SELECT tsquery_phrase('a <3> g', 'b & d', 10);

SELECT count(*) FROM (SELECT tsquery_phrase('a <3> g', 'b & d', 10)) AS _sub;


Question: What is the number of unique countries represented in the 'readers' table?

CREATE TABLE readers (id INT, name VARCHAR(50), age INT, gender VARCHAR(10), country VARCHAR(50));

SELECT COUNT(DISTINCT country) FROM readers;


Question: List of countries with the highest environmental impact score in the past year.

CREATE TABLE EnvironmentalImpact(id INT, country VARCHAR(50), year INT, score FLOAT); CREATE TABLE CountryPopulation(id INT, country VARCHAR(50), population INT);

SELECT country, score FROM (SELECT country, score, ROW_NUMBER() OVER (ORDER BY score DESC) as rank FROM EnvironmentalImpact WHERE year = YEAR(CURRENT_DATE) - 1) AS subquery WHERE rank <= 5;


Question: What is the total number of research grants awarded to faculty members in the College of Education who identify as Indigenous or Native American?

CREATE TABLE edu_grants (grant_id INT, grant_amount DECIMAL(10,2), grant_recipient VARCHAR(50), recipient_identity VARCHAR(50)); INSERT INTO edu_grants (grant_id, grant_amount, grant_recipient, recipient_identity) VALUES (1, 35000.00, 'Prof. Rivera', 'Indigenous'), (2, 45000.00, 'Prof. Thompson', 'Native American'), (3, 55000.00, 'Prof. Wang', 'Asian'), (4, 65000.00, 'Prof. Lopez', 'Hispanic');

SELECT COUNT(*) FROM edu_grants WHERE grant_recipient LIKE '%College of Education%' AND recipient_identity IN ('Indigenous', 'Native American');


Question: What is the average number of crops grown per farm in urban agriculture?

CREATE TABLE urban_farms (id INT, farm_id INT, crop_type VARCHAR(255));

SELECT farm_id, AVG(COUNT(crop_type)) AS average_crops_per_farm FROM urban_farms GROUP BY farm_id;


Question: What is the total assets value per client as of the last day of each quarter?

SELECT client_id, SUM(assets_value) as total_assets_value FROM assets WHERE assets_date IN (SELECT LAST_DAY(date_add(DATE(assets_date), INTERVAL (quarter(assets_date) - 1) * 3 MONTH)) as last_day_of_quarter FROM assets GROUP BY client_id) GROUP BY client_id;


Question: PostgreSQL regression test 'stats_ext': Write the SELECT query (example 527).

SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE mod(a,20) = 1 AND mod(b::int,10) = 1');

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

SELECT count(*) FROM (SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE mod(a,20) = 1 AND mod(b::int,10) = 1')) AS _sub;


Question: Identify factories in Asia with the highest number of labor rights violations.

CREATE TABLE factories (id INT, name VARCHAR(100), country VARCHAR(50), violations INT); INSERT INTO factories (id, name, country, violations) VALUES (1, 'AsiaTech Factory', 'China', 15), (2, 'Bright Future Factory', 'Bangladesh', 20), (3, 'Unity Factory', 'Vietnam', 10);

SELECT name, country, MAX(violations) as max_violations FROM factories WHERE country IN ('China', 'Bangladesh', 'Vietnam') GROUP BY country;


Question: What is the average sales figure for each drug in the oncology department?

CREATE TABLE drugs (id INT, name VARCHAR(50), department VARCHAR(50), sales FLOAT); INSERT INTO drugs (id, name, department, sales) VALUES (1, 'DrugA', 'Oncology', 100000), (2, 'DrugB', 'Oncology', 150000), (3, 'DrugC', 'Cardiology', 120000), (4, 'DrugD', 'Cardiology', 160000);

SELECT department, name, AVG(sales) as avg_sales FROM drugs WHERE department = 'Oncology' GROUP BY department, name;


Question: How many events had an attendance of over 100 in the last quarter?

CREATE TABLE Events (EventID INT, EventDate DATE, EventAttendance INT); INSERT INTO Events (EventID, EventDate, EventAttendance) VALUES (1, '2022-03-12', 120), (2, '2022-04-20', 80), (3, '2022-05-15', 150);

SELECT COUNT(*) FROM Events WHERE EventAttendance > 100 AND EventDate >= DATE_SUB(CURDATE(), INTERVAL 3 MONTH);


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

SELECT * FROM collate_test1 WHERE b COLLATE "C" >= 'bbc';

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

SELECT count(*) FROM (SELECT * FROM collate_test1 WHERE b COLLATE "C" >= 'bbc') AS _sub;


Question: Delete all shipments that were made from the 'Rio de Janeiro' warehouse to 'Brazil' before '2022-02-01'.

CREATE TABLE warehouse (id INT PRIMARY KEY, name VARCHAR(50), city VARCHAR(50));CREATE TABLE carrier (id INT PRIMARY KEY, name VARCHAR(50));CREATE TABLE shipment (id INT PRIMARY KEY, warehouse_id INT, carrier_id INT, pallet_count INT, shipped_date DATE);

DELETE FROM shipment WHERE warehouse_id = (SELECT id FROM warehouse WHERE city = 'Rio de Janeiro') AND (SELECT name FROM carrier WHERE id = shipment.carrier_id) = 'Brazil' AND shipped_date < '2022-02-01';


Question: pgTAP test for Usergroup (assertion 12).

SELECT * FROM check_test(
    isnt_superuser('aoijaoisjfaoidfjaisjdfosjf', 'desc'),
    false,
    'isnt_superuser(nonexistent user, desc)',
    'desc',
    '    User aoijaoisjfaoidfjaisjdfosjf does not exist'
);

Explanation: SQL assertion from pgTAP test suite for Usergroup.


Question: What is the total number of military aircrafts by type, grouped by their manufacturer and maintenance status?

CREATE TABLE Manufacturer (MID INT, Name VARCHAR(50)); INSERT INTO Manufacturer (MID, Name) VALUES (1, 'Lockheed Martin'), (2, 'Boeing'); CREATE TABLE Aircraft (AID INT, Type VARCHAR(50), ManufacturerID INT, MaintenanceStatus VARCHAR(20)); INSERT INTO Aircraft (AID, Type, ManufacturerID, MaintenanceStatus) VALUES (1, 'F-35', 1, 'Inactive'), (2, 'F-15', 1, 'Active'), (3, 'F/A-18', 2, 'Active');

SELECT m.Name, a.MaintenanceStatus, COUNT(a.AID) as Total FROM Aircraft a JOIN Manufacturer m ON a.ManufacturerID = m.MID GROUP BY m.Name, a.MaintenanceStatus;


Question: Generate PostgreSQL SQL for: What is the highest population (2008) created earlier than 1857, and the county was Sinoe?

CREATE TABLE table_name_69 (population__2008_ INTEGER, created VARCHAR, county VARCHAR)

SELECT MAX(population__2008_) FROM table_name_69 WHERE created < 1857 AND county = 'sinoe';


Question: Write the DML statement from PostgreSQL regression test 'foreign_key' (example 4).

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


Question: Generate PostgreSQL SQL for: What is the average number of top-5s for the major with 5 top-10s and fewer than 12 cuts made?

CREATE TABLE table_name_3 (top_5 INTEGER, top_10 VARCHAR, cuts_made VARCHAR)

SELECT AVG(top_5) FROM table_name_3 WHERE top_10 = 5 AND cuts_made < 12;


Question: What is the total number of public buildings in New York and Illinois?

CREATE TABLE public_buildings (name VARCHAR(255), state VARCHAR(255), size DECIMAL(10,2)); INSERT INTO public_buildings (name, state, size) VALUES ('Building1', 'New York', 120000), ('Building2', 'New York', 150000), ('Building3', 'Illinois', 180000);

SELECT SUM(size) FROM public_buildings WHERE state IN ('New York', 'Illinois');


Question: Generate PostgreSQL SQL for: What's the least amount of wins for Germany in the 1999 season having 0 points?

CREATE TABLE table_name_30 (wins INTEGER, seasons VARCHAR, points VARCHAR, country VARCHAR)

SELECT MIN(wins) FROM table_name_30 WHERE points = '0' AND country = 'germany' AND seasons = '1999';


Question: List all military equipment maintenance activities performed on aircrafts in the Asia-Pacific region since 2018.

CREATE TABLE equipment_maintenance (maintenance_id INT, maintenance_date DATE, equipment_type VARCHAR(255), region VARCHAR(255)); INSERT INTO equipment_maintenance (maintenance_id, maintenance_date, equipment_type, region) VALUES (1, '2018-12-31', 'aircraft', 'Asia-Pacific'), (2, '2019-04-04', 'tank', 'Europe'), (3, '2020-06-15', 'aircraft', 'Asia-Pacific');

SELECT * FROM equipment_maintenance WHERE equipment_type = 'aircraft' AND region = 'Asia-Pacific' AND maintenance_date >= '2018-01-01';


Question: What is the average product safety rating for cosmetic products in the French market, and how many products were rated?

CREATE TABLE product_safety_ratings (product_id INT, safety_rating INT, country TEXT);

SELECT AVG(safety_rating) as avg_safety_rating, COUNT(*) as num_products_rated FROM product_safety_ratings WHERE country = 'France';


Question: Generate PostgreSQL SQL for: What is the region for tv uskana?

CREATE TABLE table_name_5 (region VARCHAR, name VARCHAR)

SELECT region FROM table_name_5 WHERE name = 'tv uskana';


Question: Generate PostgreSQL SQL for: Which IHSAA Football Class has a County of 77 sullivan, and a School of union dugger?

CREATE TABLE table_name_14 (ihsaa_football_class VARCHAR, county VARCHAR, school VARCHAR)

SELECT ihsaa_football_class FROM table_name_14 WHERE county = '77 sullivan' AND school = 'union dugger';


Question: Generate PostgreSQL SQL for: What is the national cup statistics when the Championship is 21 app / 6 goals?

CREATE TABLE table_19333752_1 (national_cup VARCHAR, championship VARCHAR)

SELECT national_cup FROM table_19333752_1 WHERE championship = '21 app / 6 goals';


Question: Generate PostgreSQL SQL for: In which competition or tour was nordsjælland the opponent with a hr Ground?

CREATE TABLE table_name_73 (competition_or_tour VARCHAR, ground VARCHAR, opponent VARCHAR)

SELECT competition_or_tour FROM table_name_73 WHERE ground = 'hr' AND opponent = 'nordsjælland';


Question: What is the total number of military equipment pieces owned by the Navy, categorized by type?

CREATE TABLE Equipment (Equipment_Id INT, Equipment_Type VARCHAR(50), Agency VARCHAR(50), Quantity INT); INSERT INTO Equipment (Equipment_Id, Equipment_Type, Agency, Quantity) VALUES (1, 'Aircraft Carrier', 'Navy', 3); INSERT INTO Equipment (Equipment_Id, Equipment_Type, Agency, Quantity) VALUES (2, 'Submarine', 'Navy', 12); INSERT INTO Equipment (Equipment_Id, Equipment_Type, Agency, Quantity) VALUES (3, 'Destroyer', 'Navy', 25);

SELECT Equipment_Type, SUM(Quantity) FROM Equipment WHERE Agency = 'Navy' GROUP BY Equipment_Type;


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

-- drop the trigger, and now we're allowed to attach it again
drop trigger child_row_trig on child;

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


Question: List unique types of 'Emergency Relief' and their corresponding total costs.

CREATE TABLE Emergency_Relief (relief_type VARCHAR(255), cost INT); INSERT INTO Emergency_Relief (relief_type, cost) VALUES ('Food', 20000), ('Shelter', 30000), ('Medical', 15000);

SELECT relief_type, SUM(cost) FROM Emergency_Relief GROUP BY relief_type;


Question: Generate PostgreSQL SQL for: Name the least points for daniël willemsen / kenny van gaalen

CREATE TABLE table_16729457_17 (points INTEGER, driver___passenger VARCHAR)

SELECT MIN(points) FROM table_16729457_17 WHERE driver___passenger = 'Daniël Willemsen / Kenny van Gaalen';


Question: Generate PostgreSQL SQL for: Which date was the show aired on the RTL Televizija network?

CREATE TABLE table_name_35 (date_aired VARCHAR, network VARCHAR)

SELECT date_aired FROM table_name_35 WHERE network = 'rtl televizija';


Question: Write the DML statement from PostgreSQL regression test 'rangetypes' (example 250).

insert into test_range_spgist select int4range(g, g+10) from generate_series(1,2000) g;

Explanation: DML from PostgreSQL core regression test for Rangetypes.


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

select snap from snapshot_test order by nr;

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

SELECT count(*) FROM (select snap from snapshot_test order by nr) AS _sub;


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

INSERT INTO timetzcmp (r_id,a) SELECT 22,count(*) FROM timetztmp WHERE a <= '07:46:45 GMT+4';


Question: PostgreSQL regression test 'multirangetypes': Write the SELECT query (example 35).

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

SELECT count(*) FROM (select '{[a,a]}'::textmultirange) AS _sub;


Question: Generate PostgreSQL SQL for: Who was the away team during the game when the home team was the new zealand breakers?

CREATE TABLE table_name_36 (away_team VARCHAR, home_team VARCHAR)

SELECT away_team FROM table_name_36 WHERE home_team = 'new zealand breakers';


Question: What is the total duration of 'Swimming' workouts for each user in the 'workout_data' table?

CREATE TABLE workout_data (user_id INT, workout_type VARCHAR(20), duration INT); INSERT INTO workout_data (user_id, workout_type, duration) VALUES (4, 'Swimming', 300), (5, 'Swimming', 420), (4, 'Swimming', 240), (5, 'Swimming', 540);

SELECT user_id, SUM(duration) as total_duration FROM workout_data WHERE workout_type = 'Swimming' GROUP BY user_id;


Question: What is the total amount donated by donors with the 'Corporate' type?

CREATE TABLE Donors (donor_id INT PRIMARY KEY, donor_name TEXT, donor_type TEXT, amount INT);

SELECT SUM(amount) FROM Donors WHERE donor_type = 'Corporate';


Question: Write the DML statement from PostgreSQL regression test 'insert' (example 183).

Explanation: DML from PostgreSQL core regression test for Insert.


Question: Generate PostgreSQL SQL for: What is the winning song for the artist with a debut album "the winner"?

CREATE TABLE table_1646960_3 (winning_song VARCHAR, debut_album VARCHAR)

SELECT winning_song FROM table_1646960_3 WHERE debut_album = 'The winner';


Question: How many albums were released in total by Pop artists in 2021?

CREATE TABLE artists (artist_id INT, genre VARCHAR(20)); INSERT INTO artists (artist_id, genre) VALUES (1, 'Latin'), (2, 'Pop'), (3, 'Rock'), (4, 'Jazz'), (5, 'Folk'); CREATE TABLE albums (album_id INT, artist_id INT, release_date DATE); INSERT INTO albums (album_id, artist_id, release_date) VALUES (1, 2, '2021-04-12'), (2, 3, '2020-08-21'), (3, 4, '2019-11-01'), (4, 5, '2018-02-23'), (5, 2, '2021-07-15');

SELECT COUNT(albums.album_id) FROM albums INNER JOIN artists ON albums.artist_id = artists.artist_id WHERE artists.genre = 'Pop' AND albums.release_date BETWEEN '2021-01-01' AND '2021-12-31';


Question: Find the REE production amounts for each country in 2018 and 2020, including the difference.

CREATE TABLE production (country VARCHAR(255), year INT, ree_production INT); INSERT INTO production (country, year, ree_production) VALUES ('China', 2018, 120000), ('China', 2020, 140000), ('USA', 2018, 12000), ('USA', 2020, 15000), ('Australia', 2018, 20000), ('Australia', 2020, 22000);

SELECT a.country, SUM(a.ree_production) AS production_2018, SUM(b.ree_production) AS production_2020, SUM(b.ree_production) - SUM(a.ree_production) AS difference FROM production AS a JOIN production AS b ON a.country = b.country WHERE a.year = 2018 AND b.year = 2020 GROUP BY a.country;


Question: PostgreSQL regression test 'tsearch': Write the SELECT query (example 403).

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

SELECT count(*) FROM (select websearch_to_tsquery('simple', 'a:::b')) AS _sub;


Question: How many employees from underrepresented communities are employed in the 'Mining Operations' department across all sites?

CREATE TABLE Employees (EmployeeID INT, Name VARCHAR(50), Department VARCHAR(50), Community VARCHAR(50), Site VARCHAR(50)); INSERT INTO Employees (EmployeeID, Name, Department, Community, Site) VALUES (1, 'John Doe', 'Mining Operations', 'Underrepresented', 'Site A'); INSERT INTO Employees (EmployeeID, Name, Department, Community, Site) VALUES (2, 'Jane Smith', 'Mining Operations', 'Represented', 'Site B'); INSERT INTO Employees (EmployeeID, Name, Department, Community, Site) VALUES (3, 'Alice Johnson', 'Mining Operations', 'Underrepresented', 'Site A'); INSERT INTO Employees (EmployeeID, Name, Department, Community, Site) VALUES (4, 'Bob Brown', 'Mining Operations', 'Represented', 'Site B');

SELECT COUNT(*) FROM Employees WHERE Department = 'Mining Operations' AND Community = 'Underrepresented';


Question: What is the total number of students who have ever enrolled in a lifelong learning course per instructor?

CREATE TABLE enrollments (student_id INT, instructor_id INT, enrollment_date DATE);

SELECT instructor_id, COUNT(DISTINCT student_id) as total_students FROM enrollments GROUP BY instructor_id;


Question: What is the maximum budget allocated for sign language interpreters in each state?

CREATE TABLE interpreter_budget (state VARCHAR(20), budget INT); INSERT INTO interpreter_budget (state, budget) VALUES ('California', 5000); INSERT INTO interpreter_budget (state, budget) VALUES ('Texas', 7000); INSERT INTO interpreter_budget (state, budget) VALUES ('Florida', 8000);

SELECT state, MAX(budget) FROM interpreter_budget GROUP BY state;


Question: What are the names and types of all containers in the shipping_container table?

CREATE TABLE shipping_container ( id INT PRIMARY KEY, name VARCHAR(255), container_type VARCHAR(255) );

SELECT name, container_type FROM shipping_container;


Question: Add a new regulatory record 'New Regulation C' for country 'ES' in Q1 of 2023

CREATE TABLE countries (id INT, name VARCHAR(10)); INSERT INTO countries (id, name) VALUES (1, 'FR'), (2, 'DE'); CREATE TABLE regulations (id INT, country VARCHAR(10), quarter DATE, description VARCHAR(50));

INSERT INTO countries (id, name) VALUES (3, 'ES'); INSERT INTO regulations (id, country, quarter, description) VALUES (4, 'ES', '2023-01-01', 'New Regulation C');


Question: How many basketball games were played in the 2018-2019 season?

CREATE TABLE basketball_games (game_id INT, season_year INT, home_team VARCHAR(50), away_team VARCHAR(50));

SELECT COUNT(*) FROM basketball_games WHERE season_year = 2019;


Question: Generate PostgreSQL SQL for: who is the the club (city/town) with goals for/against being 14-2

CREATE TABLE table_14181578_1 (club__city_town_ VARCHAR, goals_for_against VARCHAR)

SELECT club__city_town_ FROM table_14181578_1 WHERE goals_for_against = '14-2';


Question: Show a query using PostgreSQL contrib extension 'test_decoding' (example 15).

INSERT INTO toasted_key(toasted_key, toasted_col1) VALUES(repeat('1234567890', 200), repeat('9876543210', 200));

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


Question: Generate PostgreSQL SQL for: Which tyres received 8 points?

CREATE TABLE table_name_56 (tyres VARCHAR, points VARCHAR)

SELECT tyres FROM table_name_56 WHERE points = 8;


Question: How many electric vehicle charging stations are there in Germany and Spain combined?

CREATE TABLE EVStationCounts (id INT, country VARCHAR(20), num_stations INT); INSERT INTO EVStationCounts (id, country, num_stations) VALUES (1, 'Germany', 3000), (2, 'Spain', 1500), (3, 'France', 2000);

SELECT COUNT(*) FROM EVStationCounts WHERE country IN ('Germany', 'Spain');


Question: Generate PostgreSQL SQL for: What is the away team when north melbourne is at home?

CREATE TABLE table_name_99 (away_team VARCHAR, home_team VARCHAR)

SELECT away_team FROM table_name_99 WHERE home_team = 'north melbourne';


Question: What is the minimum depth in the Southern Ocean where phytoplankton are present?

CREATE TABLE phytoplankton_depth (id INT, location VARCHAR(50), depth FLOAT, phytoplankton_present BOOLEAN); INSERT INTO phytoplankton_depth (id, location, depth, phytoplankton_present) VALUES (1, 'Southern Ocean', 50.0, TRUE); INSERT INTO phytoplankton_depth (id, location, depth, phytoplankton_present) VALUES (2, 'Southern Ocean', 75.0, TRUE);

SELECT MIN(depth) FROM phytoplankton_depth WHERE location = 'Southern Ocean' AND phytoplankton_present = TRUE;


Question: What is the minimum quantity of sustainable packaging materials available for orders?

CREATE TABLE SustainablePackaging (id INT, material VARCHAR(50), quantity INT); INSERT INTO SustainablePackaging (id, material, quantity) VALUES (1, 'Recycled Cardboard Boxes', 2000), (2, 'Biodegradable Bags', 5000), (3, 'Plant-Based Packing Peanuts', 3000);

SELECT MIN(quantity) FROM SustainablePackaging;


Question: Generate PostgreSQL SQL for: When was the episode with a 999,000 BARB rating first aired in Denmark?

CREATE TABLE table_26591309_3 (first_broadcast_denmark___dr1__ VARCHAR, official_barb_ratings VARCHAR)

SELECT first_broadcast_denmark___dr1__ FROM table_26591309_3 WHERE official_barb_ratings = '999,000';


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

SELECT '\x123456'::bytea::int2; -- error

SELECT ''::bytea::int4 AS "0";

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

SELECT count(*) FROM (SELECT '\x123456'::bytea::int2; -- error

SELECT ''::bytea::int4 AS "0") AS _sub;


Question: What is the maximum number of events each museum ('museum' table) hosted in a year?

CREATE TABLE museum (id INT, name VARCHAR(50), location VARCHAR(50), year_established INT);CREATE TABLE event (id INT, museum_id INT, name VARCHAR(50), year INT, revenue INT);

SELECT museum.name, MAX(event_year_count) FROM (SELECT museum_id, COUNT(*) AS event_year_count FROM event GROUP BY museum_id, year) AS subquery JOIN museum ON museum.id = subquery.museum_id GROUP BY museum.id;


Question: PostgreSQL regression test 'constraints': Write the SELECT query (example 200).

SELECT conname, conrelid::regclass FROM pg_constraint
  WHERE conname LIKE 'parted_uniq%' ORDER BY conname;

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

SELECT count(*) FROM (SELECT conname, conrelid::regclass FROM pg_constraint
  WHERE conname LIKE 'parted_uniq%' ORDER BY conname) AS _sub;


Question: Find the average number of tickets sold and total number of home games played by the 'Dallas Mavericks' in the 'Southwest' division for the year 2020. Assume the 'games' table has columns 'team_name', 'sale_year', 'num_tickets_sold', 'is_home_game'.

CREATE TABLE TEAMS (team_name VARCHAR(50), division VARCHAR(50)); INSERT INTO TEAMS (team_name, division) VALUES ('Dallas Mavericks', 'Southwest'); CREATE TABLE games (team_name VARCHAR(50), sale_year INT, num_tickets_sold INT, is_home_game BOOLEAN); INSERT INTO games (team_name, sale_year, num_tickets_sold, is_home_game) VALUES ('Dallas Mavericks', 2020, 18000, TRUE);

SELECT AVG(num_tickets_sold), COUNT(*) FROM games WHERE team_name = 'Dallas Mavericks' AND sale_year = 2020 AND is_home_game = TRUE AND division = (SELECT division FROM TEAMS WHERE team_name = 'Dallas Mavericks');


Question: List the total number of employees per job category and the average salary for each category in the HR database.

CREATE TABLE employees (id INT, name TEXT, job_category TEXT, salary INT); INSERT INTO employees (id, name, job_category, salary) VALUES (1, 'John Doe', 'Engineering', 70000), (2, 'Jane Smith', 'Management', 90000), (3, 'Bob Johnson', 'Assembly', 50000), (4, 'Alice Williams', 'Engineering', 75000), (5, 'Charlie Brown', 'Assembly', 55000);

SELECT job_category, COUNT(*) as total_employees, AVG(salary) as avg_salary FROM employees GROUP BY job_category;


Question: What was the total expenditure of eco-tourists in Costa Rica and Belize in 2020?

CREATE TABLE tourism_stats (country VARCHAR(255), year INT, tourism_type VARCHAR(255), expenditure DECIMAL(10, 2)); INSERT INTO tourism_stats (country, year, tourism_type, expenditure) VALUES ('Costa Rica', 2020, 'Eco-tourism', 500000), ('Costa Rica', 2020, 'Eco-tourism', 600000), ('Belize', 2020, 'Eco-tourism', 400000), ('Belize', 2020, 'Eco-tourism', 450000);

SELECT SUM(expenditure) AS total_expenditure FROM tourism_stats WHERE country IN ('Costa Rica', 'Belize') AND tourism_type = 'Eco-tourism' AND year = 2020;


Question: Generate PostgreSQL SQL for: On what date was the game in Week 9 played?

CREATE TABLE table_name_70 (date VARCHAR, week VARCHAR)

SELECT date FROM table_name_70 WHERE week = 9;


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

CREATE FUNCTION ltree_picksplit(internal, internal)
RETURNS internal as 'MODULE_PATHNAME' LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;

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


Question: PostgreSQL Rules: show example 61.

CREATE VIEW phone_number AS SELECT person, phone FROM phone_data WHERE phone NOT LIKE '412%';

Explanation: Example from PostgreSQL documentation on Rules.


Question: List all customers with fraudulent transactions in Q2 2022.

CREATE TABLE customers (customer_id INT, customer_name TEXT); CREATE TABLE transactions (transaction_id INT, customer_id INT, transaction_date DATE, is_fraudulent BOOLEAN);

SELECT c.customer_id, c.customer_name FROM customers c JOIN transactions t ON c.customer_id = t.customer_id WHERE t.transaction_date BETWEEN '2022-04-01' AND '2022-06-30' AND t.is_fraudulent = TRUE;


Question: Generate PostgreSQL SQL for: What was the location of the Havaianas Beachley Classic, held in Australia?

CREATE TABLE table_name_99 (location VARCHAR, country VARCHAR, event VARCHAR)

SELECT location FROM table_name_99 WHERE country = 'australia' AND event = 'havaianas beachley classic';


Question: Generate PostgreSQL SQL for: What is the sum of the draws with less than 2284 against, 8 losses, and more than 10 wins?

CREATE TABLE table_name_61 (draws INTEGER, wins VARCHAR, against VARCHAR, losses VARCHAR)

SELECT SUM(draws) FROM table_name_61 WHERE against < 2284 AND losses = 8 AND wins > 10;


Question: What's the total donation amount given to the Orphan Support program in Afghanistan and the Refugee Assistance program in Pakistan?

CREATE TABLE donations (id INT, donor_id INT, program_id INT, amount INT); CREATE TABLE donors (id INT, name TEXT, age INT); CREATE TABLE programs (id INT, name TEXT, location TEXT); INSERT INTO donations VALUES (1, 1, 1, 500), (2, 2, 2, 300), (3, 3, 1, 700), (4, 4, 2, 600); INSERT INTO donors VALUES (1, 'Abdul Rauf', 35), (2, 'Siddique Khan', 40), (3, 'Mohammad Hashim', 45), (4, 'Hamid Karzai', 50); INSERT INTO programs VALUES (1, 'Orphan Support', 'Afghanistan'), (2, 'Refugee Assistance', 'Pakistan');

SELECT SUM(d.amount) FROM donations d INNER JOIN programs p ON d.program_id = p.id WHERE p.name IN ('Orphan Support', 'Refugee Assistance') AND p.location IN ('Afghanistan', 'Pakistan');


Question: Generate PostgreSQL SQL for: Which Draws have Losses smaller than 16, and a Team of university, and Wins larger than 0?

CREATE TABLE table_name_38 (draws INTEGER, wins VARCHAR, losses VARCHAR, team VARCHAR)

SELECT AVG(draws) FROM table_name_38 WHERE losses < 16 AND team = 'university' AND wins > 0;


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

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


Question: List all startups founded by African entrepreneurs in the 'Fintech' industry

CREATE TABLE startups(id INT, name TEXT, founded_year INT, founder_ethnicity TEXT, industry TEXT); INSERT INTO startups (id, name, founded_year, founder_ethnicity, industry) VALUES (1, 'Delta Enterprises', 2020, 'Latinx', 'Retail'); INSERT INTO startups (id, name, founded_year, founder_ethnicity, industry) VALUES (2, 'Epsilon Co', 2018, 'Asian', 'Education'); INSERT INTO startups (id, name, founded_year, founder_ethnicity, industry) VALUES (3, 'Theta Startup', 2019, 'African', 'Fintech');

SELECT * FROM startups WHERE founder_ethnicity = 'African' AND industry = 'Fintech';


Question: What is the total investment in social impact bonds in the Caribbean?

CREATE TABLE social_impact_bonds (id INT, region VARCHAR(50), investment FLOAT); INSERT INTO social_impact_bonds (id, region, investment) VALUES (1, 'Caribbean', 250000); INSERT INTO social_impact_bonds (id, region, investment) VALUES (2, 'Caribbean', 300000);

SELECT SUM(investment) FROM social_impact_bonds WHERE region = 'Caribbean';


Question: What is the total number of patients who received therapy in South Africa?

CREATE TABLE patients (id INT, country VARCHAR(255), therapy_received BOOLEAN); INSERT INTO patients (id, country, therapy_received) VALUES (1, 'South Africa', true), (2, 'South Africa', false);

SELECT COUNT(*) FROM patients WHERE country = 'South Africa' AND therapy_received = true;


Question: Delete a network usage record from the network_usage table

CREATE TABLE network_usage (usage_id INT, subscriber_id INT, usage_date DATE, usage_type VARCHAR(50), usage_duration INT);

DELETE FROM network_usage WHERE usage_id = 3001;


Question: Generate PostgreSQL SQL for: What is the report for 10 october?

CREATE TABLE table_name_13 (report VARCHAR, date VARCHAR)

SELECT report FROM table_name_13 WHERE date = '10 october';


Question: What is the total number of properties in the city of Seoul, South Korea that have green roofs?

CREATE TABLE seoul_real_estate(id INT, city VARCHAR(50), green_roof BOOLEAN); INSERT INTO seoul_real_estate VALUES (1, 'Seoul', true);

SELECT COUNT(*) FROM seoul_real_estate WHERE city = 'Seoul' AND green_roof = true;


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

SELECT i.f1, i.f1 * int4 '2' AS x FROM INT4_TBL i
WHERE abs(f1) < 1073741824;

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

SELECT count(*) FROM (SELECT i.f1, i.f1 * int4 '2' AS x FROM INT4_TBL i
WHERE abs(f1) < 1073741824) AS _sub;


Question: Generate PostgreSQL SQL for: Who did the team play on january 9?

CREATE TABLE table_27733258_8 (team VARCHAR, date VARCHAR)

SELECT team FROM table_27733258_8 WHERE date = 'January 9';


Question: Display the percentage of patients who have experienced cultural competency in healthcare services, by their ethnicity, in descending order.

CREATE TABLE patient (patient_id INT, ethnicity VARCHAR(255), experienced_cultural_competency BOOLEAN); INSERT INTO patient (patient_id, ethnicity, experienced_cultural_competency) VALUES (1, 'Hispanic', TRUE), (2, 'Asian', FALSE), (3, 'White', TRUE), (4, 'Black', TRUE);

SELECT ethnicity, 100.0 * SUM(experienced_cultural_competency) / COUNT(*) as percentage FROM patient GROUP BY ethnicity ORDER BY percentage DESC;


Question: What is the number of job applications received, by job title, in the last month?

CREATE TABLE job_applications (application_id INT, name TEXT, job_title TEXT, application_date DATE); INSERT INTO job_applications (application_id, name, job_title, application_date) VALUES (1, 'Alice', 'HR Manager', '2022-01-01'), (2, 'Bob', 'Software Engineer', '2022-01-05'), (3, 'Charlie', 'Software Engineer', '2022-01-10'), (4, 'Dave', 'Sales Manager', '2022-01-15'), (5, 'Eve', 'Software Engineer', '2022-01-20');

SELECT job_title, COUNT(*) AS num_applications FROM job_applications WHERE application_date >= DATEADD(month, -1, GETDATE()) GROUP BY job_title;


Question: Generate PostgreSQL SQL for: For Pigeon Creek what is the per capita income?

CREATE TABLE table_1840495_2 (per_capita_income VARCHAR, place VARCHAR)

SELECT per_capita_income FROM table_1840495_2 WHERE place = 'Pigeon Creek';


Question: Generate PostgreSQL SQL for: What is the score on April 5?

CREATE TABLE table_name_64 (score VARCHAR, date VARCHAR)

SELECT score FROM table_name_64 WHERE date = 'april 5';


Question: pgTAP test for Inheritance (assertion 71).

SELECT * FROM check_test(
    isnt_ancestor_of( 'hide', 'h_parent', 'hide', 'nope', 2 ),
    true,
    'isnt_ancestor_of(psch, ptab, csch, nope, 2)',
    'Table hide.h_parent should not be ancestor 2 for hide.nope',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Inheritance.


Question: Generate PostgreSQL SQL for: Which player's runs are 270?

CREATE TABLE table_name_43 (player VARCHAR, runs VARCHAR)

SELECT player FROM table_name_43 WHERE runs = '270';


Question: Generate PostgreSQL SQL for: Who tied with 8 losses and 50% wins?

CREATE TABLE table_name_19 (tied VARCHAR, losses VARCHAR, win__percentage VARCHAR)

SELECT tied FROM table_name_19 WHERE losses = '8' AND win__percentage = '50%';


Question: What is the average number of autonomous taxis in the taxis table for each city?

CREATE TABLE taxis (id INT, city TEXT, vehicle_type TEXT, fuel_type TEXT, total_taxis INT); INSERT INTO taxis (id, city, vehicle_type, fuel_type, total_taxis) VALUES (1, 'San Francisco', 'Taxi', 'Autonomous', 100), (2, 'New York', 'Taxi', 'Gasoline', 800), (3, 'Los Angeles', 'Taxi', 'Autonomous', 150);

SELECT city, AVG(total_taxis) as avg_autonomous_taxis FROM taxis WHERE vehicle_type = 'Taxi' AND fuel_type = 'Autonomous' GROUP BY city;


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

INSERT INTO num_exp_div VALUES (0,5,'0');

Explanation: DML from PostgreSQL core regression test for Numeric.


Question: Generate PostgreSQL SQL for: What candidate is in Louisiana 6?

CREATE TABLE table_1342331_18 (candidates VARCHAR, district VARCHAR)

SELECT candidates FROM table_1342331_18 WHERE district = 'Louisiana 6';


Question: Find players who have the same email address in 'esports_players' table.

CREATE TABLE esports_players (PlayerID INT, Name VARCHAR(20), Email VARCHAR(30)); INSERT INTO esports_players (PlayerID, Name, Email) VALUES (1, 'John Doe', 'johndoe@example.com'); INSERT INTO esports_players (PlayerID, Name, Email) VALUES (2, 'Jane Doe', 'johndoe@example.com');

SELECT PlayerID, Email FROM esports_players WHERE Email IN (SELECT Email FROM esports_players GROUP BY Email HAVING COUNT(*) > 1);


Question: List all students who have never taken a mental health assessment, along with their IDs, from the 'student_mental_health' table.

CREATE TABLE student_mental_health (student_id INT, assessment_date DATE, assessment_score INT);

SELECT student_id FROM student_mental_health WHERE student_id NOT IN (SELECT student_id FROM student_mental_health WHERE assessment_date IS NOT NULL);


Question: Generate PostgreSQL SQL for: What is the maximum population size in the town of Stanthorpe?

CREATE TABLE table_12584173_1 (population__stanthorpe_ INTEGER)

SELECT MAX(population__stanthorpe_) FROM table_12584173_1;


Question: Identify menu items with a price above the 75th percentile of their category's prices.

CREATE TABLE Menu (MenuID INT, MenuItem VARCHAR(50), Category VARCHAR(50), Price DECIMAL(5,2));

SELECT MenuItem, Category, Price FROM (SELECT MenuItem, Category, Price, NTILE(4) OVER (PARTITION BY Category ORDER BY Price DESC) AS PriceQuantile FROM Menu) AS Subquery WHERE PriceQuantile = 1;


Question: Generate PostgreSQL SQL for: What position did the player have who was from the college of california?

CREATE TABLE table_name_55 (position VARCHAR, college VARCHAR)

SELECT position FROM table_name_55 WHERE college = 'california';


Question: How many articles were published in Spanish by the 'El País' newspaper in 2021?

CREATE TABLE Articles (id INT, publication_date DATE, language VARCHAR(255), newspaper VARCHAR(255), word_count INT); INSERT INTO Articles (id, publication_date, language, newspaper, word_count) VALUES (1, '2021-01-01', 'Spanish', 'El País', 800), (2, '2021-02-02', 'English', 'The New York Times', 500), (3, '2021-03-03', 'Spanish', 'El País', 600), (4, '2021-04-04', 'French', 'Le Monde', 700);

SELECT COUNT(*) FROM Articles WHERE language = 'Spanish' AND newspaper = 'El País' AND YEAR(publication_date) = 2021;


Question: pgTAP test for Pktap (assertion 11).

SELECT * FROM check_test(
    has_pk( 'hide', 'hidesometab'::name ),
    true,
    'has_pk( hideschema, hidetable )',
    'Table hide.hidesometab should have a primary key',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Pktap.


Question: PostgreSQL regression test 'create_function_sql': Write the SELECT query (example 65).

Explanation: Regression test for Create Function Sql in PostgreSQL core test suite.

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


Question: Delete the music track 'Eternal Love' by 'Sarah Brightman'.

CREATE TABLE music_track (track_id INT, title VARCHAR(100), artist VARCHAR(100)); INSERT INTO music_track (track_id, title, artist) VALUES (1, 'Eternal Love', 'Sarah Brightman');

DELETE FROM music_track WHERE title = 'Eternal Love' AND artist = 'Sarah Brightman';


Question: What is the total waste generated by each department?

CREATE TABLE factories (factory_id INT, department VARCHAR(20), waste_generated_kg INT); INSERT INTO factories VALUES (1, 'textiles', 500), (2, 'metalwork', 300), (3, 'textiles', 700), (4, 'electronics', 400), (5, 'textiles', 600);

SELECT department, SUM(waste_generated_kg) FROM factories GROUP BY department;


Question: Provide a list of intelligence operations that took place in Europe in the year 2019

CREATE TABLE intelligence_operations (id INT, name TEXT, location TEXT, year INT); INSERT INTO intelligence_operations (id, name, location, year) VALUES (1, 'Operation Red Falcon', 'Germany', 2019), (2, 'Operation Night Hawk', 'France', 2018), (3, 'Operation Black Swan', 'UK', 2019);

SELECT name FROM intelligence_operations WHERE location IN ('Germany', 'France', 'UK') AND year = 2019;


Question: Insert a new record in the athlete table with the following data: id=10, name='Alex Rodriguez', team='New York Yankees'.

CREATE TABLE athlete (id INT, name VARCHAR(50), team VARCHAR(50));

INSERT INTO athlete (id, name, team) VALUES (10, 'Alex Rodriguez', 'New York Yankees');


Question: What are the total expenses for SpaceX and Blue Origin for their launch vehicles?

CREATE TABLE spacex_expenses (company VARCHAR(20), launch_vehicle VARCHAR(30), expenses INT); INSERT INTO spacex_expenses (company, launch_vehicle, expenses) VALUES ('SpaceX', 'Falcon 1', 50000000), ('SpaceX', 'Falcon 9', 60000000), ('SpaceX', 'Falcon Heavy', 90000000); CREATE TABLE blue_origin_expenses (company VARCHAR(20), launch_vehicle VARCHAR(30), expenses INT); INSERT INTO blue_origin_expenses (company, launch_vehicle, expenses) VALUES ('Blue Origin', 'New Shepard', 100000000), ('Blue Origin', 'New Glenn', 150000000);

SELECT SUM(expenses) FROM spacex_expenses JOIN blue_origin_expenses ON FALSE;


Question: What is the minimum age for health insurance policyholders in Florida?

CREATE TABLE policyholders (id INT, state VARCHAR(2), policy_type VARCHAR(20), age INT); INSERT INTO policyholders (id, state, policy_type, age) VALUES (1, 'FL', 'Life', 25), (2, 'FL', 'Health', 30), (3, 'FL', 'Health', 40);

SELECT MIN(age) FROM policyholders WHERE state = 'FL' AND policy_type = 'Health';