Question: What is the maximum revenue for restaurants in Chicago?

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', 10000), ('Restaurant6', 8000);

SELECT MAX(revenue) FROM restaurant_revenue WHERE location LIKE '%Chicago%';


Question: What is the maximum number of comments on posts by users from Australia, for posts containing the hashtag #food, in the last month?

CREATE TABLE users (id INT, country VARCHAR(255)); CREATE TABLE posts (id INT, user_id INT, comments INT, hashtags TEXT, post_date DATE);

SELECT MAX(comments) FROM posts INNER JOIN users ON posts.user_id = users.id WHERE users.country = 'Australia' AND hashtags LIKE '%#food%' AND post_date >= DATE(NOW()) - INTERVAL 1 MONTH;


Question: How many water treatment facilities have been updated in India in 2021?

CREATE TABLE water_treatment_facilities (location VARCHAR(50), last_update DATE); INSERT INTO water_treatment_facilities (location, last_update) VALUES ('Mumbai', '2021-01-01'), ('Delhi', '2021-02-03'), ('Bangalore', '2021-04-05');

SELECT COUNT(*) FROM water_treatment_facilities WHERE last_update >= '2021-01-01' AND last_update <= '2021-12-31' AND location = 'India';


Question: List all clients who have completed any financial program and their account balances.

CREATE TABLE financial_programs (client_id INT, program_name VARCHAR(30), program_status VARCHAR(20)); INSERT INTO financial_programs (client_id, program_name, program_status) VALUES (301, 'Islamic Financial Capability', 'Completed'), (302, 'Financial Wellbeing', 'Enrolled'), (303, 'Islamic Financial Capability', 'Completed'), (304, 'Financial Capability', 'Dropped Out'); CREATE TABLE account_balances (client_id INT, account_balance DECIMAL(10,2)); INSERT INTO account_balances (client_id, account_balance) VALUES (301, 1000.00), (302, 2000.00), (303, 3000.00), (304, 4000.00);

SELECT * FROM financial_programs INNER JOIN account_balances ON financial_programs.client_id = account_balances.client_id WHERE program_status = 'Completed';


Question: Generate PostgreSQL SQL for: who is the the incumbent with candidates being ben cravens (d) unopposed

CREATE TABLE table_1342331_5 (incumbent VARCHAR, candidates VARCHAR)

SELECT incumbent FROM table_1342331_5 WHERE candidates = 'Ben Cravens (D) Unopposed';


Question: What is the total installed renewable energy capacity (in GW) for each continent in 2022?

CREATE TABLE renewable_energy_capacity (continent VARCHAR(50), year INT, renewable_energy_capacity FLOAT); INSERT INTO renewable_energy_capacity (continent, year, renewable_energy_capacity) VALUES ('Africa', 2022, 200.5), ('Asia', 2022, 800.7), ('Europe', 2022, 600.3), ('North America', 2022, 500.2), ('South America', 2022, 300.1), ('Australia', 2022, 100.9);

SELECT r.continent, SUM(r.renewable_energy_capacity) FROM renewable_energy_capacity r WHERE r.year = 2022 GROUP BY r.continent;


Question: Generate PostgreSQL SQL for: How many teams were at 10 points?

CREATE TABLE table_26473176_1 (team VARCHAR, points VARCHAR)

SELECT COUNT(team) FROM table_26473176_1 WHERE points = 10;


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

SELECT count(*) FROM datetmp WHERE a  = '2001-02-13';

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


Question: Generate PostgreSQL SQL for: tell how many wins there was when the score was 490

CREATE TABLE table_14070062_4 (won VARCHAR, points_for VARCHAR)

SELECT COUNT(won) FROM table_14070062_4 WHERE points_for = '490';


Question: Generate PostgreSQL SQL for: Who was the rider with a grid of 36?

CREATE TABLE table_name_39 (rider VARCHAR, grid VARCHAR)

SELECT rider FROM table_name_39 WHERE grid = 36;


Question: Generate PostgreSQL SQL for: Name the total number of step 6 for 11 gs grade

CREATE TABLE table_2319437_1 (step_6 VARCHAR, gs_grade VARCHAR)

SELECT COUNT(step_6) FROM table_2319437_1 WHERE gs_grade = 11;


Question: What is the maximum number of goals scored by a player in a single game?

CREATE TABLE game_stats (id INT, player TEXT, goals INT); INSERT INTO game_stats (id, player, goals) VALUES (1, 'Pele', 7), (2, 'Diego', 6), (3, 'Ronaldo', 5);


Question: Drop the table for cultural competency data

CREATE TABLE cultural_competency (id INT PRIMARY KEY, state VARCHAR(2), year INT, training_hours FLOAT);

DROP TABLE IF EXISTS cultural_competency;


Question: Update the record of the offender with ID 3 in the restorative_justice_programs table, changing the state to 'Oregon'.

CREATE TABLE restorative_justice_programs (id INT, offender_name TEXT, age INT, state TEXT); INSERT INTO restorative_justice_programs (id, offender_name, age, state) VALUES (1, 'John Doe', 34, 'California'); INSERT INTO restorative_justice_programs (id, offender_name, age, state) VALUES (2, 'Jane Smith', 27, 'California'); INSERT INTO restorative_justice_programs (id, offender_name, age, state) VALUES (3, 'Mike Brown', 30, 'California');

UPDATE restorative_justice_programs SET state = 'Oregon' WHERE id = 3;


Question: What is the total number of agricultural innovation metrics in each country, sorted by metric count in descending order?

CREATE TABLE countries (country_id INT, country_name VARCHAR(255)); CREATE TABLE metrics (metric_id INT, metric_name VARCHAR(255), country_id INT);

SELECT c.country_name, COUNT(m.metric_id) as metric_count FROM countries c JOIN metrics m ON c.country_id = m.country_id GROUP BY c.country_name ORDER BY metric_count DESC;


Question: What is the average timeline for completing commercial construction projects in Chicago, categorized by project size?

CREATE TABLE Commercial_Projects (ProjectID INT, City VARCHAR(50), Size VARCHAR(50), Timeline INT);

SELECT Size, AVG(Timeline) FROM Commercial_Projects WHERE City = 'Chicago' AND ProjectType = 'Commercial' GROUP BY Size;


Question: What was the total waste produced by the 'West Coast' plant in 2020?

CREATE TABLE waste (plant varchar(10), year int, waste_amount int); INSERT INTO waste (plant, year, waste_amount) VALUES ('North Plant', 2020, 150), ('North Plant', 2019, 140), ('West Plant', 2020, 200), ('West Plant', 2019, 180);

SELECT SUM(waste_amount) FROM waste WHERE plant = 'West Plant' AND year = 2020;


Question: Insert a new record into the MarineLife table for a species named 'Blue Whale' with an id of 1.

CREATE TABLE marine_life (id INT, species_name VARCHAR(255)); INSERT INTO marine_life (id, species_name) VALUES (1, 'Dolphin'), (2, 'Shark'), (3, 'Tuna');

INSERT INTO marine_life (id, species_name) VALUES (1, 'Blue Whale');


Question: Identify the number of public transit users in New York City by subway line.

CREATE TABLE subway_ridership (user_id INT, trip_date DATE, trip_subway_line VARCHAR(20)); INSERT INTO subway_ridership (user_id, trip_date, trip_subway_line) VALUES (1, '2022-01-01', '4'), (2, '2022-01-01', '6');

SELECT trip_subway_line, COUNT(DISTINCT user_id) AS unique_users FROM subway_ridership GROUP BY trip_subway_line;


Question: How many vessels visited each port in the US in the last 3 months?

CREATE TABLE ports (port_id INT, port_name TEXT, country TEXT);CREATE TABLE visits (visit_id INT, vessel_id INT, port_id INT, visit_date DATE);

SELECT ports.port_name, COUNT(visits.vessel_id) as num_visits FROM ports JOIN visits ON ports.port_id = visits.port_id WHERE ports.country = 'US' AND visits.visit_date BETWEEN DATEADD(month, -3, CURRENT_DATE) AND CURRENT_DATE GROUP BY ports.port_name;


Question: Generate PostgreSQL SQL for: Which opponents are on the date September 5?

CREATE TABLE table_23612439_2 (opponent VARCHAR, date VARCHAR)

SELECT opponent FROM table_23612439_2 WHERE date = 'September 5';


Question: What is the minimum salary for employees who have completed training programs in the Finance department?

CREATE TABLE employees (employee_id INT, department VARCHAR(255), salary INT); INSERT INTO employees (employee_id, department, salary) VALUES (1, 'Finance', 50000), (2, 'HR', 60000), (3, 'Finance', 55000), (4, 'Finance', 70000); CREATE TABLE training_programs (program_id INT, department VARCHAR(255)); INSERT INTO training_programs (program_id, department) VALUES (1, 'IT'), (2, 'HR'), (3, 'Finance'); CREATE TABLE completed_training (employee_id INT, program_id INT); INSERT INTO completed_training (employee_id, program_id) VALUES (1, 3), (2, 2), (3, 3);

SELECT MIN(salary) FROM employees e JOIN completed_training ct ON e.employee_id = ct.employee_id JOIN training_programs tp ON ct.program_id = tp.program_id WHERE e.department = 'Finance';


Question: How many cases were handled by female attorneys in the criminal law specialty?

CREATE TABLE attorneys (id INT, name VARCHAR(50), gender VARCHAR(50), years_of_experience INT, specialty VARCHAR(50)); INSERT INTO attorneys (id, name, gender, years_of_experience, specialty) VALUES (1, 'John Doe', 'Male', 12, 'Criminal Law'); INSERT INTO attorneys (id, name, gender, years_of_experience, specialty) VALUES (2, 'Jane Smith', 'Female', 5, 'Family Law'); INSERT INTO attorneys (id, name, gender, years_of_experience, specialty) VALUES (3, 'Maria Garcia', 'Female', 8, 'Criminal Law');

SELECT COUNT(*) FROM attorneys WHERE gender = 'Female' AND specialty = 'Criminal Law';


Question: What is the maximum daily revenue for each line in the 'mumbai' schema?

CREATE TABLE mumbai.lines (id INT, line_name VARCHAR); CREATE TABLE mumbai.revenue (id INT, line_id INT, daily_revenue DECIMAL);

SELECT mumbai.lines.line_name, MAX(mumbai.revenue.daily_revenue) FROM mumbai.lines INNER JOIN mumbai.revenue ON mumbai.lines.id = mumbai.revenue.line_id GROUP BY mumbai.lines.line_name;


Question: Generate PostgreSQL SQL for: Can you tell me the total number of Matched that has the Strike Rate smallet than 152.3, and the Balls of 395?

CREATE TABLE table_name_88 (matches VARCHAR, strike_rate VARCHAR, balls VARCHAR)

SELECT COUNT(matches) FROM table_name_88 WHERE strike_rate < 152.3 AND balls = 395;


Question: What is the maximum area of land (in hectares) used for agriculture in each region in the agro_regions dataset?

CREATE TABLE agro_regions (id INT, region VARCHAR(255), land_area INT);

SELECT region, MAX(land_area) FROM agro_regions GROUP BY region;


Question: Generate PostgreSQL SQL for: Name the total number of number disc for jimmy kaufman

CREATE TABLE table_15430606_1 (no_disc VARCHAR, directed_by VARCHAR)

SELECT COUNT(no_disc) FROM table_15430606_1 WHERE directed_by = 'Jimmy Kaufman';


Question: Which salesperson has sold the least garments in the last 30 days, ordered by the number of garments sold?

CREATE TABLE salesperson (salesperson_id INT, name VARCHAR(50)); CREATE TABLE sales (sales_id INT, salesperson_id INT, sale_date DATE);

SELECT salesperson.name, COUNT(sales.sales_id) AS quantity_sold FROM salesperson INNER JOIN sales ON salesperson.salesperson_id = sales.salesperson_id WHERE sale_date >= CURRENT_DATE - INTERVAL '30 days' GROUP BY salesperson.name ORDER BY quantity_sold ASC;


Question: What is the average energy consumption of buildings in the 'urban' schema, grouped by city?

CREATE TABLE urban.buildings (city VARCHAR(255), energy_consumption INT); INSERT INTO urban.buildings (city, energy_consumption) VALUES ('CityA', 1200), ('CityA', 1500), ('CityB', 1700), ('CityB', 1300);

SELECT city, AVG(energy_consumption) FROM urban.buildings GROUP BY city;


Question: How many drought-affected regions are there in the African continent?

CREATE TABLE droughts (id INT, region VARCHAR(50), continent VARCHAR(20)); INSERT INTO droughts (id, region, continent) VALUES (1, 'Eastern Cape', 'Africa'), (2, 'Western Cape', 'Africa'), (3, 'Northern Cape', 'Africa'), (4, 'Buenos_Aires', 'South_America');

SELECT COUNT(*) FROM droughts WHERE continent = 'Africa';


Question: Generate PostgreSQL SQL for: What denomination is mt lawley?

CREATE TABLE table_name_5 (denomination VARCHAR, location VARCHAR)

SELECT denomination FROM table_name_5 WHERE location = 'mt lawley';


Question: How many employees are there in each department in the 'hr' schema, grouped by department and sorted by the number of employees in descending order?

CREATE SCHEMA hr; CREATE TABLE departments (id INT, name VARCHAR); INSERT INTO departments VALUES (1, 'Marketing'); CREATE TABLE employees (id INT, name VARCHAR, department_id INT); INSERT INTO employees VALUES (1, 'John Doe', 1);

SELECT departments.name, COUNT(*) AS num_employees FROM hr.departments JOIN hr.employees ON departments.id = employees.department_id GROUP BY departments.name ORDER BY num_employees DESC;


Question: pgTAP test for Pgtap--1.1.0--1.2.0 (assertion 74).

-- is_window( schema, function, description )
CREATE OR REPLACE FUNCTION is_window ( NAME, NAME, TEXT )
RETURNS TEXT AS $$
    SELECT _func_compare($1, $2, _type_func('w', $1, $2), $3 );
