Question: Update records of donors with the first name 'John' and add a $250 bonus donation made on Dec 31, 2022

CREATE TABLE Donors (DonorID INT, FirstName VARCHAR(50), LastName VARCHAR(50), DonationDate DATE, Amount DECIMAL(10,2));

UPDATE Donors SET DonationDate = '2022-12-31', Amount = Amount + 250 WHERE FirstName = 'John';


Question: PostgreSQL regression test 'generated_stored': Write the SELECT query (example 26).

SELECT gtest1 FROM gtest1 ORDER BY a;  -- whole-row reference
SELECT a, (SELECT gtest1.b) FROM gtest1 ORDER BY a;  -- sublink
DELETE FROM gtest1 WHERE a >= 3;

Explanation: Regression test for Generated Stored in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT gtest1 FROM gtest1 ORDER BY a;  -- whole-row reference
SELECT a, (SELECT gtest1.b) FROM gtest1 ORDER BY a;  -- sublink
DELETE FROM gtest1 WHERE a >= 3) AS _sub;


Question: What is the average donation amount for 'Anna Lee' in 2021?

CREATE TABLE donors (donor_id INT, donor_name TEXT, donation_amount FLOAT, cause TEXT, donation_date DATE);

SELECT AVG(donation_amount) FROM donors WHERE donor_name = 'Anna Lee' AND donation_date BETWEEN '2021-01-01' AND '2021-12-31';


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

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

SELECT count(*) FROM (SELECT to_number('$1234.56','L9,999.99')) AS _sub;


Question: What was the market access strategy for 'DrugB' in Japan?

CREATE TABLE market_access(drug_name TEXT, market_country TEXT, strategy_description TEXT); INSERT INTO market_access(drug_name, market_country, strategy_description) VALUES('DrugB', 'Japan', 'Direct to consumer');

SELECT strategy_description FROM market_access WHERE drug_name = 'DrugB' AND market_country = 'Japan';


Question: Generate PostgreSQL SQL for: Who is the GamePlan when Jacqueline King is the actor in the original production?

CREATE TABLE table_name_71 (gameplan VARCHAR, actor_in_original_production VARCHAR)

SELECT gameplan FROM table_name_71 WHERE actor_in_original_production = 'jacqueline king';


Question: Write the DML statement from PostgreSQL regression test 'tsearch' (example 389).

insert into phrase_index_test values (to_tsvector('english', 'A fat cat has just eaten a rat.'));

Explanation: DML from PostgreSQL core regression test for Tsearch.


Question: Generate PostgreSQL SQL for: Can you tell me the Record that has the Opponent of vs. hamilton tiger cats?

CREATE TABLE table_name_55 (record VARCHAR, opponent VARCHAR)

SELECT record FROM table_name_55 WHERE opponent = 'vs. hamilton tiger cats';


Question: What is the average heart rate during workouts for members who have a premium membership?

CREATE TABLE member_heart_rate (member_id INT, workout_id INT, heart_rate INT); INSERT INTO member_heart_rate (member_id, workout_id, heart_rate) VALUES (1, 1, 120), (1, 2, 130), (2, 3, 150), (2, 4, 140), (3, 5, 110); CREATE TABLE premium_members (member_id INT, is_premium BOOLEAN); INSERT INTO premium_members (member_id, is_premium) VALUES (1, TRUE), (2, TRUE), (3, FALSE);

SELECT AVG(heart_rate) FROM member_heart_rate JOIN premium_members ON member_heart_rate.member_id = premium_members.member_id WHERE is_premium = TRUE;


Question: What is the number of community development initiatives and their success rate, categorized by region and initiative status?

CREATE TABLE initiative (initiative_id INT, initiative_start_date DATE, initiative_end_date DATE, budget FLOAT, region VARCHAR(50), status VARCHAR(50), success BOOLEAN); INSERT INTO initiative (initiative_id, initiative_start_date, initiative_end_date, budget, region, status, success) VALUES (3, '2018-01-01', '2019-12-31', 30000.0, 'R3', 'completed', true), (4, '2020-06-15', '2022-05-30', 80000.0, 'R4', 'in progress', false);

SELECT region, status, COUNT(*) AS num_initiatives, SUM(success) AS num_successful FROM initiative GROUP BY region, status;


Question: What is the total revenue generated by virtual tours in Mexico and Brazil?

CREATE TABLE countries (country_id INT, country TEXT); INSERT INTO countries (country_id, country) VALUES (1, 'Mexico'), (2, 'Brazil'); CREATE TABLE virtual_tours (tour_id INT, country_id INT, views INT, revenue FLOAT); INSERT INTO virtual_tours (tour_id, country_id, views, revenue) VALUES (1, 1, 500, 200.0), (2, 1, 600, 300.0), (3, 2, 700, 400.0), (4, 2, 800, 500.0);

SELECT SUM(revenue) FROM virtual_tours WHERE country_id IN (SELECT country_id FROM countries WHERE country IN ('Mexico', 'Brazil'));


Question: Generate PostgreSQL SQL for: Who were the rowers when notes were sa/b, with a time of 5:51.30?

CREATE TABLE table_name_76 (rowers VARCHAR, notes VARCHAR, time VARCHAR)

SELECT rowers FROM table_name_76 WHERE notes = 'sa/b' AND time = '5:51.30';


Question: How many teachers have completed the 'Critical Pedagogy' course in 2023?

CREATE TABLE Completions (CompletionID INT, StudentID INT, CourseID INT, CompletionDate DATE); INSERT INTO Completions (CompletionID, StudentID, CourseID, CompletionDate) VALUES (1, 1, 1, '2023-01-01'), (2, 2, 2, '2023-01-02'), (3, 3, 1, '2023-01-03'), (4, 5, 2, '2023-01-04'); CREATE TABLE Courses (CourseID INT, CourseName VARCHAR(50), Cost INT, CertificationYear INT, TargetAudience VARCHAR(20)); INSERT INTO Courses (CourseID, CourseName, Cost, CertificationYear, TargetAudience) VALUES (1, 'Critical Pedagogy', 250, 2023, 'Teachers'), (2, 'Data Analysis for Educators', 250, 2023, 'Teachers');

SELECT COUNT(*) FROM Completions INNER JOIN Courses ON Completions.CourseID = Courses.CourseID WHERE Courses.CourseName = 'Critical Pedagogy' AND CertificationYear = 2023 AND TargetAudience = 'Teachers';


Question: What was the total R&D expenditure on drugs approved in 2019?

CREATE TABLE drug_approval (drug_name TEXT, approval_year INTEGER);

SELECT SUM(expenditure) FROM rd_expenditure INNER JOIN drug_approval a ON rd_expenditure.drug_name = a.drug_name WHERE a.approval_year = 2019;


Question: Generate PostgreSQL SQL for: On what date was the surface clay with Cyril Saulnier as the opponent in the final?

CREATE TABLE table_name_28 (date VARCHAR, surface VARCHAR, opponent_in_the_final VARCHAR)

SELECT date FROM table_name_28 WHERE surface = 'clay' AND opponent_in_the_final = 'cyril saulnier';


Question: Show a SQL definition from the timescaledb project (with_telemetry, item 1).

CREATE OR REPLACE FUNCTION @extschema@.get_telemetry_report()
       RETURNS jsonb AS '@MODULE_PATHNAME@', 'ts_telemetry_get_report_jsonb'
       LANGUAGE C STABLE PARALLEL SAFE;

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


Question: Generate PostgreSQL SQL for: Who had a to par of +2 and a score of 78-69-68=215?

CREATE TABLE table_name_22 (player VARCHAR, to_par VARCHAR, score VARCHAR)

SELECT player FROM table_name_22 WHERE to_par = '+2' AND score = 78 - 69 - 68 = 215;


Question: Generate PostgreSQL SQL for: What is the City of license that has a ERP kW more than 4.5 and w23dr-d?

CREATE TABLE table_name_45 (city_of_license VARCHAR, erp_kw VARCHAR, station VARCHAR)

SELECT city_of_license FROM table_name_45 WHERE erp_kw > 4.5 AND station = 'w23dr-d';


Question: What is the minimum and maximum age of players who have participated in esports events?

CREATE TABLE EsportsPlayers (PlayerID INT, Age INT, EventID INT); INSERT INTO EsportsPlayers (PlayerID, Age, EventID) VALUES (1, 22, 1), (2, 25, 2), (3, 28, 3), (4, 30, 4);

SELECT MIN(Age), MAX(Age) FROM EsportsPlayers;


Question: List all climate change projects in India

CREATE TABLE climate_projects (project_id INT PRIMARY KEY, name VARCHAR(255), country VARCHAR(255), budget FLOAT); INSERT INTO climate_projects (project_id, name, country, budget) VALUES (1, 'Solar Power India', 'India', 5000000); INSERT INTO climate_projects (project_id, name, country, budget) VALUES (2, 'Wind Farms India', 'India', 7000000);

SELECT * FROM climate_projects WHERE country = 'India';


Question: Write the DDL statement from PostgreSQL regression test 'conversion' (example 25).

CREATE TABLE utf8_inputs (inbytes bytea, description text);

Explanation: DDL from PostgreSQL core regression test for Conversion.


Question: PL/pgSQL test: Plpgsql Call (example 80).

DO $$
BEGIN
  UPDATE t_test SET x = x + 1;
  RAISE NOTICE 'f_get_x(%)', f_get_x();
  CALL f_print_x(f_get_x());
  UPDATE t_test SET x = x + 1;
  RAISE NOTICE 'f_get_x(%)', f_get_x();
  CALL f_print_x(f_get_x());
END
$$;

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


Question: Generate PostgreSQL SQL for: What is the greatest played with a drawn less than 1 and a position of less than 1?

CREATE TABLE table_name_99 (played INTEGER, drawn VARCHAR, position VARCHAR)

SELECT MAX(played) FROM table_name_99 WHERE drawn < 1 AND position < 1;


Question: Generate PostgreSQL SQL for: Which venue has a week smaller than 2?

CREATE TABLE table_name_29 (venue VARCHAR, week INTEGER)

SELECT venue FROM table_name_29 WHERE week < 2;


Question: Generate PostgreSQL SQL for: When 60 is the tries against what is the tries for?

CREATE TABLE table_17941032_1 (tries_for VARCHAR, tries_against VARCHAR)

SELECT tries_for FROM table_17941032_1 WHERE tries_against = '60';


Question: What is the average budget of SIGINT agencies by region?

CREATE SCHEMA if not exists sigint_budget AUTHORIZATION defsec;CREATE TABLE if not exists sigint_budget.info (id INT, name VARCHAR(100), region VARCHAR(50), budget INT);INSERT INTO sigint_budget.info (id, name, region, budget) VALUES (1, 'NSA', 'US - East', 15000000000);INSERT INTO sigint_budget.info (id, name, region, budget) VALUES (2, 'GCHQ', 'Europe - West', 8000000000);INSERT INTO sigint_budget.info (id, name, region, budget) VALUES (3, 'DGSE', 'Europe - West', 5000000000);

SELECT region, AVG(budget) as avg_budget FROM sigint_budget.info WHERE name LIKE '%SIGINT%' GROUP BY region;


Question: Generate PostgreSQL SQL for: Show the first year and last year of parties with theme "Spring" or "Teqnology".

CREATE TABLE party (First_year VARCHAR, Last_year VARCHAR, Party_Theme VARCHAR)

SELECT First_year, Last_year FROM party WHERE Party_Theme = 'Spring' OR Party_Theme = 'Teqnology';


Question: Generate PostgreSQL SQL for: What is the 2011 number (,000) when the status is separated?

CREATE TABLE table_273617_6 (status VARCHAR)

SELECT 2011 AS _number__, 000 AS _ FROM table_273617_6 WHERE status = 'Separated';


Question: Generate PostgreSQL SQL for: what album is 4:30 long

CREATE TABLE table_name_95 (album VARCHAR, length VARCHAR)

SELECT album FROM table_name_95 WHERE length = '4:30';


Question: Generate PostgreSQL SQL for: what's the championship where winning score is −12 (74-66-65-71=276)

CREATE TABLE table_11570261_1 (championship VARCHAR, winning_score VARCHAR)

SELECT championship FROM table_11570261_1 WHERE winning_score = −12(74 - 66 - 65 - 71 = 276);


Question: Write the DDL statement from PostgreSQL regression test 'constraints' (example 513).

Explanation: DDL from PostgreSQL core regression test for Constraints.


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

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

SELECT count(*) FROM (SELECT regcollation('-')::oid) AS _sub;


Question: What is the average claim amount for health insurance policies, for policyholders over the age of 65?

CREATE TABLE claims (claim_id INT, policy_id INT, claim_amount DECIMAL(10,2)); CREATE TABLE policies (policy_id INT, policy_holder_id INT, policy_type VARCHAR(50), issue_date DATE, policy_holder_dob DATE);

SELECT AVG(claim_amount) FROM claims c JOIN policies p ON c.policy_id = p.policy_id WHERE p.policy_type = 'health' AND DATEDIFF(YEAR, p.policy_holder_dob, GETDATE()) > 65;


Question: Generate PostgreSQL SQL for: Which To par has a Place of t6, and a Player of nick faldo?

CREATE TABLE table_name_56 (to_par VARCHAR, place VARCHAR, player VARCHAR)

SELECT to_par FROM table_name_56 WHERE place = 't6' AND player = 'nick faldo';


Question: Generate PostgreSQL SQL for: Which Title has a Type of album in 1983?

CREATE TABLE table_name_34 (title VARCHAR, type VARCHAR, year VARCHAR)

SELECT title FROM table_name_34 WHERE type = 'album' AND year = 1983;


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

