Question: Delete policies that have been expired for more than 2 years for policyholders in California.

CREATE TABLE policies (id INT, policyholder_id INT, policy_type TEXT, issue_date DATE, expiry_date DATE); INSERT INTO policies (id, policyholder_id, policy_type, issue_date, expiry_date) VALUES (1, 3, 'Life', '2020-01-01', '2022-01-01'), (2, 4, 'Health', '2021-02-01', '2023-02-01'), (3, 5, 'Auto', '2021-03-01', '2024-03-01'); CREATE TABLE policyholders (id INT, name TEXT, state TEXT); INSERT INTO policyholders (id, name, state) VALUES (3, 'Sophia Garcia', 'California'), (4, 'Daniel Kim', 'Nevada'), (5, 'Claire Williams', 'Texas');

DELETE FROM policies WHERE policies.id IN (SELECT policies.id FROM policies JOIN policyholders ON policies.policyholder_id = policyholders.id WHERE policyholders.state = 'California' AND policies.expiry_date < DATE_SUB(CURRENT_DATE, INTERVAL 2 YEAR));


Question: List all climate adaptation projects and their respective completion years.

CREATE TABLE climate_adaptation_projects (project_id INT, project_name TEXT, completion_year INT, project_type TEXT); INSERT INTO climate_adaptation_projects (project_id, project_name, completion_year, project_type) VALUES (16, 'Coastal Erosion Protection P', 2018, 'adaptation'), (17, 'Water Management Q', 2019, 'adaptation'), (18, 'Disaster Risk Reduction R', 2020, 'adaptation'), (19, 'Climate Resilient Agriculture S', 2021, 'adaptation');

SELECT project_name, completion_year FROM climate_adaptation_projects WHERE project_type = 'adaptation';


Question: Generate PostgreSQL SQL for: What caused the collapse of the Mausoleum at Halicarnassus?

CREATE TABLE table_19342760_1 (cause_of_destruction VARCHAR, name VARCHAR)

SELECT cause_of_destruction FROM table_19342760_1 WHERE name = 'Mausoleum at Halicarnassus';


Question: Generate PostgreSQL SQL for: What is every high score for a strike rate of 84.88?

CREATE TABLE table_2985664_8 (high_score VARCHAR, strike_rate VARCHAR)

SELECT high_score FROM table_2985664_8 WHERE strike_rate = '84.88';


Question: Generate PostgreSQL SQL for: What is the lowest pole with a Flap larger than 5, and a before race 155?

CREATE TABLE table_name_49 (pole INTEGER, flap VARCHAR, race VARCHAR)

SELECT MIN(pole) FROM table_name_49 WHERE flap > 5 AND race < 155;


Question: Generate PostgreSQL SQL for: What is the 2nd leg with ldu quito as team 1?

CREATE TABLE table_name_62 (team__number1 VARCHAR)

SELECT 2 AS nd_leg FROM table_name_62 WHERE team__number1 = 'ldu quito';


Question: What is the minimum temperature (°C) for fish farms located in the Southern Ocean?

CREATE TABLE fish_farms (id INT, name TEXT, location TEXT, temperature FLOAT); INSERT INTO fish_farms (id, name, location, temperature) VALUES (1, 'Farm A', 'Southern Ocean', 10.0), (2, 'Farm B', 'Southern Ocean', 8.0), (3, 'Farm C', 'Indian Ocean', 12.0);

SELECT MIN(temperature) FROM fish_farms WHERE location = 'Southern Ocean';


Question: List all players who have participated in ESports events for a single platform, along with their demographic information.

CREATE TABLE Players (PlayerID INT, Age INT, Gender VARCHAR(10));CREATE VIEW ESportsEventsView (PlayerID, EventCount, Platform) AS SELECT PlayerID, COUNT(*), GamePlatform FROM ESportsEvents JOIN Games ON ESportsEvents.GameID = Games.GameID GROUP BY PlayerID, GamePlatform;

SELECT p.PlayerID, p.Age, p.Gender FROM Players p INNER JOIN ESportsEventsView ev ON p.PlayerID = ev.PlayerID GROUP BY p.PlayerID HAVING COUNT(DISTINCT ev.Platform) = 1;


Question: What is the percentage of dispensaries in each state that sell a particular strain, such as Blue Dream?

CREATE TABLE DispensaryStrains (dispensary VARCHAR(255), state VARCHAR(255), strain VARCHAR(255)); INSERT INTO DispensaryStrains (dispensary, state, strain) VALUES ('Dispensary A', 'CA', 'Blue Dream'), ('Dispensary A', 'CO', 'Sour Diesel'), ('Dispensary B', 'CA', 'Blue Dream'), ('Dispensary B', 'CO', 'Durban Poison');

SELECT state, COUNT(*) * 100.0 / (SELECT COUNT(*) FROM DispensaryStrains WHERE strain = 'Blue Dream') as percentage FROM DispensaryStrains WHERE strain = 'Blue Dream' GROUP BY state;


Question: Generate PostgreSQL SQL for: What is the average FAC/LC apps with a CL G greater than 0, less than 33 PL apps, a FAC/LC G of 0, and less than 2 FA YC?

CREATE TABLE table_name_46 (fac___lc_apps INTEGER, fa_yc VARCHAR, fac___lc_g VARCHAR, cl_g VARCHAR, pl_apps VARCHAR)

SELECT AVG(fac___lc_apps) FROM table_name_46 WHERE cl_g > 0 AND pl_apps < 33 AND fac___lc_g = 0 AND fa_yc < 2;


Question: Count the number of songs by artists from Canada.

CREATE TABLE Songs (song_id INT, artist_id INT, title VARCHAR(100), release_year INT); CREATE TABLE Artists (artist_id INT, name VARCHAR(100), country VARCHAR(50));

SELECT COUNT(s.song_id) FROM Songs s INNER JOIN Artists a ON s.artist_id = a.artist_id WHERE a.country = 'Canada';


Question: Which defense contractors have negotiated contracts for missile defense systems in Europe?

CREATE TABLE ContractNegotiations (contractID INT, company VARCHAR(255), systemType VARCHAR(255), region VARCHAR(255)); INSERT INTO ContractNegotiations (contractID, company, systemType, region) VALUES (1, 'Raytheon', 'Missile Defense System', 'Europe'); INSERT INTO ContractNegotiations (contractID, company, systemType, region) VALUES (2, 'Lockheed Martin', 'Missile Defense System', 'Europe');

SELECT DISTINCT company FROM ContractNegotiations WHERE systemType = 'Missile Defense System' AND region = 'Europe';


Question: What is the average cultural competency score for community health workers by gender?

CREATE TABLE community_health_workers (worker_id INT, age INT, gender VARCHAR(255), cultural_competency_score INT); INSERT INTO community_health_workers (worker_id, age, gender, cultural_competency_score) VALUES (1, 35, 'Male', 80), (2, 40, 'Female', 85), (3, 45, 'Non-binary', 90);

SELECT gender, AVG(cultural_competency_score) FROM community_health_workers GROUP BY gender;


Question: Generate PostgreSQL SQL for: How many wins for bruce fleisher with over 31 events?

CREATE TABLE table_name_16 (wins INTEGER, player VARCHAR, events VARCHAR)

SELECT AVG(wins) FROM table_name_16 WHERE player = 'bruce fleisher' AND events > 31;


Question: Which causes received donations from donors in a specific region?

CREATE TABLE Donors (DonorID INT, Region VARCHAR(50)); CREATE TABLE Donations (DonationID INT, DonorID INT, Cause VARCHAR(50), Amount DECIMAL(10,2)); INSERT INTO Donors (DonorID, Region) VALUES (1, 'North America'), (2, 'South America'), (3, 'North America'), (4, 'Europe'), (5, 'Asia'); INSERT INTO Donations (DonationID, DonorID, Cause, Amount) VALUES (1, 1, 'Education', 2000), (2, 2, 'Health', 3000), (3, 1, 'Education', 1000), (4, 4, 'Environment', 4000);

SELECT Cause FROM Donations D JOIN Donors R ON D.DonorID = R.DonorID WHERE R.Region = 'North America';


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

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

SELECT count(*) FROM (select '{"a":1 , "b":2, "c":3}'::jsonb - 'c') AS _sub;


Question: What are the mental health conditions with a patient count greater than 50000 in Europe?

CREATE TABLE european_health_conditions (id INT, name VARCHAR(255), patients INT); INSERT INTO european_health_conditions (id, name, patients) VALUES (1, 'Stress Disorder', 45000); INSERT INTO european_health_conditions (id, name, patients) VALUES (2, 'PTSD', 70000); INSERT INTO european_health_conditions (id, name, patients) VALUES (3, 'ADHD', 80000);

SELECT name FROM european_health_conditions WHERE patients > 50000;


Question: PL/pgSQL test: Pltcl Setup (example 13).

create function tcl_int4ge(int4,int4) returns bool as '
    if {$1 >= $2} {
        return t
    }
    return f
' language pltcl;

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


Question: How many water sources were offline for more than two weeks in the 'WaterSources' table?

CREATE TABLE WaterSources (ID INT, SourceID INT, Status VARCHAR(10), LastOnline DATE); INSERT INTO WaterSources (ID, SourceID, Status, LastOnline) VALUES (1, 1, 'Online', '2022-01-01'); INSERT INTO WaterSources (ID, SourceID, Status, LastOnline) VALUES (2, 2, 'Offline', '2022-06-15');

SELECT COUNT(*) FROM WaterSources WHERE Status = 'Offline' AND DATEDIFF(day, LastOnline, GETDATE()) > 14;


Question: Generate PostgreSQL SQL for: What's the value for utah when texas is humphrey?

CREATE TABLE table_name_80 (utah VARCHAR, texas VARCHAR)

SELECT utah FROM table_name_80 WHERE texas = 'humphrey';


Question: List the names and genres of games designed by developers from Latin America in the last 2 years.

CREATE TABLE game_designers (id INT, name VARCHAR(50), gender VARCHAR(50), country VARCHAR(50)); INSERT INTO game_designers (id, name, gender, country) VALUES (1, 'María Rodríguez', 'Female', 'Argentina'); INSERT INTO game_designers (id, name, gender, country) VALUES (2, 'Carlos Alvarez', 'Male', 'Brazil'); CREATE TABLE game_sales (id INT, game_name VARCHAR(50), genre VARCHAR(50), sale_date DATE); INSERT INTO game_sales (id, game_name, genre, sale_date) VALUES (1, 'Game C', 'RPG', '2022-02-01'); INSERT INTO game_sales (id, game_name, genre, sale_date) VALUES (2, 'Game D', 'Strategy', '2022-03-15');

SELECT game_sales.game_name, game_sales.genre FROM game_sales INNER JOIN game_designers ON game_sales.game_name = game_designers.name WHERE game_designers.country IN ('Argentina', 'Brazil', 'Colombia') AND game_sales.sale_date >= DATEADD(year, -2, GETDATE());


Question: Identify all marine species that have been impacted by ocean acidification and their conservation status.

CREATE TABLE marine_species (id INT, species_name TEXT, conservation_status TEXT); CREATE TABLE ocean_acidification_impact (id INT, species_id INT, PRIMARY KEY (id, species_id), FOREIGN KEY (species_id) REFERENCES marine_species(id)); INSERT INTO marine_species (id, species_name, conservation_status) VALUES (1, 'Coral', 'Vulnerable'), (2, 'Salmon', 'Least Concern'), (3, 'Sea Turtle', 'Endangered'); INSERT INTO ocean_acidification_impact (id, species_id) VALUES (1, 1), (2, 3);

SELECT marine_species.species_name, marine_species.conservation_status FROM marine_species INNER JOIN ocean_acidification_impact ON marine_species.id = ocean_acidification_impact.species_id;


Question: Generate PostgreSQL SQL for: What category was Scream nominated for at the International Horror Guild?

CREATE TABLE table_name_52 (category VARCHAR, work VARCHAR, award VARCHAR)

SELECT category FROM table_name_52 WHERE work = 'scream' AND award = 'international horror guild';


Question: Generate PostgreSQL SQL for: Name the birth date for taavi sadam

CREATE TABLE table_25058562_2 (birth_date VARCHAR, player VARCHAR)

SELECT birth_date FROM table_25058562_2 WHERE player = 'Taavi Sadam';


Question: Generate PostgreSQL SQL for: What engine scored 17 points?

CREATE TABLE table_name_86 (engine VARCHAR, points VARCHAR)

SELECT engine FROM table_name_86 WHERE points = '17';


Question: What is the total funding amount for startups founded by individuals who identify as Native American in the agriculture sector?

CREATE TABLE startup (id INT, name VARCHAR(100), industry VARCHAR(50), founder_native_american VARCHAR(3), funding FLOAT); INSERT INTO startup VALUES (1, 'StartupA', 'Agriculture', 'Yes', 1000000); INSERT INTO startup VALUES (2, 'StartupB', 'Tech', 'No', 7000000); INSERT INTO startup VALUES (3, 'StartupC', 'Agriculture', 'Yes', 1200000);

SELECT SUM(funding) FROM startup WHERE founder_native_american = 'Yes' AND industry = 'Agriculture';


Question: Generate PostgreSQL SQL for: Name the D 41 which has a D 43 of r 18

CREATE TABLE table_name_45 (d_41 VARCHAR, d_43 VARCHAR)