$$ LANGUAGE SQL;

Explanation: SQL assertion from pgTAP test suite for Pgtap--1.1.0--1.2.0.


Question: Insert a new donation of 1000 made by John Doe on 2022-02-14.

CREATE TABLE Donors (DonorID int, Name varchar(50), TotalDonation money); CREATE TABLE Donations (DonationID int, DonorID int, Amount money, DonationDate date); INSERT INTO Donors (DonorID, Name, TotalDonation) VALUES (1, 'John Doe', 5000), (2, 'Jane Smith', 7000); INSERT INTO Donations (DonationID, DonorID, Amount, DonationDate) VALUES (1, 1, 500, '2021-01-01'), (2, 1, 2000, '2021-06-15'), (3, 2, 6000, '2021-03-25');

INSERT INTO Donations (DonationID, DonorID, Amount, DonationDate) VALUES (4, 1, 1000, '2022-02-14');


Question: Generate PostgreSQL SQL for: In 2009, what Appearances had a Winning Percentage of less than 0?

CREATE TABLE table_name_30 (appearances INTEGER, season_s_ VARCHAR, winning_percentage VARCHAR)

SELECT AVG(appearances) FROM table_name_30 WHERE season_s_ = '2009' AND winning_percentage < 0;


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

SELECT date '4714-11-23 BC';  -- out of range
SELECT date '5874897-12-31';

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

SELECT count(*) FROM (SELECT date '4714-11-23 BC';  -- out of range
SELECT date '5874897-12-31') AS _sub;


Question: Generate PostgreSQL SQL for: What venue did mahela jayawardene and thilan samaraweera play at?

CREATE TABLE table_name_42 (venue VARCHAR, batting_partners VARCHAR)

SELECT venue FROM table_name_42 WHERE batting_partners = 'mahela jayawardene and thilan samaraweera';


Question: What is the average budget for peacekeeping operations in Africa since 2015?

CREATE TABLE PeacekeepingOperations (id INT PRIMARY KEY, operation VARCHAR(100), location VARCHAR(50), year INT, budget INT); INSERT INTO PeacekeepingOperations (id, operation, location, year, budget) VALUES (1, 'MINUSCA', 'Central African Republic', 2016, 864731532);

SELECT AVG(budget) FROM PeacekeepingOperations WHERE location LIKE '%Africa%' AND year >= 2015;


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

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

SELECT count(*) FROM (SELECT '2014-10-26 00:00:00 MSK'::timestamptz) AS _sub;


Question: Generate PostgreSQL SQL for: Name the venue where St Kilda was the opposing away team

CREATE TABLE table_name_76 (venue VARCHAR, away_team VARCHAR)

SELECT venue FROM table_name_76 WHERE away_team = 'st kilda';


Question: Update the quantity of 'Tank' sales records in 'Asia' to 22 for the year '2025'

CREATE TABLE military_sales (id INT PRIMARY KEY, region VARCHAR(20), year INT, equipment_name VARCHAR(30), quantity INT, value FLOAT); INSERT INTO military_sales (id, region, year, equipment_name, quantity, value) VALUES (1, 'Asia', 2025, 'Fighter Jet', 10, 6000000), (2, 'Asia', 2025, 'Tank', 20, 13000000), (3, 'Asia', 2025, 'Helicopter', 15, 9000000);

UPDATE military_sales SET quantity = 22 WHERE region = 'Asia' AND equipment_name = 'Tank' AND year = 2025;


Question: Generate PostgreSQL SQL for: What role is spoken in hindi in 2011?

CREATE TABLE table_name_26 (role VARCHAR, language VARCHAR, year VARCHAR)

SELECT role FROM table_name_26 WHERE language = 'hindi' AND year = 2011;


Question: What is the lowest price of vegan makeup products in the UK?

CREATE TABLE Makeup_Products (ProductID int, ProductName varchar(100), Country varchar(50), IsVegan bit, RetailPrice decimal(5,2)); INSERT INTO Makeup_Products (ProductID, ProductName, Country, IsVegan, RetailPrice) VALUES (1, 'Vegan Mascara', 'UK', 1, 14.99); INSERT INTO Makeup_Products (ProductID, ProductName, Country, IsVegan, RetailPrice) VALUES (2, 'Natural Eyeshadow', 'UK', 0, 10.99); INSERT INTO Makeup_Products (ProductID, ProductName, Country, IsVegan, RetailPrice) VALUES (3, 'Cruelty-Free Lipstick', 'UK', 1, 8.99);

SELECT MIN(RetailPrice) FROM Makeup_Products WHERE Country = 'UK' AND IsVegan = 1;


Question: Generate PostgreSQL SQL for: WHAT SERIES WAS RELEASED BY ITV STUDIOS AND A RELEASE DATE OF AUGUST 15, 2012?

CREATE TABLE table_name_47 (series VARCHAR, released_by VARCHAR, release_date VARCHAR)

SELECT series FROM table_name_47 WHERE released_by = 'itv studios' AND release_date = 'august 15, 2012';


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

INSERT INTO num_exp_add VALUES (8,4,'7874342.4119');

Explanation: DML from PostgreSQL core regression test for Numeric.


Question: What is the total number of volunteers in India who have completed more than 10 hours of service?

CREATE TABLE volunteers (volunteer_id int, hours_served int, country varchar(50)); INSERT INTO volunteers (volunteer_id, hours_served, country) VALUES (1, 12, 'India'), (2, 5, 'India'), (3, 20, 'India');

SELECT COUNT(volunteer_id) FROM volunteers WHERE country = 'India' GROUP BY volunteer_id HAVING hours_served > 10;


Question: What is the average account balance for customers in each city?

CREATE TABLE accounts (account_id INT, customer_id INT, account_balance DECIMAL(10,2)); CREATE TABLE customers (customer_id INT, customer_name VARCHAR(255), city VARCHAR(255)); INSERT INTO accounts (account_id, customer_id, account_balance) VALUES (1, 1, 1000.00), (2, 1, 2000.00), (3, 2, 500.00), (4, 3, 1500.00); INSERT INTO customers (customer_id, customer_name, city) VALUES (1, 'John Doe', 'New York'), (2, 'Jane Smith', 'Los Angeles'), (3, 'Bob Johnson', 'Chicago');

SELECT c.city, AVG(a.account_balance) as avg_account_balance FROM accounts a INNER JOIN customers c ON a.customer_id = c.customer_id GROUP BY c.city;


Question: What are the names and categories of the decentralized applications that have been deployed on the Binance Smart Chain and have had the most number of transactions?

CREATE TABLE IF NOT EXISTS decentralized_applications (dapp_id INT PRIMARY KEY, name VARCHAR(100), tx_id INT, category VARCHAR(50), blockchain VARCHAR(50), FOREIGN KEY (tx_id) REFERENCES blockchain_transactions(tx_id)); CREATE TABLE IF NOT EXISTS blockchain_transactions (tx_id INT PRIMARY KEY, blockchain VARCHAR(50)); INSERT INTO blockchain_transactions (tx_id, blockchain) VALUES (1, 'Binance Smart Chain');

SELECT dapp_name, category, COUNT(dapp_id) FROM decentralized_applications da JOIN blockchain_transactions bt ON da.tx_id = bt.tx_id WHERE bt.blockchain = 'Binance Smart Chain' GROUP BY dapp_name, category ORDER BY COUNT(dapp_id) DESC LIMIT 10;


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

SELECT * FROM multiout_record_as('obj', null, 2, false);

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


Question: What is the total quantity of gold mined by each mining company?

CREATE TABLE Mining_Company (id INT, name VARCHAR(50), location VARCHAR(50)); INSERT INTO Mining_Company (id, name, location) VALUES (1, 'CompanyA', 'USA'), (2, 'CompanyB', 'Canada'); CREATE TABLE Mining_Operation (id INT, company_id INT, mine_name VARCHAR(50), resource VARCHAR(10), quantity INT); INSERT INTO Mining_Operation (id, company_id, mine_name, resource, quantity) VALUES (1, 1, 'Mine1', 'Gold', 1000), (2, 1, 'Mine2', 'Gold', 1500), (3, 2, 'Mine3', 'Gold', 800), (4, 2, 'Mine4', 'Silver', 1200);

SELECT m.name, SUM(quantity) as total_gold_quantity FROM Mining_Operation o JOIN Mining_Company m ON o.company_id = m.id WHERE o.resource = 'Gold' GROUP BY m.name;


Question: What is the total duration of space missions for each spacecraft model?

CREATE TABLE space_missions (id INT, spacecraft_model VARCHAR(255), duration FLOAT);

SELECT spacecraft_model, SUM(duration) as total_duration FROM space_missions GROUP BY spacecraft_model;


Question: Add new community health worker record for Georgia

CREATE TABLE community_health_workers (chw_id INT, state VARCHAR(2), name VARCHAR(50), certification_date DATE);

INSERT INTO community_health_workers (chw_id, state, name, certification_date) VALUES (987, 'GA', 'Nia White', '2022-06-10');


Question: Generate PostgreSQL SQL for: What position was Jafus White who was picked after round 1?

CREATE TABLE table_name_87 (position VARCHAR, round VARCHAR, player VARCHAR)

SELECT position FROM table_name_87 WHERE round > 1 AND player = 'jafus white';


Question: What is the maximum budget for any public works project?

CREATE TABLE PublicWorksB(id INT, project VARCHAR(30), budget DECIMAL(10,2)); INSERT INTO PublicWorksB(id, project, budget) VALUES (1, 'Highway Construction', 800000.00), (2, 'Airport Expansion', 3000000.00);


Question: List policy numbers with the highest claim amount in the last quarter.

CREATE TABLE Policy (PolicyNumber INT, PolicyholderName VARCHAR(50)); CREATE TABLE Claim (ClaimID INT, PolicyNumber INT, ClaimDate DATE, ClaimAmount DECIMAL(10,2)); INSERT INTO Policy VALUES (1, 'John Doe'), (2, 'Jane Smith'); INSERT INTO Claim VALUES (1, 1, '2021-01-01', 5000), (2, 1, '2021-02-01', 3000), (3, 2, '2021-04-01', 7000), (4, 2, '2021-05-01', 8000), (5, 2, '2021-06-01', 9000);

SELECT PolicyNumber, MAX(ClaimAmount) as MaxClaimAmount FROM Claim WHERE ClaimDate >= DATEADD(QUARTER, -1, GETDATE()) GROUP BY PolicyNumber ORDER BY MaxClaimAmount DESC;


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

SELECT count(*) FROM ft1 a CROSS JOIN ft1 b CROSS JOIN ft1 c CROSS JOIN ft1 d;

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


Question: Generate PostgreSQL SQL for: What was the district who had their first elected in 1966?

CREATE TABLE table_1341843_44 (district VARCHAR, first_elected VARCHAR)

SELECT district FROM table_1341843_44 WHERE first_elected = 1966;


Question: Insert a new record for the 'waste_reduction' department with an average salary of $40,000 and 30 employees.

CREATE TABLE company_departments (dept_name TEXT, avg_salary NUMERIC, employee_count INTEGER);

INSERT INTO company_departments (dept_name, avg_salary, employee_count) VALUES ('waste_reduction', 40000.00, 30);


Question: Which sites have both wooden and stone artifacts?

CREATE TABLE excavation_sites (site_id INT, site_name TEXT); CREATE TABLE artifacts (artifact_id INT, site_id INT, artifact_type TEXT); INSERT INTO excavation_sites (site_id, site_name) VALUES (1, 'Site A'), (2, 'Site B'), (3, 'Site C'); INSERT INTO artifacts (artifact_id, site_id, artifact_type) VALUES (1, 1, 'wooden'), (2, 1, 'stone'), (3, 2, 'metal'), (4, 3, 'wooden'), (5, 3, 'pottery'), (6, 4, 'stone');

SELECT e.site_name FROM excavation_sites e JOIN artifacts a ON e.site_id = a.site_id WHERE a.artifact_type IN ('wooden', 'stone') GROUP BY e.site_id HAVING COUNT(DISTINCT a.artifact_type) = 2;


Question: Write the DML statement from PostgreSQL regression test 'with' (example 43).

Explanation: DML from PostgreSQL core regression test for With.


Question: Generate PostgreSQL SQL for: what is the turbo when the frequency is 2.2 ghz?

CREATE TABLE table_name_63 (turbo VARCHAR, frequency VARCHAR)

SELECT turbo FROM table_name_63 WHERE frequency = '2.2 ghz';


Question: List all suppliers that provide products for a specific restaurant, excluding any suppliers that have had food safety violations in the past year.

CREATE TABLE suppliers (id INT, name TEXT, restaurant TEXT, violation_date DATE);

SELECT name FROM suppliers WHERE restaurant = 'Restaurant A' AND id NOT IN (SELECT supplier_id FROM violations WHERE violation_date >= DATEADD(year, -1, GETDATE()));


Question: Generate PostgreSQL SQL for: What is the quantity of class B V?

CREATE TABLE table_name_55 (quantity VARCHAR, class VARCHAR)

SELECT quantity FROM table_name_55 WHERE class = 'b v';


Question: Generate PostgreSQL SQL for: Name the height in feet for the player from valparaiso

CREATE TABLE table_name_80 (height_in_ft VARCHAR, school_club_team_country VARCHAR)

SELECT height_in_ft FROM table_name_80 WHERE school_club_team_country = 'valparaiso';


Question: Insert a new record of a 'Kiwi' animal in the rescue center from the 'New Zealand Islands' region.

CREATE TABLE rescue_center_animals (animal_id INT, animal_name VARCHAR(50), region VARCHAR(50));

INSERT INTO rescue_center_animals (animal_id, animal_name, region) VALUES (3, 'Kiwi', 'New Zealand Islands');


Question: Show all suppliers from 'Jakarta'

SELECT * FROM suppliers WHERE location = 'Jakarta';


