Question: Generate PostgreSQL SQL for: meadowlands sports complex is the circuit at which city/location?

CREATE TABLE table_10707142_2 (city_location VARCHAR, circuit VARCHAR)

SELECT city_location FROM table_10707142_2 WHERE circuit = 'Meadowlands Sports Complex';


Question: How many traditional arts are practiced in Europe?

CREATE TABLE traditional_arts (id INT, name TEXT, type TEXT, region TEXT); INSERT INTO traditional_arts (id, name, type, region) VALUES (1, 'Catalan Castells', 'Construction', 'Europe');

SELECT COUNT(*) FROM traditional_arts WHERE region = 'Europe';


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

INSERT INTO TIMESTAMP_TBL VALUES ('Feb 16 17:32:01 0097 BC');

Explanation: DML from PostgreSQL core regression test for Timestamp.


Question: How many cybersecurity incidents were reported in each region in 2020?

CREATE TABLE CybersecurityIncidents (id INT, region VARCHAR(255), year INT, description TEXT); INSERT INTO CybersecurityIncidents (id, region, year, description) VALUES (1, 'North America', 2020, 'Incident 1'), (2, 'Europe', 2019, 'Incident 2'), (3, 'Asia', 2020, 'Incident 3');

SELECT region, YEAR(datetime) AS year, COUNT(*) FROM CybersecurityIncidents WHERE year = 2020 GROUP BY region;


Question: Write the DML statement from PostgreSQL regression test 'timestamptz' (example 101).

INSERT INTO TIMESTAMPTZ_TBL VALUES ('Feb 28 17:32:01 1996');

Explanation: DML from PostgreSQL core regression test for Timestamptz.


Question: Generate PostgreSQL SQL for: What is the name of Richmond's home venue?

CREATE TABLE table_name_45 (venue VARCHAR, home_team VARCHAR)

SELECT venue FROM table_name_45 WHERE home_team = 'richmond';


Question: Show an example of PostgreSQL SELECT (example 14).

Explanation: PostgreSQL SELECT command.


Question: Calculate the total fuel efficiency for vessels with successful inspections in the "vessel_summary" view.

CREATE VIEW vessel_summary AS SELECT vessel_id, AVG(avg_speed) AS average_speed, SUM(fuel_efficiency) AS total_fuel_efficiency, COUNT(*) FILTER (WHERE result = 'PASS') AS successful_inspections FROM vessel_performance JOIN safety_records ON vessel_performance.vessel_id = safety_records.vessel_id GROUP BY vessel_id;

SELECT vessel_id, SUM(total_fuel_efficiency) FROM vessel_summary WHERE successful_inspections IS NOT NULL GROUP BY vessel_id;


Question: PostgreSQL regression test 'rowtypes': Write the SELECT query (example 18).

select f1, q.c1 from quadtable;		-- fails, q is a table reference

select f1, (q).c1, (qq.q).c1.i from quadtable qq;

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

SELECT count(*) FROM (select f1, q.c1 from quadtable;		-- fails, q is a table reference

select f1, (q).c1, (qq.q).c1.i from quadtable qq) AS _sub;


Question: Generate PostgreSQL SQL for: what is the total number of reasons for change where the date the successor was seated is june 8, 1876?

CREATE TABLE table_2192067_4 (reason_for_change VARCHAR, date_successor_seated VARCHAR)

SELECT COUNT(reason_for_change) FROM table_2192067_4 WHERE date_successor_seated = 'June 8, 1876';


Question: How many athletes participated in wellbeing programs in 2021?

CREATE TABLE wellbeing (id INT, athlete_id INT, year INT, program_type VARCHAR(255)); INSERT INTO wellbeing (id, athlete_id, year, program_type) VALUES (1, 1, 2021, 'Yoga'); INSERT INTO wellbeing (id, athlete_id, year, program_type) VALUES (2, 2, 2020, 'Meditation');

SELECT COUNT(*) FROM wellbeing WHERE year = 2021;


Question: List all players who have not played any FPS games

CREATE TABLE Players (PlayerID INT, PlayedFPS BOOLEAN); INSERT INTO Players (PlayerID, PlayedFPS) VALUES (1, FALSE); INSERT INTO Players (PlayerID, PlayedFPS) VALUES (2, TRUE);

SELECT * FROM Players WHERE PlayedFPS = FALSE;


Question: List all the government buildings and their respective agencies in the state of Texas from the 'tx_government_database'

CREATE TABLE tx_agencies (id INT PRIMARY KEY, name VARCHAR(255), state VARCHAR(255));CREATE TABLE tx_buildings (id INT PRIMARY KEY, name VARCHAR(255), agency_id INT, FOREIGN KEY (agency_id) REFERENCES tx_agencies(id)); INSERT INTO tx_agencies (id, name, state) VALUES (1, 'Texas Department of Transportation', 'Texas'); INSERT INTO tx_agencies (id, name, state) VALUES (2, 'Texas Parks and Wildlife Department', 'Texas');

SELECT tx_buildings.name as building_name, tx_agencies.name as agency_name FROM tx_buildings INNER JOIN tx_agencies ON tx_buildings.agency_id = tx_agencies.id WHERE tx_agencies.state = 'Texas';


Question: What is the total area covered by marine protected areas in the 'indian_ocean'?

CREATE TABLE marine_protected_areas (name VARCHAR(255), area_size INTEGER, region VARCHAR(255));

SELECT SUM(area_size) FROM marine_protected_areas WHERE region = 'Indian Ocean';


Question: Write the DDL statement from PostgreSQL regression test 'plpgsql' (example 727).

CREATE TRIGGER transition_table_level2_ri_child_upd_trigger
  AFTER UPDATE ON transition_table_level2
  REFERENCING NEW TABLE AS i
  FOR EACH STATEMENT EXECUTE PROCEDURE
    transition_table_level2_ri_child_insupd_func();

Explanation: DDL from PostgreSQL core regression test for Plpgsql.


Question: PostgreSQL regression test 'rowtypes': Write the SELECT query (example 131).

select row(1, 'abc')::testtype3 *<> row(1, 'abd')::testtype3;

SELECT count(*) FROM (select row(1, 'abc')::testtype3 *<> row(1, 'abd')::testtype3) AS _sub;


Question: Generate PostgreSQL SQL for: What is the date of the game with 38,062 people in attendance?

CREATE TABLE table_name_80 (date VARCHAR, attendance VARCHAR)

SELECT date FROM table_name_80 WHERE attendance = '38,062';


Question: What is the minimum mass of spacecrafts manufactured by Orbital Sciences that have been launched?

CREATE TABLE Spacecrafts (id INT, name VARCHAR(100), manufacturer VARCHAR(100), mass FLOAT, launched BOOLEAN); INSERT INTO Spacecrafts (id, name, manufacturer, mass, launched) VALUES (1, 'OrbitalShip 1', 'Orbital Sciences', 1000, true), (2, 'OrbitalShip 2', 'Orbital Sciences', 2000, false);

SELECT MIN(mass) FROM Spacecrafts WHERE manufacturer = 'Orbital Sciences' AND launched = true;


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

SELECT JSON_VALUE(jsonb '"aaa"', '$' RETURNING json ERROR ON ERROR);

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

SELECT count(*) FROM (SELECT JSON_VALUE(jsonb '"aaa"', '$' RETURNING json ERROR ON ERROR)) AS _sub;


Question: What is the average age of all dams in the 'Appalachian' mountain range that were built before 1950?

CREATE TABLE Dams (id INT, name TEXT, mountainRange TEXT, constructionYear INT);

SELECT mountainRange, AVG(YEAR(CURRENT_DATE) - constructionYear) FROM Dams WHERE mountainRange = 'Appalachian' AND constructionYear < 1950 GROUP BY mountainRange;


Question: Update the age of the player with PlayerID 1 to 26.

CREATE TABLE Players (PlayerID INT, Age INT, Gender VARCHAR(10)); INSERT INTO Players VALUES (1,25,'Male'),(2,30,'Female'),(3,35,'Non-binary');

UPDATE Players SET Age = 26 WHERE PlayerID = 1;


Question: List the names and job titles of employees who have not completed diversity training.

CREATE TABLE EmployeeTraining (EmployeeID INT, TrainingID INT, Completed BOOLEAN); CREATE TABLE Employees (EmployeeID INT, EmployeeName TEXT, JobTitle TEXT); CREATE TABLE Trainings (TrainingID INT, TrainingName TEXT); INSERT INTO Employees (EmployeeID, EmployeeName, JobTitle) VALUES (1, 'John Doe', 'Software Engineer'); INSERT INTO Employees (EmployeeID, EmployeeName, JobTitle) VALUES (2, 'Jane Smith', 'Project Manager'); INSERT INTO EmployeeTraining (EmployeeID, TrainingID, Completed) VALUES (1, 1, TRUE); INSERT INTO EmployeeTraining (EmployeeID, TrainingID, Completed) VALUES (2, 1, FALSE); INSERT INTO Trainings (TrainingID, TrainingName) VALUES (1, 'Diversity Training');

SELECT Employees.EmployeeName, Employees.JobTitle FROM Employees INNER JOIN EmployeeTraining ON Employees.EmployeeID = EmployeeTraining.EmployeeID WHERE EmployeeTraining.Completed = FALSE AND EmployeeTraining.TrainingID IN (SELECT Trainings.TrainingID FROM Trainings WHERE Trainings.TrainingName = 'Diversity Training');


Question: Write the DDL statement from PostgreSQL regression test 'rules' (example 419).

create rule "_RETURN" as on select to rules_fooview_part do instead
  select 1 as x, 'aaa'::text as y;

Explanation: DDL from PostgreSQL core regression test for Rules.


Question: Generate PostgreSQL SQL for: What is the home score with marek dupnitsa as opponent?

CREATE TABLE table_name_33 (home VARCHAR, opponent VARCHAR)

SELECT home FROM table_name_33 WHERE opponent = 'marek dupnitsa';


Question: Generate PostgreSQL SQL for: What is the On-air ID with the frequency of 105.9, and purpose of commercial?

CREATE TABLE table_name_24 (on_air_id VARCHAR, frequency VARCHAR, purpose VARCHAR)

SELECT on_air_id FROM table_name_24 WHERE frequency = '105.9' AND purpose = 'commercial';


Question: Generate PostgreSQL SQL for: What is the preliminaries of the contestant with a swimsuit less than 8.948 and an interview of 8.997?

CREATE TABLE table_name_99 (preliminaries VARCHAR, swimsuit VARCHAR, interview VARCHAR)

SELECT preliminaries FROM table_name_99 WHERE swimsuit < 8.948 AND interview = 8.997;


Question: Generate PostgreSQL SQL for: which examples are pronounced et in australian

CREATE TABLE table_17798093_20 (examples VARCHAR, australian VARCHAR)

SELECT examples FROM table_17798093_20 WHERE australian = 'et';


Question: What is the average salary by mine and role?

CREATE TABLE mine (id INT, name VARCHAR(50), location VARCHAR(50)); CREATE TABLE employee (id INT, mine_id INT, gender VARCHAR(10), role VARCHAR(20), salary INT);

SELECT mine.name, employee.role, AVG(employee.salary) FROM employee JOIN mine ON employee.mine_id = mine.id GROUP BY mine.name, employee.role;


Question: Find the number of bike trips per hour for the month of January 2022

CREATE TABLE bike_trips (id INT PRIMARY KEY, trip_time TIMESTAMP, trip_duration INT);

SELECT HOUR(trip_time) AS hour, COUNT(*) AS num_trips FROM bike_trips WHERE trip_time >= '2022-01-01 00:00:00' AND trip_time < '2022-02-01 00:00:00' GROUP BY hour;


Question: Which deep-sea expeditions have discovered new species?

CREATE TABLE deep_sea_expeditions (expedition_id INT, name VARCHAR(100), discovered_new_species BOOLEAN); INSERT INTO deep_sea_expeditions (expedition_id, name, discovered_new_species) VALUES (1, 'Challenger Expedition', TRUE); INSERT INTO deep_sea_expeditions (expedition_id, name, discovered_new_species) VALUES (2, 'Galathea Expedition', FALSE);

SELECT name FROM deep_sea_expeditions WHERE discovered_new_species = TRUE;


Question: How many security incidents were reported from Asia in the last quarter?

CREATE TABLE security_incidents (id INT, region VARCHAR(255), incident_date DATE); INSERT INTO security_incidents (id, region, incident_date) VALUES (1, 'Asia', '2021-10-15'), (2, 'Europe', '2021-12-20'), (3, 'Asia', '2021-11-03');

SELECT COUNT(*) FROM security_incidents WHERE incident_date >= DATE_SUB(CURRENT_DATE, INTERVAL 3 MONTH) AND region = 'Asia';


Question: What is the success rate of medication for patients with PTSD in Florida?

CREATE TABLE patients (patient_id INT, patient_name TEXT, condition TEXT, therapist_id INT, treatment TEXT, success BOOLEAN); INSERT INTO patients (patient_id, patient_name, condition, therapist_id, treatment, success) VALUES (1, 'James Johnson', 'PTSD', 1, 'Medication', TRUE); INSERT INTO patients (patient_id, patient_name, condition, therapist_id, treatment, success) VALUES (2, 'Sophia Lee', 'PTSD', 1, 'Meditation', FALSE); CREATE TABLE therapists (therapist_id INT, therapist_name TEXT, state TEXT); INSERT INTO therapists (therapist_id, therapist_name, state) VALUES (1, 'Dr. Maria Rodriguez', 'Florida');

