Question: Generate PostgreSQL SQL for: What is the total erp w of class c3, which has a frequency mhz less than 89.9?

CREATE TABLE table_name_58 (erp_w VARCHAR, class VARCHAR, frequency_mhz VARCHAR)

SELECT COUNT(erp_w) FROM table_name_58 WHERE class = 'c3' AND frequency_mhz < 89.9;


Question: List all ports that have had cargo handled on a Sunday.

CREATE TABLE ports (port_id INT, port_name VARCHAR(50), city VARCHAR(50), country VARCHAR(50)); CREATE TABLE cargo (cargo_id INT, port_id INT, weight FLOAT, handling_date DATE);

SELECT DISTINCT port_name FROM cargo c JOIN ports p ON c.port_id = p.port_id WHERE DAYOFWEEK(handling_date) = 1;


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

-- Testing USING OPERATOR() in ORDER BY within aggregate.
-- For this, we need user defined operators along with operator family and
-- operator class.  Create those and then add them in extension.  Note that
-- user defined objects are considered unshippable unless they are part of
-- the extension.
create operator public.<^ (
 leftarg = int4,
 rightarg = int4,
 procedure = int4eq
);

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


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

/* contrib/pageinspect/pageinspect--1.2--1.3.sql */

-- complain if script is sourced in psql, rather than via ALTER EXTENSION
\echo Use "ALTER EXTENSION pageinspect UPDATE TO '1.3'" to load this file. \quit

--
-- brin_page_type()
--
CREATE FUNCTION brin_page_type(IN page bytea)
RETURNS text
AS 'MODULE_PATHNAME', 'brin_page_type'
LANGUAGE C STRICT;

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


Question: What is the maximum ocean acidification level in the Arctic Ocean?

CREATE TABLE ocean_acidification (location text, level numeric); INSERT INTO ocean_acidification (location, level) VALUES ('Arctic Ocean', 8.2), ('Atlantic Ocean', 7.9);

SELECT MAX(level) FROM ocean_acidification WHERE location = 'Arctic Ocean';


Question: Generate PostgreSQL SQL for: What skip has denmark as the country?

CREATE TABLE table_name_58 (skip VARCHAR, country VARCHAR)

SELECT skip FROM table_name_58 WHERE country = 'denmark';


Question: Write the DDL statement from PostgreSQL regression test 'xml' (example 136).

CREATE VIEW xmlview3 AS SELECT xmlelement(name element, xmlattributes (1 as ":one:", 'deuce' as two), 'content&');

Explanation: DDL from PostgreSQL core regression test for Xml.


Question: Generate PostgreSQL SQL for: What was the score in a place of t5 in the United States?

CREATE TABLE table_name_25 (score VARCHAR, place VARCHAR, nation VARCHAR)

SELECT score FROM table_name_25 WHERE place = 't5' AND nation = 'united states';


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

drop trigger child2_insert_trig on child2;

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


Question: How many countries are in the 'countries' table?

CREATE TABLE countries (id INT PRIMARY KEY, name VARCHAR(255), region VARCHAR(255)); INSERT INTO countries (id, name, region) VALUES (1, 'Canada', 'North America'), (2, 'Mexico', 'North America'), (3, 'Brazil', 'South America'), (4, 'Argentina', 'South America'), (5, 'India', 'Asia'), (6, 'China', 'Asia');


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

Explanation: DML from PostgreSQL core regression test for Numeric.


Question: Generate PostgreSQL SQL for: Name the most tier 1 capital for irish nationwide

CREATE TABLE table_22368322_2 (_€_million VARCHAR, tier_1_capital INTEGER, institution VARCHAR)

SELECT MAX(tier_1_capital), _€_million FROM table_22368322_2 WHERE institution = 'Irish Nationwide';


Question: What is the average budget for climate mitigation projects in Europe?

CREATE TABLE climate_mitigation_projects (project_id INT, project_name VARCHAR(255), location VARCHAR(255), budget DECIMAL(10,2)); INSERT INTO climate_mitigation_projects (project_id, project_name, location, budget) VALUES (1, 'Carbon Capture in Germany', 'Germany', 4000000.00), (2, 'Forest Conservation in France', 'France', 3000000.00), (3, 'Clean Transportation in UK', 'UK', 5000000.00);

SELECT AVG(budget) FROM climate_mitigation_projects WHERE location = 'Europe';


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

Explanation: DML from PostgreSQL core regression test for Rules.


Question: Update the amount of effective_altruism with id 1 to 2000000

CREATE TABLE effective_altruism (id INT PRIMARY KEY, name VARCHAR(100), amount INT, cause VARCHAR(20));

UPDATE effective_altruism SET amount = 2000000 WHERE id = 1;


Question: How many mining equipment units are there in the 'equipment_inventory' table, broken down by type?

CREATE TABLE equipment_inventory (id INT, equipment_type VARCHAR(50), quantity INT); INSERT INTO equipment_inventory (id, equipment_type, quantity) VALUES (1, 'Excavator', 10), (2, 'Drill', 15), (3, 'Haul Truck', 20);

SELECT equipment_type, quantity FROM equipment_inventory;


Question: Generate PostgreSQL SQL for: What's the lowest rank of a player who played in 2012?

CREATE TABLE table_name_50 (rank INTEGER, event VARCHAR)

SELECT MIN(rank) FROM table_name_50 WHERE event = '2012';


Question: Which communities have the highest engagement levels in language preservation in South Asia?

CREATE TABLE Communities (community_id INT PRIMARY KEY, community_name VARCHAR(255), region VARCHAR(255), engagement_level INT); INSERT INTO Communities (community_id, community_name, region, engagement_level) VALUES (2, 'Siddi', 'South Asia', 5);

SELECT c.community_name, c.region, l.language, l.script, l.speakers, c.engagement_level FROM Communities c INNER JOIN Languages l ON c.region = l.region WHERE c.engagement_level = (SELECT MAX(engagement_level) FROM Communities WHERE region = 'South Asia');


Question: Delete all fish records with a weight less than 1kg from the fish_inventory table

CREATE TABLE fish_inventory (fish_id INT, species VARCHAR(50), weight FLOAT, location VARCHAR(50));

DELETE FROM fish_inventory WHERE weight < 1.0;


Question: Generate PostgreSQL SQL for: What p;layer attended Concordia College?

CREATE TABLE table_name_40 (player VARCHAR, college VARCHAR)

SELECT player FROM table_name_40 WHERE college = 'concordia';


Question: PostgreSQL regression test 'sqljson_jsontable': Write the SELECT query (example 63).

SELECT * FROM JSON_TABLE(jsonb '"a"', '$' COLUMNS (a jsonb EXISTS PATH '$.a'));

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

SELECT count(*) FROM (SELECT * FROM JSON_TABLE(jsonb '"a"', '$' COLUMNS (a jsonb EXISTS PATH '$.a'))) AS _sub;


Question: What is the average number of donations per unique donor in the past year?

CREATE TABLE donor_donations (donor_id INT, donation_year INT); INSERT INTO donor_donations (donor_id, donation_year) VALUES (1, 2021), (2, 2021), (3, 2021), (4, 2021), (5, 2021);

SELECT AVG(cnt) AS avg_donations_per_donor FROM (SELECT donor_id, COUNT(*) AS cnt FROM donor_donations WHERE donation_year = YEAR(CURRENT_DATE) - 1 GROUP BY donor_id) subquery;


Question: What is the minimum number of military aircraft maintenance requests recorded for the Navy in the year 2022?

CREATE TABLE maintenance_requests (request_id INT, service_branch VARCHAR(255), request_date DATE); INSERT INTO maintenance_requests (request_id, service_branch, request_date) VALUES (1, 'Air Force', '2022-01-01'), (2, 'Navy', '2022-02-02'), (3, 'Air Force', '2022-03-03');

SELECT MIN(COUNT(*)) FROM maintenance_requests WHERE service_branch = 'Navy' AND EXTRACT(YEAR FROM request_date) = 2022 GROUP BY service_branch;


Question: Show an example of PostgreSQL PSQL-REF (example 5).

INSERT INTO tbls1 VALUES ($1, $2) \parse stmt1 \bind_named stmt1 'first value' 'second value' \g;

Explanation: PostgreSQL PSQL-REF command.


Question: What was the total revenue for each salesperson in the month of January?

CREATE TABLE salesperson (id INT, name TEXT, revenue FLOAT); INSERT INTO salesperson (id, name, revenue) VALUES (1, 'John', 5000.00), (2, 'Jane', 7000.00);

SELECT name, SUM(revenue) FROM salesperson WHERE EXTRACT(MONTH FROM date) = 1 GROUP BY name;


Question: What is the average donation amount for each cause in Q3 2021?

SELECT cause_id, AVG(amount) as avg_donation_amount FROM donations WHERE donation_date BETWEEN '2021-07-01' AND '2021-09-30' GROUP BY cause_id;


Question: Generate PostgreSQL SQL for: Name the date successor seated for delegate seat established

CREATE TABLE table_224837_4 (date_successor_seated VARCHAR, reason_for_change VARCHAR)

SELECT date_successor_seated FROM table_224837_4 WHERE reason_for_change = 'Delegate seat established';


Question: Write the DDL statement from PostgreSQL regression test 'domain' (example 50).

create domain domainchar4arr varchar(4)[2][3];

Explanation: DDL from PostgreSQL core regression test for Domain.


Question: Write the DDL statement from PostgreSQL regression test 'truncate' (example 15).

CREATE TABLE trunc_d (a int REFERENCES trunc_c);

Explanation: DDL from PostgreSQL core regression test for Truncate.


Question: How many public outreach events have been held at each excavation site, and what was the average attendance?

CREATE TABLE ExcavationSites (SiteID int, SiteName varchar(50), Location varchar(50)); CREATE TABLE PublicOutreach (EventID int, SiteID int, EventType varchar(20), Attendance int);

SELECT ExcavationSites.SiteName, AVG(PublicOutreach.Attendance) AS AverageAttendance, COUNT(PublicOutreach.EventID) AS NumberOfEvents FROM ExcavationSites INNER JOIN PublicOutreach ON ExcavationSites.SiteID = PublicOutreach.SiteID GROUP BY ExcavationSites.SiteName;


Question: What's the total donation amount per quarter?

CREATE TABLE Donations (DonationID INT, DonorID INT, DonationDate DATE, Amount FLOAT); INSERT INTO Donations (DonationID, DonorID, DonationDate, Amount) VALUES (1, 1, '2022-01-01', 100.00), (2, 2, '2022-02-15', 150.00);

SELECT DATE_PART('quarter', DonationDate) AS Quarter, SUM(Amount) FROM Donations GROUP BY Quarter;


Question: Generate PostgreSQL SQL for: what is the years when playoffs is 115?

CREATE TABLE table_name_51 (years VARCHAR, playoffs VARCHAR)

SELECT years FROM table_name_51 WHERE playoffs = 115;


Question: Generate PostgreSQL SQL for: What was the attendance on May 13?

CREATE TABLE table_name_76 (attendance VARCHAR, date VARCHAR)

SELECT attendance FROM table_name_76 WHERE date = 'may 13';


Question: PostgreSQL regression test 'pg_ndistinct': Write the SELECT query (example 70).

SELECT * FROM pg_input_error_info('[{"attributes" : [2,3], "ndistinct" : 4},
         {"attributes" : [2,3], "ndistinct" : 4}]', 'pg_ndistinct');

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

SELECT count(*) FROM (SELECT * FROM pg_input_error_info('[{"attributes" : [2,3], "ndistinct" : 4},
         {"attributes" : [2,3], "ndistinct" : 4}]', 'pg_ndistinct')) AS _sub;


Question: Generate PostgreSQL SQL for: What's the English name of the month abbreviated as มิ.ย.?

CREATE TABLE table_180802_2 (english_name VARCHAR, abbr VARCHAR)

SELECT english_name FROM table_180802_2 WHERE abbr = 'มิ.ย.';


Question: What is the total number of players who have participated in esports events in each country?

CREATE TABLE EsportsParticipation (PlayerID INT, Country VARCHAR(50), EventID INT); INSERT INTO EsportsParticipation (PlayerID, Country, EventID) VALUES (1, 'USA', 1), (2, 'Canada', 2), (3, 'Mexico', 3), (4, 'Germany', 4), (5, 'France', 5), (6, 'USA', 6), (7, 'Canada', 7), (8, 'Mexico', 8), (9, 'USA', 9), (10, 'Brazil', 10);

SELECT Country, COUNT(DISTINCT PlayerID) FROM EsportsParticipation GROUP BY Country;


Question: What is the explainability rating for the AI system named 'AI Judge'?

CREATE TABLE explainable_ai (ai_system TEXT, rating FLOAT); INSERT INTO explainable_ai (ai_system, rating) VALUES ('AI Judge', 0.75), ('AI Translator', 0.90), ('AI Artist', 0.60);

SELECT rating FROM explainable_ai WHERE ai_system = 'AI Judge';


Question: List the number of investments made in 'renewable energy' and 'green infrastructure' strategies, by year.

CREATE TABLE investments_strategies_3 (id INT, investment_year INT, strategy VARCHAR(30), investment_amount FLOAT); INSERT INTO investments_strategies_3 (id, investment_year, strategy, investment_amount) VALUES (1, 2019, 'renewable energy', 120000), (2, 2020, 'green infrastructure', 185000), (3, 2018, 'renewable energy', 175000);

SELECT investment_year, COUNT(*) FROM investments_strategies_3 WHERE strategy IN ('renewable energy', 'green infrastructure') GROUP BY investment_year;


Question: List all mobile subscribers who have exceeded their monthly data limit in the last month.

CREATE TABLE mobile_subscribers (subscriber_id INT, data_limit DECIMAL(5,2), data_usage DECIMAL(5,2), last_update DATE); INSERT INTO mobile_subscribers (subscriber_id, data_limit, data_usage, last_update) VALUES (1, 3.0, 3.2, '2022-01-15'), (2, 4.0, 3.8, '2022-01-07'), (3, 5.0, 4.9, '2022-01-20');

SELECT subscriber_id FROM mobile_subscribers WHERE data_usage > data_limit AND last_update >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH);