Question: Generate PostgreSQL SQL for: Which Season has a Postseason of promoted runner-up?

CREATE TABLE table_name_33 (season VARCHAR, postseason VARCHAR)

SELECT season FROM table_name_33 WHERE postseason = 'promoted runner-up';


Question: PostgreSQL regression test 'interval': Write the SELECT query (example 92).

SELECT '3 days 5 milliseconds'::interval;

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

SELECT count(*) FROM (SELECT '3 days 5 milliseconds'::interval) AS _sub;


Question: How many autonomous buses are in operation in Tokyo, Osaka, and Kyoto?

CREATE TABLE JPAutonomousBuses (id INT, city VARCHAR(20), in_operation INT);

SELECT SUM(in_operation) FROM JPAutonomousBuses WHERE city IN ('Tokyo', 'Osaka', 'Kyoto');


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

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

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


Question: Generate PostgreSQL SQL for: What was the Record on Game 50?

CREATE TABLE table_name_68 (record VARCHAR, game VARCHAR)

SELECT record FROM table_name_68 WHERE game = 50;


Question: Generate PostgreSQL SQL for: Tell me the highest opponents for record of 7-3 and vikings points more than 7

CREATE TABLE table_name_97 (opponents INTEGER, record VARCHAR, vikings_points VARCHAR)

SELECT MAX(opponents) FROM table_name_97 WHERE record = '7-3' AND vikings_points > 7;


Question: What was the total cost of satellites deployed in 2022?

CREATE TABLE Satellites (satellite_id INT, deployment_year INT, cost FLOAT); INSERT INTO Satellites (satellite_id, deployment_year, cost) VALUES (1, 2022, 20000000.0), (2, 2021, 15000000.0);

SELECT SUM(cost) FROM Satellites WHERE deployment_year = 2022;


Question: pgTAP test for Performs Ok (assertion 8).

SELECT * FROM check_test(
    performs_ok( 'SELECT TRUE', 0, 'whatever' ),
    false,
    'simple select fail',
    'whatever',
    '      runtime: [[:digit:]]+([.][[:digit:]]+)? ms
      exceeds: 0 ms',
    true
);

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


Question: What is the average consumer awareness score for the ethical fashion brand 'GreenFashions' in the 'Asia' region, and how does it compare to the global average?

CREATE TABLE consumer_awareness (id INT PRIMARY KEY, brand VARCHAR(255), region VARCHAR(255), score INT); INSERT INTO consumer_awareness (id, brand, region, score) VALUES (1, 'GreenFashions', 'Asia', 80), (2, 'GreenFashions', 'Europe', 85), (3, 'EcoFriendlyFashions', 'Asia', 75), (4, 'EcoFriendlyFashions', 'USA', 90); CREATE TABLE regions (id INT PRIMARY KEY, region VARCHAR(255)); INSERT INTO regions (id, region) VALUES (1, 'Asia'), (2, 'Europe'), (3, 'USA');

SELECT AVG(ca.score) as avg_score FROM consumer_awareness ca JOIN regions r ON ca.region = r.region WHERE ca.brand = 'GreenFashions' AND r.region = 'Asia'; SELECT AVG(score) as global_avg_score FROM consumer_awareness WHERE brand = 'GreenFashions';


Question: Delete the 'Director of Engineering' job title from the JobTitle table

CREATE TABLE JobTitle (JobTitleID INT PRIMARY KEY, JobTitleName VARCHAR(50));

DELETE FROM JobTitle WHERE JobTitleName = 'Director of Engineering';


Question: Update the game_mode column in the game_sessions table to 'Capture the Flag' for all sessions on the maps table with the name 'Stadium'

CREATE TABLE game_sessions (session_id INT, player_id INT, game_mode VARCHAR(20), map_id INT); CREATE TABLE maps (map_id INT, map_name VARCHAR(20));

UPDATE game_sessions SET game_mode = 'Capture the Flag' WHERE map_id IN (SELECT map_id FROM maps WHERE map_name = 'Stadium');


Question: Delete the bus route 12 from the public transportation system of San Francisco

CREATE TABLE bus_routes (id INT PRIMARY KEY, route_number INT, route_name VARCHAR(255), city VARCHAR(255), num_stops INT);

DELETE FROM bus_routes WHERE route_number = 12 AND city = 'San Francisco';


Question: Generate PostgreSQL SQL for: What's the lowest Losses recorded wiht a Wins of 1, Team of Dallas Stars, and a Win % that's smaller than 0.25?

CREATE TABLE table_name_60 (losses INTEGER, win__percentage VARCHAR, wins VARCHAR, team VARCHAR)

SELECT MIN(losses) FROM table_name_60 WHERE wins = 1 AND team = 'dallas stars' AND win__percentage < 0.25;


Question: Generate PostgreSQL SQL for: Tell me the driver for ford cosworth dfv 3.0 v8 and chassis of ts19 ts20

CREATE TABLE table_name_22 (driver VARCHAR, engine VARCHAR, chassis VARCHAR)

SELECT driver FROM table_name_22 WHERE engine = 'ford cosworth dfv 3.0 v8' AND chassis = 'ts19 ts20';


Question: What is the total water consumption by city in 2020, considering domestic, commercial, and agricultural consumption?

CREATE TABLE water_usage (city VARCHAR(255), year INT, domestic_consumption INT, commercial_consumption INT, agricultural_consumption INT); INSERT INTO water_usage (city, year, domestic_consumption, commercial_consumption, agricultural_consumption) VALUES ('CityA', 2020, 350, 250, 550), ('CityB', 2020, 450, 350, 650), ('CityC', 2020, 500, 400, 700), ('CityD', 2020, 400, 300, 600);

SELECT city, (domestic_consumption + commercial_consumption + agricultural_consumption) as total_consumption FROM water_usage WHERE year = 2020 GROUP BY city;


Question: Generate PostgreSQL SQL for: Where is the miss global teen?

CREATE TABLE table_1825751_14 (hometown VARCHAR, pageant VARCHAR)

SELECT hometown FROM table_1825751_14 WHERE pageant = 'Miss Global Teen';


Question: What is the number of military innovation patents filed by country in 2021?

CREATE TABLE military_patents (patent_name VARCHAR(255), country VARCHAR(255), year INT); INSERT INTO military_patents (patent_name, country, year) VALUES ('Patent 1', 'USA', 2021), ('Patent 2', 'China', 2021), ('Patent 3', 'Russia', 2021);

SELECT country, COUNT(patent_name) FROM military_patents WHERE year = 2021 GROUP BY country;


Question: Generate PostgreSQL SQL for: What is the Coach with a Big Ten that is 3rd (278)?

CREATE TABLE table_name_92 (coach VARCHAR, big_ten VARCHAR)

SELECT coach FROM table_name_92 WHERE big_ten = '3rd (278)';


Question: What is the average workout duration for users in the age group 25-34?

CREATE TABLE UserData (UserID INT, Age INT); CREATE TABLE WorkoutData (UserID INT, WorkoutDuration INT); INSERT INTO UserData (UserID, Age) VALUES (1, 27), (2, 32), (3, 24), (4, 35), (5, 29); INSERT INTO WorkoutData (UserID, WorkoutDuration) VALUES (1, 45), (1, 60), (2, 30), (3, 75), (3, 45), (4, 30), (5, 60);

SELECT AVG(WorkoutDuration) FROM WorkoutData INNER JOIN UserData ON WorkoutData.UserID = UserData.UserID WHERE Age BETWEEN 25 AND 34;


Question: pgTAP test for Partitions (assertion 17).