SELECT p1.oid, p1.proname
FROM pg_proc as p1
WHERE proargnames IS NOT NULL AND
    array_length(proargnames,1) < array_length(proargtypes,1);

Explanation: Regression test for Opr Sanity in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT p1.oid, p1.proname
FROM pg_proc as p1
WHERE proargnames IS NOT NULL AND
    array_length(proargnames,1) < array_length(proargtypes,1)) AS _sub;


Question: Generate PostgreSQL SQL for: Which Democratic has a District smaller than 7, and a Republican of dan mansell?

CREATE TABLE table_name_99 (democratic VARCHAR, district VARCHAR, republican VARCHAR)

SELECT democratic FROM table_name_99 WHERE district < 7 AND republican = 'dan mansell';


Question: What is the total number of students and teachers who have ever participated in professional development programs, regardless of completion status, in the education schema?

CREATE SCHEMA education;CREATE TABLE professional_development (id INT, role VARCHAR(10), name VARCHAR(50), completed BOOLEAN);INSERT INTO professional_development (id, role, name, completed) VALUES (1, 'student', 'John Doe', FALSE), (2, 'teacher', 'Jane Smith', TRUE);

SELECT COUNT(*) FROM education.professional_development;


Question: What is the total population of all species in the 'arctic_biodiversity' table?

CREATE TABLE arctic_biodiversity (id INTEGER, species VARCHAR(255), population INTEGER);

SELECT SUM(population) AS total_population FROM arctic_biodiversity;


Question: What are the average temperatures (in Celsius) for all chemical storage facilities in Canada and the United States, grouped by country?

CREATE TABLE storage_facilities (facility_id INT, facility_name TEXT, country TEXT, temperature DECIMAL(5,2)); INSERT INTO storage_facilities (facility_id, facility_name, country, temperature) VALUES (1, 'Facility A', 'Canada', 15.5), (2, 'Facility B', 'Canada', 18.3), (3, 'Facility C', 'USA', 22.1), (4, 'Facility D', 'USA', 20.0);

SELECT country, AVG(temperature) as avg_temperature FROM storage_facilities WHERE country IN ('Canada', 'USA') GROUP BY country;


Question: List the destinations that received less than 10 packages per day on average in October 2021

CREATE TABLE Shipments (id INT, destination VARCHAR(50), packages INT, timestamp DATE); INSERT INTO Shipments (id, destination, packages, timestamp) VALUES (1, 'Kolkata', 5, '2021-10-01'), (2, 'Mumbai', 8, '2021-10-02'), (3, 'Delhi', 3, '2021-10-03'), (4, 'Bangalore', 7, '2021-10-04'), (5, 'Hyderabad', 6, '2021-10-05');

SELECT destination FROM Shipments WHERE (packages/5) < 10 GROUP BY destination HAVING COUNT(DISTINCT timestamp) > 1;


Question: What is the average rating of algorithms 'V' and 'W'?

CREATE TABLE IF NOT EXISTS ai_feedback (algorithm_name TEXT, user_feedback TEXT, rating INTEGER); INSERT INTO ai_feedback (algorithm_name, user_feedback, rating) VALUES ('Algorithm T', 'Feedback 1', 4), ('Algorithm U', 'Feedback 2', 5), ('Algorithm V', 'Feedback 3', 5), ('Algorithm W', 'Feedback 4', 4);

SELECT AVG(rating) as avg_rating FROM ai_feedback WHERE algorithm_name IN ('Algorithm V', 'Algorithm W');


Question: Generate PostgreSQL SQL for: Name the starts for bobby labonte

CREATE TABLE table_27786562_1 (starts VARCHAR, driver VARCHAR)

SELECT starts FROM table_27786562_1 WHERE driver = 'Bobby Labonte';


Question: pgTAP test for Functap (assertion 201).

-- Test diagnostics
SELECT * FROM check_test(
    is_normal_function( 'none', 'whatever' ),
    false,
    'is_normal_function(nofunc, desc)',
    'whatever',
    '    Function "none"() does not exist'
);

Explanation: SQL assertion from pgTAP test suite for Functap.


Question: Generate PostgreSQL SQL for: What was the date of the game that had a loss of Gott (2-7)?

CREATE TABLE table_name_98 (date VARCHAR, loss VARCHAR)

SELECT date FROM table_name_98 WHERE loss = 'gott (2-7)';


Question: Generate PostgreSQL SQL for: What is Party, when Minister is "Franco Frattini"?

CREATE TABLE table_name_55 (party VARCHAR, minister VARCHAR)

SELECT party FROM table_name_55 WHERE minister = 'franco frattini';


Question: pgTAP test for Moretap (assertion 4).

-- Test fail().
\set fail_numb 3
\echo ok :fail_numb - Testing fail()
SELECT is(
    fail('oops'),
    format( E'not ok %1$s - oops\n# Failed test %1$s: "oops"', :fail_numb ),
    'We should get the proper output from fail()'
);

Explanation: SQL assertion from pgTAP test suite for Moretap.


Question: What is the minimum mental health parity score for healthcare providers in New York?

CREATE TABLE healthcare_providers (id INT, name TEXT, mental_health_parity_score INT, state TEXT); INSERT INTO healthcare_providers (id, name, mental_health_parity_score, state) VALUES (1, 'Dr. Jane Smith', 95, 'New York'); INSERT INTO healthcare_providers (id, name, mental_health_parity_score, state) VALUES (2, 'Dr. Maria Garcia', 88, 'Texas'); INSERT INTO healthcare_providers (id, name, mental_health_parity_score, state) VALUES (3, 'Dr. David Kim', 92, 'New York');

SELECT MIN(mental_health_parity_score) FROM healthcare_providers WHERE state = 'New York';


Question: What is the total revenue from broadband services for each region?

CREATE TABLE broadband_services (service_id INT, region VARCHAR(255), revenue DECIMAL(10,2)); INSERT INTO broadband_services (service_id, region, revenue) VALUES (1, 'North', 5000), (2, 'South', 7000);

SELECT region, SUM(revenue) FROM broadband_services GROUP BY region;


Question: Generate PostgreSQL SQL for: What was the result of the April 16 game?

CREATE TABLE table_name_94 (result VARCHAR, date VARCHAR)

SELECT result FROM table_name_94 WHERE date = 'april 16';


Question: Generate PostgreSQL SQL for: What was the challenge for episode 28?

CREATE TABLE table_24798489_2 (challenge VARCHAR, episode_number VARCHAR)

SELECT challenge FROM table_24798489_2 WHERE episode_number = 28;


Question: Generate PostgreSQL SQL for: Which language do 1% of males speak?

CREATE TABLE table_name_31 (percentage___percentage_ VARCHAR, males VARCHAR)

SELECT percentage___percentage_ FROM table_name_31 WHERE males = '1';


Question: What is the total revenue for each artist?

CREATE TABLE ArtSales (SaleID INT, ArtistID INT, Revenue INT); INSERT INTO ArtSales (SaleID, ArtistID, Revenue) VALUES (1, 1, 1000), (2, 1, 2000), (3, 2, 3000), (4, 2, 1500), (5, 3, 2500);

SELECT ArtistID, SUM(Revenue) as TotalRevenue FROM ArtSales GROUP BY ArtistID;


Question: Update the ticket_price for all tickets of the basketball team events by 10%

CREATE TABLE tickets (ticket_id INT, team VARCHAR(50), event_date DATE, ticket_price DECIMAL(5, 2)); INSERT INTO tickets (ticket_id, team, event_date, ticket_price) VALUES (1, 'Basketball', '2022-03-01', 50.00), (2, 'Basketball', '2022-03-15', 75.00);

UPDATE tickets SET ticket_price = ticket_price * 1.10 WHERE team = 'Basketball';


Question: What is the distribution of fair trade coffee beans by country of origin?

CREATE TABLE coffee (id INT, country TEXT, percentage FLOAT); INSERT INTO coffee (id, country, percentage) VALUES (1, 'Brazil', 30.0), (2, 'Colombia', 20.0);


Question: Generate PostgreSQL SQL for: How many points did the Weslake v12 get in 1966?

CREATE TABLE table_name_28 (points INTEGER, engine VARCHAR, year VARCHAR)

SELECT MAX(points) FROM table_name_28 WHERE engine = 'weslake v12' AND year < 1966;


Question: Increase data allowance for customers with network downtime complaints

CREATE TABLE mobile_subscribers (id INT, name VARCHAR(255), data_allowance INT, contract_start DATE); INSERT INTO mobile_subscribers (id, name, data_allowance, contract_start) VALUES (1, 'John Doe', 5000, '2020-01-01'), (2, 'Jane Doe', 3000, '2019-01-01'); CREATE TABLE customer_complaints (id INT, subscriber_id INT, complaint_date DATE, complaint_type VARCHAR(255)); INSERT INTO customer_complaints (id, subscriber_id, complaint_date, complaint_type) VALUES (1, 1, '2020-02-01', 'Network Downtime');

UPDATE mobile_subscribers SET data_allowance = 7000 WHERE id IN (SELECT subscriber_id FROM customer_complaints WHERE complaint_type = 'Network Downtime');


Question: What is the total revenue for each genre in descending order?

CREATE TABLE MusicGenre (GenreID INT, GenreName VARCHAR(50), Revenue DECIMAL(10,2)); INSERT INTO MusicGenre (GenreID, GenreName, Revenue) VALUES (1, 'Pop', 500000.00), (2, 'Rock', 450000.00), (3, 'Jazz', 300000.00), (4, 'Country', 250000.00), (5, 'Blues', 200000.00);