Question: Show the total military innovation budget by fiscal year

CREATE TABLE military_innovation (id INT, fiscal_year INT, budget DECIMAL(10, 2)); INSERT INTO military_innovation (id, fiscal_year, budget) VALUES (1, 2018, 50000), (2, 2019, 55000), (3, 2020, 60000), (4, 2021, 65000);

SELECT fiscal_year, SUM(budget) as total_budget FROM military_innovation GROUP BY fiscal_year;


Question: Update the funding amount for startup with id 1 in the 'funding' table

funding(id, startup_id, funding_round, funding_amount, date_announced)

UPDATE funding SET funding_amount = 1000000 WHERE startup_id = 1;


Question: Generate PostgreSQL SQL for: What is Rank Points, when Event is "WC Milan", and when Shooter is "Lalita Yauhleuskaya ( AUS )"?

CREATE TABLE table_name_77 (rank_points VARCHAR, event VARCHAR, shooter VARCHAR)

SELECT rank_points FROM table_name_77 WHERE event = 'wc milan' AND shooter = 'lalita yauhleuskaya ( aus )';


Question: Identify the total budget allocated for public health and education services in the city of Seattle and Austin, removing any duplicates.

CREATE TABLE HealthEducation (service VARCHAR(20), city VARCHAR(20), budget INT); INSERT INTO HealthEducation (service, city, budget) VALUES ('Public Health', 'Seattle', 6000000), ('Education', 'Seattle', 5000000), ('Public Health', 'Austin', 6500000), ('Education', 'Austin', 4500000);

SELECT DISTINCT(service), SUM(budget) FROM HealthEducation WHERE city IN ('Seattle', 'Austin') GROUP BY service;


Question: Insert a new policy with policy ID 3, policy type 'Homeowners', and effective date '2022-01-01'

CREATE TABLE policy (policy_id INT, policy_type VARCHAR(20), effective_date DATE);

INSERT INTO policy (policy_id, policy_type, effective_date) VALUES (3, 'Homeowners', '2022-01-01');


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

select jsonb_path_query('{"a": {"b": 1}}', 'lax $.**{0 to last}');

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

SELECT count(*) FROM (select jsonb_path_query('{"a": {"b": 1}}', 'lax $.**{0 to last}')) AS _sub;


Question: Show a query using PostgreSQL contrib extension 'pg_stat_statements' (example 73).

SELECT * FROM test_squash_bigint WHERE data IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);

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


Question: Generate PostgreSQL SQL for: Where did Trinidad and Tobago play?

CREATE TABLE table_name_99 (place VARCHAR, country VARCHAR)

SELECT place FROM table_name_99 WHERE country = 'trinidad and tobago';


Question: What is the average age of children supported by 'Save the Children' in 'South America'?

CREATE TABLE children (id INT, name VARCHAR(255), age INT, location VARCHAR(255), supported_by VARCHAR(255), support_date DATE); INSERT INTO children (id, name, age, location, supported_by, support_date) VALUES (1, 'James Smith', 12, 'South America', 'Save the Children', '2022-01-01');

SELECT AVG(age) FROM children WHERE location = 'South America' AND supported_by = 'Save the Children';


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

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

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


Question: Generate PostgreSQL SQL for: How many games played when the points for is 369?

CREATE TABLE table_name_89 (played VARCHAR, points_for VARCHAR)

SELECT played FROM table_name_89 WHERE points_for = '369';


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

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

SELECT count(*) FROM (select 'null'::jsonb::int8) AS _sub;


Question: Generate PostgreSQL SQL for: What Etymology ranked 12?

CREATE TABLE table_name_58 (etymology VARCHAR, rank VARCHAR)

SELECT etymology FROM table_name_58 WHERE rank = 12;


Question: Show a SQL definition from the timescaledb project (plan_hypertable_inline, item 4).

CREATE OR REPLACE FUNCTION test_f(_ts bigint)
RETURNS SETOF test LANGUAGE SQL STABLE
as $f$
   SELECT DISTINCT ON (a) * FROM test WHERE b >= _ts AND b <= _ts + 2
$f$;

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


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

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


Question: Write the DDL statement from PostgreSQL regression test 'tablespace' (example 98).

CREATE TABLE testschema.dflt (a int PRIMARY KEY) PARTITION BY LIST (a) TABLESPACE regress_tblspace;

Explanation: DDL from PostgreSQL core regression test for Tablespace.


Question: What is the average number of labor rights violations for each union in the Americas in the last year?

CREATE TABLE unions (id INT, name TEXT, location TEXT); INSERT INTO unions (id, name, location) VALUES (1, 'Union X', 'USA'), (2, 'Union Y', 'Canada'); CREATE TABLE violations (id INT, union_id INT, date DATE, violation_count INT); INSERT INTO violations (id, union_id, date, violation_count) VALUES (1, 1, '2021-02-15', 3), (2, 2, '2021-03-01', 5);

SELECT u.name, AVG(v.violation_count) FROM unions u JOIN violations v ON u.id = v.union_id WHERE u.location LIKE 'Americas%' AND v.date >= DATEADD(year, -1, CURRENT_DATE) GROUP BY u.name;


Question: Find the average donation amount for each program.

CREATE TABLE donations (donation_id INT, donor_id INT, program_id INT, amount_donated DECIMAL(10, 2)); INSERT INTO donations VALUES (1, 1, 1, 500.00), (2, 2, 2, 350.00), (3, 1, 1, 200.00); CREATE TABLE programs (program_id INT, program_name TEXT, budget DECIMAL(10, 2)); INSERT INTO programs VALUES (1, 'Education', 10000.00), (2, 'Health', 15000.00); CREATE TABLE donors (donor_id INT, name TEXT); INSERT INTO donors VALUES (1, 'Jamila Johnson'), (2, 'Jose Hernandez');

SELECT programs.program_name, AVG(donations.amount_donated) AS avg_donation FROM donations INNER JOIN programs ON donations.program_id = programs.program_id GROUP BY programs.program_name;


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

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


Question: pgTAP test for Functap (assertion 78).

SELECT * FROM check_test(
    function_lang_is( 'why', 'sql', 'whatever' ),
    false,
    'function_lang_is(non-func, sql, desc)',
    'whatever',
    '    Function why() does not exist'
);

Explanation: SQL assertion from pgTAP test suite for Functap.


Question: Generate PostgreSQL SQL for: What shows for Unit with a status of nomen oblitum?

CREATE TABLE table_name_16 (unit VARCHAR, status VARCHAR)

SELECT unit FROM table_name_16 WHERE status = 'nomen oblitum';


Question: What is the average play time for each 'Role-playing' game on PC, by publisher?

CREATE TABLE Games (Id INT, Name VARCHAR(100), Genre VARCHAR(50), Platform VARCHAR(50), Publisher VARCHAR(100), PlayTime FLOAT); INSERT INTO Games VALUES (1, 'GameG', 'Action', 'PC', 'Publisher1', 20.5), (2, 'GameH', 'Role-playing', 'VR', 'Publisher2', 35.2), (3, 'GameI', 'Action', 'Console', 'Publisher1', 18.4), (4, 'GameJ', 'Role-playing', 'PC', 'Publisher3', 45.6), (5, 'GameK', 'Role-playing', 'Console', 'Publisher3', 30.5), (6, 'GameL', 'Action', 'VR', 'Publisher2', 52.1), (7, 'GameM', 'Role-playing', 'PC', 'Publisher1', 25.8);

SELECT Publisher, AVG(PlayTime) AS Avg_PlayTime FROM Games WHERE Genre = 'Role-playing' AND Platform = 'PC' GROUP BY Publisher;


Question: Generate PostgreSQL SQL for: what is the rank for athlete hauffe, seifert, kaeufer, adamski?

CREATE TABLE table_name_88 (rank INTEGER, athlete VARCHAR)

SELECT SUM(rank) FROM table_name_88 WHERE athlete = 'hauffe, seifert, kaeufer, adamski';


Question: Generate PostgreSQL SQL for: Who is the leading scorer of the Villa De Los Barrios visitor?

CREATE TABLE table_name_56 (leading_scorer VARCHAR, visitor VARCHAR)

SELECT leading_scorer FROM table_name_56 WHERE visitor = 'villa de los barrios';


Question: Generate PostgreSQL SQL for: What was the score of the game in which Danny Granger (30) did the high points?

CREATE TABLE table_27756164_2 (score VARCHAR, high_points VARCHAR)

SELECT score FROM table_27756164_2 WHERE high_points = 'Danny Granger (30)';


Question: Delete all records from the 'oil_reservoirs' table where the oil_volume_bbls is less than 500000000

CREATE TABLE oil_reservoirs (reservoir_id INT PRIMARY KEY, reservoir_name VARCHAR(255), discovered_year INT, oil_volume_bbls BIGINT);

DELETE FROM oil_reservoirs WHERE oil_volume_bbls < 500000000;


Question: Generate PostgreSQL SQL for: Name the outgoing manager for position in table being 11th

CREATE TABLE table_17039232_3 (outgoing_manager VARCHAR, position_in_table VARCHAR)

SELECT outgoing_manager FROM table_17039232_3 WHERE position_in_table = '11th';


Question: Update the ticket price for basketball matches in the 'basketball_tickets' table in January to 50?

CREATE TABLE basketball_tickets (ticket_id INT, match_id INT, price DECIMAL(5,2), date DATE);

UPDATE basketball_tickets SET price = 50 WHERE MONTH(date) = 1;


Question: What is the average price of ethically sourced clothing items?

CREATE TABLE products (product_id INT, category VARCHAR(20), is_ethically_sourced BOOLEAN, price INT); INSERT INTO products (product_id, category, is_ethically_sourced, price) VALUES (1, 'clothing', true, 50), (2, 'electronics', false, 200), (3, 'clothing', true, 75);

SELECT AVG(products.price) FROM products WHERE products.category = 'clothing' AND products.is_ethically_sourced = true;


Question: Delete all records in the shared_bikes table in Chicago.

CREATE TABLE shared_bikes (bike_id INT, city VARCHAR(20), is_electric BOOLEAN); INSERT INTO shared_bikes (bike_id, city, is_electric) VALUES (1, 'New York', true), (2, 'Chicago', true), (3, 'New York', false);

DELETE FROM shared_bikes WHERE city = 'Chicago';


Question: What is the average salary of government employees in Washington DC, and how many of them are there?

CREATE TABLE employees (name VARCHAR(255), city VARCHAR(255), salary DECIMAL(10,2), government BOOLEAN); INSERT INTO employees (name, city, salary, government) VALUES ('John Doe', 'Washington DC', 80000.00, TRUE), ('Jane Smith', 'Washington DC', 90000.00, TRUE);

SELECT AVG(salary) FROM employees WHERE city = 'Washington DC' AND government = TRUE; SELECT COUNT(*) FROM employees WHERE city = 'Washington DC' AND government = TRUE;


Question: What is the percentage of new hires who identify as LGBTQ+ in the HR department in the past year?

CREATE TABLE Employees (EmployeeID INT, HireDate DATE, Community VARCHAR(25), Department VARCHAR(25)); INSERT INTO Employees (EmployeeID, HireDate, Community, Department) VALUES (1, '2022-01-01', 'LGBTQ+', 'HR'), (2, '2022-02-15', 'Allied', 'Marketing'), (3, '2022-02-15', 'LGBTQ+', 'IT'), (4, '2021-12-01', 'LGBTQ+', 'HR');

SELECT Department, COUNT(*) * 100.0 / (SELECT COUNT(*) FROM Employees WHERE HireDate >= DATEADD(year, -1, GETDATE())) AS Percentage FROM Employees WHERE Community = 'LGBTQ+' AND Department = 'HR' GROUP BY Department;


Question: Generate PostgreSQL SQL for: Who won on 2007-04-14

CREATE TABLE table_name_66 (result VARCHAR, date VARCHAR)

SELECT result FROM table_name_66 WHERE date = '2007-04-14';


Question: Generate PostgreSQL SQL for: How many Points have an Average smaller than 1, a Played larger than 38, and a Team of gimnasia de la plata?

CREATE TABLE table_name_73 (points INTEGER, team VARCHAR, average VARCHAR, played VARCHAR)

SELECT SUM(points) FROM table_name_73 WHERE average < 1 AND played > 38 AND team = 'gimnasia de la plata';


Question: List the types of military innovation from South Korea.

CREATE TABLE sk_innovation (id INT, country VARCHAR(50), type VARCHAR(50)); INSERT INTO sk_innovation (id, country, type) VALUES (1, 'South Korea', 'Drone Swarms'), (2, 'South Korea', 'Stealth Technology'), (3, 'South Korea', 'Artificial Intelligence'), (4, 'South Korea', 'Cyber Warfare');

SELECT DISTINCT type FROM sk_innovation WHERE country = 'South Korea';


