Question: Generate PostgreSQL SQL for: What date has 0-6700-30838-2-9 for a catalog?

CREATE TABLE table_name_88 (date VARCHAR, catalog VARCHAR)

SELECT date FROM table_name_88 WHERE catalog = '0-6700-30838-2-9';


Question: Generate PostgreSQL SQL for: What is the high capacity that has an average under 489 and a highest over 778?

CREATE TABLE table_name_90 (capacity INTEGER, average VARCHAR, highest VARCHAR)

SELECT MAX(capacity) FROM table_name_90 WHERE average < 489 AND highest > 778;


Question: What is the average delivery time for shipments to 'Africa' after the 15th of each month?

CREATE TABLE shipments (id INT, delivery_date DATE, destination VARCHAR(20), delivery_time INT); INSERT INTO shipments (id, delivery_date, destination, delivery_time) VALUES (1, '2022-02-20', 'Africa', 4), (2, '2022-03-07', 'Europe', 6), (3, '2022-02-25', 'Africa', 5);

SELECT AVG(delivery_time) FROM shipments WHERE delivery_date >= DATEADD(day, 15, EOMONTH(delivery_date)) AND destination = 'Africa';


Question: Generate PostgreSQL SQL for: List the names of all routes in alphabetic order.

CREATE TABLE Delivery_Routes (route_name VARCHAR)

SELECT route_name FROM Delivery_Routes ORDER BY route_name;


Question: How many volunteers signed up in 2021 from Australia?

CREATE TABLE volunteers (id INT, name TEXT, country TEXT, signup_date DATE); INSERT INTO volunteers (id, name, country, signup_date) VALUES (1, 'Alex Johnson', 'Australia', '2021-02-12'), (2, 'Bruce Lee', 'USA', '2020-05-23');

SELECT COUNT(*) FROM volunteers WHERE country = 'Australia' AND YEAR(signup_date) = 2021;


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

UPDATE temporal_rng
  SET valid_at = CASE WHEN lower(valid_at) = '2018-01-01' THEN daterange('2018-01-01', '2018-01-05')
                      WHEN lower(valid_at) = '2018-02-01' THEN daterange('2018-01-05', '2018-03-01') END
  WHERE id = '[6,7)';

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


Question: Which users have participated in 'Zumba' workouts in the 'workout_data' table?

CREATE TABLE workout_data (user_id INT, workout_type VARCHAR(20), duration INT); INSERT INTO workout_data (user_id, workout_type, duration) VALUES (1, 'Running', 30), (1, 'Cycling', 60), (2, 'Yoga', 45), (3, 'Pilates', 50), (6, 'Zumba', 75), (7, 'Zumba', 90);

SELECT DISTINCT user_id FROM workout_data WHERE workout_type = 'Zumba';


Question: Find the maximum price of sustainable footwear

CREATE TABLE footwear (id INT, category VARCHAR(50), subcategory VARCHAR(50), is_sustainable BOOLEAN, price DECIMAL(5,2)); INSERT INTO footwear (id, category, subcategory, is_sustainable, price) VALUES (1, 'Footwear', 'Sneakers', TRUE, 120.00), (2, 'Footwear', 'Sneakers', TRUE, 150.00), (3, 'Footwear', 'Sandals', FALSE, 60.00), (4, 'Footwear', 'Boots', TRUE, 200.00), (5, 'Footwear', 'Loafers', FALSE, 90.00);

SELECT MAX(price) FROM footwear WHERE subcategory = 'Sneakers' AND is_sustainable = TRUE;


Question: Generate PostgreSQL SQL for: Which club is associated with Hafiz Abu Sujad?

CREATE TABLE table_name_80 (club VARCHAR, name VARCHAR)

SELECT club FROM table_name_80 WHERE name = 'hafiz abu sujad';


Question: Generate PostgreSQL SQL for: What is the average height for hewitt class, with prom less than 86, and a Peak of gragareth?

CREATE TABLE table_name_45 (height__m_ INTEGER, peak VARCHAR, class VARCHAR, prom__m_ VARCHAR)

SELECT AVG(height__m_) FROM table_name_45 WHERE class = 'hewitt' AND prom__m_ < 86 AND peak = 'gragareth';


Question: What is the total number of defense diplomacy events in each region?

CREATE TABLE Defense_Diplomacy (Event_ID INT, Event_Name VARCHAR(50), Start_Date DATE, Region VARCHAR(50)); INSERT INTO Defense_Diplomacy (Event_ID, Event_Name, Start_Date, Region) VALUES (1, 'Defense Summit', '2000-01-01', 'North America');

SELECT Region, COUNT(*) as Total_Events FROM Defense_Diplomacy GROUP BY Region;


Question: What is the average distance from rural healthcare facilities to the nearest urban center in South Africa and Kenya?

CREATE TABLE facilities (name TEXT, location TEXT, distance INTEGER); INSERT INTO facilities (name, location, distance) VALUES ('Facility X', 'Rural South Africa', 100), ('Facility Y', 'Rural Kenya', 80);

SELECT AVG(distance) FROM facilities WHERE location LIKE 'Rural%';


Question: Generate PostgreSQL SQL for: Name the mccain % for dukes

CREATE TABLE table_15929156_3 (mccain__percentage VARCHAR, county VARCHAR)

SELECT mccain__percentage FROM table_15929156_3 WHERE county = 'Dukes';


Question: What is the total number of articles published in the "articles" table that have more than 500 words?

CREATE TABLE articles (id INT, title VARCHAR(100), word_count INT, publication_date DATE, category VARCHAR(50));

SELECT COUNT(*) FROM articles WHERE word_count > 500;


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

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

SELECT count(*) FROM (select jsonb_path_query('{}', '$.double()')) AS _sub;


Question: Find the total number of games and unique genres for each platform, excluding PC games.

CREATE TABLE Games (GameID INT, GameName VARCHAR(50), Platform VARCHAR(10), GameGenre VARCHAR(20));

SELECT Platform, COUNT(DISTINCT GameGenre) AS Unique_Genres, COUNT(*) AS Total_Games FROM Games WHERE Platform != 'PC' GROUP BY Platform;


Question: Generate PostgreSQL SQL for: What was the season record when the location attendance was Air Canada Centre 19,800?

CREATE TABLE table_name_26 (record VARCHAR, location_attendance VARCHAR)

SELECT record FROM table_name_26 WHERE location_attendance = 'air canada centre 19,800';


Question: Generate PostgreSQL SQL for: What was the biggest draws, for wins under 4, and points of 20-18?

CREATE TABLE table_name_29 (draws INTEGER, points VARCHAR, wins VARCHAR)

SELECT MAX(draws) FROM table_name_29 WHERE points = '20-18' AND wins < 4;


Question: Generate PostgreSQL SQL for: What is the sum of qualifying scores when the final score is 16.625?

CREATE TABLE table_name_7 (score_qualifying VARCHAR, score_final VARCHAR)

SELECT COUNT(score_qualifying) FROM table_name_7 WHERE score_final = 16.625;


Question: What is the average number of vaccinations administered per day, before January 15, 2021?

CREATE TABLE vaccinations (id INT PRIMARY KEY, patient_id INT, vaccine VARCHAR(255), date DATE); INSERT INTO vaccinations (id, patient_id, vaccine, date) VALUES (1, 12345, 'Pfizer-BioNTech', '2021-01-05'); INSERT INTO vaccinations (id, patient_id, vaccine, date) VALUES (2, 67890, 'Moderna', '2021-01-10'); INSERT INTO vaccinations (id, patient_id, vaccine, date) VALUES (3, 12345, 'Pfizer-BioNTech', '2021-01-15');

SELECT AVG(vaccinations_per_day) FROM (SELECT COUNT(*) / (DATEDIFF('2021-01-15', date)) AS vaccinations_per_day FROM vaccinations WHERE date < '2021-01-15') AS subquery;


Question: What is the average word count of articles by gender and region in 'news_articles' table?

CREATE TABLE news_articles (id INT, title VARCHAR(100), publication_date DATE, author VARCHAR(50), word_count INT, gender VARCHAR(10), region VARCHAR(50)); INSERT INTO news_articles (id, title, publication_date, author, word_count, gender, region) VALUES (1, 'Article 1', '2022-01-01', 'John Doe', 500, 'Male', 'North America'), (2, 'Article 2', '2022-01-02', 'Jane Smith', 700, 'Female', 'Europe');

SELECT gender, region, AVG(word_count) as avg_word_count FROM news_articles GROUP BY gender, region;


Question: Generate PostgreSQL SQL for: What is the viewers where the rating is 5.3?

CREATE TABLE table_11178271_1 (viewers__m_ VARCHAR, rating VARCHAR)

SELECT viewers__m_ FROM table_11178271_1 WHERE rating = '5.3';


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

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

SELECT count(*) FROM (select quote_literal('abc''')) AS _sub;


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

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

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


Question: Find the number of unique volunteers for each program?

CREATE TABLE Volunteers (VolunteerID INT, ProgramID INT); INSERT INTO Volunteers (VolunteerID, ProgramID) VALUES (1, 1), (2, 1), (3, 2), (4, 3), (5, 3);

SELECT ProgramID, COUNT(DISTINCT VolunteerID) FROM Volunteers GROUP BY ProgramID;


Question: What is the most popular color of sustainable fashion products?

CREATE TABLE sales (id INT, product_type VARCHAR(20), color VARCHAR(20), revenue DECIMAL); INSERT INTO sales (id, product_type, color, revenue) VALUES (1, 'sustainable', 'green', 100.00), (2, 'regular', 'blue', 200.00), (3, 'sustainable', 'green', 300.00), (4, 'regular', 'red', 400.00), (5, 'sustainable', 'blue', 500.00);

SELECT color, COUNT(*) FROM sales WHERE product_type = 'sustainable' GROUP BY color ORDER BY COUNT(*) DESC LIMIT 1;


Question: Find the difference between the average response times for 'Fire' and 'Medical' calls in each neighborhood.

CREATE TABLE ResponseTimes (call_id INT, call_type VARCHAR(10), neighborhood VARCHAR(20), response_time INT); INSERT INTO ResponseTimes VALUES (1, 'Fire', 'Parkside', 5), (2, 'Medical', 'Parkside', 7), (3, 'Fire', 'Downtown', 6), (4, 'Medical', 'Downtown', 8);

SELECT neighborhood, AVG(response_time) - (SELECT AVG(response_time) FROM ResponseTimes r2 WHERE r2.neighborhood = r1.neighborhood AND r2.call_type = 'Medical') AS difference FROM ResponseTimes r1 WHERE r1.call_type = 'Fire' GROUP BY neighborhood;


Question: How many traffic violations were issued in the state of New York, broken down by county, in the month of July 2022?

CREATE TABLE traffic_violations (county VARCHAR(20), violation_count INT, violation_date DATE); INSERT INTO traffic_violations (county, violation_count, violation_date) VALUES ('New York County', 500, '2022-07-01');

SELECT county, SUM(violation_count) FROM traffic_violations WHERE violation_date BETWEEN '2022-07-01' AND '2022-07-31' GROUP BY county;


Question: Generate PostgreSQL SQL for: Find the name of companies that do not make DVD drive.

CREATE TABLE manufacturers (name VARCHAR, code VARCHAR); CREATE TABLE products (Manufacturer VARCHAR, name VARCHAR); CREATE TABLE manufacturers (name VARCHAR)

SELECT name FROM manufacturers EXCEPT SELECT T2.name FROM products AS T1 JOIN manufacturers AS T2 ON T1.Manufacturer = T2.code WHERE T1.name = 'DVD drive';


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

select jsonb_to_tsvector('english', '{"a": "aaa in bbb", "b": 123, "c": 456, "d": true, "f": false, "g": null}'::jsonb, '"numeric"');

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

SELECT count(*) FROM (select jsonb_to_tsvector('english', '{"a": "aaa in bbb", "b": 123, "c": 456, "d": true, "f": false, "g": null}'::jsonb, '"numeric"')) AS _sub;


Question: Generate PostgreSQL SQL for: Name the record for cotton bowl classic

CREATE TABLE table_2517159_1 (record VARCHAR, name_of_bowl VARCHAR)

SELECT record FROM table_2517159_1 WHERE name_of_bowl = 'Cotton Bowl Classic';


Question: What is the average orbital height of satellites launched by Japan?

CREATE TABLE satellites_orbital (id INT, name VARCHAR(255), country VARCHAR(255), orbital_height FLOAT);

SELECT AVG(orbital_height) FROM satellites_orbital WHERE country = 'Japan';


Question: What is the average temperature and humidity for Farm 3?

CREATE TABLE weather_data (id INT, location VARCHAR(50), temperature FLOAT, humidity FLOAT, time TIMESTAMP); INSERT INTO weather_data (id, location, temperature, humidity, time) VALUES (1, 'Farm 3', 25.0, 60.0, '2021-01-01 10:00:00');

SELECT AVG(temperature), AVG(humidity) FROM weather_data WHERE location = 'Farm 3';


Question: What was the total cost of spacecraft manufactured by 'AeroCorp'?

CREATE TABLE SpacecraftManufacturing(company VARCHAR(20), cost INT); INSERT INTO SpacecraftManufacturing(company, cost) VALUES('AeroCorp', 5000000), ('GalacticTech', 7000000), ('SpaceEagle', 6000000);

SELECT SUM(cost) FROM SpacecraftManufacturing WHERE company = 'AeroCorp';


Question: Generate PostgreSQL SQL for: Which tournament has an Outcome of runner-up, and an Opponent of maša zec peškirič?

CREATE TABLE table_name_93 (tournament VARCHAR, outcome VARCHAR, opponent VARCHAR)

SELECT tournament FROM table_name_93 WHERE outcome = 'runner-up' AND opponent = 'maša zec peškirič';


