Question: What is the percentage of hotels in Sydney that have adopted AI technology?

CREATE TABLE hotels (hotel_id INT, hotel_name TEXT, city TEXT, ai_adoption INT); INSERT INTO hotels (hotel_id, hotel_name, city, ai_adoption) VALUES (1, 'The Park Hyatt Sydney', 'Sydney', 1), (2, 'The Four Seasons Hotel Sydney', 'Sydney', 1), (3, 'The Shangri-La Hotel Sydney', 'Sydney', 0), (4, 'The InterContinental Sydney', 'Sydney', 1), (5, 'The Langham Sydney', 'Sydney', 0);

SELECT city, 100.0 * SUM(ai_adoption) / COUNT(*) as adoption_percentage FROM hotels WHERE city = 'Sydney' GROUP BY city;


Question: What is the total amount of Shariah-compliant loans issued by Zakat Bank in 2020, segmented by loan type?

CREATE TABLE ZakatBank (id INT, loan_type VARCHAR(20), amount DECIMAL(10,2), issue_date DATE);

SELECT loan_type, SUM(amount) FROM ZakatBank WHERE YEAR(issue_date) = 2020 GROUP BY loan_type;


Question: Generate PostgreSQL SQL for: What is the highest Markatal, when Municipality is Leirvík, and when Inhabitants Per Km² is greater than 79?

CREATE TABLE table_name_69 (markatal INTEGER, municipality VARCHAR, inhabitants_per_km² VARCHAR)

SELECT MAX(markatal) FROM table_name_69 WHERE municipality = 'leirvík' AND inhabitants_per_km² > 79;


Question: Determine the current landfill capacity for 'Oceania' from the 'landfill_capacity' table

CREATE TABLE landfill_capacity (region VARCHAR(50), current_capacity INT);

SELECT current_capacity FROM landfill_capacity WHERE region = 'Oceania';


Question: Generate PostgreSQL SQL for: What is the total time for one south broad?

CREATE TABLE table_name_79 (year INTEGER, name VARCHAR)

SELECT SUM(year) FROM table_name_79 WHERE name = 'one south broad';


Question: Generate PostgreSQL SQL for: Round that greg huntington went in?

CREATE TABLE table_name_54 (round VARCHAR, name VARCHAR)

SELECT round FROM table_name_54 WHERE name = 'greg huntington';


Question: What is the number of buildings in the 'carbon_offsets' schema with energy consumption < 1000?

CREATE TABLE carbon_offsets.building_energy_consumption (building VARCHAR(50), consumption FLOAT); INSERT INTO carbon_offsets.building_energy_consumption (building, consumption) VALUES ('Rainbow Building', 900.0), ('Skylight Building', 800.0), ('Sunrise Building', 700.0), ('Morning Building', 600.0), ('Evening Building', 500.0);

SELECT COUNT(*) FROM carbon_offsets.building_energy_consumption WHERE consumption < 1000;


Question: Calculate the average sales price for each drug in 2021.

CREATE TABLE drug_sales_price (drug_name TEXT, year INTEGER, sale_price NUMERIC(10, 2)); INSERT INTO drug_sales_price (drug_name, year, sale_price) VALUES ('DrugA', 2021, 120.50), ('DrugA', 2021, 125.00), ('DrugB', 2021, 150.75), ('DrugB', 2021, 155.00), ('DrugC', 2021, 100.00), ('DrugC', 2021, 105.00);

SELECT drug_name, AVG(sale_price) as avg_sale_price FROM drug_sales_price WHERE year = 2021 GROUP BY drug_name;


Question: Generate PostgreSQL SQL for: Which of the biggest points numbers had a year more recent than 1953?

CREATE TABLE table_name_62 (points INTEGER, year INTEGER)

SELECT MAX(points) FROM table_name_62 WHERE year > 1953;


Question: Write the DDL statement from PostgreSQL regression test 'indexing' (example 82).

create index on idxpart1 using hash (a);

Explanation: DDL from PostgreSQL core regression test for Indexing.


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