SELECT COUNT(patients.success) * 100.0 / (SELECT COUNT(*) FROM patients WHERE patients.condition = 'PTSD' AND patients.therapist_id = 1) FROM patients WHERE patients.condition = 'PTSD' AND patients.treatment = 'Medication' AND patients.therapist_id = 1;


Question: What is the maximum food cost percentage for menu items that have been ordered more than 100 times?

CREATE TABLE MenuItems(menu_item_id INT, item_name VARCHAR(255), order_count INT, food_cost_percentage DECIMAL(5,2));

SELECT MAX(food_cost_percentage) FROM MenuItems WHERE order_count > 100;


Question: What is the total quantity of sustainable textiles used in manufacturing for each trend?

CREATE TABLE SustainableManufacturing (id INT, trend VARCHAR(20), fabric VARCHAR(20), quantity INT); INSERT INTO SustainableManufacturing (id, trend, fabric, quantity) VALUES (1, 'neutrals', 'organic linen', 600), (2, 'brights', 'recycled silk', 800);

SELECT trend, SUM(quantity) FROM SustainableManufacturing WHERE fabric LIKE '%sustainable%' GROUP BY trend;


Question: Generate PostgreSQL SQL for: What was the SPA FEA when the LMS FEA was 5?

CREATE TABLE table_name_60 (spa_fea VARCHAR, lms_fea VARCHAR)

SELECT spa_fea FROM table_name_60 WHERE lms_fea = '5';


Question: Generate PostgreSQL SQL for: What is Timo Lehkonen's highest pick number?

CREATE TABLE table_2850912_5 (pick__number INTEGER, player VARCHAR)

SELECT MAX(pick__number) FROM table_2850912_5 WHERE player = 'Timo Lehkonen';


Question: What is the total number of unique users who have liked a post in the 'social_media' database?

CREATE TABLE posts (id INT, user_id INT, content TEXT, timestamp TIMESTAMP, likes INT); CREATE TABLE likes (post_id INT, user_id INT); CREATE TABLE users (id INT, name VARCHAR(50), gender VARCHAR(10), age INT, location VARCHAR(50));

SELECT COUNT(DISTINCT users.id) AS total_unique_users FROM users JOIN likes ON users.id = likes.user_id JOIN posts ON likes.post_id = posts.id;


Question: What is the average rating of hotels in 'Asia' that have been reviewed more than 50 times?

CREATE TABLE hotels (hotel_id INT, hotel_name VARCHAR(255), rating DECIMAL(2,1), country VARCHAR(255)); INSERT INTO hotels (hotel_id, hotel_name, rating, country) VALUES (1, 'Hotel Tokyo', 4.3, 'Japan'), (2, 'Hotel Mumbai', 4.0, 'India'), (3, 'Hotel Bangkok', 4.7, 'Thailand');

SELECT AVG(rating) FROM (SELECT rating FROM hotels WHERE country = 'Asia' GROUP BY rating HAVING COUNT(*) > 50) AS subquery;


Question: List all deep-sea species in the Pacific Ocean and their maximum depths.

CREATE TABLE deep_sea_species (name VARCHAR(255), habitat VARCHAR(255), max_depth FLOAT); INSERT INTO deep_sea_species (name, habitat, max_depth) VALUES ('Anglerfish', 'Pacific Ocean', 3000), ('Giant Squid', 'Pacific Ocean', 3300);

SELECT name, max_depth FROM deep_sea_species WHERE habitat = 'Pacific Ocean';


Question: Generate PostgreSQL SQL for: What is the highest number of fai space flights when max mach is 5.65?

CREATE TABLE table_221315_3 (fai_space_flights INTEGER, max_mach VARCHAR)

SELECT MAX(fai_space_flights) FROM table_221315_3 WHERE max_mach = '5.65';


Question: Generate PostgreSQL SQL for: What was the score of the game that home team birmingham city played?

CREATE TABLE table_name_84 (score VARCHAR, home_team VARCHAR)

SELECT score FROM table_name_84 WHERE home_team = 'birmingham city';


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

-- test case where the partitioning operator is a SQL function whose
-- evaluation results in the table's relcache being rebuilt partway through
-- the execution of an ATTACH PARTITION command
create function at_test_sql_partop (int4, int4) returns int language sql
as $$ select case when $1 = $2 then 0 when $1 > $2 then 1 else -1 end; $$;
create operator class at_test_sql_partop for type int4 using btree as
    operator 1 < (int4, int4), operator 2 <= (int4, int4),
    operator 3 = (int4, int4), operator 4 >= (int4, int4),
    operator 5 > (int4, int4), function 1 at_test_sql_partop(int4, int4);
create table at_test_sql_partop (a int) partition by range (a at_test_sql_partop);
create table at_test_sql_partop_1 (a int);
alter table at_test_sql_partop attach partition at_test_sql_partop_1 for values from (0) to (10);
drop table at_test_sql_partop;
drop operator class at_test_sql_partop using btree;
drop function at_test_sql_partop;

/* Test case for bug #16242 */

-- We create a parent and child where the child has missing
-- non-null attribute values, and arrange to pass them through
-- tuple conversion from the child to the parent tupdesc
create table bar1 (a integer, b integer not null default 1)
  partition by range (a);
create table bar2 (a integer);
insert into bar2 values (1);
alter table bar2 add column b integer not null default 1;
-- (at this point bar2 contains tuple with natts=1)
alter table bar1 attach partition bar2 default;

-- this works:
select * from bar1;

-- this exercises tuple conversion:
create function xtrig()
  returns trigger language plpgsql
as $$
  declare
    r record;

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


Question: Generate PostgreSQL SQL for: What did the team score while away in moorabbin oval?

CREATE TABLE table_name_30 (away_team VARCHAR, venue VARCHAR)

SELECT away_team AS score FROM table_name_30 WHERE venue = 'moorabbin oval';


Question: Generate PostgreSQL SQL for: What was the finishing time of Stage SS6?

CREATE TABLE table_name_63 (time VARCHAR, stage VARCHAR)

SELECT time FROM table_name_63 WHERE stage = 'ss6';


Question: PostgreSQL regression test 'rules': Write the SELECT query (example 469).

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

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


Question: Generate PostgreSQL SQL for: What is the record when they played New York?

CREATE TABLE table_name_64 (record VARCHAR, opponent VARCHAR)

SELECT record FROM table_name_64 WHERE opponent = 'new york';


Question: Generate PostgreSQL SQL for: Name the attendance with result of won 1-0

CREATE TABLE table_name_27 (attendance VARCHAR, result VARCHAR)

SELECT attendance FROM table_name_27 WHERE result = 'won 1-0';


Question: List all public services provided by the city of San Francisco and their respective allocations for 2023, ordered by allocation amount in descending order.

CREATE TABLE city_services (city varchar(50), year int, service varchar(50), allocation int); INSERT INTO city_services (city, year, service, allocation) VALUES ('San Francisco', 2023, 'Waste Collection', 25000000), ('San Francisco', 2023, 'Street Cleaning', 15000000), ('San Francisco', 2023, 'Parks Maintenance', 10000000);

SELECT service, allocation FROM city_services WHERE city = 'San Francisco' AND year = 2023 ORDER BY allocation DESC;


Question: How many rock songs were streamed last month?

CREATE TABLE StreamingData (StreamID INT, SongID INT, StreamDate DATE, Genre VARCHAR(50), StreamCount INT); INSERT INTO StreamingData (StreamID, SongID, StreamDate, Genre, StreamCount) VALUES (1, 1, '2022-01-01', 'Rock', 100); INSERT INTO StreamingData (StreamID, SongID, StreamDate, Genre, StreamCount) VALUES (2, 2, '2022-01-02', 'Rock', 150);

SELECT SUM(StreamCount) FROM StreamingData WHERE StreamDate >= DATEADD(month, -1, GETDATE()) AND Genre = 'Rock';


Question: Generate PostgreSQL SQL for: Which Eliminated has an Entered smaller than 2?

CREATE TABLE table_name_42 (eliminated VARCHAR, entered INTEGER)

SELECT eliminated AS by FROM table_name_42 WHERE entered < 2;


Question: Generate PostgreSQL SQL for: Which Points is the lowest one that has a Position larger than 5?

CREATE TABLE table_name_36 (points INTEGER, position INTEGER)

SELECT MIN(points) FROM table_name_36 WHERE position > 5;


Question: Generate PostgreSQL SQL for: How many stumpings has Paul Nixon in his career?

CREATE TABLE table_11303072_9 (stumpings VARCHAR, player VARCHAR)

SELECT stumpings FROM table_11303072_9 WHERE player = 'Paul Nixon';


Question: What is the average budget for all movies produced in India?

CREATE TABLE indian_movies (id INT, title VARCHAR(255), budget FLOAT, production_country VARCHAR(100)); INSERT INTO indian_movies (id, title, budget, production_country) VALUES (1, 'Movie1', 5000000, 'India'), (2, 'Movie2', 7000000, 'India'), (3, 'Movie3', 3000000, 'India');


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

CREATE FUNCTION g_int_compress(internal)
RETURNS internal
AS 'MODULE_PATHNAME'
LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;

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


Question: Write the DML statement from PostgreSQL regression test 'event_trigger' (example 19).

DELETE FROM undroppable_objs WHERE object_identity = 'audit_tbls.schema_two_table_three';

Explanation: DML from PostgreSQL core regression test for Event Trigger.


Question: How many events had more than 50 attendees from historically underrepresented communities?

CREATE TABLE Events (EventID INT, EventDate DATE, TotalAttendees INT, CommunityType VARCHAR(255)); INSERT INTO Events (EventID, EventDate, TotalAttendees, CommunityType) VALUES (1, '2022-04-01', 75, 'Underrepresented'), (2, '2022-05-01', 30, 'Represented');

SELECT COUNT(*) FROM Events WHERE TotalAttendees > 50 AND CommunityType = 'Underrepresented';


Question: How many heritage sites are in each continent?

CREATE TABLE Heritagesites (id INT, name VARCHAR(255), continent VARCHAR(255)); INSERT INTO Heritagesites (id, name, continent) VALUES (1, 'Great Wall of China', 'Asia'), (2, 'Machu Picchu', 'South America'), (3, 'Eiffel Tower', 'Europe');

SELECT continent, COUNT(*) FROM Heritagesites GROUP BY continent;


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

select polyf(multirange(int4range(42, 49)), array[11]) as int, polyf(multirange(float8range(4.5, 7.8)), array[7]) as num;

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

SELECT count(*) FROM (select polyf(multirange(int4range(42, 49)), array[11]) as int, polyf(multirange(float8range(4.5, 7.8)), array[7]) as num) AS _sub;


Question: Show a query using PostgreSQL contrib extension 'pageinspect' (example 51).

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


Question: What is the average age of players who have played in at least one esports tournament, and what is the total number of tournaments they have played in?

CREATE TABLE Players (PlayerID INT, Age INT); INSERT INTO Players (PlayerID, Age) VALUES (1, 30); INSERT INTO Players (PlayerID, Age) VALUES (2, 25); CREATE TABLE Tournaments (TournamentID INT, TournamentName VARCHAR(50)); INSERT INTO Tournaments (TournamentID, TournamentName) VALUES (1, 'Tournament 1'); INSERT INTO Tournaments (TournamentID, TournamentName) VALUES (2, 'Tournament 2'); CREATE TABLE Participation (PlayerID INT, TournamentID INT); INSERT INTO Participation (PlayerID, TournamentID) VALUES (1, 1); INSERT INTO Participation (PlayerID, TournamentID) VALUES (2, 2);

SELECT AVG(Players.Age) AS AvgAge, COUNT(DISTINCT Participation.TournamentID) AS NumTournaments FROM Players INNER JOIN Participation ON Players.PlayerID = Participation.PlayerID;


Question: What are the total marketing costs for each TV show genre in Q1 2020?

CREATE TABLE TVShows (show_id INT, title VARCHAR(255), release_date DATE, genre VARCHAR(255), marketing_cost DECIMAL(5,2)); INSERT INTO TVShows (show_id, title, release_date, genre, marketing_cost) VALUES (1, 'Show1', '2019-10-01', 'Sci-Fi', 500000.00), (2, 'Show2', '2018-04-15', 'Comedy', 350000.00), (3, 'Show3', '2020-02-20', 'Action', 750000.00);

SELECT genre, SUM(marketing_cost) FROM TVShows WHERE release_date >= '2020-01-01' AND release_date < '2020-04-01' GROUP BY genre;


Question: What is the average fare collected from each vehicle type?

CREATE TABLE Fares (id INT, vehicle_type VARCHAR(10), fare DECIMAL(5,2)); INSERT INTO Fares (id, vehicle_type, fare) VALUES (1, 'Bus', 2.50), (2, 'Tram', 3.00), (3, 'Train', 5.00);

SELECT vehicle_type, AVG(fare) FROM Fares GROUP BY vehicle_type;


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

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

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

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


Question: Generate PostgreSQL SQL for: How many PPV values are listed for when television service Sky Cinema 1?

CREATE TABLE table_15887683_5 (ppv VARCHAR, television_service VARCHAR)

SELECT COUNT(ppv) FROM table_15887683_5 WHERE television_service = 'Sky Cinema 1';


Question: What was the total R&D expenditure for anti-inflammatory drugs?

CREATE TABLE rd_expenditure (drug_class TEXT, expenditure INTEGER);

SELECT SUM(expenditure) FROM rd_expenditure WHERE drug_class = 'anti-inflammatory';


Question: Generate PostgreSQL SQL for: What is every value for Under-11 if Under-19 is Leong Siu Lynn?

CREATE TABLE table_26368963_2 (under_11 VARCHAR, under_19 VARCHAR)

SELECT under_11 FROM table_26368963_2 WHERE under_19 = 'Leong Siu Lynn';


