Question: Calculate the revenue of non-toxic haircare products, excluding those sold in the South region

CREATE TABLE sales (product_type VARCHAR(20), region VARCHAR(10), revenue NUMERIC(10,2)); INSERT INTO sales (product_type, region, revenue) VALUES ('shampoo', 'East', 800), ('conditioner', 'East', 900), ('hair serum', 'West', 700), ('hair spray', 'North', 600), ('hair gel', 'South', 500), ('shampoo', 'South', 400), ('conditioner', 'North', 300); CREATE TABLE products (product_type VARCHAR(20), non_toxic BOOLEAN); INSERT INTO products (product_type, non_toxic) VALUES ('shampoo', TRUE), ('conditioner', TRUE), ('hair serum', TRUE), ('hair spray', FALSE), ('hair gel', FALSE);

SELECT SUM(revenue) FROM sales INNER JOIN products ON sales.product_type = products.product_type WHERE products.non_toxic = TRUE AND sales.region != 'South' AND sales.product_type = 'haircare';


Question: Generate PostgreSQL SQL for: What was the share when the audience was 3.944.000?

CREATE TABLE table_name_82 (share VARCHAR, audience VARCHAR)

SELECT share FROM table_name_82 WHERE audience = '3.944.000';


Question: Generate PostgreSQL SQL for: What is No. 3, when No. 7 is Abigail, and when No. 4 is Ava?

CREATE TABLE table_name_79 (no_3 VARCHAR, no_7 VARCHAR, no_4 VARCHAR)

SELECT no_3 FROM table_name_79 WHERE no_7 = 'abigail' AND no_4 = 'ava';


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

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

SELECT count(*) FROM (select jsonb_to_tsvector('[]'::jsonb, '"all"')) AS _sub;


Question: Generate PostgreSQL SQL for: If the time on Wed aug 25 was 20' 09.25 112.324mph, what was the time on sat Aug 28?

CREATE TABLE table_26986076_1 (sat_28_aug VARCHAR, wed_25_aug VARCHAR)


Question: Generate PostgreSQL SQL for: What is the number of generators where the power capicity is 78.7?

CREATE TABLE table_11456251_5 (number_of_generators VARCHAR, power_capacity__gw_ VARCHAR)

SELECT COUNT(number_of_generators) FROM table_11456251_5 WHERE power_capacity__gw_ = '78.7';


Question: Write the DDL statement from PostgreSQL regression test 'subselect' (example 195).

create operator = (procedure=bogus_int8_text_eq, leftarg=int8, rightarg=text);

Explanation: DDL from PostgreSQL core regression test for Subselect.


Question: Generate PostgreSQL SQL for: What is the result of the game when the competition was a friendly match, and the Score was 1 – 1?

CREATE TABLE table_name_65 (result VARCHAR, competition VARCHAR, score VARCHAR)

SELECT result FROM table_name_65 WHERE competition = 'friendly match' AND score = '1 – 1';


Question: Generate PostgreSQL SQL for: What was the score of the game which featured the gold coast blaze as the away team and the adelaide 36ers as the home team?

CREATE TABLE table_name_16 (score VARCHAR, away_team VARCHAR, home_team VARCHAR)

SELECT score FROM table_name_16 WHERE away_team = 'gold coast blaze' AND home_team = 'adelaide 36ers';


Question: Which product category had the lowest total revenue in Massachusetts in 2021?

CREATE TABLE mass_sales (product VARCHAR(20), revenue DECIMAL(10,2), state VARCHAR(20), year INT); INSERT INTO mass_sales (product, revenue, state, year) VALUES ('Flower', 70000, 'Massachusetts', 2021), ('Concentrate', 60000, 'Massachusetts', 2021), ('Edibles', 50000, 'Massachusetts', 2021);

SELECT product, MIN(revenue) as min_revenue FROM mass_sales WHERE state = 'Massachusetts' AND year = 2021 GROUP BY product;


Question: What is the average safety rating of electric vehicles, compared to non-electric vehicles, per manufacturer?

CREATE TABLE VehicleSafetyRatings (id INT, make VARCHAR(20), model VARCHAR(20), is_electric BOOLEAN, safety_rating FLOAT); INSERT INTO VehicleSafetyRatings (id, make, model, is_electric, safety_rating) VALUES (1, 'Tesla', 'Model S', true, 5.2), (2, 'Tesla', 'Model 3', true, 5.4), (3, 'Volvo', 'XC60', false, 5.1), (4, 'Volvo', 'S60', false, 4.9), (5, 'BMW', 'X5', false, 4.8);

SELECT make, AVG(safety_rating) FILTER (WHERE is_electric = true) AS avg_electric_safety_rating, AVG(safety_rating) FILTER (WHERE is_electric = false) AS avg_non_electric_safety_rating  FROM VehicleSafetyRatings GROUP BY make;


Question: Generate PostgreSQL SQL for: Name the mosst finals apps

CREATE TABLE table_21220720_1 (finals_apps INTEGER)

SELECT MAX(finals_apps) FROM table_21220720_1;


Question: Write the DDL statement from PostgreSQL regression test 'generated_stored' (example 17).

CREATE TABLE gtest_err_5b (a int PRIMARY KEY, b int GENERATED ALWAYS AS identity GENERATED ALWAYS AS (a * 2) STORED);

Explanation: DDL from PostgreSQL core regression test for Generated Stored.


Question: How many agricultural extension officers were trained in Kenya in 2019?

CREATE TABLE officer_training (id INT, officer_id INT, country VARCHAR(50), training_year INT, trained BOOLEAN); INSERT INTO officer_training (id, officer_id, country, training_year, trained) VALUES (1, 4001, 'Kenya', 2019, true), (2, 4002, 'Kenya', 2018, true);

SELECT COUNT(*) FROM officer_training WHERE country = 'Kenya' AND training_year = 2019 AND trained = true;


Question: What are the names of the cybersecurity strategies implemented before 2015?

CREATE TABLE Cybersecurity_Strategies (Year INT, Strategy VARCHAR(255)); INSERT INTO Cybersecurity_Strategies (Year, Strategy) VALUES (2005, 'Cybersecurity Initiative'), (2010, 'Comprehensive National Cybersecurity Initiative'), (2015, 'Cybersecurity National Action Plan');

SELECT Strategy FROM Cybersecurity_Strategies WHERE Year < 2015;


Question: Generate PostgreSQL SQL for: What is the second leg that has kk bosna?

CREATE TABLE table_name_49 (team__number1 VARCHAR)

SELECT 2 AS nd_leg FROM table_name_49 WHERE team__number1 = 'kk bosna';


Question: Which union activities in Washington have the highest average duration?

CREATE TABLE UnionActivities (id INT, union_member_id INT, activity_type VARCHAR, duration INT); CREATE TABLE UnionMembers (id INT, name VARCHAR, state VARCHAR, union_member BOOLEAN);

SELECT ua.activity_type, AVG(ua.duration) as avg_duration FROM UnionActivities ua JOIN UnionMembers um ON ua.union_member_id = um.id WHERE um.state = 'Washington' GROUP BY ua.activity_type ORDER BY avg_duration DESC LIMIT 1;


Question: What is the number of cultural competency trainings conducted in California and New York?

CREATE TABLE cultural_competency_trainings (training_id INT, location VARCHAR(50), date DATE); INSERT INTO cultural_competency_trainings (training_id, location, date) VALUES (1, 'Los Angeles, CA', '2022-01-01'), (2, 'San Diego, CA', '2022-02-01'), (3, 'San Francisco, CA', '2022-03-01'), (4, 'New York, NY', '2022-02-15');

SELECT COUNT(*) FROM cultural_competency_trainings WHERE location IN ('CA', 'NY');


Question: Find the bioprocess engineering projects that have a budget between $4M and $6M.

CREATE TABLE projects (name TEXT, budget FLOAT); INSERT INTO projects (name, budget) VALUES ('ProjectA', 4500000), ('ProjectB', 5500000), ('ProjectC', 3500000);

SELECT name FROM projects WHERE budget BETWEEN 4000000 AND 6000000;


Question: Generate PostgreSQL SQL for: What NHL team has a player in the position of Left Wing that came from the Toronto Marlboros (omjhl)?

CREATE TABLE table_name_81 (nhl_team VARCHAR, position VARCHAR, college_junior_club_team VARCHAR)

SELECT nhl_team FROM table_name_81 WHERE position = 'left wing' AND college_junior_club_team = 'toronto marlboros (omjhl)';


Question: What is the maximum number of years a traditional craft has been preserved in each province of China?

CREATE TABLE provinces (id INT, name TEXT); INSERT INTO provinces (id, name) VALUES (1, 'Yunnan'), (2, 'Guangdong'), (3, 'Sichuan'); CREATE TABLE crafts (id INT, province_id INT, name TEXT, year_preserved INT); INSERT INTO crafts (id, province_id, name, year_preserved) VALUES (1, 1, 'Batik', 800), (2, 1, 'Embroidery', 1000), (3, 2, 'Pottery', 700), (4, 2, 'Woodcarving', 500), (5, 3, 'Papermaking', 1200), (6, 3, 'Bamboo weaving', 900);

SELECT p.name, MAX(c.year_preserved) FROM provinces p JOIN crafts c ON p.id = c.province_id GROUP BY p.id;


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

Explanation: DDL from PostgreSQL core regression test for Rowsecurity.


Question: What is the maximum fairness score for each AI algorithm in the 'creative_ai' database?

CREATE TABLE creative_ai.ai_algorithms (ai_algorithm_id INT PRIMARY KEY, ai_algorithm VARCHAR(255), fairness_score FLOAT); INSERT INTO creative_ai.ai_algorithms (ai_algorithm_id, ai_algorithm, fairness_score) VALUES (1, 'Generative Adversarial Networks', 0.75), (2, 'Transformers', 0.85), (3, 'Deep Reinforcement Learning', 0.65);

SELECT ai_algorithm, MAX(fairness_score) as max_fairness_score FROM creative_ai.ai_algorithms GROUP BY ai_algorithm;


Question: Generate PostgreSQL SQL for: Which term had a Democratic representative from district 7?

CREATE TABLE table_name_22 (term VARCHAR, district VARCHAR, party VARCHAR)

SELECT term FROM table_name_22 WHERE district = '7' AND party = 'democratic';


Question: What is the number of concerts for artists who identify as female and are from Africa in 2025?

CREATE TABLE concert_events (event_id INT, artist_id INT, event_date DATE, event_location VARCHAR(255), attendance INT, revenue DECIMAL(10,2), country VARCHAR(50)); INSERT INTO concert_events (event_id, artist_id, event_date, event_location, attendance, revenue, country) VALUES (1, 1, '2025-01-01', 'NYC', 15000, 500000.00, 'South Africa'); CREATE TABLE artist_demographics (artist_id INT, artist_name VARCHAR(255), gender VARCHAR(50), ethnicity VARCHAR(50), country VARCHAR(50)); INSERT INTO artist_demographics (artist_id, artist_name, gender, ethnicity, country) VALUES (1, 'Amina Mohamed', 'female', 'African', 'South Africa');

SELECT COUNT(*) FROM concert_events ce JOIN artist_demographics ad ON ce.artist_id = ad.artist_id WHERE ad.gender = 'female' AND ad.ethnicity = 'African' AND ce.event_date BETWEEN '2025-01-01' AND '2025-12-31';


Question: Generate PostgreSQL SQL for: What is the total number of rounds of the player from lehigh college with an overall less than 152?

CREATE TABLE table_name_39 (round VARCHAR, college VARCHAR, overall VARCHAR)

SELECT COUNT(round) FROM table_name_39 WHERE college = 'lehigh' AND overall < 152;


Question: What's the total value of all digital assets on the Solana network?

CREATE TABLE solana_assets (id INT PRIMARY KEY, name VARCHAR(255), network VARCHAR(255), value DECIMAL(10, 2)); INSERT INTO solana_assets (id, name, network, value) VALUES (1, 'Asset1', 'Solana', 100), (2, 'Asset2', 'Solana', 150);

SELECT SUM(value) FROM solana_assets WHERE network = 'Solana';


Question: List all customer complaints related to mobile services in the Asia region

CREATE TABLE asia_complaints (complaint_id INT, subscriber_type VARCHAR(10), country VARCHAR(10), complaint VARCHAR(50));

SELECT complaint FROM asia_complaints WHERE subscriber_type = 'mobile' AND country IN (SELECT country FROM country WHERE region = 'Asia');


Question: What are the account types for the accounts involved in Fraud?

CREATE TABLE Accounts (AccountId INT, AccountType VARCHAR(20)); INSERT INTO Accounts (AccountId, AccountType) VALUES (1, 'Checking'), (2, 'Savings'); CREATE TABLE Fraud (FraudId INT, AccountId INT); INSERT INTO Fraud (FraudId, AccountId) VALUES (1, 1), (2, 3);

SELECT A.AccountType FROM Accounts A JOIN Fraud F ON A.AccountId = F.AccountId;


Question: Generate PostgreSQL SQL for: When 5.5 is the l-band what is the v-band?

CREATE TABLE table_186468_1 (v_band VARCHAR, k_band VARCHAR)

SELECT v_band FROM table_186468_1 WHERE k_band = '5.5';


Question: What is the total number of AI safety incidents reported in the European Union in Q2 2022?

CREATE TABLE safety_incidents (incident_id INT, incident_date DATE, country TEXT); INSERT INTO safety_incidents (incident_id, incident_date, country) VALUES (1, '2022-04-01', 'Germany'), (2, '2022-05-15', 'France'), (3, '2022-06-27', 'Italy');

SELECT COUNT(*) as num_incidents FROM safety_incidents WHERE country IN ('Germany', 'France', 'Italy') AND incident_date BETWEEN '2022-04-01' AND '2022-06-30';


