Question: What is the average rating of products manufactured using ethical labor practices?

CREATE TABLE Manufacturing (product_id INT, labor_practices TEXT); INSERT INTO Manufacturing (product_id, labor_practices) VALUES (1, 'ethical'), (2, 'unethical'), (3, 'ethical'); CREATE TABLE Ratings (product_id INT, rating FLOAT); INSERT INTO Ratings (product_id, rating) VALUES (1, 4.5), (1, 4.7), (2, 3.2), (3, 4.9), (3, 4.8);

SELECT AVG(Ratings.rating) FROM Ratings JOIN Manufacturing ON Ratings.product_id = Manufacturing.product_id WHERE Manufacturing.labor_practices = 'ethical';


Question: What is the minimum sustainable material quantity for each garment type in the 'sustainable_materials' table?

CREATE TABLE sustainable_materials (id INT, garment VARCHAR(20), material VARCHAR(20), quantity INT); INSERT INTO sustainable_materials (id, garment, material, quantity) VALUES (1, 'tshirt', 'cotton', 3000), (2, 'pants', 'wool', 2000), (3, 'dress', 'silk', 4000), (4, 'jacket', 'polyester', 5000), (5, 'shirt', 'cotton', 2500), (6, 'blouse', 'silk', 3000);

SELECT garment, MIN(quantity) FROM sustainable_materials GROUP BY garment;


Question: Generate PostgreSQL SQL for: Which Club Team has a Position of (d), a Nationality of canada, and a Player of andrew macwilliam?

CREATE TABLE table_name_7 (club_team VARCHAR, player VARCHAR, position VARCHAR, nationality VARCHAR)

SELECT club_team FROM table_name_7 WHERE position = '(d)' AND nationality = 'canada' AND player = 'andrew macwilliam';


Question: For each program, list the number of volunteers, total volunteer hours, and the average volunteer hours per volunteer.

CREATE TABLE Programs (ProgramID int, Name varchar(50), Location varchar(50)); CREATE TABLE Volunteers (VolunteerID int, Name varchar(50), ProgramID int, Hours decimal(10,2)); INSERT INTO Programs (ProgramID, Name, Location) VALUES (1, 'Feeding America', 'USA'), (2, 'Habitat for Humanity', 'Canada'); INSERT INTO Volunteers (VolunteerID, Name, ProgramID, Hours) VALUES (1, 'Bob', 1, 10.00), (2, 'Sally', 1, 15.00), (3, 'John', 2, 20.00);

SELECT P.Name, COUNT(V.VolunteerID) as VolunteerCount, SUM(V.Hours) as TotalHours, AVG(V.Hours) as AvgHoursPerVolunteer FROM Programs P JOIN Volunteers V ON P.ProgramID = V.ProgramID GROUP BY P.ProgramID, P.Name;


Question: Generate PostgreSQL SQL for: Name the horsepower for VIN code of h and engine for 351-2v cleveland v8

CREATE TABLE table_name_94 (horsepower VARCHAR, vin_code VARCHAR, engine VARCHAR)

SELECT horsepower FROM table_name_94 WHERE vin_code = 'h' AND engine = '351-2v cleveland v8';


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

CREATE TABLE ctlb (bb TEXT) INHERITS (ctla);

Explanation: DDL from PostgreSQL core regression test for Create Table Like.


Question: What is the total number of libraries and parks in California, and how many of them are located in Los Angeles County?

CREATE TABLE states (id INT, name VARCHAR(255)); INSERT INTO states (id, name) VALUES (1, 'California'); CREATE TABLE libraries (id INT, state_id INT, name VARCHAR(255)); INSERT INTO libraries (id, state_id) VALUES (1, 1), (2, 1), (3, 1); CREATE TABLE parks (id INT, state_id INT, name VARCHAR(255)); INSERT INTO parks (id, state_id) VALUES (1, 1), (2, 1), (3, 1); CREATE TABLE counties (id INT, state_id INT, name VARCHAR(255)); INSERT INTO counties (id, state_id, name) VALUES (1, 1, 'Los Angeles County');

SELECT COUNT(libraries.id) + COUNT(parks.id) AS total_locations, COUNT(counties.name) AS la_county_locations FROM libraries INNER JOIN states ON libraries.state_id = states.id INNER JOIN parks ON libraries.state_id = parks.state_id INNER JOIN counties ON states.id = counties.state_id WHERE states.name = 'California' AND counties.name = 'Los Angeles County';


Question: Generate PostgreSQL SQL for: What are the distinct cross reference source system codes which are related to the master customer details 'Gottlieb, Becker and Wyman'?

CREATE TABLE customer_master_index (master_customer_id VARCHAR, cmi_details VARCHAR); CREATE TABLE cmi_cross_references (source_system_code VARCHAR, master_customer_id VARCHAR)

SELECT DISTINCT T2.source_system_code FROM customer_master_index AS T1 JOIN cmi_cross_references AS T2 ON T1.master_customer_id = T2.master_customer_id WHERE T1.cmi_details = 'Gottlieb ,  Becker and Wyman';


Question: What is the carbon sequestration capacity (in tons) for each species in the 'carbon_sequestration' table?

CREATE TABLE carbon_sequestration (id INT, species VARCHAR(255), sequestration_rate FLOAT); INSERT INTO carbon_sequestration (id, species, sequestration_rate) VALUES (1, 'Oak', 2.5), (2, 'Maple', 2.3), (3, 'Pine', 2.8);

SELECT species, sequestration_rate * 10 AS carbon_sequestration_capacity FROM carbon_sequestration;


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

SELECT * FROM pg_input_error_info('garbage', 'date');

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

SELECT count(*) FROM (SELECT * FROM pg_input_error_info('garbage', 'date')) AS _sub;


Question: PL/pgSQL test: Plperl Shared (example 3).

create function getme(key text) returns text language plperl as $$

  my $key = shift;
  return $_SHARED{$key};

$$;

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


Question: Generate PostgreSQL SQL for: Which Administrative district has a Pre-1009 province of gwannae -do and a Post-1009 province of seohae -do?

CREATE TABLE table_name_76 (administrative_district VARCHAR, pre_1009_province VARCHAR, post_1009_province VARCHAR)

SELECT administrative_district FROM table_name_76 WHERE pre_1009_province = 'gwannae -do' AND post_1009_province = 'seohae -do';


Question: Find the combined biomass of all farmed species in Chile.

CREATE TABLE FarmI (country VARCHAR(20), species VARCHAR(20), biomass FLOAT); INSERT INTO FarmI (country, species, biomass) VALUES ('Chile', 'Salmon', 300000); INSERT INTO FarmI (country, species, biomass) VALUES ('Chile', 'Cod', 150000); INSERT INTO FarmI (country, species, biomass) VALUES ('Chile', 'Tilapia', 100000);

SELECT SUM(biomass) FROM FarmI WHERE country='Chile';


Question: What is the total biomass of all marine life in the Indian Ocean, restricted to species with a recorded biomass greater than 500?

CREATE TABLE marine_life (species TEXT, ocean TEXT, biomass INT); INSERT INTO marine_life (species, ocean, biomass) VALUES ('Whale Shark', 'Indian Ocean', 2000), ('Manta Ray', 'Indian Ocean', 300), ('Tuna', 'Indian Ocean', 150), ('Dolphin', 'Indian Ocean', 100);

SELECT SUM(biomass) FROM marine_life WHERE ocean = 'Indian Ocean' AND biomass > 500;


Question: What was the average methane emission in 2019?

CREATE TABLE gas_emissions (year INT, methane_emissions FLOAT); INSERT INTO gas_emissions

SELECT AVG(methane_emissions) FROM gas_emissions WHERE year = 2019;


Question: Update the "amount" of the "ForestryProject1" in the "CarbonOffset" table to 6000

CREATE TABLE CarbonOffset (id INT, project_name VARCHAR(20), project_type VARCHAR(20), amount INT); INSERT INTO CarbonOffset (id, project_name, project_type, amount) VALUES (1, 'ForestryProject1', 'forestry', 5000), (2, 'RenewableEnergyProject1', 'renewable', 6000), (3, 'EnergyEfficiencyProject1', 'energy_efficiency', 4000);

UPDATE CarbonOffset SET amount = 6000 WHERE project_name = 'ForestryProject1';


Question: What is the maximum number of military equipment items sold in a single transaction?

CREATE TABLE sales (id INT, quantity INT); INSERT INTO sales (id, quantity) VALUES (1, 100), (2, 50), (3, 150);

SELECT MAX(quantity) as max_quantity FROM sales;


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

SELECT * FROM pg_input_error_info('ng_catalog.||/', 'regoper');

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

SELECT count(*) FROM (SELECT * FROM pg_input_error_info('ng_catalog.||/', 'regoper')) AS _sub;


Question: What is the minimum mass of a spacecraft manufactured by 'Space Explorers Ltd.'?

CREATE TABLE spacecraft (id INT, name VARCHAR(255), manufacturer VARCHAR(255), mass FLOAT); INSERT INTO spacecraft (id, name, manufacturer, mass) VALUES (1, 'Voyager 1', 'Galactic Pioneers Inc.', 770.), (2, 'Voyager 2', 'Galactic Pioneers Inc.', 780.), (3, 'New Horizons', 'Space Explorers Ltd.', 1010.);

SELECT MIN(mass) FROM spacecraft WHERE manufacturer = 'Space Explorers Ltd.';


Question: What is the combined total installed capacity for 'Wind' and 'Solar' technologies in all cities?

CREATE TABLE renewable_energy_projects (city VARCHAR(50), technology VARCHAR(50), capacity FLOAT); INSERT INTO renewable_energy_projects (city, technology, capacity) VALUES ('CityA', 'Solar', 500.0), ('CityA', 'Wind', 600.0), ('CityB', 'Solar', 750.0), ('CityB', 'Wind', 800.0);

SELECT SUM(capacity) FROM renewable_energy_projects WHERE technology IN ('Solar', 'Wind');


Question: What is the total number of public participation events in North American cities?

CREATE TABLE City (id INT, name VARCHAR(255), region VARCHAR(255)); INSERT INTO City (id, name, region) VALUES (1, 'New York', 'North America'); INSERT INTO City (id, name, region) VALUES (2, 'Los Angeles', 'North America'); INSERT INTO City (id, name, region) VALUES (3, 'Toronto', 'North America'); CREATE TABLE PublicParticipation (id INT, city_id INT, event VARCHAR(255)); INSERT INTO PublicParticipation (id, city_id, event) VALUES (1, 1, 'Public Meeting'); INSERT INTO PublicParticipation (id, city_id, event) VALUES (2, 1, 'Community Workshop'); INSERT INTO PublicParticipation (id, city_id, event) VALUES (3, 2, 'Town Hall'); INSERT INTO PublicParticipation (id, city_id, event) VALUES (4, 3, 'Citizen Survey');

SELECT COUNT(*) FROM PublicParticipation JOIN City ON PublicParticipation.city_id = City.id WHERE City.region = 'North America';


Question: pgTAP test for Resultset (assertion 70).

INSERT INTO names (name) VALUES ('Kevin');

Explanation: SQL assertion from pgTAP test suite for Resultset.


Question: What is the average number of employees for gold mines located in Canada?

CREATE TABLE gold_mines (id INT, name VARCHAR(50), location VARCHAR(50), size INT, num_employees INT, co2_emissions INT); INSERT INTO gold_mines VALUES (1, 'Gold Mine 1', 'Canada', 450, 320, 22000); INSERT INTO gold_mines VALUES (2, 'Gold Mine 2', 'Canada', 600, 450, 28000); INSERT INTO gold_mines VALUES (3, 'Gold Mine 3', 'Mexico', 200, 180, 16000);

SELECT AVG(num_employees) FROM gold_mines WHERE location = 'Canada';


Question: List the names of the top five countries with the highest visitor counts at heritage sites in 'Asia'.

CREATE TABLE HeritageSitesAsia (SiteID INT PRIMARY KEY, SiteName VARCHAR(50), Country VARCHAR(50), VisitorCount INT); INSERT INTO HeritageSitesAsia (SiteID, SiteName, Country, VisitorCount) VALUES (1, 'Angkor Wat', 'Cambodia', 2500000), (2, 'Taj Mahal', 'India', 3000000);

SELECT Country, SUM(VisitorCount) as Total FROM HeritageSitesAsia GROUP BY Country ORDER BY Total DESC LIMIT 5;


Question: Generate PostgreSQL SQL for: what are the tries where the game was lost by 4?

CREATE TABLE table_13564637_3 (tries_against VARCHAR, lost VARCHAR)

SELECT tries_against FROM table_13564637_3 WHERE lost = '4';


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

insert into rtest_nothn4 values (50, 'too small');

Explanation: DML from PostgreSQL core regression test for Rules.


Question: Generate PostgreSQL SQL for: What was the first day cover cancellation for the University of Saskatchewan themed stamp?

CREATE TABLE table_11900773_5 (first_day_cover_cancellation VARCHAR, theme VARCHAR)

SELECT first_day_cover_cancellation FROM table_11900773_5 WHERE theme = 'University of Saskatchewan';


Question: What is the average age of audience members who attended performing arts events in urban areas of New York and Pennsylvania?

CREATE TABLE Events (id INT, state VARCHAR(2), city VARCHAR(20), category VARCHAR(20), attendees INT, event_date DATE); INSERT INTO Events (id, state, city, category, attendees, event_date) VALUES (1, 'NY', 'New York', 'Theater', 500, '2022-01-01'), (2, 'PA', 'Philadelphia', 'Dance', 300, '2022-02-01'), (3, 'NY', 'Albany', 'Music', 400, '2022-03-01'); CREATE TABLE Audience (id INT, state VARCHAR(2), zip INT, age INT); INSERT INTO Audience (id, state, zip, age) VALUES (1, 'NY', 10000, 30), (2, 'PA', 19000, 40), (3, 'NY', 12000, 35); CREATE TABLE Zipcodes (zip INT, city VARCHAR(20), urban VARCHAR(5)); INSERT INTO Zipcodes (zip, city, urban) VALUES (10000, 'New York', 'yes'), (19000, 'Philadelphia', 'yes'), (12000, 'Albany', 'yes');

