Question: Generate PostgreSQL SQL for: What is the stadium of the NK Zagreb?

CREATE TABLE table_name_70 (stadium VARCHAR, team VARCHAR)

SELECT stadium FROM table_name_70 WHERE team = 'nk zagreb';


Question: List all climate mitigation projects in Asia that were started after 2015 and their respective budgets.

CREATE TABLE climate_projects (project_name VARCHAR(50), location VARCHAR(50), start_year INT, budget INT, sector VARCHAR(50)); INSERT INTO climate_projects (project_name, location, start_year, budget, sector) VALUES ('Solar Farm A', 'China', 2017, 1000000, 'Solar'), ('Wind Farm B', 'India', 2018, 1500000, 'Wind');

SELECT project_name, location, budget FROM climate_projects WHERE location IN ('Asia') AND start_year > 2015 AND sector = 'Climate Mitigation';


Question: What is the average budget per program?

CREATE TABLE Programs (id INT, program TEXT, budget DECIMAL(10,2)); INSERT INTO Programs (id, program, budget) VALUES (1, 'Feeding the Hungry', 5000.00), (2, 'Clothing Drive', 3000.00), (3, 'Education', 7000.00);

SELECT program, AVG(budget) FROM Programs GROUP BY program;


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

SELECT * FROM bt_multi_page_stats('test2_col1_idx', 3, 2);

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


Question: pgTAP test for Ownership (assertion 55).

