instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
What is the minimum marketing budget for movies released after 2016?
CREATE TABLE Movies (movie_id INT,title VARCHAR(100),release_year INT,budget INT,marketing_budget INT); INSERT INTO Movies (movie_id,title,release_year,budget,marketing_budget) VALUES (3,'MovieC',2016,60000000,10000000); INSERT INTO Movies (movie_id,title,release_year,budget,marketing_budget) VALUES (4,'MovieD',2017,70...
SELECT MIN(marketing_budget) FROM Movies WHERE release_year > 2016;
Show the number of volunteers, total hours contributed by volunteers, and the average donation amount for each organization in the 'organizations' table.
CREATE TABLE donors (donor_id INT,donor_name TEXT,donation_amount DECIMAL,org_id INT); CREATE TABLE volunteers (volunteer_id INT,volunteer_name TEXT,hours_contributed INT,org_id INT); CREATE TABLE organizations (org_id INT,org_name TEXT);
SELECT organizations.org_name, COUNT(volunteers.volunteer_id) as num_volunteers, SUM(volunteers.hours_contributed) as total_hours, AVG(donors.donation_amount) as avg_donation FROM volunteers INNER JOIN organizations ON volunteers.org_id = organizations.org_id INNER JOIN donors ON organizations.org_id = donors.org_id GR...
List all space missions launched before 1990
CREATE TABLE missions (id INT,name VARCHAR(50),spacecraft VARCHAR(50),launch_year INT);
SELECT name FROM missions WHERE launch_year < 1990;
What is the maximum speed reached during autonomous driving research in Japan?
CREATE TABLE Autonomous_Driving_Tests (id INT,vehicle_model VARCHAR(50),test_location VARCHAR(50),max_speed FLOAT);
SELECT MAX(max_speed) FROM Autonomous_Driving_Tests WHERE test_location = 'Japan';
Show the distribution of mobile subscribers by age group for each country.
CREATE TABLE mobile_subscribers (subscriber_id INT,country VARCHAR(50),age INT);
SELECT country, CASE WHEN age >= 18 AND age <= 24 THEN '18-24' WHEN age >= 25 AND age <= 34 THEN '25-34' WHEN age >= 35 AND age <= 44 THEN '35-44' WHEN age >= 45 AND age <= 54 THEN '45-54' WHEN age >= 55 THEN '55+' END AS age_group, COUNT(*) AS subscriber_count FROM mobile_subscribers GROUP BY country, age_group;
What is the monthly change in landfill capacity?
CREATE TABLE landfill_capacity (id INT,date DATE,capacity INT); INSERT INTO landfill_capacity (id,date,capacity) VALUES (1,'2021-01-01',10000),(2,'2021-02-01',9500),(3,'2021-03-01',9200),(4,'2021-04-01',8900);
SELECT date, capacity - LAG(capacity) OVER (ORDER BY date) AS change_in_capacity FROM landfill_capacity;
Delete records of mineral extractions that have a quantity of less than 50 in the 'Europe' region.
CREATE TABLE Mineral_Extractions_2 (country TEXT,mineral TEXT,quantity INTEGER,region TEXT); INSERT INTO Mineral_Extractions_2 (country,mineral,quantity,region) VALUES ('France','Gold',75,'Europe'); INSERT INTO Mineral_Extractions_2 (country,mineral,quantity,region) VALUES ('Germany','Silver',60,'Europe'); INSERT INTO ...
DELETE FROM Mineral_Extractions_2 WHERE quantity < 50 AND region = 'Europe';
What is the total funding received by biotech startups in California?
CREATE SCHEMA if not exists biotech;CREATE TABLE if not exists biotech.startups(id INT,name TEXT,location TEXT,funding DECIMAL(10,2),sector TEXT);INSERT INTO biotech.startups (id,name,location,funding,sector) VALUES (1,'StartupA','California',1500000.00,'Biotech'),(2,'StartupB','USA',2000000.00,'Biotech'),(3,'StartupC'...
SELECT SUM(funding) FROM biotech.startups WHERE location = 'California';
Which community programs were implemented in neighborhoods with high crime rates?
CREATE TABLE neighborhoods (id INT,name TEXT,crime_rate INT); CREATE TABLE community_programs (id INT,neighborhood_id INT,program TEXT);
SELECT n.name, c.program FROM neighborhoods n JOIN community_programs c ON n.id = c.neighborhood_id WHERE n.crime_rate > 80;
List the top 3 countries with the highest number of volunteers, along with their respective volunteer counts, in the year 2020.
CREATE TABLE Volunteers (VolunteerID INT,Name TEXT,Country TEXT,Hours INT); INSERT INTO Volunteers (VolunteerID,Name,Country,Hours) VALUES (1,'Alice','USA',50),(2,'Bob','Canada',75),(3,'Charlie','Mexico',100);
SELECT Country, SUM(Hours) as TotalHours FROM Volunteers WHERE YEAR(VolunteerDate) = 2020 GROUP BY Country ORDER BY TotalHours DESC LIMIT 3;
Compare the number of tourists visiting Australia from Asia to those from North America in 2020
CREATE TABLE AustraliaVisitorCount (continent VARCHAR(255),year INT,tourists INT); INSERT INTO AustraliaVisitorCount (continent,year,tourists) VALUES ('Asia',2020,1000000),('North America',2020,1400000);
SELECT continent, tourists FROM AustraliaVisitorCount WHERE year = 2020 AND continent IN ('Asia', 'North America');
How many properties in the sustainable_urbanism table are located in 'Eco City'?
CREATE TABLE sustainable_urbanism (property_id INT,size FLOAT,location VARCHAR(255)); INSERT INTO sustainable_urbanism (property_id,size,location) VALUES (1,1200,'Eco City'),(2,1500,'Green Valley');
SELECT COUNT(*) FROM sustainable_urbanism WHERE location = 'Eco City';
Add a new intelligence operation to the 'intelligence_operations' table with 'operation_name' 'Operation Black Swan', 'operation_type' 'Cyberwarfare', 'country_targeted' 'Russia'
CREATE TABLE intelligence_operations (operation_id INT PRIMARY KEY,operation_name VARCHAR(100),operation_type VARCHAR(50),country_targeted VARCHAR(50));
INSERT INTO intelligence_operations (operation_name, operation_type, country_targeted) VALUES ('Operation Black Swan', 'Cyberwarfare', 'Russia');
What is the percentage of patients who have been hospitalized by age group and gender?
CREATE TABLE patients (id INT,name VARCHAR(50),age INT,gender VARCHAR(10),is_hospitalized BOOLEAN); INSERT INTO patients (id,name,age,gender,is_hospitalized) VALUES (1,'John Doe',45,'Male',true),(2,'Jane Smith',35,'Female',false),(3,'Alice Johnson',50,'Female',true),(4,'Bob Lee',60,'Male',false);
SELECT CASE WHEN age < 30 THEN 'Under 30' WHEN age < 50 THEN '30-49' ELSE '50 and over' END AS age_group, gender, COUNT(*) * 100.0 / (SELECT COUNT(*) FROM patients WHERE is_hospitalized = true) AS percentage FROM patients WHERE is_hospitalized = true GROUP BY age_group, gender;
What is the average number of crimes committed per day in each district, categorized by crime type?
CREATE TABLE Districts (DistrictID INT,Name VARCHAR(50)); CREATE TABLE Crimes (CrimeID INT,DistrictID INT,CrimeType VARCHAR(50),NumberOfOccurrences INT,CrimeDate DATE);
SELECT D.Name, C.CrimeType, AVG(C.NumberOfOccurrences / DATEDIFF(day, 0, C.CrimeDate)) as AvgCrimesPerDay FROM Districts D INNER JOIN Crimes C ON D.DistrictID = C.DistrictID GROUP BY D.Name, C.CrimeType;
Delete the research grant with id 3 from the 'grants' table.
CREATE TABLE grants (id INT,department_id INT,amount INT); INSERT INTO grants (id,department_id,amount) VALUES (1,1,500000),(2,2,750000),(3,1,600000);
DELETE FROM grants WHERE id = 3;
Find the number of albums released by African artists in the last 5 years.
CREATE TABLE artists (artist_id INT,artist_name TEXT,country TEXT); INSERT INTO artists (artist_id,artist_name,country) VALUES (1,'Artist 6','Nigeria'),(2,'Artist 7','South Africa'),(3,'Artist 8','USA'); CREATE TABLE albums (album_id INT,title TEXT,release_date DATE,artist_id INT); INSERT INTO albums (album_id,title,re...
SELECT COUNT(albums.album_id) FROM albums JOIN artists ON albums.artist_id = artists.artist_id WHERE artists.country IN ('Nigeria', 'South Africa') AND albums.release_date >= DATE_SUB(CURDATE(), INTERVAL 5 YEAR);
List the unique property types available in inclusive housing schemes?
CREATE TABLE inclusive_schemes (scheme_id INT,property_type VARCHAR(50)); INSERT INTO inclusive_schemes (scheme_id,property_type) VALUES (1,'Apartment'),(2,'Townhouse'),(3,'Condominium'),(1,'House');
SELECT DISTINCT property_type FROM inclusive_schemes;
What is the minimum budget allocated for public parks in the state of California?
CREATE TABLE public_parks_budget (state VARCHAR(20),budget INT); INSERT INTO public_parks_budget (state,budget) VALUES ('California',12000000); INSERT INTO public_parks_budget (state,budget) VALUES ('California',15000000); INSERT INTO public_parks_budget (state,budget) VALUES ('Florida',9000000); INSERT INTO public_par...
SELECT MIN(budget) FROM public_parks_budget WHERE state = 'California';
What is the median duration of stays in Iceland for tourists from Brazil?
CREATE TABLE tourism (visitor_country VARCHAR(50),host_country VARCHAR(50),duration INT); INSERT INTO tourism (visitor_country,host_country,duration) VALUES ('Brazil','Iceland',7),('Brazil','Iceland',10),('Brazil','Iceland',8);
SELECT AVG(duration) as median_duration FROM (SELECT DISTINCT ON (duration) duration FROM tourism WHERE visitor_country = 'Brazil' AND host_country = 'Iceland' ORDER BY duration) subquery;
List the budget for each community development initiative in the 'Women Empowerment' program.
CREATE TABLE community_development (id INT,name TEXT,program TEXT,budget INT); INSERT INTO community_development (id,name,program,budget) VALUES (1,'Initiative A','Women Empowerment',150000),(2,'Initiative B','Youth Empowerment',200000);
SELECT name, budget FROM community_development WHERE program = 'Women Empowerment';
What is the average age of athletes in the athlete_wellbeing table for each sport?
CREATE TABLE athlete_wellbeing (athlete_id INT,name VARCHAR(50),age INT,sport VARCHAR(20));
SELECT s.sport, AVG(a.age) as avg_age FROM athlete_wellbeing a JOIN sports_teams s ON a.team_id = s.team_id GROUP BY s.sport;
What is the average number of hours spent on professional development by teachers in 'remote_learning'?
CREATE TABLE teachers (teacher_id INT,name VARCHAR(20),program VARCHAR(20)); INSERT INTO teachers (teacher_id,name,program) VALUES (1,'John Doe','remote_learning'),(2,'Jane Smith','in_person'),(3,'Maria Garcia','remote_learning'); CREATE TABLE teacher_pd (teacher_id INT,course VARCHAR(20),hours INT); INSERT INTO teache...
SELECT AVG(hours) FROM teacher_pd INNER JOIN teachers ON teacher_pd.teacher_id = teachers.teacher_id WHERE teachers.program = 'remote_learning';
Which marine species have been observed in the Southern Ocean more than once?
CREATE TABLE marine_species_observations (species_name TEXT,observation_date DATE,location TEXT); INSERT INTO marine_species_observations VALUES ('Krill','2018-05-23','Southern Ocean'),('Blue Whale','2019-01-10','Southern Ocean'),('Krill','2020-12-15','Southern Ocean');
SELECT species_name, COUNT(*) FROM marine_species_observations WHERE location = 'Southern Ocean' GROUP BY species_name HAVING COUNT(*) > 1;
Find the total revenue generated by each market in the year 2020.
CREATE TABLE sales (id INT,farmer_id INT,crop_id INT,market_id INT,sale_date DATE,sold_amount DECIMAL(6,2)); CREATE TABLE farmers (id INT,name VARCHAR(30)); CREATE TABLE crops (id INT,name VARCHAR(20),price DECIMAL(6,2)); CREATE TABLE market (id INT,name VARCHAR(10));
SELECT market.name, SUM(sold_amount * crops.price) FROM sales, crops, market WHERE sales.crop_id = crops.id AND sales.market_id = market.id AND YEAR(sale_date) = 2020 GROUP BY market.name;
List all energy storage projects in Indonesia and Vietnam that were commissioned before 2018.
CREATE TABLE energy_storage_projects (id INT,country VARCHAR(255),name VARCHAR(255),commission_date DATE); INSERT INTO energy_storage_projects (id,country,name,commission_date) VALUES (1,'Indonesia','Project A','2016-01-01'); INSERT INTO energy_storage_projects (id,country,name,commission_date) VALUES (2,'Indonesia','P...
SELECT name FROM energy_storage_projects WHERE country IN ('Indonesia', 'Vietnam') AND commission_date < '2018-01-01';
What is the average value of returns from India to Brazil?
CREATE TABLE india_brazil_returns (id INT,value FLOAT); INSERT INTO india_brazil_returns (id,value) VALUES (1,120),(2,150),(3,110);
SELECT AVG(value) FROM india_brazil_returns;
Find the number of visitors who attended exhibitions in Tokyo or New York.
CREATE TABLE Visitors (id INT,city VARCHAR(20)); INSERT INTO Visitors (id,city) VALUES (1,'Tokyo'),(2,'Paris'),(3,'New York'),(4,'Berlin');
SELECT COUNT(*) FROM Visitors WHERE city IN ('Tokyo', 'New York');
Create a table named 'contract_negotiations' with columns 'contract_id', 'company_name', 'negotiation_date
CREATE TABLE contract_negotiations (contract_id INT,company_name VARCHAR(50),negotiation_date DATE);
CREATE TABLE contract_negotiations (contract_id INT, company_name VARCHAR(50), negotiation_date DATE);
What is the average number of hours played per week for players who have played "Minecraft" and are from Canada?
CREATE TABLE PlayerActivity (player_id INT,game VARCHAR(100),hours INT,week INT); INSERT INTO PlayerActivity (player_id,game,hours,week) VALUES (1,'Minecraft',10,1),(2,'Minecraft',8,2),(3,'Minecraft',12,3);
SELECT AVG(hours/52) FROM PlayerActivity pa JOIN Players p ON pa.player_id = p.player_id WHERE p.country = 'Canada' AND pa.game = 'Minecraft';
What is the average daily ridership for each mode of public transportation?
CREATE TABLE public_transportation_modes (mode VARCHAR(20),daily_ridership INT); INSERT INTO public_transportation_modes (mode,daily_ridership) VALUES ('bus',10000),('train',20000),('light_rail',5000);
SELECT mode, AVG(daily_ridership) FROM public_transportation_modes GROUP BY mode;
Find the number of medical patents, by inventor and year.
CREATE TABLE patents (id INT,inventor VARCHAR,year INT,patent VARCHAR);
SELECT p.inventor, p.year, COUNT(p.id) AS num_patents FROM patents p GROUP BY p.inventor, p.year;
Add a new column 'equipment_type' to the 'construction_equipment' table with a default value of 'Heavy'
CREATE TABLE construction_equipment (equipment_id INT,equipment_name TEXT,equipment_age INT,equipment_status TEXT);
ALTER TABLE construction_equipment ADD equipment_type TEXT DEFAULT 'Heavy';
What is the maximum distance between two subway stations in New York City?
CREATE TABLE subway_stations (station_id INT,station_name VARCHAR(255),city VARCHAR(255),distance_to_next_station INT);
SELECT MAX(distance_to_next_station) FROM subway_stations WHERE city = 'New York City';
What is the total amount of minerals extracted in China in 2020, and what was the labor productivity for each mining operation?
CREATE TABLE china_minerals_extracted (id INT,province VARCHAR(255),year INT,amount INT,productivity FLOAT);
SELECT province, year, productivity FROM china_minerals_extracted WHERE province IN ('Shandong', 'Henan', 'Shanxi', 'Inner Mongolia', 'Hebei') AND year = 2020;
What is the average distance and frequency for routes with a distance greater than 10 km and a frequency of at least 150?
CREATE TABLE route (route_id INT,start_station VARCHAR(255),end_station VARCHAR(255),distance FLOAT,frequency INT); INSERT INTO route (route_id,start_station,end_station,distance,frequency) VALUES (5,'Station E','Station F',10.5,150); INSERT INTO route (route_id,start_station,end_station,distance,frequency) VALUES (6,'...
SELECT route_id, AVG(distance) as avg_distance, AVG(frequency) as avg_frequency FROM route WHERE distance > 10 AND frequency >= 150 GROUP BY route_id;
What is the average population of caribou in the 'arctic_caribou' table, for the last 3 years?
CREATE TABLE arctic_caribou (year INT,population INT);
SELECT AVG(population) FROM arctic_caribou WHERE year BETWEEN (SELECT MAX(year) FROM arctic_caribou) - 2 AND (SELECT MAX(year) FROM arctic_caribou);
How many 4-star hotels are there in Barcelona?
CREATE TABLE hotels (hotel_id INT,name TEXT,city TEXT,stars INT); INSERT INTO hotels (hotel_id,name,city,stars) VALUES (1,'Hotel Barcelona','Barcelona',4),(2,'Hotel Madrid','Madrid',5),(3,'Hotel Sevilla','Sevilla',3),(4,'Hotel Valencia','Valencia',2),(5,'Hotel Granada','Granada',4);
SELECT COUNT(*) FROM hotels WHERE city = 'Barcelona' AND stars = 4;
Delete a mobile plan from the 'mobile_plans' table
CREATE TABLE mobile_plans (plan_id INT,plan_name VARCHAR(255),data_limit INT,price DECIMAL(5,2));
DELETE FROM mobile_plans WHERE plan_id = 2001;
Delete records from the 'inventory' table where the price is less than 10
CREATE TABLE inventory (inventory_id INT,product_name VARCHAR(255),quantity INT,price DECIMAL(5,2));
DELETE FROM inventory WHERE price < 10;
Calculate the percentage of total attendees for each event type in New York.
CREATE TABLE Events (ID INT,City VARCHAR(50),EventType VARCHAR(50),AttendeeCount INT);
SELECT EventType, AttendeeCount, PERCENT_RANK() OVER(PARTITION BY EventType ORDER BY AttendeeCount) FROM Events WHERE City = 'New York';
What is the average fuel consumption rate for VESSEL002?
CREATE TABLE vessels (id VARCHAR(20),name VARCHAR(20)); INSERT INTO vessels (id,name) VALUES ('VES001','VESSEL001'),('VES002','VESSEL002'); CREATE TABLE fuel_consumption (vessel_id VARCHAR(20),consumption_rate DECIMAL(5,2)); INSERT INTO fuel_consumption (vessel_id,consumption_rate) VALUES ('VES001',3.5),('VES001',3.2),...
SELECT AVG(consumption_rate) FROM fuel_consumption WHERE vessel_id = 'VES002';
What is the minimum number of devices owned by users?
CREATE TABLE Users (UserID INT,Devices INT); INSERT INTO Users (UserID,Devices) VALUES (1,3),(2,2),(3,1);
SELECT MIN(Devices) FROM Users;
What is the average age of community health workers who identify as Asian American or Native American?
CREATE TABLE CommunityHealthWorker (WorkerID INT,Age INT,Identity VARCHAR(50)); INSERT INTO CommunityHealthWorker (WorkerID,Age,Identity) VALUES (1,45,'African American'),(2,35,'Hispanic'),(3,50,'Asian American'),(4,40,'Native American'),(5,55,'Caucasian'),(6,30,'Asian American'),(7,45,'Native American'),(8,42,'African...
SELECT AVG(Age) as AvgAge FROM CommunityHealthWorker WHERE Identity IN ('Asian American', 'Native American');
How many times has a specific food additive been used by suppliers in the past year?
CREATE TABLE Suppliers (SupplierID int,Name varchar(50),LastInspection date); INSERT INTO Suppliers (SupplierID,Name,LastInspection) VALUES (1,'Local Farm','2022-03-15'),(2,'Texas Ranch','2022-02-10'); CREATE TABLE Additives (AdditiveID int,Name varchar(50),SupplierID int,Uses int); INSERT INTO Additives (AdditiveID,Na...
SELECT SUM(Additives.Uses) FROM Additives JOIN Suppliers ON Additives.SupplierID = Suppliers.SupplierID WHERE Suppliers.LastInspection >= '2021-01-01';
List all ethical manufacturing certifications held by each supplier and the number of certifications they have.
CREATE TABLE suppliers (supplier_id INT,name TEXT,certifications TEXT);
SELECT supplier_id, name, COUNT(certifications) as num_certifications FROM suppliers GROUP BY supplier_id;
Landfill capacity in 2022 for all regions?
CREATE TABLE landfill_capacity (region VARCHAR(50),year INT,capacity INT); INSERT INTO landfill_capacity (region,year,capacity) VALUES ('North',2022,2000),('South',2022,1800),('East',2022,2200),('West',2022,1900);
SELECT region, capacity FROM landfill_capacity WHERE year = 2022;
What is the average yield of crops for each farmer in 'farmers_table'?
CREATE TABLE farmers_table (farmer_id INT,crop VARCHAR(50),yield INT); INSERT INTO farmers_table (farmer_id,crop,yield) VALUES (1,'corn',100),(1,'wheat',80),(2,'corn',110),(2,'wheat',90),(3,'corn',95),(3,'wheat',75);
SELECT farmer_id, AVG(yield) as avg_yield FROM farmers_table GROUP BY farmer_id;
What is the total number of workouts in the last month for members who identify as female and have a smartwatch?
CREATE TABLE Members (MemberID INT,Gender VARCHAR(10),HasSmartwatch BOOLEAN); CREATE TABLE Workouts (WorkoutID INT,MemberID INT,WorkoutDate DATE);
SELECT COUNT(*) FROM Workouts INNER JOIN Members ON Workouts.MemberID = Members.MemberID WHERE Members.Gender = 'female' AND Members.HasSmartwatch = TRUE AND WorkoutDate >= DATE_SUB(CURDATE(), INTERVAL 1 MONTH);
What is the average time between train cleanings for each line?
CREATE TABLE trains (id INT,line VARCHAR(10),clean_date DATE); INSERT INTO trains (id,line,clean_date) VALUES (1,'Red','2022-01-01'),(2,'Green','2022-01-02'),(3,'Blue','2022-01-03');
SELECT line, AVG(DATEDIFF('day', LAG(clean_date) OVER (PARTITION BY line ORDER BY clean_date), clean_date)) FROM trains GROUP BY line;
Find the top 3 countries with the highest average soil temperature in May.
CREATE TABLE WeatherStats (id INT,country VARCHAR(50),month VARCHAR(10),avg_temp DECIMAL(5,2)); INSERT INTO WeatherStats (id,country,month,avg_temp) VALUES (1,'US','May',22.5),(2,'Canada','May',15.3),(3,'Mexico','May',27.2),(4,'Brazil','May',24.6),(5,'Argentina','May',18.9);
SELECT country, AVG(avg_temp) as AvgTemp FROM WeatherStats WHERE month = 'May' GROUP BY country ORDER BY AvgTemp DESC LIMIT 3;
List all unique categories of programs and their respective total budgets?
CREATE TABLE Programs (ProgramID INT,ProgramName TEXT,Category TEXT,Budget DECIMAL(10,2)); INSERT INTO Programs (ProgramID,ProgramName,Category,Budget) VALUES (1,'Arts Education','Education',3000.00),(2,'Health Awareness','Health',7000.00);
SELECT Category, SUM(Budget) AS TotalBudget FROM Programs GROUP BY Category;
List all unique municipalities with their corresponding citizen complaints, grouped by type and municipality.
CREATE TABLE municipalities (id INT PRIMARY KEY,name VARCHAR(255));CREATE TABLE complaints (id INT PRIMARY KEY,municipality_id INT,type VARCHAR(255));
SELECT m.name, c.type, COUNT(c.id) FROM municipalities m JOIN complaints c ON m.id = c.municipality_id GROUP BY m.name, c.type;
What is the total transaction amount by currency for each day in the past week?
CREATE TABLE transactions (transaction_id INT,customer_id INT,amount DECIMAL(10,2),transaction_date DATE,currency VARCHAR(50)); CREATE VIEW daily_transactions AS SELECT transaction_date,SUM(amount) as total_amount FROM transactions GROUP BY transaction_date;
SELECT dt.transaction_date, t.currency, SUM(t.amount) as currency_total FROM daily_transactions dt INNER JOIN transactions t ON dt.transaction_date = t.transaction_date GROUP BY dt.transaction_date, t.currency;
Show the total number of active rigs in the North Sea in 2019 and 2020
CREATE TABLE rigs (id INT PRIMARY KEY,name TEXT,status TEXT,location TEXT); INSERT INTO rigs (id,name,status,location) VALUES (1,'Rig A','Active','North Sea'),(2,'Rig B','Inactive','North Sea'),(3,'Rig C','Active','North Sea'),(4,'Rig D','Active','Gulf of Mexico'); CREATE TABLE rig_history (rig_id INT,year INT,active_r...
SELECT r.location, SUM(rh.active_rigs) as total_active_rigs FROM rigs r JOIN rig_history rh ON r.id = rh.rig_id WHERE r.location = 'North Sea' AND rh.year IN (2019, 2020) GROUP BY r.location;
What was the total fare collected from passengers for route 1A in January 2022?
CREATE TABLE routes (route_id INT,route_name VARCHAR(255)); INSERT INTO routes (route_id,route_name) VALUES (1,'1A'),(2,'1B'); CREATE TABLE fares (fare_id INT,route_id INT,fare_amount DECIMAL(5,2),transaction_date DATE); INSERT INTO fares (fare_id,route_id,fare_amount,transaction_date) VALUES (1,1,2.50,'2022-01-01'),(2...
SELECT SUM(fare_amount) FROM fares WHERE route_id = 1 AND transaction_date BETWEEN '2022-01-01' AND '2022-01-31';
What is the total funding received by startups founded by Latinx entrepreneurs in the fintech sector?
CREATE TABLE company (id INT,name TEXT,industry TEXT,founder_race TEXT); INSERT INTO company (id,name,industry,founder_race) VALUES (1,'EarlyBird','Fintech','Latinx');
SELECT SUM(funding_amount) FROM (SELECT funding_amount FROM investment WHERE company_id IN (SELECT id FROM company WHERE founder_race = 'Latinx' AND industry = 'Fintech')) AS subquery;
What is the average depth of marine protected areas in the Indian Ocean with a maximum depth greater than 100 meters?
CREATE TABLE marine_protected_areas_indian_ocean (area_name VARCHAR(255),min_depth DECIMAL(10,2),max_depth DECIMAL(10,2)); INSERT INTO marine_protected_areas_indian_ocean (area_name,min_depth,max_depth) VALUES ('Maldives Marine Reserve',10.00,120.50),('Chagos Marine Protected Area',50.00,150.30),('Seychelles Marine Par...
SELECT AVG(min_depth) FROM marine_protected_areas_indian_ocean WHERE max_depth > 100.00;
How many local businesses in Cairo have benefited from virtual tourism?
CREATE TABLE local_business (business_id INT,name TEXT,city TEXT,country TEXT,benefits INT); INSERT INTO local_business (business_id,name,city,country,benefits) VALUES (4,'Cairo Art Shop','Cairo','Egypt',80);
SELECT COUNT(*) FROM local_business WHERE city = 'Cairo' AND country = 'Egypt';
What is the sum of visitor counts for each heritage site in France?
CREATE TABLE heritage_sites_france (id INT,country VARCHAR(50),name VARCHAR(100),visitor_count INT); INSERT INTO heritage_sites_france (id,country,name,visitor_count) VALUES (1,'France','Site A',1000),(2,'France','Site B',2000),(3,'France','Site C',3000);
SELECT name, SUM(visitor_count) OVER (PARTITION BY country) FROM heritage_sites_france WHERE country = 'France';
Find the minimum price of products that are Cruelty-free
CREATE TABLE products (product_id INT,name VARCHAR(255),price DECIMAL(5,2),cruelty_free BOOLEAN);
SELECT MIN(price) FROM products WHERE cruelty_free = TRUE;
Create a table for aircraft manufacturing data
CREATE TABLE aircraft_manufacturing (id INT PRIMARY KEY,manufacturer VARCHAR(255),model VARCHAR(255),production_year INT,quantity INT);
CREATE TABLE aircraft_manufacturing (id INT PRIMARY KEY, manufacturer VARCHAR(255), model VARCHAR(255), production_year INT, quantity INT);
What is the maximum duration of each astronaut's spacewalk?
CREATE TABLE astronaut_spacewalks (id INT,astronaut VARCHAR,spacewalk_date DATE,duration INT);
SELECT astronaut, MAX(duration) as max_spacewalk_duration FROM astronaut_spacewalks GROUP BY astronaut;
What is the total research grant funding received by female faculty in the Mathematics department?
CREATE TABLE faculty (id INT,name VARCHAR(50),department VARCHAR(50),gender VARCHAR(50),position VARCHAR(50)); INSERT INTO faculty (id,name,department,gender,position) VALUES (1,'Alice Johnson','Mathematics','Female','Professor'); INSERT INTO faculty (id,name,department,gender,position) VALUES (2,'Bob Brown','Mathemati...
SELECT SUM(g.amount) FROM grants g JOIN faculty f ON g.faculty_id = f.id WHERE f.department = 'Mathematics' AND f.gender = 'Female';
What is the maximum billing amount for cases in the family law specialization?
CREATE TABLE Attorneys (AttorneyID INT,Specialization VARCHAR(255)); INSERT INTO Attorneys (AttorneyID,Specialization) VALUES (1,'Civil Law'); INSERT INTO Attorneys (AttorneyID,Specialization) VALUES (2,'Criminal Law'); INSERT INTO Attorneys (AttorneyID,Specialization) VALUES (3,'Family Law'); CREATE TABLE Cases (CaseI...
SELECT MAX(BillingAmount) FROM Cases INNER JOIN Attorneys ON Cases.AttorneyID = Attorneys.AttorneyID WHERE Specialization = 'Family Law';
What is the maximum productivity of workers in the copper mines, categorized by their roles, for the year 2018?
CREATE TABLE copper_mines (id INT,worker_role TEXT,productivity FLOAT,extraction_year INT); INSERT INTO copper_mines (id,worker_role,productivity,extraction_year) VALUES (1,'Engineer',14.2,2018),(2,'Miner',10.5,2018),(3,'Supervisor',12.7,2018),(4,'Engineer',13.5,2018);
SELECT worker_role, MAX(productivity) FROM copper_mines WHERE extraction_year = 2018 GROUP BY worker_role;
Update drug prices to match the median price
CREATE TABLE drugs (drug_id INT,drug_name VARCHAR(50),price DECIMAL(10,2)); INSERT INTO drugs (drug_id,drug_name,price) VALUES (1,'DrugA',50),(2,'DrugB',75),(3,'DrugC',100)
UPDATE drugs SET price = (SELECT AVG(price) FROM drugs)
What is the maximum labor cost per square foot for sustainable building projects in California?
CREATE TABLE sustainable_buildings (id INT,state VARCHAR(2),cost DECIMAL(5,2)); INSERT INTO sustainable_buildings (id,state,cost) VALUES (1,'TX',150.50),(2,'CA',200.75),(3,'TX',175.20);
SELECT MAX(cost) FROM sustainable_buildings WHERE state = 'CA';
Which faculty members have published the most articles in the last 3 years?
CREATE TABLE faculty (id INT,name TEXT,department_id INT); CREATE TABLE publications (id INT,faculty_id INT,year INT,journal TEXT); INSERT INTO faculty (id,name,department_id) VALUES (1,'Alice',1),(2,'Bob',2),(3,'Charlie',1); INSERT INTO publications (id,faculty_id,year,journal) VALUES (1,1,2020,'JMLR'),(2,1,2019,'Neu...
SELECT f.name, COUNT(p.id) as num_publications FROM faculty f JOIN publications p ON f.id = p.faculty_id WHERE p.year BETWEEN 2019 AND 2021 GROUP BY f.name ORDER BY num_publications DESC;
How many customers have a savings account in the Green Community Credit Union?
CREATE TABLE accounts (customer_id INT,account_type VARCHAR(50)); INSERT INTO accounts (customer_id,account_type) VALUES (1,'Checking'),(2,'Savings'),(3,'Checking'),(4,'Savings');
SELECT COUNT(*) FROM accounts WHERE account_type = 'Savings';
Update the 'humidity' value to 80% in the 'Plot4' on 2022-10-31.
CREATE TABLE Plot4 (date DATE,humidity FLOAT);
UPDATE Plot4 SET humidity = 80 WHERE date = '2022-10-31';
Identify states with no health equity metrics data.
CREATE TABLE state_health_equity (state VARCHAR(2),metrics INT); INSERT INTO state_health_equity (state,metrics) VALUES ('NY',10),('CA',5),('TX',0);
SELECT state FROM state_health_equity WHERE metrics = 0;
Insert new records into the species table
CREATE TABLE species(id INT,name VARCHAR(255),common_name VARCHAR(255),population INT);
INSERT INTO species (id, name, common_name, population) VALUES (1, 'Ursus maritimus', 'Polar Bear', 25000); INSERT INTO species (id, name, common_name, population) VALUES (2, 'Rangifer tarandus', 'Reindeer', 4000000);
What is the minimum water usage in the residential sector in all states in 2018?
CREATE TABLE residential_water_usage (state VARCHAR(20),year INT,usage FLOAT); INSERT INTO residential_water_usage (state,year,usage) VALUES ('New York',2018,3.2),('Florida',2018,3.8),('Texas',2018,4.1),('California',2018,4.7),('Illinois',2018,3.9);
SELECT MIN(usage) FROM residential_water_usage WHERE year = 2018;
Who are the top 3 female farmers in Indonesia by agricultural innovation program participation, and what is the name of the program they participate in the most?
CREATE TABLE farmers(id INT,name TEXT,gender TEXT,country TEXT); INSERT INTO farmers(id,name,gender,country) VALUES (1,'Sri','female','Indonesia'); INSERT INTO farmers(id,name,gender,country) VALUES (2,'Budi','male','Indonesia'); INSERT INTO farmers(id,name,gender,country) VALUES (3,'Chandra','female','Indonesia'); CRE...
SELECT f.name, p.program FROM (SELECT farmer_id, program, COUNT(*) as participation FROM programs GROUP BY farmer_id, program ORDER BY participation DESC LIMIT 3) AS t INNER JOIN farmers f ON t.farmer_id = f.id INNER JOIN programs p ON t.program = p.program WHERE f.gender = 'female' AND f.country = 'Indonesia';
What is the average release date of songs in the Hip Hop genre?
CREATE TABLE songs (id INT,name VARCHAR(255),genre VARCHAR(255),release_date DATE);
SELECT AVG(DATEDIFF('day', '1970-01-01', release_date)) as avg_release_date FROM songs WHERE genre = 'Hip Hop';
Which are the artists with the most works exhibited in the last 10 years?
CREATE TABLE artists (id INT,name TEXT); CREATE TABLE artworks (id INT,title TEXT,artist_id INT,exhibition_year INT); INSERT INTO artists (id,name) VALUES (1,'Claude Monet'),(2,'Pablo Picasso'),(3,'Vincent Van Gogh'); INSERT INTO artworks (id,title,artist_id,exhibition_year) VALUES (1,'Water Lilies',1,1905),(2,'The Bou...
SELECT artist_id, name, COUNT(*) as exhibited_works FROM artists a INNER JOIN artworks ar ON a.id = ar.artist_id WHERE exhibition_year >= YEAR(CURRENT_DATE) - 10 GROUP BY artist_id, name ORDER BY exhibited_works DESC;
Show the total quantity of products sourced from each country.
CREATE TABLE products (product_id INT,product_name VARCHAR(50),source_country VARCHAR(50),quantity INT); INSERT INTO products (product_id,product_name,source_country,quantity) VALUES (1,'T-Shirt','USA',100),(2,'Pants','China',200),(3,'Jacket','India',150),(4,'Socks','Bangladesh',250);
SELECT source_country, SUM(quantity) FROM products GROUP BY source_country;
Which sustainable material has the least number of products?
CREATE TABLE products (id INT,name VARCHAR(255),material VARCHAR(255)); INSERT INTO products (id,name,material) VALUES (1,'T-Shirt','Organic Cotton'),(2,'Hoodie','Recycled Polyester'),(3,'Pants','Hemp'),(4,'Jacket','Organic Cotton');
SELECT material, COUNT(*) as count FROM products GROUP BY material HAVING count = (SELECT MIN(count) FROM (SELECT material, COUNT(*) as count FROM products GROUP BY material) as subquery);
Delete records in the drought_impact table where severity is 'None'
CREATE TABLE drought_impact (location VARCHAR(255),year INT,severity VARCHAR(255));
DELETE FROM drought_impact WHERE severity = 'None';
What is the earliest year a spacecraft has entered interstellar space?
CREATE TABLE Spacecrafts (Id INT,Name VARCHAR(50),EntryYear INT); INSERT INTO Spacecrafts (Id,Name,EntryYear) VALUES (1,'Voyager 1',1980),(2,'Voyager 2',1985),(3,'Pioneer 10',2003),(4,'Pioneer 11',2003),(5,'New Horizons',2012);
SELECT MIN(EntryYear) FROM Spacecrafts WHERE EntryYear > 0;
Identify the dishes that have a higher calorie content than the average calorie content for all dishes?
CREATE TABLE Dishes (DishID INT,DishName VARCHAR(50),Cuisine VARCHAR(50),Calories INT); INSERT INTO Dishes (DishID,DishName,Cuisine,Calories) VALUES (1,'Hummus','Mediterranean',250),(2,'Falafel','Mediterranean',350),(3,'Pizza','Italian',800),(4,'Pasta','Italian',700);
SELECT DishName FROM Dishes WHERE Calories > (SELECT AVG(Calories) FROM Dishes);
What is the total number of posts with the hashtag #music in India?
CREATE TABLE posts (id INT,user_id INT,hashtags TEXT); INSERT INTO posts (id,user_id,hashtags) VALUES (1,1,'#music'),(2,1,'#food'),(3,2,'#music'),(4,3,'#art'),(5,4,'#music'); CREATE TABLE users (id INT,country VARCHAR(2)); INSERT INTO users (id,country) VALUES (1,'IN'),(2,'US'),(3,'IN'),(4,'CA');
SELECT COUNT(*) as num_posts FROM posts JOIN users ON posts.user_id = users.id WHERE hashtags LIKE '%#music%' AND users.country = 'IN';
What are the top 3 biosensor technology patents by patent date in Japan and the United Kingdom?
CREATE SCHEMA if not exists biosensors; USE biosensors; CREATE TABLE if not exists patents (id INT PRIMARY KEY,name VARCHAR(255),patent_date DATE,country VARCHAR(255)); INSERT INTO patents (id,name,patent_date,country) VALUES (1,'PatentG','2019-06-12','Japan'),(2,'PatentH','2020-02-28','UK'),(3,'PatentI','2018-11-11','...
SELECT * FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY country ORDER BY patent_date DESC) as row_num FROM patents WHERE country IN ('Japan', 'UK')) as patents_ranked WHERE row_num <= 3;
How many vessels were inspected for maritime safety in the Indian Ocean in 2020?
CREATE TABLE maritime_safety_inspections (id INT,vessel_name VARCHAR(255),inspection_year INT,ocean VARCHAR(255)); INSERT INTO maritime_safety_inspections (id,vessel_name,inspection_year,ocean) VALUES (1,'Vessel 1',2019,'Indian'),(2,'Vessel 2',2020,'Indian'),(3,'Vessel 3',2018,'Atlantic'),(4,'Vessel 4',2021,'Pacific');
SELECT COUNT(*) FROM maritime_safety_inspections WHERE inspection_year = 2020 AND ocean = 'Indian';
Which mobile subscribers have a billing address in a specific city?
CREATE TABLE mobile_subscribers (subscriber_id INT,first_name VARCHAR(50),last_name VARCHAR(50),billing_address VARCHAR(100),city VARCHAR(50));
SELECT subscriber_id, first_name, last_name, billing_address FROM mobile_subscribers WHERE city = 'CityName';
How many cultural heritage sites are in Kyoto?
CREATE TABLE cultural_sites (site_id INT,site_name VARCHAR(100),city VARCHAR(100),type VARCHAR(50)); INSERT INTO cultural_sites (site_id,site_name,city,type) VALUES (1,'Kinkaku-ji','Kyoto','Temple'); INSERT INTO cultural_sites (site_id,site_name,city,type) VALUES (2,'Ginkaku-ji','Kyoto','Temple');
SELECT COUNT(*) FROM cultural_sites WHERE city = 'Kyoto';
What is the average water temperature in the Salmon Farms?
CREATE TABLE Salmon_Farms (Farm_ID INT,Farm_Name TEXT,Longitude FLOAT,Latitude FLOAT,Water_Temperature FLOAT); INSERT INTO Salmon_Farms (Farm_ID,Farm_Name,Longitude,Latitude,Water_Temperature) VALUES (1,'Farm A',-122.345,47.678,12.5); INSERT INTO Salmon_Farms (Farm_ID,Farm_Name,Longitude,Latitude,Water_Temperature) VAL...
SELECT AVG(Water_Temperature) FROM Salmon_Farms;
Get the details of the authors who have not published any article in the last 3 months in 'authorperformance' database.
CREATE TABLE authors (author_id INT,name TEXT); CREATE TABLE articles (article_id INT,title TEXT,author_id INT,publish_date DATE); INSERT INTO authors VALUES (1,'John Doe'); INSERT INTO articles VALUES (1,'Article 1',1,'2022-01-01');
SELECT authors.author_id, authors.name FROM authors LEFT JOIN articles ON authors.author_id = articles.author_id WHERE articles.publish_date IS NULL AND articles.publish_date < DATE_SUB(CURDATE(), INTERVAL 3 MONTH)
List the programs with the highest and lowest total donations in H1 2021.
CREATE TABLE Programs (ProgramID int,ProgramName varchar(255)); CREATE TABLE Donations (DonationID int,ProgramID int,DonationAmt decimal(10,2),DonationDate date); INSERT INTO Programs (ProgramID,ProgramName) VALUES (101,'Education'),(102,'Health'),(103,'Environment'); INSERT INTO Donations (DonationID,ProgramID,Donatio...
SELECT ProgramName, SUM(DonationAmt) AS TotalDonations FROM Donations INNER JOIN Programs ON Donations.ProgramID = Programs.ProgramID WHERE EXTRACT(YEAR FROM DonationDate) = 2021 AND EXTRACT(MONTH FROM DonationDate) BETWEEN 1 AND 6 GROUP BY ProgramName ORDER BY TotalDonations DESC, ProgramName;
What is the total number of mining projects in South America, and what is their combined labor force?
CREATE TABLE mining_projects (project_id INT,project_name TEXT,location TEXT,number_of_employees INT); INSERT INTO mining_projects (project_id,project_name,location,number_of_employees) VALUES (1,'El Tesoro','Mexico',100),(2,'La Fortuna','Peru',150),(3,'Las Vegas','Chile',200);
SELECT SUM(number_of_employees) FROM mining_projects WHERE location LIKE 'South%America';
Insert a new record into the 'startups' table with 'name' = 'GreenGen' and 'funding_round' = 'Seed'
CREATE TABLE startups (id INT PRIMARY KEY,name VARCHAR(100),industry VARCHAR(50),funding_round VARCHAR(50),funding_amount INT);
INSERT INTO startups (name, industry, funding_round, funding_amount) VALUES ('GreenGen', 'Biotech', 'Seed', 500000);
What is the average rating of eco-friendly accommodations in Costa Rica?
CREATE TABLE eco_accommodations (id INT,country VARCHAR(50),rating DECIMAL(2,1)); INSERT INTO eco_accommodations (id,country,rating) VALUES (1,'Costa Rica',4.5),(2,'Costa Rica',4.7),(3,'Costa Rica',4.2);
SELECT AVG(rating) FROM eco_accommodations WHERE country = 'Costa Rica';
How many songs were released by each artist in the 90s?
CREATE TABLE songs (song_id INT,title TEXT,release_year INT,artist_id INT); CREATE TABLE artists (artist_id INT,name TEXT);
SELECT a.name, COUNT(s.song_id) FROM songs s JOIN artists a ON s.artist_id = a.artist_id WHERE s.release_year BETWEEN 1990 AND 1999 GROUP BY a.name;
What is the maximum landfill capacity in the African region?
CREATE TABLE LandfillCapacity (capacity_id INT,region VARCHAR(255),capacity DECIMAL(10,2)); INSERT INTO LandfillCapacity (capacity_id,region,capacity) VALUES (1,'North America',2500),(2,'South America',3000),(3,'Europe',1800),(4,'Asia-Pacific',2200),(5,'Africa',1900);
SELECT MAX(capacity) FROM LandfillCapacity WHERE region = 'Africa';
What is the maximum altitude reached by each aircraft model?
CREATE TABLE Flight_Altitude (altitude INT,aircraft_model VARCHAR(255)); INSERT INTO Flight_Altitude (altitude,aircraft_model) VALUES (40000,'B737'),(42000,'A320'),(40000,'B747');
SELECT aircraft_model, MAX(altitude) FROM Flight_Altitude GROUP BY aircraft_model;
Which economic diversification efforts were initiated in Mexico in 2019?'
CREATE TABLE EconomicDiversificationEfforts (id INT,country VARCHAR(50),effort_name VARCHAR(100),start_date DATE); INSERT INTO EconomicDiversificationEfforts (id,country,effort_name,start_date) VALUES (1,'Mexico','Renewable Energy','2019-04-01');
SELECT * FROM EconomicDiversificationEfforts WHERE country = 'Mexico' AND YEAR(start_date) = 2019;
What is the maximum labor cost for a project that used sustainable materials?
CREATE TABLE Projects (id INT,used_sustainable_materials BOOLEAN,labor_cost FLOAT); INSERT INTO Projects (id,used_sustainable_materials,labor_cost) VALUES (1,true,15000.0),(2,false,12000.0),(3,true,17000.0);
SELECT MAX(labor_cost) FROM Projects WHERE used_sustainable_materials = true;
What is the total revenue from hockey merchandise sales for the 'Northeast Division'?
CREATE TABLE sales (sale_id INT,item_type VARCHAR(50),division VARCHAR(50),sale_price DECIMAL(5,2)); INSERT INTO sales (sale_id,item_type,division) VALUES (1,'Jersey','Northeast Division'),(2,'Hat','Northeast Division'),(3,'Shirt','Northeast Division'),(4,'Scarf','Northeast Division'),(5,'Jersey','Northeast Division'),...
SELECT SUM(sale_price) FROM sales WHERE division = 'Northeast Division' AND item_type = 'Merchandise';
What is the average speed of vessels that docked in the port of Oakland in the last 6 months?
CREATE TABLE Vessels (ID INT,Name TEXT,Speed FLOAT,DockedAt DATETIME); INSERT INTO Vessels (ID,Name,Speed,DockedAt) VALUES (1,'Vessel1',20.5,'2022-01-01 10:00:00'),(2,'Vessel2',25.3,'2022-01-05 14:30:00'); CREATE TABLE Ports (ID INT,Name TEXT); INSERT INTO Ports (ID,Name) VALUES (1,'Oakland'),(2,'San_Francisco');
SELECT AVG(Speed) FROM Vessels WHERE DockedAt >= DATE_SUB(CURRENT_DATE, INTERVAL 6 MONTH) AND Ports.Name = 'Oakland';