SELECT d_41 FROM table_name_45 WHERE d_43 = 'r 18';


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

select polyf(multirange(int4range(42, 49)), 11, 2::smallint) as int, polyf(multirange(float8range(4.5, 7.8)), 7.8, 11::real) as num;

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

SELECT count(*) FROM (select polyf(multirange(int4range(42, 49)), 11, 2::smallint) as int, polyf(multirange(float8range(4.5, 7.8)), 7.8, 11::real) as num) AS _sub;


Question: What is the earliest release date of a game in the 'VirtualRealityGames' table?

CREATE TABLE VirtualRealityGames (GameID INT, GameName TEXT, ReleaseDate DATE); INSERT INTO VirtualRealityGames (GameID, GameName, ReleaseDate) VALUES (1, 'Game1', '2021-01-01'), (2, 'Game2', '2022-02-02'), (3, 'Game3', '2020-03-03');

SELECT MIN(ReleaseDate) FROM VirtualRealityGames;


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

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

SELECT count(*) FROM (select jsonb_path_query('-0.00123456', '$.decimal(2,-4)')) AS _sub;


Question: Generate PostgreSQL SQL for: How many times did drinking games win the poll?

CREATE TABLE table_15781170_3 (_number VARCHAR, poll_winner VARCHAR)

SELECT COUNT(_number) FROM table_15781170_3 WHERE poll_winner = 'Drinking Games';


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

insert into rtest_empmass values ('maier', '5000.00');

Explanation: DML from PostgreSQL core regression test for Rules.


Question: Generate PostgreSQL SQL for: What is the highest Lane used by a racer from Malta?

CREATE TABLE table_name_67 (lane INTEGER, nationality VARCHAR)

SELECT MAX(lane) FROM table_name_67 WHERE nationality = 'malta';


Question: Generate PostgreSQL SQL for: What is the total number of Wins, when Losses is less than 10, when Against is less than 1253, and when Byes is less than 0?

CREATE TABLE table_name_42 (wins VARCHAR, byes VARCHAR, losses VARCHAR, against VARCHAR)

SELECT COUNT(wins) FROM table_name_42 WHERE losses < 10 AND against < 1253 AND byes < 0;


Question: Generate PostgreSQL SQL for: After the year 2011, when the Canada - USA Rank was 46th, what was the League Rank?

CREATE TABLE table_name_54 (league VARCHAR, year VARCHAR, canada___usa_rank VARCHAR)

SELECT league AS Rank FROM table_name_54 WHERE year > 2011 AND canada___usa_rank = '46th';


Question: What is the total water consumption by each sector in the most recent year?

SELECT syc.sector, SUM(syc.consumption) as total_consumption FROM sector_year_consumption syc JOIN (SELECT MAX(year) as most_recent_year FROM sector_year_consumption) max_year ON 1=1 WHERE syc.year = max_year.most_recent_year GROUP BY syc.sector;


Question: How many climate finance projects are there in total?

CREATE TABLE climate_finance (project_name TEXT, location TEXT, amount INTEGER); INSERT INTO climate_finance (project_name, location, amount) VALUES ('Project A', 'Asia', 500000), ('Project B', 'Europe', 300000);


Question: How many visitors have attended events at multiple museum locations?

CREATE TABLE MuseumLocations (LocationID INT, LocationName VARCHAR(255)); INSERT INTO MuseumLocations (LocationID, LocationName) VALUES (1, 'Location 1'); INSERT INTO MuseumLocations (LocationID, LocationName) VALUES (2, 'Location 2'); CREATE TABLE Events (EventID INT, LocationID INT); INSERT INTO Events (EventID, LocationID) VALUES (1, 1); INSERT INTO Events (EventID, LocationID) VALUES (2, 1); INSERT INTO Events (EventID, LocationID) VALUES (3, 2); CREATE TABLE Visitors (VisitorID INT, VisitedMultipleLocations BOOLEAN); INSERT INTO Visitors (VisitorID, VisitedMultipleLocations) VALUES (1, true); INSERT INTO Visitors (VisitorID, VisitedMultipleLocations) VALUES (2, false); INSERT INTO Visitors (VisitorID, VisitedMultipleLocations) VALUES (3, true); CREATE TABLE VisitorEvents (VisitorID INT, EventID INT); INSERT INTO VisitorEvents (VisitorID, EventID) VALUES (1, 1); INSERT INTO VisitorEvents (VisitorID, EventID) VALUES (1, 2); INSERT INTO VisitorEvents (VisitorID, EventID) VALUES (3, 3);

SELECT COUNT(V.VisitorID) as TotalVisitors FROM Visitors V INNER JOIN VisitorEventsVE ON V.VisitorID = VE.VisitorID INNER JOIN Events E ON VE.EventID = E.EventID INNER JOIN MuseumLocations ML ON E.LocationID = ML.LocationID GROUP BY V.VisitorID HAVING COUNT(DISTINCT ML.LocationID) > 1;


Question: What is the minimum capacity of renewable energy projects in a given state?

CREATE TABLE State (state_id INT, state_name VARCHAR(50)); CREATE TABLE Project (project_id INT, project_name VARCHAR(50), project_capacity INT, state_id INT);

SELECT State.state_name, MIN(Project.project_capacity) as min_capacity FROM State JOIN Project ON State.state_id = Project.state_id GROUP BY State.state_name;


Question: Generate PostgreSQL SQL for: What are the id and the amount of refund of the booking that incurred the most times of payments?

CREATE TABLE Payments (booking_id VARCHAR); CREATE TABLE Bookings (booking_id VARCHAR, amount_of_refund VARCHAR)

SELECT T1.booking_id, T1.amount_of_refund FROM Bookings AS T1 JOIN Payments AS T2 ON T1.booking_id = T2.booking_id GROUP BY T1.booking_id ORDER BY COUNT(*) DESC LIMIT 1;


Question: Generate PostgreSQL SQL for: What is the highest grid that has gregorio lavilla as the rider?

CREATE TABLE table_name_89 (grid INTEGER, rider VARCHAR)

SELECT MAX(grid) FROM table_name_89 WHERE rider = 'gregorio lavilla';


Question: Identify users who have posted more than once per day on average.

CREATE TABLE users (user_id INT, user_name VARCHAR(50)); INSERT INTO users (user_id, user_name) VALUES (1001, 'user1'), (1002, 'user2'), (1003, 'user3'), (1004, 'user4');

SELECT user_id, user_name, AVG(post_count) as avg_posts_per_day FROM (SELECT user_id, user_name, post_date, COUNT(*) as post_count FROM posts JOIN users ON posts.user_id = users.user_id GROUP BY post_date, user_id) as subquery GROUP BY user_id, user_name HAVING AVG(post_count) > 1;


Question: What is the minimum number of community education programs conducted per year for each type of program?

CREATE TABLE Education_Programs (id INT, year INT, program_type VARCHAR(50), number_of_programs INT);

SELECT program_type, MIN(number_of_programs) FROM Education_Programs GROUP BY program_type;


Question: Generate PostgreSQL SQL for: Which Rank has a Lost smaller than 12, and a Played larger than 20, and an Avg Points larger than 1.73?

CREATE TABLE table_name_95 (rank INTEGER, lost VARCHAR, played VARCHAR)

SELECT MAX(rank) FROM table_name_95 WHERE lost < 12 AND played > 20 AND Avg.points > 1.73;


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

SELECT encode(overlay(E'Th\\000omas'::bytea placing E'\\002\\003'::bytea from 8),'escape');

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

SELECT count(*) FROM (SELECT encode(overlay(E'Th\\000omas'::bytea placing E'\\002\\003'::bytea from 8),'escape')) AS _sub;


Question: Generate PostgreSQL SQL for: How many series had a production code of 202?

CREATE TABLE table_23799417_1 (no_in_series VARCHAR, production_code VARCHAR)

SELECT COUNT(no_in_series) FROM table_23799417_1 WHERE production_code = 202;


Question: What is the average number of wins per season for a specific football team?

CREATE TABLE team_wins (id INT, team VARCHAR(50), sport VARCHAR(20), season VARCHAR(10), wins INT);

SELECT AVG(wins) FROM team_wins WHERE team = 'Manchester United' AND sport = 'Football' GROUP BY season;


Question: Delete the record with id 2 in the providers table.

CREATE TABLE providers (id INT, name VARCHAR(50), specialty VARCHAR(50), PRIMARY KEY(id)); INSERT INTO providers (id, name, specialty) VALUES (1, 'Dr. Ava Jones', 'Psychiatry'), (2, 'Dr. Mohamed Ahmed', 'Psychology');


Question: Write the DML statement from PostgreSQL regression test 'rowsecurity' (example 602).

UPDATE x1 SET b = b || '_updt' WHERE f_leak(b) RETURNING *;

Explanation: DML from PostgreSQL core regression test for Rowsecurity.


Question: Generate PostgreSQL SQL for: What Club has Fiba European Champion's Cup and an Italian Cup?

CREATE TABLE table_name_27 (club VARCHAR, european_cup VARCHAR, national_cup VARCHAR)

SELECT club FROM table_name_27 WHERE european_cup = 'fiba european champion's cup' AND national_cup = 'italian cup';


Question: What is the average age of patients diagnosed with Hepatitis in Canada?

CREATE TABLE PatientData (PatientID INT, Age INT, Gender VARCHAR(10), Diagnosis VARCHAR(20), Country VARCHAR(20)); INSERT INTO PatientData (PatientID, Age, Gender, Diagnosis, Country) VALUES (1, 34, 'Male', 'Hepatitis', 'Canada'); INSERT INTO PatientData (PatientID, Age, Gender, Diagnosis, Country) VALUES (2, 42, 'Female', 'Flu', 'USA');

SELECT AVG(Age) FROM PatientData WHERE Diagnosis = 'Hepatitis' AND Country = 'Canada';


Question: What is the number of properties in each property type category?

CREATE TABLE Properties (id INT, price INT, property_type TEXT); INSERT INTO Properties (id, price, property_type) VALUES (1, 500000, 'House'), (2, 400000, 'Condo'), (3, 700000, 'Townhouse');

SELECT property_type, COUNT(*) AS property_count FROM Properties GROUP BY property_type;


Question: Which countries have the highest and lowest average product prices for circular supply chain products?

CREATE TABLE products (product_id INT, price DECIMAL, circular_supply BOOLEAN, country VARCHAR(50)); INSERT INTO products (product_id, price, circular_supply, country) VALUES (1, 15.99, true, 'USA'), (2, 25.49, false, 'USA'), (3, 12.99, true, 'Canada'), (4, 18.99, true, 'Mexico'), (5, 9.99, false, 'Mexico');

SELECT country, AVG(price) FROM products WHERE circular_supply = true GROUP BY country ORDER BY AVG(price) ASC, country;


Question: What is the average daily return for all stocks in the 'America' region, ordered by return in descending order?

CREATE TABLE stocks (id INT, symbol VARCHAR(10), region VARCHAR(20), return DECIMAL(5,4)); INSERT INTO stocks (id, symbol, region, return) VALUES (1, 'AAPL', 'Asia', 0.0234); INSERT INTO stocks (id, symbol, region, return) VALUES (2, 'GOOG', 'America', 0.0187); INSERT INTO stocks (id, symbol, region, return) VALUES (3, 'BABA', 'Asia', 0.0156); INSERT INTO stocks (id, symbol, region, return) VALUES (4, 'TSLA', 'America', 0.0125);

SELECT region, AVG(return) as avg_return FROM stocks WHERE region = 'America' GROUP BY region ORDER BY avg_return DESC;


Question: Generate PostgreSQL SQL for: What was the score for place 4?

CREATE TABLE table_name_21 (score VARCHAR, place VARCHAR)

SELECT score FROM table_name_21 WHERE place = '4';


Question: Generate PostgreSQL SQL for: What is the capacity for the  institution of university of alberta?

CREATE TABLE table_27599216_6 (capacity VARCHAR, institution VARCHAR)

SELECT capacity FROM table_27599216_6 WHERE institution = 'University of Alberta';


Question: What is the total energy production (in MWh) for each country from the renewable source 'wind'?

CREATE TABLE energy_production (country TEXT, source TEXT, energy_generated FLOAT); INSERT INTO energy_production (country, source, energy_generated) VALUES ('USA', 'wind', 12000), ('Canada', 'wind', 8000), ('Mexico', 'wind', 6000);

SELECT country, SUM(energy_generated) FROM energy_production WHERE source = 'wind' GROUP BY country;


Question: Generate PostgreSQL SQL for: with a record of 73-82 what was the date?

CREATE TABLE table_name_58 (date VARCHAR, record VARCHAR)

SELECT date FROM table_name_58 WHERE record = '73-82';


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

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


Question: What is the total number of network infrastructure investments for a specific country in the last year?

CREATE TABLE network_investments (investment_id INT, investment_date DATE, country VARCHAR(50), investment_amount INT);

SELECT country, SUM(investment_amount) FROM network_investments WHERE country = 'CountryName' AND investment_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR) GROUP BY country;


Question: Update the genre of the artist with id 2 to 'R&B'.

CREATE TABLE artists (id INT, name TEXT, genre TEXT); INSERT INTO artists (id, name, genre) VALUES (1, 'Beyoncé', 'Pop'), (2, 'Rihanna', 'Hip Hop');

UPDATE artists SET genre = 'R&B' WHERE id = 2;