Question: Generate PostgreSQL SQL for: What venue listed is dated February 22, 2003?

CREATE TABLE table_name_4 (venue VARCHAR, date VARCHAR)

SELECT venue FROM table_name_4 WHERE date = 'february 22, 2003';


Question: What is the total revenue generated from digital music sales in the United States?

CREATE TABLE digital_sales (sale_id INT, platform VARCHAR(20), genre VARCHAR(20), units_sold INT, sale_price DECIMAL(5,2)); CREATE TABLE countries (country_code CHAR(2), country_name VARCHAR(50)); INSERT INTO countries (country_code, country_name) VALUES ('US', 'United States');

SELECT SUM(d.sale_price * d.units_sold) as total_revenue FROM digital_sales d INNER JOIN countries c ON d.platform = c.country_name WHERE c.country_code = 'US';


Question: What is the difference in funding amount between the latest and earliest round for each company?

CREATE TABLE funding_rounds (company_id INT, round_number INT, funding_amount INT); INSERT INTO funding_rounds (company_id, round_number, funding_amount) VALUES (1, 1, 5000000), (1, 2, 7000000), (1, 3, 10000000), (2, 1, 3000000), (2, 2, 4000000), (3, 1, 9000000), (3, 2, 11000000);

SELECT company_id, MAX(funding_amount) - MIN(funding_amount) AS funding_difference FROM funding_rounds GROUP BY company_id;


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

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

Explanation: DML from PostgreSQL core regression test for Varchar.


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

create table rtest_empmass (ename char(20), salary numeric);

Explanation: DDL from PostgreSQL core regression test for Rules.


Question: What is the average donation amount for donors from Oceania?

CREATE TABLE Donors (DonorID int, DonorName varchar(50), Country varchar(50)); INSERT INTO Donors (DonorID, DonorName, Country) VALUES (1, 'John Doe', 'United States'); INSERT INTO Donors (DonorID, DonorName, Country) VALUES (2, 'Jane Smith', 'Australia'); INSERT INTO Donors (DonorID, DonorName, Country) VALUES (3, 'Alice Johnson', 'Japan'); CREATE TABLE Donations (DonationID int, DonorID int, DonationAmount decimal(10, 2)); INSERT INTO Donations (DonationID, DonorID, DonationAmount) VALUES (1, 1, 5000); INSERT INTO Donations (DonationID, DonorID, DonationAmount) VALUES (2, 2, 1000); INSERT INTO Donations (DonationID, DonorID, DonationAmount) VALUES (3, 2, 1500); INSERT INTO Donations (DonationID, DonorID, DonationAmount) VALUES (4, 3, 2000);

SELECT AVG(Donations.DonationAmount) as AverageDonationAmount FROM Donors INNER JOIN Donations ON Donations.DonorID = Donors.DonorID WHERE Donors.Country IN ('Australia');


Question: What is the average temperature change in Africa and North America from 2015 to 2020?

CREATE TABLE africa_temperature (year INT, avg_temp FLOAT); INSERT INTO africa_temperature (year, avg_temp) VALUES (2015, 20.1), (2016, 20.5), (2017, 21.2), (2018, 20.8), (2019, 21.0), (2020, 21.5); CREATE TABLE north_america_temperature (year INT, avg_temp FLOAT); INSERT INTO north_america_temperature (year, avg_temp) VALUES (2015, 10.1), (2016, 10.5), (2017, 11.2), (2018, 10.8), (2019, 11.0), (2020, 11.5);

SELECT AVG(africa_temperature.avg_temp) AS africa_avg_temp, AVG(north_america_temperature.avg_temp) AS north_america_avg_temp FROM africa_temperature, north_america_temperature WHERE africa_temperature.year = north_america_temperature.year AND africa_temperature.year BETWEEN 2015 AND 2020;


Question: Generate PostgreSQL SQL for: How many violent catagories are listed for the year forcible rapes were 1156?

CREATE TABLE table_25271777_1 (violent VARCHAR, forcible_rape VARCHAR)

SELECT COUNT(violent) FROM table_25271777_1 WHERE forcible_rape = 1156;


Question: What is the minimum serving size for organic juice?

CREATE TABLE Beverages (id INT, is_organic BOOLEAN, category VARCHAR(20), serving_size INT); INSERT INTO Beverages (id, is_organic, category, serving_size) VALUES (1, true, 'juice', 10), (2, false, 'juice', 15), (3, true, 'smoothie', 12);

SELECT MIN(serving_size) FROM Beverages WHERE is_organic = true AND category = 'juice';


Question: What is the average cost of military equipment maintenance per incident for each type of equipment in the last year?

CREATE TABLE equipment_maintenance (id INT, incident_number VARCHAR(255), equipment_type VARCHAR(255), state VARCHAR(255), cost DECIMAL(10,2));

SELECT equipment_type, AVG(cost) FROM equipment_maintenance WHERE date >= DATE_SUB(CURRENT_DATE, INTERVAL 12 MONTH) GROUP BY equipment_type;


Question: Generate PostgreSQL SQL for: How many Points has Wins larger than 0?

CREATE TABLE table_name_24 (points VARCHAR, wins INTEGER)

SELECT COUNT(points) FROM table_name_24 WHERE wins > 0;


Question: What is the total square footage of all properties in sustainable urban areas?

CREATE TABLE urban_areas (id INT, area VARCHAR(20), sustainable BOOLEAN); INSERT INTO urban_areas (id, area, sustainable) VALUES (1, 'City A', true), (2, 'City B', false), (3, 'City C', true); CREATE TABLE properties (id INT, area VARCHAR(20), size INT); INSERT INTO properties (id, area, size) VALUES (1, 'City A', 1500), (2, 'City B', 2000), (3, 'City A', 1000);

SELECT SUM(size) FROM properties JOIN urban_areas ON properties.area = urban_areas.area WHERE urban_areas.sustainable = true;


Question: PostgreSQL regression test 'numeric': Write the SELECT query (example 749).

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

SELECT count(*) FROM (SELECT to_number('MCCM', 'RN')) AS _sub;


Question: Identify the total number of fish in the North Pacific Ocean, grouped by species, for those species with a population greater than 1000000?

CREATE TABLE FishPopulation (Species TEXT, Ocean TEXT, Population INT); INSERT INTO FishPopulation (Species, Ocean, Population) VALUES ('Salmon', 'North Pacific', 800000), ('Tuna', 'North Pacific', 1200000), ('Shark', 'North Pacific', 500000);

SELECT Species, SUM(Population) FROM FishPopulation WHERE Ocean = 'North Pacific' GROUP BY Species HAVING SUM(Population) > 1000000;


Question: Generate PostgreSQL SQL for: What is Team, when High Rebounds is "Carl Landry (11)"?

CREATE TABLE table_name_78 (team VARCHAR, high_rebounds VARCHAR)

SELECT team FROM table_name_78 WHERE high_rebounds = 'carl landry (11)';


Question: What is the maximum ESG score in the healthcare sector?

CREATE TABLE companies (id INT, name VARCHAR(255), sector VARCHAR(255), ESG_score FLOAT); INSERT INTO companies (id, name, sector, ESG_score) VALUES (1, 'Pfizer', 'Healthcare', 90.0), (2, 'Johnson & Johnson', 'Healthcare', 92.5), (3, 'Merck', 'Healthcare', 87.5);

SELECT MAX(ESG_score) FROM companies WHERE sector = 'Healthcare';


Question: What is the industry with the highest total funding?

CREATE TABLE funding (id INT, company_id INT, amount DECIMAL(10, 2)); CREATE TABLE company (id INT, name VARCHAR(255), industry VARCHAR(255)); INSERT INTO company (id, name, industry) VALUES (1, 'Fintech Inc', 'finance'), (2, 'Startup Corp', 'tech'), (3, 'Green Inc', 'green'); INSERT INTO funding (id, company_id, amount) VALUES (1, 1, 500000.00), (2, 1, 750000.00), (3, 2, 250000.00), (4, 3, 1000000.00);

SELECT industry, SUM(amount) AS total_funding FROM funding INNER JOIN company ON funding.company_id = company.id GROUP BY industry ORDER BY total_funding DESC LIMIT 1;


Question: Generate PostgreSQL SQL for: What is the best time of the team that had a qualifying 1 time of 1:01.043?

CREATE TABLE table_name_54 (best VARCHAR, qual_1 VARCHAR)

SELECT best FROM table_name_54 WHERE qual_1 = '1:01.043';


Question: Generate PostgreSQL SQL for: The Le Mans Porsche team Joest Racing is in which class?

CREATE TABLE table_name_53 (class VARCHAR, team VARCHAR)

SELECT class FROM table_name_53 WHERE team = 'le mans porsche team joest racing';


Question: Update the salary of 'Bob Johnson' in the 'Assembly' department to $65000.

CREATE TABLE employees (id INT, name TEXT, department TEXT, salary INT); INSERT INTO employees (id, name, department, salary) VALUES (1, 'John Doe', 'Engineering', 70000), (2, 'Jane Smith', 'Management', 90000), (3, 'Bob Johnson', 'Assembly', 50000), (4, 'Alice Williams', 'Engineering', 75000), (5, 'Charlie Brown', 'Assembly', 55000), (6, 'Janet Doe', 'Quality', 60000), (7, 'Jim Smith', 'Management', 85000), (8, 'Jake Johnson', 'Assembly', 60000);

UPDATE employees SET salary = 65000 WHERE id = 3;


Question: Insert a new record for a workplace in the state of Illinois without safety violations.

CREATE TABLE workplaces (id INT, name TEXT, state TEXT, safety_violation BOOLEAN);

INSERT INTO workplaces (id, name, state, safety_violation) VALUES (1, 'WXY Company', 'Illinois', false);


Question: What is the average budget for projects focused on AI ethics by year?

CREATE TABLE project_budget (project_id INT, project_name VARCHAR(255), budget DECIMAL(10,2), year INT); INSERT INTO project_budget (project_id, project_name, budget, year) VALUES (1, 'Ethical AI Research', 500000, 2020), (2, 'AI Ethics Guidelines Development', 750000, 2021);

SELECT AVG(budget) as avg_budget, year FROM project_budget WHERE project_name LIKE '%AI ethics%' GROUP BY year;


Question: Generate PostgreSQL SQL for: Which Surface has an Opponent of kerry melville reid, and a Score of 6–3, 2–6, 3–6?

CREATE TABLE table_name_53 (surface VARCHAR, opponent VARCHAR, score VARCHAR)

SELECT surface FROM table_name_53 WHERE opponent = 'kerry melville reid' AND score = '6–3, 2–6, 3–6';


Question: Generate PostgreSQL SQL for: On what date was the game where is was later than Week 4 of the season and the opponent was the New York Giants?

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

SELECT date FROM table_name_54 WHERE week > 4 AND opponent = 'new york giants';


Question: List the auto shows and number of electric vehicle models showcased in each

CREATE TABLE AutoShow (id INT, name TEXT); CREATE TABLE ElectricVehicle (id INT, name TEXT, show_id INT); INSERT INTO AutoShow (id, name) VALUES (1, 'LA Auto Show'), (2, 'Detroit Auto Show'); INSERT INTO ElectricVehicle (id, name, show_id) VALUES (1, 'Model 3', 1), (2, 'Bolt', 1), (3, 'Tesla Semi', 2);

SELECT AutoShow.name, COUNT(ElectricVehicle.id) FROM AutoShow INNER JOIN ElectricVehicle ON AutoShow.id = ElectricVehicle.show_id GROUP BY AutoShow.id;


Question: Generate PostgreSQL SQL for: What is the average finish that has 24 as the start, with a year after 1987?

CREATE TABLE table_name_89 (finish INTEGER, start VARCHAR, year VARCHAR)

SELECT AVG(finish) FROM table_name_89 WHERE start = 24 AND year > 1987;


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

SELECT * FROM (SELECT * FROM mytable FOR UPDATE) ss WHERE col1 = 5;

Explanation: PostgreSQL SELECT command.


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

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


Question: Generate PostgreSQL SQL for: What is the highest number of top-25s for events with 0 wins?

CREATE TABLE table_name_15 (top_25 INTEGER, wins INTEGER)

SELECT MAX(top_25) FROM table_name_15 WHERE wins < 0;


Question: Generate PostgreSQL SQL for: Who captains Portsmouth?

CREATE TABLE table_name_9 (captain VARCHAR, team VARCHAR)

SELECT captain FROM table_name_9 WHERE team = 'portsmouth';


Question: How many visitors with disabilities visited our museums in Germany last year?

CREATE TABLE Visitors_With_Disabilities (id INT, country VARCHAR(255), year INT, number_of_visitors INT);

SELECT SUM(number_of_visitors) FROM Visitors_With_Disabilities WHERE country = 'Germany' AND year = 2021;


Question: Generate PostgreSQL SQL for: What event did Diego Saraiva fight jorge gurgel?

CREATE TABLE table_name_98 (event VARCHAR, opponent VARCHAR)

SELECT event FROM table_name_98 WHERE opponent = 'jorge gurgel';


Question: What is the average depth of ocean floor mapping projects in the Pacific region?

CREATE TABLE OceanFloorMapping (id INT, region VARCHAR(20), depth FLOAT); INSERT INTO OceanFloorMapping (id, region, depth) VALUES (1, 'Pacific', 4500.5), (2, 'Atlantic', 3200.2), (3, 'Indian', 5000.0);

SELECT AVG(depth) FROM OceanFloorMapping WHERE region = 'Pacific';


Question: Generate PostgreSQL SQL for: Name the total number of ERP/Power W for frequency of 89.3 fm and facility ID less than 40430