SELECT AVG(Audience.age) FROM Events INNER JOIN Audience ON Events.state = Audience.state INNER JOIN Zipcodes ON Audience.zip = Zipcodes.zip WHERE urban = 'yes' AND Events.category IN ('Theater', 'Dance') AND Events.state IN ('NY', 'PA');


Question: What is the percentage of global Dysprosium production in 2019 that came from Africa?

CREATE TABLE production (element VARCHAR(10), year INT, region VARCHAR(10), quantity INT); INSERT INTO production (element, year, region, quantity) VALUES ('Dysprosium', 2019, 'Africa', 320), ('Dysprosium', 2019, 'Asia', 1200), ('Dysprosium', 2019, 'North America', 400), ('Dysprosium', 2019, 'Europe', 500);

SELECT (SUM(CASE WHEN region = 'Africa' THEN quantity ELSE 0 END) / SUM(quantity)) * 100 FROM production WHERE element = 'Dysprosium' AND year = 2019;


Question: List the names of ingredients and their sourcing countries, sorted by the sourcing date in descending order.

CREATE TABLE ingredients (ingredient_id INT, name TEXT, sourcing_country TEXT, source_date DATE); INSERT INTO ingredients (ingredient_id, name, sourcing_country, source_date) VALUES (1, 'Water', 'China', '2021-01-01'), (2, 'Glycerin', 'France', '2021-02-15'), (3, 'Retinol', 'USA', '2020-12-10');

SELECT name, sourcing_country, source_date FROM ingredients ORDER BY source_date DESC;


Question: Generate PostgreSQL SQL for: Name the 2013 for 2011 of 1r

SELECT 2013 FROM table_name_9 WHERE 2011 = '1r';


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

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

SELECT count(*) FROM (select view_a from view_a) AS _sub;


Question: Identify the astrophysics research having the highest number of citations.

CREATE TABLE astrophysics_research(id INT, title VARCHAR(50), citations INT); INSERT INTO astrophysics_research(id, title, citations) VALUES (1, 'Stars and Galaxies', 150); INSERT INTO astrophysics_research(id, title, citations) VALUES (2, 'Black Holes', 200);

SELECT title FROM astrophysics_research WHERE citations = (SELECT MAX(citations) FROM astrophysics_research);


Question: What is the total billing amount for cases in the 'Southern' region, excluding cases with a billing amount less than $5000?

CREATE TABLE cases (id INT, region VARCHAR(10), billing_amount INT); INSERT INTO cases (id, region, billing_amount) VALUES (1, 'Eastern', 5000), (2, 'Western', 7000), (3, 'Eastern', 6000), (4, 'Southern', 8000), (5, 'Southern', 4000);

SELECT SUM(billing_amount) FROM cases WHERE region = 'Southern' AND billing_amount > 5000;


Question: What is the oldest artifact in 'SiteJ'?

CREATE TABLE SiteJ (id INT PRIMARY KEY, artifact_name VARCHAR(50), date_found DATE); INSERT INTO SiteJ (id, artifact_name, date_found) VALUES (1, 'Iron Axehead', '2017-07-22'), (2, 'Leather Pouch', '2016-11-03');

SELECT artifact_name FROM (SELECT artifact_name, ROW_NUMBER() OVER (ORDER BY date_found ASC) rn FROM SiteJ) t WHERE rn = 1;


Question: What is the average mass of Mars rovers?

CREATE TABLE mars_rovers (rover_name TEXT, rover_mass REAL); INSERT INTO mars_rovers (rover_name, rover_mass) VALUES ('Sojourner', 10.6), ('Spirit', 174), ('Opportunity', 174);

SELECT AVG(rover_mass) FROM mars_rovers;


Question: What is the maximum acres of habitat preserved for each animal species?

CREATE TABLE habitat_preservation (id INT, animal_id INT, location VARCHAR(50), acres FLOAT);INSERT INTO habitat_preservation (id, animal_id, location, acres) VALUES (1, 1, 'Asia', 10000), (2, 2, 'Africa', 15000), (3, 3, 'Africa', 5000);CREATE TABLE animal_population (id INT, species VARCHAR(50), population INT);INSERT INTO animal_population (id, species, population) VALUES (1, 'Tiger', 250), (2, 'Elephant', 500), (3, 'Giraffe', 300);

SELECT ap.species, MAX(h.acres) FROM animal_population ap JOIN habitat_preservation h ON ap.id = h.animal_id GROUP BY ap.species;


Question: Update the capacities of all warehouses located in California

CREATE TABLE warehouse (id INT, city VARCHAR(20), capacity INT); INSERT INTO warehouse (id, city, capacity) VALUES (1, 'Chicago', 1000), (2, 'Houston', 1500), (3, 'Miami', 800), (4, 'Los Angeles', 1200), (5, 'San Francisco', 1800); CREATE TABLE state (id INT, name VARCHAR(20)); INSERT INTO state (id, name) VALUES (1, 'California'), (2, 'Texas'), (3, 'Florida'); CREATE VIEW warehouse_state AS SELECT * FROM warehouse INNER JOIN state ON warehouse.id = state.id;

UPDATE warehouse_state SET capacity = 1500 WHERE name IN ('California');


Question: Generate PostgreSQL SQL for: Name the Nationality / Opponent of rosario?

CREATE TABLE table_name_64 (competition VARCHAR, nationality___opponent VARCHAR)

SELECT competition FROM table_name_64 WHERE nationality___opponent = 'rosario';


Question: Generate PostgreSQL SQL for: What's the average amount of ties had when a team wins 6 and it's past the 2004 season?

CREATE TABLE table_name_55 (ties INTEGER, wins VARCHAR, season VARCHAR)

SELECT AVG(ties) FROM table_name_55 WHERE wins = 6 AND season > 2004;


Question: Which satellites were deployed by SpaceX in the year 2020?

CREATE TABLE Satellites (name VARCHAR(50), manufacturer VARCHAR(50), launch_year INT); INSERT INTO Satellites (name, manufacturer, launch_year) VALUES ('Starlink 1', 'SpaceX', 2020), ('Starlink 2', 'SpaceX', 2020);

SELECT name FROM Satellites WHERE manufacturer = 'SpaceX' AND launch_year = 2020;


Question: Generate PostgreSQL SQL for: When 4 is the v-band what is the overall amount of ka-bands?

CREATE TABLE table_186468_1 (ka_band VARCHAR, v_band VARCHAR)

SELECT COUNT(ka_band) FROM table_186468_1 WHERE v_band = '4';


Question: Generate PostgreSQL SQL for: What league played in 2011?

CREATE TABLE table_name_65 (league VARCHAR, year VARCHAR)

SELECT league FROM table_name_65 WHERE year = 2011;


Question: What is the total cost of all road projects in the city of New York with a budget over $10 million?

CREATE TABLE RoadProjects (id INT, name TEXT, city TEXT, budget DECIMAL(10,2));

SELECT SUM(budget) FROM RoadProjects WHERE city = 'New York' AND budget > 10000000;


Question: Show an example of PostgreSQL CREATE FOREIGN TABLE (example 1).

CREATE FOREIGN TABLE films ( code char(5) NOT NULL, title varchar(40) NOT NULL, did integer NOT NULL, date_prod date, kind varchar(10), len interval hour to minute ) SERVER film_server;

Explanation: PostgreSQL CREATE FOREIGN TABLE command.


Question: Generate PostgreSQL SQL for: Which 2008 Tournament has a 2007 of a and a 2010 of qf?

SELECT 2008 FROM table_name_46 WHERE 2007 = 'a' AND 2010 = 'qf';


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

CREATE OPERATOR CLASS timetz_ops
DEFAULT FOR TYPE timetz USING gin
AS
    OPERATOR        1       <,
    OPERATOR        2       <=,
    OPERATOR        3       =,
    OPERATOR        4       >=,
    OPERATOR        5       >,
    FUNCTION        1       timetz_cmp(timetz,timetz),
    FUNCTION        2       gin_extract_value_timetz(timetz, internal),
    FUNCTION        3       gin_extract_query_timetz(timetz, internal, int2, internal, internal),
    FUNCTION        4       gin_btree_consistent(internal, int2, anyelement, int4, internal, internal),
    FUNCTION        5       gin_compare_prefix_timetz(timetz,timetz,int2, internal),
STORAGE         timetz;

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


Question: Generate PostgreSQL SQL for: How many places have an area of 409.41 (km2)?

CREATE TABLE table_261222_1 (population__2010_ VARCHAR, area__km_2__ VARCHAR)

SELECT COUNT(population__2010_) FROM table_261222_1 WHERE area__km_2__ = '409.41';


Question: Generate PostgreSQL SQL for: How many heights does chad henne have?

CREATE TABLE table_15017024_2 (height VARCHAR, player_name VARCHAR)

SELECT COUNT(height) FROM table_15017024_2 WHERE player_name = 'Chad Henne';


Question: What is the total number of employees in the 'mining_operations' table, grouped by their job titles?

CREATE TABLE mining_operations (id INT, name VARCHAR(50), job_title VARCHAR(50), department VARCHAR(50), experience INT); INSERT INTO mining_operations (id, name, job_title, department, experience) VALUES (1, 'John Doe', 'Mining Engineer', 'Operations', 7); INSERT INTO mining_operations (id, name, job_title, department, experience) VALUES (2, 'Jane Smith', 'Geologist', 'Exploration', 5);

SELECT job_title, COUNT(*) as total_employees FROM mining_operations GROUP BY job_title;


Question: insert new exhibit data into 'exhibition_statistics'

CREATE TABLE exhibition_statistics (exhibit_id INT, attendance INT);

INSERT INTO exhibition_statistics (exhibit_id, attendance) VALUES (3, 600), (4, 800);


Question: Which exhibition received the most digital interactions in London?

CREATE TABLE DigitalInteractions (id INT, city VARCHAR(50), exhibition VARCHAR(50), digital_interactions INT);

SELECT exhibition, MAX(digital_interactions) FROM DigitalInteractions WHERE city = 'London' GROUP BY exhibition ORDER BY MAX(digital_interactions) DESC LIMIT 1;


Question: What is the percentage of organic cotton used in garments manufactured in Europe?

CREATE TABLE materials (garment_id INT, material VARCHAR(255), organic BOOLEAN); INSERT INTO materials (garment_id, material, organic) VALUES (1, 'cotton', TRUE); INSERT INTO materials (garment_id, material, organic) VALUES (2, 'polyester', FALSE); INSERT INTO materials (garment_id, material, organic) VALUES (3, 'silk', FALSE);

SELECT (COUNT(CASE WHEN organic THEN 1 END)/COUNT(*))*100 FROM materials WHERE material = 'cotton' AND garment_id IN (SELECT garment_id FROM garments WHERE manufacture_location LIKE 'Europe%');


Question: PostgreSQL Plpgsql: show example 4.

CREATE FUNCTION sales_tax(subtotal real) RETURNS real AS $$ BEGIN RETURN subtotal * 0.06; END; $$ LANGUAGE plpgsql;

Explanation: Example from PostgreSQL documentation on Plpgsql.


Question: Generate PostgreSQL SQL for: What is the sum of the area for the bahawalnagar district with a population more than 134,936?

CREATE TABLE table_name_32 (city_area_km_2__ INTEGER, district VARCHAR, city_population__2009_ VARCHAR)

SELECT SUM(city_area_km_2__) FROM table_name_32 WHERE district = 'bahawalnagar district' AND city_population__2009_ > 134 OFFSET 936;


Question: What is the maximum recycling rate for plastic in 2020 for each state?

CREATE TABLE recycling_rates(year INT, state VARCHAR(255), plastic_recycling FLOAT, paper_recycling FLOAT, glass_recycling FLOAT); INSERT INTO recycling_rates VALUES (2020, 'California', 0.6, 0.7, 0.5), (2020, 'Texas', 0.5, 0.6, 0.4);

SELECT MAX(plastic_recycling) AS max_plastic_recycling, state FROM recycling_rates WHERE year = 2020 GROUP BY state;


Question: Show the number of security incidents and their category by year

CREATE TABLE incident_yearly (id INT, incident_date DATE, category VARCHAR(10)); INSERT INTO incident_yearly (id, incident_date, category) VALUES (1, '2021-01-01', 'Malware'), (2, '2021-01-15', 'Phishing'), (3, '2022-01-01', 'Insider Threat'), (4, '2022-01-01', 'DDoS'), (5, '2022-02-01', 'Phishing'), (6, '2023-03-01', 'Insider Threat');

SELECT EXTRACT(YEAR FROM incident_date) as year, category, COUNT(*) as incidents FROM incident_yearly GROUP BY year, category;


Question: Generate PostgreSQL SQL for: Which is the method under the event Jungle Fight 2?

CREATE TABLE table_name_24 (method VARCHAR, event VARCHAR)

SELECT method FROM table_name_24 WHERE event = 'jungle fight 2';


Question: Create a view named 'space_debris_view' showing all debris entries

CREATE TABLE space_debris (id INT PRIMARY KEY, debris_id INT, debris_name VARCHAR(255), launch_date DATE, location VARCHAR(255), type VARCHAR(255)); CREATE VIEW space_debris_view AS SELECT * FROM space_debris;


Question: Find the daily net transaction amount (total transaction value - total withdrawal value) for the past week, grouped by day and ordered by day in ascending order for customers in Europe?

