instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
Show the total number of medals won by the 'olympic_athletes' table in descending order.
CREATE TABLE olympic_athletes (athlete_id INT,name VARCHAR(50),medals INT);
SELECT name, SUM(medals) as total_medals FROM olympic_athletes GROUP BY name ORDER BY total_medals DESC;
What is the total number of containers shipped to the Caribbean from all ports in the last quarter?
CREATE TABLE ports (id INT,name TEXT,location TEXT); INSERT INTO ports (id,name,location) VALUES (1,'Port of Kingston','Kingston,Jamaica'); CREATE TABLE shipments (id INT,container_count INT,departure_port_id INT,arrival_region TEXT,shipment_date DATE); INSERT INTO shipments (id,container_count,departure_port_id,arriva...
SELECT SUM(container_count) FROM shipments WHERE arrival_region = 'Caribbean' AND shipment_date >= DATE_SUB(CURRENT_DATE, INTERVAL 3 MONTH);
What is the total sales for each category?
CREATE TABLE Sales (SaleID int,ProductID int,ProductName varchar(50),Category varchar(50),SalesNumber int); INSERT INTO Sales (SaleID,ProductID,ProductName,Category,SalesNumber) VALUES (1,1,'Eye Shadow A','Eye Shadow',100),(2,2,'Eye Shadow B','Eye Shadow',200),(3,3,'Lipstick C','Lipstick',300);
SELECT Category, SUM(SalesNumber) as TotalSales FROM Sales GROUP BY Category;
Who was the first female astronaut from India?
CREATE TABLE astronauts (id INT,name VARCHAR(255),country VARCHAR(255),first_flight DATE); INSERT INTO astronauts (id,name,country,first_flight) VALUES (1,'Kalpana Chawla','India','1997-11-19');
SELECT name FROM astronauts WHERE country = 'India' AND id = (SELECT MIN(id) FROM astronauts WHERE country = 'India' AND gender = 'Female');
How many technology initiatives were launched in the year 2021 that are related to digital divide?
CREATE TABLE initiatives (id INT,name VARCHAR(255),launch_date DATE,type VARCHAR(255)); INSERT INTO initiatives (id,name,launch_date,type) VALUES (1,'Digital Divide Project A','2021-02-15','Digital Divide'),(2,'Social Good Project B','2020-12-01','Social Good'),(3,'Digital Divide Project C','2021-04-20','Digital Divide...
SELECT COUNT(*) FROM initiatives WHERE EXTRACT(YEAR FROM launch_date) = 2021 AND type = 'Digital Divide';
Find the total number of marine research projects funded by the European Union and the United States in the last 3 years.
CREATE TABLE research_projects (id INT,country VARCHAR(30),funder VARCHAR(30),project_name VARCHAR(50),date DATE); INSERT INTO research_projects (id,country,funder,project_name,date) VALUES (1,'France','European Union','Marine Life Research','2021-04-15'); INSERT INTO research_projects (id,country,funder,project_name,d...
SELECT SUM(total) FROM (SELECT COUNT(*) AS total FROM research_projects WHERE country = 'European Union' AND date >= DATE_SUB(CURRENT_DATE, INTERVAL 3 YEAR) UNION ALL SELECT COUNT(*) AS total FROM research_projects WHERE country = 'United States' AND date >= DATE_SUB(CURRENT_DATE, INTERVAL 3 YEAR)) AS combined_funders;
Which military equipment has the longest average time between maintenance, and what is this average time?
CREATE TABLE Equipment_Maintenance (Equipment_Type VARCHAR(255),Maintenance_Date DATE); INSERT INTO Equipment_Maintenance (Equipment_Type,Maintenance_Date) VALUES ('Aircraft','2020-01-01'),('Vehicles','2020-02-15'),('Naval','2020-03-01'),('Aircraft','2020-04-10'),('Weaponry','2020-05-01');
SELECT Equipment_Type, AVG(DATEDIFF(day, LAG(Maintenance_Date) OVER (PARTITION BY Equipment_Type ORDER BY Maintenance_Date), Maintenance_Date)) as Avg_Maintenance_Interval FROM Equipment_Maintenance GROUP BY Equipment_Type ORDER BY Avg_Maintenance_Interval DESC;
List the number of community health workers added in each region in the first quarter of the year, for the past 3 years?
CREATE TABLE WorkforceHistory (WorkerID INT,Region VARCHAR(255),HireDate DATE); INSERT INTO WorkforceHistory (WorkerID,Region,HireDate) VALUES (1,'Northeast','2020-02-01'); INSERT INTO WorkforceHistory (WorkerID,Region,HireDate) VALUES (2,'Southeast','2021-01-10'); INSERT INTO WorkforceHistory (WorkerID,Region,HireDate...
SELECT Region, COUNT(*) as NewWorkers FROM WorkforceHistory WHERE HireDate >= DATE_SUB(DATE_SUB(CURRENT_DATE, INTERVAL 1 DAY), INTERVAL 3 YEAR) AND EXTRACT(MONTH FROM HireDate) BETWEEN 1 AND 3 GROUP BY Region;
What is the total production in the 'coal' mine?
CREATE TABLE production (id INT,mine VARCHAR(20),production DECIMAL(10,2)); INSERT INTO production (id,mine,production) VALUES (1,'coal',1800.00),(2,'gold',1200.00),(3,'silver',800.00);
SELECT SUM(production) FROM production WHERE mine = 'coal';
Who are the top 3 actors with the most movies in the Media database?
CREATE TABLE Actors (Actor VARCHAR(50),MovieTitle VARCHAR(50),ReleaseYear INT); INSERT INTO Actors (Actor,MovieTitle,ReleaseYear) VALUES ('Johnny Depp','Pirates of the Caribbean: The Curse of the Black Pearl',2003),('Tom Hanks','Forrest Gump',1994),('Leonardo DiCaprio','Titanic',1997),('Johnny Depp','Charlie and the Ch...
SELECT Actor, COUNT(*) as MovieCount FROM Actors GROUP BY Actor ORDER BY MovieCount DESC LIMIT 3;
What is the most recent launch date for a Chinese space mission?
CREATE TABLE chinese_space_missions (id INT,launch_company VARCHAR(255),launch_date DATE); INSERT INTO chinese_space_missions (id,launch_company,launch_date) VALUES (1,'China National Space Administration','2003-10-15'),(2,'China National Space Administration','2011-09-29'),(3,'China National Space Administration','201...
SELECT MAX(launch_date) FROM chinese_space_missions;
Insert a new record into the "donors" table
CREATE TABLE donors (donor_id INT PRIMARY KEY,first_name VARCHAR(50),last_name VARCHAR(50),email VARCHAR(100),donation_amount DECIMAL(10,2),donation_date DATE);
INSERT INTO donors (donor_id, first_name, last_name, email, donation_amount, donation_date) VALUES (2001, 'Jane', 'Smith', 'jane.smith@example.com', 500.00, '2022-08-01');
What is the sum of embodied_carbon_kg_co2 for all materials in the sustainable_materials table?
CREATE TABLE sustainable_materials (material_name TEXT,recycled_content_percentage FLOAT,embodied_carbon_kg_co2 FLOAT); INSERT INTO sustainable_materials (material_name,recycled_content_percentage,embodied_carbon_kg_co2) VALUES ('Bamboo',90,0.45),('Reclaimed Wood',80,0.75),('Straw Bale',100,1.3);
SELECT SUM(embodied_carbon_kg_co2) FROM sustainable_materials;
What is the trend of Samarium price from 2017 to 2021?
CREATE TABLE Samarium_Price (year INT,price FLOAT); INSERT INTO Samarium_Price (year,price) VALUES (2015,150),(2016,170),(2017,190),(2018,210),(2019,230),(2020,250),(2021,270);
SELECT year, price FROM Samarium_Price WHERE year BETWEEN 2017 AND 2021;
Find the total value of agricultural innovation investments in Asia in 2020.
CREATE SCHEMA if not exists rural_dev; use rural_dev; CREATE TABLE if not exists agri_innovation_investment (year INT,country VARCHAR(255),farmer_id INT,amount FLOAT,PRIMARY KEY (year,country,farmer_id));
SELECT SUM(amount) as total_investment FROM rural_dev.agri_innovation_investment WHERE country IN (SELECT country FROM rural_dev.countries WHERE region = 'Asia') AND year = 2020;
What is the name and price of the most expensive product in each category?
CREATE TABLE products (id INT PRIMARY KEY,name VARCHAR(50),price DECIMAL(5,2),category VARCHAR(50),subcategory VARCHAR(50)); INSERT INTO products (id,name,price,category,subcategory) VALUES (1,'Laptop',999.99,'Electronics','Computers'); INSERT INTO products (id,name,price,category,subcategory) VALUES (2,'Phone',599.99,...
SELECT name, price, category FROM (SELECT name, price, category, ROW_NUMBER() OVER (PARTITION BY category ORDER BY price DESC) rn FROM products) t WHERE rn = 1;
List all building permits issued in New York City in 2020 with a value greater than $1 million.
CREATE TABLE building_permits (id INT,permit_number VARCHAR(50),issue_date DATE,value FLOAT,city VARCHAR(50));
SELECT permit_number, issue_date FROM building_permits WHERE city = 'New York City' AND issue_date BETWEEN '2020-01-01' AND '2020-12-31' AND value > 1000000.00
Which programs had the highest increase in attendance compared to the same period last year?
CREATE TABLE Programs (ProgramID INT,ProgramDate DATE,ProgramAttendance INT); INSERT INTO Programs (ProgramID,ProgramDate,ProgramAttendance) VALUES (1,'2021-06-01',50),(2,'2021-07-01',75),(3,'2021-08-01',100); INSERT INTO Programs (ProgramID,ProgramDate,ProgramAttendance) VALUES (1,'2022-06-01',75),(2,'2022-07-01',90),...
SELECT ProgramID, (ProgramAttendance - (SELECT ProgramAttendance FROM Programs WHERE ProgramID = P.ProgramID AND ProgramDate LIKE CONCAT(YEAR(ProgramDate) - 1, '%') AND ProgramID = P.ProgramID)) * 100 / (SELECT ProgramAttendance FROM Programs WHERE ProgramID = P.ProgramID AND ProgramDate LIKE CONCAT(YEAR(ProgramDate) -...
How many volunteers are needed to reach a total of 500 volunteer hours in each region?
CREATE TABLE VolunteerHours (VolunteerHourID INT,VolunteerID INT,Hours INT,HourDate DATE); CREATE TABLE Volunteers (VolunteerID INT,VolunteerName VARCHAR(50),Region VARCHAR(50));
SELECT Volunteers.Region, SUM(VolunteerHours.Hours) / 500 AS NeededVolunteers FROM Volunteers INNER JOIN VolunteerHours ON Volunteers.VolunteerID = VolunteerHours.VolunteerID GROUP BY Volunteers.Region;
How many open data initiatives were launched in California in 2020?
CREATE TABLE open_data_initiatives (id INT,state TEXT,launch_date DATE); INSERT INTO open_data_initiatives (id,state,launch_date) VALUES (1,'California','2020-01-01'),(2,'New York','2019-12-31'),(3,'California','2020-03-15'),(4,'Texas','2019-11-25');
SELECT COUNT(*) FROM open_data_initiatives WHERE state = 'California' AND EXTRACT(YEAR FROM launch_date) = 2020;
How many employees were promoted in the finance department in the last 6 months?
CREATE TABLE Promotions (PromotionID INT,EmployeeID INT,Department VARCHAR(20),PromotionDate DATE); INSERT INTO Promotions (PromotionID,EmployeeID,Department,PromotionDate) VALUES (1,5,'Finance','2022-01-05'),(2,6,'Finance','2022-06-15');
SELECT COUNT(*) FROM Promotions WHERE Department = 'Finance' AND PromotionDate >= DATE_SUB(CURDATE(), INTERVAL 6 MONTH);
Find biotech startups and their funding amounts
CREATE TABLE startups (id INT,name VARCHAR(50),domain VARCHAR(50),location VARCHAR(50)); INSERT INTO startups (id,name,domain,location) VALUES (1,'BioGenesis','Genetic Engineering','CA'); INSERT INTO startups (id,name,domain,location) VALUES (2,'BioSolutions','Biosensors','NY'); CREATE TABLE funding (id INT,startup_id ...
SELECT s.name, f.amount FROM startups s JOIN funding f ON s.id = f.startup_id;
What is the total number of attendees for dance and music events, excluding repeating attendees?
CREATE TABLE event_attendance (id INT,attendee_id INT,event_type VARCHAR(10)); INSERT INTO event_attendance (id,attendee_id,event_type) VALUES (1,101,'dance'),(2,101,'music'),(3,102,'dance'),(4,103,'music');
SELECT event_type, COUNT(DISTINCT attendee_id) AS unique_attendees FROM event_attendance GROUP BY event_type WHERE event_type IN ('dance', 'music')
List all missions conducted by the European Space Agency (ESA)
CREATE TABLE missions (agency VARCHAR(255),mission_name VARCHAR(255),start_date DATE,end_date DATE); INSERT INTO missions (agency,mission_name,start_date,end_date) VALUES ('ESA','Mission1','2005-04-16','2007-08-24'); INSERT INTO missions (agency,mission_name,start_date,end_date) VALUES ('NASA','Mission2','2010-02-22','...
SELECT mission_name FROM missions WHERE agency = 'ESA';
Calculate the average length and diameter of pipeline segments that intersect with the Keystone XL Pipeline.
CREATE TABLE PipelineIntersections (IntersectionID INT,PipelineName VARCHAR(50),SegmentID INT,SegmentName VARCHAR(50),Length DECIMAL(10,2),Diameter DECIMAL(10,2)); INSERT INTO PipelineIntersections (IntersectionID,PipelineName,SegmentID,SegmentName,Length,Diameter) VALUES (1,'Keystone XL',1,'Alaska Pipeline Segment 1',...
SELECT PipelineName, AVG(Length) AS Avg_Length, AVG(Diameter) AS Avg_Diameter FROM PipelineIntersections WHERE PipelineName = 'Keystone XL' GROUP BY PipelineName;
What is the average biomass of fish for each species across different farms?
CREATE TABLE Farm (FarmID INT,FarmName VARCHAR(255)); CREATE TABLE Stock (StockID INT,FarmID INT,FishSpecies VARCHAR(255),Weight DECIMAL(10,2),StockDate DATE); INSERT INTO Farm (FarmID,FarmName) VALUES (1,'Farm A'),(2,'Farm B'),(3,'Farm C'); INSERT INTO Stock (StockID,FarmID,FishSpecies,Weight,StockDate) VALUES (1,1,'T...
SELECT FishSpecies, AVG(Weight) OVER (PARTITION BY FishSpecies) as AvgBiomass FROM Stock JOIN Farm ON Stock.FarmID = Farm.FarmID;
How many environmental impact assessments were conducted in Europe?
CREATE TABLE impact_assessments (id INT,region VARCHAR(20),num_assessments INT); INSERT INTO impact_assessments (id,region,num_assessments) VALUES (1,'Asia-Pacific',100),(2,'Americas',50),(3,'Europe',150);
SELECT SUM(num_assessments) FROM impact_assessments WHERE region = 'Europe';
What is the total number of lines of code in all smart contracts written in Rust?
CREATE TABLE public.smart_contracts (id SERIAL PRIMARY KEY,name VARCHAR(100),project_id INT,language VARCHAR(50),lines_of_code INT); INSERT INTO public.smart_contracts (name,project_id,language,lines_of_code) VALUES ('Smart Contract 1',1,'Solidity',500); INSERT INTO public.smart_contracts (name,project_id,language,line...
SELECT SUM(lines_of_code) FROM public.smart_contracts WHERE language = 'Rust';
Which cities have held the fewest unique events, and how many events have been held in each?
CREATE TABLE events (id INT,name VARCHAR(255),city VARCHAR(255)); INSERT INTO events (id,name,city) VALUES (1,'Concert','New York'),(2,'Play','Los Angeles'),(3,'Exhibit','Chicago'),(4,'Festival','Chicago'),(5,'Workshop','San Francisco'),(6,'Recital','New York'),(7,'Lecture','Los Angeles');
SELECT city, COUNT(DISTINCT id) FROM events GROUP BY city ORDER BY COUNT(DISTINCT id) ASC;
What is the average hotel rating in the United States?
CREATE TABLE hotels (hotel_id INT,hotel_name VARCHAR(255),country VARCHAR(255),rating FLOAT); INSERT INTO hotels (hotel_id,hotel_name,country,rating) VALUES (1,'Hotel X','USA',4.5),(2,'Hotel Y','USA',3.9),(3,'Hotel Z','Canada',4.2);
SELECT AVG(rating) FROM hotels WHERE country = 'USA';
What is the maximum claim amount for policyholders with 'home insurance' policies?
CREATE TABLE claims (id INT,policy_id INT,claim_amount INT); INSERT INTO claims (id,policy_id,claim_amount) VALUES (1,1,5000),(2,2,3000),(3,3,10000); CREATE TABLE policyholders (id INT,policy_type VARCHAR(20)); INSERT INTO policyholders (id,policy_type) VALUES (1,'car insurance'),(2,'home insurance'),(3,'home insurance...
SELECT MAX(claim_amount) FROM claims JOIN policyholders ON claims.policy_id = policyholders.id WHERE policy_type = 'home insurance';
Calculate the average age of users who streamed songs released in 2021.
CREATE TABLE artists (id INT PRIMARY KEY,name VARCHAR(255),genre VARCHAR(255),country VARCHAR(255)); CREATE TABLE songs (id INT PRIMARY KEY,title VARCHAR(255),artist_id INT,released DATE); CREATE TABLE streams (id INT PRIMARY KEY,song_id INT,user_id INT,stream_date DATE,FOREIGN KEY (song_id) REFERENCES songs(id)); CREA...
SELECT AVG(u.age) AS avg_age FROM users u JOIN streams s ON u.id = s.user_id JOIN songs t ON s.song_id = t.id WHERE YEAR(t.released) = 2021;
What is the percentage of students who have access to open educational resources in each country?
CREATE TABLE students (student_id INT,student_name TEXT,country TEXT); INSERT INTO students VALUES (1,'Sophia Garcia','US'),(2,'Alex Wang','Canada'),(3,'Emma Johnson','UK'),(4,'Liam Thompson','Australia'),(5,'Ava Lee','New Zealand'); CREATE TABLE open_educational_resources (oer_id INT,student_id INT,has_access BOOLEAN)...
SELECT s.country, 100.0 * AVG(CASE WHEN oer.has_access THEN 1.0 ELSE 0.0 END) as pct_students_oer_access FROM students s JOIN open_educational_resources oer ON s.student_id = oer.student_id GROUP BY s.country;
What is the total number of hybrid vehicles in the 'vehicle_sales' table?
CREATE TABLE schema.vehicle_sales (vehicle_id INT,vehicle_type VARCHAR(50),sale_date DATE,quantity INT); INSERT INTO schema.vehicle_sales (vehicle_id,vehicle_type,sale_date,quantity) VALUES (1,'hybrid','2021-01-01',200),(2,'electric','2021-01-01',300),(3,'fossil_fuel','2021-01-01',400);
SELECT SUM(quantity) FROM schema.vehicle_sales WHERE vehicle_type = 'hybrid';
Find the total production of Praseodymium and Neodymium for each year in the given dataset?
CREATE TABLE RareEarthElements_Production (year INT,element TEXT,production INT); INSERT INTO RareEarthElements_Production (year,element,production) VALUES (2019,'Praseodymium',500); INSERT INTO RareEarthElements_Production (year,element,production) VALUES (2019,'Neodymium',1000); INSERT INTO RareEarthElements_Producti...
SELECT year, SUM(production) as total_production FROM RareEarthElements_Production WHERE element IN ('Praseodymium', 'Neodymium') GROUP BY year;
What are the total greenhouse gas emissions for each mining operation type?
CREATE TABLE MiningOperationType (id INT,name VARCHAR(255)); INSERT INTO MiningOperationType (id,name) VALUES (1,'Open Pit'),(2,'Underground'); CREATE TABLE GHGEmissions (operation_type_id INT,quantity INT); INSERT INTO GHGEmissions (operation_type_id,quantity) VALUES (1,2000),(2,1500);
SELECT m.name, SUM(g.quantity) AS ghg_emissions FROM MiningOperationType m INNER JOIN GHGEmissions g ON m.id = g.operation_type_id GROUP BY m.name;
List the diversity metrics for companies, including the percentage of LGBTQ+ founders and the average age of founders.
CREATE TABLE companies (id INT,name TEXT); CREATE TABLE founders (id INT,company_id INT,name TEXT,gender TEXT,sexual_orientation TEXT,birthdate DATE); INSERT INTO companies (id,name) VALUES (1,'GreenTech'),(2,'BlueOcean'),(3,'SolarWinds'); INSERT INTO founders (id,company_id,name,gender,sexual_orientation,birthdate) VA...
SELECT companies.name, AVG(YEAR(CURRENT_DATE) - YEAR(founders.birthdate)) as avg_age, COUNT(*) FILTER (WHERE founders.sexual_orientation IN ('Queer', 'Pansexual', 'Gay', 'Lesbian', 'Asexual')) * 100.0 / COUNT(*) as lgbtq_founders_percentage FROM companies INNER JOIN founders ON companies.id = founders.company_id GROUP ...
Update the population of 'Lion' in the 'animal_population' table to 900.
CREATE TABLE animal_population (id INT,species VARCHAR(255),population INT); INSERT INTO animal_population (id,species,population) VALUES (1,'Tiger',500),(2,'Elephant',2000),(3,'Lion',800),(4,'Giraffe',1500);
UPDATE animal_population SET population = 900 WHERE species = 'Lion';
How many agricultural innovation projects were implemented in Asia?
CREATE TABLE agricultural_innovation (id INT,project_name VARCHAR(50),location VARCHAR(50),implementation_date DATE); INSERT INTO agricultural_innovation (id,project_name,location,implementation_date) VALUES (1,'Smart Irrigation','China','2015-02-01');
SELECT COUNT(*) FROM agricultural_innovation WHERE location LIKE '%Asia%';
Summarize the number of patents granted to each country
CREATE TABLE patents (id INT,company VARCHAR(255),country VARCHAR(255),num_patents INT); INSERT INTO patents (id,company,country,num_patents) VALUES (1,'Acme Inc','USA',10),(2,'Beta Corp','USA',15),(3,'Gamma Inc','Canada',5),(4,'Delta Ltd','UK',8),(5,'Epsilon Inc','Germany',12);
SELECT country, SUM(num_patents) as total_patents FROM patents GROUP BY country;
How many 'models' are represented in the 'model_data' table?
CREATE TABLE model_data (id INT,model_name TEXT); INSERT INTO model_data (id,model_name) VALUES (1,'modelA'),(2,'modelB'),(3,'modelC'),(4,'modelD');
SELECT COUNT(DISTINCT model_name) FROM model_data;
Find the total number of electric and hybrid buses in the public transportation systems of Tokyo and Berlin.
CREATE TABLE tokyo_buses (type VARCHAR(20),quantity INT); INSERT INTO tokyo_buses (type,quantity) VALUES ('electric',1500),('hybrid',500); CREATE TABLE berlin_buses (type VARCHAR(20),quantity INT); INSERT INTO berlin_buses (type,quantity) VALUES ('electric',2000),('hybrid',700);
SELECT SUM(quantity) FROM ( SELECT quantity FROM tokyo_buses WHERE type IN ('electric', 'hybrid') UNION SELECT quantity FROM berlin_buses WHERE type IN ('electric', 'hybrid') ) AS combined_quantities;
How many transactions were there in Michigan in March 2021?
CREATE TABLE sales (id INT,state VARCHAR(20),quantity INT,month INT,year INT);
SELECT COUNT(*) FROM sales WHERE state = 'Michigan' AND month = 3 AND year = 2021;
How many investments were made in the consumer discretionary sector in Q1 2023?
CREATE TABLE investments (id INT,company_id INT,investment_date DATE); CREATE TABLE companies (id INT,name VARCHAR(255),sector VARCHAR(255)); INSERT INTO companies (id,name,sector) VALUES (1,'Starbucks','Consumer Discretionary'),(2,'Microsoft','Technology'),(3,'Amazon','Consumer Discretionary'); INSERT INTO investments...
SELECT COUNT(*) FROM investments i JOIN companies c ON i.company_id = c.id WHERE c.sector = 'Consumer Discretionary' AND YEAR(i.investment_date) = 2023 AND QUARTER(i.investment_date) = 1;
Delete all records in the 'vessel_movements' table that occurred on a specific date.
CREATE TABLE vessel_movements (id INT,vessel_id INT,movement_date DATE,PRIMARY KEY(id));
DELETE FROM vessel_movements WHERE movement_date = '2022-02-14';
List the number of albums released by each record label, ordered by the total number of albums in descending order.
CREATE TABLE record_labels (label_id INT,label_name VARCHAR(50)); INSERT INTO record_labels (label_id,label_name) VALUES (1,'Universal Music Group'),(2,'Sony Music Entertainment'),(3,'Warner Music Group'); CREATE TABLE album_details (album_id INT,label_id INT,released_year INT); INSERT INTO album_details (album_id,labe...
SELECT label_name, COUNT(album_id) as album_count FROM album_details INNER JOIN record_labels ON album_details.label_id = record_labels.label_id GROUP BY label_name ORDER BY album_count DESC;
What is the average dissolved oxygen level (in mg/L) for each species in Tank17?
CREATE TABLE Tank17 (species VARCHAR(20),dissolved_oxygen FLOAT); INSERT INTO Tank17 (species,dissolved_oxygen) VALUES ('Salmon',6.5),('Trout',7.2),('Tilapia',5.8);
SELECT species, AVG(dissolved_oxygen) FROM Tank17 GROUP BY species;
What is the name and length of the longest bridge in California?
CREATE TABLE infrastructure.bridges (bridge_id INT,name VARCHAR(255),length FLOAT,state VARCHAR(2)); INSERT INTO infrastructure.bridges (bridge_id,name,length,state) VALUES (1,'Golden Gate',2737.4,'CA'),(2,'Verrazano-Narrows',4868.6,'NY');
SELECT name, length FROM infrastructure.bridges WHERE state = 'CA' AND length = (SELECT MAX(length) FROM infrastructure.bridges WHERE state = 'CA');
What are the energy efficiency stats for each state?
CREATE TABLE energy_efficiency (state VARCHAR(255),energy_efficiency_score INT); INSERT INTO energy_efficiency (state,energy_efficiency_score) VALUES ('California',90); INSERT INTO energy_efficiency (state,energy_efficiency_score) VALUES ('Texas',75);
SELECT state, energy_efficiency_score FROM energy_efficiency;
What are the average production figures for offshore wells in the Gulf of Mexico?
CREATE TABLE offshore_wells (well_id INT,location VARCHAR(255),production_figures FLOAT); INSERT INTO offshore_wells (well_id,location,production_figures) VALUES (1,'Gulf of Mexico',10000); INSERT INTO offshore_wells (well_id,location,production_figures) VALUES (2,'North Sea',12000);
SELECT AVG(production_figures) FROM offshore_wells WHERE location = 'Gulf of Mexico';
What is the percentage of coffee shops using fair trade coffee beans, by city?
CREATE TABLE CoffeeShops (ShopID int,City varchar(50),Beans varchar(50));
SELECT City, ROUND(COUNT(*) * 100.0 / (SELECT COUNT(*) FROM CoffeeShops WHERE City = outer_table.City), 2) as percentage FROM CoffeeShops WHERE Beans = 'fair trade' GROUP BY City;
What is the total revenue for fair trade certified products in each product category?
CREATE TABLE revenue (product_id INT,category VARCHAR(255),revenue DECIMAL(10,2),fair_trade_certified BOOLEAN); INSERT INTO revenue (product_id,category,revenue,fair_trade_certified) VALUES (1,'CategoryA',1200.00,true),(2,'CategoryB',2500.00,false),(3,'CategoryA',750.00,true);
SELECT category, fair_trade_certified, SUM(revenue) AS total_revenue FROM revenue GROUP BY category, fair_trade_certified;
What is the total number of artworks by each artist from France?
CREATE TABLE Artists (ArtistID INT,ArtistName VARCHAR(100),Nationality VARCHAR(50)); INSERT INTO Artists (ArtistID,ArtistName,Nationality) VALUES (1,'Pablo Picasso','Spanish'); INSERT INTO Artists (ArtistID,ArtistName,Nationality) VALUES (2,'Claude Monet','French'); INSERT INTO Artists (ArtistID,ArtistName,Nationality)...
SELECT A.ArtistName, COUNT(AW.ArtworkID) as ArtworkCount FROM ArtWorks AW JOIN Artists A ON AW.ArtistID = A.ArtistID WHERE A.Nationality = 'French' GROUP BY A.ArtistName;
Find the total number of wells drilled in Texas and California
CREATE TABLE wells (state VARCHAR(2),num_wells INT); INSERT INTO wells (state,num_wells) VALUES ('TX',1200),('CA',800);
SELECT SUM(num_wells) FROM wells WHERE state IN ('TX', 'CA');
Update the title to 'Physician' for the record with the name 'Jane Doe' in the 'rural_healthcare_workers' table
CREATE TABLE rural_healthcare_workers (id INT,name VARCHAR(50),title VARCHAR(50),location VARCHAR(50));
UPDATE rural_healthcare_workers SET title = 'Physician' WHERE name = 'Jane Doe';
What is the maximum 'green_score' in the 'green_buildings2' table?
CREATE TABLE green_buildings2 (id INT,city VARCHAR(20),green_score INT); INSERT INTO green_buildings2 (id,city,green_score) VALUES (1,'Seattle',95),(2,'Portland',90),(3,'Las_Vegas',85);
SELECT MAX(green_score) FROM green_buildings2;
Which sustainable tourism activities in Australia have the highest revenue?
CREATE TABLE sustainable_tourism_australia (activity_id INT,activity_name TEXT,country TEXT,revenue FLOAT); INSERT INTO sustainable_tourism_australia (activity_id,activity_name,country,revenue) VALUES (1,'Eco-Friendly Wildlife Tours','Australia',80000),(2,'Sustainable Adventure Activities','Australia',70000),(3,'Green ...
SELECT activity_name, revenue FROM sustainable_tourism_australia WHERE country = 'Australia' ORDER BY revenue DESC;
How many tickets were sold for music concerts in the last 6 months by city?
CREATE TABLE music_concerts (concert_id INT,concert_name VARCHAR(50),concert_date DATE); CREATE TABLE concert_ticket_sales (concert_id INT,tickets_sold INT); INSERT INTO music_concerts (concert_id,concert_name,concert_date) VALUES (1,'Classical Music Concert','2022-01-01'),(2,'Jazz Night','2022-02-10'),(3,'Rock Festiva...
SELECT c.city, SUM(s.tickets_sold) as tickets_sold FROM (SELECT concert_id, city FROM music_concerts WHERE concert_date >= DATEADD(month, -6, GETDATE())) c INNER JOIN concert_ticket_sales s ON c.concert_id = s.concert_id GROUP BY c.city;
What is the minimum carbon sequestration in 'European Forests' in 2020?
CREATE TABLE EuropeanForests (region VARCHAR(20),year INT,carbon_sequestration FLOAT); INSERT INTO EuropeanForests (region,year,carbon_sequestration) VALUES ('European Forests',2015,11.22),('European Forests',2016,22.33),('European Forests',2017,33.44),('European Forests',2018,44.55),('European Forests',2019,55.66),('E...
SELECT MIN(carbon_sequestration) FROM EuropeanForests WHERE region = 'European Forests' AND year = 2020;
What is the total CO2 emission for each Arctic country in the last 5 years?
CREATE TABLE co2_emissions (id INT,country VARCHAR(255),date DATE,emission FLOAT); INSERT INTO co2_emissions (id,country,date,emission) VALUES (1,'Canada','2018-01-01',500.0),(2,'USA','2018-01-01',700.0);
SELECT country, SUM(emission) FROM co2_emissions WHERE date >= DATEADD(year, -5, CURRENT_DATE) GROUP BY country;
Delete records of artists who have not received any funding.
CREATE TABLE Artists (artist_id INT,artist_name VARCHAR(255),community_identifier VARCHAR(255)); CREATE TABLE Funding (funding_id INT,artist_id INT,funding_amount DECIMAL(10,2));
DELETE FROM Artists WHERE artist_id NOT IN (SELECT artist_id FROM Funding);
What is the average yield for Soybean crops under cloudy weather conditions?
CREATE TABLE crop_yield (crop VARCHAR(20),yield INT,weather_condition VARCHAR(20),location VARCHAR(20)); INSERT INTO crop_yield (crop,yield,weather_condition,location) VALUES ('Corn',120,'Sunny','Iowa'),('Soybean',80,'Cloudy','Iowa');
SELECT c.crop, AVG(c.yield) FROM crop_yield c WHERE c.crop = 'Soybean' AND c.weather_condition = 'Cloudy' GROUP BY c.crop;
What is the percentage of emergency calls with a response time below the average, for each type of call?
CREATE TABLE emergency_calls (id INT,call_type TEXT,response_time FLOAT);
SELECT call_type, AVG(response_time) as avg_response_time, 100.0 * SUM(CASE WHEN response_time < (SELECT AVG(response_time) FROM emergency_calls) THEN 1 ELSE 0 END) / COUNT(*) as pct_below_avg FROM emergency_calls GROUP BY call_type;
List the unique first names of all instructors who have taught more than 5 different classes in the entire year of 2021.
CREATE TABLE Instructors (InstructorID int,FirstName varchar(20)); INSERT INTO Instructors (InstructorID,FirstName) VALUES (1,'John'); CREATE TABLE Classes (ClassID int,InstructorID int,ClassType varchar(10)); INSERT INTO Classes (ClassID,InstructorID,ClassType) VALUES (1,1,'Yoga');
SELECT DISTINCT FirstName FROM Instructors i WHERE i.InstructorID IN (SELECT c.InstructorID FROM Classes c GROUP BY c.InstructorID HAVING COUNT(DISTINCT c.ClassType) > 5);
What is the maximum budget allocated for any category in the North region in the year 2020?
CREATE TABLE Budget (Year INT,Region VARCHAR(50),Category VARCHAR(50),Amount INT); INSERT INTO Budget (Year,Region,Category,Amount) VALUES (2020,'North','Education',5000000),(2020,'North','Public Transportation',6000000);
SELECT MAX(Amount) FROM Budget WHERE Year = 2020 AND Region = 'North';
Update the 'smart_contracts' table to set the 'contract_status' to 'Inactive' for all contracts with a 'contract_size' greater than 50000
CREATE TABLE smart_contracts (contract_id INT PRIMARY KEY,contract_name VARCHAR(100),contract_size INT,contract_status VARCHAR(50));
UPDATE smart_contracts SET contract_status = 'Inactive' WHERE contract_size > 50000;
What is the percentage of households in the state of California that have implemented water conservation measures?
CREATE TABLE households (household_id INT,state VARCHAR(20),conservation_measures BOOLEAN); INSERT INTO households (household_id,state,conservation_measures) VALUES (1,'California',true),(2,'California',false);
SELECT (COUNT(*) FILTER (WHERE conservation_measures = true) OVER (PARTITION BY state) * 100.0 / COUNT(*) OVER (PARTITION BY state)) FROM households WHERE state = 'California';
What is the average value of artworks from the Renaissance period?
CREATE TABLE ArtWorks (ArtworkID int,Title varchar(100),Value int,Period varchar(100));
SELECT AVG(Value) FROM ArtWorks WHERE Period = 'Renaissance'
What is the total number of songs released in each year by 'Taylor Swift' and 'Ariana Grande'?
CREATE TABLE songs (song_id INT,song VARCHAR(50),release_year INT,artist VARCHAR(50)); INSERT INTO songs VALUES (1,'Shake It Off',2014,'Taylor Swift'),(2,'Thank U,Next',2019,'Ariana Grande'),(3,'Love Story',2008,'Taylor Swift');
SELECT s.release_year, COUNT(s.song_id) as song_count FROM songs s WHERE s.artist IN ('Taylor Swift', 'Ariana Grande') GROUP BY s.release_year;
What is the average R&D expenditure for 'CompanyX' between 2018 and 2020?
CREATE TABLE rd_expenditures (company varchar(20),year int,amount int); INSERT INTO rd_expenditures (company,year,amount) VALUES ('CompanyX',2018,5000000),('CompanyX',2019,5500000),('CompanyX',2020,6000000);
SELECT AVG(amount) FROM rd_expenditures WHERE company = 'CompanyX' AND year BETWEEN 2018 AND 2020;
What is the average age of artifacts found in the 'european_sites' table?
CREATE TABLE european_sites (id INT,site_name VARCHAR(50),artifact_name VARCHAR(50),age INT);
SELECT AVG(age) FROM european_sites;
Add a new habitat preservation record to the 'habitats' table
CREATE TABLE habitats (id INT PRIMARY KEY,location VARCHAR(50),area FLOAT,preservation_status VARCHAR(50));
INSERT INTO habitats (id, location, area, preservation_status) VALUES (1, 'Amazon Rainforest', 6700000.0, 'Endangered');
Which suppliers provided the most sustainable materials in 2021?
CREATE TABLE supplier_sustainability (supplier_id INT,year INT,sustainable_material_percentage DECIMAL(10,2));
SELECT supplier_id, MAX(sustainable_material_percentage) AS max_sustainable_material_percentage FROM supplier_sustainability WHERE year = 2021 GROUP BY supplier_id ORDER BY max_sustainable_material_percentage DESC;
How many mental health parity violations occurred in each region in 2020?
CREATE TABLE mental_health_parity (id INT,region TEXT,violation_date DATE); INSERT INTO mental_health_parity (id,region,violation_date) VALUES (1,'Northeast','2020-01-01'); INSERT INTO mental_health_parity (id,region,violation_date) VALUES (2,'Southeast','2020-02-15');
SELECT region, COUNT(*) as violations_in_2020 FROM mental_health_parity WHERE EXTRACT(YEAR FROM violation_date) = 2020 GROUP BY region;
What is the name of the hospital with the highest patient capacity in the West region, ordered by patient capacity?
CREATE TABLE hospitals (id INT,region VARCHAR(255),name VARCHAR(255),patient_capacity INT); INSERT INTO hospitals (id,region,name,patient_capacity) VALUES (1,'Northeast','Hospital A',100),(2,'West','Hospital B',150),(3,'South','Hospital C',120);
SELECT name FROM hospitals WHERE region = 'West' ORDER BY patient_capacity DESC LIMIT 1;
How many visitors identified as artists attended events in NY and NJ combined?
CREATE TABLE Events (EventID int,EventLocation varchar(50),Attendance int); INSERT INTO Events VALUES (1,'NY Museum',500),(2,'NJ Theater',300),(3,'NY Art Gallery',200);
SELECT SUM(Attendance) FROM Events WHERE EventLocation LIKE '%NY%' OR EventLocation LIKE '%NJ%' AND EventLocation IN (SELECT DISTINCT EventLocation FROM Events WHERE EventLocation LIKE '%Artist%')
What is the total CO2 emission by each sector in 2020?
CREATE TABLE emissions (year INT,sector TEXT,co2_emission INT); INSERT INTO emissions (year,sector,co2_emission) VALUES (2015,'Energy',5000),(2015,'Industry',3000),(2015,'Transport',2000),(2020,'Energy',5500),(2020,'Industry',3200),(2020,'Transport',2100);
SELECT sector, SUM(co2_emission) FROM emissions WHERE year = 2020 GROUP BY sector;
Identify the top 3 states with the highest number of veteran employment opportunities
CREATE TABLE veteran_employment (state VARCHAR(50),job_openings INT);
SELECT state, job_openings FROM veteran_employment ORDER BY job_openings DESC LIMIT 3;
Identify the clinic in rural Kentucky with the lowest capacity.
CREATE TABLE clinics (id INT,name VARCHAR(50),type VARCHAR(50),capacity INT,region VARCHAR(50)); INSERT INTO clinics (id,name,type,capacity,region) VALUES (1,'Clinic A','Primary Care',40,'Rural Kentucky'); INSERT INTO clinics (id,name,type,capacity,region) VALUES (2,'Clinic B','General Care',45,'Rural Kentucky');
SELECT clinics.name FROM clinics WHERE clinics.region = 'Rural Kentucky' AND clinics.capacity = (SELECT MIN(clinics.capacity) FROM clinics WHERE clinics.region = 'Rural Kentucky');
Average risk rating for impact investments in the finance sector with an ESG score above 75?
CREATE TABLE impact_investments_finance (id INT,sector VARCHAR(20),ESG_score FLOAT,risk_rating FLOAT); INSERT INTO impact_investments_finance (id,sector,ESG_score,risk_rating) VALUES (1,'Finance',80.0,3.0),(2,'Finance',70.0,4.0),(3,'Finance',85.0,2.5);
SELECT AVG(risk_rating) FROM impact_investments_finance WHERE sector = 'Finance' AND ESG_score > 75;
What is the market share of online travel agencies (OTAs) in Europe, by total transactions?
CREATE TABLE otas (ota_id INT,ota_name TEXT,transactions INT,region TEXT); INSERT INTO otas (ota_id,ota_name,transactions,region) VALUES (1,'OTA X',5000,'Europe'),(2,'OTA Y',7000,'Europe');
SELECT region, (transactions / SUM(transactions) OVER (PARTITION BY region)) * 100 AS market_share FROM otas WHERE region = 'Europe';
What is the total waste generation in grams for each circular economy initiative in 2020?
CREATE TABLE circular_economy (initiative VARCHAR(50),year INT,waste_generation FLOAT); INSERT INTO circular_economy (initiative,year,waste_generation) VALUES ('Waste to Energy',2020,2500),('Recycling Program',2020,3500),('Composting Program',2020,1500);
SELECT initiative, SUM(waste_generation) FROM circular_economy WHERE year = 2020 GROUP BY initiative;
List the vessel names, their types, and the number of safety inspections for vessels that have not had any safety inspections yet?
CREATE TABLE Vessels (ID INT,Name VARCHAR(50),Type VARCHAR(50),Safety_Inspections INT); INSERT INTO Vessels (ID,Name,Type,Safety_Inspections) VALUES (1,'SV Argo','Sailing Ship',0);
SELECT Name, Type, Safety_Inspections FROM Vessels WHERE Safety_Inspections = 0;
How many green buildings have been certified in the 'green_buildings' table by certification level?
CREATE TABLE if not exists green_buildings (building_id INT,building_name VARCHAR(255),city VARCHAR(255),certification_level VARCHAR(50));
SELECT certification_level, COUNT(*) as certified_buildings FROM green_buildings GROUP BY certification_level;
What is the minimum oxygen level recorded in the 'Pacific Ocean'?
CREATE TABLE oxygen_records (id INTEGER,location TEXT,level FLOAT,date DATE);
SELECT MIN(level) FROM oxygen_records WHERE location = 'Pacific Ocean';
What is the most recent date a player from Brazil has played 'Virtual Tennis'?
CREATE TABLE GameDates (GameDate DATE,PlayerID INT,GameName VARCHAR(255)); INSERT INTO GameDates (GameDate,PlayerID,GameName) VALUES ('2022-01-01',1,'Virtual Tennis'); INSERT INTO GameDates (GameDate,PlayerID,GameName) VALUES ('2022-01-02',2,'Virtual Tennis'); INSERT INTO Players (PlayerID,Country) VALUES (1,'Brazil');...
SELECT MAX(GameDate) FROM GameDates JOIN Players ON GameDates.PlayerID = Players.PlayerID WHERE Players.Country = 'Brazil' AND GameName = 'Virtual Tennis';
What is the percentage of digital divide closure in African countries?
CREATE TABLE digital_divide (country VARCHAR(255),closure_percentage FLOAT); INSERT INTO digital_divide (country,closure_percentage) VALUES ('Country X',12.5),('Country Y',15.0),('Country Z',18.3);
SELECT country, closure_percentage, (closure_percentage / 100) * 100.0 AS div_closure_percentage FROM digital_divide;
What's the total amount of donations received by 'Doctors Without Borders' and 'International Red Cross' from 'USA'?
CREATE TABLE Donations (org VARCHAR(255),country VARCHAR(255),donation_amount INT); INSERT INTO Donations (org,country,donation_amount) VALUES ('Doctors Without Borders','USA',50000),('International Red Cross','USA',40000),('UNICEF','Canada',30000);
SELECT SUM(donation_amount) FROM Donations WHERE org IN ('Doctors Without Borders', 'International Red Cross') AND country = 'USA';
What is the maximum carbon emissions of hotels in each country?
CREATE TABLE hotels (hotel_id INT,name TEXT,country TEXT,carbon_emissions INT); INSERT INTO hotels (hotel_id,name,country,carbon_emissions) VALUES (1,'Hotel A','Canada',100),(2,'Hotel B','Mexico',200),(3,'Hotel C','Germany',300),(4,'Hotel D','Australia',400),(5,'Hotel E','USA',500);
SELECT country, MAX(carbon_emissions) FROM hotels GROUP BY country;
Delete records of subscribers with data usage below 30GB in Florida.
CREATE TABLE mobile_subscribers (subscriber_id INT,data_usage FLOAT,state VARCHAR(255)); INSERT INTO mobile_subscribers (subscriber_id,data_usage,state) VALUES (1,50.5,'Texas'),(2,60.3,'Texas'),(3,40.2,'Texas'),(4,25,'Florida'),(5,32,'Florida');
DELETE FROM mobile_subscribers WHERE data_usage < 30 AND state = 'Florida';
What is the maximum number of military vehicles sold by EliteDefense to any government in the Middle East?
CREATE TABLE EliteDefense.VehicleSales (id INT,manufacturer VARCHAR(255),model VARCHAR(255),quantity INT,price DECIMAL(10,2),buyer_country VARCHAR(255),sale_date DATE);
SELECT MAX(quantity) FROM EliteDefense.VehicleSales WHERE buyer_country LIKE 'Middle East%';
Show the number of readings for each location
temperature_readings
SELECT location, COUNT(*) as total_readings FROM temperature_readings GROUP BY location;
Delete records of wells that have negative production values.
CREATE TABLE wells (well_id INT,drill_date DATE,production FLOAT); INSERT INTO wells (well_id,drill_date,production) VALUES (1,'2020-10-15',1000),(2,'2020-11-20',-200),(3,'2020-12-31',1500);
DELETE FROM wells WHERE production < 0;
Delete all records in the world_heritage_sites table for locations outside of Japan.
CREATE TABLE world_heritage_sites (site_id INT,name TEXT,location TEXT); INSERT INTO world_heritage_sites (site_id,name,location) VALUES (1,'Mount Fuji','Japan'),(2,'Taj Mahal','India');
DELETE FROM world_heritage_sites WHERE location != 'Japan';
Delete the freight record with ID 999
CREATE TABLE freight (id INT,item_id INT,weight FLOAT); INSERT INTO freight (id,item_id,weight) VALUES (999,42,10.5),(1000,43,15.3);
DELETE FROM freight WHERE id = 999;
Find the total revenue and CO2 emissions for products that are ethically sourced
CREATE TABLE products (product_id INT,is_ethically_sourced BOOLEAN,revenue FLOAT,co2_emissions FLOAT);
SELECT SUM(revenue) as total_revenue, SUM(co2_emissions) as total_co2_emissions FROM products WHERE is_ethically_sourced = TRUE;
What is the percentage of customers who ordered online in each region?
CREATE TABLE orders(id INT,region VARCHAR(255),online BOOLEAN); INSERT INTO orders(id,region,online) VALUES (1,'North',true),(2,'South',false),(3,'East',true);
SELECT region, 100.0 * COUNT(CASE WHEN online THEN 1 END) / COUNT(*) as online_percentage FROM orders GROUP BY region;
What is the total amount of funds spent on refugee support in the Middle East?
CREATE TABLE funds (id INT,category TEXT,region TEXT,amount DECIMAL(10,2)); INSERT INTO funds (id,category,region,amount) VALUES (1,'Refugee Support','Middle East',250000.00),(2,'Disaster Response','Asia',300000.00),(3,'Community Development','Africa',150000.00);
SELECT SUM(amount) FROM funds WHERE category = 'Refugee Support' AND region = 'Middle East';
List all excavation sites in 'Canada' and the number of artifacts associated with each site.
CREATE TABLE excavation_sites (id INT,site_name VARCHAR(50),location VARCHAR(50),num_artifacts INT); INSERT INTO excavation_sites (id,site_name,location,num_artifacts) VALUES (1,'Site A','USA',30),(2,'Site B','Mexico',45),(3,'Site C','Canada',25),(4,'Site D','Canada',35);
SELECT site_name, num_artifacts FROM excavation_sites WHERE location = 'Canada';
Find the average length of podcasts in the 'science' category that are shorter than 30 minutes.
CREATE TABLE podcasts_2 (id INT,title TEXT,length INT,category TEXT); INSERT INTO podcasts_2 (id,title,length,category) VALUES (1,'Podcast1',20,'science'),(2,'Podcast2',40,'science');
SELECT AVG(length) FROM podcasts_2 WHERE length < 30 AND category = 'science';