Question: Generate PostgreSQL SQL for: What is the average no opinion score during 1954 November that is more favorable than 35?

CREATE TABLE table_name_94 (no_opinion INTEGER, date VARCHAR, favorable VARCHAR)

SELECT AVG(no_opinion) FROM table_name_94 WHERE date = '1954 november' AND favorable > 35;


Question: Generate PostgreSQL SQL for: What is the Mascot of Brook?

CREATE TABLE table_name_25 (mascot VARCHAR, location VARCHAR)

SELECT mascot FROM table_name_25 WHERE location = 'brook';


Question: Generate PostgreSQL SQL for: Which classrooms are used by grade 4?

CREATE TABLE list (classroom VARCHAR, grade VARCHAR)

SELECT DISTINCT classroom FROM list WHERE grade = 4;


Question: Update the 'cost' value for the record with 'project_id' = 1 in the 'infrastructure_development' table to 350000000

CREATE TABLE infrastructure_development (project_id INT, location VARCHAR(30), start_date DATE, end_date DATE, cost INT); INSERT INTO infrastructure_development (project_id, location, start_date, end_date, cost) VALUES (1, 'North Sea', '2017-01-01', '2021-12-31', 400000000);

UPDATE infrastructure_development SET cost = 350000000 WHERE project_id = 1;


Question: Generate PostgreSQL SQL for: What is the total number of byes that has 13 losses and wins less than 5?

CREATE TABLE table_name_41 (byes VARCHAR, losses VARCHAR, wins VARCHAR)

SELECT COUNT(byes) FROM table_name_41 WHERE losses = 13 AND wins < 5;


Question: Generate PostgreSQL SQL for: What is the Set 1 with set 2 at 21:17?

CREATE TABLE table_name_93 (set_1 VARCHAR, set_2 VARCHAR)

SELECT set_1 FROM table_name_93 WHERE set_2 = '21:17';


Question: Generate PostgreSQL SQL for: When the team is ypiranga-sp what is the number of won games?

CREATE TABLE table_15405904_1 (won INTEGER, team VARCHAR)

SELECT MIN(won) FROM table_15405904_1 WHERE team = 'Ypiranga-SP';


Question: pgTAP test for Check (assertion 3).

CREATE TABLE public.sometab(
    id    INT NOT NULL PRIMARY KEY,
    name  TEXT DEFAULT '' CHECK ( name IN ('foo', 'bar', 'baz') ),
    numb  NUMERIC(10, 2),
    myint NUMERIC(8),
    CHECK (numb > 1.0 AND myint < 10)
);

Explanation: SQL assertion from pgTAP test suite for Check.


Question: What was the minimum response time for fire incidents in the Downtown district in 2021?

CREATE TABLE districts (id INT, name TEXT); INSERT INTO districts (id, name) VALUES (1, 'Downtown'), (2, 'Uptown'), (3, 'Midtown'); CREATE TABLE fire_incidents (id INT, district_id INT, response_time INT, incident_date DATE); INSERT INTO fire_incidents (id, district_id, response_time, incident_date) VALUES (1, 1, 5, '2021-01-01'), (2, 1, 4, '2021-02-15'), (3, 1, 6, '2021-03-10');

SELECT MIN(response_time) FROM fire_incidents WHERE district_id = 1 AND YEAR(incident_date) = 2021;


Question: Generate PostgreSQL SQL for: What number pick was the player with the hometown school of concordia college?

CREATE TABLE table_name_96 (pick VARCHAR, hometown_school VARCHAR)

SELECT pick FROM table_name_96 WHERE hometown_school = 'concordia college';


Question: Who is the most prolific artist in the database?

CREATE TABLE Artworks (ArtworkID INT, Title VARCHAR(50), Gallery VARCHAR(50), ArtistID INT); INSERT INTO Artworks (ArtworkID, Title, Gallery, ArtistID) VALUES (1, 'Starry Night', 'ImpressionistGallery', 1); INSERT INTO Artworks (ArtworkID, Title, Gallery, ArtistID) VALUES (2, 'Sunflowers', 'ImpressionistGallery', 1); INSERT INTO Artworks (ArtworkID, Title, Gallery, ArtistID) VALUES (3, 'Untitled', 'ContemporaryArt', 2); INSERT INTO Artworks (ArtworkID, Title, Gallery, ArtistID) VALUES (4, 'Untitled2', 'ContemporaryArt', 2); INSERT INTO Artworks (ArtworkID, Title, Gallery, ArtistID) VALUES (5, 'Untitled3', 'ContemporaryArt', 3);

SELECT ArtistID, COUNT(*) as Count FROM Artworks GROUP BY ArtistID ORDER BY Count DESC LIMIT 1;


Question: Generate PostgreSQL SQL for: What is the social democrat released on October 10, 1999?

CREATE TABLE table_name_94 (social_democratic VARCHAR, date_released VARCHAR)

SELECT social_democratic FROM table_name_94 WHERE date_released = 'october 10, 1999';


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

Explanation: DDL from PostgreSQL core regression test for Sqljson Jsontable.


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

SELECT 1 AS "int" OFFSET 1 FETCH FIRST 2 ROW ONLY;

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


Question: What is the average score of players who joined in the same month as the release of game V?

CREATE TABLE game_V (player_id INT, join_date DATE, score INT);

SELECT AVG(score) FROM game_V WHERE MONTH(join_date) = MONTH(DATE('2022-04-01'));


Question: Which destination marketing organizations are in the Asia-Pacific region?

CREATE TABLE dmo (id INT, name TEXT, region TEXT); INSERT INTO dmo (id, name, region) VALUES (1, 'Tourism Australia', 'Australia'), (2, 'Japan National Tourism Organization', 'Japan'), (3, 'New Zealand Tourism Board', 'New Zealand');

SELECT name FROM dmo WHERE region = 'Asia-Pacific';


Question: List the names of the volunteers who have participated in disaster response training programs and their respective trainers, including the organization they represent.

CREATE TABLE Volunteers (id INT, name TEXT, organization TEXT); INSERT INTO Volunteers (id, name, organization) VALUES (1, 'Alex', 'Red Cross'), (2, 'Jamie', 'Doctors Without Borders'), (3, 'Sophia', 'World Vision'); CREATE TABLE Trainers (id INT, name TEXT, organization TEXT); INSERT INTO Trainers (id, name, organization) VALUES (4, 'Mark', 'Red Cross'), (5, 'Emily', 'Doctors Without Borders'), (6, 'Oliver', 'World Vision'); CREATE TABLE Training_Programs (id INT, trainer_id INT, volunteer_id INT, program TEXT, date DATE); INSERT INTO Training_Programs (id, trainer_id, volunteer_id, program, date) VALUES (1, 4, 1, 'Disaster Response', '2022-02-15'), (2, 5, 2, 'Disaster Response', '2022-02-16'), (3, 6, 3, 'Disaster Response', '2022-02-17');

SELECT V.name as volunteer_name, T.name as trainer_name, T.organization as trainer_organization FROM Volunteers V INNER JOIN Training_Programs TP ON V.id = TP.volunteer_id INNER JOIN Trainers T ON TP.trainer_id = T.id WHERE TP.program = 'Disaster Response';


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

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

Explanation: DML from PostgreSQL core regression test for Rangetypes.


Question: What is the average number of defense diplomacy events conducted by India from 2015 to 2020?

CREATE TABLE defense_diplomacy (country VARCHAR(50), year INT, event_count INT); INSERT INTO defense_diplomacy (country, year, event_count) VALUES ('India', 2015, 5), ('India', 2016, 6), ('India', 2017, 7), ('India', 2018, 8), ('India', 2019, 9), ('India', 2020, 10);

SELECT AVG(event_count) FROM defense_diplomacy WHERE country = 'India' AND year BETWEEN 2015 AND 2020;


Question: What is the total revenue from ticket sales for each team in the 'teams' and 'ticket_sales' tables?

CREATE TABLE teams (name VARCHAR(30), city VARCHAR(30)); CREATE TABLE ticket_sales (team VARCHAR(30), revenue INT); INSERT INTO teams (name, city) VALUES ('Knicks', 'New York'), ('Lakers', 'Los Angeles'); INSERT INTO ticket_sales (team, revenue) VALUES ('Knicks', 1000000), ('Lakers', 1200000);

SELECT teams.name, SUM(ticket_sales.revenue) FROM teams INNER JOIN ticket_sales ON teams.name = ticket_sales.team GROUP BY teams.name;


Question: Generate PostgreSQL SQL for: Who was the nominee for 2005?

CREATE TABLE table_name_83 (nominee_s_ VARCHAR, year VARCHAR)

SELECT nominee_s_ FROM table_name_83 WHERE year = 2005;


Question: Generate PostgreSQL SQL for: When did the Electricity Grid 28.12.1972 officially shutdown?

CREATE TABLE table_name_26 (shutdown VARCHAR, electricity_grid VARCHAR)

SELECT shutdown FROM table_name_26 WHERE electricity_grid = '28.12.1972';


Question: Generate PostgreSQL SQL for: Where was the Deep - 30 Impact event held?

CREATE TABLE table_name_55 (location VARCHAR, event VARCHAR)

SELECT location FROM table_name_55 WHERE event = 'deep - 30 impact';


Question: What are the unique combinations of security incident types and their corresponding statuses in the incident_responses table, excluding any records with 'In Progress' status?

CREATE TABLE incident_responses (incident VARCHAR(50), status VARCHAR(15)); INSERT INTO incident_responses (incident, status) VALUES ('Incident 1', 'Resolved'), ('Incident 2', 'In Progress'), ('Incident 3', 'Resolved'), ('Incident 4', 'In Progress'), ('Incident 5', 'Assessed');

SELECT incident, status FROM incident_responses WHERE status != 'In Progress' GROUP BY incident, status;


Question: What is the maximum discovery date of exoplanets found by ESA missions?

CREATE TABLE missions (id INT, name VARCHAR(50), agency VARCHAR(50), start_date DATE, end_date DATE); INSERT INTO missions (id, name, agency, start_date, end_date) VALUES (1, 'Gaia', 'ESA', '2013-12-19', 'ONGOING'); INSERT INTO missions (id, name, agency, start_date, end_date) VALUES (2, 'CHEOPS', 'ESA', '2019-12-18', 'ONGOING');   CREATE TABLE exoplanets (id INT, name VARCHAR(50), mission VARCHAR(50), discovery_date DATE); INSERT INTO exoplanets (id, name, mission, discovery_date) VALUES (1, 'HD 219134 b', 'CHEOPS', '2020-05-20'); INSERT INTO exoplanets (id, name, mission, discovery_date) VALUES (2, 'TOI-1235 b', 'CHEOPS', '2021-02-26');

SELECT MAX(discovery_date) FROM exoplanets INNER JOIN missions ON exoplanets.mission = missions.name WHERE missions.agency = 'ESA';


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

SELECT '{ltree.asd, tree.awdfg}'::ltree[] ?@ 'tree & aWdfg@'::ltxtquery;

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


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

CREATE OPERATOR < (
	PROCEDURE = isnlt,
	LEFTARG = ean13,
	RIGHTARG = isbn13,
	COMMUTATOR = >,
	NEGATOR = >=,
	RESTRICT = scalarltsel,
	JOIN = scalarltjoinsel);


Question: Generate PostgreSQL SQL for: Which name had an order number of 1?

CREATE TABLE table_name_4 (name VARCHAR, order VARCHAR)

SELECT name FROM table_name_4 WHERE order = 1;


Question: Generate PostgreSQL SQL for: What is the Population of the Place with an Area (km 2) larger than 498.77?

CREATE TABLE table_name_51 (population VARCHAR, area__km_2__ INTEGER)

SELECT COUNT(population) FROM table_name_51 WHERE area__km_2__ > 498.77;


Question: Who is the youngest astronaut to have participated in a space mission?

CREATE TABLE Astronauts (name VARCHAR(30), age INT, mission_name VARCHAR(30)); INSERT INTO Astronauts (name, age, mission_name) VALUES ('Gus Grissom', 36, 'Mercury-Redstone 4'), ('John Glenn', 40, 'Friendship 7');

SELECT name, age FROM Astronauts ORDER BY age LIMIT 1;


Question: What is the total amount of financial aid provided to refugees in Jordan and Turkey, grouped by organization?

CREATE TABLE financial_aid (id INT, organization VARCHAR(255), country VARCHAR(255), amount DECIMAL(10, 2)); INSERT INTO financial_aid (id, organization, country, amount) VALUES ('1', 'UNHCR', 'Jordan', '500000'), ('2', 'WFP', 'Jordan', '600000'), ('3', 'UNICEF', 'Jordan', '400000'), ('4', 'Red Cross', 'Turkey', '700000'), ('5', 'Save the Children', 'Turkey', '800000'), ('6', 'World Vision', 'Turkey', '900000');

SELECT organization, SUM(amount) as total_aid FROM financial_aid WHERE country IN ('Jordan', 'Turkey') GROUP BY organization;


Question: What is the number of accommodations provided per disability type, ordered by the most accommodated?

CREATE TABLE AccommodationsByDisability (AccommodationID INT, AccommodationName VARCHAR(50), DisabilityType VARCHAR(50), Number INT); INSERT INTO AccommodationsByDisability (AccommodationID, AccommodationName, DisabilityType, Number) VALUES (1, 'Sign Language Interpretation', 'Hearing Loss', 500), (2, 'Wheelchair Access', 'Physical Disability', 700), (3, 'Braille Materials', 'Visual Impairment', 350), (4, 'Adaptive Equipment', 'Physical Disability', 600), (5, 'Assistive Technology', 'Intellectual Disability', 400), (6, 'Sensory Rooms', 'Autism Spectrum Disorder', 300);

