Question: How many startups were founded in the healthcare sector in 2020?

CREATE TABLE startup (id INT, name TEXT, founding_year INT, industry TEXT); INSERT INTO startup (id, name, founding_year, industry) VALUES (1, 'HealthcareOne', 2020, 'Healthcare'); INSERT INTO startup (id, name, founding_year, industry) VALUES (2, 'TechStart', 2018, 'Tech');

SELECT COUNT(*) FROM startup WHERE founding_year = 2020 AND industry = 'Healthcare';


Question: Generate PostgreSQL SQL for: What date did Episode 22 originally air?

CREATE TABLE table_23392257_4 (original_airdate VARCHAR, _number VARCHAR)

SELECT COUNT(original_airdate) FROM table_23392257_4 WHERE _number = 22;


Question: What is the number of events per genre, for visual arts events in Paris, in descending order?

CREATE TABLE Events (id INT, event_name VARCHAR(100), event_type VARCHAR(50), location VARCHAR(100), start_time TIMESTAMP, end_time TIMESTAMP, genre VARCHAR(50));

SELECT genre, COUNT(*) as num_events FROM Events WHERE location LIKE '%Paris%' AND event_type = 'visual arts' GROUP BY genre ORDER BY num_events DESC;


Question: Update the "price" column in the "carbon_prices" table to 28 for records where the "country" is 'France'

CREATE TABLE carbon_prices ( id INT PRIMARY KEY, country VARCHAR(50), price DECIMAL(5,2)); INSERT INTO carbon_prices (id, country, price) VALUES (1, 'Germany', 20), (2, 'France', 18), (3, 'Spain', 22);

UPDATE carbon_prices SET price = 28 WHERE country = 'France';


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

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

SELECT count(*) FROM (SELECT to_timestamp('97/Feb/16', 'YY:Mon:DD')) AS _sub;


Question: How many support programs were implemented in the Eastern region each month for the year 2021?

CREATE TABLE SupportPrograms (ProgramID INT, ProgramName VARCHAR(50), Region VARCHAR(50), ImplementationMonth INT, ImplementationYear INT); INSERT INTO SupportPrograms (ProgramID, ProgramName, Region, ImplementationMonth, ImplementationYear) VALUES (1, 'Assistive Technology', 'Eastern', 1, 2021), (2, 'Sign Language Interpretation', 'Eastern', 2, 2021), (3, 'Accessible Furniture', 'Eastern', 3, 2021);

SELECT ImplementationYear, ImplementationMonth, COUNT(ProgramID) FROM SupportPrograms WHERE Region = 'Eastern' GROUP BY ImplementationYear, ImplementationMonth;


Question: What is the average mass of space debris in different categories?

CREATE TABLE space_debris (category TEXT, mass FLOAT); INSERT INTO space_debris (category, mass) VALUES ('Aluminum', 120.5), ('Titanium', 170.1), ('Copper', 110.1), ('Steel', 300.2), ('Other', 50.2);

SELECT category, AVG(mass) AS avg_mass FROM space_debris GROUP BY category;


Question: How many cultural heritage sites are in each region?

CREATE TABLE regions (region_id INT, region_name VARCHAR(255)); INSERT INTO regions (region_id, region_name) VALUES (1, 'North'), (2, 'South'), (3, 'East'), (4, 'West'); CREATE TABLE cultural_sites (site_id INT, site_name VARCHAR(255), region_id INT); INSERT INTO cultural_sites (site_id, site_name, region_id) VALUES (1, 'Museum A', 1), (2, 'Historic House B', 2), (3, 'Theater C', 3), (4, 'Gallery D', 4);

SELECT region_name, COUNT(*) as num_sites FROM cultural_sites JOIN regions ON cultural_sites.region_id = regions.region_id GROUP BY region_name;


Question: Generate PostgreSQL SQL for: What is the Diameter of the Dog Sled (gold variant) Theme coin?

CREATE TABLE table_name_74 (diameter VARCHAR, theme VARCHAR)

SELECT diameter FROM table_name_74 WHERE theme = 'dog sled (gold variant)';


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

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


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

SELECT  interval '0'                       AS "zero",
        interval '1-2' year to month       AS "year-month",
        interval '1 2:03:04' day to second AS "day-time",
        - interval '1-2'                   AS "negative year-month",
        - interval '1 2:03:04'             AS "negative day-time";

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

SELECT count(*) FROM (SELECT  interval '0'                       AS "zero",
        interval '1-2' year to month       AS "year-month",
        interval '1 2:03:04' day to second AS "day-time",
        - interval '1-2'                   AS "negative year-month",
        - interval '1 2:03:04'             AS "negative day-time") AS _sub;


Question: Generate PostgreSQL SQL for: What was the lowest no. of attendance on record?

CREATE TABLE table_16119656_1 (attendance INTEGER)

SELECT MIN(attendance) FROM table_16119656_1;


Question: What is the average number of marine species found in each protected marine area in Southeast Asia?

CREATE TABLE marine_areas (area_id INT, name VARCHAR(50), region VARCHAR(50), num_marine_species INT); INSERT INTO marine_areas (area_id, name, region, num_marine_species) VALUES (1, 'Tubbataha Reefs Natural Park', 'Southeast Asia', 600), (2, 'Sundarbans National Park', 'Southeast Asia', 550), (3, 'Great Barrier Reef', 'Australia', 1500);

SELECT AVG(num_marine_species) FROM marine_areas WHERE region = 'Southeast Asia';


Question: Generate PostgreSQL SQL for: What is Original title, when Film title used in nomination is Train Without A Timetable?

CREATE TABLE table_name_35 (original_title VARCHAR, film_title_used_in_nomination VARCHAR)

SELECT original_title FROM table_name_35 WHERE film_title_used_in_nomination = 'train without a timetable';


Question: What is the average budget of cybersecurity exercises in the last 6 months?

CREATE TABLE CybersecurityExercises (Id INT, Name VARCHAR(50), Budget FLOAT, Date DATE); INSERT INTO CybersecurityExercises (Id, Name, Budget, Date) VALUES (1, 'Exercise1', 5000, '2021-01-01'); INSERT INTO CybersecurityExercises (Id, Name, Budget, Date) VALUES (2, 'Exercise2', 7000, '2021-02-15');

SELECT AVG(Budget) FROM CybersecurityExercises WHERE Date >= DATE_SUB(CURRENT_DATE, INTERVAL 6 MONTH);


Question: How many ports are available in the database?

CREATE TABLE ports (port_code CHAR(3), port_name VARCHAR(20)); INSERT INTO ports (port_code, port_name) VALUES ('LA', 'Los Angeles'), ('NY', 'New York'), ('MIA', 'Miami'), ('HOU', 'Houston'), ('SFO', 'San Francisco');

SELECT COUNT(DISTINCT ports.port_code) as port_count FROM ports;


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

INSERT INTO num_exp_div VALUES (0,4,'0');

Explanation: DML from PostgreSQL core regression test for Numeric.


Question: What is the total production cost of garments produced in the last 12 months using sustainable materials?

CREATE TABLE Sustainable_Material_Garments_Time (id INT, production_date DATE, production_cost DECIMAL);

SELECT SUM(production_cost) FROM Sustainable_Material_Garments_Time WHERE production_date >= DATEADD(year, -1, GETDATE());


Question: PostgreSQL Typeconv: show example 7.

SELECT @ '-4.5e500' AS "abs"; ERROR: "-4.5e500" is out of range for type double precision;

Explanation: Example from PostgreSQL documentation on Typeconv.


Question: Determine the number of unique donors who made donations in the last quarter from the 'donations' table.

CREATE TABLE donations (id INT, donor_name VARCHAR(50), donation_date DATE, amount DECIMAL(10,2));

SELECT COUNT(DISTINCT donor_name) FROM donations WHERE donation_date >= DATEADD(quarter, -1, GETDATE());


Question: What is the total donation amount for each program in the 'ProgramDonations' table, and the average donation amount for each program?

CREATE TABLE ProgramDonations (DonationID INT, ProgramName VARCHAR(50), DonationAmount DECIMAL(10, 2), DonationDate DATE);

SELECT ProgramName, SUM(DonationAmount) AS TotalDonations, AVG(DonationAmount) AS AvgDonation FROM ProgramDonations GROUP BY ProgramName;


Question: What are the names of the factories with the highest waste generation?

CREATE TABLE factories (name TEXT, id INTEGER, waste_generation FLOAT); INSERT INTO factories (name, id, waste_generation) VALUES ('Factory A', 1, 500), ('Factory B', 2, 700), ('Factory C', 3, 800); CREATE TABLE landfill_capacity (factory_id INTEGER, capacity INTEGER); INSERT INTO landfill_capacity (factory_id, capacity) VALUES (1, 1000), (2, 1500), (3, 2000);

SELECT f.name, f.waste_generation FROM factories f ORDER BY f.waste_generation DESC LIMIT 1;


Question: What is the AI adoption percentage for 'boutique hotels'?

CREATE TABLE hotels_ai (id INT, type TEXT, ai BOOLEAN); INSERT INTO hotels_ai (id, type, ai) VALUES (1, 'Boutique', true), (2, 'Luxury', false), (3, 'Boutique', false);

SELECT 100.0 * COUNT(*) / (SELECT COUNT(*) FROM hotels_ai WHERE type = 'Boutique') FROM hotels_ai WHERE type = 'Boutique' AND ai = true;


Question: Generate PostgreSQL SQL for: Name the kurdistan democratic party for kurdistan list being 10

CREATE TABLE table_24440361_1 (kurdistan_democratic_party INTEGER, total_kurdistan_list VARCHAR)

SELECT MIN(kurdistan_democratic_party) FROM table_24440361_1 WHERE total_kurdistan_list = 10;


Question: Generate PostgreSQL SQL for: what is the mascot when the county is 43 kosciusko?

CREATE TABLE table_name_82 (mascot VARCHAR, county VARCHAR)

SELECT mascot FROM table_name_82 WHERE county = '43 kosciusko';


Question: What is the average number of autonomous vehicle tests for each city?

CREATE TABLE autonomous_vehicles (id INT, city_id INT, model VARCHAR(50), year INT, tests INT); INSERT INTO autonomous_vehicles (id, city_id, model, year, tests) VALUES (4, 3, 'Zoox', 2022, 60000); INSERT INTO autonomous_vehicles (id, city_id, model, year, tests) VALUES (5, 3, 'NVIDIA Drive', 2021, 50000);

SELECT city_id, AVG(tests) FROM autonomous_vehicles GROUP BY city_id;


Question: Generate PostgreSQL SQL for: When has Score of 4–5 and quebec nordiques as Visitor?

CREATE TABLE table_name_92 (date VARCHAR, score VARCHAR, visitor VARCHAR)

SELECT date FROM table_name_92 WHERE score = '4–5' AND visitor = 'quebec nordiques';


Question: What is the minimum fare for the commuter rail in Boston?

CREATE TABLE fares (fare_id INT, route_id INT, fare DECIMAL(5,2), fare_type VARCHAR(20)); INSERT INTO fares (fare_id, route_id, fare, fare_type) VALUES (1, 1, 8.00, 'Commuter Rail'), (2, 2, 6.50, 'Subway'), (3, 3, 9.00, 'Commuter Rail');

SELECT MIN(fare) FROM fares WHERE fare_type = 'Commuter Rail';


Question: Present the warehouse locations and their respective total storage capacity (in cubic meters) for the region 'Europe' as of 2022-02-01.

CREATE TABLE Warehouses (WarehouseID INT, WarehouseLocation VARCHAR(100), Region VARCHAR(50), StorageCapacity DECIMAL(10,2)); INSERT INTO Warehouses VALUES (1, 'Warehouse B', 'Europe', 5000);

SELECT Warehouses.WarehouseLocation, SUM(Warehouses.StorageCapacity) as TotalStorageCapacity FROM Warehouses WHERE Warehouses.Region = 'Europe' AND Warehouses.StorageCapacity IS NOT NULL GROUP BY Warehouses.WarehouseLocation;


Question: Show a SQL definition from the citus project (views_create, item 31).

CREATE VIEW "local regular view4" as SELECT count(*) as "my cny" FROM dist_regular_view JOIN "local regular view" USING (id);

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


Question: Update the round type to 'Series D' in the "investment_rounds" table for the record with id 7

CREATE TABLE investment_rounds (id INT, company_name VARCHAR(100), round_type VARCHAR(50), raised_amount FLOAT, round_date DATE); INSERT INTO investment_rounds (id, company_name, round_type, raised_amount, round_date) VALUES (6, 'Hotel Ltd.', 'Series B', 7000000, '2018-02-15'), (7, 'India Inc.', 'Series A', 5000000, '2018-01-01');

UPDATE investment_rounds SET round_type = 'Series D' WHERE id = 7;


Question: Generate PostgreSQL SQL for: Tell me the circuit for 20 august

CREATE TABLE table_name_99 (circuit VARCHAR, date VARCHAR)

SELECT circuit FROM table_name_99 WHERE date = '20 august';


Question: What is the total number of mining accidents and the associated labor productivity metrics for each country in Africa?

CREATE TABLE african_countries (id INT, country TEXT); INSERT INTO african_countries (id, country) VALUES (1, 'South Africa'), (2, 'Ghana'), (3, 'Zambia'), (4, 'Tanzania'), (5, 'Mali'); CREATE TABLE mines (id INT, country TEXT, accidents INT, productivity FLOAT); INSERT INTO mines (id, country, accidents, productivity) VALUES (1, 'South Africa', 5, 1.2), (2, 'Ghana', 3, 1.5), (3, 'Zambia', 7, 1.8), (4, 'Tanzania', 4, 1.3), (5, 'Mali', 6, 1.6);

