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

INSERT INTO s2 (SELECT x, public.fipshash(x::text) FROM generate_series(-6,6) x);

Explanation: DML from PostgreSQL core regression test for Rowsecurity.


Question: What is the average market price of Neodymium produced in the US in 2020?

CREATE TABLE Neodymium_Production (id INT, year INT, country VARCHAR(255), quantity FLOAT, market_price FLOAT);

SELECT AVG(market_price) FROM Neodymium_Production WHERE year = 2020 AND country = 'USA';


Question: What is the total number of military vehicles produced by companies based in the Asia-Pacific region in the 'military_vehicles' table?

CREATE TABLE military_vehicles (company VARCHAR(50), region VARCHAR(50), production_year INT, quantity INT); INSERT INTO military_vehicles (company, region, production_year, quantity) VALUES ('Company A', 'Asia-Pacific', 2010, 500), ('Company B', 'Asia-Pacific', 2015, 700), ('Company C', 'Europe', 2012, 600), ('Company D', 'Americas', 2018, 800);

SELECT SUM(quantity) FROM military_vehicles WHERE region = 'Asia-Pacific';


Question: Generate PostgreSQL SQL for: What office was law preservation ticket holder William E. Barron running for?

CREATE TABLE table_name_51 (office VARCHAR, law_preservation_ticket VARCHAR)

SELECT office FROM table_name_51 WHERE law_preservation_ticket = 'william e. barron';


Question: Insert data into 'agricultural_projects' table

CREATE TABLE agricultural_projects (id INT PRIMARY KEY, name VARCHAR(100), location VARCHAR(50), funding_source VARCHAR(50), start_date DATE, end_date DATE);

INSERT INTO agricultural_projects (id, name, location, funding_source, start_date, end_date) VALUES (1, 'Solar Powered Irrigation', 'Rural Kenya', 'World Bank', '2022-01-01', '2023-12-31');


Question: Generate PostgreSQL SQL for: What is the lowest area for cannonvale that speaks afrikaans?

CREATE TABLE table_name_31 (area__km_2__ INTEGER, most_spoken_language VARCHAR, place VARCHAR)

SELECT MIN(area__km_2__) FROM table_name_31 WHERE most_spoken_language = 'afrikaans' AND place = 'cannonvale';


Question: Delete all records in the species table where the scientific_name is 'Quercus robur'

CREATE TABLE species (id INT PRIMARY KEY, common_name TEXT, scientific_name TEXT, region TEXT); INSERT INTO species (id, common_name, scientific_name, region) VALUES (1, 'English Oak', 'Quercus robur', 'Europe');

DELETE FROM species WHERE scientific_name = 'Quercus robur';


Question: Find the earliest date of articles in 'Technology'

CREATE TABLE articles (id INT, title VARCHAR(100), topic VARCHAR(50), date DATE); INSERT INTO articles (id, title, topic, date) VALUES (1, 'Article 1', 'Politics', '2021-01-01'); INSERT INTO articles (id, name, topic, date) VALUES (2, 'Article 2', 'Sports', '2021-01-02'); INSERT INTO articles (id, title, topic, date) VALUES (3, 'Article 3', 'Technology', '2021-01-03');

SELECT MIN(date) as earliest_date FROM articles WHERE topic = 'Technology';


Question: What is the total number of mental health parity violations that have been reported in each region in the last year?

CREATE TABLE mental_health_parity (id INT PRIMARY KEY, incident_date DATE, incident_description TEXT, location TEXT, resolved BOOLEAN); CREATE VIEW regions AS SELECT location AS region FROM mental_health_parity GROUP BY location;

SELECT region, COUNT(*) FROM mental_health_parity WHERE incident_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR) GROUP BY region;


Question: Generate PostgreSQL SQL for: When the second intermediate period of egypt is the  ubaid period in mesopotamia how many early calcolithics are there?

CREATE TABLE table_23537091_1 (early_chalcolithic VARCHAR, ubaid_period_in_mesopotamia VARCHAR)

SELECT COUNT(early_chalcolithic) FROM table_23537091_1 WHERE ubaid_period_in_mesopotamia = 'Second Intermediate Period of Egypt';


Question: Generate PostgreSQL SQL for: What is the earliest year with an entry from Rotary Watches Stanley BRM and a BRM P207 with more than 0 points?

CREATE TABLE table_name_99 (year INTEGER, points VARCHAR, entrant VARCHAR, chassis VARCHAR)

SELECT MIN(year) FROM table_name_99 WHERE entrant = 'rotary watches stanley brm' AND chassis = 'brm p207' AND points > 0;


Question: How many complaints were received for each service type in the last month?

CREATE TABLE service_complaints (complaint_id INT, complaint_type VARCHAR(50), complaint_date DATE); INSERT INTO service_complaints (complaint_id, complaint_type, complaint_date) VALUES (1, 'Mobile Data', '2022-03-01'), (2, 'Broadband Internet', '2022-03-15'), (3, 'VoIP', '2022-04-01');

SELECT COUNT(*) as total_complaints, complaint_type FROM service_complaints WHERE complaint_date >= DATE_TRUNC('month', NOW()) - INTERVAL '1 month' GROUP BY complaint_type;


Question: Generate PostgreSQL SQL for: When 5 is the l what is the lowest amount of stolen ends?

CREATE TABLE table_29565541_2 (stolen_ends INTEGER, l VARCHAR)

SELECT MIN(stolen_ends) FROM table_29565541_2 WHERE l = 5;


Question: Generate PostgreSQL SQL for: Name the try bonus for tries against is 70

CREATE TABLE table_13741576_4 (try_bonus VARCHAR, tries_against VARCHAR)

SELECT try_bonus FROM table_13741576_4 WHERE tries_against = '70';


Question: What is the maximum budget allocated to any digital divide initiative?

CREATE TABLE div_initiatives (name TEXT, budget INTEGER); INSERT INTO div_initiatives (name, budget) VALUES ('DivBridge', 800000), ('CloseGap', 900000), ('ConnectWorld', 700000);

SELECT MAX(budget) FROM div_initiatives;


Question: What is the average temperature recorded for each spacecraft during their respective missions?

CREATE TABLE spacecraft_temperatures (spacecraft_name TEXT, mission_name TEXT, temperature FLOAT); INSERT INTO spacecraft_temperatures (spacecraft_name, mission_name, temperature) VALUES ('Voyager 1', 'Voyager 1 Mission', 80.5), ('Voyager 2', 'Voyager 2 Mission', 78.2), ('Cassini', 'Cassini Mission', 130.6);

SELECT spacecraft_name, AVG(temperature) as avg_temperature FROM spacecraft_temperatures GROUP BY spacecraft_name;


Question: Generate PostgreSQL SQL for: What is the Main use of emley moor tower (mk.3)?

CREATE TABLE table_name_54 (main_use VARCHAR, name VARCHAR)

SELECT main_use FROM table_name_54 WHERE name = 'emley moor tower (mk.3)';


Question: What is the most common art medium used by local artists?

CREATE TABLE artists (id INT, name TEXT, city TEXT, country TEXT);CREATE TABLE art_pieces (id INT, title TEXT, medium TEXT, artist_id INT);

SELECT a.city, ap.medium, COUNT(ap.id) as num_pieces FROM artists a JOIN art_pieces ap ON a.id = ap.artist_id GROUP BY a.city, ap.medium ORDER BY num_pieces DESC LIMIT 1;


Question: How many heritage sites in the Americas have more than 100,000 annual visitors?

CREATE TABLE HeritageSites (id INT, name TEXT, region TEXT, annual_visitors INT); INSERT INTO HeritageSites (id, name, region, annual_visitors) VALUES (1, 'Machu Picchu', 'Americas', 120000), (2, 'Eiffel Tower', 'Europe', 7000000), (3, 'Chichen Itza', 'Americas', 1500000);

SELECT COUNT(*) FROM HeritageSites WHERE region = 'Americas' AND annual_visitors > 100000;


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

SELECT dictinitoption FROM pg_ts_dict WHERE dictname = 'synonym';

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

SELECT count(*) FROM (SELECT dictinitoption FROM pg_ts_dict WHERE dictname = 'synonym') AS _sub;


Question: Find the change in average property price per square foot from 2021 to 2022 in each neighborhood.

CREATE TABLE neighborhoods (name VARCHAR(50), id INT, PRIMARY KEY (id)); INSERT INTO neighborhoods (name, id) VALUES ('Brewerytown', 1), ('Fairmount', 2); CREATE TABLE properties (id INT, neighborhood_id INT, price FLOAT, livable_square_feet INT, year INT, PRIMARY KEY (id), FOREIGN KEY (neighborhood_id) REFERENCES neighborhoods(id));

SELECT a.neighborhood_id, AVG(a.price/a.livable_square_feet) - AVG(b.price/b.livable_square_feet) AS price_change_per_sqft FROM properties a JOIN properties b ON a.neighborhood_id = b.neighborhood_id WHERE a.year = 2022 AND b.year = 2021 GROUP BY a.neighborhood_id;


Question: What are the names and average delivery times of all cargoes that were transported by the vessel 'MSC Chariot' and unloaded at the port of Oakland?

CREATE TABLE vessels(id INT, name VARCHAR(255)); INSERT INTO vessels VALUES (1, 'MSC Chariot'); CREATE TABLE cargo(id INT, name VARCHAR(255), delivery_time INT, vessel_id INT, port_id INT); CREATE TABLE ports(id INT, name VARCHAR(255));

SELECT cargo.name, AVG(cargo.delivery_time) FROM cargo INNER JOIN vessels ON cargo.vessel_id = vessels.id INNER JOIN ports ON cargo.port_id = ports.id WHERE vessels.name = 'MSC Chariot' AND ports.name = 'Oakland' GROUP BY cargo.name;


Question: What is the average tourist spending in Indonesia?

CREATE TABLE Spending (id INT, country TEXT, year INT, spending FLOAT); INSERT INTO Spending (id, country, year, spending) VALUES (1, 'Indonesia', 2018, 1000), (2, 'Indonesia', 2019, 1200), (3, 'Indonesia', 2020, 800);

SELECT AVG(spending) FROM Spending WHERE country = 'Indonesia';


Question: Generate PostgreSQL SQL for: What are the transit connections from Pioneer Square U?

CREATE TABLE table_22771048_2 (transit_connections VARCHAR, station VARCHAR)

SELECT transit_connections FROM table_22771048_2 WHERE station = 'Pioneer Square U';


Question: What is the average energy efficiency rating of buildings in New York and Chicago?

CREATE TABLE building_energy (building_id INT, city VARCHAR(50), rating FLOAT); INSERT INTO building_energy (building_id, city, rating) VALUES (1, 'New York', 85.3), (2, 'Chicago', 78.9), (3, 'New York', 92.1), (4, 'Chicago', 88.7), (5, 'New York', 74.5), (6, 'Chicago', 69.2);

SELECT AVG(rating) FROM building_energy WHERE city IN ('New York', 'Chicago');


Question: Generate PostgreSQL SQL for: What is the maximum memory speed for frequencies between 2.93-3.2ghz?

CREATE TABLE table_24018112_1 (max_memory_speed VARCHAR, frequency VARCHAR)

SELECT max_memory_speed FROM table_24018112_1 WHERE frequency = '2.93-3.2GHz';


Question: Generate PostgreSQL SQL for: WHAT IS THE SUM OF AST AVG WITH RANK 5 AND GAMES BIGGER THAN 108?

CREATE TABLE table_name_20 (ast_avg INTEGER, rank VARCHAR, games VARCHAR)

SELECT SUM(ast_avg) FROM table_name_20 WHERE rank = 5 AND games > 108;


Question: Generate PostgreSQL SQL for: What Constellation has a Object type of globular cluster and a NGC number of 5986?