SELECT DisabilityType, SUM(Number) as TotalAccommodations, ROW_NUMBER() OVER (ORDER BY SUM(Number) DESC) as Rank FROM AccommodationsByDisability GROUP BY DisabilityType;


Question: Generate PostgreSQL SQL for: When party did the incumbent in the Arkansas 5 district belong to?

CREATE TABLE table_1341897_6 (party VARCHAR, district VARCHAR)

SELECT party FROM table_1341897_6 WHERE district = 'Arkansas 5';


Question: What are the names and depths of the deepest ocean trenches in the Pacific Ocean?

CREATE TABLE DeepestTrenches (id INT, name VARCHAR(255), depth FLOAT); INSERT INTO DeepestTrenches (id, name, depth) VALUES (1, 'Marianas Trench', 10994); INSERT INTO DeepestTrenches (id, name, depth) VALUES (2, 'Tonga Trench', 10882);

SELECT name, depth FROM DeepestTrenches WHERE depth = (SELECT MAX(depth) FROM DeepestTrenches);


Question: What is the total number of military bases in the United States and Canada, and the number of bases for each country?

CREATE TABLE military_bases (id INT, name TEXT, location TEXT, country TEXT);INSERT INTO military_bases (id, name, location, country) VALUES (1, 'Fort Bragg', 'North Carolina', 'United States'), (2, 'CFB Trenton', 'Ontario', 'Canada');

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


Question: What are the total number of music streams and ticket sales for artists from Latin America?

CREATE TABLE music_streams(artist_id INT, region VARCHAR(50), streams INT); CREATE TABLE ticket_sales(artist_id INT, region VARCHAR(50), sales INT);

SELECT SUM(streams) AS total_streams, SUM(sales) AS total_sales FROM music_streams JOIN ticket_sales ON music_streams.artist_id = ticket_sales.artist_id WHERE region = 'Latin America';


Question: Insert records for 3 students in the student_mental_health table

CREATE TABLE student_mental_health (id INT PRIMARY KEY, student_id INT, mental_health_score INT, assessment_date DATE);


Question: Generate PostgreSQL SQL for: What are the student ids of students who don't have any allergies?

CREATE TABLE Has_allergy (StuID VARCHAR); CREATE TABLE Student (StuID VARCHAR)

SELECT StuID FROM Student EXCEPT SELECT StuID FROM Has_allergy;


Question: Which menu items have a lower preference score than the average preference score for vegetarian dishes?

CREATE TABLE Menu (item_id INT, name VARCHAR(50), is_vegetarian BOOLEAN, preference_score INT); INSERT INTO Menu (item_id, name, is_vegetarian, preference_score) VALUES (1, 'Garden Salad', true, 80), (2, 'Cheese Pizza', false, 70), (3, 'Vegetable Lasagna', true, 75);

SELECT item_id, name FROM Menu WHERE is_vegetarian = true AND preference_score < (SELECT AVG(preference_score) FROM Menu WHERE is_vegetarian = true);


Question: Generate PostgreSQL SQL for: When is an Opponent of evie dominikovic?

CREATE TABLE table_name_72 (date VARCHAR, opponent VARCHAR)

SELECT date FROM table_name_72 WHERE opponent = 'evie dominikovic';


Question: Add new record to international_alliances table, including 'NATO' as alliance_name, 'USA' as member_country, 'Article 5' as type

CREATE TABLE international_alliances (id INT PRIMARY KEY, alliance_name VARCHAR(100), member_country VARCHAR(50), type VARCHAR(50));

INSERT INTO international_alliances (alliance_name, member_country, type) VALUES ('NATO', 'USA', 'Article 5');


Question: What is the maximum depth of all uranium mines in 'Country X'?

CREATE TABLE uranium_mines (id INT, name TEXT, location TEXT, depth FLOAT); INSERT INTO uranium_mines (id, name, location, depth) VALUES (1, 'Mine F', 'Country X', 600.1); INSERT INTO uranium_mines (id, name, location, depth) VALUES (2, 'Mine G', 'Country X', 700.2); INSERT INTO uranium_mines (id, name, location, depth) VALUES (3, 'Mine H', 'Country Y', 500.3);

SELECT MAX(depth) FROM uranium_mines WHERE location = 'Country X';


Question: Generate PostgreSQL SQL for: When the under-11 was Aly Abou El Einen, who was the under-13?

CREATE TABLE table_26368963_1 (under_13 VARCHAR, under_11 VARCHAR)

SELECT under_13 FROM table_26368963_1 WHERE under_11 = 'Aly Abou El Einen';


Question: Generate PostgreSQL SQL for: WHAT IS THE HOMETOWN OF TONY STEWARD?

CREATE TABLE table_11677691_2 (hometown VARCHAR, player VARCHAR)

SELECT hometown FROM table_11677691_2 WHERE player = 'Tony Steward';


Question: What is the total biomass of fish in the Atlantic ocean by sustainable seafood category?

CREATE TABLE fish_data (id INT, species TEXT, ocean TEXT, biomass FLOAT, sustainable_category TEXT); INSERT INTO fish_data (id, species, ocean, biomass, sustainable_category) VALUES (1, 'Species A', 'Atlantic', 1200, 'Sustainable'), (2, 'Species B', 'Atlantic', 1500, 'Unsustainable'), (3, 'Species C', 'Atlantic', 1800, 'Sustainable');

SELECT sustainable_category, SUM(biomass) FROM fish_data WHERE ocean = 'Atlantic' AND sustainable_category IS NOT NULL GROUP BY sustainable_category;


Question: Write the DDL statement from PostgreSQL regression test 'truncate' (example 1).

CREATE TABLE truncate_a (col1 integer primary key);

Explanation: DDL from PostgreSQL core regression test for Truncate.


Question: Generate PostgreSQL SQL for: What is the sum of attendance for the games played at Los Angeles Rams?

CREATE TABLE table_name_39 (attendance INTEGER, opponent VARCHAR)

SELECT SUM(attendance) FROM table_name_39 WHERE opponent = 'at los angeles rams';


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

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

SELECT count(*) FROM (select jsonb '{"a": {"a": 12}}' @? '$.a.a') AS _sub;


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

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

SELECT count(*) FROM (select format('>>%1$10s<<', 'Hello')) AS _sub;


Question: Generate PostgreSQL SQL for: What is the Theme of the coin with an Issue Price of $89.95?

CREATE TABLE table_name_95 (theme VARCHAR, issue_price VARCHAR)

SELECT theme FROM table_name_95 WHERE issue_price = '$89.95';


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

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


Question: What is the number of unique severities in the 'vulnerabilities' table?

CREATE TABLE schema1.vulnerabilities (id INT, name VARCHAR(255), severity VARCHAR(50), description TEXT, date_discovered DATE, last_observed DATE); INSERT INTO schema1.vulnerabilities (id, name, severity, description, date_discovered, last_observed) VALUES (1, 'SQL Injection', 'Critical', 'Allows unauthorized access', '2021-01-01', '2021-02-01');

SELECT COUNT(DISTINCT severity) FROM schema1.vulnerabilities;


Question: Which hotel in LATAM has the highest virtual tour engagement?

CREATE TABLE latam_virtual_tours (hotel_id INT, hotel_name VARCHAR(255), views INT);

SELECT hotel_id, hotel_name, MAX(views) FROM latam_virtual_tours;


Question: Write the DML statement from PostgreSQL regression test 'truncate' (example 101).

Explanation: DML from PostgreSQL core regression test for Truncate.


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

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

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


Question: Generate PostgreSQL SQL for: What is the score of the match with a 3-2 result?

CREATE TABLE table_name_61 (score VARCHAR, result VARCHAR)

SELECT score FROM table_name_61 WHERE result = '3-2';


Question: Drop the view 'chemical_inventory'

CREATE VIEW chemical_inventory AS SELECT * FROM chemical_data;


Question: Generate PostgreSQL SQL for: What country is ranked larger than 4?

CREATE TABLE table_name_72 (country VARCHAR, rank INTEGER)

SELECT country FROM table_name_72 WHERE rank > 4;


Question: List the number of smart contracts created each month in 2021, for a specific regulatory framework?

CREATE TABLE smart_contracts (contract_id INT, creation_date DATE, regulatory_framework VARCHAR(255)); INSERT INTO smart_contracts (contract_id, creation_date, regulatory_framework) VALUES (1, '2021-01-01', 'SEC'), (2, '2021-01-15', 'EU'), (3, '2021-02-03', 'SEC'), (4, '2021-03-20', 'EU'), (5, '2021-04-01', 'SEC');

SELECT MONTH(creation_date) as month, COUNT(*) as smart_contracts_created FROM smart_contracts WHERE regulatory_framework = 'SEC' AND YEAR(creation_date) = 2021 GROUP BY month;


Question: What is the minimum age of visitors who attended exhibitions in London?

CREATE TABLE Exhibitions (exhibition_id INT, location VARCHAR(255));CREATE TABLE Visitors (visitor_id INT, exhibition_id INT, age INT); INSERT INTO Exhibitions (exhibition_id, location) VALUES (1, 'London'), (2, 'Paris'), (3, 'London'); INSERT INTO Visitors (visitor_id, exhibition_id, age) VALUES (1, 1, 30), (2, 1, 45), (3, 2, 25), (4, 3, 18), (5, 3, 19);

SELECT MIN(age) FROM Visitors JOIN Exhibitions ON Visitors.exhibition_id = Exhibitions.exhibition_id WHERE Exhibitions.location = 'London';


Question: PostgreSQL regression test 'horology': Write the SELECT query (example 334).

SELECT to_date('2011 12 18', 'YYYYxMMxDD');

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

SELECT count(*) FROM (SELECT to_date('2011 12 18', 'YYYYxMMxDD')) AS _sub;


Question: Generate PostgreSQL SQL for: How many ranks have $1,084,439,099 as the worldwide gross?

CREATE TABLE table_name_91 (rank INTEGER, worldwide_gross VARCHAR)

SELECT SUM(rank) FROM table_name_91 WHERE worldwide_gross = '$1,084,439,099';


Question: Write the DML statement from PostgreSQL regression test 'stats_rewrite' (example 40).

Explanation: DML from PostgreSQL core regression test for Stats Rewrite.


Question: Generate PostgreSQL SQL for: What is the top grid that laps less than 66 and a retried engine?

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

SELECT MAX(grid) FROM table_name_28 WHERE time_retired = 'engine' AND laps < 66;


Question: Generate PostgreSQL SQL for: How many combination classifications have the winner as Erik Zabel and a points classification as Alessandro Petacchi

CREATE TABLE table_15059783_1 (combination_classification VARCHAR, points_classification VARCHAR, winner VARCHAR)

SELECT COUNT(combination_classification) FROM table_15059783_1 WHERE points_classification = 'Alessandro Petacchi' AND winner = 'Erik Zabel';


Question: PL/pgSQL test: Plpython Composite (example 17).

SELECT * FROM multiout_record_as('dict', null, null, true);

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


Question: What is the distribution of visitor demographics by time of day?

CREATE TABLE visitor_demographics (id INT, age INT, gender TEXT, visit_time TEXT); INSERT INTO visitor_demographics (id, age, gender, visit_time) VALUES (1, 23, 'Female', 'Morning'), (2, 35, 'Male', 'Afternoon');

SELECT visit_time, age, gender, COUNT(*) FROM visitor_demographics GROUP BY visit_time, age, gender;


Question: Show Underwriting data for policies with an 'Auto' type, a premium less than or equal to $1000, and a PolicyholderID greater than 2.

CREATE TABLE Underwriting (PolicyID INT, PolicyholderID INT, PolicyType TEXT, Premium INT); INSERT INTO Underwriting (PolicyID, PolicyholderID, PolicyType, Premium) VALUES (101, 1, 'Auto', 1200), (102, 2, 'Life', 500), (103, 3, 'Auto', 800), (104, 4, 'Life', 600);

SELECT * FROM Underwriting WHERE PolicyType = 'Auto' AND Premium <= 1000 AND PolicyholderID > 2;


Question: What is the average salary of construction workers per state?

CREATE TABLE WorkerSalaries (WorkerID int, Name varchar(50), State varchar(25), Salary decimal(10,2)); INSERT INTO WorkerSalaries (WorkerID, Name, State, Salary) VALUES (1, 'John Doe', 'NY', 50000.00), (2, 'Jane Smith', 'CA', 60000.00), (3, 'Mike Johnson', 'TX', 55000.00);

SELECT State, AVG(Salary) AS AvgSalaryPerState FROM WorkerSalaries GROUP BY State;


Question: Generate PostgreSQL SQL for: Which team had a game of 82?

CREATE TABLE table_name_60 (team VARCHAR, game VARCHAR)

SELECT team FROM table_name_60 WHERE game = 82;


Question: What is the average age of visitors who attended dance performances in New York?

CREATE TABLE events (event_id INT, event_name VARCHAR(50), location VARCHAR(50)); INSERT INTO events (event_id, event_name, location) VALUES (1, 'Dance Performance', 'New York'); CREATE TABLE attendees (attendee_id INT, event_id INT, age INT); INSERT INTO attendees (attendee_id, event_id, age) VALUES (1, 1, 35), (2, 1, 42), (3, 1, 28), (4, 1, 32);

SELECT AVG(age) FROM attendees JOIN events ON attendees.event_id = events.event_id WHERE events.location = 'New York' AND events.event_name = 'Dance Performance';


Question: What is the average altitude of satellites in the Starlink constellation?