CREATE TABLE customer_europe_transactions (transaction_id INT, customer_id INT, transaction_value DECIMAL(10, 2), transaction_type VARCHAR(10), transaction_date DATE, customer_region VARCHAR(20)); INSERT INTO customer_europe_transactions (transaction_id, customer_id, transaction_value, transaction_type, transaction_date, customer_region) VALUES (1, 1, 12000, 'deposit', '2021-07-01', 'Europe'), (2, 2, -5000, 'withdrawal', '2021-07-01', 'Europe'), (3, 3, 8000, 'deposit', '2021-07-02', 'Europe');

SELECT customer_region, transaction_date, SUM(CASE WHEN transaction_type = 'deposit' THEN transaction_value ELSE -transaction_value END) as daily_net_transaction_amount FROM customer_europe_transactions WHERE transaction_date BETWEEN DATE_SUB(CURRENT_DATE, INTERVAL 7 DAY) AND CURRENT_DATE AND customer_region = 'Europe' GROUP BY customer_region, transaction_date ORDER BY transaction_date ASC;


Question: What is the maximum number of intelligence operations conducted by the United States in a single year?

CREATE TABLE intelligence_operations (country VARCHAR(255), year INT, num_operations INT); INSERT INTO intelligence_operations (country, year, num_operations) VALUES ('United States', 2015, 5000), ('United States', 2016, 6000), ('United Kingdom', 2015, 3000), ('United Kingdom', 2016, 3500);

SELECT MAX(num_operations) FROM intelligence_operations WHERE country = 'United States';


Question: What is the total number of garments sold for each manufacturer, partitioned by the manufacturer and ordered by the total number of garments sold in descending order?

CREATE TABLE Manufacturers (ManufacturerID INT, ManufacturerName VARCHAR(255));CREATE TABLE Garments (GarmentID INT, ManufacturerID INT);CREATE TABLE Sales (SaleID INT, GarmentID INT, SaleDate DATE, Quantity INT);

SELECT m.ManufacturerName, COUNT(g.GarmentID) AS TotalGarments, ROW_NUMBER() OVER (PARTITION BY NULL ORDER BY COUNT(g.GarmentID) DESC) AS Rank FROM Manufacturers m JOIN Garments g ON m.ManufacturerID = g.ManufacturerID JOIN Sales s ON g.GarmentID = s.GarmentID GROUP BY m.ManufacturerName ORDER BY Rank;


Question: Generate PostgreSQL SQL for: Name the singer for joe wilkinson

CREATE TABLE table_29135051_2 (singer_s_ VARCHAR, comedian VARCHAR)

SELECT singer_s_ FROM table_29135051_2 WHERE comedian = 'Joe Wilkinson';


Question: What are the details of the policies that have not been reviewed in the last 90 days and the number of systems associated with each?

CREATE TABLE policies (policy_id INT, policy_name VARCHAR(255), owner VARCHAR(255), review_date DATE, num_systems INT);CREATE TABLE policy_systems (policy_id INT, system_id INT);

SELECT p.policy_name, p.owner, p.num_systems, COUNT(ps.system_id) as associated_systems FROM policies p LEFT JOIN policy_systems ps ON p.policy_id = ps.policy_id WHERE p.review_date < DATE_SUB(CURRENT_DATE, INTERVAL 90 DAY) GROUP BY p.policy_id;


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

CREATE TABLE table_name_91 (score VARCHAR, year VARCHAR)

SELECT score FROM table_name_91 WHERE year = '1993';


Question: Display the names of therapists who have conducted therapy sessions for patients diagnosed with 'Anxiety Disorder'

CREATE TABLE therapists (therapist_id INT PRIMARY KEY, therapist_name TEXT, specialization TEXT); CREATE TABLE patients (patient_id INT PRIMARY KEY, patient_name TEXT, date_of_birth DATE, diagnosis TEXT); CREATE TABLE therapy_sessions (session_id INT PRIMARY KEY, patient_id INT, therapist_id INT, session_date DATE, session_duration TIME);

SELECT therapists.therapist_name FROM therapists INNER JOIN (SELECT patients.patient_id, therapy_sessions.therapist_id FROM patients INNER JOIN therapy_sessions ON patients.patient_id = therapy_sessions.patient_id WHERE patients.diagnosis = 'Anxiety Disorder') AS therapy_sessions_filtered ON therapists.therapist_id = therapy_sessions_filtered.therapist_id;


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

SELECT to_json(a) AS a, JSON_OBJECTAGG(k : v ABSENT ON NULL)
OVER (ORDER BY k)
FROM (VALUES (1,1), (1,null), (2,2)) a(k,v);

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

SELECT count(*) FROM (SELECT to_json(a) AS a, JSON_OBJECTAGG(k : v ABSENT ON NULL)
OVER (ORDER BY k)
FROM (VALUES (1,1), (1,null), (2,2)) a(k,v)) AS _sub;


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

INSERT INTO num_exp_mul VALUES (0,2,'0');

Explanation: DML from PostgreSQL core regression test for Numeric.


Question: Generate PostgreSQL SQL for: Game smaller than 34, and a December smaller than 14, and a Score of 10 - 6 has what opponent?

CREATE TABLE table_name_46 (opponent VARCHAR, score VARCHAR, game VARCHAR, december VARCHAR)

SELECT opponent FROM table_name_46 WHERE game < 34 AND december < 14 AND score = '10 - 6';


Question: Generate PostgreSQL SQL for: What percentage did McCain get in Hamilton county?

CREATE TABLE table_20799905_1 (mccain_percentage VARCHAR, county VARCHAR)

SELECT mccain_percentage FROM table_20799905_1 WHERE county = 'HAMILTON';


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

CREATE TABLE test_exists (a int, b text);

Explanation: DDL from PostgreSQL core regression test for Drop If Exists.


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

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

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

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


Question: Count the number of skincare products that contain natural ingredients and have a price above the median?

CREATE TABLE products(product_id INT, category VARCHAR(255), has_natural_ingredients BOOLEAN, price DECIMAL(5,2));INSERT INTO products (product_id, category, has_natural_ingredients, price) VALUES (1, 'Cleanser', true, 19.99), (2, 'Toner', false, 12.99), (3, 'Serum', true, 35.99), (4, 'Moisturizer', false, 24.99);

SELECT COUNT(*) FROM products WHERE category = 'skincare' AND has_natural_ingredients = true AND price > (SELECT AVG(price) FROM products WHERE category = 'skincare');


Question: Write the DDL statement from PostgreSQL regression test 'foreign_data' (example 177).

CREATE FOREIGN TABLE ft_part_1_2 (a INT NOT NULL) SERVER s0;

Explanation: DDL from PostgreSQL core regression test for Foreign Data.


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

SELECT 'a:1 b:2'::tsvector @@ 'a <2> b'::tsquery AS "false";

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

SELECT count(*) FROM (SELECT 'a:1 b:2'::tsvector @@ 'a <2> b'::tsquery AS "false") AS _sub;


Question: What are the total sales for each drug in Q3 2020?

CREATE TABLE drugs (drug_id INT, drug_name TEXT); INSERT INTO drugs (drug_id, drug_name) VALUES (1001, 'Ibuprofen'), (1002, 'Paracetamol'), (1003, 'Aspirin'); CREATE TABLE sales (sale_id INT, drug_id INT, sale_date DATE, revenue FLOAT); INSERT INTO sales (sale_id, drug_id, sale_date, revenue) VALUES (1, 1001, '2020-07-05', 1800.0), (2, 1002, '2020-08-10', 2300.0), (3, 1003, '2020-09-15', 1400.0), (4, 1001, '2020-10-20', 1900.0), (5, 1002, '2020-11-25', 2400.0);

SELECT drug_name, SUM(revenue) as total_sales FROM sales JOIN drugs ON sales.drug_id = drugs.drug_id WHERE sale_date BETWEEN '2020-07-01' AND '2020-09-30' GROUP BY drug_name;


Question: Insert new records for a game designer who has adopted virtual reality technology.

CREATE TABLE GameDesigners (DesignerID INT, Name VARCHAR(30), VRAdoption BOOLEAN);

INSERT INTO GameDesigners (DesignerID, Name, VRAdoption) VALUES (1, 'John Doe', TRUE);


Question: What is the total humanitarian assistance provided by country in the last 3 years?

CREATE TABLE HumanitarianAssistance(Year INT, Country NVARCHAR(50), Amount DECIMAL(18,2));INSERT INTO HumanitarianAssistance(Year, Country, Amount) VALUES (2018, 'United States', 6500000000), (2018, 'Germany', 2000000000), (2019, 'United States', 7000000000), (2019, 'Germany', 2500000000), (2020, 'United States', 8000000000), (2020, 'Germany', 3000000000);

SELECT Country, SUM(Amount) AS Total_Assistance FROM HumanitarianAssistance WHERE Year >= 2018 GROUP BY Country;


Question: Generate PostgreSQL SQL for: What is the Venue when the result was 88–87?

CREATE TABLE table_name_78 (venue VARCHAR, result VARCHAR)

SELECT venue FROM table_name_78 WHERE result = '88–87';


Question: What is the total cargo capacity of vessels registered in Spain?

CREATE TABLE Vessels (ID VARCHAR(10), Name VARCHAR(20), Type VARCHAR(20), Cargo_Capacity FLOAT); INSERT INTO Vessels (ID, Name, Type, Cargo_Capacity) VALUES ('1', 'Vessel A', 'Cargo', 10000.0), ('2', 'Vessel B', 'Tanker', 15000.0); CREATE TABLE Registry (ID VARCHAR(10), Vessel_ID VARCHAR(10), Registered_Country VARCHAR(20)); INSERT INTO Registry (ID, Vessel_ID, Registered_Country) VALUES ('1', '1', 'USA'), ('2', '2', 'Spain');

SELECT SUM(Cargo_Capacity) FROM Vessels INNER JOIN Registry ON Vessels.ID = Registry.Vessel_ID WHERE Registered_Country = 'Spain';


Question: What is the maximum weight of packages shipped between countries in the Middle East in the last week?

CREATE TABLE package_middle_east (id INT, package_weight FLOAT, shipped_from VARCHAR(20), shipped_to VARCHAR(20), shipped_date DATE); INSERT INTO package_middle_east (id, package_weight, shipped_from, shipped_to, shipped_date) VALUES (1, 4.5, 'Saudi Arabia', 'UAE', '2022-02-03');

SELECT MAX(package_weight) FROM package_middle_east WHERE shipped_from LIKE 'Middle East%' AND shipped_to LIKE 'Middle East%' AND shipped_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 WEEK);


Question: Generate PostgreSQL SQL for: Name the city for thailand

CREATE TABLE table_name_97 (city VARCHAR, country VARCHAR)

SELECT city FROM table_name_97 WHERE country = 'thailand';


Question: Generate PostgreSQL SQL for: Who is the March playmate with an August playmate Gianna Amore?

CREATE TABLE table_name_53 (march VARCHAR, august VARCHAR)

SELECT march FROM table_name_53 WHERE august = 'gianna amore';


Question: Generate PostgreSQL SQL for: What is the french word for fribourg?

CREATE TABLE table_name_72 (french VARCHAR, common_english VARCHAR)

SELECT french FROM table_name_72 WHERE common_english = 'fribourg';


Question: Generate PostgreSQL SQL for: Find the name and capacity of products with price greater than 700 (in USD).

CREATE TABLE Catalog_Contents (catalog_entry_name VARCHAR, capacity VARCHAR, price_in_dollars INTEGER)

SELECT catalog_entry_name, capacity FROM Catalog_Contents WHERE price_in_dollars > 700;


Question: Generate PostgreSQL SQL for: What was her highest Super G score with a Slalom score of 58 and an Overall larger than 2?

CREATE TABLE table_name_43 (super_g INTEGER, slalom VARCHAR, overall VARCHAR)

SELECT MAX(super_g) FROM table_name_43 WHERE slalom = '58' AND overall > 2;


Question: Generate PostgreSQL SQL for: Which loss had a player lower than 18?

CREATE TABLE table_name_63 (lost INTEGER, played INTEGER)

SELECT MIN(lost) FROM table_name_63 WHERE played < 18;


Question: Write the DDL statement from PostgreSQL regression test 'create_view' (example 128).

create view view_of_joins_2a as select * from tbl1 join tbl1a using (a);

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


Question: Which satellites were deployed before 2010 and after 2005?

CREATE TABLE Satellite (ID INT, LaunchDate DATE);

SELECT * FROM Satellite WHERE LaunchDate BETWEEN '2005-01-01' AND '2010-12-31';


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

CREATE TABLE truncparted1 PARTITION OF truncparted FOR VALUES IN (1);

Explanation: DDL from PostgreSQL core regression test for Truncate.


Question: What is the maximum labor productivity in the coal mining industry in the state "West Virginia" for the year 2020?

CREATE TABLE coal_mining_productivity (id INT, state TEXT, year INT, productivity FLOAT); INSERT INTO coal_mining_productivity (id, state, year, productivity) VALUES (1, 'West Virginia', 2018, 3.5); INSERT INTO coal_mining_productivity (id, state, year, productivity) VALUES (2, 'West Virginia', 2020, 4.2);

SELECT MAX(productivity) FROM coal_mining_productivity WHERE state = 'West Virginia' AND year = 2020;


Question: Show the total revenue for each music genre in descending order.

CREATE TABLE album_sales (id INT, album_name VARCHAR(50), artist_name VARCHAR(50), genre VARCHAR(20), revenue FLOAT);

SELECT genre, SUM(revenue) AS total_revenue FROM album_sales GROUP BY genre ORDER BY total_revenue DESC;


Question: Show the number of unique users who listened to the 'Hip Hop' genre in France.