SELECT * FROM check_test(
    is_partition_of( 'part1', 'parted', 'whatevs' ),
    true,
    'is_partition_of( ctab, ptab, desc )',
    'whatevs',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Partitions.


Question: What is the maximum sentence length for offenders who participated in restorative justice programs in California?

CREATE TABLE restorative_justice_sentences (sentence_id INT, program_id INT, sentence_length INT, state VARCHAR(2)); INSERT INTO restorative_justice_sentences (sentence_id, program_id, sentence_length, state) VALUES (1, 1001, 18, 'CA'), (2, 1002, 24, 'CA');

SELECT MAX(sentence_length) FROM restorative_justice_sentences WHERE state = 'CA';


Question: How many players have participated in esports events, and what is the average age of these players?

CREATE TABLE Players (id INT, name VARCHAR(50), age INT, participated_in_esports_event BOOLEAN); INSERT INTO Players (id, name, age, participated_in_esports_event) VALUES (1, 'Player1', 25, TRUE), (2, 'Player2', 30, FALSE), (3, 'Player3', 35, TRUE);

SELECT COUNT(*) AS num_players, AVG(age) AS avg_age FROM Players WHERE participated_in_esports_event = TRUE;


Question: Generate PostgreSQL SQL for: 3488 is the enrollment amount of what college?

CREATE TABLE table_1183842_1 (institution VARCHAR, enrollment VARCHAR)

SELECT institution FROM table_1183842_1 WHERE enrollment = 3488;


Question: Generate PostgreSQL SQL for: What college did Byron Williams attend?

CREATE TABLE table_14655757_1 (college VARCHAR, player VARCHAR)

SELECT college FROM table_14655757_1 WHERE player = 'Byron Williams';


Question: List the number of male members in each region who have not participated in any classes in the last week and their latest membership date.

CREATE TABLE Members (MemberID INT, Gender VARCHAR(10), Region VARCHAR(20), MembershipDate DATE); INSERT INTO Members (MemberID, Gender, Region, MembershipDate) VALUES (10, 'Male', 'Midwest', '2021-01-01'); CREATE TABLE Classes (ClassID INT, ClassType VARCHAR(20), Duration INT, MemberID INT); INSERT INTO Classes (ClassID, ClassType, Duration, MemberID) VALUES (100, 'Yoga', 60, 10);

SELECT Members.Region, COUNT(Members.MemberID) AS InactiveMembers, MAX(Members.MembershipDate) AS LatestMembershipDate FROM Members LEFT JOIN Classes ON Members.MemberID = Classes.MemberID WHERE Members.Gender = 'Male' AND Classes.MemberID IS NULL AND Members.MembershipDate <= DATE_SUB(CURRENT_DATE, INTERVAL 1 WEEK) GROUP BY Members.Region;


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

SELECT (timestamp without time zone '10:30 today' = (timestamp without time zone 'yesterday' + interval '1 day 10 hr 30 min')) as "True";

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

SELECT count(*) FROM (SELECT (timestamp without time zone '10:30 today' = (timestamp without time zone 'yesterday' + interval '1 day 10 hr 30 min')) as "True") AS _sub;


Question: Generate PostgreSQL SQL for: How many sets were played in 2007 at the tournament that had 4R in 2011 and 2R in 2009?

SELECT 2007 FROM table_name_89 WHERE 2011 = '4r' AND 2009 = '2r';


Question: Generate PostgreSQL SQL for: Name the womens singles for  raina tzvetkova petya nedelcheva

CREATE TABLE table_14903491_1 (womens_singles VARCHAR, womens_doubles VARCHAR)

SELECT womens_singles FROM table_14903491_1 WHERE womens_doubles = 'Raina Tzvetkova Petya Nedelcheva';


Question: Write the DML statement from PostgreSQL regression test 'jsonb' (example 860).

update test_jsonb_subscript set test_json['a'][2]['b'][2]['c'][2] = '1';

Explanation: DML from PostgreSQL core regression test for Jsonb.


Question: What is the total exploration cost in the 'ArabianSea' for wells drilled after 2010?

CREATE TABLE WellExplorationCosts (well_id INT, drill_year INT, exploration_cost REAL); INSERT INTO WellExplorationCosts (well_id, drill_year, exploration_cost) VALUES (1, 2008, 2000000), (2, 2012, 3000000), (3, 2015, 1500000);

SELECT SUM(exploration_cost) FROM WellExplorationCosts WHERE region = 'ArabianSea' AND drill_year > 2010;


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

INSERT INTO num_exp_div VALUES (3,0,'NaN');


Question: What is the total TEU handling for each port in the cargo_handling table, ordered by handling date in descending order?

CREATE TABLE cargo_handling (port_id INT, port_name VARCHAR(50), teu_count INT, handling_date DATE); INSERT INTO cargo_handling (port_id, port_name, teu_count, handling_date) VALUES (1, 'Port_A', 2000, '2022-01-03'), (2, 'Port_B', 3000, '2022-01-02'), (3, 'Port_C', 1000, '2022-01-01');

SELECT port_name, SUM(teu_count) OVER (PARTITION BY port_name ORDER BY handling_date DESC) as total_teu FROM cargo_handling;


Question: What is the policy number, policyholder name, and issue date for policies issued in California?

CREATE TABLE policies (policy_number INT, policyholder_name TEXT, issue_date DATE, state TEXT); INSERT INTO policies (policy_number, policyholder_name, issue_date, state) VALUES (12345, 'John Doe', '2021-06-01', 'California');

SELECT policy_number, policyholder_name, issue_date FROM policies WHERE state = 'California';


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

SELECT '294277-01-01 00:00:00+00'::timestamptz;  -- out of range
SELECT '294277-12-31 16:00:00-08'::timestamptz;  -- out of range

-- Demonstrate functions and operators
SELECT d1 FROM TIMESTAMPTZ_TBL
   WHERE d1 > timestamp with time zone '1997-01-02';

SELECT count(*) FROM (SELECT '294277-01-01 00:00:00+00'::timestamptz;  -- out of range
SELECT '294277-12-31 16:00:00-08'::timestamptz;  -- out of range

-- Demonstrate functions and operators
SELECT d1 FROM TIMESTAMPTZ_TBL
   WHERE d1 > timestamp with time zone '1997-01-02') AS _sub;


Question: Generate PostgreSQL SQL for: What is the average gold total for nations ranked 6 with 1 total medal and 1 bronze medal?

CREATE TABLE table_name_90 (gold INTEGER, bronze VARCHAR, total VARCHAR, rank VARCHAR)

SELECT AVG(gold) FROM table_name_90 WHERE total = 1 AND rank = '6' AND bronze > 1;


Question: Generate PostgreSQL SQL for: What is the total Lane with a Mark of 47.02, and a Heat higher than 5?

CREATE TABLE table_name_64 (lane INTEGER, mark VARCHAR, heat VARCHAR)

SELECT SUM(lane) FROM table_name_64 WHERE mark = '47.02' AND heat > 5;


Question: Write the DDL statement from PostgreSQL regression test 'publication' (example 90).

CREATE TABLE testpub_parted1 (LIKE testpub_parted);

Explanation: DDL from PostgreSQL core regression test for Publication.


Question: How many volunteers and total donation amount for each program in India?

CREATE TABLE Donations (id INT, donation_amount DECIMAL(10,2), donation_date DATE, program VARCHAR(50), country VARCHAR(50)); CREATE TABLE Volunteers (id INT, volunteer_name VARCHAR(50), program VARCHAR(50), country VARCHAR(50)); INSERT INTO Donations (id, donation_amount, donation_date, program, country) VALUES (1, 50.00, '2021-02-01', 'Women Empowerment', 'India'); INSERT INTO Donations (id, donation_amount, donation_date, program, country) VALUES (2, 150.00, '2021-02-02', 'Education', 'India'); INSERT INTO Volunteers (id, volunteer_name, program, country) VALUES (1, 'Deepika Singh', 'Women Empowerment', 'India'); INSERT INTO Volunteers (id, volunteer_name, program, country) VALUES (2, 'Ravi Kumar', 'Education', 'India');

SELECT p.program, COUNT(DISTINCT v.volunteer_name) as num_volunteers, SUM(d.donation_amount) as total_donations FROM Donations d INNER JOIN Volunteers v ON d.program = v.program INNER JOIN Programs p ON d.program = p.program WHERE d.country = 'India' GROUP BY p.program;


Question: Delete the record for 'ManufacturerE' from the circular_economy_initiatives table, as they are no longer participating.

CREATE TABLE circular_economy_initiatives (initiative_id INT, manufacturer_name TEXT, initiative_description TEXT); INSERT INTO circular_economy_initiatives (initiative_id, manufacturer_name, initiative_description) VALUES (1, 'ManufacturerA', 'Recycling Program'), (2, 'ManufacturerB', 'Remanufacturing Program'), (3, 'ManufacturerC', 'Waste Reduction Program'), (4, 'ManufacturerE', 'Upcycling Program');

DELETE FROM circular_economy_initiatives WHERE manufacturer_name = 'ManufacturerE';


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

select x, y
  from (select t1.unique1 as x, t1.unique2 as y from tenk1 t1, tenk1 t2) as t
  where x = 1
  group by grouping sets (x, y)
  order by 1, 2;

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

SELECT count(*) FROM (select x, y
  from (select t1.unique1 as x, t1.unique2 as y from tenk1 t1, tenk1 t2) as t
  where x = 1
  group by grouping sets (x, y)
  order by 1, 2) AS _sub;


Question: What is the average speed of public buses in CityA?

CREATE TABLE CityA_BusRoutes (route_id INT, avg_speed FLOAT, vehicle_type VARCHAR(20)); INSERT INTO CityA_BusRoutes (route_id, avg_speed, vehicle_type) VALUES (1, 45.6, 'Bus'), (2, 38.2, 'Bus'), (3, 48.7, 'Bus');

SELECT AVG(avg_speed) FROM CityA_BusRoutes WHERE vehicle_type = 'Bus';


Question: PostgreSQL Textsearch: show example 74.

SELECT ts_lexize('english_stem', 'stars'); ts_lexize ----------- {star} SELECT ts_lexize('english_stem', 'a'); ts_lexize ----------- {};

Explanation: Example from PostgreSQL documentation on Textsearch.


Question: Generate PostgreSQL SQL for: What is the release date for Destiny of the Daleks?

CREATE TABLE table_1681535_1 (release_date VARCHAR, title VARCHAR)

SELECT release_date FROM table_1681535_1 WHERE title = 'Destiny of the Daleks';


Question: Generate PostgreSQL SQL for: Name the 2010 for 2006 of 2r

SELECT 2010 FROM table_name_9 WHERE 2006 = '2r';


Question: Generate PostgreSQL SQL for: On what date is the winning team Abt Sportsline and pole position Mattias Ekström in the Circuit Ricardo Tormo , Valencia?

CREATE TABLE table_26267607_2 (date VARCHAR, circuit VARCHAR, winning_team VARCHAR, pole_position VARCHAR)

SELECT date FROM table_26267607_2 WHERE winning_team = 'Abt Sportsline' AND pole_position = 'Mattias Ekström' AND circuit = 'circuit Ricardo Tormo , Valencia';


Question: Generate PostgreSQL SQL for: What character is played by dani harmer for under 23 episodes?

CREATE TABLE table_name_51 (character VARCHAR, episodes VARCHAR, actor VARCHAR)

SELECT character FROM table_name_51 WHERE episodes < 23 AND actor = 'dani harmer';


Question: Insert new record into 'geological_survey' table with 'survey_date' as '2022-04-22' and 'survey_type' as 'Ground Penetrating Radar'

CREATE TABLE geological_survey (survey_date DATE, survey_type VARCHAR(255), PRIMARY KEY (survey_date, survey_type));

INSERT INTO geological_survey (survey_date, survey_type) VALUES ('2022-04-22', 'Ground Penetrating Radar');


Question: Generate PostgreSQL SQL for: What is the main use for the structure listed in walker city, iowa?

CREATE TABLE table_name_25 (main_use VARCHAR, town VARCHAR)

SELECT main_use FROM table_name_25 WHERE town = 'walker city, iowa';


Question: Generate PostgreSQL SQL for: What is the set 5 if the Date is jun 7, and a Set 4 is 21-25?

CREATE TABLE table_name_65 (set_5 VARCHAR, date VARCHAR, set_4 VARCHAR)

SELECT set_5 FROM table_name_65 WHERE date = 'jun 7' AND set_4 = '21-25';


Question: List all the unique organizations involved in disaster_response efforts and their respective total spending.

CREATE TABLE disaster_response (org_id INT, org_name VARCHAR(50), country VARCHAR(50), spending DECIMAL(10,2)); INSERT INTO disaster_response (org_id, org_name, country, spending) VALUES (1, 'UNICEF', 'USA', 500000.00), (2, 'Red Cross', 'Canada', 350000.00);

SELECT DISTINCT org_name, SUM(spending) FROM disaster_response GROUP BY org_name;


Question: Generate PostgreSQL SQL for: what is the fee for ankaragücü previous club

CREATE TABLE table_27998152_1 (fee VARCHAR, previous_club VARCHAR)

SELECT fee FROM table_27998152_1 WHERE previous_club = 'Ankaragücü';


Question: Generate PostgreSQL SQL for: What do the notes say for 1989 May 7?

CREATE TABLE table_name_32 (notes VARCHAR, date VARCHAR)

SELECT notes FROM table_name_32 WHERE date = '1989 may 7';


Question: Generate PostgreSQL SQL for: What is the bowling score of season 1907?

CREATE TABLE table_name_23 (bowling VARCHAR, season VARCHAR)

SELECT bowling FROM table_name_23 WHERE season = '1907';


Question: Generate PostgreSQL SQL for: What is the Yogi Bear that aired on 1959.12.21?

CREATE TABLE table_19860361_3 (yogi_bear VARCHAR, air_date VARCHAR)

SELECT yogi_bear FROM table_19860361_3 WHERE air_date = '1959.12.21';


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

--
-- Check argument name is used instead of $n in error message
--
CREATE FUNCTION fx(x WSlot) RETURNS void AS $$
BEGIN
  GET DIAGNOSTICS x = ROW_COUNT;
  RETURN;
END; $$ LANGUAGE plpgsql;

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


Question: Generate PostgreSQL SQL for: Which Born-Died has a Term start of 4 november 1943?

CREATE TABLE table_name_52 (born_died VARCHAR, term_start VARCHAR)

SELECT born_died FROM table_name_52 WHERE term_start = '4 november 1943';


Question: What is the average rating of films produced in Spain and Italy?

CREATE TABLE Films (film_id INT, title VARCHAR(255), release_date DATE, rating FLOAT, production_country VARCHAR(50)); INSERT INTO Films (film_id, title, release_date, rating, production_country) VALUES (1, 'Movie1', '2000-01-01', 7.5, 'Spain'), (2, 'Movie2', '2005-01-01', 8.2, 'Italy'), (3, 'Movie3', '2010-01-01', 6.8, 'France');

SELECT AVG(rating) FROM Films WHERE production_country IN ('Spain', 'Italy');


Question: Generate PostgreSQL SQL for: What are the payment date of the payment with amount paid higher than 300 or with payment type is 'Check'

CREATE TABLE payments (payment_date VARCHAR, amount_paid VARCHAR, payment_type_code VARCHAR)

SELECT payment_date FROM payments WHERE amount_paid > 300 OR payment_type_code = 'Check';


Question: Generate PostgreSQL SQL for: What is the score vs. Protoss when the score vs. Terran is 10 wins?

CREATE TABLE table_name_97 (vs_protoss VARCHAR, vs_terran VARCHAR)

SELECT vs_protoss FROM table_name_97 WHERE vs_terran = '10 wins';


Question: What is the total revenue for the 'Organic Greens' restaurant?

CREATE TABLE Restaurants (restaurant_name TEXT, revenue FLOAT); INSERT INTO Restaurants (restaurant_name, revenue) VALUES ('Urban Plate', 45000.0), ('Organic Greens', 38000.0), ('Fiesta Mex', 52000.0);

SELECT revenue FROM Restaurants WHERE restaurant_name = 'Organic Greens';


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

INSERT INTO test_bytea VALUES ('a'),('ab'),('abc'),('abb'),('axy'),('xyz');

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


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

select * from (x left join y on (x1 = y1)) left join x xx(xx1,xx2)
on (x1 = xx1) where (xx2 is not null);

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

SELECT count(*) FROM (select * from (x left join y on (x1 = y1)) left join x xx(xx1,xx2)
on (x1 = xx1) where (xx2 is not null)) AS _sub;


Question: What is the name and number of schools in each city?

CREATE TABLE cities (id INT, name VARCHAR(255)); CREATE TABLE schools (id INT, city_id INT, name VARCHAR(255), number INT);

SELECT c.name, s.number FROM cities c JOIN schools s ON c.id = s.city_id;


Question: Find the average funding amount for companies founded by individuals from Latin America

CREATE TABLE company_founding(id INT PRIMARY KEY, company_name VARCHAR(100), founder_country VARCHAR(50), funding_amount INT); INSERT INTO company_founding VALUES (1, 'Acme Inc', 'Brazil', 1000000); INSERT INTO company_founding VALUES (2, 'Beta Corp', 'Argentina', 2000000); INSERT INTO company_founding VALUES (3, 'Charlie LLC', 'Canada', 500000); INSERT INTO company_founding VALUES (4, 'Delta Inc', 'Mexico', 750000);

SELECT AVG(funding_amount) FROM company_founding WHERE founder_country IN ('Brazil', 'Argentina', 'Mexico');


Question: Generate PostgreSQL SQL for: Gary Barnett who has been in 0 FA Cups plays what position?

CREATE TABLE table_name_7 (position VARCHAR, fa_cup_apps VARCHAR, name VARCHAR)

SELECT position FROM table_name_7 WHERE fa_cup_apps = '0' AND name = 'gary barnett';


Question: Write the DML statement from PostgreSQL regression test 'join' (example 64).

Explanation: DML from PostgreSQL core regression test for Join.


Question: Update the type of circular economy with ID 2 to 'Redesign'

CREATE SCHEMA manufacturing;CREATE TABLE circular_economy (id INT PRIMARY KEY, name TEXT, type TEXT);INSERT INTO circular_economy (id, name, type) VALUES (1, 'Circular Economy A', 'Reuse'); INSERT INTO circular_economy (id, name, type) VALUES (2, 'Circular Economy B', 'Reduce'); INSERT INTO circular_economy (id, name, type) VALUES (3, 'Circular Economy C', 'Repurpose');

UPDATE circular_economy SET type = 'Redesign' WHERE id = 2;


Question: What is the minimum number of public hospitals in the state of "Texas"?

CREATE TABLE hospitals (hospital_id INT, hospital_name TEXT, state TEXT, type TEXT); INSERT INTO hospitals (hospital_id, hospital_name, state, type) VALUES (1, 'Texas Medical Center', 'Texas', 'Public'), (2, 'Methodist Hospital', 'Texas', 'Private'), (3, 'Memorial Hermann Hospital', 'Texas', 'Public');

SELECT MIN(hospital_id) FROM hospitals WHERE state = 'Texas' AND type = 'Public';


Question: Show a SQL definition from the pglogical project (pglogical--2.2.1, item 43).

CREATE FUNCTION pglogical.pglogical_gen_slot_name(name, name, name)
RETURNS name
IMMUTABLE STRICT LANGUAGE c AS 'MODULE_PATHNAME';

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


Question: What are the names and research interests of female professors in the Computer Science department?

CREATE TABLE professors (id INT, name TEXT, gender TEXT, research_interest TEXT); INSERT INTO professors (id, name, gender, research_interest) VALUES (1, 'Alice', 'Female', 'Machine Learning'); INSERT INTO professors (id, name, gender, research_interest) VALUES (2, 'Bob', 'Male', 'Data Science');

SELECT name, research_interest FROM professors WHERE gender = 'Female' AND department = 'Computer Science';


Question: Generate PostgreSQL SQL for: When North Melbourne played as the away team, what was the crowd numbers?

CREATE TABLE table_name_56 (crowd VARCHAR, away_team VARCHAR)

SELECT crowd FROM table_name_56 WHERE away_team = 'north melbourne';


Question: What is the total amount of water treated in wastewater treatment plants in the New York region in the last month?

CREATE TABLE wastewater_treatment (region VARCHAR(20), plant_id INT, treated_water FLOAT, timestamp TIMESTAMP); INSERT INTO wastewater_treatment (region, plant_id, treated_water, timestamp) VALUES ('New York', 1, 500000, '2022-01-01 10:00:00'), ('New York', 2, 600000, '2022-02-01 10:00:00');

SELECT SUM(treated_water) FROM wastewater_treatment WHERE region = 'New York' AND timestamp BETWEEN DATE_SUB(CURRENT_TIMESTAMP, INTERVAL 1 MONTH) AND CURRENT_TIMESTAMP;


Question: Generate PostgreSQL SQL for: What is the location where aaron grundy was the loser?

CREATE TABLE table_name_27 (location VARCHAR, loser VARCHAR)

SELECT location FROM table_name_27 WHERE loser = 'aaron grundy';


Question: Which manufacturers in Sweden have invested more than 400,000 in Industry 4.0?

CREATE TABLE manufacturers (manufacturer_id INT, name VARCHAR(255), location VARCHAR(255), industry_4_0_investment FLOAT); INSERT INTO manufacturers (manufacturer_id, name, location, industry_4_0_investment) VALUES (1, 'Smart Machines', 'Germany', 350000), (2, 'Eco Engines', 'Sweden', 420000), (3, 'Precision Robotics', 'Japan', 500000), (4, 'Green Innovations', 'Sweden', 375000), (5, 'FutureTech', 'USA', 410000);

SELECT m.name, m.industry_4_0_investment FROM manufacturers m WHERE m.location = 'Sweden' AND m.industry_4_0_investment > 400000;


Question: Show the total fuel efficiency for vessels with IDs "VT-123" and "VT-456" from the "vessel_performance" table.

CREATE TABLE vessel_performance (id INT PRIMARY KEY, vessel_id INT, max_speed FLOAT, avg_speed FLOAT, fuel_efficiency FLOAT);

SELECT SUM(fuel_efficiency) FROM vessel_performance WHERE vessel_id IN (123, 456);


Question: Insert new soil moisture data for farm_id 987

CREATE TABLE soil_moisture (id INT, farm_id INT, moisture_level FLOAT, measurement_date DATE);

INSERT INTO soil_moisture (id, farm_id, moisture_level, measurement_date) VALUES (5, 987, 45.6, '2022-06-01');


Question: Generate PostgreSQL SQL for: What is the lowest laps that has a manufacturer of yamaha, and a time/retired of +1:08.312, and a grid less than 20?

CREATE TABLE table_name_4 (laps INTEGER, grid VARCHAR, manufacturer VARCHAR, time_retired VARCHAR)

SELECT MIN(laps) FROM table_name_4 WHERE manufacturer = 'yamaha' AND time_retired = '+1:08.312' AND grid < 20;


Question: Generate PostgreSQL SQL for: What engine has an output of ps (kw; hp) @4700 rpm?

CREATE TABLE table_name_85 (engine VARCHAR, output VARCHAR)

SELECT engine FROM table_name_85 WHERE output = 'ps (kw; hp) @4700 rpm';


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

SELECT jsonb_typeof('{"c":3,"p":"o"}') AS object;

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

SELECT count(*) FROM (SELECT jsonb_typeof('{"c":3,"p":"o"}') AS object) AS _sub;


Question: What is the total CO2 emission for each factory in the Western region by country?

CREATE TABLE factories (factory_id INT, factory_name VARCHAR(50), country VARCHAR(50), co2_emission INT); CREATE TABLE country_regions (country VARCHAR(50), region VARCHAR(50));

SELECT country, SUM(co2_emission) FROM factories JOIN country_regions ON factories.country = country_regions.country WHERE region = 'Western' GROUP BY country;


Question: How many urban agriculture initiatives are there in 'Toronto'?

CREATE TABLE urban_agriculture_initiatives (id INT, name TEXT, location TEXT); INSERT INTO urban_agriculture_initiatives (id, name, location) VALUES (1, 'Initiative A', 'Toronto'), (2, 'Initiative B', 'Montreal'), (3, 'Initiative C', 'Toronto');

SELECT COUNT(*) FROM urban_agriculture_initiatives WHERE location = 'Toronto';


Question: Generate PostgreSQL SQL for: What is the production code for the episode written by  J. H. Wyman & Jeff Pinkner?

CREATE TABLE table_24649082_1 (production_code VARCHAR, written_by VARCHAR)

SELECT production_code FROM table_24649082_1 WHERE written_by = 'J. H. Wyman & Jeff Pinkner';


Question: Generate PostgreSQL SQL for: What was the surface in 1981?

CREATE TABLE table_name_56 (surface VARCHAR, date VARCHAR)

SELECT surface FROM table_name_56 WHERE date = 1981;


Question: Delete all records pertaining to organizations not focused on poverty alleviation.

CREATE TABLE organizations (id INT, name VARCHAR(255), focus VARCHAR(255)); INSERT INTO organizations (id, name, focus) VALUES (1, 'Against Poverty', 'Poverty Alleviation'), (2, 'Arts and Culture Fund', 'Arts and Culture'), (3, 'Climate Foundation', 'Climate Change');

DELETE FROM donations WHERE donations.organization_id NOT IN (SELECT id FROM organizations WHERE organizations.focus = 'Poverty Alleviation'); DELETE FROM organizations WHERE organizations.focus != 'Poverty Alleviation';


Question: Generate PostgreSQL SQL for: What week did the contestant finish in the bottom 2 with a Celine Dion song?

CREATE TABLE table_name_41 (week VARCHAR, status VARCHAR, artist VARCHAR)

SELECT week FROM table_name_41 WHERE status = 'bottom 2' AND artist = 'celine dion';


Question: Which online travel agencies have more than 50 bookings for resorts in the Caribbean?

CREATE TABLE online_travel_agency (id INT PRIMARY KEY, ota_name VARCHAR(50), hotel_name VARCHAR(50), region VARCHAR(50), bookings INT); INSERT INTO online_travel_agency (id, ota_name, hotel_name, region, bookings) VALUES (1, 'Travelocity', 'Caribbean Resort', 'Caribbean', 60), (2, 'Expedia', 'Mountain Lodge', 'Mountains', 45);

SELECT ota_name, SUM(bookings) FROM online_travel_agency WHERE region = 'Caribbean' GROUP BY ota_name HAVING SUM(bookings) > 50;


Question: List the unique court locations where legal aid was provided in Alberta and Manitoba in the last 5 years.

CREATE TABLE legal_aid_alberta (court_location VARCHAR(50), date DATE); INSERT INTO legal_aid_alberta VALUES ('Edmonton', '2022-02-01'), ('Calgary', '2021-06-15'), ('Red Deer', '2020-09-03'); CREATE TABLE legal_aid_manitoba (court_location VARCHAR(50), date DATE); INSERT INTO legal_aid_manitoba VALUES ('Winnipeg', '2022-03-10'), ('Brandon', '2021-12-20'), ('Thompson', '2020-07-25');

SELECT DISTINCT court_location FROM legal_aid_alberta WHERE date >= DATE_SUB(CURRENT_DATE, INTERVAL 5 YEAR) UNION ALL SELECT DISTINCT court_location FROM legal_aid_manitoba WHERE date >= DATE_SUB(CURRENT_DATE, INTERVAL 5 YEAR);


Question: What is the difference in average customer spending between customers in Mexico and Argentina?

CREATE TABLE CustomerSpendingMX (CustomerID INT, Country TEXT, AvgSpending DECIMAL(5,2)); INSERT INTO CustomerSpendingMX (CustomerID, Country, AvgSpending) VALUES (1, 'Mexico', 120.50), (2, 'Mexico', 110.50), (3, 'Mexico', 130.50), (4, 'Mexico', 90.50); CREATE TABLE CustomerSpendingAR (CustomerID INT, Country TEXT, AvgSpending DECIMAL(5,2)); INSERT INTO CustomerSpendingAR (CustomerID, Country, AvgSpending) VALUES (1, 'Argentina', 105.00), (2, 'Argentina', 115.00), (3, 'Argentina', 125.00), (4, 'Argentina', 135.00);

SELECT AVG(CSMX.AvgSpending) - AVG(CSA.AvgSpending) FROM CustomerSpendingMX CSMX, CustomerSpendingAR CSA WHERE CSMX.Country = 'Mexico' AND CSA.Country = 'Argentina';


Question: Display the number of cruelty-free and non-cruelty-free skincare products.

CREATE TABLE Products (id INT, name VARCHAR(50), type VARCHAR(20), cruelty_free BOOLEAN); INSERT INTO Products (id, name, type, cruelty_free) VALUES (1, 'Cleanser', 'Skincare', true), (2, 'Toner', 'Skincare', true), (3, 'Moisturizer', 'Skincare', false);

SELECT CASE WHEN cruelty_free = true THEN 'Cruelty-free' ELSE 'Non-cruelty-free' END as product_type, COUNT(*) as count FROM Products WHERE type = 'Skincare' GROUP BY product_type;


Question: What is the total revenue generated by virtual tours for each region?

CREATE TABLE tour (id INT, name TEXT, region TEXT, price INT); INSERT INTO tour (id, name, region, price) VALUES (1, 'Virtual Acropolis', 'Europe', 10); INSERT INTO tour (id, name, region, price) VALUES (2, 'Virtual Machu Picchu', 'South America', 15);

SELECT region, SUM(price) as total_revenue FROM tour WHERE name LIKE '%virtual%' GROUP BY region;


Question: What is the maximum CO2 emission reduction achieved by green building projects in Toronto, Canada, since 2015?

CREATE TABLE co2_reductions (id INT, city VARCHAR(20), country VARCHAR(20), year INT, co2_reduction FLOAT); INSERT INTO co2_reductions (id, city, country, year, co2_reduction) VALUES (1, 'Toronto', 'Canada', 2015, 1200), (2, 'Toronto', 'Canada', 2016, 1500), (3, 'Toronto', 'Canada', 2017, 1800), (4, 'Toronto', 'Canada', 2018, 2000);

SELECT MAX(co2_reduction) FROM co2_reductions WHERE city = 'Toronto' AND country = 'Canada' AND year >= 2015;


Question: Generate PostgreSQL SQL for: Which venue has a note of AM?

CREATE TABLE table_name_32 (venue VARCHAR, notes VARCHAR)

SELECT venue FROM table_name_32 WHERE notes = 'am';


Question: Generate PostgreSQL SQL for: What is South Africa's to par?

CREATE TABLE table_name_35 (to_par VARCHAR, country VARCHAR)

SELECT to_par FROM table_name_35 WHERE country = 'south africa';


Question: How many shared bicycles were available in Berlin on July 4, 2021?

CREATE TABLE shared_bicycles( bicycle_id INT, availability_status VARCHAR(50), availability_date DATE, city VARCHAR(50));

SELECT COUNT(*) FROM shared_bicycles WHERE availability_status = 'available' AND availability_date = '2021-07-04' AND city = 'Berlin';


Question: Generate PostgreSQL SQL for: Which average's against score has 2 as a difference and a lost of 5?

CREATE TABLE table_name_34 (against INTEGER, difference VARCHAR, lost VARCHAR)

SELECT AVG(against) FROM table_name_34 WHERE difference = '2' AND lost = 5;


Question: Generate PostgreSQL SQL for: What year did the Caphouse Colliery railway close?

CREATE TABLE table_name_79 (closed VARCHAR, name VARCHAR)

SELECT closed FROM table_name_79 WHERE name = 'caphouse colliery';


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

SELECT * FROM collate_test3 WHERE b >= 'BBC';

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

SELECT count(*) FROM (SELECT * FROM collate_test3 WHERE b >= 'BBC') AS _sub;


Question: What is the maximum number of likes for posts containing the hashtag "#veganfood" per month for the last two years?

CREATE TABLE posts (id INT, user_id INT, content TEXT, likes INT, timestamp DATETIME); INSERT INTO posts (id, user_id, content, likes, timestamp) VALUES (1, 1, 'Vegan food recipe', 350, '2020-01-01 10:00:00'), (2, 2, 'Delicious vegan meal', 180, '2020-01-05 15:30:00');

SELECT EXTRACT(MONTH FROM timestamp) AS month, MAX(likes) FROM posts JOIN hashtags ON posts.id = hashtags.post_id WHERE hashtag = '#veganfood' AND timestamp BETWEEN DATE_SUB(NOW(), INTERVAL 2 YEAR) AND NOW() GROUP BY month;


Question: Generate PostgreSQL SQL for: What is then engine when the notes state srt8?

CREATE TABLE table_name_91 (engine VARCHAR, notes VARCHAR)

SELECT engine FROM table_name_91 WHERE notes = 'srt8';


Question: What is the total number of cases handled by attorneys in the "public_defense" department, partitioned by the attorney's gender?

CREATE TABLE attorneys (attorney_id INT, name VARCHAR(50), department VARCHAR(50), gender VARCHAR(10)); INSERT INTO attorneys (attorney_id, name, department, gender) VALUES (1, 'John Doe', 'public_defense', 'male'); INSERT INTO attorneys (attorney_id, name, department, gender) VALUES (2, 'Jane Smith', 'public_defense', 'female'); CREATE TABLE cases (case_id INT, attorney_id INT); INSERT INTO cases (case_id, attorney_id) VALUES (1, 1); INSERT INTO cases (case_id, attorney_id) VALUES (2, 1); INSERT INTO cases (case_id, attorney_id) VALUES (3, 2);

SELECT department, gender, COUNT(*) OVER (PARTITION BY department, gender) as total_cases FROM attorneys INNER JOIN cases ON attorneys.attorney_id = cases.attorney_id WHERE department = 'public_defense';


Question: What is the most common art medium for artists from Africa?

CREATE TABLE artists (id INT, name TEXT, country TEXT, medium TEXT); INSERT INTO artists (id, name, country, medium) VALUES (1, 'John Doe', 'Nigeria', 'Sculpture'), (2, 'Jane Smith', 'Kenya', 'Painting'), (3, 'Mohamed Ahmed', 'Egypt', 'Sculpture'), (4, 'Aisha Mohamed', 'Senegal', 'Painting'), (5, 'Pedro Gonzales', 'South Africa', 'Drawing');

SELECT country, medium, COUNT(*) AS frequency FROM artists WHERE country LIKE '%Africa%' GROUP BY country, medium ORDER BY frequency DESC LIMIT 1;


Question: Write the DDL statement from PostgreSQL regression test 'groupingsets' (example 179).

create table gs_hash_1 as
select g100, g10, sum(g::numeric), count(*), max(g::text)
from gs_data_1 group by cube (g1000, g100,g10);

Explanation: DDL from PostgreSQL core regression test for Groupingsets.


Question: What is the total number of episodes and average runtime for TV shows in the reality genre?

CREATE TABLE tv_shows_data (id INT, title VARCHAR(255), genre VARCHAR(255), episodes INT, runtime INT); INSERT INTO tv_shows_data (id, title, genre, episodes, runtime) VALUES (1, 'Show1', 'Reality', 15, 30), (2, 'Show2', 'Reality', 20, 45), (3, 'Show3', 'Documentary', 10, 60), (4, 'Show4', 'Reality', 12, 60), (5, 'Show5', 'Drama', 20, 60);

SELECT genre, AVG(runtime) AS avg_runtime, SUM(episodes) AS total_episodes FROM tv_shows_data WHERE genre = 'Reality' GROUP BY genre;


Question: What is the total cost of ingredients for the 'Veggie Delight' sandwich?

CREATE TABLE Ingredients (id INT, item_name VARCHAR(50), cost DECIMAL(5,2)); INSERT INTO Ingredients VALUES (1, 'Lettuce', 0.25), (2, 'Tomato', 0.30), (3, 'Cucumber', 0.20), (4, 'Avocado', 0.50), (5, 'Bread', 0.75);

SELECT SUM(cost) FROM Ingredients WHERE item_name = 'Veggie Delight';


Question: How many evidence-based policy making projects were completed in India since 2010?

CREATE TABLE EvidenceBasedPolicy (id INT, project_name VARCHAR(50), country VARCHAR(50), start_date DATE, end_date DATE);

SELECT COUNT(*) FROM EvidenceBasedPolicy WHERE country = 'India' AND start_date <= '2010-01-01' AND end_date >= '2010-12-31';


Question: Generate PostgreSQL SQL for: On what date was the away team Sheffield Wednesday?

CREATE TABLE table_name_51 (date VARCHAR, away_team VARCHAR)

SELECT date FROM table_name_51 WHERE away_team = 'sheffield wednesday';


Question: Generate PostgreSQL SQL for: Name the stage for 08:46

CREATE TABLE table_name_85 (stage VARCHAR, time__eest_ VARCHAR)

SELECT stage FROM table_name_85 WHERE time__eest_ = '08:46';


Question: Generate PostgreSQL SQL for: Name the record for score of  l 93–104 (ot)

CREATE TABLE table_17288825_8 (record VARCHAR, score VARCHAR)

SELECT record FROM table_17288825_8 WHERE score = 'L 93–104 (OT)';


Question: PostgreSQL regression test 'stats': Write the SELECT query (example 359).

SELECT sum(reads) AS io_sum_local_before_reads
  FROM pg_stat_io WHERE context = 'normal' AND object = 'temp relation' \gset
-- Read in evicted buffers, generating reads.
SELECT COUNT(*) FROM test_io_local;

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

SELECT count(*) FROM (SELECT sum(reads) AS io_sum_local_before_reads
  FROM pg_stat_io WHERE context = 'normal' AND object = 'temp relation' \gset
-- Read in evicted buffers, generating reads.
SELECT COUNT(*) FROM test_io_local) AS _sub;


Question: Generate PostgreSQL SQL for: Name the sumof points for year less than 1994 and chassis of lola lc89b

CREATE TABLE table_name_47 (points INTEGER, year VARCHAR, chassis VARCHAR)

SELECT SUM(points) FROM table_name_47 WHERE year < 1994 AND chassis = 'lola lc89b';


Question: How many users registered per month in the 'RPG' genre for the last year?

CREATE TABLE Registrations (RegistrationID INT, UserID INT, RegistrationDate DATETIME, Game VARCHAR(50)); INSERT INTO Registrations (RegistrationID, UserID, RegistrationDate, Game) VALUES (1, 1, '2021-12-10', 'RPG'), (2, 2, '2022-01-05', 'RPG'), (3, 3, '2022-02-25', 'FPS');

SELECT MONTH(RegistrationDate), YEAR(RegistrationDate), COUNT(*) as UsersRegistered FROM Registrations WHERE Game = 'RPG' AND RegistrationDate >= DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR) GROUP BY YEAR(RegistrationDate), MONTH(RegistrationDate);