CREATE TABLE table_name_34 (erp___power_w VARCHAR, frequency VARCHAR, facility_id VARCHAR)

SELECT COUNT(erp___power_w) FROM table_name_34 WHERE frequency = '89.3 fm' AND facility_id < 40430;


Question: Show an example of PostgreSQL COPY (example 1).

COPY (SELECT * FROM country WHERE country_name LIKE 'A%') TO '/usr1/proj/bray/sql/a_list_countries.copy';

Explanation: PostgreSQL COPY command.


Question: Generate PostgreSQL SQL for: What's the total of number of FA Cup that has a League small than 29 with Play-offs less than 0?

CREATE TABLE table_name_50 (fa_cup VARCHAR, league VARCHAR, play_offs VARCHAR)

SELECT COUNT(fa_cup) FROM table_name_50 WHERE league < 29 AND play_offs < 0;


Question: What was the total cost of sustainable building projects in Texas in 2019?

CREATE TABLE Sustainable_Projects (id INT, project_cost FLOAT, year INT, state VARCHAR(20)); INSERT INTO Sustainable_Projects (id, project_cost, year, state) VALUES (1, 7000000, 2019, 'Texas');

SELECT SUM(project_cost) FROM Sustainable_Projects WHERE year = 2019 AND state = 'Texas';


Question: PostgreSQL Plpgsql: show example 53.

CREATE TABLE test (col text); INSERT INTO test VALUES ('123'); CREATE FUNCTION reffunc(refcursor) RETURNS refcursor AS ' BEGIN OPEN $1 FOR SELECT col FROM test; RETURN $1; END; ' LANGUAGE plpgsql; BEGIN; SELECT reffunc('funccursor'); FETCH ALL IN funccursor; COMMIT;

Explanation: Example from PostgreSQL documentation on Plpgsql.


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

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

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


Question: Generate PostgreSQL SQL for: What is the total number of winners when the team classification leader was Kelme-Costa Blanca and the combativity award was won by Jacky Durand?

CREATE TABLE table_2267345_2 (winner VARCHAR, team_classification VARCHAR, combativity_award VARCHAR)

SELECT COUNT(winner) FROM table_2267345_2 WHERE team_classification = 'Kelme-Costa Blanca' AND combativity_award = 'Jacky Durand';


Question: Which teams have experienced a year-over-year increase in average ticket sales for home games?

CREATE TABLE sales (sale_id INT, team_id INT, year INT, ticket_sales INT); INSERT INTO sales (sale_id, team_id, year, ticket_sales) VALUES (1, 1, 2021, 500); INSERT INTO sales (sale_id, team_id, year, ticket_sales) VALUES (2, 2, 2021, 600); INSERT INTO sales (sale_id, team_id, year, ticket_sales) VALUES (3, 1, 2020, 450); INSERT INTO sales (sale_id, team_id, year, ticket_sales) VALUES (4, 2, 2020, 550);

SELECT teams.team_name, YEAR(sales.year) as year, AVG(sales.ticket_sales) as avg_ticket_sales FROM sales JOIN teams ON sales.team_id = teams.team_id GROUP BY teams.team_name, YEAR(sales.year) HAVING AVG(sales.ticket_sales) > (SELECT AVG(sales.ticket_sales) FROM sales WHERE sales.team_id = teams.team_id AND YEAR(sales.year) = year - 1) ORDER BY teams.team_name, year;


Question: Identify intersections with high rates of electric vehicle adoption and public transit usage in Chicago and Seattle.

CREATE TABLE if not exists Intersections(location CHAR(10), ev_adoption FLOAT, transit_usage INT); INSERT INTO Intersections(location, ev_adoption, transit_usage) VALUES ('Chicago_1st', 0.25, 1200), ('Chicago_1st', 0.25, 1250), ('Chicago_2nd', 0.31, 1500), ('Chicago_2nd', 0.31, 1450), ('Seattle_1st', 0.28, 800), ('Seattle_1st', 0.28, 850), ('Seattle_2nd', 0.33, 1100), ('Seattle_2nd', 0.33, 1050);

SELECT location, ev_adoption, transit_usage FROM Intersections WHERE location IN ('Chicago_1st', 'Chicago_2nd', 'Seattle_1st', 'Seattle_2nd') AND ev_adoption > 0.25 AND transit_usage > 1000;


Question: Generate PostgreSQL SQL for: What is the player number for the player from Centenary?

CREATE TABLE table_name_66 (no_s_ VARCHAR, school_club_team_country VARCHAR)

SELECT no_s_ FROM table_name_66 WHERE school_club_team_country = 'centenary';


Question: What is the average temperature recorded by IoT sensors for each crop type in the past month?

CREATE TABLE sensor_data (sensor_id INT, crop_type VARCHAR(255), temperature DECIMAL(5,2), record_date DATE); INSERT INTO sensor_data (sensor_id, crop_type, temperature, record_date) VALUES (1, 'corn', 22.5, '2022-01-01'), (2, 'soybean', 24.3, '2022-01-02');

SELECT s.crop_type, AVG(s.temperature) as avg_temperature FROM sensor_data s INNER JOIN (SELECT crop_type, MAX(record_date) as max_date FROM sensor_data WHERE record_date >= DATE_SUB(CURDATE(), INTERVAL 1 MONTH) GROUP BY crop_type) md ON s.crop_type = md.crop_type AND s.record_date = md.max_date GROUP BY s.crop_type;


Question: Find the total production quantity (in metric tons) of Europium for 2018 and 2019.

CREATE TABLE production_data (year INT, element TEXT, production_quantity FLOAT); INSERT INTO production_data (year, element, production_quantity) VALUES (2018, 'Europium', 120); INSERT INTO production_data (year, element, production_quantity) VALUES (2019, 'Europium', 150); INSERT INTO production_data (year, element, production_quantity) VALUES (2020, 'Europium', 180);

SELECT SUM(production_quantity) FROM production_data WHERE element = 'Europium' AND year IN (2018, 2019);


Question: What is the average safety score for each creative AI application?

CREATE TABLE CreativeAI (id INT, application VARCHAR(255), safety_score DECIMAL(5,2)); INSERT INTO CreativeAI (id, application, safety_score) VALUES (1, 'Artistic Image Generation', 85.67), (2, 'Automated Journalism', 91.23), (3, 'Music Composition', 88.98);

SELECT application, AVG(safety_score) as avg_safety_score FROM CreativeAI GROUP BY application;


Question: Generate PostgreSQL SQL for: What is the total number of runs where the average is less than 27.22?

CREATE TABLE table_name_87 (runs VARCHAR, average INTEGER)

SELECT COUNT(runs) FROM table_name_87 WHERE average < 27.22;


Question: Generate PostgreSQL SQL for: Which Days of the week has a Time of broadcast in january–february, june 2002?

CREATE TABLE table_name_31 (days_of_the_week VARCHAR, time_of_broadcast VARCHAR)

SELECT days_of_the_week FROM table_name_31 WHERE time_of_broadcast = 'january–february, june 2002';


Question: Generate PostgreSQL SQL for: How many 5+/inns have tyron henderson as the player, with wickets less than 21?

CREATE TABLE table_name_40 (_inns VARCHAR, player VARCHAR, wickets VARCHAR)

SELECT COUNT(5) + _inns FROM table_name_40 WHERE player = 'tyron henderson' AND wickets < 21;


Question: How many clients had their total assets increased by more than 10% in Q1 2022 compared to Q1 2021?

CREATE TABLE clients (client_id INT, name VARCHAR(50), total_assets DECIMAL(10,2));CREATE TABLE transactions (transaction_id INT, client_id INT, transaction_date DATE, total_amount DECIMAL(10,2));

SELECT COUNT(DISTINCT c.client_id) FROM clients c INNER JOIN (SELECT client_id, SUM(total_amount) as total_q1_2022 FROM transactions WHERE transaction_date BETWEEN '2022-01-01' AND '2022-03-31' GROUP BY client_id) t1 ON c.client_id = t1.client_id INNER JOIN (SELECT client_id, SUM(total_amount) as total_q1_2021 FROM transactions WHERE transaction_date BETWEEN '2021-01-01' AND '2021-03-31' GROUP BY client_id) t2 ON c.client_id = t2.client_id WHERE t1.total_q1_2022 > 1.1 * t2.total_q1_2021;


Question: Which ethical labor certifications are present in the Manufacturing table?

CREATE TABLE Manufacturing (manufacturer_id INT, manufacturer_name TEXT, certification TEXT); INSERT INTO Manufacturing (manufacturer_id, manufacturer_name, certification) VALUES (101, 'Textile Co', 'SA8000'); INSERT INTO Manufacturing (manufacturer_id, manufacturer_name, certification) VALUES (102, 'Gadgets Inc', 'Fair Labor'); INSERT INTO Manufacturing (manufacturer_id, manufacturer_name, certification) VALUES (103, 'Eco Parts Ltd', 'ISO 14001');

SELECT DISTINCT certification FROM Manufacturing;


Question: Generate PostgreSQL SQL for: What is the Athlete from Burbank High School?

CREATE TABLE table_name_25 (athlete VARCHAR, school VARCHAR)

SELECT athlete FROM table_name_25 WHERE school = 'burbank high school';


Question: How many male and female employees are there in the company?

CREATE TABLE employees (id INT, name VARCHAR(50), gender VARCHAR(10), department VARCHAR(50)); INSERT INTO employees (id, name, gender, department) VALUES (1, 'John Doe', 'Male', 'Marketing'), (2, 'Jane Smith', 'Female', 'Marketing');

SELECT gender, COUNT(*) FROM employees GROUP BY gender;


Question: Generate PostgreSQL SQL for: What's the Denomination listed for the Date of Issue 12 April 2005?

CREATE TABLE table_name_88 (denomination VARCHAR, date_of_issue VARCHAR)

SELECT denomination FROM table_name_88 WHERE date_of_issue = '12 april 2005';


Question: Delete all 'Monorail' routes

CREATE TABLE monorail_routes (route_id INT PRIMARY KEY, start_location TEXT, end_location TEXT);


Question: Show a SQL definition from the citus project (multi_alter_table_add_foreign_key_without_name, item 15).

CREATE TABLE referencing_table(id int, ref_id int);

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


Question: Generate PostgreSQL SQL for: What's the maximum wickets taken by players named Bill Lockwood?

CREATE TABLE table_2482547_5 (wickets_taken INTEGER, name VARCHAR)

SELECT MAX(wickets_taken) FROM table_2482547_5 WHERE name = 'Bill Lockwood';


Question: Generate PostgreSQL SQL for: What is Place, when Weapon is "35mm fire", and when Date is "27 May 1982"?

CREATE TABLE table_name_15 (place VARCHAR, weapon VARCHAR, date VARCHAR)

SELECT place FROM table_name_15 WHERE weapon = '35mm fire' AND date = '27 may 1982';


Question: What is the minimum explainability score for AI models in the energy sector in Oceania?

CREATE TABLE explainability_scores_2 (id INT, model_name VARCHAR(50), sector VARCHAR(50), region VARCHAR(50), score FLOAT); INSERT INTO explainability_scores_2 VALUES (1, 'EnergyModel1', 'Energy', 'Oceania', 0.75), (2, 'EnergyModel2', 'Energy', 'Oceania', 0.82), (3, 'EnergyModel3', 'Energy', 'Europe', 0.93);

SELECT MIN(score) FROM explainability_scores_2 WHERE sector = 'Energy' AND region = 'Oceania';


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

create table boolrangep_tf partition of boolrangep for values from ('true', 'false', 0) to ('true', 'false', 100);

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


Question: What are the names and locations of all Ytterbium mines in North America?

CREATE TABLE ytterbium_mines (mine_name VARCHAR(50), country VARCHAR(20)); INSERT INTO ytterbium_mines (mine_name, country) VALUES ('Y1 Mine', 'USA'), ('Y2 Mine', 'Canada'), ('Y3 Mine', 'Mexico');

SELECT mine_name, country FROM ytterbium_mines WHERE country IN ('USA', 'Canada', 'Mexico');


Question: Generate PostgreSQL SQL for: Who is the away captain when the game resulted in [[|]] by 7 wickets?

CREATE TABLE table_name_68 (away_captain VARCHAR, result VARCHAR)

SELECT away_captain FROM table_name_68 WHERE result = '[[|]] by 7 wickets';


Question: Generate PostgreSQL SQL for: What is the date of the Italian Grand Prix?

CREATE TABLE table_28925058_1 (date VARCHAR, grand_prix VARCHAR)

SELECT date FROM table_28925058_1 WHERE grand_prix = 'Italian grand_prix';


Question: Generate PostgreSQL SQL for: What is the catalogue number for Brazil?

CREATE TABLE table_name_8 (catalogue__number VARCHAR, country VARCHAR)

SELECT catalogue__number FROM table_name_8 WHERE country = 'brazil';


Question: What is the total budget for agricultural innovation projects in Europe?

CREATE TABLE agricultural_innovation (id INT, project_name VARCHAR(50), location VARCHAR(50), budget FLOAT); INSERT INTO agricultural_innovation (id, project_name, location, budget) VALUES (1, 'Precision Farming', 'France', 600000.00);

SELECT SUM(budget) FROM agricultural_innovation WHERE location LIKE '%Europe%';


Question: What is the minimum efficiency achieved by each energy project in a given year?

CREATE TABLE efficiency_stats (id INT PRIMARY KEY, project_id INT, year INT, efficiency FLOAT, FOREIGN KEY (project_id) REFERENCES projects(id)); INSERT INTO efficiency_stats (id, project_id, year, efficiency) VALUES (7, 1, 2020, 0.15), (8, 2, 2020, 0.28);

SELECT project_id, MIN(efficiency) FROM efficiency_stats GROUP BY project_id;


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