CREATE TABLE listens (user_id INT, song_id INT, date DATE); CREATE TABLE songs (id INT, title VARCHAR(100), genre VARCHAR(50)); INSERT INTO listens (user_id, song_id, date) VALUES (1, 1, '2020-01-01'), (1, 2, '2020-01-02'), (2, 1, '2020-01-01'), (3, 3, '2020-01-03'), (3, 1, '2020-01-04'); INSERT INTO songs (id, title, genre) VALUES (1, 'Song1', 'Hip Hop'), (2, 'Song2', 'Pop'), (3, 'Song3', 'Hip Hop');

SELECT COUNT(DISTINCT user_id) FROM listens JOIN songs ON listens.song_id = songs.id WHERE songs.genre = 'Hip Hop' AND listens.date BETWEEN '2020-01-01' AND '2020-12-31' AND listens.country = 'France';


Question: Generate PostgreSQL SQL for: How many teams scored 616 points?

CREATE TABLE table_13018091_1 (won VARCHAR, pts_for VARCHAR)

SELECT COUNT(won) FROM table_13018091_1 WHERE pts_for = 616;


Question: pgTAP test for Index (assertion 18).

SELECT * FROM check_test(
    has_index( 'public', 'sometab', 'idx_foo', 'name'::name ),
    true,
    'has_index() hash index no desc',
    'Index idx_foo should exist',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Index.


Question: Generate PostgreSQL SQL for: What year was the result did not qualify?

CREATE TABLE table_name_85 (year VARCHAR, result VARCHAR)

SELECT year FROM table_name_85 WHERE result = 'did not qualify';


Question: What is the total number of articles published by 'The New York Times' and 'The Washington Post'?

CREATE TABLE ny_times (article_id INT, title TEXT, publisher TEXT); INSERT INTO ny_times (article_id, title, publisher) VALUES (1, 'Article 1', 'The New York Times'), (2, 'Article 2', 'The New York Times'); CREATE TABLE wa_post (article_id INT, title TEXT, publisher TEXT); INSERT INTO wa_post (article_id, title, publisher) VALUES (3, 'Article 3', 'The Washington Post'), (4, 'Article 4', 'The Washington Post');

SELECT COUNT(*) FROM ( (SELECT * FROM ny_times) UNION (SELECT * FROM wa_post) );


Question: Generate PostgreSQL SQL for: what's the date of birth with end of term being 5july1978

CREATE TABLE table_12134383_1 (date_of_birth VARCHAR, end_of_term VARCHAR)

SELECT date_of_birth FROM table_12134383_1 WHERE end_of_term = '5July1978';


Question: Update the position of the employee with ID 2 in the "employee_records" table

CREATE TABLE employee_records (employee_id INT PRIMARY KEY, name TEXT, position TEXT, leaving_date DATE); INSERT INTO employee_records (employee_id, name, position, leaving_date) VALUES (1, 'John Doe', 'CTO', '2018-01-01'); INSERT INTO employee_records (employee_id, name, position, leaving_date) VALUES (2, 'Jane Smith', 'COO', '2019-05-15'); INSERT INTO employee_records (employee_id, name, position, leaving_date) VALUES (3, 'Alice Johnson', 'Data Analyst', '2020-03-20');

UPDATE employee_records SET position = 'VP of Operations' WHERE employee_id = 2;


Question: What is the minimum age of sea ice in the Beaufort Sea in 2021?

CREATE TABLE sea_ice_age (sea VARCHAR(50), year INT, age INT);

SELECT MIN(age) FROM sea_ice_age WHERE sea = 'Beaufort Sea' AND year = 2021;


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

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

SELECT count(*) FROM (select regexp_matches('ab', 'a(?<=a)b*(?<=b)c*')) AS _sub;


Question: What is the total quantity of each textile material sourced from each country?

CREATE TABLE Textiles (id INT, material VARCHAR(20), country VARCHAR(20), quantity INT); CREATE VIEW TextilesByCountryMaterial AS SELECT material, country, SUM(quantity) as total_quantity FROM Textiles GROUP BY material, country;

SELECT material, country, total_quantity FROM TextilesByCountryMaterial;


Question: Generate PostgreSQL SQL for: Which school/club has a pick smaller than 196, a round higher than 5 and has Blake Miller?

CREATE TABLE table_name_25 (school_club_team VARCHAR, player VARCHAR, pick VARCHAR, round VARCHAR)

SELECT school_club_team FROM table_name_25 WHERE pick < 196 AND round > 5 AND player = 'blake miller';


Question: Generate PostgreSQL SQL for: Who were the finalists in the 1972–73 season?

CREATE TABLE table_name_53 (finalists VARCHAR, season VARCHAR)

SELECT finalists FROM table_name_53 WHERE season = '1972–73';


Question: Minimum how many solar panels are installed in buildings located in Australia?

CREATE TABLE solar_panels (building_id INT, quantity INT); CREATE TABLE buildings (id INT, country TEXT);

SELECT MIN(quantity) FROM solar_panels JOIN buildings ON solar_panels.building_id = buildings.id WHERE country = 'Australia';


Question: Generate PostgreSQL SQL for: When North Melbourne is the Away team, what is the total number of the Crowd?

CREATE TABLE table_name_46 (crowd VARCHAR, away_team VARCHAR)

SELECT COUNT(crowd) FROM table_name_46 WHERE away_team = 'north melbourne';


Question: Which country has the most space debris?

CREATE TABLE space_debris (debris_id INT, name VARCHAR(255), country VARCHAR(255), debris_type VARCHAR(255));

SELECT country, COUNT(*) as total_debris FROM space_debris GROUP BY country ORDER BY total_debris DESC LIMIT 1;


Question: What is the total funding received by organizations in the Arctic region in the year 2022?

CREATE TABLE funding (id INT PRIMARY KEY, name VARCHAR(255), amount INT, organization VARCHAR(255), region VARCHAR(255), year INT); INSERT INTO funding (id, name, amount, organization, region, year) VALUES (1, 'Funding A', 100000, 'National Science Foundation', 'Arctic', 2023), (2, 'Funding B', 200000, 'University of the Arctic', 'Arctic', 2022), (3, 'Funding C', 50000, 'Arctic Council', 'Antarctic', 2023);

SELECT SUM(f.amount) AS total_funding FROM funding f WHERE f.region = 'Arctic' AND f.year = 2022;


Question: What is the total number of community health workers by gender?

CREATE TABLE workers (worker_id INT, worker_name VARCHAR(50), gender VARCHAR(10), region_id INT);

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


Question: Generate PostgreSQL SQL for: what's the first operational with programming being not programmable—single purpose

CREATE TABLE table_13636_1 (first_operational VARCHAR, programming VARCHAR)

SELECT first_operational FROM table_13636_1 WHERE programming = 'Not programmable—single purpose';


Question: Generate PostgreSQL SQL for: What is the mascot for the school in 32 Hendricks County?

CREATE TABLE table_name_11 (mascot VARCHAR, county VARCHAR)

SELECT mascot FROM table_name_11 WHERE county = '32 hendricks';


Question: What is the maximum fare for a trip on the Red Line?

CREATE TABLE if not exists metro_lines (line_id serial primary key,name varchar(255));CREATE TABLE if not exists metro_stations (station_id serial primary key,name varchar(255),line_id int);CREATE TABLE if not exists routes (route_id serial primary key,line_id int,start_station_id int,end_station_id int);CREATE TABLE if not exists fares (fare_id serial primary key,route_id int,price decimal);

SELECT MAX(f.price) FROM fares f JOIN routes r ON f.route_id = r.route_id JOIN metro_stations s ON r.start_station_id = s.station_id WHERE s.line_id = 1;


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

INSERT INTO J1_TBL VALUES (7, 7, 'seven');

Explanation: DML from PostgreSQL core regression test for Join.


Question: What is the total funding received by biotech startups in India, grouped by year?

CREATE TABLE startups (id INT, name VARCHAR(255), country VARCHAR(255), funding FLOAT, date DATE); INSERT INTO startups (id, name, country, funding, date) VALUES (1, 'StartupA', 'India', 5000000, '2020-01-01'); INSERT INTO startups (id, name, country, funding, date) VALUES (2, 'StartupB', 'India', 7000000, '2019-01-01');

SELECT country, YEAR(date) AS year, SUM(funding) FROM startups WHERE country = 'India' GROUP BY year, country;


Question: Update the 'LastEruption' date of the 'Eyjafjallajökull' volcano in the 'UnderwaterVolcanoes' table

CREATE TABLE UnderwaterVolcanoes (VolcanoID INT, VolcanoName VARCHAR(255), Location VARCHAR(255), LastEruption DATE);

UPDATE UnderwaterVolcanoes SET LastEruption = '2010-04-14' WHERE VolcanoName = 'Eyjafjallajökull';


Question: Generate PostgreSQL SQL for: How many Connecticut home games were broadcast?

CREATE TABLE table_28298589_4 (broadcast VARCHAR, home_team VARCHAR)

SELECT COUNT(broadcast) FROM table_28298589_4 WHERE home_team = 'Connecticut';


Question: List all funding sources with amounts greater than $10,000

CREATE TABLE FundingSources (FundingSourceID INT PRIMARY KEY, Name VARCHAR(100), Amount FLOAT, Date DATE); INSERT INTO FundingSources (FundingSourceID, Name, Amount, Date) VALUES (1, 'National Endowment for the Arts', 50000, '2021-12-15');

SELECT * FROM FundingSources WHERE Amount > 10000;


Question: Show the names of all destinations that were marketed in 2020 and had more than 15000 tourists visiting in that year.

CREATE TABLE marketing_campaigns (destination VARCHAR(20), year INT); CREATE TABLE tourism_stats (destination VARCHAR(20), year INT, tourists INT); INSERT INTO marketing_campaigns (destination, year) VALUES ('Japan', 2020), ('France', 2020), ('Germany', 2021), ('Italy', 2020); INSERT INTO tourism_stats (destination, year, tourists) VALUES ('Japan', 2020, 20000), ('Japan', 2021, 25000), ('France', 2020, 16000), ('France', 2021, 18000), ('Germany', 2021, 12000), ('Italy', 2020, 15000), ('Italy', 2021, 17000);

SELECT destination FROM marketing_campaigns WHERE year = 2020 INTERSECT SELECT destination FROM tourism_stats WHERE tourists > 15000 AND year = 2020;


Question: What is the maximum number of items produced using fair labor practices in a single factory?

CREATE TABLE FairLaborFactories (id INT, factory_name VARCHAR(50), items INT); INSERT INTO FairLaborFactories (id, factory_name, items) VALUES (1, 'GreenFactory', 2000), (2, 'EcoTextiles', 3000), (3, 'SustainableWeaves', 1000);

SELECT MAX(items) FROM FairLaborFactories;


Question: What is the maximum budget allocated for a single cybersecurity project?

CREATE TABLE CybersecurityBudget (id INT, project VARCHAR(100), budget FLOAT); INSERT INTO CybersecurityBudget (id, project, budget) VALUES (1, 'Project1', 250000.00); INSERT INTO CybersecurityBudget (id, project, budget) VALUES (2, 'Project2', 1000000.00);

SELECT MAX(budget) FROM CybersecurityBudget;


Question: How many users have played 'GameA' and 'GameB'?

SELECT game_id, COUNT(DISTINCT user_id) as unique_users FROM users_games WHERE game_id IN (1, 2) GROUP BY game_id;


Question: Identify the regions with highest carbon sequestration in 2020.

CREATE TABLE carbon_sequestration (year INT, region VARCHAR(255), sequestration FLOAT); INSERT INTO carbon_sequestration (year, region, sequestration) VALUES (2020, 'Region A', 1300.0), (2020, 'Region B', 1400.0), (2020, 'Region C', 1200.0);

SELECT region FROM carbon_sequestration WHERE sequestration = (SELECT MAX(sequestration) FROM carbon_sequestration WHERE year = 2020);


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

SELECT * FROM test_float4 WHERE i<=1::float8 ORDER BY i;

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


Question: What's the name of the blockchain with the highest market capitalization?

CREATE TABLE market_cap (id INT, blockchain_name VARCHAR(255), market_cap INT); INSERT INTO market_cap (id, blockchain_name, market_cap) VALUES (1, 'Bitcoin', 1000000000), (2, 'Ethereum', 500000000), (3, 'Ripple', 200000000);

SELECT blockchain_name FROM market_cap WHERE market_cap = (SELECT MAX(market_cap) FROM market_cap);


Question: Generate PostgreSQL SQL for: What status of school is informatics international college?

CREATE TABLE table_2589963_1 (status VARCHAR, institution VARCHAR)

SELECT status FROM table_2589963_1 WHERE institution = 'Informatics International College';


Question: Generate PostgreSQL SQL for: What is the lowest rank for puerto rico?

CREATE TABLE table_150340_3 (rank INTEGER, country VARCHAR)

SELECT MIN(rank) FROM table_150340_3 WHERE country = 'Puerto Rico';


Question: Generate PostgreSQL SQL for: Among all the claims, what is the amount claimed in the claim with the least amount settled? List both the settlement amount and claim amount.

CREATE TABLE Claims (Amount_Settled VARCHAR, Amount_Claimed VARCHAR)

SELECT Amount_Settled, Amount_Claimed FROM Claims ORDER BY Amount_Settled LIMIT 1;


Question: How many articles were published per month in the 'technology' category over the last 2 years?

CREATE TABLE articles (id INT, title TEXT, category TEXT, publish_date DATE); INSERT INTO articles (id, title, category, publish_date) VALUES (1, 'Article Title 1', 'technology', '2020-02-01'), (2, 'Article Title 2', 'technology', '2022-06-05');

SELECT DATE_FORMAT(publish_date, '%Y-%m') AS pub_month, COUNT(*) AS num_articles FROM articles WHERE category = 'technology' AND publish_date >= NOW() - INTERVAL 2 YEAR GROUP BY pub_month ORDER BY pub_month;


Question: Generate PostgreSQL SQL for: What is the average number of wins of the year with less than 5 top 10s, a winning of $39,190 and less than 2 starts?

CREATE TABLE table_name_17 (wins INTEGER, starts VARCHAR, top_10 VARCHAR, winnings VARCHAR)

SELECT AVG(wins) FROM table_name_17 WHERE top_10 < 5 AND winnings = '$39,190' AND starts < 2;


Question: Generate PostgreSQL SQL for: What is the year with a Kurtis Kraft 500a chassis, and less than 1.5 points?

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

SELECT SUM(year) FROM table_name_10 WHERE chassis = 'kurtis kraft 500a' AND points < 1.5;


Question: Generate PostgreSQL SQL for: What is Score, when Date is "13 March 1985", and when Away Team is "Millwall"?

CREATE TABLE table_name_67 (score VARCHAR, date VARCHAR, away_team VARCHAR)

SELECT score FROM table_name_67 WHERE date = '13 march 1985' AND away_team = 'millwall';


Question: Generate PostgreSQL SQL for: What league has 2-3 as the away?

CREATE TABLE table_name_18 (league VARCHAR, away VARCHAR)

SELECT league FROM table_name_18 WHERE away = '2-3';


Question: What is the average price of 'Sustainable T-Shirts' sold in the 'Europe' region in Q1 2022?

CREATE TABLE Sales (id INT, product VARCHAR(20), region VARCHAR(20), price DECIMAL(5,2), sale_date DATE); INSERT INTO Sales (id, product, region, price, sale_date) VALUES (1, 'Sustainable T-Shirt', 'Europe', 25.99, '2022-01-02'), (2, 'Regular T-Shirt', 'North America', 19.99, '2022-02-15'), (3, 'Sustainable T-Shirt', 'Europe', 27.49, '2022-03-28');

SELECT AVG(price) FROM Sales WHERE product = 'Sustainable T-Shirt' AND region = 'Europe' AND sale_date BETWEEN '2022-01-01' AND '2022-03-31';


Question: What is the total investment in the retail sector for customers in all regions?

CREATE TABLE investment_data (customer_id INT, sector VARCHAR(20), investment FLOAT); INSERT INTO investment_data (customer_id, sector, investment) VALUES (1, 'technology', 5000), (2, 'retail', 8000), (3, 'retail', 3000); CREATE TABLE customer_data (customer_id INT, name VARCHAR(20), region VARCHAR(10)); INSERT INTO customer_data (customer_id, name, region) VALUES (1, 'John Doe', 'east'), (2, 'Jane Smith', 'south'), (3, 'Mary Johnson', 'west');

SELECT SUM(investment) FROM investment_data INNER JOIN customer_data ON investment_data.customer_id = customer_data.customer_id WHERE sector = 'retail';


Question: PL/pgSQL test: Plpython Types (example 87).

SELECT * FROM test_type_conversion_array_int4(ARRAY[NULL,1]);

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


Question: Add a new row to the carbon_offset_programs table for a program with id 6, name 'Public Transportation', start_date 2024-01-01 and end_date 2026-12-31

CREATE TABLE carbon_offset_programs (id INT, name TEXT, start_date DATE, end_date DATE);

INSERT INTO carbon_offset_programs (id, name, start_date, end_date) VALUES (6, 'Public Transportation', '2024-01-01', '2026-12-31');


Question: Generate PostgreSQL SQL for: Find the names of nurses who are nursing an undergoing treatment.

CREATE TABLE undergoes (AssistingNurse VARCHAR); CREATE TABLE nurse (name VARCHAR, EmployeeID VARCHAR)

SELECT DISTINCT T2.name FROM undergoes AS T1 JOIN nurse AS T2 ON T1.AssistingNurse = T2.EmployeeID;


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

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


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

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

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


Question: Generate PostgreSQL SQL for: What is Language, when Content is Sport, when HDTV is No, and when Television Service is ESPN America?

CREATE TABLE table_name_71 (language VARCHAR, television_service VARCHAR, content VARCHAR, hdtv VARCHAR)

SELECT language FROM table_name_71 WHERE content = 'sport' AND hdtv = 'no' AND television_service = 'espn america';


Question: Which city generated the most revenue from hip-hop concerts in the last 2 years?

CREATE TABLE Concerts (location VARCHAR(50), concert_genre VARCHAR(20), year INT, revenue FLOAT); INSERT INTO Concerts (location, concert_genre, year, revenue) VALUES ('New York', 'Hip-Hop', 2020, 45000.00), ('Atlanta', 'Hip-Hop', 2020, 55000.00), ('Los Angeles', 'Hip-Hop', 2021, 65000.00);

SELECT location, MAX(revenue) FROM Concerts WHERE concert_genre = 'Hip-Hop' AND year BETWEEN (SELECT MAX(year) - 2 FROM Concerts) AND MAX(year) GROUP BY location;


Question: List all organic farming practices in descending order of their associated costs (in dollars) in the 'food_justice' schema?

CREATE SCHEMA food_justice;CREATE TABLE organic_practices (id INT, practice VARCHAR(50), cost FLOAT);INSERT INTO food_justice.organic_practices (id, practice, cost) VALUES (1, 'Practice A', 150.5), (2, 'Practice B', 200.3), (3, 'Practice C', 250.0);

SELECT practice, cost FROM food_justice.organic_practices ORDER BY cost DESC;


Question: Find the maximum number of points scored in a single game in NBA history?

CREATE TABLE NBA_Matches (MatchID INT, HomeTeam VARCHAR(50), AwayTeam VARCHAR(50), HomeTeamScore INT, AwayTeamScore INT); INSERT INTO NBA_Matches (MatchID, HomeTeam, AwayTeam, HomeTeamScore, AwayTeamScore) VALUES (1, 'Chicago Bulls', 'Golden State Warriors', 142, 128);

SELECT MAX(HomeTeamScore + AwayTeamScore) FROM NBA_Matches;


Question: Generate PostgreSQL SQL for: who won on 29 may?

CREATE TABLE table_name_32 (winner VARCHAR, date VARCHAR)

SELECT winner FROM table_name_32 WHERE date = '29 may';


Question: Generate PostgreSQL SQL for: What were all the tries for when the try bonus was 8?

CREATE TABLE table_13564637_5 (tries_for VARCHAR, try_bonus VARCHAR)

SELECT tries_for FROM table_13564637_5 WHERE try_bonus = '8';


Question: What is the minimum age of attendees who visited the museum last year?

CREATE TABLE MuseumAttendees (attendeeID INT, visitDate DATE, age INT); INSERT INTO MuseumAttendees (attendeeID, visitDate, age) VALUES (1, '2022-02-03', 35), (2, '2022-08-17', 42), (3, '2022-12-25', 28);

SELECT MIN(age) FROM MuseumAttendees WHERE visitDate >= '2022-01-01' AND visitDate <= '2022-12-31';


Question: How many species are present in each region?

CREATE TABLE species (species_id INT, species_name TEXT);CREATE TABLE regions (region_id INT, region_name TEXT);CREATE TABLE species_regions (species_region_id INT, species_id INT, region_id INT); INSERT INTO species (species_id, species_name) VALUES (1, 'Oak'), (2, 'Pine'), (3, 'Maple'); INSERT INTO regions (region_id, region_name) VALUES (1, 'Region A'), (2, 'Region B'); INSERT INTO species_regions (species_region_id, species_id, region_id) VALUES (1, 1, 1), (2, 2, 1), (3, 3, 2);

SELECT r.region_id, r.region_name, COUNT(sr.species_id) FROM regions AS r JOIN species_regions AS sr ON r.region_id = sr.region_id GROUP BY r.region_id, r.region_name;


Question: Generate PostgreSQL SQL for: What was the Candlelight Records Catalog of Candle053tin format?

CREATE TABLE table_name_93 (format VARCHAR, label VARCHAR, catalog VARCHAR)

SELECT format FROM table_name_93 WHERE label = 'candlelight records' AND catalog = 'candle053tin';


Question: What is the name and type of all satellites launched by spacecraft that were launched after the year 2010?

CREATE TABLE Spacecraft (id INT, name VARCHAR(50), country VARCHAR(50), launch_date DATE); INSERT INTO Spacecraft (id, name, country, launch_date) VALUES (1, 'Falcon 9', 'USA', '2010-06-04'); INSERT INTO Spacecraft (id, name, country, launch_date) VALUES (2, 'Soyuz-FG', 'Russia', '2001-11-02'); INSERT INTO Spacecraft (id, name, country, launch_date) VALUES (3, 'Long March 3B', 'China', '1996-02-19');   CREATE TABLE Satellites (id INT, name VARCHAR(50), type VARCHAR(50), spacecraft_id INT); INSERT INTO Satellites (id, name, type, spacecraft_id) VALUES (1, 'TESS', 'Observation', 1); INSERT INTO Satellites (id, name, type, spacecraft_id) VALUES (2, 'MetOp-C', 'Weather', 2); INSERT INTO Satellites (id, name, type, spacecraft_id) VALUES (3, 'Chinasat 18', 'Communication', 3);

SELECT s.name, s.type FROM Satellites s JOIN Spacecraft sp ON s.spacecraft_id = sp.id WHERE sp.launch_date > '2010-01-01';


Question: Generate PostgreSQL SQL for: What was the score on november 21?

CREATE TABLE table_name_2 (score VARCHAR, date VARCHAR)

SELECT score FROM table_name_2 WHERE date = 'november 21';


Question: Show the revenue for each product category

CREATE TABLE products (product_id INT, product_name VARCHAR(255), category VARCHAR(255)); INSERT INTO products (product_id, product_name, category) VALUES (1, 'Apples', 'Fruit'), (2, 'Bananas', 'Fruit'), (3, 'Milk', 'Dairy'); CREATE TABLE sales (sale_id INT, product_id INT, revenue INT); INSERT INTO sales (sale_id, product_id, revenue) VALUES (1, 1, 100), (2, 2, 50), (3, 3, 200);

SELECT products.category, SUM(sales.revenue) FROM sales INNER JOIN products ON sales.product_id = products.product_id GROUP BY products.category;


Question: Generate PostgreSQL SQL for: I want the player for NHL team for mighty ducks of anaheim

CREATE TABLE table_name_89 (player VARCHAR, nhl_team VARCHAR)

SELECT player FROM table_name_89 WHERE nhl_team = 'mighty ducks of anaheim';


Question: Update the genre of the genre with id 2 to 'New Genre' in the 'genres' table

CREATE TABLE genres (id INT, genre TEXT);

UPDATE genres SET genre = 'New Genre' WHERE id = 2;


Question: List all organizations that have received grants in the Climate Change sector, in alphabetical order?

CREATE TABLE Organizations (OrgID INT, OrgName TEXT, Sector TEXT); CREATE TABLE Grants (GrantID INT, GrantName TEXT, OrgID INT, Sector TEXT, Amount DECIMAL);

SELECT OrgName FROM Organizations JOIN Grants ON Organizations.OrgID = Grants.OrgID WHERE Sector = 'Climate Change' ORDER BY OrgName;


Question: Write the DDL statement from PostgreSQL regression test 'create_am' (example 105).

CREATE TABLE am_partitioned_1 PARTITION OF am_partitioned
  FOR VALUES WITH (MODULUS 10, REMAINDER 1);

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


Question: How many research grants were awarded to each department in the past two years, and what was the total amount awarded?

CREATE TABLE research_grants (id INT, department TEXT, amount INT, year INT); INSERT INTO research_grants (id, department, amount, year) VALUES (8, 'Computer Science', 6000, 2021); INSERT INTO research_grants (id, department, amount, year) VALUES (9, 'Mathematics', 4000, 2020);

SELECT department, COUNT(*) as num_grants, SUM(amount) as total_amount FROM research_grants WHERE year BETWEEN 2020 AND 2021 GROUP BY department;


Question: What is the percentage of crimes committed by juveniles compared to adults?

CREATE TABLE crimes (age VARCHAR(255), count INT); INSERT INTO crimes (age, count) VALUES ('Juvenile', 25), ('Adult', 75);

SELECT age, count, 100.0 * count / SUM(count) OVER () FROM crimes;


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

SELECT '19970210 173201' AT TIME ZONE 'America/New_York';

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

SELECT count(*) FROM (SELECT '19970210 173201' AT TIME ZONE 'America/New_York') AS _sub;


Question: Generate PostgreSQL SQL for: List all the log ids and their descriptions from the problem logs.

CREATE TABLE problem_log (problem_log_id VARCHAR, log_entry_description VARCHAR)

SELECT problem_log_id, log_entry_description FROM problem_log;


Question: Show the total sales for each supplier country, from the sales_fact table, grouped by supplier_country.

CREATE TABLE order_fact (order_id INT, sale_id INT, supplier_id INT, order_date DATE);

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


Question: What is the change in temperature for each Arctic research station over the last year?

CREATE TABLE temperature_data (station VARCHAR(255), year INT, temperature FLOAT);

SELECT station, (temperature - LAG(temperature) OVER (PARTITION BY station ORDER BY year)) AS temperature_change  FROM temperature_data WHERE year BETWEEN 2022 AND 2022;


Question: Generate PostgreSQL SQL for: What are all the policy types of the customer named "Dayana Robel"?

CREATE TABLE customers (customer_id VARCHAR, customer_name VARCHAR); CREATE TABLE available_policies (policy_type_code VARCHAR, policy_id VARCHAR); CREATE TABLE customers_policies (customer_id VARCHAR, policy_id VARCHAR)

SELECT DISTINCT t3.policy_type_code FROM customers AS t1 JOIN customers_policies AS t2 ON t1.customer_id = t2.customer_id JOIN available_policies AS t3 ON t2.policy_id = t3.policy_id WHERE t1.customer_name = 'Dayana Robel';


Question: Who has the highest number of career home runs among players from Japan in Major League Baseball?

CREATE TABLE mlb_players (player_name VARCHAR(100), country VARCHAR(50), home_runs INT); INSERT INTO mlb_players VALUES ('Hideki Matsui', 'Japan', 175), ('Ichiro Suzuki', 'Japan', 117), ('Masahiro Tanaka', 'Japan', 1), ('Shohei Ohtani', 'Japan', 71);

SELECT player_name, home_runs FROM mlb_players WHERE country = 'Japan' ORDER BY home_runs DESC LIMIT 1;


Question: What is the total funding received by startups founded by individuals with disabilities in the fintech sector?

CREATE TABLE startups (id INT, name TEXT, industry TEXT, founding_date DATE, founders TEXT, funding FLOAT); INSERT INTO startups (id, name, industry, founding_date, founders, funding) VALUES (1, 'FintechForAll', 'Fintech', '2020-01-01', 'Individuals with disabilities', 3000000.0);

SELECT SUM(funding) FROM startups WHERE founders = 'Individuals with disabilities' AND industry = 'Fintech';


Question: Generate PostgreSQL SQL for: Which supercharger gear ratio has a Octane rating of 68?

CREATE TABLE table_name_22 (supercharger_gear_ratio VARCHAR, octane_rating VARCHAR)

SELECT supercharger_gear_ratio FROM table_name_22 WHERE octane_rating = '68';


Question: Generate PostgreSQL SQL for: List the name of all rooms sorted by their prices.

CREATE TABLE Rooms (roomName VARCHAR, basePrice VARCHAR)

SELECT roomName FROM Rooms ORDER BY basePrice;


Question: Generate PostgreSQL SQL for: Operation of find-min has what binary?

CREATE TABLE table_name_98 (binary VARCHAR, operation VARCHAR)

SELECT binary FROM table_name_98 WHERE operation = 'find-min';


Question: Generate PostgreSQL SQL for: What is the air date for the episode with production code ad1c13?

CREATE TABLE table_name_64 (original_air_date VARCHAR, production_code VARCHAR)

SELECT original_air_date FROM table_name_64 WHERE production_code = 'ad1c13';


Question: Generate PostgreSQL SQL for: How much Frequency MHz has a Call sign of w264bg?

CREATE TABLE table_name_95 (frequency_mhz VARCHAR, call_sign VARCHAR)

SELECT COUNT(frequency_mhz) FROM table_name_95 WHERE call_sign = 'w264bg';


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

INSERT INTO tr_sub(path) VALUES ('2-top-1...--#1');

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


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

CREATE FUNCTION customer_credit(int) RETURNS text
    AS 'SELECT regexp_replace(ccredit, ''-[0-9]+$'', ''-????'') FROM customer WHERE cid = $1'
    LANGUAGE sql;

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


Question: Show total sales revenue for recycled products in the last month.

CREATE TABLE products (product_id INT, name VARCHAR(255), recycled_materials BOOLEAN); INSERT INTO products (product_id, name, recycled_materials) VALUES (1, 'Recycled Notebook', TRUE), (2, 'Plastic Phone Case', FALSE); CREATE TABLE sales (sale_id INT, product_id INT, sale_price DECIMAL(10, 2), sale_date DATE); INSERT INTO sales (sale_id, product_id, sale_price, sale_date) VALUES (1, 1, 12.99, '2022-12-05'), (2, 2, 5.99, '2022-11-10'), (3, 1, 12.99, '2022-12-20');

SELECT SUM(sale_price) FROM products JOIN sales ON products.product_id = sales.product_id WHERE recycled_materials = TRUE AND sale_date BETWEEN '2022-12-01' AND '2022-12-31';


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

SELECT *
  FROM citext_matview m
  FULL JOIN citext_table t ON (t.id = m.id AND t *= m)
  WHERE t.id IS NULL OR m.id IS NULL;

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


Question: Generate PostgreSQL SQL for: What is the lowest car number sponsored by UPS before 2001?

CREATE TABLE table_name_22 (car__number INTEGER, sponsor VARCHAR, season VARCHAR)

SELECT MIN(car__number) FROM table_name_22 WHERE sponsor = 'ups' AND season < 2001;


Question: Generate PostgreSQL SQL for: Who is the winning driver of the race on 2 June with a.z.k./roc-compétition a.z.k./roc-compétition as the winning team?

CREATE TABLE table_name_15 (winning_driver VARCHAR, winning_team VARCHAR, date VARCHAR)

SELECT winning_driver FROM table_name_15 WHERE winning_team = 'a.z.k./roc-compétition a.z.k./roc-compétition' AND date = '2 june';


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

-- Test trigger renaming on partitioned tables
create table grandparent (id int, primary key (id)) partition by range (id);

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


Question: Get the average mass (in kg) of spacecraft by country of origin.

CREATE TABLE spacecraft_mass_kg (spacecraft_name VARCHAR(50), country VARCHAR(50), mass FLOAT);

SELECT country, AVG(mass) as avg_mass_kg FROM spacecraft_mass_kg GROUP BY country;


Question: Generate PostgreSQL SQL for: what is the salary and name of the employee who has the most number of aircraft certificates?

CREATE TABLE Certificate (eid VARCHAR); CREATE TABLE Employee (name VARCHAR, salary VARCHAR, eid VARCHAR)

SELECT T1.name, T1.salary FROM Employee AS T1 JOIN Certificate AS T2 ON T1.eid = T2.eid GROUP BY T1.eid ORDER BY COUNT(*) DESC LIMIT 1;


Question: What is the total number of artworks by female artists in the 'Impressionist' movement?

CREATE TABLE Artists (ArtistID INT, Name VARCHAR(50), Gender VARCHAR(10), Nationality VARCHAR(50), ArtMovement VARCHAR(50)); INSERT INTO Artists (ArtistID, Name, Gender, Nationality, ArtMovement) VALUES (1, 'Claude Monet', 'Male', 'French', 'Impressionist'); INSERT INTO Artists (ArtistID, Name, Gender, Nationality, ArtMovement) VALUES (2, 'Berthe Morisot', 'Female', 'French', 'Impressionist');

SELECT COUNT(*) FROM Artists WHERE Gender = 'Female' AND ArtMovement = 'Impressionist';


Question: Generate PostgreSQL SQL for: How many years has 2 points?

CREATE TABLE table_name_85 (year INTEGER, points VARCHAR)

SELECT SUM(year) FROM table_name_85 WHERE points = 2;


Question: PL/pgSQL test: Plpgsql Simple (example 11).

-- make sure flushing local caches changes nothing
\c -

select simplecaller();

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


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

CREATE TABLE table_name_93 (score VARCHAR, date VARCHAR)

SELECT score FROM table_name_93 WHERE date = '2000-05-23';


Question: What is the total area of all community gardens in New York City?

CREATE TABLE community_gardens (garden_id INT, name TEXT, location TEXT, area REAL, city TEXT, state TEXT, zip_code TEXT); INSERT INTO community_gardens (garden_id, name, location, area, city, state, zip_code) VALUES (1, 'Green Oasis', '123 Main St', 0.25, 'New York', 'NY', '10001');

SELECT SUM(area) FROM community_gardens WHERE city = 'New York' AND state = 'NY';


Question: Write the DDL statement from PostgreSQL regression test 'copy2' (example 194).

CREATE TABLE rls_t1 (a int, b int, c int);

Explanation: DDL from PostgreSQL core regression test for Copy2.


Question: Write the DML statement from PostgreSQL regression test 'create_index' (example 227).

INSERT INTO concur_heap VALUES  ('a','b');

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


Question: How many games were sold in each region in the 'sales' schema?

CREATE TABLE sales.games (id INT, title VARCHAR(50), region VARCHAR(20), units_sold INT);

SELECT region, SUM(units_sold) AS total_units_sold FROM sales.games GROUP BY region;


Question: Show companies with a diversity score above the industry average

CREATE TABLE companies (id INT, name VARCHAR(50), industry VARCHAR(50), diversity_score DECIMAL(3,2)); INSERT INTO companies VALUES (1, 'Acme Corp', 'Technology', 0.85); INSERT INTO companies VALUES (2, 'Beta Inc', 'Retail', 0.70);

SELECT companies.name, companies.diversity_score FROM companies INNER JOIN (SELECT industry, AVG(diversity_score) AS industry_avg FROM companies GROUP BY industry) AS industry_averages ON companies.industry = industry_averages.industry WHERE companies.diversity_score > industry_averages.industry_avg;


Question: Delete records in the menu_items table where the item_name is 'Chicken Caesar Salad' AND price is greater than 12.00

CREATE TABLE menu_items (item_name VARCHAR(255), price DECIMAL(5,2));

DELETE FROM menu_items WHERE item_name = 'Chicken Caesar Salad' AND price > 12.00;


Question: Generate PostgreSQL SQL for: What was the highest Pick # for the College of Simon Fraser?

CREATE TABLE table_name_14 (pick__number INTEGER, college VARCHAR)

SELECT MAX(pick__number) FROM table_name_14 WHERE college = 'simon fraser';


Question: Find the number of unique IP addresses involved in each type of attack, for the last month?

SELECT attack_type, COUNT(DISTINCT ip_address) as unique_ip_addresses FROM attacks WHERE attack_date >= DATEADD(month, -1, GETDATE()) GROUP BY attack_type;


Question: Generate PostgreSQL SQL for: What is the phone and email for customer with first name Aniyah and last name Feest?

CREATE TABLE Customers (customer_phone VARCHAR, customer_email VARCHAR, customer_first_name VARCHAR, customer_last_name VARCHAR)

SELECT customer_phone, customer_email FROM Customers WHERE customer_first_name = 'Aniyah' AND customer_last_name = 'Feest';


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

CREATE VIEW xmlview4 AS SELECT xmlelement(name employee, xmlforest(name, age, salary as pay)) FROM emp;

Explanation: DDL from PostgreSQL core regression test for Xml.


Question: What is the total number of animals adopted by each community education program?

CREATE TABLE community_education_programs (id INT, name VARCHAR(255), city VARCHAR(255)); INSERT INTO community_education_programs (id, name, city) VALUES (1, 'Wildlife Wonders', 'San Francisco'), (2, 'Nature Nurturers', 'New York'), (3, 'Eco Explorers', 'Los Angeles'); CREATE TABLE animal_adoptions (id INT, program_id INT, animal_id INT);

SELECT cep.name, COUNT(aa.id) AS total_adoptions FROM community_education_programs cep JOIN animal_adoptions aa ON cep.id = aa.program_id GROUP BY cep.name;


Question: Generate PostgreSQL SQL for: What is the sum of all crowds present at the Glenferrie Oval venue?

CREATE TABLE table_name_35 (crowd INTEGER, venue VARCHAR)

SELECT SUM(crowd) FROM table_name_35 WHERE venue = 'glenferrie oval';


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

create table agg_group_2 as
select * from
  (values (100), (300), (500)) as r(a),
  lateral (
    select (g/2)::numeric as c1,
           array_agg(g::numeric) as c2,
	   count(*) as c3
    from agg_data_2k
    where g < r.a
    group by g/2) as s;

Explanation: DDL from PostgreSQL core regression test for Aggregates.


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

CREATE FUNCTION make_valid(ismn13)
	RETURNS ismn13
	AS 'MODULE_PATHNAME'
	LANGUAGE C
	IMMUTABLE STRICT
	PARALLEL SAFE;

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


Question: How many natural disasters were reported in the state of Florida in 2019?

CREATE TABLE natural_disasters (id INT, state VARCHAR(255), year INT, number_of_disasters INT); INSERT INTO natural_disasters (id, state, year, number_of_disasters) VALUES (1, 'Florida', 2019, 50), (2, 'California', 2019, 75);

SELECT SUM(number_of_disasters) FROM natural_disasters WHERE state = 'Florida' AND year = 2019;


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

SELECT cube_ll_coord(ll_to_earth(90,180),1)::numeric(20,5),
 cube_ll_coord(ll_to_earth(90,180),2)::numeric(20,5),
 cube_ll_coord(ll_to_earth(90,180),3)::numeric(20,5);

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


Question: How many security incidents were reported in the education sector in the last month?

CREATE TABLE incidents (incident_id INT, incident_date DATE, incident_sector VARCHAR(255));

SELECT COUNT(*) FROM incidents WHERE incident_sector = 'Education' AND incident_date >= DATEADD(month, -1, GETDATE());


Question: Generate PostgreSQL SQL for: What was the score against fabrice martin?

CREATE TABLE table_name_66 (score VARCHAR, opponent VARCHAR)

SELECT score FROM table_name_66 WHERE opponent = 'fabrice martin';


Question: Generate PostgreSQL SQL for: All players are position mark polak.

CREATE TABLE table_1013129_10 (position VARCHAR, player VARCHAR)

SELECT position FROM table_1013129_10 WHERE player = 'Mark Polak';


Question: Insert new record of military equipment sale to 'South America' in 2021

CREATE TABLE military_sales_3 (id INT, region VARCHAR, year INT, value FLOAT);

INSERT INTO military_sales_3 (id, region, year, value) VALUES (1, 'South America', 2021, 500000);


Question: What is the average production quantity for wells in the 'onshore' category?

CREATE TABLE wells (id INT, name VARCHAR(255), category VARCHAR(255), production_quantity INT); INSERT INTO wells (id, name, category, production_quantity) VALUES (1, 'Well A', 'onshore', 1000), (2, 'Well B', 'offshore', 2000), (3, 'Well C', 'onshore', 1500);

SELECT AVG(production_quantity) FROM wells WHERE category = 'onshore';


Question: List the names and prices of menu items that are not offered at any restaurant located in 'New York'.

CREATE TABLE restaurants (restaurant_id INT, name VARCHAR(255), cuisine VARCHAR(255), location VARCHAR(255)); INSERT INTO restaurants (restaurant_id, name, cuisine, location) VALUES (1, 'Big Burger', 'American', 'New York'); INSERT INTO restaurants (restaurant_id, name, cuisine, location) VALUES (2, 'Sushi Hana', 'Japanese', 'California'); INSERT INTO restaurants (restaurant_id, name, cuisine, location) VALUES (3, 'Taco Time', 'Mexican', 'Texas'); CREATE TABLE menu_items (menu_item_id INT, name VARCHAR(255), price DECIMAL(5,2), restaurant_id INT); INSERT INTO menu_items (menu_item_id, name, price, restaurant_id) VALUES (1, 'Big Burger', 12.99, 1); INSERT INTO menu_items (menu_item_id, name, price, restaurant_id) VALUES (2, 'Chicken Teriyaki', 15.99, 2); INSERT INTO menu_items (menu_item_id, name, price, restaurant_id) VALUES (3, 'Garden Salad', 7.99, 1); INSERT INTO menu_items (menu_item_id, name, price, restaurant_id) VALUES (4, 'Sushi Roll', 18.99, 2); INSERT INTO menu_items (menu_item_id, name, price, restaurant_id) VALUES (5, 'Taco', 6.99, 3); INSERT INTO menu_items (menu_item_id, name, price, restaurant_id) VALUES (6, 'Nachos', 8.99, 3); INSERT INTO menu_items (menu_item_id, name, price, restaurant_id) VALUES (7, 'Pizza', 10.99, NULL);

SELECT name, price FROM menu_items WHERE menu_item_id NOT IN (SELECT menu_items.restaurant_id FROM menu_items JOIN restaurants ON menu_items.restaurant_id = restaurants.restaurant_id WHERE restaurants.location = 'New York') AND restaurant_id IS NULL;


Question: Generate PostgreSQL SQL for: Who was the opponent in which the bout ended in round 2?

CREATE TABLE table_name_71 (opponent VARCHAR, round VARCHAR)

SELECT opponent FROM table_name_71 WHERE round = 2;


Question: Who is the fastest athlete in each sport?

CREATE TABLE athletes (sport VARCHAR(50), name VARCHAR(50), time FLOAT); INSERT INTO athletes (sport, name, time) VALUES ('Swimming', 'Smith', 23.45), ('Swimming', 'Jones', 22.67), ('Athletics', 'Brown', 9.87), ('Athletics', 'Williams', 9.81);

SELECT sport, name, MIN(time) AS fastest_time  FROM athletes  GROUP BY sport;


Question: Generate PostgreSQL SQL for: What is the time of the 100m freestyle event?

CREATE TABLE table_name_54 (time VARCHAR, event VARCHAR)

SELECT time FROM table_name_54 WHERE event = '100m freestyle';


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

END$$;
CREATE MATERIALIZED VIEW sro_index_mv AS SELECT 1 AS c;
CREATE UNIQUE INDEX ON sro_index_mv (c) WHERE unwanted_grant_nofail(1) > 0;
\c -
REFRESH MATERIALIZED VIEW CONCURRENTLY sro_index_mv;
REFRESH MATERIALIZED VIEW sro_index_mv;

DROP OWNED BY regress_sro_user;
DROP ROLE regress_sro_user;

-- Admin options

SET SESSION AUTHORIZATION regress_priv_user4;
CREATE FUNCTION dogrant_ok() RETURNS void LANGUAGE sql SECURITY DEFINER AS
	'GRANT regress_priv_group2 TO regress_priv_user5';
GRANT regress_priv_group2 TO regress_priv_user5; -- ok: had ADMIN OPTION
SET ROLE regress_priv_group2;
GRANT regress_priv_group2 TO regress_priv_user5; -- fails: SET ROLE suspended privilege

SET SESSION AUTHORIZATION regress_priv_user1;
GRANT regress_priv_group2 TO regress_priv_user5; -- fails: no ADMIN OPTION
SELECT dogrant_ok();			-- ok: SECURITY DEFINER conveys ADMIN
SET ROLE regress_priv_group2;
GRANT regress_priv_group2 TO regress_priv_user5; -- fails: SET ROLE did not help

SET SESSION AUTHORIZATION regress_priv_group2;
GRANT regress_priv_group2 TO regress_priv_user5; -- fails: no self-admin

SET SESSION AUTHORIZATION regress_priv_user4;
DROP FUNCTION dogrant_ok();
REVOKE regress_priv_group2 FROM regress_priv_user5;

-- has_sequence_privilege tests
\c -

CREATE SEQUENCE x_seq;

GRANT USAGE on x_seq to regress_priv_user2;

SELECT has_sequence_privilege('regress_priv_user1', 'atest1', 'SELECT');
SELECT has_sequence_privilege('regress_priv_user1', 'x_seq', 'INSERT');
SELECT has_sequence_privilege('regress_priv_user1', 'x_seq', 'SELECT');

SET SESSION AUTHORIZATION regress_priv_user2;

SELECT has_sequence_privilege('x_seq', 'USAGE');

-- largeobject privilege tests
\c -
SET SESSION AUTHORIZATION regress_priv_user1;

SELECT lo_create(1001);
SELECT lo_create(1002);
SELECT lo_create(1003);
SELECT lo_create(1004);
SELECT lo_create(1005);

GRANT ALL ON LARGE OBJECT 1001 TO PUBLIC;
GRANT SELECT ON LARGE OBJECT 1003 TO regress_priv_user2;
GRANT SELECT,UPDATE ON LARGE OBJECT 1004 TO regress_priv_user2;
GRANT ALL ON LARGE OBJECT 1005 TO regress_priv_user2;
GRANT SELECT ON LARGE OBJECT 1005 TO regress_priv_user2 WITH GRANT OPTION;

GRANT SELECT, INSERT ON LARGE OBJECT 1001 TO PUBLIC;	-- to be failed
GRANT SELECT, UPDATE ON LARGE OBJECT 1001 TO nosuchuser;	-- to be failed
GRANT SELECT, UPDATE ON LARGE OBJECT  999 TO PUBLIC;	-- to be failed

\c -
SET SESSION AUTHORIZATION regress_priv_user2;

SELECT lo_create(2001);
SELECT lo_create(2002);

SELECT loread(lo_open(1001, x'20000'::int), 32);	-- allowed, for now
SELECT lowrite(lo_open(1001, x'40000'::int), 'abcd');	-- fail, wrong mode

SELECT loread(lo_open(1001, x'40000'::int), 32);
SELECT loread(lo_open(1002, x'40000'::int), 32);	-- to be denied
SELECT loread(lo_open(1003, x'40000'::int), 32);
SELECT loread(lo_open(1004, x'40000'::int), 32);

SELECT lowrite(lo_open(1001, x'20000'::int), 'abcd');
SELECT lowrite(lo_open(1002, x'20000'::int), 'abcd');	-- to be denied
SELECT lowrite(lo_open(1003, x'20000'::int), 'abcd');	-- to be denied
SELECT lowrite(lo_open(1004, x'20000'::int), 'abcd');

GRANT SELECT ON LARGE OBJECT 1005 TO regress_priv_user3;
GRANT UPDATE ON LARGE OBJECT 1006 TO regress_priv_user3;	-- to be denied
REVOKE ALL ON LARGE OBJECT 2001, 2002 FROM PUBLIC;
GRANT ALL ON LARGE OBJECT 2001 TO regress_priv_user3;

SELECT lo_unlink(1001);		-- to be denied
SELECT lo_unlink(2002);

\c -
-- confirm ACL setting
SELECT oid, pg_get_userbyid(lomowner) ownername, lomacl FROM pg_largeobject_metadata WHERE oid >= 1000 AND oid < 3000 ORDER BY oid;

SET SESSION AUTHORIZATION regress_priv_user3;

SELECT loread(lo_open(1001, x'40000'::int), 32);
SELECT loread(lo_open(1003, x'40000'::int), 32);	-- to be denied
SELECT loread(lo_open(1005, x'40000'::int), 32);

SELECT lo_truncate(lo_open(1005, x'20000'::int), 10);	-- to be denied
SELECT lo_truncate(lo_open(2001, x'20000'::int), 10);

\c -
-- confirm role with privileges of pg_read_all_data can read large objects
SET SESSION AUTHORIZATION regress_priv_user6;

SELECT loread(lo_open(1002, x'40000'::int), 32);
SELECT lo_get(1002);
SELECT lowrite(lo_open(1002, x'20000'::int), 'abcd');	-- to be denied
SELECT lo_put(1002, 1, 'abcd');							-- to be denied
SELECT lo_truncate(lo_open(1002, x'20000'::int), 0);	-- to be denied
SELECT lo_unlink(1002);									-- to be denied

\c -
-- confirm role with privileges of pg_write_all_data can write large objects
GRANT SELECT ON LARGE OBJECT 1002 TO regress_priv_user7;
SET SESSION AUTHORIZATION regress_priv_user7;

SELECT lowrite(lo_open(1002, x'20000'::int), 'abcd');
SELECT lo_put(1002, 1, 'abcd');
SELECT lo_truncate(lo_open(1002, x'20000'::int), 0);
SELECT lo_unlink(1002);									-- to be denied

-- has_largeobject_privilege function

-- superuser
\c -
SELECT has_largeobject_privilege(1001, 'SELECT');
SELECT has_largeobject_privilege(1002, 'SELECT');
SELECT has_largeobject_privilege(1003, 'SELECT');
SELECT has_largeobject_privilege(1004, 'SELECT');

SELECT has_largeobject_privilege(1001, 'UPDATE');
SELECT has_largeobject_privilege(1002, 'UPDATE');
SELECT has_largeobject_privilege(1003, 'UPDATE');
SELECT has_largeobject_privilege(1004, 'UPDATE');

-- not-existing large object
SELECT has_largeobject_privilege(9999, 'SELECT');	-- NULL

-- non-superuser
SET SESSION AUTHORIZATION regress_priv_user2;
SELECT has_largeobject_privilege(1001, 'SELECT');
SELECT has_largeobject_privilege(1002, 'SELECT');	-- false
SELECT has_largeobject_privilege(1003, 'SELECT');
SELECT has_largeobject_privilege(1004, 'SELECT');

SELECT has_largeobject_privilege(1001, 'UPDATE');
SELECT has_largeobject_privilege(1002, 'UPDATE');	-- false
SELECT has_largeobject_privilege(1003, 'UPDATE');	-- false
SELECT has_largeobject_privilege(1004, 'UPDATE');

SELECT has_largeobject_privilege('regress_priv_user3', 1001, 'SELECT');
SELECT has_largeobject_privilege('regress_priv_user3', 1003, 'SELECT');	-- false
SELECT has_largeobject_privilege('regress_priv_user3', 1005, 'SELECT');

SELECT has_largeobject_privilege('regress_priv_user3', 1005, 'UPDATE');	-- false
SELECT has_largeobject_privilege('regress_priv_user3', 2001, 'UPDATE');

-- compatibility mode in largeobject permission
\c -
SET lo_compat_privileges = false;	-- default setting
SET SESSION AUTHORIZATION regress_priv_user4;

SELECT has_largeobject_privilege(1002, 'SELECT'); -- false
SELECT has_largeobject_privilege(1002, 'UPDATE'); -- false

SELECT loread(lo_open(1002, x'40000'::int), 32);	-- to be denied
SELECT lowrite(lo_open(1002, x'20000'::int), 'abcd');	-- to be denied
SELECT lo_truncate(lo_open(1002, x'20000'::int), 10);	-- to be denied
SELECT lo_put(1002, 1, 'abcd');				-- to be denied
SELECT lo_unlink(1002);					-- to be denied
SELECT lo_export(1001, '/dev/null');			-- to be denied
SELECT lo_import('/dev/null');				-- to be denied
SELECT lo_import('/dev/null', 2003);			-- to be denied

\c -
SET lo_compat_privileges = true;	-- compatibility mode
SET SESSION AUTHORIZATION regress_priv_user4;

SELECT has_largeobject_privilege(1002, 'SELECT'); -- true
SELECT has_largeobject_privilege(1002, 'UPDATE'); -- true

SELECT loread(lo_open(1002, x'40000'::int), 32);
SELECT lowrite(lo_open(1002, x'20000'::int), 'abcd');
SELECT lo_truncate(lo_open(1002, x'20000'::int), 10);
SELECT lo_unlink(1002);
SELECT lo_export(1001, '/dev/null');			-- to be denied

-- don't allow unpriv users to access pg_largeobject contents
\c -
SELECT * FROM pg_largeobject LIMIT 0;

SET SESSION AUTHORIZATION regress_priv_user1;
SELECT * FROM pg_largeobject LIMIT 0;			-- to be denied

-- pg_signal_backend can't signal superusers
RESET SESSION AUTHORIZATION;
BEGIN;
CREATE OR REPLACE FUNCTION terminate_nothrow(pid int) RETURNS bool
	LANGUAGE plpgsql SECURITY DEFINER SET client_min_messages = error AS $$
BEGIN
	RETURN pg_terminate_backend($1);

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


Question: Generate PostgreSQL SQL for: What is the highest number of losses with 23 points and 22 plays?

CREATE TABLE table_name_58 (lost INTEGER, points VARCHAR, played VARCHAR)

SELECT MAX(lost) FROM table_name_58 WHERE points = 23 AND played > 22;


Question: What is the total number of mental health parity violation incidents by state?

CREATE TABLE mental_health_parity (state VARCHAR(2), incidents INT); INSERT INTO mental_health_parity (state, incidents) VALUES ('CA', 120), ('NY', 150), ('TX', 80);

SELECT state, SUM(incidents) FROM mental_health_parity GROUP BY state;


Question: Display the names and fairness scores of models that have a higher fairness score than the average fairness score.

CREATE TABLE model_fairness (model_id INT, fairness_score DECIMAL(3,2)); INSERT INTO model_fairness (model_id, fairness_score) VALUES (1, 0.85), (2, 0.70), (3, 0.92), (4, 0.68), (5, 0.89);

SELECT model_id, fairness_score FROM model_fairness WHERE fairness_score > (SELECT AVG(fairness_score) FROM model_fairness);


Question: Generate PostgreSQL SQL for: I want the total number of rank for Grid less than 20 and dick rathmann and Qual more than 130.92

CREATE TABLE table_name_73 (rank VARCHAR, qual VARCHAR, grid VARCHAR, driver VARCHAR)

SELECT COUNT(rank) FROM table_name_73 WHERE grid < 20 AND driver = 'dick rathmann' AND qual > 130.92;


Question: PostgreSQL Plpgsql: show example 3.

quantity integer DEFAULT 32; url varchar := 'http://mysite.com'; transaction_time CONSTANT timestamp with time zone := now();

Explanation: Example from PostgreSQL documentation on Plpgsql.


Question: Generate PostgreSQL SQL for: What is the abbreviation of the district of Mahbubnagar?

CREATE TABLE table_1610301_1 (code VARCHAR, district VARCHAR)

SELECT code FROM table_1610301_1 WHERE district = 'Mahbubnagar';


Question: Generate PostgreSQL SQL for: What is the score of the away team that played Essendon?

CREATE TABLE table_name_98 (away_team VARCHAR, home_team VARCHAR)

SELECT away_team AS score FROM table_name_98 WHERE home_team = 'essendon';


Question: What are the names and annual revenues of all cultural heritage sites located in Tokyo, Japan?

CREATE TABLE Cultural_Heritage_Sites (id INT, name VARCHAR(255), location VARCHAR(255), year_established INT, PRIMARY KEY(id)); INSERT INTO Cultural_Heritage_Sites (id, name, location, year_established) VALUES (1, 'Todai-ji Temple', 'Nara, Japan', 745);

SELECT c.name, c.annual_revenue FROM Cultural_Heritage_Sites c WHERE c.location = 'Tokyo, Japan';


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

CREATE OPERATOR CLASS gin__int_ops
FOR TYPE _int4 USING gin
AS
	OPERATOR	3	&&,
	OPERATOR	6	= (anyarray, anyarray),
	OPERATOR	7	@>,
	OPERATOR	8	<@,
	OPERATOR	13	@,
	OPERATOR	14	~,
	OPERATOR	20	@@ (_int4, query_int),
	FUNCTION	1	btint4cmp (int4, int4),
	FUNCTION	2	ginarrayextract (anyarray, internal, internal),
	FUNCTION	3	ginint4_queryextract (_int4, internal, int2, internal, internal, internal, internal),
	FUNCTION	4	ginint4_consistent (internal, int2, _int4, int4, internal, internal, internal, internal),
	STORAGE		int4;


Question: Generate PostgreSQL SQL for: What team got a draft pick player from McGill?

CREATE TABLE table_25085059_3 (cfl_team VARCHAR, college VARCHAR)

SELECT cfl_team FROM table_25085059_3 WHERE college = 'McGill';


Question: Generate PostgreSQL SQL for: What was the bleeding time during the prolonged partial thromboplastin time in which the prothrombin time is unaffected?

CREATE TABLE table_238124_1 (bleeding_time VARCHAR, partial_thromboplastin_time VARCHAR, prothrombin_time VARCHAR)

SELECT bleeding_time FROM table_238124_1 WHERE partial_thromboplastin_time = 'Prolonged' AND prothrombin_time = 'Unaffected';


Question: Generate PostgreSQL SQL for: What method has randy couture as the opponent?

CREATE TABLE table_name_15 (method VARCHAR, opponent VARCHAR)

SELECT method FROM table_name_15 WHERE opponent = 'randy couture';


Question: Delete records in landfill_capacity table where capacity is greater than 30000 tons

CREATE TABLE landfill_capacity (location VARCHAR(50), capacity INT);

DELETE FROM landfill_capacity WHERE capacity > 30000;


Question: Generate PostgreSQL SQL for: Find the maximum and total number of followers of all users.

CREATE TABLE user_profiles (followers INTEGER)

SELECT MAX(followers), SUM(followers) FROM user_profiles;


Question: Find the total revenue for each music genre in the current month.

CREATE TABLE music_revenue (song VARCHAR(255), genre VARCHAR(255), revenue INT, revenue_date DATE); INSERT INTO music_revenue (song, genre, revenue, revenue_date) VALUES ('Song1', 'Genre1', 5000000, '2022-02-01'), ('Song2', 'Genre2', 7000000, '2022-02-02'), ('Song3', 'Genre1', 6000000, '2022-02-03'), ('Song4', 'Genre2', 8000000, '2022-02-04'); ALTER TABLE music_revenue ADD CONSTRAINT chk_revenue_date CHECK (revenue_date >= DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0));