SELECT m.country, COUNT(m.id) AS total_accidents, AVG(m.productivity) AS avg_productivity FROM mines m GROUP BY m.country;


Question: What is the total number of vehicles sold in the Sales_Data table in the first half of 2021?

CREATE TABLE Sales_Data (Sale_Date DATE, Vehicle_Type VARCHAR(20), Quantity_Sold INT);

SELECT SUM(Quantity_Sold) FROM Sales_Data WHERE Sale_Date BETWEEN '2021-01-01' AND '2021-06-30';


Question: Generate PostgreSQL SQL for: Who lost with a time of 0:58?

CREATE TABLE table_name_44 (loser VARCHAR, time VARCHAR)

SELECT loser FROM table_name_44 WHERE time = '0:58';


Question: Update email of players from 'US' to 'new_email@usa.com'

player (player_id, name, email, age, gender, country, total_games_played)

UPDATE player SET email = 'new_email@usa.com' WHERE country = 'US';


Question: Generate PostgreSQL SQL for: Which opponent played a 1990 wcq type of game, where the results were 0:0?

CREATE TABLE table_name_99 (opponent VARCHAR, type_of_game VARCHAR, results¹ VARCHAR)

SELECT opponent FROM table_name_99 WHERE type_of_game = '1990 wcq' AND results¹ = '0:0';


Question: Write the DDL statement from PostgreSQL regression test 'sequence' (example 17).

CREATE SEQUENCE sequence_test13 AS smallint MINVALUE -32768;

Explanation: DDL from PostgreSQL core regression test for Sequence.


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

SELECT to_tsvector('ispell_tst', 'Booking the skies after rebookings for footballklubber from a foot');

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

SELECT count(*) FROM (SELECT to_tsvector('ispell_tst', 'Booking the skies after rebookings for footballklubber from a foot')) AS _sub;


Question: Generate PostgreSQL SQL for: Find the names of states that have some college students playing in goalie and mid positions.

CREATE TABLE tryout (cName VARCHAR, pPos VARCHAR); CREATE TABLE college (state VARCHAR, cName VARCHAR)

SELECT T1.state FROM college AS T1 JOIN tryout AS T2 ON T1.cName = T2.cName WHERE T2.pPos = 'goalie' INTERSECT SELECT T1.state FROM college AS T1 JOIN tryout AS T2 ON T1.cName = T2.cName WHERE T2.pPos = 'mid';


Question: Generate PostgreSQL SQL for: How much was the cost of in-county tuition per credit hour at the Gloucester College by the fall of 2009?

CREATE TABLE table_22308881_2 (in_county_tuition_per_credit_hour__fall_2009_ VARCHAR, college VARCHAR)

SELECT in_county_tuition_per_credit_hour__fall_2009_ FROM table_22308881_2 WHERE college = 'Gloucester';


Question: Generate PostgreSQL SQL for: what is the minimum rank

CREATE TABLE table_11174272_1 (rank INTEGER)


Question: How many fish are farmed in each country based on the fish_farming table?

CREATE TABLE countries (country_id INT, country_name VARCHAR(50)); INSERT INTO countries (country_id, country_name) VALUES (1, 'Norway'), (2, 'Chile'), (3, 'Canada'); CREATE TABLE fish_farming (country_id INT, species VARCHAR(50), quantity INT); INSERT INTO fish_farming (country_id, species, quantity) VALUES (1, 'Salmon', 5000), (2, 'Tilapia', 3000), (3, 'Trout', 4000), (1, 'Cod', 2000);

SELECT c.country_name, SUM(ff.quantity) as total_farmed_fish FROM countries c JOIN fish_farming ff ON c.country_id = ff.country_id GROUP BY c.country_name;


Question: Generate PostgreSQL SQL for: What is the lowest Frequency where the Hemholtz pitch is d?

CREATE TABLE table_name_48 (frequency___hz__ INTEGER, helmholtz_pitch VARCHAR)

SELECT MIN(frequency___hz__) FROM table_name_48 WHERE helmholtz_pitch = 'd';


Question: List all climate adaptation policies enacted by Pacific Island nations and their corresponding impact scores.

CREATE TABLE policies (id INT, name VARCHAR(50), country VARCHAR(50), type VARCHAR(50), enactment_date DATE); INSERT INTO policies (id, name, country, type, enactment_date) VALUES (1, 'Coastal Protection Policy', 'Fiji', 'Adaptation', '2018-01-01'); INSERT INTO policies (id, name, country, type, enactment_date) VALUES (2, 'Climate-Resilient Infrastructure Policy', 'Marshall Islands', 'Adaptation', '2019-05-05'); INSERT INTO policies (id, name, country, type, enactment_date) VALUES (3, 'Water Management Policy', 'Palau', 'Adaptation', '2017-12-12'); INSERT INTO policies (id, name, country, type, enactment_date) VALUES (4, 'Disaster Risk Reduction Policy', 'Samoa', 'Adaptation', '2020-06-26'); INSERT INTO policies (id, name, country, type, enactment_date) VALUES (5, 'Agricultural Adaptation Policy', 'Vanuatu', 'Adaptation', '2021-09-15');

SELECT p.name, p.country, p.type, p.enactment_date, coalesce(avg(i.impact_score), 0) as avg_impact_score FROM policies p LEFT JOIN impact_assessments i ON p.id = i.policy_id WHERE p.type = 'Adaptation' AND p.country LIKE 'Pacific%' GROUP BY p.name, p.country, p.type, p.enactment_date;


Question: pgTAP test for Pktap (assertion 25).