CREATE TABLE Satellites (satellite_id INT, name VARCHAR(255), country VARCHAR(255), altitude FLOAT, constellation VARCHAR(255)); INSERT INTO Satellites (satellite_id, name, country, altitude, constellation) VALUES (1, 'SpaceX-1', 'USA', 550, 'Starlink'), (2, 'SpaceX-2', 'USA', 550, 'Starlink'), (3, 'OneWeb-1', 'UK', 1200, 'OneWeb');

SELECT AVG(altitude) FROM Satellites WHERE constellation = 'Starlink';


Question: Generate PostgreSQL SQL for: Which Song has Points smaller than 54, and a Draw smaller than 4, and a Place smaller than 10?

CREATE TABLE table_name_90 (song VARCHAR, place VARCHAR, points VARCHAR, draw VARCHAR)

SELECT song FROM table_name_90 WHERE points < 54 AND draw < 4 AND place < 10;


Question: Generate PostgreSQL SQL for: Name the surface for paul goldstein and date of october 2, 2006

CREATE TABLE table_name_79 (surface VARCHAR, partnering VARCHAR, date VARCHAR)

SELECT surface FROM table_name_79 WHERE partnering = 'paul goldstein' AND date = 'october 2, 2006';


Question: What is the total weight of ingredients sourced from the US, for each product category?

CREATE TABLE product_ingredients (ingredient_id INT, product_id INT, ingredient VARCHAR(255), source_country VARCHAR(255)); CREATE TABLE products (product_id INT, product VARCHAR(255), category VARCHAR(255)); INSERT INTO product_ingredients (ingredient_id, product_id, ingredient, source_country) VALUES (1, 1, 'Vitamin C', 'US'), (2, 1, 'Shea Butter', 'Ghana'), (3, 2, 'Jojoba Oil', 'US'), (4, 2, 'Aloe Vera', 'Mexico'); INSERT INTO products (product_id, product, category) VALUES (1, 'Face Cream', 'Skin Care'), (2, 'Hair Serum', 'Hair Care');

SELECT p.category, SUM(pi.ingredient_id) as total_us_weight FROM product_ingredients pi JOIN products p ON pi.product_id = p.product_id WHERE pi.source_country = 'US' GROUP BY p.category;


Question: Generate PostgreSQL SQL for: Which writer worked for Intrepido LTD for a film on 17/03/04?

CREATE TABLE table_name_35 (writer_s_ VARCHAR, recipient VARCHAR, date VARCHAR)

SELECT writer_s_ FROM table_name_35 WHERE recipient = 'intrepido ltd' AND date = '17/03/04';


Question: What are the total greenhouse gas emissions for each mine, ranked from highest to lowest?

CREATE TABLE Mine (MineID int, MineName varchar(50), Location varchar(50)); CREATE TABLE Emission (EmissionID int, MineID int, EmissionType varchar(50), EmissionQuantity int); INSERT INTO Mine VALUES (1, 'ABC Mine', 'Colorado'), (2, 'DEF Mine', 'Wyoming'), (3, 'GHI Mine', 'West Virginia'); INSERT INTO Emission VALUES (1, 1, 'CO2', 1000), (2, 1, 'CH4', 200), (3, 2, 'CO2', 1500), (4, 2, 'CH4', 300), (5, 3, 'CO2', 1200), (6, 3, 'CH4', 400);

SELECT MineName, SUM(EmissionQuantity) as TotalEmissionQuantity FROM Emission INNER JOIN Mine ON Emission.MineID = Mine.MineID GROUP BY MineName ORDER BY TotalEmissionQuantity DESC;


Question: What is the average size of marine protected areas in the Indian Ocean and Mediterranean Sea?

CREATE TABLE marine_protected_areas (id INT, name VARCHAR(255), location VARCHAR(255), size FLOAT); INSERT INTO marine_protected_areas (id, name, location, size) VALUES (1, 'Maldives Atoll Marine Park', 'Indian Ocean', 90000); INSERT INTO marine_protected_areas (id, name, location, size) VALUES (2, 'Palestine National Marine Park', 'Mediterranean Sea', 3500);

SELECT AVG(size) FROM marine_protected_areas WHERE location IN ('Indian Ocean', 'Mediterranean Sea');


Question: What is the latest smart city technology adoption date in the 'smart_city_technology' table?

CREATE TABLE smart_city_technology (tech_id INT, tech_name VARCHAR(100), adoption_date DATE); INSERT INTO smart_city_technology (tech_id, tech_name, adoption_date) VALUES (1, 'Smart Grid', '2020-03-15'), (2, 'Smart Lighting', '2019-08-01');

SELECT MAX(adoption_date) FROM smart_city_technology;


Question: What's the total number of players who play strategy games on VR platforms?

CREATE TABLE Players (PlayerID INT, Name VARCHAR(100), Age INT, FavoriteGenre VARCHAR(50), VRPossible BOOLEAN); INSERT INTO Players (PlayerID, Name, Age, FavoriteGenre, VRPossible) VALUES (1, 'John Doe', 25, 'Action', true), (2, 'Jane Smith', 28, 'Adventure', true), (3, 'James Johnson', 30, 'Simulation', false), (4, 'Emily Davis', 24, 'Strategy', true);

SELECT COUNT(*) FROM Players WHERE FavoriteGenre = 'Strategy' AND VRPossible = true;


Question: Generate PostgreSQL SQL for: How many players had 8 goals?

CREATE TABLE table_28286776_52 (player VARCHAR, goal_s_ VARCHAR)

SELECT COUNT(player) FROM table_28286776_52 WHERE goal_s_ = 8;


Question: Generate PostgreSQL SQL for: What date has 2:48 as the time?

CREATE TABLE table_name_48 (date VARCHAR, time VARCHAR)

SELECT date FROM table_name_48 WHERE time = '2:48';


Question: What is the total area (in hectares) of farmland in the 'organic_farms' table?

CREATE TABLE organic_farms (farmer_id INT, farm_name VARCHAR(50), location VARCHAR(50), area_ha FLOAT); INSERT INTO organic_farms (farmer_id, farm_name, location, area_ha) VALUES (1, 'Farm 1', 'Location 1', 15.6);


Question: List all environmental impact stats for mining operations in Russia and Canada?

CREATE TABLE canadian_provinces (id INT, name VARCHAR(50)); CREATE TABLE russian_regions (id INT, name VARCHAR(50)); CREATE TABLE mining_operations (id INT, country_id INT, region VARCHAR(20), annual_co2_emissions INT); INSERT INTO canadian_provinces (id, name) VALUES (1, 'Alberta'), (2, 'British Columbia'); INSERT INTO russian_regions (id, name) VALUES (1, 'Siberia'), (2, 'Urals'); INSERT INTO mining_operations (id, country_id, region, annual_co2_emissions) VALUES (1, 1, 'Canada', 5000), (2, 1, 'Canada', 6000), (3, 2, 'Russia', 7000), (4, 2, 'Russia', 8000);

SELECT m.annual_co2_emissions, m.region FROM mining_operations m INNER JOIN (SELECT * FROM canadian_provinces WHERE name = 'Alberta' UNION ALL SELECT * FROM russian_regions WHERE name = 'Siberia') c ON m.country_id = c.id;


Question: Generate PostgreSQL SQL for: Name the total number 1980 mil for soviet union

CREATE TABLE table_22071705_6 (country VARCHAR)

SELECT COUNT(1980 AS __mil_) FROM table_22071705_6 WHERE country = 'Soviet Union';


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

CREATE TABLE table_name_52 (home_team VARCHAR)

SELECT home_team AS score FROM table_name_52 WHERE home_team = 'north melbourne';


Question: Delete the 'gene sequencing' project from the 'researchers' table.

CREATE TABLE researchers (id INT, name VARCHAR(50), project VARCHAR(50)); INSERT INTO researchers (id, name, project) VALUES (1, 'Alice', 'gene sequencing'), (2, 'Bob', 'biosensor development'), (3, 'Charlie', 'gene sequencing');

DELETE FROM researchers WHERE project = 'gene sequencing';


Question: What is the average age of visitors to dance programs in 2022?

CREATE TABLE dance_attendance (id INT, attendee_age INT, program_type VARCHAR(255), visit_year INT);

SELECT program_type, AVG(attendee_age) OVER (PARTITION BY program_type) AS avg_age_by_program_type  FROM dance_attendance WHERE visit_year = 2022 AND program_type LIKE '%dance%' ORDER BY program_type;


Question: How many military aircraft are currently under maintenance?

CREATE TABLE aircraft (id INT, model VARCHAR(50), maintenance_status VARCHAR(50)); INSERT INTO aircraft (id, model, maintenance_status) VALUES (1, 'F-16', 'under_maintenance'), (2, 'F-35', 'operational'), (3, 'A-10', 'under_maintenance');

SELECT COUNT(*) FROM aircraft WHERE maintenance_status = 'under_maintenance';


Question: Show a SQL definition from the timescaledb project (util_time, item 14).

-- Convert integer UNIX timestamps in microsecond to a timestamp range.
CREATE OR REPLACE FUNCTION _timescaledb_functions.make_multirange_from_internal_time(
    base tstzrange, low_usec bigint, high_usec bigint
) RETURNS TSTZMULTIRANGE AS
$body$
  select multirange(tstzrange(_timescaledb_functions.to_timestamp(low_usec),
			      _timescaledb_functions.to_timestamp(high_usec)));

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


Question: Find the number of players who adopted VR technology in Canada

CREATE TABLE Players (PlayerID INT, PlayerName VARCHAR(50), Country VARCHAR(50)); INSERT INTO Players (PlayerID, PlayerName, Country) VALUES (1, 'John Smith', 'Canada'); INSERT INTO Players (PlayerID, PlayerName, Country) VALUES (2, 'Jane Doe', 'USA'); CREATE TABLE VRAdoption (PlayerID INT, VRAdopted DATE); INSERT INTO VRAdoption (PlayerID, VRAdopted) VALUES (1, '2021-08-01');

SELECT COUNT(*) FROM Players p INNER JOIN VRAdoption va ON p.PlayerID = va.PlayerID WHERE p.Country = 'Canada';


Question: What is the average cost of medical procedures performed in each hospital in 2020?

CREATE TABLE medical_procedures (id INT, name TEXT, hospital TEXT, procedure_date DATE, cost FLOAT); INSERT INTO medical_procedures (id, name, hospital, procedure_date, cost) VALUES (1, 'Medical Procedure 1', 'Hospital A', '2020-01-01', 100.00), (2, 'Medical Procedure 2', 'Hospital A', '2020-02-01', 200.00), (3, 'Medical Procedure 3', 'Hospital B', '2020-03-01', 300.00), (4, 'Medical Procedure 4', 'Hospital C', '2020-04-01', 400.00);

SELECT hospital, AVG(cost) as avg_cost FROM medical_procedures WHERE procedure_date >= '2020-01-01' AND procedure_date < '2021-01-01' GROUP BY hospital;


Question: Find the number of wells drilled in each country in 2020

CREATE TABLE wells (id INT, country VARCHAR(50), drill_date DATE); INSERT INTO wells (id, country, drill_date) VALUES (1, 'USA', '2020-01-01'); INSERT INTO wells (id, country, drill_date) VALUES (2, 'Canada', '2020-02-15');

SELECT country, COUNT(*) as num_wells FROM wells WHERE YEAR(drill_date) = 2020 GROUP BY country;


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

SELECT '2011-03-26 23:59:59 UTC'::timestamptz AT TIME ZONE 'MSK';

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

SELECT count(*) FROM (SELECT '2011-03-26 23:59:59 UTC'::timestamptz AT TIME ZONE 'MSK') AS _sub;


Question: What is the average contract amount for negotiations in the defense sector?

CREATE TABLE negotiations (id INT PRIMARY KEY, sector VARCHAR(255), contract_amount DECIMAL(10,2), negotiation_date DATE); INSERT INTO negotiations (id, sector, contract_amount, negotiation_date) VALUES (1, 'Defense', 150000000.00, '2022-08-01');

SELECT AVG(contract_amount) FROM negotiations WHERE sector = 'Defense';


Question: Update all mental health assessment scores below 70 for students in the past month in the 'student_mental_health' table to 70.

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

UPDATE student_mental_health SET assessment_score = 70 WHERE assessment_score < 70 AND assessment_date >= DATE(NOW()) - INTERVAL 1 MONTH;


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

CREATE FUNCTION gbt_oid_fetch(internal)
RETURNS internal
AS 'MODULE_PATHNAME'
LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;

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


Question: Show an example of PostgreSQL ALTER TABLE (example 6).

ALTER TABLE foo ALTER COLUMN foo_timestamp SET DATA TYPE timestamp with time zone USING timestamp with time zone 'epoch' + foo_timestamp * interval '1 second';

Explanation: PostgreSQL ALTER TABLE command.


Question: Insert a new record into the "international_visitor_statistics" table for "China" with 2022 visit data

CREATE TABLE international_visitor_statistics (id INT PRIMARY KEY, country TEXT, year INT, visitor_count INT);

INSERT INTO international_visitor_statistics (id, country, year, visitor_count) VALUES (1, 'China', 2022, 20000000);


Question: Generate PostgreSQL SQL for: What's the original airdate of the episode directed by Pete Travis?

CREATE TABLE table_12919003_3 (original_airdate VARCHAR, director VARCHAR)

SELECT original_airdate FROM table_12919003_3 WHERE director = 'Pete Travis';


Question: Write the DDL statement from PostgreSQL regression test 'rules' (example 232).

Explanation: DDL from PostgreSQL core regression test for Rules.


Question: Generate PostgreSQL SQL for: Which team does Pierre Duguay play for?

CREATE TABLE table_1213511_6 (nhl_team VARCHAR, player VARCHAR)

SELECT nhl_team FROM table_1213511_6 WHERE player = 'Pierre Duguay';