SELECT genre, SUM(revenue) as total_revenue FROM music_revenue GROUP BY genre ORDER BY total_revenue DESC;


Question: Generate PostgreSQL SQL for: How many goals were scored when they had over 28 points and played over 18 games?

CREATE TABLE table_name_33 (goals_scored INTEGER, points VARCHAR, played VARCHAR)

SELECT MAX(goals_scored) FROM table_name_33 WHERE points > 28 AND played > 18;


Question: Generate PostgreSQL SQL for: How many goals were scored by Eugene Galeković?

CREATE TABLE table_name_54 (goals VARCHAR, player VARCHAR)

SELECT goals FROM table_name_54 WHERE player = 'eugene galeković';


Question: PostgreSQL regression test 'aggregates': Write the SELECT query (example 283).

select aggfstr(distinct a,b,c order by b)
  from (values (1,3,'foo'),(0,null,null),(2,2,'bar'),(3,1,'baz')) v(a,b,c),
       generate_series(1,3) i;

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

SELECT count(*) FROM (select aggfstr(distinct a,b,c order by b)
  from (values (1,3,'foo'),(0,null,null),(2,2,'bar'),(3,1,'baz')) v(a,b,c),
       generate_series(1,3) i) AS _sub;


Question: What is the total quantity of organic cotton and recycled polyester used in our sustainable clothing line?