Question: Generate PostgreSQL SQL for: Show the names of phones that have total number of stocks bigger than 2000, in descending order of the total number of stocks.

CREATE TABLE phone_market (Phone_ID VARCHAR, Num_of_stock INTEGER); CREATE TABLE phone (Name VARCHAR, Phone_ID VARCHAR)

SELECT T2.Name FROM phone_market AS T1 JOIN phone AS T2 ON T1.Phone_ID = T2.Phone_ID GROUP BY T2.Name HAVING SUM(T1.Num_of_stock) >= 2000 ORDER BY SUM(T1.Num_of_stock) DESC;


Question: Create a table named 'veteran_employment' to store veteran employment statistics

CREATE TABLE veteran_employment (id INT PRIMARY KEY, state VARCHAR(2), year INT, total_veterans INT, employed_veterans INT, unemployed_veterans INT);


Question: Write the DDL statement from PostgreSQL regression test 'lock' (example 7).

CREATE VIEW lock_view3 AS SELECT * from lock_view2;

Explanation: DDL from PostgreSQL core regression test for Lock.


Question: What is the average total funding for startups founded by underrepresented minorities in the Tech sector?

CREATE TABLE startups(id INT, name TEXT, industry TEXT, total_funding FLOAT, founder TEXT); INSERT INTO startups VALUES(1, 'StartupA', 'Tech', 15000000, 'Asian'); INSERT INTO startups VALUES(2, 'StartupB', 'Tech', 20000000, 'White'); INSERT INTO startups VALUES(3, 'StartupC', 'Healthcare', 12000000, 'Hispanic'); INSERT INTO startups VALUES(4, 'StartupD', 'Finance', 30000000, 'Black'); INSERT INTO startups VALUES(5, 'StartupE', 'Tech', 8000000, 'Underrepresented Minority');

SELECT AVG(total_funding) FROM startups WHERE industry = 'Tech' AND founder IN ('Underrepresented Minority', 'African American', 'Hispanic', 'Native American');


Question: What is the average GPA of graduate students in each department?

CREATE TABLE graduate_students (student_id INT, name TEXT, gpa DECIMAL(3,2), department TEXT);

SELECT gs.department, AVG(gs.gpa) FROM graduate_students gs GROUP BY gs.department;


Question: Add a new column 'country' to the 'member_demographics' table

CREATE TABLE member_demographics (member_id INT, age INT, gender VARCHAR(10), city VARCHAR(50), state VARCHAR(20));

ALTER TABLE member_demographics ADD country VARCHAR(50);


Question: Generate PostgreSQL SQL for: What is the Date of the game where the Cavaliers have a Record of 15-27?

CREATE TABLE table_name_57 (date VARCHAR, record VARCHAR)

SELECT date FROM table_name_57 WHERE record = '15-27';


Question: Generate PostgreSQL SQL for: when is the opponent lyoto machida?

CREATE TABLE table_name_94 (date VARCHAR, opponent VARCHAR)

SELECT date FROM table_name_94 WHERE opponent = 'lyoto machida';


Question: How many players have played the game 'Puzzle Pioneers' and achieved a score between 500 and 1500?

CREATE TABLE Puzzle_Pioneers (player_id INT, player_name VARCHAR(50), score INT); INSERT INTO Puzzle_Pioneers (player_id, player_name, score) VALUES (1, 'Alex Brown', 700), (2, 'Bella Johnson', 1600), (3, 'Charlie Lee', 400);

SELECT COUNT(DISTINCT player_id) FROM Puzzle_Pioneers WHERE score BETWEEN 500 AND 1500;


Question: Generate PostgreSQL SQL for: What is the sum of Total, when Nation is West Germany, and when Gold is greater than 2?

CREATE TABLE table_name_45 (total INTEGER, nation VARCHAR, gold VARCHAR)

SELECT SUM(total) FROM table_name_45 WHERE nation = 'west germany' AND gold > 2;


Question: Write the DDL statement from PostgreSQL regression test 'jsonb' (example 177).

CREATE TEMP TABLE foo (serial_num int, name text, type text);

Explanation: DDL from PostgreSQL core regression test for Jsonb.


Question: Find the average travel speed for each vessel, grouped by vessel type and month.

CREATE TABLE vessels (vessel_id INT, vessel_name VARCHAR(50), flag_state VARCHAR(50), vessel_type VARCHAR(50)); CREATE TABLE voyages (id INT, vessel_id INT, start_port_id INT, end_port_id INT, distance FLOAT, travel_time FLOAT, voyage_date DATE);

SELECT v.vessel_type, DATE_FORMAT(voyages.voyage_date, '%Y-%m') as time_period, AVG(voyages.distance/voyages.travel_time*24) as avg_speed FROM vessels JOIN voyages ON vessels.vessel_id = voyages.vessel_id GROUP BY v.vessel_type, time_period;


Question: What is the average altitude of satellites in the 'satellite_info' table?

CREATE TABLE satellite_info (id INT PRIMARY KEY, satellite_name VARCHAR(255), country VARCHAR(255), launch_date DATE, altitude INT);

SELECT AVG(altitude) FROM satellite_info;


Question: List all the transactions that occurred in the last month in the ethical labor practices retail sector.

CREATE TABLE Transactions (transactionID int, transactionDate datetime, retailSector varchar(255)); INSERT INTO Transactions VALUES (1, '2022-01-01', 'ethical labor practices');

SELECT * FROM Transactions WHERE transactionDate >= DATE_SUB(NOW(), INTERVAL 1 MONTH) AND retailSector = 'ethical labor practices';


Question: Generate PostgreSQL SQL for: What is Category, when Result is "Nominated", when Award is "Drama Desk Award", and when Nominee is "Nathan Lane"?

CREATE TABLE table_name_95 (category VARCHAR, nominee VARCHAR, result VARCHAR, award VARCHAR)

SELECT category FROM table_name_95 WHERE result = 'nominated' AND award = 'drama desk award' AND nominee = 'nathan lane';


Question: Generate PostgreSQL SQL for: What Player had a Score of 70-71=141?

CREATE TABLE table_name_80 (player VARCHAR, score VARCHAR)

SELECT player FROM table_name_80 WHERE score = 70 - 71 = 141;


Question: Generate PostgreSQL SQL for: What's the quantity preserved when the fleet number was 700?

CREATE TABLE table_name_57 (quantity_preserved VARCHAR, fleet_number_s_ VARCHAR)

SELECT quantity_preserved FROM table_name_57 WHERE fleet_number_s_ = '700';


Question: What is the maximum risk score of Brown Investment Group's portfolio in the agriculture sector?

CREATE TABLE Brown_Investment_Group (id INT, sector VARCHAR(20), risk_score INT); INSERT INTO Brown_Investment_Group (id, sector, risk_score) VALUES (1, 'Agriculture', 50), (2, 'Manufacturing', 40);

SELECT MAX(risk_score) FROM Brown_Investment_Group WHERE sector = 'Agriculture';


Question: pgTAP test for Moretap (assertion 9).

SELECT is(
    (SELECT * FROM finish(NULL) LIMIT 1),
    '# Looks like you failed 1 test of 8',
    'The output of finish(NULL) should reflect the test failure'
);

Explanation: SQL assertion from pgTAP test suite for Moretap.


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

SELECT a, lower(nullif(x, 'foo')), lower(nullif(y, 'foo')) FROM collate_test10;

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

SELECT count(*) FROM (SELECT a, lower(nullif(x, 'foo')), lower(nullif(y, 'foo')) FROM collate_test10) AS _sub;


Question: Generate PostgreSQL SQL for: Which player is in the position of Guard/Forward?

CREATE TABLE table_name_67 (name VARCHAR, position VARCHAR)

SELECT name FROM table_name_67 WHERE position = 'guard/forward';


Question: How many artworks are on display in the 'ImpressionistGallery'?

CREATE TABLE Artworks (ArtworkID INT, Title VARCHAR(50), Gallery VARCHAR(50)); INSERT INTO Artworks (ArtworkID, Title, Gallery) VALUES (1, 'Starry Night', 'ImpressionistGallery'); INSERT INTO Artworks (ArtworkID, Title, Gallery) VALUES (2, 'Sunflowers', 'ImpressionistGallery');

SELECT COUNT(*) FROM Artworks WHERE Gallery = 'ImpressionistGallery';


Question: Identify the circular economy initiatives that have a direct impact on waste generation metrics in the waste management industry?

CREATE TABLE circular_economy_initiatives (initiative VARCHAR(50), impacted_metrics VARCHAR(50)); INSERT INTO circular_economy_initiatives VALUES ('Product-as-a-service', 'Waste generation, Reuse rate'), ('Waste-to-Energy', 'Waste generation, Landfill capacity'), ('Recycling education programs', 'Recycling rate'), ('Biodegradable plastics', 'Waste generation, Landfill capacity');

SELECT initiative, impacted_metrics FROM circular_economy_initiatives;


Question: Generate PostgreSQL SQL for: What is the Stuffit ability that has a gzip of yes, ISO/CD images of no and LHA/LZH of no?

CREATE TABLE table_name_75 (stuffit VARCHAR, lha_lzh VARCHAR, gzip VARCHAR, iso_cd_image VARCHAR)

SELECT stuffit FROM table_name_75 WHERE gzip = 'yes' AND iso_cd_image = 'no' AND lha_lzh = 'no';


Question: Generate PostgreSQL SQL for: Name the least lost with points more than 6 and games less than 5

CREATE TABLE table_name_4 (lost INTEGER, points VARCHAR, games VARCHAR)

SELECT MIN(lost) FROM table_name_4 WHERE points > 6 AND games < 5;


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

INSERT INTO TIMESTAMP_TBL VALUES ('1997-01-02 03:04:05');

Explanation: DML from PostgreSQL core regression test for Timestamp.


Question: Generate PostgreSQL SQL for: What's the part 4 for the verb whose part 3 is borgen?

CREATE TABLE table_1745843_7 (part_4 VARCHAR, part_3 VARCHAR)

SELECT part_4 FROM table_1745843_7 WHERE part_3 = 'borgen';


Question: Generate PostgreSQL SQL for: When were the callback auditions for the audition city in the episode aired on February 9, 2011?

CREATE TABLE table_27455867_1 (callback_audition_date VARCHAR, episode_air_date VARCHAR)

SELECT callback_audition_date FROM table_27455867_1 WHERE episode_air_date = 'February 9, 2011';


Question: How many unique donors have there been in each of the last 3 months?

CREATE TABLE donation_timeline (id INT, donor_id INT, donation_date DATE);

SELECT DATE_FORMAT(donation_date, '%Y-%m') as donation_month, COUNT(DISTINCT donor_id) as unique_donors FROM donation_timeline WHERE donation_date >= DATE_SUB(CURDATE(), INTERVAL 3 MONTH) GROUP BY donation_month;


Question: Generate PostgreSQL SQL for: What is the win-loss when 2008 has a value of Q1 at Australian Open?

CREATE TABLE table_name_65 (career_win_loss VARCHAR, tournament VARCHAR)

SELECT career_win_loss FROM table_name_65 WHERE 2008 = 'q1' AND tournament = 'australian open';


Question: What is the maximum income in the "South" district?

CREATE TABLE district (name VARCHAR(20), income FLOAT); INSERT INTO district (name, income) VALUES ('North', 45000.0), ('East', 50000.0), ('West', 40000.0), ('South', 55000.0), ('South', 58000.0), ('South', 56000.0);

SELECT MAX(income) FROM district WHERE name = 'South';


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

create table parted_notnull_inh_test1 partition of parted_notnull_inh_test (a not null, b default 1) for values in (1);

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


Question: Generate PostgreSQL SQL for: Who had the fastest lap(s) when josef newgarden led the most laps at edmonton?

CREATE TABLE table_29690363_3 (fastest_lap VARCHAR, most_laps_led VARCHAR, race VARCHAR)

SELECT fastest_lap FROM table_29690363_3 WHERE most_laps_led = 'Josef Newgarden' AND race = 'Edmonton';


Question: Determine the most efficient garment manufacturing countries in Q1 2022.

CREATE TABLE garment_manufacturing (id INT, garment_id INT, country VARCHAR(20), manufacturing_date DATE, workers INT, efficiency DECIMAL(4,2));CREATE VIEW efficient_manufacturers_q1_2022 AS SELECT country, AVG(efficiency) as avg_efficiency FROM garment_manufacturing WHERE manufacturing_date >= '2022-01-01' AND manufacturing_date < '2022-04-01' AND workers > 50 GROUP BY country;

SELECT country, avg_efficiency, RANK() OVER (ORDER BY avg_efficiency DESC) as efficiency_rank FROM efficient_manufacturers_q1_2022;


Question: What is the maximum number of hours volunteered by a single volunteer in a year?

CREATE TABLE volunteer_hours (id INT, volunteer_id INT, year INT, num_hours INT); INSERT INTO volunteer_hours (id, volunteer_id, year, num_hours) VALUES (1, 1, 2019, 100), (2, 1, 2020, 150), (3, 2, 2019, 75), (4, 2, 2020, 200), (5, 3, 2019, 125), (6, 3, 2020, 175);

SELECT year, MAX(num_hours) as max_hours FROM volunteer_hours GROUP BY year;


Question: Generate PostgreSQL SQL for: What is To Par, when Country is United States, and when Score is 71-68-73=212?

CREATE TABLE table_name_22 (to_par VARCHAR, country VARCHAR, score VARCHAR)

SELECT to_par FROM table_name_22 WHERE country = 'united states' AND score = 71 - 68 - 73 = 212;


Question: Generate PostgreSQL SQL for: When did Archbishop Albert Daeger vacate the throne?

CREATE TABLE table_name_63 (vacated_throne VARCHAR, archbishop VARCHAR)

SELECT vacated_throne FROM table_name_63 WHERE archbishop = 'albert daeger';


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