$$;
SELECT * FROM pa_target ORDER BY tid, val;
ROLLBACK;

-- as above, but blocked by BEFORE INSERT ROW trigger
BEGIN;
CREATE FUNCTION trig_fn() RETURNS trigger LANGUAGE plpgsql AS
  $$ BEGIN RETURN NULL; END; $$;

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


Question: Generate PostgreSQL SQL for: what is the max fs where the status is status and the method is method?

CREATE TABLE table_17157367_1 (max_fs VARCHAR)

SELECT max_fs FROM table_17157367_1 WHERE "status" = 'status' AND "method" = 'method';


Question: What is the total installed capacity of wind farms in the 'renewable_energy' schema?

CREATE TABLE wind_farms (id INT, name VARCHAR(50), location VARCHAR(50), installed_capacity FLOAT); INSERT INTO wind_farms (id, name, location, installed_capacity) VALUES (1, 'Wind Farm 1', 'Location A', 100.5), (2, 'Wind Farm 2', 'Location B', 150.2);

SELECT SUM(installed_capacity) FROM wind_farms;


Question: Add a column 'gender' to the 'farmers' table

CREATE TABLE farmers (farmer_id INT PRIMARY KEY, name VARCHAR(255), age INT, location VARCHAR(255));

ALTER TABLE farmers ADD COLUMN gender VARCHAR(10);


Question: Generate PostgreSQL SQL for: What name has tour Apps larger than 7, tests larger than 4, and a Career caps of 20?

CREATE TABLE table_name_22 (name VARCHAR, career_caps VARCHAR, tour_apps VARCHAR, tests VARCHAR)

SELECT name FROM table_name_22 WHERE tour_apps > 7 AND tests > 4 AND career_caps = 20;


Question: Get the number of passengers per train for the 8 AM train on each route

CREATE TABLE passengers (passenger_id INT, train_id INT, route_id INT, num_passengers INT);

SELECT route_id, num_passengers FROM passengers WHERE train_id IN (SELECT train_id FROM train_schedule WHERE departure_time = '08:00:00') GROUP BY route_id;


Question: Generate PostgreSQL SQL for: What was the Record on Week 13 at the Hoosier Dome?

CREATE TABLE table_name_97 (record VARCHAR, game_site VARCHAR, week VARCHAR)

SELECT record FROM table_name_97 WHERE game_site = 'hoosier dome' AND week = 13;


Question: Generate PostgreSQL SQL for: Which Season has a Score of 3 – 3 aet , 4–3 pen

CREATE TABLE table_name_31 (season VARCHAR, score VARCHAR)

SELECT season FROM table_name_31 WHERE score = '3 – 3 aet , 4–3 pen';


Question: PostgreSQL regression test 'numeric': Write the SELECT query (example 611).

SELECT count(*) FROM (SELECT 'NaN'::numeric::int8) AS _sub;


Question: Generate PostgreSQL SQL for: What is the Venue, when the Winner is iain pyman?

CREATE TABLE table_name_19 (venue VARCHAR, winner VARCHAR)

SELECT venue FROM table_name_19 WHERE winner = 'iain pyman';


Question: How many mobile customers have a postpaid subscription in the country of Australia?

CREATE TABLE mobile_subscribers (subscriber_id INT, subscription_type VARCHAR(10), country VARCHAR(20)); INSERT INTO mobile_subscribers (subscriber_id, subscription_type, country) VALUES (1, 'postpaid', 'Australia'), (2, 'prepaid', 'Australia'), (3, 'postpaid', 'Australia');

SELECT COUNT(*) FROM mobile_subscribers WHERE subscription_type = 'postpaid' AND country = 'Australia';


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

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


Question: Generate PostgreSQL SQL for: What Title has a Presentation of Credentials of October 4, 1988?

CREATE TABLE table_name_90 (title VARCHAR, presentation_of_credentials VARCHAR)

SELECT title FROM table_name_90 WHERE presentation_of_credentials = 'october 4, 1988';


Question: Generate PostgreSQL SQL for: What city is Mackey Arena in?

CREATE TABLE table_name_46 (city VARCHAR, venue VARCHAR)

SELECT city FROM table_name_46 WHERE venue = 'mackey arena';


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

--
-- the next two queries demonstrate how functions generate bogus duplicates.
-- this is a "feature" ..
--
SELECT DISTINCT hobbies_r.name, name(hobbies_r.equipment) FROM hobbies_r
  ORDER BY 1,2;

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


Question: Delete all records from the table "marine_protected_areas" where country is 'Indonesia'

CREATE TABLE marine_protected_areas (id INT, name VARCHAR(50), size FLOAT, country VARCHAR(50));

DELETE FROM marine_protected_areas WHERE country = 'Indonesia';


Question: Which food supplier had the most safety violations in 2021?

CREATE TABLE SupplierSafetyRecords (SupplierName VARCHAR(50), Year INT, SafetyViolations INT); INSERT INTO SupplierSafetyRecords (SupplierName, Year, SafetyViolations) VALUES ('ABC Foods', 2021, 5), ('XYZ Foods', 2021, 8), ('123 Foods', 2021, 3), ('FoodCo', 2021, 7), ('EcoFoods', 2021, 4);

SELECT SupplierName, MAX(SafetyViolations) FROM SupplierSafetyRecords WHERE Year = 2021 GROUP BY SupplierName;


Question: How many songs were added to Deezer's Latin music library in the last month?

CREATE TABLE DeezerSongs (SongID INT, AddedDate DATE, Genre VARCHAR(50)); INSERT INTO DeezerSongs (SongID, AddedDate, Genre) VALUES (1, '2022-02-15', 'Latin'), (2, '2022-02-16', 'Pop');

SELECT COUNT(*) FROM DeezerSongs WHERE AddedDate >= DATEADD(MONTH, -1, GETDATE()) AND Genre = 'Latin';


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

INSERT INTO mcv_lists (a, b, c, ia, filler1)
     SELECT mod(i,100), mod(i,50), mod(i,25), array[mod(i,25)], i
       FROM generate_series(1,5000) s(i);

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


Question: Generate PostgreSQL SQL for: Show theme and year for all exhibitions with ticket prices lower than 15.

CREATE TABLE exhibition (theme VARCHAR, YEAR VARCHAR, ticket_price INTEGER)

SELECT theme, YEAR FROM exhibition WHERE ticket_price < 15;


Question: Generate PostgreSQL SQL for: What is the indoor track status for the school that has yes for tennis and no for golf?

CREATE TABLE table_name_91 (indoor_track VARCHAR, tennis VARCHAR, golf VARCHAR)

SELECT indoor_track FROM table_name_91 WHERE tennis = 'yes' AND golf = 'no';


Question: How many doctors are there in each hospital in 'rural_healthcare' schema?

CREATE TABLE Doctors (id INT, name VARCHAR(100), hospital_id INT); INSERT INTO Doctors VALUES (1, 'Dr. Smith', 1), (2, 'Dr. Johnson', 1), (3, 'Dr. Brown', 2), (4, 'Dr. Davis', 3);

SELECT h.name, COUNT(d.id) as doctor_count FROM Hospitals h JOIN Doctors d ON h.id = d.hospital_id GROUP BY h.name;


Question: What is the average number of employees for startups founded by individuals who identify as Two-Spirit?

CREATE TABLE companies (id INT, name TEXT, founding_year INT, founder_identifies_as_two_spirit BOOLEAN, num_employees INT); INSERT INTO companies (id, name, founding_year, founder_identifies_as_two_spirit, num_employees) VALUES (1, 'Theta Labs', 2022, true, 50); INSERT INTO companies (id, name, founding_year, founder_identifies_as_two_spirit, num_employees) VALUES (2, 'Iota Inc', 2019, false, 30); INSERT INTO companies (id, name, founding_year, founder_identifies_as_two_spirit, num_employees) VALUES (3, 'Kappa Corp', 2020, true, 75);

SELECT AVG(num_employees) FROM companies WHERE founder_identifies_as_two_spirit = true;


Question: What are the names and locations of indigenous communities in Greenland with a population over 10,000 that speak Greenlandic?

CREATE TABLE Indigenous_Communities (id INT, name VARCHAR(100), population INT, location VARCHAR(100), language VARCHAR(100)); INSERT INTO Indigenous_Communities (id, name, population, location, language) VALUES (1, 'Inuit', 15000, 'Greenland', 'Greenlandic'); INSERT INTO Indigenous_Communities (id, name, population, location, language) VALUES (2, 'Kalaallit', 20000, 'Greenland', 'Greenlandic');

SELECT name, location FROM Indigenous_Communities WHERE population > 10000 AND language = 'Greenlandic';


Question: What is the total fare collected for each route on January 1, 2022?

CREATE TABLE route (route_id INT, route_name VARCHAR(255)); INSERT INTO route (route_id, route_name) VALUES (1, 'Route 1'), (2, 'Route 2'); CREATE TABLE fares (fare_id INT, route_id INT, fare_amount DECIMAL, fare_date DATE); INSERT INTO fares (fare_id, route_id, fare_amount, fare_date) VALUES (1, 1, 2.50, '2022-01-01'), (2, 1, 2.50, '2022-01-01'), (3, 2, 3.25, '2022-01-01'), (4, 2, 3.25, '2022-01-01');

SELECT r.route_name, SUM(f.fare_amount) as total_fare FROM fares f JOIN route r ON f.route_id = r.route_id WHERE f.fare_date = '2022-01-01' GROUP BY r.route_name;


Question: Generate PostgreSQL SQL for: Where was the landing site when the duration on the lunar surface was 21:31?

CREATE TABLE table_name_52 (lunar_landing_site VARCHAR, duration_on_lunar_surface VARCHAR)

SELECT lunar_landing_site FROM table_name_52 WHERE duration_on_lunar_surface = '21:31';


Question: What is the total data usage for each mobile user?

CREATE TABLE mobile_data (user_id INT, username VARCHAR(50), data_usage INT); INSERT INTO mobile_data VALUES (1, 'User 1', 200); INSERT INTO mobile_data VALUES (2, 'User 2', 300); INSERT INTO mobile_data VALUES (3, 'User 3', 150); INSERT INTO mobile_data VALUES (4, 'User 4', 400);

SELECT username, SUM(data_usage) as total_data_usage FROM mobile_data GROUP BY username;


Question: Generate PostgreSQL SQL for: On what date is Jerilyn Britz the runner-up?

CREATE TABLE table_name_32 (date VARCHAR, runner_s__up VARCHAR)

SELECT date FROM table_name_32 WHERE runner_s__up = 'jerilyn britz';


Question: What is the total number of co-owned properties in affordable neighborhoods in Paris?

CREATE TABLE Paris_Neighborhoods (Neighborhood_Name TEXT, Affordability BOOLEAN); INSERT INTO Paris_Neighborhoods (Neighborhood_Name, Affordability) VALUES ('Marais', false), ('Saint Germain', false), ('Latin Quarter', true), ('Bastille', true), ('Montmartre', false); CREATE TABLE Paris_Properties (Neighborhood_Name TEXT, Co_Ownership BOOLEAN); INSERT INTO Paris_Properties (Neighborhood_Name, Co_Ownership) VALUES ('Marais', true), ('Saint Germain', false), ('Latin Quarter', true), ('Bastille', true), ('Montmartre', false);

SELECT COUNT(Paris_Properties.Co_Ownership) FROM Paris_Properties INNER JOIN Paris_Neighborhoods ON Paris_Properties.Neighborhood_Name = Paris_Neighborhoods.Neighborhood_Name WHERE Paris_Neighborhoods.Affordability = true AND Paris_Properties.Co_Ownership = true;


Question: Generate PostgreSQL SQL for: How many people attended the game when the game was won 4-2?

CREATE TABLE table_name_44 (attendance VARCHAR, result VARCHAR)

SELECT COUNT(attendance) FROM table_name_44 WHERE result = 'won 4-2';


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


Question: Generate PostgreSQL SQL for: List the name of the phone model launched in year 2002 and with the highest RAM size.

CREATE TABLE chip_model (Model_name VARCHAR, Launch_year VARCHAR, RAM_MiB VARCHAR); CREATE TABLE phone (Hardware_Model_name VARCHAR, chip_model VARCHAR)

SELECT T2.Hardware_Model_name FROM chip_model AS T1 JOIN phone AS T2 ON T1.Model_name = T2.chip_model WHERE T1.Launch_year = 2002 ORDER BY T1.RAM_MiB DESC LIMIT 1;


Question: Generate PostgreSQL SQL for: What is the April 28 rank when the Mar 24 is 17?

CREATE TABLE table_name_92 (april_28 VARCHAR, mar_24 VARCHAR)

SELECT april_28 FROM table_name_92 WHERE mar_24 = '17';


Question: Which movies have the lowest IMDb rating per genre, sorted by release year?

CREATE TABLE movie_ratings (id INT, title VARCHAR(255), release_year INT, genre VARCHAR(255), imdb_rating DECIMAL(3,2)); INSERT INTO movie_ratings (id, title, release_year, genre, imdb_rating) VALUES (1, 'Movie1', 2018, 'Action', 5.2), (2, 'Movie2', 2019, 'Comedy', 5.5), (3, 'Movie3', 2017, 'Drama', 6.0), (4, 'Movie4', 2018, 'Animation', 4.8), (5, 'Movie5', 2019, 'Documentary', 5.3);

SELECT genre, title, release_year, MIN(imdb_rating) AS lowest_imdb_rating FROM movie_ratings GROUP BY genre ORDER BY release_year, lowest_imdb_rating;


Question: What is the total revenue for each game in the 'gaming' database?

CREATE TABLE games (game_id INT, game_name VARCHAR(50), revenue FLOAT); INSERT INTO games (game_id, game_name, revenue) VALUES (1, 'GameA', 5000000), (2, 'GameB', 7000000), (3, 'GameC', 3000000);