CREATE TABLE Fabrics (FabricID INT, FabricName TEXT, IsSustainable BOOLEAN, Quantity INT); INSERT INTO Fabrics (FabricID, FabricName, IsSustainable, Quantity) VALUES (1, 'Organic Cotton', TRUE, 1000), (2, 'Recycled Polyester', TRUE, 800), (3, 'Hemp', TRUE, 700), (4, 'Polyester', FALSE, 500);

SELECT SUM(Quantity) FROM Fabrics WHERE (FabricName = 'Organic Cotton' OR FabricName = 'Recycled Polyester') AND IsSustainable = TRUE;


Question: List all community policing initiatives in the state of Texas.

CREATE TABLE community_policing (id INT, state VARCHAR(20), initiative VARCHAR(50)); INSERT INTO community_policing (id, state, initiative) VALUES (1, 'Texas', 'Neighborhood Watch'), (2, 'California', 'Coffee with a Cop'), (3, 'Texas', 'Citizens Police Academy');

SELECT initiative FROM community_policing WHERE state = 'Texas';


Question: Generate PostgreSQL SQL for: What is every year when the reporters were Lesley Visser and Robin Roberts?

CREATE TABLE table_22654139_3 (year VARCHAR, reporters VARCHAR)

SELECT year FROM table_22654139_3 WHERE reporters = 'Lesley Visser and Robin Roberts';