SELECT GenreName, SUM(Revenue) OVER (ORDER BY GenreName DESC ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS TotalRevenue FROM MusicGenre;


Question: Generate PostgreSQL SQL for: Which episode had bbc ranking and canle ranking of n/a?

CREATE TABLE table_24399615_10 (episode_no VARCHAR, bbc_three_weekly_ranking VARCHAR, cable_rank VARCHAR)

SELECT COUNT(episode_no) FROM table_24399615_10 WHERE bbc_three_weekly_ranking = 'N/A' AND cable_rank = 'N/A';


Question: PostgreSQL Queries: show example 53.

WITH t AS ( DELETE FROM foo ) DELETE FROM bar;

Explanation: Example from PostgreSQL documentation on Queries.


Question: What is the total installed capacity of wind farms in Germany?

CREATE TABLE wind_farms (id INT, name TEXT, country TEXT, capacity FLOAT); INSERT INTO wind_farms (id, name, country, capacity) VALUES (1, 'Windpark Nordsee', 'Germany', 330.0), (2, 'Bard Offshore 1', 'Germany', 400.0);

SELECT SUM(capacity) FROM wind_farms WHERE country = 'Germany';


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

$$ language plpgsql;

create function stacked_diagnostics_test() returns void as $$
declare _sqlstate text;

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


Question: What is the number of students who have taken each open pedagogy course?

CREATE TABLE open_pedagogy_courses (course_id INT, course_name VARCHAR(255), student_count INT); INSERT INTO open_pedagogy_courses (course_id, course_name, student_count) VALUES (1001, 'Open Course 1', 50), (1002, 'Open Course 2', 75), (1003, 'Open Course 3', 100), (1004, 'Open Course 4', 125), (1005, 'Open Course 5', 150);

SELECT course_name, student_count FROM open_pedagogy_courses;


Question: What is the total number of products in the 'sustainable_products' table that are certified by the 'certified_products' table?

CREATE TABLE sustainable_products (product_id INT, category VARCHAR(255), price DECIMAL(10,2), recycled BOOLEAN, certified_by INT);CREATE TABLE certified_products (certification_id INT, name VARCHAR(255));

SELECT COUNT(*) FROM sustainable_products WHERE certified_by IS NOT NULL;


Question: Generate PostgreSQL SQL for: How many poles were there in 1996?

CREATE TABLE table_2182573_2 (poles INTEGER, year VARCHAR)

SELECT MIN(poles) FROM table_2182573_2 WHERE year = 1996;


Question: Generate PostgreSQL SQL for: What is the black caribbean population when the black African population is less than 10552.0?

CREATE TABLE table_19149550_7 (black_caribbean_population INTEGER, black_african_population INTEGER)

SELECT MIN(black_caribbean_population) FROM table_19149550_7 WHERE black_african_population < 10552.0;


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

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

SELECT count(*) FROM (SELECT random('NaN'::numeric, 10)) AS _sub;


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

SELECT * FROM test_timestamp WHERE i>'2004-10-27'::date ORDER BY i;

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


Question: What is the total amount of food assistance provided to refugees?

CREATE TABLE refugees (id INT, camp_id INT, food_assistance_given BOOLEAN); INSERT INTO refugees (id, camp_id, food_assistance_given) VALUES (1, 1001, TRUE), (2, 1001, FALSE), (3, 1002, TRUE); CREATE TABLE food_assistance (id INT, camp_id INT, amount FLOAT); INSERT INTO food_assistance (id, camp_id, amount) VALUES (1001, 1001, 500), (1002, 1001, 700), (1003, 1002, 900);

SELECT SUM(amount) FROM food_assistance fa JOIN refugees r ON fa.camp_id = r.camp_id WHERE r.food_assistance_given = TRUE;


Question: What's the total budget for programs in education and healthcare?

CREATE TABLE Programs (ProgramID INT, ProgramName TEXT, Budget DECIMAL(10,2), Category TEXT); INSERT INTO Programs (ProgramID, ProgramName, Budget, Category) VALUES (1, 'Healthcare 101', 10000.00, 'Healthcare');

SELECT SUM(Budget) FROM Programs WHERE Category IN ('Education', 'Healthcare');


Question: Determine the average number of posts per day for the 'social_media' database.

SELECT AVG(num_posts_per_day) FROM (SELECT user_id, COUNT(*) / COUNT(DISTINCT post_date) AS num_posts_per_day FROM posts GROUP BY user_id) AS subquery;


Question: Generate PostgreSQL SQL for: In which yearly change was there a capacity of 78.4% and a rank smaller than 3?

CREATE TABLE table_name_31 (annual_change VARCHAR, rank VARCHAR, capacity_in_use VARCHAR)

SELECT annual_change FROM table_name_31 WHERE rank < 3 AND capacity_in_use = '78.4%';


Question: Delete all records in the "waste_management" table where the "waste_type" is 'Toxic'

CREATE TABLE waste_management (waste_id INT PRIMARY KEY, waste_type VARCHAR(20)); INSERT INTO waste_management (waste_id, waste_type) VALUES (1, 'Non-Toxic'), (2, 'Toxic'), (3, 'Non-Toxic');

DELETE FROM waste_management WHERE waste_type = 'Toxic';


Question: Generate PostgreSQL SQL for: What hometown is Kyle love from?

CREATE TABLE table_name_47 (hometown VARCHAR, name VARCHAR)

SELECT hometown FROM table_name_47 WHERE name = 'kyle love';


Question: Generate PostgreSQL SQL for: What is the birth date of the woman who ceased to be Queen on 18 Jun 1297?

CREATE TABLE table_name_47 (birth VARCHAR, ceased_to_be_queen VARCHAR)

SELECT birth FROM table_name_47 WHERE ceased_to_be_queen = '18 jun 1297';


Question: Generate PostgreSQL SQL for: What was the average finish in 2007?

CREATE TABLE table_2182573_2 (avg_finish VARCHAR, year VARCHAR)

SELECT avg_finish FROM table_2182573_2 WHERE year = 2007;


Question: Generate PostgreSQL SQL for: What was the sum of the rounds for the player who had a position of LS and an overall draft pick bigger than 230?

CREATE TABLE table_name_10 (round INTEGER, position VARCHAR, overall VARCHAR)

SELECT SUM(round) FROM table_name_10 WHERE position = 'ls' AND overall > 230;


Question: Which ocean has the most maritime safety incidents?

CREATE TABLE incidents (location varchar(255), date date); INSERT INTO incidents (location, date) VALUES ('Pacific Ocean', '2021-08-23'), ('Atlantic Ocean', '2022-02-12'), ('Indian Ocean', '2021-11-18');

SELECT location, COUNT(*) FROM incidents GROUP BY location ORDER BY COUNT(*) DESC LIMIT 1;


Question: Generate PostgreSQL SQL for: In what order were the Bee Gees as the artist when it was a result of bottom 3?

CREATE TABLE table_name_30 (order__number VARCHAR, result VARCHAR, original_artist VARCHAR)

SELECT order__number FROM table_name_30 WHERE result = 'bottom 3' AND original_artist = 'bee gees';


Question: Generate PostgreSQL SQL for: Which Major League Soccer team for the 2005 season has the lowest goals?

CREATE TABLE table_name_63 (goals INTEGER, league VARCHAR, season VARCHAR)

SELECT MIN(goals) FROM table_name_63 WHERE league = 'major league soccer' AND season = '2005';


Question: Generate PostgreSQL SQL for: What date was the game at Comiskey Park and had a 4th Inning?

CREATE TABLE table_name_47 (date VARCHAR, location VARCHAR, inning VARCHAR)

SELECT date FROM table_name_47 WHERE location = 'comiskey park' AND inning = '4th';


Question: What is the minimum production time for fair trade products in South America?

CREATE TABLE fair_trade_products (id INT, product VARCHAR(255), south_american_country VARCHAR(255), production_time INT); INSERT INTO fair_trade_products VALUES (1, 'Reusable Tote Bag', 'Brazil', 30), (2, 'Fair Trade Coffee', 'Colombia', 20), (3, 'Handmade Jewelry', 'Peru', 45), (4, 'Organic Cotton T-Shirt', 'Brazil', 60);

SELECT MIN(production_time) FROM fair_trade_products WHERE south_american_country IN ('Brazil', 'Colombia', 'Peru');


Question: What is the total fuel consumption of each ship type in the fleet?

CREATE TABLE fleet (id INT, name VARCHAR(50), type VARCHAR(50), fuel_capacity INT); CREATE TABLE fuel_consumption (id INT, ship_id INT, fuel_consumption INT, consumption_date DATE); INSERT INTO fleet VALUES (1, 'Ship 1', 'Cargo', 10000); INSERT INTO fleet VALUES (2, 'Ship 2', 'Passenger', 12000); INSERT INTO fuel_consumption VALUES (1, 1, 500, '2022-01-01'); INSERT INTO fuel_consumption VALUES (2, 2, 600, '2022-01-15'); INSERT INTO fuel_consumption VALUES (3, 1, 550, '2022-02-01');

SELECT fleet.type, SUM(fuel_consumption.fuel_consumption) FROM fleet INNER JOIN fuel_consumption ON fleet.id = fuel_consumption.ship_id GROUP BY fleet.type;


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

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


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

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


Question: What is the maximum salary of construction workers in each occupation?

CREATE TABLE construction_workers (worker_id INT, occupation VARCHAR(50), state VARCHAR(50), salary INT); INSERT INTO construction_workers (worker_id, occupation, state, salary) VALUES (1, 'Carpenter', 'California', 60000); INSERT INTO construction_workers (worker_id, occupation, state, salary) VALUES (2, 'Electrician', 'California', 70000);

SELECT occupation, MAX(salary) FROM construction_workers GROUP BY occupation;


Question: Show the names of startups that have 'diverse' teams.

CREATE TABLE diversity (id INT, startup_name VARCHAR(50), team_diversity VARCHAR(10));

SELECT startup_name FROM diversity WHERE team_diversity = 'diverse';


Question: Generate PostgreSQL SQL for: List the id and type of each thing, and the details of the organization that owns it.

CREATE TABLE Organizations (organization_details VARCHAR, organization_id VARCHAR); CREATE TABLE Things (thing_id VARCHAR, type_of_Thing_Code VARCHAR, organization_id VARCHAR)

SELECT T1.thing_id, T1.type_of_Thing_Code, T2.organization_details FROM Things AS T1 JOIN Organizations AS T2 ON T1.organization_id = T2.organization_id;


Question: Write the DML statement from PostgreSQL regression test 'transactions' (example 120).

Explanation: DML from PostgreSQL core regression test for Transactions.


Question: Generate PostgreSQL SQL for: What's the Backed after 2008 with a label of Wild World?

CREATE TABLE table_name_24 (backed_with VARCHAR, record_label VARCHAR, date VARCHAR)

SELECT backed_with FROM table_name_24 WHERE record_label = 'wild world' AND date > 2008;


Question: List all AI ethics principles related to data privacy and security.

CREATE TABLE AI_Ethics (principle_id INT, principle_name VARCHAR(50), category VARCHAR(20)); INSERT INTO AI_Ethics (principle_id, principle_name, category) VALUES (1, 'Fairness', 'General'), (2, 'Accountability', 'General'), (3, 'Transparency', 'General'), (4, 'Data Privacy', 'Data'), (5, 'Data Security', 'Data');

SELECT principle_name FROM AI_Ethics WHERE category = 'Data';


Question: Find the minimum sustainable material usage in garments produced in Asia.

CREATE TABLE garment_production_asia (id INT, material_percentage DECIMAL, region VARCHAR(20)); INSERT INTO garment_production_asia (id, material_percentage, region) VALUES (1, 75.00, 'Asia'), (2, 80.00, 'Asia'), (3, 78.00, 'Asia');

SELECT MIN(material_percentage) FROM garment_production_asia WHERE region = 'Asia';


Question: Generate PostgreSQL SQL for: Find the name of the products that have the color description "red" and have the characteristic name "fast".

CREATE TABLE CHARACTERISTICS (characteristic_id VARCHAR, characteristic_name VARCHAR); CREATE TABLE ref_colors (color_code VARCHAR, color_description VARCHAR); CREATE TABLE products (product_id VARCHAR, color_code VARCHAR); CREATE TABLE product_characteristics (product_id VARCHAR, characteristic_id VARCHAR)

SELECT product_name FROM products AS t1 JOIN product_characteristics AS t2 ON t1.product_id = t2.product_id JOIN CHARACTERISTICS AS t3 ON t2.characteristic_id = t3.characteristic_id JOIN ref_colors AS t4 ON t1.color_code = t4.color_code WHERE t4.color_description = 'red' AND t3.characteristic_name = 'fast';


Question: Generate PostgreSQL SQL for: What are the High points for Team @ portland?

CREATE TABLE table_name_75 (high_points VARCHAR, team VARCHAR)

SELECT high_points FROM table_name_75 WHERE team = '@ portland';


Question: PostgreSQL regression test 'collate.icu.utf8': Write the SELECT query (example 81).

SELECT a, b, greatest(b, 'CCC') FROM collate_test1 ORDER BY 3;

Explanation: Regression test for Collate.Icu.Utf8 in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT a, b, greatest(b, 'CCC') FROM collate_test1 ORDER BY 3) AS _sub;


Question: Generate PostgreSQL SQL for: What is the May 7 finalist?

CREATE TABLE table_name_14 (finalist VARCHAR, week VARCHAR)

SELECT finalist FROM table_name_14 WHERE week = 'may 7';


Question: Generate PostgreSQL SQL for: Which player had a to par score larger than 7 and a total score of 298?

CREATE TABLE table_name_5 (player VARCHAR, to_par VARCHAR, total VARCHAR)

SELECT player FROM table_name_5 WHERE to_par > 7 AND total = 298;


Question: Generate PostgreSQL SQL for: What is the highest number of games with 1 loss and points less than 18?

CREATE TABLE table_name_9 (games INTEGER, lost VARCHAR, points VARCHAR)

SELECT MAX(games) FROM table_name_9 WHERE lost = 1 AND points < 18;


Question: Find all brands that use ingredients from 'Brazil' and have a safety record after 2021-01-01

CREATE TABLE ingredient (product_id INT, ingredient TEXT, origin TEXT);

SELECT DISTINCT brand FROM ingredient INNER JOIN safety_record ON ingredient.product_id = safety_record.product_id WHERE origin = 'Brazil' AND report_date > '2021-01-01';


Question: What is the total production output for all factories in France?

CREATE TABLE factory (id INT, name TEXT, sector TEXT, country TEXT); INSERT INTO factory (id, name, sector, country) VALUES (1, 'FactoryA', 'automotive', 'France'), (2, 'FactoryB', 'aerospace', 'France'), (3, 'FactoryC', 'electronics', 'Germany'); CREATE TABLE production (factory_id INT, output REAL); INSERT INTO production (factory_id, output) VALUES (1, 1000), (1, 1200), (2, 1500), (3, 1800);

SELECT SUM(production.output) FROM production INNER JOIN factory ON production.factory_id = factory.id WHERE factory.country = 'France';


Question: Generate PostgreSQL SQL for: Who was the Class C winner in round 8?

CREATE TABLE table_24852622_1 (class_c_winner VARCHAR, round VARCHAR)

SELECT class_c_winner FROM table_24852622_1 WHERE round = '8';


Question: Generate PostgreSQL SQL for: Which date  has a Week smaller than 14, and an Opponent of san francisco 49ers?

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

SELECT date FROM table_name_92 WHERE week < 14 AND opponent = 'san francisco 49ers';


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

SELECT jsonb_exists_any('{"a":null, "b":"qq"}', ARRAY['c','a']);

SELECT count(*) FROM (SELECT jsonb_exists_any('{"a":null, "b":"qq"}', ARRAY['c','a'])) AS _sub;


Question: Generate PostgreSQL SQL for: Name the total water resources m3 for rainfall being 650

CREATE TABLE table_22854436_1 (per_capita_average_annual_renewable_water_resources_m_3 VARCHAR, average_annual_rainfall__mm_ VARCHAR)

SELECT COUNT(per_capita_average_annual_renewable_water_resources_m_3) FROM table_22854436_1 WHERE average_annual_rainfall__mm_ = '650';


Question: Show the national security events with their corresponding severity levels, and calculate the average severity level.

CREATE TABLE national_security_events (id INT, event VARCHAR, severity INT); INSERT INTO national_security_events (id, event, severity) VALUES (1, 'Terrorist Attack', 8), (2, 'Cyber Espionage', 5), (3, 'Nuclear Missile Test', 10);

SELECT event, severity, AVG(severity) OVER () as avg_severity FROM national_security_events;


Question: Update the gender of the founder for a specific company.

CREATE TABLE companies (id INT, name TEXT, founded_date DATE, founder_gender TEXT); INSERT INTO companies (id, name, founded_date, founder_gender) VALUES (1, 'Acme Inc', '2010-01-01', 'male'); INSERT INTO companies (id, name, founded_date, founder_gender) VALUES (2, 'Beta Corp', '2015-05-15', 'male');

UPDATE companies SET founder_gender = 'female' WHERE id = 1;


Question: List the names and ethnicities of all journalists in the 'reporting' department

CREATE TABLE journalists (id INT PRIMARY KEY, name VARCHAR(255), department VARCHAR(255), ethnicity VARCHAR(255)); INSERT INTO journalists (id, name, department, ethnicity) VALUES (1, 'Sanaa Ahmed', 'reporting', 'Pakistani'), (2, 'José Rodriguez', 'reporting', 'Mexican'), (3, 'Emma Thompson', 'editing', 'British'), (4, 'Mohammed Ali', 'photography', 'Egyptian');