-- Operators that are commutator pairs should have identical volatility
-- and leakproofness markings on their implementation functions.
SELECT o1.oid, o1.oprcode, o2.oid, o2.oprcode
FROM pg_operator AS o1, pg_operator AS o2, pg_proc AS p1, pg_proc AS p2
WHERE o1.oprcom = o2.oid AND p1.oid = o1.oprcode AND p2.oid = o2.oprcode AND
    (p1.provolatile != p2.provolatile OR
     p1.proleakproof != p2.proleakproof);

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


Question: Which farmers have less than 5 years of experience in the agriculture database?

CREATE TABLE Farmers (id INT, name VARCHAR, location VARCHAR, years_of_experience INT); INSERT INTO Farmers (id, name, location, years_of_experience) VALUES (1, 'Nur Afiqah', 'Singapore', 2), (2, 'Max Schmidt', 'Berlin', 4), (3, 'Anastasia Kuznetsova', 'Moscow', 6), (4, 'Jacob Nielsen', 'Oslo', 8), (5, 'Carla Moraes', 'Sao Paulo', 10);

SELECT name FROM Farmers WHERE years_of_experience < 5;


Question: Generate PostgreSQL SQL for: What is the largest season with a Third Driver of jimmy davies?

CREATE TABLE table_name_2 (season INTEGER, third_driver VARCHAR)

SELECT MAX(season) FROM table_name_2 WHERE third_driver = 'jimmy davies';


Question: What is the minimum yield of corn crops by country?

CREATE TABLE Country (id INT, name VARCHAR(255)); INSERT INTO Country (id, name) VALUES (1, 'Canada'), (2, 'Mexico'), (3, 'Brazil'); CREATE TABLE Crop (id INT, name VARCHAR(255), country_id INT, yield INT); INSERT INTO Crop (id, name, country_id, yield) VALUES (1, 'Corn', 1, 20), (2, 'Soybean', 2, 30), (3, 'Corn', 3, 10);

SELECT MIN(Crop.yield) FROM Crop INNER JOIN Country ON Crop.country_id = Country.id WHERE Crop.name = 'Corn';


Question: Generate PostgreSQL SQL for: Luis Salom had the fastest lap on which circuits?

CREATE TABLE table_18303274_1 (circuit VARCHAR, fastest_lap VARCHAR)

SELECT circuit FROM table_18303274_1 WHERE fastest_lap = 'Luis Salom';


Question: What is the total number of students who participated in lifelong learning programs in 'Suburb B' and 'City C'?

CREATE TABLE SuburbBLifelong (studentID INT, suburb VARCHAR(50), program VARCHAR(50)); INSERT INTO SuburbBLifelong (studentID, suburb, program) VALUES (1, 'Suburb B', 'lifelong learning'), (2, 'City C', 'lifelong learning'); CREATE TABLE CityCLifelong (studentID INT, city VARCHAR(50), program VARCHAR(50)); INSERT INTO CityCLifelong (studentID, city, program) VALUES (3, 'City C', 'lifelong learning');

SELECT COUNT(DISTINCT studentID) FROM SuburbBLifelong WHERE suburb IN ('Suburb B', 'City C') AND program = 'lifelong learning' UNION ALL SELECT COUNT(DISTINCT studentID) FROM CityCLifelong WHERE city IN ('Suburb B', 'City C') AND program = 'lifelong learning';


Question: pgTAP test for Throwtap (assertion 34).

SELECT * FROM check_test(
    throws_imatching(
        'SELECT 1',
        'HUH.+',
        'whatever'
    ),
    false,
    'throws_imatching(valid sql, regex, desc)',
    'whatever',
    '    no exception thrown'
);

Explanation: SQL assertion from pgTAP test suite for Throwtap.


Question: How many workers are employed in each company's 'geological survey' department?

CREATE TABLE companies (company_id INT, company_name VARCHAR(50));CREATE TABLE workers (worker_id INT, company_id INT, department VARCHAR(20), num_employees INT);

SELECT c.company_name, w.department, SUM(w.num_employees) AS total_employees FROM workers w INNER JOIN companies c ON w.company_id = c.company_id GROUP BY w.department, c.company_name HAVING department = 'geological survey';


Question: What is the total number of green buildings in the UK with a gold rating?

CREATE TABLE green_buildings (building_id INT, building_name VARCHAR(255), country VARCHAR(255), rating VARCHAR(255));

SELECT COUNT(*) FROM green_buildings WHERE country = 'UK' AND rating = 'gold';


Question: Write the DML statement from PostgreSQL regression test 'insert_conflict' (example 80).

insert into insertconflicttest values (23, 'Blackberry') on conflict (fruit) do update set fruit = excluded.fruit;

Explanation: DML from PostgreSQL core regression test for Insert Conflict.


Question: pgTAP test for Unique (assertion 11).

/****************************************************************************/
-- Test col_is_unique().

