Question: List the number of research grants awarded to each department in the past year.

CREATE TABLE Departments(DepartmentID INT, Department VARCHAR(255)); INSERT INTO Departments VALUES (1, 'Computer Science'); CREATE TABLE ResearchGrants(GranteeID INT, DepartmentID INT, GrantAmount DECIMAL(10, 2), GrantDate DATE); INSERT INTO ResearchGrants VALUES (1, 1, 50000.00, '2021-01-01');

SELECT Departments.Department, COUNT(ResearchGrants.GranteeID) FROM Departments INNER JOIN ResearchGrants ON Departments.DepartmentID = ResearchGrants.DepartmentID WHERE ResearchGrants.GrantDate >= DATEADD(year, -1, GETDATE()) GROUP BY Departments.Department;


Question: Generate PostgreSQL SQL for: How many districts does william b. oliver represent?

CREATE TABLE table_1342359_2 (district VARCHAR, incumbent VARCHAR)

SELECT COUNT(district) FROM table_1342359_2 WHERE incumbent = 'William B. Oliver';


Question: List the names of all regulatory frameworks in the database.

CREATE TABLE regulatory_frameworks (framework_id serial, framework_name varchar(20)); INSERT INTO regulatory_frameworks (framework_id, framework_name) VALUES (1, 'GDPR'), (2, 'HIPAA'), (3, 'PCI-DSS');

SELECT framework_name FROM regulatory_frameworks;


Question: Generate PostgreSQL SQL for: What was the operator of the ensemble from Yorkshire?

CREATE TABLE table_name_89 (operator VARCHAR, region VARCHAR)

SELECT operator FROM table_name_89 WHERE region = 'yorkshire';


Question: What is the maximum price of natural makeup products sold in Germany?

CREATE TABLE MakeupProducts(productId INT, productName VARCHAR(100), isNatural BOOLEAN, country VARCHAR(50), price DECIMAL(5,2)); INSERT INTO MakeupProducts(productId, productName, isNatural, country, price) VALUES (1, 'Mineral Foundation', true, 'Germany', 34.99), (2, 'Shea Butter Mascara', true, 'Germany', 19.99);

SELECT MAX(price) FROM MakeupProducts WHERE isNatural = true AND country = 'Germany';


Question: pgTAP test for Cmpok (assertion 5).