Question: How many units of each garment type were sold in 2021?

CREATE TABLE sales (sale_id INT, product_id INT, sale_date DATE, units INT); CREATE TABLE products (product_id INT, product_name VARCHAR(50), product_type VARCHAR(50));

SELECT p.product_type, SUM(s.units) as total_units FROM sales s JOIN products p ON s.product_id = p.product_id WHERE s.sale_date BETWEEN '2021-01-01' AND '2021-12-31' GROUP BY p.product_type;


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

SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists_partial WHERE a = 10 AND b = 10 AND c = 10');

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

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


Question: What percentage of tourists visiting Sydney speak English?

CREATE TABLE language_stats (id INT, city VARCHAR(20), country VARCHAR(10), language VARCHAR(10), num_tourists INT); INSERT INTO language_stats (id, city, country, language, num_tourists) VALUES (1, 'Sydney', 'Australia', 'English', 50000), (2, 'Sydney', 'China', 'Mandarin', 20000), (3, 'Sydney', 'USA', 'English', 30000);

SELECT (SUM(CASE WHEN language = 'English' THEN num_tourists ELSE 0 END) * 100.0 / SUM(num_tourists)) AS percentage FROM language_stats WHERE city = 'Sydney';


Question: Generate PostgreSQL SQL for: Which Free polite has a Genitive 3 of *n(i)-ami?

CREATE TABLE table_name_40 (free VARCHAR, genitive_3 VARCHAR)

SELECT free AS polite FROM table_name_40 WHERE genitive_3 = '*n(i)-ami';


Question: Generate PostgreSQL SQL for: How many times is the score 98–90?

CREATE TABLE table_11959669_6 (location_attendance VARCHAR, score VARCHAR)

SELECT COUNT(location_attendance) FROM table_11959669_6 WHERE score = '98–90';


Question: Show the total impact investment in the Healthcare sector for the year 2022.

CREATE TABLE impact_investments (id INT, investment_id INT, sector VARCHAR(255), investment_amount FLOAT, investment_date DATE); INSERT INTO impact_investments (id, investment_id, sector, investment_amount, investment_date) VALUES (1, 3, 'Healthcare', 500000.0, '2022-03-22');

SELECT SUM(investment_amount) FROM impact_investments WHERE sector = 'Healthcare' AND investment_date BETWEEN '2022-01-01' AND '2022-12-31';


Question: Delete community health worker records that have not been updated in the last 2 years.

CREATE TABLE community_health_workers (id INT, name TEXT, last_update DATE); INSERT INTO community_health_workers (id, name, last_update) VALUES (1, 'Sophia Lee', '2019-01-01'), (2, 'Daniel Park', '2020-01-01');

DELETE FROM community_health_workers WHERE last_update < DATE_SUB(CURDATE(), INTERVAL 2 YEAR);


Question: Generate PostgreSQL SQL for: Which Champion has a Coeff of 1.000?

CREATE TABLE table_name_85 (champions VARCHAR, coeff VARCHAR)

SELECT champions FROM table_name_85 WHERE coeff = '1.000';


Question: What is the total energy produced by solar power plants in Australia?

CREATE TABLE solar_production (country VARCHAR(20), energy NUMERIC(12,2)); INSERT INTO solar_production (country, energy) VALUES ('Australia', 1500.0), ('Australia', 1600.5), ('Australia', 1400.0), ('Australia', 1750.2);

SELECT SUM(energy) FROM solar_production WHERE country = 'Australia';


Question: Write the DDL statement from PostgreSQL regression test 'generated_stored' (example 20).

CREATE TABLE gtest_err_7b (a int PRIMARY KEY, b int GENERATED ALWAYS AS (row_number() OVER (ORDER BY a)) STORED);

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


Question: Generate PostgreSQL SQL for: Who's ranked less than 2?

CREATE TABLE table_name_32 (player VARCHAR, rank INTEGER)

SELECT player FROM table_name_32 WHERE rank < 2;


Question: What is the total oil production in the Gulf of Mexico in 2019?

CREATE TABLE production_figures (well_id INT, year INT, oil_production INT, gas_production INT); INSERT INTO production_figures (well_id, year, oil_production, gas_production) VALUES (1, 2019, 120000, 50000); INSERT INTO production_figures (well_id, year, oil_production, gas_production) VALUES (2, 2018, 130000, 60000); INSERT INTO production_figures (well_id, year, oil_production, gas_production) VALUES (3, 2019, 110000, 45000);

SELECT SUM(oil_production) FROM production_figures WHERE year = 2019 AND region = 'Gulf of Mexico';


Question: Generate PostgreSQL SQL for: What was the 3rd Party in the Election of 1922?

CREATE TABLE table_name_35 (election VARCHAR)

SELECT 3 AS rd_party FROM table_name_35 WHERE election = '1922';


Question: Identify the number of military equipment repairs for each type in the last month

CREATE TABLE EquipmentRepairs (id INT, repair_date DATE, equipment_type VARCHAR(50), repair_cost FLOAT); INSERT INTO EquipmentRepairs (id, repair_date, equipment_type, repair_cost) VALUES (1, '2022-02-15', 'Artillery', 5000);

SELECT equipment_type, COUNT(*) FROM EquipmentRepairs WHERE repair_date >= CURDATE() - INTERVAL 1 MONTH GROUP BY equipment_type;


Question: Show the number of garments made from ethical materials, grouped by garment type.

CREATE TABLE garment_type_cost (id INT, garment_type VARCHAR(255), production_cost DECIMAL(10,2));

SELECT garment_type, COUNT(*) AS garment_count FROM garment_type_cost GROUP BY garment_type;


Question: Which suppliers are located in Canada and have a sustainability rating of 4 or higher?

CREATE TABLE Suppliers (id INT PRIMARY KEY, supplier_name VARCHAR(255), country VARCHAR(100), sustainability_rating INT); INSERT INTO Suppliers (id, supplier_name, country, sustainability_rating) VALUES (1, 'Green Farms', 'Canada', 4), (2, 'Tropical Fruits', 'Brazil', 3), (3, 'Ocean Harvest', 'Norway', 5);

SELECT supplier_name FROM Suppliers WHERE country = 'Canada' AND sustainability_rating >= 4;


Question: Write the DDL statement from PostgreSQL regression test 'aggregates' (example 305).

create or replace view agg_view1 as
  select aggfns(a,b,c order by c using ~<~)
    from (values (1,3,'foo'),(0,null,null),(2,2,'bar'),(3,1,'baz')) v(a,b,c);

Explanation: DDL from PostgreSQL core regression test for Aggregates.


Question: What is the minimum AI adoption score for hotels in 'Africa'?

CREATE TABLE ai_adoption (hotel_id INT, score INT);

SELECT MIN(score) FROM ai_adoption WHERE country = 'Africa';


Question: Generate PostgreSQL SQL for: What was the results of the game at Doha?

CREATE TABLE table_name_51 (result VARCHAR, venue VARCHAR)

SELECT result FROM table_name_51 WHERE venue = 'doha';


Question: How many Freedom of Information Act (FOIA) requests were submitted per state in 'foia_requests' table?

CREATE TABLE foia_requests (request_id INT, request_date DATE, request_state VARCHAR(255));

SELECT request_state, COUNT(request_id) AS foia_requests_per_state FROM foia_requests GROUP BY request_state;


Question: What is the total number of customers and their total assets value for each investment strategy?

CREATE TABLE customers (id INT, name TEXT, age INT, country TEXT, assets FLOAT, investment_strategy TEXT); INSERT INTO customers (id, name, age, country, assets, investment_strategy) VALUES (1, 'John Doe', 45, 'USA', 250000.00, 'Conservative'); INSERT INTO customers (id, name, age, country, assets, investment_strategy) VALUES (2, 'Jane Smith', 34, 'Canada', 320000.00, 'Moderate'); INSERT INTO customers (id, name, age, country, assets, investment_strategy) VALUES (3, 'Alice Johnson', 29, 'UK', 450000.00, 'Aggressive'); INSERT INTO customers (id, name, age, country, assets, investment_strategy) VALUES (4, 'Bob Brown', 51, 'UK', 150000.00, 'Conservative'); INSERT INTO customers (id, name, age, country, assets, investment_strategy) VALUES (5, 'Charlie Davis', 48, 'USA', 800000.00, 'Aggressive'); INSERT INTO customers (id, name, age, country, assets, investment_strategy) VALUES (6, 'David Kim', 38, 'Singapore', 520000.00, 'Moderate');

SELECT investment_strategy, COUNT(*), SUM(assets) FROM customers GROUP BY investment_strategy;


Question: Generate PostgreSQL SQL for: Which rounds do Arciero Wines sponsor a March 85c chassis?

CREATE TABLE table_name_7 (rounds VARCHAR, sponsor_s_ VARCHAR, chassis VARCHAR)

SELECT rounds FROM table_name_7 WHERE sponsor_s_ = 'arciero wines' AND chassis = 'march 85c';


Question: What is the total number of electric bikes in the city of Seattle?

CREATE TABLE if not exists bike_share (id INT, city VARCHAR(20), bike_type VARCHAR(20), quantity INT);INSERT INTO bike_share (id, city, bike_type, quantity) VALUES (1, 'Seattle', 'electric_bike', 500), (2, 'Portland', 'electric_bike', 350), (3, 'Seattle', 'classic_bike', 800);

SELECT SUM(quantity) FROM bike_share WHERE city = 'Seattle' AND bike_type = 'electric_bike';


Question: Generate PostgreSQL SQL for: How many won the Men's Open if the players are from Sweden?

CREATE TABLE table_182298_5 (mens_open VARCHAR, country VARCHAR)

SELECT COUNT(mens_open) FROM table_182298_5 WHERE country = 'Sweden';


Question: What is the total number of songs for each artist?

CREATE TABLE Artist (ArtistID INT, ArtistName VARCHAR(50)); CREATE TABLE Song (SongID INT, SongName VARCHAR(50), ArtistID INT); INSERT INTO Artist (ArtistID, ArtistName) VALUES (1, 'Taylor Swift'), (2, 'BTS'), (3, 'Adele'); INSERT INTO Song (SongID, SongName, ArtistID) VALUES (1, 'Shake it Off', 1), (2, 'Blank Space', 1), (3, 'Dynamite', 2), (4, 'Butter', 2), (5, 'Rolling in the Deep', 3);

SELECT ArtistName, COUNT(SongName) OVER (PARTITION BY ArtistID) AS SongCount FROM Artist JOIN Song ON Artist.ArtistID = Song.ArtistID;


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

SELECT '2011-03-27 01:59:59 Europe/Moscow'::timestamptz;

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

SELECT count(*) FROM (SELECT '2011-03-27 01:59:59 Europe/Moscow'::timestamptz) AS _sub;


Question: Generate PostgreSQL SQL for: Name the dominant religion 2002 for  меленци

CREATE TABLE table_2562572_35 (dominant_religion__2002_ VARCHAR, cyrillic_name_other_names VARCHAR)

SELECT dominant_religion__2002_ FROM table_2562572_35 WHERE cyrillic_name_other_names = 'Меленци';


Question: How many media representation initiatives are there in the EU?

CREATE TABLE Countries (Country TEXT, MediaRepresentationInitiatives INT); INSERT INTO Countries (Country, MediaRepresentationInitiatives) VALUES ('Germany', 4), ('France', 3), ('Italy', 2), ('Spain', 1);

SELECT SUM(MediaRepresentationInitiatives) FROM Countries WHERE Country IN ('Germany', 'France', 'Italy', 'Spain', 'Belgium', 'Netherlands', 'Luxembourg', 'Ireland', 'Austria', 'Portugal', 'Finland', 'Sweden', 'Denmark', 'Estonia', 'Latvia', 'Lithuania', 'Slovakia', 'Slovenia', 'Czech Republic', 'Hungary', 'Poland', 'Romania', 'Bulgaria', 'Croatia', 'Malta', 'Cyprus');


Question: Calculate the average ticket price for concerts in Canada.

CREATE TABLE concerts (id INT, artist_id INT, location TEXT, price DECIMAL);

SELECT AVG(price) FROM concerts WHERE location LIKE '%Canada%';


Question: Generate PostgreSQL SQL for: How many picks are there with an affiliation is the University of California Norcal Lamorinda United?

CREATE TABLE table_25518547_2 (pick__number VARCHAR, affiliation VARCHAR)

SELECT COUNT(pick__number) FROM table_25518547_2 WHERE affiliation = 'University of California NorCal Lamorinda United';


Question: What is the maximum R&D expenditure per year for drugs that were approved after 2017?

CREATE TABLE rd_expenditure (id INT PRIMARY KEY, drug_id INT, year INT, amount DECIMAL(10,2)); CREATE TABLE drugs (id INT PRIMARY KEY, name VARCHAR(255), manufacturer VARCHAR(255), approval_date DATE);

SELECT MAX(amount) as max_annual_rd_expenditure FROM rd_expenditure JOIN drugs ON rd_expenditure.drug_id = drugs.id WHERE approval_date > '2017-01-01' GROUP BY rd_expenditure.year;


Question: Who is the manufacturer of 'DrugD'?

CREATE TABLE drug_info (drug_name TEXT, manufacturer TEXT);

SELECT manufacturer FROM drug_info WHERE drug_name = 'DrugD';


Question: Generate PostgreSQL SQL for: What is the Score of the match on a clay surface with an outcome of winner, at the tournament ciudad juárez, and an Opponent in the final of estefania craciún?