SELECT * FROM check_test(
    table_owner_is('apart', current_user, 'mumble'),
	true,
    'table_owner_is(part, user, desc)',
    'mumble',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Ownership.


Question: Update the launch date of digital asset with id = 2 to '2021-03-16'.

CREATE TABLE digital_assets (id INT, name VARCHAR(255), company VARCHAR(255), launch_date DATE, developer VARCHAR(255)); INSERT INTO digital_assets (id, name, company, launch_date, developer) VALUES (1, 'Asset 1', 'Company A', '2021-01-01', 'Alice Johnson'), (2, 'Asset 2', 'Company B', '2021-02-15', 'Bruno Alvarez');

UPDATE digital_assets SET launch_date = '2021-03-16' WHERE id = 2;


Question: What is the average length of hospital stays for patients with eating disorders?

CREATE TABLE stays (id INT, patient_id INT, length INT, condition TEXT); CREATE TABLE conditions (id INT, name TEXT); INSERT INTO conditions (id, name) VALUES (1, 'Eating Disorder');

SELECT AVG(length) FROM stays WHERE condition = 'Eating Disorder';


Question: Generate PostgreSQL SQL for: During the game at Candlestick Park, who was the visiting team?

CREATE TABLE table_name_99 (visiting_team VARCHAR, stadium VARCHAR)

SELECT visiting_team FROM table_name_99 WHERE stadium = 'candlestick park';


Question: Which cruelty-free cosmetic products have the highest sales in the UK?

CREATE TABLE products (product_id INT, product_name TEXT, is_cruelty_free BOOLEAN, sales INT, country TEXT); INSERT INTO products (product_id, product_name, is_cruelty_free, sales, country) VALUES (1, 'Lipstick', true, 550, 'UK'), (2, 'Foundation', false, 600, 'UK'), (3, 'Mascara', true, 700, 'UK');

SELECT product_name, SUM(sales) as total_sales FROM products WHERE is_cruelty_free = true AND country = 'UK' GROUP BY product_name ORDER BY total_sales DESC;


Question: What is the total revenue by platform?

CREATE TABLE ad_data (platform VARCHAR(20), revenue NUMERIC(10,2));INSERT INTO ad_data VALUES ('FB',1000),('IG',2000),('TW',3000),('SN',4000),('LI',5000);

SELECT platform, SUM(revenue) FROM ad_data GROUP BY platform;


Question: What is the minimum GPA of graduate students in the Physics department?

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

SELECT MIN(gs.gpa) FROM graduate_students gs WHERE gs.department = 'Physics';


Question: What is the average temperature trend in the Arctic Ocean, grouped by month, from January 2021 to December 2021?

CREATE TABLE OceanTemperature (Date DATE, Location VARCHAR(255), Temperature FLOAT); INSERT INTO OceanTemperature (Date, Location, Temperature) VALUES ('2021-01-01', 'Arctic Ocean', -1.5), ('2021-02-01', 'Arctic Ocean', -2.0);

SELECT DATE_FORMAT(Date, '%Y-%m') AS Month, AVG(Temperature) FROM OceanTemperature WHERE Date BETWEEN '2021-01-01' AND '2021-12-31' GROUP BY Month;


Question: What was the average exhibition duration for paintings, partitioned by artist?

CREATE TABLE GalleryG (gallery_name VARCHAR(20), artist VARCHAR(20), artwork_type VARCHAR(20), exhibition_duration INT); INSERT INTO GalleryG (gallery_name, artist, artwork_type, exhibition_duration) VALUES ('GalleryG', 'Picasso', 'Painting', 120), ('GalleryG', 'Picasso', 'Painting', 90), ('GalleryG', 'Dali', 'Painting', 60);

SELECT artist, AVG(exhibition_duration) as avg_duration FROM (SELECT gallery_name, artist, artwork_type, exhibition_duration, ROW_NUMBER() OVER (PARTITION BY gallery_name, artist ORDER BY exhibition_duration) as rn FROM GalleryG) tmp WHERE rn = 1 GROUP BY artist;


Question: List transactions from the last 30 days

CREATE TABLE transactions (id INT PRIMARY KEY, customer_id INT, amount DECIMAL(10,2), transaction_date DATE); INSERT INTO transactions (id, customer_id, amount, transaction_date) VALUES (1, 1, 500.00, '2022-01-01'); INSERT INTO transactions (id, customer_id, amount, transaction_date) VALUES (2, 2, 750.00, '2022-01-02');

SELECT * FROM transactions t WHERE t.transaction_date >= CURDATE() - INTERVAL 30 DAY;


Question: What is the total number of luxury hotels in Japan and Germany?

CREATE TABLE Hotels (id INT, country VARCHAR(50), category VARCHAR(50), PRIMARY KEY(id)); INSERT INTO Hotels (id, country, category) VALUES (1, 'Japan', 'Luxury'), (2, 'Germany', 'Luxury'), (3, 'Japan', 'Budget');

SELECT SUM(CASE WHEN country IN ('Japan', 'Germany') AND category = 'Luxury' THEN 1 ELSE 0 END) FROM Hotels;


Question: Generate PostgreSQL SQL for: What is the transfer window for Christian Nerlinger?

CREATE TABLE table_name_23 (transfer_window VARCHAR, name VARCHAR)

SELECT transfer_window FROM table_name_23 WHERE name = 'christian nerlinger';


Question: What is the maximum hectares of any forest in Brazil?

CREATE TABLE Forests (id INT, name VARCHAR(50), hectares FLOAT, country VARCHAR(50)); INSERT INTO Forests (id, name, hectares, country) VALUES (1, 'Amazon Rainforest', 55000000.0, 'Brazil'); CREATE TABLE Forest_Hectares (id INT, forest_id INT, hectares FLOAT); INSERT INTO Forest_Hectares (id, forest_id, hectares) VALUES (1, 1, 55000000.0);

SELECT MAX(hectares) FROM Forest_Hectares WHERE forest_id IN (SELECT id FROM Forests WHERE country = 'Brazil');


Question: Generate PostgreSQL SQL for: What is High Assists, when High Points is "Kobe Bryant (27)", and when High Rebounds is "Pau Gasol (11)"?

CREATE TABLE table_name_13 (high_assists VARCHAR, high_points VARCHAR, high_rebounds VARCHAR)

SELECT high_assists FROM table_name_13 WHERE high_points = 'kobe bryant (27)' AND high_rebounds = 'pau gasol (11)';


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

insert into test_range_spgist select 'empty'::int4range from generate_series(1,500) g;

Explanation: DML from PostgreSQL core regression test for Rangetypes.


Question: Generate PostgreSQL SQL for: With Laps greater than 78, what is the lowest Grid?

CREATE TABLE table_name_30 (grid INTEGER, laps INTEGER)

SELECT MIN(grid) FROM table_name_30 WHERE laps > 78;


Question: Generate PostgreSQL SQL for: What is the result for the date of august 23?

CREATE TABLE table_name_83 (result VARCHAR, date VARCHAR)

SELECT result FROM table_name_83 WHERE date = 'august 23';


Question: What are the health equity metrics in Colorado?

CREATE TABLE HealthEquity (id INT, metric_name TEXT, state TEXT); INSERT INTO HealthEquity (id, metric_name, state) VALUES (1, 'Access Index 2020', 'Colorado'); INSERT INTO HealthEquity (id, metric_name, state) VALUES (2, 'Quality Index 2018', 'Colorado');

SELECT * FROM HealthEquity WHERE state = 'Colorado';


Question: What is the minimum distance traveled by an electric vehicle in 'tokyo'?

CREATE TABLE vehicles (id INT, city VARCHAR(20), type VARCHAR(20), is_electric BOOLEAN, daily_distance INT); INSERT INTO vehicles VALUES (1, 'tokyo', 'sedan', true, 30); INSERT INTO vehicles VALUES (2, 'tokyo', 'suv', true, 40); INSERT INTO vehicles VALUES (3, 'osaka', 'truck', false, 50);

SELECT MIN(daily_distance) FROM vehicles WHERE city = 'tokyo' AND is_electric = true;


Question: What is the total quantity of chicken dishes sold in the month of January 2022?

CREATE TABLE menu (menu_id INT, name VARCHAR(50), category VARCHAR(50), price DECIMAL(5,2)); INSERT INTO menu (menu_id, name, category, price) VALUES (1, 'Chicken Alfredo', 'Pasta', 12.99), (2, 'Chicken Parmesan', 'Entree', 16.99); CREATE TABLE orders (order_id INT, order_date DATE, menu_id INT, quantity INT); INSERT INTO orders (order_id, order_date, menu_id, quantity) VALUES (1, '2022-01-03', 1, 3), (2, '2022-01-03', 2, 2), (3, '2022-01-05', 1, 1);

SELECT SUM(quantity) FROM orders JOIN menu ON orders.menu_id = menu.menu_id WHERE menu.category = 'Pasta' AND orders.order_date BETWEEN '2022-01-01' AND '2022-01-31';


Question: Generate PostgreSQL SQL for: When @ new orleans is the team who has the highest amount of rebounds?

CREATE TABLE table_17288825_6 (high_rebounds VARCHAR, team VARCHAR)

SELECT high_rebounds FROM table_17288825_6 WHERE team = '@ New Orleans';


Question: What is the total number of hours of professional development completed by teachers in the "Urban Education" district?

CREATE TABLE Teachers (TeacherID INT PRIMARY KEY, District VARCHAR(50), Hours INT); INSERT INTO Teachers (TeacherID, District, Hours) VALUES (1, 'Urban Education', 20);

SELECT SUM(Hours) FROM Teachers WHERE District = 'Urban Education';


Question: Generate PostgreSQL SQL for: Performer 2 of compilation 2 is what performer 1?

CREATE TABLE table_name_91 (performer_1 VARCHAR, performer_2 VARCHAR)

SELECT performer_1 FROM table_name_91 WHERE performer_2 = 'compilation 2';


Question: List all journalists who have published articles on a specific topic

CREATE TABLE journalists (id INT PRIMARY KEY, name TEXT NOT NULL); CREATE TABLE articles (id INT PRIMARY KEY, title TEXT NOT NULL, author_id INT, published_at DATE); CREATE TABLE articles_topics (article_id INT, topic_id INT); CREATE TABLE topics (id INT PRIMARY KEY, name TEXT NOT NULL);

SELECT journalists.name FROM journalists INNER JOIN articles ON journalists.id = articles.author_id INNER JOIN articles_topics ON articles.id = articles_topics.article_id INNER JOIN topics ON articles_topics.topic_id = topics.id WHERE topics.name = 'specific_topic';


Question: Display the names and construction dates of all bridges in Washington

CREATE TABLE bridges (id INT, name TEXT, construction_date DATE, location TEXT); INSERT INTO bridges (id, name, construction_date, location) VALUES (1, 'Bridge A', '1975-01-01', 'Washington'), (2, 'Bridge B', '1982-06-30', 'Texas');

SELECT name, construction_date FROM bridges WHERE location = 'Washington';


Question: What is the total number of building permits issued in each state for sustainable building practices?

CREATE TABLE permit_data (state VARCHAR(255), permit INT, sustainable BOOLEAN);   INSERT INTO permit_data (state, permit, sustainable) VALUES ('California', 500, TRUE), ('Texas', 400, FALSE), ('New York', 600, TRUE);

SELECT state, SUM(permit) FROM permit_data WHERE sustainable = TRUE GROUP BY state;


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

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


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

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

SELECT count(*) FROM (SELECT stddev_pop('inf'::numeric), stddev_samp('inf'::numeric)) AS _sub;


Question: How many donors from each country donated in 2023?

CREATE TABLE donors (donor_id INT, donation_date DATE, donation_amount DECIMAL(10, 2), country VARCHAR(50)); INSERT INTO donors VALUES (17, '2023-01-01', 50.00, 'Brazil'), (18, '2023-01-15', 100.00, 'India'), (19, '2023-03-05', 200.00, 'China');

SELECT country, COUNT(DISTINCT donor_id) FROM donors WHERE donation_date BETWEEN '2023-01-01' AND '2023-12-31' GROUP BY country;


Question: List all ships that entered the ports located in the USA in 2022, including their arrival dates and maximum cargo capacity.

CREATE TABLE ship (ship_id INT, ship_name VARCHAR(50), max_cargo_capacity INT); INSERT INTO ship VALUES (1, 'Sealand Eagle', 12000); INSERT INTO ship VALUES (2, 'MSC Flaminia', 15000); CREATE TABLE port_of_call (port_id INT, ship_id INT, call_date DATE, port_country VARCHAR(50)); INSERT INTO port_of_call VALUES (1, 1, '2022-03-20', 'USA');

SELECT s.ship_name, poc.call_date, s.max_cargo_capacity FROM ship s JOIN port_of_call poc ON s.ship_id = poc.ship_id JOIN port p ON poc.port_id = p.port_id WHERE p.port_country = 'USA' AND poc.call_date >= '2022-01-01' AND poc.call_date < '2023-01-01';


Question: Write the DML statement from PostgreSQL regression test 'macaddr8' (example 27).

INSERT INTO macaddr8_data VALUES (20, '08002b01:02030405');

Explanation: DML from PostgreSQL core regression test for Macaddr8.


Question: Generate PostgreSQL SQL for: How many total points does Mike Hyndman have with more than 119 assists?

CREATE TABLE table_name_98 (points INTEGER, player VARCHAR, assists VARCHAR)

SELECT SUM(points) FROM table_name_98 WHERE player = 'mike hyndman' AND assists > 119;


Question: Generate PostgreSQL SQL for: What is the country of the play based in Athens at the Attis Theatre company?

CREATE TABLE table_name_33 (country VARCHAR, base VARCHAR, company VARCHAR)

SELECT country FROM table_name_33 WHERE base = 'athens' AND company = 'attis theatre';


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

CREATE FUNCTION check_foreign_key()
RETURNS trigger
AS 'MODULE_PATHNAME'
LANGUAGE C;

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


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

INSERT INTO fk_notpartitioned_pk VALUES (2502, 2503);

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


Question: Calculate the average calories of vegan menu items in 'HealthyDiner' view.

CREATE VIEW HealthyDiner AS SELECT * FROM MenuItems WHERE is_vegan = TRUE;

SELECT AVG(calories) FROM HealthyDiner WHERE item_type = 'Main Course';


Question: List the total cargo weight for each cargo type in the 'cargo_tracking' table, grouped by week?

CREATE TABLE cargo_tracking (cargo_id INT, cargo_type VARCHAR(50), weight FLOAT, timestamp TIMESTAMP);

SELECT DATE_FORMAT(timestamp, '%Y-%u') AS week, cargo_type, SUM(weight) FROM cargo_tracking GROUP BY week, cargo_type;


Question: Delete the record for the veteran with the SSN 123-45-6789 from the employees table.

CREATE TABLE employees (ssn VARCHAR(11), first_name VARCHAR(20), last_name VARCHAR(20), job_title VARCHAR(30));

DELETE FROM employees WHERE ssn = '123-45-6789';


Question: pgTAP test for Valueset (assertion 311).

Explanation: SQL assertion from pgTAP test suite for Valueset.


Question: Generate PostgreSQL SQL for: Who is the opponent of the game after week 4 on Sun. Nov. 17?

CREATE TABLE table_name_70 (opponent VARCHAR, week VARCHAR, date VARCHAR)

SELECT opponent FROM table_name_70 WHERE week > 4 AND date = 'sun. nov. 17';


Question: Calculate the average property price for properties with inclusive housing policies in New York.

CREATE TABLE properties_inclusive_ny (id INT, price FLOAT); INSERT INTO properties_inclusive_ny (id, price) VALUES (1, 550000), (2, 600000), (3, 650000);

SELECT AVG(price) FROM properties_inclusive_ny WHERE id IN (SELECT property_id FROM inclusive_housing WHERE city = 'New York');


Question: What is the average CO2 emission (in grams) of factories in the 'Europe' region that manufactured 'Wool Sweaters' in Q4 of 2021?

CREATE TABLE CO2Emission (id INT PRIMARY KEY, factory_name VARCHAR(50), region VARCHAR(50), garment_type VARCHAR(50), co2_emission INT, manufacturing_date DATE); INSERT INTO CO2Emission (id, factory_name, region, garment_type, co2_emission, manufacturing_date) VALUES (1, 'Factory B', 'Europe', 'Wool Sweaters', 500, '2021-11-12');

SELECT AVG(co2_emission) as avg_co2_emission FROM CO2Emission WHERE region = 'Europe' AND garment_type = 'Wool Sweaters' AND manufacturing_date BETWEEN '2021-10-01' AND '2021-12-31';


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

SELECT citext_cmp('aardvark'::citext, 'aardVark'::citext) AS zero;

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


Question: What is the average dapp rating for each category?

CREATE TABLE dapp_categories (category_id INT, category_name VARCHAR(30), category_description TEXT, avg_rating DECIMAL(3,2), total_dapps INT); INSERT INTO dapp_categories (category_id, category_name, category_description, avg_rating, total_dapps) VALUES (1, 'Gaming', 'Interactive gaming applications', 4.4, 12), (2, 'Finance', 'Decentralized financial services', 4.6, 8), (3, 'Social', 'Social media and networking platforms', 4.1, 15);

SELECT category_name, avg_rating FROM dapp_categories;


Question: What is the average age of employees with the title 'Supervisor' in the 'employees' table?

CREATE TABLE employees(id INT, name VARCHAR(255), title VARCHAR(255), age INT); INSERT INTO employees(id, name, title, age) VALUES ('1', 'Jane Smith', 'Mining Supervisor', '55');

SELECT AVG(age) FROM employees WHERE title LIKE '%Supervisor%';


Question: Identify the number of unique ethical clothing brands in the inventory.

CREATE TABLE Inventory (id INT, product_name VARCHAR(255), brand VARCHAR(255), is_ethical BOOLEAN); INSERT INTO Inventory (id, product_name, brand, is_ethical) VALUES (1, 'Organic Cotton T-Shirt', 'Green Values', true), (2, 'Recycled Polyester Hoodie', 'EcoWear', true), (3, 'Regular T-Shirt', 'Fashion First', false);

SELECT COUNT(DISTINCT brand) FROM Inventory WHERE is_ethical = true;


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

ALTER TABLE cities ATTACH PARTITION cities_ab FOR VALUES IN ('a', 'b');

Explanation: PostgreSQL ALTER TABLE command.


Question: Generate PostgreSQL SQL for: Who replaced when position in table is pre-season?

CREATE TABLE table_10592536_8 (replaced_by VARCHAR, position_in_table VARCHAR)

SELECT replaced_by FROM table_10592536_8 WHERE position_in_table = 'Pre-season';


Question: Generate PostgreSQL SQL for: From what series is Peck Up Your Troubles?

CREATE TABLE table_name_66 (series VARCHAR, title VARCHAR)

SELECT series FROM table_name_66 WHERE title = 'peck up your troubles';


Question: Generate PostgreSQL SQL for: What is the date of the away game in week 8?

CREATE TABLE table_name_2 (date VARCHAR, home_away_game VARCHAR, week VARCHAR)

SELECT date FROM table_name_2 WHERE home_away_game = 'away' AND week = 8;


Question: Which community policing districts have the highest police interactions?

CREATE TABLE CommunityPolicing (id INT, district VARCHAR(255), police_interactions INT);

SELECT district, MAX(police_interactions) FROM CommunityPolicing GROUP BY district;


Question: How many satellites have been launched by each organization?

CREATE TABLE satellites_by_org (org TEXT, num_satellites INT); INSERT INTO satellites_by_org (org, num_satellites) VALUES ('NASA', 500), ('SpaceX', 300), ('ESA', 250), ('ULA', 200), ('ISRO', 150), ('Roscosmos', 100);

SELECT org, SUM(num_satellites) FROM satellites_by_org GROUP BY org;


Question: Generate PostgreSQL SQL for: What is the rank of The Big Doll House?

CREATE TABLE table_name_62 (rank INTEGER, title VARCHAR)

SELECT MIN(rank) FROM table_name_62 WHERE title = 'the big doll house';


Question: Which country has the highest total production of lead, Peru or the USA?

CREATE TABLE lead_production (country VARCHAR(20), quantity INT); INSERT INTO lead_production (country, quantity) VALUES ('Peru', 450000), ('USA', 400000);

SELECT country, MAX(quantity) FROM lead_production WHERE country IN ('Peru', 'USA') GROUP BY country;


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

SELECT * FROM pg_input_error_info('1,y', 'point');

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

SELECT count(*) FROM (SELECT * FROM pg_input_error_info('1,y', 'point')) AS _sub;


Question: What is the average recycling rate in percentage for the bottom 2 material types in 2019?

CREATE TABLE recycling_rates (material VARCHAR(255), year INT, rate FLOAT); INSERT INTO recycling_rates (material, year, rate) VALUES ('Plastic', 2019, 12.0), ('Glass', 2019, 22.0), ('Paper', 2019, 35.0), ('Metal', 2019, 45.0);

SELECT r.material, AVG(r.rate) as avg_rate FROM recycling_rates r WHERE r.year = 2019 AND r.material IN (SELECT material FROM recycling_rates WHERE year = 2019 ORDER BY rate LIMIT 2 OFFSET 2) GROUP BY r.material;


Question: Generate PostgreSQL SQL for: What is the sum of the ranks for the film, eddie murphy raw?

CREATE TABLE table_name_19 (rank INTEGER, title VARCHAR)

SELECT SUM(rank) FROM table_name_19 WHERE title = 'eddie murphy raw';


Question: Generate PostgreSQL SQL for: what's the no with current club being panathinaikos and position being forward

CREATE TABLE table_12962773_1 (no VARCHAR, current_club VARCHAR, position VARCHAR)

SELECT COUNT(no) FROM table_12962773_1 WHERE current_club = 'Panathinaikos' AND position = 'Forward';


Question: Generate PostgreSQL SQL for: How many totals does Chile have when the number of silvers is more than 0?

CREATE TABLE table_name_73 (total VARCHAR, nation VARCHAR, silver VARCHAR)

SELECT COUNT(total) FROM table_name_73 WHERE nation = 'chile' AND silver > 0;


Question: What is the average age of patients who have received cognitive behavioral therapy (CBT)?

CREATE TABLE patients (patient_id INT, age INT, gender VARCHAR(20), condition VARCHAR(50)); INSERT INTO patients (patient_id, age, gender, condition) VALUES (1, 35, 'Female', 'Depression'); CREATE TABLE treatments (treatment_id INT, patient_id INT, therapy_type VARCHAR(50), duration INT); INSERT INTO treatments (treatment_id, patient_id, therapy_type, duration) VALUES (1, 1, 'CBT', 12);

SELECT AVG(patients.age) FROM patients JOIN treatments ON patients.patient_id = treatments.patient_id WHERE treatments.therapy_type = 'CBT';


Question: What is the maximum daily water usage (in million gallons) in the state of New York in the summer months (June, July, August)?

CREATE TABLE ny_water_usage (id INT, daily_usage FLOAT, usage_location VARCHAR(255), usage_date DATE); INSERT INTO ny_water_usage (id, daily_usage, usage_location, usage_date) VALUES (1, 5.6, 'New York', '2022-07-01'), (2, 6.2, 'New York', '2022-08-01'), (3, 4.8, 'New York', '2022-05-01');

SELECT MAX(daily_usage) FROM ny_water_usage WHERE usage_location = 'New York' AND EXTRACT(MONTH FROM usage_date) IN (6, 7, 8);


Question: Write the DML statement from PostgreSQL regression test 'vacuum' (example 88).

INSERT INTO pvactst2 SELECT generate_series(1, 1000);

Explanation: DML from PostgreSQL core regression test for Vacuum.


Question: Generate PostgreSQL SQL for: How many people are in the crowd in south melbourne?

CREATE TABLE table_name_66 (crowd VARCHAR, home_team VARCHAR)

SELECT COUNT(crowd) FROM table_name_66 WHERE home_team = 'south melbourne';


Question: What is the total number of crimes committed in 'Sydney' in the month of 'February' for each year?

CREATE TABLE crimes (id INT, city VARCHAR(20), month VARCHAR(10), year INT, crimes INT);

SELECT year, SUM(crimes) FROM crimes WHERE city = 'Sydney' AND month = 'February' GROUP BY year;


Question: Calculate the maximum daily production quantity of copper for mining sites in Africa, for the year 2018, with over 50 employees.

CREATE TABLE copper_mine (site_id INT, country VARCHAR(50), num_employees INT, extraction_date DATE, quantity INT); INSERT INTO copper_mine (site_id, country, num_employees, extraction_date, quantity) VALUES (1, 'Africa', 65, '2018-01-02', 1500), (2, 'Africa', 55, '2018-12-31', 1700), (3, 'Africa', 70, '2018-03-04', 2100);

SELECT country, MAX(quantity) as max_daily_copper_prod FROM copper_mine WHERE num_employees > 50 AND country = 'Africa' AND extraction_date >= '2018-01-01' AND extraction_date <= '2018-12-31' GROUP BY country;


Question: What is the total number of autonomous vehicles sold in South Korea in 2020?

CREATE TABLE AutonomousSales (Id INT, Vehicle VARCHAR(100), Year INT, Country VARCHAR(50), IsAutonomous BOOLEAN); INSERT INTO AutonomousSales (Id, Vehicle, Year, Country, IsAutonomous) VALUES (1, 'Model S', 2020, 'South Korea', true), (2, 'Model 3', 2020, 'South Korea', true), (3, 'Golf', 2020, 'South Korea', false), (4, 'Polo', 2020, 'South Korea', false), (5, 'Tesla Model X', 2020, 'South Korea', true);

SELECT COUNT(*) FROM AutonomousSales WHERE Year = 2020 AND Country = 'South Korea' AND IsAutonomous = true;


Question: Generate PostgreSQL SQL for: What medium was used for the sculpture of George Harold Baker?

CREATE TABLE table_20903658_1 (medium VARCHAR, title_subject VARCHAR)

SELECT medium FROM table_20903658_1 WHERE title_subject = 'George Harold Baker';


Question: Compare the total sales revenue of recreational and medical cannabis in Michigan and Illinois.

CREATE TABLE sales_revenue (sales_type VARCHAR(10), state VARCHAR(20), revenue INT); INSERT INTO sales_revenue (sales_type, state, revenue) VALUES ('Recreational', 'Michigan', 1000); INSERT INTO sales_revenue (sales_type, state, revenue) VALUES ('Medical', 'Michigan', 800); INSERT INTO sales_revenue (sales_type, state, revenue) VALUES ('Recreational', 'Illinois', 1200); INSERT INTO sales_revenue (sales_type, state, revenue) VALUES ('Medical', 'Illinois', 900);

SELECT sales_type, state, SUM(revenue) FROM sales_revenue WHERE state IN ('Michigan', 'Illinois') GROUP BY sales_type, state;


Question: Write the DDL statement from PostgreSQL regression test 'create_type' (example 16).

CREATE TYPE int42 (
   internallength = 4,
   input = int42_in,
   output = int42_out,
   alignment = int4,
   default = 42,
   passedbyvalue
);

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


Question: What is the total revenue for restaurants that serve sustainable menu items?

CREATE TABLE restaurant_revenue(location VARCHAR(255), revenue INT); INSERT INTO restaurant_revenue(location, revenue) VALUES ('Location1', 5000), ('Location2', 7000), ('Location3', 3000), ('Restaurant4', 6000), ('Restaurant5', 4000), ('Restaurant9', 9000), ('Restaurant10', 8000);

SELECT SUM(revenue) FROM restaurant_revenue INNER JOIN sustainable_sourcing ON restaurant_revenue.location = sustainable_sourcing.menu_item WHERE sustainable = TRUE;


Question: What is the total number of network devices installed in each region and the total number of mobile subscribers in those regions?

CREATE TABLE network_devices (id INT, region VARCHAR(20), install_date DATE); CREATE TABLE mobile_subscribers (id INT, region VARCHAR(20), data_usage INT, usage_date DATE);

SELECT n.region, COUNT(n.id) AS num_devices, COUNT(m.id) AS num_subscribers FROM network_devices n INNER JOIN mobile_subscribers m ON n.region = m.region GROUP BY n.region;


Question: What is the total number of tourists visiting countries with a travel advisory level of 3 or higher?

CREATE TABLE travel_advisory (id INT, country VARCHAR(20), level INT); INSERT INTO travel_advisory (id, country, level) VALUES (1, 'Mexico', 2), (2, 'Brazil', 3), (3, 'Spain', 1), (4, 'Italy', 3), (5, 'Germany', 1);

SELECT SUM(tourists) FROM (SELECT 1 AS tourists FROM travel_advisory WHERE level >= 3);


Question: Generate PostgreSQL SQL for: What was the final score for the game that was contested on February 1, 2009?

CREATE TABLE table_10548224_1 (final_score VARCHAR, date_contested VARCHAR)

SELECT final_score FROM table_10548224_1 WHERE date_contested = 'February 1, 2009';


Question: Generate PostgreSQL SQL for: Where is the free fare zone for the Arena station?

CREATE TABLE table_name_65 (free_fare_zone VARCHAR, station_name VARCHAR)

SELECT free_fare_zone FROM table_name_65 WHERE station_name = 'arena';


Question: What is the total number of fish in all tanks on the farm?

CREATE TABLE Tank_Inventory (tank VARCHAR(50), species VARCHAR(50), quantity INT); INSERT INTO Tank_Inventory (tank, species, quantity) VALUES ('Tank1', 'Salmon', 200), ('Tank1', 'Trout', 150), ('Tank2', 'Salmon', 250), ('Tank2', 'Tilapia', 300);

SELECT SUM(quantity) FROM Tank_Inventory;


Question: How many green building projects are there in each city in the 'smart_cities' schema?

CREATE TABLE projects (project_id INT, city TEXT, schema_name TEXT); INSERT INTO projects (project_id, city, schema_name) VALUES (1, 'New York', 'smart_cities'), (2, 'Los Angeles', 'smart_cities'), (3, 'Chicago', 'smart_cities'), (4, 'Houston', 'smart_cities'); CREATE TABLE green_projects (project_id INT, project_type TEXT); INSERT INTO green_projects (project_id, project_type) VALUES (1, 'green building'), (2, 'renewable energy'), (3, 'smart city'), (4, 'carbon offset');

SELECT city, COUNT(DISTINCT project_id) FROM projects JOIN green_projects ON projects.project_id = green_projects.project_id WHERE schema_name = 'smart_cities' GROUP BY city;


Question: What is the maximum claim amount for renters insurance in Texas in the last month?

CREATE TABLE claims (id INT, state VARCHAR(2), policy_type VARCHAR(20), claim_amount DECIMAL(10,2), claim_date DATE); INSERT INTO claims (id, state, policy_type, claim_amount, claim_date) VALUES (1, 'TX', 'Auto', 2500, '2022-02-12'), (2, 'TX', 'Auto', 3500, '2022-06-23'), (3, 'TX', 'Renters', 1200, '2022-01-14');

SELECT MAX(claim_amount) FROM claims WHERE state = 'TX' AND policy_type = 'Renters' AND MONTH(claim_date) = 1;


Question: Generate PostgreSQL SQL for: What's the earliest year the new york giants lost at new meadowlands stadium?

CREATE TABLE table_name_31 (year INTEGER, loser VARCHAR, location VARCHAR)

SELECT MIN(year) FROM table_name_31 WHERE loser = 'new york giants' AND location = 'new meadowlands stadium';


Question: What is the average number of shots on goal for each team in the teams table, grouped by their league, and only for teams who have more than 200 shots on goal in total?

CREATE TABLE teams_stats (team_id INT PRIMARY KEY, team_name VARCHAR(255), league VARCHAR(50), shots_on_goal INT, FOREIGN KEY (team_id) REFERENCES teams(team_id));

SELECT league, AVG(shots_on_goal) as avg_shots_on_goal FROM teams_stats GROUP BY league HAVING SUM(shots_on_goal) > 200;


Question: Generate PostgreSQL SQL for: Where was Outback Steakhouse Pro-AM held?

CREATE TABLE table_15346009_1 (location VARCHAR, tournament VARCHAR)

SELECT location FROM table_15346009_1 WHERE tournament = 'Outback Steakhouse Pro-Am';


Question: Count the number of users who have achieved a step count greater than 15000 for at least 20 days in the last 30 days.

CREATE TABLE user_steps (user_id INT, date DATE, steps INT);

SELECT COUNT(DISTINCT user_id) FROM user_steps WHERE steps > 15000 GROUP BY user_id HAVING COUNT(DISTINCT date) >= 20 AND date >= CURDATE() - INTERVAL 30 DAY;


Question: What are the total biomass and stock counts for each species in Q1 2022?

CREATE TABLE fish_stock (date DATE, species VARCHAR(50), biomass FLOAT, stock_count INTEGER); INSERT INTO fish_stock (date, species, biomass, stock_count) VALUES ('2022-01-01', 'Tilapia', 2500, 5000);

SELECT EXTRACT(QUARTER FROM date) as quarter, species, SUM(biomass) as total_biomass, SUM(stock_count) as total_stock_count FROM fish_stock WHERE date >= '2022-01-01' AND date <= '2022-03-31' GROUP BY quarter, species;


Question: What is the average number of hours volunteered per volunteer?

CREATE TABLE Volunteer_Hours (id INT, hours INT, volunteer_id INT, month INT); CREATE TABLE Volunteers (id INT, name TEXT);

SELECT AVG(hours) as avg_hours_per_volunteer FROM Volunteer_Hours JOIN Volunteers ON Volunteer_Hours.volunteer_id = Volunteers.id;


Question: Show a query using PostgreSQL contrib extension 'isn' (example 4).

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


Question: What is the minimum price of eco-friendly tours in Costa Rica?

CREATE TABLE eco_tours (tour_id INT, name VARCHAR(255), country VARCHAR(255), price FLOAT, eco_friendly BOOLEAN); INSERT INTO eco_tours (tour_id, name, country, price, eco_friendly) VALUES (1, 'Rainforest Adventure', 'Costa Rica', 120.0, true), (2, 'Volcano Hike', 'Costa Rica', 80.0, true), (3, 'Beach Cleanup', 'Costa Rica', 50.0, true);

SELECT MIN(price) FROM eco_tours WHERE country = 'Costa Rica' AND eco_friendly = true;


Question: Which programs had the highest increase in total expenses compared to the same quarter last year?

CREATE TABLE programs (id INT, program_name VARCHAR(50), quarter INT, year INT, expenses DECIMAL(10,2)); INSERT INTO programs (id, program_name, quarter, year, expenses) VALUES (1, 'Education', 1, 2021, 15000.00), (2, 'Health', 2, 2021, 20000.00), (3, 'Education', 1, 2022, 17000.00), (4, 'Health', 2, 2022, 25000.00);

SELECT program_name, (expenses - (SELECT expenses FROM programs p2 WHERE p2.program_name = programs.program_name AND p2.quarter = programs.quarter AND p2.year = programs.year - 1)) AS difference INTO tmp_table FROM programs ORDER BY difference DESC LIMIT 1; SELECT program_name, difference FROM tmp_table; DROP TABLE tmp_table;


Question: What is the average time to complete threat intelligence reports, by region, for the top three contractors in the defense industry in the past year?

CREATE TABLE threat_intelligence_reports (report_id INT, report_date DATE, contractor TEXT, region TEXT, report_description TEXT, completion_date DATE); INSERT INTO threat_intelligence_reports (report_id, report_date, contractor, region, report_description, completion_date) VALUES (1, '2022-02-01', 'ACME Inc', 'Northeast', 'Cyber threat', '2022-02-05'), (2, '2022-03-15', 'Beta Corp', 'Midwest', 'Physical security threat', '2022-03-17'), (3, '2022-06-30', 'Gamma Industries', 'Southwest', 'Insider threat', '2022-07-05');

SELECT region, AVG(DATEDIFF(completion_date, report_date)) as avg_time_to_complete FROM threat_intelligence_reports WHERE contractor IN (SELECT contractor FROM (SELECT contractor, COUNT(*) as num_reports FROM threat_intelligence_reports GROUP BY contractor ORDER BY num_reports DESC LIMIT 3) as top_three_contractors) GROUP BY region;


Question: What is the total number of electric vehicle adoption statistics records for each country in the database?

CREATE TABLE ElectricVehicleAdoptionStatistics (Id INT, Country VARCHAR(50), AdoptionRate DECIMAL(5,2), Year INT); INSERT INTO ElectricVehicleAdoptionStatistics (Id, Country, AdoptionRate, Year) VALUES (1, 'USA', 0.12, 2018); INSERT INTO ElectricVehicleAdoptionStatistics (Id, Country, AdoptionRate, Year) VALUES (2, 'China', 0.23, 2018); INSERT INTO ElectricVehicleAdoptionStatistics (Id, Country, AdoptionRate, Year) VALUES (3, 'Germany', 0.08, 2018); INSERT INTO ElectricVehicleAdoptionStatistics (Id, Country, AdoptionRate, Year) VALUES (4, 'Japan', 0.17, 2018);

SELECT Country, COUNT(*) FROM ElectricVehicleAdoptionStatistics GROUP BY Country;


Question: Delete all records from the inventory table that are more than 30 days old.

CREATE TABLE inventory (id INT, ingredient_name TEXT, quantity INT, last_updated DATE);

DELETE FROM inventory WHERE last_updated < DATE(NOW()) - INTERVAL 30 DAY;


Question: Generate PostgreSQL SQL for: What language did the word mahjong originate from?

CREATE TABLE table_name_31 (source_language VARCHAR, meaning VARCHAR)

SELECT source_language FROM table_name_31 WHERE meaning = 'mahjong';


Question: What is the average productivity of workers in the gold mines, categorized by their roles, for the year 2020?

CREATE TABLE gold_mines (id INT, worker_role TEXT, productivity FLOAT, extraction_year INT); INSERT INTO gold_mines (id, worker_role, productivity, extraction_year) VALUES (1, 'Engineer', 12.5, 2020), (2, 'Miner', 8.3, 2020), (3, 'Supervisor', 10.8, 2020);

SELECT worker_role, AVG(productivity) FROM gold_mines WHERE extraction_year = 2020 GROUP BY worker_role;


Question: Generate PostgreSQL SQL for: Where did the team in which Tom Pryce was in Pole Position race?

CREATE TABLE table_name_10 (location VARCHAR, pole_position VARCHAR)

SELECT location FROM table_name_10 WHERE pole_position = 'tom pryce';


Question: What were the total sales revenues for the drug "Humira" by company in 2019?

CREATE TABLE pharmaceutical_sales (company VARCHAR(255), drug VARCHAR(255), qty_sold INT, sales_revenue FLOAT, sale_date DATE); INSERT INTO pharmaceutical_sales (company, drug, qty_sold, sales_revenue, sale_date) VALUES ('AbbVie', 'Humira', 300, 18000.00, '2019-01-01');

SELECT company, SUM(sales_revenue) FROM pharmaceutical_sales WHERE drug = 'Humira' AND sale_date BETWEEN '2019-01-01' AND '2019-12-31' GROUP BY company;


Question: What was the most recent Mars rover launch?

CREATE TABLE Mars_Rover_Launches (rover_name TEXT, launch_date DATE); INSERT INTO Mars_Rover_Launches (rover_name, launch_date) VALUES ('Sojourner', '1996-12-04'), ('Spirit', '2003-06-10'), ('Opportunity', '2003-07-07'), ('Curiosity', '2011-11-26'), ('Perseverance', '2020-07-30');

SELECT rover_name, launch_date FROM Mars_Rover_Launches ORDER BY launch_date DESC LIMIT 1;


Question: What is the total funding amount for startups founded by people from underrepresented racial or ethnic groups in the USA?

CREATE TABLE startups (id INT, name TEXT, location TEXT, founder_race TEXT, funding_amount INT); INSERT INTO startups (id, name, location, founder_race, funding_amount) VALUES (1, 'Startup A', 'USA', 'African American', 3000000); INSERT INTO startups (id, name, location, founder_race, funding_amount) VALUES (2, 'Startup B', 'Canada', 'Caucasian', 5000000); INSERT INTO startups (id, name, location, founder_race, funding_amount) VALUES (3, 'Startup C', 'USA', 'Hispanic', 4000000);

SELECT SUM(funding_amount) FROM startups WHERE location = 'USA' AND founder_race IN ('African American', 'Hispanic', 'Native American', 'Pacific Islander');


Question: Find the difference in revenue between restaurants 1 and 2. Display the result as a single value.

CREATE TABLE restaurant_revenue (restaurant_id INT, revenue INT); INSERT INTO restaurant_revenue (restaurant_id, revenue) VALUES (1, 1200), (2, 1500), (3, 800), (4, 2000), (5, 1700);

SELECT ABS(SUM(r1.revenue) - SUM(r2.revenue)) as revenue_difference FROM restaurant_revenue r1, restaurant_revenue r2 WHERE r1.restaurant_id = 1 AND r2.restaurant_id = 2;


Question: What is the total revenue for each sales region?

CREATE TABLE sales_region (id INT, region VARCHAR(255), revenue INT); INSERT INTO sales_region (id, region, revenue) VALUES (1, 'Northeast', 500000), (2, 'Southeast', 600000), (3, 'Midwest', 400000), (4, 'Southwest', 700000), (5, 'West', 800000);

SELECT region, SUM(revenue) FROM sales_region GROUP BY region;


Question: What is the total budget for all dam projects with more than 10 million budget?

CREATE TABLE Projects (id INT PRIMARY KEY, name VARCHAR(255), budget INT, start_date DATE, end_date DATE, Infrastructure_id INT, FOREIGN KEY (Infrastructure_id) REFERENCES Infrastructure(id));

SELECT SUM(budget) as total_budget FROM Projects WHERE Infrastructure_id IN (SELECT id FROM Infrastructure WHERE type = 'Dam') GROUP BY Infrastructure_id HAVING total_budget > 10000000;


Question: What was the total funding received by programs targeting 'youth'?

CREATE TABLE Programs (program_id INT, target_group VARCHAR(50), funding_amount DECIMAL(10,2), funding_date DATE); INSERT INTO Programs (program_id, target_group, funding_amount, funding_date) VALUES (1, 'youth', 5000.00, '2021-01-01'), (2, 'seniors', 7000.00, '2021-02-01'), (3, 'adults', 3000.00, '2021-03-01');

SELECT SUM(funding_amount) AS total_funding FROM Programs WHERE target_group = 'youth';


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

Explanation: Regression test for Create View in PostgreSQL core test suite.

SELECT count(*) FROM (select pg_get_viewdef('tt23v', true)) AS _sub;


Question: Generate PostgreSQL SQL for: Which average Points have a Lost larger than 2, and Drawn larger than 2, and a Difference of 0?

CREATE TABLE table_name_74 (points INTEGER, difference VARCHAR, lost VARCHAR, drawn VARCHAR)

SELECT AVG(points) FROM table_name_74 WHERE lost > 2 AND drawn > 2 AND difference = '0';


Question: What is the average depth of all marine protected areas in the Pacific Ocean?

CREATE TABLE marine_protected_areas (name TEXT, location TEXT, avg_depth FLOAT);   CREATE TABLE ocean_regions (name TEXT, area FLOAT);

SELECT AVG(avg_depth)    FROM marine_protected_areas   WHERE location = (SELECT name FROM ocean_regions WHERE area = 'Pacific Ocean');


Question: Generate PostgreSQL SQL for: What race has a distance of 1200 m?

CREATE TABLE table_2062148_3 (race VARCHAR, distance VARCHAR)

SELECT race FROM table_2062148_3 WHERE distance = '1200 m';


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

SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists_partial WHERE a = 0 OR b = 0 OR c = 0');

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

SELECT count(*) FROM (SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists_partial WHERE a = 0 OR b = 0 OR c = 0')) AS _sub;


Question: PostgreSQL regression test 'partition_info': Write the SELECT query (example 68).

Explanation: Regression test for Partition Info in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT pg_partition_root('ptif_test_matview')) AS _sub;


Question: Insert new satellite image

CREATE TABLE satellite_images (id INT PRIMARY KEY, farm_id INT, image_url VARCHAR(100), capture_date TIMESTAMP);

INSERT INTO satellite_images (id, farm_id, image_url, capture_date) VALUES (1, 123, 'https://example.com/image1.jpg', '2022-02-01 14:30:00');


Question: Generate PostgreSQL SQL for: What's the count for obese children and adolescents ranked 48?

CREATE TABLE table_name_1 (obese_children_and_adolescents VARCHAR, obesity_rank VARCHAR)

SELECT obese_children_and_adolescents FROM table_name_1 WHERE obesity_rank = 48;


Question: pgTAP test for Index (assertion 68).

Explanation: SQL assertion from pgTAP test suite for Index.


Question: What is the total biomass of each species in the Arctic Ocean by year?

CREATE TABLE ArcticOceanBiomassYearly(year INT, species VARCHAR(50), biomass FLOAT);INSERT INTO ArcticOceanBiomassYearly(year, species, biomass) VALUES(2018, 'Polar Bear', 550.0), (2019, 'Seal', 210.0), (2020, 'Walrus', 1050.0), (2018, 'Polar Bear', 600.0), (2019, 'Seal', 220.0);

SELECT species, year, SUM(biomass) FROM ArcticOceanBiomassYearly GROUP BY species, year;


Question: What is the total number of members in all unions?

CREATE TABLE union_membership (id INT, union VARCHAR(20), member_count INT); INSERT INTO union_membership (id, union, member_count) VALUES (1, 'construction', 3500), (2, 'education', 8000), (3, 'manufacturing', 5000);

SELECT SUM(member_count) FROM union_membership;


Question: Show a SQL definition from the zombodb project (zombodb--3000.1.14--3000.1.15, item 2).

CREATE FUNCTION zdb.schema_version() RETURNS text LANGUAGE sql AS $$
SELECT '3000.1.15 (4edcf0acb878db742412f1757abf17e9441e0efa)'
$$;

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


Question: Create a new table for storing concert ticket sales data, with columns for concert_id, artist_name, city, and revenue.

CREATE TABLE concert_ticket_sales (concert_id INT, artist_name VARCHAR(255), city VARCHAR(255), revenue FLOAT);


Question: What is the internet penetration in African countries with a total population greater than 20 million?

CREATE TABLE internet_access (id INT, country VARCHAR(50), urban_population FLOAT, rural_population FLOAT, total_population FLOAT, internet_users FLOAT); INSERT INTO internet_access (id, country, urban_population, rural_population, total_population, internet_users) VALUES (3, 'Nigeria', 71.4, 57.1, 200.96, 112.03);

SELECT country, (internet_users / total_population) * 100 as internet_penetration FROM internet_access WHERE total_population > 20000000 AND country IN ('Nigeria', 'South Africa', 'Egypt', 'Ethiopia', 'Kenya') ORDER BY internet_penetration DESC;


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

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

SELECT count(*) FROM (SELECT '{"a":"b"}'::jsonb <@ '{"a":"b", "b":1, "c":null}') AS _sub;


Question: What is the maximum amount of water consumed in a single day in the 'environmental_data' table?

CREATE TABLE environmental_data (id INT, date DATE, water_consumption INT); INSERT INTO environmental_data (id, date, water_consumption) VALUES (1, '2022-01-01', 5000); INSERT INTO environmental_data (id, date, water_consumption) VALUES (2, '2022-01-02', 5500);

SELECT MAX(water_consumption) as max_water_consumption FROM environmental_data;


Question: Generate PostgreSQL SQL for: What were the investment earnings in the year that State and Federal taxes were $13,999,169?

CREATE TABLE table_name_26 (investment_earnings VARCHAR, state_ VARCHAR, _federal VARCHAR)

SELECT investment_earnings FROM table_name_26 WHERE state_ & _federal = '13,999,169';


Question: What is the minimum energy storage capacity by technology in 2030?

CREATE TABLE energy_storage_2030 (technology VARCHAR(255), capacity FLOAT); INSERT INTO energy_storage_2030 (technology, capacity) VALUES ('Lithium-ion', 18000.0), ('Flow', 25000.1), ('Sodium-ion', 32000.2);

SELECT technology, MIN(capacity) AS min_capacity FROM energy_storage_2030 GROUP BY technology;


Question: Generate PostgreSQL SQL for: Tell me the home team score for richmond home team

CREATE TABLE table_name_87 (home_team VARCHAR)

SELECT home_team AS score FROM table_name_87 WHERE home_team = 'richmond';


Question: What is the age and nationality distribution of employees?

CREATE TABLE EmployeeDemographics (EmployeeID INT, Age INT, Nationality VARCHAR(50)); INSERT INTO EmployeeDemographics (EmployeeID, Age, Nationality) VALUES (1, 30, 'American'), (2, 40, 'Canadian'), (3, 35, 'British'), (4, 28, 'Mexican'), (5, 45, 'German'), (6, 32, 'Indian');

SELECT Nationality, Age, COUNT(*) FROM EmployeeDemographics GROUP BY Nationality, Age;


Question: Generate PostgreSQL SQL for: What's the total attendance of games against the New York Giants after week 13?

CREATE TABLE table_name_51 (attendance VARCHAR, week VARCHAR, opponent VARCHAR)

SELECT COUNT(attendance) FROM table_name_51 WHERE week > 13 AND opponent = 'new york giants';


Question: Compare the average budget allocated for education in Mexico and Argentina in 2018.

CREATE SCHEMA latam_schema;CREATE TABLE latam_schema.education_budget (country VARCHAR(20), year INT, avg_budget DECIMAL(5,2));INSERT INTO latam_schema.education_budget (country, year, avg_budget) VALUES ('Mexico', 2018, 3000.00), ('Argentina', 2018, 4000.00);

SELECT country, avg_budget FROM latam_schema.education_budget WHERE (country = 'Mexico' OR country = 'Argentina') AND year = 2018;


Question: Update the conservation_efforts table to reflect a successful conservation project for species with id 3 and 7

CREATE TABLE conservation_efforts (id INT, species_id INT, project_status VARCHAR(20));

UPDATE conservation_efforts SET project_status = 'successful' WHERE species_id IN (3, 7);


Question: What is the maximum cargo weight transported by a vessel with a compliance score above 90 in the Indian Ocean in 2022?

CREATE TABLE vessels (id INT, name TEXT, type TEXT, compliance_score INT);CREATE TABLE cargos (id INT, vessel_id INT, weight FLOAT, destination TEXT, date DATE); INSERT INTO vessels (id, name, type, compliance_score) VALUES (1, 'VesselI', 'Container', 95); INSERT INTO cargos (id, vessel_id, weight, destination, date) VALUES (1, 1, 25000, 'Indian', '2022-03-15');

SELECT MAX(c.weight) FROM vessels v JOIN cargos c ON v.id = c.vessel_id WHERE v.compliance_score > 90 AND c.destination = 'Indian' AND c.date BETWEEN '2022-01-01' AND '2022-12-31';


Question: Which menu items have sold more than 500 units in the last 6 months, and how many units were sold?

CREATE TABLE menu_sales (menu_item VARCHAR(255), sales_quantity INT, sale_date DATE); INSERT INTO menu_sales (menu_item, sales_quantity, sale_date) VALUES ('Burger', 300, '2022-01-01'); INSERT INTO menu_sales (menu_item, sales_quantity, sale_date) VALUES ('Pizza', 550, '2022-01-02');

SELECT menu_item, SUM(sales_quantity) as total_sold FROM menu_sales WHERE sale_date >= DATE_SUB(CURRENT_DATE, INTERVAL 6 MONTH) GROUP BY menu_item HAVING total_sold > 500;


Question: Find the number of employees in each department who have been with the company for more than five years.

CREATE TABLE employee (id INT, name VARCHAR(255), gender VARCHAR(50), ethnicity VARCHAR(50), department_id INT, hire_date DATE);

SELECT department.name AS department, COUNT(*) AS employee_count FROM department INNER JOIN employee ON department.id = employee.department_id WHERE DATEDIFF(CURDATE(), hire_date) > 5 * 365 GROUP BY department.name;


Question: Generate PostgreSQL SQL for: What is the total number of games lost when 22 have been played, the losing BP number is 2, and the club is Merthyr RFC?

CREATE TABLE table_name_52 (lost VARCHAR, club VARCHAR, played VARCHAR, losing_bp VARCHAR)

SELECT lost FROM table_name_52 WHERE played = '22' AND losing_bp = '2' AND club = 'merthyr rfc';


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

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


Question: Generate PostgreSQL SQL for: Name the date for eastern creek raceway

CREATE TABLE table_2446333_2 (date VARCHAR, circuit VARCHAR)

SELECT date FROM table_2446333_2 WHERE circuit = 'Eastern Creek Raceway';


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

Explanation: DML from PostgreSQL core regression test for Rules.


Question: What is the total installed capacity (in MW) of renewable energy projects in India that were completed after 2018, grouped by type?

CREATE TABLE india_renewable_projects (name TEXT, type TEXT, completion_date DATE, capacity_mw REAL); INSERT INTO india_renewable_projects (name, type, completion_date, capacity_mw) VALUES ('Solar Project 1', 'Solar', '2019-01-01', 50), ('Wind Project 2', 'Wind', '2020-01-01', 75);

SELECT type, SUM(capacity_mw) FROM india_renewable_projects WHERE completion_date > '2018-12-31' GROUP BY type;


Question: What is the average age of astronauts from Japan during their first space mission in 2025?

CREATE TABLE AstronautsT (astronaut_name VARCHAR(30), age INT, first_mission_date DATE, nationality VARCHAR(20)); INSERT INTO AstronautsT (astronaut_name, age, first_mission_date, nationality) VALUES ('Astronaut5', 50, '2025-01-01', 'Japan');

SELECT AVG(age) FROM AstronautsT WHERE nationality = 'Japan' AND first_mission_date = (SELECT MIN(first_mission_date) FROM AstronautsT WHERE nationality = 'Japan' AND YEAR(first_mission_date) = 2025);


Question: Generate PostgreSQL SQL for: List all different genre types.


Question: pgTAP test for Index (assertion 101).

SELECT * FROM check_test(
    index_is_type( 'idx_bar', 'hash' ),
    false,
    'index_is_type() no table fail',
    'Index idx_bar should be a hash index',
    '        have: btree
        want: hash'
);


Question: Generate PostgreSQL SQL for: What catalog has june 1990 as the date?

CREATE TABLE table_name_73 (catalog VARCHAR, date VARCHAR)

SELECT catalog FROM table_name_73 WHERE date = 'june 1990';


Question: What is the average age of community health workers by state?

CREATE TABLE community_health_workers (worker_id INT, name TEXT, age INT, state TEXT); INSERT INTO community_health_workers (worker_id, name, age, state) VALUES (1, 'Alice', 45, 'NY'), (2, 'Bob', 35, 'CA'), (3, 'Charlie', 50, 'NY'), (4, 'Diana', 30, 'CA');

SELECT state, AVG(age) FROM community_health_workers GROUP BY state;


Question: Generate PostgreSQL SQL for: Attendance larger than 55,189 is which average game?

CREATE TABLE table_name_25 (game INTEGER, attendance INTEGER)

SELECT AVG(game) FROM table_name_25 WHERE attendance > 55 OFFSET 189;


Question: Delete records from the financial_wellbeing table where the financial_score is less than 65 or the date is after 2022-02-28.

DELETE FROM financial_wellbeing WHERE financial_score < 65 OR date > '2022-02-28';


Question: Calculate the average sustainability score for accommodations in Australia and New Zealand.

CREATE TABLE accommodations (id INT, country VARCHAR(50), accommodation_type VARCHAR(50), sustainability_score INT); INSERT INTO accommodations (id, country, accommodation_type, sustainability_score) VALUES (1, 'Australia', 'Hotel', 75); INSERT INTO accommodations (id, country, accommodation_type, sustainability_score) VALUES (2, 'Australia', 'Resort', 80); INSERT INTO accommodations (id, country, accommodation_type, sustainability_score) VALUES (3, 'New Zealand', 'Hostel', 85);

SELECT AVG(sustainability_score) FROM accommodations WHERE country IN ('Australia', 'New Zealand');


Question: Generate PostgreSQL SQL for: Which region has the format CD and label MCA?

CREATE TABLE table_name_15 (region VARCHAR, format VARCHAR, label VARCHAR)

SELECT region FROM table_name_15 WHERE format = 'cd' AND label = 'mca';


Question: Generate PostgreSQL SQL for: Name the most season for old hoss radbourn

CREATE TABLE table_242813_2 (season INTEGER, pitcher VARCHAR)

SELECT MAX(season) FROM table_242813_2 WHERE pitcher = 'Old Hoss Radbourn';


Question: Summarize the number of regulatory frameworks implemented in the Americas (North and South) between 2019 and 2021.

CREATE TABLE regulatory_frameworks (id INT, name VARCHAR(255), country VARCHAR(255), implementation_date DATE); INSERT INTO regulatory_frameworks (id, name, country, implementation_date) VALUES (1, 'Framework 1', 'USA', '2020-05-01'), (2, 'Framework 2', 'Brazil', '2021-02-15');

SELECT COUNT(*) FROM regulatory_frameworks WHERE country IN ('USA', 'Brazil') AND implementation_date BETWEEN '2019-01-01' AND '2021-12-31';


Question: Generate PostgreSQL SQL for: What is the highest River Mile that has a pool length of 42.2 miles or a lock/lift drop of 21 feet?

CREATE TABLE table_name_71 (river_mile INTEGER, pool_length__miles_ VARCHAR, lock_lift_drop__in_feet_ VARCHAR)

SELECT MAX(river_mile) FROM table_name_71 WHERE pool_length__miles_ = '42.2' AND lock_lift_drop__in_feet_ = '21';


Question: Generate PostgreSQL SQL for: What player had the high point on July 7?

CREATE TABLE table_name_21 (high_points VARCHAR, date VARCHAR)

SELECT high_points FROM table_name_21 WHERE date = 'july 7';


Question: pgTAP test for Moretap (assertion 8).

SELECT is( _set('plan', 8), 8, 'Increase internal plan value after testing finish' );

Explanation: SQL assertion from pgTAP test suite for Moretap.


Question: Generate PostgreSQL SQL for: Which Total is the lowest one that has a Country of united states, and a To par of +12?

CREATE TABLE table_name_99 (total INTEGER, country VARCHAR, to_par VARCHAR)

SELECT MIN(total) FROM table_name_99 WHERE country = 'united states' AND to_par = '+12';


Question: Generate PostgreSQL SQL for: what is the score when the opponent is fernando vicente?

CREATE TABLE table_name_9 (score VARCHAR, opponent VARCHAR)

SELECT score FROM table_name_9 WHERE opponent = 'fernando vicente';


Question: Generate PostgreSQL SQL for: What is the highest SP+FS that has 131.02 Points, and a Rank larger than 15?

CREATE TABLE table_name_84 (fs VARCHAR, sp INTEGER, points VARCHAR, rank VARCHAR)

SELECT MAX(sp) + fs FROM table_name_84 WHERE points = 131.02 AND rank > 15;


Question: Show a query using PostgreSQL contrib extension 'hstore_plperl' (example 10).

SELECT test1arr(array['aa=>bb, cc=>NULL'::hstore, 'dd=>ee']);

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


Question: What is the average expenditure by tourists from Germany in Berlin, Munich, and Hamburg combined?

CREATE TABLE tourism_stats (visitor_country VARCHAR(20), destination VARCHAR(20), expenditure DECIMAL(10,2)); INSERT INTO tourism_stats (visitor_country, destination, expenditure) VALUES ('Germany', 'Berlin', 400.00), ('Germany', 'Berlin', 450.00), ('Germany', 'Munich', 350.00), ('Germany', 'Hamburg', 300.00);

SELECT AVG(expenditure) FROM (SELECT expenditure FROM tourism_stats WHERE visitor_country = 'Germany' AND destination IN ('Berlin', 'Munich', 'Hamburg')) subquery;


Question: Generate PostgreSQL SQL for: What is the total number of television channels when one of the radio stations is onda madrid?

CREATE TABLE table_23143607_1 (television_channels VARCHAR, radio_stations VARCHAR)

SELECT COUNT(television_channels) FROM table_23143607_1 WHERE radio_stations = 'Onda Madrid';


Question: Count the number of carbon offset initiatives in each city

CREATE TABLE city_carbon_offsets (city VARCHAR(50), offset_initiative VARCHAR(50), PRIMARY KEY (city, offset_initiative));

SELECT city, COUNT(*) FROM city_carbon_offsets GROUP BY city;


Question: Present the number of hospitals in each state

CREATE TABLE hospitals (hospital_id INT, name VARCHAR(255), state VARCHAR(255)); INSERT INTO hospitals (hospital_id, name, state) VALUES (1, 'Johns Hopkins Hospital', 'Maryland'); INSERT INTO hospitals (hospital_id, name, state) VALUES (2, 'Massachusetts General Hospital', 'Massachusetts');

SELECT state, COUNT(*) FROM hospitals GROUP BY state;


Question: Generate PostgreSQL SQL for: What's the highest league of the Nova Scotia Clippers with a total season of less than 4?

CREATE TABLE table_name_2 (highest_league VARCHAR, total_seasons VARCHAR, team VARCHAR)

SELECT highest_league FROM table_name_2 WHERE total_seasons < 4 AND team = 'nova scotia clippers';


Question: Generate PostgreSQL SQL for: What volume number has the ISBN of 978-1-59582-712-8 (hc) 978-1-59582-713-5 (tpb)?

CREATE TABLE table_name_38 (volume VARCHAR, isbn VARCHAR)


Question: Calculate the total quantity of products in all categories

CREATE TABLE products (product_id INT, category VARCHAR(20), quantity INT); INSERT INTO products (product_id, category, quantity) VALUES (1, 'apparel', 50), (2, 'accessories', 70), (3, 'home_decor', 40), (4, 'electronics', 600), (5, 'grocery', 60), (6, 'toys', 30), (7, 'furniture', 150);


Question: What is the average risk score for all green infrastructure projects in the Asia Pacific region?

CREATE TABLE infrastructure_projects (project_id INT, project_name TEXT, sector TEXT, region TEXT, risk_score INT); INSERT INTO infrastructure_projects (project_id, project_name, sector, region, risk_score) VALUES (1, 'Project C', 'Green Infrastructure', 'Asia Pacific', 12), (2, 'Project D', 'Green Infrastructure', 'Europe', 10);

SELECT AVG(risk_score) FROM infrastructure_projects WHERE sector = 'Green Infrastructure' AND region = 'Asia Pacific';


Question: How many chemical engineers were employed in each plant in the past quarter?

CREATE TABLE plants (plant_id INT, plant_name VARCHAR(50)); CREATE TABLE employees (employee_id INT, plant_id INT, employee_type VARCHAR(50), employment_date DATE); INSERT INTO plants (plant_id, plant_name) VALUES (1, 'Plant A'), (2, 'Plant B'); INSERT INTO employees (employee_id, plant_id, employee_type, employment_date) VALUES (1, 1, 'Chemical Engineer', '2022-01-01'), (2, 2, 'Chemical Engineer', '2022-01-01');

SELECT plants.plant_name, COUNT(employees.employee_id) FROM plants INNER JOIN employees ON plants.plant_id = employees.plant_id WHERE employees.employee_type = 'Chemical Engineer' AND employees.employment_date >= DATE_SUB(CURDATE(), INTERVAL 3 MONTH) GROUP BY plants.plant_name;


Question: Generate PostgreSQL SQL for: What is the description of the type of the company who concluded its contracts most recently?

CREATE TABLE Maintenance_Contracts (maintenance_contract_company_id VARCHAR, contract_end_date VARCHAR); CREATE TABLE Third_Party_Companies (company_name VARCHAR, company_id VARCHAR, company_type_code VARCHAR); CREATE TABLE Ref_Company_Types (company_type_code VARCHAR)

SELECT T1.company_name FROM Third_Party_Companies AS T1 JOIN Maintenance_Contracts AS T2 ON T1.company_id = T2.maintenance_contract_company_id JOIN Ref_Company_Types AS T3 ON T1.company_type_code = T3.company_type_code ORDER BY T2.contract_end_date DESC LIMIT 1;


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

CREATE INDEX concur_reindex_part_index_0 ON ONLY concur_reindex_part_0 (c1);

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


Question: PostgreSQL regression test 'partition_info': Write the SELECT query (example 43).

SELECT relid, parentrelid, level, isleaf
  FROM pg_partition_tree('ptif_test0_index') p
  JOIN pg_class c ON (p.relid = c.oid);

SELECT count(*) FROM (SELECT relid, parentrelid, level, isleaf
  FROM pg_partition_tree('ptif_test0_index') p
  JOIN pg_class c ON (p.relid = c.oid)) AS _sub;


Question: List the names and professional development hours of teachers who have participated in workshops on open pedagogy and lifelong learning, sorted alphabetically by name.

CREATE TABLE Teachers (teacher_id INT, name VARCHAR(255), professional_development_hours INT); CREATE TABLE Workshops (workshop_id INT, name VARCHAR(255), topic VARCHAR(255)); INSERT INTO Workshops (workshop_id, name, topic) VALUES (1, 'Open Pedagogy Workshop', 'open pedagogy'), (2, 'Lifelong Learning Seminar', 'lifelong learning'); CREATE TABLE TeacherWorkshops (teacher_id INT, workshop_id INT);

SELECT Teachers.name, Teachers.professional_development_hours FROM Teachers INNER JOIN TeacherWorkshops ON Teachers.teacher_id = TeacherWorkshops.teacher_id INNER JOIN Workshops ON TeacherWorkshops.workshop_id = Workshops.workshop_id WHERE Workshops.topic IN ('open pedagogy', 'lifelong learning') ORDER BY Teachers.name ASC;


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

CREATE FUNCTION hashisbn13(isbn13)
	RETURNS int4
	AS 'hashint8'
	LANGUAGE 'internal'
	IMMUTABLE STRICT
	PARALLEL SAFE;

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


Question: pgTAP test for Resultset (assertion 47).

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

Explanation: SQL assertion from pgTAP test suite for Resultset.


Question: What is the average energy efficiency rating for renewable energy projects in 'Urban Area X'?

CREATE TABLE renewable_projects (project_id INT, project_name TEXT, location TEXT, energy_efficiency_rating FLOAT); INSERT INTO renewable_projects (project_id, project_name, location, energy_efficiency_rating) VALUES (1, 'Solar Farm A', 'Rural Region Y', 0.23), (2, 'Wind Farm B', 'Rural Region X', 0.35), (3, 'Hydro Plant C', 'Rural Region Y', 0.42), (4, 'Solar Farm D', 'Urban Area X', 0.50);

SELECT AVG(energy_efficiency_rating) as avg_rating FROM renewable_projects WHERE location = 'Urban Area X';


Question: Generate PostgreSQL SQL for: How many laps were there for the car with a qual of 138.750?

CREATE TABLE table_name_3 (laps VARCHAR, qual VARCHAR)

SELECT laps FROM table_name_3 WHERE qual = '138.750';


Question: Generate PostgreSQL SQL for: Who has a nationality of Czech Republic and a position of right wing?

CREATE TABLE table_name_49 (player VARCHAR, position VARCHAR, nationality VARCHAR)

SELECT player FROM table_name_49 WHERE position = 'right wing' AND nationality = 'czech republic';


Question: Insert a new excavation site named "La Santana" into the excavation_sites table.

CREATE TABLE excavation_sites (id INT, name VARCHAR(255));

INSERT INTO excavation_sites (id, name) VALUES ((SELECT MAX(id) FROM excavation_sites) + 1, 'La Santana');


Question: Generate PostgreSQL SQL for: What year was the Competition of World Junior Championships with a 20th (qf) position?

CREATE TABLE table_name_18 (year INTEGER, competition VARCHAR, position VARCHAR)

SELECT AVG(year) FROM table_name_18 WHERE competition = 'world junior championships' AND position = '20th (qf)';


Question: Generate PostgreSQL SQL for: Tell me the total number of years for lady cecily waynflete and opera house, kennedy center

CREATE TABLE table_name_51 (year VARCHAR, role VARCHAR, theatre VARCHAR)

SELECT COUNT(year) FROM table_name_51 WHERE role = 'lady cecily waynflete' AND theatre = 'opera house, kennedy center';


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

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

SELECT count(*) FROM (select intr_multirange(intr(1,10))) AS _sub;


Question: Generate PostgreSQL SQL for: What was the title of the episode with a production code of 1gowo04?

CREATE TABLE table_name_3 (episode_title VARCHAR, prod_code VARCHAR)

SELECT episode_title FROM table_name_3 WHERE prod_code = '1gowo04';


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

CREATE FUNCTION gen_random_bytes(int4)
RETURNS bytea
AS 'MODULE_PATHNAME', 'pg_random_bytes'
LANGUAGE C VOLATILE STRICT PARALLEL SAFE;


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

CREATE TRIGGER transition_table_base_ins_trig
  AFTER INSERT ON transition_table_base
  REFERENCING OLD TABLE AS oldtable NEW TABLE AS newtable
  FOR EACH STATEMENT
  EXECUTE PROCEDURE transition_table_base_ins_func();

Explanation: DDL from PostgreSQL core regression test for Plpgsql.


Question: How many tourists visited each region in 2020?

CREATE TABLE region (region_code CHAR(2), region_name VARCHAR(50)); INSERT INTO region VALUES ('NA', 'North America'), ('EU', 'Europe'); CREATE TABLE visit_summary (region_code CHAR(2), year INT, visitor_count INT); INSERT INTO visit_summary VALUES ('NA', 2020, 1000), ('NA', 2019, 1200), ('EU', 2020, 2000), ('EU', 2019, 2500);

SELECT region_code, SUM(visitor_count) OVER (PARTITION BY region_code) FROM visit_summary WHERE year = 2020;


Question: Generate PostgreSQL SQL for: Which stage has kourdali as the name?

CREATE TABLE table_21578303_2 (stage VARCHAR, name VARCHAR)

SELECT stage FROM table_21578303_2 WHERE name = 'Kourdali';


Question: Generate PostgreSQL SQL for: Which Frequency has a Webcast of •, and a Callsign of xemr?

CREATE TABLE table_name_31 (frequency INTEGER, webcast VARCHAR, callsign VARCHAR)

SELECT AVG(frequency) FROM table_name_31 WHERE webcast = '•' AND callsign = 'xemr';


Question: What is the earliest date a parcel was shipped from 'SYD' to 'PEK'?

CREATE TABLE shipments (id INT, source_airport VARCHAR(5), destination_airport VARCHAR(5), shipped_date DATE); INSERT INTO shipments (id, source_airport, destination_airport, shipped_date) VALUES (1, 'SYD', 'PEK', '2022-03-02'), (2, 'SYD', 'PEK', '2022-03-10'), (3, 'PEK', 'SYD', '2022-03-15');

SELECT MIN(shipped_date) FROM shipments WHERE source_airport = 'SYD' AND destination_airport = 'PEK';


Question: Generate PostgreSQL SQL for: What's the loss for September 16?

CREATE TABLE table_name_62 (loss VARCHAR, date VARCHAR)

SELECT loss FROM table_name_62 WHERE date = 'september 16';


Question: What is the average dissolved oxygen level for each species in the 'fish_data' table?

CREATE TABLE fish_data (species VARCHAR(255), dissolved_oxygen FLOAT); INSERT INTO fish_data (species, dissolved_oxygen) VALUES ('Tilapia', 6.5), ('Salmon', 8.5), ('Catfish', 5.5);

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


Question: Generate PostgreSQL SQL for: What party did hilda solis represent?

CREATE TABLE table_1805191_6 (party VARCHAR, incumbent VARCHAR)

SELECT party FROM table_1805191_6 WHERE incumbent = 'Hilda Solis';


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

insert into tab_batch_local select i, 'test'|| i from generate_series(1, 45) i;

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


Question: Count the number of successful PTSD treatment outcomes for veterans in the United States.

CREATE TABLE patients (patient_id INT, patient_name VARCHAR(50), condition VARCHAR(50), country VARCHAR(50), veteran_status VARCHAR(50), treatment_outcome VARCHAR(50)); INSERT INTO patients (patient_id, patient_name, condition, country, veteran_status, treatment_outcome) VALUES (1, 'James Smith', 'PTSD', 'USA', 'Veteran', 'Successful'), (2, 'Olivia Brown', 'PTSD', 'USA', 'Civilian', 'Successful');

SELECT COUNT(patient_id) FROM patients WHERE patients.condition = 'PTSD' AND patients.country = 'USA' AND patients.veteran_status = 'Veteran' AND patients.treatment_outcome = 'Successful';


Question: What is the total number of public participation events in each city, partitioned by event type?

CREATE TABLE PublicEvents (city VARCHAR(50), event_type VARCHAR(50), participation INT); INSERT INTO PublicEvents (city, event_type, participation) VALUES ('CityA', 'Workshop', 50), ('CityA', 'Meeting', 30), ('CityB', 'Workshop', 40), ('CityB', 'Meeting', 60);

SELECT city, event_type, SUM(participation) AS total_participation FROM PublicEvents GROUP BY city, event_type;


Question: Write the DML statement from PostgreSQL regression test 'varchar' (example 6).

INSERT INTO VARCHAR_TBL (f1) VALUES ('3');

Explanation: DML from PostgreSQL core regression test for Varchar.


Question: What was the total number of shipments from Vietnam to South Africa in the first half of May 2021?

CREATE TABLE shipments (id INT, origin VARCHAR(255), destination VARCHAR(255), shipped_at TIMESTAMP); INSERT INTO shipments (id, origin, destination, shipped_at) VALUES (1, 'Vietnam', 'South Africa', '2021-05-02 10:30:00'), (2, 'Vietnam', 'South Africa', '2021-05-15 15:45:00');

SELECT COUNT(*) FROM shipments WHERE origin = 'Vietnam' AND destination = 'South Africa' AND shipped_at >= '2021-05-01' AND shipped_at < '2021-05-16';


Question: What is the total number of flight hours for each aircraft model in the flight_hours table?

CREATE TABLE flight_hours (flight_id INT, model_id INT, flight_hours INT);

SELECT model_id, SUM(flight_hours) as total_flight_hours FROM flight_hours GROUP BY model_id;


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

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


Question: Generate PostgreSQL SQL for: Which round was the winning constructor was Benetton - Ford and in the Pole Position was Damon Hill?

CREATE TABLE table_1137702_3 (round VARCHAR, winning_constructor VARCHAR, pole_position VARCHAR)

SELECT round FROM table_1137702_3 WHERE winning_constructor = 'Benetton - Ford' AND pole_position = 'Damon Hill';


Question: What is the total credit and debit amount per day for all customers?

CREATE TABLE transactions (id INT, customer_id INT, transaction_date DATE, amount DECIMAL(10,2), type VARCHAR(10)); INSERT INTO transactions (id, customer_id, transaction_date, amount, type) VALUES (1, 1, '2022-01-01', 100.00, 'debit'); INSERT INTO transactions (id, customer_id, transaction_date, amount, type) VALUES (2, 1, '2022-01-02', 50.00, 'credit'); INSERT INTO transactions (id, customer_id, transaction_date, amount, type) VALUES (3, 2, '2022-01-03', 200.00, 'debit');

SELECT transaction_date, SUM(CASE WHEN type = 'debit' THEN -amount ELSE amount END) AS total_amount FROM transactions GROUP BY transaction_date;


Question: What is the average time to detect a security incident in the education sector in 2022?

CREATE TABLE security_incidents (sector VARCHAR(255), year INT, time_to_detect FLOAT); INSERT INTO security_incidents (sector, year, time_to_detect) VALUES ('Education', 2022, 4.2), ('Education', 2022, 5.6), ('Education', 2022, 3.9), ('Education', 2022, 6.1), ('Education', 2022, 4.5);

SELECT AVG(time_to_detect) FROM security_incidents WHERE sector = 'Education' AND year = 2022;


Question: What is the average budget allocated for language preservation projects in Africa?

CREATE TABLE Languages (LanguageID INT PRIMARY KEY, LanguageName VARCHAR(50), Location VARCHAR(50), Budget DECIMAL(10,2)); INSERT INTO Languages (LanguageID, LanguageName, Location, Budget) VALUES (1, 'Swahili', 'Tanzania', 500000.00), (2, 'Hausa', 'Nigeria', 750000.00);

SELECT AVG(Budget) FROM Languages WHERE Location LIKE '%Africa%';


Question: pgTAP test for Functap (assertion 69).

SELECT * FROM check_test(
    function_lang_is( 'yay', '{}'::name[], 'sql' ),
    true,
    'function_lang_is(func, 0 args, sql)',
    'Function yay() should be written in sql',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Functap.


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

SELECT lpad('hi'::citext, 5, 'xy'::text  ) = 'xyxhi' AS t;

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


Question: What is the average delivery time for shipments that were delivered to warehouses in the state of New York?

CREATE TABLE Shipment (shipment_id INT, warehouse_id INT, delivery_date DATE); INSERT INTO Shipment (shipment_id, warehouse_id, delivery_date) VALUES (1, 1, '2022-01-01'), (2, 2, '2022-02-01'), (3, 3, '2022-03-01'), (4, 1, '2022-04-01'), (5, 2, '2022-05-01'); CREATE TABLE Warehouse (warehouse_id INT, warehouse_name VARCHAR(50), state VARCHAR(50)); INSERT INTO Warehouse (warehouse_id, warehouse_name, state) VALUES (1, 'Los Angeles Warehouse', 'California'), (2, 'New York Warehouse', 'New York'), (3, 'Texas Warehouse', 'Texas');

SELECT AVG(DATEDIFF('day', s.delivery_date, w.state_joined_date)) as avg_delivery_time FROM Shipment s JOIN Warehouse w ON s.warehouse_id = w.warehouse_id WHERE w.state = 'New York';


Question: PostgreSQL regression test 'date': Write the SELECT query (example 187).

SELECT EXTRACT(ISOYEAR       FROM DATE '2020-08-11 BC');

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

SELECT count(*) FROM (SELECT EXTRACT(ISOYEAR       FROM DATE '2020-08-11 BC')) AS _sub;


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

SELECT * FROM array_op_test WHERE i <@ '{NULL}' ORDER BY seqno;

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

SELECT count(*) FROM (SELECT * FROM array_op_test WHERE i <@ '{NULL}' ORDER BY seqno) AS _sub;


Question: Generate PostgreSQL SQL for: what's the operational period with camp  sajmište

CREATE TABLE table_10335_1 (operational VARCHAR, camp VARCHAR)

SELECT operational FROM table_10335_1 WHERE camp = 'Sajmište';


Question: Generate PostgreSQL SQL for: What is the 2004 population for 山海关区?

CREATE TABLE table_name_46 (population__2004_est_ VARCHAR, hanzi VARCHAR)

SELECT population__2004_est_ FROM table_name_46 WHERE hanzi = '山海关区';


Question: What is the total revenue from refrigerated cargo shipments in Q1 2021?

CREATE TABLE shipments (shipment_id INT, shipment_type TEXT, revenue FLOAT, order_date DATE); INSERT INTO shipments (shipment_id, shipment_type, revenue, order_date) VALUES (1, 'Refrigerated', 3000.00, '2021-01-05'), (2, 'Dry', 4000.00, '2021-01-10');

SELECT SUM(revenue) FROM shipments WHERE shipment_type = 'Refrigerated' AND EXTRACT(MONTH FROM order_date) BETWEEN 1 AND 3;


Question: Generate PostgreSQL SQL for: What is the Cook PVI for the location that has a representative of Mike Thompson?

CREATE TABLE table_19283806_4 (cook_pvi VARCHAR, representative VARCHAR)

SELECT cook_pvi FROM table_19283806_4 WHERE representative = 'Mike Thompson';


Question: List the vessel names and their total cargo weight for the vessels that have visited Dubai in January 2021 or later?

CREATE TABLE Vessel (vessel_id INT PRIMARY KEY, vessel_name VARCHAR(255)); CREATE TABLE Cargo (cargo_id INT, vessel_id INT, cargo_weight INT, PRIMARY KEY (cargo_id, vessel_id)); CREATE TABLE Vessel_Movement (vessel_id INT, movement_date DATE, PRIMARY KEY (vessel_id, movement_date));

SELECT V.vessel_name, SUM(C.cargo_weight) FROM Vessel V JOIN Cargo C ON V.vessel_id = C.vessel_id JOIN Vessel_Movement VM ON V.vessel_id = VM.vessel_id WHERE VM.movement_date >= '2021-01-01' AND VM.port_id IN (SELECT port_id FROM Port WHERE port_name = 'Dubai') GROUP BY V.vessel_name;


Question: What are the types and quantities of artifacts found in 'SiteA'?

CREATE TABLE SiteA (artifact_id INT, artifact_type TEXT, quantity INT); INSERT INTO SiteA (artifact_id, artifact_type, quantity) VALUES (1, 'Pottery', 30), (2, 'Tools', 15), (3, 'Jewelry', 25);

SELECT artifact_type, SUM(quantity) FROM SiteA GROUP BY artifact_type;


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

select * from nummultirange_test2 where nmr = '{}';

SELECT count(*) FROM (select * from nummultirange_test2 where nmr = '{}') AS _sub;


Question: Generate PostgreSQL SQL for: Name the least population for 2002 for 2011 being 9564

CREATE TABLE table_2562572_5 (population__2002_ INTEGER, population__2011_ VARCHAR)

SELECT MIN(population__2002_) FROM table_2562572_5 WHERE population__2011_ = 9564;


Question: Generate PostgreSQL SQL for: What is the date when the opponent in the final is gastón etlis martín rodríguez?

CREATE TABLE table_name_22 (date VARCHAR, opponents_in_the_final VARCHAR)

SELECT date FROM table_name_22 WHERE opponents_in_the_final = 'gastón etlis martín rodríguez';


Question: Generate PostgreSQL SQL for: Which school is located in trafalgar?

CREATE TABLE table_name_73 (school VARCHAR, location VARCHAR)

SELECT school FROM table_name_73 WHERE location = 'trafalgar';


Question: What is the average delivery time for shipments from South Korea, partitioned by warehouse?

CREATE TABLE Warehouses (WarehouseID INT, WarehouseName VARCHAR(50), Country VARCHAR(50)); INSERT INTO Warehouses (WarehouseID, WarehouseName, Country) VALUES (1, 'Seoul Warehouse', 'South Korea'); CREATE TABLE Shipments (ShipmentID INT, WarehouseID INT, DeliveryTime INT);

SELECT WarehouseID, AVG(DeliveryTime) OVER (PARTITION BY WarehouseID) AS AvgDeliveryTime FROM Shipments WHERE Country = 'South Korea';


Question: Generate PostgreSQL SQL for: What is the title rank of the actor who played the character of arthur hastings during series 1-8, 13?

CREATE TABLE table_name_24 (title_rank VARCHAR, series VARCHAR, character VARCHAR)

SELECT title_rank FROM table_name_24 WHERE series = '1-8, 13' AND character = 'arthur hastings';


Question: Generate PostgreSQL SQL for: Name the 2010 for 2007 of a and 2012 of a

SELECT 2010 FROM table_name_77 WHERE 2007 = 'a' AND 2012 = 'a';


Question: What is the average age of community health workers by race?

CREATE TABLE community_health_workers (worker_id INT, name TEXT, age INT, race TEXT); INSERT INTO community_health_workers (worker_id, name, age, race) VALUES (1, 'John Doe', 35, 'White'), (2, 'Jane Smith', 40, 'Black'), (3, 'Maria Garcia', 45, 'Hispanic');

SELECT race, AVG(age) FROM community_health_workers GROUP BY race;


Question: Generate PostgreSQL SQL for: Where is every location where Nick is Bru?

CREATE TABLE table_2112260_1 (location VARCHAR, nick VARCHAR)

SELECT location FROM table_2112260_1 WHERE nick = 'BRU';


Question: What are the production forecasts for the wells in the North Sea, ranked by production volume in descending order for each production year?

CREATE TABLE production_forecasts (forecast_id INT, well_id INT, production_year INT, production_volume FLOAT, region VARCHAR(50)); INSERT INTO production_forecasts (forecast_id, well_id, production_year, production_volume, region) VALUES (5, 5, 2022, 250.6, 'North Sea'); INSERT INTO production_forecasts (forecast_id, well_id, production_year, production_volume, region) VALUES (6, 6, 2023, 235.4, 'North Sea');

SELECT forecast_id, well_id, production_year, production_volume, region, ROW_NUMBER() OVER (PARTITION BY production_year ORDER BY production_volume DESC) as rank FROM production_forecasts WHERE region = 'North Sea';


Question: Generate PostgreSQL SQL for: How many laps were completed with a start of 33, and a finish of 18?

CREATE TABLE table_name_67 (laps INTEGER, start VARCHAR, finish VARCHAR)

SELECT MAX(laps) FROM table_name_67 WHERE start = '33' AND finish = '18';


Question: What is the average population size of the blue whale for every 2 consecutive years?

CREATE TABLE blue_whale_population (year INT, population INT); INSERT INTO blue_whale_population (year, population) VALUES (2000, 9000), (2001, 9500), (2002, 10000), (2003, 10500);

SELECT AVG(population) FROM (SELECT population, ROW_NUMBER() OVER (ORDER BY year) / 2 as group_number FROM blue_whale_population) as grouped_populations GROUP BY group_number;


Question: Generate PostgreSQL SQL for: What did billy andrade to par?

CREATE TABLE table_name_5 (to_par VARCHAR, player VARCHAR)

SELECT to_par FROM table_name_5 WHERE player = 'billy andrade';


Question: How many incidents were reported for VesselB?

CREATE TABLE incidents (id INT, vessel_id INT, incident_type TEXT, reported_date DATE); INSERT INTO incidents (id, vessel_id, incident_type, reported_date) VALUES (1, 2, 'Collision', '2022-01-01');

SELECT COUNT(*) FROM incidents WHERE vessel_id = 2;


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

ALTER EXTENSION pgtap ADD FUNCTION has_column ( NAME, NAME );

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


Question: What is the total length of all railroads in Canada and the United States?

CREATE TABLE railroads (id INT, country VARCHAR(255), total_length FLOAT); INSERT INTO railroads (id, country, total_length) VALUES (1, 'Canada', 48000), (2, 'United States', 246000);

SELECT SUM(total_length) FROM railroads WHERE country IN ('Canada', 'United States');


Question: pgTAP test for Ownership (assertion 52).

-- It should ignore the sequence.
SELECT * FROM check_test(
    table_owner_is('public', 'someseq', current_user, 'mumble'),
	false,
    'table_owner_is(sch, seq, user, desc)',
    'mumble',
    '    Table public.someseq does not exist'
);

Explanation: SQL assertion from pgTAP test suite for Ownership.


Question: Generate PostgreSQL SQL for: How many teams listed for game 45?

CREATE TABLE table_27721131_8 (team VARCHAR, game VARCHAR)

SELECT COUNT(team) FROM table_27721131_8 WHERE game = 45;


Question: pgTAP test for Runjusttests (assertion 10).

CREATE OR REPLACE FUNCTION whatever.testz() RETURNS SETOF TEXT AS $$
    SELECT is( MAX(id), NULL, 'Late test should find nothing in the test table') FROM whatever.foo;
$$ LANGUAGE SQL;

Explanation: SQL assertion from pgTAP test suite for Runjusttests.


Question: What is the average budget for humanitarian assistance events in the Arctic region?

CREATE TABLE humanitarian_assistance (id INT PRIMARY KEY, event_name VARCHAR(100), budget DECIMAL(10, 2), region VARCHAR(50)); INSERT INTO humanitarian_assistance (id, event_name, budget, region) VALUES (1, 'Event 1', 50000, 'Arctic'), (2, 'Event 2', 75000, 'Antarctic'), (3, 'Event 3', 30000, 'Arctic');

SELECT AVG(budget) FROM humanitarian_assistance WHERE region = 'Arctic';


Question: What is the average size of the largest order for each salesperson?

CREATE TABLE salesperson (id INT, name VARCHAR(50), region VARCHAR(50)); INSERT INTO salesperson (id, name, region) VALUES (1, 'John Doe', 'North'), (2, 'Jane Smith', 'South'); CREATE TABLE orders (id INT, salesperson_id INT, size INT); INSERT INTO orders (id, salesperson_id, size) VALUES (1, 1, 10), (2, 1, 15), (3, 2, 20), (4, 2, 25);

SELECT salesperson_id, AVG(size) as avg_max_order_size FROM (SELECT salesperson_id, MAX(size) as size FROM orders GROUP BY salesperson_id) subquery GROUP BY salesperson_id;


Question: What is the average age of healthcare workers in the "healthcare_workers" table?

CREATE TABLE healthcare_workers (id INT, name VARCHAR(50), age INT, gender VARCHAR(10), location VARCHAR(50)); INSERT INTO healthcare_workers (id, name, age, gender, location) VALUES (1, 'John Doe', 35, 'Male', 'New York'); INSERT INTO healthcare_workers (id, name, age, gender, location) VALUES (2, 'Jane Smith', 32, 'Female', 'California');

SELECT AVG(age) FROM healthcare_workers;


Question: pgTAP test for Pgtap--0.92.0--0.93.0 (assertion 35).

-- language_owner_is ( language, user )
CREATE OR REPLACE FUNCTION language_owner_is ( NAME, NAME )
RETURNS TEXT AS $$
    SELECT language_owner_is(
        $1, $2,
        'Language ' || quote_ident($1) || ' should be owned by ' || quote_ident($2)
    );
$$ LANGUAGE sql;

Explanation: SQL assertion from pgTAP test suite for Pgtap--0.92.0--0.93.0.


Question: Generate PostgreSQL SQL for: Name the team for co-drivers of david brabham mario andretti

CREATE TABLE table_name_15 (team VARCHAR, co_drivers VARCHAR)

SELECT team FROM table_name_15 WHERE co_drivers = 'david brabham mario andretti';


Question: Generate PostgreSQL SQL for: Find the name of rooms whose base price is between 120 and 150.

CREATE TABLE rooms (roomname VARCHAR, baseprice INTEGER)

SELECT roomname FROM rooms WHERE baseprice BETWEEN 120 AND 150;


Question: What is the total budget allocated to parks in each borough?

CREATE TABLE budget_allocations (allocation_id INT, borough TEXT, category TEXT, budget INT); INSERT INTO budget_allocations (allocation_id, borough, category, budget) VALUES (1, 'Manhattan', 'Parks', 5000000), (2, 'Brooklyn', 'Libraries', 3000000), (3, 'Bronx', 'Parks', 2000000);

SELECT borough, SUM(budget) FROM budget_allocations WHERE category = 'Parks' GROUP BY borough;


Question: Identify the minimum score achieved by user 11 in game 'C'

CREATE TABLE game_scores (user_id INT, game_name VARCHAR(10), score INT); INSERT INTO game_scores (user_id, game_name, score) VALUES (11, 'C', 50), (11, 'C', 75), (11, 'D', 100), (12, 'A', 150), (13, 'B', 200), (13, 'C', 250);

SELECT MIN(score) FROM game_scores WHERE user_id = 11 AND game_name = 'C';


Question: How many public transportation trips were taken in each borough in 2020?

CREATE TABLE PublicTransportation (Year INT, Borough VARCHAR(20), Trips INT); INSERT INTO PublicTransportation (Year, Borough, Trips) VALUES (2020, 'Manhattan', 5000000), (2020, 'Brooklyn', 4000000), (2020, 'Queens', 3500000), (2020, 'Bronx', 3000000), (2020, 'Staten Island', 2000000);

SELECT Borough, Year, SUM(Trips) as Total_Trips FROM PublicTransportation GROUP BY Borough, Year;


Question: Generate PostgreSQL SQL for: How did Cleveland do in the Open Cup in 2009?

CREATE TABLE table_2357201_1 (open_cup VARCHAR, year VARCHAR)

SELECT open_cup FROM table_2357201_1 WHERE year = 2009;


Question: Delete all marine protected areas with a depth greater than 200 meters.

CREATE TABLE marine_protected_areas (id INT, name VARCHAR(255), location VARCHAR(255), depth FLOAT); INSERT INTO marine_protected_areas (id, name, location, depth) VALUES (1, 'MPA 1', 'Pacific Ocean', 123.4), (2, 'MPA 2', 'Atlantic Ocean', 150.0), (3, 'MPA 3', 'Indian Ocean', 75.0), (4, 'MPA 4', 'Pacific Ocean', 300.0);

DELETE FROM marine_protected_areas WHERE depth > 200;


Question: List all unique metro stations and their respective lines in the 'berlin' schema.

CREATE TABLE berlin.metro_stations (id INT, station_name VARCHAR); CREATE TABLE berlin.station_lines (id INT, station_id INT, line_name VARCHAR);

SELECT DISTINCT berlin.metro_stations.station_name, berlin.station_lines.line_name FROM berlin.metro_stations INNER JOIN berlin.station_lines ON berlin.metro_stations.id = berlin.station_lines.station_id;


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

SELECT t1.c1, t2.c2, t3.c3 FROM ft2 t1 LEFT JOIN ft2 t2 ON (t1.c1 = t2.c1) LEFT JOIN ft4 t3 ON (t2.c1 = t3.c1) OFFSET 10 LIMIT 10;


Question: What is the total population of indigenous communities in each Arctic country?

CREATE TABLE IndigenousCommunity (ID INT, Name TEXT, Country TEXT, Population INT); INSERT INTO IndigenousCommunity (ID, Name, Country, Population) VALUES (1, 'Community1', 'Canada', 200); INSERT INTO IndigenousCommunity (ID, Name, Country, Population) VALUES (2, 'Community2', 'Canada', 300); INSERT INTO IndigenousCommunity (ID, Name, Country, Population) VALUES (3, 'Community3', 'Russia', 400);

SELECT Country, SUM(Population) as Total_Population FROM IndigenousCommunity GROUP BY Country;


Question: Generate PostgreSQL SQL for: What is the home stadium of the Tennessee Titans?

CREATE TABLE table_name_10 (stadium VARCHAR, host_team VARCHAR)

SELECT stadium FROM table_name_10 WHERE host_team = 'tennessee titans';


Question: Generate PostgreSQL SQL for: What is the winning score of standard register ping tournament, which has Kelly Robbins as the runner-up?

CREATE TABLE table_name_46 (winning_score VARCHAR, tournament VARCHAR, runner_s__up VARCHAR)

SELECT winning_score FROM table_name_46 WHERE tournament = 'standard register ping' AND runner_s__up = 'kelly robbins';


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

CREATE UNIQUE INDEX CONCURRENTLY concur_index3 ON concur_heap(f2);


Question: What is the total number of ships involved in maritime accidents in the Atlantic Ocean?

CREATE TABLE maritime_accidents (ocean TEXT, year INT, ships_involved INT); INSERT INTO maritime_accidents (ocean, year, ships_involved) VALUES ('Atlantic', 2019, 123), ('Pacific', 2020, 456), ('Indian', 2018, 789);

SELECT SUM(ships_involved) FROM maritime_accidents WHERE ocean = 'Atlantic';


Question: What is the highest score in the 'basketball_games' table?

CREATE TABLE basketball_games (game_id INT, home_team INT, away_team INT, home_team_score INT, away_team_score INT); INSERT INTO basketball_games (game_id, home_team, away_team, home_team_score, away_team_score) VALUES (1, 1, 2, 100, 90), (2, 2, 1, 95, 105);

SELECT GREATEST(home_team_score, away_team_score) AS highest_score FROM basketball_games;


Question: What is the average number of hours spent on professional development by teachers in 'remote_learning'?

CREATE TABLE teachers (teacher_id INT, name VARCHAR(20), program VARCHAR(20)); INSERT INTO teachers (teacher_id, name, program) VALUES (1, 'John Doe', 'remote_learning'), (2, 'Jane Smith', 'in_person'), (3, 'Maria Garcia', 'remote_learning'); CREATE TABLE teacher_pd (teacher_id INT, course VARCHAR(20), hours INT); INSERT INTO teacher_pd (teacher_id, course, hours) VALUES (1, 'technology integration', 12), (2, 'classroom_management', 10), (3, 'diversity_equity_inclusion', 15);

SELECT AVG(hours) FROM teacher_pd INNER JOIN teachers ON teacher_pd.teacher_id = teachers.teacher_id WHERE teachers.program = 'remote_learning';


Question: Generate PostgreSQL SQL for: What is the type of the player whose transfer fee was €20m?

CREATE TABLE table_13770460_3 (type VARCHAR, transfer_fee VARCHAR)

SELECT type FROM table_13770460_3 WHERE transfer_fee = '€20M';


Question: Generate PostgreSQL SQL for: List all years in Orlando where Jeryl Sasser was a player.

CREATE TABLE table_15621965_17 (years_in_orlando VARCHAR, player VARCHAR)

SELECT years_in_orlando FROM table_15621965_17 WHERE player = 'Jeryl Sasser';


Question: What is the number of policy advocacy events held in 2021?

CREATE TABLE Policy_Advocacy_Events (event_id INT, year INT, type VARCHAR(255)); INSERT INTO Policy_Advocacy_Events VALUES (1, 2021, 'Webinar');

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


Question: What is the total number of visitors who are members of the museum, broken down by member type?

CREATE TABLE members(member_id INT, name VARCHAR(50), member_type VARCHAR(50)); INSERT INTO members (member_id, name, member_type) VALUES (1, 'John Doe', 'Individual'), (2, 'Jane Smith', 'Family'), (3, 'Alice Johnson', 'Individual');

SELECT member_type, COUNT(member_id) FROM members GROUP BY member_type;


Question: Generate PostgreSQL SQL for: Name the total number of high rebounds for february 10

CREATE TABLE table_17058151_8 (high_rebounds VARCHAR, date VARCHAR)

SELECT COUNT(high_rebounds) FROM table_17058151_8 WHERE date = 'February 10';


Question: PL/pgSQL test: Pltcl Queries (example 6).

select tcl_record_arg(row('tkey', 42, 'ref2')::d_comp1, 'ref1');

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


Question: Generate PostgreSQL SQL for: What is the transfer period for habarugira?

CREATE TABLE table_name_16 (transfer_window VARCHAR, name VARCHAR)

SELECT transfer_window FROM table_name_16 WHERE name = 'habarugira';


Question: How many travel advisories were issued for Japan in the last 5 years?

CREATE TABLE travel_advisories (advisory_id INT, country TEXT, issue_date DATE); INSERT INTO travel_advisories (advisory_id, country, issue_date) VALUES (1, 'Japan', '2017-01-01'), (2, 'Japan', '2018-03-15'), (3, 'Japan', '2019-07-28'), (4, 'Japan', '2020-12-22'), (5, 'Japan', '2021-03-04');

SELECT COUNT(*) FROM travel_advisories WHERE country = 'Japan' AND issue_date >= DATE('now', '-5 year');


Question: Generate PostgreSQL SQL for: What is the decile of the school with a roll larger than 513?

CREATE TABLE table_name_36 (decile INTEGER, roll INTEGER)

SELECT SUM(decile) FROM table_name_36 WHERE roll > 513;


Question: pgTAP test for Resultset (assertion 18).

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


Question: What is the weight (in kg) of the heaviest spacecraft ever built?

CREATE TABLE spacecraft(id INT, name VARCHAR(255), weight_kg FLOAT); INSERT INTO spacecraft(id, name, weight_kg) VALUES (1, 'Saturn V', 303540.0), (2, 'Space Shuttle', 110000.0);


Question: Write the DML statement from PostgreSQL regression test 'partition_split' (example 230).

Explanation: DML from PostgreSQL core regression test for Partition Split.


Question: PostgreSQL regression test 'hash_func': Write the SELECT query (example 26).

SELECT v as value, pg_lsn_hash(v)::bit(32) as standard,
       pg_lsn_hash_extended(v, 0)::bit(32) as extended0,
       pg_lsn_hash_extended(v, 1)::bit(32) as extended1
FROM   (VALUES (NULL::pg_lsn), ('16/B374D84'), ('30/B374D84'),
        ('255/B374D84'), ('25/B379D90'), ('900/F37FD90')) x(v)
WHERE  pg_lsn_hash(v)::bit(32) != pg_lsn_hash_extended(v, 0)::bit(32)
       OR pg_lsn_hash(v)::bit(32) = pg_lsn_hash_extended(v, 1)::bit(32);

Explanation: Regression test for Hash Func in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT v as value, pg_lsn_hash(v)::bit(32) as standard,
       pg_lsn_hash_extended(v, 0)::bit(32) as extended0,
       pg_lsn_hash_extended(v, 1)::bit(32) as extended1
FROM   (VALUES (NULL::pg_lsn), ('16/B374D84'), ('30/B374D84'),
        ('255/B374D84'), ('25/B379D90'), ('900/F37FD90')) x(v)
WHERE  pg_lsn_hash(v)::bit(32) != pg_lsn_hash_extended(v, 0)::bit(32)
       OR pg_lsn_hash(v)::bit(32) = pg_lsn_hash_extended(v, 1)::bit(32)) AS _sub;


Question: Find the number of rural healthcare providers that offer mental health services, grouped by provider type.

CREATE TABLE healthcare_providers (id INT, name TEXT, type TEXT, services TEXT);

SELECT type, COUNT(*) FROM healthcare_providers WHERE services LIKE '%Mental Health%' GROUP BY type;


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

ALTER EXTENSION pgtap ADD FUNCTION _relcomp( TEXT, TEXT, TEXT, TEXT );


Question: Which fair labor practices are most frequently implemented in the footwear industry across countries?

CREATE TABLE Practices (id INT, name VARCHAR(255), type VARCHAR(255), implementation_location VARCHAR(255), industry VARCHAR(255)); INSERT INTO Practices (id, name, type, implementation_location, industry) VALUES (1, 'Living Wage', 'Fair Labor Practice', 'Indonesia', 'Footwear'); INSERT INTO Practices (id, name, type, implementation_location, industry) VALUES (2, 'Safe Workplace', 'Fair Labor Practice', 'Italy', 'Footwear'); INSERT INTO Practices (id, name, type, implementation_location, industry) VALUES (3, 'Collective Bargaining', 'Fair Labor Practice', 'Brazil', 'Footwear');

SELECT implementation_location, COUNT(*) FROM Practices WHERE type = 'Fair Labor Practice' AND industry = 'Footwear' GROUP BY implementation_location ORDER BY COUNT(*) DESC LIMIT 1;


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

select tableoid::regclass, * from hp order by c;

Explanation: Regression test for Partition Prune in PostgreSQL core test suite.

SELECT count(*) FROM (select tableoid::regclass, * from hp order by c) AS _sub;


Question: What was the total number of art pieces sold at the "London Art Gallery" in the first quarter of 2021?

CREATE TABLE ArtSales5 (GalleryName TEXT, SaleDate DATE, NumPieces INTEGER); INSERT INTO ArtSales5 (GalleryName, SaleDate, NumPieces) VALUES ('London Art Gallery', '2021-01-01', 8), ('London Art Gallery', '2021-02-15', 12), ('London Art Gallery', '2021-03-20', 16);

SELECT SUM(NumPieces) FROM ArtSales5 WHERE GalleryName = 'London Art Gallery' AND QUARTER(SaleDate) = 1 AND YEAR(SaleDate) = 2021;


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

SELECT * FROM pg_input_error_info('[{"attributes" : null, "dependency" : 4, "degree": 1.000}]', 'pg_dependencies');

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

SELECT count(*) FROM (SELECT * FROM pg_input_error_info('[{"attributes" : null, "dependency" : 4, "degree": 1.000}]', 'pg_dependencies')) AS _sub;


Question: What is the minimum age of visitors who attended the exhibition 'The Art of the Silk Road'?

CREATE TABLE exhibitions (id INT, city VARCHAR(20), visitor_age INT, visit_date DATE); INSERT INTO exhibitions (id, city, visitor_age, visit_date) VALUES (1, 'New York', 12, '2022-01-01'); INSERT INTO exhibitions (id, city, visitor_age, visit_date) VALUES (2, 'Los Angeles', 15, '2022-02-15');

SELECT MIN(visitor_age) FROM exhibitions WHERE exhibition_name = 'The Art of the Silk Road';


Question: Add a new column 'precinct' to the 'crime_statistics' table

CREATE TABLE crime_statistics(id INT, location VARCHAR(20), time DATE);

ALTER TABLE crime_statistics ADD COLUMN precinct VARCHAR(10);


Question: What is the name of the forest where the highest temperature was recorded and it was established after the average year of establishment?

CREATE TABLE Forests (id INT, name VARCHAR(50), country VARCHAR(50), hectares INT, year_established INT); CREATE TABLE Climate (id INT, temperature FLOAT, year INT, forest_id INT); INSERT INTO Forests (id, name, country, hectares, year_established) VALUES (1, 'Bialowieza', 'Poland', 141000, 1921), (2, 'Amazon', 'Brazil', 340000, 1968), (3, 'Daintree', 'Australia', 12000, 1770); INSERT INTO Climate (id, temperature, year, forest_id) VALUES (1, 15.5, 1921, 1), (2, 28.7, 2005, 2), (3, 34.1, 1998, 3), (4, 26.3, 1982, 2);

SELECT Forests.name FROM Forests, Climate WHERE Forests.id = Climate.forest_id AND temperature = (SELECT MAX(temperature) FROM Climate) AND year_established > (SELECT AVG(year_established) FROM Forests);


Question: Generate PostgreSQL SQL for: If the location is Chicago, Illinois, what is the airport name?

CREATE TABLE table_18047346_4 (airport_name VARCHAR, location VARCHAR)

SELECT airport_name FROM table_18047346_4 WHERE location = 'Chicago, Illinois';


Question: What is the percentage of sales by ethical material?

CREATE TABLE SalesByMaterial (SaleID INT, Material VARCHAR(50), Sales DECIMAL(5,2)); INSERT INTO SalesByMaterial (SaleID, Material, Sales) VALUES (1, 'Organic Cotton', 1200.50), (2, 'Hemp', 752.20), (3, 'Recycled Polyester', 986.60), (4, 'Tencel', 310.10);

SELECT Material, ROUND(SUM(Sales) / (SELECT SUM(Sales) FROM SalesByMaterial) * 100, 2) AS Percentage FROM SalesByMaterial GROUP BY Material;