CREATE TABLE table_name_17 (constellation VARCHAR, object_type VARCHAR, ngc_number VARCHAR)

SELECT constellation FROM table_name_17 WHERE object_type = 'globular cluster' AND ngc_number = 5986;


Question: Generate PostgreSQL SQL for: What is the production code for episode 96 in the series?

CREATE TABLE table_2818164_5 (production_code INTEGER, no_in_series VARCHAR)

SELECT MIN(production_code) FROM table_2818164_5 WHERE no_in_series = '96';


Question: Generate PostgreSQL SQL for: What is the Time/Retired for emerson fittipaldi?

CREATE TABLE table_name_14 (time_retired VARCHAR, driver VARCHAR)

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


Question: What is the average account balance for clients in Oceania in Q2 2022?

CREATE TABLE accounts (client_id INT, balance DECIMAL(10,2), country VARCHAR(50), account_date DATE); INSERT INTO accounts (client_id, balance, country, account_date) VALUES (1, 12000.00, 'Australia', '2022-04-01'), (2, 25000.00, 'New Zealand', '2022-05-15'), (3, 18000.00, 'Papua New Guinea', '2022-06-01');

SELECT AVG(balance) as avg_balance FROM accounts WHERE country IN ('Australia', 'New Zealand', 'Papua New Guinea') AND account_date BETWEEN '2022-04-01' AND '2022-06-30';


Question: What is the total volume of oil spilled in the Gulf of Mexico and the Arabian Sea?

CREATE TABLE oil_spills(region VARCHAR(255), volume FLOAT);INSERT INTO oil_spills(region, volume) VALUES ('Gulf of Mexico', 4000000), ('Arabian Sea', 2000000);

SELECT SUM(volume) FROM oil_spills WHERE region IN ('Gulf of Mexico', 'Arabian Sea');


Question: Generate PostgreSQL SQL for: Name where bethany college is

CREATE TABLE table_262476_1 (location VARCHAR, institution VARCHAR)

SELECT location FROM table_262476_1 WHERE institution = 'Bethany College';


Question: Generate PostgreSQL SQL for: Name the example when the environment is #_x

CREATE TABLE table_name_46 (example VARCHAR, environment VARCHAR)

SELECT example FROM table_name_46 WHERE environment = '#_x';


Question: Show a query using PostgreSQL contrib extension 'postgres_fdw' (example 171).

SELECT t1.c1, t2.c1 FROM ft4 t1 FULL JOIN ft5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c1, t2.c1 OFFSET 45 LIMIT 10;

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


Question: Generate PostgreSQL SQL for: Name the score for fiji

CREATE TABLE table_name_99 (score VARCHAR, country VARCHAR)

SELECT score FROM table_name_99 WHERE country = 'fiji';


Question: Show an example of PostgreSQL INSERT (example 6).

INSERT INTO films SELECT * FROM tmp_films WHERE date_prod < '2004-05-07';

Explanation: PostgreSQL INSERT command.


Question: Generate PostgreSQL SQL for: Which FA Cup apps has league goals of 1 with total goals less than 1?

CREATE TABLE table_name_47 (fa_cup_apps INTEGER, league_goals VARCHAR, total_goals VARCHAR)

SELECT AVG(fa_cup_apps) FROM table_name_47 WHERE league_goals = 1 AND total_goals < 1;


Question: What is the number of vessels inspected in the Caribbean sea?

CREATE TABLE vessels (name VARCHAR(255), type VARCHAR(255), flag_state VARCHAR(255));   CREATE TABLE inspections (inspection_id INT, vessel_name VARCHAR(255), inspection_date DATE, region VARCHAR(255));   CREATE TABLE caribbean_sea (name VARCHAR(255), region_type VARCHAR(255));  INSERT INTO vessels (name, type, flag_state) VALUES ('VESSEL1', 'Cargo', 'Italy'), ('VESSEL2', 'Passenger', 'Spain');   INSERT INTO inspections (inspection_id, vessel_name, inspection_date, region) VALUES (1, 'VESSEL1', '2022-01-01', 'Caribbean Sea'), (2, 'VESSEL3', '2022-02-01', 'Caribbean Sea');   INSERT INTO caribbean_sea (name, region_type) VALUES ('VESSEL1', 'Caribbean Sea');

SELECT COUNT(*) FROM inspections i INNER JOIN caribbean_sea cs ON i.region = cs.region;


Question: Generate PostgreSQL SQL for: What week was the opponent the San Diego Chargers?

CREATE TABLE table_name_71 (week INTEGER, opponent VARCHAR)

SELECT AVG(week) FROM table_name_71 WHERE opponent = 'san diego chargers';


Question: Which community has the lowest obesity rate in Canada?

CREATE TABLE Community (Name TEXT, Country TEXT, ObesityRate FLOAT); INSERT INTO Community (Name, Country, ObesityRate) VALUES ('Community A', 'Canada', 20.0); INSERT INTO Community (Name, Country, ObesityRate) VALUES ('Community B', 'US', 25.0);

SELECT Name, ObesityRate FROM Community WHERE Country = 'Canada' ORDER BY ObesityRate ASC LIMIT 1;


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

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

SELECT count(*) FROM (SELECT pg_partition_root('ptif_test01')) AS _sub;


Question: PostgreSQL regression test 'transactions': Write the SELECT query (example 105).

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

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


Question: What is the average retail price of organic apples sold in the United States?

CREATE TABLE OrganicFruitsPrices (fruit_name TEXT, country TEXT, price NUMERIC); INSERT INTO OrganicFruitsPrices (fruit_name, country, price) VALUES ('Apples', 'United States', 2.95);

SELECT AVG(price) FROM OrganicFruitsPrices WHERE fruit_name = 'Apples' AND country = 'United States';


Question: Generate PostgreSQL SQL for: When Benall DFL is Goorambat with less than 13 wins, what is the least amount of losses?

CREATE TABLE table_name_15 (losses INTEGER, benalla_dfl VARCHAR, wins VARCHAR)

SELECT MIN(losses) FROM table_name_15 WHERE benalla_dfl = 'goorambat' AND wins < 13;


Question: What is the average energy efficiency rating for buildings constructed before 2000 in the 'energy_efficiency' schema?

CREATE TABLE energy_efficiency (id INT, building_id INT, rating FLOAT, construction_year INT); INSERT INTO energy_efficiency (id, building_id, rating, construction_year) VALUES (1, 1, 8.5, 1995), (2, 2, 9.2, 1999), (3, 3, 6.8, 2002);

SELECT AVG(rating) FROM energy_efficiency WHERE construction_year < 2000;


Question: Generate PostgreSQL SQL for: what is the date when the home team is st kilda?

CREATE TABLE table_name_26 (date VARCHAR, home_team VARCHAR)

SELECT date FROM table_name_26 WHERE home_team = 'st kilda';


Question: Which cities have more than 2000 affordable housing units?

CREATE TABLE affordable_housing (id INT, city VARCHAR(50), num_units INT); INSERT INTO affordable_housing (id, city, num_units) VALUES (1, 'Chicago', 3000), (2, 'Houston', 1500), (3, 'Chicago', 2500);

SELECT city FROM affordable_housing GROUP BY city HAVING SUM(num_units) > 2000;


Question: What is the total number of education volunteers?

CREATE TABLE Volunteers (id INT, program VARCHAR(25), volunteer_count INT); INSERT INTO Volunteers (id, program, volunteer_count) VALUES (1, 'Education', 50), (2, 'Health', 75), (3, 'Environment', 100), (4, 'Arts', 80), (5, 'Social Services', 120), (6, 'Education', 30), (7, 'Health', 60), (8, 'Environment', 80), (9, 'Arts', 90), (10, 'Social Services', 110);

SELECT SUM(volunteer_count) as total_education_volunteers FROM Volunteers WHERE program = 'Education';


Question: Generate PostgreSQL SQL for: What was the attendance during the week 1 match?

CREATE TABLE table_name_2 (attendance VARCHAR, week VARCHAR)

SELECT attendance FROM table_name_2 WHERE week = 1;


Question: What is the total biomass of fish in farms located in the Pacific Ocean and using recirculating aquaculture systems?

CREATE TABLE Farm (farm_id INT, location VARCHAR(255), system_type VARCHAR(255), PRIMARY KEY(farm_id)); INSERT INTO Farm (farm_id, location, system_type) VALUES (1, 'Pacific Ocean', 'Recirculating'), (2, 'Atlantic Ocean', 'Flow-through'), (3, 'Mediterranean Sea', 'Recirculating'); CREATE TABLE Fish (fish_id INT, farm_id INT, biomass FLOAT), (4, 1, 500), (5, 1, 600), (6, 3, 700);

SELECT SUM(f.biomass) FROM Fish f INNER JOIN Farm ff ON f.farm_id = ff.farm_id WHERE ff.location = 'Pacific Ocean' AND ff.system_type = 'Recirculating';


Question: Show an example of PostgreSQL ALTER TABLE (example 17).

ALTER TABLE distributors ADD CONSTRAINT distfk FOREIGN KEY (address) REFERENCES addresses (address);

Explanation: PostgreSQL ALTER TABLE command.


Question: Generate PostgreSQL SQL for: Name the total number of rank for 348cc petty manx

CREATE TABLE table_name_54 (rank VARCHAR, team VARCHAR)

SELECT COUNT(rank) FROM table_name_54 WHERE team = '348cc petty manx';


Question: Show a SQL definition from the citus project (foreign_key_to_reference_table, item 9).

CREATE VIEW table_fkeys_in_workers AS
SELECT
(json_populate_record(NULL::foreign_details,
  json_array_elements_text((run_command_on_workers( $$
    SELECT
      COALESCE(json_agg(row_to_json(d)), '[]'::json)
    FROM
      (
        SELECT
          distinct name,
          relid::regclass::text,
          refd_relid::regclass::text
        FROM
          table_fkey_cols
        WHERE
          "schema" = 'fkey_reference_table'
      )
      d $$ )).RESULT::json )::json )).* ;

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


Question: Insert a new record into the 'manufacturing_output' table with the chemical_name 'He' and quantity 1000, if 'He' is not already present in the 'chemicals' table.

CREATE TABLE manufacturing_output (id INT, chemical_name VARCHAR(255), quantity INT); CREATE TABLE chemicals (id INT, chemical_name VARCHAR(255), safety_rating INT); INSERT INTO chemicals (id, chemical_name, safety_rating) VALUES (1, 'H2O', 90), (2, 'CO2', 70); INSERT INTO manufacturing_output (id, chemical_name, quantity) VALUES (1, 'H2O', 1000), (2, 'CO2', 2000);

INSERT INTO manufacturing_output (chemical_name, quantity) SELECT 'He' as chemical_name, 1000 as quantity FROM chemicals WHERE chemical_name = 'He' LIMIT 1;


Question: What is the maximum number of buses per station in the 'south' region?

CREATE TABLE station_counts (region VARCHAR(10), num_stations INT, num_buses INT); INSERT INTO station_counts (region, num_stations, num_buses) VALUES ('east', 10, 50), ('west', 12, 60), ('north', 15, 75), ('south', 8, 40);

SELECT MAX(num_buses/num_stations) FROM station_counts WHERE region = 'south';


Question: what is the total number of electric vehicles in the world?

CREATE TABLE electric_vehicles (vehicle_id INT, vehicle_type VARCHAR(255), city VARCHAR(255), state VARCHAR(255));


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

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


Question: List all unique train routes in Tokyo with more than 1000 riders per day

CREATE TABLE tokyo_train (route_id INT, num_riders INT, route_name VARCHAR(255));

SELECT DISTINCT route_id, route_name FROM tokyo_train WHERE num_riders > 1000;


Question: Generate PostgreSQL SQL for: What was the original air date for season number 2?