CREATE TABLE table_name_48 (score VARCHAR, opponent_in_the_final VARCHAR, tournament VARCHAR, surface VARCHAR, outcome VARCHAR)

SELECT score FROM table_name_48 WHERE surface = 'clay' AND outcome = 'winner' AND tournament = 'ciudad juárez' AND opponent_in_the_final = 'estefania craciún';


Question: Generate PostgreSQL SQL for: What season did they play queensland at wicket 4?

CREATE TABLE table_name_81 (season VARCHAR, opponent VARCHAR, wicket VARCHAR)

SELECT season FROM table_name_81 WHERE opponent = 'queensland' AND wicket = '4';


Question: What is the total number of restorative justice programs, by state, with a start date within the last 5 years?

CREATE TABLE restorative_justice_programs (program_id INT, state VARCHAR(20), start_date DATE); INSERT INTO restorative_justice_programs (program_id, state, start_date) VALUES (1, 'California', '2017-01-01'), (2, 'Texas', '2018-06-15'), (3, 'New York', '2019-02-03');

SELECT restorative_justice_programs.state, COUNT(*) as num_programs FROM restorative_justice_programs WHERE restorative_justice_programs.start_date >= DATE_SUB(CURRENT_DATE, INTERVAL 5 YEAR) GROUP BY restorative_justice_programs.state;


Question: Generate PostgreSQL SQL for: Which score happened on 11 february 1996?

CREATE TABLE table_name_37 (score VARCHAR, date VARCHAR)

SELECT score FROM table_name_37 WHERE date = '11 february 1996';


Question: How many agricultural innovation projects were completed in the last 3 years, grouped by completion year?

CREATE TABLE agri_innovation (id INT, project_name TEXT, completion_date DATE); INSERT INTO agri_innovation (id, project_name, completion_date) VALUES (1, 'Precision Agriculture Test', '2020-05-01'), (2, 'Drip Irrigation Implementation', '2021-08-15'), (3, 'Vertical Farming Study', '2022-02-28');

SELECT YEAR(completion_date) AS completion_year, COUNT(*) AS projects_completed FROM agri_innovation WHERE completion_date >= DATE('2019-01-01') GROUP BY completion_year;


Question: Generate PostgreSQL SQL for: What team picked 80?

CREATE TABLE table_name_94 (team VARCHAR, pick VARCHAR)

SELECT team FROM table_name_94 WHERE pick = 80;


Question: What is the average age of players who use VR technology, by country?

CREATE TABLE PlayerDemographics (PlayerID INT, Age INT, Gender VARCHAR(10), Country VARCHAR(50), VRTechnology BOOLEAN); INSERT INTO PlayerDemographics (PlayerID, Age, Gender, Country, VRTechnology) VALUES (1, 25, 'Male', 'USA', TRUE), (2, 30, 'Female', 'Canada', FALSE), (3, 22, 'Male', 'Mexico', TRUE);

SELECT Country, AVG(Age) FROM PlayerDemographics WHERE VRTechnology = TRUE GROUP BY Country;


Question: What are the names of vehicles that failed safety tests in Brazil in 2019?

CREATE TABLE VehicleSafetyTestsBrazil (vehicle_id INT, model VARCHAR(100), passed BOOLEAN, country VARCHAR(50), year INT); INSERT INTO VehicleSafetyTestsBrazil (vehicle_id, model, passed, country, year) VALUES (1, 'Model S', false, 'Brazil', 2019), (2, 'Gol', true, 'Brazil', 2019);

SELECT model FROM VehicleSafetyTestsBrazil WHERE passed = false AND country = 'Brazil' AND year = 2019;


Question: What is the total value of virtual tour engagement in 'North America' in the last month?

CREATE TABLE virtual_tours (virtual_tour_id INT, virtual_tour_location TEXT, engagement_date DATE, engagement_value INT); INSERT INTO virtual_tours (virtual_tour_id, virtual_tour_location, engagement_date, engagement_value) VALUES (1, 'Virtual Tour North America', '2022-02-01', 200), (2, 'Virtual Tour North America', '2022-02-05', 150);

SELECT SUM(engagement_value) FROM virtual_tours WHERE engagement_date >= DATEADD(month, -1, GETDATE()) AND virtual_tour_location = 'North America';


Question: Generate PostgreSQL SQL for: What time was the fastest lap during Stoh's 200 in 1982?

CREATE TABLE table_name_74 (fastest_lap VARCHAR, name VARCHAR)

SELECT fastest_lap FROM table_name_74 WHERE name = 'stoh's 200';


Question: What is the total number of posts, likes, and shares for each sector in the ai_companies table?

CREATE TABLE ai_companies (id INT, name VARCHAR(20), location VARCHAR(20), sector VARCHAR(20), employees INT, ethical_ai BOOLEAN); INSERT INTO ai_companies (id, name, location, sector, employees, ethical_ai) VALUES (3, 'DEF Tech', 'Canada', 'Natural Language Processing', 40, true);

SELECT sector, COUNT(*) as posts, SUM(likes) as total_likes, SUM(shares) as total_shares FROM social_media_posts JOIN ai_companies ON social_media_posts.user_id = ai_companies.id GROUP BY sector;


Question: What is the maximum duration of a single weightlifting workout?

CREATE TABLE Workouts (WorkoutID INT, MemberID INT, Duration INT, WorkoutType VARCHAR(20)); INSERT INTO Workouts (WorkoutID, MemberID, Duration, WorkoutType) VALUES (1, 1, 60, 'Yoga'), (2, 2, 90, 'Weightlifting'), (3, 3, 60, 'Yoga'), (4, 1, 45, 'Running'), (5, 2, 120, 'Weightlifting');

SELECT MAX(Duration) FROM Workouts WHERE WorkoutType = 'Weightlifting';


Question: What is the distribution of severity scores for vulnerabilities in the VulnAssess table?

CREATE TABLE VulnAssess (systemName VARCHAR(50), severityScore INT); INSERT INTO VulnAssess (systemName, severityScore) VALUES ('SystemA', 7), ('SystemB', 5), ('SystemC', 3), ('SystemD', 6), ('SystemE', 8);

SELECT severityScore, COUNT(*) FROM VulnAssess GROUP BY severityScore;


Question: Find the number of students who dropped out in the last 3 months from the "SchoolA" database

CREATE TABLE SchoolA (student_id INT, dropout_date DATE); INSERT INTO SchoolA (student_id, dropout_date) VALUES (1, '2022-01-01'), (2, '2022-02-15'), (3, '2021-12-20');

SELECT COUNT(*) FROM SchoolA WHERE dropout_date >= DATE_SUB(CURDATE(), INTERVAL 3 MONTH);


Question: Write the DDL statement from PostgreSQL regression test 'multirangetypes' (example 560).

create temp table test2(f1 multitextrange1[]);  -- fail

drop table test1;

Explanation: DDL from PostgreSQL core regression test for Multirangetypes.


Question: Generate PostgreSQL SQL for: How many languages for the 2001 (74th) awards?

CREATE TABLE table_16254861_1 (language_s_ VARCHAR, year__ceremony_ VARCHAR)

SELECT COUNT(language_s_) FROM table_16254861_1 WHERE year__ceremony_ = '2001 (74th)';


Question: Generate PostgreSQL SQL for: Show order ids and the number of products in each order.

CREATE TABLE Order_items (order_id VARCHAR, product_id VARCHAR)

SELECT order_id, COUNT(DISTINCT product_id) FROM Order_items GROUP BY order_id;


Question: Create a view to display average response time by response type

CREATE TABLE emergency_response (response_type VARCHAR(255), response_time TIME, location VARCHAR(255));

CREATE VIEW avg_response_time AS SELECT response_type, AVG(TIME_TO_SEC(response_time))/60 as avg_response_time FROM emergency_response GROUP BY response_type;


Question: Generate PostgreSQL SQL for: What team had a high rebound of perkins (9) and a game smaller than 78?

CREATE TABLE table_name_39 (team VARCHAR, game VARCHAR, high_rebounds VARCHAR)

SELECT team FROM table_name_39 WHERE game < 78 AND high_rebounds = 'perkins (9)';


Question: Generate PostgreSQL SQL for: What Brands Hatch race had Niki Lauda as its Fastest Lap?

CREATE TABLE table_name_78 (race VARCHAR, fastest_lap VARCHAR, location VARCHAR)

SELECT race FROM table_name_78 WHERE fastest_lap = 'niki lauda' AND location = 'brands hatch';


Question: What is the total CO2 offset for each carbon offset project?

CREATE TABLE CarbonOffsetProjects (id INT, name VARCHAR(50), co2_offset FLOAT); INSERT INTO CarbonOffsetProjects (id, name, co2_offset) VALUES (1, 'ProjectA', 1000), (2, 'ProjectB', 2000), (3, 'ProjectC', 3000);

SELECT name, SUM(co2_offset) FROM CarbonOffsetProjects GROUP BY name;


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

Explanation: DML from PostgreSQL core regression test for Identity.


Question: Generate PostgreSQL SQL for: What is Res., when Round is greater than 2, and when Event is "Midwest Cage Championships 25: Inferno"?

CREATE TABLE table_name_92 (res VARCHAR, round VARCHAR, event VARCHAR)

SELECT res FROM table_name_92 WHERE round > 2 AND event = 'midwest cage championships 25: inferno';


Question: List the names of soccer teams in the Premier League that have more than 50% of their players born outside of the UK.

CREATE TABLE IF NOT EXISTS players (id INT, name VARCHAR(50), position VARCHAR(50), team VARCHAR(50), country VARCHAR(50)); CREATE VIEW IF NOT EXISTS uk_players AS SELECT team, COUNT(*) AS count FROM players WHERE country = 'UK' GROUP BY team;

SELECT team FROM players JOIN uk_players ON players.team = uk_players.team WHERE players.team IN (SELECT team FROM uk_players WHERE count < COUNT(*) * 0.5) AND players.country != 'UK' GROUP BY team HAVING COUNT(*) > (SELECT COUNT(*)/2 FROM players WHERE team = players.team);


Question: What is the maximum depth of all the oceans?'

CREATE TABLE ocean_depths (ocean TEXT, max_depth FLOAT); INSERT INTO ocean_depths (ocean, max_depth) VALUES ('Pacific', 36000.0); INSERT INTO ocean_depths (ocean, max_depth) VALUES ('Atlantic', 32000.0);

SELECT ocean, MAX(max_depth) FROM ocean_depths;


Question: Generate PostgreSQL SQL for: In the 2004 season with a 0-2 score what was the name of the venue?

CREATE TABLE table_name_5 (venue VARCHAR, score VARCHAR, season VARCHAR)

SELECT venue FROM table_name_5 WHERE score = '0-2' AND season = 2004;


Question: What is the number of employees by department and gender?

CREATE TABLE Employees (EmployeeID int, FirstName varchar(50), LastName varchar(50), Department varchar(50), Gender varchar(50), Salary decimal(10,2)); INSERT INTO Employees (EmployeeID, FirstName, LastName, Department, Gender, Salary) VALUES (1, 'John', 'Doe', 'IT', 'Male', 75000); INSERT INTO Employees (EmployeeID, FirstName, LastName, Department, Gender, Salary) VALUES (2, 'Jane', 'Doe', 'HR', 'Female', 80000);

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


Question: What is the average temperature anomaly for the year 2020?

CREATE TABLE climate_data (id INT, year INT, temperature_anomaly DECIMAL); INSERT INTO climate_data (id, year, temperature_anomaly) VALUES (1, 2020, 1.2); INSERT INTO climate_data (id, year, temperature_anomaly) VALUES (2, 2019, 0.8);

SELECT AVG(temperature_anomaly) FROM climate_data WHERE year = 2020;


Question: What is the average claim amount for policyholders with 'life insurance' policies in the 'west' region?

CREATE TABLE policyholders (id INT, policy_type VARCHAR(20), region VARCHAR(10), claim_amount INT); INSERT INTO policyholders (id, policy_type, region, claim_amount) VALUES (1, 'life insurance', 'west', 5000), (2, 'health insurance', 'east', 3000), (3, 'life insurance', 'west', 1000);

SELECT AVG(claim_amount) FROM policyholders WHERE policy_type = 'life insurance' AND region = 'west';


Question: Generate PostgreSQL SQL for: Who was the visitor at 5:00 pm?

CREATE TABLE table_name_42 (visitor VARCHAR, time VARCHAR)

SELECT visitor FROM table_name_42 WHERE time = '5:00 pm';


Question: Generate PostgreSQL SQL for: What is the highest number of votes for the French Professor?

CREATE TABLE table_name_20 (votes INTEGER, occupation VARCHAR)

SELECT MAX(votes) FROM table_name_20 WHERE occupation = 'french professor';


Question: What is the total funding received by each space agency for space exploration programs?

CREATE TABLE space_agencies (id INT, name VARCHAR(255), total_funding FLOAT, PRIMARY KEY(id)); INSERT INTO space_agencies (id, name, total_funding) VALUES (1, 'Agency1', 1000000), (2, 'Agency2', 2000000), (3, 'Agency3', 1500000);

SELECT space_agencies.name, SUM(space_agencies.total_funding) FROM space_agencies GROUP BY space_agencies.name;


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

CREATE TABLE part_grants (
    parent_table text PRIMARY KEY REFERENCES @extschema@.part_config (parent_table) ON DELETE CASCADE ON UPDATE CASCADE,
    grants text,
    roles text
);

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


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