Question: Generate PostgreSQL SQL for: What is the lowest average points per race entered of driver kimi räikkönen, who has more than 194 entries?

CREATE TABLE table_name_3 (average_points_per_race_entered INTEGER, driver VARCHAR, entries VARCHAR)

SELECT MIN(average_points_per_race_entered) FROM table_name_3 WHERE driver = 'kimi räikkönen' AND entries > 194;


Question: What is the number of startups founded by individuals from underrepresented racial or ethnic backgrounds in the tech sector?

CREATE TABLE startup (id INT, name TEXT, industry TEXT, founding_date DATE, founder_race TEXT); INSERT INTO startup (id, name, industry, founding_date, founder_race) VALUES (1, 'AptDeco', 'E-commerce', '2014-02-14', 'Black'), (2, 'Blavity', 'Media', '2014-07-17', 'Black');

SELECT COUNT(*) FROM startup WHERE industry = 'Tech' AND founder_race IN ('Black', 'Hispanic', 'Indigenous', 'Asian', 'Pacific Islander', 'Multiracial');


Question: Generate PostgreSQL SQL for: What is the Time/Retired for the car going 42 Laps?

CREATE TABLE table_name_2 (time_retired VARCHAR, laps VARCHAR)

SELECT time_retired FROM table_name_2 WHERE laps = 42;


Question: pgTAP test for Hastap (assertion 86).