CREATE TABLE table_21781578_2 (original_air_date VARCHAR, season_no VARCHAR)

SELECT original_air_date FROM table_21781578_2 WHERE season_no = 2;


Question: List all cities with their total energy consumption and the number of buildings in the 'RenewableEnergy' schema, grouped by continent.

CREATE TABLE RenewableEnergy.CityEnergy (city VARCHAR(50), energy_consumption FLOAT, num_buildings INT, continent VARCHAR(50)); INSERT INTO RenewableEnergy.CityEnergy (city, energy_consumption, num_buildings, continent) VALUES ('Sao Paulo', 123456.7, 2000, 'South America'), ('Mexico City', 150000.2, 3000, 'North America'), ('Rio de Janeiro', 105000.1, 1500, 'South America'), ('Buenos Aires', 140000.5, 2500, 'South America'), ('Lima', 180000.9, 3500, 'South America');

SELECT continent, city, SUM(energy_consumption) AS total_energy, num_buildings FROM RenewableEnergy.CityEnergy GROUP BY continent, city;


Question: Generate PostgreSQL SQL for: What is the label of release we are the rage with a cd format?

CREATE TABLE table_name_28 (label VARCHAR, format VARCHAR, release VARCHAR)

SELECT label FROM table_name_28 WHERE format = 'cd' AND release = 'we are the rage';


Question: Generate PostgreSQL SQL for: How many laps did Jo Bonnier driver when the grid number was smaller than 11?

CREATE TABLE table_name_6 (laps INTEGER, driver VARCHAR, grid VARCHAR)

SELECT SUM(laps) FROM table_name_6 WHERE driver = 'jo bonnier' AND grid < 11;


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

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


Question: Generate PostgreSQL SQL for: Who was the co-driver in 1970 for the race of Targa Florio?

CREATE TABLE table_name_46 (co_driver VARCHAR, year VARCHAR, race VARCHAR)

SELECT co_driver FROM table_name_46 WHERE year = 1970 AND race = 'targa florio';


Question: Show a query using PostgreSQL contrib extension 'hstore' (example 206).

select hstore_to_array('aa=>1, cq=>l, b=>g, fg=>NULL'::hstore);

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


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

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


Question: Generate PostgreSQL SQL for: What was the attendance for a week larger than 3, and an opponent of philadelphia eagles?

CREATE TABLE table_name_58 (attendance VARCHAR, week VARCHAR, opponent VARCHAR)

SELECT attendance FROM table_name_58 WHERE week > 3 AND opponent = 'philadelphia eagles';


Question: What is the maximum water consumption in a single day for all wastewater treatment plants?

CREATE TABLE wastewater_treatment_plants (plant_id INT, daily_consumption FLOAT, consumption_date DATE); INSERT INTO wastewater_treatment_plants (plant_id, daily_consumption, consumption_date) VALUES (1, 1000, '2022-03-01'), (2, 1500, '2022-03-02'), (3, 1200, '2022-03-03');

SELECT MAX(daily_consumption) FROM wastewater_treatment_plants;


Question: Generate PostgreSQL SQL for: What is the name of the second who has Caroline Reed as third?

CREATE TABLE table_name_96 (second VARCHAR, third VARCHAR)

SELECT second FROM table_name_96 WHERE third = 'caroline reed';


Question: Generate PostgreSQL SQL for: What is the total number of drivers who have cars constructed by Mercedes-Benz?

CREATE TABLE table_18893428_1 (driver VARCHAR, constructor VARCHAR)

SELECT COUNT(driver) FROM table_18893428_1 WHERE constructor = 'Mercedes-Benz';


Question: Generate PostgreSQL SQL for: how many time was points 6675?

CREATE TABLE table_26218783_7 (points VARCHAR)

SELECT COUNT(points) AS won FROM table_26218783_7 WHERE points = 6675;


Question: Generate PostgreSQL SQL for: Which Player has a To par of +9?

CREATE TABLE table_name_8 (player VARCHAR, to_par VARCHAR)

SELECT player FROM table_name_8 WHERE to_par = '+9';


Question: Generate PostgreSQL SQL for: Name the least bronze for silver being less than 0

CREATE TABLE table_name_45 (bronze INTEGER, silver INTEGER)

SELECT MIN(bronze) FROM table_name_45 WHERE silver < 0;


Question: What was the average monthly donation amount in the 'Health' project category for the past 12 months?

CREATE TABLE donations (donation_id INT, donation_amount DECIMAL, donation_date DATE, project_category VARCHAR(255)); INSERT INTO donations (donation_id, donation_amount, donation_date, project_category) VALUES (1, 500, '2022-01-05', 'Health'), (2, 300, '2022-01-10', 'Health'), (3, 700, '2022-02-15', 'Environment');

SELECT AVG(donation_amount) / 12 as avg_monthly_donation FROM donations WHERE project_category = 'Health' AND donation_date BETWEEN DATE_SUB(CURDATE(), INTERVAL 12 MONTH) AND CURDATE();


Question: Generate PostgreSQL SQL for: who was the winner /2nd for the British Champion Stakes race?

CREATE TABLE table_24850630_4 (winner_2nd VARCHAR, race VARCHAR)

SELECT winner_2nd FROM table_24850630_4 WHERE race = 'British Champion Stakes';


Question: What is the total number of military innovation projects for each department in the 'military_innovation' and 'departments' tables?

CREATE TABLE departments (department_id INT, department_name VARCHAR(50)); CREATE TABLE military_innovation (innovation_id INT, innovation_name VARCHAR(50), department_id INT); INSERT INTO departments VALUES (1, 'Research'), (2, 'Development'), (3, 'Procurement'); INSERT INTO military_innovation VALUES (1, 'Stealth Technology', 1), (2, 'Advanced Radar Systems', 1), (3, 'Electric Armored Vehicles', 2), (4, 'Automated Turrets', 2), (5, 'Conventional Rifles', 3), (6, 'Body Armor', 3);

SELECT d.department_name, COUNT(mi.innovation_id) as total_projects FROM departments d JOIN military_innovation mi ON d.department_id = mi.department_id GROUP BY d.department_name;


Question: Which regions had the highest total donation amounts in Q2 2021?

SELECT region_id, SUM(amount) as total_donations FROM donations WHERE donation_date BETWEEN '2021-04-01' AND '2021-06-30' GROUP BY region_id ORDER BY total_donations DESC;


Question: Write the DDL statement from PostgreSQL regression test 'collate' (example 109).

CREATE COLLATION coll_dup_chk (LC_CTYPE = "POSIX", LC_CTYPE = "NONSENSE", LC_COLLATE = "POSIX");

Explanation: DDL from PostgreSQL core regression test for Collate.


Question: Update the number of followers for a user from Brazil

CREATE TABLE users (id INT, username VARCHAR(255), followers INT, country VARCHAR(255));

UPDATE users SET followers = followers + 100 WHERE username = 'user_brazil' AND country = 'Brazil';


Question: Generate PostgreSQL SQL for: How many locations have a school that is nicknamed the Panthers?

CREATE TABLE table_262560_2 (location VARCHAR, nickname VARCHAR)

SELECT COUNT(location) FROM table_262560_2 WHERE nickname = 'Panthers';


Question: What is the most popular activity among male members in their 50s?

CREATE TABLE members (id INT, age INT, gender VARCHAR(10)); INSERT INTO members (id, age, gender) VALUES (1, 52, 'Male'); CREATE TABLE workouts (id INT, member_id INT, activity VARCHAR(50), duration INT); INSERT INTO workouts (id, member_id, activity, duration) VALUES (1, 1, 'Swimming', 60);

SELECT activity, COUNT(*) AS count FROM members JOIN workouts ON members.id = workouts.member_id WHERE members.gender = 'Male' AND members.age BETWEEN 50 AND 59 GROUP BY activity ORDER BY count DESC LIMIT 1;


Question: Update the 'capacity_mw' value to 30 in the 'energy_storage' table where the 'technology' is 'Lithium-ion'

CREATE TABLE energy_storage (id INT PRIMARY KEY, technology VARCHAR(255), capacity_mw FLOAT, country VARCHAR(255));

UPDATE energy_storage SET capacity_mw = 30 WHERE technology = 'Lithium-ion';


Question: Generate PostgreSQL SQL for: Who is the Opponent when the Score is 2-8?

CREATE TABLE table_name_16 (opponent VARCHAR, score VARCHAR)

SELECT opponent FROM table_name_16 WHERE score = '2-8';


Question: Generate PostgreSQL SQL for: What club had a score of 18.1?

CREATE TABLE table_name_87 (club VARCHAR, score VARCHAR)

SELECT club FROM table_name_87 WHERE score = '18.1';


Question: Find the total number of streams for artists from Africa in 2021.

CREATE TABLE streams (id INT, artist VARCHAR(50), country VARCHAR(50), streams INT, year INT); INSERT INTO streams (id, artist, country, streams, year) VALUES (1, 'Burna Boy', 'Nigeria', 4000000, 2021); INSERT INTO streams (id, artist, country, streams, year) VALUES (2, 'Wizkid', 'Nigeria', 5000000, 2021); INSERT INTO streams (id, artist, country, streams, year) VALUES (3, 'Angélique Kidjo', 'Benin', 3000000, 2021); INSERT INTO streams (id, artist, country, streams, year) VALUES (4, 'Tiwa Savage', 'Nigeria', 6000000, 2021); INSERT INTO streams (id, artist, country, streams, year) VALUES (5, 'Davido', 'Nigeria', 7000000, 2021);

SELECT SUM(streams) FROM streams WHERE country IN (SELECT DISTINCT country FROM artists WHERE continent = 'Africa') AND year = 2021;


Question: What is the maximum capacity of the largest hotel in Brazil?

CREATE TABLE Hotels (id INT, name TEXT, location TEXT, capacity INT); INSERT INTO Hotels (id, name, location, capacity) VALUES (1, 'Hotel Rio', 'Rio de Janeiro, Brazil', 800), (2, 'Hotel Sao Paulo', 'Sao Paulo, Brazil', 1000), (3, 'Hotel Amazon', 'Amazonas, Brazil', 1200);

SELECT MAX(capacity) FROM Hotels WHERE location LIKE '%Brazil%';


Question: What is the total number of employees in each mine type?

CREATE TABLE labor_productivity (id INT, mine_id INT, type TEXT, employees INT); INSERT INTO labor_productivity (id, mine_id, type, employees) VALUES (1, 1, 'Gold', 50), (2, 2, 'Silver', 25), (3, 3, 'Bronze', 15), (4, 4, 'Platinum', 40);

SELECT type, SUM(employees) as total_employees FROM labor_productivity GROUP BY type;


Question: What is the average daily energy production (in MWh) for each wind farm in the month of January 2021?

CREATE TABLE wind_farms (name VARCHAR(50), location VARCHAR(50), capacity FLOAT, primary key (name)); INSERT INTO wind_farms (name, location, capacity) VALUES ('Farm A', 'California', 100), ('Farm B', 'Texas', 150), ('Farm C', 'Oregon', 200); CREATE TABLE production (wind_farm VARCHAR(50), date DATE, energy_production FLOAT, primary key (wind_farm, date), foreign key (wind_farm) references wind_farms(name)); INSERT INTO production (wind_farm, date, energy_production) VALUES ('Farm A', '2021-01-01', 2500), ('Farm A', '2021-01-02', 2400), ('Farm B', '2021-01-01', 3500), ('Farm B', '2021-01-02', 3700), ('Farm C', '2021-01-01', 4500), ('Farm C', '2021-01-02', 4300);

SELECT wind_farm, AVG(energy_production) as avg_daily_production FROM production WHERE date BETWEEN '2021-01-01' AND '2021-01-31' GROUP BY wind_farm, EXTRACT(MONTH FROM date), EXTRACT(YEAR FROM date);