Question: What is the average water usage in Mumbai and Delhi?

CREATE TABLE WaterUsage (Location VARCHAR(100), Usage FLOAT, Date DATE); INSERT INTO WaterUsage (Location, Usage, Date) VALUES ('Mumbai', 150, '2022-01-01'), ('Delhi', 200, '2022-01-01');

SELECT Location, AVG(Usage) FROM WaterUsage GROUP BY Location;


Question: Generate PostgreSQL SQL for: What was the result on October 20, 2002?

CREATE TABLE table_name_87 (result VARCHAR, date VARCHAR)

SELECT result FROM table_name_87 WHERE date = 'october 20, 2002';


Question: Generate PostgreSQL SQL for: Which ship was launched from Devonport, Devon?

CREATE TABLE table_name_30 (ship VARCHAR, location VARCHAR)

SELECT ship FROM table_name_30 WHERE location = 'devonport, devon';


Question: Generate PostgreSQL SQL for: What is the muzzle device with a 1:7 barrel twist and a stock 4th generation?

CREATE TABLE table_name_47 (muzzle_device VARCHAR, barrel_twist VARCHAR, stock VARCHAR)

SELECT muzzle_device FROM table_name_47 WHERE barrel_twist = '1:7' AND stock = '4th generation';


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

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

SELECT count(*) FROM (SELECT U&'wrong: \db99\0061') AS _sub;


