instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
What percentage of vehicles in New York are electric in 2022?
CREATE TABLE vehicle_stats (year INT,location VARCHAR(255),vehicle_type VARCHAR(255),percentage FLOAT); INSERT INTO vehicle_stats (year,location,vehicle_type,percentage) VALUES (2022,'New York','Electric',0.25),(2022,'New York','Gasoline',0.75);
SELECT percentage FROM vehicle_stats WHERE year = 2022 AND location = 'New York' AND vehicle_type = 'Electric';
Which countries received defense diplomacy visits in 2012?
CREATE TABLE DefenseDiplomacy (Country VARCHAR(50),Year INT,Visit BOOLEAN); INSERT INTO DefenseDiplomacy (Country,Year,Visit) VALUES ('Country 1',2012,TRUE),('Country 2',2012,FALSE);
SELECT Country FROM DefenseDiplomacy WHERE Year = 2012 AND Visit = TRUE;
What is the total number of new public housing units constructed in the last fiscal year, by city?
CREATE TABLE PublicHousing (City VARCHAR(50),Year INT,Units INT); INSERT INTO PublicHousing (City,Year,Units) VALUES ('New York',2021,2000),('Los Angeles',2021,3000),('Chicago',2021,1500),('Houston',2021,2500),('Philadelphia',2021,1800);
SELECT City, SUM(Units) as TotalUnits FROM PublicHousing WHERE Year = 2021 GROUP BY City;
Average excavation date in 'european_archaeology'?
CREATE TABLE european_archaeology (site_id INT,excavation_date DATE);
SELECT AVG(EXTRACT(YEAR FROM excavation_date)) FROM european_archaeology;
Show the minimum water consumption in liters for the state of California in the month of January 2022
CREATE TABLE water_usage (id INT,state VARCHAR(50),consumption FLOAT,date DATE); INSERT INTO water_usage (id,state,consumption,date) VALUES (1,'California',12000,'2022-01-01'); INSERT INTO water_usage (id,state,consumption,date) VALUES (2,'California',13000,'2022-01-02');
SELECT MIN(consumption) FROM water_usage WHERE state = 'California' AND date >= '2022-01-01' AND date <= '2022-01-31';
List all aircraft accidents with their investigation status and the number of fatalities.
CREATE TABLE Accidents (Id INT,Aircraft VARCHAR(50),Date DATE,Location VARCHAR(50),Investigation_Status VARCHAR(50),Fatalities INT); INSERT INTO Accidents (Id,Aircraft,Date,Location,Investigation_Status,Fatalities) VALUES (1,'B737','2015-01-01','Country1','Open',50),(2,'A320','2016-02-02','Country2','Closed',20);
SELECT Aircraft, Investigation_Status, Fatalities FROM Accidents;
Insert 5 new records of players into the 'players' table
CREATE TABLE players (id INT,name TEXT,level INT);
INSERT INTO players (id, name, level) VALUES (1, 'Player1', 12), (2, 'Player2', 15), (3, 'Player3', 10), (4, 'Player4', 18), (5, 'Player5', 13);
How many pallets are currently stored in each warehouse, broken down by warehouse type?
CREATE TABLE warehouses (id INT,type VARCHAR(50),pallets INT); INSERT INTO warehouses (id,type,pallets) VALUES (1,'Cool',200),(2,'Dry',300),(3,'Frozen',150);
SELECT type, SUM(pallets) as total_pallets FROM warehouses GROUP BY type;
Delete the records of artists who have not attended any cultural events
ARTIST(artist_id,name,gender); CULTURAL_EVENT_ATTENDANCE(attendance_id,artist_id,event_id)
DELETE a1 FROM ARTIST a1 LEFT JOIN CULTURAL_EVENT_ATTENDANCE a2 ON a1.artist_id = a2.artist_id WHERE a2.attendance_id IS NULL;
List all the programs that were started in the first half of 2021.
CREATE TABLE programs (program_id INT,program_name VARCHAR(50),program_start_date DATE);
SELECT program_name, program_start_date FROM programs WHERE program_start_date >= '2021-01-01' AND program_start_date < '2021-07-01';
What is the ratio of sustainable to non-sustainable garments sold?
CREATE TABLE garment_sustainability (id INT,garment_id INT,is_sustainable BOOLEAN); INSERT INTO garment_sustainability (id,garment_id,is_sustainable) VALUES
SELECT AVG(is_sustainable::INT) FROM garments INNER JOIN garment_sustainability ON garments.id = garment_sustainability.garment_id;
Find the total number of accidents for each vehicle make where the number of accidents is greater than 50.
CREATE TABLE VehicleSafetyTesting (VehicleMake VARCHAR(255),AccidentCount INT); INSERT INTO VehicleSafetyTesting (VehicleMake,AccidentCount) VALUES ('Tesla',45),('Toyota',30),('Honda',35),('Volvo',20);
SELECT VehicleMake, COUNT(*) as TotalAccidents FROM VehicleSafetyTesting GROUP BY VehicleMake HAVING TotalAccidents > 50;
Delete records of crops not present in 2021
CREATE TABLE crops (id INT,year INT,crop TEXT,quantity INT); INSERT INTO crops (id,year,crop,quantity) VALUES (1,2021,'corn',120),(2,2020,'potatoes',80),(3,2019,'carrots',90);
DELETE FROM crops WHERE year != 2021;
Which urban farms in Albuquerque, NM have the lowest yield per acre?
CREATE TABLE urban_farms_nm (name TEXT,city TEXT,state TEXT,acres NUMERIC,yield NUMERIC); INSERT INTO urban_farms_nm (name,city,state,acres,yield) VALUES ('Los Poblanos','Albuquerque','NM',3.1,11000),('Albuquerque Farm Co-op','Albuquerque','NM',2.7,9000),('Rio Grande Community Farms','Albuquerque','NM',1.8,6000);
SELECT name, acres, yield, ROW_NUMBER() OVER (ORDER BY yield/acres ASC) as rank FROM urban_farms_nm WHERE city = 'Albuquerque' AND state = 'NM';
What is the average rating of cruelty-free cosmetics products launched in the last year?
CREATE TABLE product (product_id INT,name TEXT,launch_date DATE,rating FLOAT,cruelty_free BOOLEAN);
SELECT AVG(rating) FROM product WHERE cruelty_free = TRUE AND launch_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR);
What is the most common type of incident in the 'safety_records' table?
CREATE TABLE safety_records (id INT,incident_type VARCHAR(50),incident_date DATE,description VARCHAR(100));
SELECT incident_type, COUNT(*) FROM safety_records GROUP BY incident_type ORDER BY COUNT(*) DESC LIMIT 1;
List the top 5 most water-consuming cities in California in 2021
CREATE TABLE cities (id INT,state VARCHAR(255)); INSERT INTO cities (id,state) VALUES (1,'California'); CREATE TABLE water_meter_readings (id INT,city_id INT,consumption FLOAT,reading_date DATE); INSERT INTO water_meter_readings (id,city_id,consumption,reading_date) VALUES (1,1,100000,'2021-01-01'); INSERT INTO water_meter_readings (id,city_id,consumption,reading_date) VALUES (2,1,120000,'2021-02-01');
SELECT water_meter_readings.city_id, SUM(water_meter_readings.consumption) as total_consumption FROM water_meter_readings WHERE EXTRACT(YEAR FROM water_meter_readings.reading_date) = 2021 AND water_meter_readings.city_id IN (SELECT id FROM cities WHERE state = 'California') GROUP BY water_meter_readings.city_id ORDER BY total_consumption DESC LIMIT 5;
What is the total amount donated by individual donors from Canada and Mexico in 2021?
CREATE TABLE Donors (DonorID INT,DonorName TEXT,Country TEXT); INSERT INTO Donors (DonorID,DonorName,Country) VALUES (1,'John Doe','Canada'),(2,'Jane Smith','Mexico'); CREATE TABLE Donations (DonationID INT,DonorID INT,Amount DECIMAL,DonationYear INT); INSERT INTO Donations (DonationID,DonorID,Amount,DonationYear) VALUES (1,1,100,2021),(2,2,150,2021);
SELECT SUM(d.Amount) FROM Donations d JOIN Donors don ON d.DonorID = don.DonorID WHERE don.Country IN ('Canada', 'Mexico') AND d.DonationYear = 2021;
How many electric scooters are available in Berlin?
CREATE TABLE berlin_scooters (id INT,dock_id VARCHAR(20),scooter_type VARCHAR(20),available BOOLEAN);
SELECT COUNT(*) FROM berlin_scooters WHERE scooter_type = 'electric' AND available = TRUE;
Update the research interests of all professors in the Electrical Engineering department to 'Electrical Power Systems'.
CREATE TABLE professors (id INT,name VARCHAR(50),department VARCHAR(50),research_interest VARCHAR(50)); INSERT INTO professors (id,name,department,research_interest) VALUES (1,'John Doe','Computer Science','Machine Learning'),(2,'Sam Smith','Electrical Engineering','Power Systems'),(3,'Jane Smith','Computer Science','Data Science');
UPDATE professors SET research_interest = 'Electrical Power Systems' WHERE department = 'Electrical Engineering';
What is the average response time for each category in 'incident_response' table for the year 2021?
CREATE TABLE incident_response (incident_id INT,incident_date DATE,category VARCHAR(20),response_time INT); INSERT INTO incident_response (incident_id,incident_date,category,response_time) VALUES (1,'2021-01-01','Medical',8),(2,'2021-02-15','Fire',6),(3,'2021-03-01','Traffic',10);
SELECT category, AVG(response_time) FROM incident_response WHERE YEAR(incident_date) = 2021 GROUP BY category;
Find the 'total area' of 'coniferous' forests in '2021'.
CREATE TABLE forests (id INT,biome VARCHAR(50),area FLOAT,year INT); INSERT INTO forests (id,biome,area,year) VALUES (1,'coniferous',5000.0,2021);
SELECT SUM(area) FROM forests WHERE biome = 'coniferous' AND year = 2021;
What is the minimum sea ice extent in the Arctic Ocean in September 2020?
CREATE TABLE sea_ice_extent (location TEXT,date DATE,extent REAL); INSERT INTO sea_ice_extent (location,date,extent) VALUES ('Arctic Ocean','2020-09-01',4.0),('Arctic Ocean','2020-09-02',3.5);
SELECT MIN(extent) FROM sea_ice_extent WHERE location = 'Arctic Ocean' AND date BETWEEN '2020-09-01' AND '2020-09-30';
How many restaurants are there in total?
CREATE TABLE restaurant (restaurant_id INT); INSERT INTO restaurant (restaurant_id) VALUES (1),(2),(3),(4);
SELECT COUNT(*) FROM restaurant;
What is the maximum delivery time for each warehouse, and which warehouse has the latest shipment?
CREATE TABLE Warehouse (id INT,location VARCHAR(255),capacity INT); INSERT INTO Warehouse (id,location,capacity) VALUES (1,'New York',500),(2,'Toronto',700),(3,'Montreal',600); CREATE TABLE Shipment (id INT,warehouse_id INT,delivery_time INT); INSERT INTO Shipment (id,warehouse_id,delivery_time) VALUES (1,1,5),(2,2,12),(3,3,4),(4,1,6),(5,2,3),(6,3,15),(7,1,10);
SELECT warehouse_id, MAX(delivery_time) as max_delivery_time FROM Shipment GROUP BY warehouse_id ORDER BY max_delivery_time DESC LIMIT 1;
Which TV show had the highest viewership from Australia?
CREATE TABLE tv_shows_aus (show_id INT PRIMARY KEY,name VARCHAR(255),country VARCHAR(2),viewers INT); INSERT INTO tv_shows_aus (show_id,name,country,viewers) VALUES (1,'Breaking Bad','Australia',1400000),(2,'Game of Thrones','Australia',1700000),(3,'Friends','Australia',1350000);
SELECT * FROM tv_shows_aus WHERE country = 'Australia' ORDER BY viewers DESC LIMIT 1;
What percentage of cruelty-free certified cosmetic products are available in Australia?
CREATE TABLE Cruelty_Free_Certification (ProductID INT,Certified BOOLEAN,Country VARCHAR(50)); INSERT INTO Cruelty_Free_Certification (ProductID,Certified,Country) VALUES (4001,TRUE,'Australia'),(4002,FALSE,'Australia'),(4003,TRUE,'Australia'),(4004,TRUE,'Australia'),(4005,FALSE,'Australia');
SELECT (COUNT(ProductID) FILTER (WHERE Certified = TRUE AND Country = 'Australia') * 100.0 / COUNT(ProductID)) as Percentage FROM Cruelty_Free_Certification WHERE Country = 'Australia';
Get the total number of tickets sold for each team's games, excluding 'Atlanta Hawks'.
CREATE TABLE teams (id INT,name TEXT,city TEXT); INSERT INTO teams (id,name,city) VALUES (1,'Golden State Warriors','San Francisco'),(2,'Los Angeles Lakers','LA'),(3,'Brooklyn Nets','Brooklyn'),(4,'Toronto Raptors','Toronto'),(5,'Philadelphia 76ers','Philadelphia'),(6,'Atlanta Hawks','Atlanta'); CREATE TABLE tickets (id INT,team TEXT,home_team TEXT,quantity INT); INSERT INTO tickets (id,team,home_team,quantity) VALUES (1,'Golden State Warriors','Golden State Warriors',200),(2,'Los Angeles Lakers','Los Angeles Lakers',180),(3,'Brooklyn Nets','Brooklyn Nets',160),(4,'Toronto Raptors','Toronto Raptors',190),(5,'Philadelphia 76ers','Philadelphia 76ers',140),(6,'Atlanta Hawks','Atlanta Hawks',150);
SELECT team, SUM(quantity) as total_sold FROM tickets WHERE team NOT IN ('Atlanta Hawks') GROUP BY team;
Show the total number of tickets sold for each sport.
CREATE TABLE tickets_2 (team TEXT,quantity INTEGER,sport TEXT); INSERT INTO tickets_2 (team,quantity,sport) VALUES ('Broncos',20000,'Football'),('Lakers',15000,'Basketball'),('Dodgers',30000,'Baseball');
SELECT sport, SUM(quantity) FROM tickets_2 GROUP BY sport;
What is the maximum number of digital exhibits in a city in Europe?
CREATE TABLE DigitalExhibits (ExhibitID INT,Title VARCHAR(50),Curator VARCHAR(50),City VARCHAR(50)); INSERT INTO DigitalExhibits (ExhibitID,Title,Curator,City) VALUES (1,'Digital Art Museum','Alice Johnson','London'); INSERT INTO DigitalExhibits (ExhibitID,Title,Curator,City) VALUES (2,'Virtual Reality Experience','Bob Smith','Paris'); INSERT INTO DigitalExhibits (ExhibitID,Title,Curator,City) VALUES (3,'Interactive Art Gallery','Charlie Brown','Berlin'); INSERT INTO DigitalExhibits (ExhibitID,Title,Curator,City) VALUES (4,'Digital Art Exhibition','David Wilson','Rome');
SELECT MAX(COUNT(*)) FROM DigitalExhibits GROUP BY DigitalExhibits.City;
What is the minimum ticket price for hip-hop concerts?
CREATE TABLE ConcertTickets (ticket_id INT,genre VARCHAR(20),price DECIMAL(5,2));
SELECT MIN(price) FROM ConcertTickets WHERE genre = 'hip-hop';
Who are the top 5 artists by number of streams on Apple Music in Q2 2022?
CREATE TABLE AppleMusicStreams (artist VARCHAR(255),quarter INT,streams INT);
SELECT artist, SUM(streams) AS total_streams FROM AppleMusicStreams WHERE quarter = 2 GROUP BY artist ORDER BY total_streams DESC LIMIT 5;
Update the rating of the TV show 'The Witcher' to 8.9.
CREATE TABLE TV_Shows (id INT,title VARCHAR(100),rating DECIMAL(2,1)); INSERT INTO TV_Shows (id,title,rating) VALUES (1,'Stranger Things',8.7); INSERT INTO TV_Shows (id,title,rating) VALUES (2,'The Witcher',8.6);
UPDATE TV_Shows SET rating = 8.9 WHERE title = 'The Witcher';
What is the average age of all trees in the 'Trees' table?
CREATE TABLE Trees (id INT,species VARCHAR(50),age INT); INSERT INTO Trees (id,species,age) VALUES (1,'Pine',30),(2,'Oak',50),(3,'Maple',25);
SELECT AVG(age) FROM Trees;
Update the ticket price for 'Philadelphia 76ers' to $140.
CREATE TABLE teams (id INT,name TEXT,city TEXT); INSERT INTO teams (id,name,city) VALUES (1,'Golden State Warriors','San Francisco'),(2,'Los Angeles Lakers','LA'),(3,'Brooklyn Nets','Brooklyn'),(4,'Toronto Raptors','Toronto'),(5,'Philadelphia 76ers','Philadelphia'); CREATE TABLE tickets (id INT,team TEXT,home_team TEXT,price DECIMAL(5,2)); INSERT INTO tickets (id,team,price) VALUES (1,'Golden State Warriors',200),(2,'Los Angeles Lakers',180),(3,'Brooklyn Nets',160),(4,'Toronto Raptors',190),(5,'Philadelphia 76ers',130);
UPDATE tickets SET price = 140 WHERE team = 'Philadelphia 76ers';
What are the top 3 destinations with the highest number of travel advisories issued since 2018?
CREATE TABLE advisories (destination VARCHAR(50),advisory_issue_date DATE); INSERT INTO advisories (destination,advisory_issue_date) VALUES ('Mexico','2018-02-14'),('Thailand','2018-04-05'),('Mexico','2019-03-01'),('Thailand','2019-09-12'),('India','2020-01-15'),('Mexico','2020-08-03');
SELECT destination, COUNT(*) as num_advisories FROM advisories WHERE advisory_issue_date >= '2018-01-01' GROUP BY destination ORDER BY num_advisories DESC LIMIT 3;
Insert a new exhibition 'Modern Art from Africa' with 500 visitors.
CREATE TABLE Exhibitions (exhibition_id INT,name VARCHAR(100),visitor_count INT);
INSERT INTO Exhibitions (exhibition_id, name, visitor_count) VALUES (1, 'Modern Art from Africa', 500);
What is the average travel time to the nearest healthcare facility per rural community?
CREATE TABLE healthcare_facilities (id INT,name TEXT,location TEXT,travel_time FLOAT);
SELECT AVG(travel_time) avg_time, location FROM healthcare_facilities WHERE location LIKE '%rural%' GROUP BY location ORDER BY avg_time DESC;
Who are the top 3 cities with the most investigative journalism stories in the past month?
CREATE TABLE stories (id INT,city VARCHAR(20),date DATE); CREATE TABLE categories (id INT,category VARCHAR(20)); INSERT INTO stories VALUES (1,'New York','2022-01-01'); INSERT INTO categories VALUES (1,'investigative journalism');
SELECT city, COUNT(*) as story_count FROM stories INNER JOIN categories ON stories.id = categories.id WHERE stories.date >= '2022-02-01' GROUP BY city ORDER BY story_count DESC LIMIT 3;
What is the average price of sustainably produced products in Africa?
CREATE TABLE regions (id INT,name TEXT); INSERT INTO regions (id,name) VALUES (1,'North America'),(2,'South America'),(3,'Europe'),(4,'Asia'),(5,'Africa'); CREATE TABLE products (id INT,name TEXT,is_sustainable BOOLEAN,price DECIMAL(5,2)); INSERT INTO products (id,name,is_sustainable,price) VALUES (1,'Product X',true,50.00),(2,'Product Y',false,30.00),(3,'Product Z',true,70.00),(4,'Product W',false,40.00); CREATE TABLE sales (id INT,product TEXT,quantity INT,region TEXT); INSERT INTO sales (id,product,quantity,region) VALUES (1,'Product X',100,'Africa'),(2,'Product Y',150,'North America'),(3,'Product Z',80,'Europe'),(4,'Product W',120,'Asia');
SELECT AVG(products.price) FROM products INNER JOIN sales ON products.name = sales.product INNER JOIN regions ON sales.region = regions.name WHERE products.is_sustainable = true AND regions.name = 'Africa';
What is the average time spent on disability-related policy advocacy per quarter?
CREATE TABLE PolicyAdvocacy (advocate_id INT,date DATE,hours_spent FLOAT); INSERT INTO PolicyAdvocacy (advocate_id,date,hours_spent) VALUES (1,'2022-01-05',5.5); INSERT INTO PolicyAdvocacy (advocate_id,date,hours_spent) VALUES (2,'2022-02-10',7.3); INSERT INTO PolicyAdvocacy (advocate_id,date,hours_spent) VALUES (3,'2022-04-15',9.2);
SELECT AVG(hours_spent) as avg_hours_per_quarter FROM PolicyAdvocacy WHERE date BETWEEN '2022-01-01' AND LAST_DAY('2022-03-31') OR date BETWEEN '2022-04-01' AND LAST_DAY('2022-06-30') OR date BETWEEN '2022-07-01' AND LAST_DAY('2022-09-30') OR date BETWEEN '2022-10-01' AND LAST_DAY('2022-12-31');
What was the total amount donated by 'Greenpeace' in 'Asia'?
CREATE TABLE Donors (DonorID INT,DonorName TEXT,Country TEXT); INSERT INTO Donors (DonorID,DonorName,Country) VALUES (1,'Greenpeace','Asia'); CREATE TABLE Contributions (ContributionID INT,DonorID INT,Amount DECIMAL); INSERT INTO Contributions (ContributionID,DonorID,Amount) VALUES (1,1,20000);
SELECT SUM(Contributions.Amount) FROM Contributions INNER JOIN Donors ON Contributions.DonorID = Donors.DonorID WHERE Donors.DonorName = 'Greenpeace' AND Donors.Country = 'Asia';
What is the percentage of cases won by attorneys with a law degree from Harvard University?
CREATE TABLE Attorneys (AttorneyID INT,LawDegreeSchool VARCHAR(255),WinRate DECIMAL); CREATE TABLE Cases (CaseID INT,AttorneyID INT,CaseOutcome VARCHAR(10));
SELECT AVG(WinRate) FROM Attorneys JOIN Cases ON Attorneys.AttorneyID = Cases.AttorneyID WHERE LawDegreeSchool = 'Harvard University';
What is the minimum size in square feet of properties with inclusive housing policies in rural areas?
CREATE TABLE property (id INT,size_sqft INT,area VARCHAR(255),has_inclusive_policy BOOLEAN); INSERT INTO property (id,size_sqft,area,has_inclusive_policy) VALUES (1,1200,'Seattle',true),(2,800,'New York',false),(3,1500,'rural',true),(4,900,'rural',false);
SELECT MIN(size_sqft) FROM property WHERE area = 'rural' AND has_inclusive_policy = true;
What are the average diversity scores for suppliers in the manufacturing industry?
CREATE TABLE suppliers (supplier_id INT,name TEXT,industry TEXT,diversity_score FLOAT);
SELECT AVG(diversity_score) as avg_diversity_score FROM suppliers WHERE industry = 'manufacturing';
Determine the annual visitor growth rate for each country between 2018 and 2019.
CREATE TABLE CountryVisitorData (id INT,country_id INT,year INT,visitors INT); INSERT INTO CountryVisitorData (id,country_id,year,visitors) VALUES (1,1,2018,5000000); INSERT INTO CountryVisitorData (id,country_id,year,visitors) VALUES (2,1,2019,5250000); INSERT INTO CountryVisitorData (id,country_id,year,visitors) VALUES (3,2,2018,8000000); INSERT INTO CountryVisitorData (id,country_id,year,visitors) VALUES (4,2,2019,8500000); INSERT INTO CountryVisitorData (id,country_id,year,visitors) VALUES (5,3,2018,6000000); INSERT INTO CountryVisitorData (id,country_id,year,visitors) VALUES (6,3,2019,6500000); INSERT INTO CountryVisitorData (id,country_id,year,visitors) VALUES (7,4,2018,9000000); INSERT INTO CountryVisitorData (id,country_id,year,visitors) VALUES (8,4,2019,9500000);
SELECT country_id, (visitors - LAG(visitors, 1) OVER (PARTITION BY country_id ORDER BY year)) * 100.0 / LAG(visitors, 1) OVER (PARTITION BY country_id ORDER BY year) as growth_rate FROM CountryVisitorData;
Find the mode of exit strategies (IPO, Acquisition, Merger, Liquidation) for startups in the ArtificialIntelligence sector.
CREATE TABLE startup (id INT,name TEXT,industry TEXT,exit_strategy TEXT);
SELECT exit_strategy, COUNT(*) AS frequency FROM startup WHERE industry = 'ArtificialIntelligence' GROUP BY exit_strategy ORDER BY frequency DESC LIMIT 1;
Count the number of companies founded by individuals from underrepresented racial and ethnic groups
CREATE TABLE company_founding(id INT PRIMARY KEY,company_name VARCHAR(100),founder_race VARCHAR(50)); INSERT INTO company_founding VALUES (1,'Acme Inc','Asian'); INSERT INTO company_founding VALUES (2,'Beta Corp','White'); INSERT INTO company_founding VALUES (3,'Charlie LLC','Hispanic');
SELECT COUNT(*) FROM company_founding WHERE founder_race IN ('Black', 'Hispanic', 'Indigenous', 'Pacific Islander');
What is the total quantity of items with type 'A' in warehouse E and warehouse F?
CREATE TABLE warehouse_e(item_id INT,item_type VARCHAR(10),quantity INT);CREATE TABLE warehouse_f(item_id INT,item_type VARCHAR(10),quantity INT);INSERT INTO warehouse_e(item_id,item_type,quantity) VALUES (1,'A',200),(2,'B',300),(3,'A',50);INSERT INTO warehouse_f(item_id,item_type,quantity) VALUES (1,'A',150),(2,'B',250),(3,'A',40);
SELECT quantity FROM warehouse_e WHERE item_type = 'A' UNION ALL SELECT quantity FROM warehouse_f WHERE item_type = 'A';
Show the percentage of meals in Mexico with less than 500 calories.
CREATE TABLE meals (user_id INT,meal_date DATE,calories INT); INSERT INTO meals (user_id,meal_date,calories) VALUES (1,'2022-01-01',600),(1,'2022-01-02',800),(2,'2022-01-01',500); CREATE TABLE users (user_id INT,country VARCHAR(255)); INSERT INTO users (user_id,country) VALUES (1,'USA'),(2,'Mexico');
SELECT 100.0 * COUNT(*) / (SELECT COUNT(*) FROM meals JOIN users ON meals.user_id = users.user_id WHERE users.country = 'Mexico') as pct_meals FROM meals JOIN users ON meals.user_id = users.user_id WHERE users.country = 'Mexico' AND calories < 500;
How many deep-sea species have been discovered in each ocean?
CREATE TABLE deep_sea_species (ocean text,species_count integer); INSERT INTO deep_sea_species (ocean,species_count) VALUES ('Pacific Ocean',500),('Atlantic Ocean',600),('Indian Ocean',400);
SELECT ocean, species_count FROM deep_sea_species;
What is the minimum heart rate recorded for users in the evening?
CREATE TABLE heart_rate_times (user_id INT,heart_rate INT,measurement_time TIME); INSERT INTO heart_rate_times (user_id,heart_rate,measurement_time) VALUES (5,50,'20:00:00'),(6,55,'21:00:00'),(7,60,'19:30:00'),(8,65,'22:00:00');
SELECT MIN(heart_rate) FROM heart_rate_times WHERE EXTRACT(HOUR FROM measurement_time) BETWEEN 18 AND 23;
How many satellites were launched in 2022?
CREATE TABLE SatelliteLaunches (id INT PRIMARY KEY,country VARCHAR(255),launch_date DATE); CREATE TABLE Satellites (id INT PRIMARY KEY,name VARCHAR(255),launch_id INT,FOREIGN KEY (launch_id) REFERENCES SatelliteLaunches(id));
SELECT COUNT(s.id) as num_satellites FROM SatelliteLaunches l LEFT JOIN Satellites s ON l.id = s.launch_id WHERE YEAR(launch_date) = 2022;
What is the percentage of cases where alternative sentencing was granted in European countries and the US?
CREATE TABLE europe_alternative_sentencing (id INT,country VARCHAR(255),cases INT); INSERT INTO europe_alternative_sentencing (id,country,cases) VALUES (1,'France',1000),(2,'Germany',1500),(3,'Spain',800);CREATE TABLE us_alternative_sentencing (id INT,country VARCHAR(255),cases INT); INSERT INTO us_alternative_sentencing (id,country,cases) VALUES (1,'USA',5000);
SELECT ((SUM(europe_alternative_sentencing.cases) / (SUM(europe_alternative_sentencing.cases) + us_alternative_sentencing.cases)) * 100) AS percentage FROM europe_alternative_sentencing, us_alternative_sentencing;
What is the total data usage for the top 5 customers in the city of Tokyo?
CREATE TABLE customers (id INT,name VARCHAR(50),data_usage FLOAT,city VARCHAR(50));
SELECT SUM(data_usage) FROM customers WHERE city = 'Tokyo' AND id IN (SELECT id FROM (SELECT id FROM customers WHERE city = 'Tokyo' ORDER BY data_usage DESC LIMIT 5) subquery) ORDER BY data_usage DESC;
What is the total number of peacekeeping personnel by continent?
CREATE TABLE peacekeeping_personnel (continent VARCHAR(255),personnel_count INT); INSERT INTO peacekeeping_personnel (continent,personnel_count) VALUES ('Africa',1000),('Asia',1500),('Europe',800);
SELECT continent, SUM(personnel_count) FROM peacekeeping_personnel GROUP BY continent;
Find the total amount of interest earned from Shariah-compliant financing in Q1 2022.
CREATE TABLE shariah_financing (transaction_id INT,client_id INT,transaction_date DATE,interest_rate DECIMAL(10,2),principal DECIMAL(10,2)); INSERT INTO shariah_financing (transaction_id,client_id,transaction_date,interest_rate,principal) VALUES (1,201,'2022-01-05',0.02,1000.00),(2,202,'2022-02-15',0.03,2000.00),(3,203,'2022-03-30',0.01,500.00);
SELECT SUM(principal * interest_rate) FROM shariah_financing WHERE transaction_date BETWEEN '2022-01-01' AND '2022-03-31';
What is the maximum quantity of silver mined in the second half of 2022 from the 'SilverMine'?
CREATE TABLE SilverMine (date DATE,quantity INT);INSERT INTO SilverMine (date,quantity) VALUES ('2022-07-01',120),('2022-07-05',150),('2022-08-10',200),('2022-09-20',220);
SELECT MAX(quantity) FROM SilverMine WHERE date < '2023-01-01' AND date >= '2022-07-01';
Count the number of patients who improved after therapy in the United States?
CREATE TABLE patient_outcomes (patient_id INT,improvement_status VARCHAR(255),country VARCHAR(255)); INSERT INTO patient_outcomes (patient_id,improvement_status,country) VALUES (1,'Improved','USA'); INSERT INTO patient_outcomes (patient_id,improvement_status,country) VALUES (2,'Not Improved','USA');
SELECT COUNT(*) FROM patient_outcomes WHERE improvement_status = 'Improved' AND country = 'USA';
What is the number of education programs conducted in each region, sorted by the number of programs in descending order?
CREATE TABLE education_programs (region TEXT,program_count INTEGER); INSERT INTO education_programs (region,program_count) VALUES ('North',15),('South',20),('East',10),('West',25);
SELECT region, program_count FROM education_programs ORDER BY program_count DESC;
Delete the records of artists who have not created any artwork
ARTIST(artist_id,name,gender); ARTWORK(artwork_id,title,date_created,period,artist_id)
DELETE a1 FROM ARTIST a1 LEFT JOIN ARTWORK a2 ON a1.artist_id = a2.artist_id WHERE a2.artwork_id IS NULL;
What is the average number of marine species in the Arctic Ocean per region?
CREATE TABLE marine_species (name VARCHAR(255),region VARCHAR(255),population INT);INSERT INTO marine_species (name,region,population) VALUES ('Species 1','Arctic Ocean',15000),('Species 2','Arctic Ocean',12000),('Species 3','Arctic Ocean',9000),('Species 4','Arctic Ocean',7000);
SELECT AVG(population) FROM marine_species WHERE region = 'Arctic Ocean';
Identify the suppliers who have provided both conventional and organic produce in the past year.
CREATE TABLE suppliers (supplier_id INT,supplier_name TEXT);CREATE TABLE produce (produce_id INT,produce_name TEXT,is_organic BOOLEAN,last_delivery_date DATE);CREATE TABLE deliveries (supplier_id INT,produce_id INT);
SELECT suppliers.supplier_name FROM suppliers JOIN deliveries ON suppliers.supplier_id = deliveries.supplier_id JOIN produce ON deliveries.produce_id = produce.produce_id WHERE produce.is_organic = TRUE AND produce.last_delivery_date >= DATEADD(year, -1, GETDATE()) INTERSECT SELECT suppliers.supplier_name FROM suppliers JOIN deliveries ON suppliers.supplier_id = deliveries.supplier_id JOIN produce ON deliveries.produce_id = produce.produce_id WHERE produce.is_organic = FALSE AND produce.last_delivery_date >= DATEADD(year, -1, GETDATE());
Determine the number of artworks by artists who identify as LGBTQ+.
CREATE TABLE artworks (id INT,artist_name VARCHAR(255),sexual_orientation VARCHAR(255)); INSERT INTO artworks (id,artist_name,sexual_orientation) VALUES (1,'Keith Haring','Gay'),(2,'Jean-Michel Basquiat','Straight'),(3,'Catherine Opie','Lesbian');
SELECT COUNT(*) FROM artworks WHERE sexual_orientation IN ('Gay', 'Lesbian', 'Bisexual', 'Transgender', 'Queer', 'Questioning');
What is the total amount of funding allocated for Arctic research in 2021?
CREATE TABLE ResearchFunding (project VARCHAR(255),year INT,amount FLOAT); INSERT INTO ResearchFunding (project,year,amount) VALUES ('Climate Change',2021,1500000); INSERT INTO ResearchFunding (project,year,amount) VALUES ('Biodiversity',2021,1200000);
SELECT SUM(amount) FROM ResearchFunding WHERE year = 2021 AND project IN ('Climate Change', 'Biodiversity', 'Indigenous Communities', 'Resource Management');
What is the average citizen satisfaction rating for public housing and public utilities services combined, in the 'StateData' schema's 'StateSatisfaction' table, for the year 2023?
CREATE SCHEMA StateData; CREATE TABLE StateSatisfaction (Service varchar(255),Year int,Satisfaction int); INSERT INTO StateSatisfaction (Service,Year,Satisfaction) VALUES ('Public Housing',2023,6),('Public Housing',2023,7),('Public Utilities',2023,8),('Public Utilities',2023,9);
SELECT AVG(Satisfaction) FROM StateData.StateSatisfaction WHERE Year = 2023 AND Service IN ('Public Housing', 'Public Utilities');
Delete genetic research projects that did not use biosensor technologies in Germany.
CREATE TABLE projects(name VARCHAR(50),location VARCHAR(20),biosensor_used BOOLEAN); INSERT INTO projects(name,location,biosensor_used) VALUES('ProjectX','Germany',true),('ProjectY','Germany',false);
DELETE FROM projects WHERE location = 'Germany' AND biosensor_used = false;
What is the total revenue generated by virtual tours for each region?
CREATE TABLE tour (id INT,name TEXT,region TEXT,price INT); INSERT INTO tour (id,name,region,price) VALUES (1,'Virtual Acropolis','Europe',10); INSERT INTO tour (id,name,region,price) VALUES (2,'Virtual Machu Picchu','South America',15);
SELECT region, SUM(price) as total_revenue FROM tour WHERE name LIKE '%virtual%' GROUP BY region;
Get the number of dams in each county in Texas
CREATE TABLE Dams (dam_id int,dam_name varchar(255),county varchar(255),state varchar(255));
SELECT county, COUNT(*) FROM Dams WHERE state = 'Texas' GROUP BY county;
What is the total number of military bases and their respective countries for each type of base?
CREATE TABLE MilitaryBases (BaseID INT,BaseType VARCHAR(20),BaseCountry VARCHAR(30)); INSERT INTO MilitaryBases (BaseID,BaseType,BaseCountry) VALUES (1,'Air Force','USA'),(2,'Army','Canada'),(3,'Navy','UK'),(4,'Marines','Australia');
SELECT BaseType, BaseCountry, COUNT(*) as Total FROM MilitaryBases GROUP BY BaseType, BaseCountry;
Show the total number of volunteers and total amount donated in each state of the USA, ordered by the total donation amount in descending order.
CREATE TABLE Donors (DonorID INT,DonorName TEXT,State TEXT,TotalDonation DECIMAL); CREATE TABLE Volunteers (VolunteerID INT,VolunteerName TEXT,State TEXT);
SELECT V.State, COUNT(DISTINCT V.VolunteerID) as Volunteers, SUM(D.TotalDonation) as TotalDonation FROM Volunteers V JOIN Donors D ON V.State = D.State GROUP BY V.State ORDER BY TotalDonation DESC;
Which countries had the most sustainable fashion metrics in the past month?
CREATE TABLE country_metric (id INT,country TEXT,metric FLOAT,date DATE);
SELECT country, AVG(metric) FROM country_metric WHERE date >= DATE_SUB(CURDATE(), INTERVAL 1 MONTH) GROUP BY country ORDER BY AVG(metric) DESC LIMIT 1;
How many satellites were deployed by each organization in the Satellites table?
CREATE TABLE Satellites (satellite_id INT,organization VARCHAR(50),launch_date DATE); INSERT INTO Satellites (satellite_id,organization,launch_date) VALUES (1,'NASA','2000-01-01'),(2,'SpaceX','2010-01-01'),(3,'NASA','2020-01-01');
SELECT organization, COUNT(*) AS satellites_deployed FROM Satellites GROUP BY organization;
What is the total number of 5G mobile customers in the state of California?
CREATE TABLE mobile_customers (customer_id INT,state VARCHAR(20),network_type VARCHAR(10)); INSERT INTO mobile_customers (customer_id,state,network_type) VALUES (1,'California','5G'),(2,'California','4G'),(3,'New York','5G');
SELECT COUNT(*) FROM mobile_customers WHERE state = 'California' AND network_type = '5G';
What is the average number of hospital beds in hospitals located in urban areas?
CREATE TABLE Hospitals (name VARCHAR(255),location VARCHAR(255),type VARCHAR(255),num_beds INT); INSERT INTO Hospitals (name,location,type,num_beds) VALUES ('Urban General Hospital','Meadowville','Hospital',300),('Rural General Hospital','Springfield','Hospital',50);
SELECT AVG(num_beds) FROM Hospitals WHERE location LIKE '%urban%';
Who are the top 2 contributors to language preservation efforts in 'North America' for indigenous languages?
CREATE TABLE LanguagePreservation (ID INT,Contributor TEXT,Language TEXT,Contribution TEXT,Region TEXT); INSERT INTO LanguagePreservation (ID,Contributor,Language,Contribution,Region) VALUES (1,'First Nations Language Council','Nuu-chah-nulth','Language support','North America'),(2,'Native American Languages Program','Cherokee','Language support','North America');
SELECT Contributor, Contribution FROM LanguagePreservation WHERE Language IN ('Nuu-chah-nulth', 'Cherokee') AND Region = 'North America' LIMIT 2;
What is the total quantity of organic skincare products sold in Canada between January 1, 2021 and January 31, 2021?
CREATE TABLE products (id INT,name VARCHAR(50),category VARCHAR(50),price DECIMAL(5,2),supplier_country VARCHAR(50),organic BOOLEAN);CREATE TABLE sales (id INT,product_id INT,quantity INT,sale_date DATE);
SELECT SUM(sales.quantity) FROM sales JOIN products ON sales.product_id = products.id WHERE products.category = 'Skincare' AND products.supplier_country = 'Canada' AND products.organic = TRUE AND sales.sale_date BETWEEN '2021-01-01' AND '2021-01-31';
What is the total quantity of non-vegan cosmetics sold in the past year in Europe?
CREATE TABLE sales (product_id INT,sale_quantity INT,sale_country TEXT); CREATE TABLE products (product_id INT,is_vegan BOOLEAN);
SELECT SUM(sale_quantity) FROM sales INNER JOIN products ON sales.product_id = products.product_id WHERE sale_country LIKE 'Europe%' AND is_vegan = FALSE AND sales.sale_date >= NOW() - INTERVAL '1 year';
What are the top 3 preferred cosmetic products by consumers in the Asia-Pacific region?
CREATE TABLE consumer_preferences (id INT,consumer_id INT,product_id INT,preference_score INT,country VARCHAR(50)); INSERT INTO consumer_preferences (id,consumer_id,product_id,preference_score,country) VALUES (1,1,101,8,'Asia-Pacific'),(2,2,102,9,'Asia-Pacific'),(3,3,101,7,'Asia-Pacific'),(4,4,103,10,'Asia-Pacific'),(5,5,102,8,'Asia-Pacific');
SELECT product_id, SUM(preference_score) as total_score FROM consumer_preferences WHERE country = 'Asia-Pacific' GROUP BY product_id ORDER BY total_score DESC LIMIT 3;
How many players have reached 'Expert' status in 'Galactic Crusaders' per continent?
CREATE TABLE Continents (ContinentID INT,Continent VARCHAR(255)); INSERT INTO Continents (ContinentID,Continent) VALUES (1,'Africa'); INSERT INTO Continents (ContinentID,Continent) VALUES (2,'Asia'); INSERT INTO Players (PlayerID,PlayerStatus,GameName,ContinentID) VALUES (1,'Expert','Galactic Crusaders',2); INSERT INTO Players (PlayerID,PlayerStatus,GameName,ContinentID) VALUES (2,'Beginner','Galactic Crusaders',1);
SELECT Continent, COUNT(*) as PlayerCount FROM Players JOIN Continents ON Players.ContinentID = Continents.ContinentID WHERE PlayerStatus = 'Expert' AND GameName = 'Galactic Crusaders' GROUP BY Continent;
What is the year the oldest chemical was introduced to the market?
CREATE TABLE chemical_lifecycle (id INT PRIMARY KEY,chemical_name VARCHAR(255),year_introduced INT,production_status VARCHAR(255)); INSERT INTO chemical_lifecycle (id,chemical_name,year_introduced,production_status) VALUES (1,'Hydrochloric Acid',1950,'Produced'); INSERT INTO chemical_lifecycle (id,chemical_name,year_introduced,production_status) VALUES (2,'Sodium Hydroxide',1980,'Discontinued');
SELECT MIN(year_introduced) FROM chemical_lifecycle WHERE production_status = 'Produced';
What is the average price of sustainable clothing items by designer?
CREATE TABLE ClothingItems (ItemID INT,ItemName TEXT,DesignerID INT,IsSustainable BOOLEAN,Price INT); INSERT INTO ClothingItems (ItemID,ItemName,DesignerID,IsSustainable,Price) VALUES (1,'Top',1,true,50),(2,'Pants',2,false,30),(3,'Dress',1,true,75); CREATE TABLE Designers (DesignerID INT,DesignerName TEXT); INSERT INTO Designers (DesignerID,DesignerName) VALUES (1,'DesignerA'),(2,'DesignerB');
SELECT DesignerName, AVG(Price) as AvgSustainablePrice FROM ClothingItems JOIN Designers ON ClothingItems.DesignerID = Designers.DesignerID WHERE IsSustainable = true GROUP BY DesignerName;
Delete all traffic violation records in the city of Los Angeles from the year 2020.
CREATE TABLE la_traffic_violations (id INT,violation_type VARCHAR(255),violation_date TIMESTAMP); INSERT INTO la_traffic_violations (id,violation_type,violation_date) VALUES (1,'Speeding','2020-01-01 12:00:00');
DELETE FROM la_traffic_violations WHERE violation_date BETWEEN '2020-01-01 00:00:00' AND '2020-12-31 23:59:59';
Delete all refined rare earth element quantities from 2021 from the production_data table
CREATE TABLE production_data (id INT PRIMARY KEY,year INT,refined_rare_earth_element TEXT,quantity INT); INSERT INTO production_data (id,year,refined_rare_earth_element,quantity) VALUES (1,2019,'Neodymium',500),(2,2019,'Praseodymium',350),(3,2021,'Neodymium',600),(4,2021,'Praseodymium',400);
DELETE FROM production_data WHERE year = 2021;
How many manned missions have been flown to the Moon?
CREATE TABLE space_missions(id INT,name VARCHAR(255),type VARCHAR(10)); INSERT INTO space_missions(id,name,type) VALUES (1,'Apollo 11','manned'),(2,'Apollo 12','manned');
SELECT COUNT(*) FROM space_missions WHERE type = 'manned' AND name LIKE 'Apollo%';
What is the average billing amount for cases in the 'Southern' region?
CREATE TABLE Regions (CaseID INT,Region VARCHAR(50)); INSERT INTO Regions (CaseID,Region) VALUES (1,'Western'),(2,'Northern'),(3,'Southern'),(4,'Eastern'),(5,'Southern');
SELECT AVG(BillingAmount) FROM CaseBilling INNER JOIN Regions ON CaseBilling.CaseID = Regions.CaseID WHERE Region = 'Southern';
Find the total number of security incidents per severity level
CREATE TABLE security_incidents (id INT,severity VARCHAR(10),description TEXT); INSERT INTO security_incidents (id,severity,description) VALUES (1,'Low','Incident 1 description'),(2,'Medium','Incident 2 description'),(3,'High','Incident 3 description'),(4,'Critical','Incident 4 description');
SELECT severity, COUNT(*) as total FROM security_incidents GROUP BY severity;
How many garment factories are in Cambodia?
CREATE TABLE garment_factories (country VARCHAR(255),factory_id INT,factory_name VARCHAR(255),city VARCHAR(255)); INSERT INTO garment_factories (country,factory_id,factory_name,city) VALUES ('Cambodia',1,'Srey Sros Garment Co.','Phnom Penh'); INSERT INTO garment_factories (country,factory_id,factory_name,city) VALUES ('Cambodia',2,'Grand Twins International','Phnom Penh');
SELECT COUNT(DISTINCT factory_id) FROM garment_factories WHERE country = 'Cambodia';
Identify the number of projects and their respective types for each organization in the urban agriculture domain.
CREATE TABLE orgs (id INT,name TEXT); INSERT INTO orgs (id,name) VALUES (1,'Seeds of Hope'); INSERT INTO orgs (id,name) VALUES (2,'Green Urban'); INSERT INTO orgs (id,name) VALUES (3,'Harvest Together'); CREATE TABLE projects (id INT,org_id INT,name TEXT,type TEXT); INSERT INTO projects (id,org_id,name,type) VALUES (1,1,'Community Garden','Urban Agriculture'); INSERT INTO projects (id,org_id,name,type) VALUES (2,1,'Cooking Classes','Food Justice'); INSERT INTO projects (id,org_id,name,type) VALUES (3,3,'Food Co-op','Urban Agriculture');
SELECT o.name, p.type, COUNT(p.id) FROM orgs o JOIN projects p ON o.id = p.org_id WHERE o.name IN ('Seeds of Hope', 'Green Urban', 'Harvest Together') AND p.type = 'Urban Agriculture' GROUP BY o.name, p.type;
What is the total number of visitors from the US and Canada?
CREATE TABLE visitors (id INT,name TEXT,country TEXT,age INT); INSERT INTO visitors VALUES (1,'John','USA',30);
SELECT SUM(visitors.rows) FROM (SELECT * FROM visitors WHERE country = 'USA' UNION ALL SELECT * FROM visitors WHERE country = 'Canada') AS visitors;
What is the number of employees and their gender diversity for each mine?
CREATE TABLE mine (mine_id INT,mine_name TEXT,location TEXT); CREATE TABLE employee (employee_id INT,mine_id INT,employee_name TEXT,gender TEXT); INSERT INTO mine VALUES (1,'ABC Mine'),(2,'DEF Mine'),(3,'GHI Mine'); INSERT INTO employee VALUES (1,1,'John Doe','Male'),(2,1,'Jane Smith','Female'),(3,2,'Mike Johnson','Male'),(4,3,'Emily Davis','Female'),(5,3,'Alex Nguyen','Non-binary');
SELECT mine_name, gender, COUNT(*) as count FROM employee GROUP BY mine_name, gender;
How many infectious disease cases were reported in New York City in 2020?
CREATE TABLE infectious_disease (id INT,case_number INT,city TEXT,state TEXT,date TEXT); INSERT INTO infectious_disease (id,case_number,city,state,date) VALUES (1,123,'New York City','New York','2020-01-01'); INSERT INTO infectious_disease (id,case_number,city,state,date) VALUES (2,456,'New York City','New York','2020-02-01');
SELECT COUNT(*) FROM infectious_disease WHERE city = 'New York City' AND date BETWEEN '2020-01-01' AND '2020-12-31';
What is the most frequently used smart contract function in the last 14 days?
CREATE TABLE smart_contract_calls (call_id INT,timestamp TIMESTAMP,contract_address VARCHAR(50),function_name VARCHAR(50),caller_address VARCHAR(50),gas_used INT); INSERT INTO smart_contract_calls VALUES (3,'2022-02-03 14:00:00','con3','set','caller2',60000);
SELECT function_name, COUNT(*) OVER (PARTITION BY function_name ORDER BY timestamp ROWS BETWEEN 14 PRECEDING AND CURRENT ROW) as call_count_14d, RANK() OVER (ORDER BY call_count_14d DESC) as function_rank FROM smart_contract_calls WHERE timestamp BETWEEN (CURRENT_TIMESTAMP - INTERVAL '14 days') AND CURRENT_TIMESTAMP ORDER BY call_count_14d DESC
What is the total number of donations and volunteer hours for each program?
CREATE TABLE program (id INT,name VARCHAR(255)); INSERT INTO program (id,name) VALUES (1,'Education'),(2,'Health'),(3,'Environment'); CREATE TABLE donation (id INT,program_id INT,amount DECIMAL(10,2)); INSERT INTO donation (id,program_id,amount) VALUES (1,1,500),(2,2,750),(3,3,600); CREATE TABLE volunteer (id INT,program_id INT,hours INT); INSERT INTO volunteer (id,program_id,hours) VALUES (1,1,25),(2,2,30),(3,3,35);
SELECT p.name, SUM(d.amount) AS total_donation, SUM(v.hours) AS total_volunteer_hours FROM program p LEFT JOIN donation d ON p.id = d.program_id LEFT JOIN volunteer v ON p.id = v.program_id GROUP BY p.id;
How many home games did the New York Yankees win in the 2018 season?
CREATE TABLE baseball_games(id INT,team VARCHAR(50),location VARCHAR(50),result VARCHAR(10),year INT); INSERT INTO baseball_games(id,team,location,result,year) VALUES (1,'New York Yankees','Yankee Stadium','Win',2018),(2,'New York Yankees','Yankee Stadium','Loss',2018),(3,'New York Yankees','Yankee Stadium','Win',2018);
SELECT COUNT(*) FROM baseball_games WHERE team = 'New York Yankees' AND location = 'Yankee Stadium' AND result = 'Win' AND year = 2018;
List the names of all volunteers who participate in community programs.
CREATE TABLE Community_Programs (program_id INT,program_name VARCHAR(100),location VARCHAR(100),PRIMARY KEY (program_id));CREATE TABLE Program_Participants (participant_id INT,participant_name VARCHAR(100),program_id INT,PRIMARY KEY (participant_id),FOREIGN KEY (program_id) REFERENCES Community_Programs(program_id));CREATE TABLE Program_Volunteers (volunteer_id INT,volunteer_name VARCHAR(100),program_id INT,PRIMARY KEY (volunteer_id),FOREIGN KEY (program_id) REFERENCES Community_Programs(program_id));
SELECT Program_Volunteers.volunteer_name FROM Program_Volunteers;
What is the total weight of all shipments from the 'Oceanic Harvest' supplier?
CREATE TABLE Suppliers (id INT,name VARCHAR(50)); CREATE TABLE Shipments (id INT,Supplier_id INT,weight INT); INSERT INTO Suppliers (id,name) VALUES (1,'Oceanic Harvest'); INSERT INTO Shipments (id,Supplier_id,weight) VALUES (1,1,500),(2,1,300);
SELECT SUM(weight) FROM Shipments WHERE Supplier_id = (SELECT id FROM Suppliers WHERE name = 'Oceanic Harvest');
Which artist has the highest number of concert appearances in the USA?
CREATE TABLE ConcertAppearances (AppearanceID INT,Artist VARCHAR(255),Venue VARCHAR(255),Country VARCHAR(255),Year INT,Appearances INT); INSERT INTO ConcertAppearances VALUES (10,'Bruce Springsteen','Madison Square Garden','USA',2022,5); INSERT INTO ConcertAppearances VALUES (11,'Billy Joel','Madison Square Garden','USA',2022,12);
SELECT Artist, MAX(Appearances) FROM ConcertAppearances WHERE Country = 'USA' GROUP BY Artist;
What is the total quantity of fish by species in farms that use recirculating aquaculture systems (RAS)?
CREATE TABLE fish_farms (id INT,name TEXT,location TEXT,water_type TEXT,system_type TEXT); INSERT INTO fish_farms (id,name,location,water_type,system_type) VALUES (1,'Farm K','Cape Town','Saltwater','RAS'); INSERT INTO fish_farms (id,name,location,water_type,system_type) VALUES (2,'Farm L','Rio de Janeiro','Freshwater','RAS'); CREATE TABLE fish_species (id INT,name TEXT); INSERT INTO fish_species (id,name) VALUES (1,'Sardines'); INSERT INTO fish_species (id,name) VALUES (2,'Tuna'); CREATE TABLE fish_inventory (fish_farm_id INT,fish_species_id INT,quantity INT); INSERT INTO fish_inventory (fish_farm_id,fish_species_id,quantity) VALUES (1,1,500); INSERT INTO fish_inventory (fish_farm_id,fish_species_id,quantity) VALUES (1,2,300); INSERT INTO fish_inventory (fish_farm_id,fish_species_id,quantity) VALUES (2,1,400); INSERT INTO fish_inventory (fish_farm_id,fish_species_id,quantity) VALUES (2,2,600);
SELECT fs.name AS species_name, SUM(fi.quantity) AS total_quantity FROM fish_farms ff JOIN fish_inventory fi ON ff.id = fi.fish_farm_id JOIN fish_species fs ON fi.fish_species_id = fs.id WHERE ff.system_type = 'RAS' GROUP BY fs.name;
Which artists have had exhibitions in both 'New York' and 'Los Angeles'?
CREATE TABLE artist_exhibitions (id INT,artist_id INT,city VARCHAR(20)); INSERT INTO artist_exhibitions (id,artist_id,city) VALUES (1,1,'New York'),(2,2,'Los Angeles'),(3,3,'Los Angeles'),(4,1,'Los Angeles');
SELECT artist_id FROM artist_exhibitions WHERE city IN ('New York', 'Los Angeles') GROUP BY artist_id HAVING COUNT(DISTINCT city) = 2;