Question: Generate PostgreSQL SQL for: What is the highest decile of Tarras school, which had a state authority?

CREATE TABLE table_name_58 (decile INTEGER, authority VARCHAR, name VARCHAR)

SELECT MAX(decile) FROM table_name_58 WHERE authority = 'state' AND name = 'tarras school';


Question: What is the lowest dissolved oxygen level in the Pacific Ocean for tuna farms?

CREATE TABLE Pacific_Ocean (id INT, dissolved_oxygen DECIMAL(5,2)); INSERT INTO Pacific_Ocean (id, dissolved_oxygen) VALUES (1, 6.5), (2, 7.2), (3, 5.9); CREATE TABLE Tuna_Farms (id INT, ocean VARCHAR(20)); INSERT INTO Tuna_Farms (id, ocean) VALUES (1, 'Pacific'), (2, 'Indian'), (3, 'Pacific');

SELECT MIN(Pacific_Ocean.dissolved_oxygen) FROM Pacific_Ocean INNER JOIN Tuna_Farms ON Pacific_Ocean.id = Tuna_Farms.id WHERE Tuna_Farms.ocean = 'Pacific';


Question: Generate PostgreSQL SQL for: What was the Orangemen record during game 3?

CREATE TABLE table_23346983_1 (record VARCHAR, game VARCHAR)

SELECT record FROM table_23346983_1 WHERE game = 3;


Question: Generate PostgreSQL SQL for: What is the average number of goals for players ranked above 9 and playing more than 205 matches?

CREATE TABLE table_name_91 (goals INTEGER, matches VARCHAR, rank VARCHAR)

SELECT AVG(goals) FROM table_name_91 WHERE matches = 205 AND rank > 9;


Question: What is the total balance of Shariah-compliant savings accounts for customers in California, grouped by city?

CREATE TABLE savings_accounts (id INT, customer_id INT, account_type VARCHAR(20), balance DECIMAL(10, 2), state VARCHAR(2)); INSERT INTO savings_accounts (id, customer_id, account_type, balance, state) VALUES (1, 101, 'Shariah', 5000, 'California'); CREATE TABLE customers (id INT, first_name VARCHAR(20), last_name VARCHAR(20), city VARCHAR(20)); INSERT INTO customers (id, first_name, last_name, city) VALUES (101, 'Ahmad', 'Ali', 'San Francisco');

SELECT savings_accounts.state, customers.city, SUM(savings_accounts.balance) FROM savings_accounts INNER JOIN customers ON savings_accounts.customer_id = customers.id WHERE savings_accounts.account_type = 'Shariah' AND savings_accounts.state = 'California' GROUP BY customers.city;


Question: List all transactions made by 'Mateo Davis' and their details.

SELECT * FROM transactions WHERE client_id = (SELECT id FROM clients WHERE name = 'Mateo Davis');


Question: What is the number of financially capable individuals in each country?

CREATE TABLE if not exists individuals (id INT, country VARCHAR(50), is_financially_capable BOOLEAN, age INT, gender VARCHAR(10));

SELECT country, COUNT(*) FROM individuals WHERE is_financially_capable = TRUE GROUP BY country;


Question: Generate PostgreSQL SQL for: What is the frequency for katherine?

CREATE TABLE table_name_99 (frequency VARCHAR, area_served VARCHAR)

SELECT frequency FROM table_name_99 WHERE area_served = 'katherine';


Question: Generate PostgreSQL SQL for: Find the number and averaged salary of all instructors who are in the department with the highest budget.

CREATE TABLE department (dept_name VARCHAR, budget VARCHAR); CREATE TABLE instructor (salary INTEGER, dept_name VARCHAR)

SELECT AVG(T1.salary), COUNT(*) FROM instructor AS T1 JOIN department AS T2 ON T1.dept_name = T2.dept_name ORDER BY T2.budget DESC LIMIT 1;


Question: Generate PostgreSQL SQL for: Which Class has a Year(s) of Manufacture of 1899?

CREATE TABLE table_name_32 (class VARCHAR, year_s__of_manufacture VARCHAR)

SELECT class FROM table_name_32 WHERE year_s__of_manufacture = '1899';


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

CREATE FUNCTION pg_stat_statements_reset(IN userid Oid DEFAULT 0,
	IN dbid Oid DEFAULT 0,
	IN queryid bigint DEFAULT 0,
	IN minmax_only boolean DEFAULT false
)
RETURNS timestamp with time zone
AS 'MODULE_PATHNAME', 'pg_stat_statements_reset_1_11'
LANGUAGE C STRICT PARALLEL SAFE;

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


Question: How many regulatory frameworks have been implemented in Africa per year?

CREATE TABLE regulatory_frameworks (framework_id INT, framework_name VARCHAR(50), framework_jurisdiction VARCHAR(50), enforcement_agency VARCHAR(50), implementation_year INT);

CREATE VIEW africa_frameworks_per_year AS SELECT TO_CHAR(implementation_year, 'YYYY') AS implementation_year, COUNT(framework_id) AS frameworks_implemented FROM regulatory_frameworks WHERE framework_jurisdiction = 'Africa' GROUP BY implementation_year ORDER BY implementation_year;


Question: What is the total amount donated by the donor with the id 2?

CREATE TABLE donations (id INT, donor_id INT, amount DECIMAL(10,2)); INSERT INTO donations (id, donor_id, amount) VALUES (1, 2, 50.00), (2, 2, 30.00), (3, 2, 100.00);

SELECT SUM(amount) FROM donations WHERE donor_id = 2;


Question: What is the distribution of carbon pricing schemes by region in the carbon_pricing table?

CREATE TABLE carbon_pricing (id INT, name VARCHAR(50), type VARCHAR(50), region VARCHAR(50), start_date DATE, end_date DATE);

SELECT region, COUNT(*) as num_pricing_schemes FROM carbon_pricing GROUP BY region ORDER BY num_pricing_schemes DESC;


Question: Generate PostgreSQL SQL for: What is the % similarity to C7orf38 of the animal whose % identity to C7orf38 is 81?

CREATE TABLE table_26957063_3 (_percentage_similarity_to_c7orf38 INTEGER, _percentage_identity_to_c7orf38 VARCHAR)

SELECT MAX(_percentage_similarity_to_c7orf38) FROM table_26957063_3 WHERE _percentage_identity_to_c7orf38 = 81;


Question: Generate PostgreSQL SQL for: What is the height of Josh Tabb?

CREATE TABLE table_name_28 (height VARCHAR, name VARCHAR)

SELECT height FROM table_name_28 WHERE name = 'josh tabb';


Question: Generate PostgreSQL SQL for: Who won gold in the games where Pan Cheng-Tsung won silver?

CREATE TABLE table_name_76 (gold VARCHAR, silver VARCHAR)

SELECT gold FROM table_name_76 WHERE silver = 'pan cheng-tsung';


Question: Generate PostgreSQL SQL for: How many laps did ben spies do on the grid less than 7?

CREATE TABLE table_name_86 (laps VARCHAR, grid VARCHAR, rider VARCHAR)

SELECT COUNT(laps) FROM table_name_86 WHERE grid < 7 AND rider = 'ben spies';


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

SELECT timestamp with time zone 'Y2001M12D27H04MM05S06.789-08';

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

SELECT count(*) FROM (SELECT timestamp with time zone 'Y2001M12D27H04MM05S06.789-08') AS _sub;


Question: Generate PostgreSQL SQL for: Name the most goals for total club and apps less than 120

CREATE TABLE table_name_34 (goals INTEGER, club VARCHAR, apps VARCHAR)

SELECT MAX(goals) FROM table_name_34 WHERE club = 'total' AND apps < 120;


Question: Generate PostgreSQL SQL for: How many different series numbers are there for the episode seen by 7.84 million people in the US?

CREATE TABLE table_23242933_2 (no_in_series VARCHAR, us_viewers__millions_ VARCHAR)

SELECT COUNT(no_in_series) FROM table_23242933_2 WHERE us_viewers__millions_ = '7.84';


Question: Insert a new record for a tennis match in France with 1500 tickets sold.

CREATE TABLE matches (match_id INT, sport VARCHAR(50), location VARCHAR(50), tickets_sold INT);

INSERT INTO matches (match_id, sport, location, tickets_sold) VALUES (3, 'Tennis', 'France', 1500);


Question: Identify the daily sales trend for the past year, including the current day, by calculating the moving average of units sold per day.

SELECT sale_date, AVG(units_sold) OVER (ORDER BY sale_date ROWS BETWEEN 29 PRECEDING AND CURRENT ROW) AS moving_average FROM daily_sales WHERE sale_date >= DATE_TRUNC('day', CURRENT_DATE - INTERVAL '365 day') ORDER BY sale_date;


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

create trigger tg_wslot_biu before insert or update
    on WSlot for each row execute procedure tg_wslot_biu();

Explanation: DDL from PostgreSQL core regression test for Plpgsql.


Question: Generate PostgreSQL SQL for: what is the maximum 1st prize( $ ) where score is 193 (-17)

CREATE TABLE table_11622255_1 (score VARCHAR)

SELECT MAX(1 AS st_prize__) AS $__ FROM table_11622255_1 WHERE score = '193 (-17)';


Question: What is the total number of cruelty-free products with natural ingredients?

CREATE TABLE Products (product_id INT, is_cruelty_free BOOLEAN, has_natural_ingredients BOOLEAN);

SELECT COUNT(*) FROM Products WHERE is_cruelty_free = TRUE AND has_natural_ingredients = TRUE;


Question: Generate PostgreSQL SQL for: What is Episodes (TV+extra) 2, when Broadcasts (TV) 1 is less than 13, and when Directors is "Shigehito Takayanagi"?

CREATE TABLE table_name_26 (episodes__tv VARCHAR, extra__2 VARCHAR, broadcasts__tv__1 VARCHAR, directors VARCHAR)

SELECT episodes__tv + extra__2 FROM table_name_26 WHERE broadcasts__tv__1 < 13 AND directors = 'shigehito takayanagi';


Question: Generate PostgreSQL SQL for: Where did the player in Pos mf, move to until 30 june 2009 ?

CREATE TABLE table_name_18 (moving_to VARCHAR, date_to VARCHAR, pos VARCHAR)

SELECT moving_to FROM table_name_18 WHERE date_to = '30 june 2009' AND pos = 'mf';


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

select numrange(1,2) << nummultirange();

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

SELECT count(*) FROM (select numrange(1,2) << nummultirange()) AS _sub;


Question: Generate PostgreSQL SQL for: Which IATA has a ICAO of slk?

CREATE TABLE table_name_14 (iata VARCHAR, icao VARCHAR)

SELECT iata FROM table_name_14 WHERE icao = 'slk';


Question: How many military bases are there in total for each country, ordered by the number of bases in descending order?

CREATE TABLE BasesByCountry (Country varchar(50), BaseID int); INSERT INTO BasesByCountry (Country, BaseID) VALUES ('USA', 1), ('USA', 2), ('UK', 3), ('Iraq', 4), ('Iraq', 5);

SELECT Country, COUNT(*) as TotalBases FROM BasesByCountry GROUP BY Country ORDER BY TotalBases DESC;


Question: What is the total number of artworks donated by each artist, ordered by the total count in descending order?

CREATE TABLE Artists (ArtistID int, ArtistName varchar(50), NumberOfArtworks int);INSERT INTO Artists (ArtistID, ArtistName, NumberOfArtworks) VALUES (1, 'Pablo Picasso', 500), (2, 'Vincent Van Gogh', 450), (3, 'Claude Monet', 350);

SELECT ArtistName, SUM(NumberOfArtworks) OVER (PARTITION BY ArtistID ORDER BY ArtistID) as TotalArtworksDonated FROM Artists ORDER BY TotalArtworksDonated DESC;


Question: What is the average water consumption per person in the city of San Francisco, calculated monthly?

CREATE TABLE people (person_id INT, city VARCHAR(20), water_consumption FLOAT, consumption_date DATE); INSERT INTO people (person_id, city, water_consumption, consumption_date) VALUES (1, 'San Francisco', 50.0, '2022-01-01'), (2, 'San Francisco', 60.0, '2022-02-01'), (3, 'San Francisco', 55.0, '2022-03-01');

SELECT city, AVG(water_consumption) FROM (SELECT city, person_id, AVG(water_consumption) AS water_consumption FROM people GROUP BY city, PERIOD_DIFF(consumption_date, DATE_FORMAT(consumption_date, '%Y%m')) * 100) AS monthly_consumption GROUP BY city;


Question: Rank dishes by popularity, considering only orders from the last month, for each category in Chinese restaurants?

CREATE TABLE Restaurants (id INT, name TEXT, cuisine TEXT); INSERT INTO Restaurants (id, name, cuisine) VALUES (1, 'Golden Palace', 'Chinese'), (2, 'La Trattoria', 'Italian'); CREATE TABLE Menu (id INT, name TEXT, category TEXT, price FLOAT, restaurant_id INT); CREATE TABLE Orders (id INT, menu_id INT, order_date DATE, quantity INT);

SELECT menu.name, menu.category, SUM(orders.quantity) as total_quantity, ROW_NUMBER() OVER (PARTITION BY menu.category ORDER BY SUM(orders.quantity) DESC) as rank FROM Orders JOIN Menu ON Orders.menu_id = Menu.id JOIN Restaurants ON Menu.restaurant_id = Restaurants.id WHERE Restaurants.cuisine = 'Chinese' AND Orders.order_date >= CURRENT_DATE - INTERVAL '1 month' GROUP BY menu.name, menu.category ORDER BY menu.category, rank;