Question: Generate PostgreSQL SQL for: What Silver has a Golf of Li AO?

CREATE TABLE table_name_20 (silver VARCHAR, gold VARCHAR)

SELECT silver FROM table_name_20 WHERE gold = 'li ao';


Question: How many graduate students in the Engineering department come from each country?

CREATE TABLE student_demographics (id INT, student_id INT, country VARCHAR(50), department VARCHAR(50)); INSERT INTO student_demographics (id, student_id, country, department) VALUES (1, 1, 'USA', 'Engineering'), (2, 2, 'Canada', 'Engineering'), (3, 3, 'Mexico', 'Engineering');

SELECT country, COUNT(DISTINCT student_id) FROM student_demographics WHERE department = 'Engineering' GROUP BY country;


Question: Generate PostgreSQL SQL for: When cardboard boxes is segment c what is segment a?

CREATE TABLE table_15187735_5 (segment_a VARCHAR, segment_c VARCHAR)

SELECT segment_a FROM table_15187735_5 WHERE segment_c = 'Cardboard Boxes';


Question: Generate PostgreSQL SQL for: What is the smallest Wins with a Position of 20th, and Poles smaller than 0?

CREATE TABLE table_name_19 (wins INTEGER, position VARCHAR, poles VARCHAR)

SELECT MIN(wins) FROM table_name_19 WHERE position = '20th' AND poles < 0;


Question: Generate PostgreSQL SQL for: When was the game with the loss of Moore (0-1)?

CREATE TABLE table_name_82 (date VARCHAR, loss VARCHAR)

SELECT date FROM table_name_82 WHERE loss = 'moore (0-1)';


Question: Generate PostgreSQL SQL for: How many episodes were seen by 0.67 million US viewers on their original air dates?

CREATE TABLE table_13336122_7 (original_air_date VARCHAR, us_viewers__million_ VARCHAR)

SELECT COUNT(original_air_date) FROM table_13336122_7 WHERE us_viewers__million_ = '0.67';


Question: Generate PostgreSQL SQL for: Which fault log included the most number of faulty parts? List the fault log id, description and record time.

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

SELECT T1.fault_log_entry_id, T1.fault_description, T1.fault_log_entry_datetime FROM Fault_Log AS T1 JOIN Fault_Log_Parts AS T2 ON T1.fault_log_entry_id = T2.fault_log_entry_id GROUP BY T1.fault_log_entry_id ORDER BY COUNT(*) DESC LIMIT 1;


Question: PostgreSQL Indices: show example 12.

CREATE INDEX people_names ON people ((first_name || ' ' || last_name));

Explanation: Example from PostgreSQL documentation on Indices.


Question: Show permit data for projects with permit numbers greater than 500?

CREATE TABLE permit_data (id INT, project VARCHAR(50), permit_number INT, start_date DATE); INSERT INTO permit_data (id, project, permit_number, start_date) VALUES (1, 'Office Building', 450, '2019-12-20'), (2, 'Residential Apartments', 551, '2021-03-01'), (3, 'School', 333, '2020-05-15');

SELECT * FROM permit_data WHERE permit_number > 500;


Question: Generate PostgreSQL SQL for: What assists has the Team SMU and the total points of 85?

CREATE TABLE table_name_14 (assists VARCHAR, team VARCHAR, total_points VARCHAR)

SELECT assists FROM table_name_14 WHERE team = 'smu' AND total_points = '85';


Question: Generate PostgreSQL SQL for: What is the total number of races when there was more than 1 pole, and the fastest number of laps was less than 4?

CREATE TABLE table_name_8 (races INTEGER, poles VARCHAR, fastest_laps VARCHAR)

SELECT SUM(races) FROM table_name_8 WHERE poles > 1 AND fastest_laps < 4;


Question: Generate PostgreSQL SQL for: Name the rank on channel for pilot

CREATE TABLE table_24222929_4 (rank_on_channel VARCHAR, title VARCHAR)

SELECT rank_on_channel FROM table_24222929_4 WHERE title = 'Pilot';


Question: Generate PostgreSQL SQL for: How many original titles did Marriage Italian-Style have?

CREATE TABLE table_10321805_1 (original_title VARCHAR, film_title_used_in_nomination VARCHAR)

SELECT COUNT(original_title) FROM table_10321805_1 WHERE film_title_used_in_nomination = 'Marriage Italian-Style';


Question: Generate PostgreSQL SQL for: what is the dadar xi b where pifa colaba is sporting options?

CREATE TABLE table_28759261_5 (dadar_xi_‘b’ VARCHAR, pifa_colaba_fc_u_17 VARCHAR)

SELECT dadar_xi_‘b’ FROM table_28759261_5 WHERE pifa_colaba_fc_u_17 = 'Sporting Options';


Question: Compare sales quantities between 'EcoStitch' and 'FairFashion' across all materials.

CREATE TABLE SupplierSales (SaleID INT, SupplierName TEXT, Material TEXT, Quantity INT); INSERT INTO SupplierSales (SaleID, SupplierName, Material, Quantity) VALUES (4, 'EcoStitch', 'Silk', 10), (5, 'EcoStitch', 'Cotton', 20), (6, 'FairFashion', 'Silk', 15), (7, 'FairFashion', 'Cotton', 25);

SELECT s1.SupplierName, SUM(s1.Quantity) - SUM(s2.Quantity) FROM SupplierSales s1 INNER JOIN SupplierSales s2 ON s1.Material = s2.Material AND (s1.SupplierName = 'EcoStitch' AND s2.SupplierName = 'FairFashion') GROUP BY s1.SupplierName;


Question: Write the DML statement from PostgreSQL regression test 'xml' (example 2).

INSERT INTO xmltest VALUES (1, '<value>one</value>');

Explanation: DML from PostgreSQL core regression test for Xml.


Question: What is the total amount of climate finance provided to countries in the Asia-Pacific region for climate adaptation projects in 2020?

CREATE TABLE climate_finance (year INT, region VARCHAR(50), funding_type VARCHAR(50), amount INT);INSERT INTO climate_finance (year, region, funding_type, amount) VALUES (2020, 'Asia-Pacific', 'climate adaptation', 15000000);

SELECT SUM(amount) FROM climate_finance WHERE year = 2020 AND region = 'Asia-Pacific' AND funding_type = 'climate adaptation';


Question: Generate PostgreSQL SQL for: Which song has Drunkard Groom listed as additional information?

CREATE TABLE table_2528382_1 (song VARCHAR, additional_info VARCHAR)

SELECT song FROM table_2528382_1 WHERE additional_info = 'Drunkard Groom';


Question: Generate PostgreSQL SQL for: What is the percent for in manitoba?

CREATE TABLE table_120778_1 (percent_for VARCHAR, jurisdiction VARCHAR)

SELECT percent_for FROM table_120778_1 WHERE jurisdiction = 'Manitoba';


Question: What is the maximum revenue generated by virtual tours in Spain?

CREATE TABLE virtual_tours_spain (tour_id INT, tour_name TEXT, country TEXT, revenue FLOAT); INSERT INTO virtual_tours_spain (tour_id, tour_name, country, revenue) VALUES (1, 'Sagrada Familia Virtual Tour', 'Spain', 25000), (2, 'Alhambra Virtual Tour', 'Spain', 30000);

SELECT MAX(revenue) FROM virtual_tours_spain WHERE country = 'Spain';


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

CREATE TABLE grad_students (id INT, name TEXT, department TEXT, gpa DECIMAL(3,2)); INSERT INTO grad_students (id, name, department, gpa) VALUES (1, 'John Doe', 'Physics', 3.8); INSERT INTO grad_students (id, name, department, gpa) VALUES (2, 'Jane Smith', 'Physics', 3.6);