SELECT game_name, SUM(revenue) as total_revenue FROM games GROUP BY game_name;


Question: Insert new network infrastructure investment records for the Northeast region.

CREATE TABLE network_investments (investment_id INT, amount FLOAT, region VARCHAR(20));

INSERT INTO network_investments (investment_id, amount, region) VALUES (1, 50000.0, 'Northeast'), (2, 60000.0, 'Northeast'), (3, 45000.0, 'Northeast');


Question: What is the average age of male reporters in the 'news' table?

CREATE TABLE news (id INT, name VARCHAR(50), gender VARCHAR(10), age INT); INSERT INTO news (id, name, gender, age) VALUES (1, 'John', 'Male', 35), (2, 'Alex', 'Male', 45);

SELECT AVG(age) FROM news WHERE gender = 'Male';


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

SELECT 'init' FROM pg_create_physical_replication_slot('orig_slot2', false);

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


Question: What is the total revenue for each restaurant in 'Downtown'?

CREATE TABLE sales (sale_id INT, restaurant_id INT, menu_category VARCHAR(255), revenue INT); INSERT INTO sales (sale_id, restaurant_id, menu_category, revenue) VALUES (1, 1, 'Appetizers', 500), (2, 1, 'Entrees', 700), (3, 2, 'Desserts', 600), (4, 2, 'Beverages', 800); CREATE TABLE restaurants (restaurant_id INT, name VARCHAR(255), area VARCHAR(255)); INSERT INTO restaurants (restaurant_id, name, area) VALUES (1, 'Gourmet Delight', 'Downtown'), (2, 'Spicy Express', 'Uptown');

SELECT r.name, SUM(s.revenue) AS total_revenue FROM sales s JOIN restaurants r ON s.restaurant_id = r.restaurant_id WHERE r.area = 'Downtown' GROUP BY r.name;


Question: What is the total length of bridges in the transport division?

CREATE TABLE Projects (id INT, division VARCHAR(10)); INSERT INTO Projects (id, division) VALUES (1, 'water'), (2, 'transport'), (3, 'energy'); CREATE TABLE TransportProjects (id INT, project_id INT, length DECIMAL(10,2)); INSERT INTO TransportProjects (id, project_id, length) VALUES (1, 2, 500), (2, 2, 550), (3, 3, 600);

SELECT SUM(t.length) FROM TransportProjects t JOIN Projects p ON t.project_id = p.id WHERE p.division = 'transport';


Question: What is the number of public bicycles available in each city in the Netherlands?

CREATE TABLE if not exists public_bicycles (id INT, city VARCHAR(255), bikes INT); INSERT INTO public_bicycles (id, city, bikes) VALUES (1, 'Amsterdam', 15000), (2, 'Utrecht', 12000), (3, 'Rotterdam', 8000), (4, 'The Hague', 6000);

SELECT city, bikes FROM public_bicycles;


Question: Generate PostgreSQL SQL for: What was the margin of the Masters Tournament?

CREATE TABLE table_13026799_1 (margin VARCHAR, championship VARCHAR)

SELECT margin FROM table_13026799_1 WHERE championship = 'Masters Tournament';


Question: Generate PostgreSQL SQL for: When did Ismail Qemali Bej's term start?

CREATE TABLE table_name_61 (term_start VARCHAR, name VARCHAR)

SELECT term_start FROM table_name_61 WHERE name = 'ismail qemali bej';


Question: PostgreSQL regression test 'tidrangescan': Write the SELECT query (example 29).

SELECT ctid FROM tidrangescan WHERE ctid < '(0,0)' LIMIT 1;

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

SELECT count(*) FROM (SELECT ctid FROM tidrangescan WHERE ctid < '(0,0)' LIMIT 1) AS _sub;


Question: What is the total number of volunteers for each program in the year 2020?

CREATE TABLE programs (id INT, name VARCHAR(255)); INSERT INTO programs (id, name) VALUES (1, 'Education'), (2, 'Health'), (3, 'Environment'); CREATE TABLE volunteers (id INT, program_id INT, volunteer_date DATE); INSERT INTO volunteers (id, program_id, volunteer_date) VALUES (1, 1, '2020-01-01'), (2, 1, '2020-02-01'), (3, 2, '2020-03-01');

SELECT v.program_id, COUNT(*) as total_volunteers FROM volunteers v WHERE YEAR(v.volunteer_date) = 2020 GROUP BY v.program_id;


Question: Generate PostgreSQL SQL for: What is the nationality of the player from round 5?

CREATE TABLE table_name_31 (nationality VARCHAR, round VARCHAR)

SELECT nationality FROM table_name_31 WHERE round = 5;


Question: PostgreSQL regression test 'float8': Write the SELECT query (example 110).

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

SELECT count(*) FROM (SELECT cosh(float8 '1')) AS _sub;


Question: What is the most common type of incident in the 'safety_records' table?

CREATE TABLE safety_records (id INT, incident_type VARCHAR(50), incident_date DATE, description VARCHAR(100));

SELECT incident_type, COUNT(*) FROM safety_records GROUP BY incident_type ORDER BY COUNT(*) DESC LIMIT 1;


Question: Generate PostgreSQL SQL for: How many pressure figures are given for the .380 acp cartridge?

CREATE TABLE table_173103_1 (max_pressure VARCHAR, cartridge VARCHAR)

SELECT COUNT(max_pressure) FROM table_173103_1 WHERE cartridge = '.380 ACP';


Question: Generate PostgreSQL SQL for: Who built giancarlo fisichella's car?

CREATE TABLE table_name_96 (constructor VARCHAR, driver VARCHAR)

SELECT constructor FROM table_name_96 WHERE driver = 'giancarlo fisichella';


Question: Generate PostgreSQL SQL for: Madrid (Stuttgart) tournament with a 1996 of A has this for a Career SR?

CREATE TABLE table_name_66 (career_sr VARCHAR, tournament VARCHAR)

SELECT career_sr FROM table_name_66 WHERE 1996 = 'a' AND tournament = 'madrid (stuttgart)';


Question: What is the average income of residents in urban areas who have completed a bachelor's degree or higher, by state?

CREATE TABLE residents (id INT PRIMARY KEY, state VARCHAR(2), education VARCHAR(50), income FLOAT, area VARCHAR(10)); INSERT INTO residents (id, state, education, income, area) VALUES (1, 'NY', 'Bachelor’s Degree', 60000, 'Urban');

SELECT AVG(income) FROM residents WHERE education LIKE '%Bachelor’s Degree%' AND area = 'Urban' GROUP BY state;


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


Question: What is the difference in average temperature between the hottest and coldest regions for each month, in a given year?

CREATE TABLE temperature_data (region VARCHAR(255), temperature INT, date DATE); INSERT INTO temperature_data (region, temperature, date) VALUES ('North', 25, '2022-01-01'), ('South', 10, '2022-01-01'), ('East', 15, '2022-01-01'), ('West', 30, '2022-01-01');

SELECT hottest.region, hottest.max_temp - coldest.min_temp as temp_diff FROM (SELECT region, MAX(temperature) as max_temp FROM temperature_data GROUP BY region) hottest INNER JOIN (SELECT region, MIN(temperature) as min_temp FROM temperature_data GROUP BY region) coldest ON hottest.region = coldest.region;


Question: Generate PostgreSQL SQL for: What is the total number of Wins, when Draws is less than 2?

CREATE TABLE table_name_48 (wins VARCHAR, draws INTEGER)

SELECT COUNT(wins) FROM table_name_48 WHERE draws < 2;


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

SELECT date '1991-02-03' - time with time zone '04:05:06 UTC' AS "Subtract Time UTC";

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

SELECT count(*) FROM (SELECT date '1991-02-03' - time with time zone '04:05:06 UTC' AS "Subtract Time UTC") AS _sub;


Question: Delete policyholders who have not made any claims in the last 3 years.

CREATE TABLE Policyholders (ID INT, Name VARCHAR(50), Age INT, Gender VARCHAR(10), City VARCHAR(50), State VARCHAR(20), ZipCode VARCHAR(10)); CREATE TABLE Claims (ID INT, PolicyholderID INT, ClaimAmount DECIMAL(10,2), ClaimDate DATE);

DELETE FROM Policyholders WHERE ID NOT IN (SELECT PolicyholderID FROM Claims WHERE ClaimDate > DATE_SUB(CURDATE(), INTERVAL 3 YEAR));


Question: Display the usernames of users who have posted about mental health in the past month and have less than 1,000 followers, sorted by the number of posts related to mental health in descending order.

CREATE TABLE users (user_id INT, user_name VARCHAR(50), join_date DATE, follower_count INT);CREATE TABLE posts (post_id INT, user_id INT, post_content TEXT, post_date DATE);INSERT INTO users (user_id, user_name, join_date, follower_count) VALUES (1, 'user1', '2021-01-01', 15000), (2, 'user2', '2021-02-01', 12000), (3, 'user3', '2021-03-01', 5000), (4, 'user4', '2021-03-01', 800), (5, 'user5', '2021-03-01', 150);

SELECT u.user_name FROM users u JOIN posts p ON u.user_id = p.user_id WHERE p.post_content LIKE '%mental health%' AND p.post_date >= DATEADD(month, -1, GETDATE()) AND u.follower_count < 1000 GROUP BY u.user_name ORDER BY COUNT(p.post_id) DESC;


Question: Delete the record of the reader with the ID of 4 if it exists.

CREATE TABLE readers (id INT, name VARCHAR(50), age INT, preference VARCHAR(50)); INSERT INTO readers (id, name, age, preference) VALUES (1, 'John Doe', 30, 'technology'), (2, 'Jane Smith', 45, 'sports'), (3, 'Bob Johnson', 28, 'politics'), (4, 'Alice Davis', 34, 'international');


Question: What is the average age of female offenders in the justice_data schema's adult_offenders table?

CREATE TABLE justice_data.adult_offenders (id INT, name VARCHAR(50), age INT, gender VARCHAR(10), offense VARCHAR(50));

SELECT AVG(age) FROM justice_data.adult_offenders WHERE gender = 'female';


Question: Who is the oldest visitor from Sydney?

CREATE TABLE Visitors (id INT, name VARCHAR(20), age INT, city VARCHAR(20)); INSERT INTO Visitors (id, name, age, city) VALUES (1, 'Alex', 45, 'Sydney'), (2, 'Beth', 30, 'Sydney');

SELECT name, MAX(age) as max_age FROM Visitors WHERE city = 'Sydney';


Question: List all cases that have a billing amount greater than the average billing amount for all cases.

CREATE TABLE cases (case_id INT, billing_amount INT); INSERT INTO cases (case_id, billing_amount) VALUES (1, 8000), (2, 6000), (3, 12000), (4, 4000), (5, 9000), (6, 5000);

SELECT cases.case_id, cases.billing_amount FROM cases WHERE cases.billing_amount > (SELECT AVG(cases.billing_amount) FROM cases);


Question: Write the DML statement from PostgreSQL regression test 'time' (example 11).

INSERT INTO TIME_TBL VALUES ('2003-07-07 15:36:39 America/New_York');

Explanation: DML from PostgreSQL core regression test for Time.


Question: Generate PostgreSQL SQL for: There is a building at 800 Boylston Street, how many floors does it have?

CREATE TABLE table_name_81 (floors INTEGER, street_address VARCHAR)

SELECT SUM(floors) FROM table_name_81 WHERE street_address = '800 boylston street';


Question: List the policyholders who have made at least one claim in descending order of claim amount.

CREATE TABLE Policyholders (PolicyholderID INT, Name VARCHAR(50)); CREATE TABLE Claims (PolicyholderID INT, ClaimAmount DECIMAL(10,2)); INSERT INTO Policyholders VALUES (1, 'John Doe'); INSERT INTO Policyholders VALUES (2, 'Jane Smith'); INSERT INTO Claims VALUES (1, 2000); INSERT INTO Claims VALUES (2, 3000); INSERT INTO Claims VALUES (3, 1000);

SELECT Policyholders.PolicyholderID, Policyholders.Name, Claims.ClaimAmount FROM Policyholders INNER JOIN Claims ON Policyholders.PolicyholderID = Claims.PolicyholderID WHERE Policyholders.PolicyholderID IN (SELECT PolicyholderID FROM Claims) ORDER BY ClaimAmount DESC;


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

CREATE FUNCTION oid_dist(oid, oid)
RETURNS oid
AS 'MODULE_PATHNAME'
LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;

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


Question: What is the total number of veteran job applications in California in the last year?

CREATE TABLE veteran_jobs (id INT, state VARCHAR(50), application_date DATE); INSERT INTO veteran_jobs (id, state, application_date) VALUES (1, 'Texas', '2021-02-15'), (2, 'California', '2021-04-10'), (3, 'Texas', '2022-01-05'), (4, 'California', '2022-03-08');

SELECT COUNT(*) FROM veteran_jobs WHERE state = 'California' AND application_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR);


Question: Find the average investment amount for carbon offset projects in the 'Africa' and 'Europe' regions, excluding oceanic projects.

CREATE SCHEMA carbon_offsets; CREATE TABLE projects (project_name VARCHAR(255), region VARCHAR(255), investment_amount INT); INSERT INTO projects (project_name, region, investment_amount) VALUES ('Tropical Forest Conservation', 'Asia', 5000000), ('Wind Power Generation', 'Europe', 8000000), ('Soil Carbon Sequestration', 'Africa', 3000000), ('Oceanic Algae Farming', 'Oceania', 7000000);

SELECT region, AVG(investment_amount) FROM carbon_offsets.projects WHERE region IN ('Africa', 'Europe') AND region != 'Oceania' GROUP BY region;