SELECT * FROM check_test(
    col_is_unique( 'public', 'sometab', 'name', 'public.sometab.name should be unique' ),
    true,
    'col_is_unique( schema, table, column, description )',
    'public.sometab.name should be unique',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Unique.


Question: Write the DML statement from PostgreSQL regression test 'alter_table' (example 171).

Explanation: DML from PostgreSQL core regression test for Alter Table.


Question: Generate PostgreSQL SQL for: What were the results for the incumbent from Iowa 2 district?

CREATE TABLE table_name_12 (results VARCHAR, district VARCHAR)

SELECT results FROM table_name_12 WHERE district = 'iowa 2';


Question: Generate PostgreSQL SQL for: Tell me the call sign for frequency of 0 97.3 fm

CREATE TABLE table_name_67 (call_sign VARCHAR, frequency VARCHAR)

SELECT call_sign FROM table_name_67 WHERE frequency = '0 97.3 fm';


Question: How many marine protected areas are there in the Caribbean Sea?

CREATE TABLE marine_protected_areas (id INT, area_name VARCHAR(255), ocean VARCHAR(255)); INSERT INTO marine_protected_areas (id, area_name, ocean) VALUES (1, 'Area 1', 'Caribbean'), (2, 'Area 2', 'Caribbean'), (3, 'Area 3', 'Mediterranean'), (4, 'Area 4', 'Pacific');

SELECT COUNT(*) FROM marine_protected_areas WHERE ocean = 'Caribbean';


Question: Generate PostgreSQL SQL for: Which player is from Sweden?

CREATE TABLE table_name_3 (player VARCHAR, country VARCHAR)

SELECT player FROM table_name_3 WHERE country = 'sweden';


Question: What is the total amount donated by recurring donors for dance performances in San Francisco?

CREATE TABLE donors (donor_id INT, name VARCHAR(50), is_recurring BOOLEAN, city VARCHAR(50)); CREATE TABLE donations (donation_id INT, donor_id INT, amount DECIMAL(10,2), event_type VARCHAR(50)); INSERT INTO donors (donor_id, name, is_recurring, city) VALUES (1, 'Jane Smith', TRUE, 'San Francisco'); INSERT INTO donations (donation_id, donor_id, amount, event_type) VALUES (1, 1, 100.00, 'Dance');

SELECT SUM(d.amount) AS total_donated FROM donations d JOIN donors don ON d.donor_id = don.donor_id WHERE don.city = 'San Francisco' AND don.is_recurring = TRUE AND d.event_type = 'Dance';


Question: Generate PostgreSQL SQL for: Which country is Jay Haas from when he had a to par of E?

CREATE TABLE table_name_92 (country VARCHAR, to_par VARCHAR, player VARCHAR)

SELECT country FROM table_name_92 WHERE to_par = 'e' AND player = 'jay haas';


Question: What is the name of the graduate student who received the largest research grant in the past year?

CREATE TABLE students (student_id INT, name TEXT); INSERT INTO students (student_id, name) VALUES (1, 'Alice Johnson'), (2, 'Bob Brown'); CREATE TABLE grants (grant_id INT, student_id INT, year INT, amount INT); INSERT INTO grants (grant_id, student_id, year, amount) VALUES (1, 1, 2021, 10000), (2, 2, 2022, 20000);

SELECT s.name FROM students s INNER JOIN (SELECT student_id, MAX(amount) as max_amount FROM grants WHERE year = 2022 GROUP BY student_id) g ON s.student_id = g.student_id WHERE g.max_amount = (SELECT MAX(amount) FROM grants WHERE year = 2022);


Question: Insert a new habitat named Australia with a size of 220000 into the 'habitats' table.

CREATE TABLE habitats (id INT PRIMARY KEY, name VARCHAR(50), size INT);

INSERT INTO habitats (name, size) VALUES ('Australia', 220000);


Question: What is the average production cost of organic cotton t-shirts?

CREATE TABLE OrganicCottonTShirts (id INT, production_cost DECIMAL);

SELECT AVG(production_cost) FROM OrganicCottonTShirts;


Question: Determine geopolitical risk assessments with a risk_level of 'High' and their assessment_date.

CREATE SCHEMA IF NOT EXISTS geopolitical_risk;CREATE TABLE IF NOT EXISTS geopolitical_risk_assessments (assessment_id INT, assessment_date DATE, risk_level VARCHAR(10));INSERT INTO geopolitical_risk_assessments (assessment_id, assessment_date, risk_level) VALUES (1, '2021-01-01', 'Medium'), (2, '2021-02-01', 'High'), (3, '2021-03-01', 'Low');

SELECT assessment_date, risk_level FROM geopolitical_risk_assessments WHERE risk_level = 'High';


Question: What is the total budget and number of departments for each manager, grouped by manager gender?

CREATE TABLE Manager (id INT, Name VARCHAR(50), Gender VARCHAR(10)); INSERT INTO Manager (id, Name, Gender) VALUES (101, 'Manager1', 'Male'); INSERT INTO Manager (id, Name, Gender) VALUES (102, 'Manager2', 'Female'); CREATE TABLE Department (id INT, Name VARCHAR(50), ManagerID INT, Budget FLOAT); INSERT INTO Department (id, Name, ManagerID, Budget) VALUES (1, 'Department1', 101, 500000); INSERT INTO Department (id, Name, ManagerID, Budget) VALUES (2, 'Department2', 101, 750000); INSERT INTO Department (id, Name, ManagerID, Budget) VALUES (3, 'Department3', 102, 600000);

SELECT m.Gender, SUM(d.Budget) AS TotalBudget, COUNT(d.id) AS NumberOfDepartments FROM Manager m JOIN Department d ON m.id = d.ManagerID GROUP BY m.Gender;


Question: List all space missions that have lasted more than 300 days

CREATE TABLE SpaceMissions (id INT, mission_name VARCHAR(30), duration INT); INSERT INTO SpaceMissions (id, mission_name, duration) VALUES (1, 'Mars Exploration', 400); INSERT INTO SpaceMissions (id, mission_name, duration) VALUES (2, 'Asteroid Survey', 250);

SELECT mission_name FROM SpaceMissions WHERE duration > 300;


Question: What is the number of members who have extended their membership in the last 3 months?

CREATE TABLE gym_memberships (id INT, member_name VARCHAR(50), start_date DATE, end_date DATE, membership_type VARCHAR(50), price DECIMAL(5,2));

SELECT COUNT(DISTINCT member_name) AS extended_members FROM gym_memberships WHERE end_date < DATE_SUB(CURDATE(), INTERVAL 3 MONTH) AND DATE_ADD(end_date, INTERVAL 1 MONTH) > CURDATE();


Question: Show a SQL definition from the timescaledb project (partitioned_hypertable, item 38).

-- FOREIGN KEY from hypertable to hypertable
CREATE TABLE ref_ht(
    time TIMESTAMPTZ NOT NULL ,
    id INT,
    CONSTRAINT ref_ht_pkey PRIMARY KEY (time, id)
) WITH (timescaledb.hypertable, timescaledb.partition_column='time');

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


Question: Generate PostgreSQL SQL for: Who is the player with a 77-68=145 score?

CREATE TABLE table_name_56 (player VARCHAR, score VARCHAR)

SELECT player FROM table_name_56 WHERE score = 77 - 68 = 145;


Question: Which aquatic species have health metrics above the average?

CREATE TABLE health_metrics (id INT, species VARCHAR(50), metric FLOAT); INSERT INTO health_metrics (id, species, metric) VALUES (1, 'Tilapia', 75.0), (2, 'Catfish', 80.0), (3, 'Salmon', 60.0);

SELECT species FROM health_metrics WHERE metric > (SELECT AVG(metric) FROM health_metrics);


Question: What is the average playtime for players who have played games with a price greater than 50?

CREATE TABLE Players (PlayerID INT, Age INT, Gender VARCHAR(10), Country VARCHAR(50)); INSERT INTO Players (PlayerID, Age, Gender, Country) VALUES (1, 25, 'Male', 'USA'), (2, 30, 'Female', 'Canada'), (3, 22, 'Male', 'Mexico'); CREATE TABLE GamePlay (PlayerID INT, Playtime INT, GamePrice DECIMAL(5, 2)); INSERT INTO GamePlay (PlayerID, Playtime, GamePrice) VALUES (1, 120, 60.00), (2, 90, 45.00), (3, 150, 55.00);

SELECT AVG(GamePlay.Playtime) FROM GamePlay INNER JOIN Players ON GamePlay.PlayerID = Players.PlayerID WHERE GamePrice > 50;


Question: What is the total quantity of items with type 'I' in warehouse S and warehouse T?

CREATE TABLE warehouse_s(item_id INT, item_type VARCHAR(10), quantity INT);CREATE TABLE warehouse_t(item_id INT, item_type VARCHAR(10), quantity INT);INSERT INTO warehouse_s(item_id, item_type, quantity) VALUES (1, 'I', 200), (2, 'I', 300), (3, 'I', 50);INSERT INTO warehouse_t(item_id, item_type, quantity) VALUES (1, 'I', 150), (2, 'I', 250), (3, 'I', 40);

SELECT quantity FROM warehouse_s WHERE item_type = 'I' UNION ALL SELECT quantity FROM warehouse_t WHERE item_type = 'I';


Question: Generate PostgreSQL SQL for: Name the type for hobart college

CREATE TABLE table_1974482_1 (type VARCHAR, institution VARCHAR)

SELECT type FROM table_1974482_1 WHERE institution = 'Hobart College';


Question: Generate PostgreSQL SQL for: Which district had first elected earlier than 2006 for representation of Broken Arrow, Tulsa?

CREATE TABLE table_name_7 (district VARCHAR, first_elected VARCHAR, towns_represented VARCHAR)

SELECT district FROM table_name_7 WHERE first_elected < 2006 AND towns_represented = 'broken arrow, tulsa';


Question: Which cruelty-free cosmetic brands are most popular in the US?

CREATE TABLE brands (brand_id INT, brand_name TEXT, is_cruelty_free BOOLEAN); INSERT INTO brands (brand_id, brand_name, is_cruelty_free) VALUES (1, 'Flawless Faced', true), (2, 'Naturally Radiant', true), (3, 'Cruelty Free Cosmetics', true), (4, 'Animal Tested Brands', false); CREATE TABLE sales (sale_id INT, brand_id INT, sale_quantity INT, sale_country TEXT); INSERT INTO sales (sale_id, brand_id, sale_quantity, sale_country) VALUES (1, 1, 500, 'US'), (2, 2, 700, 'US'), (3, 3, 300, 'US'), (4, 4, 800, 'US'), (5, 1, 600, 'CA'), (6, 2, 400, 'CA');

SELECT b.brand_name, SUM(s.sale_quantity) as total_sales_quantity FROM sales s JOIN brands b ON s.brand_id = b.brand_id WHERE b.is_cruelty_free = true AND s.sale_country = 'US' GROUP BY b.brand_name ORDER BY total_sales_quantity DESC;


Question: Generate PostgreSQL SQL for: What happened in Mazar-i-sharif?

CREATE TABLE table_name_3 (circumstances VARCHAR, location VARCHAR)

SELECT circumstances FROM table_name_3 WHERE location = 'mazar-i-sharif';


Question: Generate PostgreSQL SQL for: When 22 is the number what is the episode title?

CREATE TABLE table_29475589_3 (episode_title VARCHAR, no VARCHAR)

SELECT episode_title FROM table_29475589_3 WHERE no = 22;


Question: What is the average wind speed and solar radiation for each city by month?

CREATE TABLE sensors (id INT, city VARCHAR(255), type VARCHAR(255), value FLOAT, timestamp TIMESTAMP); INSERT INTO sensors (id, city, type, value, timestamp) VALUES (1, 'EcoCity', 'Wind Speed', 7.2, '2022-04-01 10:00:00'), (2, 'EcoCity', 'Solar Radiation', 500, '2022-04-01 10:00:00');

SELECT city, type, AVG(value) as avg_value, DATE_FORMAT(timestamp, '%%Y-%%m') as month FROM sensors GROUP BY city, type, month;


Question: Show all workers who have more than 5 years of experience

CREATE TABLE experience (id INT, worker VARCHAR(50), years_of_experience INT); INSERT INTO experience (id, worker, years_of_experience) VALUES (1, 'John Doe', 3), (2, 'Jane Smith', 7), (3, 'Alice Johnson', 6);

SELECT worker FROM experience WHERE years_of_experience > 5;


Question: Find the total volume of timber harvested in 'Africa' from 'coniferous' type

CREATE TABLE forest_types (id INT, type VARCHAR(20)); INSERT INTO forest_types (id, type) VALUES (3, 'coniferous');

SELECT SUM(volume) FROM timber_harvest t JOIN forest_types ft ON t.forest_type_id = ft.id WHERE t.harvest_location = 'Africa' AND ft.type = 'coniferous';


Question: Find the names of graduate students who have never received a research grant.

CREATE TABLE grad_students (id INT, name VARCHAR(50));CREATE TABLE research_grants (id INT, grant_id INT, student_id INT);

SELECT DISTINCT gs.name FROM grad_students gs LEFT JOIN research_grants rg ON gs.id = rg.student_id WHERE rg.id IS NULL;


Question: Insert a new species into the marine_species table with a conservation_status of 'Near Threatened' and a primary productivity value of 100.

CREATE TABLE marine_species (id INT PRIMARY KEY, name VARCHAR(255), conservation_status VARCHAR(255)); INSERT INTO marine_species (id, name, conservation_status) VALUES (1, 'Humpback Whale', 'Vulnerable'); CREATE TABLE oceanography (id INT PRIMARY KEY, species_id INT, primary_productivity INT); INSERT INTO oceanography (id, species_id, primary_productivity) VALUES (1, 1, 50);

INSERT INTO marine_species (id, name, conservation_status) VALUES (2, 'Narwhal', 'Near Threatened'); INSERT INTO oceanography (id, species_id, primary_productivity) VALUES (2, 2, 100);


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

CREATE FUNCTION regexp_matches( citext, citext, text ) RETURNS SETOF TEXT[] AS $$
    SELECT pg_catalog.regexp_matches( $1::pg_catalog.text, $2::pg_catalog.text, CASE WHEN pg_catalog.strpos($3, 'c') = 0 THEN  $3 || 'i' ELSE $3 END );
$$ LANGUAGE SQL IMMUTABLE STRICT ROWS 10;

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


Question: Find the total quantity of seafood products in the inventory, grouped by supplier country.

CREATE TABLE inventory(id INT PRIMARY KEY, product VARCHAR(50), quantity INT, supplier_id INT, supplier_country VARCHAR(50)); INSERT INTO inventory(id, product, quantity, supplier_id, supplier_country) VALUES (1, 'salmon', 100, 1, 'Canada'), (2, 'shrimp', 200, 2, 'Thailand'), (3, 'tuna', 150, 3, 'Spain'), (4, 'crab', 250, 2, 'Thailand'), (5, 'lobster', 300, 4, 'Mexico'); CREATE TABLE suppliers(id INT PRIMARY KEY, country VARCHAR(50)); INSERT INTO suppliers(id, country) VALUES (1, 'Canada'), (2, 'Thailand'), (3, 'Spain'), (4, 'Mexico'); CREATE TABLE product_types(id INT PRIMARY KEY, product VARCHAR(50), type VARCHAR(50)); INSERT INTO product_types(id, product, type) VALUES (1, 'salmon', 'seafood'), (2, 'shrimp', 'seafood'), (3, 'tuna', 'seafood'), (4, 'crab', 'seafood'), (5, 'lobster', 'seafood'), (6, 'beef', 'meat'), (7, 'chicken', 'meat');

SELECT s.country AS supplier_country, pt.type, SUM(i.quantity) FROM inventory i JOIN suppliers s ON i.supplier_id = s.id JOIN product_types pt ON i.product = pt.product WHERE pt.type = 'seafood' GROUP BY s.country, pt.type;


Question: What is the distribution of mental health scores for students in private and public schools in the US and Canada?

CREATE TABLE student_mental_health (student_id INT, school_type VARCHAR(50), country VARCHAR(50), score INT); INSERT INTO student_mental_health (student_id, school_type, country, score) VALUES (1, 'Private', 'USA', 75), (2, 'Public', 'Canada', 80), (3, 'Private', 'USA', 70), (4, 'Public', 'Canada', 75), (5, 'Private', 'USA', 85), (6, 'Public', 'Canada', 80);

SELECT school_type, country, AVG(score) as avg_score, STDDEV(score) as stddev_score FROM student_mental_health GROUP BY school_type, country;


Question: What is the minimum depth of any underwater mountain in the Pacific ocean?

CREATE TABLE underwater_mountains (mountain_name TEXT, location TEXT, min_depth FLOAT); INSERT INTO underwater_mountains (mountain_name, location, min_depth) VALUES ('Mountain 1', 'Pacific Ocean', 1200.0), ('Mountain 2', 'Atlantic Ocean', 900.0), ('Mountain 3', 'Pacific Ocean', 1500.0);

SELECT MIN(min_depth) FROM underwater_mountains WHERE location = 'Pacific Ocean';


Question: What is the total number of dams in India and China combined?

CREATE TABLE Dams (DamID INT, Name TEXT, Height FLOAT, Location TEXT, Country TEXT); INSERT INTO Dams (DamID, Name, Height, Location, Country) VALUES (1, 'Tehri Dam', 260.5, 'Tehri, India', 'India'); INSERT INTO Dams (DamID, Name, Height, Location, Country) VALUES (2, 'Xiaowan Dam', 292.0, 'Luxi, China', 'China');

SELECT COUNT(*) FROM Dams WHERE Dams.Country = 'India' OR Dams.Country = 'China';


Question: pgTAP test for Check (assertion 12).

SELECT * FROM check_test(
    col_has_check( 'sometab', 'name', 'sometab.name should have a check' ),
    true,
    'col_has_check( tab, col, desc )',
    'sometab.name should have a check',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Check.


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

INSERT INTO shoelace_data VALUES ('sl7', 7, 'brown', 60 , 'cm');

Explanation: DML from PostgreSQL core regression test for Rules.


Question: What's the average budget of TV shows in the 'Comedy' genre?

CREATE TABLE tv_show_budgets (id INT, title VARCHAR(255), genre VARCHAR(255), budget INT); INSERT INTO tv_show_budgets (id, title, genre, budget) VALUES (1, 'The Big Bang Theory', 'Comedy', 8000000), (2, 'Friends', 'Comedy', 10000000), (3, 'Breaking Bad', 'Drama', 3000000);

SELECT AVG(budget) FROM tv_show_budgets WHERE genre = 'Comedy';


Question: Generate PostgreSQL SQL for: How many blockings occured in the game with 198 rebounds?

CREATE TABLE table_22993636_5 (blocks INTEGER, rebounds VARCHAR)

SELECT MAX(blocks) FROM table_22993636_5 WHERE rebounds = 198;


Question: How many countries have launched objects into space?

CREATE TABLE space_objects (object_name TEXT, launch_country TEXT); INSERT INTO space_objects (object_name, launch_country) VALUES ('Sputnik 1', 'USSR'), ('Explorer 1', 'USA');

SELECT launch_country, COUNT(DISTINCT launch_country) as country_count FROM space_objects GROUP BY launch_country HAVING COUNT(DISTINCT launch_country) > 1;


Question: Generate PostgreSQL SQL for: What were the starts when the points dropped 18?

CREATE TABLE table_24937583_1 (races__starts_ VARCHAR, points__dropped_points_ VARCHAR)

SELECT races__starts_ FROM table_24937583_1 WHERE points__dropped_points_ = '18';


Question: What is the average data usage for postpaid mobile customers in the city of Seattle?

CREATE TABLE mobile_subscribers (subscriber_id INT, data_usage FLOAT, city VARCHAR(20)); CREATE TABLE postpaid_subscribers (subscriber_id INT, plan_type VARCHAR(10)); INSERT INTO mobile_subscribers (subscriber_id, data_usage, city) VALUES (1, 5.6, 'Seattle'), (2, 7.8, 'New York'), (3, 3.4, 'Seattle'); INSERT INTO postpaid_subscribers (subscriber_id, plan_type) VALUES (1, 'postpaid'), (2, 'prepaid'), (3, 'postpaid');

SELECT AVG(data_usage) FROM mobile_subscribers INNER JOIN postpaid_subscribers ON mobile_subscribers.subscriber_id = postpaid_subscribers.subscriber_id WHERE city = 'Seattle';


Question: Generate PostgreSQL SQL for: what is the mascot for the enrollment 08-09 of 320?

CREATE TABLE table_name_73 (mascot VARCHAR, enrollment_08_09 VARCHAR)

SELECT mascot FROM table_name_73 WHERE enrollment_08_09 = 320;


Question: How many members are there in the 'solidarity_union' union?

CREATE TABLE solidarity_union (member_id INT, name VARCHAR(50), union_joined_date DATE); INSERT INTO solidarity_union (member_id, name, union_joined_date) VALUES (29, 'Jayden Thompson', '2021-09-03'), (30, 'Katie Wright', '2021-10-12'), (31, 'Lila Jackson', '2021-11-27');


Question: Generate PostgreSQL SQL for: What country won in 1993?

CREATE TABLE table_name_28 (country VARCHAR, year_s__won VARCHAR)

SELECT country FROM table_name_28 WHERE year_s__won = '1993';


Question: Generate PostgreSQL SQL for: If Tuesday 1 June is 21' 05.27 107.351mph, what is the rider total number?

CREATE TABLE table_25220821_3 (rider VARCHAR, tues_1_june VARCHAR)

SELECT COUNT(rider) FROM table_25220821_3 WHERE tues_1_june = '21' 05.27 107.351mph';


Question: Delete the graduate student with id 4 from the 'students' table.

CREATE TABLE students (id INT, region TEXT, start_year INT); INSERT INTO students (id, region, start_year) VALUES (1, 'India', 2019), (2, 'China', 2020), (3, 'Japan', 2018), (4, 'Mexico', 2021);


Question: PL/pgSQL test: Plpython Setof (example 25).

-- set-returning function that modifies its parameters
CREATE OR REPLACE FUNCTION ugly(x int, lim int) RETURNS SETOF int AS $$
global x
while x <= lim:
    yield x
    x = x + 1
$$ LANGUAGE plpython3u;

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


Question: Generate PostgreSQL SQL for: Find the total amount claimed in the most recently created document.

CREATE TABLE claim_headers (amount_claimed INTEGER, claim_header_id VARCHAR); CREATE TABLE claims_documents (claim_id VARCHAR, created_date VARCHAR); CREATE TABLE claims_documents (created_date VARCHAR)

SELECT SUM(t1.amount_claimed) FROM claim_headers AS t1 JOIN claims_documents AS t2 ON t1.claim_header_id = t2.claim_id WHERE t2.created_date = (SELECT created_date FROM claims_documents ORDER BY created_date LIMIT 1);


Question: List open pedagogy courses that are not yet completed by any student.

CREATE TABLE Courses (id INT, name VARCHAR(20), completed BOOLEAN); INSERT INTO Courses (id, name, completed) VALUES (1, 'Introduction to Open Pedagogy', FALSE), (2, 'Advanced Open Pedagogy', FALSE), (3, 'SQL for Open Pedagogy', TRUE);

SELECT * FROM Courses WHERE completed = FALSE;


Question: Generate PostgreSQL SQL for: What date has a Game site of bye?

CREATE TABLE table_name_77 (date VARCHAR, game_site VARCHAR)

SELECT date FROM table_name_77 WHERE game_site = 'bye';


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

SELECT OVERLAY('yabadoo' PLACING 'daba' FROM 5 FOR 0) AS "yabadabadoo";

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

SELECT count(*) FROM (SELECT OVERLAY('yabadoo' PLACING 'daba' FROM 5 FOR 0) AS "yabadabadoo") AS _sub;


Question: What is the total budget for rural infrastructure projects in Africa that were completed in the past 3 years, grouped by country?

CREATE TABLE rural_infrastructure (id INT, project_budget INT, project_status TEXT, completion_date DATE, country TEXT); INSERT INTO rural_infrastructure (id, project_budget, project_status, completion_date, country) VALUES (1, 50000, 'completed', '2019-01-01', 'Kenya'), (2, 75000, 'in_progress', '2021-05-15', 'Nigeria'), (3, 60000, 'completed', '2020-12-31', 'South Africa');

SELECT country, SUM(project_budget) FROM rural_infrastructure WHERE project_status = 'completed' AND completion_date >= DATE_SUB(NOW(), INTERVAL 3 YEAR) GROUP BY country;


Question: Generate PostgreSQL SQL for: Name the nominating festival for director of 2004

CREATE TABLE table_name_1 (nominating_festival VARCHAR, director_s_ VARCHAR)

SELECT nominating_festival FROM table_name_1 WHERE director_s_ = '2004';


Question: Delete records with a membership older than 5 years in the members table

CREATE TABLE members (id INT, name VARCHAR(50), membership_start_date DATE);

DELETE FROM members WHERE membership_start_date <= DATE_SUB(CURRENT_DATE, INTERVAL 5 YEAR);


Question: Write the DML statement from PostgreSQL regression test 'time' (example 8).

Explanation: DML from PostgreSQL core regression test for Time.


Question: Generate PostgreSQL SQL for: Which driver has a Time/Retired of +6 laps?

CREATE TABLE table_name_21 (driver VARCHAR, time_retired VARCHAR)

SELECT driver FROM table_name_21 WHERE time_retired = '+6 laps';


Question: Generate PostgreSQL SQL for: who is the away team when the tie no is more than 13 and the home team is team bath?

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

SELECT away_team FROM table_name_30 WHERE tie_no > 13 AND home_team = 'team bath';


Question: Generate PostgreSQL SQL for: What team was Paolo Quinteros on?

CREATE TABLE table_name_59 (team VARCHAR, name VARCHAR)

SELECT team FROM table_name_59 WHERE name = 'paolo quinteros';


Question: Generate PostgreSQL SQL for: Who is the alternate for the team for which Monika Wagner is the third?

CREATE TABLE table_name_60 (alternate VARCHAR, third VARCHAR)

SELECT alternate FROM table_name_60 WHERE third = 'monika wagner';


Question: What is the maximum depth recorded for any underwater canyon?

CREATE TABLE underwater_canyons (canyon_name TEXT, max_depth_m INT); INSERT INTO underwater_canyons (canyon_name, max_depth_m) VALUES ('Milwaukee Deep', 8380), ('Sirena Deep', 9816), ('Tonga Trench', 10882);

SELECT MAX(max_depth_m) FROM underwater_canyons;


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

CREATE FUNCTION _int_contained_sel(internal, oid, internal, integer)
RETURNS float8
AS 'MODULE_PATHNAME'
LANGUAGE C STRICT STABLE PARALLEL SAFE;


Question: PostgreSQL regression test 'macaddr8': Write the SELECT query (example 29).

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

SELECT count(*) FROM (SELECT * FROM macaddr8_data ORDER BY 1) AS _sub;


Question: Generate PostgreSQL SQL for: Who had the highest assists on the November 13 game?

CREATE TABLE table_name_56 (high_assists VARCHAR, date VARCHAR)

SELECT high_assists FROM table_name_56 WHERE date = 'november 13';


Question: List all events with attendance greater than 100

CREATE TABLE EventAttendance (EventID INT PRIMARY KEY, EventName VARCHAR(100), Date DATE, TotalAttendance INT); INSERT INTO EventAttendance (EventID, EventName, Date, TotalAttendance) VALUES (1, 'Theater Performance', '2022-02-20', 150), (2, 'Art Exhibit', '2022-01-15', 125), (3, 'Music Concert', '2021-12-10', 200);

SELECT * FROM EventAttendance WHERE TotalAttendance > 100;


Question: How many indigenous languages are endangered in 'Pacific Islands'?

CREATE TABLE IndigenousLanguages (LanguageID INT PRIMARY KEY, LanguageName VARCHAR(50), Status VARCHAR(50), Location VARCHAR(50)); INSERT INTO IndigenousLanguages (LanguageID, LanguageName, Status, Location) VALUES (1, 'Rapa Nui', 'Endangered', 'Easter Island'), (2, 'Palauan', 'Vulnerable', 'Palau');

SELECT COUNT(*) FROM IndigenousLanguages WHERE Location LIKE '%Pacific Islands%' AND Status = 'Endangered';


Question: What is the average safety rating for explainable AI models?

CREATE TABLE explainable_ai (model_name TEXT, safety_rating INTEGER); INSERT INTO explainable_ai (model_name, safety_rating) VALUES ('Model D', 7), ('Model E', 9), ('Model F', 8);

SELECT AVG(safety_rating) FROM explainable_ai WHERE model_name LIKE '%explainable%';


Question: Generate PostgreSQL SQL for: what is the least silver when overall is less than 67, team is saami and gold is less than 5?

CREATE TABLE table_name_2 (silver INTEGER, gold VARCHAR, overall VARCHAR, team VARCHAR)

SELECT MIN(silver) FROM table_name_2 WHERE overall < 67 AND team = 'saami' AND gold < 5;


Question: List all peacekeeping operations with their corresponding operation start and end dates.

CREATE TABLE peacekeeping_operations (id INT, name TEXT, start_date DATE, end_date DATE); INSERT INTO peacekeeping_operations (id, name, start_date, end_date) VALUES (1, 'Operation1', '2010-01-01', '2015-01-01'), (2, 'Operation2', '2015-01-01', '2020-01-01'), (3, 'Operation3', '2020-01-01', '2022-01-01');

SELECT name, start_date, end_date FROM peacekeeping_operations;


Question: How many clinical trials were conducted for drug 'LMN-789'?

CREATE TABLE clinical_trials (trial_id INTEGER, drug_name TEXT, year INTEGER);

SELECT COUNT(*) FROM clinical_trials WHERE drug_name = 'LMN-789';


Question: Provide the average environmental impact score for gold mines in the Western region.

CREATE TABLE environmental_impact (mine_type VARCHAR(20), region VARCHAR(20), score FLOAT); INSERT INTO environmental_impact (mine_type, region, score) VALUES ('Gold', 'West', 70.5), ('Gold', 'West', 71.2), ('Gold', 'East', 75.0), ('Gold', 'East', 73.1), ('Gold', 'North', 68.8), ('Gold', 'South', 72.4);

SELECT AVG(score) FROM environmental_impact WHERE mine_type = 'Gold' AND region = 'West';


Question: Update the temperature sensor readings to 25 degrees Celsius for sensor_id 12

CREATE TABLE temperature_sensor_data (sensor_id INT, temperature FLOAT, timestamp TIMESTAMP); INSERT INTO temperature_sensor_data (sensor_id, temperature, timestamp) VALUES (12, 23.6, '2022-05-21 10:00:00');

WITH updated_data AS (UPDATE temperature_sensor_data SET temperature = 25 WHERE sensor_id = 12 RETURNING *) SELECT * FROM updated_data;


Question: What is the total revenue generated by hotel bookings in the APAC region in Q1 2022?

CREATE TABLE bookings (booking_id INT, booking_date DATE, region VARCHAR(255), revenue DECIMAL(10,2)); INSERT INTO bookings (booking_id, booking_date, region, revenue) VALUES (1, '2022-01-01', 'APAC', 100), (2, '2022-02-01', 'APAC', 200), (3, '2022-03-01', 'APAC', 300);

SELECT SUM(revenue) FROM bookings WHERE region = 'APAC' AND booking_date >= '2022-01-01' AND booking_date < '2022-04-01';


Question: What is the total number of shelter units constructed in Iraq and Lebanon, grouped by construction company?

CREATE TABLE shelter_info (id INT, company VARCHAR(255), country VARCHAR(255), units_constructed INT); INSERT INTO shelter_info (id, company, country, units_constructed) VALUES ('1', 'Alpha Construction', 'Iraq', '10'), ('2', 'Beta Construction', 'Iraq', '15'), ('3', 'Gamma Construction', 'Lebanon', '20'), ('4', 'Delta Construction', 'Lebanon', '25'), ('5', 'Epsilon Construction', 'Iraq', '30'), ('6', 'Zeta Construction', 'Lebanon', '35');

SELECT company, SUM(units_constructed) as total_units FROM shelter_info WHERE country IN ('Iraq', 'Lebanon') GROUP BY company;


Question: What is the distribution of cases by case type, in each district, in the last month?

CREATE TABLE cases (case_id INT, district_id INT, case_type VARCHAR(20), open_date DATE); INSERT INTO cases (case_id, district_id, case_type, open_date) VALUES (1, 1, 'Civil', '2022-01-05'), (2, 2, 'Criminal', '2022-03-10'), (3, 1, 'Civil', '2022-04-01');

SELECT cases.district_id, cases.case_type, COUNT(*) as num_cases FROM cases WHERE open_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH) GROUP BY cases.district_id, cases.case_type;


Question: Generate PostgreSQL SQL for: Who is listed under mens singles when womens has wang nan zhang yining?

CREATE TABLE table_28138035_27 (mens_singles VARCHAR, womens_doubles VARCHAR)

SELECT mens_singles FROM table_28138035_27 WHERE womens_doubles = 'Wang Nan Zhang Yining';


Question: Which shrimp farms in Ecuador have experienced water temperatures above 30°C in the last 30 days?

CREATE TABLE shrimp_farms (id INT, name TEXT, country TEXT, latitude DECIMAL(9,6), longitude DECIMAL(9,6)); INSERT INTO shrimp_farms (id, name, country, latitude, longitude) VALUES (1, 'Farm C', 'Ecuador', -2.123456, -79.123456); INSERT INTO shrimp_farms (id, name, country, latitude, longitude) VALUES (2, 'Farm D', 'Ecuador', -1.123456, -78.123456); CREATE TABLE shrimp_temperature_data (id INT, farm_id INT, timestamp TIMESTAMP, temperature DECIMAL(5,2)); INSERT INTO shrimp_temperature_data (id, farm_id, timestamp, temperature) VALUES (1, 1, '2022-05-01 00:00:00', 28.5); INSERT INTO shrimp_temperature_data (id, farm_id, timestamp, temperature) VALUES (2, 1, '2022-05-02 00:00:00', 31.2); INSERT INTO shrimp_temperature_data (id, farm_id, timestamp, temperature) VALUES (3, 2, '2022-05-01 00:00:00', 29.8); INSERT INTO shrimp_temperature_data (id, farm_id, timestamp, temperature) VALUES (4, 2, '2022-05-02 00:00:00', 27.6);

SELECT st.farm_id, sf.name FROM shrimp_temperature_data st JOIN shrimp_farms sf ON st.farm_id = sf.id WHERE sf.country = 'Ecuador' AND st.temperature > 30 AND st.timestamp >= NOW() - INTERVAL 30 DAY;


Question: Generate PostgreSQL SQL for: When was someone first elected in the district with incumbent john smith?

CREATE TABLE table_2668378_18 (first_elected VARCHAR, incumbent VARCHAR)

SELECT first_elected FROM table_2668378_18 WHERE incumbent = 'John Smith';


Question: Generate PostgreSQL SQL for: What is the Country that has a Player of Scott Hoch?

CREATE TABLE table_name_31 (country VARCHAR, player VARCHAR)

SELECT country FROM table_name_31 WHERE player = 'scott hoch';


Question: Generate PostgreSQL SQL for: What's the highest Year for the Venue of Santiago De Chile and the Event of 800 m?

CREATE TABLE table_name_67 (year INTEGER, event VARCHAR, venue VARCHAR)

SELECT MAX(year) FROM table_name_67 WHERE event = '800 m' AND venue = 'santiago de chile';


Question: pgTAP test for Aretap (assertion 81).

SELECT * FROM check_test(
    functions_are( array_append(___myfunk('check_test'), '__booyah__'), 'whatever' ),
    false,
    'functions_are(functions, desc) + extra & missing',
    'whatever',
    '    Extra functions:
        check_test
    Missing functions:
        __booyah__'
);

Explanation: SQL assertion from pgTAP test suite for Aretap.


Question: PostgreSQL regression test 'pg_ndistinct': Write the SELECT query (example 55).

SELECT * FROM pg_input_error_info('[{"attributes" : [2,"a"], "ndistinct" : 4}]', 'pg_ndistinct');

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

SELECT count(*) FROM (SELECT * FROM pg_input_error_info('[{"attributes" : [2,"a"], "ndistinct" : 4}]', 'pg_ndistinct')) AS _sub;


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

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


Question: Generate PostgreSQL SQL for: What is Position, when Laps is 156?

CREATE TABLE table_name_90 (position VARCHAR, laps VARCHAR)

SELECT position FROM table_name_90 WHERE laps = 156;


Question: Generate PostgreSQL SQL for: Which tournament was held on 9 Jun 2002?

CREATE TABLE table_name_57 (tournament VARCHAR, date VARCHAR)

SELECT tournament FROM table_name_57 WHERE date = '9 jun 2002';


Question: How many astronauts are from each country?

CREATE TABLE astronauts (id INT PRIMARY KEY, astronaut_name VARCHAR(50), country VARCHAR(50));

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


Question: Total number of therapy sessions conducted in each country.

CREATE TABLE therapy_sessions (session_id INT, patient_id INT, country VARCHAR(50), session_count INT); INSERT INTO therapy_sessions (session_id, patient_id, country, session_count) VALUES (1, 1, 'USA', 5), (2, 2, 'Canada', 3), (3, 3, 'Japan', 4);

SELECT country, COUNT(DISTINCT patient_id) AS number_of_patients, SUM(session_count) AS total_sessions FROM therapy_sessions GROUP BY country;


Question: What is the total biomass of all the trees in the Trees table, if each tree has a biomass of 0.022 pounds per year per inch of age?

CREATE TABLE Trees (id INT, species VARCHAR(255), age INT); INSERT INTO Trees (id, species, age) VALUES (1, 'Oak', 50), (2, 'Pine', 30), (3, 'Maple', 40);


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

select jsonb_path_query('"-inf"', '$.double()', silent => true);

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

SELECT count(*) FROM (select jsonb_path_query('"-inf"', '$.double()', silent => true)) AS _sub;


Question: Generate PostgreSQL SQL for: How many appelations are in Napa Country?

CREATE TABLE APPELLATIONS (County VARCHAR)

SELECT COUNT(*) FROM APPELLATIONS WHERE County = 'Napa';


Question: Write the DDL statement from PostgreSQL regression test 'merge' (example 493).

CREATE TABLE measurement_y2006m02 (
    CHECK ( logdate >= DATE '2006-02-01' AND logdate < DATE '2006-03-01' )
) INHERITS (measurement) WITH (autovacuum_enabled=off);

Explanation: DDL from PostgreSQL core regression test for Merge.


Question: Generate PostgreSQL SQL for: Who was the player with a score of 70-69=139?

CREATE TABLE table_name_37 (player VARCHAR, score VARCHAR)

SELECT player FROM table_name_37 WHERE score = 70 - 69 = 139;


Question: What is the total budget for all education programs?

CREATE VIEW Education_Programs AS SELECT 'Wildlife_Ambassadors' AS program, 15000 AS budget UNION SELECT 'Conservation_Champions', 20000;

SELECT SUM(budget) FROM Education_Programs;


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

SELECT * FROM pg_input_error_info('Nonexistent', 'regdatabase');

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

SELECT count(*) FROM (SELECT * FROM pg_input_error_info('Nonexistent', 'regdatabase')) AS _sub;


Question: Generate PostgreSQL SQL for: Which owner owns the most dogs? List the owner id, first name and last name.

CREATE TABLE Owners (first_name VARCHAR, last_name VARCHAR, owner_id VARCHAR); CREATE TABLE Dogs (owner_id VARCHAR)

SELECT T1.owner_id, T2.first_name, T2.last_name FROM Dogs AS T1 JOIN Owners AS T2 ON T1.owner_id = T2.owner_id GROUP BY T1.owner_id ORDER BY COUNT(*) DESC LIMIT 1;


Question: Generate PostgreSQL SQL for: What is the number of people in attendance when the decision was brodeur and the home was ottawa?

CREATE TABLE table_name_60 (attendance VARCHAR, decision VARCHAR, home VARCHAR)

SELECT attendance FROM table_name_60 WHERE decision = 'brodeur' AND home = 'ottawa';


Question: PostgreSQL regression test 'pg_ndistinct': Write the SELECT query (example 22).

SELECT * FROM pg_input_error_info('[{"ndistinct" : 4}]', 'pg_ndistinct');

SELECT count(*) FROM (SELECT * FROM pg_input_error_info('[{"ndistinct" : 4}]', 'pg_ndistinct')) AS _sub;


Question: What was the total amount donated by individual donors from the US in Q1 2021?

CREATE TABLE donors (id INT, name TEXT, country TEXT, donation FLOAT); INSERT INTO donors (id, name, country, donation) VALUES (1, 'John Doe', 'USA', 500.00), (2, 'Jane Smith', 'Canada', 300.00);

SELECT SUM(donation) FROM donors WHERE country = 'USA' AND donation_date BETWEEN '2021-01-01' AND '2021-03-31';


Question: What is the name of the community health worker who conducted the least number of mental health parity consultations in New York?

CREATE TABLE community_health_workers (id INT, name TEXT, zip TEXT, consultations INT); INSERT INTO community_health_workers (id, name, zip, consultations) VALUES (1, 'John Doe', '10001', 10), (2, 'Jane Smith', '11223', 20); CREATE VIEW ny_workers AS SELECT * FROM community_health_workers WHERE zip BETWEEN '10001' AND '11999';

SELECT name FROM ny_workers WHERE consultations = (SELECT MIN(consultations) FROM ny_workers);


Question: Determine the total revenue for each strain, including those with no sales.

CREATE TABLE Strains (id INT, name TEXT, price DECIMAL); INSERT INTO Strains (id, name, price) VALUES (1, 'Purple Haze', 12.50), (2, 'Blue Dream', 14.25), (3, 'Girl Scout Cookies', 15.00), (4, 'OG Kush', 16.00), (5, 'Sour Diesel', 13.75); CREATE TABLE Sales (id INT, strain_id INT, quantity INT, sale_date DATE); INSERT INTO Sales (id, strain_id, quantity, sale_date) VALUES (1, 1, 50, '2022-01-01'), (2, 1, 75, '2022-01-05'), (3, 2, 60, '2022-01-03'), (4, 2, 40, '2022-01-07'), (5, 4, 100, '2022-01-06');

SELECT Strains.name, COALESCE(SUM(Strains.price * Sales.quantity), 0) as total_revenue FROM Strains LEFT JOIN Sales ON Strains.id = Sales.strain_id GROUP BY Strains.name;


Question: Which space telescope has the largest primary mirror?

CREATE TABLE space_telescopes (name TEXT, primary_mirror_m INTEGER); INSERT INTO space_telescopes (name, primary_mirror_m) VALUES ('Hubble Space Telescope', 2400), ('James Webb Space Telescope', 6500), ('Spitzer Space Telescope', 850);

SELECT name FROM space_telescopes ORDER BY primary_mirror_m DESC LIMIT 1;


Question: What is the total cost of ingredients for vegan dishes, updated to reflect the current inventory levels?

CREATE TABLE ingredients (id INT, ingredient_name TEXT, unit_price DECIMAL, quantity INT);

SELECT SUM(unit_price * quantity) FROM ingredients WHERE ingredient_name IN (SELECT ingredient_name FROM menu_items WHERE is_vegan = TRUE);


Question: Generate PostgreSQL SQL for: What was the least amount for Goals Olimpia?

CREATE TABLE table_13688489_1 (goals_olimpia INTEGER)

SELECT MIN(goals_olimpia) FROM table_13688489_1;


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

SELECT 'xAb' ~* '[W-Y]' COLLATE PG_C_UTF8;

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

SELECT count(*) FROM (SELECT 'xAb' ~* '[W-Y]' COLLATE PG_C_UTF8) AS _sub;


Question: Which dams are located in 'Texas' and their respective construction costs from the 'dams' and 'dam_construction_costs' tables?

CREATE TABLE dams (id INT, name VARCHAR(255), location VARCHAR(255)); CREATE TABLE dam_construction_costs (dam_id INT, cost DECIMAL(10, 2));

SELECT d.name, dcc.cost as construction_cost FROM dams d INNER JOIN dam_construction_costs dcc ON d.id = dcc.dam_id WHERE d.location = 'Texas';


Question: What is the maximum salary paid to a worker in the workforce development sector?

CREATE TABLE workers (worker_id INT, sector VARCHAR(255), salary DECIMAL(10,2)); INSERT INTO workers (worker_id, sector, salary) VALUES (1, 'Workforce Development', 80000.00), (2, 'Workforce Development', 85000.00), (3, 'Workforce Development', 70000.00);

SELECT MAX(salary) FROM workers WHERE sector = 'Workforce Development';


Question: Show an example of PostgreSQL CREATE TRIGGER (example 4).

CREATE TRIGGER log_update AFTER UPDATE ON accounts FOR EACH ROW WHEN (OLD.* IS DISTINCT FROM NEW.*) EXECUTE FUNCTION log_account_update();

Explanation: PostgreSQL CREATE TRIGGER command.


Question: Add a new department to the "departments" table

CREATE TABLE departments (id INT, department VARCHAR(50));

INSERT INTO departments (id, department) VALUES (5, 'Diversity & Inclusion');


Question: Generate PostgreSQL SQL for: Which Goals have Games smaller than 41, and a Player of mark amos?

CREATE TABLE table_name_57 (goals INTEGER, games VARCHAR, player VARCHAR)

SELECT MIN(goals) FROM table_name_57 WHERE games < 41 AND player = 'mark amos';


Question: List all community groups that Officer 007 has interacted with in the last month

CREATE TABLE community_groups (id SERIAL PRIMARY KEY, name VARCHAR(255)); CREATE TABLE officer_details (id SERIAL PRIMARY KEY, name VARCHAR(255), badge_number INTEGER); CREATE TABLE community_interaction (id SERIAL PRIMARY KEY, community_group_id INTEGER, officer_id INTEGER, interaction_type VARCHAR(255), interaction_timestamp TIMESTAMP); INSERT INTO community_groups (name) VALUES ('Neighborhood Watch'), ('Youth Council'), ('Senior Citizens Club'); INSERT INTO officer_details (name, badge_number) VALUES ('John Doe', 7), ('Jane Smith', 8); INSERT INTO community_interaction (community_group_id, officer_id, interaction_type, interaction_timestamp) VALUES (1, 7, 'Meeting', '2023-03-15 10:00:00'), (2, 8, 'Presentation', '2023-03-20 14:00:00');

SELECT cg.name FROM community_groups cg JOIN community_interaction ci ON cg.id = ci.community_group_id JOIN officer_details od ON od.id = ci.officer_id WHERE od.badge_number = 7 AND ci.interaction_timestamp >= (CURRENT_DATE - INTERVAL '1 month');


Question: Determine the AI safety algorithms that have at least one transaction but are not included in any AI bias mitigation transaction lists.

CREATE TABLE ai_safety_algorithms_2 (id INT, algorithm_name VARCHAR(30)); INSERT INTO ai_safety_algorithms_2 (id, algorithm_name) VALUES (1, 'SafeAI 1.1'); INSERT INTO ai_safety_algorithms_2 (id, algorithm_name) VALUES (2, 'SafeAI 2.1'); INSERT INTO ai_safety_algorithms_2 (id, algorithm_name) VALUES (3, 'SafeAI 3.1'); INSERT INTO ai_safety_algorithms_2 (id, algorithm_name) VALUES (4, 'SafeAI 4.1'); CREATE TABLE ai_bias_mitigation_transaction_lists (algorithm_id INT); INSERT INTO ai_bias_mitigation_transaction_lists (algorithm_id) VALUES (1); INSERT INTO ai_bias_mitigation_transaction_lists (algorithm_id) VALUES (3);

SELECT algorithm_name FROM ai_safety_algorithms_2 WHERE id IN (SELECT id FROM transactions) AND id NOT IN (SELECT algorithm_id FROM ai_bias_mitigation_transaction_lists);


Question: What is the change in CO2 emissions for each mine over time?

CREATE TABLE environmental_impact (id INT, mine_id INT, impact_type VARCHAR(50), value INT, PRIMARY KEY (id), FOREIGN KEY (mine_id) REFERENCES mines(id)); INSERT INTO environmental_impact (id, mine_id, impact_type, value) VALUES (1, 1, 'CO2 Emissions', 1200); INSERT INTO environmental_impact (id, mine_id, impact_type, value) VALUES (2, 1, 'CO2 Emissions', 1250); INSERT INTO environmental_impact (id, mine_id, impact_type, value) VALUES (3, 2, 'CO2 Emissions', 2000); INSERT INTO environmental_impact (id, mine_id, impact_type, value) VALUES (4, 2, 'CO2 Emissions', 2100); CREATE TABLE mines (id INT, name VARCHAR(50), location VARCHAR(50), annual_production INT, PRIMARY KEY (id)); INSERT INTO mines (id, name, location, annual_production) VALUES (1, 'Golden Mine', 'California', 15000); INSERT INTO mines (id, name, location, annual_production) VALUES (2, 'Silver Mine', 'Nevada', 22000);

SELECT mine_id, impact_type, value, LAG(value) OVER (PARTITION BY mine_id ORDER BY id) as previous_value FROM environmental_impact;


Question: What is the total number of legal service providers and the number of providers offering services in Spanish, by state?

CREATE TABLE legal_service_providers (id INT, state VARCHAR(50), offers_spanish_services BOOLEAN);

SELECT state, COUNT(*) total_providers, SUM(CASE WHEN offers_spanish_services = TRUE THEN 1 ELSE 0 END) AS providers_spanish_services FROM legal_service_providers GROUP BY state;


Question: Generate PostgreSQL SQL for: What is the sum of golds for ranks of 6 and totals over 3?

CREATE TABLE table_name_36 (gold INTEGER, rank VARCHAR, total VARCHAR)

SELECT SUM(gold) FROM table_name_36 WHERE rank = '6' AND total > 3;


Question: Generate PostgreSQL SQL for: What high school did Jeff Malm attend?

CREATE TABLE table_11677100_15 (school VARCHAR, player VARCHAR)

SELECT school FROM table_11677100_15 WHERE player = 'Jeff Malm';


Question: What is the average carbon footprint of travelers from each continent visiting sustainable destinations?

CREATE TABLE continents (continent_name VARCHAR(50), country_code CHAR(3));CREATE TABLE travelers (traveler_id INT, country_code CHAR(3), carbon_footprint INT);CREATE TABLE destinations (destination_id INT, destination_name VARCHAR(100), is_sustainable BOOLEAN);CREATE TABLE visits (visit_id INT, traveler_id INT, destination_id INT);INSERT INTO continents (continent_name, country_code) VALUES ('North America', 'USA'), ('North America', 'CAN'), ('Europe', 'DEU'), ('Europe', 'GBR'), ('Asia', 'CHN'), ('Africa', 'ZAF'), ('Oceania', 'AUS');

SELECT c.continent_name, AVG(t.carbon_footprint) FROM continents c JOIN (SELECT traveler_id, carbon_footprint FROM travelers t JOIN visits v ON t.traveler_id = v.traveler_id WHERE v.destination_id IN (SELECT destination_id FROM destinations d WHERE d.is_sustainable = TRUE)) subquery ON c.country_code = subquery.country_code GROUP BY c.continent_name;


Question: How many properties in each borough have a SustainabilityRating of at least 2?

CREATE TABLE Properties (PropertyID int, Price int, Borough varchar(255), SustainabilityRating int); INSERT INTO Properties (PropertyID, Price, Borough, SustainabilityRating) VALUES (1, 350000, 'Manhattan', 2);

SELECT Borough, COUNT(*) as PropertyCount FROM Properties WHERE SustainabilityRating >= 2 GROUP BY Borough;


Question: PostgreSQL regression test 'cluster': Write the SELECT query (example 117).

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

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


Question: Delete a product from the "products" table

CREATE TABLE products (product_id INT, name VARCHAR(255), category VARCHAR(255), price DECIMAL(5,2));

DELETE FROM products WHERE product_id = 1001;


Question: What is the name of the disability support programs offered in a specific state?

CREATE TABLE States (StateID INT, State VARCHAR(50)); INSERT INTO States (StateID, State) VALUES (1, 'California'); INSERT INTO States (StateID, State) VALUES (2, 'Texas');

SELECT SupportPrograms.ProgramName FROM SupportPrograms INNER JOIN States ON SupportPrograms.StateID = States.StateID WHERE States.State = 'California';


Question: Add sales data for the month of January 2022

CREATE TABLE sales (id INT PRIMARY KEY, product VARCHAR(255), quantity INT, sale_date DATE); INSERT INTO sales (id, product, quantity, sale_date) VALUES (1, 'Sativa Flower', 25, '2022-01-01');

INSERT INTO sales (id, product, quantity, sale_date) VALUES (2, 'Indica Flower', 30, '2022-01-05'); INSERT INTO sales (id, product, quantity, sale_date) VALUES (3, 'Hybrid Flower', 35, '2022-01-10');


Question: How many tree species have a total volume greater than 1000 cubic meters in the boreal forest?

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, volume FLOAT, FOREIGN KEY (biome_id) REFERENCES biomes(biome_id)); INSERT INTO trees (tree_id, species, biome_id, volume) VALUES (1, 'Norway Spruce', 3, 500.0), (2, 'Scots Pine', 3, 750.0), (3, 'Birch', 3, 450.0);