SELECT * FROM check_test(
    hasnt_composite( 'public', 'sometype', 'desc' ),
    false,
    'hasnt_composite(sch, tab, desc)',
    'desc',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Hastap.


Question: PostgreSQL regression test 'groupingsets': Write the SELECT query (example 99).

select ten, grouping(ten) from onek
group by (ten) having grouping(ten) >= 0
order by 2,1;

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

SELECT count(*) FROM (select ten, grouping(ten) from onek
group by (ten) having grouping(ten) >= 0
order by 2,1) AS _sub;


Question: How many employees were hired in 2021?

CREATE TABLE employees (id INT, name VARCHAR(50), hire_date DATE); INSERT INTO employees (id, name, hire_date) VALUES (1, 'John Doe', '2021-02-14'), (2, 'Jane Smith', '2021-05-02');

SELECT COUNT(*) FROM employees WHERE YEAR(hire_date) = 2021;


Question: Generate PostgreSQL SQL for: Which Matches have a Rank of 2?

CREATE TABLE table_name_94 (matches VARCHAR, rank VARCHAR)

SELECT COUNT(matches) FROM table_name_94 WHERE rank = 2;


Question: How many yellow cards were given to players in the last 30 days?

CREATE TABLE players (player_id INT, player_name VARCHAR(255), team_id INT, yellow_cards INT, red_cards INT);

SELECT SUM(yellow_cards) as total_yellow_cards FROM players WHERE yellow_cards > 0 AND player_id IN (SELECT player_id FROM players WHERE match_date >= DATEADD(day, -30, GETDATE()));


Question: Write the DDL statement from PostgreSQL regression test 'aggregates' (example 206).

Explanation: DDL from PostgreSQL core regression test for Aggregates.


Question: What is the longest song in the metal genre?

CREATE TABLE songs (song_id INT, song_name VARCHAR(100), genre VARCHAR(50), length_sec INT); INSERT INTO songs (song_id, song_name, genre, length_sec) VALUES (1, 'Battery', 'metal', 506), (2, 'Master of Puppets', 'metal', 857), (3, 'Epic', 'rock', 909), (4, 'Stairway to Heaven', 'rock', 792), (5, 'In-A-Gadda-Da-Vida', 'rock', 1701);

SELECT song_name, length_sec FROM songs WHERE genre = 'metal' ORDER BY length_sec DESC LIMIT 1;


Question: What is the average response time for emergency incidents in the city of Los Angeles, categorized by incident type?

CREATE TABLE emergency_responses (id INT, incident_id INT, response_time INT); CREATE TABLE emergency_incidents (id INT, incident_type VARCHAR(255), report_date DATE); INSERT INTO emergency_incidents (id, incident_type, report_date) VALUES (1, 'Medical Emergency', '2022-01-01'), (2, 'Fire', '2022-01-02'); INSERT INTO emergency_responses (id, incident_id, response_time) VALUES (1, 1, 10), (2, 1, 12), (3, 2, 20);

SELECT incident_type, AVG(response_time) FROM emergency_responses JOIN emergency_incidents ON emergency_responses.incident_id = emergency_incidents.id GROUP BY incident_type;


Question: Find the number of safety tests passed, failed, and total for each vehicle model.

CREATE TABLE safety_tests (id INT, vehicle_model VARCHAR(20), test_result VARCHAR(10)); INSERT INTO safety_tests (id, vehicle_model, test_result) VALUES (1, 'Model X', 'Pass'), (2, 'Model X', 'Pass'), (3, 'Model Y', 'Fail');

SELECT vehicle_model, COUNT(*) FILTER (WHERE test_result = 'Pass') AS passes, COUNT(*) FILTER (WHERE test_result = 'Fail') AS fails, COUNT(*) AS total FROM safety_tests GROUP BY vehicle_model;


Question: Generate PostgreSQL SQL for: How many battles resulted in Battle of the Yellow Sea?

CREATE TABLE table_26977890_1 (result VARCHAR, battles VARCHAR)

SELECT COUNT(result) FROM table_26977890_1 WHERE battles = 'Battle of the Yellow Sea';


Question: What is the total number of artists and the total number of artworks in the database?

CREATE TABLE artists (id INT, name VARCHAR(255), year_of_birth INT); CREATE TABLE artworks (id INT, artist_id INT, title VARCHAR(255), year_of_creation INT);

SELECT (SELECT COUNT(*) FROM artists) AS total_artists, (SELECT COUNT(*) FROM artworks) AS total_artworks;


Question: Generate PostgreSQL SQL for: What European Cup is in Israeli Premier League?

CREATE TABLE table_name_24 (european_cup VARCHAR, national_league VARCHAR)

SELECT european_cup FROM table_name_24 WHERE national_league = 'israeli premier league';


Question: Generate PostgreSQL SQL for: Which countries won by 9 strokes?

CREATE TABLE table_1520559_1 (country VARCHAR, margin_of_victory VARCHAR)

SELECT country FROM table_1520559_1 WHERE margin_of_victory = '9 strokes';


Question: Generate PostgreSQL SQL for: What date was the game in Minneapolis?

CREATE TABLE table_name_21 (date VARCHAR, city VARCHAR)

SELECT date FROM table_name_21 WHERE city = 'minneapolis';


Question: What is the number of new subscribers per day, by country, for the last 60 days?

CREATE TABLE subscribers (subscriber_id INT, country VARCHAR(255), subscribe_date DATE);  CREATE VIEW daily_subscribers AS SELECT country, DATE_TRUNC('day', subscribe_date) as date, COUNT(DISTINCT subscriber_id) as new_subscribers FROM subscribers WHERE subscribe_date >= DATEADD(day, -60, CURRENT_DATE) GROUP BY country, date;


Question: List the artists in the 'artists' table, grouped by their country of origin.

CREATE TABLE artists (artist_id INT, name VARCHAR(50), country VARCHAR(50), genre VARCHAR(50), birth_year INT);

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


Question: Generate PostgreSQL SQL for: What is the winning score with a margin of victory of 4 strokes for the NEC Invitational tournament?

CREATE TABLE table_name_93 (winning_score VARCHAR, margin_of_victory VARCHAR, tournament VARCHAR)

SELECT winning_score FROM table_name_93 WHERE margin_of_victory = '4 strokes' AND tournament = 'nec invitational';


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

ALTER EXTENSION pgtap ADD FUNCTION col_default_is ( NAME, NAME, anyelement, TEXT );

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


Question: What is the average calorie intake per meal for vegetarian customers in New York?

CREATE TABLE Customers (CustomerID INT, Name VARCHAR(50), DietaryPreference VARCHAR(20), City VARCHAR(20)); INSERT INTO Customers VALUES (1, 'John Doe', 'Vegetarian', 'New York'); INSERT INTO Customers VALUES (2, 'Jane Smith', 'Non-Vegetarian', 'Los Angeles'); CREATE TABLE Meals (MealID INT, CustomerID INT, Calories INT); INSERT INTO Meals VALUES (1, 1, 600); INSERT INTO Meals VALUES (2, 1, 400); INSERT INTO Meals VALUES (3, 2, 800);

SELECT AVG(Meals.Calories) FROM Customers INNER JOIN Meals ON Customers.CustomerID = Meals.CustomerID WHERE Customers.DietaryPreference = 'Vegetarian' AND Customers.City = 'New York';


Question: Generate PostgreSQL SQL for: How many games did team iurbentia bilbao have with rebounds higher than 212?

CREATE TABLE table_name_27 (games INTEGER, team VARCHAR, rebounds VARCHAR)

SELECT SUM(games) FROM table_name_27 WHERE team = 'iurbentia bilbao' AND rebounds > 212;


Question: Show the average number of hospital beds in rural hospitals with at least 100 beds, grouped by hospital location state.

CREATE TABLE hospitals (hospital_id INT, hospital_name TEXT, beds INT, rural BOOLEAN, state_id INT); INSERT INTO hospitals (hospital_id, hospital_name, beds, rural, state_id) VALUES (1, 'Hospital A', 100, true, 1); CREATE TABLE states (state_id INT, state TEXT); INSERT INTO states (state_id, state) VALUES (1, 'Alabama'), (2, 'Alaska');

SELECT states.state, AVG(hospitals.beds) avg_beds FROM hospitals JOIN states ON hospitals.state_id = states.state_id WHERE hospitals.rural = true AND hospitals.beds >= 100 GROUP BY states.state;


Question: Generate PostgreSQL SQL for: When did Oliver Jarvis have pole position?

CREATE TABLE table_21321935_2 (date VARCHAR, pole_position VARCHAR)

SELECT date FROM table_21321935_2 WHERE pole_position = 'Oliver Jarvis';


Question: Which restaurants had a daily revenue above $500 on Valentine's Day 2022?

CREATE TABLE revenue (restaurant_name TEXT, daily_revenue NUMERIC, date DATE); INSERT INTO revenue (restaurant_name, daily_revenue, date) VALUES ('ABC Bistro', 600, '2022-02-14'), ('DEF Diner', 400, '2022-02-14'), ('GHI Grill', 300, '2022-02-14'), ('JKL Bistro', 550, '2022-02-14');

SELECT restaurant_name FROM revenue WHERE daily_revenue > 500 AND date = '2022-02-14';


Question: What is the total cost of humanitarian assistance provided by the EU to South American countries since 2016?

CREATE TABLE eu_humanitarian_assistance (donor VARCHAR(255), recipient VARCHAR(255), cost DECIMAL(10, 2), assistance_date DATE);

SELECT SUM(cost) FROM eu_humanitarian_assistance WHERE donor = 'EU' AND recipient LIKE 'South America%' AND assistance_date >= '2016-01-01';


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

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

SELECT count(*) FROM (select string_to_array('1|2|3', '')) AS _sub;


Question: What is the minimum budget dedicated to technology for social good by organizations in the Latin America region?

CREATE TABLE Organizations (id INT, name TEXT, region TEXT, budget_social_good FLOAT); INSERT INTO Organizations (id, name, region, budget_social_good) VALUES (1, 'Tech4Good', 'Latin America', 700000), (2, 'SocialImpactLab', 'Latin America', 500000), (3, 'GreenInnovations', 'North America', 900000), (4, 'CommunityTech', 'Europe', 800000), (5, 'TechForAll', 'Latin America', 600000);

SELECT MIN(budget_social_good) FROM Organizations WHERE region = 'Latin America';


Question: Generate PostgreSQL SQL for: Name the team for arif asadov

CREATE TABLE table_22848931_3 (team VARCHAR, replaced_by VARCHAR)

SELECT team FROM table_22848931_3 WHERE replaced_by = 'Arif Asadov';


Question: What is the total funding received by companies founded in 2017, ordered by the amount of funding?

CREATE TABLE Funding (company_id INT, funding_year INT, amount INT); INSERT INTO Funding (company_id, funding_year, amount) VALUES (1, 2015, 3000000); INSERT INTO Funding (company_id, funding_year, amount) VALUES (2, 2017, 5000000); INSERT INTO Funding (company_id, funding_year, amount) VALUES (3, 2017, 7000000);

SELECT company_id, SUM(amount) as total_funding FROM Funding WHERE funding_year = 2017 GROUP BY company_id ORDER BY total_funding DESC;


Question: Generate PostgreSQL SQL for: Who played the Rams on October 2, 2005?

CREATE TABLE table_name_22 (opponent VARCHAR, date VARCHAR)

SELECT opponent FROM table_name_22 WHERE date = 'october 2, 2005';


Question: pgTAP test for Functap (assertion 379).

SELECT * FROM check_test(
    volatility_is( 'oww', 'immutable', 'whatever' ),
    true,
    'function_volatility(func, immutable, desc)',
    'whatever',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Functap.


Question: Generate PostgreSQL SQL for: What is the most recent year founded that has a nickname of bruins?

CREATE TABLE table_name_7 (founded INTEGER, nickname VARCHAR)

SELECT MAX(founded) FROM table_name_7 WHERE nickname = 'bruins';


Question: get the average age of athletes in the basketball team

CREATE TABLE athletes (id INT PRIMARY KEY, name VARCHAR(100), age INT, sport VARCHAR(50), team VARCHAR(50));

SELECT AVG(age) FROM athletes WHERE sport = 'Basketball' AND team = 'Chicago Bulls';


Question: What is the maximum speed reached by an electric vehicle in a shared fleet in San Francisco?

CREATE TABLE shared_ev (vehicle_id INT, trip_id INT, trip_start_time TIMESTAMP, trip_end_time TIMESTAMP, start_latitude DECIMAL(9,6), start_longitude DECIMAL(9,6), end_latitude DECIMAL(9,6), end_longitude DECIMAL(9,6), distance DECIMAL(10,2), max_speed DECIMAL(5,2));

SELECT MAX(max_speed) FROM shared_ev WHERE start_longitude BETWEEN -122.6 AND -121.9 AND start_latitude BETWEEN 37.6 AND 38.1;


Question: Generate PostgreSQL SQL for: When the Border Conference was held, who was the tournament winner?

CREATE TABLE table_22733636_1 (tournament_winner VARCHAR, conference VARCHAR)

SELECT tournament_winner FROM table_22733636_1 WHERE conference = 'Border conference';


Question: Find the difference in costs between the first and last project in 'Road_Infrastructure' table.

CREATE TABLE Road_Infrastructure (id INT, project_name VARCHAR(50), location VARCHAR(50), cost INT);

SELECT (MAX(cost) - MIN(cost)) AS cost_difference FROM (SELECT cost FROM Road_Infrastructure ORDER BY id LIMIT 1 OFFSET 1) AS first_project CROSS JOIN (SELECT cost FROM Road_Infrastructure ORDER BY id DESC LIMIT 1) AS last_project;


Question: Delete records in circular_economy table where initiative is 'Composting Program'

CREATE TABLE circular_economy (id INT PRIMARY KEY, location VARCHAR(255), initiative VARCHAR(255), start_date DATE, end_date DATE);

DELETE FROM circular_economy WHERE initiative = 'Composting Program';


Question: List all farms in the 'farms' table and their corresponding region.

CREATE TABLE farms (id INT, name TEXT, region TEXT); INSERT INTO farms (id, name, region) VALUES (1, 'Farm A', 'Asia-Pacific'); INSERT INTO farms (id, name, region) VALUES (2, 'Farm B', 'Europe'); INSERT INTO farms (id, name, region) VALUES (3, 'Farm C', 'Asia-Pacific'); INSERT INTO farms (id, name, region) VALUES (4, 'Farm D', 'Europe');


Question: pgTAP test for Performs Within (assertion 4).

SELECT * FROM check_test(
    performs_within( 'SELECT TRUE', 99.99, 99.99 ),
    true,
    'simple select numeric',
    'Should run within 99.99 +/- 99.99 ms',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Performs Within.


Question: What is the minimum donation amount made by donors from each country in Q3 of 2021?

CREATE TABLE Donors (id INT, name TEXT, country TEXT, donation FLOAT, quarter TEXT, year INT); INSERT INTO Donors (id, name, country, donation, quarter, year) VALUES (1, 'Charlie', 'USA', 120.0, 'Q3', 2021), (2, 'David', 'Mexico', 90.0, 'Q3', 2021), (3, 'Eve', 'Canada', 110.0, 'Q3', 2021), (4, 'Frank', 'USA', 130.0, 'Q3', 2021);

SELECT country, MIN(donation) FROM Donors WHERE quarter = 'Q3' AND year = 2021 GROUP BY country;


Question: What is the average diversity score of startups that have received funding in the last 3 years, grouped by industry?

CREATE TABLE company (id INT, name TEXT, industry TEXT, founding_year INT, diversity_score INT); INSERT INTO company (id, name, industry, founding_year, diversity_score) VALUES (1, 'InnoTech', 'Tech', 2018, 80); INSERT INTO company (id, name, industry, founding_year, diversity_score) VALUES (2, 'GreenEnergy', 'Energy', 2019, 90); INSERT INTO company (id, name, industry, founding_year, diversity_score) VALUES (3, 'EduTech', 'Education', 2020, 85); CREATE TABLE funding (company_id INT, amount INT, funding_date DATE); INSERT INTO funding (company_id, amount, funding_date) VALUES (1, 1500000, '2021-01-01'); INSERT INTO funding (company_id, amount, funding_date) VALUES (2, 1200000, '2020-01-01'); INSERT INTO funding (company_id, amount, funding_date) VALUES (3, 800000, '2019-01-01');

SELECT industry, AVG(diversity_score) FROM company INNER JOIN funding ON company.id = funding.company_id WHERE funding.funding_date >= DATEADD(year, -3, GETDATE()) GROUP BY industry;


Question: Write the DML statement from PostgreSQL regression test 'create_table_like' (example 60).

INSERT INTO inhg (xx, yy, x) VALUES ('test', 5, 10);

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


Question: What is the average cargo handling time for each port?

CREATE TABLE cargo_handling (id INT, ship_id INT, port_id INT, handling_time INT); INSERT INTO cargo_handling (id, ship_id, port_id, handling_time) VALUES (1, 1, 1, 50), (2, 2, 2, 75), (3, 3, 1, 35); CREATE TABLE ports (id INT, name VARCHAR(50)); INSERT INTO ports (id, name) VALUES (1, 'Port of New York'), (2, 'Port of Los Angeles'), (3, 'Port of Miami');

SELECT ports.name, AVG(cargo_handling.handling_time) FROM cargo_handling JOIN ports ON cargo_handling.port_id = ports.id GROUP BY ports.id, ports.name;


Question: Generate PostgreSQL SQL for: How many players went to depaul?

CREATE TABLE table_16494599_2 (player VARCHAR, school_club_team VARCHAR)

SELECT COUNT(player) FROM table_16494599_2 WHERE school_club_team = 'DePaul';


Question: What is the distribution of employees by department and job level?

CREATE TABLE departments (dept_id INT, dept_name TEXT); INSERT INTO departments (dept_id, dept_name) VALUES (1, 'HR'), (2, 'IT'), (3, 'Sales'); CREATE TABLE employees (employee_id INT, name TEXT, salary INT, dept_id INT, job_level TEXT); INSERT INTO employees (employee_id, name, salary, dept_id, job_level) VALUES (1, 'Alice', 50000, 1, 'Manager'), (2, 'Bob', 60000, 2, 'Senior'), (3, 'Charlie', 55000, 1, 'Junior'), (4, 'Dave', 65000, 2, 'Senior'), (5, 'Eve', 52000, 1, 'Manager');

SELECT dept_name, job_level, COUNT(*) AS num_employees FROM employees JOIN departments ON employees.dept_id = departments.dept_id GROUP BY dept_name, job_level;


Question: What is the minimum ocean acidification level ever recorded?

CREATE TABLE ocean_acidification (id INT, avg_level FLOAT); INSERT INTO ocean_acidification (id, avg_level) VALUES (1, 7.5); INSERT INTO ocean_acidification (id, avg_level) VALUES (2, 8.0);

SELECT MIN(avg_level) FROM ocean_acidification;


Question: Delete the TalentAcquisition table

CREATE TABLE TalentAcquisition (ApplicantID INT PRIMARY KEY, JobTitle VARCHAR(30), Department VARCHAR(20), ApplicationDate DATE);


Question: Generate PostgreSQL SQL for: What is the Laid down for the Hyperion ship?

CREATE TABLE table_name_55 (laid_down VARCHAR, ship VARCHAR)

SELECT laid_down FROM table_name_55 WHERE ship = 'hyperion';


Question: Generate PostgreSQL SQL for: What was the place in Germany with a score of 69-69=138?

CREATE TABLE table_name_24 (place VARCHAR, country VARCHAR, score VARCHAR)

SELECT place FROM table_name_24 WHERE score = 69 - 69 = 138 AND country = 'germany';


Question: Write the DDL statement from PostgreSQL regression test 'stats_ext' (example 735).

CREATE FUNCTION op_leak(record, record) RETURNS bool
    AS 'BEGIN RAISE NOTICE ''op_leak => %, %'', $1, $2; RETURN $1 < $2; END'
    LANGUAGE plpgsql;

Explanation: DDL from PostgreSQL core regression test for Stats Ext.


Question: How many patients have been treated in mental health facilities in Florida since 2017?

CREATE TABLE patients (id INT, treatment_date DATE, state TEXT); INSERT INTO patients (id, treatment_date, state) VALUES (1, '2017-01-01', 'Florida'); INSERT INTO patients (id, treatment_date, state) VALUES (2, '2016-12-31', 'California');

SELECT COUNT(*) FROM patients WHERE state = 'Florida' AND treatment_date >= '2017-01-01';


Question: Generate PostgreSQL SQL for: What visiting team has a record of 9–5–2?

CREATE TABLE table_name_93 (visitor VARCHAR, record VARCHAR)

SELECT visitor FROM table_name_93 WHERE record = '9–5–2';


Question: What is the average cargo handling time for vessels in port 'Seattle'?

CREATE TABLE cargo_handling (id INT, vessel_name VARCHAR(50), port VARCHAR(50), handling_time INT); INSERT INTO cargo_handling (id, vessel_name, port, handling_time) VALUES (1, 'Seattle Voyager', 'Seattle', 8), (2, 'Seattle Voyager', 'Seattle', 10);

SELECT AVG(handling_time) FROM cargo_handling WHERE port = 'Seattle';


Question: Which climate monitoring stations are located in the same country as 'Station A'?

CREATE TABLE climate_monitoring_stations (id INT, station_name VARCHAR(255), country VARCHAR(255)); INSERT INTO climate_monitoring_stations (id, station_name, country) VALUES (1, 'Station A', 'canada'), (2, 'Station B', 'greenland'), (3, 'Station C', 'canada'), (4, 'Station D', 'norway');

SELECT station_name FROM climate_monitoring_stations WHERE country = (SELECT country FROM climate_monitoring_stations WHERE station_name = 'Station A');


Question: Generate PostgreSQL SQL for: Name the last appearance for music city bowl

CREATE TABLE table_2517159_1 (last_appearance VARCHAR, name_of_bowl VARCHAR)

SELECT last_appearance FROM table_2517159_1 WHERE name_of_bowl = 'Music City Bowl';


Question: Which explainable AI techniques are used in 'lime' tool?

CREATE TABLE explainable_ai (tool VARCHAR(255), technique VARCHAR(255)); INSERT INTO explainable_ai (tool, technique) VALUES ('LIME', 'Local Surrogate Models'), ('SHAP', 'Additive Feature Attribution');

SELECT technique FROM explainable_ai WHERE tool = 'LIME';


Question: Generate PostgreSQL SQL for: What purses had a winners share equal to $428650?

CREATE TABLE table_1520559_1 (purse___$__ VARCHAR, winners_share__$_ VARCHAR)

SELECT purse___$__ FROM table_1520559_1 WHERE winners_share__$_ = 428650;


Question: pgTAP test for Coltap (assertion 72).

/****************************************************************************/
-- Test col_default_is().

SELECT * FROM check_test(
    col_default_is( 'public', 'sometab', 'name', ''::text, 'name should default to empty string' ),
    true,
    'col_default_is( sch, tab, col, def, desc )',
    'name should default to empty string',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Coltap.


Question: Write the DDL statement from PostgreSQL regression test 'partition_merge' (example 62).

CREATE TABLE sales_dec2022 PARTITION OF sales_date FOR VALUES FROM (2021, 12, 1) TO (2022, 1, 1);

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


Question: What is the total production of Lanthanum in 2018 and 2019?

CREATE TABLE production (year INT, element VARCHAR(10), quantity INT); INSERT INTO production (year, element, quantity) VALUES (2017, 'Lanthanum', 1500), (2018, 'Lanthanum', 1600), (2019, 'Lanthanum', 1700), (2020, 'Lanthanum', 1800);

SELECT SUM(quantity) FROM production WHERE element = 'Lanthanum' AND year IN (2018, 2019);


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

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


Question: What is the minimum adoption revenue of virtual reality hardware in Middle East?

CREATE TABLE VRHardwareMiddleEast (HardwareID INT, HardwareName VARCHAR(100), AdoptionRevenue DECIMAL(10,2), Country VARCHAR(50)); INSERT INTO VRHardwareMiddleEast (HardwareID, HardwareName, AdoptionRevenue, Country) VALUES (1, 'VR Headset A', 700.00, 'Saudi Arabia'), (2, 'VR Headset B', 800.00, 'United Arab Emirates'), (3, 'VR Headset C', 900.00, 'Turkey');

SELECT MIN(AdoptionRevenue) FROM VRHardwareMiddleEast WHERE Country = 'Middle East';


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

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

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


Question: Generate PostgreSQL SQL for: What are all the fault descriptions and the fault status of all the faults recoreded in the logs?

CREATE TABLE Fault_Log (fault_description VARCHAR, fault_log_entry_id VARCHAR); CREATE TABLE Fault_Log_Parts (fault_status VARCHAR, fault_log_entry_id VARCHAR)

SELECT T1.fault_description, T2.fault_status FROM Fault_Log AS T1 JOIN Fault_Log_Parts AS T2 ON T1.fault_log_entry_id = T2.fault_log_entry_id;


Question: Generate PostgreSQL SQL for: What team has tony parker (10) as the high assists, kurt thomas (12) as the high rebounds?

CREATE TABLE table_name_57 (team VARCHAR, high_assists VARCHAR, high_rebounds VARCHAR)

SELECT team FROM table_name_57 WHERE high_assists = 'tony parker (10)' AND high_rebounds = 'kurt thomas (12)';


Question: Generate PostgreSQL SQL for: What was the record for the game on April 9, 2008?

CREATE TABLE table_name_9 (record VARCHAR, date VARCHAR)

SELECT record FROM table_name_9 WHERE date = 'april 9, 2008';


Question: Generate PostgreSQL SQL for: What is Japan's Area km²?

CREATE TABLE table_name_45 (area_km² VARCHAR, country VARCHAR)

SELECT area_km² FROM table_name_45 WHERE country = 'japan';


Question: List all donations made to the 'Education' program in the 'NonprofitDB' database, along with the donor's name and address.

CREATE TABLE Donation (ID INT, Amount DECIMAL(10, 2), DonorID INT, ProgramID INT); INSERT INTO Donation (ID, Amount, DonorID, ProgramID) VALUES (1, 500.00, 1, 1), (2, 1000.00, 2, 1), (3, 250.00, 3, 1), (4, 750.00, 4, 2); CREATE TABLE Donor (ID INT, Name VARCHAR(255), Address VARCHAR(255)); INSERT INTO Donor (ID, Name, Address) VALUES (1, 'John Doe', '123 Main St'), (2, 'Jane Smith', '456 Elm St'), (3, 'Alice Johnson', '789 Oak St'), (4, 'Bob Brown', '321 Pine St');

SELECT d.Amount, d.DonorID, donor.Name, donor.Address FROM Donation d JOIN Donor donor ON d.DonorID = donor.ID WHERE d.ProgramID = 1;


Question: Generate PostgreSQL SQL for: What is the total roll with a decile less than 7, and an authority of state, in the Macraes Flat area?

CREATE TABLE table_name_98 (roll VARCHAR, area VARCHAR, decile VARCHAR, authority VARCHAR)

SELECT COUNT(roll) FROM table_name_98 WHERE decile = 7 AND authority = 'state' AND area = 'macraes flat';


Question: Update the org_location of 'Habitat for Humanity' to 'San Francisco' in the 'Organizations' table

CREATE TABLE Organizations (org_id INT, org_name TEXT, org_location TEXT);

UPDATE Organizations SET org_location = 'San Francisco' WHERE org_name = 'Habitat for Humanity';


Question: List all policies that are related to mobility impairments and the corresponding policy advocates.

CREATE TABLE Policies (PolicyID INT, PolicyName VARCHAR(50), PolicyType VARCHAR(50)); INSERT INTO Policies VALUES (1, 'Ramp Accessibility', 'Infrastructure'); CREATE TABLE PolicyAdvocates (AdvocateID INT, AdvocateName VARCHAR(50), PolicyID INT); INSERT INTO PolicyAdvocates VALUES (1, 'Jane Doe', 1); CREATE TABLE PolicyDetails (PolicyID INT, DisabilityType VARCHAR(50)); INSERT INTO PolicyDetails VALUES (1, 'Mobility Impairment');

SELECT p.PolicyName, pa.AdvocateName FROM Policies p INNER JOIN PolicyDetails pd ON p.PolicyID = pd.PolicyID INNER JOIN PolicyAdvocates pa ON p.PolicyID = pa.PolicyID WHERE pd.DisabilityType = 'Mobility Impairment';


Question: Generate PostgreSQL SQL for: Who did the team play against when a record of 3-1, #16 was achieved?

CREATE TABLE table_21063459_1 (opponent VARCHAR, record VARCHAR)

SELECT opponent FROM table_21063459_1 WHERE record = '3-1, #16';


Question: What are the names of the biosensor technology development projects in Canada?

CREATE SCHEMA if not exists biosensors;CREATE TABLE if not exists biosensors.projects (id INT PRIMARY KEY, name VARCHAR(100), country VARCHAR(50)); INSERT INTO biosensors.projects (id, name, country) VALUES (1, 'ProjectX', 'Germany'), (2, 'ProjectY', 'Canada'), (3, 'ProjectZ', 'USA');

SELECT name FROM biosensors.projects WHERE country = 'Canada';


Question: List all defense diplomacy events that have taken place in the Asia-Pacific region in the last 5 years, along with the number of participating countries.

CREATE TABLE DefenseDiplomacy (ID INT, EventName TEXT, EventDate DATE, ParticipatingCountries TEXT); INSERT INTO DefenseDiplomacy VALUES (1, 'Event 1', '2017-01-01', 'China, Japan, South Korea'); CREATE VIEW AsiaPacific AS SELECT Country FROM DefenseDiplomacy WHERE Country IN ('China', 'Japan', 'South Korea', 'Australia', 'India');

SELECT EventName, ParticipatingCountries, COUNT(DISTINCT SUBSTRING_INDEX(ParticipatingCountries, ',', n)) as NumberOfCountries FROM DefenseDiplomacy d CROSS JOIN (SELECT numbers.N FROM (SELECT 1 as N UNION ALL SELECT 2 UNION ALL SELECT 3) numbers) n JOIN AsiaPacific ap ON d.Country = ap.Country WHERE EventDate BETWEEN DATEADD(year, -5, GETDATE()) AND GETDATE() GROUP BY EventName, ParticipatingCountries;


Question: What is the percentage of users who liked articles about 'sports' and also liked articles about 'entertainment'?

CREATE TABLE users (id INT, name TEXT, likes INT); CREATE TABLE user_likes (user_id INT, article_id INT); CREATE TABLE articles (id INT, title TEXT, category TEXT);

SELECT (COUNT(*) / (SELECT COUNT(*) FROM users)) * 100.0 AS percentage FROM user_likes JOIN users ON user_likes.user_id = users.id JOIN articles ON user_likes.article_id = articles.id WHERE articles.category = 'sports' INTERSECT SELECT user_likes.user_id FROM user_likes JOIN users ON user_likes.user_id = users.id JOIN articles ON user_likes.article_id = articles.id WHERE articles.category = 'entertainment';


Question: Generate PostgreSQL SQL for: What percentages of social democratic correspond to a 5.5% left bloc?

CREATE TABLE table_1463383_1 (social_democratic VARCHAR, left_bloc VARCHAR)

SELECT social_democratic FROM table_1463383_1 WHERE left_bloc = '5.5%';


Question: Generate PostgreSQL SQL for: find the program owners that have some programs in both morning and night time.

CREATE TABLE broadcast (program_id VARCHAR, Time_of_day VARCHAR); CREATE TABLE program (owner VARCHAR, program_id VARCHAR)

SELECT t1.owner FROM program AS t1 JOIN broadcast AS t2 ON t1.program_id = t2.program_id WHERE t2.Time_of_day = 'Morning' INTERSECT SELECT t1.owner FROM program AS t1 JOIN broadcast AS t2 ON t1.program_id = t2.program_id WHERE t2.Time_of_day = 'Night';


Question: Generate PostgreSQL SQL for: what is the biggest series episode number whose production code is 2t7211?

CREATE TABLE table_21979779_1 (no INTEGER, production_code VARCHAR)

SELECT MAX(no) FROM table_21979779_1 WHERE production_code = '2T7211';


Question: Generate PostgreSQL SQL for: How many problems does the product with the most problems have? List the number of the problems and product name.

CREATE TABLE problems (product_id VARCHAR); CREATE TABLE product (product_name VARCHAR, product_id VARCHAR)

SELECT COUNT(*), T1.product_name FROM product AS T1 JOIN problems AS T2 ON T1.product_id = T2.product_id GROUP BY T1.product_name ORDER BY COUNT(*) DESC LIMIT 1;


Question: List all the forest types with their respective wildlife habitat areas.

CREATE TABLE forest_types (id INT, type VARCHAR(255)); CREATE TABLE wildlife_habitat (id INT, type VARCHAR(255), area INT); INSERT INTO forest_types (id, type) VALUES (1, 'Coniferous'), (2, 'Deciduous'), (3, 'Mangrove'); INSERT INTO wildlife_habitat (id, type, area) VALUES (1, 'Coniferous', 500), (2, 'Deciduous', 700), (3, 'Mangrove', 600);

SELECT forest_types.type, wildlife_habitat.area FROM forest_types INNER JOIN wildlife_habitat ON forest_types.id = wildlife_habitat.id;


Question: Delete all records in the "RuralInfrastructure" table where type is 'dam' and the construction_year is before 1980

CREATE TABLE RuralInfrastructure (id INT PRIMARY KEY, type VARCHAR(255), construction_year INT);

DELETE FROM RuralInfrastructure WHERE type = 'dam' AND construction_year < 1980;


Question: Generate PostgreSQL SQL for: Which province has the partido Socialista del Pueblo Extremeño party?

CREATE TABLE table_name_31 (province VARCHAR, party VARCHAR)

SELECT province FROM table_name_31 WHERE party = 'partido socialista del pueblo extremeño';


Question: What is the total number of artifacts and the total number of unique materials represented at each excavation site?

CREATE TABLE ExcavationSites (SiteID int, SiteName varchar(50), Location varchar(50)); CREATE TABLE Artifacts (ArtifactID int, SiteID int, Material varchar(20), Description varchar(100));

SELECT ExcavationSites.SiteName, COUNT(DISTINCT Artifacts.ArtifactID) AS NumberOfArtifacts, COUNT(DISTINCT Artifacts.Material) AS NumberOfMaterials FROM ExcavationSites INNER JOIN Artifacts ON ExcavationSites.SiteID = Artifacts.SiteID GROUP BY ExcavationSites.SiteName;


Question: What is the maximum number of threat indicators for the healthcare sector in the United States?

CREATE TABLE threat_indicators (id INT, sector TEXT, country TEXT, confidence INT); INSERT INTO threat_indicators (id, sector, country, confidence) VALUES (1, 'Healthcare', 'USA', 85); INSERT INTO threat_indicators (id, sector, country, confidence) VALUES (2, 'Healthcare', 'USA', 70); INSERT INTO threat_indicators (id, sector, country, confidence) VALUES (3, 'Healthcare', 'Canada', 88);

SELECT MAX(confidence) FROM threat_indicators WHERE sector = 'Healthcare' AND country = 'USA';


Question: Generate PostgreSQL SQL for: In what competition was the score reported as 12.8 (80) - 8.7 (55)?

CREATE TABLE table_name_30 (competition VARCHAR, score VARCHAR)

SELECT competition FROM table_name_30 WHERE score = '12.8 (80) - 8.7 (55)';


Question: Generate PostgreSQL SQL for: What is the highest number of games drawn, where the games played was less than 7?

CREATE TABLE table_name_86 (drawn INTEGER, games INTEGER)

SELECT MAX(drawn) FROM table_name_86 WHERE games < 7;


Question: What is the number of drugs approved for use in 'RegionH' between Q1 and Q3 of 2020?

CREATE TABLE drug_approval(drug_name TEXT, region TEXT, approval_quarter INT); INSERT INTO drug_approval (drug_name, region, approval_quarter) VALUES ('DrugA', 'RegionX', 1), ('DrugB', 'RegionY', 2), ('DrugD', 'RegionH', 1), ('DrugC', 'RegionZ', 4), ('DrugE', 'RegionH', 3), ('DrugF', 'RegionH', 2);

SELECT COUNT(*) FROM drug_approval WHERE region = 'RegionH' AND approval_quarter BETWEEN 1 AND 3;


Question: What is the maximum number of streams for R&B songs released in 2021?

CREATE TABLE songs (song_id INT, genre VARCHAR(20), release_year INT, streams INT); INSERT INTO songs (song_id, genre, release_year, streams) VALUES (1, 'R&B', 2021, 7000); INSERT INTO songs (song_id, genre, release_year, streams) VALUES (2, 'R&B', 2021, 8000); INSERT INTO songs (song_id, genre, release_year, streams) VALUES (3, 'R&B', 2021, 9000);

SELECT MAX(streams) FROM songs WHERE genre = 'R&B' AND release_year = 2021;


Question: Generate PostgreSQL SQL for: Who was the writer of the episode with a production code of 5aky04?

CREATE TABLE table_26826304_1 (written_by VARCHAR, production_code VARCHAR)

SELECT written_by FROM table_26826304_1 WHERE production_code = '5AKY04';


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

create temp table inner_text (c1 text, c2 text);

Explanation: DDL from PostgreSQL core regression test for Subselect.


Question: Generate PostgreSQL SQL for: Who directed the episode which originally aired February 4, 2005?

CREATE TABLE table_228973_11 (directed_by VARCHAR, original_air_date VARCHAR)

SELECT directed_by FROM table_228973_11 WHERE original_air_date = 'February 4, 2005';


Question: Generate PostgreSQL SQL for: What's the Nordbayern with a Württemberg of Union Böckingen in the year before 1932?

CREATE TABLE table_name_92 (nordbayern VARCHAR, year VARCHAR, württemberg VARCHAR)

SELECT nordbayern FROM table_name_92 WHERE year < 1932 AND württemberg = 'union böckingen';


Question: Generate PostgreSQL SQL for: Which season has Caps lower than 36 for the Club of NAC Breda?

CREATE TABLE table_name_35 (season VARCHAR, caps VARCHAR, club VARCHAR)

SELECT season FROM table_name_35 WHERE caps < 36 AND club = 'nac breda';


Question: What is the total cargo capacity for all vessels in the 'vessels' table that have an even ID?

CREATE TABLE vessels (vessel_id INT, vessel_name VARCHAR(50), registry VARCHAR(50), capacity INT); INSERT INTO vessels (vessel_id, vessel_name, registry, capacity) VALUES (1, 'CSCL Globe', 'China', 197500), (2, 'OOCL Hong Kong', 'Hong Kong', 210000), (3, 'MSC Maya', 'Panama', 192240);

SELECT SUM(capacity) FROM vessels WHERE MOD(vessel_id, 2) = 0;


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

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

SELECT count(*) FROM (select jsonb_path_query('[1,"2",3]', '+$')) AS _sub;


Question: Generate PostgreSQL SQL for: What score has houston texans as the opponent?

CREATE TABLE table_name_62 (score VARCHAR, opponent VARCHAR)

SELECT score FROM table_name_62 WHERE opponent = 'houston texans';