SELECT AVG(gpa) FROM grad_students WHERE department = 'Physics';


Question: What is the total number of properties in urban areas with inclusive housing policies and their average price?

CREATE TABLE property (id INT, price INT, area VARCHAR(255), has_inclusive_policy BOOLEAN); INSERT INTO property (id, price, area, has_inclusive_policy) VALUES (1, 200000, 'urban', true), (2, 300000, 'rural', false);

SELECT SUM(price), AVG(price) FROM property WHERE area = 'urban' AND has_inclusive_policy = true;


Question: Who are the farmers that raised animals in 'region1' and what was the total quantity of animals?

CREATE TABLE farmer (farmer_id INT, farmer_name TEXT, region TEXT); INSERT INTO farmer (farmer_id, farmer_name, region) VALUES (1, 'FarmerA', 'region1'), (2, 'FarmerB', 'region2'), (3, 'FarmerC', 'region2'); CREATE TABLE animal_rearing (rearing_id INT, farmer_id INT, animal_type TEXT, quantity INT); INSERT INTO animal_rearing (rearing_id, farmer_id, animal_type, quantity) VALUES (1, 1, 'Cattle', 10), (2, 1, 'Chickens', 50), (3, 2, 'Pigs', 20), (4, 3, 'Goats', 30);

SELECT f.farmer_name, SUM(ar.quantity) as total_animals FROM farmer f INNER JOIN animal_rearing ar ON f.farmer_id = ar.farmer_id WHERE f.region = 'region1' GROUP BY f.farmer_name;


Question: What are the total expenses for restorative justice programs in the state of New York?

CREATE TABLE restorative_justice_programs (program_id INT, program_name TEXT, state TEXT, expenses DECIMAL(10,2)); INSERT INTO restorative_justice_programs (program_id, program_name, state, expenses) VALUES (1, 'Victim-Offender Mediation', 'New York', 50000), (2, 'Restorative Circles', 'New York', 35000), (3, 'Peacemaking Circles', 'New York', 75000);

SELECT SUM(expenses) FROM restorative_justice_programs WHERE state = 'New York';


Question: Generate PostgreSQL SQL for: What was the average when the strike rate is 75.78?

CREATE TABLE table_26041144_10 (average VARCHAR, strike_rate VARCHAR)

SELECT average FROM table_26041144_10 WHERE strike_rate = '75.78';


Question: Which AI safety measures have a higher than average transparency rating?

CREATE TABLE SafetyMeasures (id INT, measure VARCHAR(255), transparency_rating DECIMAL(5,2)); INSERT INTO SafetyMeasures (id, measure, transparency_rating) VALUES (1, 'AI Risk Assessment', 8.00), (2, 'AI Incident Response', 9.00), (3, 'AI Monitoring', 8.50);

SELECT measure FROM SafetyMeasures WHERE transparency_rating > (SELECT AVG(transparency_rating) FROM SafetyMeasures);


Question: Generate PostgreSQL SQL for: What date was the episode with production code 176265 aired?

CREATE TABLE table_14889988_1 (original_air_date VARCHAR, production_code VARCHAR)

SELECT original_air_date FROM table_14889988_1 WHERE production_code = 176265;


Question: What are the average home run distances for athletes in the MLB?

CREATE TABLE mlb_home_runs (player_id INT, player_name VARCHAR(50), home_run_distance FLOAT); INSERT INTO mlb_home_runs (player_id, player_name, home_run_distance) VALUES (1, 'Aaron Judge', 449.6), (2, 'Giancarlo Stanton', 434.7), (3, 'Nelson Cruz', 423.5);

SELECT AVG(home_run_distance) FROM mlb_home_runs;


Question: Generate PostgreSQL SQL for: What is every growth rate in 1991-2001 when sex ratio in 2001 is 937?

CREATE TABLE table_19589113_5 (growth_rate_1991_01 VARCHAR, sex_ratio_‡_2001 VARCHAR)

SELECT growth_rate_1991_01 FROM table_19589113_5 WHERE sex_ratio_‡_2001 = 937;


Question: What was the average marine species count per year by region?

CREATE TABLE marine_species_by_region (region VARCHAR(255), year INT, species_count INT); INSERT INTO marine_species_by_region (region, year, species_count) VALUES ('Atlantic', 2010, 1000), ('Atlantic', 2011, 1050), ('Atlantic', 2012, 1100), ('Pacific', 2010, 1500), ('Pacific', 2011, 1600), ('Pacific', 2012, 1700);

SELECT region, AVG(species_count) FROM marine_species_by_region GROUP BY region;


Question: How many tourists visited Asian countries from North America in 2019?

CREATE TABLE tourists (id INT, continent VARCHAR(50), country VARCHAR(50), visitors INT, year INT); INSERT INTO tourists (id, continent, country, visitors, year) VALUES (1, 'Asia', 'Japan', 2500, 2019), (2, 'Asia', 'China', 3000, 2019), (3, 'North America', 'USA', 1500, 2019), (4, 'North America', 'Canada', 1000, 2019);

SELECT SUM(visitors) FROM tourists WHERE continent = 'Asia' AND year = 2019 AND country IN (SELECT country FROM tourists WHERE continent = 'North America');


Question: What is the percentage of unvaccinated children in rural areas?

CREATE TABLE vaccinations (id INT, rural BOOLEAN, vaccinated BOOLEAN); INSERT INTO vaccinations (id, rural, vaccinated) VALUES (1, true, true), (2, false, false), (3, true, false);

SELECT COUNT(*) * 100.0 / (SELECT COUNT(*) FROM vaccinations WHERE rural = true) FROM vaccinations WHERE rural = true AND vaccinated = false;


Question: Generate PostgreSQL SQL for: What is the number of finishes associated with an elimination of Adriana?

CREATE TABLE table_24122653_2 (finish VARCHAR, eliminated VARCHAR)

SELECT COUNT(finish) FROM table_24122653_2 WHERE eliminated = 'Adriana';


Question: List the suppliers and their total sales, from the order_fact and sales_fact tables, ordered by total sales in descending order.

CREATE TABLE sustainability_fact (sustainability_id INT, menu_item_id INT, sustainability_rating DECIMAL, sustainability_certified BOOLEAN);

SELECT s.supplier_name, SUM(sf.sale_quantity * sf.sale_price) as total_sales FROM sales_fact sf JOIN order_fact o ON sf.sale_id = o.sale_id JOIN supplier_dim s ON o.supplier_id = s.supplier_id GROUP BY s.supplier_name ORDER BY total_sales DESC;


Question: List all the unique countries that received military innovation support from the Army in 2017 and 2018.

CREATE TABLE military_innovation (id INT, service VARCHAR(10), year INT, country VARCHAR(50)); INSERT INTO military_innovation (id, service, year, country) VALUES (1, 'Army', 2017, 'Canada'); INSERT INTO military_innovation (id, service, year, country) VALUES (2, 'Army', 2018, 'Mexico');

SELECT DISTINCT country FROM military_innovation WHERE service = 'Army' AND year IN (2017, 2018);


Question: Generate PostgreSQL SQL for: What was the earliest year that had a start of Saint-Gaudens and a stage smaller than 15?

CREATE TABLE table_name_56 (year INTEGER, start VARCHAR, stage VARCHAR)

SELECT MIN(year) FROM table_name_56 WHERE start = 'saint-gaudens' AND stage < 15;


Question: Find the total production of Promethium in 2019 and 2020 from the Mineral_Production_6 table?

CREATE TABLE Mineral_Production_6 (year INT, promethium_production FLOAT);

SELECT SUM(promethium_production) FROM Mineral_Production_6 WHERE year IN (2019, 2020);


Question: What was the total construction cost for infrastructure projects in New York from 2017 to 2019, broken down by project type?

CREATE TABLE InfrastructureCostsNY (State TEXT, Year INTEGER, ProjectType TEXT, ConstructionCost REAL); INSERT INTO InfrastructureCostsNY (State, Year, ProjectType, ConstructionCost) VALUES ('New York', 2017, 'Bridge', 1750000.0), ('New York', 2017, 'Highway', 2350000.0), ('New York', 2017, 'Tunnel', 3250000.0), ('New York', 2018, 'Bridge', 1850000.0), ('New York', 2018, 'Highway', 2450000.0), ('New York', 2018, 'Tunnel', 3350000.0), ('New York', 2019, 'Bridge', 1700000.0), ('New York', 2019, 'Highway', 2300000.0), ('New York', 2019, 'Tunnel', 3200000.0);

SELECT Year, ProjectType, SUM(ConstructionCost) as TotalCost FROM InfrastructureCostsNY WHERE State = 'New York' GROUP BY Year, ProjectType;


Question: Update the "physician_practices" table to reflect the correct "total_doctors" for the practice with id 2

CREATE TABLE physician_practices (id INT PRIMARY KEY, name TEXT, state TEXT, total_doctors INT); INSERT INTO physician_practices (id, name, state, total_doctors) VALUES (1, 'Practice 1', 'TX', 10), (2, 'Practice 2', 'NY', 15), (3, 'Practice 3', 'FL', 20);

UPDATE physician_practices SET total_doctors = 20 WHERE id = 2;


Question: Calculate the average Yttrium production per month in 2018.

SELECT AVG(Quantity) FROM Yttrium_Production WHERE Year = 2018;


Question: What was the total budget allocated for the 'Healthcare' department in the year 2021?

CREATE TABLE Budget(year INT, department VARCHAR(20), amount INT); INSERT INTO Budget VALUES (2021, 'Healthcare', 7000000), (2021, 'Education', 5000000), (2022, 'Healthcare', 7800000), (2022, 'Education', 5500000);

SELECT SUM(amount) FROM Budget WHERE department = 'Healthcare' AND year = 2021;


Question: Generate PostgreSQL SQL for: What is Score, when Attendance is Gund Arena 20,562, and when Date is January 27?

CREATE TABLE table_name_33 (score VARCHAR, attendance VARCHAR, date VARCHAR)

SELECT score FROM table_name_33 WHERE attendance = 'gund arena 20,562' AND date = 'january 27';


Question: What is the average account balance for customers in the 'young adults' age group?

CREATE TABLE customers (id INT, name VARCHAR(255), age INT, account_balance DECIMAL(10, 2)); INSERT INTO customers (id, name, age, account_balance) VALUES (1, 'John Doe', 23, 5000.00), (2, 'Jane Smith', 27, 7000.00);

SELECT AVG(account_balance) FROM customers WHERE age BETWEEN 18 AND 35;


Question: What is the average revenue per sustainable meal?

CREATE TABLE MenuEngineering(meal_type VARCHAR(10), sustainable BOOLEAN, revenue INT); INSERT INTO MenuEngineering(meal_type, sustainable, revenue) VALUES ('Burger', FALSE, 1000), ('Salad', TRUE, 800);

SELECT AVG(revenue) FROM MenuEngineering WHERE sustainable = TRUE;


Question: Update the production capacity of manufacturer 'Fashion Inc.' in the US to 5000.

CREATE TABLE manufacturers (id INT, name VARCHAR(255), country VARCHAR(255), production_capacity INT);

UPDATE manufacturers SET production_capacity = 5000 WHERE name = 'Fashion Inc.' AND country = 'United States';


Question: What is the latest satellite launch year by SpaceX?

CREATE TABLE space_company (name TEXT, satellites_deployed INTEGER); INSERT INTO space_company (name, satellites_deployed) VALUES ('SpaceX', 2000); CREATE TABLE spacex_satellites (id INTEGER, name TEXT, launch_year INTEGER); INSERT INTO spacex_satellites (id, name, launch_year) VALUES (1, 'Starlink 1', 2019), (2, 'Starlink 2', 2020), (3, 'Starlink 3', 2021);

SELECT MAX(launch_year) FROM spacex_satellites;


Question: List all mobile subscribers in South America who have used more than 10 GB of data in the last week and have an active broadband subscription?

CREATE TABLE mobile_subscribers (id INT, region VARCHAR(20), data_usage INT, usage_date DATE, broadband BOOLEAN);

SELECT m.id, m.region, m.data_usage, m.usage_date FROM mobile_subscribers m INNER JOIN (SELECT subscriber_id FROM mobile_subscribers WHERE data_usage > 10000 AND usage_date > DATE_SUB(CURRENT_DATE, INTERVAL 1 WEEK)) d ON m.id = d.subscriber_id WHERE m.region = 'South America' AND m.broadband = TRUE;


Question: What is the total distance traveled by autonomous vehicles in CityC?

CREATE TABLE CityC_VehicleMovement (vehicle_id INT, vehicle_type VARCHAR(20), is_autonomous BOOLEAN, distance FLOAT); INSERT INTO CityC_VehicleMovement (vehicle_id, vehicle_type, is_autonomous, distance) VALUES (1, 'Car', true, 56.2), (2, 'Bike', false, 12.4), (3, 'Car', false, 34.6), (4, 'Bus', true, 78.9);

SELECT SUM(distance) FROM CityC_VehicleMovement WHERE is_autonomous = true;


Question: Generate PostgreSQL SQL for: Find the number of universities that have over a 20000 enrollment size for each affiliation type.

CREATE TABLE university (affiliation VARCHAR, enrollment INTEGER)

SELECT COUNT(*), affiliation FROM university WHERE enrollment > 20000 GROUP BY affiliation;


Question: What's the total number of military vehicles by type in the 'military_equipment' table?

CREATE TABLE military_equipment (type VARCHAR(20), count INT); INSERT INTO military_equipment (type, count) VALUES ('armored_vehicles', 1500), ('artillery', 1200), ('aircraft', 1800), ('naval_vessels', 2000);

SELECT type, SUM(count) FROM military_equipment GROUP BY type;


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

/* using plpy.warning should not produce a traceback
*/
CREATE FUNCTION nested_warning() RETURNS text
	AS
'def fun1():
	plpy.warning("boom")

def fun2():
	fun1()