Question: Generate PostgreSQL SQL for: Name the club with date of appointment of 1 november 2007

CREATE TABLE table_name_67 (club VARCHAR, date_of_appointment VARCHAR)

SELECT club FROM table_name_67 WHERE date_of_appointment = '1 november 2007';


Question: Generate PostgreSQL SQL for: What is the average decile of Ruapehu college, which has a state authority?

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

SELECT AVG(decile) FROM table_name_64 WHERE authority = 'state' AND name = 'ruapehu college';


Question: What is the regulatory status of digital assets by type?

CREATE TABLE RegulatoryFrameworks (FrameworkID int, AssetType varchar(50), RegulatoryStatus varchar(50)); INSERT INTO RegulatoryFrameworks (FrameworkID, AssetType, RegulatoryStatus) VALUES (1, 'Cryptocurrency', 'Regulated'), (2, 'Security Token', 'Partially Regulated'), (3, 'Utility Token', 'Unregulated'), (4, 'Stablecoin', 'Partially Regulated');

SELECT AssetType, RegulatoryStatus, COUNT(*) as Count FROM RegulatoryFrameworks GROUP BY AssetType, RegulatoryStatus;


Question: Generate PostgreSQL SQL for: In language where Thursday is برس وار bres'var, what is Sunday?

CREATE TABLE table_1277350_3 (sunday_surya__the_sun_ VARCHAR, thursday_guru__jupiter_ VARCHAR)

SELECT sunday_surya__the_sun_ FROM table_1277350_3 WHERE thursday_guru__jupiter_ = 'برس وار Bres'var';


Question: Generate PostgreSQL SQL for: What is the score of the game before January 22 with a 30-7-7 record?

CREATE TABLE table_name_54 (score VARCHAR, january VARCHAR, record VARCHAR)

SELECT score FROM table_name_54 WHERE january < 22 AND record = '30-7-7';


Question: How many cruelty-free certifications were granted to each brand in the past 2 years?

CREATE TABLE brands (brand_id INT, brand_name TEXT); CREATE TABLE cruelty_free_certifications (certification_id INT, brand_id INT, certification_date DATE);

SELECT brand_name, COUNT(*) as certifications_in_past_2_years FROM brands JOIN cruelty_free_certifications ON brands.brand_id = cruelty_free_certifications.brand_id WHERE certification_date > DATEADD(year, -2, CURRENT_DATE) GROUP BY brand_name;


Question: Write the DDL statement from PostgreSQL regression test 'alter_table' (example 163).

CREATE TABLE like_constraint_rename_cache
  (LIKE constraint_rename_cache INCLUDING ALL);

Explanation: DDL from PostgreSQL core regression test for Alter Table.


Question: Generate PostgreSQL SQL for: What's the Order with an Elector of Marino Bulcani?

CREATE TABLE table_name_61 (order VARCHAR, elector VARCHAR)

SELECT order FROM table_name_61 WHERE elector = 'marino bulcani';


Question: Generate PostgreSQL SQL for: What was the date of the game when North Melbourne was the away team?

CREATE TABLE table_name_10 (date VARCHAR, away_team VARCHAR)

SELECT date FROM table_name_10 WHERE away_team = 'north melbourne';


Question: Generate PostgreSQL SQL for: How many female students (sex is F) whose age is below 25?

CREATE TABLE student (sex VARCHAR, age VARCHAR)

SELECT COUNT(*) FROM student WHERE sex = 'F' AND age < 25;


Question: What was the total weight of artifacts excavated per analyst each year?

CREATE TABLE analysts (analyst_id INT, name VARCHAR(50), start_date DATE); INSERT INTO analysts (analyst_id, name, start_date) VALUES (1, 'John Doe', '2020-01-01'); CREATE TABLE artifact_analysis (analysis_id INT, artifact_id INT, analyst_id INT, analysis_date DATE, weight DECIMAL(5,2));

SELECT a.name, EXTRACT(YEAR FROM aa.analysis_date) as analysis_year, SUM(aa.weight) as total_weight FROM analysts a JOIN artifact_analysis aa ON a.analyst_id = aa.analyst_id GROUP BY a.analyst_id, a.name, analysis_year ORDER BY analysis_year, total_weight DESC;


Question: Generate PostgreSQL SQL for: How many incumbents were first elected in 1984?

CREATE TABLE table_1341453_40 (incumbent VARCHAR, first_elected VARCHAR)

SELECT COUNT(incumbent) FROM table_1341453_40 WHERE first_elected = '1984';


Question: What is the total duration of sunlight for each field in the past year?

CREATE TABLE field (id INT, field_id INT, sunlight_duration INT, timestamp DATETIME);

SELECT field_id, SUM(sunlight_duration) as total_sunlight_duration FROM field WHERE timestamp >= DATE_SUB(CURRENT_TIMESTAMP, INTERVAL 1 YEAR) GROUP BY field_id;


Question: How many algorithmic fairness assessments were conducted in Canada, Spain, and Germany in Q1 2022?

CREATE TABLE fairness_assessments (assessment_id INT, assessment_date DATE, country TEXT); INSERT INTO fairness_assessments (assessment_id, assessment_date, country) VALUES (1, '2022-01-02', 'Canada'), (2, '2022-02-15', 'Spain'), (3, '2022-03-27', 'Germany');

SELECT COUNT(*) as num_assessments FROM fairness_assessments WHERE country IN ('Canada', 'Spain', 'Germany') AND assessment_date BETWEEN '2022-01-01' AND '2022-03-31';


Question: List all compliance violations and corresponding dispensaries in Washington state.

CREATE TABLE violations (id INT, dispensary_id INT, description VARCHAR(255)); INSERT INTO violations (id, dispensary_id, description) VALUES (1, 1, 'Incorrect labeling'), (2, 2, 'Missing security cameras');

SELECT d.name, v.description FROM dispensaries d INNER JOIN violations v ON d.id = v.dispensary_id WHERE d.state = 'WA';


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

-- test exact cases for trigonometric functions in degrees

SELECT x,
       sind(x),
       sind(x) IN (-1,-0.5,0,0.5,1) AS sind_exact
FROM (VALUES (0), (30), (90), (150), (180),
      (210), (270), (330), (360)) AS t(x);

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


Question: Who are the military technology asset manufacturers with the highest number of acquisitions by country?

CREATE TABLE military_tech_manufacturers (manufacturer_id INT PRIMARY KEY, manufacturer_name VARCHAR(255), country VARCHAR(255), num_of_acquisitions INT); INSERT INTO military_tech_manufacturers (manufacturer_id, manufacturer_name, country, num_of_acquisitions) VALUES (1, 'Lockheed Martin', 'USA', 50), (2, 'BAE Systems', 'UK', 45), (3, 'Elbit Systems', 'Israel', 40), (4, 'Mitsubishi Heavy Industries', 'Japan', 35);

SELECT country, manufacturer_name, num_of_acquisitions FROM military_tech_manufacturers ORDER BY num_of_acquisitions DESC, country ASC;


Question: Calculate the average revenue per album for all rock albums available on the 'desktop' platform.

CREATE TABLE artists (id INT, name TEXT, genre TEXT); CREATE TABLE albums (id INT, title TEXT, artist_id INT, platform TEXT); CREATE TABLE sales (id INT, album_id INT, quantity INT, revenue DECIMAL); CREATE VIEW rock_desktop_albums AS SELECT a.id, a.title, ar.name FROM albums a JOIN artists ar ON a.artist_id = ar.id WHERE ar.genre = 'rock' AND a.platform = 'desktop'; CREATE VIEW rock_desktop_sales AS SELECT s.album_id, AVG(s.revenue) as avg_revenue FROM sales s JOIN rock_desktop_albums rda ON s.album_id = rda.id GROUP BY album_id;

SELECT avg_revenue FROM rock_desktop_sales;


Question: What is the minimum maintenance cost for military helicopters in the last quarter?

CREATE TABLE military_aircraft (aircraft_id INT, aircraft_model TEXT, age INT, maintenance_cost DECIMAL(10,2), aircraft_type TEXT);

SELECT MIN(maintenance_cost) FROM military_aircraft WHERE aircraft_type = 'helicopter' AND maintenance_date >= DATE_SUB(CURRENT_DATE, INTERVAL 3 MONTH);


Question: pgTAP test for Functap (assertion 192).