SELECT COUNT(DISTINCT species) FROM trees JOIN biomes ON trees.biome_id = biomes.biome_id GROUP BY biomes.name HAVING SUM(trees.volume) > 1000;


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

create view vv5 as select x,y,z from tt9 join tt10 using(x);

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


Question: Generate PostgreSQL SQL for: In the game resulting in a 5-11 record, who scored the high rebounds?

CREATE TABLE table_17118657_8 (high_rebounds VARCHAR, record VARCHAR)

SELECT high_rebounds FROM table_17118657_8 WHERE record = '5-11';


Question: What is the percentage of community health workers who identify as Hispanic or Latino by state?

CREATE TABLE States (state_id INT, state_name TEXT); CREATE TABLE CommunityHealthWorkers (worker_id INT, worker_ethnicity TEXT, state_id INT);

SELECT COUNT(*) FILTER (WHERE worker_ethnicity = 'Hispanic or Latino') * 100.0 / COUNT(*) as pct_hispanic_workers, s.state_name FROM CommunityHealthWorkers chw JOIN States s ON chw.state_id = s.state_id GROUP BY s.state_id;


Question: List all unions with their corresponding headquarters' addresses.

CREATE TABLE if not exists unions (union_id INT, union_name TEXT, headquarters_address TEXT); INSERT INTO unions (union_id, union_name, headquarters_address) VALUES (1, 'United Steelworkers', '60 Boulevard of the Allies, Pittsburgh, PA 15222'), (2, 'Teamsters', '25 Louisiana Ave NW, Washington, DC 20001'), (3, 'UAW', '8000 E Jefferson Ave, Detroit, MI 48214');


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