Question: Generate PostgreSQL SQL for: What is the average score of submissions?

CREATE TABLE submission (Scores INTEGER)


Question: Generate PostgreSQL SQL for: Name the Tally of an Opposition of westmeath?

CREATE TABLE table_name_76 (tally VARCHAR, opposition VARCHAR)

SELECT tally FROM table_name_76 WHERE opposition = 'westmeath';


Question: Generate PostgreSQL SQL for: How many joined Manchester University?

CREATE TABLE table_255205_1 (joined VARCHAR, institution VARCHAR)

SELECT joined FROM table_255205_1 WHERE institution = 'Manchester University';


Question: Generate PostgreSQL SQL for: What is the highest number of bronze for the United States with more than 1 silver?

CREATE TABLE table_name_13 (bronze INTEGER, nation VARCHAR, silver VARCHAR)

SELECT MAX(bronze) FROM table_name_13 WHERE nation = 'united states' AND silver > 1;


Question: Retrieve all sites from the Cultural_Heritage table that were established after 1600.

CREATE TABLE Cultural_Heritage (Site VARCHAR(50), Year_Established INT, Historical_Significance TEXT); INSERT INTO Cultural_Heritage (Site, Year_Established, Historical_Significance) VALUES ('Machu Picchu', 1450, 'An Incan citadel set high in the Andes Mountains, above the Sacred Valley. It is renowned for its sophisticated dry-stone walls that fuse huge blocks without the use of mortar.'), ('Angkor Wat', 1113, 'A temple complex in Cambodia and one of the largest religious monuments in the world.'), ('Petra', 312, 'An archaeological city in southern Jordan, known for its rock-cut architecture and water conduit system.'), ('Taj Mahal', 1632, 'A white marble mausoleum located in Agra, India, built by Mughal Emperor Shah Jahan in memory of his wife Mumtaz Mahal.');

SELECT Site FROM Cultural_Heritage WHERE Year_Established > 1600;


Question: What is the total amount of funds raised by each sector in 'disaster_response' schema?

CREATE TABLE funds (fund_id INT, sector VARCHAR(255), amount DECIMAL(10, 2), donation_date DATE); INSERT INTO funds (fund_id, sector, amount, donation_date) VALUES (1, 'Education', 5000.00, '2021-01-01');

SELECT sector, SUM(amount) as total_funds_raised FROM funds GROUP BY sector;


Question: What is the total number of patients who have been diagnosed with HIV and hepatitis C in the state of New York?

CREATE TABLE patients (patient_id INT, age INT, gender VARCHAR(10), state VARCHAR(20), disease VARCHAR(20)); INSERT INTO patients (patient_id, age, gender, state, disease) VALUES (1, 45, 'Male', 'New York', 'HIV'); INSERT INTO patients (patient_id, age, gender, state, disease) VALUES (2, 34, 'Female', 'California', 'Hepatitis C');

SELECT COUNT(*) FROM patients WHERE state = 'New York' AND (disease = 'HIV' OR disease = 'Hepatitis C');


Question: Display the names of all workers who have not completed any workforce development training in the circular economy.

CREATE TABLE workers (id INT, name VARCHAR(50), training VARCHAR(30)); CREATE TABLE circular_economy (id INT, training VARCHAR(30)); INSERT INTO workers (id, name, training) VALUES (1, 'John Smith', 'Recycling'), (2, 'Jane Doe', 'Upcycling'), (3, 'Bob Johnson', 'Waste Reduction'), (4, 'Alice Williams', 'Composting'), (5, 'Jim Brown', NULL), (6, 'Karen Green', NULL); INSERT INTO circular_economy (id, training) VALUES (1, 'Recycling'), (2, 'Upcycling');

SELECT w.name FROM workers w LEFT JOIN circular_economy c ON w.training = c.training WHERE c.training IS NULL;


Question: What is the maximum fare for a trip on the London underground?

CREATE TABLE underground (id INT, line VARCHAR(20), fare DECIMAL(5,2)); INSERT INTO underground (id, line, fare) VALUES (1, 'Circle', 4.90), (2, 'District', 5.10), (3, 'Hammersmith', 6.00);


Question: Get the total water usage for mining in 'Baotou'

CREATE TABLE mining_impact (id INT PRIMARY KEY, location VARCHAR(255), water_usage INT, air_pollution INT, land_degradation INT);

SELECT SUM(water_usage) FROM mining_impact WHERE location = 'Baotou';


Question: Generate PostgreSQL SQL for: Can you tell me the Miss Pilipinas that has the Second runner-up of maria penson?

CREATE TABLE table_name_55 (miss_maja_pilipinas VARCHAR, second_runner_up VARCHAR)

SELECT miss_maja_pilipinas FROM table_name_55 WHERE second_runner_up = 'maria penson';


Question: Generate PostgreSQL SQL for: What is the time when ss12 is stage?

CREATE TABLE table_21578303_2 (time VARCHAR, stage VARCHAR)

SELECT time FROM table_21578303_2 WHERE stage = 'SS12';


Question: Generate PostgreSQL SQL for: what is the least silver for germany when gold is more than 4?

CREATE TABLE table_name_94 (silver INTEGER, nation VARCHAR, gold VARCHAR)

SELECT MIN(silver) FROM table_name_94 WHERE nation = 'germany' AND gold > 4;


Question: Generate PostgreSQL SQL for: Which League Cup has a Scottish Cup larger than 69?

CREATE TABLE table_name_42 (league INTEGER, scottish_cup INTEGER)

SELECT SUM(league) AS Cup FROM table_name_42 WHERE scottish_cup > 69;


Question: How many marine species have a population of less than 1000 in the Pacific Ocean?

CREATE TABLE marine_life (id INT PRIMARY KEY, species VARCHAR(255), population INT, habitat VARCHAR(255));

SELECT COUNT(*) FROM marine_life WHERE population < 1000 AND habitat LIKE '%Pacific%';


Question: Generate PostgreSQL SQL for: in which year was available the  rubber as kickdrum pad

CREATE TABLE table_2889300_6 (years_available VARCHAR, kickdrum_pad VARCHAR)

SELECT years_available FROM table_2889300_6 WHERE kickdrum_pad = 'Rubber';


Question: Insert a new record into the 'crypto_exchanges' table with 'exchange_name' 'Kraken', 'exchange_location' 'USA', and 'year_founded' 2011

CREATE TABLE crypto_exchanges (exchange_name VARCHAR(50), exchange_location VARCHAR(50), year_founded INT, regulatory_status VARCHAR(20));

INSERT INTO crypto_exchanges (exchange_name, exchange_location, year_founded, regulatory_status) VALUES ('Kraken', 'USA', 2011, 'Registered');


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

SELECT t1.c1, t2.c1 FROM ft5 t1 RIGHT JOIN ft4 t2 ON (t1.c1 = t2.c1) ORDER BY t2.c1, t1.c1 OFFSET 10 LIMIT 10;

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


Question: What percentage of products are certified cruelty-free in the UK?

CREATE TABLE cosmetics.product_safety (product_id INT, country VARCHAR(50), is_cruelty_free BOOLEAN); INSERT INTO cosmetics.product_safety (product_id, country, is_cruelty_free) VALUES (1, 'UK', true), (2, 'France', false), (3, 'Germany', true), (4, 'Italy', true), (5, 'Spain', false);

SELECT (SUM(is_cruelty_free) * 100.0 / COUNT(*)) as cruelty_free_percentage FROM cosmetics.product_safety WHERE country = 'UK';


Question: What is the average temperature of the Mediterranean Sea?

CREATE TABLE Seas (id INT, name VARCHAR(50), temperature DECIMAL(3,1)); INSERT INTO Seas (id, name, temperature) VALUES (1, 'Mediterranean', 21.5), (2, 'Caribbean', 27.5), (3, 'Baltic', 16.8);

SELECT AVG(Seas.temperature) FROM Seas WHERE Seas.name = 'Mediterranean';


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

-- isnt_procedure( schema, function )
CREATE OR REPLACE FUNCTION isnt_procedure( NAME, NAME )
RETURNS TEXT AS $$
    SELECT _func_compare(
        $1, $2,  NOT _type_func('p', $1, $2),
        'Function ' || quote_ident($1) || '.' || quote_ident($2) || '() should not be a procedure'
    );
$$ LANGUAGE sql;

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


Question: Show a query using PostgreSQL contrib extension 'pgcrypto' (example 12).

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


Question: What is the total number of community events in Chicago this year?

CREATE TABLE CommunityEvents (id INT, city VARCHAR(50), event_date DATE, event_type VARCHAR(50));

SELECT COUNT(*) FROM CommunityEvents WHERE city = 'Chicago' AND event_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR) AND event_type = 'community';


Question: What is the maximum number of visitors at a cultural event in Sydney?

CREATE TABLE Cultural_Events (id INT, city VARCHAR(50), attendance INT); CREATE VIEW Sydney_Events AS SELECT * FROM Cultural_Events WHERE city = 'Sydney';

SELECT MAX(attendance) FROM Sydney_Events;


Question: What is the number of international visitors to Japan in 2021 and their average expenditures?

CREATE TABLE Visitors_Japan (id INT, year INT, country VARCHAR(50), expenditure FLOAT); INSERT INTO Visitors_Japan (id, year, country, expenditure) VALUES (1, 2021, 'Japan', 2000), (2, 2021, 'Japan', 2100), (3, 2021, 'Japan', 2200);

SELECT AVG(Visitors_Japan.expenditure) FROM Visitors_Japan WHERE Visitors_Japan.country = 'Japan' AND Visitors_Japan.year = 2021;


Question: What is the total number of permits issued by month and type?

CREATE TABLE Permits (ID INT, PermitType VARCHAR(50), IssueMonth VARCHAR(50)); INSERT INTO Permits VALUES (1, 'Building', 'January'), (2, 'Plumbing', 'February'), (3, 'Building', 'March');

SELECT IssueMonth, PermitType, COUNT(*) OVER (PARTITION BY IssueMonth, PermitType) AS PermitCount FROM Permits;


Question: Generate PostgreSQL SQL for: Show name of all students who have some friends and also are liked by someone else.

CREATE TABLE Highschooler (name VARCHAR, id VARCHAR); CREATE TABLE Likes (student_id VARCHAR, liked_id VARCHAR); CREATE TABLE Friend (student_id VARCHAR, liked_id VARCHAR)

SELECT T2.name FROM Friend AS T1 JOIN Highschooler AS T2 ON T1.student_id = T2.id INTERSECT SELECT T2.name FROM Likes AS T1 JOIN Highschooler AS T2 ON T1.liked_id = T2.id;


Question: Generate PostgreSQL SQL for: How may times did a player that attended Iowa state appear on the all time roster?

CREATE TABLE table_11734041_1 (years_for_rockets VARCHAR, school_club_team_country VARCHAR)

SELECT COUNT(years_for_rockets) FROM table_11734041_1 WHERE school_club_team_country = 'Iowa State';


Question: Find the average ESG score for each sector, only showing sectors with more than 2 investments.

CREATE TABLE investments(id INT, sector VARCHAR(20), esg_score INT); INSERT INTO investments VALUES(1, 'Tech', 85), (2, 'Healthcare', 75), (3, 'Tech', 82);

SELECT sector, AVG(esg_score) as avg_esg_score FROM investments GROUP BY sector HAVING COUNT(*) > 2;


Question: pgTAP test for Hastap (assertion 257).