SELECT * FROM check_test(
    col_is_pk( 'sometab', 'id' ),
    true,
    'col_is_pk( table, column )',
    'Column sometab(id) should be a primary key',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Pktap.


Question: Generate PostgreSQL SQL for: What is the Score that has a Winnipeg Jets as Visitor on april 7?

CREATE TABLE table_name_10 (score VARCHAR, visitor VARCHAR, date VARCHAR)

SELECT score FROM table_name_10 WHERE visitor = 'winnipeg jets' AND date = 'april 7';


Question: Generate PostgreSQL SQL for: What was the fate and location of the Ringstad?

CREATE TABLE table_name_3 (fate_and_location VARCHAR, ship VARCHAR)

SELECT fate_and_location FROM table_name_3 WHERE ship = 'ringstad';


Question: What is the total number of successful and failed aid deliveries for each organization?

CREATE TABLE aid_deliveries (delivery_id INT, organization VARCHAR(50), delivery_status VARCHAR(10)); INSERT INTO aid_deliveries (delivery_id, organization, delivery_status) VALUES (1, 'Org A', 'successful'), (2, 'Org B', 'failed'), (3, 'Org A', 'successful'), (4, 'Org C', 'successful'), (5, 'Org B', 'failed'), (6, 'Org A', 'successful'); CREATE TABLE organizations (org_id INT, name VARCHAR(50)); INSERT INTO organizations (org_id, name) VALUES (1, 'Org A'), (2, 'Org B'), (3, 'Org C');

SELECT o.name, SUM(CASE WHEN ad.delivery_status = 'successful' THEN 1 ELSE 0 END) AS num_successful, SUM(CASE WHEN ad.delivery_status = 'failed' THEN 1 ELSE 0 END) AS num_failed FROM aid_deliveries ad JOIN organizations o ON ad.organization = o.name GROUP BY o.name;


Question: as of 2022

INSERT INTO music_genres_ext (id, genre, popularity) VALUES (4, 'Hip Hop', 30000000);

INSERT INTO music_genres_ext (id, genre, popularity, release_year);


Question: What is the total amount of funding received by graduate students from research grants in the Mathematics department?

CREATE TABLE graduate_students (id INT, name VARCHAR(50), department VARCHAR(50)); CREATE TABLE research_grants (id INT, graduate_student_id INT, amount DECIMAL(10,2));

SELECT SUM(rg.amount) FROM research_grants rg JOIN graduate_students gs ON rg.graduate_student_id = gs.id WHERE gs.department = 'Mathematics';


Question: What is the maximum budget allocated for ethical AI initiatives in a single year in Europe?

CREATE TABLE Ethical_AI_Budget_Year (Year INT, Budget INT);

SELECT MAX(Budget) FROM Ethical_AI_Budget_Year WHERE Year IN (SELECT Year FROM Ethical_AI_Budget_Year WHERE Country IN ('Germany', 'France', 'Spain', 'Italy', 'UK') GROUP BY Year);


Question: Create a view for active recycling initiatives

CREATE TABLE recycling_initiatives ( id INT PRIMARY KEY, region VARCHAR(255), initiative_name VARCHAR(255), initiative_description TEXT, start_date DATE, end_date DATE); INSERT INTO recycling_initiatives (id, region, initiative_name, initiative_description, start_date, end_date) VALUES (1, 'Africa', 'Plastic Bottle Collection', 'Collecting plastic bottles in schools and parks.', '2020-01-01', '2020-12-31'), (2, 'South America', 'E-Waste Disposal', 'Establishing e-waste drop-off points in major cities.', '2019-06-15', '2021-06-14'), (3, 'Oceania', 'Composting Program', 'Implementing composting programs in households.', '2018-04-22', '2022-04-21'), (4, 'Antarctica', 'Research and Development', 'Researching new waste reduction methods.', '2023-07-04', '2026-07-03'); CREATE VIEW active_recycling_initiatives AS SELECT * FROM recycling_initiatives WHERE end_date >= CURDATE();


Question: How many renewable energy projects were completed in each region in the past 3 years?

CREATE TABLE renewable_projects (id INT, region VARCHAR(50), completion_year INT);

SELECT region, COUNT(*) FROM renewable_projects WHERE completion_year >= YEAR(CURRENT_DATE) - 3 GROUP BY region;


Question: Generate PostgreSQL SQL for: What location was the game on October 6?

CREATE TABLE table_21761882_4 (location VARCHAR, date VARCHAR)

SELECT location FROM table_21761882_4 WHERE date = 'October 6';


Question: Generate PostgreSQL SQL for: Name the 2010 for tournament of us open

CREATE TABLE table_name_95 (tournament VARCHAR)

SELECT 2010 FROM table_name_95 WHERE tournament = 'us open';


Question: Determine the total sales revenue for each month of the year

SELECT DATE_FORMAT(sale_date, '%Y-%m') AS month, SUM(price * quantity) AS total_sales_revenue FROM sales_data_2 GROUP BY month;


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

SELECT count(*) FROM (SELECT ts_lexize('hunspell', 'skies')) AS _sub;


Question: Number of community development initiatives, by region and gender, for the year 2018?

CREATE TABLE community_development (id INT, region VARCHAR(255), gender VARCHAR(255), initiative_count INT, year INT); INSERT INTO community_development (id, region, gender, initiative_count, year) VALUES (1, 'Caribbean', 'Female', 120, 2018), (2, 'Caribbean', 'Male', 85, 2018), (3, 'Central America', 'Female', 160, 2018);

SELECT region, gender, SUM(initiative_count) as total_initiative_count FROM community_development WHERE year = 2018 GROUP BY region, gender;


Question: What is the total number of humanitarian assistance missions conducted by each military branch in 2020?

CREATE TABLE military_branch (id INT PRIMARY KEY, name VARCHAR(255)); INSERT INTO military_branch (id, name) VALUES (1, 'Army'), (2, 'Navy'), (3, 'Air Force'), (4, 'Marines'), (5, 'Coast Guard'); CREATE TABLE missions (id INT PRIMARY KEY, military_branch_id INT, type VARCHAR(255), year INT, FOREIGN KEY (military_branch_id) REFERENCES military_branch(id)); INSERT INTO missions (id, military_branch_id, type, year) VALUES (1, 1, 'Humanitarian Assistance', 2020), (2, 2, 'Humanitarian Assistance', 2020), (3, 3, 'Humanitarian Assistance', 2020), (4, 4, 'Humanitarian Assistance', 2020), (5, 5, 'Humanitarian Assistance', 2020);

SELECT m.name, COUNT(missions.id) as total_missions FROM missions JOIN military_branch m ON missions.military_branch_id = m.id WHERE missions.type = 'Humanitarian Assistance' AND missions.year = 2020 GROUP BY m.name;


Question: Generate PostgreSQL SQL for: Name the total number of record for 61

CREATE TABLE table_27722408_10 (record VARCHAR, game VARCHAR)

SELECT COUNT(record) FROM table_27722408_10 WHERE game = 61;


Question: What's the minimum ESG score for companies in the 'healthcare' or 'pharmaceutical' sectors?

CREATE TABLE companies_esg_3 (id INT, sector VARCHAR(20), ESG_score FLOAT); INSERT INTO companies_esg_3 (id, sector, ESG_score) VALUES (1, 'healthcare', 72.5), (2, 'pharmaceutical', 80.2), (3, 'healthcare', 76.1);

SELECT MIN(ESG_score) FROM companies_esg_3 WHERE sector IN ('healthcare', 'pharmaceutical');


Question: Generate PostgreSQL SQL for: What is every prefix class for the equivalent of NTE101?

CREATE TABLE table_30011_2 (prefix_class VARCHAR, equivalent VARCHAR)

SELECT prefix_class FROM table_30011_2 WHERE equivalent = 'NTE101';


Question: Generate PostgreSQL SQL for: Which chassis has marlboro brm as the team?

CREATE TABLE table_name_89 (chassis VARCHAR, team VARCHAR)

SELECT chassis FROM table_name_89 WHERE team = 'marlboro brm';


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

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

SELECT count(*) FROM (select jsonb_path_query('"1.23aaa"', '$.bigint()')) AS _sub;


Question: Generate PostgreSQL SQL for: What is essendon's away team score?

CREATE TABLE table_name_1 (away_team VARCHAR)

SELECT away_team AS score FROM table_name_1 WHERE away_team = 'essendon';


Question: What is the total number of hours spent on open pedagogy projects by students in each school?

CREATE TABLE open_pedagogy_projects (id INT, project_name VARCHAR(50), school_id INT, student_id INT, hours_spent INT);   CREATE TABLE students (id INT, name VARCHAR(50), age INT, school_id INT);   CREATE TABLE schools (id INT, school_name VARCHAR(50), PRIMARY KEY(id));

SELECT s.school_name, SUM(opp.hours_spent) as total_hours_spent   FROM open_pedagogy_projects opp   JOIN students st ON opp.student_id = st.id   JOIN schools s ON st.school_id = s.id   GROUP BY s.school_name;


Question: How many circular economy initiatives were implemented in the residential sector in 2019?

CREATE TABLE CircularEconomy (year INT, sector VARCHAR(20), initiatives INT); INSERT INTO CircularEconomy (year, sector, initiatives) VALUES (2018, 'residential', 300), (2018, 'commercial', 200), (2019, 'residential', NULL), (2019, 'commercial', 300);

SELECT initiatives FROM CircularEconomy WHERE year = 2019 AND sector = 'residential';


Question: Which regions have the highest VR set adoption rates?

CREATE TABLE Region_VR_Adoption (Region VARCHAR(20), VR_Users INT, Total_Users INT); INSERT INTO Region_VR_Adoption (Region, VR_Users, Total_Users) VALUES ('North America', 5000, 10000), ('Europe', 7000, 15000), ('Asia', 8000, 20000), ('South America', 3000, 12000), ('Africa', 1000, 5000);

SELECT Region, (VR_Users * 100.0 / Total_Users) AS Adoption_Rate FROM Region_VR_Adoption;


Question: What was the average attendance for exhibitions in the 'Art Museum' in 2020?

CREATE TABLE Art_Exhibition (exhibition_id INT, museum_name VARCHAR(255), year INT, attendance INT);

SELECT AVG(attendance) FROM Art_Exhibition WHERE museum_name = 'Art Museum' AND year = 2020;


Question: Generate PostgreSQL SQL for: Which Bronze has a Total smaller than 1?

CREATE TABLE table_name_15 (bronze INTEGER, total INTEGER)

SELECT AVG(bronze) FROM table_name_15 WHERE total < 1;


Question: PostgreSQL regression test 'arrays': Write the SELECT query (example 165).

SELECT array_agg(x) || array_agg(x) FROM (VALUES (ROW(1,2)), (ROW(3,4))) v(x);

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

SELECT count(*) FROM (SELECT array_agg(x) || array_agg(x) FROM (VALUES (ROW(1,2)), (ROW(3,4))) v(x)) AS _sub;


Question: Generate PostgreSQL SQL for: What county has others at 5?

CREATE TABLE table_20573232_1 (county VARCHAR, others_number VARCHAR)

SELECT county FROM table_20573232_1 WHERE others_number = 5;


Question: PostgreSQL regression test 'varchar': Write the SELECT query (example 12).

SELECT c.*
   FROM VARCHAR_TBL c
   WHERE c.f1 = 'a';

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

SELECT count(*) FROM (SELECT c.*
   FROM VARCHAR_TBL c
   WHERE c.f1 = 'a') AS _sub;


Question: Delete records from the 'player_scores' table where the player's score is below 500

CREATE TABLE player_scores (player_id INT, score INT); INSERT INTO player_scores (player_id, score) VALUES (1, 600), (2, 300), (3, 700);

WITH low_scores AS (DELETE FROM player_scores WHERE score < 500 RETURNING *) SELECT * FROM low_scores;


Question: Generate PostgreSQL SQL for: What's the mean week number for November 12, 1978?

CREATE TABLE table_name_9 (week INTEGER, date VARCHAR)

SELECT AVG(week) FROM table_name_9 WHERE date = 'november 12, 1978';


Question: Generate PostgreSQL SQL for: What team was promoted in the Serbian League East in the same season when Kolubara was promoted in the Serbian League Belgrade?

CREATE TABLE table_12283621_6 (serbian_league_east VARCHAR, serbian_league_belgrade VARCHAR)

SELECT serbian_league_east FROM table_12283621_6 WHERE serbian_league_belgrade = 'Kolubara';


Question: Generate PostgreSQL SQL for: Name the broadcast network for saitama prefecture

CREATE TABLE table_21076286_2 (broadcast_network VARCHAR, broadcast_scope VARCHAR)

SELECT broadcast_network FROM table_21076286_2 WHERE broadcast_scope = 'Saitama Prefecture';


Question: PostgreSQL Ddl: show example 80.

Explanation: Example from PostgreSQL documentation on Ddl.


Question: What is the sum of donations and number of volunteers for each program in Q3 2021?

CREATE TABLE ProgramVolunteers (ProgramID INT, VolunteerCount INT); INSERT INTO ProgramVolunteers (ProgramID, VolunteerCount) VALUES (1, 10), (2, 20);

SELECT ProgramName, SUM(DonationAmount) as TotalDonation, SUM(VolunteerCount) as TotalVolunteers FROM Programs JOIN ProgramVolunteers ON Programs.ProgramID = ProgramVolunteers.ProgramID WHERE DonationDate BETWEEN '2021-07-01' AND '2021-09-30' GROUP BY ProgramName;


Question: Generate PostgreSQL SQL for: What type of car does Jeff Fuller drive?

CREATE TABLE table_2182170_1 (car_s_ VARCHAR, driver_s_ VARCHAR)

SELECT car_s_ FROM table_2182170_1 WHERE driver_s_ = 'Jeff Fuller';


Question: Generate PostgreSQL SQL for: Name the number for simon cellan jones

CREATE TABLE table_26914076_2 (no VARCHAR, directed_by VARCHAR)

SELECT no FROM table_26914076_2 WHERE directed_by = 'Simon Cellan Jones';


Question: What is the most attended cultural event in 'events' table for 2022?

CREATE TABLE events (event_id INT, title VARCHAR(50), year INT, location VARCHAR(50), attendance INT); INSERT INTO events (event_id, title, year, location, attendance) VALUES (1, 'Art Exhibition', 2022, 'Paris', 15000); INSERT INTO events (event_id, title, year, location, attendance) VALUES (2, 'Theater Performance', 2022, 'Tokyo', 12000);

SELECT title, MAX(attendance) FROM events WHERE year = 2022;


Question: Generate PostgreSQL SQL for: What is the title of every song, and how many weeks was each song at #1 for Rihanna in 2012?

CREATE TABLE table_19542477_9 (song_s__—_weeks VARCHAR, issue_years VARCHAR, artist_s_ VARCHAR)

SELECT song_s__—_weeks FROM table_19542477_9 WHERE issue_years = 2012 AND artist_s_ = 'Rihanna';


Question: Delete all records of workers who have been terminated and replace them with new hires who have received ethical manufacturing training.

CREATE TABLE Workers (ID INT, Terminated BOOLEAN, Ethical_Training BOOLEAN); INSERT INTO Workers (ID, Terminated, Ethical_Training) VALUES (1, TRUE, FALSE); INSERT INTO Workers (ID, Terminated, Ethical_Training) VALUES (2, FALSE, TRUE); INSERT INTO Workers (ID, Terminated, Ethical_Training) VALUES (3, TRUE, FALSE); INSERT INTO Workers (ID, Terminated, Ethical_Training) VALUES (4, FALSE, TRUE); DELETE FROM Workers WHERE Terminated = TRUE; INSERT INTO Workers (ID, Terminated, Ethical_Training) VALUES (5, FALSE, TRUE); INSERT INTO Workers (ID, Terminated, Ethical_Training) VALUES (6, FALSE, TRUE);

DELETE FROM Workers WHERE Terminated = TRUE; INSERT INTO Workers (ID, Terminated, Ethical_Training) VALUES (5, FALSE, TRUE), (6, FALSE, TRUE);


Question: Show a query using PostgreSQL contrib extension 'pg_trgm' (example 78).

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


Question: Rank countries by the percentage of international visitors who travel sustainably in 2019.

CREATE TABLE CountrySustainableTravel (country_id INT, year INT, pct_sustainable_travel FLOAT); INSERT INTO CountrySustainableTravel (country_id, year, pct_sustainable_travel) VALUES (1, 2019, 0.5); INSERT INTO CountrySustainableTravel (country_id, year, pct_sustainable_travel) VALUES (2, 2019, 0.7); INSERT INTO CountrySustainableTravel (country_id, year, pct_sustainable_travel) VALUES (3, 2019, 0.6); INSERT INTO CountrySustainableTravel (country_id, year, pct_sustainable_travel) VALUES (4, 2019, 0.8);

SELECT country_id, RANK() OVER (ORDER BY pct_sustainable_travel DESC) as rank FROM CountrySustainableTravel WHERE year = 2019;


Question: What was the total amount of funding received by cultural organizations in Brazil and Russia?

CREATE TABLE CulturalOrganizations (id INT, organization_name VARCHAR(50), country VARCHAR(50), funding_amount DECIMAL(10, 2)); INSERT INTO CulturalOrganizations (id, organization_name, country, funding_amount) VALUES (1, 'Museum', 'Brazil', 50000.00), (2, 'Theater', 'Russia', 75000.00), (3, 'Art Gallery', 'Brazil', 60000.00), (4, 'Dance Company', 'Russia', 80000.00);

SELECT SUM(funding_amount) FROM CulturalOrganizations WHERE country IN ('Brazil', 'Russia');


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

SELECT JSON_OBJECT(1: 1, '1': NULL ABSENT ON NULL WITH UNIQUE RETURNING jsonb);

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

SELECT count(*) FROM (SELECT JSON_OBJECT(1: 1, '1': NULL ABSENT ON NULL WITH UNIQUE RETURNING jsonb)) AS _sub;


Question: Find the number of distinct species in the 'habitat_preservation' program

CREATE TABLE habitat_preservation (animal_id INT, species VARCHAR(20)); INSERT INTO habitat_preservation (animal_id, species) VALUES (1, 'tiger'), (2, 'elephant'), (3, 'tiger');

SELECT COUNT(DISTINCT species) FROM habitat_preservation;


Question: What is the total number of explainable AI models with a satisfaction score greater than 85?

CREATE TABLE explainable_ai (model_name TEXT, satisfaction_score INTEGER, date DATE); INSERT INTO explainable_ai (model_name, satisfaction_score, date) VALUES ('Model1', 80, '2020-01-01'), ('Model2', 85, '2019-04-03'), ('Model3', 90, '2021-05-22'), ('Model4', 87, '2021-02-15');

SELECT COUNT(*) FROM explainable_ai WHERE satisfaction_score > 85;


Question: Generate PostgreSQL SQL for: How much February has a Game larger than 37, and an Opponent of chicago black hawks?

CREATE TABLE table_name_95 (february VARCHAR, game VARCHAR, opponent VARCHAR)

SELECT COUNT(february) FROM table_name_95 WHERE game > 37 AND opponent = 'chicago black hawks';


Question: Generate PostgreSQL SQL for: What was the decision when Chicago was the visiting team?

CREATE TABLE table_name_85 (decision VARCHAR, visitor VARCHAR)

SELECT decision FROM table_name_85 WHERE visitor = 'chicago';


Question: Identify the space organizations that have launched satellites in the last 3 years.

CREATE TABLE organization_satellites (organization TEXT, launch_date DATE); INSERT INTO organization_satellites (organization, launch_date) VALUES ('NASA', '2020-01-01'), ('NASA', '2019-01-01'), ('ESA', '2018-01-01'), ('SpaceX', '2021-01-01'), ('ISRO', '2020-01-01');

SELECT DISTINCT organization FROM organization_satellites WHERE launch_date >= DATEADD(year, -3, GETDATE());


Question: Generate PostgreSQL SQL for: How many yards did Davin Meggett have with more than 9 Rec.?

CREATE TABLE table_name_62 (yards INTEGER, player VARCHAR, rec VARCHAR)

SELECT SUM(yards) FROM table_name_62 WHERE player = 'davin meggett' AND rec > 9;


Question: Count the number of military equipment maintenance requests from each branch of the military

CREATE TABLE maintenance_requests (request_id INT, equipment_id INT, request_date DATE, branch VARCHAR(255)); CREATE VIEW equipment_by_branch AS SELECT equipment_id, branch FROM military_equipment JOIN maintenance_requests ON military_equipment.equipment_id = maintenance_requests.equipment_id;

SELECT branch, COUNT(*) as num_requests FROM equipment_by_branch GROUP BY branch;


Question: What is the average budget per student for accommodations in each building?

CREATE TABLE Students (StudentID INT, BuildingID INT); INSERT INTO Students (StudentID, BuildingID) VALUES (1, 1); INSERT INTO Students (StudentID, BuildingID) VALUES (2, 1); INSERT INTO Students (StudentID, BuildingID) VALUES (3, 2);

SELECT b.BuildingName, AVG(bb.BudgetAmount / COUNT(s.StudentID)) AS AvgBudgetPerStudent FROM BuildingBudgets bb INNER JOIN Buildings b ON bb.BuildingID = b.BuildingID INNER JOIN Students s ON bb.BuildingID = s.BuildingID GROUP BY b.BuildingName;


Question: Generate PostgreSQL SQL for: What is the notes when the displacement is 220cid (3,604cc)?

CREATE TABLE table_name_78 (notes VARCHAR, displacement VARCHAR)

SELECT notes FROM table_name_78 WHERE displacement = '220cid (3,604cc)';


Question: How many players are there in each city, and which games are they playing?

CREATE TABLE Players (PlayerID INT, City VARCHAR(50)); INSERT INTO Players (PlayerID, City) VALUES (1, 'Los Angeles'), (2, 'Paris'), (3, 'Tokyo'), (4, 'Sydney'); CREATE TABLE GameSessions (PlayerID INT, GameID INT); INSERT INTO GameSessions (PlayerID, GameID) VALUES (1, 1), (1, 2), (2, 2), (2, 3), (3, 3), (4, 4); CREATE TABLE GameDesign (GameID INT, GameName VARCHAR(50)); INSERT INTO GameDesign (GameID, GameName) VALUES (1, 'Space Explorer'), (2, 'Racing Fever'), (3, 'VR Puzzle'), (4, 'Underwater Adventure');

SELECT Players.City, COUNT(Players.PlayerID) AS Players_in_City, GameDesign.GameName FROM Players INNER JOIN GameSessions ON Players.PlayerID = GameSessions.PlayerID INNER JOIN GameDesign ON GameSessions.GameID = GameDesign.GameID GROUP BY Players.City, GameDesign.GameName;


Question: Find the total number of hotel listings in Europe and Asia, excluding duplicates.

CREATE TABLE hotel_listings (hotel_id INT, location VARCHAR(20)); INSERT INTO hotel_listings (hotel_id, location) VALUES (1, 'Paris'), (2, 'Berlin'), (3, 'Tokyo');

SELECT location, COUNT(DISTINCT hotel_id) as total_hotels FROM hotel_listings WHERE location IN ('Europe', 'Asia') GROUP BY location;


Question: Generate PostgreSQL SQL for: What was the crowd size of the match featuring Hawthorn as the Away team?

CREATE TABLE table_name_84 (crowd VARCHAR, away_team VARCHAR)

SELECT crowd FROM table_name_84 WHERE away_team = 'hawthorn';


Question: What is the average account balance of low-income borrowers in Latin America who have taken out socially responsible loans?

CREATE TABLE Customers (CustomerID int, IncomeLevel varchar(50), Location varchar(50)); INSERT INTO Customers (CustomerID, IncomeLevel, Location) VALUES (1, 'Low Income', 'Latin America'); CREATE TABLE Loans (LoanID int, CustomerID int, Type varchar(50), SociallyResponsible bit); INSERT INTO Loans (LoanID, CustomerID, Type, SociallyResponsible) VALUES (1, 1, 'Personal Loan', 1); CREATE TABLE Accounts (AccountID int, CustomerID int, Balance decimal(10,2)); INSERT INTO Accounts (AccountID, CustomerID, Balance) VALUES (1, 1, 500.00);

SELECT AVG(A.Balance) FROM Accounts A INNER JOIN Customers C ON A.CustomerID = C.CustomerID INNER JOIN Loans L ON C.CustomerID = L.CustomerID WHERE C.Location = 'Latin America' AND C.IncomeLevel = 'Low Income' AND L.SociallyResponsible = 1;


Question: Show the number of smart contracts deployed per month for the 'Polkadot' network in the current year.

CREATE TABLE polkadot_network (deployment_date DATE, smart_contract_count INTEGER, network_name TEXT);

SELECT DATE_TRUNC('month', deployment_date) as month, COUNT(*) as smart_contracts_deployed FROM polkadot_network WHERE network_name = 'Polkadot' AND EXTRACT(YEAR FROM deployment_date) = EXTRACT(YEAR FROM CURRENT_DATE) GROUP BY month ORDER BY month;


Question: What is the maximum budget for climate mitigation projects in each continent?

CREATE TABLE climate_mitigation(project_name TEXT, country TEXT, budget FLOAT); INSERT INTO climate_mitigation(project_name, country, budget) VALUES ('Project P', 'USA', 800000.00), ('Project Q', 'Brazil', 900000.00), ('Project R', 'South Africa', 700000.00);

SELECT country, MAX(budget) FROM climate_mitigation GROUP BY (CASE WHEN country = 'USA' THEN 'North America' WHEN country = 'Brazil' THEN 'South America' WHEN country = 'South Africa' THEN 'Africa' END);


Question: Generate PostgreSQL SQL for: On what date was the opponent the White Sox and the record 18-13?

CREATE TABLE table_name_90 (date VARCHAR, opponent VARCHAR, record VARCHAR)

SELECT date FROM table_name_90 WHERE opponent = 'white sox' AND record = '18-13';


Question: Which countries have the highest number of defense contracts?

CREATE TABLE Contract_Country (id INT, country VARCHAR(50), contract_count INT); INSERT INTO Contract_Country (id, country, contract_count) VALUES (1, 'USA', 50), (2, 'Canada', 30); CREATE TABLE Contract_Country_Mapping (contract_id INT, country_id INT); INSERT INTO Contract_Country_Mapping (contract_id, country_id) VALUES (1, 1), (2, 1), (3, 2);

SELECT Contract_Country.country, SUM(Contract_Country_Mapping.contract_id) AS contract_count FROM Contract_Country JOIN Contract_Country_Mapping ON Contract_Country.id = Contract_Country_Mapping.country_id GROUP BY Contract_Country.country ORDER BY contract_count DESC;


Question: What is the total number of crimes reported in 2020 and 2021?

CREATE TABLE Crime (cid INT, year INT, category VARCHAR(255), location VARCHAR(255));

SELECT YEAR(Crime.year), COUNT(*) FROM Crime WHERE Crime.year IN (2020, 2021) GROUP BY YEAR(Crime.year);


Question: pgTAP test for Util (assertion 16).

SELECT is(
    test_variadic(),
    'foo
bar
baz',
    'variadic collect_tap() should simply collect tap'
);

Explanation: SQL assertion from pgTAP test suite for Util.


Question: Generate PostgreSQL SQL for: How many segment b's when segment a is filigree glass

CREATE TABLE table_15187735_16 (segment_b VARCHAR, segment_a VARCHAR)

SELECT COUNT(segment_b) FROM table_15187735_16 WHERE segment_a = 'Filigree Glass';


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

SELECT * FROM test_varbit WHERE i='100'::varbit ORDER BY i;

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


Question: Generate PostgreSQL SQL for: Which writer wrote episode 18-09 (652)?

CREATE TABLE table_name_29 (writer_s_ VARCHAR, episode VARCHAR)

SELECT writer_s_ FROM table_name_29 WHERE episode = '18-09 (652)';


Question: Update the year of events to 2025 if the year is greater than 2023

CREATE TABLE events (event_id INT, event_name VARCHAR(50), year INT); INSERT INTO events (event_id, event_name, year) VALUES (1, 'FIFA World Cup', 2022), (2, 'NBA Finals', 2023), (3, 'Super Bowl', 2022);

UPDATE events SET year = 2025 WHERE year > 2023;


Question: Generate PostgreSQL SQL for: Where is the German Grand Prix?

CREATE TABLE table_1140082_2 (location VARCHAR, race VARCHAR)

SELECT location FROM table_1140082_2 WHERE race = 'German Grand Prix';


Question: Generate PostgreSQL SQL for: What's the production code of the episode with a series number 37b?

CREATE TABLE table_14035132_3 (production_code VARCHAR, no_in_series VARCHAR)

SELECT production_code FROM table_14035132_3 WHERE no_in_series = '37b';


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

select * from
  (select jsonb_path_query_array(module->'lectures', '$[*]') as lecture
   from unnest(array['{"lectures": [{"id": "1"}]}'::jsonb])
        as unnested_modules(module)) as ss,
  jsonb_to_recordset(ss.lecture) as j (id text);

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

SELECT count(*) FROM (select * from
  (select jsonb_path_query_array(module->'lectures', '$[*]') as lecture
   from unnest(array['{"lectures": [{"id": "1"}]}'::jsonb])
        as unnested_modules(module)) as ss,
  jsonb_to_recordset(ss.lecture) as j (id text)) AS _sub;


Question: Insert a new cultural heritage site in Kyoto, Japan named "Kiyomizu-dera" with an ID of 3

CREATE TABLE cultural_sites (site_id INT, name TEXT, location TEXT); INSERT INTO cultural_sites (site_id, name, location) VALUES (1, 'Meiji Shrine', 'Tokyo'); INSERT INTO cultural_sites (site_id, name, location) VALUES (2, 'Todai-ji Temple', 'Nara');

INSERT INTO cultural_sites (site_id, name, location) VALUES (3, 'Kiyomizu-dera', 'Kyoto');


Question: What is the total CO2 emissions for the 'suppliers' table?

CREATE TABLE suppliers (id INT, name VARCHAR(50), co2_emissions INT); INSERT INTO suppliers (id, name, co2_emissions) VALUES (1, 'Supplier A', 500), (2, 'Supplier B', 800), (3, 'Supplier C', 300);

SELECT SUM(co2_emissions) FROM suppliers;


Question: What is the total amount of money invested in the technology sector?

CREATE TABLE investments (id INT, sector VARCHAR(255), amount FLOAT); INSERT INTO investments (id, sector, amount) VALUES (1, 'Technology', 9000000.0), (2, 'Technology', 10000000.0), (3, 'Healthcare', 8000000.0);

SELECT SUM(amount) FROM investments WHERE sector = 'Technology';


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

$$
language plpgsql;
create trigger base_tab_def_view_instrig instead of insert on base_tab_def_view
  for each row execute function base_tab_def_view_instrig_func();
truncate base_tab_def;
insert into base_tab_def values (1);
insert into base_tab_def values (2), (3);
insert into base_tab_def values (4, default, default, default, default);
insert into base_tab_def values (5, default, default, default, default),
                                (6, default, default, default, default);
insert into base_tab_def_view values (11);
insert into base_tab_def_view values (12), (13);
insert into base_tab_def_view values (14, default, default, default, default);
insert into base_tab_def_view values (15, default, default, default, default),
                                     (16, default, default, default, default);
insert into base_tab_def_view values (17), (default);
select * from base_tab_def order by a;

-- Using an unconditional DO INSTEAD rule should also cause NULLs to be
-- inserted where there are no view defaults.
drop trigger base_tab_def_view_instrig on base_tab_def_view;
drop function base_tab_def_view_instrig_func;
create rule base_tab_def_view_ins_rule as on insert to base_tab_def_view
  do instead insert into base_tab_def values (new.a, new.b, new.c, new.d, new.e);
truncate base_tab_def;
insert into base_tab_def values (1);
insert into base_tab_def values (2), (3);
insert into base_tab_def values (4, default, default, default, default);
insert into base_tab_def values (5, default, default, default, default),
                                (6, default, default, default, default);
insert into base_tab_def_view values (11);
insert into base_tab_def_view values (12), (13);
insert into base_tab_def_view values (14, default, default, default, default);
insert into base_tab_def_view values (15, default, default, default, default),
                                     (16, default, default, default, default);
insert into base_tab_def_view values (17), (default);
select * from base_tab_def order by a;

-- A DO ALSO rule should cause each row to be inserted twice. The first
-- insert should behave the same as an auto-updatable view (using table
-- defaults, unless overridden by view defaults). The second insert should
-- behave the same as a rule-updatable view (inserting NULLs where there are
-- no view defaults).
drop rule base_tab_def_view_ins_rule on base_tab_def_view;
create rule base_tab_def_view_ins_rule as on insert to base_tab_def_view
  do also insert into base_tab_def values (new.a, new.b, new.c, new.d, new.e);
truncate base_tab_def;
insert into base_tab_def values (1);
insert into base_tab_def values (2), (3);
insert into base_tab_def values (4, default, default, default, default);
insert into base_tab_def values (5, default, default, default, default),
                                (6, default, default, default, default);
insert into base_tab_def_view values (11);
insert into base_tab_def_view values (12), (13);
insert into base_tab_def_view values (14, default, default, default, default);
insert into base_tab_def_view values (15, default, default, default, default),
                                     (16, default, default, default, default);
insert into base_tab_def_view values (17), (default);
select * from base_tab_def order by a, c NULLS LAST;

-- Test a DO ALSO INSERT ... SELECT rule
drop rule base_tab_def_view_ins_rule on base_tab_def_view;
create rule base_tab_def_view_ins_rule as on insert to base_tab_def_view
  do also insert into base_tab_def (a, b, e) select new.a, new.b, 'xxx';
truncate base_tab_def;
insert into base_tab_def_view values (1, default, default, default, default);
insert into base_tab_def_view values (2, default, default, default, default),
                                     (3, default, default, default, default);
select * from base_tab_def order by a, e nulls first;

drop view base_tab_def_view;
drop table base_tab_def;

-- Test defaults with array assignments
create table base_tab (a serial, b int[], c text, d text default 'Table default');
create view base_tab_view as select c, a, b from base_tab;
alter view base_tab_view alter column c set default 'View default';
insert into base_tab_view (b[1], b[2], c, b[5], b[4], a, b[3])
values (1, 2, default, 5, 4, default, 3), (10, 11, 'C value', 14, 13, 100, 12);
select * from base_tab order by a;
drop view base_tab_view;
drop table base_tab;

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


Question: What is the difference in assets between customers with savings and checking?

CREATE TABLE Accounts (CustomerID INT, AccountType VARCHAR(50), Balance DECIMAL(10,2)); INSERT INTO Accounts (CustomerID, AccountType, Balance) VALUES (1, 'Savings', 10000); INSERT INTO Accounts (CustomerID, AccountType, Balance) VALUES (2, 'Checking', 5000);

SELECT SUM(CASE WHEN AccountType = 'Savings' THEN Balance ELSE -Balance END) FROM Accounts;


Question: Generate PostgreSQL SQL for: What U.S. Rap has life in the concrete jungle as the album?

CREATE TABLE table_name_15 (us_rap VARCHAR, album VARCHAR)

SELECT us_rap FROM table_name_15 WHERE album = 'life in the concrete jungle';


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

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

SELECT count(*) FROM (select to_oct(256*256*256 - 1) AS "77777777") AS _sub;


Question: pgTAP test for Ownership (assertion 72).

-- It should ignore the view.
SELECT * FROM check_test(
    sequence_owner_is('public', 'someview', current_user, 'mumble'),
	false,
    'sequence_owner_is(sch, view, user, desc)',
    'mumble',
    '    Sequence public.someview does not exist'
);

Explanation: SQL assertion from pgTAP test suite for Ownership.


Question: How many news articles were published in each quarter of 2022?

CREATE TABLE news_publication_dates_2 (title VARCHAR(100), publication_date DATE); INSERT INTO news_publication_dates_2 (title, publication_date) VALUES ('Article 6', '2022-01-01'), ('Article 7', '2022-02-03'), ('Article 8', '2022-02-15'), ('Article 9', '2022-03-05'), ('Article 10', '2022-04-10'), ('Article 11', '2022-05-12');

SELECT EXTRACT(QUARTER FROM publication_date) AS quarter, COUNT(*) AS articles_published FROM news_publication_dates_2 GROUP BY quarter;


Question: Generate PostgreSQL SQL for: Name the equipment for bike number 6

CREATE TABLE table_16941304_4 (equipment VARCHAR, bike_no VARCHAR)

SELECT equipment FROM table_16941304_4 WHERE bike_no = 6;


Question: Write the DDL statement from PostgreSQL regression test 'predicate' (example 56).

CREATE INDEX pred_tab_pred_idx ON pred_tab (a) WHERE b IS NOT NULL AND c IS NOT NULL;

Explanation: DDL from PostgreSQL core regression test for Predicate.


Question: Generate PostgreSQL SQL for: At what venue was the game played where the away team was South Melbourne

CREATE TABLE table_name_49 (venue VARCHAR, away_team VARCHAR)

SELECT venue FROM table_name_49 WHERE away_team = 'south melbourne';


Question: Generate PostgreSQL SQL for: What is Team, when Location Attendance is "Rose Garden 20,020"?

CREATE TABLE table_name_69 (team VARCHAR, location_attendance VARCHAR)

SELECT team FROM table_name_69 WHERE location_attendance = 'rose garden 20,020';


Question: What is the average transaction amount for each digital asset in the 'crypto_transactions' table, partitioned by week?

CREATE TABLE crypto_transactions (transaction_id INT, digital_asset VARCHAR(20), transaction_amount DECIMAL(10,2), transaction_time DATETIME);

SELECT digital_asset, AVG(transaction_amount) as avg_transaction_amount, DATE_TRUNC('week', transaction_time) as week FROM crypto_transactions GROUP BY digital_asset, week ORDER BY week;


Question: How many properties were co-owned in each city, ordered by the number of co-owned properties in the 'co_ownership' table?

CREATE TABLE co_ownership (id INT, city VARCHAR(255), property_id INT); INSERT INTO co_ownership (id, city, property_id) VALUES (1, 'Seattle', 101), (2, 'Seattle', 102), (3, 'Portland', 103), (4, 'Portland', 104), (5, 'Portland', 105), (6, 'Boston', 106);

SELECT city, COUNT(property_id) OVER (PARTITION BY city ORDER BY COUNT(property_id) DESC) AS num_co_owned_properties FROM co_ownership;


Question: What is the average rating for cruelty-free products in each brand in the database?

CREATE TABLE Brand_Rating (id INT, brand VARCHAR(255), product VARCHAR(255), rating INT, cruelty_free BOOLEAN); INSERT INTO Brand_Rating (id, brand, product, rating, cruelty_free) VALUES (1, 'Lush', 'Soak Stimulant Bath Bomb', 5, true), (2, 'The Body Shop', 'Born Lippy Strawberry Lip Balm', 4, true), (3, 'Estee Lauder', 'Advanced Night Repair Synchronized Recovery Complex II', 5, false), (4, 'Lush', 'Angels on Bare Skin Cleanser', 4, true), (5, 'The Body Shop', 'Tea Tree Skin Clearing Facial Wash', 3, true);

SELECT brand, AVG(rating) as avg_rating FROM Brand_Rating WHERE cruelty_free = true GROUP BY brand;


Question: Generate PostgreSQL SQL for: How many breadth entries are there when the vessel is marianarray?

CREATE TABLE table_28132970_5 (breadth VARCHAR, vessel VARCHAR)

SELECT COUNT(breadth) FROM table_28132970_5 WHERE vessel = 'Marianarray';


Question: Calculate the total volume of carbon sequestered in the year 2020 in private and public forests across the United States.

CREATE TABLE forests_us (id INT, name VARCHAR(50), state VARCHAR(50), is_private BOOLEAN, is_national_park BOOLEAN); INSERT INTO forests_us (id, name, state, is_private, is_national_park) VALUES (1, 'Adirondack Forest', 'New York', true, false); CREATE TABLE carbon_sequestration_us (id INT, forest_id INT, year INT, sequestration FLOAT); INSERT INTO carbon_sequestration_us (id, forest_id, year, sequestration) VALUES (1, 1, 2020, 2500);

SELECT SUM(cs.sequestration) FROM carbon_sequestration_us cs JOIN forests_us f ON cs.forest_id = f.id WHERE f.is_private = true OR f.is_national_park = true AND cs.year = 2020;


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

create view tt15v as select row(i)::nestedcomposite from int8_tbl i;

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


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

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

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


Question: Get the names of all menu items that have a price greater than 20 dollars

CREATE TABLE menu_items (item_id INT, item_name TEXT, price DECIMAL(5,2)); INSERT INTO menu_items (item_id, item_name, price) VALUES (1, 'Burger', 9.99), (2, 'Lobster', 34.99), (3, 'Salad', 15.50);

SELECT item_name FROM menu_items WHERE price > 20.00;


Question: Which education resources were distributed in South Sudan in Q4 2021?

CREATE TABLE education_resources (id INT, resource TEXT, quantity INT, country TEXT, quarter INT, year INT); INSERT INTO education_resources (id, resource, quantity, country, quarter, year) VALUES (1, 'Textbooks', 500, 'South Sudan', 4, 2021), (2, 'School Supplies', 300, 'South Sudan', 4, 2021), (3, 'Laptops', 200, 'South Sudan', 4, 2021);

SELECT DISTINCT resource FROM education_resources WHERE country = 'South Sudan' AND quarter = 4 AND year = 2021;


Question: What are the unique astrophysics observations made in the Antarctic region?

CREATE TABLE Astrophysics_Observations (id INT, observation VARCHAR(100), researcher VARCHAR(100), observation_region VARCHAR(100), observation_date DATE); INSERT INTO Astrophysics_Observations (id, observation, researcher, observation_region, observation_date) VALUES (1, 'Gamma Ray Burst', 'Dr. J. Doe', 'Arctic', '2021-12-18'), (2, 'Neutron Star Merger', 'Dr. A. Smith', 'Antarctic', '2018-02-03');

SELECT DISTINCT observation FROM Astrophysics_Observations WHERE observation_region = 'Antarctic';


Question: Generate PostgreSQL SQL for: How many times was Arizona the team and the round was bigger than 11?

CREATE TABLE table_name_86 (overall VARCHAR, school_club_team VARCHAR, round VARCHAR)

SELECT COUNT(overall) FROM table_name_86 WHERE school_club_team = 'arizona' AND round > 11;


Question: How many art exhibitions were there in total in 2018 and 2019 combined?

CREATE TABLE Exhibitions (id INT, year INT);INSERT INTO Exhibitions (id, year) VALUES (1, 2018), (2, 2019), (3, 2018), (4, 2017);

SELECT COUNT(*) FROM Exhibitions WHERE year IN (2018, 2019);


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

select regexp_match('abc', '(B)(c)', 'i');

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

SELECT count(*) FROM (select regexp_match('abc', '(B)(c)', 'i')) AS _sub;


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

-- Check that all serialization functions have signature
-- serialize(internal) returns bytea
-- Also insist that they be strict; it's wasteful to run them on NULLs.

SELECT a.aggfnoid, p.proname
FROM pg_aggregate as a, pg_proc as p
WHERE a.aggserialfn = p.oid AND
    (p.prorettype != 'bytea'::regtype OR p.pronargs != 1 OR
     p.proargtypes[0] != 'internal'::regtype OR
     NOT p.proisstrict);

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


Question: Generate PostgreSQL SQL for: What are the number of points for associated with exactly 3 stolen ends?

CREATE TABLE table_25176088_2 (pf VARCHAR, stolen_ends VARCHAR)

SELECT COUNT(pf) FROM table_25176088_2 WHERE stolen_ends = 3;


Question: Show a SQL definition from the pg_partman project (pg_partman--0.4.2--1.0.0, item 9).

/*
 * Create the trigger function for the parent table of a time-based partition set
 */
CREATE OR REPLACE FUNCTION create_time_function(p_parent_table text) RETURNS void
    LANGUAGE plpgsql SECURITY DEFINER
    AS $$
DECLARE

v_control                       text;
v_current_partition_name        text;
v_current_partition_timestamp   timestamptz;
v_datetime_string               text;
v_final_partition_timestamp     timestamptz;
v_job_id                        bigint;
v_jobmon_schema                 text;
v_old_search_path               text;
v_next_partition_name           text;
v_next_partition_timestamp      timestamptz;
v_part_interval                 interval;
v_premake                       int;
v_prev_partition_name           text;
v_prev_partition_timestamp      timestamptz;
v_step_id                       bigint;
v_trig_func                     text;
v_type                          text;

BEGIN

SELECT nspname INTO v_jobmon_schema FROM pg_namespace n, pg_extension e WHERE e.extname = 'pg_jobmon' AND e.extnamespace = n.oid;
IF v_jobmon_schema IS NOT NULL THEN
    SELECT current_setting('search_path') INTO v_old_search_path;
    EXECUTE 'SELECT set_config(''search_path'',''@extschema@,'||v_jobmon_schema||''',''false'')';
END IF;

IF v_jobmon_schema IS NOT NULL THEN
    v_job_id := add_job('PARTMAN CREATE FUNCTION: '||p_parent_table);
    v_step_id := add_step(v_job_id, 'Creating partition function for table '||p_parent_table);
END IF;

SELECT type
    , part_interval::interval
    , control
    , premake
    , datetime_string
INTO v_type
    , v_part_interval
    , v_control
    , v_premake
    , v_datetime_string
FROM @extschema@.part_config
WHERE parent_table = p_parent_table
AND (type = 'time-static' OR type = 'time-dynamic');

IF NOT FOUND THEN
    RAISE EXCEPTION 'ERROR: no config found for %', p_parent_table;
END IF;

IF v_type = 'time-static' THEN

    CASE
        WHEN v_part_interval = '15 mins' THEN
            v_current_partition_timestamp := date_trunc('hour', CURRENT_TIMESTAMP) +
                '15min'::interval * floor(date_part('minute', CURRENT_TIMESTAMP) / 15.0);
        WHEN v_part_interval = '30 mins' THEN
            v_current_partition_timestamp := date_trunc('hour', CURRENT_TIMESTAMP) +
                '30min'::interval * floor(date_part('minute', CURRENT_TIMESTAMP) / 30.0);
        WHEN v_part_interval = '1 hour' THEN
            v_current_partition_timestamp := date_trunc('hour', CURRENT_TIMESTAMP);
         WHEN v_part_interval = '1 day' THEN
            v_current_partition_timestamp := date_trunc('day', CURRENT_TIMESTAMP);
        WHEN v_part_interval = '1 week' THEN
            v_current_partition_timestamp := date_trunc('week', CURRENT_TIMESTAMP);
        WHEN v_part_interval = '1 month' THEN
            v_current_partition_timestamp := date_trunc('month', CURRENT_TIMESTAMP);
        WHEN v_part_interval = '3 months' THEN
            v_current_partition_timestamp := date_trunc('quarter', CURRENT_TIMESTAMP);
        WHEN v_part_interval = '1 year' THEN
            v_current_partition_timestamp := date_trunc('year', CURRENT_TIMESTAMP);
    END CASE;

    v_current_partition_name := p_parent_table || '_p' || to_char(v_current_partition_timestamp, v_datetime_string);
    v_next_partition_timestamp := v_current_partition_timestamp + v_part_interval::interval;

    v_trig_func := 'CREATE OR REPLACE FUNCTION '||p_parent_table||'_part_trig_func() RETURNS trigger LANGUAGE plpgsql AS $t$
        BEGIN
        IF TG_OP = ''INSERT'' THEN
            IF NEW.'||v_control||' >= '||quote_literal(v_current_partition_timestamp)||' AND NEW.'||v_control||' < '||quote_literal(v_next_partition_timestamp)|| ' THEN
                INSERT INTO '||v_current_partition_name||' VALUES (NEW.*); ';
    FOR i IN 1..v_premake LOOP
        v_prev_partition_timestamp := v_current_partition_timestamp - (v_part_interval::interval * i);
        v_next_partition_timestamp := v_current_partition_timestamp + (v_part_interval::interval * i);
        v_final_partition_timestamp := v_next_partition_timestamp + (v_part_interval::interval);
        v_prev_partition_name := p_parent_table || '_p' || to_char(v_prev_partition_timestamp, v_datetime_string);
        v_next_partition_name := p_parent_table || '_p' || to_char(v_next_partition_timestamp, v_datetime_string);

        v_trig_func := v_trig_func ||'
            ELSIF NEW.'||v_control||' >= '||quote_literal(v_prev_partition_timestamp)||' AND NEW.'||v_control||' < '||
                    quote_literal(v_prev_partition_timestamp + v_part_interval::interval)|| ' THEN
                INSERT INTO '||v_prev_partition_name||' VALUES (NEW.*);
            ELSIF NEW.'||v_control||' >= '||quote_literal(v_next_partition_timestamp)||' AND NEW.'||v_control||' < '||
                    quote_literal(v_final_partition_timestamp)|| ' THEN
                INSERT INTO '||v_next_partition_name||' VALUES (NEW.*); ';
    END LOOP;
    v_trig_func := v_trig_func ||'
            ELSE
                RETURN NEW;
            END IF;
        END IF;
        RETURN NULL;
        END $t$;';

    EXECUTE v_trig_func;

    IF v_jobmon_schema IS NOT NULL THEN
        PERFORM update_step(v_step_id, 'OK', 'Added function for current time interval: '||
            v_current_partition_timestamp||' to '||(v_final_partition_timestamp-'1sec'::interval));
    END IF;

ELSIF v_type = 'time-dynamic' THEN

    v_trig_func := 'CREATE OR REPLACE FUNCTION '||p_parent_table||'_part_trig_func() RETURNS trigger LANGUAGE plpgsql AS $t$
        DECLARE
            v_count                 int;
            v_partition_name        text;
            v_partition_timestamp   timestamptz;
            v_schemaname            text;
            v_tablename             text;
        BEGIN
        IF TG_OP = ''INSERT'' THEN
            ';
        CASE
            WHEN v_part_interval = '15 mins' THEN
                v_trig_func := v_trig_func||'v_partition_timestamp := date_trunc(''hour'', NEW.'||v_control||') +
                    ''15min''::interval * floor(date_part(''minute'', NEW.'||v_control||') / 15.0);';
            WHEN v_part_interval = '30 mins' THEN
                v_trig_func := v_trig_func||'v_partition_timestamp := date_trunc(''hour'', NEW.'||v_control||') +
                    ''30min''::interval * floor(date_part(''minute'', NEW.'||v_control||') / 30.0);';
            WHEN v_part_interval = '1 hour' THEN
                v_trig_func := v_trig_func||'v_partition_timestamp := date_trunc(''hour'', NEW.'||v_control||');';
             WHEN v_part_interval = '1 day' THEN
                v_trig_func := v_trig_func||'v_partition_timestamp := date_trunc(''day'', NEW.'||v_control||');';
            WHEN v_part_interval = '1 week' THEN
                v_trig_func := v_trig_func||'v_partition_timestamp := date_trunc(''week'', NEW.'||v_control||');';
            WHEN v_part_interval = '1 month' THEN
                v_trig_func := v_trig_func||'v_partition_timestamp := date_trunc(''month'', NEW.'||v_control||');';
            WHEN v_part_interval = '3 months' THEN
                v_trig_func := v_trig_func||'v_partition_timestamp := date_trunc(''quarter'', NEW.'||v_control||');';
            WHEN v_part_interval = '1 year' THEN
                v_trig_func := v_trig_func||'v_partition_timestamp := date_trunc(''year'', NEW.'||v_control||');';
        END CASE;

        v_trig_func := v_trig_func||'
            v_partition_name := '''||p_parent_table||'_p''|| to_char(v_partition_timestamp, '||quote_literal(v_datetime_string)||');
            v_schemaname := split_part(v_partition_name, ''.'', 1);
            v_tablename := split_part(v_partition_name, ''.'', 2);
            SELECT count(*) INTO v_count FROM pg_tables WHERE schemaname = v_schemaname AND tablename = v_tablename;
            IF v_count > 0 THEN
                EXECUTE ''INSERT INTO ''||v_partition_name||'' VALUES($1.*)'' USING NEW;
            ELSE
                RETURN NEW;
            END IF;
        END IF;

        RETURN NULL;
        END $t$;';

    EXECUTE v_trig_func;

    IF v_jobmon_schema IS NOT NULL THEN
        PERFORM update_step(v_step_id, 'OK', 'Added function for dynamic time table: '||p_parent_table);
    END IF;

ELSE
    RAISE EXCEPTION 'ERROR: Invalid time partitioning type given: %', v_type;
END IF;

IF v_jobmon_schema IS NOT NULL THEN
    PERFORM close_job(v_job_id);
    EXECUTE 'SELECT set_config(''search_path'','''||v_old_search_path||''',''false'')';
END IF;

EXCEPTION
    WHEN OTHERS THEN
        IF v_jobmon_schema IS NOT NULL THEN
            EXECUTE 'SELECT set_config(''search_path'',''@extschema@,'||v_jobmon_schema||''',''false'')';
            IF v_job_id IS NULL THEN
                v_job_id := add_job('PARTMAN CREATE FUNCTION: '||p_parent_table);
                v_step_id := add_step(v_job_id, 'Partition function maintenance for table '||p_parent_table||' failed');
            ELSIF v_step_id IS NULL THEN
                v_step_id := add_step(v_job_id, 'EXCEPTION before first step logged');
            END IF;
            PERFORM update_step(v_step_id, 'CRITICAL', 'ERROR: '||coalesce(SQLERRM,'unknown'));
            PERFORM fail_job(v_job_id);
            EXECUTE 'SELECT set_config(''search_path'','''||v_old_search_path||''',''false'')';
        END IF;
        RAISE EXCEPTION '%', SQLERRM;
END
$$;

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


Question: What is the percentage of legal aid clinics that are located in urban areas?

CREATE TABLE legal_aid_clinics (clinic_id INT, area_type VARCHAR(10));

SELECT 100.0 * COUNT(*) / (SELECT COUNT(*) FROM legal_aid_clinics) AS percentage FROM legal_aid_clinics WHERE area_type = 'urban';


Question: What is the total number of cybersecurity incidents detected in the Middle East and North Africa (MENA) region in 2021?

CREATE TABLE security_incidents (id INT, region VARCHAR(50), incident_date DATE, incident_number INT); INSERT INTO security_incidents (id, region, incident_date, incident_number) VALUES (1, 'MENA', '2021-02-03', 100), (2, 'MENA', '2021-12-20', 200);

SELECT SUM(incident_number) FROM security_incidents WHERE region = 'MENA' AND incident_date BETWEEN '2021-01-01' AND '2021-12-31';


Question: PostgreSQL regression test 'encoding': Write the SELECT query (example 9).

SELECT good, truncated, with_nul FROM regress_encoding;

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

SELECT count(*) FROM (SELECT good, truncated, with_nul FROM regress_encoding) AS _sub;


Question: Generate PostgreSQL SQL for: What season has 2 as a rank?

CREATE TABLE table_name_18 (season VARCHAR, rank VARCHAR)

SELECT season FROM table_name_18 WHERE rank = '2';


Question: Generate PostgreSQL SQL for: What is the Margin, when Date is 19 July 2008 (Round 19)?

CREATE TABLE table_name_27 (margin VARCHAR, date VARCHAR)

SELECT margin FROM table_name_27 WHERE date = '19 july 2008 (round 19)';


Question: Generate PostgreSQL SQL for: What is the Year for Jazz club of Houston?

CREATE TABLE table_name_54 (years_for_jazz VARCHAR, school_club_team VARCHAR)

SELECT years_for_jazz FROM table_name_54 WHERE school_club_team = 'houston';


Question: Generate PostgreSQL SQL for: What was the TO par for the player who scored 68-69=137?

CREATE TABLE table_name_82 (to_par VARCHAR, score VARCHAR)

SELECT to_par FROM table_name_82 WHERE score = 68 - 69 = 137;


Question: Generate PostgreSQL SQL for: what city is the toamasina airport in?

CREATE TABLE table_name_42 (city VARCHAR, airport VARCHAR)

SELECT city FROM table_name_42 WHERE airport = 'toamasina airport';


Question: Generate PostgreSQL SQL for: Which team 1 played against team 2 of Tours FC (D2)?

CREATE TABLE table_name_21 (team_1 VARCHAR, team_2 VARCHAR)

SELECT team_1 FROM table_name_21 WHERE team_2 = 'tours fc (d2)';


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

CREATE FUNCTION pgstattuple(IN reloid regclass,
    OUT table_len BIGINT,		-- physical table length in bytes
    OUT tuple_count BIGINT,		-- number of live tuples
    OUT tuple_len BIGINT,		-- total tuples length in bytes
    OUT tuple_percent FLOAT8,		-- live tuples in %
    OUT dead_tuple_count BIGINT,	-- number of dead tuples
    OUT dead_tuple_len BIGINT,		-- total dead tuples length in bytes
    OUT dead_tuple_percent FLOAT8,	-- dead tuples in %
    OUT free_space BIGINT,		-- free space in bytes
    OUT free_percent FLOAT8)		-- free space in %
AS 'MODULE_PATHNAME', 'pgstattuplebyid'
LANGUAGE C STRICT;

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


Question: Generate PostgreSQL SQL for: Who had the high assists on November 17?

CREATE TABLE table_27744976_6 (high_assists VARCHAR, date VARCHAR)

SELECT high_assists FROM table_27744976_6 WHERE date = 'November 17';


Question: List the facilities located in California and their corresponding environmental impact scores from the 'facilities' and 'scores' tables.

CREATE TABLE facilities(facility_id INT, facility_name TEXT, state TEXT); CREATE TABLE scores(facility_id INT, environmental_score INT);

SELECT facilities.facility_name, scores.environmental_score FROM facilities INNER JOIN scores ON facilities.facility_id = scores.facility_id WHERE facilities.state = 'California';


Question: Update the names of all authors from the 'Freelance' category to 'Independent Contributor'.

CREATE TABLE authors (id INT, name TEXT, category TEXT); INSERT INTO authors (id, name, category) VALUES (1, 'Jane Doe', 'Freelance');

UPDATE authors SET category = 'Independent Contributor' WHERE category = 'Freelance';


Question: Which country has the highest total production of rare earth elements, Australia or Brazil?

CREATE TABLE rare_earth_production (country VARCHAR(20), quantity INT); INSERT INTO rare_earth_production (country, quantity) VALUES ('Australia', 20000), ('Brazil', 15000);

SELECT country, MAX(quantity) FROM rare_earth_production WHERE country IN ('Australia', 'Brazil') GROUP BY country;


Question: What is the total greenhouse gas emissions reduction due to energy efficiency projects in the EU?

CREATE TABLE greenhouse_gas_emissions (id INT PRIMARY KEY, source_type VARCHAR(50), country VARCHAR(50), year INT, amount DECIMAL(10,2));CREATE TABLE energy_efficiency_projects (id INT PRIMARY KEY, project_type VARCHAR(50), country VARCHAR(50), year INT, energy_savings DECIMAL(10,2));CREATE VIEW v_eu_energy_efficiency_projects AS SELECT eep.project_type, eep.country, SUM(eep.energy_savings) AS total_energy_savings FROM energy_efficiency_projects eep WHERE eep.country LIKE 'EU%' GROUP BY eep.project_type, eep.country;CREATE VIEW v_ghg_emissions_reductions AS SELECT ghe.source_type, ghe.country, SUM(ghe.amount) * -1 AS total_reduction FROM greenhouse_gas_emissions ghe JOIN v_eu_energy_efficiency_projects eep ON ghe.country = eep.country WHERE ghe.source_type = 'Energy' GROUP BY ghe.source_type, ghe.country;

SELECT total_reduction FROM v_ghg_emissions_reductions WHERE source_type = 'Energy';


Question: Generate PostgreSQL SQL for: What was the airdate of the episode with 106000 dave ja vu viewers?

CREATE TABLE table_25721_3 (airdate VARCHAR, dave_ja_vu_viewers VARCHAR)

SELECT airdate FROM table_25721_3 WHERE dave_ja_vu_viewers = 106000;


Question: Update the financialWellbeing table to reflect increased financial wellbeing for user 'Ahmed'.

CREATE TABLE FinancialWellbeing (userID VARCHAR(20), wellbeingScore INT); INSERT INTO FinancialWellbeing (userID, wellbeingScore) VALUES ('Ahmed', 6), ('Sara', 8);

UPDATE FinancialWellbeing SET wellbeingScore = 8 WHERE userID = 'Ahmed';


Question: Update the mental health parity data to reflect the correct number of mental health visits for patient 5.

CREATE TABLE MentalHealthParity (PatientID int, MentalHealthVisits int); INSERT INTO MentalHealthParity (PatientID, MentalHealthVisits) VALUES (1, 5), (2, 3), (3, 6), (4, 4), (5, 8), (6, 7);

UPDATE MentalHealthParity SET MentalHealthVisits = 7 WHERE PatientID = 5;


Question: Generate PostgreSQL SQL for: What is the number of Frequency MHz in woodstock, georgia?

CREATE TABLE table_name_91 (frequency_mhz INTEGER, city_of_license VARCHAR)

SELECT SUM(frequency_mhz) FROM table_name_91 WHERE city_of_license = 'woodstock, georgia';


Question: Generate PostgreSQL SQL for: What is the Score of the Burnley Home game?

CREATE TABLE table_name_57 (score VARCHAR, home_team VARCHAR)

SELECT score FROM table_name_57 WHERE home_team = 'burnley';


Question: Generate PostgreSQL SQL for: Which lap number had a grid number bigger than 9 and where the driver was Mark Webber?

CREATE TABLE table_name_77 (laps VARCHAR, grid VARCHAR, driver VARCHAR)

SELECT laps FROM table_name_77 WHERE grid > 9 AND driver = 'mark webber';


Question: Update the population of the Arctic Fox by 150.

CREATE TABLE species (id INT PRIMARY KEY, name VARCHAR(50), population INT);

WITH updated_population AS (UPDATE species SET population = population + 150 WHERE name = 'Arctic Fox') SELECT * FROM species WHERE name = 'Arctic Fox';


Question: What is the maximum support duration for each location?

CREATE TABLE If Not Exists refugee_support (supporter_id INT, supporter_name TEXT, location TEXT, support_duration INT); INSERT INTO refugee_support (supporter_id, supporter_name, location, support_duration) VALUES (4, 'Alex Johnson', 'Afghanistan', 75), (5, 'Sophia Lee', 'Pakistan', 50);

SELECT location, MAX(support_duration) as max_support_duration FROM refugee_support GROUP BY location;


Question: What is the sum of all ticket sales in Asia?

CREATE TABLE asia_concerts (concert_id INT, sales DECIMAL(10, 2)); INSERT INTO asia_concerts (concert_id, sales) VALUES (1, 5000), (2, 6000), (3, 7000), (4, 8000);

SELECT SUM(sales) AS total_sales FROM asia_concerts WHERE country = 'Asia';


Question: Find the number of male and female students in the 'Student' table

CREATE TABLE Student (StudentID INT, Gender VARCHAR(10)); INSERT INTO Student (StudentID, Gender) VALUES (1, 'Male'), (2, 'Female'), (3, 'Male');

SELECT Gender, COUNT(*) FROM Student GROUP BY Gender;


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

DROP TRIGGER show_trigger_data_trig on trigger_test;

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


Question: Generate PostgreSQL SQL for: Where did the game(s) against Iowa take place?

CREATE TABLE table_name_94 (site VARCHAR, opponent VARCHAR)

SELECT site FROM table_name_94 WHERE opponent = 'iowa';


Question: Generate PostgreSQL SQL for: What is the Date of the Rodez, France Tournament?

CREATE TABLE table_name_63 (date VARCHAR, tournament VARCHAR)

SELECT date FROM table_name_63 WHERE tournament = 'rodez, france';


Question: What is the count of packages in 'received' status at each warehouse in 'Asia'?

CREATE TABLE Warehouse (id INT, name VARCHAR(20), city VARCHAR(20), country VARCHAR(20)); INSERT INTO Warehouse (id, name, city, country) VALUES (1, 'Seoul Warehouse', 'Seoul', 'South Korea'), (2, 'Mumbai Warehouse', 'Mumbai', 'India'), (3, 'Tokyo Warehouse', 'Tokyo', 'Japan'); CREATE TABLE Packages (id INT, warehouse_id INT, status VARCHAR(20)); INSERT INTO Packages (id, warehouse_id, status) VALUES (1, 1, 'received'), (2, 1, 'processing'), (3, 2, 'received'), (4, 2, 'received'), (5, 3, 'processing');

SELECT warehouse_id, COUNT(*) FROM Packages WHERE status = 'received' GROUP BY warehouse_id HAVING country = 'Asia';


Question: PL/pgSQL test: Plpgsql Transaction (example 27).

$$;

CALL transaction_test8();

-- commit inside cursor loop
CREATE TABLE test2 (x int);
INSERT INTO test2 VALUES (0), (1), (2), (3), (4);

TRUNCATE test1;

DO LANGUAGE plpgsql $$
DECLARE
    r RECORD;

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


Question: Generate PostgreSQL SQL for: Which Percentage has a Draw of 6?

CREATE TABLE table_name_9 (percentage VARCHAR, draw VARCHAR)

SELECT percentage FROM table_name_9 WHERE draw = 6;


Question: Generate PostgreSQL SQL for: Who are the players that have attended Stanford?

CREATE TABLE table_16494599_10 (player VARCHAR, school_club_team VARCHAR)

SELECT player FROM table_16494599_10 WHERE school_club_team = 'Stanford';


Question: Generate PostgreSQL SQL for: Which LEMA/SUBLEMA has a Ch of Senators of 2?

CREATE TABLE table_name_4 (lema_sublema VARCHAR, ch_of_senators VARCHAR)

SELECT lema_sublema FROM table_name_4 WHERE ch_of_senators = '2';


Question: Generate PostgreSQL SQL for: Name the number of series for 19

CREATE TABLE table_23958944_6 (no_by_series VARCHAR, no_by_season VARCHAR)

SELECT no_by_series FROM table_23958944_6 WHERE no_by_season = 19;


Question: Who are the founders of the startups that have received funding of over 2000000?

CREATE TABLE company (name VARCHAR(255), founder_name VARCHAR(100)); INSERT INTO company (name, founder_name) VALUES ('CompanyA', 'John Smith'), ('CompanyB', 'Jane Doe'), ('CompanyC', 'Michael Brown'), ('CompanyD', 'Sarah Johnson'); CREATE TABLE funding (company_name VARCHAR(255), amount INT); INSERT INTO funding (company_name, amount) VALUES ('CompanyA', 1000000), ('CompanyB', 2500000), ('CompanyC', 1500000), ('CompanyD', 3000000);

SELECT company.founder_name FROM company INNER JOIN funding ON company.name = funding.company_name WHERE funding.amount > 2000000;


Question: What is the average rating of cultural heritage sites in Madrid?

CREATE TABLE heritage_sites (site_id INT, site_name TEXT, city TEXT, rating INT); INSERT INTO heritage_sites (site_id, site_name, city, rating) VALUES (1, 'Prado Museum', 'Madrid', 5), (2, 'Royal Palace', 'Madrid', 4), (3, 'Retiro Park', 'Madrid', 4);

SELECT AVG(rating) FROM heritage_sites WHERE city = 'Madrid';


Question: Generate PostgreSQL SQL for: How many picks for round 12?

CREATE TABLE table_name_5 (pick__number VARCHAR, round VARCHAR)

SELECT COUNT(pick__number) FROM table_name_5 WHERE round = 12;


Question: Generate PostgreSQL SQL for: Who was the opponent in a week less than 8 on October 9, 1960?

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

SELECT opponent FROM table_name_24 WHERE week < 8 AND date = 'october 9, 1960';


Question: What is the total billing amount by attorney in the Southwest region?

CREATE TABLE Attorneys (AttorneyID int, Name varchar(50), Region varchar(10)); INSERT INTO Attorneys VALUES (1, 'Alex Garcia', 'Southwest'), (2, 'Hee Jun Lee', 'Northeast'); CREATE TABLE Billing (BillingID int, AttorneyID int, Amount decimal(10,2)); INSERT INTO Billing VALUES (1, 1, 800.00), (2, 1, 1200.00), (3, 2, 500.00), (4, 2, 700.00);

SELECT A.Name, SUM(B.Amount) as TotalBilling FROM Attorneys A JOIN Billing B ON A.AttorneyID = B.AttorneyID WHERE A.Region = 'Southwest' GROUP BY A.Name;


Question: Update the 'space_exploration' table to mark the 'Apollo 11' mission as 'successful'

CREATE TABLE space_exploration (id INT PRIMARY KEY, mission_name VARCHAR(50), mission_status VARCHAR(20));

UPDATE space_exploration SET mission_status = 'successful' WHERE mission_name = 'Apollo 11';


Question: Generate PostgreSQL SQL for: Who got the loss on the game that ended in a 52-36 record?

CREATE TABLE table_name_22 (loss VARCHAR, record VARCHAR)

SELECT loss FROM table_name_22 WHERE record = '52-36';


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

SELECT 2000 FROM table_name_67 WHERE 1998 = '1.5';


Question: What is the maximum funding received by startups in the clean energy sector that were founded after 2010?

CREATE TABLE company (id INT, name TEXT, industry TEXT, founding_year INT); INSERT INTO company (id, name, industry, founding_year) VALUES (1, 'CleanTechInnovations', 'Clean Energy', 2011), (2, 'PowerEasy', 'Clean Energy', 2016); CREATE TABLE funding (id INT, company_id INT, amount INT); INSERT INTO funding (id, company_id, amount) VALUES (1, 1, 3000000), (2, 2, 1000000);

SELECT MAX(funding.amount) FROM funding INNER JOIN company ON funding.company_id = company.id WHERE company.industry = 'Clean Energy' AND company.founding_year > 2010;


Question: How many events are in the 'events' table for each type?

CREATE TABLE events (event_id INT, name VARCHAR(50), type VARCHAR(50), attendance INT); INSERT INTO events (event_id, name, type, attendance) VALUES (1, 'Art Exhibit', 'Painting', 1500); INSERT INTO events (event_id, name, type, attendance) VALUES (2, 'Theater Performance', 'Play', 850); INSERT INTO events (event_id, name, type, attendance) VALUES (3, 'Art Exhibit', 'Sculpture', 1200);

SELECT type, COUNT(*) as event_count FROM events GROUP BY type;


Question: What is the maximum energy storage capacity (in MWh) in South Korea?

CREATE TABLE energy_storage (country VARCHAR(20), capacity FLOAT); INSERT INTO energy_storage (country, capacity) VALUES ('South Korea', 500.0), ('South Korea', 600.0), ('South Korea', 700.0);

SELECT MAX(capacity) FROM energy_storage WHERE country = 'South Korea';


Question: Generate PostgreSQL SQL for: Which player on the Bulls has a 6 May 1978 birthday?

CREATE TABLE table_name_58 (player VARCHAR, club_province VARCHAR, date_of_birth__age_ VARCHAR)

SELECT player FROM table_name_58 WHERE club_province = 'bulls' AND date_of_birth__age_ = '6 may 1978';


Question: Update the record for provider with ID 12345 to reflect their new title, 'Senior Community Health Worker'

CREATE TABLE providers (id INT PRIMARY KEY, name VARCHAR(100), city VARCHAR(50), specialty VARCHAR(50));

UPDATE providers SET specialty = 'Senior Community Health Worker' WHERE id = 12345;


Question: Select the details of the fields that have a size greater than 5000 square meters

CREATE TABLE PrecisionAgriculture.FieldDetails (FieldID INT, FieldSize FLOAT, Location VARCHAR(255));

SELECT FieldID, FieldSize, Location FROM PrecisionAgriculture.FieldDetails WHERE FieldSize > 5000;


Question: Generate PostgreSQL SQL for: What is the name of the Home Stadium in which the Division is in the south, and Conference is national, as well as being in the city named charlotte, North Carolina?

CREATE TABLE table_name_64 (home_stadium VARCHAR, city VARCHAR, division VARCHAR, conference VARCHAR)

SELECT home_stadium FROM table_name_64 WHERE division = 'south' AND conference = 'national' AND city = 'charlotte, north carolina';


Question: Generate PostgreSQL SQL for: What was the result of the election in the Texas 3 district?

CREATE TABLE table_1342149_43 (result VARCHAR, district VARCHAR)

SELECT result FROM table_1342149_43 WHERE district = 'Texas 3';


Question: Change the court id from 3 to 4 for judge with id 4

CREATE TABLE judges (id INT, first_name VARCHAR(20), last_name VARCHAR(20), court_id INT); INSERT INTO judges (id, first_name, last_name, court_id) VALUES (4, 'Fatima', 'Adebayo', 3); CREATE TABLE courts (id INT, name VARCHAR(50), location VARCHAR(50)); INSERT INTO courts (id, name, location) VALUES (3, 'High Court of New Zealand', 'Wellington'); INSERT INTO courts (id, name, location) VALUES (4, 'Federal Court of Nigeria', 'Abuja');

UPDATE judges SET court_id = 4 WHERE id = 4;


Question: Generate PostgreSQL SQL for: What was the album Closer: The Best of Sarah Mclachlan certified as?

CREATE TABLE table_name_88 (certification VARCHAR, album VARCHAR)

SELECT certification FROM table_name_88 WHERE album = 'closer: the best of sarah mclachlan';


Question: Generate PostgreSQL SQL for: What is the date amer sulaiman won?

CREATE TABLE table_name_50 (date VARCHAR, winner VARCHAR)

SELECT date FROM table_name_50 WHERE winner = 'amer sulaiman';


Question: Generate PostgreSQL SQL for: How big was the largest crowd recorded at the Arden Street Oval venue?

CREATE TABLE table_name_73 (crowd INTEGER, venue VARCHAR)

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


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

CREATE FUNCTION g_intbig_options(internal)
RETURNS void
AS 'MODULE_PATHNAME', 'g_intbig_options'
LANGUAGE C IMMUTABLE PARALLEL SAFE;


Question: Write the DML statement from PostgreSQL regression test 'foreign_key' (example 302).

update pktable set base1=base1*4 where base1<3;

Explanation: DML from PostgreSQL core regression test for Foreign Key.


Question: How many students are enrolled in the 'AssistiveTechnology' and 'SignLanguageInterpreter' programs in the 'StudentPrograms' table?

CREATE TABLE StudentPrograms (student_id INT, program_name VARCHAR(255)); INSERT INTO StudentPrograms (student_id, program_name) VALUES (1, 'AssistiveTechnology'), (2, 'SignLanguageInterpreter'), (3, 'ExtendedTestingTime'), (4, 'AssistiveTechnology'), (5, 'ExtendedTestingTime');

SELECT COUNT(*) FROM StudentPrograms WHERE program_name IN ('AssistiveTechnology', 'SignLanguageInterpreter');


Question: What is the average financial capability score for men in South Africa and Brazil?

CREATE TABLE afc_scores (name TEXT, gender TEXT, country TEXT, score NUMERIC); INSERT INTO afc_scores (name, gender, country, score) VALUES ('John Doe', 'Male', 'South Africa', 70), ('John Smith', 'Male', 'Brazil', 75), ('Jane Doe', 'Female', 'South Africa', 75);

SELECT AVG(score) FROM afc_scores WHERE gender = 'Male' AND country IN ('South Africa', 'Brazil');


Question: List all wildlife species and their respective habitats.

CREATE TABLE wildlife_species (id INT, species VARCHAR(255)); CREATE TABLE wildlife_habitat (id INT, habitat VARCHAR(255)); INSERT INTO wildlife_species (id, species) VALUES (1, 'Tiger'), (2, 'Elephant'), (3, 'Monkey'); INSERT INTO wildlife_habitat (id, habitat) VALUES (1, 'Jungle'), (2, 'Savannah'), (3, 'Forest');

SELECT wildlife_species.species, wildlife_habitat.habitat FROM wildlife_species INNER JOIN wildlife_habitat ON wildlife_species.id = wildlife_habitat.id;


Question: What is the total revenue from Electronic dance music concerts in May?

CREATE TABLE Concerts (id INT, genre VARCHAR(20), price DECIMAL(5,2)); INSERT INTO Concerts (id, genre, price) VALUES (1, 'Electronic dance music', 100.00), (2, 'Rock', 75.00), (3, 'Electronic dance music', 120.00); CREATE TABLE Dates (id INT, concert_id INT, date DATE); INSERT INTO Dates (id, concert_id) VALUES (1, 1), (2, 2), (3, 3);

SELECT SUM(price) FROM Concerts JOIN Dates ON Concerts.id = Dates.concert_id WHERE Concerts.genre = 'Electronic dance music' AND Dates.date BETWEEN '2022-05-01' AND '2022-05-31';


Question: List all routes with fare collections in July.

SELECT route_name FROM route JOIN fare ON route.route_id = fare.route_id WHERE MONTH(collection_date) = 7;


Question: List all artworks and their respective curators.

CREATE TABLE Artworks (artwork_name TEXT, curator TEXT);

SELECT artwork_name, curator FROM Artworks;


Question: Generate PostgreSQL SQL for: what is the location for the date (to) 8 october 1922?

CREATE TABLE table_12562214_1 (location VARCHAR, date__to_ VARCHAR)

SELECT location FROM table_12562214_1 WHERE date__to_ = '8 October 1922';


Question: How many IoT sensors were installed in rural and urban areas in each country in the past quarter?

CREATE TABLE country (id INTEGER, name TEXT);CREATE TABLE region (id INTEGER, country_id INTEGER, name TEXT, type TEXT);CREATE TABLE iot_sensor (id INTEGER, region_id INTEGER, installed_date DATE);

SELECT co.name as country, r.type as area_type, COUNT(s.id) as num_sensors FROM country co INNER JOIN region r ON co.id = r.country_id INNER JOIN iot_sensor s ON r.id = s.region_id WHERE s.installed_date >= DATEADD(quarter, -1, CURRENT_DATE) GROUP BY co.name, r.type;


Question: Number of underwater volcanoes near the Philippines

CREATE TABLE Underwater_Volcanoes (id INT, volcano_name VARCHAR(50), location VARCHAR(50), depth FLOAT); INSERT INTO Underwater_Volcanoes (id, volcano_name, location, depth) VALUES (1, 'Apo', 'Philippines', -2200);

SELECT location, COUNT(*) FROM Underwater_Volcanoes GROUP BY location HAVING location = 'Philippines';


Question: What is the total cost of accommodations for students with visual impairments in H1 2021?

CREATE TABLE accommodations (id INT, student_id INT, accommodation_type VARCHAR(50), cost FLOAT, accommodation_date DATE); INSERT INTO accommodations (id, student_id, accommodation_type, cost, accommodation_date) VALUES (1, 2, 'Sign Language Interpreter', 50.00, '2021-01-01'), (2, 3, 'Assistive Listening Devices', 300.00, '2021-04-01');

SELECT SUM(cost) FROM accommodations WHERE accommodation_date BETWEEN '2021-01-01' AND '2021-06-30' AND EXISTS (SELECT * FROM students WHERE students.id = accommodations.student_id AND students.disability_type = 'Visual Impairment');


Question: Generate PostgreSQL SQL for: Name the Tag Team with a Time of 03:34?

CREATE TABLE table_name_10 (tag_team VARCHAR, time VARCHAR)

SELECT tag_team FROM table_name_10 WHERE time = '03:34';


Question: Insert a new record into the "manufacturing_data" table

CREATE TABLE manufacturing_data (id INT PRIMARY KEY, chemical_name VARCHAR(255), quantity_produced INT, date_manufactured DATE);

INSERT INTO manufacturing_data (id, chemical_name, quantity_produced, date_manufactured) VALUES (1, 'Ammonia', 100, '2022-01-01');


Question: Generate PostgreSQL SQL for: On what date was Keiichi Ubukata the mediator and Mitsuko Mori the red team host?

CREATE TABLE table_1315616_1 (date VARCHAR, mediator VARCHAR, red_team_host VARCHAR)

SELECT date FROM table_1315616_1 WHERE mediator = 'Keiichi Ubukata' AND red_team_host = 'Mitsuko Mori';


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

CREATE OPERATOR <-> (
	LEFTARG = interval,
	RIGHTARG = interval,
	PROCEDURE = interval_dist,
	COMMUTATOR = '<->'
);


Question: Generate PostgreSQL SQL for: What was the result in 2013 in the tournament whose 2010 result was q2?

SELECT 2013 FROM table_name_8 WHERE 2010 = 'q2';


Question: Which artists have released the most songs in the Jazz genre on Apple Music?

CREATE TABLE AppleMusicSongs (ArtistID INT, ArtistName VARCHAR(100), Genre VARCHAR(50), SongID INT); INSERT INTO AppleMusicSongs (ArtistID, ArtistName, Genre, SongID) VALUES (1, 'Miles Davis', 'Jazz', 1), (2, 'John Coltrane', 'Jazz', 2), (3, 'Miles Davis', 'Jazz', 3);

SELECT ArtistName, COUNT(*) as SongCount FROM AppleMusicSongs WHERE Genre = 'Jazz' GROUP BY ArtistName ORDER BY SongCount DESC;


Question: Write the DML statement from PostgreSQL regression test 'create_misc' (example 12).

INSERT INTO b_star (class, b) VALUES ('b', 'bumble'::text);

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


Question: What is the average amount of research funding received by each department in the past two years?

CREATE TABLE Departments (DepartmentID INT, Name VARCHAR(50)); INSERT INTO Departments VALUES (1, 'Computer Science'); CREATE TABLE ResearchGrants (GrantID INT, DepartmentID INT, Amount DECIMAL(10,2)); INSERT INTO ResearchGrants VALUES (1, 1, 5000); INSERT INTO ResearchGrants VALUES (2, 1, 7000);

SELECT Departments.Name, AVG(ResearchGrants.Amount) FROM Departments INNER JOIN ResearchGrants ON Departments.DepartmentID = ResearchGrants.DepartmentID WHERE ResearchGrants.GrantID >= DATEADD(year, -2, GETDATE()) GROUP BY Departments.Name;


Question: Generate PostgreSQL SQL for: Name the most legs for steinlager 2

CREATE TABLE table_256862_1 (legs INTEGER, winning_yacht VARCHAR)

SELECT MAX(legs) FROM table_256862_1 WHERE winning_yacht = 'Steinlager 2';


Question: What is the maximum water consumption per day in Egypt?

CREATE TABLE daily_water_consumption (country VARCHAR(20), max_consumption FLOAT); INSERT INTO daily_water_consumption (country, max_consumption) VALUES ('Egypt', 1200000);

SELECT max_consumption FROM daily_water_consumption WHERE country = 'Egypt';


Question: What is the total amount donated by each donor in the 'donors' table, sorted by the total donation amount in descending order?

CREATE TABLE donors (donor_id INT, donor_name TEXT, donation_amount FLOAT); INSERT INTO donors (donor_id, donor_name, donation_amount) VALUES (1, 'John Doe', 250.00), (2, 'Jane Smith', 200.00), (3, 'Alice Johnson', 150.00);

SELECT donor_name, SUM(donation_amount) as total_donation FROM donors GROUP BY donor_name ORDER BY total_donation DESC;


Question: Generate PostgreSQL SQL for: What is the latest first elected?

CREATE TABLE table_2668405_17 (first_elected INTEGER)

SELECT MAX(first_elected) FROM table_2668405_17;


Question: Generate PostgreSQL SQL for: Which rider has time of +19.751?

CREATE TABLE table_name_59 (rider VARCHAR, time VARCHAR)

SELECT rider FROM table_name_59 WHERE time = '+19.751';


Question: Generate PostgreSQL SQL for: What is the minimum number of members Europe had at the time Africa had 7375139?

CREATE TABLE table_1914090_2 (europe INTEGER, africa VARCHAR)

SELECT MIN(europe) FROM table_1914090_2 WHERE africa = 7375139;


Question: How many food safety violations were there in each restaurant in February 2022?

CREATE TABLE restaurants (id INT, name TEXT, location TEXT); INSERT INTO restaurants (id, name, location) VALUES (1, 'Restaurant A', 'City A'), (2, 'Restaurant B', 'City B'); CREATE TABLE inspections (restaurant_id INT, date DATE, violations INT); INSERT INTO inspections (restaurant_id, date, violations) VALUES (1, '2022-02-01', 2), (1, '2022-02-15', 1), (2, '2022-02-03', 3), (2, '2022-02-20', 0);

SELECT r.id, SUM(i.violations) as total_violations FROM inspections i JOIN restaurants r ON i.restaurant_id = r.id WHERE i.date BETWEEN '2022-02-01' AND '2022-02-28' GROUP BY r.id;


Question: Generate PostgreSQL SQL for: What high assists have a game greater than 46?

CREATE TABLE table_name_61 (high_assists VARCHAR, game INTEGER)

SELECT high_assists FROM table_name_61 WHERE game > 46;


Question: Generate PostgreSQL SQL for: What is the nationality of the player picked to go to Washington Capitals?

CREATE TABLE table_2897457_2 (nationality VARCHAR, nhl_team VARCHAR)

SELECT nationality FROM table_2897457_2 WHERE nhl_team = 'Washington Capitals';


Question: What is the average sentence length for each type of crime in Los Angeles County in 2019?

CREATE TABLE sentences (crime_type VARCHAR(255), sentence_length INT); INSERT INTO sentences (crime_type, sentence_length) VALUES ('Murder', 25);

SELECT crime_type, AVG(sentence_length) OVER (PARTITION BY crime_type) as avg_sentence FROM sentences WHERE YEAR(sentence_date) = 2019;


Question: Generate PostgreSQL SQL for: What is the Third in the 1993-94 season where Philippe Caux was a lead?

CREATE TABLE table_name_39 (third VARCHAR, lead VARCHAR, season VARCHAR)

SELECT third FROM table_name_39 WHERE lead = 'philippe caux' AND season = '1993-94';


Question: Generate PostgreSQL SQL for: Which Venue has a Notes of 2:28:31?

CREATE TABLE table_name_83 (venue VARCHAR, notes VARCHAR)

SELECT venue FROM table_name_83 WHERE notes = '2:28:31';


Question: Update the quantity of a sustainable material for a brand.

CREATE TABLE brands (id INT, name VARCHAR(50)); CREATE TABLE materials_used (id INT, brand_id INT, material VARCHAR(50), quantity INT); INSERT INTO brands (id, name) VALUES (1, 'Brand A'), (2, 'Brand B'); INSERT INTO materials_used (id, brand_id, material, quantity) VALUES (1, 1, 'Organic Cotton', 100), (2, 1, 'Recycled Polyester', 150), (3, 2, 'Organic Cotton', 200);

UPDATE materials_used SET quantity = 175 WHERE id = 1;


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

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

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


Question: Generate PostgreSQL SQL for: Which Sanskrit has an English of mindfulness of breathing?

CREATE TABLE table_name_26 (sanskrit VARCHAR, english VARCHAR)

SELECT sanskrit FROM table_name_26 WHERE english = 'mindfulness of breathing';


Question: Generate PostgreSQL SQL for: What is the home team score with Away team Richmond?

CREATE TABLE table_name_20 (home_team VARCHAR, away_team VARCHAR)

SELECT home_team AS score FROM table_name_20 WHERE away_team = 'richmond';


Question: What is the maximum revenue generated by a single OTA for a hotel in Japan with a 4-star rating?

CREATE TABLE hotels (hotel_id INT, hotel_name TEXT, country TEXT, stars INT, revenue FLOAT); INSERT INTO hotels (hotel_id, hotel_name, country, stars, revenue) VALUES (1, 'Hotel V', 'Japan', 4, 12000), (2, 'Hotel W', 'Japan', 5, 18000), (3, 'Hotel X', 'Japan', 4, 15000); CREATE TABLE otas (ota_id INT, ota_name TEXT, hotel_id INT, otas_revenue FLOAT); INSERT INTO otas (ota_id, ota_name, hotel_id, otas_revenue) VALUES (1, 'OTA1', 1, 8000), (2, 'OTA2', 2, 10000), (3, 'OTA3', 3, 13000), (4, 'OTA4', 1, 10000);

SELECT MAX(otas_revenue) FROM otas JOIN hotels ON otas.hotel_id = hotels.hotel_id WHERE hotels.country = 'Japan' AND hotels.stars = 4;