instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
Create a table for auto show information
CREATE TABLE auto_show (id INT PRIMARY KEY,show_name VARCHAR(255),location VARCHAR(255),start_date DATE,end_date DATE);
CREATE TABLE auto_show (id INT PRIMARY KEY, show_name VARCHAR(255), location VARCHAR(255), start_date DATE, end_date DATE);
List all products that use recycled materials and their respective factories.
CREATE TABLE Products (product_id INT,name VARCHAR(255),category VARCHAR(255),material_id INT); INSERT INTO Products (product_id,name,category,material_id) VALUES (1,'Recycled Polyester T-Shirt','Clothing',1),(2,'Bamboo Socks','Clothing',2),(3,'Recycled Plastic Water Bottle','Accessories',3); CREATE TABLE Materials (ma...
SELECT Products.name, Factories.name FROM Products INNER JOIN Materials ON Products.material_id = Materials.material_id INNER JOIN ProductFactories ON Products.product_id = ProductFactories.product_id INNER JOIN Factories ON ProductFactories.factory_id = Factories.factory_id WHERE Materials.is_recycled = TRUE;
What is the feed conversion ratio for each species in 2020?
CREATE TABLE Species_Feed (Species_Name TEXT,Year INT,Feed_Conversion_Ratio FLOAT); INSERT INTO Species_Feed (Species_Name,Year,Feed_Conversion_Ratio) VALUES ('Salmon',2019,1.2),('Trout',2019,1.3),('Shrimp',2019,1.5),('Salmon',2020,1.1),('Trout',2020,1.2),('Shrimp',2020,1.4);
SELECT Species_Name, Feed_Conversion_Ratio FROM Species_Feed WHERE Year = 2020;
Update the budget of the Sonar Mapping Project in the 'ocean_floor_mapping_projects' table
CREATE TABLE ocean_floor_mapping_projects (id INT PRIMARY KEY,project_name VARCHAR(255),start_date DATE,end_date DATE,budget FLOAT);
UPDATE ocean_floor_mapping_projects SET budget = 500000 WHERE project_name = 'Sonar Mapping Project';
Which menu items have the highest cost?
CREATE TABLE menu_items (menu_item_id INT,item_name VARCHAR(255),category VARCHAR(255),price INT); INSERT INTO menu_items (menu_item_id,item_name,category,price) VALUES (1,'Steak','Entree',25),(2,'Fries','Side',5),(3,'Burger','Entree',15),(4,'Salad','Side',8);
SELECT item_name, price FROM menu_items ORDER BY price DESC LIMIT 2;
What is the average health equity metric score for each region?
CREATE TABLE health_equity_metrics (metric_id INT,region VARCHAR(255),score INT); INSERT INTO health_equity_metrics (metric_id,region,score) VALUES (1,'Northeast',75),(2,'Southeast',80),(3,'Northeast',85);
SELECT region, AVG(score) FROM health_equity_metrics GROUP BY region;
What is the average donation amount from donors located in California?
CREATE TABLE Donors (DonorID INT,DonationAmount DECIMAL(10,2),DonorState VARCHAR(2));
SELECT AVG(DonationAmount) FROM Donors WHERE DonorState = 'CA';
Remove the record for machine "Machine 1" from the "machines" table
CREATE TABLE machines (id INT PRIMARY KEY,name VARCHAR(50),type VARCHAR(50),status VARCHAR(50));
DELETE FROM machines WHERE name = 'Machine 1';
Which countries are involved in peacekeeping operations in Africa?
CREATE TABLE peacekeeping_operations (id INT,country VARCHAR(50),location VARCHAR(50)); INSERT INTO peacekeeping_operations (id,country,location) VALUES (1,'Ethiopia','Somalia'),(2,'Kenya','Somalia'),(3,'Burundi','South Sudan'),(4,'Senegal','Mali');
SELECT DISTINCT country FROM peacekeeping_operations WHERE location = 'Somalia' OR location = 'South Sudan' OR location = 'Mali';
Which heritage sites are located in France and Spain?
CREATE TABLE HeritageSites (SiteID int,SiteName text,Country text); INSERT INTO HeritageSites (SiteID,SiteName,Country) VALUES (1,'Eiffel Tower','France'),(2,'Mont Saint-Michel','France'),(3,'Alhambra','Spain');
SELECT SiteName FROM HeritageSites WHERE Country = 'France' INTERSECT SELECT SiteName FROM HeritageSites WHERE Country = 'Spain';
What is the total number of bike share trips taken in the month of June?
CREATE TABLE if not exists bike_stations (station_id serial primary key,name varchar(255),region varchar(255));CREATE TABLE if not exists bike_trips (trip_id serial primary key,start_station_id int,end_station_id int,start_date date,end_date date);CREATE TABLE if not exists calendar (calendar_id serial primary key,date...
SELECT COUNT(*) FROM bike_trips bt JOIN calendar c ON bt.start_date = c.date WHERE c.date BETWEEN '2022-06-01' AND '2022-06-30';
What is the current budget for 'Coastal Preservation Alliance'?
CREATE TABLE marine_conservation_organizations (id INT PRIMARY KEY,organization VARCHAR(255),location VARCHAR(255),budget INT); INSERT INTO marine_conservation_organizations (id,organization,location,budget) VALUES (1,'Coastal Preservation Alliance','Florida',7000000);
SELECT budget FROM marine_conservation_organizations WHERE organization = 'Coastal Preservation Alliance';
What is the total claim amount paid to policyholders from 'High Risk' underwriting group?
CREATE TABLE underwriting (id INT,group VARCHAR(10),name VARCHAR(20),claim_amount DECIMAL(10,2)); INSERT INTO underwriting (id,group,name,claim_amount) VALUES (1,'High Risk','John Doe',5000.00),(2,'Low Risk','Jane Smith',2000.00),(3,'High Risk','Mike Johnson',7000.00);
SELECT SUM(claim_amount) FROM underwriting WHERE group = 'High Risk';
What is the average trip duration for tourists visiting Indonesia?
CREATE TABLE tourism_stats (country VARCHAR(20),trip_duration INT); INSERT INTO tourism_stats (country,trip_duration) VALUES ('Indonesia',14);
SELECT AVG(trip_duration) FROM tourism_stats WHERE country = 'Indonesia';
How many animals of each species are there in 'Nature's Guardians'?
CREATE TABLE Nature_s_Guardians (Animal_ID INT,Animal_Name VARCHAR(50),Species VARCHAR(50),Age INT); INSERT INTO Nature_s_Guardians VALUES (1,'Bambi','Deer',3); INSERT INTO Nature_s_Guardians VALUES (2,'Fiona','Turtle',10); INSERT INTO Nature_s_Guardians VALUES (3,'Chirpy','Eagle',5); INSERT INTO Nature_s_Guardians VAL...
SELECT Species, COUNT(*) AS Number_of_Animals FROM Nature_s_Guardians GROUP BY Species
How many accidents occurred in the Mediterranean Sea in the last 5 years, broken down by the quarter they happened in?
CREATE TABLE accidents (id INT,vessel_name VARCHAR(50),date DATE,region VARCHAR(50)); INSERT INTO accidents (id,vessel_name,date,region) VALUES (1,'Vessel A','2018-01-01','Mediterranean Sea'),(2,'Vessel B','2018-04-01','Mediterranean Sea');
SELECT COUNT(*), DATE_FORMAT(date, '%Y-%m') AS quarter FROM accidents WHERE region = 'Mediterranean Sea' AND date >= DATE_SUB(CURDATE(), INTERVAL 5 YEAR) GROUP BY quarter;
What is the total number of academic papers published by graduate students from each continent, in the last 4 years?
CREATE TABLE grad_students (id INT,name VARCHAR(50),continent VARCHAR(50));CREATE TABLE papers (id INT,paper_id INT,title VARCHAR(100),year INT,author_id INT);
SELECT gs.continent, COUNT(DISTINCT p.id) AS num_papers FROM grad_students gs JOIN papers p ON gs.id = p.author_id WHERE p.year BETWEEN YEAR(CURRENT_DATE) - 4 AND YEAR(CURRENT_DATE) GROUP BY gs.continent;
What are the names and policies of all cybersecurity policies that have been updated in the past month?
CREATE TABLE cybersecurity_policies (id INT,name VARCHAR,last_updated DATE); INSERT INTO cybersecurity_policies (id,name,last_updated) VALUES (1,'Incident Response Plan','2021-01-01'),(2,'Access Control Policy','2021-02-01'),(3,'Data Protection Policy','2021-03-01'),(4,'Network Security Policy','2021-04-01'),(5,'Accept...
SELECT name, last_updated FROM cybersecurity_policies WHERE last_updated >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH);
What is the name and material of the bridge with the longest span length in the 'infrastructure' schema?
CREATE TABLE bridges (id INT,name VARCHAR(50),span_length FLOAT,material VARCHAR(20)); INSERT INTO bridges (id,name,span_length,material) VALUES (1,'Golden Gate',2737.4,'Steel');
SELECT name, material FROM bridges WHERE span_length = (SELECT MAX(span_length) FROM bridges);
What is the total number of male and female news reporters in the "reporters" table?
CREATE TABLE reporters (id INT,name VARCHAR(50),gender VARCHAR(10),age INT,country VARCHAR(50));
SELECT gender, COUNT(*) FROM reporters GROUP BY gender;
What was the total water consumption by water treatment plants in 2020?
CREATE TABLE water_treatment_plants (id INT,name VARCHAR(50),location VARCHAR(50),year_established INT); INSERT INTO water_treatment_plants (id,name,location,year_established) VALUES (1,'PlantA','CityA',1990),(2,'PlantB','CityB',2005),(3,'PlantC','CityC',2010),(4,'PlantD','CityD',2015); CREATE TABLE water_consumption_p...
SELECT wtp.name, SUM(wcp.consumption) as total_consumption FROM water_treatment_plants wtp JOIN water_consumption_plants wcp ON wtp.id = wcp.plant_id WHERE wcp.year = 2020 GROUP BY wtp.name;
Insert a new marine protected area with ID 3, name 'Azores', depth 1000, and ocean 'Atlantic'
CREATE TABLE marine_protected_areas (area_id INT,name VARCHAR(50),depth FLOAT,ocean VARCHAR(10));
INSERT INTO marine_protected_areas (area_id, name, depth, ocean) VALUES (3, 'Azores', 1000, 'Atlantic');
Which hotels have the highest virtual tour engagement in Asia?
CREATE TABLE virtual_tours (hotel_id INT,hotel_name VARCHAR(255),region VARCHAR(255),views INT);
SELECT hotel_id, hotel_name, MAX(views) FROM virtual_tours WHERE region = 'Asia' GROUP BY hotel_id, hotel_name;
What is the total donation amount per state?
CREATE TABLE Donors (DonorID INT,Name VARCHAR(50),City VARCHAR(50),State VARCHAR(2),Zip VARCHAR(10),DonationAmount DECIMAL(10,2)); CREATE TABLE Grants (GrantID INT,DonorID INT,NonprofitID INT,GrantAmount DECIMAL(10,2),Date DATE);
SELECT State, SUM(DonationAmount) FROM Donors D INNER JOIN Grants G ON D.DonorID = G.DonorID GROUP BY State;
Which spacecraft have had the most maintenance issues and what was the average duration of each maintenance issue?
CREATE TABLE MaintenanceIssues (id INT,spacecraft VARCHAR(255),issue_date DATE,resolution_date DATE); INSERT INTO MaintenanceIssues (id,spacecraft,issue_date,resolution_date) VALUES (1,'ISS','2022-01-01','2022-01-05'); INSERT INTO MaintenanceIssues (id,spacecraft,issue_date,resolution_date) VALUES (2,'ISS','2022-01-03'...
SELECT spacecraft, COUNT(*) as issue_count, AVG(DATEDIFF(resolution_date, issue_date)) as avg_duration FROM MaintenanceIssues GROUP BY spacecraft ORDER BY issue_count DESC;
What is the most common healthcare provider specialty for each rural clinic in the "rural_clinics" table, partitioned by clinic location?
CREATE TABLE rural_clinics (clinic_location VARCHAR(255),healthcare_provider_specialty VARCHAR(255)); INSERT INTO rural_clinics (clinic_location,healthcare_provider_specialty) VALUES ('Location1','SpecialtyA'),('Location1','SpecialtyA'),('Location1','SpecialtyB'),('Location2','SpecialtyA'),('Location2','SpecialtyA'),('...
SELECT clinic_location, healthcare_provider_specialty, COUNT(*) OVER (PARTITION BY clinic_location, healthcare_provider_specialty) FROM rural_clinics;
Identify the top two community health workers with the most unique patients served who identify as Hispanic or Latino, along with the number of patients they have served.
CREATE TABLE CommunityHealthWorker (ID INT,Name TEXT); INSERT INTO CommunityHealthWorker (ID,Name) VALUES (1,'Maria Rodriguez'); INSERT INTO CommunityHealthWorker (ID,Name) VALUES (2,'Jose Hernandez'); INSERT INTO CommunityHealthWorker (ID,Name) VALUES (3,'Fatima Khan'); CREATE TABLE PatientCommunityHealthWorker (Patie...
SELECT CommunityHealthWorkerID, COUNT(DISTINCT PatientID) as PatientsServed FROM PatientCommunityHealthWorker WHERE Ethnicity = 'Hispanic or Latino' GROUP BY CommunityHealthWorkerID ORDER BY PatientsServed DESC LIMIT 2;
What is the total quantity of organic cotton products sold in each country?
CREATE TABLE sales (order_id INT,product_id INT,quantity_sold INT,country VARCHAR(50)); CREATE TABLE products (product_id INT,product_name VARCHAR(50),material VARCHAR(50),organic BOOLEAN); INSERT INTO sales (order_id,product_id,quantity_sold,country) VALUES (1,101,50,'US'),(2,102,75,'CA'),(3,103,30,'MX'); INSERT INTO ...
SELECT country, SUM(quantity_sold) FROM sales JOIN products ON sales.product_id = products.product_id WHERE material = 'Cotton' AND organic = true GROUP BY country;
What is the number of smart contract transactions per day?
CREATE TABLE DailyTransactions (TransactionID int,TransactionDate date); INSERT INTO DailyTransactions (TransactionID,TransactionDate) VALUES (1,'2021-01-02'),(2,'2021-02-15'),(3,'2021-05-03'),(4,'2021-12-30'),(5,'2021-12-30'),(6,'2021-12-30');
SELECT TransactionDate, COUNT(*) as TransactionsPerDay FROM DailyTransactions GROUP BY TransactionDate;
What is the total number of marine species recorded in each country's Exclusive Economic Zone (EEZ)?
CREATE TABLE EEZ (id INT,country VARCHAR(255),species VARCHAR(255)); INSERT INTO EEZ (id,country,species) VALUES (1,'Canada','Salmon');
SELECT country, COUNT(species) FROM EEZ GROUP BY country;
Retrieve the total construction cost of all transportation projects in 'transportation_projects' table
CREATE TABLE transportation_projects (project_id INT PRIMARY KEY,project_name VARCHAR(100),construction_cost FLOAT,project_type VARCHAR(50));
SELECT SUM(construction_cost) FROM transportation_projects WHERE project_type = 'transportation';
How many doctors are there in rural Louisiana?
CREATE TABLE doctors (id INT,name VARCHAR(50),location VARCHAR(20)); INSERT INTO doctors (id,name,location) VALUES (1,'Dr. Smith','rural Louisiana');
SELECT COUNT(*) FROM doctors WHERE location = 'rural Louisiana';
What are the construction labor statistics for Indigenous workers in Alberta?
CREATE TABLE Construction_Labor (Employee_ID INT,Employee_Name VARCHAR(100),Skill VARCHAR(50),Hourly_Wage FLOAT,City VARCHAR(50),State CHAR(2),Zipcode INT,Ethnicity VARCHAR(50)); CREATE VIEW AB_Construction_Labor AS SELECT * FROM Construction_Labor WHERE State = 'AB';
SELECT AVG(Hourly_Wage), COUNT(*) FROM AB_Construction_Labor WHERE Ethnicity = 'Indigenous';
Display the number of unique donors and total donation amount for each program
CREATE TABLE programs (program_id INT,program_name TEXT,location TEXT);
SELECT programs.program_name, COUNT(DISTINCT donations.donor_id) as num_donors, SUM(donations.donation_amount) as total_donated FROM donations JOIN programs ON donations.program_id = programs.program_id GROUP BY programs.program_name;
What is the total carbon pricing revenue in Canada and Mexico?
CREATE TABLE carbon_pricing (id INT,country VARCHAR(255),revenue FLOAT); INSERT INTO carbon_pricing (id,country,revenue) VALUES (1,'Canada',5000000),(2,'Mexico',3000000),(3,'Canada',6000000),(4,'Mexico',4000000);
SELECT SUM(revenue) as total_revenue, country FROM carbon_pricing GROUP BY country;
What is the trend of AI adoption in the hotel industry in the last year?
CREATE TABLE ai_adoption (adoption_id INT,hotel_name VARCHAR(255),adoption_date DATE,adoption_level INT);
SELECT adoption_date, AVG(adoption_level) FROM ai_adoption WHERE hotel_name IN (SELECT hotel_name FROM hotels WHERE industry = 'hotel') GROUP BY adoption_date ORDER BY adoption_date;
What is the total amount donated in Q1 2022?
CREATE TABLE Donations (DonationID INT,DonorID INT,Amount FLOAT,DonationDate DATE); INSERT INTO Donations (DonationID,DonorID,Amount,DonationDate) VALUES (1,1,500.00,'2021-01-01'),(2,2,800.00,'2021-02-01'),(3,1,300.00,'2022-03-15');
SELECT SUM(Amount) FROM Donations WHERE DATE_FORMAT(DonationDate, '%Y-%m') BETWEEN '2022-01' AND '2022-03';
Calculate the moving average of animal populations for each species over the last three records, if available.
CREATE TABLE animal_population (species VARCHAR(255),year INT,population INT); INSERT INTO animal_population (species,year,population) VALUES ('Tiger',2018,63),('Tiger',2019,65),('Tiger',2020,68),('Lion',2018,50),('Lion',2019,52),('Lion',2020,55);
SELECT species, year, AVG(population) OVER (PARTITION BY species ORDER BY year ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS moving_average FROM animal_population;
What are the names and populations of the 10 largest cities in Africa, excluding cities with populations under 1,000,000?
CREATE TABLE africa_cities (id INT,city VARCHAR(255),population INT); INSERT INTO africa_cities (id,city,population) VALUES (1,'Cairo',20500000);
SELECT city, population FROM africa_cities WHERE population >= 1000000 ORDER BY population DESC LIMIT 10;
How many shared bicycles were available in Seoul on March 20, 2022?
CREATE TABLE if not exists Bicycles (id INT,city VARCHAR(20),available INT,date DATE); INSERT INTO Bicycles (id,city,available,date) VALUES (1,'Seoul',3500,'2022-03-20'),(2,'Seoul',3200,'2022-03-19'),(3,'Busan',2000,'2022-03-20');
SELECT available FROM Bicycles WHERE city = 'Seoul' AND date = '2022-03-20';
What is the environmental impact score trend for the last 5 products produced?
CREATE TABLE environmental_impact (product_id INT,environmental_impact_score FLOAT,production_date DATE); INSERT INTO environmental_impact (product_id,environmental_impact_score,production_date) VALUES (1,5.2,'2023-03-01'),(2,6.1,'2023-03-02'),(3,4.9,'2023-03-03');
SELECT environmental_impact_score, LAG(environmental_impact_score, 1) OVER (ORDER BY production_date) AS prev_impact_score FROM environmental_impact WHERE product_id >= 4;
How many rural infrastructure projects were completed in India between 2017 and 2019?
CREATE TABLE infrastructure_projects (project_id INT,country TEXT,start_year INT,end_year INT,completion_year INT); INSERT INTO infrastructure_projects (project_id,country,start_year,end_year,completion_year) VALUES (1,'India',2016,2019,2018),(2,'India',2017,2020,2019),(3,'India',2018,2021,NULL);
SELECT COUNT(*) FROM infrastructure_projects WHERE country = 'India' AND completion_year BETWEEN 2017 AND 2019;
Which IoT sensors have been used in Africa in the past 6 months?
CREATE TABLE sensors (sensor_id INT,sensor_type VARCHAR(255),last_used_date DATE,location VARCHAR(255)); INSERT INTO sensors (sensor_id,sensor_type,last_used_date,location) VALUES (1,'temperature','2022-02-15','Kenya'),(2,'infrared','2021-12-28','Nigeria'),(3,'multispectral','2022-03-05','South Africa'),(4,'hyperspectr...
SELECT sensors.sensor_type FROM sensors WHERE sensors.last_used_date >= DATE_SUB(CURRENT_DATE, INTERVAL 6 MONTH) AND sensors.location LIKE 'Africa%';
Update the 'teacher_id' for a record in the 'professional_development' table
CREATE TABLE professional_development (teacher_id INT,course_title VARCHAR(100),date_completed DATE);
UPDATE professional_development SET teacher_id = 201 WHERE course_title = 'Open Pedagogy 101';
What is the total weight of artifacts made of 'gold' in 'african_archaeology'?
CREATE TABLE african_archaeology (artifact_id INT,weight FLOAT,material VARCHAR(255));
SELECT SUM(weight) FROM african_archaeology WHERE material = 'gold';
Show the total volume of timber production for each region in 2020, sorted by the greatest amount.
CREATE TABLE timber_production (id INT PRIMARY KEY,region VARCHAR(50),year INT,volume INT);
SELECT region, SUM(volume) as total_volume FROM timber_production WHERE year = 2020 GROUP BY region ORDER BY total_volume DESC;
What is the average age of attendees for music and dance events in Texas and their total funding?
CREATE TABLE tx_events (id INT,event_type VARCHAR(10),avg_age FLOAT,funding INT); INSERT INTO tx_events (id,event_type,avg_age,funding) VALUES (1,'Music',40.5,15000),(2,'Dance',35.0,20000);
SELECT AVG(txe.avg_age), SUM(txe.funding) FROM tx_events txe WHERE txe.event_type IN ('Music', 'Dance') AND txe.state = 'TX';
How many cultural heritage sites are there in Germany with more than 50 reviews?
CREATE TABLE heritage_sites(id INT,name TEXT,country TEXT,num_reviews INT); INSERT INTO heritage_sites (id,name,country,num_reviews) VALUES (1,'Castle A','Germany',60),(2,'Museum B','Germany',45),(3,'Historical Site C','Germany',75);
SELECT COUNT(*) FROM heritage_sites WHERE country = 'Germany' AND num_reviews > 50;
Find the total number of games and unique genres for each platform, excluding virtual reality (VR) games.
CREATE TABLE Games (GameID INT,GameName VARCHAR(50),Platform VARCHAR(10),GameGenre VARCHAR(20),VR_Game BOOLEAN);
SELECT Platform, COUNT(DISTINCT GameGenre) AS Unique_Genres, COUNT(*) AS Total_Games FROM Games WHERE VR_Game = FALSE GROUP BY Platform;
List all aircraft accidents that occurred in the United States and Canada.
CREATE TABLE AircraftAccidents (ID INT,Location VARCHAR(50),Date DATE); INSERT INTO AircraftAccidents (ID,Location,Date) VALUES (1,'United States','2022-01-01'),(2,'Canada','2022-02-01'),(3,'United States','2022-03-01'),(4,'Mexico','2022-04-01');
SELECT Location, Date FROM AircraftAccidents WHERE Location IN ('United States', 'Canada');
Delete all student records with incomplete information from 'California' and 'Illinois'
CREATE TABLE StudentRecords (StudentID INT,State VARCHAR(10),Info VARCHAR(50)); INSERT INTO StudentRecords (StudentID,State,Info) VALUES (1,'IL','Incomplete');
DELETE FROM StudentRecords WHERE State IN ('California', 'Illinois') AND Info = 'Incomplete';
What is the average rating of movies directed by women?
CREATE TABLE movies (title VARCHAR(255),rating INT,director_gender VARCHAR(50)); INSERT INTO movies (title,rating,director_gender) VALUES ('Movie1',8,'Female'),('Movie2',7,'Male'),('Movie3',9,'Female'),('Movie4',6,'Male');
SELECT AVG(rating) as avg_rating FROM movies WHERE director_gender = 'Female';
What are the total artifacts and their average dimensions per country?
CREATE TABLE CountryDimensions (Country TEXT,Length DECIMAL(5,2),Width DECIMAL(5,2),Height DECIMAL(5,2)); INSERT INTO CountryDimensions (Country,Length,Width,Height) VALUES ('Italy',10.2,6.8,4.3); INSERT INTO CountryDimensions (Country,Length,Width,Height) VALUES ('Egypt',11.5,7.6,5.1);
SELECT e.Country, COUNT(a.ArtifactID) AS TotalArtifacts, AVG(d.Length) AS AvgLength, AVG(d.Width) AS AvgWidth, AVG(d.Height) AS AvgHeight FROM ExcavationSites e JOIN ArtifactAnalysis a ON e.SiteID = a.SiteID JOIN ArtifactDates d ON a.ArtifactID = d.ArtifactID JOIN CountryDimensions cd ON e.Country = cd.Country GROUP BY...
What is the average rating of all movies produced in Spain?
CREATE TABLE movies (id INT,title VARCHAR(255),rating FLOAT,production_country VARCHAR(100)); INSERT INTO movies (id,title,rating,production_country) VALUES (1,'Movie1',7.5,'USA'),(2,'Movie2',8.2,'Spain');
SELECT AVG(rating) FROM movies WHERE production_country = 'Spain';
How many community health centers are there in each borough of New York City?
CREATE TABLE nyc_boroughs (id INT,borough VARCHAR(50)); CREATE TABLE health_centers (id INT,name VARCHAR(50),borough_id INT); INSERT INTO nyc_boroughs (id,borough) VALUES (1,'Manhattan'),(2,'Brooklyn'),(3,'Bronx'); INSERT INTO health_centers (id,name,borough_id) VALUES (1,'Harlem United',1),(2,'Bedford Stuyvesant Famil...
SELECT b.borough, COUNT(h.id) AS total_health_centers FROM health_centers h JOIN nyc_boroughs b ON h.borough_id = b.id GROUP BY b.borough;
What is the total number of hospital beds in rural hospitals of Hawaii that have less than 150 beds or were built after 2010?
CREATE TABLE hospitals (id INT,name TEXT,location TEXT,beds INT,rural BOOLEAN,built DATE); INSERT INTO hospitals (id,name,location,beds,rural,built) VALUES (1,'Hospital A','Hawaii',120,true,'2011-01-01'),(2,'Hospital B','Hawaii',100,true,'2012-01-01');
SELECT SUM(beds) FROM hospitals WHERE location = 'Hawaii' AND rural = true AND (beds < 150 OR built > '2010-01-01');
What is the maximum age of policyholders who have a policy with a premium less than $1000?
CREATE TABLE Policyholders (PolicyholderID INT,Age INT,Premium DECIMAL(10,2)); INSERT INTO Policyholders (PolicyholderID,Age,Premium) VALUES (1,35,5000),(2,45,1500),(3,50,300),(4,60,2000);
SELECT MAX(Age) FROM Policyholders WHERE Premium < 1000;
What is the earliest start date for projects in the 'Sewer_System' table?
CREATE TABLE Sewer_System (project_id INT,project_name VARCHAR(100),start_date DATE); INSERT INTO Sewer_System (project_id,project_name,start_date) VALUES (2,'Sewer Line Replacement','2021-04-15'),(5,'Sewage Treatment Plant Upgrade','2022-01-02'),(7,'Manhole Rehabilitation','2021-02-28');
SELECT MIN(start_date) FROM Sewer_System;
Identify the number of ethical AI patents filed by Latinx inventors between 2018 and 2020.
CREATE TABLE inventors (inventor_id INT,inventor_name VARCHAR(100),ethnicity VARCHAR(50)); INSERT INTO inventors VALUES (1,'Grace Hopper','Not Latinx'),(2,'Alan Turing','Not Latinx'),(3,'Carlos Alvarado','Latinx'); CREATE TABLE patents (patent_id INT,patent_name VARCHAR(100),inventor_id INT,filed_year INT); INSERT INTO...
SELECT COUNT(*) FROM patents INNER JOIN inventors ON patents.inventor_id = inventors.inventor_id INNER JOIN patent_categories ON patents.patent_id = patent_categories.patent_id WHERE ethnicity = 'Latinx' AND filed_year BETWEEN 2018 AND 2020 AND category = 'ethical AI';
What is the number of clients who have received Shariah-compliant loans, but not socially responsible loans?
CREATE TABLE shariah_loans (id INT,client_id INT); INSERT INTO shariah_loans (id,client_id) VALUES (1,101),(2,101),(1,102); CREATE TABLE socially_responsible_loans (id INT,client_id INT); INSERT INTO socially_responsible_loans (id,client_id) VALUES (1,102),(2,103),(1,104);
SELECT COUNT(DISTINCT shariah_loans.client_id) FROM shariah_loans LEFT JOIN socially_responsible_loans ON shariah_loans.client_id = socially_responsible_loans.client_id WHERE socially_responsible_loans.client_id IS NULL;
What is the average capacity (MW) of wind farms in Germany that have more than 5 turbines?
CREATE TABLE wind_farms (id INT,name TEXT,country TEXT,num_turbines INT,capacity FLOAT); INSERT INTO wind_farms (id,name,country,num_turbines,capacity) VALUES (1,'Windpark Nord','Germany',6,144.5),(2,'Gode Wind','Germany',7,178.3);
SELECT AVG(capacity) FROM wind_farms WHERE country = 'Germany' AND num_turbines > 5;
List all businesses in Europe that received funding for economic diversification projects since 2015.
CREATE TABLE Businesses (id INT PRIMARY KEY,region VARCHAR(20),funded_project BOOLEAN);CREATE TABLE EconomicDiversification (id INT PRIMARY KEY,business_id INT,project_date DATE);
SELECT Businesses.id FROM Businesses INNER JOIN EconomicDiversification ON Businesses.id = EconomicDiversification.business_id WHERE Businesses.region = 'Europe' AND YEAR(EconomicDiversification.project_date) >= 2015 AND funded_project = TRUE;
What is the maximum playtime for each player on a single day in 'player_daily_playtime_v3'?
CREATE TABLE player_daily_playtime_v3 (player_id INT,play_date DATE,playtime INT); INSERT INTO player_daily_playtime_v3 (player_id,play_date,playtime) VALUES (7,'2021-03-01',700),(7,'2021-03-02',800),(7,'2021-03-03',900),(8,'2021-03-01',1000),(8,'2021-03-02',1100),(8,'2021-03-03',1200);
SELECT player_id, MAX(playtime) FROM player_daily_playtime_v3 GROUP BY player_id;
What is the average salary of non-union workers in the healthcare sector?
CREATE TABLE healthcare (id INT,union_member BOOLEAN,salary FLOAT); INSERT INTO healthcare (id,union_member,salary) VALUES (1,FALSE,80000),(2,TRUE,90000),(3,FALSE,85000);
SELECT AVG(salary) FROM healthcare WHERE union_member = FALSE;
What is the maximum cost of projects in the energy division?
CREATE TABLE Projects (id INT,division VARCHAR(10)); INSERT INTO Projects (id,division) VALUES (1,'water'),(2,'transport'),(3,'energy'); CREATE TABLE EnergyProjects (id INT,project_id INT,cost DECIMAL(10,2)); INSERT INTO EnergyProjects (id,project_id,cost) VALUES (1,3,700000),(2,3,750000),(3,1,800000);
SELECT MAX(e.cost) FROM EnergyProjects e JOIN Projects p ON e.project_id = p.id WHERE p.division = 'energy';
Find the average price of organic vegetables sold by vendors in 'Downtown' district
CREATE TABLE vendors (vendor_id INT,vendor_name TEXT,district TEXT); INSERT INTO vendors (vendor_id,vendor_name,district) VALUES (1,'VendorA','Downtown'),(2,'VendorB','Uptown'); CREATE TABLE produce (produce_id INT,produce_name TEXT,price DECIMAL,organic BOOLEAN,vendor_id INT); INSERT INTO produce (produce_id,produce_n...
SELECT AVG(price) FROM produce JOIN vendors ON produce.vendor_id = vendors.vendor_id WHERE organic = true AND district = 'Downtown';
List all food safety inspections with a failing grade and the corresponding restaurant for restaurants located in 'Downtown'.
CREATE TABLE Restaurants (RestaurantID int,RestaurantName varchar(255),Region varchar(255)); CREATE TABLE Inspections (InspectionID int,RestaurantID int,InspectionGrade varchar(10),InspectionDate date);
SELECT R.RestaurantName, I.InspectionGrade, I.InspectionDate FROM Restaurants R INNER JOIN Inspections I ON R.RestaurantID = I.RestaurantID WHERE R.Region = 'Downtown' AND I.InspectionGrade = 'Fail';
Delete the vessel record with ID 44455 from the "fleet_vessels" table
CREATE TABLE fleet_vessels (id INT PRIMARY KEY,name VARCHAR(255),type VARCHAR(255),year INT);
WITH deleted_vessel AS (DELETE FROM fleet_vessels WHERE id = 44455 RETURNING id, name, type, year) SELECT * FROM deleted_vessel;
What is the average mental health score for students in each grade?
CREATE TABLE students (id INT,name VARCHAR(255),grade INT,mental_health_score INT); INSERT INTO students (id,name,grade,mental_health_score) VALUES (1,'Jane Doe',10,75),(2,'John Doe',11,85),(3,'Jim Smith',12,90);
SELECT grade, AVG(mental_health_score) FROM students GROUP BY grade;
What is the total number of cases heard and resolved by race for each community board in Brooklyn?
CREATE TABLE community_board (community_board_number INT,community_board_name TEXT,race TEXT,cases_heard INT,cases_resolved INT); INSERT INTO community_board (community_board_number,community_board_name,race,cases_heard,cases_resolved) VALUES (1,'Brooklyn Community Board 1','African American',250,230),(1,'Brooklyn Comm...
SELECT community_board_name, race, SUM(cases_heard) AS total_cases_heard, SUM(cases_resolved) AS total_cases_resolved FROM community_board GROUP BY community_board_name, race;
Update status to 'Sold Out' in the inventory table for all records with quantity=0
CREATE TABLE inventory (id INT,product_id INT,quantity INT,status VARCHAR(50));
UPDATE inventory SET status = 'Sold Out' WHERE quantity = 0;
What is the maximum number of habitat preservation projects in South America, focusing on 'Rainforest Conservation'?
CREATE TABLE HabitatProjects (ProjectID INT,Project VARCHAR(50),Maximum INT,Location VARCHAR(50)); INSERT INTO HabitatProjects (ProjectID,Project,Maximum,Location) VALUES (1,'Rainforest Conservation',100,'South America'); INSERT INTO HabitatProjects (ProjectID,Project,Maximum,Location) VALUES (2,'Ocean Preservation',80...
SELECT MAX(Maximum) FROM HabitatProjects WHERE Project = 'Rainforest Conservation' AND Location = 'South America';
What is the average daily ridership of public buses in New York?
CREATE TABLE public_buses (bus_id INT,trip_date DATE,daily_ridership INT); INSERT INTO public_buses (bus_id,trip_date,daily_ridership) VALUES (1,'2022-01-02',3000),(2,'2022-01-02',3200);
SELECT trip_date, AVG(daily_ridership) FROM public_buses GROUP BY trip_date;
Which artists have not released any albums in the Jazz genre?
CREATE TABLE Albums (AlbumID INT,AlbumName VARCHAR(100),ReleaseYear INT,Artist VARCHAR(100),Genre VARCHAR(50)); INSERT INTO Albums (AlbumID,AlbumName,ReleaseYear,Artist,Genre) VALUES (1,'DAMN',2017,'Kendrick Lamar','Rap'); INSERT INTO Albums (AlbumID,AlbumName,ReleaseYear,Artist,Genre) VALUES (2,'Reputation',2017,'Tayl...
SELECT Artist FROM Albums WHERE Genre <> 'Jazz' GROUP BY Artist;
List the total water usage for 'commercial' purposes each month in '2021' from the 'water_usage' table
CREATE TABLE water_usage (id INT,usage FLOAT,purpose VARCHAR(20),date DATE); INSERT INTO water_usage (id,usage,purpose,date) VALUES (1,150,'residential','2021-07-01'); INSERT INTO water_usage (id,usage,purpose,date) VALUES (2,120,'commercial','2021-07-01');
SELECT EXTRACT(MONTH FROM date) as month, SUM(CASE WHEN purpose = 'commercial' THEN usage ELSE 0 END) as total_usage FROM water_usage WHERE date BETWEEN '2021-01-01' AND '2021-12-31' GROUP BY month;
What is the total number of confirmed COVID-19 cases in Canada and Australia?
CREATE TABLE countries (name PRIMARY KEY,region VARCHAR(20)); CREATE TABLE covid_cases (country VARCHAR(20),year INT,cases INT); INSERT INTO countries (name,region) VALUES ('Canada','Americas'),('Australia','Oceania'); INSERT INTO covid_cases (country,year,cases) VALUES ('Canada',2021,1234567),('Australia',2021,890123)...
SELECT SUM(c.cases) FROM covid_cases c JOIN countries ct ON c.country = ct.name WHERE ct.region IN ('Americas', 'Oceania') AND c.year = 2021;
What is the average ethical AI score for each country, ordered by the highest average score?
CREATE TABLE ethical_ai (country VARCHAR(50),score INT); INSERT INTO ethical_ai (country,score) VALUES ('USA',85),('India',70),('Brazil',80);
SELECT country, AVG(score) as avg_score FROM ethical_ai GROUP BY country ORDER BY avg_score DESC;
Identify the top 2 cities with the highest number of security incidents in the past week.
CREATE TABLE security_incidents (id INT,city VARCHAR(50),incident_date DATE); INSERT INTO security_incidents (id,city,incident_date) VALUES (1,'New York','2021-05-01'); INSERT INTO security_incidents (id,city,incident_date) VALUES (2,'Toronto','2021-05-02'); INSERT INTO security_incidents (id,city,incident_date) VALUES...
SELECT city, COUNT(*) OVER (PARTITION BY city) as incident_count, RANK() OVER (ORDER BY COUNT(*) DESC) as city_rank FROM security_incidents WHERE incident_date >= DATEADD(week, -1, CURRENT_DATE) GROUP BY city;
What is the average fish density (fish/m3) for fish farms located in the South China Sea?
CREATE TABLE fish_farms (id INT,name TEXT,location TEXT,fish_density FLOAT); INSERT INTO fish_farms (id,name,location,fish_density) VALUES (1,'Farm A','South China Sea',500.5),(2,'Farm B','South China Sea',600.0);
SELECT AVG(fish_density) FROM fish_farms WHERE location = 'South China Sea';
How many electric vehicle charging stations are there in Asia?
CREATE TABLE ElectricVehicleChargingStations (id INT,region VARCHAR(50),num_stations INT); INSERT INTO ElectricVehicleChargingStations (id,region,num_stations) VALUES (1,'Asia',50000);
SELECT region, SUM(num_stations) FROM ElectricVehicleChargingStations WHERE region = 'Asia' GROUP BY region;
Which organizations have received grants from the 'Arthur Foundation'?
CREATE TABLE organization (id INT PRIMARY KEY,name VARCHAR(255));CREATE TABLE grant (id INT PRIMARY KEY,organization_id INT,foundation_name VARCHAR(255));
SELECT o.name FROM organization o JOIN grant g ON o.id = g.organization_id WHERE g.foundation_name = 'Arthur Foundation';
What is the total funding for all research grants, pivoted by faculty member and department?
CREATE TABLE Department (id INT,name VARCHAR(255),college VARCHAR(255)); INSERT INTO Department (id,name,college) VALUES (1,'Biology','College of Science'),(2,'Chemistry','College of Science'),(3,'Physics','College of Science'); CREATE TABLE Faculty (id INT,name VARCHAR(255),department_id INT,minority VARCHAR(50)); INS...
SELECT d.name AS Department, f.name AS Faculty, SUM(rg.funding) AS TotalFunding FROM ResearchGrants rg JOIN Faculty f ON rg.faculty_id = f.id JOIN Department d ON f.department_id = d.id GROUP BY d.name, f.name;
List the collective bargaining agreements that have expired in the past year, sorted by the most recent expiration date.
CREATE TABLE cb_agreements (id INT,union_chapter VARCHAR(255),expiration_date DATE); INSERT INTO cb_agreements (id,union_chapter,expiration_date) VALUES (1,'NYC','2022-04-01'),(2,'LA','2022-06-15'),(3,'NYC','2022-07-30'),(4,'LA','2022-12-25'),(5,'NYC','2021-02-15'),(6,'LA','2021-09-01');
SELECT * FROM cb_agreements WHERE expiration_date BETWEEN DATE_SUB(CURDATE(), INTERVAL 1 YEAR) AND DATE_SUB(CURDATE(), INTERVAL 365 DAY) ORDER BY expiration_date DESC;
What is the R&D expenditure for the drug 'RemedX' in Europe?
CREATE TABLE rd_expenditure_3 (drug_name TEXT,expenditure NUMERIC,region TEXT); INSERT INTO rd_expenditure_3 (drug_name,expenditure,region) VALUES ('Curely',5000000,'Germany'),('RemedX',7000000,'France');
SELECT expenditure FROM rd_expenditure_3 WHERE drug_name = 'RemedX' AND region = 'Europe';
What is the average amount of waste produced by the gold mines in the region 'Yukon' between 2017 and 2020?
CREATE TABLE gold_mines_waste (id INT,mine_region TEXT,waste_amount FLOAT,extraction_year INT); INSERT INTO gold_mines_waste (id,mine_region,waste_amount,extraction_year) VALUES (1,'Yukon',1500,2017),(2,'Yukon',1800,2018),(3,'Yukon',1600,2019),(4,'Yukon',1700,2020);
SELECT AVG(waste_amount) FROM gold_mines_waste WHERE mine_region = 'Yukon' AND extraction_year BETWEEN 2017 AND 2020;
What are the names of the first three aircraft manufactured by 'OtherCorp'?
CREATE TABLE Aircraft (id INT,name VARCHAR(50),manufacturer VARCHAR(50)); INSERT INTO Aircraft (id,name,manufacturer) VALUES (1,'F-16','AeroCorp'),(2,'F-35','AeroCorp'),(3,'A-10','OtherCorp'),(4,'A-11','OtherCorp'),(5,'A-12','OtherCorp');
SELECT name FROM Aircraft WHERE manufacturer = 'OtherCorp' LIMIT 3;
What is the total number of volunteers in each program and the average hours they have volunteered?
CREATE TABLE Volunteers (VolunteerID int,Name varchar(50),Program varchar(50),Hours numeric(5,2)); INSERT INTO Volunteers (VolunteerID,Name,Program,Hours) VALUES (1,'Alice','ProgramA',20.00),(2,'Bob','ProgramB',30.00),(3,'Charlie','ProgramA',25.00);
SELECT Program, COUNT(VolunteerID) AS NumVolunteers, AVG(Hours) AS AvgHours FROM Volunteers GROUP BY Program;
How many products use plastic packaging?
CREATE TABLE packaging (package_id INT,product_id INT,material VARCHAR(20),recyclable BOOLEAN); INSERT INTO packaging (package_id,product_id,material,recyclable) VALUES (1,1,'plastic',false),(2,2,'glass',true),(3,3,'paper',true);
SELECT COUNT(*) FROM packaging WHERE material = 'plastic';
What is the average calorie intake for each meal type in the US?
CREATE TABLE meals (id INT,name VARCHAR(255),country VARCHAR(255),avg_calories FLOAT);
SELECT name, AVG(avg_calories) FROM meals WHERE country = 'US' GROUP BY name;
Insert a new record for a tennis match with match_id 6, match_name 'French Open Final', and goals 3.
CREATE TABLE matches (match_id INT,match_name VARCHAR(50),goals INT);
INSERT INTO matches (match_id, match_name, goals) VALUES (6, 'French Open Final', 3);
Insert a new record for 'Recycled Polyester' with a CO2 emission reduction of '30%' into the 'sustainability_metrics' table
CREATE TABLE sustainability_metrics (id INT PRIMARY KEY,fabric VARCHAR(50),co2_reduction DECIMAL(3,2));
INSERT INTO sustainability_metrics (id, fabric, co2_reduction) VALUES (1, 'Recycled Polyester', 0.30);
What is the total biomass of fish for each farming location, grouped by species?
CREATE TABLE farm_locations (location VARCHAR,fish_id INT); CREATE TABLE fish_stock (fish_id INT,species VARCHAR,biomass FLOAT); INSERT INTO farm_locations (location,fish_id) VALUES ('Location A',1),('Location B',2),('Location A',3),('Location C',4); INSERT INTO fish_stock (fish_id,species,biomass) VALUES (1,'Tilapia',...
SELECT fs.species, f.location, SUM(fs.biomass) FROM fish_stock fs JOIN farm_locations f ON fs.fish_id = f.fish_id GROUP BY fs.species, f.location;
What is the total CO2 emission reduction from green building projects?
CREATE TABLE projects (id INT,name TEXT,co2_reduction FLOAT);
SELECT SUM(co2_reduction) FROM projects WHERE projects.name LIKE 'Green%';
What is the success rate of dialectical behavior therapy (DBT) in the UK?
CREATE TABLE mental_health.treatment_outcomes (outcome_id INT,patient_id INT,treatment_id INT,outcome_type VARCHAR(50),outcome_value INT); INSERT INTO mental_health.treatment_outcomes (outcome_id,patient_id,treatment_id,outcome_type,outcome_value) VALUES (6,1004,501,'DBT Success',1);
SELECT AVG(CASE WHEN outcome_type = 'DBT Success' THEN outcome_value ELSE NULL END) FROM mental_health.treatment_outcomes o JOIN mental_health.treatments t ON o.treatment_id = t.treatment_id WHERE t.country = 'UK';
What is the total revenue by ticket type for the year 2022?
CREATE TABLE ticket_sales (sale_id INT,sale_date DATE,ticket_type VARCHAR(255),price DECIMAL(5,2)); INSERT INTO ticket_sales (sale_id,sale_date,ticket_type,price) VALUES (1,'2022-01-01','VIP',200),(2,'2022-02-01','Regular',100),(3,'2022-03-01','VIP',250),(4,'2022-04-01','Regular',150);
SELECT ticket_type, SUM(price) as total_revenue FROM ticket_sales WHERE sale_date >= '2022-01-01' AND sale_date <= '2022-12-31' GROUP BY ticket_type;
What is the average depth of the Mariana Trench?
CREATE TABLE mariana_trench (trench_name TEXT,average_depth REAL); INSERT INTO mariana_trench (trench_name,average_depth) VALUES ('Mariana Trench',10994);
SELECT AVG(average_depth) FROM mariana_trench;
What is the average research grant amount awarded to female assistant professors in the Computer Science department?
CREATE TABLE faculty (id INT,name VARCHAR(50),title VARCHAR(20),department VARCHAR(50),gender VARCHAR(10)); INSERT INTO faculty (id,name,title,department,gender) VALUES (1,'Alice Johnson','Assistant Professor','Computer Science','Female'); INSERT INTO faculty (id,name,title,department,gender) VALUES (2,'Bob Smith','Ass...
SELECT AVG(amount) FROM grants JOIN faculty ON grants.faculty_id = faculty.id WHERE department = 'Computer Science' AND gender = 'Female' AND grant_type = 'Research';
What is the total word count for articles related to a specific topic, in the last year?
CREATE TABLE articles (article_id INT,article_title VARCHAR(100),article_text TEXT,article_date DATE,topic VARCHAR(50)); INSERT INTO articles VALUES (1,'Article 1','Climate change is...','2022-01-01','climate change'),(2,'Article 2','Global warming is...','2022-02-15','climate change'),(3,'Article 3','The environment i...
SELECT SUM(LENGTH(article_text) - LENGTH(REPLACE(article_text, ' ', '')) + 1) as total_word_count FROM articles WHERE topic = 'climate change' AND article_date >= DATE_SUB(CURDATE(), INTERVAL 1 YEAR);
Delete all autonomous taxis in San Francisco that are not in use.
CREATE TABLE public.taxis (id SERIAL PRIMARY KEY,name TEXT,in_use BOOLEAN,city TEXT); INSERT INTO public.taxis (name,in_use,city) VALUES ('Autonomous Taxi 1',FALSE,'San Francisco'),('Autonomous Taxi 2',TRUE,'San Francisco');
DELETE FROM public.taxis WHERE city = 'San Francisco' AND name LIKE 'Autonomous Taxi%' AND in_use = FALSE;
What is the total cargo weight transported by each vessel that visited Australian ports?
CREATE TABLE cargo (id INT,vessel_name VARCHAR(255),cargo_weight INT,port VARCHAR(255),unload_date DATE); INSERT INTO cargo (id,vessel_name,cargo_weight,port,unload_date) VALUES (1,'VesselA',12000,'Sydney','2021-12-20');
SELECT vessel_name, SUM(cargo_weight) as total_weight FROM cargo WHERE port IN ('Sydney', 'Melbourne', 'Brisbane', 'Perth', 'Adelaide') GROUP BY vessel_name;