Question: Generate PostgreSQL SQL for: PER is the IATA for which city?

CREATE TABLE table_name_84 (city VARCHAR, iata VARCHAR)

SELECT city FROM table_name_84 WHERE iata = 'per';


Question: What are the common ethical manufacturing practices in factories owned by women or non-binary individuals?

CREATE TABLE factories (factory_id INT, name TEXT, location TEXT, owner TEXT, ethical_manufacturing BOOLEAN); INSERT INTO factories (factory_id, name, location, owner, ethical_manufacturing) VALUES (1, 'Factory A', 'City A', 'Female', true), (2, 'Factory B', 'City B', 'Male', false), (3, 'Factory C', 'City C', 'Non-binary', true), (4, 'Factory D', 'City D', 'Female', false);

SELECT f1.owner, i1.ethical_manufacturing FROM factories f1 JOIN factories i1 ON f1.owner = i1.owner WHERE f1.owner IN ('Female', 'Non-binary') GROUP BY f1.owner, i1.ethical_manufacturing HAVING COUNT(*) > 1;


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

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


Question: What is the average number of visits per vessel for vessels that have visited 'Port G'?

CREATE TABLE ports (port_id INT, port_name TEXT, country TEXT); INSERT INTO ports (port_id, port_name, country) VALUES (1, 'Port A', 'USA'), (2, 'Port B', 'Canada'), (3, 'Port C', 'USA'), (4, 'Port D', 'Mexico'), (5, 'Port E', 'Brazil'), (6, 'Port F', 'Chile'), (7, 'Port G', 'Argentina'); CREATE TABLE visits (visit_id INT, vessel_id INT, port_id INT); INSERT INTO visits (visit_id, vessel_id, port_id) VALUES (1, 1, 1), (2, 2, 1), (3, 1, 2), (4, 2, 2), (5, 4, 5), (6, 3, 7), (7, 2, 7), (8, 1, 7);

SELECT AVG(visits_per_vessel) FROM (SELECT COUNT(vessel_id) AS visits_per_vessel FROM visits WHERE port_id = (SELECT port_id FROM ports WHERE port_name = 'Port G') GROUP BY vessel_id) AS subquery;


Question: What is the number of cases of malaria in Kenya in 2017?

CREATE TABLE infectious_diseases_2 (id INT, disease TEXT, state TEXT, year INT, cases INT); INSERT INTO infectious_diseases_2 (id, disease, state, year, cases) VALUES (1, 'malaria', 'Kenya', 2017, 100);

SELECT disease, SUM(cases) as num_cases FROM infectious_diseases_2 WHERE state = 'Kenya' AND year = 2017 GROUP BY disease;


Question: Generate PostgreSQL SQL for: Which Barrel twist has a Stock of canadian 3rd generation and a Hand guards of short ribbed?

CREATE TABLE table_name_33 (barrel_twist VARCHAR, stock VARCHAR, hand_guards VARCHAR)

SELECT barrel_twist FROM table_name_33 WHERE stock = 'canadian 3rd generation' AND hand_guards = 'short ribbed';


Question: Generate PostgreSQL SQL for: What player has The United States as the country, with t2 as the place?

CREATE TABLE table_name_9 (player VARCHAR, country VARCHAR, place VARCHAR)

SELECT player FROM table_name_9 WHERE country = 'united states' AND place = 't2';


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

CREATE FUNCTION isnge(ean13, isbn13)
	RETURNS boolean
	AS 'int8ge'
	LANGUAGE 'internal'
	IMMUTABLE STRICT
	PARALLEL SAFE;

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


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

SELECT jsonb_populate_record(row(1,2)::jb_ordered_pair, '{"x": 1, "y": 0}');

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

SELECT count(*) FROM (SELECT jsonb_populate_record(row(1,2)::jb_ordered_pair, '{"x": 1, "y": 0}')) AS _sub;


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

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

SELECT count(*) FROM (select * from jsonb_path_query('[1,"1",2,"2",null]', '$[*] ? (@ == "1")')) AS _sub;


Question: Generate PostgreSQL SQL for: When did the team score 21 goals?

CREATE TABLE table_name_67 (date VARCHAR, goal VARCHAR)

SELECT date FROM table_name_67 WHERE goal = 21;


Question: What is the maximum donation amount per organization, for organizations that have received donations?

CREATE TABLE donors (id INT, name TEXT, organization TEXT, country TEXT);CREATE TABLE donations (id INT, donor_id INT, amount DECIMAL(10,2)); INSERT INTO donors (id, name, organization, country) VALUES (1, 'Donor A', 'Organization 1', 'Country A'), (2, 'Donor B', 'Organization 2', 'Country A'), (3, 'Donor C', 'Organization 3', 'Country B'), (4, 'Donor D', 'Organization 4', 'Country C'); INSERT INTO donations (id, donor_id, amount) VALUES (1, 1, 500.00), (2, 1, 750.00), (3, 2, 300.00), (4, 3, 1000.00), (5, 4, 250.00);

SELECT donors.organization, MAX(donations.amount) FROM donors INNER JOIN donations ON donors.id = donations.donor_id GROUP BY donors.organization;


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

SELECT count(*) FROM int8tmp WHERE a  = 464571291354841;

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


Question: What is the average safety violation cost per chemical plant in India?

CREATE TABLE chemical_plants (plant_id INT, plant_name VARCHAR(50), country VARCHAR(50), safety_violation_cost DECIMAL(10,2)); INSERT INTO chemical_plants (plant_id, plant_name, country, safety_violation_cost) VALUES (1, 'Plant A', 'India', 5000), (2, 'Plant B', 'India', 7000), (3, 'Plant C', 'USA', 3000);

SELECT AVG(safety_violation_cost) FROM chemical_plants WHERE country = 'India';


Question: How many mobile customers are there in each country?

CREATE TABLE mobile_customers (customer_id INT, country VARCHAR(20)); INSERT INTO mobile_customers (customer_id, country) VALUES (1, 'USA'), (2, 'Canada'), (3, 'Mexico'), (4, 'USA'), (5, 'Canada');

SELECT country, COUNT(*) FROM mobile_customers GROUP BY country;


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

SELECT objtype, objname, label FROM pg_seclabels
    WHERE provider = 'selinux' AND objtype = 'table' AND objname in ('t1', 't2', 't3',
                                                                     'tpart',
																	 'tpart_ones',
																	 'tpart_tens')
    ORDER BY objname COLLATE "C" ASC;

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


Question: What is the average popularity of products in each size per month?

CREATE TABLE trend (id INT, product_id INT, popularity INT, date DATE); INSERT INTO trend (id, product_id, popularity, date) VALUES (1, 1, 100, '2023-01-01'); CREATE TABLE size (id INT, size VARCHAR(50)); INSERT INTO size (id, size) VALUES (1, 'Small'), (2, 'Medium'), (3, 'Large');

SELECT s.size, AVG(t.popularity) as avg_popularity, DATE_TRUNC('month', t.date) as month FROM trend t JOIN product p ON t.product_id = p.id JOIN size s ON p.size = s.size GROUP BY month, s.size ORDER BY month;


Question: Generate PostgreSQL SQL for: What are the id and name of the photos for mountains?

CREATE TABLE photos (mountain_id VARCHAR); CREATE TABLE mountain (id VARCHAR, name VARCHAR, height INTEGER)

SELECT T1.id, T1.name FROM mountain AS T1 JOIN photos AS T2 ON T1.id = T2.mountain_id WHERE T1.height > 4000;


Question: Generate PostgreSQL SQL for: What country is player ed sneed, who has a to par of +3, from?

CREATE TABLE table_name_70 (country VARCHAR, to_par VARCHAR, player VARCHAR)

SELECT country FROM table_name_70 WHERE to_par = '+3' AND player = 'ed sneed';


Question: Generate PostgreSQL SQL for: What are the won games with losing bonus of 0?

CREATE TABLE table_13758945_1 (won VARCHAR, losing_bonus VARCHAR)

SELECT won FROM table_13758945_1 WHERE losing_bonus = '0';


Question: Generate PostgreSQL SQL for: Name the season for position 4th

CREATE TABLE table_25375093_1 (season VARCHAR, position VARCHAR)

SELECT COUNT(season) FROM table_25375093_1 WHERE position = '4th';


Question: PostgreSQL regression test 'int8': Write the SELECT query (example 42).

SELECT * FROM INT8_TBL WHERE '123'::int2 >= q1;

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

SELECT count(*) FROM (SELECT * FROM INT8_TBL WHERE '123'::int2 >= q1) AS _sub;


Question: pgTAP test for Functap (assertion 319).

-- Test diagnostics
SELECT * FROM check_test(
    is_window( 'nonesuch'::name, 'whatever' ),
    false,
    'is_window(nowin, desc)',
    'whatever',
    '    Function nonesuch() does not exist'
);

Explanation: SQL assertion from pgTAP test suite for Functap.


Question: What is the average rating of cruelty-free eyeshadows?

CREATE TABLE product_rating (product_id INT, rating INT, cruelty_free BOOLEAN); INSERT INTO product_rating (product_id, rating, cruelty_free) VALUES (1, 4, true), (2, 3, false), (3, 5, true), (4, 4, false), (5, 5, true); CREATE TABLE product (product_id INT, product_name VARCHAR(30), product_type VARCHAR(30)); INSERT INTO product (product_id, product_name, product_type) VALUES (1, 'Eyeshadow', 'Powder'), (2, 'Foundation', 'Liquid'), (3, 'Lipstick', 'Matte'), (4, 'Moisturizer', 'Cream'), (5, 'Eyeshadow', 'Cream');

SELECT AVG(rating) as avg_rating FROM product_rating JOIN product ON product_rating.product_id = product.product_id WHERE cruelty_free = true AND product_type = 'Eyeshadow';


Question: Write the DDL statement from PostgreSQL regression test 'update' (example 214).

CREATE TABLE list_parted (
	a text,
	b int
) PARTITION BY list (a);

Explanation: DDL from PostgreSQL core regression test for Update.


Question: pgTAP test for Hastap (assertion 40).