-- IN
SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE (a * 2) IN (2, 102) AND upper(b) = ''1''');

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


Question: Generate PostgreSQL SQL for: Which IATA's ICAO is rjss?

CREATE TABLE table_name_17 (iata VARCHAR, icao VARCHAR)

SELECT iata FROM table_name_17 WHERE icao = 'rjss';


Question: Generate PostgreSQL SQL for: On which date did Ger Loughnane from Team Clare have a match?

CREATE TABLE table_name_88 (date VARCHAR, team VARCHAR, player VARCHAR)

SELECT date FROM table_name_88 WHERE team = 'clare' AND player = 'ger loughnane';


Question: Write the DML statement from PostgreSQL regression test 'identity' (example 176).

INSERT INTO pitest2_p2 (f1, f2, f3) VALUES ('2016-08-6', 'from pitest2_p2', 300);

Explanation: DML from PostgreSQL core regression test for Identity.


Question: Insert a new community development initiative in 'Amazonas' region with ID 3, name 'Cultural Center', and status 'planning' into the 'community_development' table.

CREATE TABLE community_development(id INT, region TEXT, initiative_name TEXT, status TEXT);

INSERT INTO community_development (id, region, initiative_name, status) VALUES (3, 'Amazonas', 'Cultural Center', 'planning');


Question: Find the number of unique chemicals produced by each factory.

CREATE TABLE factories (id INT, name TEXT); INSERT INTO factories (id, name) VALUES (1, 'Factory A'), (2, 'Factory B'); CREATE TABLE chemical_produced (factory_id INT, chemical_name TEXT); INSERT INTO chemical_produced (factory_id, chemical_name) VALUES (1, 'Chemical X'), (1, 'Chemical X'), (2, 'Chemical Y'), (2, 'Chemical Z');

SELECT factory_id, COUNT(DISTINCT chemical_name) AS unique_chemicals_produced FROM chemical_produced GROUP BY factory_id;


Question: What is the average daily engagement for virtual tours in the 'Americas' region for the year 2022?

CREATE TABLE virtual_tour_engagement (id INT, hotel_id INT, region TEXT, calendar DATE, engagement INT);

SELECT region, AVG(engagement) FROM virtual_tour_engagement WHERE region = 'Americas' AND YEAR(calendar) = 2022 GROUP BY region;


Question: Generate PostgreSQL SQL for: What is Brown Motors best point total using the Offenhauser L4 engine since 1950?

CREATE TABLE table_name_72 (points INTEGER, entrant VARCHAR, year VARCHAR, engine VARCHAR)

SELECT MAX(points) FROM table_name_72 WHERE year > 1950 AND engine = 'offenhauser l4' AND entrant = 'brown motors';


Question: Generate PostgreSQL SQL for: Which Pick has a Nationality of canada, and a Round of 5?

CREATE TABLE table_name_98 (pick VARCHAR, nationality VARCHAR, round VARCHAR)

SELECT pick FROM table_name_98 WHERE nationality = 'canada' AND round = 5;


Question: How many community policing events were held in the Los Angeles County in the year 2020?

CREATE TABLE community_policing (id INT, county VARCHAR(20), year INT, events INT);

SELECT COUNT(*) FROM community_policing WHERE county = 'Los Angeles' AND year = 2020;


Question: Generate PostgreSQL SQL for: Show names for all aircrafts with distances more than the average.

CREATE TABLE Aircraft (name VARCHAR, distance INTEGER)

SELECT name FROM Aircraft WHERE distance > (SELECT AVG(distance) FROM Aircraft);


Question: How many unique donors have there been for each program?

CREATE TABLE donations (id INT, donor_id INT, donation_amount DECIMAL, donation_date DATE, donation_program VARCHAR); INSERT INTO donations (id, donor_id, donation_amount, donation_date, donation_program) VALUES (1, 101, '500', '2021-01-01', 'Education'), (2, 102, '300', '2021-02-01', 'Environment'), (3, 101, '800', '2021-03-01', 'Education'); CREATE TABLE programs (id INT, name VARCHAR); INSERT INTO programs (id, name) VALUES (1, 'Education'), (2, 'Environment');

SELECT p.name as program_name, COUNT(DISTINCT d.donor_id) as num_unique_donors FROM donations d JOIN programs p ON d.donation_program = p.name GROUP BY p.name;


Question: How many athletes have participated in a specific event?

CREATE TABLE events (event_id INT, event_name VARCHAR(50)); CREATE TABLE athlete_events (athlete_id INT, event_id INT);

SELECT e.event_name, COUNT(*) as athlete_count FROM events e JOIN athlete_events ae ON e.event_id = ae.event_id GROUP BY e.event_name;


Question: Generate PostgreSQL SQL for: What was the date of the week 13 game?

CREATE TABLE table_name_96 (date VARCHAR, week VARCHAR)

SELECT date FROM table_name_96 WHERE week = 13;


Question: Generate PostgreSQL SQL for: What was the earliest week the team played the chicago cardinals in front of less than 25,312?

CREATE TABLE table_name_12 (week INTEGER, opponent VARCHAR, attendance VARCHAR)

SELECT MIN(week) FROM table_name_12 WHERE opponent = 'chicago cardinals' AND attendance < 25 OFFSET 312;


Question: Write the DDL statement from PostgreSQL regression test 'indirect_toast' (example 3).

CREATE TABLE indtoasttest(descr text, cnt int DEFAULT 0, f1 text, f2 text);

Explanation: DDL from PostgreSQL core regression test for Indirect Toast.


Question: What is the total revenue of restaurants located in California?

CREATE TABLE restaurants (id INT, name TEXT, state TEXT); INSERT INTO restaurants (id, name, state) VALUES (1, 'Restaurant A', 'California'), (2, 'Restaurant B', 'New York'); CREATE TABLE revenue (restaurant_id INT, amount INT); INSERT INTO revenue (restaurant_id, amount) VALUES (1, 10000), (1, 12000), (2, 8000);

SELECT SUM(revenue.amount) FROM revenue JOIN restaurants ON revenue.restaurant_id = restaurants.id WHERE restaurants.state = 'California';


Question: List the titles and authors of all publications in the field of 'Machine Learning' that were published after the year 2010.

CREATE TABLE publications (id INT, title TEXT, author VARCHAR(50), field VARCHAR(50), year INT); INSERT INTO publications (id, title, author, field, year) VALUES (1, 'Data Science for Dummies', 'Alice', 'Data Science', 2015); INSERT INTO publications (id, title, author, field, year) VALUES (2, 'Calculus: A Complete Course', 'John Doe', 'Calculus', 2005); INSERT INTO publications (id, title, author, field, year) VALUES (3, 'Machine Learning: A Comprehensive Introduction', 'Eve Researcher', 'Machine Learning', 2012);

SELECT title, author FROM publications WHERE field = 'Machine Learning' AND year > 2010;


Question: Generate PostgreSQL SQL for: For the episode(s) aired in the U.S. on 4 april 2008, what were the names?

CREATE TABLE table_10935205_1 (title VARCHAR, us_airdate VARCHAR)

SELECT title FROM table_10935205_1 WHERE us_airdate = '4 April 2008';


Question: Generate PostgreSQL SQL for: what's the win with points for being 376

CREATE TABLE table_12828723_3 (won VARCHAR, points_for VARCHAR)

SELECT won FROM table_12828723_3 WHERE points_for = '376';


Question: Generate PostgreSQL SQL for: What are the Asian countries which have a population larger than that of any country in Africa?

CREATE TABLE country (Name VARCHAR, Continent VARCHAR, population INTEGER)

SELECT Name FROM country WHERE Continent = 'Asia' AND population > (SELECT MIN(population) FROM country WHERE Continent = 'Africa');


Question: What is the number of workers employed in factories that use renewable energy sources in Germany and France?

CREATE TABLE factories (factory_id INT, country VARCHAR(50), energy_source VARCHAR(50)); CREATE TABLE workers (worker_id INT, factory_id INT, position VARCHAR(50)); INSERT INTO factories (factory_id, country, energy_source) VALUES (1, 'Germany', 'renewable'), (2, 'France', 'fossil fuel'), (3, 'Germany', 'renewable'); INSERT INTO workers (worker_id, factory_id, position) VALUES (1, 1, 'manager'), (2, 1, 'engineer'), (3, 2, 'worker'), (4, 3, 'manager');

SELECT COUNT(workers.worker_id) FROM workers INNER JOIN factories ON workers.factory_id = factories.factory_id WHERE factories.country IN ('Germany', 'France') AND factories.energy_source = 'renewable';


Question: pgTAP test for Hastap (assertion 127).

SELECT * FROM check_test(
    hasnt_domain( 'public'::name, 'us_postal_code'::name ),
    false,
    'hasnt_domain(scheam, domain)',
    'Domain public.us_postal_code should not exist',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Hastap.


Question: Generate PostgreSQL SQL for: What was the population of сурдук in 2011?

CREATE TABLE table_2562572_53 (population__2011_ VARCHAR, cyrillic_name VARCHAR)

SELECT COUNT(population__2011_) FROM table_2562572_53 WHERE cyrillic_name = 'Сурдук';


Question: Generate PostgreSQL SQL for: What was the earliest year that Târlea took 7th place?

CREATE TABLE table_name_6 (year INTEGER, position VARCHAR)

SELECT MIN(year) FROM table_name_6 WHERE position = '7th';


Question: pgTAP test for Cmpok (assertion 6).

Explanation: SQL assertion from pgTAP test suite for Cmpok.


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

DELETE FROM temporal_rng WHERE id = '[5,6)' AND valid_at = daterange('2018-01-01', '2018-02-01');

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


Question: Generate PostgreSQL SQL for: How many different sizes (in acres) are noted for Rathcoola East?

CREATE TABLE table_30120566_1 (area__acres__ VARCHAR, townland VARCHAR)

SELECT COUNT(area__acres__) FROM table_30120566_1 WHERE townland = 'Rathcoola East';


Question: Generate PostgreSQL SQL for: What was the Ravens' record on December 5, 1999?

CREATE TABLE table_name_33 (record VARCHAR, date VARCHAR)

SELECT record FROM table_name_33 WHERE date = 'december 5, 1999';


Question: Generate PostgreSQL SQL for: What score has 33 as the points?

CREATE TABLE table_name_93 (score VARCHAR, points VARCHAR)

SELECT score FROM table_name_93 WHERE points = 33;


Question: Show an example of PostgreSQL UPDATE (example 7).

UPDATE accounts SET (contact_first_name, contact_last_name) = (SELECT first_name, last_name FROM employees WHERE employees.id = accounts.sales_person);

Explanation: PostgreSQL UPDATE command.


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

SELECT count(*) FROM timetmp WHERE a  = '10:57:11'::time;

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


Question: Find the mining operations in the 'Andes' mountain range with the highest CO2 emissions

CREATE TABLE MiningOperations (id INT, name VARCHAR(255), type VARCHAR(255), co2_emissions INT, location VARCHAR(255)); INSERT INTO MiningOperations (id, name, type, co2_emissions, location) VALUES (1, 'Open Pit Mining', 'Surface', 500, 'Andes'), (2, 'Underground Mining', 'Underground', 300, 'Andes'), (3, 'Mountaintop Removal Mining', 'Surface', 700, 'Appalachians'), (4, 'Placer Mining', 'Surface', 200, 'Himalayas'), (5, 'Hard Rock Mining', 'Underground', 800, 'Urals');

SELECT name, type, co2_emissions FROM MiningOperations WHERE location = 'Andes' ORDER BY co2_emissions DESC LIMIT 1;


Question: Generate PostgreSQL SQL for: What was the Decision when the Visitor was Carolina?

CREATE TABLE table_name_53 (decision VARCHAR, visitor VARCHAR)

SELECT decision FROM table_name_53 WHERE visitor = 'carolina';


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

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

SELECT count(*) FROM (SELECT bit_count('\x1234567890'::bytea)) AS _sub;


Question: Delete the record of the investment round with id 5 in the investment_rounds table

CREATE TABLE investment_rounds (id INT, company_id INT, funding_amount INT);

DELETE FROM investment_rounds WHERE id = 5;


Question: What is the total amount spent on raw materials for each product line?

CREATE TABLE raw_materials (id INT, product_line VARCHAR(50), amount INT); INSERT INTO raw_materials (id, product_line, amount) VALUES (1, 'product1', 10000); INSERT INTO raw_materials (id, product_line, amount) VALUES (2, 'product2', 15000);

SELECT product_line, SUM(amount) FROM raw_materials GROUP BY product_line;


Question: Generate PostgreSQL SQL for: What type is the misurina to bassano del grappa course?

CREATE TABLE table_name_24 (type VARCHAR, course VARCHAR)

SELECT type FROM table_name_24 WHERE course = 'misurina to bassano del grappa';


Question: Identify the mental health facilities that have the highest and lowest capacity for each type.

CREATE TABLE mental_health_facilities (facility_id INT, name VARCHAR(255), location VARCHAR(255), type VARCHAR(255), capacity INT); INSERT INTO mental_health_facilities (facility_id, name, location, type, capacity) VALUES (1, 'Serenity House', 'New York, NY', 'Inpatient', 50), (2, 'Harmony House', 'New York, NY', 'Inpatient', 80), (3, 'Tranquility House', 'New York, NY', 'Outpatient', 30), (4, 'Zenith House', 'New York, NY', 'Outpatient', 60);

SELECT facility_id, name, type, capacity, MIN(capacity) OVER(PARTITION BY type) as lowest_capacity, MAX(capacity) OVER(PARTITION BY type) as highest_capacity FROM mental_health_facilities;


Question: Identify the vessels that have transported more than 120 containers to India in the month of May 2020.

CREATE TABLE Vessel_Movements (id INT, vessel VARCHAR(255), quantity INT, port VARCHAR(255), time DATETIME); INSERT INTO Vessel_Movements (id, vessel, quantity, port, time) VALUES (1, 'Indian Ocean Giant', 150, 'Mumbai', '2020-05-01 10:00:00'), (2, 'Maritime Marvel', 120, 'Chennai', '2020-05-15 15:30:00');

SELECT vessel FROM Vessel_Movements VM JOIN (SELECT vessel, SUM(quantity) AS total_quantity FROM Vessel_Movements WHERE port = 'India' AND MONTH(time) = 5 AND YEAR(time) = 2020 GROUP BY vessel) V ON VM.vessel = V.vessel WHERE V.total_quantity > 120;


Question: Generate PostgreSQL SQL for: What state is Tanya Plibersek from?

CREATE TABLE table_name_15 (state VARCHAR, member VARCHAR)

SELECT state FROM table_name_15 WHERE member = 'tanya plibersek';


Question: List all product safety records with a rating below 70 for Indian-manufactured cosmetics.

CREATE TABLE product_safety (product_name TEXT, manufactured_country TEXT, safety_rating INT); INSERT INTO product_safety VALUES ('Cleanser 1', 'India', 65), ('Toner 1', 'India', 72), ('Moisturizer 1', 'India', 80), ('Cleanser 2', 'USA', 78), ('Toner 2', 'France', 85);

SELECT product_name, manufactured_country, safety_rating FROM product_safety WHERE manufactured_country = 'India' AND safety_rating < 70;


Question: What is the total number of smart city devices in cities with a population greater than 500,000?

CREATE TABLE City (id INT, name VARCHAR(255), population INT, smart_city_devices INT); INSERT INTO City (id, name, population, smart_city_devices) VALUES (1, 'Tokyo', 9000000, 500); INSERT INTO City (id, name, population, smart_city_devices) VALUES (2, 'Berlin', 3500000, 300);

SELECT COUNT(smart_city_devices) FROM City WHERE population > 500000;


Question: Which climate adaptation projects have the same budget as any project in the climate finance domain?

CREATE TABLE climate_adaptation(project_name TEXT, budget FLOAT); INSERT INTO climate_adaptation(project_name, budget) VALUES ('Project I', 200000.00), ('Project J', 250000.00), ('Project K', 300000.00), ('Project L', 350000.00);

SELECT project_name FROM climate_adaptation WHERE budget IN (SELECT budget FROM climate_finance);


Question: Insert a new sale for the state of Washington in Q3 2022 with a revenue of 20000 and a strain of "Purple Haze"

CREATE TABLE sales (id INT, state VARCHAR(50), quarter VARCHAR(10), strain VARCHAR(50), revenue INT);

INSERT INTO sales (state, quarter, strain, revenue) VALUES ('Washington', 'Q3', 'Purple Haze', 20000);


Question: How many healthcare projects in the 'healthcare_projects' table have a budget over 2 million dollars?

CREATE TABLE healthcare_projects (project VARCHAR(50), budget INT); INSERT INTO healthcare_projects (project, budget) VALUES ('Hospital Building', 4000000); INSERT INTO healthcare_projects (project, budget) VALUES ('Medical Equipment', 1000000); INSERT INTO healthcare_projects (project, budget) VALUES ('Clinic Expansion', 2500000);

SELECT COUNT(*) FROM healthcare_projects WHERE budget > 2000000;


Question: PL/pgSQL test: Plpython Trigger (example 102).

CREATE FUNCTION composite_trigger_noop_f() RETURNS trigger AS $$
    return 'MODIFY'
$$ LANGUAGE plpython3u;

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


Question: Delete records of fashion trends that were discontinued in the last year, based on the UpdateDate in the FashionTrends table.

CREATE TABLE FashionTrends (TrendID INT, TrendName VARCHAR(50), Category VARCHAR(50), UpdateDate DATE);

DELETE FROM FashionTrends WHERE UpdateDate < DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR);


Question: For the "defense_diplomacy" table, insert new records for each of the following: Malaysia, 2021, Bilateral; Thailand, 2022, Multilateral

CREATE TABLE defense_diplomacy (id INT PRIMARY KEY, country VARCHAR(50), year INT, type VARCHAR(20));

INSERT INTO defense_diplomacy (id, country, year, type) VALUES (1, 'Malaysia', 2021, 'Bilateral'), (2, 'Thailand', 2022, 'Multilateral');


Question: What is the total revenue generated by sustainable tourism in Germany and France last year?

CREATE TABLE tourism_revenue (year INT, country VARCHAR(255), revenue INT); INSERT INTO tourism_revenue (year, country, revenue) VALUES (2021, 'Germany', 9000000), (2021, 'France', 10000000);

SELECT SUM(revenue) FROM tourism_revenue WHERE country IN ('Germany', 'France') AND year = 2021;


Question: What was the average delay for defense projects in the Asia-Pacific region in 2020?

CREATE SCHEMA if not exists defense_projects;CREATE TABLE if not exists defense_project_delays(project_name text, delay_region text, delay_year integer, delay_duration integer);INSERT INTO defense_project_delays(project_name, delay_region, delay_year, delay_duration) VALUES('F-35', 'Asia-Pacific', 2020, 2), ('Joint Light Tactical Vehicle', 'Asia-Pacific', 2020, 3), ('Global Hawk', 'Asia-Pacific', 2020, 1);

SELECT AVG(delay_duration) FROM defense_project_delays WHERE delay_region = 'Asia-Pacific' AND delay_year = 2020;


Question: Generate PostgreSQL SQL for: What Venue on October 27, 2005 had a Score of 5-0?

CREATE TABLE table_name_65 (venue VARCHAR, score VARCHAR, date VARCHAR)

SELECT venue FROM table_name_65 WHERE score = '5-0' AND date = 'october 27, 2005';


Question: Generate PostgreSQL SQL for: When BVA was 3%, what was the Ipsos?

CREATE TABLE table_name_16 (ipsos_5_30_09 VARCHAR, bva_6_1_09 VARCHAR)

SELECT ipsos_5_30_09 FROM table_name_16 WHERE bva_6_1_09 = '3%';


Question: Write the DML statement from PostgreSQL regression test 'stats_ext' (example 638).

INSERT INTO mcv_lists_multi (a, b, c, d)
    SELECT
         mod(i,5),
         mod(i,5),
         mod(i,7),
         mod(i,7)
    FROM generate_series(1,5000) s(i);

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


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

-- infer anyelement from anyrange
create function inoutparam_succeed(out i anyelement, inout r anyrange)
  as $$ select upper($1), $1 $$ language sql;

select * from inoutparam_succeed(int4range(1,2));

create function table_succeed(r anyrange)
  returns table(l anyelement, u anyelement)
  as $$ select lower($1), upper($1) $$
  language sql;

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


Question: Generate PostgreSQL SQL for: Who is every young rider classification when Jelle Vanendert is the winner?

CREATE TABLE table_25999087_2 (young_rider_classification VARCHAR, winner VARCHAR)

SELECT young_rider_classification FROM table_25999087_2 WHERE winner = 'Jelle Vanendert';


Question: Generate PostgreSQL SQL for: What is the sum of UCI points for Kim Kirchen?

CREATE TABLE table_name_42 (uci_points INTEGER, cyclist VARCHAR)

SELECT SUM(uci_points) FROM table_name_42 WHERE cyclist = 'kim kirchen';


Question: List all marine species that are threatened or endangered and have been recorded at a depth greater than 2000 meters.

CREATE TABLE marine_species (species_id INT, species_name VARCHAR(100), conservation_status VARCHAR(50), max_depth FLOAT, order_name VARCHAR(50));

SELECT species_name FROM marine_species WHERE conservation_status IN ('Threatened', 'Endangered') AND max_depth > 2000;


Question: How many solar power plants were built in '2020' and '2021' that have an efficiency rating above 20%?

CREATE TABLE solar_plants (id INT, name VARCHAR(50), built_year INT, location VARCHAR(50), efficiency FLOAT); INSERT INTO solar_plants (id, name, built_year, location, efficiency) VALUES (1, 'SolarPlant1', 2020, 'LocationA', 0.22), (2, 'SolarPlant2', 2021, 'LocationB', 0.18);

SELECT COUNT(*) FROM solar_plants WHERE built_year IN (2020, 2021) AND efficiency > 0.20;


Question: Generate PostgreSQL SQL for: Who is the opponent in the final when frankfurt is championship and the year is less than 1993.0?

CREATE TABLE table_22834834_2 (opponent_in_the_final VARCHAR, championship VARCHAR, year VARCHAR)

SELECT opponent_in_the_final FROM table_22834834_2 WHERE championship = 'Frankfurt' AND year < 1993.0;


Question: Generate PostgreSQL SQL for: Ashley Grimes had what to club?

CREATE TABLE table_name_26 (to_club VARCHAR, player VARCHAR)

SELECT to_club FROM table_name_26 WHERE player = 'ashley grimes';


Question: Generate PostgreSQL SQL for: What is the Round of 16 value for the nation with a value of 5 for Ranking Round Rank?

CREATE TABLE table_name_83 (round_of_16 VARCHAR, ranking_round_rank VARCHAR)

SELECT round_of_16 FROM table_name_83 WHERE ranking_round_rank = 5;


Question: Generate PostgreSQL SQL for: What is the average grid for jack brabham going over 32 laps?

CREATE TABLE table_name_66 (grid INTEGER, driver VARCHAR, laps VARCHAR)

SELECT AVG(grid) FROM table_name_66 WHERE driver = 'jack brabham' AND laps > 32;


Question: What is the total number of employees working in mining sites located in California?

CREATE TABLE sites (site_id INT, site_name VARCHAR(100), state VARCHAR(50)); INSERT INTO sites (site_id, site_name, state) VALUES (1, 'Golden Mining Site', 'California'); INSERT INTO sites (site_id, site_name, state) VALUES (2, 'Silver Peak Mine', 'Nevada'); CREATE TABLE employees (employee_id INT, employee_name VARCHAR(100), site_id INT); INSERT INTO employees (employee_id, employee_name, site_id) VALUES (1, 'John Doe', 1); INSERT INTO employees (employee_id, employee_name, site_id) VALUES (2, 'Jane Smith', 1); INSERT INTO employees (employee_id, employee_name, site_id) VALUES (3, 'Robert Johnson', 2);

SELECT COUNT(*) FROM employees WHERE site_id IN (SELECT site_id FROM sites WHERE state = 'California');


Question: What is the total production cost of bamboo viscose in China?

CREATE TABLE ProductionCosts (product VARCHAR(255), material VARCHAR(255), cost DECIMAL(10,2)); INSERT INTO ProductionCosts (product, material, cost) VALUES ('Bamboo Viscose', 'China', 8.5);

SELECT SUM(cost) FROM ProductionCosts WHERE product = 'Bamboo Viscose' AND material = 'China';


Question: What is the average warehouse management cost per item for each warehouse in Q3 2021?

CREATE TABLE warehouse_management (item_id INT, warehouse_id INT, cost FLOAT, order_date DATE);

SELECT warehouse_id, AVG(cost/COUNT(*)) as avg_cost_per_item FROM warehouse_management WHERE EXTRACT(MONTH FROM order_date) BETWEEN 7 AND 9 GROUP BY warehouse_id;


Question: Generate PostgreSQL SQL for: What is the amount of viewers if the series number is 14?

CREATE TABLE table_24639086_3 (viewers__in_millions_ VARCHAR, series__number VARCHAR)

SELECT viewers__in_millions_ FROM table_24639086_3 WHERE series__number = 14;


Question: How many volunteers engaged in each program in Q1 2021, grouped by city?

CREATE TABLE Volunteers (VolunteerID INT, Name TEXT, City TEXT); CREATE TABLE Programs (ProgramID INT, Name TEXT, VolunteerID INT, StartDate DATE); INSERT INTO Volunteers (VolunteerID, Name, City) VALUES (1, 'James Johnson', 'New York'), (2, 'Natalie Brown', 'Los Angeles'), (3, 'Michael Davis', 'Chicago'); INSERT INTO Programs (ProgramID, Name, VolunteerID, StartDate) VALUES (1, 'Tutoring Kids', 1, '2021-01-05'), (2, 'Cleaning Beaches', 2, '2021-03-20'), (3, 'Planting Trees', 3, '2021-02-01');

SELECT City, COUNT(DISTINCT Volunteers.VolunteerID) as 'Number of Volunteers' FROM Programs INNER JOIN Volunteers ON Programs.VolunteerID = Volunteers.VolunteerID WHERE Programs.StartDate BETWEEN '2021-01-01' AND '2021-03-31' GROUP BY City;


Question: What is the percentage of users in the entertainment industry, in the United States, who have opted out of targeted advertising?

CREATE TABLE users (id INT, country VARCHAR(255), industry VARCHAR(255), opted_out BOOLEAN);

SELECT 100.0 * SUM(CASE WHEN opted_out THEN 1 ELSE 0 END) / COUNT(*) FROM users WHERE country = 'United States' AND industry = 'entertainment';


Question: What is the name, age, and country of donors who have donated more than $5000?

CREATE TABLE Donors (DonorID int, Name varchar(50), Age int, Country varchar(50), Donations int); INSERT INTO Donors (DonorID, Name, Age, Country, Donations) VALUES (1, 'John Doe', 30, 'USA', 5000), (2, 'Jane Smith', 45, 'Canada', 7000), (3, 'Pedro Martinez', 25, 'Mexico', 6000);

SELECT d.Name, d.Age, d.Country FROM Donors d WHERE d.Donations > 5000;


Question: List the countries and their military branches that use drone technology.

CREATE TABLE DroneMilitary (Country VARCHAR(255), Branch VARCHAR(255)); INSERT INTO DroneMilitary (Country, Branch) VALUES ('USA', 'Air Force'), ('USA', 'Navy'), ('Israel', 'Air Force'), ('Turkey', 'Air Force');

SELECT Country FROM DroneMilitary WHERE Branch IN ('Air Force', 'Navy');


Question: What is the average number of views for news stories published in the "news" table for each month in 2020?

CREATE TABLE news (id INT, title VARCHAR(100), views INT, date DATE);

SELECT MONTH(date) AS month, AVG(views) AS avg_views FROM news WHERE YEAR(date) = 2020 GROUP BY month;


Question: How many social equity dispensary licenses were issued in Oakland before 2020?

CREATE TABLE licenses (id INT, type TEXT, applicant TEXT, city TEXT, issue_date DATE); INSERT INTO licenses (id, type, applicant, city, issue_date) VALUES (1, 'dispensary', 'social equity', 'Oakland', '2019-01-01'), (2, 'manufacturing', 'general', 'Oakland', '2018-01-01');

SELECT COUNT(*) FROM licenses WHERE type = 'dispensary' AND applicant = 'social equity' AND city = 'Oakland' AND issue_date < '2020-01-01';


Question: pgTAP test for Inheritance (assertion 119).

SELECT * FROM check_test(
    isnt_descendent_of( 'hide', 'h_child2', 'hide', 'h_parent', 2, 'Lookie' ),
    false,
    'isnt_descendent_of(csch, ctab, psch, ptab, 2, desc)',
    'Lookie',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Inheritance.


Question: What is the total waste generation (in kg) for each city and material type?

CREATE TABLE waste_generation_material (city VARCHAR(255), material VARCHAR(255), year INT, amount FLOAT); INSERT INTO waste_generation_material (city, material, year, amount) VALUES ('CityA', 'Plastic', 2019, 300.0), ('CityA', 'Paper', 2019, 400.0), ('CityA', 'Glass', 2019, 500.0), ('CityB', 'Plastic', 2019, 200.0), ('CityB', 'Paper', 2019, 350.0), ('CityB', 'Glass', 2019, 450.0);

SELECT city, material, SUM(amount) FROM waste_generation_material GROUP BY city, material;


Question: Generate PostgreSQL SQL for: What is the type where the name is bojan?

CREATE TABLE table_11891841_2 (type VARCHAR, name VARCHAR)

SELECT type FROM table_11891841_2 WHERE name = 'Bojan';


Question: Generate PostgreSQL SQL for: What was the Play-by-play when the color commentator was Eric Wynalda, earlier than 2005?

CREATE TABLE table_name_11 (play_by_play VARCHAR, color_commentator_s_ VARCHAR, year VARCHAR)

SELECT play_by_play FROM table_name_11 WHERE color_commentator_s_ = 'eric wynalda' AND year < 2005;


Question: How many players are there in the "EpicRacers" table, grouped by their preferred gaming platform (PC, Console, Mobile)?

CREATE TABLE EpicRacers (PlayerID INT, Name VARCHAR(50), Platform VARCHAR(10)); INSERT INTO EpicRacers (PlayerID, Name, Platform) VALUES (1, 'John', 'PC'), (2, 'Amy', 'Console'), (3, 'Mike', 'Mobile'), (4, 'Linda', 'PC'), (5, 'Sam', 'Console');

SELECT Platform, COUNT(PlayerID) FROM EpicRacers GROUP BY Platform;


Question: Generate PostgreSQL SQL for: What is the womens singles of marcus ellis gabrielle white?

CREATE TABLE table_12104319_1 (womens_singles VARCHAR, mixed_doubles VARCHAR)

SELECT womens_singles FROM table_12104319_1 WHERE mixed_doubles = 'Marcus Ellis Gabrielle White';


Question: Which industries have the most diverse founding teams in terms of gender?

CREATE TABLE company (id INT, name VARCHAR(50), industry VARCHAR(50), founder_gender VARCHAR(10)); INSERT INTO company (id, name, industry, founder_gender) VALUES (1, 'Acme Inc', 'Tech', 'Female'), (2, 'Beta Corp', 'Finance', 'Male'), (3, 'Gamma Startup', 'Tech', 'Female'), (4, 'Delta Company', 'Finance', 'Non-binary');

SELECT industry, COUNT(DISTINCT founder_gender) AS diversity_score FROM company GROUP BY industry ORDER BY diversity_score DESC;


Question: Get the number of renewable energy projects in the RenewableEnergy schema

CREATE SCHEMA RenewableEnergy; USE RenewableEnergy; CREATE TABLE RenewableEnergyProjects (id INT, project_name VARCHAR(100), type VARCHAR(50)); INSERT INTO RenewableEnergyProjects (id, project_name, type) VALUES (1, 'Hydroelectric Plant', 'Hydro'), (2, 'Wind Farm', 'Wind'), (3, 'Solar Farm', 'Solar');

SELECT COUNT(*) FROM RenewableEnergy.RenewableEnergyProjects WHERE type IN ('Hydro', 'Wind', 'Solar');


Question: What is the total number of creative AI applications developed in Africa?

CREATE TABLE AIApplications (ApplicationId INT, Name TEXT, Type TEXT, CreativityScore FLOAT, Country TEXT); INSERT INTO AIApplications (ApplicationId, Name, Type, CreativityScore, Country) VALUES (1, 'ApplicationX', 'Art Generation', 0.85, 'Nigeria'), (2, 'ApplicationY', 'Music Generation', 0.95, 'South Africa'), (3, 'ApplicationZ', 'Writing Generation', 0.75, 'Egypt');

SELECT SUM(CreativityScore) FROM AIApplications WHERE Type = 'Creative';


Question: PostgreSQL regression test 'temp': Write the SELECT query (example 163).

SELECT pg_relation_size('test_temp') / current_setting('block_size')::int8 > 200;

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

SELECT count(*) FROM (SELECT pg_relation_size('test_temp') / current_setting('block_size')::int8 > 200) AS _sub;


Question: List all the distinct rare earth elements in the market trends data.

CREATE TABLE market_trends (element VARCHAR(255), price DECIMAL(10,2), quantity INT); INSERT INTO market_trends (element, price, quantity) VALUES ('Neodymium', 92.50, 5000), ('Praseodymium', 85.20, 3000), ('Dysprosium', 120.00, 2000);

SELECT DISTINCT element FROM market_trends;


Question: What is the percentage of security incidents caused by insiders in the energy sector?

CREATE TABLE energy_sector (sector VARCHAR(255), incident_type VARCHAR(255), incidents INT); INSERT INTO energy_sector (sector, incident_type, incidents) VALUES ('Energy', 'Insider Threat', 50), ('Energy', 'Phishing', 100), ('Energy', 'Malware', 75), ('Energy', 'Ransomware', 100), ('Energy', 'DDoS', 100);

SELECT (SUM(CASE WHEN incident_type = 'Insider Threat' THEN incidents ELSE 0 END) / SUM(incidents)) * 100 FROM energy_sector WHERE sector = 'Energy';


Question: Which destinations issued travel advisories in the first half of 2020?

CREATE TABLE advisories (destination VARCHAR(50), advisory_issue_date DATE); INSERT INTO advisories (destination, advisory_issue_date) VALUES ('Brazil', '2020-01-20'), ('Argentina', '2020-03-15'), ('Colombia', '2020-06-01');

SELECT destination FROM advisories WHERE MONTH(advisory_issue_date) <= 6 AND YEAR(advisory_issue_date) = 2020;


Question: Generate PostgreSQL SQL for: What is the sum of Silver with a Bronze that is larger than 0 with a Gold smaller than 0?

CREATE TABLE table_name_26 (silver INTEGER, bronze VARCHAR, gold VARCHAR)

SELECT SUM(silver) FROM table_name_26 WHERE bronze > 0 AND gold < 0;


Question: Generate PostgreSQL SQL for: What was tyre that was made by cooper - bristol that was driven by bob gerard?

CREATE TABLE table_name_77 (tyre VARCHAR, constructor VARCHAR, driver VARCHAR)

SELECT tyre FROM table_name_77 WHERE constructor = 'cooper - bristol' AND driver = 'bob gerard';


Question: Generate PostgreSQL SQL for: In what League is the Reed School?

CREATE TABLE table_name_87 (league VARCHAR, school VARCHAR)

SELECT league FROM table_name_87 WHERE school = 'reed';


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

INSERT INTO num_exp_add VALUES (7,1,'-83028485');

Explanation: DML from PostgreSQL core regression test for Numeric.


Question: What is the average CO2 emissions per garment for the Fall 2021 collection?

CREATE TABLE emissions (collection VARCHAR(10), co2_emissions FLOAT, units INT); INSERT INTO emissions (collection, co2_emissions, units) VALUES ('Fall_2021', 12.5, 1000), ('Fall_2021', 11.7, 1500), ('Fall_2021', 13.2, 1200);

SELECT AVG(co2_emissions) FROM emissions WHERE collection = 'Fall_2021';


Question: What is the total number of marine species observed in the Arctic Ocean, and how many of these species are endemic to the Arctic?

CREATE TABLE marine_species (species_name TEXT, ocean TEXT, endemic BOOLEAN); INSERT INTO marine_species (species_name, ocean, endemic) VALUES ('Species C', 'Arctic Ocean', TRUE); INSERT INTO marine_species (species_name, ocean, endemic) VALUES ('Species D', 'Arctic Ocean', FALSE);

SELECT COUNT(*) AS total_species, SUM(endemic) AS endemic_species FROM marine_species WHERE ocean = 'Arctic Ocean';


Question: Generate PostgreSQL SQL for: Who holds third place in the tournament with a score of 2–6, 7–6(3), [10–5]?

CREATE TABLE table_name_16 (third_place VARCHAR, score VARCHAR)

SELECT third_place FROM table_name_16 WHERE score = '2–6, 7–6(3), [10–5]';


Question: Generate PostgreSQL SQL for: What's the venue for the asian games tournament?

CREATE TABLE table_name_55 (venue VARCHAR, tournament VARCHAR)

SELECT venue FROM table_name_55 WHERE tournament = 'asian games';


Question: pgTAP test for Functap (assertion 221).

SELECT * FROM check_test(
    isnt_aggregate( 'public', 'nope', ARRAY[etype()], 'whatever' ),
    false,
    'isnt_aggregate(schema, noagg, arg, desc)',
    'whatever',
    '    Function public.nope(' || etype() || ') does not exist'
);

Explanation: SQL assertion from pgTAP test suite for Functap.


Question: Write the DML statement from PostgreSQL regression test 'prepared_xacts' (example 53).

Explanation: DML from PostgreSQL core regression test for Prepared Xacts.


Question: Generate PostgreSQL SQL for: Who was Home on December 5, 2007?

CREATE TABLE table_name_11 (home VARCHAR, date VARCHAR)

SELECT home FROM table_name_11 WHERE date = 'december 5, 2007';


Question: What is the number of flu shots administered in rural California this year?

CREATE TABLE flu_shots (shot_id INT, patient_name TEXT, shot_date DATE, location TEXT); INSERT INTO flu_shots (shot_id, patient_name, shot_date, location) VALUES (1, 'Jane Doe', '2022-02-15', 'California');

SELECT COUNT(*) FROM flu_shots WHERE EXTRACT(YEAR FROM shot_date) = EXTRACT(YEAR FROM CURRENT_DATE) AND location = 'California';


Question: What is the percentage of tickets sold for each event type, for events in Los Angeles?

CREATE TABLE Events (id INT, event_name VARCHAR(100), event_type VARCHAR(50), location VARCHAR(100), start_time TIMESTAMP); CREATE TABLE Tickets (id INT, ticket_number INT, event_id INT, purchaser_name VARCHAR(100), purchase_date DATE);

SELECT event_type, 100.0 * COUNT(ticket_number) / SUM(COUNT(ticket_number)) OVER (PARTITION BY NULL) as percentage FROM Events JOIN Tickets ON Events.id = Tickets.event_id WHERE location LIKE '%Los Angeles%' GROUP BY event_type;


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

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

SELECT count(*) FROM (SELECT to_regprocedure('-')::oid) AS _sub;


Question: What is the average water requirement for crops grown in each province in India?

CREATE TABLE irrigation (id INT, farm_id INT, irrigation_amount INT); INSERT INTO irrigation (id, farm_id, irrigation_amount) VALUES (1, 1, 1000), (2, 2, 1500);

SELECT provinces.name, AVG(crops.water_requirement) FROM crops JOIN (SELECT farm_id FROM farms WHERE provinces.name = provinces.name) as subquery ON crops.id = subquery.farm_id JOIN irrigation ON crops.id = irrigation.farm_id JOIN provinces ON farms.id = provinces.id GROUP BY provinces.name;


Question: Generate PostgreSQL SQL for: What was the time of the driver with a finish position of 19?

CREATE TABLE table_name_13 (time_retired VARCHAR, fin_pos VARCHAR)

SELECT time_retired FROM table_name_13 WHERE fin_pos = '19';


Question: How many volunteers signed up in Q1 2022, by their state?

CREATE TABLE volunteers (id INT, name VARCHAR(255), signup_date DATE, state VARCHAR(255)); INSERT INTO volunteers (id, name, signup_date, state) VALUES (1, 'John Doe', '2022-01-02', 'New York'), (2, 'Jane Smith', '2022-04-15', 'California'), (3, 'Mike Johnson', '2022-03-28', 'Illinois');

SELECT state, COUNT(*) FROM volunteers WHERE signup_date >= '2022-01-01' AND signup_date < '2022-04-01' GROUP BY state;


Question: PostgreSQL Ddl: show example 17.

CREATE TABLE products ( product_no integer, name text, price numeric, CHECK (price > 0), discounted_price numeric, CHECK (discounted_price > 0), CONSTRAINT valid_discount CHECK (price > discounted_price) );

Explanation: Example from PostgreSQL documentation on Ddl.


Question: What's the average number of artworks viewed per visitor in the 'Europe' region?

CREATE TABLE Artworks (ArtworkID INT, ExhibitionID INT, VisitorID INT);

SELECT AVG(a.ArtworksViewed) FROM (SELECT v.VisitorID, COUNT(a.ArtworkID) ArtworksViewed FROM Artworks a JOIN Exhibitions e ON a.ExhibitionID = e.ExhibitionID JOIN Visitors v ON a.VisitorID = v.VisitorID JOIN Regions r ON v.Country = r.CountryName WHERE r.Region = 'Europe' GROUP BY v.VisitorID) a;


Question: Generate PostgreSQL SQL for: What district first elected a Democratic incumbent in 1998?

CREATE TABLE table_1805191_50 (district VARCHAR, party VARCHAR, first_elected VARCHAR)

SELECT district FROM table_1805191_50 WHERE party = 'Democratic' AND first_elected = 1998;


Question: List decentralized applications and their respective regulatory frameworks.

CREATE TABLE DApps (DAppId INT, DAppName VARCHAR(50), RegulatorId INT); CREATE TABLE Regulators (RegulatorId INT, RegulatorName VARCHAR(50), Region VARCHAR(50)); INSERT INTO DApps (DAppId, DAppName, RegulatorId) VALUES (1, 'App1', 1); INSERT INTO DApps (DAppId, DAppName, RegulatorId) VALUES (2, 'App2', 2); INSERT INTO DApps (DAppId, DAppName, RegulatorId) VALUES (3, 'App3', 3); INSERT INTO Regulators (RegulatorId, RegulatorName, Region) VALUES (1, 'Regulator1', 'US'); INSERT INTO Regulators (RegulatorId, RegulatorName, Region) VALUES (2, 'Regulator2', 'EU'); INSERT INTO Regulators (RegulatorId, RegulatorName, Region) VALUES (3, 'Regulator3', 'UK');

SELECT da.DAppName, r.RegulatorName FROM DApps da INNER JOIN Regulators r ON da.RegulatorId = r.RegulatorId;


Question: How many cases were opened for each attorney in the 'Southeast' district in 2021?

CREATE TABLE attorney_cases(attorney_id INT, case_id INT, district VARCHAR(20), opened_date DATE); INSERT INTO attorney_cases(attorney_id, case_id, district, opened_date) VALUES (1, 101, 'Southeast', '2021-03-01'), (2, 102, 'Northeast', '2021-08-15'), (3, 103, 'Southeast', '2021-11-29'), (1, 104, 'Southeast', '2021-05-12'), (4, 105, 'Southeast', '2021-09-22');

SELECT attorney_id, COUNT(*) FROM attorney_cases WHERE district = 'Southeast' AND YEAR(opened_date) = 2021 GROUP BY attorney_id;


Question: What is the average claim amount for policies in the 'Home' coverage type?

CREATE TABLE Policy (PolicyNumber INT, CoverageType VARCHAR(50)); CREATE TABLE Claim (ClaimNumber INT, PolicyNumber INT, ClaimAmount INT); INSERT INTO Policy (PolicyNumber, CoverageType) VALUES (1, 'Home'); INSERT INTO Policy (PolicyNumber, CoverageType) VALUES (2, 'Auto'); INSERT INTO Claim (ClaimNumber, PolicyNumber, ClaimAmount) VALUES (1, 1, 5000); INSERT INTO Claim (ClaimNumber, PolicyNumber, ClaimAmount) VALUES (2, 1, 7000); INSERT INTO Claim (ClaimNumber, PolicyNumber, ClaimAmount) VALUES (3, 2, 3000);

SELECT AVG(ClaimAmount) FROM Claim JOIN Policy ON Claim.PolicyNumber = Policy.PolicyNumber WHERE Policy.CoverageType = 'Home';


Question: Find the number of units of women's garments produced using recycled materials.

CREATE TABLE garment_units_recycled_materials (id INT, garment_type VARCHAR(50), units INT, recycled_material BOOLEAN); INSERT INTO garment_units_recycled_materials (id, garment_type, units, recycled_material) VALUES (1, 'Dress', 300, true); INSERT INTO garment_units_recycled_materials (id, garment_type, units, recycled_material) VALUES (2, 'Skirt', 200, true); INSERT INTO garment_units_recycled_materials (id, garment_type, units, recycled_material) VALUES (3, 'Shirt', 400, false);

SELECT SUM(units) FROM garment_units_recycled_materials WHERE garment_type LIKE '%Women%' AND recycled_material = true;


Question: Generate PostgreSQL SQL for: What is the title of the episode with the production code 2-19?

CREATE TABLE table_234886_3 (title VARCHAR, prod_code VARCHAR)

SELECT title FROM table_234886_3 WHERE prod_code = '2-19';


Question: What is the average property price in the "GreenCommunity" and "SolarVillage" neighborhoods, grouped by property type?

CREATE TABLE Property (id INT, neighborhood VARCHAR(20), price FLOAT, property_type VARCHAR(20)); INSERT INTO Property (id, neighborhood, price, property_type) VALUES (1, 'GreenCommunity', 500000, 'Apartment'), (2, 'SolarVillage', 700000, 'House');

SELECT Property.property_type, AVG(Property.price) FROM Property WHERE Property.neighborhood IN ('GreenCommunity', 'SolarVillage') GROUP BY Property.property_type;


Question: Generate PostgreSQL SQL for: What was David Backes' Offer Team?

CREATE TABLE table_name_59 (offer_team VARCHAR, player VARCHAR)

SELECT offer_team FROM table_name_59 WHERE player = 'david backes';


Question: Generate PostgreSQL SQL for: Which Net profit/loss (SEK) has a Basic eps (SEK) of -6.58, and Employees (Average/Year) larger than 31,035?

CREATE TABLE table_name_87 (net_profit_loss__sek_ INTEGER, basic_eps__sek_ VARCHAR, employees__average_year_ VARCHAR)

SELECT SUM(net_profit_loss__sek_) FROM table_name_87 WHERE basic_eps__sek_ = -6.58 AND employees__average_year_ > 31 OFFSET 035;


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

select jsonb_path_query('123', '$.bigint() * 2');

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

SELECT count(*) FROM (select jsonb_path_query('123', '$.bigint() * 2')) AS _sub;


Question: What is the total revenue for each music genre in Q1 2022?

SELECT Genre, SUM(Revenue) as Total_Revenue FROM MusicStreaming WHERE Date BETWEEN '2022-01-01' AND '2022-03-31' GROUP BY Genre;


Question: Generate PostgreSQL SQL for: Name the highest Long that has an Avg/G smaller than 8.4, and an GP-GS of 4–0?

CREATE TABLE table_name_88 (long INTEGER, avg_g VARCHAR, gp_gs VARCHAR)

SELECT MAX(long) FROM table_name_88 WHERE avg_g < 8.4 AND gp_gs = '4–0';


Question: What are the research grant titles that do not have a corresponding publication?

CREATE TABLE grant (id INT, title VARCHAR(100)); CREATE TABLE publication (id INT, title VARCHAR(100), grant_id INT);

SELECT g.title FROM grant g LEFT JOIN publication p ON g.title = p.title WHERE p.id IS NULL;


Question: What is the earliest year in which a country launched a satellite in the SpaceRadar table?

CREATE TABLE SpaceRadar (id INT, country VARCHAR(50), year INT, satellites INT); INSERT INTO SpaceRadar (id, country, year, satellites) VALUES (1, 'USA', 2000, 10), (2, 'China', 2005, 8), (3, 'Russia', 1995, 12);

SELECT country, MIN(year) AS earliest_year FROM SpaceRadar GROUP BY country;


Question: Write the DML statement from PostgreSQL regression test 'triggers' (example 522).

insert into merge_source_table
  values (1, 'initial1'), (2, 'initial2'),
		 (3, 'initial3'), (4, 'initial4');

Explanation: DML from PostgreSQL core regression test for Triggers.


Question: What is the percentage of financially capable individuals in the rural areas of the country?

CREATE TABLE financial_capability_rural (location TEXT, capable BOOLEAN); INSERT INTO financial_capability_rural (location, capable) VALUES ('Village A', TRUE), ('Village B', FALSE), ('Village C', TRUE), ('Hamlet D', FALSE);

SELECT (COUNT(*) FILTER (WHERE capable = TRUE)) * 100.0 / COUNT(*) FROM financial_capability_rural WHERE location LIKE '%rural%';


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

-- Should fail. duplicate operator number / function number in ALTER OPERATOR FAMILY ... ADD FUNCTION
CREATE OPERATOR FAMILY alt_opf17 USING btree;

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


Question: Insert a new record into the 'equipment' table for a centrifuge with an ID of 101

CREATE TABLE equipment (equipment_id INT PRIMARY KEY, equipment_name VARCHAR(50), equipment_type VARCHAR(50));

INSERT INTO equipment (equipment_id, equipment_name, equipment_type) VALUES (101, 'Centrifuge', 'Equipment');


Question: How many security incidents were recorded in each city in the last 6 months?

CREATE TABLE security_incidents (id INT, city VARCHAR(255), timestamp TIMESTAMP);

SELECT city, COUNT(*) FROM security_incidents WHERE timestamp >= NOW() - INTERVAL 6 MONTH GROUP BY city;


Question: How many public libraries exist in urban and rural areas, respectively?

CREATE TABLE Libraries (Location TEXT, Count INT); INSERT INTO Libraries (Location, Count) VALUES ('Urban', 150), ('Rural', 50);


Question: Calculate the moving average of water consumption by mining operations in the past 6 months.

SELECT MineID, AVG(Consumption) OVER (PARTITION BY MineID ORDER BY Date ROWS BETWEEN 5 PRECEDING AND CURRENT ROW) as MovingAvg FROM WaterConsumption;


Question: Generate PostgreSQL SQL for: When was the cataglogue EPA 4054 released with a 1/12/57 recorded?

CREATE TABLE table_name_31 (release_date VARCHAR, catalogue VARCHAR, recorded VARCHAR)

SELECT release_date FROM table_name_31 WHERE catalogue = 'epa 4054' AND recorded = '1/12/57';


Question: Generate PostgreSQL SQL for: What is the year of the disc with a catalogue number mash02?

CREATE TABLE table_name_22 (year VARCHAR, catalogue_number VARCHAR)

SELECT year FROM table_name_22 WHERE catalogue_number = 'mash02';


Question: Generate PostgreSQL SQL for: What is the Trofeo Fast Team when stage is 19?

CREATE TABLE table_name_34 (trofeo_fast_team VARCHAR, stage VARCHAR)

SELECT trofeo_fast_team FROM table_name_34 WHERE stage = '19';


Question: What is the total value of defense contracts signed by company 'MNO Corp' in Q1 2020?

CREATE TABLE defense_contracts (contract_id INT, company VARCHAR(255), value FLOAT, date DATE); INSERT INTO defense_contracts (contract_id, company, value, date) VALUES (3, 'MNO Corp', 300000, '2020-01-01'); INSERT INTO defense_contracts (contract_id, company, value, date) VALUES (4, 'DEF Inc', 450000, '2020-01-05');

SELECT SUM(value) FROM defense_contracts WHERE company = 'MNO Corp' AND date BETWEEN '2020-01-01' AND '2020-03-31';


Question: Generate PostgreSQL SQL for: What is the name of the department that has the largest number of students enrolled?

CREATE TABLE enroll (class_code VARCHAR); CREATE TABLE CLASS (class_code VARCHAR, crs_code VARCHAR); CREATE TABLE course (dept_code VARCHAR, crs_code VARCHAR); CREATE TABLE department (dept_name VARCHAR, dept_code VARCHAR)

SELECT T4.dept_name FROM CLASS AS T1 JOIN enroll AS T2 ON T1.class_code = T2.class_code JOIN course AS T3 ON T1.crs_code = T3.crs_code JOIN department AS T4 ON T3.dept_code = T4.dept_code GROUP BY T3.dept_code ORDER BY COUNT(*) DESC LIMIT 1;


Question: How many rural health clinics are there in Australia and New Zealand that have a patient satisfaction score greater than 85?

CREATE TABLE clinics (country VARCHAR(20), clinic_name VARCHAR(50), patient_satisfaction_score INT); INSERT INTO clinics (country, clinic_name, patient_satisfaction_score) VALUES ('Australia', 'Clinic E', 90), ('Australia', 'Clinic F', 80), ('New Zealand', 'Clinic G', 88), ('New Zealand', 'Clinic H', 92);

SELECT country, COUNT(*) FROM clinics WHERE patient_satisfaction_score > 85 GROUP BY country;


Question: Delete consumer awareness data for a specific region.

CREATE TABLE consumer_awareness (region_id INT PRIMARY KEY, awareness_score INT, year INT);

DELETE FROM consumer_awareness WHERE region_id = 456 AND year = 2021;


Question: What is the difference in popularity between the most and least popular songs per platform?

CREATE TABLE songs (song_id INT, title TEXT, popularity INT, platform TEXT);

SELECT platform, MAX(popularity) - MIN(popularity) FROM songs GROUP BY platform;


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

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

SELECT count(*) FROM (SELECT pg_input_is_valid('asdf', 'int2')) AS _sub;


Question: What is the total number of failed satellite launches by Israeli and Indian space programs?

CREATE TABLE Satellite_Launches (launch_date DATE, country VARCHAR(255), success BOOLEAN); INSERT INTO Satellite_Launches (launch_date, country, success) VALUES ('2020-01-01', 'Israel', FALSE), ('2020-02-01', 'India', TRUE), ('2020-03-01', 'Israel', FALSE), ('2020-04-01', 'India', TRUE), ('2020-05-01', 'Israel', FALSE);

SELECT SUM(success) AS total_failed_launches FROM (SELECT success FROM Satellite_Launches WHERE country IN ('Israel', 'India')) AS subquery WHERE success = FALSE;


Question: How many pallets are currently stored in each warehouse, broken down by warehouse type?

CREATE TABLE warehouses (id INT, type VARCHAR(50), pallets INT); INSERT INTO warehouses (id, type, pallets) VALUES (1, 'Cool', 200), (2, 'Dry', 300), (3, 'Frozen', 150);

SELECT type, SUM(pallets) as total_pallets FROM warehouses GROUP BY type;


Question: Show the total CO2 emissions for each store in the state of California.

CREATE TABLE stores (store_id INT, store_name VARCHAR(255), store_state VARCHAR(255), co2_emissions INT);

SELECT store_state, SUM(co2_emissions) as total_emissions FROM stores WHERE store_state = 'California' GROUP BY store_state;


Question: What is the average expenditure per day for tourists visiting New Zealand from Europe?

CREATE TABLE expenditures (destination_country VARCHAR(50), visitor_country VARCHAR(50), avg_daily_expenditure FLOAT); INSERT INTO expenditures (destination_country, visitor_country, avg_daily_expenditure) VALUES ('New Zealand', 'Europe', 150.0);

SELECT avg_daily_expenditure FROM expenditures WHERE destination_country = 'New Zealand' AND visitor_country = 'Europe';


Question: Find ingredients sourced from a specific country

Ingredients (ingredient_id, name, source, last_updated)

SELECT * FROM Ingredients WHERE source LIKE '%country%';


Question: Generate PostgreSQL SQL for: What is the team mascot for the soccer team in Charlottetown?

CREATE TABLE table_27369069_1 (varsity_name VARCHAR, city VARCHAR)

SELECT varsity_name FROM table_27369069_1 WHERE city = 'Charlottetown';


Question: Generate PostgreSQL SQL for: Faith of –, and a Name of greenway has what type?

CREATE TABLE table_name_79 (type VARCHAR, faith VARCHAR, name VARCHAR)

SELECT type FROM table_name_79 WHERE faith = '–' AND name = 'greenway';


Question: What is the total number of investments made by each investor?

CREATE TABLE Investors (InvestorID INT, InvestorName VARCHAR(50)); CREATE TABLE Investments (InvestmentID INT, InvestorID INT, CompanyID INT, InvestmentAmount DECIMAL(10, 2));

SELECT I.InvestorName, COUNT(I.InvestmentID) AS TotalInvestments FROM Investments I JOIN Investors ON I.InvestorID = Investors.InvestorID GROUP BY I.InvestorName;


Question: What is the total number of streams for Latin songs in Brazil in 2020?

CREATE TABLE Streaming (country VARCHAR(50), year INT, genre VARCHAR(50), streams INT); INSERT INTO Streaming (country, year, genre, streams) VALUES ('Brazil', 2020, 'Latin', 900000); INSERT INTO Streaming (country, year, genre, streams) VALUES ('Brazil', 2020, 'Latin', 950000);

SELECT SUM(streams) FROM Streaming WHERE country = 'Brazil' AND year = 2020 AND genre = 'Latin';


Question: Write the DML statement from PostgreSQL regression test 'float8' (example 13).

INSERT INTO FLOAT8_TBL(f1) VALUES ('     ');

Explanation: DML from PostgreSQL core regression test for Float8.


Question: Show a query using PostgreSQL contrib extension 'dblink' (example 6).

INSERT INTO foo VALUES (0,'a','{"a0","b0","c0"}');

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


Question: What is the number of animals adopted by each community in 2018?

CREATE TABLE CommunityAdoptions(Year INT, Community VARCHAR(20), Animals INT); INSERT INTO CommunityAdoptions VALUES (2017, 'CommunityA', 35), (2018, 'CommunityA', 40), (2017, 'CommunityB', 28), (2018, 'CommunityB', 32);

SELECT Community, SUM(Animals) FROM CommunityAdoptions WHERE Year = 2018 GROUP BY Community;


Question: Generate PostgreSQL SQL for: What is the score for april 29?

CREATE TABLE table_11964263_13 (score VARCHAR, date VARCHAR)

SELECT score FROM table_11964263_13 WHERE date = 'April 29';


Question: Generate PostgreSQL SQL for: Which event in the 2008 Beijing Games had a bronze medal?

CREATE TABLE table_name_34 (event VARCHAR, games VARCHAR, medal VARCHAR)

SELECT event FROM table_name_34 WHERE games = '2008 beijing' AND medal = 'bronze';


Question: Generate PostgreSQL SQL for: Who was ashley sampi's opponent?

CREATE TABLE table_name_71 (opponent VARCHAR, player VARCHAR)

SELECT opponent FROM table_name_71 WHERE player = 'ashley sampi';


Question: Generate PostgreSQL SQL for: Show the date valid from and the date valid to for the card with card number '4560596484842'.

CREATE TABLE Customers_cards (date_valid_from VARCHAR, date_valid_to VARCHAR, card_number VARCHAR)

SELECT date_valid_from, date_valid_to FROM Customers_cards WHERE card_number = '4560596484842';


Question: Generate PostgreSQL SQL for: How many Rebounds did Novica Veličković get in less than 22 Games?

CREATE TABLE table_name_6 (rebounds INTEGER, name VARCHAR, games VARCHAR)

SELECT SUM(rebounds) FROM table_name_6 WHERE name = 'novica veličković' AND games < 22;


Question: Generate PostgreSQL SQL for: On what weekday was the match that had Perth Glory as the away team?

CREATE TABLE table_name_86 (weekday VARCHAR, away VARCHAR)

SELECT weekday FROM table_name_86 WHERE away = 'perth glory';


Question: What is the minimum stay required for volunteer tourism in Nepal?

CREATE TABLE volunteer_programs (id INT, location VARCHAR(20), min_stay INT); INSERT INTO volunteer_programs (id, location, min_stay) VALUES (1, 'Nepal', 14), (2, 'Nepal', 21), (3, 'Nepal', 10);

SELECT MIN(min_stay) FROM volunteer_programs WHERE location = 'Nepal';


Question: What is the total number of funding records for companies with female founders in the Healthcare industry?

CREATE TABLE Companies (id INT, name VARCHAR(50), industry VARCHAR(50), country VARCHAR(50), founding_year INT, founder_gender VARCHAR(10)); CREATE TABLE Funding (id INT, company_name VARCHAR(50), funding_amount INT); INSERT INTO Companies (id, name, industry, country, founding_year, founder_gender) VALUES (1, 'HealthHer', 'Healthcare', 'USA', 2016, 'Female'); INSERT INTO Funding (id, company_name, funding_amount) VALUES (1, 'HealthHer', 2000000);

SELECT COUNT(*) as funding_records_count FROM Funding INNER JOIN Companies ON Funding.company_name = Companies.name WHERE Companies.industry = 'Healthcare' AND Companies.founder_gender = 'Female';


Question: Write the DML statement from PostgreSQL regression test 'date' (example 5).

INSERT INTO DATE_TBL VALUES ('1996-02-29');

Explanation: DML from PostgreSQL core regression test for Date.


Question: What is the percentage of international tourists visiting museums in South America compared to North America?

CREATE TABLE south_america_tourists (id INT, country TEXT, museum_visits INT); INSERT INTO south_america_tourists VALUES (1, 'Brazil', 2000), (2, 'Argentina', 3000); CREATE TABLE north_america_tourists (id INT, country TEXT, museum_visits INT); INSERT INTO north_america_tourists VALUES (1, 'USA', 5000), (2, 'Canada', 4000);

SELECT 100.0 * SUM(museum_visits) / (SELECT SUM(museum_visits) FROM north_america_tourists) FROM south_america_tourists;


Question: What is the number of students who have taken more than one lifelong learning course?

CREATE TABLE students (student_id INT, student_name VARCHAR(255)); INSERT INTO students VALUES (1, 'Student A'), (2, 'Student B'), (3, 'Student C'), (4, 'Student D'); CREATE TABLE student_courses (student_id INT, course_id INT); INSERT INTO student_courses VALUES (1, 1), (1, 2), (2, 1), (3, 2), (3, 3), (4, 1), (4, 2), (4, 3); CREATE TABLE lifelong_learning_courses (course_id INT, course_name VARCHAR(255), course_type VARCHAR(255)); INSERT INTO lifelong_learning_courses VALUES (1, 'Lifelong Learning Course 1', 'Lifelong Learning'), (2, 'Lifelong Learning Course 2', 'Lifelong Learning'), (3, 'Professional Development Course 1', 'Professional Development');

SELECT COUNT(sc.student_id) as students_with_more_than_one_lifelong_learning_course FROM student_courses sc JOIN lifelong_learning_courses llc ON sc.course_id = llc.course_id GROUP BY llc.course_type HAVING COUNT(sc.student_id) > 1;


Question: Show a query using PostgreSQL contrib extension 'amcheck' (example 39).

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


Question: Generate PostgreSQL SQL for: what's the saturday saturnus ( saturn) with wednesday mercurius (mercury) being mercuridi

CREATE TABLE table_1277350_1 (saturday_saturnus___saturn_ VARCHAR, wednesday_mercurius__mercury_ VARCHAR)

SELECT saturday_saturnus___saturn_ FROM table_1277350_1 WHERE wednesday_mercurius__mercury_ = 'Mercuridi';


Question: What is the total production for offshore wells, partitioned by the well's region and status?

CREATE TABLE offshore_wells (well_id INT, well_name VARCHAR(255), location VARCHAR(255), production FLOAT, well_status VARCHAR(50), region VARCHAR(50)); INSERT INTO offshore_wells (well_id, well_name, location, production, well_status, region) VALUES (11, 'Well E', 'North Sea', 800.0, 'Active', 'Europe'), (12, 'Well F', 'North Sea', 700.0, 'Inactive', 'Europe');

SELECT region, well_status, SUM(production) OVER (PARTITION BY region, well_status) as total_production FROM offshore_wells WHERE location = 'offshore';


Question: What is the total area of cropland (in hectares) for each crop type?

CREATE TABLE cropland_types (type VARCHAR(50), area INT); INSERT INTO cropland_types (type, area) VALUES ('Maize', 150000), ('Rice', 200000), ('Wheat', 180000);


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

SELECT count(*) > 0 FROM pg_buffercache_os_pages;

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


Question: Find the total number of marine research projects funded by the European Union and the United States in the last 3 years.

CREATE TABLE research_projects (id INT, country VARCHAR(30), funder VARCHAR(30), project_name VARCHAR(50), date DATE); INSERT INTO research_projects (id, country, funder, project_name, date) VALUES (1, 'France', 'European Union', 'Marine Life Research', '2021-04-15'); INSERT INTO research_projects (id, country, funder, project_name, date) VALUES (2, 'Spain', 'United States', 'Ocean Mapping', '2020-07-22');

SELECT SUM(total) FROM (SELECT COUNT(*) AS total FROM research_projects WHERE country = 'European Union' AND date >= DATE_SUB(CURRENT_DATE, INTERVAL 3 YEAR) UNION ALL SELECT COUNT(*) AS total FROM research_projects WHERE country = 'United States' AND date >= DATE_SUB(CURRENT_DATE, INTERVAL 3 YEAR)) AS combined_funders;


Question: What is the difference in budget allocation between infrastructure and social services in the state of California?

CREATE TABLE states (state VARCHAR(255), service VARCHAR(255), budget INT); INSERT INTO states (state, service, budget) VALUES ('California', 'infrastructure', 1200000), ('California', 'social services', 800000);

SELECT infrastructure_budget - social_services_budget AS budget_difference FROM (SELECT SUM(budget) AS infrastructure_budget FROM states WHERE state = 'California' AND service = 'infrastructure') AS infrastructure_budget, (SELECT SUM(budget) AS social_services_budget FROM states WHERE state = 'California' AND service = 'social services') AS social_services_budget;


Question: Generate PostgreSQL SQL for: Which province has the contestant elixandra tobias carasco?

CREATE TABLE table_name_81 (province VARCHAR, _community VARCHAR, contestant VARCHAR)

SELECT province, _community FROM table_name_81 WHERE contestant = 'elixandra tobias carasco';


Question: How many wells in the 'WELL_COUNT' view are in the 'NORTH_SEA' region?

CREATE VIEW WELL_COUNT AS SELECT COUNT(*), REGION FROM OIL_WELLS GROUP BY REGION;

SELECT COUNT(*) FROM WELL_COUNT WHERE REGION = 'NORTH_SEA';


Question: Generate PostgreSQL SQL for: What is the to par of the player with a t4 place and a score of 75-69-74-72=290?

CREATE TABLE table_name_46 (to_par VARCHAR, place VARCHAR, score VARCHAR)

SELECT to_par FROM table_name_46 WHERE place = 't4' AND score = 75 - 69 - 74 - 72 = 290;


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

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


Question: Count the number of properties with inclusive housing policies in each city.

CREATE TABLE inclusive_housing (id INT, property_id INT, city VARCHAR(20)); INSERT INTO inclusive_housing (id, property_id, city) VALUES (1, 1001, 'New York'), (2, 1002, 'Los Angeles'), (3, 1003, 'New York');

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


Question: Add a new record to the "warehouses" table with the following data: warehouse_name = "Mumbai Warehouse", country = "India", capacity = 5000, and current_inventory = 3000

CREATE TABLE warehouses (id INT, warehouse_name VARCHAR(50), country VARCHAR(50), capacity INT, current_inventory INT);

INSERT INTO warehouses (id, warehouse_name, country, capacity, current_inventory) VALUES (1, 'Mumbai Warehouse', 'India', 5000, 3000);


Question: Calculate the total amount of resources depleted in the mining industry, broken down by resource type.

CREATE TABLE resource_depletion (id INT, mining_operation_id INT, resource_type VARCHAR(50), amount_depleted FLOAT);

SELECT resource_type, SUM(amount_depleted) FROM resource_depletion GROUP BY resource_type;


Question: Which community programs have the most participants in Suburb I?

CREATE TABLE CommunityPrograms (id INT, program_name VARCHAR(50), location VARCHAR(50), participants INT); INSERT INTO CommunityPrograms (id, program_name, location, participants) VALUES (1, 'Youth Mentoring', 'Suburb I', 150);

SELECT program_name, MAX(participants) FROM CommunityPrograms WHERE location = 'Suburb I';


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

INSERT INTO num_exp_div VALUES (1,7,'0');


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

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


Question: Generate PostgreSQL SQL for: What was the final score agains Dynamo Kyiv, when the group position was 1st?

CREATE TABLE table_name_39 (result_f___a VARCHAR, group_position VARCHAR, opponents VARCHAR)

SELECT result_f___a FROM table_name_39 WHERE group_position = '1st' AND opponents = 'dynamo kyiv';


Question: Write the DML statement from PostgreSQL regression test 'btree_index' (example 78).

insert into btree_bpchar values ('foo'), ('fool'), ('bar'), ('quux');

Explanation: DML from PostgreSQL core regression test for Btree Index.


Question: What is the average amount of research grants received by faculty members in the Education department in the year 2018?

CREATE TABLE Faculty (FacultyID INT, Name VARCHAR(50), Department VARCHAR(50), Gender VARCHAR(10), GrantAmt FLOAT, GrantYear INT);

SELECT AVG(GrantAmt) FROM Faculty WHERE Department = 'Education' AND GrantYear = 2018;


Question: Generate PostgreSQL SQL for: The firs park stadium had the lowest average attendence of what?

CREATE TABLE table_11206916_1 (average INTEGER, stadium VARCHAR)

SELECT MIN(average) FROM table_11206916_1 WHERE stadium = 'Firs Park';


Question: What are the total waste generation quantities for each waste type, including recycling rates, for each region in 2019 and 2020?

CREATE TABLE WasteGeneration (Region VARCHAR(50), WasteType VARCHAR(50), Quantity INT, Year INT); CREATE TABLE RecyclingRates (WasteType VARCHAR(50), RecyclingRate DECIMAL(5,2)); INSERT INTO WasteGeneration (Region, WasteType, Quantity, Year) VALUES ('RegionA', 'Plastic', 1200, 2019), ('RegionA', 'Glass', 1500, 2019), ('RegionB', 'Plastic', 1800, 2019), ('RegionB', 'Glass', 2000, 2019), ('RegionA', 'Plastic', 1300, 2020), ('RegionA', 'Glass', 1400, 2020), ('RegionB', 'Plastic', 1500, 2020), ('RegionB', 'Glass', 1800, 2020); INSERT INTO RecyclingRates (WasteType, RecyclingRate) VALUES ('Plastic', 0.2), ('Glass', 0.3);

SELECT WasteGeneration.Region, WasteGeneration.WasteType, SUM(WasteGeneration.Quantity) AS TotalWasteQuantity, RecyclingRates.RecyclingRate FROM WasteGeneration INNER JOIN RecyclingRates ON WasteGeneration.WasteType = RecyclingRates.WasteType WHERE WasteGeneration.Year BETWEEN 2019 AND 2020 GROUP BY WasteGeneration.Region, WasteGeneration.WasteType, RecyclingRates.RecyclingRate;


Question: Generate PostgreSQL SQL for: What is the sum of rounds that has a pick of 9 and is named jim pyburn?

CREATE TABLE table_name_62 (round INTEGER, pick VARCHAR, name VARCHAR)

SELECT SUM(round) FROM table_name_62 WHERE pick = 9 AND name = 'jim pyburn';


Question: What is the total word count of articles written by John Doe?

CREATE TABLE Articles (id INT, title VARCHAR(255), word_count INT, author VARCHAR(255)); INSERT INTO Articles (id, title, word_count, author) VALUES (1, 'Article 1', 500, 'John Doe'), (2, 'Article 2', 600, 'Jane Smith'), (3, 'Article 3', 700, 'John Doe'), (4, 'Article 4', 800, 'Jane Smith'), (5, 'Article 5', 900, 'John Doe'), (6, 'Article 6', 1000, 'John Doe'), (7, 'Article 7', 1100, 'Jane Smith'), (8, 'Article 8', 1200, 'John Doe'), (9, 'Article 9', 1300, 'Jane Smith'), (10, 'Article 10', 1400, 'John Doe'), (11, 'Article 11', 1500, 'Jane Smith'), (12, 'Article 12', 1600, 'John Doe');

SELECT SUM(word_count) FROM Articles WHERE author = 'John Doe';


Question: What is the average height of female basketball players in the players table?

CREATE TABLE players (player_id INT, name VARCHAR(50), position VARCHAR(50), height FLOAT, weight INT, team_id INT, league VARCHAR(50)); INSERT INTO players (player_id, name, position, height, weight, team_id, league) VALUES (1, 'Alice', 'Guard', 1.75, 70, 101, 'NBA');

SELECT AVG(height) FROM players WHERE position = 'Guard' AND league = 'NBA' AND gender = 'Female';


Question: Generate PostgreSQL SQL for: What was Matthew Warchus' Award?

CREATE TABLE table_name_29 (award VARCHAR, nominee VARCHAR)

SELECT award FROM table_name_29 WHERE nominee = 'matthew warchus';


Question: Generate PostgreSQL SQL for: What is the software with version 1.2.2.0?

CREATE TABLE table_15038373_1 (software VARCHAR, version VARCHAR)

SELECT software FROM table_15038373_1 WHERE version = '1.2.2.0';


Question: Generate PostgreSQL SQL for: What college did the defensive back attend?

CREATE TABLE table_14650162_1 (college VARCHAR, position VARCHAR)

SELECT college FROM table_14650162_1 WHERE position = 'Defensive Back';


Question: How many traditional artists are engaged in each cultural preservation program?

CREATE TABLE traditional_artists (id INT, name VARCHAR(50), program VARCHAR(50), location VARCHAR(50)); INSERT INTO traditional_artists (id, name, program, location) VALUES (1, 'John Doe', 'Weaving', 'Peru'), (2, 'Jane Smith', 'Pottery', 'Bolivia');

SELECT program, COUNT(*) FROM traditional_artists GROUP BY program;


Question: Generate PostgreSQL SQL for: What was the result after 1994 for team MB2 and 31 starts?

CREATE TABLE table_name_64 (finish VARCHAR, start VARCHAR, year VARCHAR, team VARCHAR)

SELECT finish FROM table_name_64 WHERE year > 1994 AND team = 'mb2' AND start = '31';


Question: Delete all records in the 'oil_spills' table where 'spill_year' is before 1990

CREATE TABLE oil_spills (spill_id INT PRIMARY KEY, spill_name VARCHAR(50), spill_year INT, spilled_volume FLOAT);

DELETE FROM oil_spills WHERE spill_year < 1990;


Question: PostgreSQL regression test 'enum': Write the SELECT query (example 140).

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

SELECT count(*) FROM (SELECT 'bad'::bogon) AS _sub;


Question: Generate PostgreSQL SQL for: What is the Latin for "you sang"?

CREATE TABLE table_26614365_1 (latin VARCHAR, english VARCHAR)

SELECT latin FROM table_26614365_1 WHERE english = 'you sang';


Question: Which cruelty-free makeup brands have the highest average rating?

CREATE TABLE cruelty_free_makeup (brand VARCHAR(255), product VARCHAR(255), rating DECIMAL(2,1), cruelty_free BOOLEAN); INSERT INTO cruelty_free_makeup (brand, product, rating, cruelty_free) VALUES ('Pacifica', 'Foundation', 4.3, true), ('NYX', 'Mascara', 4.5, true), ('e.l.f.', 'Eyeshadow', 4.2, true), ('Milani', 'Lipstick', 4.4, true);

SELECT brand, AVG(rating) as avg_rating FROM cruelty_free_makeup WHERE cruelty_free = true GROUP BY brand ORDER BY avg_rating DESC;


Question: List the broadband subscribers with compliance issues and the corresponding compliance issue description, along with the subscribers' geographic areas.

CREATE TABLE geographic_area (geographic_area VARCHAR(20)); INSERT INTO geographic_area (geographic_area) VALUES ('urban'), ('rural'); CREATE TABLE broadband_subscribers (subscriber_id INT, name VARCHAR(50), geographic_area VARCHAR(20), has_compliance_issue INT); CREATE TABLE compliance_issues (issue_id INT, description VARCHAR(100)); INSERT INTO broadband_subscribers (subscriber_id, name, geographic_area, has_compliance_issue) VALUES (1, 'Jane Doe', 'urban', 1); INSERT INTO compliance_issues (issue_id, description) VALUES (1, 'Non-payment of annual fee');

SELECT broadband_subscribers.name, geographic_area.geographic_area, compliance_issues.description FROM broadband_subscribers JOIN geographic_area ON broadband_subscribers.geographic_area = geographic_area.geographic_area JOIN compliance_issues ON broadband_subscribers.has_compliance_issue = compliance_issues.issue_id;


Question: What is the most common type of emergency incident in the Central district?

CREATE TABLE emergency_incidents (id INT, district VARCHAR(20), type VARCHAR(20), date DATE); INSERT INTO emergency_incidents (id, district, type, date) VALUES (1, 'Downtown', 'Fire', '2022-01-01'); INSERT INTO emergency_incidents (id, district, type, date) VALUES (2, 'Uptown', 'Medical', '2022-01-01'); INSERT INTO emergency_incidents (id, district, type, date) VALUES (3, 'Central', 'Fire', '2022-01-01'); INSERT INTO emergency_incidents (id, district, type, date) VALUES (4, 'Central', 'Traffic', '2022-01-02');

SELECT type, COUNT(*) AS count FROM emergency_incidents WHERE district = 'Central' GROUP BY type ORDER BY count DESC LIMIT 1;


Question: Generate PostgreSQL SQL for: Who is the opponent of the match with a win result and a time of 3:02?

CREATE TABLE table_name_13 (opponent VARCHAR, res VARCHAR, time VARCHAR)

SELECT opponent FROM table_name_13 WHERE res = 'win' AND time = '3:02';


Question: What is the minimum number of ethical AI courses offered in South America in 2020?

CREATE TABLE ethical_ai_courses_south_america (country VARCHAR(20), year INT, courses INT); INSERT INTO ethical_ai_courses_south_america (country, year, courses) VALUES ('Brazil', 2020, 10), ('Argentina', 2020, 15), ('Colombia', 2020, 12);

SELECT MIN(courses) FROM ethical_ai_courses_south_america WHERE country = 'South America' AND year = 2020;


Question: What is the distribution of ticket prices for each team, split into price ranges (low, medium, high)?

CREATE TABLE tickets (ticket_id INT, team_id INT, ticket_price DECIMAL(5,2), price_range ENUM('low', 'medium', 'high')); INSERT INTO tickets (ticket_id, team_id, ticket_price, price_range) VALUES (1, 1, 50, 'low'); INSERT INTO tickets (ticket_id, team_id, ticket_price, price_range) VALUES (2, 2, 100, 'medium');

SELECT teams.team_name, price_range, COUNT(*) as ticket_count FROM tickets JOIN teams ON tickets.team_id = teams.team_id GROUP BY teams.team_name, price_range;


Question: Generate PostgreSQL SQL for: What is the 123 south broad street address name before 1973?

CREATE TABLE table_name_33 (name VARCHAR, year VARCHAR, address VARCHAR)

SELECT name FROM table_name_33 WHERE year < 1973 AND address = '123 south broad street';


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

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


Question: Generate PostgreSQL SQL for: What is the Game # that scored 87-92?

CREATE TABLE table_name_46 (game INTEGER, score VARCHAR)

SELECT SUM(game) FROM table_name_46 WHERE score = '87-92';


Question: What is the average carbon offset of Green building projects in the Middle East?

CREATE TABLE green_building_projects (project_id INT, project_name VARCHAR(50), region VARCHAR(20), carbon_offsets INT); INSERT INTO green_building_projects (project_id, project_name, region, carbon_offsets) VALUES (1, 'Green Office', 'Middle East', 600), (2, 'Sustainable Apartments', 'Middle East', 800), (3, 'Eco-friendly Mall', 'Africa', 1000);

SELECT AVG(carbon_offsets) FROM green_building_projects WHERE region = 'Middle East';


Question: What is the total number of cybersecurity incidents reported by the military in 2020?

CREATE TABLE CybersecurityIncidents (id INT, branch VARCHAR(255), year INT, incidents INT); INSERT INTO CybersecurityIncidents (id, branch, year, incidents) VALUES (1, 'Air Force', 2019, 20), (2, 'Navy', 2018, 30), (3, 'Army', 2020, 40), (4, 'Air Force', 2020, 50), (5, 'Navy', 2020, 60), (6, 'Army', 2019, 70);

SELECT SUM(incidents) FROM CybersecurityIncidents WHERE year = 2020;


Question: Generate PostgreSQL SQL for: Who was born on 10 May 1788 that ceased to be queen?

CREATE TABLE table_name_3 (ceased_to_be_queen VARCHAR, birth VARCHAR)

SELECT ceased_to_be_queen FROM table_name_3 WHERE birth = '10 may 1788';


Question: What is the average size of artworks displayed in the 'ContemporaryArt' gallery?

CREATE TABLE Artworks (ArtworkID INT, Title VARCHAR(50), Gallery VARCHAR(50), Size INT); INSERT INTO Artworks (ArtworkID, Title, Gallery, Size) VALUES (1, 'Untitled', 'ContemporaryArt', 100); INSERT INTO Artworks (ArtworkID, Title, Gallery, Size) VALUES (2, 'Untitled2', 'ContemporaryArt', 200);

SELECT AVG(Size) FROM Artworks WHERE Gallery = 'ContemporaryArt';


Question: What is the average fare for public buses in New York City?

CREATE TABLE public_transportation (city VARCHAR(20), transport_type VARCHAR(20), fare DECIMAL(5,2)); INSERT INTO public_transportation VALUES ('New York City', 'Bus', 2.75);

SELECT AVG(fare) FROM public_transportation WHERE city = 'New York City' AND transport_type = 'Bus';


Question: Generate PostgreSQL SQL for: Name the main location for public and masters university

CREATE TABLE table_2076533_1 (main_location VARCHAR, control VARCHAR, type VARCHAR)

SELECT main_location FROM table_2076533_1 WHERE control = 'Public' AND type = 'Masters university';


Question: List all mines in China that mined nickel in 2018

CREATE TABLE mining_operations (id INT, mine_name TEXT, location TEXT, material TEXT, quantity INT, date DATE); INSERT INTO mining_operations (id, mine_name, location, material, quantity, date) VALUES (8, 'Nickel Nexus', 'China', 'nickel', 6000, '2018-01-01');

SELECT DISTINCT mine_name FROM mining_operations WHERE material = 'nickel' AND location = 'China' AND date = '2018-01-01';


Question: Generate PostgreSQL SQL for: When did the VFL pay at Victoria Park?

CREATE TABLE table_name_17 (date VARCHAR, venue VARCHAR)

SELECT date FROM table_name_17 WHERE venue = 'victoria park';


Question: Generate PostgreSQL SQL for: What is the sample size of the poll taken on Dec 13-15, 2007 that had a margin of error of more than 4 and resulted with Republican Mike Huckabee?

CREATE TABLE table_name_5 (sample_size INTEGER, date VARCHAR, republican VARCHAR, margin_of_error VARCHAR)

SELECT AVG(sample_size) FROM table_name_5 WHERE republican = 'mike huckabee' AND margin_of_error > 4 AND date = 'dec 13-15, 2007';


Question: Generate PostgreSQL SQL for: What is Result, when Date is "2000-05-23"?

CREATE TABLE table_name_57 (result VARCHAR, date VARCHAR)

SELECT result FROM table_name_57 WHERE date = '2000-05-23';


Question: What is the total number of satellites deployed per year and the percentage change in satellite deployment from the previous year, by country?

CREATE SCHEMA Satellite;CREATE TABLE Satellite.SatelliteDeployment (country VARCHAR(50), year INT, num_satellites INT);INSERT INTO Satellite.SatelliteDeployment (country, year, num_satellites) VALUES ('USA', 2010, 100), ('China', 2010, 50), ('Russia', 2010, 40), ('India', 2010, 30), ('USA', 2011, 120), ('China', 2011, 60), ('Russia', 2011, 45), ('India', 2011, 35);

SELECT s1.country, s1.year, s1.num_satellites, (s1.num_satellites - COALESCE(s2.num_satellites, 0)) * 100.0 / COALESCE(s2.num_satellites, 1) AS percentage_change FROM Satellite.SatelliteDeployment s1 LEFT JOIN Satellite.SatelliteDeployment s2 ON s1.country = s2.country AND s1.year = s2.year + 1;


Question: What is the total number of concerts for the Hip Hop genre in Asia in the last 2 years?

CREATE TABLE concerts (concert_id INT, artist_id INT, genre VARCHAR(50), country VARCHAR(50), timestamp TIMESTAMP); INSERT INTO concerts (concert_id, artist_id, genre, country, timestamp) VALUES (1, 2001, 'Hip Hop', 'Japan', '2022-01-01 00:00:00'), (2, 2002, 'Hip Hop', 'China', '2022-01-02 12:30:00'); CREATE TABLE artists (artist_id INT, name VARCHAR(100)); INSERT INTO artists (artist_id, name) VALUES (2001, 'Kendrick Lamar'), (2002, 'Drake');

SELECT COUNT(*) FROM concerts JOIN artists ON concerts.artist_id = artists.artist_id WHERE artists.genre = 'Hip Hop' AND concerts.country IN ('Japan', 'China', 'India', 'South Korea', 'Indonesia') AND concerts.timestamp >= '2020-01-01' AND concerts.timestamp < '2022-01-01';


Question: Generate PostgreSQL SQL for: Name the winner for genoa to livorno

CREATE TABLE table_name_39 (winner VARCHAR, course VARCHAR)

SELECT winner FROM table_name_39 WHERE course = 'genoa to livorno';


Question: Which courses have more than 50 students enrolled?

CREATE TABLE courses (course_id INT, course_name VARCHAR(255), num_students INT); INSERT INTO courses (course_id, course_name, num_students) VALUES (101, 'Intro to Psychology', 60), (102, 'Data Science', 75), (103, 'Calculus', 45);

SELECT course_name FROM courses WHERE num_students > 50;


Question: Which rural health clinics were established after 2010, and what are their names?

CREATE TABLE clinics (name VARCHAR(255), establishment_date DATE); INSERT INTO clinics (name, establishment_date) VALUES ('Clinic C', '2011-01-01'), ('Clinic D', '2015-05-15');

SELECT name FROM clinics WHERE establishment_date > '2010-12-31';


Question: pgTAP test for Functap (assertion 258).

SELECT * FROM check_test(
    is_aggregate( 'someproc' ),
    false,
    'is_aggregate(proc)',
    'Function someproc() should be an aggregate function',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Functap.


Question: Generate PostgreSQL SQL for: What is the location of the perpetrator with the largest kills.

CREATE TABLE perpetrator (LOCATION VARCHAR, Killed VARCHAR)

SELECT LOCATION FROM perpetrator ORDER BY Killed DESC LIMIT 1;


Question: Generate PostgreSQL SQL for: player is jim henshall what are all the position

CREATE TABLE table_26996293_2 (position VARCHAR, player VARCHAR)

SELECT position FROM table_26996293_2 WHERE player = 'Jim Henshall';


Question: Write the DDL statement from PostgreSQL regression test 'sequence' (example 21).

CREATE SEQUENCE sequence_testx AS smallint MAXVALUE 100000;

Explanation: DDL from PostgreSQL core regression test for Sequence.


Question: What is the total number of unique marine species observed by expeditions for the 'Marine Investigators' organization?

CREATE TABLE expedition (org VARCHAR(20), species VARCHAR(50)); INSERT INTO expedition VALUES ('Ocean Explorer', 'Dolphin'), ('Ocean Explorer', 'Tuna'), ('Sea Discoverers', 'Shark'), ('Sea Discoverers', 'Whale'), ('Marine Investigators', 'Starfish'), ('Marine Investigators', 'Jellyfish'), ('Marine Investigators', 'Coral'), ('Deep Sea Divers', 'Squid');

SELECT COUNT(DISTINCT species) FROM expedition WHERE org = 'Marine Investigators';


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

SELECT count(*) FROM (select jsonb_path_query('"a"', '-$')) AS _sub;