def fun3():
	fun2()

fun3()
return "you''ve been warned"
'
	LANGUAGE plpython3u;

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


Question: Generate PostgreSQL SQL for: How many locations have the Sun Life Stadium?

CREATE TABLE table_15647838_3 (location VARCHAR, stadium VARCHAR)

SELECT COUNT(location) FROM table_15647838_3 WHERE stadium = 'Sun Life stadium';


Question: What are the top three countries with the most reported cybersecurity incidents?

CREATE TABLE cybersecurity_incidents (id INT, country VARCHAR(255), date DATE);

SELECT country, COUNT(*) as incident_count FROM cybersecurity_incidents WHERE date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR) GROUP BY country ORDER BY incident_count DESC LIMIT 3;


Question: Write the DML statement from PostgreSQL regression test 'plpgsql' (example 754).

INSERT INTO alter_table_under_transition_tables
  VALUES (1, '1'), (2, '2'), (3, '3');

Explanation: DML from PostgreSQL core regression test for Plpgsql.


Question: Find the number of Renewable Energy projects in each state in the USA

CREATE TABLE renewable_projects (project_id INT, name VARCHAR(50), type VARCHAR(50), location VARCHAR(50)); INSERT INTO renewable_projects (project_id, name, type, location) VALUES (1, 'Wind Farm 1', 'Wind', 'Texas');

SELECT location, COUNT(*) FROM renewable_projects WHERE location LIKE 'USA%' GROUP BY location;


Question: What is the total volume of timber produced by each region in Asia?

CREATE TABLE timber_production_asia (region VARCHAR(255), volume INT); INSERT INTO timber_production_asia (region, volume) VALUES ('East Asia', 2500), ('South Asia', 1800), ('Southeast Asia', 1200);

SELECT region, SUM(volume) FROM timber_production_asia GROUP BY region;


Question: What is the total number of employees who have changed departments in the last year?

CREATE TABLE Employees (Employee_ID INT, First_Name VARCHAR(20), Last_Name VARCHAR(20), Department VARCHAR(20), Country VARCHAR(20), Join_Date DATE, Previous_Department VARCHAR(20), Change_Date DATE);

SELECT COUNT(*) FROM Employees WHERE Change_Date >= DATEADD(year, -1, GETDATE());


Question: Identify the total mass of space debris collected by NASA and JAXA.

CREATE TABLE space_debris (id INT, name VARCHAR(255), collection_date DATE, collecting_agency VARCHAR(255), mass FLOAT); INSERT INTO space_debris (id, name, collection_date, collecting_agency, mass) VALUES (1, 'RemoveDEBRIS', '2018-04-16', 'NASA', 220.0); INSERT INTO space_debris (id, name, collection_date, collecting_agency, mass) VALUES (2, 'RAMA', '2024-09-27', 'JAXA', 550.5); CREATE VIEW space_debris_nasa AS SELECT * FROM space_debris WHERE collecting_agency = 'NASA'; CREATE VIEW space_debris_jaxa AS SELECT * FROM space_debris WHERE collecting_agency = 'JAXA';

SELECT SUM(s.mass) as total_mass FROM space_debris s INNER JOIN space_debris_nasa n ON s.id = n.id INNER JOIN space_debris_jaxa j ON s.id = j.id;


Question: Generate PostgreSQL SQL for: What is the lowest number of participants in 2013 when there were more than 5 participants in 2010, less than 4 participants in 2012 and country was germany?

CREATE TABLE table_name_34 (country VARCHAR)

SELECT MIN(2013) FROM table_name_34 WHERE 2010 > 5 AND country = 'germany' AND 2012 < 4;


Question: Generate PostgreSQL SQL for: What is the Worldwide Gross of the Film with a Rank of 16?

CREATE TABLE table_name_68 (worldwide_gross VARCHAR, rank VARCHAR)

SELECT worldwide_gross FROM table_name_68 WHERE rank = 16;


Question: Generate PostgreSQL SQL for: When has a Record of 1–0?

CREATE TABLE table_name_52 (date VARCHAR, record VARCHAR)

SELECT date FROM table_name_52 WHERE record = '1–0';


Question: What is the minimum food safety score for restaurants in New York?

CREATE TABLE food_safety_inspections(restaurant VARCHAR(255), score INT, city VARCHAR(255)); INSERT INTO food_safety_inspections(restaurant, score, city) VALUES ('Restaurant1', 95, 'New York'), ('Restaurant2', 85, 'Los Angeles'), ('Restaurant3', 90, 'New York'), ('Restaurant4', 92, 'San Francisco'), ('Restaurant5', 88, 'San Francisco');

SELECT MIN(score) FROM food_safety_inspections WHERE city = 'New York';


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

ALTER EXTENSION pgtap ADD FUNCTION col_isnt_fk ( NAME, NAME[], TEXT );

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


Question: How many IoT sensors recorded data in "Field3" on June 15, 2022?

CREATE TABLE Field3_Temp (sensor_id INT, sensor_reading DATE); INSERT INTO Field3_Temp (sensor_id, sensor_reading) VALUES (1, '2022-06-15'), (2, '2022-06-15'), (3, '2022-06-15'), (4, '2022-06-14');

SELECT COUNT(DISTINCT sensor_id) FROM Field3_Temp WHERE sensor_reading = '2022-06-15';


Question: What is the number of donations made by each donor in 2017?

CREATE TABLE Donors (DonorID INT, DonorName TEXT, DonationYear INT); INSERT INTO Donors (DonorID, DonorName, DonationYear) VALUES (1, 'Donor A', 2017), (2, 'Donor B', 2017), (3, 'Donor C', 2017), (1, 'Donor A', 2017), (2, 'Donor B', 2017);

SELECT DonorName, COUNT(*) as NumberOfDonations FROM Donors WHERE DonationYear = 2017 GROUP BY DonorName;


Question: Write the DML statement from PostgreSQL regression test 'cluster' (example 21).

INSERT INTO clstr_tst (b, c) VALUES (21, 'veintiuno');

Explanation: DML from PostgreSQL core regression test for Cluster.


Question: Which art movement has the highest average visitor count?

CREATE TABLE Exhibitions (exhibition_name VARCHAR(255), theme VARCHAR(255), visitor_count INT); INSERT INTO Exhibitions (exhibition_name, theme, visitor_count) VALUES ('Impressionist', 'Impressionism', 2000), ('Cubist', 'Cubism', 1500), ('Surrealist', 'Surrealism', 1800);

SELECT theme, AVG(visitor_count) as avg_visitor_count FROM Exhibitions GROUP BY theme ORDER BY avg_visitor_count DESC LIMIT 1;


Question: What is the average climate finance project funding per country in 2021?

CREATE TABLE climate_finance_projects (year INT, country VARCHAR(255), funding FLOAT); INSERT INTO climate_finance_projects (year, country, funding) VALUES (2020, 'USA', 12000000), (2020, 'France', 18000000), (2020, 'Brazil', 15000000), (2021, 'India', 10000000), (2021, 'China', 17000000);

SELECT country, AVG(funding) AS avg_funding FROM climate_finance_projects WHERE year = 2021 GROUP BY country;


Question: Generate PostgreSQL SQL for: Which country has the most of TV Channels? List the country and number of TV Channels it has.

CREATE TABLE TV_Channel (Country VARCHAR)

SELECT Country, COUNT(*) FROM TV_Channel GROUP BY Country ORDER BY COUNT(*) DESC LIMIT 1;


Question: Generate PostgreSQL SQL for: What candidates ran in the election that featured harry lane englebright?

CREATE TABLE table_1342370_5 (candidates VARCHAR, incumbent VARCHAR)

SELECT candidates FROM table_1342370_5 WHERE incumbent = 'Harry Lane Englebright';


Question: Generate PostgreSQL SQL for: What is the Time of the Athlete with a Reaction time of 0.164?

CREATE TABLE table_name_48 (time INTEGER, reaction_time VARCHAR)

SELECT SUM(time) FROM table_name_48 WHERE reaction_time = 0.164;


Question: What is the total length of all railways in Canada and the United States, grouped by the type of rail (e.g., freight, passenger, or high-speed)?

CREATE TABLE Railways (RailwayID INT, Name VARCHAR(255), Country VARCHAR(255), Type VARCHAR(255), Length FLOAT); INSERT INTO Railways VALUES (1, 'Railway A', 'Canada', 'Freight', 1200); INSERT INTO Railways VALUES (2, 'Railway B', 'United States', 'Passenger', 1500); INSERT INTO Railways VALUES (3, 'Railway C', 'Canada', 'High-Speed', 800);

SELECT Country, Type, SUM(Length) as TotalLength FROM Railways GROUP BY Country, Type;


Question: Generate PostgreSQL SQL for: How many byes were then when there were less than 737 against?

CREATE TABLE table_name_13 (byes INTEGER, against INTEGER)

SELECT SUM(byes) FROM table_name_13 WHERE against < 737;


Question: How many rides started between 6-7 AM for each system in May 2022?

CREATE TABLE trips (trip_id INT, trip_start_time DATETIME, trip_end_time DATETIME, system_name VARCHAR(20));

SELECT system_name, COUNT(*) FROM trips WHERE trip_start_time BETWEEN '2022-05-01 06:00:00' AND '2022-05-31 07:00:00' GROUP BY system_name;


Question: What is the monthly sales trend of cosmetic products in India, and which product categories have the highest and lowest sales?

CREATE TABLE sales (id INT, product_name VARCHAR(255), product_category VARCHAR(255), sale_date DATE, sales_amount DECIMAL(10, 2), country VARCHAR(255));

SELECT DATE_TRUNC('month', sale_date) as month, product_category, AVG(sales_amount) as avg_sales FROM sales WHERE country = 'India' GROUP BY month, product_category ORDER BY month, avg_sales DESC;


Question: Generate PostgreSQL SQL for: Which Year(s) won has a Total larger than 295?

CREATE TABLE table_name_31 (year_s__won VARCHAR, total INTEGER)

SELECT year_s__won FROM table_name_31 WHERE total > 295;


Question: What is the total revenue generated by each art category?

CREATE TABLE ArtSales (id INT, art_category VARCHAR(255), revenue DECIMAL(10,2)); INSERT INTO ArtSales (id, art_category, revenue) VALUES (1, 'Painting', 5000), (2, 'Sculpture', 7000), (3, 'Photography', 3000);

SELECT art_category, SUM(revenue) FROM ArtSales GROUP BY art_category;


Question: What is the maximum cultural heritage preservation score for any country in 2022?

CREATE TABLE country_data (country VARCHAR(255), year INT, score INT); INSERT INTO country_data (country, year, score) VALUES ('Australia', 2022, 95), ('Brazil', 2022, 92), ('Russia', 2022, 97);

SELECT MAX(score) FROM country_data WHERE year = 2022;


Question: Generate PostgreSQL SQL for: What's the smallest week that had a result of t 17–17?

CREATE TABLE table_name_75 (week INTEGER, result VARCHAR)

SELECT MIN(week) FROM table_name_75 WHERE result = 't 17–17';


Question: List all songs released in the last 6 months that belong to the 'Indie' genre.

CREATE TABLE Songs (SongId INT, SongName VARCHAR(255), Genre VARCHAR(255), ReleaseDate DATE); INSERT INTO Songs (SongId, SongName, Genre, ReleaseDate) VALUES (1, 'Bohemian Rhapsody', 'Rock', '1975-11-30'), (2, 'Stairway to Heaven', 'Rock', '1971-11-08'), (3, 'Hey Jude', 'Pop', '1968-08-26'), (4, 'Sultans of Swing', 'Jazz', '1978-04-21');

SELECT SongName FROM Songs WHERE Genre = 'Indie' AND ReleaseDate >= DATE_SUB(CURDATE(), INTERVAL 6 MONTH);


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

select to_tsvector('simple', 'x y q y') @@ '!x <-> y' AS "true";

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

SELECT count(*) FROM (select to_tsvector('simple', 'x y q y') @@ '!x <-> y' AS "true") AS _sub;


Question: What is the daily revenue for 'Restaurant D'?

CREATE TABLE sales (id INT, restaurant_id INT, sales DECIMAL(5,2)); INSERT INTO sales (id, restaurant_id, sales) VALUES (1, 1, 100.00), (2, 1, 200.00), (3, 2, 150.00), (4, 3, 50.00), (5, 4, 300.00);

SELECT SUM(sales) FROM sales WHERE restaurant_id = 4 GROUP BY DATE(time);


Question: Which basketball players have the most total points scored in each game for the last 30 days?

CREATE TABLE games (game_date DATE, team VARCHAR(50), player VARCHAR(50), points INT); INSERT INTO games (game_date, team, player, points) VALUES ('2022-01-01', 'Bulls', 'Johnson', 30), ('2022-01-01', 'Bulls', 'Brown', 20), ('2022-01-02', 'Bulls', 'Johnson', 35), ('2022-01-02', 'Bulls', 'Brown', 15);

SELECT game_date, player, SUM(points) AS total_points  FROM games  WHERE game_date >= DATEADD(day, -30, GETDATE())  GROUP BY game_date, player;


Question: What is the maximum price of nail polish products that are cruelty-free?

CREATE TABLE products (product_id INT, product_name VARCHAR(100), price DECIMAL(5,2), is_cruelty_free BOOLEAN, category VARCHAR(50));

SELECT MAX(price) FROM products WHERE category = 'Nail Polish' AND is_cruelty_free = TRUE;


Question: Generate PostgreSQL SQL for: what's the trim with engine being 3.5l lz4 v6

CREATE TABLE table_1373768_1 (trim VARCHAR, engine VARCHAR)

SELECT trim FROM table_1373768_1 WHERE engine = '3.5L LZ4 V6';


Question: Write the DDL statement from PostgreSQL regression test 'partition_join' (example 110).

CREATE TABLE prt1_m_p2 PARTITION OF prt1_m FOR VALUES FROM (250, 250) TO (500, 500);

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