Question: Show a SQL definition from the citus project (pg13, item 25).

-- row suffix notation works fine
CREATE TABLE ab (a int, b int);

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


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

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

SELECT count(*) FROM (SELECT tanh(float8 'infinity')) AS _sub;


Question: Find the number of defense contracts awarded per quarter in the 'defense_contracts' table

CREATE TABLE defense_contracts (contract_id INT, company_name VARCHAR(100), contract_value DECIMAL(10, 2), contract_date DATE);

SELECT EXTRACT(QUARTER FROM contract_date) as quarter, COUNT(*) as num_contracts FROM defense_contracts GROUP BY quarter;


Question: List all green building materials and the number of each material used in a specific city, for projects in London.

CREATE TABLE GreenBuildingMaterials (MaterialID INT, MaterialName VARCHAR(50));CREATE TABLE GreenBuildingMaterialsUsage (UsageID INT, MaterialID INT, CityID INT, ProjectID INT);

SELECT GreenBuildingMaterials.MaterialName, COUNT(GreenBuildingMaterialsUsage.UsageID) FROM GreenBuildingMaterials INNER JOIN GreenBuildingMaterialsUsage ON GreenBuildingMaterials.MaterialID = GreenBuildingMaterialsUsage.MaterialID WHERE GreenBuildingMaterialsUsage.CityID = 2 GROUP BY GreenBuildingMaterials.MaterialName;