SELECT * FROM check_test(
    domain_type_is( 'public'::name, 'us_postal_code', 'text'),
    true,
    'domain_type_is(schema, domain, type)',
    'Domain public.us_postal_code should extend type text',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Hastap.


Question: Generate PostgreSQL SQL for: Name the loss with record of 14-19

CREATE TABLE table_name_68 (loss VARCHAR, record VARCHAR)

SELECT loss FROM table_name_68 WHERE record = '14-19';


Question: What is the average ticket price for each concert in the 'music_festivals' table?

CREATE TABLE music_festivals (festival_name VARCHAR(255), location VARCHAR(255), date DATE, tier_1_price INT, tier_2_price INT);

SELECT festival_name, (tier_1_price + tier_2_price)/2 as avg_ticket_price FROM music_festivals;


Question: What is the number of hospitals and clinics in urban areas of California, by city?

CREATE TABLE hospitals (id INT, name VARCHAR(255), location VARCHAR(255), num_beds INT, is_urban BOOLEAN);CREATE TABLE clinics (id INT, name VARCHAR(255), location VARCHAR(255), is_urban BOOLEAN);

SELECT c.city, COUNT(h.name) AS num_hospitals, COUNT(cl.name) AS num_clinics FROM (SELECT location AS city FROM hospitals WHERE is_urban = TRUE UNION SELECT location AS city FROM clinics WHERE is_urban = TRUE) AS c LEFT JOIN hospitals h ON c.city = h.location AND h.is_urban = TRUE LEFT JOIN clinics cl ON c.city = cl.location AND cl.is_urban = TRUE GROUP BY c.city;


Question: How many workers in each role have been employed in mines for more than 5 years?

CREATE TABLE worker (id INT, name TEXT, role TEXT, mine_id INT, employment_year INT);

SELECT worker.role, COUNT(worker.id) as workers_count FROM worker WHERE worker.employment_year < (CURRENT_DATE - INTERVAL 5 YEAR) GROUP BY worker.role;


Question: Identify customers who have had an increasing balance for the past three consecutive transactions, for all accounts.

CREATE TABLE accounts (customer_id INT, account_type VARCHAR(20), balance DECIMAL(10, 2), transaction_date DATE);

SELECT customer_id, account_type, balance FROM (SELECT customer_id, account_type, balance, transaction_date, LAG(balance, 2) OVER (PARTITION BY customer_id ORDER BY transaction_date) AS lag_balance_2 FROM accounts) AS lagged_accounts WHERE balance > lag_balance_2;


Question: What are the names of UNESCO heritage sites in Europe and their types?

CREATE TABLE UNESCO_SITES (id INT PRIMARY KEY, name VARCHAR(255), region VARCHAR(255), type VARCHAR(255)); INSERT INTO UNESCO_SITES (id, name, region, type) VALUES (1, 'Colosseum', 'Europe', 'Cultural');

SELECT name, type FROM UNESCO_SITES WHERE region = 'Europe';


Question: List the community health workers and their cultural competency scores.

CREATE TABLE community_health_workers (worker_id INT, name VARCHAR(50), cultural_competency_score INT);

SELECT worker_id, name, cultural_competency_score FROM community_health_workers;


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

select pg_get_ruledef(oid, true) from pg_rewrite
  where ev_class = 'tt23v'::regclass and ev_type = '1';

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

SELECT count(*) FROM (select pg_get_ruledef(oid, true) from pg_rewrite
  where ev_class = 'tt23v'::regclass and ev_type = '1') AS _sub;


Question: What is the maximum rating of any attraction?

CREATE TABLE attractions (id INT, name VARCHAR(50), city VARCHAR(20), rating FLOAT); INSERT INTO attractions (id, name, city, rating) VALUES (1, 'Opera House', 'Sydney', 4.6), (2, 'Bridge', 'Sydney', 3.8), (3, 'Tower', 'New York', 4.8);


Question: What is the average budget of biotech startups in California?

CREATE TABLE biotech_startups (id INT, name TEXT, location TEXT, budget FLOAT); INSERT INTO biotech_startups (id, name, location, budget) VALUES (1, 'Genetix', 'California', 15000000.0); INSERT INTO biotech_startups (id, name, location, budget) VALUES (2, 'BioEngineer', 'California', 20000000.0);

SELECT AVG(budget) FROM biotech_startups WHERE location = 'California';


Question: Generate PostgreSQL SQL for: What is the maximum ITV1 weekly ranking?

CREATE TABLE table_25664518_3 (itv1_weekly_ranking INTEGER)

SELECT MAX(itv1_weekly_ranking) FROM table_25664518_3;


Question: Generate PostgreSQL SQL for: What is the largest number of assists for the second rank when there were less than 2 games?

CREATE TABLE table_name_71 (assists INTEGER, rank VARCHAR, games VARCHAR)

SELECT MAX(assists) FROM table_name_71 WHERE rank = 2 AND games < 2;


Question: What is the average number of accommodations requested per student in the Midwest?

CREATE TABLE Accommodations (student_id INT, accommodation_type VARCHAR(50), request_date DATE); CREATE TABLE Students (student_id INT, state VARCHAR(50));

SELECT AVG(accommodation_count) FROM (SELECT student_id, COUNT(*) accommodation_count FROM Accommodations A INNER JOIN Students S ON A.student_id = S.student_id WHERE S.state IN ('Indiana', 'Illinois', 'Iowa', 'Kansas', 'Michigan', 'Minnesota', 'Missouri', 'Nebraska', 'North Dakota', 'Ohio', 'South Dakota', 'Wisconsin') GROUP BY student_id) T;


Question: Generate PostgreSQL SQL for: What is the Format(s) of the release on September 23, 2008?

CREATE TABLE table_name_40 (format_s_ VARCHAR, date VARCHAR)

SELECT format_s_ FROM table_name_40 WHERE date = 'september 23, 2008';


Question: Find the number of environmental impact assessments conducted in the last 6 months for each facility.

CREATE TABLE environmental_assessments (id INT, facility TEXT, assessment_date DATE); INSERT INTO environmental_assessments (id, facility, assessment_date) VALUES (1, 'Facility1', '2022-01-01'), (2, 'Facility1', '2022-03-15'), (3, 'Facility2', '2022-02-01');

SELECT facility, COUNT(*) FROM environmental_assessments WHERE assessment_date >= DATEADD(month, -6, CURRENT_DATE) GROUP BY facility;


Question: Generate PostgreSQL SQL for: What is the British for the Australian ɔ?

CREATE TABLE table_name_93 (british VARCHAR, australian VARCHAR)

SELECT british FROM table_name_93 WHERE australian = 'ɔ';


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

SELECT count(*) FROM macaddrtmp WHERE a >= '22:00:5c:e5:9b:0d';

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


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

-- Don't want cursor names and plpgsql function lines in the error messages
\set VERBOSITY terse

/* helper function to create cursors for each page in [p_start, p_end] */
CREATE FUNCTION test_temp_pin(p_start int, p_end int)
RETURNS void
LANGUAGE plpgsql
AS $f$
  DECLARE
      cursorname text;

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


Question: What is the number of patients and their respective genders in remote areas of Arizona?

CREATE TABLE patients(id INT, name TEXT, location TEXT, gender TEXT); INSERT INTO patients(id, name, location, gender) VALUES (1, 'Patient A', 'Arizona Remote', 'Female'), (2, 'Patient B', 'Arizona Remote', 'Male'), (3, 'Patient C', 'Arizona Urban', 'Female'), (4, 'Patient D', 'Arizona Urban', 'Non-binary');

SELECT COUNT(*) as patient_count, gender FROM patients WHERE location LIKE '%Arizona Remote%' GROUP BY gender;


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

CREATE TABLE table_name_99 (result VARCHAR, score VARCHAR)

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


Question: Generate PostgreSQL SQL for: When 6.00 is the land area in kilometers squared what is the highest population of 2011?

CREATE TABLE table_189598_7 (population__2011_ INTEGER, land_area__km²_ VARCHAR)

SELECT MAX(population__2011_) FROM table_189598_7 WHERE land_area__km²_ = '6.00';


Question: Find the warehouse with the highest average package weight in the 'northeast' region.

CREATE TABLE warehouses (id INT, name TEXT, region TEXT); INSERT INTO warehouses (id, name, region) VALUES (1, 'Boston Warehouse', 'northeast'), (2, 'New York Warehouse', 'northeast'); CREATE TABLE packages (id INT, warehouse_id INT, weight FLOAT, state TEXT); INSERT INTO packages (id, warehouse_id, weight, state) VALUES (1, 1, 28.5, 'Massachusetts'), (2, 1, 23.3, 'New York'), (3, 2, 30.8, 'New York');

SELECT w.name FROM warehouses w JOIN (SELECT warehouse_id, MAX(avg_weight) as avg_weight FROM (SELECT warehouse_id, AVG(weight) as avg_weight FROM packages GROUP BY warehouse_id) sub) max_weight ON w.id = max_weight.warehouse_id WHERE w.region = 'northeast';


Question: Generate PostgreSQL SQL for: Which continent has the most diverse languages?

CREATE TABLE countrylanguage (CountryCode VARCHAR); CREATE TABLE country (Continent VARCHAR, Code VARCHAR)

SELECT T1.Continent FROM country AS T1 JOIN countrylanguage AS T2 ON T1.Code = T2.CountryCode GROUP BY T1.Continent ORDER BY COUNT(*) DESC LIMIT 1;


Question: List all military equipment sales in the European Union

CREATE TABLE military_equipment_sales (id INT, country VARCHAR(255), sale_value FLOAT); INSERT INTO military_equipment_sales (id, country, sale_value) VALUES (1, 'Country A', 2000000); INSERT INTO military_equipment_sales (id, country, sale_value) VALUES (2, 'Country B', 3000000);

SELECT sale_value FROM military_equipment_sales WHERE country IN ('European Union');


Question: Generate PostgreSQL SQL for: Name the total number of value for revenue more than 193 and rank less than 12 for manchester united

CREATE TABLE table_name_21 (value__ VARCHAR, team VARCHAR, revenue__$m_ VARCHAR, rank VARCHAR)

SELECT COUNT(value__) AS $m_ FROM table_name_21 WHERE revenue__$m_ > 193 AND rank < 12 AND team = 'manchester united';


Question: List all employees who have not completed the required safety training for their department.

CREATE TABLE Employees (id INT, name VARCHAR(255), department VARCHAR(255)); CREATE TABLE Training (id INT, employee INT, completed BOOLEAN); INSERT INTO Employees (id, name, department) VALUES (1, 'John Doe', 'DeptA'), (2, 'Jane Smith', 'DeptB'); INSERT INTO Training (id, employee, completed) VALUES (1, 1, TRUE), (2, 2, FALSE);

SELECT e.name, e.department FROM Employees e LEFT JOIN Training t ON e.id = t.employee WHERE t.completed IS NULL;


Question: What is the total water usage in Cairo and Istanbul?

CREATE TABLE water_usage_ME (city VARCHAR(50), usage INT); INSERT INTO water_usage_ME (city, usage) VALUES ('Cairo', 12000), ('Istanbul', 8000);

SELECT SUM(usage) FROM water_usage_ME WHERE city IN ('Cairo', 'Istanbul');


Question: PostgreSQL regression test 'xmlmap': Write the SELECT query (example 14).

SELECT table_to_xmlschema('testxmlschema.test1', true, false, '');

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

SELECT count(*) FROM (SELECT table_to_xmlschema('testxmlschema.test1', true, false, '')) AS _sub;


Question: Generate PostgreSQL SQL for: How many people were in attendance on may 17?

CREATE TABLE table_name_7 (attendance INTEGER, date VARCHAR)

SELECT MIN(attendance) FROM table_name_7 WHERE date = 'may 17';


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

INSERT INTO num_typemod_test (millionths) VALUES (0.0009995);

Explanation: DML from PostgreSQL core regression test for Numeric.


Question: Show a SQL definition from the pg_partman project (pg_partman--3.2.1--4.0.0, item 1).

-- IMPORTANT POSTGRESQL 11 UPGRADE STEPS
    -- All foreign keys, any non-unique indexes, and any unique indexes that include the partition key must be created on the actual parent table and removed from the template table for those property inheritances to continue working. Foreign key inheritance from the template table no longer works at all.
    -- Any unique indexes or primary keys that do not include the partition column must still use the template table in order to be inherited to child tables.
    -- Indexes defined on the parent will take precidence over those defined on the template table. Duplicate indexes should not happen. If they do, please report this as a bug.

-- Note that if this version is installed on PG10 and older, the procedures will not be created. A migration script to update pg_partman to include those will be made available once PG11 stable has been released.

-- Major change in privilege/security of this extension. SECURITY DEFINER is no longer in use to cause most of pg_partman's functions to run as the owner of the called function. This is mostly due to the requirements to support PROCEDUREs in PG11, but it's also generally a better idea for security in the long run.
    -- It is recommended to create a dedicated role for pg_partman maintenance runs and give it the privileges outlined in the setup section of the top level README.
    -- The role running maintenance must now have permissions to create tables in the target schema. If you start seeing permission errors after upgrading, this is most likely what needs to be fixed.
    -- The role running maintenance must now always be the owner of the tables it is managing. This shouldn't be too drastic of a change since previously it was making the maintenace function owner the owner of the partitioned tables. However, if you've changed partition table ownership after initial creation, you may run into issues until you set the pg_partman role as the owner.
    -- If you are using logical replication, the partman maintenance role must be the owner of the publication in use.
    -- As a bonus, the ALTER DEFAULT PRIVILEGES feature should now be much easier to use since you have a dedicated role for maintaining partitions. Check the documentation for this feature so that you can set any read/write privileges you want new partition sets to have at the time they are initially created.
    -- Two functions retain their SECURITY DEFINER status:
        -- check_name_length() - Used inside the trigger function and I don't want to break existing installations. It's an IMMUTABLE function so the security implications aren't that great.
        -- apply_privileges() - Requires access to pg_authid & also potentially changes object ownership.
    -- If you're using pg_jobmon, privileges for that extension are managed independently of pg_partman. See that extension's documentation for privileges it requires.

-- For PostgreSQL 11+, started conversion of some python scripts into PROCEDUREs that are now installed within the database. Scripts are still available for pre-11 versions, but will be phased out as soon as PG10 is no longer under support.
    -- Note that the user that calls these procedures must have permissions to write to the partition set and create/drop partitions in the set.
    -- partition_data.py script is now the partition_data_proc() PROCEDURE.
    -- undo_partition.py script is now the undo_partition_proc() PROCEDURE.
    -- reapply_constraints.py is now the reapply_constraints_proc() PROCEDURE.
    -- reapply_foreign_keys.py not converted since it's not needed for PG11+. Foreign keys can be applied to the parent and will automatically be inherited.
    -- reapply_indexes.py was not converted yet because concurrent index creation is not yet possible inside a PROCEDURE.
    -- Unable to turn autovacuum off/on reliably in PROCEDURE as was previously done with python scripts. If autovac is an issue when (un)partitioning large tables, recommend manually disabling it.

-- Consolidated undo_partition_time(), undo_partition_id(), and undo_partition_native() functions into a single undo_partition() function.
-- The old undo_partition() function that just copied data from child tables to the parent has been removed. The only utility this really had was a possible way to support undoing partition sets not maintained by pg_partman. With native partitioning now in place, its continued usability is now questionable and it was also causing confusion since people were using it and not the previous ones specialized for pg_partman. Can incorporate back in if someone can provide a further beneficial use case.

-- For PG11+, a DEFAULT partition is automatically created as part of the partition set to handle any data that does not have a matching child table.
    -- It's just given a _default suffix on the existing parent table name.
    -- Support within pg_partman for moving data out of the default partition is not included in 4.0.0, but will be included in a future release.
    -- New parameter to show_partitions() can include the DEFAULT in its output, but it's not output unless specifically requested since it's not commonly needed in internal code where it's mostly used.

-- For native partitioning, added option to give a "source" table to the partition_data*() functions that is different from the parent table of the partition set. This assists with partitioning an existing table to a natively partitioned table.

-- For PostgreSQL 11+, run_maintenance_proc() has been added and should cause much less contention when running against many large partition sets in a single call.
    -- For PG11+, this is the preferred maintenance method to run over the old run_maintenance() function. The old one will continue to work for the next few major releases, but please update all pg_partman maintenence calls in your environment to use the new procedure.

-- Simplified --type argument for undo_partition.py script for PG versions 10 and below. Similar to create_parent(), values are now 'partman' or 'native'.

-- Maintenance that creates new partitions on PG11+ and is using native partitioning will no longer analyze the partition sets by default. This should greatly cut down on maintenance run time and contention issues. If you're noticing any odd query plans, especially if you're using additionally configured constraints, you may need to schedule some manual analyzes or you can set the p_analyze parameter in either the function or procedure call to "true".

-- Fixed bug in run_maintenance() with subpartitioning where it would throw an error if retention dropped one of the parent tables undergoing maintenance.

-- Fixed template table inheritance for PG10 not working on minor version PostgreSQL 10.0 (but you really shouldn't be running this version anymore).

-- Fixed compilation errors for background worker against PostgreSQL 11.

-- ########################  START POSTGRESQL 11 ONLY SECTION ##############################
DO $pg11only$
DECLARE

v_partition_data_sql        text;

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


Question: Generate PostgreSQL SQL for: What were the highest losses for a byes larger than 2?

CREATE TABLE table_name_99 (losses INTEGER, byes INTEGER)

SELECT MAX(losses) FROM table_name_99 WHERE byes > 2;


Question: Generate PostgreSQL SQL for: What position does allister brown play.

CREATE TABLE table_2850912_12 (position VARCHAR, player VARCHAR)

SELECT position FROM table_2850912_12 WHERE player = 'Allister Brown';


Question: Generate PostgreSQL SQL for: What Player has less than 10 Touchdowns and 0 Extra points and more than 5 Points?

CREATE TABLE table_name_77 (player VARCHAR, points VARCHAR, touchdowns VARCHAR, extra_points VARCHAR)

SELECT player FROM table_name_77 WHERE touchdowns < 10 AND extra_points = 0 AND points > 5;


Question: Generate PostgreSQL SQL for: What is the total number of Maidens when E.R. is less than 9.5, and a Overs Bowled larger than 57, and a Wickets of 9?

CREATE TABLE table_name_95 (maidens VARCHAR, wickets VARCHAR, er VARCHAR, overs_bowled VARCHAR)

SELECT COUNT(maidens) FROM table_name_95 WHERE er < 9.5 AND overs_bowled > 57 AND wickets = 9;


Question: Update the 'start_date' of the 'Unmanned Aerial Vehicle' project for 'Brown Security' to 2024-01-01 if the current start_date is before 2024-01-01.

CREATE TABLE BrownSecurityProjects(id INT, contractor VARCHAR(255), project VARCHAR(255), start_date DATE, end_date DATE);INSERT INTO BrownSecurityProjects(id, contractor, project, start_date, end_date) VALUES (1, 'Brown Security', 'Unmanned Aerial Vehicle', '2023-01-01', '2025-12-31');

UPDATE BrownSecurityProjects SET start_date = '2024-01-01' WHERE contractor = 'Brown Security' AND project = 'Unmanned Aerial Vehicle' AND start_date < '2024-01-01';


Question: Delete all player records from the 'Players to Delete' list.

CREATE TABLE players (id INT, name VARCHAR(255), age INT, country VARCHAR(255)); CREATE TABLE players_to_delete (id INT); INSERT INTO players (id, name, age, country) VALUES (1, 'John Doe', 25, 'USA'), (2, 'Jane Doe', 30, 'Canada'); INSERT INTO players_to_delete (id) VALUES (1), (3);

DELETE FROM players WHERE id IN (SELECT id FROM players_to_delete);


Question: PL/pgSQL test: Plpgsql Domain (example 49).

--
-- Domains within composite
--

CREATE TYPE nnint_container AS (f1 int, f2 nnint);

Explanation: PL/pgSQL example from PostgreSQL source test for Plpgsql Domain.


Question: Generate PostgreSQL SQL for: Who are enrolled in 2 degree programs in one semester? List the first name, middle name and last name and the id.

CREATE TABLE Students (first_name VARCHAR, middle_name VARCHAR, last_name VARCHAR, student_id VARCHAR); CREATE TABLE Student_Enrolment (student_id VARCHAR)

SELECT T1.first_name, T1.middle_name, T1.last_name, T1.student_id FROM Students AS T1 JOIN Student_Enrolment AS T2 ON T1.student_id = T2.student_id GROUP BY T1.student_id HAVING COUNT(*) = 2;


Question: Delete all records from the Volunteers table where the VolunteerActivity is 'Clothing Drive'.

CREATE TABLE Volunteers (VolunteerID INT, VolunteerName VARCHAR(50), HoursSpent INT, VolunteerActivity VARCHAR(50), VolunteerDate DATE);

DELETE FROM Volunteers WHERE VolunteerActivity = 'Clothing Drive';


Question: get the number of unique customers in the 'Eco-friendly' size range

CREATE TABLE customers (id INT, name VARCHAR(50), size VARCHAR(20), sustainable_range BOOLEAN); INSERT INTO customers (id, name, size, sustainable_range) VALUES (1, 'Alice', 'M', true); INSERT INTO customers (id, name, size, sustainable_range) VALUES (2, 'Bob', 'XL', true); INSERT INTO customers (id, name, size, sustainable_range) VALUES (3, 'Charlie', 'S', false);

SELECT COUNT(DISTINCT id) FROM customers WHERE sustainable_range = true AND size IN ('XS', 'S', 'M', 'L', 'XL');


Question: What is the maximum weight of a penguin for each species?

CREATE TABLE penguins (id INT, species VARCHAR(20), weight FLOAT);

SELECT species, MAX(weight) FROM penguins GROUP BY species;


Question: What is the veteran employment rate in the state of New York?

CREATE TABLE veteran_employment (veteran_id INT, state VARCHAR(255), employed BOOLEAN); INSERT INTO veteran_employment (veteran_id, state, employed) VALUES (7, 'New York', TRUE), (8, 'New York', FALSE), (9, 'New York', TRUE);

SELECT (COUNT(*) - SUM(employed)) * 100.0 / COUNT(*) as employment_rate FROM veteran_employment WHERE state = 'New York';


Question: Retrieve the names and maintenance dates of structures in Texas with a resilience score greater than 85

CREATE TABLE Infrastructure (id INT, name VARCHAR(255), type VARCHAR(255), location VARCHAR(255), resilience_score INT); CREATE TABLE Maintenance (id INT, infrastructure_id INT, maintenance_date DATE); INSERT INTO Infrastructure (id, name, type, location, resilience_score) VALUES (1, 'Road A', 'Road', 'Texas', 88); INSERT INTO Infrastructure (id, name, type, location, resilience_score) VALUES (2, 'Bridge B', 'Bridge', 'California', 70); INSERT INTO Maintenance (id, infrastructure_id, maintenance_date) VALUES (1, 1, '2022-01-01'); INSERT INTO Maintenance (id, infrastructure_id, maintenance_date) VALUES (2, 2, '2022-02-01');

SELECT Infrastructure.name, Maintenance.maintenance_date FROM Infrastructure INNER JOIN Maintenance ON Infrastructure.id = Maintenance.infrastructure_id WHERE Infrastructure.location = 'Texas' AND Infrastructure.resilience_score > 85;


Question: PostgreSQL regression test 'jsonpath': Write the SELECT query (example 114).

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

SELECT count(*) FROM (select '$ ? (@.a < -0.1)'::jsonpath) AS _sub;


Question: What is the maximum range of Level 2 EV chargers?

CREATE TABLE Chargers (Id INT, Type VARCHAR(255), Manufacturer VARCHAR(255), Range INT); INSERT INTO Chargers (Id, Type, Manufacturer, Range) VALUES (1, 'Level 2', 'Blink', 25), (2, 'Level 2', 'ChargePoint', 30), (3, 'Level 2', 'EVgo', 28), (4, 'Level 2', 'SemaConnect', 32);

SELECT MAX(Range) FROM Chargers WHERE Type = 'Level 2';


Question: Generate PostgreSQL SQL for: What is 2nd Member, when Assembled is "30 March 1298"?

CREATE TABLE table_name_96 (assembled VARCHAR)

SELECT 2 AS nd_member FROM table_name_96 WHERE assembled = '30 march 1298';


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

Explanation: PostgreSQL CREATE CAST command.


Question: Generate PostgreSQL SQL for: With a house edge of 3.53% and a Non-Suited Matched of 3:1, name the Double Non-Suited Match.

CREATE TABLE table_name_99 (Double VARCHAR, non_suited_match VARCHAR, house_edge VARCHAR)

SELECT Double AS non_suited_match FROM table_name_99 WHERE non_suited_match = '3:1' AND house_edge = '3.53%';


Question: How many employees are there in each department?

CREATE TABLE Employees (EmployeeID INT, Name VARCHAR(50), Department VARCHAR(50), Position VARCHAR(50), Salary FLOAT); INSERT INTO Employees (EmployeeID, Name, Department, Position, Salary) VALUES (1, 'John Doe', 'IT', 'Developer', 75000.00), (2, 'Jane Smith', 'IT', 'Developer', 80000.00), (3, 'Alice Johnson', 'Marketing', 'Marketing Specialist', 60000.00), (4, 'Bob Brown', 'HR', 'HR Specialist', 65000.00);

SELECT Department, COUNT(*) FROM Employees GROUP BY Department;


Question: Generate PostgreSQL SQL for: Which players have a pick number of 27?

CREATE TABLE table_10975034_4 (player VARCHAR, pick__number VARCHAR)

SELECT player FROM table_10975034_4 WHERE pick__number = 27;


Question: How many passengers traveled on each route on a specific date?

SELECT r.route_name, t.trip_date, COUNT(t.route_id) AS passengers FROM trips t JOIN routes r ON t.route_id = r.route_id GROUP BY r.route_name, t.trip_date;


Question: How many unique volunteers worked on each project in 2022?

CREATE TABLE projects (id INT, name VARCHAR(50), start_date DATE, end_date DATE); CREATE TABLE volunteers (id INT, name VARCHAR(50), project_id INT, volunteer_date DATE); INSERT INTO projects (id, name, start_date, end_date) VALUES (1, 'Project A', '2022-01-01', '2022-12-31'), (2, 'Project B', '2022-07-01', '2022-12-31'); INSERT INTO volunteers (id, name, project_id, volunteer_date) VALUES (1, 'Volunteer 1', 1, '2022-02-01'), (2, 'Volunteer 2', 1, '2022-03-01'), (3, 'Volunteer 3', 2, '2022-08-01');

SELECT p.name, COUNT(DISTINCT v.id) AS num_volunteers FROM projects p JOIN volunteers v ON p.id = v.project_id WHERE YEAR(v.volunteer_date) = 2022 GROUP BY p.id;


Question: List all sustainable building practices in the state of Washington

CREATE TABLE sustainable_practices (practice_id INT, building_type VARCHAR(20), state VARCHAR(20), description TEXT); INSERT INTO sustainable_practices (practice_id, building_type, state, description) VALUES (1, 'Residential', 'WA', 'Use of recycled materials');

SELECT * FROM sustainable_practices WHERE state = 'WA';


Question: What was the total budget for community development initiatives in Africa in the year 2020?

CREATE TABLE community_development (id INT, initiative_name VARCHAR(50), location VARCHAR(50), budget FLOAT, implementation_date DATE); INSERT INTO community_development (id, initiative_name, location, budget, implementation_date) VALUES (1, 'Village Technology Center', 'Kenya', 35000.00, '2020-03-15');

SELECT SUM(budget) FROM community_development WHERE location LIKE '%Africa%' AND implementation_date >= '2020-01-01' AND implementation_date <= '2020-12-31';


Question: Generate PostgreSQL SQL for: Who is the director of the best foreign film?

CREATE TABLE table_name_14 (director VARCHAR, original_title VARCHAR)

SELECT director FROM table_name_14 WHERE original_title = 'best foreign film';


Question: What is the total revenue from cultural heritage experiences in Indonesia?

CREATE TABLE Countries (id INT, name VARCHAR(50)); INSERT INTO Countries (id, name) VALUES (1, 'Indonesia'); CREATE TABLE Transactions (id INT, country_id INT, experience_type VARCHAR(50), revenue INT); INSERT INTO Transactions (id, country_id, experience_type, revenue) VALUES (1, 1, 'Cultural Heritage', 800);

SELECT SUM(t.revenue) as total_revenue FROM Transactions t JOIN Countries c ON t.country_id = c.id WHERE t.experience_type = 'Cultural Heritage';


Question: Generate PostgreSQL SQL for: What is Date, when Against is "22"?

CREATE TABLE table_name_87 (date VARCHAR, against VARCHAR)

SELECT date FROM table_name_87 WHERE against = 22;


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

SELECT JSON_VALUE(jsonb '"123"', '$' RETURNING int) + 234;

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

SELECT count(*) FROM (SELECT JSON_VALUE(jsonb '"123"', '$' RETURNING int) + 234) AS _sub;


Question: Add a new entry to the 'virtual_reality_headsets' table with ID 5, name 'Oculus Rift S', and price 399

CREATE TABLE virtual_reality_headsets (id INT, name VARCHAR(255), price INT);

INSERT INTO virtual_reality_headsets (id, name, price) VALUES (5, 'Oculus Rift S', 399);


Question: Generate PostgreSQL SQL for: Which British has Examples of exit?

CREATE TABLE table_name_88 (british VARCHAR, examples VARCHAR)

SELECT british FROM table_name_88 WHERE examples = 'exit';


Question: What is the average engagement for virtual tours in the 'Europe' region?

CREATE TABLE virtual_tours_engagement (tour_id INT, name TEXT, region TEXT, engagement INT); INSERT INTO virtual_tours_engagement (tour_id, name, region, engagement) VALUES (1, 'Tour A', 'Americas', 1000), (2, 'Tour B', 'Europe', 800), (3, 'Tour C', 'Asia', 1200);

SELECT AVG(engagement) FROM virtual_tours_engagement WHERE region = 'Europe';


Question: What is the total weight of organic apples and bananas shipped from Costa Rica to New York in the first quarter of 2022?

CREATE TABLE shipments(id INT, product VARCHAR(20), weight FLOAT, country VARCHAR(20), date DATE); INSERT INTO shipments(id, product, weight, country, date) VALUES (1, 'apples', 500, 'Costa Rica', '2022-01-05'); INSERT INTO shipments(id, product, weight, country, date) VALUES (2, 'bananas', 800, 'Costa Rica', '2022-01-07');

SELECT SUM(weight) FROM shipments WHERE product IN ('apples', 'bananas') AND country = 'Costa Rica' AND date BETWEEN '2022-01-01' AND '2022-03-31' AND product LIKE 'organic%';


Question: Generate PostgreSQL SQL for: What was the score of the game when the record was 28–19?

CREATE TABLE table_name_62 (score VARCHAR, record VARCHAR)

SELECT score FROM table_name_62 WHERE record = '28–19';


Question: How many defense diplomacy events took place between India and Pakistan from 2015 to 2019?

CREATE TABLE DiplomacyEvents(Country1 NVARCHAR(50), Country2 NVARCHAR(50), EventType VARCHAR(50), Year INT);INSERT INTO DiplomacyEvents(Country1, Country2, EventType, Year) VALUES ('India', 'Pakistan', 'Defense Talks', 2015), ('Pakistan', 'India', 'Military Exercise', 2016), ('India', 'Pakistan', 'Joint Military Training', 2017), ('Pakistan', 'India', 'Defense Talks', 2018), ('India', 'Pakistan', 'Military Exercise', 2019);

SELECT COUNT(*) AS Total_Events FROM DiplomacyEvents WHERE (Country1 = 'India' AND Country2 = 'Pakistan') OR (Country1 = 'Pakistan' AND Country2 = 'India') AND Year BETWEEN 2015 AND 2019;


Question: Generate PostgreSQL SQL for: What was the attendance for the game after game 4?

CREATE TABLE table_name_96 (attendance VARCHAR, game INTEGER)

SELECT attendance FROM table_name_96 WHERE game > 4;


Question: How many steps did members take in total, in the past week, separated by membership type?

CREATE TABLE membership (member_id INT, membership_type VARCHAR(20), gender VARCHAR(10)); INSERT INTO membership (member_id, membership_type, gender) VALUES (1, 'Platinum', 'Female'), (2, 'Gold', 'Male'), (3, 'Platinum', 'Non-binary'); CREATE TABLE activity_data (member_id INT, steps INT, timestamp TIMESTAMP); INSERT INTO activity_data (member_id, steps, timestamp) VALUES (1, 5000, '2022-01-01 10:00:00'), (1, 7000, '2022-01-01 11:00:00'), (2, 8000, '2022-01-01 10:00:00'), (2, 9000, '2022-01-01 11:00:00'), (3, 4000, '2022-01-01 10:00:00'), (3, 6000, '2022-01-01 11:00:00');

SELECT membership_type, SUM(steps) as total_steps FROM activity_data a JOIN membership m ON a.member_id = m.member_id WHERE timestamp BETWEEN '2022-01-01 00:00:00' AND '2022-01-08 23:59:59' GROUP BY membership_type;


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

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

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


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

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


Question: What is the maximum duration of a single workout session for each member?

CREATE TABLE members (member_id INT, name VARCHAR(50), gender VARCHAR(10), dob DATE); INSERT INTO members (member_id, name, gender, dob) VALUES (1, 'Leila Alvarez', 'Female', '2002-04-02'); INSERT INTO members (member_id, name, gender, dob) VALUES (2, 'Mohammed Ibrahim', 'Male', '2000-11-28'); CREATE TABLE workout_sessions (session_id INT, member_id INT, session_date DATE, duration INT); INSERT INTO workout_sessions (session_id, member_id, session_date, duration) VALUES (1, 1, '2023-02-02', 45); INSERT INTO workout_sessions (session_id, member_id, session_date, duration) VALUES (2, 1, '2023-02-05', 60); INSERT INTO workout_sessions (session_id, member_id, session_date, duration) VALUES (3, 2, '2023-02-07', 75); INSERT INTO workout_sessions (session_id, member_id, session_date, duration) VALUES (4, 1, '2023-02-13', 30);

SELECT member_id, MAX(duration) AS max_duration FROM workout_sessions GROUP BY member_id;


Question: How many virtual tours were conducted in Japan in the past month?

CREATE TABLE virtual_tours (tour_id INT, tour_name TEXT, country TEXT, tour_date DATE); INSERT INTO virtual_tours (tour_id, tour_name, country, tour_date) VALUES (1, 'Mt. Fuji Tour', 'Japan', '2022-03-05'), (2, 'Tokyo City Tour', 'Japan', '2022-03-10');

SELECT COUNT(*) FROM virtual_tours WHERE country = 'Japan' AND tour_date >= DATEADD(day, -30, CURRENT_DATE);


Question: What is the total rainfall (in inches) for each region in Texas in the first half of 2022?

CREATE TABLE regions (id INT, name VARCHAR(255)); INSERT INTO regions (id, name) VALUES (1, 'RegionA'), (2, 'RegionB'), (3, 'RegionC'); CREATE TABLE rainfall (region_id INT, rainfall DECIMAL(5,2), date DATE); INSERT INTO rainfall (region_id, rainfall, date) VALUES (1, 2.5, '2022-01-01'), (1, 3.0, '2022-01-02'), (2, 1.5, '2022-01-01'), (2, 2.0, '2022-01-02'), (3, 3.5, '2022-01-01'), (3, 4.0, '2022-01-02');

SELECT region_id, SUM(rainfall) as total_rainfall FROM rainfall WHERE date BETWEEN '2022-01-01' AND '2022-06-30' GROUP BY region_id;


Question: Generate PostgreSQL SQL for: What was the result of the election of the incumbent harry r. sheppard?

CREATE TABLE table_1341973_6 (result VARCHAR, incumbent VARCHAR)

SELECT result FROM table_1341973_6 WHERE incumbent = 'Harry R. Sheppard';


Question: Write the DDL statement from PostgreSQL regression test 'sqljson_queryfuncs' (example 244).

CREATE INDEX ON test_jsonb_mutability (JSON_VALUE(js, '$' DEFAULT random()::int ON ERROR));

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


Question: Delete all shipments that were handled by the 'Sydney' warehouse.

CREATE TABLE Warehouse (id INT, name VARCHAR(20), city VARCHAR(20)); INSERT INTO Warehouse (id, name, city) VALUES (1, 'Sydney Warehouse', 'Sydney'); CREATE TABLE Handling (id INT, shipment_id INT, warehouse_id INT); INSERT INTO Handling (id, shipment_id, warehouse_id) VALUES (1, 101, 1), (2, 102, 1), (3, 103, 2); CREATE TABLE Shipment (id INT, weight INT); INSERT INTO Shipment (id, weight) VALUES (101, 10000), (102, 15000), (103, 8000);

DELETE FROM Shipment WHERE id IN (SELECT Handling.shipment_id FROM Handling JOIN Warehouse ON Handling.warehouse_id = Warehouse.id WHERE Warehouse.city = 'Sydney');


Question: Generate PostgreSQL SQL for: Who directed the episode that had 6.76 million U.S. viewers?

CREATE TABLE table_23242968_1 (directed_by VARCHAR, us_viewers__millions_ VARCHAR)

SELECT directed_by FROM table_23242968_1 WHERE us_viewers__millions_ = '6.76';


Question: Generate PostgreSQL SQL for: What was the largest crowd size at arden street oval?

CREATE TABLE table_name_58 (crowd INTEGER, venue VARCHAR)

SELECT MAX(crowd) FROM table_name_58 WHERE venue = 'arden street oval';


Question: Generate PostgreSQL SQL for: What team does the player who went to Nebraska play for?

CREATE TABLE table_21321804_3 (cfl_team VARCHAR, college VARCHAR)

SELECT cfl_team FROM table_21321804_3 WHERE college = 'Nebraska';


Question: What is the average CO2 emissions reduction achieved per sustainable fabric type, grouped by textile supplier?

CREATE TABLE TextileSuppliers (supplier_id INT, supplier_country VARCHAR(20), CO2_emissions_reduction FLOAT); CREATE TABLE Fabrics (fabric_id INT, fabric_type VARCHAR(20), supplier_id INT); INSERT INTO TextileSuppliers (supplier_id, supplier_country, CO2_emissions_reduction) VALUES (1, 'Italy', 15.2);

SELECT Fabrics.fabric_type, AVG(TextileSuppliers.CO2_emissions_reduction) as avg_reduction FROM Fabrics JOIN TextileSuppliers ON Fabrics.supplier_id = TextileSuppliers.supplier_id GROUP BY Fabrics.fabric_type;


Question: What is the total budget spent on each project in 2022?

CREATE TABLE Projects (id INT, project_name TEXT, budget_allocated FLOAT, start_date DATE);

SELECT project_name, SUM(budget_allocated) as total_budget_spent FROM Projects WHERE YEAR(start_date) = 2022 GROUP BY project_name;


Question: Generate PostgreSQL SQL for: Who wrote the episode with the production code of BN103?

CREATE TABLE table_21304155_1 (written_by VARCHAR, production_code VARCHAR)

SELECT written_by FROM table_21304155_1 WHERE production_code = 'BN103';


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

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


Question: How many unique clothing items were produced in size XS and size XXL in the first quarter of 2021?

CREATE TABLE ClothingItems (ItemID INT, ItemName TEXT, Size TEXT, ProductionDate DATE); INSERT INTO ClothingItems (ItemID, ItemName, Size, ProductionDate) VALUES (1, 'Organic Cotton T-Shirt', 'XS', '2021-01-05'), (2, 'Bamboo Viscose Blouse', 'XXL', '2021-01-10'), (3, 'Recycled Polyester Pants', 'XS', '2021-02-15'), (4, 'Tencel Jacket', 'XXL', '2021-03-01');

SELECT COUNT(DISTINCT ItemID) as UniqueItems FROM ClothingItems WHERE Size IN ('XS', 'XXL') AND ProductionDate BETWEEN '2021-01-01' AND '2021-03-31';


Question: Generate PostgreSQL SQL for: Which giant slalom had an Overall number of 25?

CREATE TABLE table_name_34 (Giant VARCHAR, overall VARCHAR)

SELECT Giant AS slalom FROM table_name_34 WHERE overall = 25;


Question: Generate PostgreSQL SQL for: What is the lowest pick number for the Russian Major League?

CREATE TABLE table_name_70 (pick__number INTEGER, league_from VARCHAR)

SELECT MIN(pick__number) FROM table_name_70 WHERE league_from = 'russian major league';


Question: Generate PostgreSQL SQL for: Which Reason is given when 1103 is the date for Became heir?

CREATE TABLE table_name_7 (reason VARCHAR, became_heir VARCHAR)

SELECT reason FROM table_name_7 WHERE became_heir = '1103';


Question: Generate PostgreSQL SQL for: If the Away team is essendon, what was the Date they played?

CREATE TABLE table_name_62 (date VARCHAR, away_team VARCHAR)

SELECT date FROM table_name_62 WHERE away_team = 'essendon';


Question: Generate PostgreSQL SQL for: What production code does episode 174 of Melrose place have?

CREATE TABLE table_name_92 (production_code VARCHAR, no_in_series VARCHAR)

SELECT production_code FROM table_name_92 WHERE no_in_series = 174;


Question: Generate PostgreSQL SQL for: What is Alexandr Elke's Weight?

CREATE TABLE table_name_59 (weight VARCHAR, name VARCHAR)

SELECT weight FROM table_name_59 WHERE name = 'alexandr elke';


Question: Find carbon offset initiatives in Australia and their corresponding funded amounts.

CREATE TABLE carbon_offsets (id INT, country VARCHAR(255), initiative VARCHAR(255), funded_amount INT); INSERT INTO carbon_offsets (id, country, initiative, funded_amount) VALUES (1, 'Australia', 'Tree planting', 50000), (2, 'Australia', 'Renewable energy', 100000), (3, 'Canada', 'Energy efficiency', 75000);

SELECT initiative, funded_amount FROM carbon_offsets WHERE country = 'Australia';


Question: List all pollution control initiatives in the North Atlantic and their corresponding funding amounts.

CREATE TABLE pollution_control_initiatives (id INT, initiative TEXT, region TEXT, funding FLOAT); INSERT INTO pollution_control_initiatives (id, initiative, region, funding) VALUES (1, 'Initiative X', 'North Atlantic', 500000), (2, 'Initiative Y', 'Arctic', 700000), (3, 'Initiative Z', 'North Atlantic', 600000);

SELECT initiative, funding FROM pollution_control_initiatives WHERE region = 'North Atlantic';


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

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


Question: Generate PostgreSQL SQL for: How many categories for elapsed time exist for the $16.50 fixed-limit badugi game?

CREATE TABLE table_22050544_3 (elapsed_time VARCHAR, event VARCHAR)

SELECT COUNT(elapsed_time) FROM table_22050544_3 WHERE event = '$16.50 Fixed-Limit Badugi';


Question: Calculate the average daily water consumption in the state of Rajasthan, India for the month of May

CREATE TABLE states (id INT, name VARCHAR(255)); INSERT INTO states (id, name) VALUES (1, 'Rajasthan'); CREATE TABLE water_meter_readings (id INT, state_id INT, consumption FLOAT, reading_date DATE); INSERT INTO water_meter_readings (id, state_id, consumption, reading_date) VALUES (1, 1, 100, '2022-05-01');

SELECT AVG(water_meter_readings.consumption) as avg_daily_consumption FROM water_meter_readings WHERE water_meter_readings.reading_date >= '2022-05-01' AND water_meter_readings.reading_date <= '2022-05-31' AND water_meter_readings.state_id IN (SELECT id FROM states WHERE name = 'Rajasthan');


Question: What is the total budget for education in Ontario?

CREATE TABLE budgets (id INT, category VARCHAR(50), amount INT, province VARCHAR(20)); INSERT INTO budgets (id, category, amount, province) VALUES (1, 'Education', 30000000, 'Ontario'); INSERT INTO budgets (id, category, amount, province) VALUES (2, 'Healthcare', 40000000, 'Ontario');

SELECT SUM(amount) FROM budgets WHERE category = 'Education' AND province = 'Ontario';


Question: What is the average soil moisture level for crops in the 'South' region?

CREATE TABLE IoTDevices (device_id INT, device_type VARCHAR(20), region VARCHAR(10), moisture FLOAT); INSERT INTO IoTDevices (device_id, device_type, region, moisture) VALUES (1, 'Soil Moisture Sensor', 'West', 50.5); INSERT INTO IoTDevices (device_id, device_type, region, moisture) VALUES (2, 'Soil Moisture Sensor', 'East', 55.3); INSERT INTO IoTDevices (device_id, device_type, region, moisture) VALUES (3, 'Soil Moisture Sensor', 'North', 60.1); INSERT INTO IoTDevices (device_id, device_type, region, moisture) VALUES (4, 'Soil Moisture Sensor', 'South', 65.7);

SELECT AVG(moisture) FROM IoTDevices WHERE region = 'South';


Question: Generate PostgreSQL SQL for: Bhiwani district have what constituency number?

CREATE TABLE table_name_37 (constituency_number VARCHAR, district VARCHAR)

SELECT constituency_number FROM table_name_37 WHERE district = 'bhiwani';


Question: How many public hospitals are there in each location type?

CREATE TABLE hospitals (name VARCHAR(50), type VARCHAR(50), beds INT, location VARCHAR(50)); INSERT INTO hospitals (name, type, beds, location) VALUES ('Hospital A', 'Public', 300, 'City'); INSERT INTO hospitals (name, type, beds, location) VALUES ('Hospital B', 'Private', 200, 'Suburban'); INSERT INTO hospitals (name, type, beds, location) VALUES ('Hospital C', 'Public', 400, 'Rural');

SELECT location, COUNT(*) as NumPublicHospitals FROM hospitals WHERE type = 'Public' GROUP BY location;


Question: Generate PostgreSQL SQL for: What is the Score of a Record 24–23–3?

CREATE TABLE table_name_69 (score VARCHAR, record VARCHAR)

SELECT score FROM table_name_69 WHERE record = '24–23–3';


Question: pgTAP test for Proctap (assertion 16).

SELECT * FROM check_test(
    isnt_procedure( 'procschema', 'argproc', ARRAY['integer', 'text'], 'whatever' ),
    false,
    'isnt_procedure(schema, proc, args, desc)',
    'whatever',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Proctap.


Question: Which countries have the most organizations working on accessible technology?

CREATE TABLE accessible_tech (organization_name TEXT, country TEXT); INSERT INTO accessible_tech (organization_name, country) VALUES ('AccessibleTech', 'Canada'), ('EqualTech', 'United States'), ('InclusiveTech', 'United Kingdom'), ('AccessTech', 'Canada'), ('EqualAI', 'United States');

SELECT country, COUNT(*) as organization_count FROM accessible_tech GROUP BY country ORDER BY organization_count DESC;


Question: PostgreSQL Rangetypes: show example 6.

CREATE TYPE floatrange AS RANGE ( subtype = float8, subtype_diff = float8mi ); SELECT '[1.234, 5.678]'::floatrange;

Explanation: Example from PostgreSQL documentation on Rangetypes.


Question: Generate PostgreSQL SQL for: What is the crowd size of the game at Brunswick Street Oval?

CREATE TABLE table_name_61 (crowd INTEGER, venue VARCHAR)

SELECT SUM(crowd) FROM table_name_61 WHERE venue = 'brunswick street oval';


Question: What is the budget for each military technology program in the United Kingdom?

CREATE TABLE MilitaryTechnology (id INT, country VARCHAR(255), program VARCHAR(255), budget FLOAT); INSERT INTO MilitaryTechnology (id, country, program, budget) VALUES (1, 'United Kingdom', 'F-35B Lightning II', 3500000); INSERT INTO MilitaryTechnology (id, country, program, budget) VALUES (2, 'United Kingdom', 'Type 45 Destroyer', 1200000);

SELECT program, budget FROM MilitaryTechnology WHERE country = 'United Kingdom';


Question: Generate PostgreSQL SQL for: What is the save of the game that 23,394 people attended?

CREATE TABLE table_name_49 (save VARCHAR, attendance VARCHAR)

SELECT save FROM table_name_49 WHERE attendance = '23,394';


Question: Generate PostgreSQL SQL for: How many points did Goole Town accumulate?

CREATE TABLE table_17358515_1 (points_2 VARCHAR, team VARCHAR)

SELECT COUNT(points_2) FROM table_17358515_1 WHERE team = 'Goole Town';


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

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

SELECT count(*) FROM (SELECT interval '1 2' day to minute) AS _sub;


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

SELECT * FROM ltreetest WHERE t ? '{23.*.1,23.*.2}' order by t asc;


Question: Generate PostgreSQL SQL for: What is the average rank Finland, which has 1 bronze, more than 1 silver, and less than 0 gold, has?

CREATE TABLE table_name_6 (rank INTEGER, gold VARCHAR, nation VARCHAR, bronze VARCHAR, silver VARCHAR)

SELECT AVG(rank) FROM table_name_6 WHERE bronze = 1 AND silver > 1 AND nation = 'finland' AND gold < 0;


Question: What are the origins of the ethical clothing products?

CREATE TABLE EthicalClothing (product_id INT, product_name TEXT, origin TEXT); INSERT INTO EthicalClothing (product_id, product_name, origin) VALUES (1, 'Organic Cotton T-Shirt', 'Nepal'), (2, 'Hemp Pants', 'China'), (3, 'Recycled Polyester Jacket', 'Haiti');

SELECT DISTINCT origin FROM EthicalClothing;


Question: What is the total number of farms that have implemented agroforestry practices in the agroforestry_practices dataset?

CREATE TABLE agroforestry_practices (id INT, farm_id INT, agroforestry_practice BOOLEAN);

SELECT COUNT(*) FROM agroforestry_practices WHERE agroforestry_practice = TRUE;


Question: Find the total number of labor rights violations for unions that have a focus on worker safety.

CREATE TABLE union_violation_safety (union_id INT, violation_count INT, safety_focus BOOLEAN); INSERT INTO union_violation_safety (union_id, violation_count, safety_focus) VALUES (1, 10, true), (2, 20, false), (3, 30, true), (4, 40, true);

SELECT SUM(union_violation_safety.violation_count) FROM union_violation_safety WHERE union_violation_safety.safety_focus = true;


Question: Generate PostgreSQL SQL for: What is the total of overall values with a safety position in a round greater than 1?

CREATE TABLE table_name_26 (overall VARCHAR, position VARCHAR, round VARCHAR)

SELECT COUNT(overall) FROM table_name_26 WHERE position = 'safety' AND round > 1;


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

SELECT count(*) FROM vchartmp WHERE a >=  '31b0'::varchar(32);


Question: Generate PostgreSQL SQL for: What Chassis has g Tyres before 1987?

CREATE TABLE table_name_26 (chassis VARCHAR, tyres VARCHAR, year VARCHAR)

SELECT chassis FROM table_name_26 WHERE tyres = 'g' AND year < 1987;


Question: PostgreSQL regression test 'bit': Write the SELECT query (example 25).

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

SELECT count(*) FROM (SELECT SUBSTRING('01010101'::bit(8) FROM -10 FOR -2147483646) AS "error") AS _sub;


Question: Generate PostgreSQL SQL for: What is the shooting preference of Matthew Myers, acquired in 2010?

CREATE TABLE table_name_99 (shoots VARCHAR, acquired VARCHAR, player VARCHAR)

SELECT shoots FROM table_name_99 WHERE acquired = 2010 AND player = 'matthew myers';


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

select 'abc abc abd' ~ '^(.+)( \1)+$' as f;

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

SELECT count(*) FROM (select 'abc abc abd' ~ '^(.+)( \1)+$' as f) AS _sub;


Question: Generate PostgreSQL SQL for: What type of government does Kyrgyzstan have?

CREATE TABLE table_1604579_2 (country VARCHAR)

SELECT 2012 AS _democracy_index FROM table_1604579_2 WHERE country = 'Kyrgyzstan';


Question: How many legal cases were opened and closed in each borough of New York City in the last year?

CREATE TABLE legal_cases (case_number INT, borough TEXT, open_date DATE, close_date DATE); INSERT INTO legal_cases (case_number, borough, open_date, close_date) VALUES (1, 'Manhattan', '2021-01-01', '2021-03-01'), (2, 'Brooklyn', '2021-02-01', '2021-04-01'), (3, 'Queens', '2021-03-01', '2021-06-01'), (4, 'Bronx', '2021-04-01', '2021-07-01');

SELECT borough, COUNT(*) AS cases_opened FROM legal_cases WHERE open_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR) GROUP BY borough; SELECT borough, COUNT(*) AS cases_closed FROM legal_cases WHERE close_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR) GROUP BY borough;


Question: How many total attendees participated in events organized by the Cultural Center?

CREATE TABLE Venues (id INT PRIMARY KEY, name VARCHAR(20)); CREATE TABLE Events (id INT PRIMARY KEY, name VARCHAR(20), venue VARCHAR(20), attendees INT); INSERT INTO Venues (id, name) VALUES (1, 'Cultural Center'); INSERT INTO Events (id, name, venue, attendees) VALUES (1, 'Dance Performance', 'Cultural Center', 100); INSERT INTO Events (id, name, venue, attendees) VALUES (2, 'Music Concert', 'Art Gallery', 50);

SELECT SUM(attendees) FROM Events WHERE venue = 'Cultural Center';


Question: What is the maximum price per gram of flower sold by Grower B in Q1 2022?

CREATE TABLE grow (id INT, grower VARCHAR(255), product VARCHAR(255), price FLOAT, gram_weight FLOAT); INSERT INTO grow (id, grower, product, price, gram_weight) VALUES (1, 'Grower B', 'Flower', 15.0, 3.5);

SELECT MAX(price / gram_weight) FROM grow WHERE grower = 'Grower B' AND product = 'Flower' AND QUARTER(sale_date) = 1 AND YEAR(sale_date) = 2022;


Question: Generate PostgreSQL SQL for: What is the highest Total, when Season is "1996-97", and when Second is less than 33?

CREATE TABLE table_name_23 (total INTEGER, season VARCHAR, second VARCHAR)

SELECT MAX(total) FROM table_name_23 WHERE season = '1996-97' AND second < 33;


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

$$ language plpgsql;

select forc01();

-- try updating the cursor's current row

create temp table forc_test as
  select n as i, n as j from generate_series(1,10) n;

create or replace function forc01() returns void as $$
declare
  c cursor for select * from forc_test;

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