SELECT * FROM check_test(
    cmp_ok( ARRAY[1, 2], '=', ARRAY[1, 2]),
    true,
    'cmp_ok( int[], =, int[] )',
    '',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Cmpok.


Question: Find the maximum ocean acidification level measured in each monitoring station and the corresponding date.'

CREATE TABLE monitoring_stations (station_id TEXT, station_name TEXT);   CREATE TABLE measurements (measurement_id TEXT, station_id TEXT, acidification_level FLOAT, measurement_date DATE);

SELECT monitoring_stations.station_name, MAX(measurements.acidification_level), measurements.measurement_date   FROM monitoring_stations   JOIN measurements ON monitoring_stations.station_id = measurements.station_id   GROUP BY monitoring_stations.station_name;


Question: Generate PostgreSQL SQL for: How many total goals did the squad with 2 playoff apps, 2 FA Cup Apps, and 0 League Cup goals get?

CREATE TABLE table_name_88 (total_goals INTEGER, league_cup_goals VARCHAR, playoff_apps VARCHAR, fa_cup_apps VARCHAR)

SELECT SUM(total_goals) FROM table_name_88 WHERE playoff_apps = '2' AND fa_cup_apps = '2' AND league_cup_goals < 0;


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

create table parted_index_col_drop2 partition of parted_index_col_drop
  for values in (2) partition by list (a);

Explanation: DDL from PostgreSQL core regression test for Indexing.


Question: pgTAP test for Policy (assertion 71).

SELECT * FROM check_test(
    policy_cmd_is( 'public', 'passwd', 'root_all', 'all', 'whatever' ),
    true,
    'policy_cmd_is(schema, table, policy, command, desc) for ALL',
    'whatever',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Policy.


Question: What is the total cost of smart city technology adoptions in the city of Toronto?

CREATE TABLE smart_city_tech (tech_id INT, tech_name VARCHAR(30), city VARCHAR(20), cost DECIMAL(10,2)); INSERT INTO smart_city_tech (tech_id, tech_name, city, cost) VALUES (1, 'Smart Grids', 'Toronto', 5000000.00), (2, 'Smart Lighting', 'Montreal', 3000000.00), (3, 'Smart Traffic Management', 'Vancouver', 4000000.00);

SELECT SUM(cost) FROM smart_city_tech WHERE city = 'Toronto';


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

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


Question: Generate PostgreSQL SQL for: How many seats in 2001 with a quantity greater than 4?

CREATE TABLE table_name_17 (number_of_seats VARCHAR, year VARCHAR, quantity VARCHAR)

SELECT COUNT(number_of_seats) FROM table_name_17 WHERE year = '2001' AND quantity > 4;


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

--
-- These functions are used in tests that used to use md5(), which we now
-- mostly avoid so that the tests will pass in FIPS mode.
--

create function fipshash(bytea)
    returns text
    strict immutable parallel safe leakproof
    return substr(encode(sha256($1), 'hex'), 1, 32);

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


Question: Generate PostgreSQL SQL for: What is the Week when anke huber chanda rubin shows for Semi finalists, and the Runner-up is meredith mcgrath larisa savchenko?

CREATE TABLE table_name_2 (week_of VARCHAR, semi_finalists VARCHAR, runner_up VARCHAR)

SELECT week_of FROM table_name_2 WHERE semi_finalists = 'anke huber chanda rubin' AND runner_up = 'meredith mcgrath larisa savchenko';


Question: Insert a new sustainable sourcing record for restaurant 2 with a rating of 95. Use the sustainable_sourcing table.

CREATE TABLE sustainable_sourcing (restaurant_id INT, rating INT); INSERT INTO sustainable_sourcing (restaurant_id, rating) VALUES (2, 95);


Question: Find the total production of Praseodymium and Neodymium for each year in the given dataset?

CREATE TABLE RareEarthElements_Production (year INT, element TEXT, production INT); INSERT INTO RareEarthElements_Production (year, element, production) VALUES (2019, 'Praseodymium', 500); INSERT INTO RareEarthElements_Production (year, element, production) VALUES (2019, 'Neodymium', 1000); INSERT INTO RareEarthElements_Production (year, element, production) VALUES (2020, 'Praseodymium', 600); INSERT INTO RareEarthElements_Production (year, element, production) VALUES (2020, 'Neodymium', 1200); INSERT INTO RareEarthElements_Production (year, element, production) VALUES (2021, 'Praseodymium', 700); INSERT INTO RareEarthElements_Production (year, element, production) VALUES (2021, 'Neodymium', 1400);

SELECT year, SUM(production) as total_production FROM RareEarthElements_Production WHERE element IN ('Praseodymium', 'Neodymium') GROUP BY year;


Question: Calculate attendance by age group for the 'Art of the Americas'.

CREATE TABLE attendance (id INT, age INT, event VARCHAR(50), visitors INT);   INSERT INTO attendance (id, age, event, visitors) VALUES   (1, 18, 'Art of the Americas', 500), (2, 25, 'Art of the Americas', 700), (3, 35, 'Art of the Americas', 800);

SELECT event, AVG(age) as avg_age, COUNT(*) as total   FROM attendance   WHERE event = 'Art of the Americas'   GROUP BY event;


Question: List the number of mental health parity violations in each state for the last 3 years, ordered by the date of violation in descending order.

CREATE TABLE MentalHealthParityViolations (ViolationID INT, State VARCHAR(255), ViolationDate DATE); INSERT INTO MentalHealthParityViolations (ViolationID, State, ViolationDate) VALUES (1, 'California', '2019-04-01'); INSERT INTO MentalHealthParityViolations (ViolationID, State, ViolationDate) VALUES (2, 'Texas', '2020-01-15'); INSERT INTO MentalHealthParityViolations (ViolationID, State, ViolationDate) VALUES (3, 'California', '2021-03-05');

SELECT State, COUNT(*) as NumberOfViolations, ViolationDate FROM MentalHealthParityViolations WHERE ViolationDate >= DATE_SUB(CURRENT_DATE, INTERVAL 3 YEAR) GROUP BY State, ViolationDate ORDER BY ViolationDate DESC;


Question: Show a query using PostgreSQL contrib extension 'pageinspect' (example 10).

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


Question: List the names and capacities of hotels with sustainability certifications in New York.

CREATE TABLE hotels (hotel_id INT, name VARCHAR(255), city VARCHAR(255), capacity INT, certified BOOLEAN); INSERT INTO hotels (hotel_id, name, city, capacity, certified) VALUES (1, 'EcoHotel NY', 'New York', 150, TRUE), (2, 'GreenHotel NY', 'New York', 200, FALSE);

SELECT name, capacity FROM hotels WHERE city = 'New York' AND certified = TRUE;


Question: Generate PostgreSQL SQL for: What opponent had an attendance of 63,659?

CREATE TABLE table_name_78 (opponent_number VARCHAR, attendance VARCHAR)

SELECT opponent_number FROM table_name_78 WHERE attendance = '63,659';


Question: List all fish species from the "fish_species" table that belong to the "Salmonidae" family

create table fish_species (id integer, name text, family text, region text); insert into fish_species (id, name, family, region) values (1, 'Salmon', 'Salmonidae', 'North Atlantic'); insert into fish_species (id, name, family, region) values (2, 'Trout', 'Salmonidae', 'North Pacific');

select * from fish_species where family = 'Salmonidae';


Question: What is the maximum carbon dioxide level (in ppm) recorded for fish farming in Japan?

CREATE TABLE co2_measurements (id INT, farm_id INT, timestamp TIMESTAMP, co2_level FLOAT);  CREATE VIEW japan_co2_measurements AS SELECT * FROM co2_measurements WHERE country = 'Japan';

SELECT MAX(co2_level) FROM japan_co2_measurements;


Question: Generate PostgreSQL SQL for: Name the total number of cars for panther racing and grid of 9

CREATE TABLE table_17304308_1 (car_no VARCHAR, team VARCHAR, grid VARCHAR)

SELECT COUNT(car_no) FROM table_17304308_1 WHERE team = 'Panther Racing' AND grid = 9;


Question: How many visual artists are represented in the database, and what is the distribution by their gender?

CREATE TABLE artists (id INT, name VARCHAR(255), birth_date DATE, gender VARCHAR(50));

SELECT COUNT(*) as total_artists, gender FROM artists GROUP BY gender;


Question: Update the region to 'Asia Pacific' for all records with a revenue above 8000 in the SkincareSales table.

CREATE TABLE SkincareSales (productID INT, productName VARCHAR(50), region VARCHAR(50), revenue DECIMAL(10,2)); INSERT INTO SkincareSales (productID, productName, region, revenue) VALUES (1, 'Nourishing Cream', 'Europe', 5000.00), (2, 'Soothing Lotion', 'Europe', 7000.00), (3, 'Regenerating Serum', 'Europe', 8000.00), (4, 'Revitalizing Moisturizer', 'North America', 6000.00), (5, 'Purifying Cleanser', 'North America', 9000.00);

UPDATE SkincareSales SET region = 'Asia Pacific' WHERE revenue > 8000;


Question: Generate PostgreSQL SQL for: What is the 1991 finish for the 1993 Grand Slams?

SELECT 1991 FROM table_name_60 WHERE 1993 = 'grand slams';


Question: Generate PostgreSQL SQL for: Which Pos has a Car # of 33?

CREATE TABLE table_name_72 (pos INTEGER, car__number VARCHAR)

SELECT SUM(pos) FROM table_name_72 WHERE car__number = 33;


Question: Generate PostgreSQL SQL for: What was the result in round qf?

CREATE TABLE table_name_56 (result VARCHAR, round VARCHAR)

SELECT result FROM table_name_56 WHERE round = 'qf';


Question: Generate PostgreSQL SQL for: Find the product type whose average price is higher than the average price of all products.

CREATE TABLE products (product_type_code VARCHAR, product_price INTEGER)

SELECT product_type_code FROM products GROUP BY product_type_code HAVING AVG(product_price) > (SELECT AVG(product_price) FROM products);


Question: What is the minimum CO2 emission reduction (in metric tons) achieved by carbon offset programs in 'NorthAmerica' in '2020'?

CREATE TABLE carbon_offsets (id INT, program_name VARCHAR(50), location VARCHAR(50), year INT, co2_reduction INT); INSERT INTO carbon_offsets (id, program_name, location, year, co2_reduction) VALUES (1, 'ProgramA', 'NorthAmerica', 2020, 800), (2, 'ProgramB', 'NorthAmerica', 2020, 1000);

SELECT MIN(co2_reduction) FROM carbon_offsets WHERE location = 'NorthAmerica' AND year = 2020;


Question: pgTAP test for Resultset (assertion 91).

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

Explanation: SQL assertion from pgTAP test suite for Resultset.


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

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

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


Question: Generate PostgreSQL SQL for: What is the number of males 977 948?

CREATE TABLE table_name_20 (number VARCHAR, males VARCHAR)

SELECT number FROM table_name_20 WHERE males = '977 948';


Question: Generate PostgreSQL SQL for: How many points did Carlton score?

CREATE TABLE table_name_41 (home_team VARCHAR, away_team VARCHAR)

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


Question: pgTAP test for Pgtap--0.91.0--0.92.0 (assertion 62).

-- triggers_are( schema, table, triggers[], description )
CREATE OR REPLACE FUNCTION triggers_are( NAME, NAME, NAME[], TEXT )
RETURNS TEXT AS $$
    SELECT _are(
        'triggers',
        ARRAY(
            SELECT t.tgname
              FROM pg_catalog.pg_trigger t
              JOIN pg_catalog.pg_class c     ON c.oid = t.tgrelid
              JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
             WHERE n.nspname = $1
               AND c.relname = $2
               AND NOT t.tgisinternal
            EXCEPT
            SELECT $3[i]
              FROM generate_series(1, array_upper($3, 1)) s(i)
        ),
        ARRAY(
            SELECT $3[i]
              FROM generate_series(1, array_upper($3, 1)) s(i)
            EXCEPT
            SELECT t.tgname
              FROM pg_catalog.pg_trigger t
              JOIN pg_catalog.pg_class c     ON c.oid = t.tgrelid
              JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
             WHERE n.nspname = $1
               AND c.relname = $2
               AND NOT t.tgisinternal
        ),
        $4
    );
$$ LANGUAGE SQL;

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


Question: Identify policyholders who have made more than two claims in Wisconsin

CREATE TABLE claims (policyholder_id INT, claim_number INT, state VARCHAR(2)); INSERT INTO claims (policyholder_id, claim_number, state) VALUES (1, 1, 'WI'), (1, 2, 'WI'), (1, 3, 'WI'), (2, 1, 'WI');

SELECT policyholder_id FROM claims WHERE state = 'WI' GROUP BY policyholder_id HAVING COUNT(*) > 2;


Question: PostgreSQL regression test 'int2': Write the SELECT query (example 62).

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

SELECT count(*) FROM (SELECT int2 '0x8000') AS _sub;


Question: Generate PostgreSQL SQL for: What is the IATA when the ICAO is wipp?

CREATE TABLE table_name_52 (iata VARCHAR, icao VARCHAR)

SELECT iata FROM table_name_52 WHERE icao = 'wipp';


Question: Generate PostgreSQL SQL for: In what country is the El Hamada area of operation?

CREATE TABLE table_13150274_1 (country VARCHAR, area_of_operation VARCHAR)

SELECT country FROM table_13150274_1 WHERE area_of_operation = 'El Hamada';


Question: Find the customer with the highest balance in the socially_responsible_lending accounts, and display their account number, name, and balance.

CREATE TABLE socially_responsible_lending (acct_number INT, name VARCHAR(50), balance DECIMAL(10,2)); INSERT INTO socially_responsible_lending (acct_number, name, balance) VALUES (3001, 'Jamal', 12000.00), (3002, 'Nadia', 16000.00), (3003, 'Zaki', 10000.00), (3004, 'Sara', 20000.00);

SELECT acct_number, name, balance FROM (SELECT acct_number, name, balance, ROW_NUMBER() OVER (ORDER BY balance DESC) as rn FROM socially_responsible_lending) t WHERE rn = 1;


Question: Which programs did volunteer 'Zoe' engage with in 2022?

CREATE TABLE Programs (ProgramID int, ProgramName varchar(255)); INSERT INTO Programs (ProgramID, ProgramName) VALUES (1, 'Education'), (2, 'Health'), (3, 'Environment'); CREATE TABLE Volunteers (VolunteerID int, VolunteerName varchar(255), ProgramID int, VolunteerDate date); INSERT INTO Volunteers (VolunteerID, VolunteerName, ProgramID, VolunteerDate) VALUES (10, 'Zoe', 1, '2022-02-20'), (11, 'Zoe', 2, '2022-09-10'), (12, 'Zoe', 3, '2022-11-20');

SELECT DISTINCT ProgramName FROM Volunteers V JOIN Programs P ON V.ProgramID = P.ProgramID WHERE VolunteerName = 'Zoe';


Question: What is the average donation amount by age group in Canada?

CREATE TABLE donations_age_canada (donation_id INT, donor_age INT, amount DECIMAL(10,2), country VARCHAR(255)); INSERT INTO donations_age_canada (donation_id, donor_age, amount, country) VALUES (5, 31, 450.00, 'Canada'), (6, 47, 300.00, 'Canada'), (7, 53, 500.00, 'Canada');

SELECT AVG(amount) as avg_donation, FLOOR(donor_age / 10) * 10 as age_group FROM donations_age_canada WHERE country = 'Canada' GROUP BY age_group;


Question: List the number of safe AI algorithms designed for autonomous vehicles grouped by their evaluation category.

CREATE TABLE safe_ai_algorithms_av (id INT, algorithm VARCHAR(25), evaluation VARCHAR(25), score FLOAT); INSERT INTO safe_ai_algorithms_av (id, algorithm, evaluation, score) VALUES (1, 'AlgorithmJ', 'Robustness', 0.93), (2, 'AlgorithmK', 'Security', 0.96), (3, 'AlgorithmL', 'Reliability', 0.92), (4, 'AlgorithmM', 'Robustness', 0.97);

SELECT evaluation, COUNT(*) as num_algorithms FROM safe_ai_algorithms_av WHERE evaluation IN ('Robustness', 'Security', 'Reliability') GROUP BY evaluation;


Question: What is the minimum mental health score of students in 'Winter 2022' by school district?

CREATE TABLE student_mental_health (student_id INT, mental_health_score INT, school_district VARCHAR(255), date DATE); INSERT INTO student_mental_health (student_id, mental_health_score, school_district, date) VALUES (1, 75, 'ABC School District', '2022-02-01'); CREATE VIEW winter_2022_smh AS SELECT * FROM student_mental_health WHERE date BETWEEN '2022-01-01' AND '2022-03-31';

SELECT MIN(mental_health_score) as min_mental_health, school_district FROM winter_2022_smh GROUP BY school_district;


Question: Insert a new indigenous community record for the Inuit community in Greenland.

CREATE TABLE arctic_communities (community_id INT, community_name VARCHAR(50), region_id INT);

INSERT INTO arctic_communities (community_id, community_name, region_id) VALUES (1, 'Inuit', (SELECT region_id FROM arctic_regions WHERE region_name = 'Greenland'));


Question: Generate PostgreSQL SQL for: What is the lowest To par, when Total is greater than 148, and when Year(s) Won is "1959 , 1968 , 1974"?

CREATE TABLE table_name_97 (to_par INTEGER, total VARCHAR, year_s__won VARCHAR)

SELECT MIN(to_par) FROM table_name_97 WHERE total < 148 AND year_s__won = '1959 , 1968 , 1974';


Question: Generate PostgreSQL SQL for: WHere is the friends' school?

CREATE TABLE table_name_65 (location VARCHAR, school VARCHAR)

SELECT location FROM table_name_65 WHERE school = 'the friends' school';


Question: List all the vessels that entered the port of Oakland and their corresponding cargo types, sorted by the cargo type.

CREATE TABLE port (port_id INT, port_name VARCHAR(50)); INSERT INTO port (port_id, port_name) VALUES (1, 'Oakland'), (2, 'Seattle'); CREATE TABLE vessels (vessel_id INT, port_id INT, quantity_containers INT); INSERT INTO vessels (vessel_id, port_id, quantity_containers) VALUES (101, 1, 500), (102, 1, 700), (103, 2, 800); CREATE TABLE cargo (cargo_id INT, cargo_type VARCHAR(50), vessel_id INT); INSERT INTO cargo (cargo_id, cargo_type, vessel_id) VALUES (201, 'Containers', 101), (202, 'Vehicles', 102), (203, 'Bulk', 103);

SELECT vessels.vessel_id, cargo.cargo_type FROM vessels JOIN port ON vessels.port_id = port.port_id JOIN cargo ON vessels.vessel_id = cargo.vessel_id WHERE port.port_name = 'Oakland' ORDER BY cargo.cargo_type;


Question: Generate PostgreSQL SQL for: What is the points when the lost was 11?

CREATE TABLE table_name_29 (points_for VARCHAR, lost VARCHAR)

SELECT points_for FROM table_name_29 WHERE lost = '11';


Question: Calculate the number of properties co-owned by people from underrepresented communities in each neighborhood, including Indigenous, Latinx, and African American.

CREATE TABLE Properties (PropertyID INT, CoOwnedBy VARCHAR(50), Neighborhood VARCHAR(20)); INSERT INTO Properties (PropertyID, CoOwnedBy, Neighborhood) VALUES (1, 'Female, Indigenous', 'UrbanCore'), (2, 'Male, African American', 'UrbanCore'), (3, 'Female, Latinx', 'Suburban');

SELECT Neighborhood, COUNT(*) FROM Properties WHERE CoOwnedBy LIKE '%Female, Indigenous%' OR CoOwnedBy LIKE '%Male, African American%' OR CoOwnedBy LIKE '%Female, Latinx%' GROUP BY Neighborhood;


Question: What is the total area of all wildlife habitats in the forestry database?

CREATE TABLE habitat (id INT, name VARCHAR(255), area FLOAT); INSERT INTO habitat (id, name, area) VALUES (1, 'Habitat1', 123.45); INSERT INTO habitat (id, name, area) VALUES (2, 'Habitat2', 234.56); CREATE TABLE region (id INT, name VARCHAR(255), habitat_id INT); INSERT INTO region (id, name, habitat_id) VALUES (1, 'Region1', 1); INSERT INTO region (id, name, habitat_id) VALUES (2, 'Region2', 2);

SELECT SUM(h.area) FROM habitat h JOIN region r ON h.id = r.habitat_id;


Question: How many marine species are found in the Pacific Ocean?

CREATE TABLE marine_species_by_ocean (name VARCHAR(255), ocean VARCHAR(255)); INSERT INTO marine_species_by_ocean (name, ocean) VALUES ('Clownfish', 'Pacific Ocean'), ('Sea Otter', 'Pacific Ocean');

SELECT COUNT(*) FROM marine_species_by_ocean WHERE ocean = 'Pacific Ocean';


Question: Find investment strategies with an ESG score below 70 and risk level above 4.

CREATE TABLE investment_strategies (strategy_id INT, ESG_score FLOAT, risk_level INT); INSERT INTO investment_strategies (strategy_id, ESG_score, risk_level) VALUES (101, 86.2, 3), (102, 78.9, 5), (103, 88.7, 2), (104, 65.1, 6);

SELECT strategy_id FROM investment_strategies WHERE ESG_score < 70 AND risk_level > 4;


Question: What is the total number of artworks by medium in Oceania?

CREATE TABLE Artworks (ArtworkID INT, ArtworkName TEXT, Medium TEXT); INSERT INTO Artworks (ArtworkID, ArtworkName, Medium) VALUES (1, 'The Starry Night', 'Oil on Canvas'); INSERT INTO Artworks (ArtworkID, ArtworkName, Medium) VALUES (2, 'Guernica', 'Oil on Canvas');

SELECT Medium, COUNT(*) as NumArtworks FROM Artworks WHERE Region = 'Oceania' GROUP BY Medium;


Question: What is the average time to resolve each type of case in the justice system?

CREATE TABLE Justice_System_Case_Resolution (ID INT, Case_Type VARCHAR(30), Avg_Time_To_Resolve INT); INSERT INTO Justice_System_Case_Resolution (ID, Case_Type, Avg_Time_To_Resolve) VALUES (1, 'Criminal', 60), (2, 'Civil', 90), (3, 'Family', 45);

SELECT Case_Type, AVG(Avg_Time_To_Resolve) FROM Justice_System_Case_Resolution GROUP BY Case_Type;


Question: Add new records of cybersecurity incidents in a specific year to the "cybersecurity_incidents" table

CREATE TABLE cybersecurity_incidents (id INT, year INT, type VARCHAR(255), country VARCHAR(255), description TEXT);

INSERT INTO cybersecurity_incidents (id, year, type, country, description) VALUES (1, 2018, 'Data Breach', 'US', 'Unauthorized access to sensitive personal information'), (2, 2018, 'Phishing', 'Canada', 'Fraudulent emails sent to steal personal information');


Question: Generate PostgreSQL SQL for: What is the day 1 when the day 3 is math?

CREATE TABLE table_name_16 (day_1 VARCHAR, day_3 VARCHAR)

SELECT day_1 FROM table_name_16 WHERE day_3 = 'math';


Question: Generate PostgreSQL SQL for: How many millions of people in the US saw the episode with season number 1?

CREATE TABLE table_19401346_1 (us_viewers__millions_ VARCHAR, no_in_season VARCHAR)

SELECT us_viewers__millions_ FROM table_19401346_1 WHERE no_in_season = 1;


Question: Delete records with a Population less than 1000 from the 'AnimalPopulation' table.

CREATE TABLE AnimalPopulation (AnimalID int, AnimalName varchar(50), Population int); INSERT INTO AnimalPopulation (AnimalID, AnimalName, Population) VALUES (1, 'Tiger', 2000), (2, 'Elephant', 500), (3, 'Giraffe', 1200);

DELETE FROM AnimalPopulation WHERE Population < 1000;


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

$$;

\df ptest1
SELECT pg_get_functiondef('ptest1'::regproc);

-- show only normal functions
\dfn public.*test*1

-- show only procedures
\dfp public.*test*1

SELECT ptest1('x');  -- error
CALL ptest1('a');  -- ok
CALL ptest1('xy' || 'zzy');  -- ok, constant-folded arg
CALL ptest1(substring(random()::numeric(20,15)::text, 1, 1));  -- ok, volatile arg

SELECT * FROM cp_test ORDER BY b COLLATE "C";

-- SQL-standard body
CREATE PROCEDURE ptest1s(x text)
LANGUAGE SQL
BEGIN ATOMIC
  INSERT INTO cp_test VALUES (1, x);
END;

\df ptest1s
SELECT pg_get_functiondef('ptest1s'::regproc);

CALL ptest1s('b');

SELECT * FROM cp_test ORDER BY b COLLATE "C";

-- utility functions currently not supported here
CREATE PROCEDURE ptestx()
LANGUAGE SQL
BEGIN ATOMIC
  CREATE TABLE x (a int);
END;

CREATE PROCEDURE ptest2()
LANGUAGE SQL
AS $$
SELECT 5;

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


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

ALTER EXTENSION pgtap ADD FUNCTION diag( VARIADIC anyarray );

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


Question: Generate PostgreSQL SQL for: What year did she compete in tampere, finland?

CREATE TABLE table_name_95 (year INTEGER, venue VARCHAR)

SELECT AVG(year) FROM table_name_95 WHERE venue = 'tampere, finland';


Question: What is the annual production volume trend for the mine with the ID 'mine001'?

CREATE TABLE production_data (id INT PRIMARY KEY, mine_id INT, year INT, monthly_production INT);

SELECT year, AVG(monthly_production) as annual_production FROM production_data WHERE mine_id = 'mine001' GROUP BY year;


Question: Generate PostgreSQL SQL for: Who was the batsmen at the Brit Oval location?

CREATE TABLE table_name_76 (batsmen VARCHAR, location VARCHAR)

SELECT batsmen FROM table_name_76 WHERE location = 'the brit oval';


Question: Delete records in the 'employee' table where the 'position' is 'field worker'

CREATE TABLE employee (employee_id INT, name VARCHAR(50), position VARCHAR(20));

DELETE FROM employee WHERE position = 'field worker';


Question: Generate PostgreSQL SQL for: How many finals had more than 0 goals and 8 assists?

CREATE TABLE table_name_14 (finals VARCHAR, goals VARCHAR, assists VARCHAR)

SELECT finals FROM table_name_14 WHERE goals > 0 AND assists = 8;


Question: What is the average age of players who have played a game using VR technology in the last 6 months, grouped by their preferred gaming genre?

CREATE TABLE Players (PlayerID INT, Age INT, PreferredGenre VARCHAR(20), LastVRGame DATETIME); CREATE TABLE Games (GameID INT, Genre VARCHAR(20)); CREATE VIEW Game_Library AS SELECT PlayerID, GameID FROM Player_Games; CREATE VIEW Game_Details AS SELECT GameID, Genre FROM Games; CREATE VIEW VR_Games AS SELECT PlayerID FROM Game_Library WHERE GameID IN (SELECT GameID FROM Games WHERE VRCompatible = 1);

SELECT PreferredGenre, AVG(Age) FROM Players JOIN VR_Games ON Players.PlayerID = VR_Games.PlayerID JOIN Game_Details ON Game_Library.GameID = Games.GameID WHERE LastVRGame >= DATE_SUB(CURRENT_DATE, INTERVAL 6 MONTH) GROUP BY PreferredGenre;


Question: What are the vehicle types and test results for safety tests conducted in the first quarter of 2022?

CREATE TABLE VehicleSafetyTests (TestID INT PRIMARY KEY, VehicleID INT, TestDate DATE, TestResults VARCHAR(50)); CREATE TABLE Vehicles (VehicleID INT PRIMARY KEY, VehicleType VARCHAR(50), Manufacturer VARCHAR(50));

SELECT Vehicles.VehicleType, VehicleSafetyTests.TestResults FROM Vehicles INNER JOIN VehicleSafetyTests ON Vehicles.VehicleID = VehicleSafetyTests.VehicleID WHERE VehicleSafetyTests.TestDate BETWEEN '2022-01-01' AND '2022-03-31';


Question: What is the total assets of clients who have invested in at least two different types of investments?

CREATE TABLE clients (client_id INT, name TEXT, age INT, gender TEXT, total_assets DECIMAL(10,2)); INSERT INTO clients VALUES (1, 'John Doe', 35, 'Male', 250000.00), (2, 'Jane Smith', 45, 'Female', 500000.00), (3, 'Bob Johnson', 50, 'Male', 800000.00); CREATE TABLE investments (client_id INT, investment_type TEXT); INSERT INTO investments VALUES (1, 'Stocks'), (1, 'Bonds'), (2, 'Stocks'), (2, 'Mutual Funds'), (3, 'Mutual Funds'), (3, 'Real Estate');

SELECT c.total_assets FROM clients c INNER JOIN investments i1 ON c.client_id = i1.client_id INNER JOIN investments i2 ON c.client_id = i2.client_id AND i1.investment_type <> i2.investment_type GROUP BY c.client_id;


Question: What is the average price of fair trade materials in the materials table?

CREATE TABLE materials (material_id INT, material_name TEXT, is_fair_trade BOOLEAN, price DECIMAL); INSERT INTO materials VALUES (1, 'Handwoven Cotton', TRUE, 5.5); INSERT INTO materials VALUES (2, 'Recycled Polyester', FALSE, 3.25);

SELECT AVG(price) FROM materials WHERE is_fair_trade = TRUE;


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


Question: What is the average age of community health workers who speak a language other than English?

CREATE TABLE Languages (language_id INT, language_name TEXT);CREATE TABLE CommunityHealthWorkers (worker_id INT, worker_language INT, worker_age INT);

SELECT AVG(worker_age) FROM CommunityHealthWorkers cwh WHERE worker_language IN (SELECT language_id FROM Languages WHERE language_name != 'English');


Question: Generate PostgreSQL SQL for: What was the last year that they had less than 16 points in class 500cc?

CREATE TABLE table_name_11 (year INTEGER, points VARCHAR, class VARCHAR)

SELECT MAX(year) FROM table_name_11 WHERE points < 16 AND class = '500cc';


Question: Generate PostgreSQL SQL for: What is the highest position for less than 42 played?

CREATE TABLE table_name_48 (position INTEGER, played INTEGER)

SELECT MAX(position) FROM table_name_48 WHERE played < 42;


Question: What is the maximum supply of each digital asset issued by companies based in the UK?

CREATE TABLE Digital_Assets (Asset_ID INT, Asset_Name VARCHAR(100), Max_Supply BIGINT); INSERT INTO Digital_Assets (Asset_ID, Asset_Name, Max_Supply) VALUES (1, 'Asset1', 1000000), (2, 'Asset2', 500000), (3, 'Asset3', 200000);

SELECT Asset_ID, Asset_Name, MAX(Max_Supply) FROM Digital_Assets WHERE Issuer_Country = 'UK' GROUP BY Asset_ID, Asset_Name;


Question: How many unions focus on 'Transportation' and have more than 100,000 members?

CREATE TABLE unions (id INT, name TEXT, domain TEXT, members INT); INSERT INTO unions (id, name, domain, members) VALUES (1, 'International Brotherhood of Teamsters', 'Transportation', 1200000); INSERT INTO unions (id, name, domain, members) VALUES (2, 'United Steelworkers', 'Metals, Mining, Energy, Construction', 850000);

SELECT COUNT(*) FROM unions WHERE domain = 'Transportation' AND members > 100000;


Question: Generate PostgreSQL SQL for: What is the segment A on episode 237?

CREATE TABLE table_15187735_19 (segment_a VARCHAR, episode VARCHAR)

SELECT segment_a FROM table_15187735_19 WHERE episode = 237;


Question: What is the maximum cargo weight (in metric tons) for each port?

CREATE TABLE ports (port_id INT, port_name VARCHAR(50), country VARCHAR(50)); INSERT INTO ports VALUES (1, 'Tanjung Priok', 'Indonesia'); INSERT INTO ports VALUES (2, 'Belawan', 'Indonesia'); CREATE TABLE cargo (cargo_id INT, port_id INT, weight_ton FLOAT); INSERT INTO cargo VALUES (1, 1, 5000); INSERT INTO cargo VALUES (2, 1, 7000); INSERT INTO cargo VALUES (3, 2, 3000); INSERT INTO cargo VALUES (4, 2, 4000);

SELECT ports.port_name, MAX(cargo.weight_ton) FROM cargo JOIN ports ON cargo.port_id = ports.port_id GROUP BY ports.port_name;


Question: pgTAP test for Cmpok (assertion 7).

SELECT * FROM check_test(
    cmp_ok( 1, '=', 2, '1 should = 2' ),
    false,
    'cmp_ok() fail',
    '1 should = 2',
    '    ''1''
        =
    ''2'''
);


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

SELECT * FROM test_timestamp WHERE i<'-infinity'::date ORDER BY i;

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


Question: What is the maximum donation amount from donors living in 'India'?

CREATE TABLE donors (donor_id INT, donor_name TEXT, donation_amount DECIMAL(10,2), country TEXT); INSERT INTO donors (donor_id, donor_name, donation_amount, country) VALUES (1, 'John Doe', 500.00, 'United States'); INSERT INTO donors (donor_id, donor_name, donation_amount, country) VALUES (2, 'Jane Smith', 300.00, 'Canada'); INSERT INTO donors (donor_id, donor_name, donation_amount, country) VALUES (3, 'Jose Garcia', 250.00, 'Brazil'); INSERT INTO donors (donor_id, donor_name, donation_amount, country) VALUES (4, 'Raj Patel', 700.00, 'India');

SELECT MAX(donation_amount) FROM donors WHERE country = 'India';


Question: What is the percentage of sustainable products for each brand?

CREATE TABLE products (product_id INT, product_name TEXT, brand_id INT, sustainable_product BOOLEAN); INSERT INTO products (product_id, product_name, brand_id, sustainable_product) VALUES (1, 'Organic Cotton Shirt', 1, TRUE), (2, 'Polyester Jacket', 1, FALSE), (3, 'Hemp T-Shirt', 2, TRUE), (4, 'Viscose Dress', 2, FALSE);

SELECT brands.brand_name, ROUND(COUNT(CASE WHEN products.sustainable_product = TRUE THEN 1 END) * 100.0 / COUNT(*), 2) as percentage FROM products JOIN brands ON products.brand_id = brands.brand_id GROUP BY brands.brand_name;


Question: Show the total number of medals won by each country in the Olympics, including the number of gold, silver, and bronze medals.

CREATE TABLE olympic_medals (country VARCHAR(255), medal VARCHAR(255), count INT); INSERT INTO olympic_medals VALUES ('USA', 'Gold', 50); INSERT INTO olympic_medals VALUES ('China', 'Silver', 30); INSERT INTO olympic_medals VALUES ('Russia', 'Bronze', 20);

SELECT country, SUM(CASE WHEN medal = 'Gold' THEN count ELSE 0 END) as gold_medals, SUM(CASE WHEN medal = 'Silver' THEN count ELSE 0 END) as silver_medals, SUM(CASE WHEN medal = 'Bronze' THEN count ELSE 0 END) as bronze_medals, SUM(count) as total_medals FROM olympic_medals GROUP BY country;


Question: What is the average sustainability rating for garments manufactured in Africa?

CREATE TABLE garment_info (garment_id INT, sustainability_rating DECIMAL(3, 2)); INSERT INTO garment_info (garment_id, sustainability_rating) VALUES (1001, 4.2), (1002, 3.5), (1003, 4.8), (1004, 2.9), (1005, 4.5), (1006, 3.7); CREATE TABLE garment_manufacturing (manufacturing_id INT, garment_id INT, country VARCHAR(255)); INSERT INTO garment_manufacturing (manufacturing_id, garment_id, country) VALUES (1, 1001, 'Nigeria'), (2, 1002, 'Egypt'), (3, 1003, 'UK'), (4, 1004, 'China'), (5, 1005, 'Bangladesh'), (6, 1006, 'Indonesia');

SELECT AVG(g.sustainability_rating) AS avg_sustainability_rating FROM garment_info g INNER JOIN garment_manufacturing m ON g.garment_id = m.garment_id WHERE m.country IN ('Nigeria', 'Egypt');


Question: Generate PostgreSQL SQL for: What was the reanking of Hamid Veisi?

CREATE TABLE table_name_44 (rank VARCHAR, athlete VARCHAR)

SELECT rank FROM table_name_44 WHERE athlete = 'hamid veisi';


Question: What is the maximum ticket price for concerts in the 'Hip Hop' genre?

CREATE TABLE ConcertGenre (ConcertID INT, GenreID INT); INSERT INTO ConcertGenre VALUES (7, 3), (8, 1), (9, 2), (13, 5);

SELECT MAX(TicketPrice) FROM Concerts JOIN ConcertGenre ON Concerts.ConcertID = ConcertGenre.ConcertID JOIN Genre ON ConcertGenre.GenreID = Genre.GenreID WHERE Genre.Genre = 'Hip Hop';


Question: Write the DML statement from PostgreSQL regression test 'merge' (example 506).

INSERT INTO measurement VALUES (1, '2007-01-17', 10, 10);

Explanation: DML from PostgreSQL core regression test for Merge.


Question: Show the location and treatment type for each wastewater treatment plant

CREATE TABLE wastewater_treatment (id INT, location VARCHAR(255), treatment_type VARCHAR(255), capacity INT);

SELECT location, treatment_type FROM wastewater_treatment;


Question: Generate PostgreSQL SQL for: What color is the super-soft compound?

CREATE TABLE table_name_31 (colour VARCHAR, compound_name VARCHAR)

SELECT colour FROM table_name_31 WHERE compound_name = 'super-soft';


Question: What is the maximum duration of a virtual tour?

CREATE TABLE virtual_tours(id INT, name TEXT, country TEXT, duration INT); INSERT INTO virtual_tours (id, name, country, duration) VALUES (1, 'Tokyo Sky Tree Virtual Tour', 'Japan', 60), (2, 'Paris Virtual Tour', 'France', 90);

SELECT MAX(duration) FROM virtual_tours;


Question: Delete all records from the 'sustainable_tourism_practices' table.

CREATE TABLE sustainable_tourism_practices (id INT, title TEXT, description TEXT, country TEXT);


Question: What was the production of Samarium in 2018 and 2021?

CREATE TABLE production_data (year INT, element VARCHAR(10), quantity INT); INSERT INTO production_data (year, element, quantity) VALUES (2018, 'Samarium', 80), (2019, 'Samarium', 90), (2020, 'Samarium', 100), (2021, 'Samarium', 110);

SELECT quantity FROM production_data WHERE element = 'Samarium' AND year IN (2018, 2021);


Question: Generate PostgreSQL SQL for: What is the Opponent of the game in Week 3?

CREATE TABLE table_name_21 (opponent VARCHAR, week VARCHAR)

SELECT opponent FROM table_name_21 WHERE week = 3;


Question: Find the minimum and maximum depth of mines in South Africa.

CREATE TABLE mines (id INT, name TEXT, location TEXT, depth INT); INSERT INTO mines (id, name, location, depth) VALUES (1, 'Diamond Mine', 'South Africa', 1500); INSERT INTO mines (id, name, location, depth) VALUES (2, 'Gold Mine', 'South Africa', 2000);

SELECT MIN(depth), MAX(depth) FROM mines WHERE location = 'South Africa';


Question: What is the average number of hours volunteered per week by volunteers from Asia?

CREATE TABLE volunteer_hours (id INT, volunteer_id INT, hours DECIMAL, week INT); INSERT INTO volunteer_hours (id, volunteer_id, hours, week) VALUES (1, 1, 5.0, 1), (2, 2, 10.0, 1), (3, 3, 7.5, 1), (4, 1, 4.0, 2), (5, 3, 8.0, 2); CREATE TABLE volunteers (id INT, name TEXT, region TEXT); INSERT INTO volunteers (id, name, region) VALUES (1, 'Alice', 'Asia'), (2, 'Bob', 'Europe'), (3, 'Charlie', 'Africa');

SELECT AVG(hours) FROM volunteer_hours INNER JOIN volunteers ON volunteer_hours.volunteer_id = volunteers.id WHERE volunteers.region = 'Asia';


Question: Identify the most common vulnerabilities in the Caribbean region in Q4 of 2021.

CREATE TABLE vulnerabilities_caribbean (id INT, vulnerability VARCHAR(255), region VARCHAR(255), detection_date DATE); INSERT INTO vulnerabilities_caribbean (id, vulnerability, region, detection_date) VALUES (1, 'SQL Injection', 'Caribbean', '2021-10-01'), (2, 'Cross-Site Scripting', 'Caribbean', '2021-11-01'), (3, 'Broken Authentication', 'Caribbean', '2021-12-01');

SELECT vulnerability, COUNT(*) AS detection_count FROM vulnerabilities_caribbean WHERE region = 'Caribbean' AND detection_date >= DATE_SUB('2021-12-31', INTERVAL 3 MONTH) GROUP BY vulnerability ORDER BY detection_count DESC;


Question: Show the total cost of completed projects in the 'transportation_infrastructure' table.

CREATE TABLE transportation_infrastructure (id INT, project_name VARCHAR(50), location VARCHAR(50), cost FLOAT, status VARCHAR(20)); INSERT INTO transportation_infrastructure (id, project_name, location, cost, status) VALUES (1, 'Bridge Construction', 'City U', 12000000.00, 'completed'), (2, 'Traffic Signal Upgrade', 'Region V', 500000.00, 'in_progress');

SELECT SUM(cost) FROM transportation_infrastructure WHERE status = 'completed';


Question: PostgreSQL regression test 'updatable_views': Write the SELECT query (example 91).

Explanation: Regression test for Updatable Views in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT * FROM rw_view2 ORDER BY aaa) AS _sub;


Question: Generate PostgreSQL SQL for: What place has a draw smaller than 2?

CREATE TABLE table_name_90 (place INTEGER, draw INTEGER)

SELECT AVG(place) FROM table_name_90 WHERE draw < 2;


Question: What is the average rating of movies directed by 'Director2'?

CREATE TABLE movies (id INT, title VARCHAR(255), rating FLOAT, director VARCHAR(255)); INSERT INTO movies (id, title, rating, director) VALUES (1, 'Movie1', 4.5, 'Director1'), (2, 'Movie2', 3.2, 'Director2'), (3, 'Movie3', 4.7, 'Director2'), (4, 'Movie4', 2.9, 'Director3');

SELECT AVG(rating) FROM movies WHERE director = 'Director2';


Question: Generate PostgreSQL SQL for: How many lanes have a Nationality of iceland?

CREATE TABLE table_name_58 (lane INTEGER, nationality VARCHAR)

SELECT SUM(lane) FROM table_name_58 WHERE nationality = 'iceland';


Question: Insert a new record for 'Bamboo Viscose' with a water consumption reduction of '50%' into the 'sustainability_metrics' table

CREATE TABLE sustainability_metrics (id INT PRIMARY KEY, fabric VARCHAR(50), water_reduction DECIMAL(3,2));

INSERT INTO sustainability_metrics (id, fabric, water_reduction) VALUES (2, 'Bamboo Viscose', 0.50);


Question: Generate PostgreSQL SQL for: In how many game was the attendance at Staples Center 18,997?

CREATE TABLE table_17058151_5 (game VARCHAR, location_attendance VARCHAR)

SELECT COUNT(game) FROM table_17058151_5 WHERE location_attendance = 'Staples Center 18,997';


Question: How many components were manufactured using renewable energy sources in Q2 of 2021?

CREATE TABLE components (id INT, manufacturer TEXT, energy_source TEXT, quantity INT); INSERT INTO components (id, manufacturer, energy_source, quantity) VALUES (1, 'XYZ', 'solar', 500), (2, 'ABC', 'wind', 700); CREATE TABLE dates (id INT, component_id INT, date DATE); INSERT INTO dates (id, component_id, date) VALUES (1, 1, '2021-04-01'), (2, 2, '2021-05-15');

SELECT SUM(quantity) FROM components c JOIN dates d ON c.id = d.component_id WHERE energy_source IN ('solar', 'wind') AND date BETWEEN '2021-04-01' AND '2021-06-30';


Question: Generate PostgreSQL SQL for: How many values are in the ends won cell corresponding to a PA of 39?

CREATE TABLE table_17012578_37 (Ends VARCHAR, pa VARCHAR)

SELECT COUNT(Ends) AS won FROM table_17012578_37 WHERE pa = 39;


Question: Generate PostgreSQL SQL for: What is the first election year listed?

CREATE TABLE table_1341472_20 (first_elected INTEGER)

SELECT MIN(first_elected) FROM table_1341472_20;


Question: Generate PostgreSQL SQL for: What is the sum of Rank with a build year earlier than 2007 for the howard johnson hotel bucharest?

CREATE TABLE table_name_39 (rank INTEGER, built VARCHAR, building VARCHAR)

SELECT SUM(rank) FROM table_name_39 WHERE built < 2007 AND building = 'howard johnson hotel bucharest';


Question: Add a new research grant to the grants table.

CREATE TABLE grants (id INT, name VARCHAR(50), amount DECIMAL(10,2), principal_investigator VARCHAR(50), department VARCHAR(50));

INSERT INTO grants (id, name, amount, principal_investigator, department) VALUES (2, 'DOE Grant', 75000, 'Benjamin Thomas', 'Engineering');


Question: Generate PostgreSQL SQL for: Find the names of all English songs.

CREATE TABLE song (song_name VARCHAR, languages VARCHAR)

SELECT song_name FROM song WHERE languages = 'english';


Question: What is the total revenue for each restaurant that offers vegan options in Q3 2022?

CREATE TABLE restaurant_menu (restaurant_id INT, has_vegan_options BOOLEAN); INSERT INTO restaurant_menu (restaurant_id, has_vegan_options) VALUES (1, true), (2, false); CREATE TABLE restaurant_revenue (restaurant_id INT, revenue DECIMAL(10,2), transaction_date DATE); INSERT INTO restaurant_revenue (restaurant_id, revenue, transaction_date) VALUES (1, 10000, '2022-07-01'), (2, 8000, '2022-07-02');

SELECT r.restaurant_id, SUM(revenue) as total_revenue FROM restaurant_revenue r JOIN restaurant_menu m ON r.restaurant_id = m.restaurant_id WHERE m.has_vegan_options = true GROUP BY r.restaurant_id;


Question: Find the artist with the highest total revenue from art sales.

CREATE TABLE ArtSales (artist VARCHAR(255), sale_price DECIMAL(10,2)); INSERT INTO ArtSales (artist, sale_price) VALUES ('Artist A', 5000), ('Artist A', 7000), ('Artist B', 6000), ('Artist B', 8000), ('Artist C', 9000), ('Artist C', 10000);

SELECT artist, SUM(sale_price) as total_revenue FROM ArtSales GROUP BY artist ORDER BY total_revenue DESC LIMIT 1;


Question: Generate PostgreSQL SQL for: What rank is Germany?

CREATE TABLE table_name_74 (rank VARCHAR, country VARCHAR)

SELECT rank FROM table_name_74 WHERE country = 'germany';


Question: What is the total number of alternative sentencing programs implemented in Illinois since 2017?

CREATE TABLE alternative_sentencing_programs (program_id INT, year INT, state VARCHAR(20)); INSERT INTO alternative_sentencing_programs (program_id, year, state) VALUES (1, 2022, 'Illinois'), (2, 2021, 'Illinois'), (3, 2020, 'Illinois'), (4, 2019, 'Illinois'), (5, 2018, 'Illinois'), (6, 2017, 'Illinois');

SELECT COUNT(*) FROM alternative_sentencing_programs WHERE year >= 2017 AND state = 'Illinois';


Question: What is the total amount of research grants awarded by country?

CREATE TABLE research_grants (id INT, student_id INT, year INT, amount DECIMAL(10, 2), country VARCHAR(50)); INSERT INTO research_grants VALUES (1, 1, 2021, 10000, 'USA'); INSERT INTO research_grants VALUES (2, 2, 2020, 12000, 'Canada'); INSERT INTO research_grants VALUES (3, 3, 2021, 15000, 'Mexico');

SELECT r.country, SUM(r.amount) FROM research_grants r GROUP BY r.country;


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

SELECT '2011-03-26 23:00:00 UTC'::timestamptz AT TIME ZONE 'Europe/Moscow';

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

SELECT count(*) FROM (SELECT '2011-03-26 23:00:00 UTC'::timestamptz AT TIME ZONE 'Europe/Moscow') AS _sub;


Question: What is the average annual visitors to cultural heritage sites in Italy?

CREATE TABLE cultural_heritage_sites_italy (site_id INT, site_name TEXT, country TEXT, annual_visitors INT); INSERT INTO cultural_heritage_sites_italy (site_id, site_name, country, annual_visitors) VALUES (1, 'Colosseum', 'Italy', 2000000), (2, 'Leaning Tower of Pisa', 'Italy', 1500000);

SELECT AVG(annual_visitors) FROM cultural_heritage_sites_italy;


Question: Generate PostgreSQL SQL for: What did the home team score when playing Fitzroy as the away team?

CREATE TABLE table_name_8 (home_team VARCHAR, away_team VARCHAR)

SELECT home_team AS score FROM table_name_8 WHERE away_team = 'fitzroy';


Question: What is the total transaction amount for 'South America' customers?

CREATE TABLE transactions (id INT, customer_region VARCHAR(20), transaction_amount DECIMAL(10,2)); INSERT INTO transactions (id, customer_region, transaction_amount) VALUES (1, 'North America', 500.00), (2, 'North America', 750.00), (3, 'South America', 800.00), (4, 'Europe', 900.00);

SELECT SUM(transaction_amount) FROM transactions WHERE customer_region = 'South America';


Question: What is the most common word used in posts made by users from Germany?

CREATE TABLE posts (id INT, user_id INT, content TEXT); INSERT INTO posts (id, user_id, content) VALUES (1, 1, 'Hello World'), (2, 1, 'I love data'), (3, 2, 'Guten Tag'), (4, 2, 'Ich liebe Deutschland'); CREATE TABLE users (id INT, name VARCHAR(100), country VARCHAR(50)); INSERT INTO users (id, name, country) VALUES (1, 'John Doe', 'USA'), (2, 'Hans Schmidt', 'Germany');

SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(content, ' ', n.n), ' ', -1) word, COUNT(*) count FROM posts JOIN users ON posts.user_id = users.id CROSS JOIN (SELECT 1 n UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5) n WHERE users.country = 'Germany' GROUP BY word ORDER BY count DESC LIMIT 1;


Question: Generate PostgreSQL SQL for: How many episodes aired in Sydney in Week 3?

CREATE TABLE table_24291077_4 (sydney VARCHAR, week VARCHAR)

SELECT COUNT(sydney) FROM table_24291077_4 WHERE week = 3;


Question: How many research grants were awarded to the Physics department in 2020?

CREATE TABLE grants (id INT, department VARCHAR(255), year INT, amount DECIMAL(10,2)); INSERT INTO grants (id, department, year, amount) VALUES (1, 'Physics', 2020, 50000), (2, 'Physics', 2019, 75000), (3, 'Chemistry', 2020, 60000);

SELECT COUNT(*) FROM grants WHERE department = 'Physics' AND year = 2020;


Question: Which artist has created the most artwork entries in Africa in each decade since 1900?

CREATE TABLE Artwork (ArtworkID INT, ArtistID INT, CreationDate DATE); INSERT INTO Artwork (ArtworkID, ArtistID, CreationDate) VALUES (1, 2, '1905-01-01'), (2, 2, '1910-05-15');

SELECT ArtistID, EXTRACT(YEAR FROM CreationDate) AS Decade, COUNT(*) as ArtworkCount FROM Artwork WHERE Continent = 'Africa' GROUP BY ArtistID, Decade ORDER BY Decade, ArtworkCount DESC;


Question: What is the total number of sustainable building projects in the 'sustainable_buildings' table with a timeline of more than 365 days?

CREATE TABLE sustainable_buildings (project_id INT, project_name TEXT, timeline_days INT);

SELECT COUNT(*) FROM sustainable_buildings WHERE timeline_days > 365;


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

SELECT ROW(x.*) FROM J1_TBL JOIN J2_TBL USING (i) AS x WHERE J1_TBL.t = 'one';

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

SELECT count(*) FROM (SELECT ROW(x.*) FROM J1_TBL JOIN J2_TBL USING (i) AS x WHERE J1_TBL.t = 'one') AS _sub;


Question: determine the average fare for all train lines in 'Rail System'

CREATE TABLE TrainLines (line VARCHAR(10), fare DECIMAL(5,2)); INSERT INTO TrainLines (line, fare) VALUES ('North', 2.50), ('South', 3.25), ('East', 2.75);


Question: Update the player's name in the players table

CREATE TABLE players (player_id INT, name VARCHAR(100), game VARCHAR(50));

UPDATE players SET name = 'NewPlayerName' WHERE player_id = 1;


Question: Insert a new record into the market_trends table for 2022: price_per_kg = 70.00, total_kg = 22000

CREATE TABLE market_trends ( id INT PRIMARY KEY, year INT, price_per_kg DECIMAL(10,2), total_kg INT );

INSERT INTO market_trends (id, year, price_per_kg, total_kg) VALUES (5, 2022, 70.00, 22000);


Question: Generate PostgreSQL SQL for: What is Location, when Result is 28-21?

CREATE TABLE table_name_93 (location VARCHAR, result VARCHAR)

SELECT location FROM table_name_93 WHERE result = '28-21';


Question: Which public transportation systems are available in Canada and the United States?

CREATE TABLE public_transportation (id INT, city VARCHAR(50), country VARCHAR(50), system VARCHAR(50)); INSERT INTO public_transportation (id, city, country, system) VALUES (1, 'Toronto', 'Canada', 'Subway'), (2, 'Montreal', 'Canada', 'Bus'), (3, 'New York', 'USA', 'Subway'), (4, 'Los Angeles', 'USA', 'Bus');

SELECT DISTINCT system FROM public_transportation WHERE country IN ('Canada', 'USA');


Question: What are the total REE production amounts for each country in 2020, excluding China?

CREATE TABLE production (country VARCHAR(255), year INT, ree_production INT); INSERT INTO production (country, year, ree_production) VALUES ('China', 2020, 140000), ('USA', 2020, 15000), ('Australia', 2020, 22000), ('India', 2020, 5200), ('Brazil', 2020, 3000), ('Russia', 2020, 4000);

SELECT country, SUM(ree_production) FROM production WHERE country NOT IN ('China') AND year = 2020 GROUP BY country;


Question: Generate PostgreSQL SQL for: Who is the shirt sponsor for the manufacturer Nike?

CREATE TABLE table_name_54 (shirt_sponsor VARCHAR, kit_manufacturer VARCHAR)

SELECT shirt_sponsor FROM table_name_54 WHERE kit_manufacturer = 'nike';


Question: Who is the coach of the team with the best win-loss record in the current season?

CREATE TABLE coaches (team_id INT, coach_name VARCHAR(255)); INSERT INTO coaches (team_id, coach_name) VALUES (1, 'CoachA'), (2, 'CoachB'), (3, 'CoachC'); CREATE TABLE games (team_id INT, result VARCHAR(5)); INSERT INTO games (team_id, result) VALUES (1, 'Win'), (1, 'Win'), (1, 'Win'), (1, 'Loss'), (2, 'Win'), (2, 'Win'), (3, 'Win'), (3, 'Win'), (3, 'Win');

SELECT coach_name FROM coaches INNER JOIN (SELECT team_id, SUM(CASE WHEN result = 'Win' THEN 1 ELSE 0 END) AS wins, SUM(CASE WHEN result = 'Loss' THEN 1 ELSE 0 END) AS losses FROM games GROUP BY team_id) AS subquery ON coaches.team_id = subquery.team_id WHERE subquery.wins >= (SELECT MAX(subquery2.wins) FROM subquery AS subquery2 WHERE subquery2.losses = subquery.losses) AND subquery.losses = (SELECT MIN(subquery3.losses) FROM subquery AS subquery3 WHERE subquery3.wins = subquery.wins);


Question: pgTAP test for Ownership (assertion 20).

/****************************************************************************/
-- Test schema_owner_is().
SELECT * FROM check_test(
    schema_owner_is(current_schema(), _get_schema_owner(current_schema()), 'mumble'),
	true,
    'schema_owner_is(schema, user, desc)',
    'mumble',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Ownership.


Question: Generate PostgreSQL SQL for: Who was the Constructor at the Argentine Grand Prix?

CREATE TABLE table_name_21 (constructor VARCHAR, race VARCHAR)

SELECT constructor FROM table_name_21 WHERE race = 'argentine grand prix';


Question: Generate PostgreSQL SQL for: What is the total number of casualties when there are 12 total deaths and more than 1 military death?

CREATE TABLE table_name_47 (total_casualties VARCHAR, total_deaths VARCHAR, military_deaths VARCHAR)

SELECT total_casualties FROM table_name_47 WHERE total_deaths = 12 AND military_deaths > 1;


Question: Which ocean has the minimum temperature?

CREATE TABLE temperature_readings (location TEXT, temperature FLOAT); INSERT INTO temperature_readings (location, temperature) VALUES ('Arctic Ocean', -2.34), ('North Atlantic', 12.56), ('North Pacific', 15.43);

SELECT location FROM temperature_readings WHERE temperature = (SELECT MIN(temperature) FROM temperature_readings);


Question: Generate PostgreSQL SQL for: Name the sabaean for sabʕ-

CREATE TABLE table_26919_6 (sabaean VARCHAR, arabic VARCHAR)

SELECT sabaean FROM table_26919_6 WHERE arabic = 'sabʕ-';


Question: Generate PostgreSQL SQL for: What regular season had a record of 16-12?

CREATE TABLE table_name_7 (reg_season VARCHAR, record VARCHAR)

SELECT reg_season FROM table_name_7 WHERE record = '16-12';


Question: Generate PostgreSQL SQL for: What was 2009, when 2012 was A, when 2003 was A, and then the Tournament was the Madrid Masters?

CREATE TABLE table_name_18 (tournament VARCHAR)

SELECT 2009 FROM table_name_18 WHERE 2012 = 'a' AND 2003 = 'a' AND tournament = 'madrid masters';


Question: Generate PostgreSQL SQL for: What incumbent won the district of texas 22?

CREATE TABLE table_1341598_44 (incumbent VARCHAR, district VARCHAR)

SELECT incumbent FROM table_1341598_44 WHERE district = 'Texas 22';


Question: Show veteran employment statistics for the state of 'California'

CREATE TABLE veteran_employment (state VARCHAR(255), employed INT, unemployed INT, total_veterans INT); INSERT INTO veteran_employment (state, employed, unemployed, total_veterans) VALUES ('California', 50000, 3000, 55000), ('New York', 45000, 4000, 50000);

SELECT employed, unemployed, total_veterans FROM veteran_employment WHERE state = 'California';


Question: Find the total sales of beauty products that are not vegan and not cruelty-free

CREATE TABLE sales (product_type VARCHAR(20), region VARCHAR(10), sales NUMERIC(10,2)); INSERT INTO sales (product_type, region, sales) VALUES ('lipstick', 'North', 500), ('mascara', 'East', 600), ('eyeshadow', 'West', 400), ('blush', 'South', 700), ('foundation', 'North', 800), ('lipstick', 'West', 900); CREATE TABLE products (product_type VARCHAR(20), vegan BOOLEAN, cruelty_free BOOLEAN); INSERT INTO products (product_type, vegan, cruelty_free) VALUES ('lipstick', FALSE, FALSE), ('mascara', TRUE, FALSE), ('eyeshadow', FALSE, TRUE), ('blush', FALSE, TRUE), ('foundation', FALSE, FALSE);

SELECT SUM(sales) FROM sales INNER JOIN products ON sales.product_type = products.product_type WHERE products.vegan = FALSE AND products.cruelty_free = FALSE;


Question: What are the labor productivity metrics for mining in Australia and Canada in 2019?

CREATE TABLE LaborProductivity (Country VARCHAR(255), Year INT, Sector VARCHAR(255), Productivity DECIMAL(5,2)); INSERT INTO LaborProductivity (Country, Year, Sector, Productivity) VALUES ('Australia', 2019, 'Mining', 45.67), ('Australia', 2019, 'Mining', 50.11), ('Canada', 2019, 'Mining', 60.00), ('Canada', 2019, 'Mining', 65.55);

SELECT Context.Country, Context.Productivity FROM LaborProductivity as Context WHERE Context.Year = 2019 AND Context.Sector = 'Mining' AND Context.Country IN ('Australia', 'Canada');


Question: Calculate the total volume of wastewater treated in 'Rio de Janeiro' for the first half of the year 2021

CREATE TABLE wastewater_treatment (region VARCHAR(50), date DATE, volume FLOAT); INSERT INTO wastewater_treatment (region, date, volume) VALUES ('Rio de Janeiro', '2021-01-01', 500), ('Rio de Janeiro', '2021-02-01', 550), ('Rio de Janeiro', '2021-03-01', 600);

SELECT SUM(volume) FROM wastewater_treatment WHERE region = 'Rio de Janeiro' AND date BETWEEN '2021-01-01' AND '2021-06-30';


Question: What is the minimum price of a product in the education_products table?

CREATE TABLE education_products (product_id INT, product_name TEXT, price DECIMAL); INSERT INTO education_products (product_id, product_name, price) VALUES (1, 'Sustainability Guidebook', 20), (2, 'Eco-Friendly Craft Kit', 30), (3, 'Educational Poster', 10);

SELECT MIN(price) FROM education_products;


Question: What was the total revenue for all artworks sold by the 'Impressionist' movement in the year 2010?

CREATE TABLE Artworks (artwork_id INT, movement VARCHAR(255), sale_year INT, revenue DECIMAL(10, 2));

SELECT SUM(revenue) FROM Artworks WHERE movement = 'Impressionist' AND sale_year = 2010;


Question: Generate PostgreSQL SQL for: What season saw 6 cup apps and 5 cup goals?

CREATE TABLE table_name_87 (season VARCHAR, cup_apps VARCHAR, cup_goals VARCHAR)

SELECT season FROM table_name_87 WHERE cup_apps = 6 AND cup_goals = 5;


Question: Generate PostgreSQL SQL for: What is the Date of the 1999 fifa confederations cup?

CREATE TABLE table_name_45 (date VARCHAR, competition VARCHAR)

SELECT date FROM table_name_45 WHERE competition = '1999 fifa confederations cup';


Question: Generate PostgreSQL SQL for: What is the time/retired for the driver emerson fittipaldi?

CREATE TABLE table_name_55 (time_retired VARCHAR, driver VARCHAR)

SELECT time_retired FROM table_name_55 WHERE driver = 'emerson fittipaldi';


Question: Generate PostgreSQL SQL for: Who was the opponent with the record of 4-0-0?

CREATE TABLE table_name_46 (opponent VARCHAR, record VARCHAR)

SELECT opponent FROM table_name_46 WHERE record = '4-0-0';


Question: What is the average energy consumption of hotels in Canada per square foot?

CREATE TABLE hotel_data(id INT, hotel_name TEXT, country TEXT, sqft INT, energy_consumption INT); INSERT INTO hotel_data (id, hotel_name, country, sqft, energy_consumption) VALUES (1, 'Hotel A', 'Canada', 10000, 1200), (2, 'Hotel B', 'Canada', 12000, 1400), (3, 'Hotel C', 'Canada', 15000, 1800);

SELECT AVG(energy_consumption / sqft) FROM hotel_data WHERE country = 'Canada';


Question: How many sustainable sourcing audits were conducted in 'California' and 'Texas'?

CREATE TABLE sourcing_audits (restaurant_name TEXT, location TEXT, audit_date DATE); INSERT INTO sourcing_audits (restaurant_name, location, audit_date) VALUES ('Restaurant A', 'California', '2021-06-01'), ('Restaurant B', 'California', '2021-07-15'), ('Restaurant C', 'Texas', '2021-08-05'), ('Restaurant D', 'California', '2021-09-01');

SELECT COUNT(*) FROM sourcing_audits WHERE location IN ('California', 'Texas');


Question: Generate PostgreSQL SQL for: Name the least attendance for 52-37 record

CREATE TABLE table_name_53 (attendance INTEGER, record VARCHAR)

SELECT MIN(attendance) FROM table_name_53 WHERE record = '52-37';


Question: What is the total number of workouts in the last month for members who identify as female and have a smartwatch?

CREATE TABLE Members (MemberID INT, Gender VARCHAR(10), HasSmartwatch BOOLEAN); CREATE TABLE Workouts (WorkoutID INT, MemberID INT, WorkoutDate DATE);

SELECT COUNT(*) FROM Workouts INNER JOIN Members ON Workouts.MemberID = Members.MemberID WHERE Members.Gender = 'female' AND Members.HasSmartwatch = TRUE AND WorkoutDate >= DATE_SUB(CURDATE(), INTERVAL 1 MONTH);


Question: How many police stations are there in New Delhi and Bangkok?

CREATE TABLE Stations (City VARCHAR(20), Number INT); INSERT INTO Stations (City, Number) VALUES ('New Delhi', 12), ('Bangkok', 8);

SELECT SUM(Number) FROM Stations WHERE City IN ('New Delhi', 'Bangkok');


Question: Select the total number of public libraries in New York City

CREATE TABLE public_libraries (library_id INT, name VARCHAR(255), location VARCHAR(255), city VARCHAR(255), state VARCHAR(255), zip INT); INSERT INTO public_libraries (library_id, name, location, city, state, zip) VALUES (1, 'New York Public Library', 'Fifth Avenue', 'New York', 'NY', 10003); INSERT INTO public_libraries (library_id, name, location, city, state, zip) VALUES (2, 'Brooklyn Public Library', 'Grand Army Plaza', 'Brooklyn', 'NY', 11238);

SELECT COUNT(*) FROM public_libraries WHERE city = 'New York';


Question: Generate PostgreSQL SQL for: Competition of friendly, and a Date of 03-jun-62 had what score?

CREATE TABLE table_name_72 (score VARCHAR, competition VARCHAR, date VARCHAR)

SELECT score FROM table_name_72 WHERE competition = 'friendly' AND date = '03-jun-62';


Question: Generate PostgreSQL SQL for: how many female dependents are there?

SELECT COUNT(*) FROM dependent WHERE sex = 'F';


Question: Update the location of the 'Batik' art to 'Indonesia' in the Arts table.

CREATE TABLE Arts (ArtID INT, ArtName VARCHAR(50), Type VARCHAR(50), Location VARCHAR(50)); INSERT INTO Arts (ArtID, ArtName, Type, Location) VALUES (1, 'Batik', 'Textile', 'Nigeria');

UPDATE Arts SET Location = 'Indonesia' WHERE ArtName = 'Batik';


Question: What is the total number of wildlife habitats for each type?

CREATE TABLE wildlife_habitat(type VARCHAR(255), count INT); INSERT INTO wildlife_habitat(type, count) VALUES ('Forest', 300), ('Wetland', 200), ('Grassland', 150), ('Desert', 50);

SELECT type, SUM(count) FROM wildlife_habitat;


Question: Generate PostgreSQL SQL for: What was the attendance on June 27?

CREATE TABLE table_name_6 (att INTEGER, date VARCHAR)

SELECT MIN(att) FROM table_name_6 WHERE date = 'june 27';


Question: Generate PostgreSQL SQL for: What is the lowest React, when Mark is 46.26 sb, and when Lane is greater than 6?

CREATE TABLE table_name_61 (react INTEGER, mark VARCHAR, lane VARCHAR)

SELECT MIN(react) FROM table_name_61 WHERE mark = '46.26 sb' AND lane > 6;


Question: What is the percentage of students who have completed a lifelong learning course in 'South High' school?

CREATE TABLE students_lifelong_learning (student_id INT, school_id INT, completed_course INT); INSERT INTO students_lifelong_learning VALUES (1, 1, 1); INSERT INTO students_lifelong_learning VALUES (2, 1, 0); INSERT INTO students_lifelong_learning VALUES (3, 2, 1); INSERT INTO students_lifelong_learning VALUES (4, 2, 1); CREATE TABLE school_roster (student_id INT, school_id INT, school_name VARCHAR(255)); INSERT INTO school_roster VALUES (1, 1, 'South High'); INSERT INTO school_roster VALUES (2, 1, 'South High'); INSERT INTO school_roster VALUES (3, 2, 'North Middle'); INSERT INTO school_roster VALUES (4, 2, 'North Middle');

SELECT s.school_name, 100.0 * SUM(CASE WHEN sl.completed_course = 1 THEN 1 ELSE 0 END) / COUNT(sr.student_id) AS completion_percentage FROM school_roster sr INNER JOIN students_lifelong_learning sl ON sr.student_id = sl.student_id INNER JOIN schools s ON sr.school_id = s.school_id WHERE s.school_name = 'South High' GROUP BY s.school_name;


Question: Generate PostgreSQL SQL for: What is team Yamaha with 3 points ranked?

CREATE TABLE table_name_8 (rank VARCHAR, team VARCHAR, points VARCHAR)

SELECT rank FROM table_name_8 WHERE team = 'yamaha' AND points = 3;


Question: Generate PostgreSQL SQL for: What is the highest Pick number that had a road number that was less than 6, featured Bob Dailey as a player, and which had a Reg GP bigger than 257?

CREATE TABLE table_name_43 (pick__number INTEGER, reg_gp VARCHAR, rd__number VARCHAR, player VARCHAR)

SELECT MAX(pick__number) FROM table_name_43 WHERE rd__number < 6 AND player = 'bob dailey' AND reg_gp > 257;


Question: Delete all records of founders who have not raised any funds.

CREATE TABLE founders (id INT, name TEXT, race TEXT, funds_raised FLOAT); INSERT INTO founders (id, name, race, funds_raised) VALUES (1, 'Alice', 'Asian', 5000000), (2, 'Bob', 'Black', NULL), (3, 'Charlie', 'Latinx', 3000000), (4, 'Diana', 'White', 1000000), (5, 'Eve', 'Asian', NULL), (6, 'Frank', 'Black', 2000000), (7, 'Grace', 'Latinx', NULL), (8, 'Hugo', 'White', 8000000);

DELETE FROM founders WHERE funds_raised IS NULL;


Question: Generate PostgreSQL SQL for: What is Wheel Arrangement, when Quantity Made is 44?

CREATE TABLE table_name_8 (wheel_arrangement VARCHAR, quantity_made VARCHAR)

SELECT wheel_arrangement FROM table_name_8 WHERE quantity_made = '44';


Question: Generate PostgreSQL SQL for: What is the pick number average for the player who was drafted before round 7, and went to college at Tennessee?

CREATE TABLE table_name_40 (pick__number INTEGER, round VARCHAR, college VARCHAR)

SELECT AVG(pick__number) FROM table_name_40 WHERE round < 7 AND college = 'tennessee';


Question: Write the DML statement from PostgreSQL regression test 'compression_lz4' (example 17).

INSERT INTO cmmove3 SELECT * FROM cmdata_pglz;

Explanation: DML from PostgreSQL core regression test for Compression Lz4.


Question: Generate PostgreSQL SQL for: On what date was the record 4-2?

CREATE TABLE table_name_66 (date VARCHAR, record VARCHAR)

SELECT date FROM table_name_66 WHERE record = '4-2';


Question: Generate PostgreSQL SQL for: What are the average, maximum, and minimum number of floors for all buildings?

SELECT AVG(floors), MAX(floors), MIN(floors) FROM building;


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

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


Question: Identify the states with increasing water consumption in the last 6 months.

SELECT state FROM monthly_usage WHERE consumption > (SELECT consumption FROM monthly_usage WHERE state = monthly_usage.state AND month = DATE_SUB(month, INTERVAL 1 MONTH)) GROUP BY state HAVING COUNT(*) = 6;


Question: Generate PostgreSQL SQL for: What is the quantity made number for the quantity preserved 4-6-0 — ooooo — ten-wheeler?

CREATE TABLE table_name_65 (quantity_made VARCHAR, quantity_preserved VARCHAR)

SELECT quantity_made FROM table_name_65 WHERE quantity_preserved = '4-6-0 — ooooo — ten-wheeler';


Question: Show the total number of game sessions for each game in the 'GameSessions' table

CREATE TABLE GameSessions (GameID INT, SessionDuration TIME);

SELECT GameID, COUNT(*) as TotalGameSessions FROM GameSessions GROUP BY GameID;


Question: Insert a new team in the Teams table

CREATE TABLE Teams (TeamID INT, TeamName VARCHAR(50), City VARCHAR(50), Sport VARCHAR(20), EstablishedYear INT);

INSERT INTO Teams (TeamID, TeamName, City, Sport, EstablishedYear) VALUES (3, 'Atlanta United FC', 'Atlanta', 'Soccer', 2017);


Question: List the states with water usage greater than 5000 in 2021.

CREATE TABLE water_usage(state VARCHAR(20), year INT, usage FLOAT);

SELECT state FROM water_usage WHERE year=2021 GROUP BY state HAVING SUM(usage) > 5000;


Question: What is the total number of trees planted for habitat preservation in the Congo Basin?

CREATE TABLE Tree_Planting (Id INT, Planting_Date DATE, Trees_Planted INT, Location VARCHAR(50)); INSERT INTO Tree_Planting (Id, Planting_Date, Trees_Planted, Location) VALUES (1, '2022-01-01', 500, 'Congo Basin'); INSERT INTO Tree_Planting (Id, Planting_Date, Trees_Planted, Location) VALUES (2, '2022-01-02', 700, 'Congo Basin');

SELECT SUM(Trees_Planted) FROM Tree_Planting WHERE Location = 'Congo Basin';


Question: Find the number of mental health parity violations by state in the last 6 months.

CREATE TABLE if not exists mental_health_parity (violation_id INT, violation_date DATE, state VARCHAR(255));

SELECT COUNT(*), state FROM mental_health_parity WHERE violation_date >= DATEADD(month, -6, GETDATE()) GROUP BY state;


Question: Generate PostgreSQL SQL for: who is the the pole position with rnd being 16

CREATE TABLE table_14638077_2 (pole_position VARCHAR, rnd VARCHAR)

SELECT pole_position FROM table_14638077_2 WHERE rnd = 16;


Question: Generate PostgreSQL SQL for: How many points did the opponent score on Sept. 14?

CREATE TABLE table_16677887_2 (opponents INTEGER, date VARCHAR)

SELECT MAX(opponents) FROM table_16677887_2 WHERE date = 'Sept. 14';


Question: Generate PostgreSQL SQL for: What was the venue when the home team was Fitzroy?

CREATE TABLE table_name_76 (venue VARCHAR, home_team VARCHAR)

SELECT venue FROM table_name_76 WHERE home_team = 'fitzroy';


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

UPDATE temporal_rng SET valid_at = daterange('2018-01-15', '2018-02-15')
  WHERE id = '[2,3)';

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


Question: What is the total distance covered by all runners in the 2019 marathon?

CREATE TABLE runners (id INT, name TEXT, distance FLOAT, marathon INT); INSERT INTO runners (id, name, distance, marathon) VALUES (1, 'John Doe', 42.2, 2019), (2, 'Jane Smith', 40.5, 2019), (3, 'Alberto Rodriguez', 38.7, 2019);

SELECT SUM(distance) FROM runners WHERE marathon = 2019;


Question: How many patients have 'Anxiety' as their primary diagnosis in 'clinic_NY'?

CREATE TABLE clinic_NY (patient_id INT, name VARCHAR(50), primary_diagnosis VARCHAR(50)); INSERT INTO clinic_NY (patient_id, name, primary_diagnosis) VALUES (1, 'James Johnson', 'Anxiety'), (2, 'Sophia Williams', 'Depression'), (3, 'Michael Brown', 'Anxiety');

SELECT COUNT(*) FROM clinic_NY WHERE primary_diagnosis = 'Anxiety';


Question: Generate PostgreSQL SQL for: Which driver had points over 252 in the season of 2012 with a percentage of possible points at 55.60%?

CREATE TABLE table_name_40 (driver VARCHAR, percentage_of_possible_points VARCHAR, points VARCHAR, season VARCHAR)

SELECT driver FROM table_name_40 WHERE points > 252 AND season = '2012' AND percentage_of_possible_points = '55.60%';


Question: Generate PostgreSQL SQL for: Which position has 50+12 points and fewer than 10 draws?

CREATE TABLE table_name_92 (position INTEGER, points VARCHAR, draws VARCHAR)

SELECT MAX(position) FROM table_name_92 WHERE points = '50+12' AND draws < 10;


Question: Generate PostgreSQL SQL for: What is the population (1991) where population (2002) was  14250?

CREATE TABLE table_2562572_7 (population__1991_ VARCHAR, population__2002_ VARCHAR)

SELECT COUNT(population__1991_) FROM table_2562572_7 WHERE population__2002_ = 14250;


Question: What is the total budget allocated to each department?

CREATE TABLE Departments (id INT, department_name TEXT, budget_allocated FLOAT);

SELECT department_name, SUM(budget_allocated) as total_budget FROM Departments GROUP BY department_name;


Question: Generate PostgreSQL SQL for: What Brazil scorers have a 1-1 Score?

CREATE TABLE table_name_93 (brazil_scorers VARCHAR, score VARCHAR)

SELECT brazil_scorers FROM table_name_93 WHERE score = '1-1';


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

SELECT m.*
  FROM pg_statistic_ext s, pg_statistic_ext_data d,
       pg_mcv_list_items(d.stxdmcv) m
 WHERE s.stxname = 'mcv_lists_stats'
   AND d.stxoid = s.oid;

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

SELECT count(*) FROM (SELECT m.*
  FROM pg_statistic_ext s, pg_statistic_ext_data d,
       pg_mcv_list_items(d.stxdmcv) m
 WHERE s.stxname = 'mcv_lists_stats'
   AND d.stxoid = s.oid) AS _sub;


Question: Generate PostgreSQL SQL for: How many airlines does Russia has?

SELECT COUNT(*) FROM airlines WHERE country = 'Russia';


Question: What is the number of reported cases of Zika virus by month in 2017 in Florida?

CREATE TABLE zika_virus (id INT, patient_id INT, report_date DATE, state VARCHAR(20));

SELECT COUNT(*) FROM zika_virus WHERE state = 'Florida' AND YEAR(report_date) = 2017 GROUP BY MONTH(report_date);


Question: Generate PostgreSQL SQL for: what are every one of the rivals in conclusive where title is zürich

CREATE TABLE table_23197088_4 (opponents_in_final VARCHAR, championship VARCHAR)

SELECT opponents_in_final FROM table_23197088_4 WHERE championship = 'Zürich';


Question: Generate PostgreSQL SQL for: which NHL team has a College/Junior/Club Team (League) of shattuck-saint mary's school (midget major aaa)?

CREATE TABLE table_name_63 (nhl_team VARCHAR, college_junior_club_team__league_ VARCHAR)

SELECT nhl_team FROM table_name_63 WHERE college_junior_club_team__league_ = 'shattuck-saint mary's school (midget major aaa)';


Question: Generate PostgreSQL SQL for: Name the high rebounds for american airlines center 20,557

CREATE TABLE table_23284271_11 (high_rebounds VARCHAR, location_attendance VARCHAR)

SELECT high_rebounds FROM table_23284271_11 WHERE location_attendance = 'American Airlines Center 20,557';


Question: Generate PostgreSQL SQL for: List the most common type of competition.

CREATE TABLE competition (Competition_type VARCHAR)

SELECT Competition_type FROM competition GROUP BY Competition_type ORDER BY COUNT(*) DESC LIMIT 1;


Question: Generate PostgreSQL SQL for: Which Mountains classification has a Team classification of quick step?

CREATE TABLE table_name_81 (mountains_classification VARCHAR, team_classification VARCHAR)

SELECT mountains_classification FROM table_name_81 WHERE team_classification = 'quick step';


Question: Generate PostgreSQL SQL for: What format is catalogue WPCR13504 in?

CREATE TABLE table_name_94 (format VARCHAR, catalogue VARCHAR)

SELECT format FROM table_name_94 WHERE catalogue = 'wpcr13504';


Question: Update the genre of the TV show 'Breaking Bad' to 'Crime' in the 'TV_Shows' table.

CREATE TABLE TV_Shows (show_id INT PRIMARY KEY, name VARCHAR(100), genre VARCHAR(50)); INSERT INTO TV_Shows (show_id, name, genre) VALUES (1, 'Breaking Bad', 'Drama'), (2, 'Stranger Things', 'Sci-fi');

UPDATE TV_Shows SET genre = 'Crime' WHERE name = 'Breaking Bad';


Question: Generate PostgreSQL SQL for: Rider of stéphane mertens had what lowest points?

CREATE TABLE table_name_84 (points INTEGER, rider VARCHAR)

SELECT MIN(points) FROM table_name_84 WHERE rider = 'stéphane mertens';


Question: Which players have the highest win rate in FPS games?

CREATE TABLE Players (PlayerID INT, Name VARCHAR(50), Wins INT, Losses INT); INSERT INTO Players (PlayerID, Name, Wins, Losses) VALUES (1, 'Bob', 100, 20);

SELECT p.Name, (SUM(p.Wins) / (SUM(p.Wins) + SUM(p.Losses))) as WinRate FROM Players p JOIN GameResults gr ON p.PlayerID = gr.PlayerID WHERE gr.GameType = 'FPS' GROUP BY p.Name ORDER BY WinRate DESC;


Question: Generate PostgreSQL SQL for: What is the last year that someone is first elected?

CREATE TABLE table_1341690_9 (first_elected INTEGER)

SELECT MAX(first_elected) FROM table_1341690_9;


Question: What is the distribution of aircraft engine types by manufacturer?

CREATE TABLE aircraft_engines (id INT, manufacturer VARCHAR(255), engine_type VARCHAR(255), engine_count INT);

SELECT manufacturer, engine_type, SUM(engine_count) as total_engine_count FROM aircraft_engines GROUP BY 1, 2;


Question: What is the total donation and investment amount for each cause, separated by donations and investments, in the 'cause_donations' and 'cause_investments' tables, respectively, ordered by the total amount in descending order?

CREATE TABLE cause_donations (cause_id INT, cause_name TEXT, total_donations DECIMAL(10, 2)); CREATE TABLE cause_investments (cause_id INT, cause_name TEXT, total_investments DECIMAL(10, 2));

SELECT cause_name, SUM(total_donations) as total_donation_amount FROM cause_donations GROUP BY cause_name UNION ALL SELECT cause_name, SUM(total_investments) as total_investment_amount FROM cause_investments GROUP BY cause_name ORDER BY total_donation_amount DESC;


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

SELECT * FROM test_macaddr WHERE i<='22:00:5c:08:55:08'::macaddr ORDER BY i;


Question: What is the minimum number of launches for any SpaceX mission?

CREATE TABLE SpaceX_Missions (Id INT, Name VARCHAR(50), NumLaunches INT); INSERT INTO SpaceX_Missions (Id, Name, NumLaunches) VALUES (1, 'Falcon1', 5), (2, 'Falcon9', 10), (3, 'FalconHeavy', 3);

SELECT MIN(NumLaunches) FROM SpaceX_Missions;


Question: Generate PostgreSQL SQL for: Which rank has a more than 0 silver, 4 bronze, and a total smaller than 10?

CREATE TABLE table_name_34 (rank INTEGER, total VARCHAR, silver VARCHAR, bronze VARCHAR)

SELECT SUM(rank) FROM table_name_34 WHERE silver > 0 AND bronze = 4 AND total < 10;


Question: Generate PostgreSQL SQL for: What is the record for game where Columbus is visitor, Phoenix is home, and decision is made by Denis?

CREATE TABLE table_name_3 (record VARCHAR, home VARCHAR, visitor VARCHAR, decision VARCHAR)

SELECT record FROM table_name_3 WHERE visitor = 'columbus' AND decision = 'denis' AND home = 'phoenix';


Question: Generate PostgreSQL SQL for: What year did the Capital City Giants have a game with the final score of 8-0?

CREATE TABLE table_name_54 (year INTEGER, team VARCHAR, score VARCHAR)

SELECT AVG(year) FROM table_name_54 WHERE team = 'capital city giants' AND score = '8-0';


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

-- reverse-listing of various special function syntaxes required by SQL

create view tt201v as
select
  ('2022-12-01'::date + '1 day'::interval) at time zone 'UTC' as atz,
  extract(day from now()) as extr,
  (now(), '1 day'::interval) overlaps
    (current_timestamp(2), '1 day'::interval) as o,
  'foo' is normalized isn,
  'foo' is nfkc normalized isnn,
  normalize('foo') as n,
  normalize('foo', nfkd) as nfkd,
  overlay('foo' placing 'bar' from 2) as ovl,
  overlay('foo' placing 'bar' from 2 for 3) as ovl2,
  position('foo' in 'foobar') as p,
  substring('foo' from 2 for 3) as s,
  substring('foo' similar 'f' escape '#') as ss,
  substring('foo' from 'oo') as ssf,  -- historically-permitted abuse
  trim(' ' from ' foo ') as bt,
  trim(leading ' ' from ' foo ') as lt,
  trim(trailing ' foo ') as rt,
  trim(E'\\000'::bytea from E'\\000Tom\\000'::bytea) as btb,
  trim(leading E'\\000'::bytea from E'\\000Tom\\000'::bytea) as ltb,
  trim(trailing E'\\000'::bytea from E'\\000Tom\\000'::bytea) as rtb,
  CURRENT_DATE as cd,
  (select * from CURRENT_DATE) as cd2,
  CURRENT_TIME as ct,
  (select * from CURRENT_TIME) as ct2,
  CURRENT_TIME (1) as ct3,
  (select * from CURRENT_TIME (1)) as ct4,
  CURRENT_TIMESTAMP as ct5,
  (select * from CURRENT_TIMESTAMP) as ct6,
  CURRENT_TIMESTAMP (1) as ct7,
  (select * from CURRENT_TIMESTAMP (1)) as ct8,
  LOCALTIME as lt1,
  (select * from LOCALTIME) as lt2,
  LOCALTIME (1) as lt3,
  (select * from LOCALTIME (1)) as lt4,
  LOCALTIMESTAMP as lt5,
  (select * from LOCALTIMESTAMP) as lt6,
  LOCALTIMESTAMP (1) as lt7,
  (select * from LOCALTIMESTAMP (1)) as lt8,
  CURRENT_CATALOG as ca,
  (select * from CURRENT_CATALOG) as ca2,
  CURRENT_ROLE as cr,
  (select * from CURRENT_ROLE) as cr2,
  CURRENT_SCHEMA as cs,
  (select * from CURRENT_SCHEMA) as cs2,
  CURRENT_USER as cu,
  (select * from CURRENT_USER) as cu2,
  USER as us,
  (select * from USER) as us2,
  SESSION_USER seu,
  (select * from SESSION_USER) as seu2,
  SYSTEM_USER as su,
  (select * from SYSTEM_USER) as su2;

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


Question: Generate PostgreSQL SQL for: What is the lowest First Elected, when District is "Massachusetts 10"?

CREATE TABLE table_name_40 (first_elected INTEGER, district VARCHAR)

SELECT MIN(first_elected) FROM table_name_40 WHERE district = 'massachusetts 10';


Question: Generate PostgreSQL SQL for: Which Against has a Draws larger than 0, a Losses smaller than 16, and a Wins smaller than 4?

CREATE TABLE table_name_50 (against INTEGER, wins VARCHAR, draws VARCHAR, losses VARCHAR)

SELECT MAX(against) FROM table_name_50 WHERE draws > 0 AND losses < 16 AND wins < 4;


Question: How many transactions were made by each client in Q1 of 2021?

CREATE TABLE clients (client_id INT, name VARCHAR(50)); CREATE TABLE transactions (transaction_id INT, client_id INT, date DATE); INSERT INTO clients (client_id, name) VALUES (1, 'John Doe'), (2, 'Jane Smith'); INSERT INTO transactions (transaction_id, client_id, date) VALUES (1, 1, '2021-01-01'), (2, 1, '2021-01-15'), (3, 2, '2021-01-30');

SELECT c.client_id, c.name, COUNT(*) FROM clients c INNER JOIN transactions t ON c.client_id = t.client_id WHERE t.date BETWEEN '2021-01-01' AND '2021-03-31' GROUP BY c.client_id, c.name;


Question: What's the total gross for the director with ID 1?

CREATE TABLE movies(movie_id INT, title VARCHAR(50), director_id INT, budget INT, gross INT); INSERT INTO movies(movie_id, title, director_id, budget, gross) VALUES (1, 'Inception', 1, 160000000, 825532381), (2, 'Interstellar', 1, 165000000, 675044311), (3, 'The Dark Knight', 1, 185000000, 1004558444), (4, 'The Avengers', 2, 220000000, 1518812988), (5, 'Iron Man 3', 2, 200000000, 1215429827);

SELECT SUM(gross) FROM movies WHERE director_id = 1;


Question: Delete all attorneys from the 'attorneys' table with attorney_email containing '@gmail.com'

CREATE TABLE attorneys (attorney_id INT, attorney_name VARCHAR(50), attorney_email VARCHAR(50), attorney_phone VARCHAR(15)); INSERT INTO attorneys (attorney_id, attorney_name, attorney_email, attorney_phone) VALUES (1, 'John Smith', 'john.smith@lawfirm.com', '555-555-1111');

DELETE FROM attorneys WHERE attorney_email LIKE '%@gmail.com';


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

CREATE TYPE query_int (
	INTERNALLENGTH = -1,
	INPUT = bqarr_in,
	OUTPUT = bqarr_out
);


Question: How many teachers participated in professional development courses in '2021'?

CREATE TABLE teacher_professional_development (teacher_id INT, course_year INT); INSERT INTO teacher_professional_development (teacher_id, course_year) VALUES (1, 2020), (2, 2021), (3, 2021), (4, 2019);

SELECT COUNT(*) FROM teacher_professional_development WHERE course_year = 2021;


Question: Generate PostgreSQL SQL for: Name the total number of Round in liverpool , england?

CREATE TABLE table_name_73 (round VARCHAR, location VARCHAR)

SELECT COUNT(round) FROM table_name_73 WHERE location = 'liverpool , england';


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

--
-- External C-functions for R-tree methods
--

-- Comparison methods

CREATE FUNCTION cube_eq(cube, cube)
RETURNS bool
AS 'MODULE_PATHNAME'
LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;


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

select interval '-0.1 weeks -9223372036854775808 microseconds';

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

SELECT count(*) FROM (select interval '-0.1 weeks -9223372036854775808 microseconds') AS _sub;


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

INSERT INTO tbl_created_outside_xact(id) VALUES('1');

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


Question: Generate PostgreSQL SQL for: When was millwall the home team?

CREATE TABLE table_name_11 (date VARCHAR, home_team VARCHAR)

SELECT date FROM table_name_11 WHERE home_team = 'millwall';


Question: What is the minimum fare for buses in each city?

CREATE TABLE buses (route_id INT, fare DECIMAL(5,2), city VARCHAR(20)); CREATE TABLE routes (route_id INT, city VARCHAR(20));

SELECT r.city, MIN(b.fare) FROM buses b JOIN routes r ON b.route_id = r.route_id GROUP BY r.city;


Question: Which countries have more than 5 excavated artifacts?

CREATE TABLE Artifacts (ArtifactID int, Name text, SiteID int, ExcavationYear int, Country text); INSERT INTO Artifacts (ArtifactID, Name, SiteID, ExcavationYear, Country) VALUES (1, 'Artifact1', 3, 2000, 'CountryA');

SELECT Country, COUNT(*) as ArtifactCount FROM Artifacts GROUP BY Country HAVING ArtifactCount > 5;


Question: What is the average dissolved oxygen level in the Atlantic Ocean by region?

CREATE TABLE ocean_regions (region VARCHAR(255), id INTEGER); INSERT INTO ocean_regions (region, id) VALUES ('North Atlantic', 1), ('South Atlantic', 2); CREATE TABLE dissolved_oxygen (region_id INTEGER, value FLOAT);

SELECT o.region, AVG(d.value) FROM dissolved_oxygen d JOIN ocean_regions o ON d.region_id = o.id GROUP BY o.region;


Question: What's the average ESG rating for companies in the healthcare sector?

CREATE TABLE companies (id INT, name TEXT, sector TEXT, ESG_rating FLOAT); INSERT INTO companies (id, name, sector, ESG_rating) VALUES (1, 'Innovative Healthcare', 'Healthcare', 8.3); INSERT INTO companies (id, name, sector, ESG_rating) VALUES (2, 'GreenTech Medical', 'Healthcare', 7.9);

SELECT AVG(ESG_rating) FROM companies WHERE sector = 'Healthcare';


Question: How many marine species are found in the Southern Ocean?

CREATE TABLE marine_species (name VARCHAR(50), common_name VARCHAR(50), location VARCHAR(50));

SELECT COUNT(*) FROM marine_species WHERE location = 'Southern Ocean';


Question: Generate PostgreSQL SQL for: How many people attended the game with a Tie no of 30?

CREATE TABLE table_name_88 (attendance VARCHAR, tie_no VARCHAR)

SELECT attendance FROM table_name_88 WHERE tie_no = '30';


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

SELECT a, a <-> '10:57:11' FROM timetmp ORDER BY a <-> '10:57:11' LIMIT 3;

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


Question: Generate PostgreSQL SQL for: What is the total amount of money spent by Lucas Mancini?

CREATE TABLE invoices (total INTEGER, customer_id VARCHAR); CREATE TABLE customers (id VARCHAR, first_name VARCHAR, last_name VARCHAR)

SELECT SUM(T2.total) FROM customers AS T1 JOIN invoices AS T2 ON T1.id = T2.customer_id WHERE T1.first_name = 'Lucas' AND T1.last_name = 'Mancini';


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

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


Question: Generate PostgreSQL SQL for: What's the service number of the Pune Duronto train that departures at 21:35?

CREATE TABLE table_23477312_1 (service VARCHAR, train_name VARCHAR, departure VARCHAR)

SELECT service FROM table_23477312_1 WHERE train_name = 'Pune Duronto' AND departure = '21:35';


Question: Generate PostgreSQL SQL for: What is the name of the away team that played at Kardinia Park?

CREATE TABLE table_name_2 (away_team VARCHAR, venue VARCHAR)

SELECT away_team FROM table_name_2 WHERE venue = 'kardinia park';


Question: What is the total number of tickets sold for events in the 'theater' category?

CREATE TABLE events (id INT, name TEXT, category TEXT, tickets_sold INT); INSERT INTO events (id, name, category, tickets_sold) VALUES (1, 'Concert', 'music', 200), (2, 'Play', 'theater', 150), (3, 'Festival', 'music', 300);

SELECT SUM(tickets_sold) FROM events WHERE category = 'theater';


Question: Generate PostgreSQL SQL for: Which opponent plays against the Pohang Steelers?

CREATE TABLE table_name_58 (name VARCHAR, opponent VARCHAR)

SELECT name FROM table_name_58 WHERE opponent = 'pohang steelers';


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

Explanation: DML from PostgreSQL core regression test for Case.


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

SELECT earth_box(ll_to_earth(0,0),
       earth_distance(ll_to_earth(0,0),ll_to_earth(0,0.01))*.57735) @>
       ll_to_earth(0,0.01);

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


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

ALTER EXTENSION pgtap ADD FUNCTION hasnt_fk ( NAME );

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


Question: Generate PostgreSQL SQL for: Who was the home team of the game with manu ginóbili (34) as the leading scorer?

CREATE TABLE table_name_74 (home VARCHAR, leading_scorer VARCHAR)

SELECT home FROM table_name_74 WHERE leading_scorer = 'manu ginóbili (34)';


Question: Generate PostgreSQL SQL for: What player was chosen for the Chicago Sky?

CREATE TABLE table_name_57 (player VARCHAR, wnba_team VARCHAR)

SELECT player FROM table_name_57 WHERE wnba_team = 'chicago sky';


Question: Generate PostgreSQL SQL for: What is the highest number of byes when draws are larger than 0?

CREATE TABLE table_name_37 (byes INTEGER, draws INTEGER)

SELECT MAX(byes) FROM table_name_37 WHERE draws > 0;


Question: What is the total crop yield for small-scale farms (less than 50 acres) in the United States?

CREATE TABLE farms (id INT, farm_name VARCHAR(50), acres INT, total_yield INT); INSERT INTO farms (id, farm_name, acres, total_yield) VALUES (1, 'Farm 1', 25, 10000), (2, 'Farm 2', 75, 20000), (3, 'Farm 3', 45, 15000), (4, 'Farm 4', 55, 25000), (5, 'Farm 5', 35, 12000);

SELECT SUM(total_yield) FROM farms WHERE acres < 50;


Question: Generate PostgreSQL SQL for: Which game number had a location/attendance of US Airways Center 7,311 respectively?

CREATE TABLE table_17118657_7 (game INTEGER, location_attendance VARCHAR)

SELECT MAX(game) FROM table_17118657_7 WHERE location_attendance = 'US Airways Center 7,311';


Question: What is the total billing amount for cases resolved in January 2021?

CREATE TABLE cases (case_id INT, case_status VARCHAR(10), resolved_date DATE, billing_amount DECIMAL); INSERT INTO cases (case_id, case_status, resolved_date, billing_amount) VALUES (1, 'Defendant', '2021-01-15', 5000.00), (2, 'Plaintiff', '2021-02-20', 4000.00), (3, 'Defendant', '2021-03-05', 6000.00);

SELECT SUM(billing_amount) FROM cases WHERE resolved_date >= '2021-01-01' AND resolved_date < '2021-02-01';


Question: What is the average age of refugees supported by 'Red Crescent' in 'Europe'?

CREATE TABLE refugee (id INT, name VARCHAR(255), age INT, location VARCHAR(255), supported_by VARCHAR(255), support_date DATE); INSERT INTO refugee (id, name, age, location, supported_by, support_date) VALUES (1, 'Jane Doe', 35, 'Europe', 'Red Crescent', '2022-01-01');

SELECT AVG(age) FROM refugee WHERE location = 'Europe' AND supported_by = 'Red Crescent';


Question: What is the minimum response time for emergency calls in each district?

CREATE TABLE emergency_calls (call_id INT, district TEXT, response_time FLOAT); INSERT INTO emergency_calls (call_id, district, response_time) VALUES (1, 'Downtown', 10.5), (2, 'Uptown', 12.0), (3, 'Harbor', 8.0);

SELECT district, MIN(response_time) FROM emergency_calls GROUP BY district;


Question: Generate PostgreSQL SQL for: What is the Visitor with a Home with chicago, and a Score of 3 – 2?

CREATE TABLE table_name_34 (visitor VARCHAR, home VARCHAR, score VARCHAR)

SELECT visitor FROM table_name_34 WHERE home = 'chicago' AND score = '3 – 2';


Question: Generate PostgreSQL SQL for: How many areas are named West Isles?

CREATE TABLE table_170969_2 (area_km_2 VARCHAR, official_name VARCHAR)

SELECT COUNT(area_km_2) FROM table_170969_2 WHERE official_name = 'West Isles';


Question: Generate PostgreSQL SQL for: What is the mountain classification name if the winner is Bernhard Eisel?

CREATE TABLE table_22941863_19 (mountains_classification VARCHAR, winner VARCHAR)

SELECT mountains_classification FROM table_22941863_19 WHERE winner = 'Bernhard Eisel';


Question: PostgreSQL Rowtypes: show example 1.

CREATE TYPE complex AS ( r double precision, i double precision ); CREATE TYPE inventory_item AS ( name text, supplier_id integer, price numeric );

Explanation: Example from PostgreSQL documentation on Rowtypes.


Question: PostgreSQL regression test 'union': Write the SELECT query (example 13).

SELECT 1.0::float8 AS two UNION ALL SELECT 1 ORDER BY 1;

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

SELECT count(*) FROM (SELECT 1.0::float8 AS two UNION ALL SELECT 1 ORDER BY 1) AS _sub;


Question: What is the maximum salary in the Engineering department?

CREATE TABLE Employees (EmployeeID INT, Department VARCHAR(20), Salary FLOAT); INSERT INTO Employees (EmployeeID, Department, Salary) VALUES (1, 'IT', 75000.00), (2, 'IT', 70000.00), (3, 'Engineering', 95000.00), (4, 'Finance', 85000.00);

SELECT MAX(Salary) FROM Employees WHERE Department = 'Engineering';


Question: Generate PostgreSQL SQL for: What is the percentage of all the literate people where females are 73.17?

CREATE TABLE table_14598_9 (literate_persons___percentage_ VARCHAR, females___percentage_ VARCHAR)

SELECT literate_persons___percentage_ FROM table_14598_9 WHERE females___percentage_ = '73.17';


Question: What is the maximum number of citizens participating in public meetings for each meeting type in 'Meetings' table?

CREATE TABLE Meetings (MeetingID INT, MeetingType VARCHAR(20), Citizens INT); INSERT INTO Meetings (MeetingID, MeetingType, Citizens) VALUES (1, 'TownHall', 50), (2, 'Committee', 30), (3, 'TownHall', 60);

SELECT MeetingType, MAX(Citizens) AS MaxCitizens FROM Meetings GROUP BY MeetingType;


Question: Generate PostgreSQL SQL for: What was Carlton's score as the home team?

CREATE TABLE table_name_65 (home_team VARCHAR)

SELECT home_team AS score FROM table_name_65 WHERE home_team = 'carlton';


Question: How many volunteers from underrepresented communities in Canada joined in 2020?

CREATE TABLE volunteers (volunteer_id INT, joined_date DATE, underrepresented_community BOOLEAN); INSERT INTO volunteers (volunteer_id, joined_date, underrepresented_community) VALUES (1, '2020-05-12', true), (2, '2019-11-04', false);

SELECT COUNT(*) FROM volunteers WHERE joined_date BETWEEN '2020-01-01' AND '2020-12-31' AND underrepresented_community = true AND country = 'Canada';


Question: What is the total number of employees in each department, and what percentage of them identify as LGBTQ+?

CREATE TABLE Employees (EmployeeID INT, FirstName VARCHAR(50), LastName VARCHAR(50), Department VARCHAR(50), Position VARCHAR(50), LGBTQ INT); INSERT INTO Employees (EmployeeID, FirstName, LastName, Department, Position, LGBTQ) VALUES (1, 'John', 'Doe', 'IT', 'Developer', 1), (2, 'Jane', 'Smith', 'IT', 'Developer', 0), (3, 'Alice', 'Johnson', 'IT', 'Manager', 1), (4, 'Bob', 'Brown', 'HR', 'Manager', 0);

SELECT Employees.Department, COUNT(Employees.EmployeeID) AS Total_Employees, (SUM(Employees.LGBTQ) / COUNT(Employees.EmployeeID)) * 100 AS Percentage_LGBTQ FROM Employees GROUP BY Employees.Department;


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

--
--
--
-- int2 ops
--
--
--
-- define the GiST support methods
CREATE FUNCTION gbt_int2_consistent(internal,int2,int2,oid,internal)
RETURNS bool
AS 'MODULE_PATHNAME'
LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;

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


Question: Generate PostgreSQL SQL for: Name the least week for opponent of washington redskins

CREATE TABLE table_name_87 (week INTEGER, opponent VARCHAR)

SELECT MIN(week) FROM table_name_87 WHERE opponent = 'washington redskins';


Question: What was the total budget for community development initiatives in Tanzania in 2018?

CREATE TABLE CommunityDevelopment (id INT, country VARCHAR(50), initiative VARCHAR(50), budget FLOAT, year INT); INSERT INTO CommunityDevelopment (id, country, initiative, budget, year) VALUES (1, 'Tanzania', 'Youth Skills Training', 300000, 2018), (2, 'Tanzania', 'Community Health Center', 500000, 2019), (3, 'Kenya', 'Women Empowerment Program', 400000, 2018);

SELECT SUM(budget) FROM CommunityDevelopment WHERE country = 'Tanzania' AND year = 2018;


Question: List all marine research facilities in the Southern Ocean.

CREATE TABLE marine_research_facilities (id INT, name TEXT, location TEXT, ocean TEXT); INSERT INTO marine_research_facilities (id, name, location, ocean) VALUES (1, 'Palmer Station', 'Antarctica', 'Southern'), (2, 'McMurdo Station', 'Antarctica', 'Southern');

SELECT * FROM marine_research_facilities WHERE ocean = 'Southern';


Question: Generate PostgreSQL SQL for: Who used the Ford Cosworth DFV 3.0 v8 engine in rounds 3-12, with a G tire?

CREATE TABLE table_name_22 (driver VARCHAR, tyre VARCHAR, engine VARCHAR, rounds VARCHAR)

SELECT driver FROM table_name_22 WHERE engine = 'ford cosworth dfv 3.0 v8' AND rounds = '3-12' AND tyre = 'g';


Question: What is the average age of patients who have completed the recovery program for depression in Canada?

CREATE TABLE patients (patient_id INT, age INT, condition VARCHAR(50), country VARCHAR(50)); INSERT INTO patients (patient_id, age, condition, country) VALUES (1, 35, 'Depression', 'Canada'); CREATE TABLE recovery_program (program_id INT, patient_id INT, completion_date DATE); INSERT INTO recovery_program (program_id, patient_id, completion_date) VALUES (1, 1, '2020-03-01');

SELECT AVG(patients.age) FROM patients JOIN recovery_program ON patients.patient_id = recovery_program.patient_id WHERE patients.condition = 'Depression' AND patients.country = 'Canada';


Question: Generate PostgreSQL SQL for: In what year did a car have a yamaha v12 engine and a brabham bt60y chassis

CREATE TABLE table_name_70 (year VARCHAR, engine VARCHAR, chassis VARCHAR)

SELECT year FROM table_name_70 WHERE engine = 'yamaha v12' AND chassis = 'brabham bt60y';


Question: Insert data into 'GameDesign'

CREATE TABLE GameDesign (GameID INT PRIMARY KEY, GameName VARCHAR(50), Genre VARCHAR(50), Platform VARCHAR(50)); INSERT INTO GameDesign (GameID, GameName, Genre, Platform) VALUES (1, 'Fortnite', 'Battle Royale', 'PC'), (2, 'Among Us', 'Party', 'Mobile');

INSERT INTO GameDesign (GameID, GameName, Genre, Platform) VALUES (3, 'Minecraft', 'Sandbox', 'PC');


Question: Generate PostgreSQL SQL for: What is the highest # Of Constituency Votes, when Election is 2005?

CREATE TABLE table_name_22 (_number_of_constituency_votes INTEGER, election VARCHAR)

SELECT MAX(_number_of_constituency_votes) FROM table_name_22 WHERE election = 2005;


Question: Generate PostgreSQL SQL for: What is the week 3 with addison miller in week 2?

CREATE TABLE table_name_17 (week_3 VARCHAR, week_2 VARCHAR)

SELECT week_3 FROM table_name_17 WHERE week_2 = 'addison miller';


Question: Show landfill capacity data for landfills with capacity over 500,000 tons, sorted by capacity in descending order.

CREATE TABLE Landfills (id INT, name VARCHAR(255), capacity INT); INSERT INTO Landfills (id, name, capacity) VALUES (1, 'SiteA', 600000), (2, 'SiteB', 400000), (3, 'SiteC', 700000), (4, 'SiteD', 300000);

SELECT * FROM Landfills WHERE capacity > 500000 ORDER BY capacity DESC;