ALTER EXTENSION pgtap ADD FUNCTION has_rightop ( NAME, NAME, NAME, TEXT );


Question: What is the count of 'Sustainable Fashion' related events held in 'Africa' in the year 2022?

CREATE TABLE africa_events (id INT, event_type VARCHAR(30), event_year INT);INSERT INTO africa_events (id, event_type, event_year) VALUES (1, 'Sustainable Fashion', 2022), (2, 'Fashion Trend', 2021), (3, 'Sustainable Fashion', 2023), (4, 'Fashion Trend', 2020);

SELECT COUNT(*) FROM africa_events WHERE event_type = 'Sustainable Fashion' AND event_year = 2022;


Question: Generate PostgreSQL SQL for: How many losses did the Michigan State Spartans have?

CREATE TABLE table_1672976_2 (loss INTEGER, institution VARCHAR)

SELECT MAX(loss) FROM table_1672976_2 WHERE institution = 'Michigan State Spartans';


Question: What are the names of the algorithms that address algorithmic fairness and are part of the 'fairness_algorithms' table?

CREATE TABLE fairness_algorithms (algorithm_id INT, algorithm_name VARCHAR(50), algorithm_type VARCHAR(20), description TEXT); INSERT INTO fairness_algorithms (algorithm_id, algorithm_name, algorithm_type, description) VALUES (1, 'Demographic Parity', 'pre-processing', 'A method that adjusts the training data to meet demographic parity.'), (2, 'Equal Opportunity', 'post-processing', 'A method that adjusts predictions to meet equal opportunity.'), (3, 'Reweighing', 'pre-processing', 'A method that reweights the training instances to meet fairness criteria.');

SELECT algorithm_name FROM fairness_algorithms;


Question: Generate PostgreSQL SQL for: What is the total for the team with 0 bronze and 3 silver?

CREATE TABLE table_name_41 (total INTEGER, bronze VARCHAR, silver VARCHAR)

SELECT SUM(total) FROM table_name_41 WHERE bronze = 0 AND silver = 3;


Question: PostgreSQL regression test 'sequence': Write the SELECT query (example 66).

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

SELECT count(*) FROM (SELECT * FROM foo_seq_new) AS _sub;


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

SELECT JSON_SERIALIZE('{ "a" : 1 } ' RETURNING bytea);

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

SELECT count(*) FROM (SELECT JSON_SERIALIZE('{ "a" : 1 } ' RETURNING bytea)) AS _sub;


Question: Delete companies founded before a specific year

CREATE TABLE companies (id INT, name TEXT, founded DATE); INSERT INTO companies (id, name, founded) VALUES (1, 'Foobar Inc', '2017-01-01'), (2, 'Gizmos Inc', '2019-06-15'), (3, 'Widgets Inc', '2015-09-27'), (4, 'Doodads Inc', '2018-03-12'), (5, 'Thingamajigs Inc', '2021-01-01');

DELETE FROM companies WHERE founded < '2018-01-01';


Question: What is the maximum maritime law penalty in the Caribbean in USD?

CREATE TABLE maritime_laws (law_id INT, law_name VARCHAR(50), region VARCHAR(50), penalty_amount INT);

SELECT MAX(penalty_amount) FROM maritime_laws WHERE region = 'Caribbean';


Question: Generate PostgreSQL SQL for: What is Date of Appointment, when Outgoing Manager is "Giray Bulak"?

CREATE TABLE table_name_69 (date_of_appointment VARCHAR, outgoing_manager VARCHAR)

SELECT date_of_appointment FROM table_name_69 WHERE outgoing_manager = 'giray bulak';


Question: What is the average number of publications by graduate students in the English program?

CREATE TABLE GraduateStudents(Id INT, Name VARCHAR(100), Program VARCHAR(50), Publications INT); INSERT INTO GraduateStudents(Id, Name, Program, Publications) VALUES (1, 'Sam', 'English', 3), (2, 'Tina', 'English', 4);

SELECT AVG(Publications) FROM GraduateStudents WHERE Program = 'English';


Question: What is the total weight of cannabis flower sold by dispensaries in Washington in Q2 2022?

CREATE TABLE Dispensaries (id INT, name TEXT, state TEXT);CREATE TABLE Sales (id INT, dispensary_id INT, weight DECIMAL, sale_date DATE, product_type TEXT); INSERT INTO Dispensaries (id, name, state) VALUES (1, 'Dispensary A', 'Washington'); INSERT INTO Sales (id, dispensary_id, weight, sale_date, product_type) VALUES (1, 1, 100, '2022-04-01', 'flower');

SELECT SUM(s.weight) FROM Dispensaries d INNER JOIN Sales s ON d.id = s.dispensary_id WHERE d.state = 'Washington' AND s.product_type = 'flower' AND s.sale_date BETWEEN '2022-04-01' AND '2022-06-30';


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

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


Question: Rank teams by their average ticket sales, in descending order.

CREATE TABLE team_performance (team_id INT, sales INT);

SELECT team_id, RANK() OVER (ORDER BY AVG(sales) DESC) as rank FROM team_performance GROUP BY team_id;


Question: Generate PostgreSQL SQL for: What's the season number of the episode with series number 84?

CREATE TABLE table_2226817_6 (no_in_season INTEGER, no_in_series VARCHAR)

SELECT MIN(no_in_season) FROM table_2226817_6 WHERE no_in_series = 84;


Question: Generate PostgreSQL SQL for: How many original air dates were there for episode 17?

CREATE TABLE table_15430813_1 (original_air_date VARCHAR, no_in_season VARCHAR)

SELECT COUNT(original_air_date) FROM table_15430813_1 WHERE no_in_season = 17;


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

SELECT 'a'::citext ~<=~ 'B'::citext AS t;

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


Question: List all farmers who cultivate 'Rice' and their corresponding regions.

CREATE TABLE farmer (id INT PRIMARY KEY, name VARCHAR(50), crop_id INT, region_id INT); CREATE TABLE crop (id INT PRIMARY KEY, name VARCHAR(50)); CREATE TABLE region (id INT PRIMARY KEY, name VARCHAR(50)); INSERT INTO crop (id, name) VALUES (1, 'Rice'); INSERT INTO region (id, name) VALUES (1, 'Delta Region'); INSERT INTO farmer (id, name, crop_id, region_id) VALUES (1, 'John Doe', 1, 1);

SELECT f.name, r.name AS region_name FROM farmer f INNER JOIN crop c ON f.crop_id = c.id INNER JOIN region r ON f.region_id = r.id WHERE c.name = 'Rice';


Question: Delete the 'Antarctica' habitat record from the 'habitats' table

CREATE TABLE habitats (id INT, name VARCHAR(50), location VARCHAR(50), size FLOAT);

DELETE FROM habitats WHERE location = 'Antarctica';


Question: Generate PostgreSQL SQL for: which episode was Transmitted on wednesday if the episode of "438 magic: the gathering mini masters tournament" was transmitted on thursday?

CREATE TABLE table_18173916_8 (wednesday VARCHAR, thursday VARCHAR)

SELECT wednesday FROM table_18173916_8 WHERE thursday = '438 Magic: The Gathering Mini Masters Tournament';


Question: What is the difference in the number of male and female players who prefer using VR technology for gaming?

CREATE TABLE PlayerGenders (PlayerID INT, Gender VARCHAR(50)); INSERT INTO PlayerGenders (PlayerID, Gender) VALUES (1, 'Male'), (2, 'Female'), (3, 'Male'), (4, 'Male'), (5, 'Female'); CREATE TABLE PlayerPreferences (PlayerID INT, Preference VARCHAR(50)); INSERT INTO PlayerPreferences (PlayerID, Preference) VALUES (1, 'VR'), (2, 'Non-VR'), (3, 'VR'), (4, 'VR'), (5, 'Non-VR');

(SELECT COUNT(*) FROM PlayerPreferences JOIN PlayerGenders ON PlayerPreferences.PlayerID = PlayerGenders.PlayerID WHERE PlayerPreferences.Preference = 'VR' AND PlayerGenders.Gender = 'Male' EXCEPT SELECT COUNT(*) FROM PlayerPreferences JOIN PlayerGenders ON PlayerPreferences.PlayerID = PlayerGenders.PlayerID WHERE PlayerPreferences.Preference = 'VR' AND PlayerGenders.Gender = 'Female');


Question: What is the average age of teachers who have completed at least one professional development course in the past year?

CREATE TABLE teachers (teacher_id INT, age INT, num_courses_completed INT); INSERT INTO teachers (teacher_id, age, num_courses_completed) VALUES (1, 35, 2), (2, 45, 0), (3, 30, 1), (4, 50, 3);

SELECT AVG(age) FROM teachers WHERE num_courses_completed >= (SELECT COUNT(course_id) FROM courses WHERE completion_date > DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR));


Question: What is the name of the communication campaign that started last in the 'climate_communication' table?

CREATE TABLE climate_communication (campaign_name TEXT, start_date DATE); INSERT INTO climate_communication (campaign_name, start_date) VALUES ('Climate Action', '2021-01-01'), ('Green Tomorrow', '2022-01-01'), ('Green Horizons', '2023-01-01');

SELECT campaign_name FROM climate_communication ORDER BY start_date DESC LIMIT 1;


Question: What is the distribution of sentiment scores for creative AI applications in different countries?

CREATE TABLE creative_ai (id INT, country VARCHAR, timestamp TIMESTAMP, sentiment FLOAT);

SELECT country, PERCENT_RANK() OVER (PARTITION BY country ORDER BY timestamp, sentiment) FROM creative_ai;


Question: What is the minimum donation amount and the number of donors who made donations equal to the minimum amount?

CREATE TABLE Donors (DonorID INT, DonorName TEXT, DonationAmount DECIMAL(10,2)); INSERT INTO Donors (DonorID, DonorName, DonationAmount) VALUES (1, 'John Doe', 50.00); INSERT INTO Donors (DonorID, DonorName, DonationAmount) VALUES (2, 'Jane Smith', 100.00); INSERT INTO Donors (DonorID, DonorName, DonationAmount) VALUES (3, 'Bob Johnson', 50.00);

SELECT MIN(DonationAmount), COUNT(*) FROM Donors GROUP BY DonationAmount HAVING DonationAmount = (SELECT MIN(DonationAmount) FROM Donors);


Question: What is the average delivery time for each transportation mode, computed across all shipments?

CREATE TABLE shipments (id INT, transportation_mode VARCHAR(50), delivery_time INT); INSERT INTO shipments (id, transportation_mode, delivery_time) VALUES (1, 'Air', 5), (2, 'Sea', 7), (3, 'Rail', 6), (4, 'Air', 4);

SELECT transportation_mode, AVG(delivery_time) as avg_delivery_time FROM shipments GROUP BY transportation_mode;


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

SELECT width_bucket(5.0::float8, 3.0::float8, 4.0::float8, -5);

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

SELECT count(*) FROM (SELECT width_bucket(5.0::float8, 3.0::float8, 4.0::float8, -5)) AS _sub;


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

CREATE INDEX grect2ind ON fast_emp4000 USING gist (home_base);

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


Question: Generate PostgreSQL SQL for: Name the incumbent for first elected 1956

CREATE TABLE table_1341930_40 (incumbent VARCHAR, first_elected VARCHAR)

SELECT incumbent FROM table_1341930_40 WHERE first_elected = 1956;


Question: What is the minimum cargo weight and the number of voyages for vessels with 'OOCL' prefix in the Atlantic Ocean in 2018?

CREATE TABLE Vessels (ID INT, Name TEXT, Cargo_Weight INT, Voyages INT, Prefix TEXT, Year INT);CREATE VIEW Atlantic_Ocean_Vessels AS SELECT * FROM Vessels WHERE Region = 'Atlantic Ocean';

SELECT MIN(Cargo_Weight), SUM(Voyages) FROM Atlantic_Ocean_Vessels WHERE Prefix = 'OOCL' AND Year = 2018;


Question: PL/pgSQL test: Plperl Trigger (example 41).

INSERT INTO trigger_test (i, v) values (10000, 'top');

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


Question: Generate PostgreSQL SQL for: What is the aggregate number of yes votes where no votes is littler than 299939.1619948521 and % yes is 66.49%

CREATE TABLE table_256286_41 (yes_votes VARCHAR, no_votes VARCHAR, _percentage_yes VARCHAR)

SELECT COUNT(yes_votes) FROM table_256286_41 WHERE no_votes < 299939.1619948521 AND _percentage_yes = '66.49%';


Question: Generate PostgreSQL SQL for: What is the English title for season 6?

CREATE TABLE table_name_91 (title__english_ VARCHAR, number_of_season VARCHAR)

SELECT title__english_ FROM table_name_91 WHERE number_of_season = 6;


Question: PostgreSQL regression test 'explain': Write the SELECT query (example 50).

select explain_filter('explain (verbose) select * from int8_tbl i8');

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

SELECT count(*) FROM (select explain_filter('explain (verbose) select * from int8_tbl i8')) AS _sub;


Question: Generate PostgreSQL SQL for: What is the Korean dialect in the daegu capital?

CREATE TABLE table_name_71 (korean_dialect VARCHAR, capital VARCHAR)

SELECT korean_dialect FROM table_name_71 WHERE capital = 'daegu';


Question: Which climate adaptation projects were completed in Southeast Asia in 2017 and what was their combined cost?

CREATE TABLE climate_adaptation (year INT, region VARCHAR(50), project VARCHAR(50), cost FLOAT); INSERT INTO climate_adaptation (year, region, project, cost) VALUES (2017, 'Southeast Asia', 'Adaptation Project 1', 150000);