SELECT * FROM check_test(
    isnt_normal_function( 'oww', ARRAY['int', 'text'] ),
    false,
    'isnt_normal_function(func, noargs)',
    'Function oww(int, text) should not be a normal function',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Functap.


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

CREATE INDEX fdeps_abc_idx ON functional_dependencies (a, b, c);

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


Question: What is the average age of patients with diabetes in rural areas, grouped by state?

CREATE TABLE patients (patient_id INT, age INT, has_diabetes BOOLEAN, state VARCHAR); INSERT INTO patients (patient_id, age, has_diabetes, state) VALUES (1, 60, true, 'Ohio'); INSERT INTO patients (patient_id, age, has_diabetes, state) VALUES (2, 55, false, 'Ohio'); CREATE TABLE rural_areas (area_id INT, state VARCHAR); INSERT INTO rural_areas (area_id, state) VALUES (1, 'Ohio'); INSERT INTO rural_areas (area_id, state) VALUES (2, 'Texas');

SELECT state, AVG(age) FROM patients JOIN rural_areas ON patients.state = rural_areas.state WHERE has_diabetes = true GROUP BY state;


Question: Calculate the moving average of donation amounts for the last three months for each donor, ordered by donation date.

CREATE TABLE Donors (DonorID int, Name varchar(50)); CREATE TABLE Donations (DonationID int, DonorID int, Amount decimal(10,2), DonationDate date); INSERT INTO Donors (DonorID, Name) VALUES (1, 'James'), (2, 'Michelle'), (3, 'David'); INSERT INTO Donations (DonationID, DonorID, Amount, DonationDate) VALUES (1, 1, 500.00, '2022-01-15'), (2, 1, 300.00, '2022-02-01'), (3, 2, 200.00, '2022-03-01'), (4, 3, 1500.00, '2022-04-01'), (5, 1, 800.00, '2022-05-01'), (6, 2, 400.00, '2022-06-01');

SELECT D.DonorID, D.Name, D.DonationDate, AVG(D.Amount) OVER (PARTITION BY D.DonorID ORDER BY D.DonationDate ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS MovingAverage FROM Donors D JOIN Donations DD ON D.DonorID = DD.DonorID ORDER BY DD.DonationDate;


Question: Find the number of impact investments made by each investor in 2020.

CREATE TABLE Investments (InvestmentID int, InvestorName varchar(50), InvestmentType varchar(50), Sector varchar(50), InvestmentAmount numeric(18,2), InvestmentDate date); INSERT INTO Investments (InvestmentID, InvestorName, InvestmentType, Sector, InvestmentAmount, InvestmentDate) VALUES (1, 'Investor1', 'Impact Investment', 'Technology', 10000, '2020-01-01'), (2, 'Investor2', 'Impact Investment', 'Finance', 15000, '2019-01-01'), (3, 'Investor1', 'Impact Investment', 'Renewable Energy', 12000, '2020-01-01'), (4, 'Investor3', 'Impact Investment', 'Healthcare', 14000, '2020-01-01');

SELECT InvestorName, COUNT(*) FROM Investments WHERE YEAR(InvestmentDate) = 2020 AND InvestmentType = 'Impact Investment' GROUP BY InvestorName;


Question: What is the maximum number of flight hours for commercial airlines in the European Union in 2019?

CREATE TABLE flight_safety (airline VARCHAR(50), region VARCHAR(50), flight_hours INT, year INT); INSERT INTO flight_safety (airline, region, flight_hours, year) VALUES ('Lufthansa', 'European Union', 120000, 2019), ('Ryanair', 'European Union', 150000, 2019);

SELECT MAX(flight_hours) FROM flight_safety WHERE region = 'European Union' AND year = 2019;


Question: Generate PostgreSQL SQL for: How many countries has a gdp (nominal) of $29.9 billion?

CREATE TABLE table_11780179_1 (gdp_per_capita__nominal_ VARCHAR, gdp__nominal_ VARCHAR)

SELECT COUNT(gdp_per_capita__nominal_) FROM table_11780179_1 WHERE gdp__nominal_ = '$29.9 billion';


Question: Write the DDL statement from PostgreSQL regression test 'partition_prune' (example 158).

create table iboolpart_t partition of iboolpart for values in ('false');


Question: PL/pgSQL test: Plpython Record (example 58).

ALTER TYPE type_record DROP ATTRIBUTE second;

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


Question: Generate PostgreSQL SQL for: How many deaths occurred during Darby?

CREATE TABLE table_name_64 (deaths VARCHAR, storm_name VARCHAR)

SELECT deaths FROM table_name_64 WHERE storm_name = 'darby';


Question: Generate PostgreSQL SQL for: What was the airdate of 21 series number?

CREATE TABLE table_11630008_3 (original_air_date VARCHAR, series_no VARCHAR)

SELECT original_air_date FROM table_11630008_3 WHERE series_no = 21;


Question: Delete the investment with the given id.

CREATE TABLE investments (id INT, sector VARCHAR(20), amount FLOAT); INSERT INTO investments (id, sector, amount) VALUES (1, 'Education', 150000.00), (2, 'Healthcare', 120000.00);


Question: How many military vehicles were maintained in Texas in the last 6 months?

CREATE TABLE military_equipment (equipment_id INT, equipment_type TEXT, last_maintenance_date DATE, state TEXT); INSERT INTO military_equipment (equipment_id, equipment_type, last_maintenance_date, state) VALUES (1, 'Tank', '2022-01-01', 'Texas');

SELECT COUNT(*) FROM military_equipment WHERE last_maintenance_date >= DATE_SUB(CURRENT_DATE, INTERVAL 6 MONTH) AND state = 'Texas' AND equipment_type = 'Tank';


Question: pgTAP test for Functap (assertion 279).

SELECT * FROM check_test(
    isnt_window( 'someschema', 'nada', ARRAY['int'] ),
    false,
    'isnt_window(schema, nowin, arg)',
    'Function someschema.nada(int) should not be a window function',
    '    Function someschema.nada(int) does not exist'
);


Question: Generate PostgreSQL SQL for: Which france nationality has a lane larger than 3?

CREATE TABLE table_name_19 (name VARCHAR, lane VARCHAR, nationality VARCHAR)

SELECT name FROM table_name_19 WHERE lane > 3 AND nationality = 'france';


Question: How many spacecraft were deployed by the US and Europe by 2015-12-31?

CREATE TABLE Spacecraft (ID INT, Name TEXT, Country TEXT, LaunchDate DATE); INSERT INTO Spacecraft (ID, Name, Country, LaunchDate) VALUES (1, 'GSAT-1', 'India', '2004-06-18'), (2, 'INSAT-3A', 'India', '2003-04-10'), (3, 'RS-1', 'Russia', '2012-06-17'), (4, 'Sentinel-1A', 'Europe', '2014-04-03'), (5, 'Juno', 'United States', '2011-08-05'), (6, 'Curiosity', 'United States', '2012-08-06');

SELECT COUNT(*) AS TotalSpacecraft FROM Spacecraft WHERE Country IN ('United States', 'Europe') AND LaunchDate <= '2015-12-31';


Question: Delete the record with ID 2 from the oceanography_data table

CREATE TABLE oceanography_data (id INT PRIMARY KEY, location VARCHAR(255), temperature DECIMAL(5,2), salinity DECIMAL(5,2), depth DECIMAL(5,2));

WITH deleted_data AS (DELETE FROM oceanography_data WHERE id = 2 RETURNING *) SELECT * FROM deleted_data;


Question: What is the average sustainable urbanism score and total property price for properties in the "SustainableCity" schema, grouped by property type?

CREATE TABLE Property (id INT, property_type VARCHAR(20), price FLOAT, sustainable_score INT, city VARCHAR(20)); INSERT INTO Property (id, property_type, price, sustainable_score, city) VALUES (1, 'Apartment', 500000, 85, 'SustainableCity'), (2, 'House', 700000, 70, 'SustainableCity'), (3, 'Condo', 300000, 90, 'SustainableCity');

SELECT Property.property_type, AVG(Property.sustainable_score) AS avg_sustainable_score, SUM(Property.price) AS total_price FROM Property WHERE Property.city = 'SustainableCity' GROUP BY Property.property_type;


Question: What is the number of clinics in the 'rural_healthcare' table located in 'Forest Region'?

CREATE TABLE rural_healthcare (name VARCHAR(255), type VARCHAR(255), location VARCHAR(255)); INSERT INTO rural_healthcare (name, type, location) VALUES ('Rural General Hospital', 'Hospital', 'Bushland'), ('Rural Community Hospital', 'Hospital', 'Forest Region'), ('Rural Mental Health Clinic', 'Clinic', 'Desert Region'), ('Rural Dental Clinic', 'Clinic', 'Forest Region');

SELECT COUNT(*) FROM rural_healthcare WHERE type = 'Clinic' AND location = 'Forest Region';


Question: Generate PostgreSQL SQL for: WHAT HOMETOWN DOES HE PLAY AS THE CATCHER FOR?

CREATE TABLE table_11677100_11 (hometown VARCHAR, position VARCHAR)

SELECT hometown FROM table_11677100_11 WHERE position = 'Catcher';


Question: Generate PostgreSQL SQL for: Name the average ERP W and call sign of w237br

CREATE TABLE table_name_36 (erp_w INTEGER, call_sign VARCHAR)

SELECT AVG(erp_w) FROM table_name_36 WHERE call_sign = 'w237br';


Question: Generate PostgreSQL SQL for: What's the English name for the month with พ.ย. abbreviation?

CREATE TABLE table_180802_2 (english_name VARCHAR, abbr VARCHAR)

SELECT english_name FROM table_180802_2 WHERE abbr = 'พ.ย.';


Question: Write the DDL statement from PostgreSQL regression test 'generated_virtual' (example 22).

CREATE TABLE gtest_err_7d (a int PRIMARY KEY, b int GENERATED ALWAYS AS (generate_series(1, a)) VIRTUAL);

Explanation: DDL from PostgreSQL core regression test for Generated Virtual.


Question: Show an example of PostgreSQL CREATE SEQUENCE (example 3).

SELECT nextval('serial'); nextval --------- 101;

Explanation: PostgreSQL CREATE SEQUENCE command.


Question: PostgreSQL regression test 'case': Write the SELECT query (example 31).

SELECT NULLIF(a.i,b.i) AS "NULLIF(a.i,b.i)",
  NULLIF(b.i, 4) AS "NULLIF(b.i,4)"
  FROM CASE_TBL a, CASE2_TBL b;

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

SELECT count(*) FROM (SELECT NULLIF(a.i,b.i) AS "NULLIF(a.i,b.i)",
  NULLIF(b.i, 4) AS "NULLIF(b.i,4)"
  FROM CASE_TBL a, CASE2_TBL b) AS _sub;


Question: What was the total defense diplomacy spending for East European nations in 2017?

CREATE TABLE DefenseDiplomacy (nation VARCHAR(50), year INT, spending FLOAT); INSERT INTO DefenseDiplomacy (nation, year, spending) VALUES ('Poland', 2017, 25000000), ('Romania', 2017, 30000000), ('Ukraine', 2017, 35000000), ('Hungary', 2017, 22000000), ('Czech Republic', 2017, 28000000);

SELECT SUM(spending) FROM DefenseDiplomacy WHERE nation IN ('Poland', 'Romania', 'Ukraine', 'Hungary', 'Czech Republic') AND year = 2017;


Question: What is the total number of articles published in each state of the USA for the current year?

CREATE TABLE articles (article_id INT, publication_date DATE, state VARCHAR(255)); INSERT INTO articles (article_id, publication_date, state) VALUES (1, '2022-01-01', 'California'), (2, '2022-01-02', 'Texas'), (3, '2022-01-03', 'Florida');

SELECT state, COUNT(article_id) FROM articles WHERE YEAR(publication_date) = YEAR(GETDATE()) AND state IN ('California', 'Texas', 'Florida', 'New York', 'Pennsylvania') GROUP BY state;


Question: What is the total salary of community health workers by race?

CREATE TABLE community_health_workers (id INT, name VARCHAR(50), race VARCHAR(50), salary DECIMAL(10,2)); INSERT INTO community_health_workers (id, name, race, salary) VALUES (1, 'John Doe', 'White', 60000.00), (2, 'Jane Smith', 'Black', 55000.00), (3, 'Jim Brown', 'Hispanic', 72000.00);

SELECT race, SUM(salary) FROM community_health_workers GROUP BY race;


Question: Calculate the moving average of animal populations for each species over the last three records, if available.

CREATE TABLE animal_population (species VARCHAR(255), year INT, population INT); INSERT INTO animal_population (species, year, population) VALUES ('Tiger', 2018, 63), ('Tiger', 2019, 65), ('Tiger', 2020, 68), ('Lion', 2018, 50), ('Lion', 2019, 52), ('Lion', 2020, 55);

SELECT species, year, AVG(population) OVER (PARTITION BY species ORDER BY year ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS moving_average FROM animal_population;


Question: What is the minimum humidity recorded for each sensor in 'farm2'?

CREATE TABLE sensor (id INT, name VARCHAR(20), location VARCHAR(20), type VARCHAR(20)); INSERT INTO sensor (id, name, location, type) VALUES (1, 'sensor1', 'farm1', 'temperature'), (2, 'sensor2', 'farm2', 'humidity'), (3, 'sensor3', 'farm3', 'temperature'); CREATE TABLE humidity (id INT, sensor_id INT, timestamp DATETIME, value FLOAT); INSERT INTO humidity (id, sensor_id, timestamp, value) VALUES (1, 2, '2022-07-01 00:00:00', 60.3), (2, 2, '2022-07-01 12:00:00', 55.1), (3, 2, '2022-07-02 00:00:00', 58.9);

SELECT sensor.name as sensor_name, MIN(value) as min_humidity FROM humidity JOIN sensor ON humidity.sensor_id = sensor.id WHERE sensor.location = 'farm2' GROUP BY sensor.name;


Question: Generate PostgreSQL SQL for: What is the average number of gold medals for clubs?


Question: List all the transactions from socially responsible lending with a transaction amount greater than $5000.

CREATE TABLE socially_responsible_lending (transaction_id INT, client_id INT, transaction_amount DECIMAL(10,2)); INSERT INTO socially_responsible_lending (transaction_id, client_id, transaction_amount) VALUES (1, 4, 7000.00), (2, 5, 6000.00), (3, 6, 5500.00), (4, 7, 8000.00);

SELECT * FROM socially_responsible_lending WHERE transaction_amount > 5000;


Question: What are the launch dates of space missions having the same launch country?

CREATE TABLE space_missions (id INT, name VARCHAR(50), start_date DATE, launch_country VARCHAR(50)); INSERT INTO space_missions VALUES (1, 'Apollo 11', '1969-07-16', 'USA'), (2, 'Apollo 13', '1970-04-11', 'USA'), (3, 'Mars Pathfinder', '1996-12-04', 'USA'), (4, 'Cassini-Huygens', '1997-10-15', 'France');

SELECT name, launch_country, start_date FROM space_missions WHERE launch_country IN (SELECT launch_country FROM space_missions GROUP BY launch_country HAVING COUNT(*) > 1);


Question: Generate PostgreSQL SQL for: which train number arrives in lonavla at 17:45

CREATE TABLE table_29301050_1 (train_number VARCHAR, arrival_lonavla VARCHAR)

SELECT train_number FROM table_29301050_1 WHERE arrival_lonavla = '17:45';


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

SELECT nummultirange(numrange(1,5), numrange(6,9)) @> numrange(6,7);

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

SELECT count(*) FROM (SELECT nummultirange(numrange(1,5), numrange(6,9)) @> numrange(6,7)) AS _sub;


Question: Generate PostgreSQL SQL for: Advisor 1121 has how many students?

SELECT COUNT(*) FROM Student WHERE Advisor = 1121;


Question: Generate PostgreSQL SQL for: Find the number of routes with destination airports in Italy.

CREATE TABLE routes (dst_apid VARCHAR); CREATE TABLE airports (apid VARCHAR, country VARCHAR)

SELECT COUNT(*) FROM routes AS T1 JOIN airports AS T2 ON T1.dst_apid = T2.apid WHERE T2.country = 'Italy';


Question: Update the contact information for the disability services office at the specified campus, including phone number and email address.

CREATE TABLE campus (id INT, name VARCHAR(50), region VARCHAR(50)); CREATE TABLE disability_services_office (id INT, campus_id INT, phone VARCHAR(20), email VARCHAR(50));

UPDATE disability_services_office dso SET phone = '555-123-4567', email = 'ds@campus.edu' WHERE campus_id = (SELECT id FROM campus WHERE name = 'Campus Name');


Question: Generate PostgreSQL SQL for: Which game was played at the Forum and led to a series result of 0-1?

CREATE TABLE table_name_85 (game VARCHAR, location_attendance VARCHAR, series VARCHAR)

SELECT game FROM table_name_85 WHERE location_attendance = 'the forum' AND series = '0-1';


Question: How many clinical trials were conducted in Asia in 2019?

CREATE TABLE clinical_trials (country TEXT, year INTEGER, trials INTEGER); INSERT INTO clinical_trials (country, year, trials) VALUES ('Japan', 2019, 500); INSERT INTO clinical_trials (country, year, trials) VALUES ('China', 2019, 800);

SELECT SUM(trials) FROM clinical_trials WHERE country IN ('Japan', 'China') AND year = 2019;


Question: What is the percentage of fair trade products by category?

CREATE TABLE FairTradeProducts (product_id INT, product_name VARCHAR(255), category VARCHAR(255), is_fair_trade BOOLEAN); INSERT INTO FairTradeProducts (product_id, product_name, category, is_fair_trade) VALUES (1, 'Organic Cotton T-Shirt', 'Tops', true), (2, 'Conventional Cotton Pants', 'Bottoms', false), (3, 'Fair Trade Coffee', 'Food', true), (4, 'Recycled Polyester Jacket', 'Outerwear', true), (5, 'Conventional Cotton Socks', 'Accessories', false);

SELECT category, ROUND(COUNT(*) FILTER (WHERE is_fair_trade = true) * 100.0 / COUNT(*), 2) as fair_trade_percentage FROM FairTradeProducts GROUP BY category;


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

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


Question: Generate PostgreSQL SQL for: What is Tournament, when Margin is Victory of 6 Strokes?

CREATE TABLE table_name_30 (tournament VARCHAR, margin_of_victory VARCHAR)

SELECT tournament FROM table_name_30 WHERE margin_of_victory = '6 strokes';


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

select * from j1
inner join j2 on j1.id1 = j2.id1 and j1.id2 = j2.id2
where j1.id1 % 1000 = 1 and j2.id1 % 1000 = 1 and j2.id1 >= any (array[1,5]);

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

SELECT count(*) FROM (select * from j1
inner join j2 on j1.id1 = j2.id1 and j1.id2 = j2.id2
where j1.id1 % 1000 = 1 and j2.id1 % 1000 = 1 and j2.id1 >= any (array[1,5])) AS _sub;


Question: Generate PostgreSQL SQL for: What is the status of the building for 2014 with 33 floors?

CREATE TABLE table_name_54 (status VARCHAR, year VARCHAR, floors VARCHAR)

SELECT status FROM table_name_54 WHERE year < 2014 AND floors = 33;


Question: Generate PostgreSQL SQL for: What was the away score for Carlton?

CREATE TABLE table_name_41 (away_team VARCHAR)

SELECT away_team AS score FROM table_name_41 WHERE away_team = 'carlton';


Question: PostgreSQL Queries: show example 59.

=> SELECT * FROM t1 LEFT JOIN t2 ON t1.num = t2.num WHERE t2.value = 'xxx'; num | name | num | value -----+------+-----+------- 1 | a | 1 | xxx (1 row);

Explanation: Example from PostgreSQL documentation on Queries.


Question: Generate PostgreSQL SQL for: What is the League Goals when the FA Cup Goals are 0, position is mf, League Cup Apps of 0, and name is Ben Thornley?

CREATE TABLE table_name_98 (league_goals INTEGER, name VARCHAR, league_cup_apps VARCHAR, fa_cup_goals VARCHAR, position VARCHAR)

SELECT AVG(league_goals) FROM table_name_98 WHERE fa_cup_goals = '0' AND position = 'mf' AND league_cup_apps = '0' AND name = 'ben thornley';


Question: Generate PostgreSQL SQL for: What are the original names of the districts where the population in the 2010 census was 210450?

CREATE TABLE table_1104312_5 (original_name VARCHAR, population_at_2010_census VARCHAR)

SELECT original_name FROM table_1104312_5 WHERE population_at_2010_census = 210450;


Question: Generate PostgreSQL SQL for: Name the sum of draws when the position is less than 17 and wins is less than 11

CREATE TABLE table_name_82 (draws INTEGER, position VARCHAR, wins VARCHAR)

SELECT SUM(draws) FROM table_name_82 WHERE position < 17 AND wins < 11;


Question: How many farms are there in each location with an area greater than 150 acres, and what is the total irrigated area in those farms?

CREATE TABLE farms (id INT, name VARCHAR(50), location VARCHAR(50), acres FLOAT, irrigation BOOLEAN); INSERT INTO farms (id, name, location, acres, irrigation) VALUES (1, 'Smith Farm', 'Georgia', 200.5, TRUE); INSERT INTO farms (id, name, location, acres, irrigation) VALUES (2, 'Brown Farm', 'California', 180.0, FALSE); INSERT INTO farms (id, name, location, acres, irrigation) VALUES (3, 'Jones Farm', 'California', 250.0, TRUE);

SELECT context.location AS location, COUNT(*) AS num_farms, SUM(CASE WHEN context.irrigation = TRUE THEN context.acres END) AS irrigated_acres FROM (SELECT location, acres, irrigation FROM farms WHERE acres > 150) AS context GROUP BY context.location;


Question: Generate PostgreSQL SQL for: Name the To par of payne stewart?

CREATE TABLE table_name_4 (to_par VARCHAR, player VARCHAR)

SELECT to_par FROM table_name_4 WHERE player = 'payne stewart';


Question: PostgreSQL regression test 'rangefuncs': Write the SELECT query (example 220).

SELECT * FROM (VALUES (1),(2),(3)) v1(r1),
              LATERAL (SELECT r1, * FROM (VALUES (10),(20),(30)) v2(r2)
                                         LEFT JOIN generate_series(r2,r2+3) f(i) ON ((r2+i)<100) OFFSET 0) s1;

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

SELECT count(*) FROM (SELECT * FROM (VALUES (1),(2),(3)) v1(r1),
              LATERAL (SELECT r1, * FROM (VALUES (10),(20),(30)) v2(r2)
                                         LEFT JOIN generate_series(r2,r2+3) f(i) ON ((r2+i)<100) OFFSET 0) s1) AS _sub;


Question: Generate PostgreSQL SQL for: Which country has the score 70-76-68-214?

CREATE TABLE table_name_71 (country VARCHAR, score VARCHAR)

SELECT country FROM table_name_71 WHERE score = '70-76-68-214';


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

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

SELECT count(*) FROM (SELECT interval 'infinity' / 'nan') AS _sub;


Question: Generate PostgreSQL SQL for: What is the frequency of the processor with an sSpec number of sl3bn(kc0)sl3e9(kc0)?

CREATE TABLE table_name_79 (frequency VARCHAR, sspec_number VARCHAR)

SELECT frequency FROM table_name_79 WHERE sspec_number = 'sl3bn(kc0)sl3e9(kc0)';


Question: What are the maximum and minimum temperature for each habitat type?

CREATE TABLE fish_habitats (id INT, fish_id INT, habitat_type VARCHAR(20), temperature DECIMAL(5,2)); INSERT INTO fish_habitats (id, fish_id, habitat_type, temperature) VALUES (1, 1, 'tropical', 28.3); INSERT INTO fish_habitats (id, fish_id, habitat_type, temperature) VALUES (2, 2, 'temperate', 15.5);

SELECT habitat_type, MAX(temperature) as max_temp, MIN(temperature) as min_temp FROM fish_habitats GROUP BY habitat_type;


Question: Generate PostgreSQL SQL for: Which School/Club Team has a Pick of 198?

CREATE TABLE table_name_7 (school_club_team VARCHAR, pick VARCHAR)

SELECT school_club_team FROM table_name_7 WHERE pick = 198;


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

SELECT soundex('Anne'), soundex('Andrew'), difference('Anne', 'Andrew');

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


Question: How many disability support programs were added in 'Florida' since 2015?

CREATE TABLE program_history (program_id INT, program_name VARCHAR(50), state VARCHAR(50), start_year INT); INSERT INTO program_history (program_id, program_name, state, start_year) VALUES (1, 'Accessible Transportation', 'Florida', 2015), (2, 'Sign Language Interpretation', 'Florida', 2016), (3, 'Adaptive Equipment', 'Florida', 2017);

SELECT COUNT(*) FROM program_history WHERE state = 'Florida' AND start_year > 2015;


Question: Generate PostgreSQL SQL for: What is the average number of injuries caused each time?


Question: What is the percentage of hospitals in Los Angeles that offer free COVID-19 testing?

CREATE TABLE Hospitals (HospitalID INT, Name VARCHAR(50), City VARCHAR(30), State VARCHAR(20), FreeTesting BOOLEAN); INSERT INTO Hospitals (HospitalID, Name, City, State, FreeTesting) VALUES (1, 'Cedars-Sinai', 'Los Angeles', 'California', TRUE); INSERT INTO Hospitals (HospitalID, Name, City, State, FreeTesting) VALUES (2, 'UCLA Medical Center', 'Los Angeles', 'California', FALSE);

SELECT (COUNT(*) * 100.0 / (SELECT COUNT(*) FROM Hospitals WHERE City = 'Los Angeles')) FROM Hospitals WHERE City = 'Los Angeles' AND FreeTesting = TRUE;


Question: What is the number of circular economy initiatives for each province in China in 2020?

CREATE TABLE circular_economy_china (province VARCHAR(50), year INT, initiatives INT); INSERT INTO circular_economy_china (province, year, initiatives) VALUES ('Anhui', 2020, 12), ('Beijing', 2020, 15), ('Chongqing', 2020, 18), ('Fujian', 2020, 10), ('Gansu', 2020, 20);

SELECT province, initiatives FROM circular_economy_china WHERE year = 2020;


Question: Generate PostgreSQL SQL for: Name the most number of believers for ܓܘܝܠܢ

CREATE TABLE table_24613895_1 (number_of_believers INTEGER, name_in_syriac VARCHAR)

SELECT MAX(number_of_believers) FROM table_24613895_1 WHERE name_in_syriac = 'ܓܘܝܠܢ';


Question: Generate PostgreSQL SQL for: Name the number of population for  врбас

CREATE TABLE table_2562572_20 (population__2011_ VARCHAR, cyrillic_name_other_names VARCHAR)

SELECT COUNT(population__2011_) FROM table_2562572_20 WHERE cyrillic_name_other_names = 'Врбас';


Question: Delete records of health centers in Northern Mariana Islands.

CREATE TABLE health_centers (id INT, name TEXT, location TEXT); INSERT INTO health_centers (id, name, location) VALUES (1, 'Health Center A', 'Rural Alaska'); INSERT INTO health_centers (id, name, location) VALUES (5, 'Health Center E', 'Northern Mariana Islands');

DELETE FROM health_centers WHERE location = 'Northern Mariana Islands';


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

SELECT * FROM test_bit WHERE i>'100'::bit(3) ORDER BY i;

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


Question: Generate PostgreSQL SQL for: what is the overall number of chosen ideas where the person is scott parker

CREATE TABLE table_2840500_3 (pick VARCHAR, player VARCHAR)

SELECT COUNT(pick) FROM table_2840500_3 WHERE player = 'Scott Parker';


Question: Show a SQL definition from the citus project (distributed_types_xact_add_enum_value, item 7).

CREATE TABLE t1 (a int PRIMARY KEY, b xact_enum_edit);

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


Question: What is the total revenue for the 'Spring 2021' and 'Summer 2021' collections?

CREATE TABLE sales (collection VARCHAR(20), revenue INT); INSERT INTO sales (collection, revenue) VALUES ('Spring 2021', 500000), ('Summer 2021', 600000);

SELECT collection, SUM(revenue) FROM sales WHERE collection IN ('Spring 2021', 'Summer 2021') GROUP BY collection;


Question: Which supplier provided the most Praseodymium in 2017?

CREATE TABLE praseodymium_supply (year INT, supplier VARCHAR(20), praseodymium_supply INT); INSERT INTO praseodymium_supply VALUES (2015, 'Supplier F', 22), (2016, 'Supplier G', 27), (2017, 'Supplier H', 32), (2018, 'Supplier I', 37), (2019, 'Supplier J', 42);

SELECT supplier, MAX(praseodymium_supply) FROM praseodymium_supply WHERE year = 2017 GROUP BY supplier;


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

SELECT * FROM t1p_tens WHERE o > 50 AND p like '%64%';

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


Question: Delete properties with sustainable urbanism ratings below 70 from the view

CREATE VIEW properties AS SELECT * FROM property;

DELETE FROM properties WHERE rating < 70;


Question: Generate PostgreSQL SQL for: In which venue is South Melbourne the home team?

CREATE TABLE table_name_11 (venue VARCHAR, home_team VARCHAR)

SELECT venue FROM table_name_11 WHERE home_team = 'south melbourne';


Question: Delete all warehouses in Germany

CREATE TABLE warehouse (id INT, city VARCHAR(20), capacity INT); CREATE TABLE country (id INT, name VARCHAR(20)); INSERT INTO country (id, name) VALUES (1, 'India'), (2, 'USA'), (3, 'Germany'); CREATE VIEW warehouse_country AS SELECT * FROM warehouse INNER JOIN country ON warehouse.id = country.id; INSERT INTO warehouse (id, city, capacity) VALUES (10, 'Berlin', 3000), (11, 'Munich', 3500), (12, 'Frankfurt', 4000); INSERT INTO country (id, name) VALUES (4, 'Germany'); INSERT INTO warehouse_country (id, city, capacity, name) VALUES (10, 'Berlin', 3000, 'Germany'), (11, 'Munich', 3500, 'Germany'), (12, 'Frankfurt', 4000, 'Germany');

DELETE FROM warehouse_country WHERE name = 'Germany'; DELETE FROM warehouse WHERE name = 'Germany';


Question: Update the type of 'Venus Express' in the 'space_missions' table to 'orbiter'

CREATE TABLE space_missions (id INT PRIMARY KEY, name VARCHAR(50), type VARCHAR(50)); INSERT INTO space_missions (id, name, type) VALUES (1, 'Mars Pathfinder', 'rover'), (2, 'Spirit', 'rover'), (3, 'Opportunity', 'rover'), (4, 'Curiosity', 'rover'), (5, 'Venus Express', 'lander');

UPDATE space_missions SET type = 'orbiter' WHERE name = 'Venus Express';


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

CREATE PUBLICATION testpub6 FOR TABLE rf_bug WHERE (status = 'open') WITH (publish = 'insert');

Explanation: DDL from PostgreSQL core regression test for Publication.


Question: Generate PostgreSQL SQL for: Name the team for oct 30, 1989

CREATE TABLE table_1594772_2 (team__b_ VARCHAR, match_date VARCHAR)

SELECT team__b_ FROM table_1594772_2 WHERE match_date = 'Oct 30, 1989';


Question: Generate PostgreSQL SQL for: Which gender makes up the majority of the staff?

SELECT gender FROM staff GROUP BY gender ORDER BY COUNT(*) DESC LIMIT 1;


Question: What is the maximum production cost for items made of recycled polyester?

CREATE TABLE products (id INT, name TEXT, material TEXT, production_cost FLOAT); INSERT INTO products (id, name, material, production_cost) VALUES (1, 'Jacket', 'Recycled Polyester', 75.0), (2, 'Shoes', 'Recycled Polyester', 50.0);

SELECT MAX(production_cost) FROM products WHERE material = 'Recycled Polyester';


Question: What is the minimum size (in square kilometers) of a habitat for animals in the 'habitats' table that are not mammals?

CREATE TABLE habitats (id INT, animal_type VARCHAR(50), size_km FLOAT); INSERT INTO habitats (id, animal_type, size_km) VALUES (1, 'Mammal', 45.1), (2, 'Reptile', 25.1);

SELECT MIN(size_km) FROM habitats WHERE animal_type != 'Mammal';


Question: Generate PostgreSQL SQL for: Who was the broadcaster in 2003?

CREATE TABLE table_name_24 (broadcaster VARCHAR, year VARCHAR)

SELECT broadcaster FROM table_name_24 WHERE year = '2003';