SELECT name, ethnicity FROM journalists WHERE department = 'reporting';


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

select interval '-9223372036854775808 microseconds -0.01 months';

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

SELECT count(*) FROM (select interval '-9223372036854775808 microseconds -0.01 months') AS _sub;


Question: Display the number of construction workers who have worked on projects in each city, sorted alphabetically by city name.

CREATE TABLE construction_workers (worker_id INT, name TEXT); CREATE TABLE project_locations (project_id INT, city TEXT, state TEXT); CREATE TABLE worker_projects (worker_id INT, project_id INT); INSERT INTO construction_workers (worker_id, name) VALUES (1, 'John Doe'), (2, 'Jane Smith'), (3, 'Maria Garcia'), (4, 'Ahmed Patel'); INSERT INTO project_locations (project_id, city, state) VALUES (1, 'New York City', 'New York'), (2, 'Houston', 'Texas'), (3, 'Los Angeles', 'California'), (4, 'New York City', 'New York'); INSERT INTO worker_projects (worker_id, project_id) VALUES (1, 1), (1, 2), (2, 2), (3, 1), (3, 3), (4, 1), (4, 4);

SELECT project_locations.city, COUNT(DISTINCT worker_projects.worker_id) FROM worker_projects INNER JOIN project_locations ON worker_projects.project_id = project_locations.project_id GROUP BY project_locations.city ORDER BY project_locations.city ASC;


Question: How many hotels in 'Tokyo' have adopted AI chatbots?

CREATE TABLE hotels (hotel_id INT, name TEXT, city TEXT, ai_chatbot BOOLEAN);

SELECT city, COUNT(*) as num_hotels FROM hotels WHERE city = 'Tokyo' AND ai_chatbot = TRUE GROUP BY city;


Question: What is the average funding amount received by startups founded by women in the healthcare industry?

CREATE TABLE company (id INT, name TEXT, industry TEXT, founder_gender TEXT); INSERT INTO company (id, name, industry, founder_gender) VALUES (1, 'MedHealth', 'Healthcare', 'Female'); INSERT INTO company (id, name, industry, founder_gender) VALUES (2, 'TechBio', 'Biotechnology', 'Male');

SELECT AVG(funding_amount) FROM funding INNER JOIN company ON funding.company_id = company.id WHERE company.founder_gender = 'Female' AND company.industry = 'Healthcare';


Question: What is the total landfill capacity for each region in the country of Canada?

CREATE TABLE regions (id INT, name VARCHAR(255), country VARCHAR(255)); INSERT INTO regions (id, name, country) VALUES (1, 'Ontario', 'Canada'), (2, 'Quebec', 'Canada'), (3, 'British Columbia', 'Canada'); CREATE TABLE landfill_capacity (region_id INT, capacity INT); INSERT INTO landfill_capacity (region_id, capacity) VALUES (1, 1000000), (1, 1200000), (2, 800000), (3, 1500000);

SELECT r.name as region, SUM(lc.capacity) as total_capacity FROM regions r JOIN landfill_capacity lc ON r.id = lc.region_id WHERE r.country = 'Canada' GROUP BY r.name;


Question: Determine the average ocean acidification level in the Arctic Ocean.

CREATE TABLE ocean_acidification_arctic (location VARCHAR(255), level FLOAT); INSERT INTO ocean_acidification_arctic (location, level) VALUES ('Arctic Ocean', 8.15);

SELECT AVG(level) FROM ocean_acidification_arctic WHERE location = 'Arctic Ocean';


Question: What is the total duration of all films in the 'foreign' category?

CREATE TABLE films (id INT, title TEXT, category TEXT, duration INT); INSERT INTO films (id, title, category, duration) VALUES (1, 'Film 1', 'foreign', 120), (2, 'Film 2', 'domestic', 90), (3, 'Film 3', 'foreign', 180);

SELECT SUM(duration) FROM films WHERE category = 'foreign';


Question: Generate PostgreSQL SQL for: What was the loss of the game attended by 29,704?

CREATE TABLE table_name_21 (loss VARCHAR, attendance VARCHAR)

SELECT loss FROM table_name_21 WHERE attendance = '29,704';


Question: Generate PostgreSQL SQL for: What was the total number for the Bulls when they were at Old Trafford?

CREATE TABLE table_name_27 (bulls VARCHAR, venue VARCHAR)

SELECT COUNT(bulls) FROM table_name_27 WHERE venue = 'old trafford';


Question: What is the average carbon price in the EU and USA?

CREATE TABLE carbon_pricing (country VARCHAR(20), carbon_price DECIMAL(5,2)); INSERT INTO carbon_pricing (country, carbon_price) VALUES ('Germany', 25.00), ('France', 32.00), ('USA', 12.00), ('UK', 28.00), ('Italy', 22.00);

SELECT AVG(carbon_price) FROM carbon_pricing WHERE country IN ('EU', 'USA');


Question: Generate PostgreSQL SQL for: What is the broadcast are for channel 1?

CREATE TABLE table_2638104_1 (broadcast_area VARCHAR, channel VARCHAR)

SELECT broadcast_area FROM table_2638104_1 WHERE channel = 1;


Question: Present founders who identify as LGBTQ+.

CREATE TABLE lgbtq_founders (company_id INT, founder_id INT, founder_lgbtq BOOLEAN); INSERT INTO lgbtq_founders (company_id, founder_id, founder_lgbtq) VALUES (1, 1, FALSE), (1, 2, TRUE), (2, 1, FALSE), (3, 1, FALSE);

SELECT company_id, founder_id FROM lgbtq_founders WHERE founder_lgbtq = TRUE;


Question: pgTAP test for Policy (assertion 19).