SELECT region, SUM(cost) FROM climate_adaptation WHERE year = 2017 AND region = 'Southeast Asia' GROUP BY region;


Question: How many times has the term 'disinformation' appeared in articles published by media outlet C in the last 5 years?

CREATE TABLE articles (id INT, title VARCHAR(255), publication_date DATE, outlet_name VARCHAR(50)); INSERT INTO articles (id, title, publication_date, outlet_name) VALUES (1, 'Article1', '2021-01-01', 'OutletC'), (2, 'Article2', '2020-12-31', 'OutletC');

SELECT COUNT(*) as disinformation_mentions FROM articles WHERE outlet_name = 'OutletC' AND publication_date >= DATE_SUB(CURDATE(), INTERVAL 5 YEAR) AND title LIKE '%disinformation%';


Question: Generate PostgreSQL SQL for: " what's the engine with turbo being yes (mitsubishi td04-15g ) "

CREATE TABLE table_11167610_1 (engine VARCHAR, turbo VARCHAR)

SELECT engine FROM table_11167610_1 WHERE turbo = 'Yes (Mitsubishi TD04-15g )';


Question: pgTAP test for Index (assertion 66).

SELECT * FROM check_test(
    index_is_unique( 'idx_bar' ),
    false,
    'index_is_unique() fail index only',
    'Index idx_bar should be unique',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Index.


Question: Generate PostgreSQL SQL for: What home team has a score of 5 - 5?

CREATE TABLE table_name_30 (home_team VARCHAR, score VARCHAR)

SELECT home_team FROM table_name_30 WHERE score = '5 - 5';


Question: What is the total revenue for stores in each country, with a 10% discount applied?

CREATE TABLE regions (id INT, country VARCHAR(255), sales_volume FLOAT); INSERT INTO regions (id, country, sales_volume) VALUES (3, 'Germany', 7000.00); INSERT INTO regions (id, country, sales_volume) VALUES (4, 'Spain', 4000.00);

SELECT r.country, SUM(s.revenue * 0.9) as total_revenue FROM sales s JOIN regions r ON s.store LIKE CONCAT('%', r.country, '%') GROUP BY r.country;


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

CREATE TABLE testpub_parted2 (LIKE testpub_parted);

Explanation: DDL from PostgreSQL core regression test for Publication.


Question: Generate PostgreSQL SQL for: When was terry cook picked?

CREATE TABLE table_name_92 (pick INTEGER, player VARCHAR)

SELECT AVG(pick) FROM table_name_92 WHERE player = 'terry cook';


Question: Generate PostgreSQL SQL for: What years are listed for the Tahunanui school with an authority of state?

CREATE TABLE table_name_31 (years VARCHAR, authority VARCHAR, name VARCHAR)

SELECT years FROM table_name_31 WHERE authority = 'state' AND name = 'tahunanui school';


Question: Generate PostgreSQL SQL for: Which Year is the highest one that has a Next Highest Spender of aarp, and a US Cham Spending of $39,805,000, and a US Cham Rank larger than 1?

CREATE TABLE table_name_16 (year INTEGER, us_cham_rank VARCHAR, next_highest_spender VARCHAR, us_cham_spending VARCHAR)

SELECT MAX(year) FROM table_name_16 WHERE next_highest_spender = 'aarp' AND us_cham_spending = '$39,805,000' AND us_cham_rank > 1;


Question: Identify the most popular pick-up and drop-off locations for bus trips

CREATE TABLE bus_trip (trip_id INT, pickup_location VARCHAR(50), dropoff_location VARCHAR(50), trip_date DATE);

SELECT pickup_location AS most_popular_pickup, dropoff_location AS most_popular_dropoff, COUNT(*) AS trip_count FROM bus_trip GROUP BY pickup_location, dropoff_location ORDER BY trip_count DESC LIMIT 1;


Question: Which esports events had more than 10000 attendees?

CREATE TABLE esports_events (id INT, name VARCHAR(50), attendees INT); INSERT INTO esports_events (id, name, attendees) VALUES (1, 'ESL One', 15000), (2, 'DreamHack', 12000), (3, 'PGL Major', 25000);

SELECT name FROM esports_events WHERE attendees > 10000;


Question: What is the total number of Green_Infrastructure projects in 'City O' and 'City P'?

CREATE TABLE Green_Infrastructure (id INT, project_name VARCHAR(50), location VARCHAR(50), cost FLOAT); INSERT INTO Green_Infrastructure (id, project_name, location, cost) VALUES (1, 'Urban Farming', 'City O', 2000000); INSERT INTO Green_Infrastructure (id, project_name, location, cost) VALUES (2, 'Community Gardens', 'City P', 3000000);

SELECT COUNT(*) FROM Green_Infrastructure WHERE location IN ('City O', 'City P');


Question: PL/pgSQL test: Plpython Spi (example 27).

CREATE FUNCTION result_empty_test() RETURNS void
AS $$
result = plpy.execute("select 1 where false")

plpy.info(result[:])

$$ LANGUAGE plpython3u;

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


Question: What is the average session length for each game genre, sorted by average session length?

CREATE TABLE game_sessions(id INT, user_id INT, game_name VARCHAR(50), start_time DATETIME, end_time DATETIME); CREATE TABLE games(id INT, name VARCHAR(50), genre VARCHAR(50));

SELECT genres.genre, AVG(TIMESTAMPDIFF(SECOND, start_time, end_time)) as avg_session_length FROM game_sessions JOIN games ON game_sessions.game_name = games.name JOIN (SELECT DISTINCT game_name, genre FROM game_sessions JOIN games ON game_sessions.game_name = games.name) genres ON games.name = genres.game_name GROUP BY genres.genre ORDER BY avg_session_length DESC;


Question: What is the average order value per customer for the last week, with orders ranked by total price in descending order?

CREATE TABLE orders (order_id INT, customer_id INT, order_date DATE, total_price DECIMAL(10,2));

SELECT customer_id, AVG(total_price) as avg_order_value FROM orders WHERE order_date >= DATEADD(day, -7, GETDATE()) GROUP BY customer_id ORDER BY AVG(total_price) DESC;


Question: What is the maximum number of hours volunteered in a single week by a volunteer, and who was the volunteer?

CREATE TABLE volunteer_hours (id INT, volunteer_id INT, hours DECIMAL, week INT); INSERT INTO volunteer_hours (id, volunteer_id, hours, week) VALUES (1, 1, 5.0, 1), (2, 2, 10.0, 1), (3, 3, 7.5, 1), (4, 1, 4.0, 2), (5, 3, 8.0, 2); CREATE TABLE volunteers (id INT, name TEXT); INSERT INTO volunteers (id, name) VALUES (1, 'Samir'), (2, 'Sophia'), (3, 'Taro');

SELECT MAX(hours) AS max_hours, volunteer_id FROM volunteer_hours GROUP BY volunteer_id; SELECT name, volunteer_id FROM volunteers WHERE volunteer_id IN (SELECT volunteer_id FROM (SELECT MAX(hours) AS max_hours, volunteer_id FROM volunteer_hours GROUP BY volunteer_id) AS subquery WHERE max_hours = (SELECT MAX(hours) FROM volunteer_hours));


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

SELECT count(*) FROM (SELECT to_char('100e9'::numeric, 'RN')) AS _sub;


Question: Find the names and positions of employees who earn more than the average salary?

CREATE TABLE employee_salaries (id INT, name VARCHAR(50), position VARCHAR(50), salary INT); CREATE VIEW avg_salary AS SELECT AVG(salary) AS avg_salary FROM employee_salaries;

SELECT name, position FROM employee_salaries WHERE salary > (SELECT avg_salary FROM avg_salary);


Question: Find the number of applicants by job title and the percentage of applicants who were hired

CREATE TABLE job_applications(app_id INT, job_id INT, hired BOOLEAN); INSERT INTO job_applications VALUES (1, 1, TRUE), (2, 1, FALSE), (3, 2, TRUE), (4, 2, TRUE), (5, 3, FALSE);

SELECT j.job_title, COUNT(a.app_id) as num_applicants, (COUNT(CASE WHEN a.hired THEN 1 END) / COUNT(a.app_id)) * 100 as pct_hired  FROM job_applications a JOIN job_openings j ON a.job_id = j.job_id GROUP BY j.job_title;


Question: Generate PostgreSQL SQL for: Who had the most rebounds when the team record was 15-27?

CREATE TABLE table_23285805_6 (high_rebounds VARCHAR, record VARCHAR)

SELECT high_rebounds FROM table_23285805_6 WHERE record = '15-27';


Question: Generate PostgreSQL SQL for: What was the date of the tournament held in Indonesia?

CREATE TABLE table_name_23 (date VARCHAR, country VARCHAR)

SELECT date FROM table_name_23 WHERE country = 'indonesia';


Question: Generate PostgreSQL SQL for: Total larger than 3, and a Rank of 4, and a Silver larger than 0 has what average gold?

CREATE TABLE table_name_2 (gold INTEGER, silver VARCHAR, total VARCHAR, rank VARCHAR)

SELECT AVG(gold) FROM table_name_2 WHERE total > 3 AND rank = '4' AND silver > 0;


Question: Generate PostgreSQL SQL for: What is the position of club Melilla CF, with a goal difference smaller than -10?

CREATE TABLE table_name_63 (position INTEGER, club VARCHAR, goal_difference VARCHAR)

SELECT SUM(position) FROM table_name_63 WHERE club = 'melilla cf' AND goal_difference < -10;


Question: What is the total transaction amount for the 'Online' customer segment in the last quarter?

CREATE TABLE customers (id INT, segment VARCHAR(20)); CREATE TABLE transactions (id INT, customer_id INT, amount DECIMAL(10,2), transaction_date DATE); INSERT INTO customers (id, segment) VALUES (1, 'Online'); INSERT INTO transactions (id, customer_id, amount, transaction_date) VALUES (1, 1, 500, '2022-04-01');

SELECT SUM(amount) FROM transactions JOIN customers ON transactions.customer_id = customers.id WHERE customers.segment = 'Online' AND transaction_date >= DATE_SUB(CURDATE(), INTERVAL 3 MONTH);


Question: Generate PostgreSQL SQL for: What is the withdrawal rate for the school district with a graduation rate of 89.3%?

CREATE TABLE table_21514460_1 (withdrawal_rate__2010_11_ VARCHAR, graduation_rate__2011_12_ VARCHAR)

SELECT withdrawal_rate__2010_11_ FROM table_21514460_1 WHERE graduation_rate__2011_12_ = '89.3%';


Question: What is the running total of 'tech_for_social_good_hours' for each volunteer, for the 'tech4good' database, ordered by volunteer_id and date?

CREATE TABLE tech4good (id INT, volunteer_id INT, tech_for_social_good_date DATE, tech_for_social_good_hours INT); INSERT INTO tech4good (id, volunteer_id, tech_for_social_good_date, tech_for_social_good_hours) VALUES (1, 1001, '2022-01-01', 6); INSERT INTO tech4good (id, volunteer_id, tech_for_social_good_date, tech_for_social_good_hours) VALUES (2, 1001, '2022-01-03', 9); INSERT INTO tech4good (id, volunteer_id, tech_for_social_good_date, tech_for_social_good_hours) VALUES (3, 1002, '2022-01-02', 4);

SELECT volunteer_id, tech_for_social_good_date, tech_for_social_good_hours, SUM(tech_for_social_good_hours) OVER (PARTITION BY volunteer_id ORDER BY tech_for_social_good_date) as running_total FROM tech4good;


Question: Find the total number of intelligence operations involving submarines.

CREATE SCHEMA if not exists intel_ops (Operation VARCHAR(255), Equipment VARCHAR(255)); INSERT INTO intel_ops VALUES ('Op1', 'Submarine'), ('Op2', 'Satellite');

SELECT COUNT(*) FROM intel_ops WHERE Equipment = 'Submarine';


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

CREATE FUNCTION isnle(isbn, ean13)
	RETURNS boolean
	AS 'int8le'
	LANGUAGE 'internal'
	IMMUTABLE STRICT
	PARALLEL SAFE;

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


Question: What is the earliest discovery date for an exoplanet?

CREATE TABLE exoplanets (id INT, name VARCHAR(255), discovery_date DATE, discovery_method VARCHAR(255));

SELECT MIN(exoplanets.discovery_date) FROM exoplanets;


Question: What is the percentage of climate finance allocated to the Indigenous communities?

CREATE TABLE finance_distribution (group VARCHAR(255), funding FLOAT);

SELECT (SUM(CASE WHEN group = 'Indigenous communities' THEN funding ELSE 0 END) / SUM(funding)) * 100 FROM finance_distribution;


Question: How many instances of disinformation were detected in a specific time period?

CREATE TABLE disinformation (id INT, detected_at TIMESTAMP, source VARCHAR, confirmed BOOLEAN); INSERT INTO disinformation (id, detected_at, source, confirmed) VALUES (1, '2021-01-01 12:00:00', 'WebsiteA', true); INSERT INTO disinformation (id, detected_at, source, confirmed) VALUES (2, '2021-01-02 13:00:00', 'WebsiteB', false);

SELECT COUNT(*) FROM disinformation WHERE detected_at BETWEEN '2021-01-01' AND '2021-01-07' AND confirmed = true;


Question: Generate PostgreSQL SQL for: what is the number of losses with wins less than 4 and goals against more than 39?

CREATE TABLE table_name_28 (losses VARCHAR, goals_against VARCHAR, wins VARCHAR)

SELECT COUNT(losses) FROM table_name_28 WHERE goals_against > 39 AND wins < 4;


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

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

SELECT count(*) FROM (select jsonb_path_query('"12:34:56.789 +05:30"', '$.time_tz(2)')) AS _sub;


Question: Update the weight of the 'Elephant' in the 'Forest' habitat to 5500.0.

CREATE TABLE animals (id INT, animal_name VARCHAR(255), habitat_type VARCHAR(255), weight DECIMAL(5,2)); INSERT INTO animals (id, animal_name, habitat_type, weight) VALUES (1, 'Lion', 'Savannah', 190.0), (2, 'Elephant', 'Forest', 6000.0), (3, 'Hippo', 'Wetlands', 3300.0), (4, 'Giraffe', 'Savannah', 1600.0), (5, 'Duck', 'Wetlands', 15.0), (6, 'Bear', 'Mountains', 300.0);

UPDATE animals SET weight = 5500.0 WHERE animal_name = 'Elephant' AND habitat_type = 'Forest';


Question: Generate PostgreSQL SQL for: What was the score in the game played on December 2, 1984?

CREATE TABLE table_14863869_1 (record VARCHAR, date VARCHAR)

SELECT record FROM table_14863869_1 WHERE date = 'December 2, 1984';


Question: What is the total investment for each product?

CREATE TABLE investments (client_id INT, product VARCHAR(50), value DECIMAL(10,2)); INSERT INTO investments (client_id, product, value) VALUES (1, 'Stocks', 25000.00); INSERT INTO investments (client_id, product, value) VALUES (1, 'Bonds', 15000.00); INSERT INTO investments (client_id, product, value) VALUES (2, 'Stocks', 30000.00); INSERT INTO investments (client_id, product, value) VALUES (2, 'Mutual Funds', 10000.00);

SELECT product, SUM(value) as total_investment FROM investments GROUP BY product;


Question: Determine the number of unique habitats where each species is present, and display the results in a table format with species and their respective number of habitats.

CREATE TABLE AnimalHabitats (id INT PRIMARY KEY, species VARCHAR(50), habitat VARCHAR(50));

SELECT AnimalHabitats.species, COUNT(DISTINCT AnimalHabitats.habitat) FROM AnimalHabitats GROUP BY AnimalHabitats.species;


Question: Generate PostgreSQL SQL for: What is the smallest number against when the draws are less than 0?

CREATE TABLE table_name_21 (against INTEGER, draws INTEGER)

SELECT MIN(against) FROM table_name_21 WHERE draws < 0;


Question: Generate PostgreSQL SQL for: What is the bleeding time in Bernard-soulier syndrome?

CREATE TABLE table_1557752_1 (bleeding_time VARCHAR, condition VARCHAR)

SELECT bleeding_time FROM table_1557752_1 WHERE condition = 'Bernard-Soulier syndrome';


Question: What is the average price of vegan dishes in each category?

CREATE TABLE menu_categories (category_id INT, category VARCHAR(255));

SELECT category, AVG(price) as avg_price FROM menus JOIN menu_categories ON menus.category = menu_categories.category WHERE menus.category IN ('vegan appetizers', 'vegan entrees', 'vegan desserts') GROUP BY category;


Question: What is the total funding from private and public sources for each program category?

CREATE TABLE program_funding (program_category VARCHAR(15), funding_source VARCHAR(15), amount INT);

SELECT program_category, SUM(CASE WHEN funding_source = 'private' THEN 1 ELSE 0 END) + SUM(CASE WHEN funding_source = 'public' THEN 1 ELSE 0 END) AS total_funding FROM program_funding GROUP BY program_category;


Question: PL/pgSQL test: Plpython Setof (example 9).

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


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

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

SELECT count(*) FROM (SELECT date '1999-08-01') AS _sub;


Question: Generate PostgreSQL SQL for: What is the NBA draft result of the player from Dunbar High School?

CREATE TABLE table_name_61 (nba_draft VARCHAR, school VARCHAR)

SELECT nba_draft FROM table_name_61 WHERE school = 'dunbar high school';


Question: Generate PostgreSQL SQL for: Which headphone models have a driver-matched DB of 0.1 and a US MSRP of $49?

CREATE TABLE table_1601027_1 (headphone_model VARCHAR, driver_matched_db VARCHAR, us_msrp VARCHAR)

SELECT headphone_model FROM table_1601027_1 WHERE driver_matched_db = '0.1' AND us_msrp = '$49';


Question: Generate PostgreSQL SQL for: What is the lowest Draft, when Nationality is "Canada", when Player is "Shane Doan Category:Articles with hCards", and when Round is less than 1?

CREATE TABLE table_name_7 (draft INTEGER, round VARCHAR, nationality VARCHAR, player VARCHAR)

SELECT MIN(draft) FROM table_name_7 WHERE nationality = 'canada' AND player = 'shane doan category:articles with hcards' AND round < 1;


Question: Generate PostgreSQL SQL for: Which Label has a Format of cd, a Country of Japan and a Catalog of vjcp-68403?

CREATE TABLE table_name_89 (label VARCHAR, catalog VARCHAR, format VARCHAR, country VARCHAR)

SELECT label FROM table_name_89 WHERE format = 'cd' AND country = 'japan' AND catalog = 'vjcp-68403';


Question: What is the distribution of user locations for articles about climate change?

CREATE TABLE articles (title text, category text, user_location text); INSERT INTO articles (title, category, user_location) VALUES ('Article 1', 'climate change', 'USA'); INSERT INTO articles (title, category, user_location) VALUES ('Article 2', 'climate change', 'Canada');

SELECT user_location, COUNT(*) as count FROM articles WHERE category = 'climate change' GROUP BY user_location;


Question: What is the total number of volunteers and total hours donated by them in '2022'?

CREATE TABLE Volunteers (VolunteerID int, VolunteerName varchar(50), HoursDonated int, VolunteerYear int); INSERT INTO Volunteers (VolunteerID, VolunteerName, HoursDonated, VolunteerYear) VALUES (1, 'Grace Blue', 30, 2022), (2, 'Harry Yellow', 20, 2022), (3, 'Ivy Purple', 15, 2022), (4, 'Jack Orange', 25, 2022);

SELECT COUNT(VolunteerName) as TotalVolunteers, SUM(HoursDonated) as TotalHours FROM Volunteers WHERE VolunteerYear = 2022;


Question: Write the DDL statement from PostgreSQL regression test 'tsdicts' (example 75).

CREATE TEXT SEARCH DICTIONARY hunspell_err (
						Template=ispell,
						DictFile=hunspell_sample_num,
						AffFile=hunspell_sample_long
);

Explanation: DDL from PostgreSQL core regression test for Tsdicts.


Question: Generate PostgreSQL SQL for: What is the average number of bronze medals when the team's silver are more than 1 but the total medals are less than 9?

CREATE TABLE table_name_87 (bronze INTEGER, silver VARCHAR, total VARCHAR)

SELECT AVG(bronze) FROM table_name_87 WHERE silver > 1 AND total < 9;


Question: List all communities that have both eco-friendly and inclusive housing policies.

CREATE TABLE communities (community VARCHAR(255), eco_friendly BOOLEAN, inclusive_policy BOOLEAN); INSERT INTO communities (community, eco_friendly, inclusive_policy) VALUES ('CommunityA', true, true), ('CommunityB', false, true), ('CommunityC', true, false);

SELECT community FROM communities WHERE eco_friendly = true AND inclusive_policy = true;


Question: Generate PostgreSQL SQL for: What is the result for Wisconsin?

CREATE TABLE table_22603701_1 (result VARCHAR, college VARCHAR)

SELECT result FROM table_22603701_1 WHERE college = 'Wisconsin';


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

INSERT INTO bv1 VALUES (-1, 'xxx'); -- should fail view WCO
INSERT INTO bv1 VALUES (11, 'xxx'); -- should fail RLS check
INSERT INTO bv1 VALUES (12, 'xxx'); -- ok

EXPLAIN (COSTS OFF) UPDATE bv1 SET b = 'yyy' WHERE a = 4 AND f_leak(b);

Explanation: DML from PostgreSQL core regression test for Rowsecurity.


Question: Generate PostgreSQL SQL for: Find the ids of all the order items whose product id is 11.

CREATE TABLE order_items (order_item_id VARCHAR, product_id VARCHAR)

SELECT order_item_id FROM order_items WHERE product_id = 11;


Question: List the number of male and female patients diagnosed with any infectious disease in Seattle.

CREATE TABLE Genders (GenderID INT, Age INT, Gender VARCHAR(10), City VARCHAR(20), Disease VARCHAR(20)); INSERT INTO Genders (GenderID, Age, Gender, City, Disease) VALUES (1, 50, 'Female', 'Seattle', 'Measles');

SELECT Gender, COUNT(*) as PatientCount FROM Genders WHERE City = 'Seattle' GROUP BY Gender;


Question: Show an example of PostgreSQL WAIT FOR (example 5).

postgres=# WAIT FOR LSN '0/306EE20' WITH (MODE 'primary_flush'); status --------- success (1 row);

Explanation: PostgreSQL WAIT FOR command.


Question: Generate PostgreSQL SQL for: What was the constructor when the laps were larger than 54, and the time/retired was +1 lap on a grid of 20?

CREATE TABLE table_name_28 (constructor VARCHAR, grid VARCHAR, laps VARCHAR, time_retired VARCHAR)

SELECT constructor FROM table_name_28 WHERE laps > 54 AND time_retired = '+1 lap' AND grid = 20;


Question: Show the number of satellites in each type of orbit

CREATE TABLE satellites_by_country (satellite_id INT, country VARCHAR(50), orbit_type VARCHAR(50)); INSERT INTO satellites_by_country (satellite_id, country, orbit_type) VALUES (1, 'USA', 'Geostationary'); INSERT INTO satellites_by_country (satellite_id, country, orbit_type) VALUES (2, 'Russia', 'Low Earth Orbit'); INSERT INTO satellites_by_country (satellite_id, country, orbit_type) VALUES (3, 'China', 'Geostationary');

SELECT orbit_type, COUNT(*) as num_satellites FROM satellites_by_country GROUP BY orbit_type;


Question: Average risk rating for impact investments in the finance sector with an ESG score above 75?

CREATE TABLE impact_investments_finance (id INT, sector VARCHAR(20), ESG_score FLOAT, risk_rating FLOAT); INSERT INTO impact_investments_finance (id, sector, ESG_score, risk_rating) VALUES (1, 'Finance', 80.0, 3.0), (2, 'Finance', 70.0, 4.0), (3, 'Finance', 85.0, 2.5);

SELECT AVG(risk_rating) FROM impact_investments_finance WHERE sector = 'Finance' AND ESG_score > 75;


Question: List all defense projects that have experienced delays of more than 30 days, along with their original and current completion dates, and the names of the contractors responsible for each project.

CREATE TABLE defense_projects (id INT, name VARCHAR(255), contractor_id INT, original_completion_date DATE, current_completion_date DATE); INSERT INTO defense_projects (id, name, contractor_id, original_completion_date, current_completion_date) VALUES (1, 'F-35 Joint Strike Fighter', 1, '2025-01-01', '2025-02-01'), (2, 'Boeing 777X', 2, '2024-01-01', '2024-01-15'), (3, 'Columbia-class Submarine', 3, '2028-01-01', '2028-05-01'); CREATE TABLE contractors (id INT, name VARCHAR(255)); INSERT INTO contractors (id, name) VALUES (1, 'Lockheed Martin'), (2, 'Boeing'), (3, 'General Dynamics');

SELECT d.name, c.name as contractor_name, d.original_completion_date, d.current_completion_date, DATEDIFF(d.current_completion_date, d.original_completion_date) as delay_days FROM defense_projects d JOIN contractors c ON d.contractor_id = c.id WHERE DATEDIFF(d.current_completion_date, d.original_completion_date) > 30;


Question: Generate PostgreSQL SQL for: who is the constructor when the driver is juan pablo montoya?

CREATE TABLE table_name_41 (constructor VARCHAR, driver VARCHAR)

SELECT constructor FROM table_name_41 WHERE driver = 'juan pablo montoya';


Question: What was the first spacecraft launched by each manufacturer?

CREATE TABLE Spacecraft (id INT, name VARCHAR(50), manufacturer VARCHAR(50), launch_date DATE); INSERT INTO Spacecraft (id, name, manufacturer, launch_date) VALUES (1, 'Voyager 1', 'NASA', '1977-09-05'); INSERT INTO Spacecraft (id, name, manufacturer, launch_date) VALUES (2, 'Voyager 2', 'NASA', '1977-08-20'); INSERT INTO Spacecraft (id, name, manufacturer, launch_date) VALUES (3, 'Sputnik 1', 'Roscosmos', '1957-10-04');

SELECT manufacturer, MIN(launch_date) as first_launch_date FROM Spacecraft GROUP BY manufacturer;


Question: Generate PostgreSQL SQL for: what character did Laara sadiq play

CREATE TABLE table_name_50 (character_name VARCHAR, voice_actor__english_1998___pioneer_ VARCHAR)

SELECT character_name FROM table_name_50 WHERE voice_actor__english_1998___pioneer_ = 'laara sadiq';


Question: Generate PostgreSQL SQL for: Name the nominated work for 1996 and festival of black maria film and video festival

CREATE TABLE table_name_7 (nominated_work VARCHAR, year VARCHAR, festival VARCHAR)

SELECT nominated_work FROM table_name_7 WHERE year = 1996 AND festival = 'black maria film and video festival';


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

CREATE TABLE table_name_93 (date VARCHAR, game VARCHAR)

SELECT date FROM table_name_93 WHERE game = 75;


Question: Generate PostgreSQL SQL for: What was the result for years prior to 2005?

CREATE TABLE table_name_83 (result VARCHAR, year INTEGER)

SELECT result FROM table_name_83 WHERE year < 2005;


Question: What is the number of hospital visits for patients with diabetes by age group in Florida in 2019?

CREATE TABLE hospital_visits_2 (id INT, patient_id INT, age_group TEXT, state TEXT, diagnosis TEXT, visit_date DATE); INSERT INTO hospital_visits_2 (id, patient_id, age_group, state, diagnosis, visit_date) VALUES (1, 789, '5-9', 'Florida', 'diabetes', '2019-03-04');

SELECT age_group, SUM(CASE WHEN diagnosis = 'diabetes' THEN 1 ELSE 0 END) as num_visits FROM hospital_visits_2 WHERE state = 'Florida' AND visit_date >= '2019-01-01' AND visit_date < '2020-01-01' GROUP BY age_group;


Question: Write the DDL statement from PostgreSQL regression test 'event_trigger' (example 8).

CREATE AGGREGATE schema_two.newton
  (BASETYPE = int, SFUNC = schema_two.add, STYPE = int);

Explanation: DDL from PostgreSQL core regression test for Event Trigger.


Question: Generate PostgreSQL SQL for: What is the capital of the district who's simplified name is  信州区?

CREATE TABLE table_1300525_1 (pinyin VARCHAR, simplified VARCHAR)

SELECT COUNT(pinyin) FROM table_1300525_1 WHERE simplified = '信州区';


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

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


Question: Generate PostgreSQL SQL for: What is the IATA for Ringway Airport in the United Kingdom?

CREATE TABLE table_name_1 (iata VARCHAR, country VARCHAR, airport VARCHAR)

SELECT iata FROM table_name_1 WHERE country = 'united kingdom' AND airport = 'ringway airport';


Question: Write the DDL statement from PostgreSQL regression test 'copyselect' (example 1).

Explanation: DDL from PostgreSQL core regression test for Copyselect.


Question: Find the total number of transactions per month for the last year.

CREATE TABLE transactions (transaction_id INT, customer_id INT, transaction_date DATE); INSERT INTO transactions (transaction_id, customer_id, transaction_date) VALUES (1, 1, '2021-01-01'); INSERT INTO transactions (transaction_id, customer_id, transaction_date) VALUES (2, 2, '2021-02-01');

SELECT DATEPART(YEAR, transaction_date) as year, DATEPART(MONTH, transaction_date) as month, COUNT(*) as total_transactions FROM transactions WHERE transaction_date BETWEEN DATEADD(year, -1, GETDATE()) AND GETDATE() GROUP BY DATEPART(YEAR, transaction_date), DATEPART(MONTH, transaction_date);


Question: What is the total production by crop type for indigenous food systems?

CREATE TABLE crops (id INT, farmer_id INT, crop_name VARCHAR(255), yield INT, sale_price FLOAT, system_type VARCHAR(255)); INSERT INTO crops (id, farmer_id, crop_name, yield, sale_price, system_type) VALUES (1, 1, 'Corn', 80, 2.50, 'Indigenous'); INSERT INTO crops (id, farmer_id, crop_name, yield, sale_price, system_type) VALUES (2, 1, 'Soybeans', 120, 3.25, 'Indigenous'); INSERT INTO crops (id, farmer_id, crop_name, yield, sale_price, system_type) VALUES (3, 2, 'Corn', 90, 2.75, 'Agroecology'); INSERT INTO crops (id, farmer_id, crop_name, yield, sale_price, system_type) VALUES (4, 2, 'Wheat', 100, 3.00, 'Urban Agriculture');

SELECT crop_name, SUM(yield) as total_production FROM crops WHERE system_type = 'Indigenous' GROUP BY crop_name;


Question: List the number of mental health parity incidents in each province for the last 6 months.

CREATE TABLE MentalHealthParity (IncidentID INT, IncidentDate DATE, Province VARCHAR(255)); INSERT INTO MentalHealthParity (IncidentID, IncidentDate, Province) VALUES (1, '2022-01-01', 'Ontario'); INSERT INTO MentalHealthParity (IncidentID, IncidentDate, Province) VALUES (2, '2022-02-15', 'Quebec'); INSERT INTO MentalHealthParity (IncidentID, IncidentDate, Province) VALUES (3, '2022-03-05', 'British Columbia'); INSERT INTO MentalHealthParity (IncidentID, IncidentDate, Province) VALUES (4, '2022-04-10', 'Alberta');

SELECT Province, COUNT(*) FROM MentalHealthParity WHERE IncidentDate >= DATEADD(month, -6, GETDATE()) GROUP BY Province;


Question: What is the average depth for marine species in the Actinopterygii order, grouped by their family?

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

SELECT family, AVG(max_depth) FROM marine_species WHERE order_name = 'Actinopterygii' GROUP BY family;


Question: Generate PostgreSQL SQL for: What's the number of the episode seen by 2.99 millions of people in the US, where performer 2 was Heather Anne Campbell?

CREATE TABLE table_23294081_11 (_number INTEGER, performer_2 VARCHAR, us_viewers__millions_ VARCHAR)

SELECT MIN(_number) FROM table_23294081_11 WHERE performer_2 = 'Heather Anne Campbell' AND us_viewers__millions_ = '2.99';


Question: Generate PostgreSQL SQL for: Which song was picked that was originally performed by Marisa Monte?

CREATE TABLE table_27616663_1 (song_choice VARCHAR, original_artist VARCHAR)

SELECT song_choice FROM table_27616663_1 WHERE original_artist = 'Marisa Monte';


Question: Show a query using PostgreSQL contrib extension 'seg' (example 119).

SELECT '0 .. 1'::seg << '0'::seg AS bool;

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


Question: Generate PostgreSQL SQL for: What is the Overall of 15 Club team with a Nationality of Canada?

CREATE TABLE table_name_37 (club_team VARCHAR, nationality VARCHAR, overall VARCHAR)

SELECT club_team FROM table_name_37 WHERE nationality = 'canada' AND overall = '15';


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

create table idxpart (a int, b int, c int) partition by range(a);

Explanation: DDL from PostgreSQL core regression test for Indexing.


Question: Insert a new record into the fair_trade table with the following information: 'Cooperative E', 'Africa', 'Yes'

CREATE TABLE fair_trade (id INT PRIMARY KEY, cooperative VARCHAR(255), region VARCHAR(255), certified VARCHAR(5));

INSERT INTO fair_trade (cooperative, region, certified) VALUES ('Cooperative E', 'Africa', 'Yes');


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

$$ language plpgsql;

select exc_using(5);

drop function exc_using(int);

-- test FOR-over-cursor

create or replace function forc01() returns void as $$
declare
  c cursor(r1 integer, r2 integer)
       for select * from generate_series(r1,r2) i;

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


Question: Generate PostgreSQL SQL for: Which position did Redden play?

CREATE TABLE table_14342210_6 (position VARCHAR, player VARCHAR)

SELECT position FROM table_14342210_6 WHERE player = 'Redden';


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

select (select grouping(ss.x))
from int8_tbl i1
cross join lateral (select (select i1.q1) as x) ss
group by ss.x;

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

SELECT count(*) FROM (select (select grouping(ss.x))
from int8_tbl i1
cross join lateral (select (select i1.q1) as x) ss
group by ss.x) AS _sub;


Question: Generate PostgreSQL SQL for: What venue has don bradman (nsw) as the player?

CREATE TABLE table_name_7 (venue VARCHAR, player VARCHAR)

SELECT venue FROM table_name_7 WHERE player = 'don bradman (nsw)';


Question: Generate PostgreSQL SQL for: What day did Geelong play as the away team?

CREATE TABLE table_name_73 (date VARCHAR, away_team VARCHAR)

SELECT date FROM table_name_73 WHERE away_team = 'geelong';


Question: What is the total installed capacity of wind turbines in China?

CREATE TABLE wind_turbines (id INT, name TEXT, country TEXT, installed_capacity INT); INSERT INTO wind_turbines (id, name, country, installed_capacity) VALUES (1, 'Gansu Wind Farm', 'China', 7965), (2, 'Jiuquan Wind Power Base', 'China', 10000);

SELECT SUM(installed_capacity) FROM wind_turbines WHERE country = 'China';


Question: How many ethical AI projects were completed by organizations in Europe?

CREATE TABLE AIProjects (id INT, name VARCHAR(50), organization VARCHAR(50), region VARCHAR(50), completed BOOLEAN); INSERT INTO AIProjects (id, name, organization, region, completed) VALUES (1, 'AI for Accessibility', 'Equal Tech', 'Asia-Pacific', true), (2, 'Ethical AI Education', 'Tech Learning', 'North America', true), (3, 'Digital Divide Research', 'Global Connect', 'Europe', false);

SELECT COUNT(*) FROM AIProjects WHERE region = 'Europe' AND completed = true;


Question: Identify the departments with the highest and lowest number of employees

CREATE TABLE Departments (id INT, department_name VARCHAR(50), employee_id INT); CREATE TABLE Employees (id INT, salary DECIMAL(10, 2));

SELECT department_name, COUNT(*) AS employees_count FROM Departments JOIN Employees ON Departments.employee_id = Employees.id GROUP BY department_name ORDER BY employees_count DESC, department_name LIMIT 1; SELECT department_name, COUNT(*) AS employees_count FROM Departments JOIN Employees ON Departments.employee_id = Employees.id GROUP BY department_name ORDER BY employees_count ASC, department_name LIMIT 1;


Question: Generate PostgreSQL SQL for: What date did the episode air that had n/a for it's bbc three weekly ranking?

CREATE TABLE table_24399615_4 (airdate VARCHAR, bbc_three_weekly_ranking VARCHAR)

SELECT airdate FROM table_24399615_4 WHERE bbc_three_weekly_ranking = 'N/A';


Question: What is the total amount of humanitarian assistance provided by year?

CREATE TABLE humanitarian_assistance (id INT PRIMARY KEY, amount FLOAT, year INT, country VARCHAR(255));

SELECT year, SUM(amount) as total_assistance FROM humanitarian_assistance GROUP BY year;


Question: Who are the legal aid providers in New York that have served the most clients in the last 3 years?

CREATE TABLE legal_aid_providers (id INT, name VARCHAR(50), state VARCHAR(2)); INSERT INTO legal_aid_providers (id, name, state) VALUES (1, 'Legal Aid Society', 'NY'); CREATE TABLE clients (id INT, provider_id INT, year INT);

SELECT legal_aid_providers.name, COUNT(clients.id) AS client_count FROM legal_aid_providers INNER JOIN clients ON legal_aid_providers.id = clients.provider_id WHERE clients.year BETWEEN YEAR(CURRENT_DATE()) - 3 AND YEAR(CURRENT_DATE()) GROUP BY legal_aid_providers.name ORDER BY client_count DESC;


Question: What is the average salinity of the ocean in each hemisphere?

CREATE TABLE ocean_salinity (id INT, year INT, hemisphere VARCHAR(50), avg_salinity FLOAT); INSERT INTO ocean_salinity (id, year, hemisphere, avg_salinity) VALUES (1, 2020, 'Northern Hemisphere', 35); INSERT INTO ocean_salinity (id, year, hemisphere, avg_salinity) VALUES (2, 2020, 'Southern Hemisphere', 34.7);

SELECT hemisphere, AVG(avg_salinity) FROM ocean_salinity GROUP BY hemisphere;


Question: What is the name of the AI algorithm with the lowest fairness score in the 'algorithmic_fairness' table?

CREATE TABLE algorithmic_fairness (algorithm_id INT, name TEXT, fairness_score FLOAT); INSERT INTO algorithmic_fairness (algorithm_id, name, fairness_score) VALUES (1, 'AlgorithmA', 0.75), (2, 'AlgorithmB', 0.68), (3, 'AlgorithmC', 0.81);

SELECT name FROM algorithmic_fairness ORDER BY fairness_score ASC LIMIT 1;


Question: pgTAP test for Functap (assertion 50).

SELECT * FROM check_test(
    can( 'pg_catalog', ARRAY['lower', 'foo', 'bar'], 'whatever' ),
    false,
    'fail can(schema) with desc',
    'whatever',
    '    pg_catalog.foo() missing
    pg_catalog.bar() missing'
);

Explanation: SQL assertion from pgTAP test suite for Functap.


Question: Generate PostgreSQL SQL for: What was the result of the 1990 world cup qualifying competition?

CREATE TABLE table_name_55 (result VARCHAR, competition VARCHAR)

SELECT result FROM table_name_55 WHERE competition = '1990 world cup qualifying';


Question: Generate PostgreSQL SQL for: report the total number of degrees granted between 1998 and 2002.

CREATE TABLE campuses (campus VARCHAR, id VARCHAR); CREATE TABLE degrees (degrees INTEGER, campus VARCHAR, year VARCHAR)

SELECT T1.campus, SUM(T2.degrees) FROM campuses AS T1 JOIN degrees AS T2 ON T1.id = T2.campus WHERE T2.year >= 1998 AND T2.year <= 2002 GROUP BY T1.campus;