Question: Show the total claim amounts for policyholders in California who made claims in the last 3 months.

CREATE TABLE Claims (ClaimID INT, PolicyID INT, ClaimAmount DECIMAL(5,2), ClaimDate DATE); INSERT INTO Claims (ClaimID, PolicyID, ClaimAmount, ClaimDate) VALUES (1, 1, 500, '2020-01-01'); INSERT INTO Claims (ClaimID, PolicyID, ClaimAmount, ClaimDate) VALUES (2, 1, 750, '2020-02-01'); INSERT INTO Claims (ClaimID, PolicyID, ClaimAmount, ClaimDate) VALUES (3, 2, 400, '2020-03-01'); CREATE TABLE Policyholders (PolicyID INT, PolicyholderName VARCHAR(50), State VARCHAR(2)); INSERT INTO Policyholders (PolicyID, PolicyholderName, State) VALUES (1, 'Maria Rodriguez', 'California'); INSERT INTO Policyholders (PolicyID, PolicyholderName, State) VALUES (2, 'David Kim', 'California');

SELECT PolicyholderName, SUM(ClaimAmount) FROM Claims JOIN Policyholders ON Claims.PolicyID = Policyholders.PolicyID WHERE Policyholders.State = 'California' AND ClaimDate >= DATEADD(month, -3, CURRENT_DATE) GROUP BY PolicyholderName;


Question: Show a query using PostgreSQL contrib extension 'pg_visibility' (example 43).

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


Question: PostgreSQL regression test 'partition_info': Write the SELECT query (example 60).

SELECT * FROM pg_partition_tree('ptif_test_matview');

Explanation: Regression test for Partition Info in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT * FROM pg_partition_tree('ptif_test_matview')) AS _sub;


Question: Write the DML statement from PostgreSQL regression test 'path' (example 10).

INSERT INTO PATH_TBL VALUES ('( 11,12,13,14) ');

Explanation: DML from PostgreSQL core regression test for Path.


Question: What is the total number of hours volunteered in all programs?

CREATE TABLE volunteers (id INT, name TEXT, program TEXT, hours INT); INSERT INTO volunteers (id, name, program, hours) VALUES (1, 'John Doe', 'Food Distribution', 10), (2, 'Jane Smith', 'Education Support', 20);


Question: What is the explainability score for each AI safety concern?

CREATE TABLE AISafety (id INT, concern VARCHAR(255), explainability_score DECIMAL(5,2)); INSERT INTO AISafety (id, concern, explainability_score) VALUES (1, 'Data Privacy', 78.91), (2, 'Unintended Consequences', 65.23), (3, 'Bias', 82.34);

SELECT concern, AVG(explainability_score) as avg_explainability_score FROM AISafety GROUP BY concern;


Question: Generate PostgreSQL SQL for: What is the 2000 value if the 1998 value is 1.5?

SELECT 2000 FROM table_name_5 WHERE 1998 = '1.5';


Question: What is the earliest date a 'subway' station was cleaned?

CREATE TABLE public.cleaning (cleaning_id SERIAL PRIMARY KEY, cleaning_type VARCHAR(20), cleaning_date DATE, station_id INTEGER, FOREIGN KEY (station_id) REFERENCES public.station(station_id)); INSERT INTO public.cleaning (cleaning_type, cleaning_date, station_id) VALUES ('routine cleaning', '2022-03-03', 1), ('deep cleaning', '2022-03-15', 2);

SELECT MIN(cleaning_date) FROM public.cleaning INNER JOIN public.station ON public.cleaning.station_id = public.station.station_id WHERE route_type = 'subway';


Question: Which country has the most hotels in the 'Global_Hotels' table?

CREATE TABLE Global_Hotels (country VARCHAR(50), hotel_count INT); INSERT INTO Global_Hotels (country, hotel_count) VALUES ('USA', 5000), ('Canada', 1000), ('Mexico', 2000);

SELECT country, MAX(hotel_count) FROM Global_Hotels;


Question: What is the average monthly donation per donor for the last 12 months?

CREATE TABLE donors (id INT, name VARCHAR(255)); CREATE TABLE donations (id INT, donor_id INT, donation_date DATE, amount DECIMAL(10, 2));

SELECT AVG(donations.amount) FROM donations JOIN donors ON donations.donor_id = donors.id WHERE donations.donation_date BETWEEN DATE_SUB(CURRENT_DATE, INTERVAL 12 MONTH) AND CURRENT_DATE GROUP BY EXTRACT(MONTH FROM donations.donation_date);


Question: Show a SQL definition from the zombodb project (zombodb--3000.1.3--3000.1.4, item 2).

CREATE FUNCTION zdb.schema_version() RETURNS text LANGUAGE sql AS $$
SELECT '3000.1.4 (759bfe45fe5b8ee13cdb0100dc49eff9e6dd116a)'
$$;

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