/****************************************************************************/
-- Test policies_are().
SELECT * FROM check_test(
    policies_are( 'public', 'passwd', ARRAY['root_all', 'all_view', 'user_mod', 'daemon_insert', 'daemon_delete'], 'whatever' ),
    true,
    'policies_are(schema, table, policies, desc)',
    'whatever',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Policy.


Question: Generate PostgreSQL SQL for: Which song has a Picturization of Vijay?

CREATE TABLE table_name_86 (song VARCHAR, picturization VARCHAR)

SELECT song FROM table_name_86 WHERE picturization = 'vijay';


Question: What is the total number of pollution control initiatives in the 'Pollution' schema from 2018 to 2021?

CREATE SCHEMA Pollution; CREATE TABLE Initiatives (initiative_id INT, year INT); INSERT INTO Initiatives (initiative_id, year) VALUES (1, 2018), (2, 2019), (3, 2020), (4, 2021), (5, 2022);

SELECT COUNT(*) FROM Pollution.Initiatives WHERE year BETWEEN 2018 AND 2021;


Question: Generate PostgreSQL SQL for: Can you tell me the average Total that has the To par of 15?

CREATE TABLE table_name_36 (total INTEGER, to_par VARCHAR)

SELECT AVG(total) FROM table_name_36 WHERE to_par = 15;


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

ALTER EXTENSION pgtap ADD FUNCTION set_hasnt( TEXT, TEXT );

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


Question: Generate PostgreSQL SQL for: What is the low week from october 15, 1961?

CREATE TABLE table_name_82 (week INTEGER, date VARCHAR)

SELECT MIN(week) FROM table_name_82 WHERE date = 'october 15, 1961';


Question: Determine the number of customers who exclusively purchase sustainable clothing.

CREATE TABLE Customers (CustomerID INT, PurchaseHistory VARCHAR(255)); INSERT INTO Customers (CustomerID, PurchaseHistory) VALUES (1, 'Organic Cotton T-Shirt, Recycled Polyester Leggings'), (2, 'Bamboo Blouse, Conventional Cotton Jeans'), (3, 'Tencel Skirt'), (4, 'Recycled Nylon Jacket'), (5, 'Viscose Dress');

SELECT COUNT(*) FROM Customers WHERE PurchaseHistory NOT LIKE '%Conventional Cotton%' AND PurchaseHistory NOT LIKE '%Viscose%';


Question: How many wheelchair accessible taxis are available in the fleet?

CREATE TABLE taxis (id INT, type VARCHAR(10), capacity INT, accessible BOOLEAN); INSERT INTO taxis (id, type, capacity, accessible) VALUES (1, 'Sedan', 4, FALSE), (2, 'SUV', 6, FALSE), (3, 'Wheelchair', 4, TRUE);

SELECT COUNT(*) FROM taxis WHERE type = 'Wheelchair' AND accessible = TRUE;


Question: Generate PostgreSQL SQL for: Who was placed third in 2001?

CREATE TABLE table_17632217_2 (third_place VARCHAR, season VARCHAR)

SELECT third_place FROM table_17632217_2 WHERE season = 2001;


Question: Generate PostgreSQL SQL for: Name the play for 1976

CREATE TABLE table_name_20 (play VARCHAR, year VARCHAR)

SELECT play FROM table_name_20 WHERE year = 1976;


Question: Find the average sustainability score of products supplied by companies in 'China' and 'Japan'?

CREATE TABLE suppliers (id INT PRIMARY KEY, name VARCHAR(255), country VARCHAR(255), sustainability_score INT); INSERT INTO suppliers (id, name, country, sustainability_score) VALUES (1, 'Supplier A', 'China', 80), (2, 'Supplier B', 'Japan', 85), (3, 'Supplier C', 'China', 90), (4, 'Supplier D', 'Japan', 95); CREATE TABLE products (id INT PRIMARY KEY, name VARCHAR(255), supplier_id INT, sustainability_score INT, FOREIGN KEY (supplier_id) REFERENCES suppliers(id)); INSERT INTO products (id, name, supplier_id, sustainability_score) VALUES (1, 'Product A', 1, 85), (2, 'Product B', 2, 88), (3, 'Product C', 3, 92), (4, 'Product D', 4, 96);

SELECT AVG(p.sustainability_score) FROM products p INNER JOIN suppliers s ON p.supplier_id = s.id WHERE s.country IN ('China', 'Japan');


Question: List all protected forests located in 'South America' with an area smaller than 600.

CREATE TABLE protected_forests_2 (id INT, name VARCHAR(50), area FLOAT, region VARCHAR(50)); INSERT INTO protected_forests_2 (id, name, area, region) VALUES (1, 'Sierra Forest', 550.0, 'South America'), (2, 'Rainforest Reserve', 700.0, 'South America');

SELECT name FROM protected_forests_2 WHERE area < 600 AND region = 'South America';


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

SELECT data FROM pg_logical_slot_get_changes('regression_slot2', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1');

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


Question: Generate PostgreSQL SQL for: What are the ends for the player with a transfer fee of loan?

CREATE TABLE table_name_33 (ends VARCHAR, transfer_fee VARCHAR)

SELECT ends FROM table_name_33 WHERE transfer_fee = 'loan';


Question: Generate PostgreSQL SQL for: What is the junior type with an intake of 60 and a DCSF number less than 3386 with the smallest Ofsted number?

CREATE TABLE table_name_62 (ofsted_number INTEGER, dcsf_number VARCHAR, intake VARCHAR, type VARCHAR)

SELECT MIN(ofsted_number) FROM table_name_62 WHERE intake = 60 AND type = 'junior' AND dcsf_number < 3386;


Question: Find the average age of players who play games with the 'Racing' genre

CREATE TABLE PlayerDemographics (PlayerID INT, Game VARCHAR(20), Age INT); INSERT INTO PlayerDemographics (PlayerID, Game, Age) VALUES (1, 'Need for Speed', 28), (2, 'F1 2020', 32), (3, 'Mario Kart 8', 18), (4, 'Gran Turismo Sport', 35);

SELECT AVG(Age) FROM (SELECT Age FROM PlayerDemographics WHERE Game IN (SELECT Game FROM GameDesignData WHERE Genre = 'Racing')) AS Subquery;


Question: What is the distribution of financial literacy scores for customers in Texas?

CREATE TABLE customers (customer_id INT, name VARCHAR(255), state VARCHAR(255), financial_literacy_score INT);

SELECT state, COUNT(*) as count, MIN(financial_literacy_score) as min_score, AVG(financial_literacy_score) as avg_score, MAX(financial_literacy_score) as max_score FROM customers WHERE state = 'Texas' GROUP BY state;


Question: PostgreSQL regression test 'predicate': Write the SELECT query (example 112).

SELECT id FROM dist_tab WHERE (val_null, val_null) IS NOT DISTINCT FROM NULL::RECORD;

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

SELECT count(*) FROM (SELECT id FROM dist_tab WHERE (val_null, val_null) IS NOT DISTINCT FROM NULL::RECORD) AS _sub;


Question: What is the maximum capacity of Wind Farms in Germany?

CREATE TABLE Wind_Farms (project_id INT, location VARCHAR(50), capacity FLOAT); INSERT INTO Wind_Farms (project_id, location, capacity) VALUES (1, 'Germany', 120.5), (2, 'France', 95.3), (3, 'Germany', 152.8), (4, 'Spain', 119.9);

SELECT MAX(capacity) FROM Wind_Farms WHERE location = 'Germany';


Question: Generate PostgreSQL SQL for: How many assists does cam long average in under 132 games?

CREATE TABLE table_name_28 (ast_avg INTEGER, player VARCHAR, games VARCHAR)

SELECT MAX(ast_avg) FROM table_name_28 WHERE player = 'cam long' AND games < 132;


Question: How many policies were issued in the last quarter in New York?

CREATE TABLE policies (id INT, policyholder_id INT, policy_type TEXT, issue_date DATE, expiry_date DATE); INSERT INTO policies (id, policyholder_id, policy_type, issue_date, expiry_date) VALUES (1, 3, 'Life', '2021-01-01', '2022-01-01'), (2, 4, 'Health', '2021-02-01', '2022-02-01'), (3, 5, 'Auto', '2021-03-01', '2022-03-01');

SELECT COUNT(policies.id) FROM policies WHERE policies.issue_date >= '2021-04-01' AND policies.issue_date < '2021-07-01' AND policies.state = 'New York';


Question: What is the total production for wells in the 'offshore' region in 2020?

CREATE TABLE wells (well_id INT, well_name VARCHAR(50), region VARCHAR(20), production FLOAT, year INT); INSERT INTO wells (well_id, well_name, region, production, year) VALUES (1, 'Well A', 'onshore', 100.0, 2019); INSERT INTO wells (well_id, well_name, region, production, year) VALUES (2, 'Well B', 'offshore', 200.0, 2020); INSERT INTO wells (well_id, well_name, region, production, year) VALUES (3, 'Well C', 'onshore', 150.0, 2021);

SELECT SUM(production) FROM wells WHERE region = 'offshore' AND year = 2020;


Question: Generate PostgreSQL SQL for: What is Race 1, when Race 4 is 1?

CREATE TABLE table_name_85 (race_1 VARCHAR, race_4 VARCHAR)

SELECT race_1 FROM table_name_85 WHERE race_4 = '1';


Question: Generate PostgreSQL SQL for: What is the average rank of Elise Matthysen in lanes under 8?

CREATE TABLE table_name_46 (rank INTEGER, name VARCHAR, lane VARCHAR)

SELECT AVG(rank) FROM table_name_46 WHERE name = 'elise matthysen' AND lane < 8;


Question: PL/pgSQL test: Plpython Subtransaction (example 13).

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


Question: Delete all records with an employment date before '2020-01-01' from the 'veteran_employment' table

CREATE TABLE veteran_employment (veteran_id INT, sector VARCHAR(255), employment_date DATE); INSERT INTO veteran_employment (veteran_id, sector, employment_date) VALUES (1, 'IT', '2020-01-01'), (2, 'Healthcare', '2019-06-15'), (3, 'Finance', '2018-09-30'), (4, 'Manufacturing', '2021-04-01'), (5, 'Education', '2020-12-15');

DELETE FROM veteran_employment WHERE employment_date < '2020-01-01';


Question: Generate PostgreSQL SQL for: How many top-25s are associated with more than 91 events?

CREATE TABLE table_name_24 (top_25 INTEGER, events INTEGER)

SELECT SUM(top_25) FROM table_name_24 WHERE events > 91;


Question: What was the total revenue generated by events with more than 150 attendees, sorted by event name?

CREATE TABLE Events (EventID int, EventName varchar(50), Attendance int, TicketPrice numeric); INSERT INTO Events VALUES (1, 'Dance Recital', 200, 30), (2, 'Poetry Slam', 100, 40), (3, 'Art Exhibit', 250, 50);

SELECT SUM(Attendance * TicketPrice) AS TotalRevenue FROM Events WHERE Attendance > 150 GROUP BY EventName ORDER BY EventName;


Question: Find the average severity of vulnerabilities for each asset in the 'vulnerabilities' and 'assets' tables

CREATE TABLE assets (asset_id INT PRIMARY KEY, asset_name VARCHAR(255)); INSERT INTO assets (asset_id, asset_name) VALUES (1, 'Printer01'), (2, 'Workstation02'); CREATE TABLE vulnerabilities (vulnerability_id INT PRIMARY KEY, asset_id INT, vulnerability_severity INT); INSERT INTO vulnerabilities (vulnerability_id, asset_id, vulnerability_severity) VALUES (1, 1, 5), (2, 1, 6), (3, 2, 8), (4, 2, 9);

SELECT a.asset_name, AVG(v.vulnerability_severity) as avg_severity FROM assets a INNER JOIN vulnerabilities v ON a.asset_id = v.asset_id GROUP BY a.asset_name;


Question: How many destinations are there for each type of tourism?

CREATE TABLE destinations (destination_id INT, name TEXT, type TEXT); INSERT INTO destinations (destination_id, name, type) VALUES (1, 'Parksville', 'Eco-friendly'), (2, 'Tofino', 'Eco-friendly'), (3, 'Vancouver', 'Urban'), (4, 'Whistler', 'Ski'), (5, 'Banff', 'Sustainable'), (6, 'Jasper', 'Sustainable');

SELECT type, COUNT(*) FROM destinations GROUP BY type;


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

SELECT JSON('{"a": 1, "a": 2}' WITHOUT UNIQUE KEYS);

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

SELECT count(*) FROM (SELECT JSON('{"a": 1, "a": 2}' WITHOUT UNIQUE KEYS)) AS _sub;


Question: What is the total production cost and revenue for each indigenous food system in the "indigenous_food_systems" and "expenses" tables?

CREATE TABLE indigenous_food_systems (id INT, food_system_name VARCHAR(50), revenue INT); CREATE TABLE expenses (id INT, food_system_id INT, cost INT);

SELECT indigenous_food_systems.food_system_name, SUM(expenses.cost) AS total_cost, SUM(indigenous_food_systems.revenue) AS total_revenue FROM indigenous_food_systems INNER JOIN expenses ON indigenous_food_systems.id = expenses.food_system_id GROUP BY indigenous_food_systems.food_system_name;


Question: Show a SQL definition from the timescaledb project (sql_query, item 6).

--test integer partition key
CREATE TABLE "int_part"(time timestamp, object_id int, temp float);

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


Question: Generate PostgreSQL SQL for: Who played defensive when the rookie Craig Point was playing during week 6?

CREATE TABLE table_name_97 (defensive VARCHAR, rookie VARCHAR, week VARCHAR)

SELECT defensive FROM table_name_97 WHERE rookie = 'craig point' AND week = 6;


Question: List all electric vehicle charging stations in the state of New York, along with their locations.

CREATE TABLE ev_charging_stations (id INT, station_name VARCHAR(50), state VARCHAR(50), location VARCHAR(50)); INSERT INTO ev_charging_stations (id, station_name, state, location) VALUES (1, 'New York City EV Charging', 'New York', 'Manhattan');

SELECT station_name, location FROM ev_charging_stations WHERE state = 'New York';


Question: What was the total sales revenue for DrugA in Q2 2020?

CREATE TABLE sales(drug_name TEXT, quarter INT, year INT, revenue FLOAT); INSERT INTO sales(drug_name, quarter, year, revenue) VALUES('DrugA', 1, 2020, 150000), ('DrugA', 2, 2020, 200000), ('DrugA', 3, 2020, 180000), ('DrugA', 4, 2020, 220000);

SELECT SUM(revenue) FROM sales WHERE drug_name = 'DrugA' AND quarter = 2 AND year = 2020;


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

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


Question: What is the earliest transaction date for 'VendorW' in the reverse logistics domain?

CREATE TABLE Vendors (VendorID VARCHAR(20), VendorName VARCHAR(20)); INSERT INTO Vendors (VendorID, VendorName) VALUES ('X', 'VendorX'), ('W', 'VendorW'); CREATE TABLE ReverseLogisticsTransactions (TransactionID INT, VendorID VARCHAR(20), TransactionStatus VARCHAR(20), TransactionDate DATE); INSERT INTO ReverseLogisticsTransactions (TransactionID, VendorID, TransactionStatus, TransactionDate) VALUES (4, 'W', 'Returned', '2022-01-04');

SELECT MIN(ReverseLogisticsTransactions.TransactionDate) AS EarliestTransactionDate FROM ReverseLogisticsTransactions JOIN Vendors ON ReverseLogisticsTransactions.VendorID = Vendors.VendorID WHERE Vendors.VendorName = 'VendorW';


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

CREATE FUNCTION intarray_del_elem(_int4, int4)
RETURNS _int4
AS 'MODULE_PATHNAME'
LANGUAGE C STRICT IMMUTABLE PARALLEL SAFE;

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


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

CREATE TYPE gbtreekey2 (
	INTERNALLENGTH = 2,
	INPUT  = gbtreekey2_in,
	OUTPUT = gbtreekey2_out
);


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

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


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

CREATE TABLE road (
	name		text,
	thepath 	path
);

Explanation: DDL from PostgreSQL core regression test for Test Setup.


Question: What is the minimum account balance for customers in the Midwest region?

CREATE TABLE customers (customer_id INT, name VARCHAR(50), region VARCHAR(50), account_balance DECIMAL(10,2)); INSERT INTO customers (customer_id, name, region, account_balance) VALUES (1, 'John Doe', 'Midwest', 5000.00), (2, 'Jane Smith', 'Northeast', 7000.00);

SELECT MIN(account_balance) FROM customers WHERE region = 'Midwest';


Question: What is the distribution of cruelty-free certifications by year for cosmetics products in the makeup category?

CREATE TABLE certifications(certification_id INT, product_id INT, certification_type VARCHAR(50), certified_date DATE);

SELECT YEAR(certified_date) as certification_year, COUNT(*) as cruelty_free_count FROM certifications JOIN cosmetics_products ON certifications.product_id = cosmetics_products.product_id WHERE certifications.certification_type = 'cruelty-free' AND cosmetics_products.category = 'makeup' GROUP BY certification_year;


Question: Generate PostgreSQL SQL for: Name the total number of game sites for chicago bears

CREATE TABLE table_14977592_1 (game_site VARCHAR, opponent VARCHAR)

SELECT COUNT(game_site) FROM table_14977592_1 WHERE opponent = 'Chicago Bears';


Question: Generate PostgreSQL SQL for: What team owns the Venue of western oval?

CREATE TABLE table_name_52 (home_team VARCHAR, venue VARCHAR)

SELECT home_team FROM table_name_52 WHERE venue = 'western oval';


Question: Generate PostgreSQL SQL for: How many values for number of clubs have Shandong as the runner-up?

CREATE TABLE table_17632217_1 (number_of_clubs VARCHAR, runners_up VARCHAR)

SELECT COUNT(number_of_clubs) FROM table_17632217_1 WHERE runners_up = 'Shandong';


Question: Provide the number of customers who have taken out loans with a maturity of 5 years or more, broken down by gender and age group, in Germany?

CREATE TABLE customers (customer_id INT, customer_name TEXT, gender TEXT, age INT, country TEXT); INSERT INTO customers (customer_id, customer_name, gender, age, country) VALUES (1, 'Alex', 'Male', 35, 'Germany'), (2, 'Sarah', 'Female', 40, 'Germany'); CREATE TABLE loans (loan_id INT, customer_id INT, maturity INT); INSERT INTO loans (loan_id, customer_id, maturity) VALUES (1, 1, 5), (2, 2, 6);

SELECT gender, CASE WHEN age < 30 THEN '18-29' WHEN age < 50 THEN '30-49' ELSE '50+' END AS age_group, COUNT(*) FROM customers JOIN loans ON customers.customer_id = loans.customer_id WHERE country = 'Germany' AND maturity >= 5 GROUP BY gender, age_group;


Question: Generate PostgreSQL SQL for: What was the attendance of the game that lasted 3:55?

CREATE TABLE table_name_1 (att VARCHAR, time VARCHAR)

SELECT att FROM table_name_1 WHERE time = '3:55';


Question: Generate PostgreSQL SQL for: In which title was Ann Rutherford the leading lady for Joseph Kane?

CREATE TABLE table_name_73 (title VARCHAR, leading_lady VARCHAR, director VARCHAR)

SELECT title FROM table_name_73 WHERE leading_lady = 'ann rutherford' AND director = 'joseph kane';


Question: Generate PostgreSQL SQL for: What is the cost of 972 Min Press caused 52 death?

CREATE TABLE table_name_36 (damage__millions_usd__ VARCHAR, min_press___mbar__ VARCHAR, deaths VARCHAR)

SELECT damage__millions_usd__ FROM table_name_36 WHERE min_press___mbar__ = '972' AND deaths = '52';


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

CREATE OPERATOR CLASS issn13_ops DEFAULT
	FOR TYPE issn13 USING btree FAMILY isn_ops AS
	OPERATOR 1  <,
	OPERATOR 2  <=,
	OPERATOR 3  =,
	OPERATOR 4  >=,
	OPERATOR 5  >,
	FUNCTION 1  btissn13cmp(issn13, issn13);


Question: How many public health policy violations were reported in the Western and Asian regions?

CREATE TABLE western_policy_violations (region VARCHAR(255), violation VARCHAR(255)); INSERT INTO western_policy_violations (region, violation) VALUES ('Western', 'Smoking Ban Violation'); INSERT INTO western_policy_violations (region, violation) VALUES ('Western', 'Noise Complaint'); CREATE TABLE asian_policy_violations (region VARCHAR(255), violation VARCHAR(255)); INSERT INTO asian_policy_violations (region, violation) VALUES ('Asian', 'Food Safety Violation'); INSERT INTO asian_policy_violations (region, violation) VALUES ('Asian', 'Building Code Violation');

SELECT COUNT(*) FROM western_policy_violations UNION ALL SELECT COUNT(*) FROM asian_policy_violations;


Question: Generate PostgreSQL SQL for: What was the venue when Jerran Hart won?

CREATE TABLE table_name_20 (venue VARCHAR, winner VARCHAR)

SELECT venue FROM table_name_20 WHERE winner = 'jerran hart';


Question: Generate PostgreSQL SQL for: What is the lowest total that has a rank less than 8, a silver greater than 6, and 20 as the bronze?

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

SELECT MIN(total) FROM table_name_70 WHERE rank < 8 AND silver > 6 AND bronze = 20;


Question: What is the recycling rate trend by material type in the last 3 months?

CREATE TABLE recycling_rate_trend(date DATE, material VARCHAR(255), recycling_rate FLOAT);

SELECT date, material, recycling_rate FROM recycling_rate_trend WHERE date >= DATEADD(month, -3, GETDATE()) ORDER BY date;


Question: Generate PostgreSQL SQL for: What type of bridge is Colton's Crossing Bridge?

CREATE TABLE table_name_46 (type VARCHAR, name VARCHAR)

SELECT type FROM table_name_46 WHERE name = 'colton's crossing bridge';


Question: Generate PostgreSQL SQL for: What is the record for November 4, with a decision made by Denis?

CREATE TABLE table_name_10 (record VARCHAR, decision VARCHAR, date VARCHAR)

SELECT record FROM table_name_10 WHERE decision = 'denis' AND date = 'november 4';


Question: Generate PostgreSQL SQL for: What is the smallest number of goals against when 8 games were lost, and the goals for are 60?

CREATE TABLE table_name_86 (goals_against INTEGER, lost VARCHAR, goals_for VARCHAR)

SELECT MIN(goals_against) FROM table_name_86 WHERE lost = 8 AND goals_for = 60;


Question: How many hybrid vehicles were sold in Canada in 2021?

CREATE TABLE VehicleSales (Id INT, VehicleType VARCHAR(50), Year INT, Country VARCHAR(50), Sales INT); INSERT INTO VehicleSales (Id, VehicleType, Year, Country, Sales) VALUES (1, 'Electric', 2021, 'Canada', 25000), (2, 'Hybrid', 2021, 'Canada', 30000), (3, 'Gasoline', 2021, 'Canada', 150000), (4, 'Electric', 2021, 'USA', 40000), (5, 'Hybrid', 2021, 'USA', 50000);

SELECT SUM(Sales) FROM VehicleSales WHERE Year = 2021 AND Country = 'Canada' AND VehicleType = 'Hybrid';


Question: Generate PostgreSQL SQL for: What was the average attendance when the New York Mets were opponents with a record of 51-33?

CREATE TABLE table_name_81 (attendance INTEGER, opponent VARCHAR, record VARCHAR)

SELECT AVG(attendance) FROM table_name_81 WHERE opponent = 'new york mets' AND record = '51-33';


Question: Generate PostgreSQL SQL for: What is the type for the Cathay Pacific Holidays company, an incorporation of Hong Kong and listed activities as Travel Agency?

CREATE TABLE table_name_42 (type VARCHAR, company VARCHAR, incorporated_in VARCHAR, principal_activities VARCHAR)

SELECT type FROM table_name_42 WHERE incorporated_in = 'hong kong' AND principal_activities = 'travel agency' AND company = 'cathay pacific holidays';


Question: List all affordable housing units in the state of New York that have a size less than 1000 square feet.

CREATE TABLE AffordableHousing (id INT, state VARCHAR(20), size FLOAT);

SELECT * FROM AffordableHousing WHERE state = 'New York' AND size < 1000;


Question: What is the change in air pollution levels (PM2.5) by month, for the past year, for a specific mining location?

SELECT EXTRACT(MONTH FROM date) as month, (LEAD(pm2_5) OVER (ORDER BY date) - pm2_5) as pm2_5_change FROM environment WHERE mine_id = 1 AND date BETWEEN DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR) AND CURRENT_DATE;


Question: What is the minimum dissolved oxygen level recorded in the Arctic Ocean?

CREATE TABLE ocean_properties (location VARCHAR(255), dissolved_oxygen FLOAT); INSERT INTO ocean_properties (location, dissolved_oxygen) VALUES ('Arctic Ocean', 5.6), ('Antarctic Ocean', 6.2);

SELECT MIN(dissolved_oxygen) FROM ocean_properties WHERE location = 'Arctic Ocean';


Question: What is the maximum donation amount in the 'Donations' table?

CREATE TABLE Donations (id INT, department VARCHAR(20), amount FLOAT); INSERT INTO Donations (id, department, amount) VALUES (1, 'Animals', 500.00), (2, 'Education', 300.00);


Question: Insert records into the TalentAcquisition table

CREATE TABLE TalentAcquisition (ApplicantID INT PRIMARY KEY, JobTitle VARCHAR(30), Department VARCHAR(20), ApplicationDate DATE);

INSERT INTO TalentAcquisition (ApplicantID, JobTitle, Department, ApplicationDate) VALUES (1, 'Software Engineer', 'Engineering', '2022-01-01'), (2, 'Data Analyst', 'Marketing', '2022-02-15'), (3, 'Project Manager', 'Operations', '2022-03-05');


Question: pgTAP test for Partitions (assertion 23).

-- is_partition_of() should fail for partition sub but wrong base.
SELECT * FROM check_test(
    is_partition_of( 'public', 'part1', 'public', 'base', 'whatevs' ),
    false,
    'is_partition_of( csch, ctab, psch, non-part ptab, desc )',
    'whatevs',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Partitions.


Question: What is the average movie rating for each director?

CREATE TABLE movies (title VARCHAR(255), rating INT, director VARCHAR(50)); INSERT INTO movies (title, rating, director) VALUES ('Movie1', 8, 'DirectorA'), ('Movie2', 7, 'DirectorB'), ('Movie3', 9, 'DirectorA'), ('Movie4', 6, 'DirectorB');

SELECT director, AVG(rating) as avg_rating FROM movies GROUP BY director;


Question: What is the total water usage by all agricultural customers in the month of July?

CREATE TABLE water_usage(customer_id INT, usage FLOAT, month DATE); INSERT INTO water_usage(customer_id, usage, month) VALUES (1, 500, '2022-07-01'), (2, 350, '2022-07-01'), (3, 700, '2022-07-01');

SELECT SUM(usage) FROM water_usage WHERE month = '2022-07-01' AND customer_type = 'agricultural';


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

select count(*) from test_trgm where t ~ '[qwerty]{2}-?[qwerty]{2}';

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


Question: Generate PostgreSQL SQL for: Who was the opponent at the game that had a record of 93-54?

CREATE TABLE table_name_73 (opponent VARCHAR, record VARCHAR)

SELECT opponent FROM table_name_73 WHERE record = '93-54';


Question: What is the total value of works in the impressionism category?

CREATE TABLE sales (sale_id INT PRIMARY KEY, work_id INT, sale_price FLOAT, sale_date DATE, FOREIGN KEY (work_id) REFERENCES works(work_id));

SELECT SUM(s.sale_price) AS total_value FROM sales s JOIN works w ON s.work_id = w.work_id WHERE w.style = 'Impressionism';


Question: How many cybersecurity incidents were reported by the Navy in H1 2021?

CREATE TABLE NavyCybersecurityIncidents (id INT, incident_date DATE, incidents INT); INSERT INTO NavyCybersecurityIncidents (id, incident_date, incidents) VALUES (1, '2021-01-01', 10), (2, '2021-02-01', 15), (3, '2021-03-01', 20), (4, '2021-04-01', 25), (5, '2021-05-01', 30), (6, '2021-06-01', 35);

SELECT SUM(incidents) FROM NavyCybersecurityIncidents WHERE incident_date BETWEEN '2021-01-01' AND '2021-06-01' AND MONTH(incident_date) <= 6;


Question: What is the average property price in each neighborhood in the city of "Oakland"?

CREATE TABLE neighborhoods (neighborhood_id INT, neighborhood_name TEXT, city_id INT, PRIMARY KEY (neighborhood_id)); INSERT INTO neighborhoods (neighborhood_id, neighborhood_name, city_id) VALUES (1, 'Jack London', 3), (2, 'Chinatown', 3), (3, 'West Oakland', 3); CREATE TABLE properties (property_id INT, price FLOAT, neighborhood_id INT, PRIMARY KEY (property_id), FOREIGN KEY (neighborhood_id) REFERENCES neighborhoods(neighborhood_id));

SELECT n.neighborhood_name, AVG(p.price) FROM properties p JOIN neighborhoods n ON p.neighborhood_id = n.neighborhood_id WHERE n.city_id = 3 GROUP BY n.neighborhood_name;


Question: Generate PostgreSQL SQL for: What is the smallest crowd at victoria park?

CREATE TABLE table_name_22 (crowd INTEGER, venue VARCHAR)

SELECT MIN(crowd) FROM table_name_22 WHERE venue = 'victoria park';


Question: How many games have been played by each player in the "RetroGamers" community?

CREATE TABLE Players (PlayerID INT PRIMARY KEY, Name VARCHAR(50), GamingCommunity VARCHAR(50)); CREATE TABLE Games (GameID INT PRIMARY KEY, GameName VARCHAR(50), PlayerID INT, FOREIGN KEY (PlayerID) REFERENCES Players(PlayerID)); INSERT INTO Players (PlayerID, Name, GamingCommunity) VALUES (1, 'John Doe', 'RetroGamers'), (2, 'Jane Smith', 'RetroGamers'), (3, 'Alice Johnson', 'GamingCommunity'); INSERT INTO Games (GameID, GameName, PlayerID) VALUES (1, 'Mario', 1), (2, 'Sonic', 1), (3, 'PacMan', 2), (4, 'Tetris', 3);

SELECT Players.Name, COUNT(Games.GameName) FROM Players JOIN Games ON Players.PlayerID = Games.PlayerID WHERE Players.GamingCommunity = 'RetroGamers' GROUP BY Players.Name;


Question: What is the total number of vessels that docked in the Port of Long Beach in the past year?

CREATE TABLE port_long_beach_vessels (vessel_id INT, docking_date DATE);

SELECT COUNT(*) FROM port_long_beach_vessels WHERE docking_date >= DATEADD(year, -1, GETDATE());


Question: Generate PostgreSQL SQL for: How much did the home team st kilda score?

CREATE TABLE table_name_76 (home_team VARCHAR)

SELECT home_team AS score FROM table_name_76 WHERE home_team = 'st kilda';


Question: Generate PostgreSQL SQL for: Which American Labor candidate ran against Democratic candidate Robert F. Wagner?

CREATE TABLE table_name_51 (american_labor_ticket VARCHAR, democratic_ticket VARCHAR)

SELECT american_labor_ticket FROM table_name_51 WHERE democratic_ticket = 'robert f. wagner';


Question: Insert a new environmental impact assessment for 'Ammonia' in the "environmental_impact" table

CREATE TABLE environmental_impact (id INT PRIMARY KEY, chemical_name VARCHAR(255), environmental_impact VARCHAR(255), date_assessed DATE);

INSERT INTO environmental_impact (id, chemical_name, environmental_impact, date_assessed) VALUES (1, 'Ammonia', 'High greenhouse gas emissions', '2022-01-01');


Question: What is the average daily budget for ad campaigns?

CREATE TABLE ad_campaigns (id INT, name VARCHAR(50), budget INT, start_date DATE, end_date DATE); INSERT INTO ad_campaigns (id, name, budget, start_date, end_date) VALUES (7, 'Holi', 8000, '2021-03-28', '2021-03-30'), (8, 'Navruz', 11000, '2021-03-21', '2021-03-23');

SELECT AVG(budget / DATEDIFF(day, start_date, end_date)) as avg_daily_budget FROM ad_campaigns;


Question: How many military aircraft maintenance requests were recorded for the Air Force in Q4 2019?

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

SELECT COUNT(*) FROM maintenance_requests WHERE service_branch = 'Air Force' AND EXTRACT(QUARTER FROM request_date) = 4 AND EXTRACT(YEAR FROM request_date) = 2019;


Question: How many vessels are there in total for each flag?

CREATE TABLE Vessels (Id INT, Name VARCHAR(50), Type VARCHAR(50), Flag VARCHAR(50)); INSERT INTO Vessels (Id, Name, Type, Flag) VALUES (3, 'VesselC', 'Bulk Carrier', 'Brazil'), (4, 'VesselD', 'Container Ship', 'Brazil');

SELECT V.Flag, COUNT(V.Id) FROM Vessels V GROUP BY V.Flag;


Question: What is the maximum sales for any vegetarian item?

CREATE TABLE menu (item_id INT, item_name TEXT, type TEXT, sales INT); INSERT INTO menu VALUES (1, 'Veggie Burger', 'Vegetarian', 250), (2, 'Falafel Wrap', 'Vegetarian', 150), (3, 'Garden Salad', 'Vegetarian', 100), (4, 'Hummus Plate', 'Vegetarian', 120);

SELECT MAX(sales) FROM menu WHERE type = 'Vegetarian';


Question: Generate PostgreSQL SQL for: What is the result where the original artist is Prince and the Revolution?

CREATE TABLE table_25374338_1 (result VARCHAR, original_artist VARCHAR)

SELECT result FROM table_25374338_1 WHERE original_artist = 'Prince and The Revolution';


Question: Show a SQL definition from the pg_partman project (pg_partman--3.2.1--4.0.0, item 33).

CREATE FUNCTION @extschema@.autovacuum_reset(p_parent_schema text, p_parent_tablename text, p_source_schema text DEFAULT NULL, p_source_tablename text DEFAULT NULL) RETURNS boolean
    LANGUAGE plpgsql
    AS $$
DECLARE

v_row       record;
v_sql       text;

BEGIN

    v_sql = format('ALTER TABLE %I.%I RESET (autovacuum_enabled, toast.autovacuum_enabled)', p_parent_schema, p_parent_tablename);
    RAISE DEBUG 'partition_data sql: %', v_sql;
    EXECUTE v_sql;

    IF p_source_tablename IS NOT NULL THEN
        v_sql = format('ALTER TABLE %I.%I RESET (autovacuum_enabled, toast.autovacuum_enabled)', p_source_schema, p_source_tablename);
        RAISE DEBUG 'partition_data sql: %', v_sql;
        EXECUTE v_sql;
    END IF;

    FOR v_row IN
        SELECT partition_schemaname, partition_tablename FROM @extschema@.show_partitions(p_parent_schema||'.'||p_parent_tablename, 'ASC')
    LOOP
        v_sql = format('ALTER TABLE %I.%I RESET (autovacuum_enabled, toast.autovacuum_enabled)', v_row.partition_schemaname, v_row.partition_tablename);
        RAISE DEBUG 'partition_data sql: %', v_sql;
        EXECUTE v_sql;
    END LOOP;

    RETURN true;
END
$$;

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


Question: Write the DDL statement from PostgreSQL regression test 'subscription' (example 4).

CREATE ROLE regress_subscription_user_dummy LOGIN NOSUPERUSER;

Explanation: DDL from PostgreSQL core regression test for Subscription.


Question: Generate PostgreSQL SQL for: Which professionals live in a city containing the substring 'West'? List his or her role, street, city and state.

CREATE TABLE professionals (role_code VARCHAR, street VARCHAR, city VARCHAR, state VARCHAR)

SELECT role_code, street, city, state FROM professionals WHERE city LIKE '%West%';


Question: What is the total attendance at events organized by museums in Germany?

CREATE TABLE museum_events (id INT, name VARCHAR(255), date DATE, museum_name VARCHAR(255), attendance INT); INSERT INTO museum_events (id, name, date, museum_name, attendance) VALUES (1, 'Art Exhibition', '2020-02-01', 'German Museum', 1500), (2, 'History Conference', '2020-03-15', 'German Museum', 1200), (3, 'Science Fair', '2020-04-01', 'German Museum', 1800);

SELECT SUM(attendance) FROM museum_events WHERE museum_name LIKE '%German%';


Question: Generate PostgreSQL SQL for: What year is the latest year that has no under director?

CREATE TABLE table_name_18 (year INTEGER, director VARCHAR)

SELECT MAX(year) FROM table_name_18 WHERE director = 'no';


Question: PostgreSQL Perform: show example 19.

Explanation: Example from PostgreSQL documentation on Perform.


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

SELECT 1.1 AS two UNION SELECT 2.2 ORDER BY 1;

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

SELECT count(*) FROM (SELECT 1.1 AS two UNION SELECT 2.2 ORDER BY 1) AS _sub;


Question: What is the mental health score distribution by healthcare provider's years of experience?

CREATE TABLE Experience (ExperienceID INT, Experience VARCHAR(50)); CREATE TABLE MentalHealthScores (MH_ID INT, ExperienceID INT, MentalHealthScore INT); INSERT INTO Experience (ExperienceID, Experience) VALUES (1, '0-5 years'), (2, '6-10 years'), (3, '11-20 years'), (4, '20+ years'); INSERT INTO MentalHealthScores (MH_ID, ExperienceID, MentalHealthScore) VALUES (1, 1, 85), (2, 1, 90), (3, 2, 75), (4, 2, 70), (5, 3, 80), (6, 3, 85), (7, 4, 65), (8, 4, 70), (9, 1, 95), (10, 2, 80);

SELECT e.Experience, AVG(mhs.MentalHealthScore) as Avg_Score FROM MentalHealthScores mhs JOIN Experience e ON mhs.ExperienceID = e.ExperienceID GROUP BY e.Experience;


Question: Calculate the total funding for neurological disorder related projects.

CREATE SCHEMA if not exists genetic_research;CREATE TABLE if not exists genetic_research.projects(id INT, name TEXT, lead_researcher TEXT, disease_category TEXT, funding FLOAT);INSERT INTO genetic_research.projects (id, name, lead_researcher, disease_category, funding) VALUES (1, 'ProjectX', 'Dr. Jane Smith', 'Cancer', 2000000), (2, 'ProjectY', 'Dr. John Doe', 'Neurological Disorders', 3000000), (3, 'ProjectZ', 'Dr. Maria Garcia', 'Cancer', 4000000);

SELECT SUM(funding) FROM genetic_research.projects WHERE disease_category = 'Neurological Disorders';


Question: Which products have a higher consumer preference score than their average consumer preference score for their respective categories?

CREATE TABLE categories (id INT, product_id INT, category TEXT); INSERT INTO categories (id, product_id, category) VALUES (1, 1, 'Skincare'), (2, 2, 'Haircare'), (3, 3, 'Skincare'); CREATE TABLE category_averages (category TEXT, avg_preference FLOAT); INSERT INTO category_averages (category, avg_preference) VALUES ('Skincare', 4.4), ('Haircare', 4.2);

SELECT p.product_name, p.consumer_preference FROM products p JOIN categories c ON p.product_id = c.product_id JOIN category_averages ca ON c.category = ca.category WHERE p.consumer_preference > ca.avg_preference;


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

ALTER EXTENSION pgtap ADD FUNCTION is_strict( NAME );


Question: What was the budget for defense project Z in 2019 and 2020?

CREATE TABLE defense_projects (id INT, project VARCHAR(50), year INT, budget FLOAT); INSERT INTO defense_projects (id, project, year, budget) VALUES (1, 'Project Z', 2019, 1100000), (2, 'Project Z', 2020, 1300000);

SELECT project, year, budget FROM defense_projects WHERE project = 'Project Z';


Question: Generate PostgreSQL SQL for: What is the earliest year with less than 3 points and Parmalat Forti Ford was the entrant?

CREATE TABLE table_name_40 (year INTEGER, points VARCHAR, entrant VARCHAR)

SELECT MIN(year) FROM table_name_40 WHERE points < 3 AND entrant = 'parmalat forti ford';


Question: Generate PostgreSQL SQL for: Which Lane has a Time larger than 47.83?

CREATE TABLE table_name_8 (lane INTEGER, time INTEGER)

SELECT AVG(lane) FROM table_name_8 WHERE time > 47.83;


Question: What is the total production of oil from the fields in the North Sea?

CREATE TABLE north_sea_oil_production (field VARCHAR(255), year INT, production FLOAT);

SELECT SUM(production) FROM north_sea_oil_production WHERE field LIKE '%North Sea%';


Question: PostgreSQL regression test 'sqljson_queryfuncs': Write the SELECT query (example 7).

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

SELECT count(*) FROM (SELECT JSON_EXISTS(jsonb '1', '$.a')) AS _sub;


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

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

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

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


Question: Show the total data usage for mobile and broadband subscribers in 'rural' areas, excluding those with billing issues in the past 6 months.

CREATE TABLE Subscribers (SubscriberID int, DataUsage int, Service varchar(10), Area varchar(10), BillingIssue bit); INSERT INTO Subscribers (SubscriberID, DataUsage, Service, Area, BillingIssue) VALUES (1, 20000, 'mobile', 'rural', 0), (2, 30000, 'broadband', 'urban', 1), (3, 15000, 'mobile', 'rural', 1), (4, 25000, 'broadband', 'urban', 0), (5, 35000, 'broadband', 'rural', 0);

SELECT DataUsage FROM Subscribers WHERE Area = 'rural' AND BillingIssue = 0 AND Service IN ('mobile', 'broadband');


Question: Generate PostgreSQL SQL for: What is the last match with a vacancy date of round 2 and Ney Franco as outgoing manager?

CREATE TABLE table_name_26 (last_match VARCHAR, date_of_vacancy VARCHAR, outgoing_manager VARCHAR)

SELECT last_match FROM table_name_26 WHERE date_of_vacancy = 'round 2' AND outgoing_manager = 'ney franco';


Question: Add a new diversity metric record into the 'diversity_metrics' table

CREATE TABLE diversity_metrics (id INT PRIMARY KEY, year INT, gender VARCHAR(10), percentage_representation DECIMAL(5,2));

INSERT INTO diversity_metrics (id, year, gender, percentage_representation) VALUES (2022, 'Female', 45.30);


Question: What is the average rating of eco-friendly hotels in Portugal and Spain?

CREATE TABLE eco_hotels (hotel_id INT, name TEXT, country TEXT, rating FLOAT); INSERT INTO eco_hotels VALUES (1, 'Eco Hotel Lisbon', 'Portugal', 4.6), (2, 'Green Hotel Barcelona', 'Spain', 4.4);

SELECT AVG(rating) FROM eco_hotels WHERE country IN ('Portugal', 'Spain');


Question: List all biotech startups that received funding in the last 6 months.

CREATE SCHEMA if not exists biotech;CREATE TABLE biotech.startups_funding (id INT, startup_name VARCHAR(50), funding_date DATE, funding_amount DECIMAL(10,2));INSERT INTO biotech.startups_funding (id, startup_name, funding_date, funding_amount) VALUES (1, 'StartupA', '2022-01-15', 5000000.00), (2, 'StartupB', '2022-06-30', 3000000.00), (3, 'StartupC', '2021-12-31', 2000000.00);

SELECT * FROM biotech.startups_funding WHERE funding_date >= DATE_SUB(CURDATE(), INTERVAL 6 MONTH);


Question: What is the total number of male and female members?

CREATE TABLE membership (id INT, member_id INT, gender VARCHAR(10)); INSERT INTO membership (id, member_id, gender) VALUES (1, 401, 'male'), (2, 402, 'female'), (3, 403, 'male'), (4, 404, 'non-binary');

SELECT SUM(gender = 'male') AS male_count, SUM(gender = 'female') AS female_count FROM membership;


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

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


Question: List all the shipments that were delayed by more than 2 hours from the 'shipments' table.

CREATE TABLE shipments (shipment_id INT, customer_id INT, shipped_date TIMESTAMP, shipped_time TIME, delivered_date TIMESTAMP, delivered_time TIME, status TEXT, delay DECIMAL(3,2));

SELECT shipment_id, customer_id, shipped_date, shipped_time, delivered_date, delivered_time, status, delay FROM shipments WHERE delay > 2;


Question: Generate PostgreSQL SQL for: Who was the arranger for the song that had a lyricist of Sirapatara Kalayapanid?

CREATE TABLE table_name_8 (arranger_s_ VARCHAR, lyricist_s_ VARCHAR)

SELECT arranger_s_ FROM table_name_8 WHERE lyricist_s_ = 'sirapatara kalayapanid';


Question: How many military technology patents were filed by each country in the last 3 years?

CREATE TABLE MilitaryPatents (Id INT, Country VARCHAR(50), Patent VARCHAR(50), Year INT); INSERT INTO MilitaryPatents (Id, Country, Patent, Year) VALUES (1, 'USA', 'Laser Communication', 2021); INSERT INTO MilitaryPatents (Id, Country, Patent, Year) VALUES (2, 'China', 'Drone Swarm', 2021);

SELECT COUNT(*), Country FROM MilitaryPatents WHERE Year >= (YEAR(CURRENT_DATE) - 3) GROUP BY Country;


Question: pgTAP test for Aretap (assertion 124).

SELECT * FROM check_test(
    rules_are( 'public', 'fou', ARRAY['ins_me', 'upd_me', 'del_me'] ),
    false,
    'rules_are(schema, table, rules) + missing',
    'Relation public.fou should have the correct rules',
    '    Missing rules:
        del_me'
);

Explanation: SQL assertion from pgTAP test suite for Aretap.


Question: What is the maximum budget allocated for any category in the West region in the year 2020?

CREATE TABLE Budget (Year INT, Region VARCHAR(50), Category VARCHAR(50), Amount INT); INSERT INTO Budget (Year, Region, Category, Amount) VALUES (2020, 'West', 'Education', 5000000), (2020, 'West', 'Public Transportation', 6000000);

SELECT MAX(Amount) FROM Budget WHERE Year = 2020 AND Region = 'West';


Question: What is the distribution of food safety inspections by month?

CREATE TABLE inspections (id INT, date TEXT, result TEXT); INSERT INTO inspections (id, date, result) VALUES (1, '2020-01-01', 'Pass'), (2, '2020-02-01', 'Fail');

SELECT EXTRACT(MONTH FROM date) AS month, COUNT(*) AS num_inspections FROM inspections GROUP BY month;


Question: Generate PostgreSQL SQL for: what was the away team for the north melbourne home team?

CREATE TABLE table_name_60 (away_team VARCHAR, home_team VARCHAR)

SELECT away_team FROM table_name_60 WHERE home_team = 'north melbourne';


Question: Show the number of wind farms in Oklahoma

CREATE TABLE Infrastructure (id INT, name VARCHAR(100), type VARCHAR(50), location VARCHAR(100), state VARCHAR(50)); INSERT INTO Infrastructure (id, name, type, location, state) VALUES (9, 'Western Plains Wind Farm', 'Wind Farm', 'Woodward', 'Oklahoma');

SELECT COUNT(*) FROM Infrastructure WHERE type = 'Wind Farm' AND state = 'Oklahoma';


Question: Who are the teachers that have not taken any professional development courses and have more than 5 years of experience?

CREATE TABLE Teachers (TeacherID INT, Name VARCHAR(50), ProfessionalDevelopmentCourse INT, YearsOfExperience INT); INSERT INTO Teachers (TeacherID, Name, ProfessionalDevelopmentCourse, YearsOfExperience) VALUES (5, 'Ava Red', 0, 6); INSERT INTO Teachers (TeacherID, Name, ProfessionalDevelopmentCourse, YearsOfExperience) VALUES (6, 'Benjamin Orange', 0, 3);

SELECT Name FROM Teachers WHERE ProfessionalDevelopmentCourse = 0 AND YearsOfExperience > 5;


Question: How many 'Education' events were held in 'Toronto' and 'Vancouver' between 2020-01-01 and 2020-12-31?

CREATE TABLE Donors (DonorID INT PRIMARY KEY, FirstName VARCHAR(50), LastName VARCHAR(50), DonationAmount DECIMAL(10,2), DonationDate DATE); CREATE TABLE DonationEvents (EventID INT PRIMARY KEY, EventName VARCHAR(100), EventType VARCHAR(100), DonationID INT, EventLocation VARCHAR(100), EventDate DATE, FOREIGN KEY (DonationID) REFERENCES Donors(DonorID));

SELECT COUNT(*) as NumberOfEvents FROM DonationEvents e WHERE e.EventType = 'Education' AND e.EventLocation IN ('Toronto', 'Vancouver') AND e.EventDate BETWEEN '2020-01-01' AND '2020-12-31';


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

SELECT * FROM tststats.priv_test_parent_tbl WHERE a <<< 0 AND b <<< 0; -- Permission denied
SELECT * FROM tststats.priv_test_parent_tbl WHERE a <<< 0 OR b <<< 0; -- Permission denied
SELECT * FROM tststats.priv_test_parent_tbl t
 WHERE a <<< 0 AND (b <<< 0 OR t.* <<< (1, 1) IS NOT NULL); -- Permission denied
DELETE FROM tststats.priv_test_parent_tbl WHERE a <<< 0 AND b <<< 0; -- Permission denied

-- Grant table access to parent, but hide all data with RLS
RESET SESSION AUTHORIZATION;

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

SELECT count(*) FROM (SELECT * FROM tststats.priv_test_parent_tbl WHERE a <<< 0 AND b <<< 0; -- Permission denied
SELECT * FROM tststats.priv_test_parent_tbl WHERE a <<< 0 OR b <<< 0; -- Permission denied
SELECT * FROM tststats.priv_test_parent_tbl t
 WHERE a <<< 0 AND (b <<< 0 OR t.* <<< (1, 1) IS NOT NULL); -- Permission denied
DELETE FROM tststats.priv_test_parent_tbl WHERE a <<< 0 AND b <<< 0; -- Permission denied

-- Grant table access to parent, but hide all data with RLS
RESET SESSION AUTHORIZATION) AS _sub;


Question: pgTAP test for Inheritance (assertion 143).

SELECT * FROM check_test(
    isnt_descendent_of( 'child2', 'parent' ),
    false,
    'isnt_descendent_of( ctab2, ptab )',
    'Table child2 should not be a descendent of parent',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Inheritance.


Question: What is the average safety rating for products with cruelty-free certification?

CREATE TABLE product_safety_records (id INT PRIMARY KEY, product_name VARCHAR(100), safety_rating INT, inspection_date DATE); CREATE TABLE cruelty_free_certification (id INT PRIMARY KEY, product_name VARCHAR(100), certification_date DATE, certification_status VARCHAR(10)); INSERT INTO cruelty_free_certification (id, product_name, certification_date, certification_status) VALUES (1, 'Lotion', '2021-01-01', 'Certified'); INSERT INTO cruelty_free_certification (id, product_name, certification_date, certification_status) VALUES (2, 'Lip Balm', '2021-01-02', 'Not Certified');

SELECT AVG(safety_rating) as avg_safety_rating FROM product_safety_records ps INNER JOIN cruelty_free_certification cfc ON ps.product_name = cfc.product_name WHERE cfc.certification_status = 'Certified';


Question: Generate PostgreSQL SQL for: What was the name of the host team dated December 16?

CREATE TABLE table_name_39 (host_team VARCHAR, date VARCHAR)

SELECT host_team FROM table_name_39 WHERE date = 'december 16';


Question: Show a SQL definition from the pg_partman project (pg_partman--2.2.3--2.3.0, item 17).

CREATE OR REPLACE FUNCTION create_trigger(p_parent_table text) RETURNS void
    LANGUAGE plpgsql SECURITY DEFINER
    AS $$
DECLARE

v_function_name         text;
v_new_length            int;
v_parent_schema         text;
v_parent_tablename      text;
v_trig_name             text;
v_trig_sql              text;

BEGIN

SELECT schemaname, tablename INTO v_parent_schema, v_parent_tablename
FROM pg_catalog.pg_tables
WHERE schemaname = split_part(p_parent_table, '.', 1)
AND tablename = split_part(p_parent_table, '.', 2);
v_trig_name := @extschema@.check_name_length(p_object_name := v_parent_tablename, p_suffix := '_part_trig');
-- Ensure function name matches the naming pattern
v_function_name := @extschema@.check_name_length(v_parent_tablename, '_part_trig_func', FALSE);
v_trig_sql := format('CREATE TRIGGER %I BEFORE INSERT ON %I.%I FOR EACH ROW EXECUTE PROCEDURE %I.%I()'
    , v_trig_name
    , v_parent_schema
    , v_parent_tablename
    , v_parent_schema
    , v_function_name);

EXECUTE v_trig_sql;

END
$$;


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

CREATE PUBLICATION testpub4 FOR TABLES IN SCHEMA pub_test;

Explanation: DDL from PostgreSQL core regression test for Publication.


Question: Generate PostgreSQL SQL for: What is the title of the original airing on e4 May 2, 2010?

CREATE TABLE table_22170495_6 (title VARCHAR, original_airing_on_e4 VARCHAR)

SELECT title FROM table_22170495_6 WHERE original_airing_on_e4 = 'May 2, 2010';


Question: Generate PostgreSQL SQL for: What was the Outcome of the match with Partner Kateryna Bondarenko?

CREATE TABLE table_name_84 (outcome VARCHAR, partner VARCHAR)

SELECT outcome FROM table_name_84 WHERE partner = 'kateryna bondarenko';


Question: PostgreSQL regression test 'float4': Write the SELECT query (example 64).

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

SELECT count(*) FROM (SELECT '-32768.6'::float4::int2) AS _sub;


Question: Generate PostgreSQL SQL for: How many points is there when the lost is 6 and the try bonus is 9?

CREATE TABLE table_name_24 (points_for VARCHAR, lost VARCHAR, try_bonus VARCHAR)

SELECT points_for FROM table_name_24 WHERE lost = '6' AND try_bonus = '9';


Question: How many traffic violations were issued in the past month for each district in the Transportation department?

CREATE TABLE TrafficViolations (ViolationID INT, ViolationDate DATE, District VARCHAR(255)); INSERT INTO TrafficViolations (ViolationID, ViolationDate, District) VALUES (1, '2022-01-01', 'District A'), (2, '2022-01-15', 'District B'), (3, '2022-02-01', 'District A');

SELECT COUNT(*), District FROM TrafficViolations WHERE ViolationDate >= DATEADD(month, -1, GETDATE()) GROUP BY District;


Question: Generate PostgreSQL SQL for: What position does Kerry Wood play in?

CREATE TABLE table_11677100_3 (position VARCHAR, player VARCHAR)

SELECT position FROM table_11677100_3 WHERE player = 'Kerry Wood';


Question: What is the percentage of customers using 4G and 5G networks in each customer region?

CREATE TABLE customer_network_data (customer_region VARCHAR(20), network_type VARCHAR(20), customer_count INT); INSERT INTO customer_network_data (customer_region, network_type, customer_count) VALUES ('Northeast', '4G', 2500), ('Southwest', '4G', 2000), ('Midwest', '4G', 2200), ('Northeast', '5G', 3000), ('Southwest', '5G', 2500), ('Midwest', '5G', 3300);

SELECT customer_region, ((SUM(CASE WHEN network_type = '5G' THEN customer_count ELSE 0 END) / SUM(customer_count)) * 100) AS pct_5g_customers, ((SUM(CASE WHEN network_type = '4G' THEN customer_count ELSE 0 END) / SUM(customer_count)) * 100) AS pct_4g_customers FROM customer_network_data GROUP BY customer_region;


Question: What is the total number of news stories published in the "news" table for each country in the "reporters" table?

CREATE TABLE reporters (id INT, name VARCHAR(50), gender VARCHAR(10), age INT, country VARCHAR(50)); CREATE TABLE published_stories (reporter_id INT, news_id INT); CREATE TABLE news (id INT, title VARCHAR(100), views INT, date DATE, country VARCHAR(50));

SELECT r.country, COUNT(*) AS total_stories FROM reporters r INNER JOIN published_stories ps ON r.id = ps.reporter_id INNER JOIN news n ON ps.news_id = n.id GROUP BY r.country;


Question: Generate PostgreSQL SQL for: What year was the name mount roskill grammar school?

CREATE TABLE table_name_35 (years VARCHAR, name VARCHAR)

SELECT years FROM table_name_35 WHERE name = 'mount roskill grammar school';


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

create event trigger no_rewrite_allowed on table_rewrite
  execute procedure test_evtrig_no_rewrite();

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


Question: Generate PostgreSQL SQL for: List the name of musicals that do not have actors.

CREATE TABLE actor (Name VARCHAR, Musical_ID VARCHAR); CREATE TABLE musical (Name VARCHAR, Musical_ID VARCHAR)

SELECT Name FROM musical WHERE NOT Musical_ID IN (SELECT Musical_ID FROM actor);


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

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

SELECT count(*) FROM (SELECT interval '1 2' minute to second) AS _sub;


Question: pgTAP test for Fktap (assertion 4).

CREATE TABLE public.fk (
    id    INT NOT NULL PRIMARY KEY,
    pk_id INT NOT NULL REFERENCES pk(id)
);

Explanation: SQL assertion from pgTAP test suite for Fktap.


Question: Generate PostgreSQL SQL for: Which Multi 1 has a Frequency of 2300mhz, and a Release date of q3 2008 and a Model number of turion x2 ultra zm-84?

CREATE TABLE table_name_7 (multi_1 VARCHAR, model_number VARCHAR, frequency VARCHAR, release_date VARCHAR)

SELECT multi_1 FROM table_name_7 WHERE frequency = '2300mhz' AND release_date = 'q3 2008' AND model_number = 'turion x2 ultra zm-84';


Question: Insert a new record for a farm with farm ID 2 and species ID 2

CREATE TABLE Aquatic_Farm (Farm_ID INT, Farm_Name VARCHAR(100), Species_ID INT, Stock_Quantity INT); INSERT INTO Aquatic_Farm (Farm_ID, Farm_Name, Species_ID, Stock_Quantity) VALUES (1, 'North Sea Fishery', 1, 25000);

INSERT INTO Aquatic_Farm (Farm_ID, Farm_Name, Species_ID, Stock_Quantity) VALUES (2, 'Pacific Fishery', 2, 15000);


Question: Generate PostgreSQL SQL for: Name the most attendance

CREATE TABLE table_16227492_1 (attendance INTEGER)

SELECT MAX(attendance) FROM table_16227492_1;


Question: How many community health workers have completed health equity training by race?

CREATE TABLE CommunityHealthWorkers (WorkerID INT, Age INT, Race VARCHAR(25)); INSERT INTO CommunityHealthWorkers (WorkerID, Age, Race) VALUES (1, 35, 'Hispanic'), (2, 42, 'African American'), (3, 50, 'Caucasian'); CREATE TABLE HealthEquityTraining (WorkerID INT, Completed BOOLEAN); INSERT INTO HealthEquityTraining (WorkerID, Completed) VALUES (1, TRUE), (2, FALSE), (3, TRUE);

SELECT c.Race, COUNT(*) AS CompletedHealthEquityTraining FROM CommunityHealthWorkers c INNER JOIN HealthEquityTraining t ON c.WorkerID = t.WorkerID WHERE t.Completed = TRUE GROUP BY c.Race;


Question: Show a SQL definition from the timescaledb project (create_table, item 6).

\set ON_ERROR_STOP 1

CREATE TABLE test_delete(time timestamp with time zone PRIMARY KEY, temp float);

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


Question: Generate PostgreSQL SQL for: Show the names of countries that have more than one roller coaster.

CREATE TABLE roller_coaster (Country_ID VARCHAR); CREATE TABLE country (Name VARCHAR, Country_ID VARCHAR)

SELECT T1.Name FROM country AS T1 JOIN roller_coaster AS T2 ON T1.Country_ID = T2.Country_ID GROUP BY T1.Name HAVING COUNT(*) > 1;


Question: Generate PostgreSQL SQL for: What is the minimum die size for an SM count of exactly 2?

CREATE TABLE table_26040604_1 (die_size__mm_2__ INTEGER, sm_count VARCHAR)

SELECT MIN(die_size__mm_2__) FROM table_26040604_1 WHERE sm_count = 2;


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

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

SELECT count(*) FROM (select 33 * any (44)) AS _sub;


Question: How many police officers are assigned to each district?

CREATE TABLE police_department (id INT, district_name VARCHAR(20), officer_count INT); INSERT INTO police_department (id, district_name, officer_count) VALUES (1, 'District1', 120), (2, 'District2', 130), (3, 'District3', 150);

SELECT district_name, officer_count, officer_count/SUM(officer_count) OVER () * 100 AS percentage FROM police_department;


Question: Which drug was approved by the FDA in 2019 with the highest sales?

CREATE TABLE Drug_Approvals(drug VARCHAR(20), approval_year INT, company VARCHAR(20));CREATE TABLE Drug_Sales(drug VARCHAR(20), year INT, sales DECIMAL(10,2));INSERT INTO Drug_Approvals VALUES('DrugA', 2019, 'PharmaCorp');INSERT INTO Drug_Sales VALUES('DrugA', 2019, 2000000.00);

SELECT a.drug, MAX(s.sales) FROM Drug_Approvals a INNER JOIN Drug_Sales s ON a.drug = s.drug WHERE a.approval_year = 2019 GROUP BY a.drug;