SELECT * FROM check_test(
    hasnt_table( '__SDFSDFD__', 'lol'::name ),
    true,
    'hasnt_table(non-existent schema, tab)',
    'Table "__SDFSDFD__".lol should not exist',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Hastap.


Question: PostgreSQL regression test 'xml': Write the SELECT query (example 186).

SELECT COUNT(id) FROM xmltest, query WHERE xmlexists(expr PASSING BY REF data);

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

SELECT count(*) FROM (SELECT COUNT(id) FROM xmltest, query WHERE xmlexists(expr PASSING BY REF data)) AS _sub;


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

SELECT '          -INFINiTY   '::float4;

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

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


Question: Write the DML statement from PostgreSQL regression test 'incremental_sort' (example 124).

insert into prt_tbl select i%200, i from generate_series(1,1000)i;

Explanation: DML from PostgreSQL core regression test for Incremental Sort.


Question: PostgreSQL regression test 'privileges': Write the SELECT query (example 152).

SELECT * FROM atest2 WHERE ( col1 IN ( SELECT b FROM atest1 ) );

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

SELECT count(*) FROM (SELECT * FROM atest2 WHERE ( col1 IN ( SELECT b FROM atest1 ) )) AS _sub;


Question: PL/pgSQL test: Plpgsql Domain (example 31).

SELECT * FROM test_argresult_array_domain(ARRAY[0, 100]::ordered_pair_domain);

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


Question: PostgreSQL regression test 'foreign_key': Write the SELECT query (example 505).

select conname from pg_constraint where conrelid = 'fktable2'::regclass order by conname;

Explanation: Regression test for Foreign Key in PostgreSQL core test suite.

SELECT count(*) FROM (select conname from pg_constraint where conrelid = 'fktable2'::regclass order by conname) AS _sub;


Question: PL/pgSQL test: Pltcl Setup (example 4).

create function tcl_argisnull(text) returns bool as '
    argisnull 1
' language pltcl;

Explanation: PL/pgSQL example from PostgreSQL source test for Pltcl Setup.


Question: Write the DML statement from PostgreSQL regression test 'sequence' (example 38).

INSERT INTO serialTest2 (f1, f6)
  VALUES ('bogus', -9223372036854775809);

Explanation: DML from PostgreSQL core regression test for Sequence.


Question: pgTAP test for Resultset (assertion 93).

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

Explanation: SQL assertion from pgTAP test suite for Resultset.


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

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

SELECT count(*) FROM (SELECT to_date('-100000000', 'CC')) AS _sub;


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

CREATE SEQUENCE sequence_testx INCREMENT BY -1 START 10;

Explanation: DDL from PostgreSQL core regression test for Sequence.


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

INSERT INTO d_star (class, a, b, c)
   VALUES ('d', 8, 'stumble'::text, 'hi koko'::name);

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


Question: PostgreSQL regression test 'errors': Write the SELECT query (example 10).

select null from pg_database group by grouping sets (()) for update;

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

SELECT count(*) FROM (select null from pg_database group by grouping sets (()) for update) AS _sub;


Question: pgTAP test for Aretap (assertion 108).

SELECT * FROM check_test(
    languages_are( array_append(___mylangs(''), 'plomgwtf'), 'whatever' ),
    false,
    'languages_are(languages, desc) missing',
    'whatever',
    '    Missing languages:
        plomgwtf'
);

Explanation: SQL assertion from pgTAP test suite for Aretap.


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

create function simple1.simpletarget(int) returns int language plpgsql
as $$begin return $1; end$$;

create function simpletarget(int) returns int language plpgsql
as $$begin return $1 + 100; end$$;

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


Question: PostgreSQL regression test 'rowsecurity': Write the SELECT query (example 830).

SELECT attname, most_common_vals FROM pg_stats
  WHERE tablename = 'current_check'
  ORDER BY 1;

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

SELECT count(*) FROM (SELECT attname, most_common_vals FROM pg_stats
  WHERE tablename = 'current_check'
  ORDER BY 1) AS _sub;


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

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

SELECT count(*) FROM (select array_fill('juhu'::text, array[3,3])) AS _sub;


Question: Write the DML statement from PostgreSQL regression test 'timestamptz' (example 38).

INSERT INTO TIMESTAMPTZ_TBL VALUES ('1997-02-10 17:32:01-08');

Explanation: DML from PostgreSQL core regression test for Timestamptz.


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

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


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

begin
	new.description = 'updated in trigger';

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


Question: PostgreSQL regression test 'int8': Write the SELECT query (example 139).

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


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

SELECT JSON_QUERY(jsonb 'null', '$ts' PASSING timestamptz '2018-02-21 12:34:56 +10' AS ts RETURNING json);

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

SELECT count(*) FROM (SELECT JSON_QUERY(jsonb 'null', '$ts' PASSING timestamptz '2018-02-21 12:34:56 +10' AS ts RETURNING json)) AS _sub;


Question: pgTAP test for Functap (assertion 275).

SELECT * FROM check_test(
    isnt_window( 'pg_catalog', 'dense_rank', '{}'::name[] ),
    false,
    'isnt_window(schema, win, noargs)',
    'Function pg_catalog.dense_rank() should not be a window function',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Functap.


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

CREATE TABLE parted_uniq_tbl_2 PARTITION OF parted_uniq_tbl FOR VALUES FROM (20) TO (30);

Explanation: DDL from PostgreSQL core regression test for Constraints.


Question: pgTAP test for Aretap (assertion 122).

SELECT * FROM check_test(
    rules_are( 'public', 'fou', ARRAY['ins_me', 'upd_me'] ),
    true,
    'rules_are(schema, table, rules)',
    'Relation public.fou should have the correct rules',
    ''
);


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

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


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

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

SELECT count(*) FROM (SELECT ((SELECT 2) UNION SELECT 2)) AS _sub;


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

-- Create the operator class
CREATE OPERATOR CLASS gist_time_ops
DEFAULT FOR TYPE time USING gist
AS
	OPERATOR	1	<  ,
	OPERATOR	2	<= ,
	OPERATOR	3	=  ,
	OPERATOR	4	>= ,
	OPERATOR	5	>  ,
	OPERATOR	6	<> ,
	OPERATOR	15	<-> FOR ORDER BY pg_catalog.interval_ops ,
	FUNCTION	1	gbt_time_consistent (internal, time, int2, oid, internal),
	FUNCTION	2	gbt_time_union (internal, internal),
	FUNCTION	3	gbt_time_compress (internal),
	FUNCTION	4	gbt_decompress (internal),
	FUNCTION	5	gbt_time_penalty (internal, internal, internal),
	FUNCTION	6	gbt_time_picksplit (internal, internal),
	FUNCTION	7	gbt_time_same (gbtreekey16, gbtreekey16, internal),
	FUNCTION	8	gbt_time_distance (internal, time, int2, oid, internal),
	FUNCTION	9	gbt_time_fetch (internal),
	FUNCTION	11	gbt_time_sortsupport (internal),
	FUNCTION	12 ("any", "any") gist_translate_cmptype_btree (int),
	STORAGE		gbtreekey16;

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


Question: Write the DDL statement from PostgreSQL regression test 'without_overlaps' (example 392).

CREATE TABLE temporal_rng2 (
  id1 int4range,
  id2 int4range,
  valid_at daterange,
  CONSTRAINT temporal_rng2_pk PRIMARY KEY (id1, id2, valid_at WITHOUT OVERLAPS)
);

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


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

SELECT ts_rank_cd(' a:1 s:2B d g'::tsvector, 'a & s');

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

SELECT count(*) FROM (SELECT ts_rank_cd(' a:1 s:2B d g'::tsvector, 'a & s')) AS _sub;


Question: PostgreSQL regression test 'stats': Write the SELECT query (example 248).

SELECT wal_bytes > :wal_bytes_before FROM pg_stat_wal;

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

SELECT count(*) FROM (SELECT wal_bytes > :wal_bytes_before FROM pg_stat_wal) AS _sub;


Question: PostgreSQL regression test 'polymorphism': Write the SELECT query (example 204).

select formarray(1.1, variadic array[1.2,55.5]);

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

SELECT count(*) FROM (select formarray(1.1, variadic array[1.2,55.5])) AS _sub;


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

create table pk51 partition of pk5 for values from (4000) to (4500);

Explanation: DDL from PostgreSQL core regression test for Indexing.


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

DROP FUNCTION IF EXISTS test_function_exists(int, text, int[]);

Explanation: PL/pgSQL object from PostgreSQL core test for Drop If Exists.


Question: pgTAP test for Ownership (assertion 59).

SELECT * FROM check_test(
    view_owner_is('public', '__not__someview', current_user, 'mumble'),
	false,
    'view_owner_is(sch, non-view, user)',
    'mumble',
    '    View public.__not__someview does not exist'
);

Explanation: SQL assertion from pgTAP test suite for Ownership.


Question: Show a SQL definition from the zombodb project (_mappings, item 6).

CREATE TABLE zdb.type_mappings
(
    type_name  regtype               NOT NULL PRIMARY KEY,
    definition jsonb   DEFAULT NULL,
    is_default boolean DEFAULT false NOT NULL,
    funcid     regproc DEFAULT null
);

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


Question: PostgreSQL regression test 'truncate': Write the SELECT query (example 151).

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

SELECT count(*) FROM (select tp_ins_data()) AS _sub;


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

INSERT INTO num_exp_add VALUES (4,8,'7874342.4119');

Explanation: DML from PostgreSQL core regression test for Numeric.


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

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


Question: pgTAP test for Hastap (assertion 207).

SELECT * FROM check_test(
  has_leftop( '+', 'text', 'inte', 'desc' ),
  false,
  'has_leftop( name, right, result, desc ) fail',
  'desc',
  ''
);

Explanation: SQL assertion from pgTAP test suite for Hastap.


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

SELECT setweight('a:1,3A asd:1C w:5,6,12B,13A zxc:81,222A,567'::tsvector, 'c');

SELECT count(*) FROM (SELECT setweight('a:1,3A asd:1C w:5,6,12B,13A zxc:81,222A,567'::tsvector, 'c')) AS _sub;


Question: PostgreSQL regression test 'name': Write the SELECT query (example 19).

SELECT c.f1 FROM NAME_TBL c WHERE c.f1 !~ '.*';

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

SELECT count(*) FROM (SELECT c.f1 FROM NAME_TBL c WHERE c.f1 !~ '.*') AS _sub;


Question: Write the DDL statement from PostgreSQL regression test 'partition_merge' (example 118).

CREATE TABLE sales_apr2022_10_20 PARTITION OF sales_apr2022 FOR VALUES FROM ('2022-04-10') TO ('2022-04-20');

Explanation: DDL from PostgreSQL core regression test for Partition Merge.


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

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


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

/* contrib/btree_gin/btree_gin--1.0.sql */

-- complain if script is sourced in psql, rather than via CREATE EXTENSION
\echo Use "CREATE EXTENSION btree_gin" to load this file. \quit

CREATE FUNCTION gin_btree_consistent(internal, int2, anyelement, int4, internal, internal)
RETURNS bool
AS 'MODULE_PATHNAME'
LANGUAGE C STRICT IMMUTABLE;


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

ALTER EXTENSION pgtap ADD FUNCTION _ckeys ( NAME, CHAR );

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


Question: PostgreSQL regression test 'stats': Write the SELECT query (example 381).

SELECT sum(evictions) + sum(reuses) + sum(extends) + sum(fsyncs) + sum(reads) + sum(writes) + sum(writebacks) + sum(hits) AS my_io_stats_post_reset
  FROM pg_stat_get_backend_io(pg_backend_pid()) \gset
-- pg_stat_reset_shared() did not reset backend IO stats
SELECT :my_io_stats_pre_reset <= :my_io_stats_post_reset;

SELECT count(*) FROM (SELECT sum(evictions) + sum(reuses) + sum(extends) + sum(fsyncs) + sum(reads) + sum(writes) + sum(writebacks) + sum(hits) AS my_io_stats_post_reset
  FROM pg_stat_get_backend_io(pg_backend_pid()) \gset
-- pg_stat_reset_shared() did not reset backend IO stats
SELECT :my_io_stats_pre_reset <= :my_io_stats_post_reset) AS _sub;


Question: PostgreSQL regression test 'money': Write the SELECT query (example 90).

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

SELECT count(*) FROM (SELECT (-12345678901234567)::money) AS _sub;


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

CREATE TABLE notnull_tbl4_cld () INHERITS (notnull_tbl4);

Explanation: DDL from PostgreSQL core regression test for Constraints.


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

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

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

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


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

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

SELECT count(*) FROM (select unnest('11 22 33'::oidvector)) AS _sub;


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

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


Question: PostgreSQL Plpgsql: show example 48.

DECLARE curs1 refcursor; curs2 CURSOR FOR SELECT * FROM tenk1; curs3 CURSOR (key integer) FOR SELECT * FROM tenk1 WHERE unique1 = key;

Explanation: Example from PostgreSQL documentation on Plpgsql.


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

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


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

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


Question: pgTAP test for Index (assertion 109).

SELECT * FROM check_test(
    is_indexed( 'public', 'sometab'::name, 'myint'::name ),
    false,
    'is_indexed( schema, table, column ) fail',
    'Should have an index on public.sometab(myint)',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Index.


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

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

SELECT count(*) FROM (select jsonb_path_query('[]', '$.number()')) AS _sub;


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

/* contrib/ltree/ltree--1.1.sql */

-- complain if script is sourced in psql, rather than via CREATE EXTENSION
\echo Use "CREATE EXTENSION ltree" to load this file. \quit

CREATE FUNCTION ltree_in(cstring)
RETURNS ltree
AS 'MODULE_PATHNAME'
LANGUAGE C STRICT IMMUTABLE PARALLEL SAFE;

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


Question: Write the DDL statement from PostgreSQL regression test 'stats_ext' (example 525).

CREATE STATISTICS mcv_lists_stats_3 ON (mod(c,5)) FROM mcv_lists;

Explanation: DDL from PostgreSQL core regression test for Stats Ext.


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

INSERT INTO num_exp_sub VALUES (8,7,'83103366');

Explanation: DML from PostgreSQL core regression test for Numeric.


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

SELECT test_json ->> 'field4' FROM test_jsonb WHERE json_type = 'object';

SELECT count(*) FROM (SELECT test_json ->> 'field4' FROM test_jsonb WHERE json_type = 'object') AS _sub;


Question: Show a query using PostgreSQL contrib extension 'intarray' (example 66).


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

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


Question: PostgreSQL Ddl: show example 2.

CREATE TABLE products ( product_no integer, name text, price numeric );

Explanation: Example from PostgreSQL documentation on Ddl.


Question: PostgreSQL regression test 'xml': Write the SELECT query (example 74).

SELECT xmlroot(xml '<foo/>', version no value, standalone yes);

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

SELECT count(*) FROM (SELECT xmlroot(xml '<foo/>', version no value, standalone yes)) AS _sub;


Question: Write the DDL statement from PostgreSQL regression test 'psql' (example 214).

create table child_20_30 partition of parent_tab
  for values from (20) to (30);

Explanation: DDL from PostgreSQL core regression test for Psql.


Question: pgTAP test for Enumtap (assertion 31).

SELECT * FROM check_test(
    enums_are( 'public', ARRAY['freddy'], 'whatever' ),
    false,
    'enums_are(schema, enums, desc) fail',
    'whatever',
    '    Extra types:
        bug_status
    Missing types:
        freddy'
);

Explanation: SQL assertion from pgTAP test suite for Enumtap.


Question: Write the DDL statement from PostgreSQL regression test 'create_table' (example 139).

CREATE TABLE fail_part PARTITION OF hash_parted FOR VALUES WITH (MODULUS 150, REMAINDER 3);

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


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

-- language_privs_are ( lang, user, privileges[] )
CREATE OR REPLACE FUNCTION language_privs_are ( NAME, NAME, NAME[] )
RETURNS TEXT AS $$
    SELECT language_privs_are(
        $1, $2, $3,
        'Role ' || quote_ident($2) || ' should be granted '
            || CASE WHEN $3[1] IS NULL THEN 'no privileges' ELSE array_to_string($3, ', ') END
            || ' on language ' || quote_ident($1)
    );
$$ LANGUAGE SQL;

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


Question: Write the DDL statement from PostgreSQL regression test 'brin_bloom' (example 62).

CREATE INDEX brin_summarize_bloom_idx ON brin_summarize_bloom USING brin (value) WITH (pages_per_range=2);

Explanation: DDL from PostgreSQL core regression test for Brin Bloom.


Question: Write the DDL statement from PostgreSQL regression test 'numeric_big' (example 16).

CREATE TABLE num_exp_sqrt (id int4, expected numeric(1000,800));

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


Question: Show a query using PostgreSQL contrib extension 'pgstattuple' (example 75).

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


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

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


Question: Write the DML statement from PostgreSQL regression test 'generated_stored' (example 115).

INSERT INTO gtest_varlena (a) VALUES('01234567890123456789');

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


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

SELECT interval '1 2:03:04.5678' hour to second(2);

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

SELECT count(*) FROM (SELECT interval '1 2:03:04.5678' hour to second(2)) AS _sub;


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

CREATE FUNCTION isngt(ismn13, ismn)
	RETURNS boolean
	AS 'int8gt'
	LANGUAGE 'internal'
	IMMUTABLE STRICT
	PARALLEL SAFE;


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

select sum(c) from gstest2
  group by grouping sets(grouping sets((a, (b))))
  order by 1 desc;

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

SELECT count(*) FROM (select sum(c) from gstest2
  group by grouping sets(grouping sets((a, (b))))
  order by 1 desc) AS _sub;


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

-- error functions
-- we run these with extra_float_digits = -1, to get consistently rounded
-- results on all platforms.
SET extra_float_digits = -1;

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


Question: PostgreSQL Textsearch: show example 40.

SELECT plainto_tsquery('english', 'The Fat Rats'); plainto_tsquery ----------------- 'fat' & 'rat';

Explanation: Example from PostgreSQL documentation on Textsearch.


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

SELECT jsonb_object_agg_unique_strict(i, null) OVER (ORDER BY i)
  FROM generate_series(1, 10) g(i);

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

SELECT count(*) FROM (SELECT jsonb_object_agg_unique_strict(i, null) OVER (ORDER BY i)
  FROM generate_series(1, 10) g(i)) AS _sub;


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

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

SELECT count(*) FROM (SELECT float4send('887745e-11'::float4)) AS _sub;


Question: Write the DML statement from PostgreSQL regression test 'float4' (example 5).

Explanation: DML from PostgreSQL core regression test for Float4.


Question: Show an example of PostgreSQL CREATE PUBLICATION (example 5).

CREATE PUBLICATION production_publication FOR TABLE users, departments, TABLES IN SCHEMA production;

Explanation: PostgreSQL CREATE PUBLICATION command.


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

INSERT INTO rls_test_src VALUES (1, 'src a');

Explanation: DML from PostgreSQL core regression test for Rowsecurity.


Question: pgTAP test for Pktap (assertion 33).

SELECT * FROM check_test(
    col_is_pk( 'argh', ARRAY['id', 'name'], 'id + name should be a pk' ),
    true,
    'col_is_pk( table, column[], description )',
    'id + name should be a pk',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Pktap.


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


Question: Write the DDL statement from PostgreSQL regression test 'triggers' (example 158).

create function trigger_nothing() returns trigger
  language plpgsql as $$ begin end; $$;
create trigger failed instead of update on parted_trig
  for each row execute procedure trigger_nothing();
create trigger failed after update on parted_trig
  referencing old table as old_table
  for each row execute procedure trigger_nothing();
drop table parted_trig;

--
-- Verify trigger creation for partitioned tables, and drop behavior
--
create table trigpart (a int, b int) partition by range (a);
create table trigpart1 partition of trigpart for values from (0) to (1000);
create trigger trg1 after insert on trigpart for each row execute procedure trigger_nothing();
create table trigpart2 partition of trigpart for values from (1000) to (2000);
create table trigpart3 (like trigpart);
alter table trigpart attach partition trigpart3 for values from (2000) to (3000);
create table trigpart4 partition of trigpart for values from (3000) to (4000) partition by range (a);
create table trigpart41 partition of trigpart4 for values from (3000) to (3500);
create table trigpart42 (like trigpart);
alter table trigpart4 attach partition trigpart42 for values from (3500) to (4000);
select tgrelid::regclass, tgname, tgfoid::regproc from pg_trigger
  where tgrelid::regclass::text like 'trigpart%' order by tgrelid::regclass::text;
drop trigger trg1 on trigpart1;	-- fail
drop trigger trg1 on trigpart2;	-- fail
drop trigger trg1 on trigpart3;	-- fail
drop table trigpart2;			-- ok, trigger should be gone in that partition
select tgrelid::regclass, tgname, tgfoid::regproc from pg_trigger
  where tgrelid::regclass::text like 'trigpart%' order by tgrelid::regclass::text;
drop trigger trg1 on trigpart;		-- ok, all gone
select tgrelid::regclass, tgname, tgfoid::regproc from pg_trigger
  where tgrelid::regclass::text like 'trigpart%' order by tgrelid::regclass::text;

-- check detach behavior
create trigger trg1 after insert on trigpart for each row execute procedure trigger_nothing();
\d trigpart3
alter table trigpart detach partition trigpart3;
drop trigger trg1 on trigpart3; -- fail due to "does not exist"
alter table trigpart detach partition trigpart4;
drop trigger trg1 on trigpart41; -- fail due to "does not exist"
drop table trigpart4;
alter table trigpart attach partition trigpart3 for values from (2000) to (3000);
alter table trigpart detach partition trigpart3;
alter table trigpart attach partition trigpart3 for values from (2000) to (3000);
drop table trigpart3;

select tgrelid::regclass::text, tgname, tgfoid::regproc, tgenabled, tgisinternal from pg_trigger
  where tgname ~ '^trg1' order by 1;
create table trigpart3 (like trigpart);
create trigger trg1 after insert on trigpart3 for each row execute procedure trigger_nothing();
\d trigpart3
alter table trigpart attach partition trigpart3 FOR VALUES FROM (2000) to (3000); -- fail
drop table trigpart3;

-- check display of unrelated triggers
create trigger samename after delete on trigpart execute function trigger_nothing();
create trigger samename after delete on trigpart1 execute function trigger_nothing();
\d trigpart1

drop table trigpart;
drop function trigger_nothing();

--
-- Verify that triggers are fired for partitioned tables
--
create table parted_stmt_trig (a int) partition by list (a);
create table parted_stmt_trig1 partition of parted_stmt_trig for values in (1);
create table parted_stmt_trig2 partition of parted_stmt_trig for values in (2);

create table parted2_stmt_trig (a int) partition by list (a);
create table parted2_stmt_trig1 partition of parted2_stmt_trig for values in (1);
create table parted2_stmt_trig2 partition of parted2_stmt_trig for values in (2);

create or replace function trigger_notice() returns trigger as $$
  begin
    raise notice 'trigger % on % % % for %', TG_NAME, TG_TABLE_NAME, TG_WHEN, TG_OP, TG_LEVEL;

Explanation: DDL from PostgreSQL core regression test for Triggers.


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

INSERT INTO timetzcmp (r_id,a) SELECT  2,count(*) FROM timetztmp WHERE a <= '07:46:45 GMT+3';

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


Question: pgTAP test for Functap (assertion 107).

Explanation: SQL assertion from pgTAP test suite for Functap.


Question: PostgreSQL Textsearch: show example 7.

SELECT title FROM pgweb WHERE to_tsvector('english', body) @@ to_tsquery('english', 'friend');


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

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


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

SELECT jsonb_build_array('a', NULL); -- ok
SELECT jsonb_build_array(VARIADIC NULL::text[]); -- ok
SELECT jsonb_build_array(VARIADIC '{}'::text[]); -- ok
SELECT jsonb_build_array(VARIADIC '{a,b,c}'::text[]); -- ok
SELECT jsonb_build_array(VARIADIC ARRAY['a', NULL]::text[]); -- ok
SELECT jsonb_build_array(VARIADIC '{1,2,3,4}'::text[]); -- ok
SELECT jsonb_build_array(VARIADIC '{1,2,3,4}'::int[]); -- ok
SELECT jsonb_build_array(VARIADIC '{{1,4},{2,5},{3,6}}'::int[][]); -- ok

SELECT jsonb_build_object('a',1,'b',1.2,'c',true,'d',null,'e',json '{"x": 3, "y": [1,2,3]}');

SELECT count(*) FROM (SELECT jsonb_build_array('a', NULL); -- ok
SELECT jsonb_build_array(VARIADIC NULL::text[]); -- ok
SELECT jsonb_build_array(VARIADIC '{}'::text[]); -- ok
SELECT jsonb_build_array(VARIADIC '{a,b,c}'::text[]); -- ok
SELECT jsonb_build_array(VARIADIC ARRAY['a', NULL]::text[]); -- ok
SELECT jsonb_build_array(VARIADIC '{1,2,3,4}'::text[]); -- ok
SELECT jsonb_build_array(VARIADIC '{1,2,3,4}'::int[]); -- ok
SELECT jsonb_build_array(VARIADIC '{{1,4},{2,5},{3,6}}'::int[][]); -- ok

SELECT jsonb_build_object('a',1,'b',1.2,'c',true,'d',null,'e',json '{"x": 3, "y": [1,2,3]}')) AS _sub;


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

INSERT INTO replication_example(somedata, text) VALUES (1, 5);

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


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

CREATE FUNCTION postgres_fdw_disconnect (text)
RETURNS bool
AS 'MODULE_PATHNAME'
LANGUAGE C STRICT PARALLEL RESTRICTED;

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


Question: Write the DDL statement from PostgreSQL regression test 'memoize' (example 45).

CREATE TABLE prt_p2 PARTITION OF prt FOR VALUES FROM (10) TO (20);

Explanation: DDL from PostgreSQL core regression test for Memoize.


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

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


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

CREATE FUNCTION test_type_conversion_float8(x float8) RETURNS float8 AS $$
plpy.info(x, type(x))
return x
$$ LANGUAGE plpython3u;

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


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

CREATE FUNCTION spi_prepared_plan_test_nested(a text) RETURNS text
	AS
'if "myplan" not in SD:
	q = "SELECT spi_prepared_plan_test_one(''%s'') as count" % a
	SD["myplan"] = plpy.prepare(q)
try:
	rv = plpy.execute(SD["myplan"])
	if len(rv):
		return rv[0]["count"]
except Exception as ex:
	plpy.error(str(ex))
return None
'
	LANGUAGE plpython3u;

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


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

select * from jsonb_to_recordset('[{"a":1,"b":"foo","d":false},{"a":2,"b":"bar","c":true}]')
    as x(a int, b text, c boolean);

SELECT count(*) FROM (select * from jsonb_to_recordset('[{"a":1,"b":"foo","d":false},{"a":2,"b":"bar","c":true}]')
    as x(a int, b text, c boolean)) AS _sub;


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

SELECT regexp_substr('abcabcabc', 'a.c', 2);

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

SELECT count(*) FROM (SELECT regexp_substr('abcabcabc', 'a.c', 2)) AS _sub;


Question: PostgreSQL regression test 'rules': Write the SELECT query (example 317).

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

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


Question: Write the DDL statement from PostgreSQL regression test 'create_table' (example 100).

CREATE TABLE part_bogus_expr_fail PARTITION OF list_parted FOR VALUES IN ((1+1) collate "POSIX");

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


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

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

SELECT count(*) FROM (SELECT to_number('CLXC', 'RN')) AS _sub;


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

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

SELECT count(*) FROM (select nextval('ts1')) AS _sub;


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

Explanation: DML from PostgreSQL core regression test for Numeric.


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

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

Explanation: DDL from PostgreSQL core regression test for Indexing.


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

INSERT INTO num_exp_add VALUES (4,5,'7815858.450391');


Question: PostgreSQL regression test 'xml': Write the SELECT query (example 147).

SELECT xpath(NULL, NULL) IS NULL FROM xmltest;

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

SELECT count(*) FROM (SELECT xpath(NULL, NULL) IS NULL FROM xmltest) AS _sub;


Question: Write the DML statement from PostgreSQL regression test 'aggregates' (example 181).

insert into minmaxtest values(11), (12);

Explanation: DML from PostgreSQL core regression test for Aggregates.


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

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


Question: PostgreSQL Textsearch: show example 6.

SELECT phraseto_tsquery('cats ate rats'); phraseto_tsquery ------------------------------- 'cat' <-> 'ate' <-> 'rat' SELECT phraseto_tsquery('the cats ate the rats'); phraseto_tsquery ------------------------------- 'cat' <-> 'ate' <2> 'rat';

Explanation: Example from PostgreSQL documentation on Textsearch.


Question: pgTAP test for Aretap (assertion 11).

CREATE VIEW public.vou AS SELECT * FROM fou;

Explanation: SQL assertion from pgTAP test suite for Aretap.


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

create table parted_replica_tab_1 partition of parted_replica_tab
  for values from (1) to (10) partition by range (id);


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

INSERT INTO itestv11 VALUES (10, 'xyz');

Explanation: DML from PostgreSQL core regression test for Identity.


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

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


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

CREATE FOREIGN DATA WRAPPER foo OPTIONS (testing '1');

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


Question: PostgreSQL regression test 'xml': Write the SELECT query (example 175).

SELECT COUNT(id) FROM xmltest WHERE xmlexists('/menu/beer' PASSING BY REF data BY REF);

SELECT count(*) FROM (SELECT COUNT(id) FROM xmltest WHERE xmlexists('/menu/beer' PASSING BY REF data BY REF)) AS _sub;


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

INSERT INTO entry (accession, txid) VALUES ('A00002', '1') ;

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


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

CREATE FUNCTION seg_lower(seg)
RETURNS float4
AS 'MODULE_PATHNAME'
LANGUAGE C STRICT IMMUTABLE PARALLEL SAFE;

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


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

ALTER EXTENSION pgtap ADD FUNCTION _definer ( NAME, NAME[] );

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


Question: PostgreSQL regression test 'stats_import': Write the SELECT query (example 232).

SELECT replace(e.n_distinct,   '}, ', E'},\n') AS n_distinct,
       replace(e.dependencies, '}, ', E'},\n') AS dependencies,
       replace(e.most_common_vals::text, '},', E'},\n ') AS mcvs,
       e.most_common_val_nulls,
       e.most_common_freqs, e.most_common_base_freqs
FROM pg_stats_ext AS e
WHERE e.statistics_schemaname = 'stats_import' AND
    e.statistics_name = 'test_mr_stat' AND
    e.inherited = false
\gx

-- Test the ability of pg_restore_extended_stats() to import all of the
-- statistic values from an extended statistic object that has been
-- populated via a regular ANALYZE.  This checks after the statistics
-- kinds supported by pg_restore_extended_stats().
--
-- Note: Keep this test at the bottom of the file, so as the amount of
-- statistics data handled is maximized.
ANALYZE stats_import.test;

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

SELECT count(*) FROM (SELECT replace(e.n_distinct,   '}, ', E'},\n') AS n_distinct,
       replace(e.dependencies, '}, ', E'},\n') AS dependencies,
       replace(e.most_common_vals::text, '},', E'},\n ') AS mcvs,
       e.most_common_val_nulls,
       e.most_common_freqs, e.most_common_base_freqs
FROM pg_stats_ext AS e
WHERE e.statistics_schemaname = 'stats_import' AND
    e.statistics_name = 'test_mr_stat' AND
    e.inherited = false
\gx

-- Test the ability of pg_restore_extended_stats() to import all of the
-- statistic values from an extended statistic object that has been
-- populated via a regular ANALYZE.  This checks after the statistics
-- kinds supported by pg_restore_extended_stats().
--
-- Note: Keep this test at the bottom of the file, so as the amount of
-- statistics data handled is maximized.
ANALYZE stats_import.test) AS _sub;


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

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


Question: Write the DML statement from PostgreSQL regression test 'vacuum' (example 2).

Explanation: DML from PostgreSQL core regression test for Vacuum.


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

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


Question: Write the DML statement from PostgreSQL regression test 'domain' (example 172).

insert into nulltest values ('a', 'b', 'c', 'd', 'a');

Explanation: DML from PostgreSQL core regression test for Domain.


Question: Write the DML statement from PostgreSQL regression test 'interval' (example 21).

INSERT INTO INTERVAL_TBL (f1) VALUES ('6 years');

Explanation: DML from PostgreSQL core regression test for Interval.


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

INSERT INTO temporal_rng3 (id, valid_at) VALUES ('[1,2)', daterange('2018-03-03', '2018-04-04'));

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


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

CREATE FUNCTION zdb.schema_version() RETURNS text LANGUAGE sql AS $$
SELECT '3000.2.5 (4704c7982040b2dd33d97334d3d4743082549630)'
$$;

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


Question: PostgreSQL regression test 'window': Write the SELECT query (example 54).

SELECT sum(unique1) over (rows between 2 preceding and 2 following),
	unique1, four
FROM tenk1 WHERE unique1 < 10;

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

SELECT count(*) FROM (SELECT sum(unique1) over (rows between 2 preceding and 2 following),
	unique1, four
FROM tenk1 WHERE unique1 < 10) AS _sub;


Question: Write the DML statement from PostgreSQL regression test 'copy' (example 5).

insert into copytest values(E'esc\\ape',E'a\\r\\\r\\\n\\nb',4);

Explanation: DML from PostgreSQL core regression test for Copy.


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

SELECT * FROM bt_page_items(get_raw_page('test1_a_idx', 1));

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


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

-- create statistics on expressions
CREATE STATISTICS func_deps_stat (dependencies) ON (a * 2), upper(b), (c + 1) FROM functional_dependencies;

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


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

SELECT timestamp with time zone 'J2452271 04:05:06+08';

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

SELECT count(*) FROM (SELECT timestamp with time zone 'J2452271 04:05:06+08') AS _sub;


Question: pgTAP test for Pgtap--1.3.0--1.3.1 (assertion 14).

-- has_pk( schema, table )
CREATE OR REPLACE FUNCTION has_pk ( NAME, NAME )
RETURNS TEXT AS $$
    SELECT has_pk( $1, $2, 'Table ' || quote_ident($1) || '.' || quote_ident($2) || ' should have a primary key' );
$$ LANGUAGE sql;

Explanation: SQL assertion from pgTAP test suite for Pgtap--1.3.0--1.3.1.


Question: PostgreSQL regression test 'alter_table': Write the SELECT query (example 649).

SELECT coninhcount, conislocal FROM pg_constraint WHERE conrelid = 'part_3_4'::regclass AND conname = 'check_a';

Explanation: Regression test for Alter Table in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT coninhcount, conislocal FROM pg_constraint WHERE conrelid = 'part_3_4'::regclass AND conname = 'check_a') AS _sub;


Question: PostgreSQL regression test 'int8': Write the SELECT query (example 28).

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

SELECT count(*) FROM (SELECT * FROM INT8_TBL WHERE 123 > q1) AS _sub;


Question: Write the DDL statement from PostgreSQL regression test 'partition_prune' (example 46).

create table rlp5_default partition of rlp5 default;

Explanation: DDL from PostgreSQL core regression test for Partition Prune.


Question: pgTAP test for Pgtap--1.3.0--1.3.1 (assertion 4).

-- col_type_is( schema, table, column, schema, type )
CREATE OR REPLACE FUNCTION col_type_is ( NAME, NAME, NAME, NAME, TEXT )
RETURNS TEXT AS $$
    SELECT col_type_is( $1, $2, $3, $4, $5, 'Column ' || quote_ident($1) || '.' || quote_ident($2)
        || '.' || quote_ident($3) || ' should be type ' || quote_ident($4) || '.' || $5);
$$ LANGUAGE SQL;


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

CREATE TYPE cube (
	INTERNALLENGTH = variable,
	INPUT = cube_in,
	OUTPUT = cube_out,
	ALIGNMENT = double
);

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


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

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


Question: PostgreSQL regression test 'with': Write the SELECT query (example 204).

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

SELECT count(*) FROM (SELECT * from id_alw1) AS _sub;


Question: Show a SQL definition from the timescaledb project (telemetry, item 5).

CREATE OR REPLACE FUNCTION _timescaledb_internal.test_telemetry_main_conn(text, text)
RETURNS BOOLEAN AS :MODULE_PATHNAME, 'ts_test_telemetry_main_conn' LANGUAGE C IMMUTABLE PARALLEL SAFE;

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


Question: pgTAP test for Pgtap--0.94.0--0.95.0 (assertion 22).

-- hasnt_materialized_view( materialized_view )
CREATE OR REPLACE FUNCTION hasnt_materialized_view ( NAME )
RETURNS TEXT AS $$
    SELECT hasnt_materialized_view( $1, 'Materialized view ' || quote_ident($1) || ' should not exist' );
$$ LANGUAGE SQL;

Explanation: SQL assertion from pgTAP test suite for Pgtap--0.94.0--0.95.0.


Question: Write the DDL statement from PostgreSQL regression test 'partition_join' (example 115).

CREATE TABLE prt2_m_p1 PARTITION OF prt2_m FOR VALUES FROM (0, 0) TO (250, 250);

Explanation: DDL from PostgreSQL core regression test for Partition Join.


Question: Show a SQL definition from the zombodb project (_postgis-support, item 4).

-- casting functions
    EXECUTE format('create or replace function zdb.geometry_to_json(%I.geometry, typmod integer DEFAULT -1) returns json parallel safe immutable strict language sql as $$
          SELECT CASE WHEN %I.postgis_typmod_type($2) = ''Point'' THEN
                    zdb.point_to_json(%I.st_transform($1, 4326)::point)::json
                 ELSE
                    %I.st_asgeojson(%I.st_transform($1, 4326))::json
                 END
          $$;',
      geojson_namespace, geojson_namespace, geojson_namespace, geojson_namespace, geojson_namespace);


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

CREATE FUNCTION gin_extract_query_char("char", internal, int2, internal, internal)
RETURNS internal
AS 'MODULE_PATHNAME'
LANGUAGE C STRICT IMMUTABLE;


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

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

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


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

SELECT f1 AS three FROM VARCHAR_TBL
UNION
SELECT CAST(f1 AS varchar) FROM CHAR_TBL
ORDER BY 1;

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

SELECT count(*) FROM (SELECT f1 AS three FROM VARCHAR_TBL
UNION
SELECT CAST(f1 AS varchar) FROM CHAR_TBL
ORDER BY 1) AS _sub;


Question: Write the DML statement from PostgreSQL regression test 'timestamptz' (example 86).

INSERT INTO TIMESTAMPTZ_TBL VALUES ('Feb 11 17:32:01 1997');

Explanation: DML from PostgreSQL core regression test for Timestamptz.


Question: pgTAP test for Throwtap (assertion 1).

\unset ECHO
\i test/setup.sql

SELECT plan(97);

Explanation: SQL assertion from pgTAP test suite for Throwtap.


Question: PL/pgSQL test: Plperl Array (example 18).

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


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

CREATE INDEX part_parent_i ON stats_import.part_parent(i);

Explanation: DDL from PostgreSQL core regression test for Stats Import.


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

create index on idxpart2 (a) where b > 1000;

Explanation: DDL from PostgreSQL core regression test for Indexing.


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

SELECT
	pg_advisory_lock(1), pg_advisory_lock_shared(2),
	pg_advisory_lock(1, 1), pg_advisory_lock_shared(2, 2);

Explanation: Regression test for Advisory Lock in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT
	pg_advisory_lock(1), pg_advisory_lock_shared(2),
	pg_advisory_lock(1, 1), pg_advisory_lock_shared(2, 2)) AS _sub;


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

-- Now the same test with plpgsql (since it depends on SPI which is different)
create or replace function max_xacttest() returns smallint language plpgsql as
'begin return max(a) from xacttest; end' stable;

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


Question: Show a SQL definition from the pgaudit project (pgaudit--18.0, item 1).

\echo Use "CREATE EXTENSION pgaudit" to load this file.\quit

CREATE FUNCTION pgaudit_ddl_command_end()
	RETURNS event_trigger
	SECURITY DEFINER
	SET search_path = pg_catalog, pg_temp
	LANGUAGE C
	AS 'MODULE_PATHNAME', 'pgaudit_ddl_command_end';

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


Question: Show an example of PostgreSQL INSERT (example 9).

WITH upd AS ( UPDATE employees SET sales_count = sales_count + 1 WHERE id = (SELECT sales_person FROM accounts WHERE name = 'Acme Corporation') RETURNING * ) INSERT INTO employees_log SELECT *, current_timestamp FROM upd;

Explanation: PostgreSQL INSERT command.


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

INSERT INTO spill_test SELECT 'serialize-subbig--1:'||g.i FROM generate_series(1, 5000) g(i);

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


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

Explanation: DML from PostgreSQL core regression test for Numeric.


Question: PostgreSQL regression test 'text': Write the SELECT query (example 37).

select format('INSERT INTO %I VALUES(%L,%L)', 'mytab', NULL, 'Hello');

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

SELECT count(*) FROM (select format('INSERT INTO %I VALUES(%L,%L)', 'mytab', NULL, 'Hello')) AS _sub;


Question: Write the DDL statement from PostgreSQL regression test 'join' (example 496).

CREATE TEMP TABLE parted_b1 partition of parted_b for values from (0) to (10);

Explanation: DDL from PostgreSQL core regression test for Join.


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

select ' ( " a " " a ", " z " " z " )  '::textrange;

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

SELECT count(*) FROM (select ' ( " a " " a ", " z " " z " )  '::textrange) AS _sub;


Question: PL/pgSQL test: Plpgsql Domain (example 23).

SELECT * FROM test_argresult_nnint(null, 20);

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


Question: pgTAP test for Coltap (assertion 90).

-- Make sure that it works when the default is a reserved SQL expression.
CREATE OR REPLACE FUNCTION ckreserve() RETURNS SETOF TEXT LANGUAGE PLPGSQL AS $$
DECLARE
    funcs text[] := '{CURRENT_CATALOG,CURRENT_ROLE,CURRENT_SCHEMA,CURRENT_USER,SESSION_USER,USER,CURRENT_DATE,CURRENT_TIME,CURRENT_TIMESTAMP,LOCALTIME,LOCALTIMESTAMP}';
    cols  TEXT[] := '{ccat,crole,csch,cuser,suser,auser,cdate,ctime,ctstz,ltime,ltstz}';
    exp   TEXT[] := funcs;
    tap           record;
    last_index    INTEGER;
BEGIN
    last_index := array_upper(funcs, 1);
    IF pg_version_num() < 100000 THEN
       -- Prior to PostgreSQL 10, these were functions rendered with paretheses or as casts.
       exp := ARRAY['current_database()','"current_user"()','"current_schema"()','"current_user"()','"session_user"()','"current_user"()','(''now''::text)::date','(''now''::text)::time with time zone','now()','(''now''::text)::time without time zone','(''now''::text)::timestamp without time zone'];
    END IF;

    FOR i IN 1..last_index LOOP
        FOR tap IN SELECT * FROM check_test(
            col_default_is( 'sometab', cols[i], exp[i], 'Test ' || funcs[i] ),
            true,
            'col_default_is( tab, col, ' || funcs[i] || ' )',
            'Test ' || funcs[i],
            ''
        ) AS b LOOP RETURN NEXT tap.b; END LOOP;
    END LOOP;
END;
$$;

Explanation: SQL assertion from pgTAP test suite for Coltap.


Question: PL/pgSQL test: Plpython Record (example 19).

SELECT * FROM test_table_record_as('list', 'one', null, false);

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


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

SELECT JSON_QUERY(jsonb '123', '$' RETURNING queryfuncs_char2_chk ERROR ON ERROR);

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

SELECT count(*) FROM (SELECT JSON_QUERY(jsonb '123', '$' RETURNING queryfuncs_char2_chk ERROR ON ERROR)) AS _sub;


Question: Write the DDL statement from PostgreSQL regression test 'partition_prune' (example 223).

create table rp2 partition of rp for values from (2) to (maxvalue);

Explanation: DDL from PostgreSQL core regression test for Partition Prune.


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

insert into inserttest (col1, col2, col3) values (1, 2);

Explanation: DML from PostgreSQL core regression test for Insert.


Question: Show a SQL definition from the timescaledb project (compat, item 23).

CREATE OR REPLACE FUNCTION _timescaledb_internal.get_partition_hash(val anyelement) RETURNS integer LANGUAGE PLPGSQL AS $$
BEGIN
  IF current_setting('timescaledb.enable_deprecation_warnings', true)::bool THEN
    RAISE WARNING 'function _timescaledb_internal.get_partition_hash(anyelement) is deprecated and has been moved to _timescaledb_functions schema. this compatibility function will be removed in a future version.';
  END IF;
  RETURN _timescaledb_functions.get_partition_hash($1);
END$$
SET search_path TO pg_catalog,pg_temp;

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


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

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


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

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


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

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


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

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

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


Question: Write the DDL statement from PostgreSQL regression test 'merge' (example 367).

CREATE TABLE part3 PARTITION OF pa_target FOR VALUES IN (3,8,9)
  WITH (autovacuum_enabled=off);

Explanation: DDL from PostgreSQL core regression test for Merge.


Question: pgTAP test for Index (assertion 16).

SELECT * FROM check_test(
    has_index( 'public', 'sometab', 'idx_hey', 'numb'::name ),
    true,
    'has_index() single column no desc',
    'Index idx_hey should exist',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Index.


Question: PostgreSQL Rules: show example 51.

UPDATE shoelace_data SET sl_name = s.sl_name, sl_avail = s.sl_avail + shoelace_arrive.arr_quant, sl_color = s.sl_color, sl_len = s.sl_len, sl_unit = s.sl_unit FROM shoelace_arrive shoelace_arrive, shoelace_ok shoelace_ok, shoelace_ok old, shoelace_ok new, shoelace shoelace, shoelace old, shoelace new, shoelace_data shoelace_data, shoelace old, shoelace new, shoelace_data s, unit u WHERE s.sl_name = shoelace_arrive.arr_name AND shoelace_data.sl_name = s.sl_name;

Explanation: Example from PostgreSQL documentation on Rules.


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

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

SELECT count(*) FROM (SELECT to_regnamespace('foo.bar')) AS _sub;


Question: Show a SQL definition from the pg_partman project (test-time-mixed-case, item 9).

CREATE TABLE "Partman_Test"."FK_Test_Reference" ("Col2" text unique not null);

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


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

CREATE FOREIGN DATA WRAPPER fdw_heap2 VALIDATOR postgresql_fdw_validator;

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


Question: Write the DDL statement from PostgreSQL regression test 'jsonb' (example 265).

CREATE DOMAIN jsb_int_not_null  AS int     NOT NULL;

Explanation: DDL from PostgreSQL core regression test for Jsonb.


Question: Write the DDL statement from PostgreSQL regression test 'rules' (example 314).

CREATE TABLE shoelace_log (
        sl_name    char(10),      -- shoelace changed
        sl_avail   integer,       -- new available value
        log_who    name,          -- who did it
        log_when   timestamp      -- when
    );

Explanation: DDL from PostgreSQL core regression test for Rules.


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

CREATE OPERATOR ~ (
    PROCEDURE = texticregexeq,
    LEFTARG   = citext,
    RIGHTARG  = text,
    NEGATOR   = !~,
    RESTRICT  = icregexeqsel,
    JOIN      = icregexeqjoinsel
);

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


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

SELECT * FROM connectby('connectby_int', 'keyid', 'parent_keyid', '2', 0) AS t(keyid int, parent_keyid text, level int);

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


Question: pgTAP test for Index (assertion 77).


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


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

SELECT regexp_replace('Thomas'::citext, '.[MN]A.'::citext, 'M', 'c') = 'Thomas' AS t;

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


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

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

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


Question: PostgreSQL regression test 'inet': Write the SELECT query (example 57).

SELECT * FROM inet_tbl WHERE i && '192.168.1.0/24'::cidr ORDER BY i;

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

SELECT count(*) FROM (SELECT * FROM inet_tbl WHERE i && '192.168.1.0/24'::cidr ORDER BY i) AS _sub;