select unnest(array(select '11 22 33'::int2vector from generate_series(1,5)));

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

SELECT count(*) FROM (select unnest(array(select '11 22 33'::int2vector from generate_series(1,5)))) AS _sub;


Question: Generate PostgreSQL SQL for: What is the average round of the match in the Hero's 9 event with a time of 5:00?

CREATE TABLE table_name_7 (round INTEGER, time VARCHAR, event VARCHAR)

SELECT AVG(round) FROM table_name_7 WHERE time = '5:00' AND event = 'hero's 9';


Question: Generate PostgreSQL SQL for: Count the number of trips that did not end in San Francisco city.

CREATE TABLE trip (end_station_id VARCHAR); CREATE TABLE station (id VARCHAR, city VARCHAR)

SELECT COUNT(*) FROM trip AS T1 JOIN station AS T2 ON T1.end_station_id = T2.id WHERE T2.city <> "San Francisco";


Question: pgTAP test for Ruletap (assertion 16).

SELECT * FROM check_test(
    has_rule( 'sometab', 'ins_me', 'whatever' ),
    true,
    'has_rule(table, rule, desc)',
    'whatever',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Ruletap.


Question: Generate PostgreSQL SQL for: What is the overall score when the set 2 score is 25–18?

CREATE TABLE table_name_57 (score VARCHAR, set_2 VARCHAR)

SELECT score FROM table_name_57 WHERE set_2 = '25–18';


Question: What are the earliest and latest departure times for trams in the suburbs?

CREATE TABLE schedules (route_id INT, vehicle_id INT, departure_time TIME); INSERT INTO schedules VALUES (1, 1, '06:00:00'), (1, 2, '06:15:00'), (1, 3, '06:30:00'), (2, 4, '07:00:00'), (2, 5, '07:15:00'); CREATE TABLE routes (route_id INT, city VARCHAR(50), type VARCHAR(50)); INSERT INTO routes VALUES (1, 'City Center', 'Bus'), (2, 'Suburbs', 'Tram');

SELECT MIN(departure_time) AS earliest, MAX(departure_time) AS latest FROM schedules JOIN routes ON schedules.route_id = routes.route_id WHERE routes.city = 'Suburbs' AND routes.type = 'Tram';


Question: Generate PostgreSQL SQL for: Name the gold for silver of 39

CREATE TABLE table_name_56 (gold VARCHAR, silver VARCHAR)

SELECT gold FROM table_name_56 WHERE silver = 39;


Question: What is the total number of hours played by all players in Valorant?

CREATE TABLE players (id INT, name VARCHAR(50), age INT, game VARCHAR(50), hours_played INT); INSERT INTO players (id, name, age, game, hours_played) VALUES (1, 'John Doe', 25, 'Valorant', 50);

SELECT SUM(hours_played) AS total_hours FROM players WHERE game = 'Valorant';


Question: What is the number of public libraries in Seattle, Washington that offer free Wi-Fi access?

CREATE TABLE public_libraries (library_id INT, library_name TEXT, city TEXT, state TEXT, wi_fi_access BOOLEAN); INSERT INTO public_libraries (library_id, library_name, city, state, wi_fi_access) VALUES (1, 'Seattle Central Library', 'Seattle', 'Washington', TRUE); INSERT INTO public_libraries (library_id, library_name, city, state, wi_fi_access) VALUES (2, 'The Seattle Public Library - Ballard Branch', 'Seattle', 'Washington', TRUE); INSERT INTO public_libraries (library_id, library_name, city, state, wi_fi_access) VALUES (3, 'The Seattle Public Library - Green Lake Branch', 'Seattle', 'Washington', FALSE);

SELECT COUNT(*) FROM public_libraries WHERE city = 'Seattle' AND state = 'Washington' AND wi_fi_access = TRUE;


Question: What is the total yield of crops by country in 'crop_distribution' table?

CREATE TABLE crop_distribution (country VARCHAR(50), crop VARCHAR(50), yield INT); INSERT INTO crop_distribution (country, crop, yield) VALUES ('Canada', 'corn', 1000), ('Canada', 'wheat', 2000), ('USA', 'corn', 3000), ('USA', 'wheat', 4000), ('Mexico', 'corn', 2500), ('Mexico', 'wheat', 1500); CREATE TABLE country_total (country VARCHAR(50), total INT); INSERT INTO country_total (country, total) SELECT country, SUM(yield) FROM crop_distribution GROUP BY country;

SELECT ct.country, ct.total FROM country_total ct;


Question: Generate PostgreSQL SQL for: with delivery date 1997 1997 what is the owns?

CREATE TABLE table_name_65 (owns VARCHAR, delivery_date VARCHAR)

SELECT owns FROM table_name_65 WHERE delivery_date = '1997 1997';


Question: Generate PostgreSQL SQL for: Which Marriage has a Became Duchess of 12 december 1666?

CREATE TABLE table_name_68 (marriage VARCHAR, became_duchess VARCHAR)

SELECT marriage FROM table_name_68 WHERE became_duchess = '12 december 1666';


Question: Generate PostgreSQL SQL for: What is the highest number of points the cosworth straight-4 engine scored?

CREATE TABLE table_name_51 (pts INTEGER, engine VARCHAR)

SELECT MAX(pts) FROM table_name_51 WHERE engine = 'cosworth straight-4';


Question: PostgreSQL regression test 'portals': Write the SELECT query (example 288).

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

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


Question: Update the mobile_plans table to add a new plan with a name "Unlimited Data Family Plan" and monthly_cost 80.00

CREATE TABLE mobile_plans (plan_id INT, plan_name VARCHAR(50), monthly_cost DECIMAL(5,2));

UPDATE mobile_plans SET plan_name = 'Unlimited Data Family Plan', monthly_cost = 80.00 WHERE plan_id = (SELECT MAX(plan_id) FROM mobile_plans) + 1;


Question: What is the average design pressure for all dams in the database?

CREATE TABLE Dams (id INT, name VARCHAR(100), design_pressure FLOAT); INSERT INTO Dams (id, name, design_pressure) VALUES (1, 'Hoover Dam', 4500), (2, 'Glen Canyon Dam', 2000), (3, 'Oroville Dam', 3500);


Question: Generate PostgreSQL SQL for: what is the average points when played is less than 16?

CREATE TABLE table_name_55 (points INTEGER, played INTEGER)

SELECT AVG(points) FROM table_name_55 WHERE played < 16;


Question: Generate PostgreSQL SQL for: Please show the categories of the music festivals and the count.

CREATE TABLE music_festival (Category VARCHAR)

SELECT Category, COUNT(*) FROM music_festival GROUP BY Category;


Question: Generate PostgreSQL SQL for: Who had high assists in game number 9?

CREATE TABLE table_27712702_7 (high_assists VARCHAR, game VARCHAR)

SELECT high_assists FROM table_27712702_7 WHERE game = 9;


Question: Generate PostgreSQL SQL for: what's the cover date where character(s) is sandman (wesley dodds)

CREATE TABLE table_1217448_1 (cover_date VARCHAR, character_s_ VARCHAR)

SELECT cover_date FROM table_1217448_1 WHERE character_s_ = 'Sandman (Wesley Dodds)';


Question: What is the number of unique users who have streamed a specific song?

CREATE TABLE StreamingData (StreamID INT, UserID INT, SongID INT, StreamDate DATE); INSERT INTO StreamingData VALUES (1, 1, 1001, '2022-01-01'); INSERT INTO StreamingData VALUES (2, 2, 1002, '2022-01-02'); CREATE TABLE Songs (SongID INT, SongName VARCHAR(100), ArtistID INT); INSERT INTO Songs VALUES (1001, 'Shake It Off', 1); INSERT INTO Songs VALUES (1002, 'Dynamite', 1); CREATE TABLE Users (UserID INT, UserName VARCHAR(50)); INSERT INTO Users VALUES (1, 'Alice'); INSERT INTO Users VALUES (2, 'Bob');

SELECT COUNT(DISTINCT UserID) FROM StreamingData JOIN Songs ON StreamingData.SongID = Songs.SongID WHERE Songs.SongName = 'Shake It Off';


Question: Insert a new row into the 'vehicle_sales' table with the following values: 'Mahindra', 'Mumbai', 45

CREATE TABLE vehicle_sales (vehicle_make VARCHAR(255), city VARCHAR(255), sales_count INT);

INSERT INTO vehicle_sales (vehicle_make, city, sales_count) VALUES ('Mahindra', 'Mumbai', 45);


Question: Generate PostgreSQL SQL for: What is the sum of number of bearers in 2009 for a rank above 1, a type of patronymic, an etymology meaning son of Christian, and the number of bearers in 1971 greater than 45.984?

CREATE TABLE table_name_3 (number_of_bearers_2009 INTEGER, number_of_bearers_1971 VARCHAR, etymology VARCHAR, rank VARCHAR, type VARCHAR)

SELECT SUM(number_of_bearers_2009) FROM table_name_3 WHERE rank > 1 AND type = 'patronymic' AND etymology = 'son of christian' AND number_of_bearers_1971 > 45.984;


Question: Generate PostgreSQL SQL for: Which tournament had a score of 6–3, 7–6?

CREATE TABLE table_name_75 (tournament VARCHAR, score VARCHAR)

SELECT tournament FROM table_name_75 WHERE score = '6–3, 7–6';


Question: Delete retailers that have not made a purchase in the last year

CREATE TABLE retailers(retailer_id INT, name TEXT, last_purchase_date DATE); INSERT INTO retailers(retailer_id, name, last_purchase_date) VALUES (101, 'Retailer A', '2021-12-01'), (102, 'Retailer B', '2022-02-15'), (103, 'Retailer C', NULL), (104, 'Retailer D', '2022-03-01');

DELETE FROM retailers WHERE last_purchase_date < (CURRENT_DATE - INTERVAL '1 year');


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

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


Question: Generate PostgreSQL SQL for: What is the release date for the standard cd release format in north america?

CREATE TABLE table_name_18 (release_date VARCHAR, release_format VARCHAR, country VARCHAR)

SELECT release_date FROM table_name_18 WHERE release_format = 'standard cd' AND country = 'north america';


Question: What is the total number of ads served to users in the United States and Canada, broken down by day, for the past week?

CREATE TABLE ads_served (user_id INT, ad_id INT, country VARCHAR(2), serving_date DATE); INSERT INTO ads_served (user_id, ad_id, country, serving_date) VALUES (1, 1001, 'US', '2022-03-01'), (2, 1002, 'CA', '2022-03-02');

SELECT serving_date, COUNT(*) as total_ads FROM ads_served WHERE country IN ('US', 'CA') GROUP BY serving_date ORDER BY serving_date DESC LIMIT 7;


Question: Generate PostgreSQL SQL for: I want the name for rank less than 6 and year more than 1974

CREATE TABLE table_name_75 (name VARCHAR, rank VARCHAR, year VARCHAR)

SELECT name FROM table_name_75 WHERE rank < 6 AND year > 1974;


Question: Generate PostgreSQL SQL for: How many regions had an hdi of 0.896?

CREATE TABLE table_25042332_33 (combined_gross_enrollment_ratio__2009_ VARCHAR, hdi VARCHAR)

SELECT COUNT(combined_gross_enrollment_ratio__2009_) FROM table_25042332_33 WHERE hdi = '0.896';


Question: What is the total billing amount for cases handled by attorneys who identify as female?

CREATE TABLE Attorneys (AttorneyID INT, Gender VARCHAR(255)); INSERT INTO Attorneys (AttorneyID, Gender) VALUES (1, 'Female'), (2, 'Male'), (3, 'Female'), (4, 'Non-binary'); CREATE TABLE Cases (CaseID INT, AttorneyID INT, BillingAmount DECIMAL(10,2)); INSERT INTO Cases (CaseID, AttorneyID, BillingAmount) VALUES (1, 1, 5000.00), (2, 1, 7000.00), (3, 2, 3000.00), (4, 3, 8000.00), (5, 3, 9000.00);

SELECT SUM(BillingAmount) FROM Cases JOIN Attorneys ON Cases.AttorneyID = Attorneys.AttorneyID WHERE Gender = 'Female';


Question: What is the average age of patients who had positive outcomes after CBT treatment?

CREATE TABLE patients (patient_id INT, age INT, treatment_outcome VARCHAR(10)); INSERT INTO patients (patient_id, age, treatment_outcome) VALUES (1, 30, 'positive'), (2, 45, 'negative'), (3, 50, 'positive'); CREATE TABLE treatments (treatment_id INT, treatment_name VARCHAR(10), patient_id INT); INSERT INTO treatments (treatment_id, treatment_name, patient_id) VALUES (1, 'CBT', 1), (2, 'CBT', 2), (3, 'CBT', 3);

SELECT AVG(patients.age) FROM patients JOIN treatments ON patients.patient_id = treatments.patient_id WHERE treatments.treatment_name = 'CBT' AND patients.treatment_outcome = 'positive';


Question: Update the name of the character with id 3 to 'New Character Name' in the 'characters' table

CREATE TABLE characters (id INT, name TEXT, show_id INT);

UPDATE characters SET name = 'New Character Name' WHERE id = 3;


Question: Generate PostgreSQL SQL for: When the number of gold medals is greater than 59, and the rank is total, what is the average bronze medals?

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

SELECT AVG(bronze) FROM table_name_89 WHERE rank = 'total' AND gold > 59;


Question: Delete the "hotel_review_summary" view

CREATE TABLE hotel_reviews (hotel_id INT, review_date DATE, review_score INT); CREATE VIEW hotel_review_summary AS SELECT hotel_id, COUNT(*), AVG(review_score) FROM hotel_reviews GROUP BY hotel_id;


Question: Delete workouts that have a duration longer than 2 hours for members with a Basic membership tier in the last month.

CREATE TABLE workouts (workout_id INT, member_id INT, duration INT, date DATE); INSERT INTO workouts VALUES (10,14,130,'2022-03-05'); INSERT INTO workouts VALUES (11,15,150,'2022-03-10'); CREATE TABLE members (member_id INT, tier VARCHAR(10)); INSERT INTO members VALUES (14,'Basic'); INSERT INTO members VALUES (15,'Premium');

DELETE FROM workouts WHERE workouts.duration > 120 AND workouts.date >= DATEADD(month, -1, GETDATE()) AND EXISTS (SELECT 1 FROM members WHERE members.member_id = workouts.member_id AND members.tier = 'Basic');


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

CREATE FUNCTION gbt_macad8_penalty(internal,internal,internal)
RETURNS internal
AS 'MODULE_PATHNAME'
LANGUAGE C IMMUTABLE STRICT;

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


Question: Generate PostgreSQL SQL for: Tell me the goals for score of 38-28

CREATE TABLE table_name_54 (goals VARCHAR, score VARCHAR)

SELECT goals FROM table_name_54 WHERE score = '38-28';


Question: List all financial capability programs in the Caribbean and Central America with a budget greater than $15,000.

CREATE TABLE capability_programs (id INT, region VARCHAR(20), budget DECIMAL(10,2)); INSERT INTO capability_programs (id, region, budget) VALUES (1, 'Caribbean', 12000.00), (2, 'Central America', 18000.00), (3, 'Europe', 9000.00);

SELECT * FROM capability_programs WHERE region IN ('Caribbean', 'Central America') AND budget > 15000.00;


Question: Find articles with the word 'investigation' in the 'category' column.

CREATE TABLE articles (id INT, title VARCHAR(100), content TEXT, category VARCHAR(50), publication_date DATE); INSERT INTO articles (id, title, content, category, publication_date) VALUES (1, 'Article...', '...', 'investigation', '2022-03-01');

SELECT * FROM articles WHERE category LIKE '%investigation%';


Question: What is the total number of electric ferries in Oslo and their total passenger capacity?

CREATE TABLE electric_ferries (ferry_id INT, passenger_capacity INT, city VARCHAR(50));

SELECT COUNT(*), SUM(passenger_capacity) FROM electric_ferries WHERE city = 'Oslo';


Question: pgTAP test for Ownership (assertion 92).

SELECT * FROM check_test(
    function_owner_is('test_fdw', '{}'::NAME[], current_user),
	true,
    'function_owner_is(function, args[], user)',
    'Function test_fdw() should be owned by ' || quote_ident(current_user),
    ''
);

Explanation: SQL assertion from pgTAP test suite for Ownership.


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

SELECT cube_ll_coord(ll_to_earth(0,-180),1)::numeric(20,5),
 cube_ll_coord(ll_to_earth(0,-180),2)::numeric(20,5),
 cube_ll_coord(ll_to_earth(0,-180),3)::numeric(20,5);

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


Question: PL/pgSQL test: Pltclu--1.0 (example 2).

CREATE LANGUAGE pltclu
  HANDLER pltclu_call_handler;

Explanation: PL/pgSQL example from PostgreSQL source test for Pltclu--1.0.


Question: How many defense contracts were awarded each month in 2020?

SELECT EXTRACT(MONTH FROM ContractDate) AS Month, COUNT(*) FROM ContractMonths WHERE ContractDate BETWEEN '2020-01-01' AND '2020-12-31' GROUP BY Month ORDER BY Month;


Question: Generate PostgreSQL SQL for: What is total number of wins for England?

CREATE TABLE table_name_59 (total INTEGER, nation VARCHAR)

SELECT SUM(total) FROM table_name_59 WHERE nation = 'england';


Question: Update the 'battery_range' column for the 'Tesla_Model_S' row to 405 miles

CREATE TABLE vehicle_stats (vehicle_make VARCHAR(255), vehicle_model VARCHAR(255), battery_range FLOAT);

UPDATE vehicle_stats SET battery_range = 405 WHERE vehicle_make = 'Tesla' AND vehicle_model = 'Model S';


Question: What is the average population of marine species in the Indian Ocean?

CREATE TABLE marine_species_indian (name VARCHAR(255), region VARCHAR(255), population INT); INSERT INTO marine_species_indian (name, region, population) VALUES ('Manta Ray', 'Indian', 500), ('Whale Shark', 'Indian', 1000);

SELECT AVG(population) FROM marine_species_indian WHERE region = 'Indian';


Question: Insert a new record into the menu_items table for item_name 'Tofu Stir Fry' with price set to 11.99

CREATE TABLE menu_items (item_name VARCHAR(255), price DECIMAL(5,2));

INSERT INTO menu_items (item_name, price) VALUES ('Tofu Stir Fry', 11.99);


Question: Generate PostgreSQL SQL for: How many totals have 1 gold and a rank smaller than 2?

CREATE TABLE table_name_32 (total VARCHAR, gold VARCHAR, rank VARCHAR)

SELECT COUNT(total) FROM table_name_32 WHERE gold = 1 AND rank < 2;


Question: Generate PostgreSQL SQL for: Which terminations correspond with headphone model SR80I?

CREATE TABLE table_1601027_1 (termination VARCHAR, headphone_model VARCHAR)

SELECT termination FROM table_1601027_1 WHERE headphone_model = 'SR80i';


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

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


Question: What are the names and balances of all digital assets that are of type 'ERC20' or 'ERC721'?

CREATE TABLE digital_assets (name TEXT, balance INTEGER, type TEXT); INSERT INTO digital_assets (name, balance, type) VALUES ('Asset1', 100, 'ERC20'), ('Asset2', 200, 'ERC721');

SELECT name, balance FROM digital_assets WHERE type IN ('ERC20', 'ERC721');


Question: Generate PostgreSQL SQL for: What date has a Decision of osgood, and a Score of 3 – 4?

CREATE TABLE table_name_63 (date VARCHAR, decision VARCHAR, score VARCHAR)

SELECT date FROM table_name_63 WHERE decision = 'osgood' AND score = '3 – 4';


Question: What is the price of the most expensive garment in the 'Fall 2022' collection?

CREATE TABLE garment_prices (collection VARCHAR(20), garment_name VARCHAR(30), price INT); INSERT INTO garment_prices (collection, garment_name, price) VALUES ('Fall 2022', 'Cashmere Sweater', 300);

SELECT collection, MAX(price) FROM garment_prices GROUP BY collection;


Question: What is the total number of farmers who received training in the last 2 years from the 'Capacity Building' program in the 'ruraldev' schema?

CREATE TABLE ruraldev.farmers (id INT, name VARCHAR(50), training_program VARCHAR(50), training_year INT); INSERT INTO ruraldev.farmers (id, name, training_program, training_year) VALUES (1, 'John Doe', 'Capacity Building', 2020), (2, 'Jane Smith', 'Soil Conservation', 2019), (3, 'Raj Patel', 'Capacity Building', 2021);

SELECT COUNT(*) FROM ruraldev.farmers WHERE training_program = 'Capacity Building' AND training_year >= 2020;


Question: What is the average age of students who have taken a course on lifelong learning?

CREATE TABLE Students (StudentID INT, Age INT, Gender VARCHAR(10), CoursesTaken VARCHAR(20)); INSERT INTO Students (StudentID, Age, Gender, CoursesTaken) VALUES (1, 22, 'Male', 'Lifelong Learning'); INSERT INTO Students (StudentID, Age, Gender, CoursesTaken) VALUES (2, 20, 'Female', 'Open Pedagogy'); INSERT INTO Students (StudentID, Age, Gender, CoursesTaken) VALUES (3, 25, 'Male', 'Lifelong Learning'); INSERT INTO Students (StudentID, Age, Gender, CoursesTaken) VALUES (4, 23, 'Female', 'Lifelong Learning');

SELECT AVG(Age) FROM Students WHERE CoursesTaken = 'Lifelong Learning';


Question: Generate PostgreSQL SQL for: WHAT IS THE WORST SCORE WHEN THE BEST SCORE WAS 8.8 AND AVERAGE WAS LARGER THAN 6.2?

CREATE TABLE table_name_72 (worst_score VARCHAR, best_score VARCHAR, average VARCHAR)

SELECT COUNT(worst_score) FROM table_name_72 WHERE best_score = 8.8 AND average > 6.2;


Question: PostgreSQL regression test 'int8': Write the SELECT query (example 11).

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

SELECT count(*) FROM (SELECT pg_input_is_valid('10000000000000000000', 'int8')) AS _sub;


Question: List all pollution control initiatives and their respective budgets.

CREATE TABLE pollution_control_initiatives (initiative_id INT, name TEXT, budget INT); INSERT INTO pollution_control_initiatives (initiative_id, name, budget) VALUES (1, 'Project A', 100000), (2, 'Project B', 250000), (3, 'Project C', 180000);

SELECT name, budget FROM pollution_control_initiatives;