instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
Show vessels with the least frequent safety inspection failures in the last two years.
CREATE TABLE vessels (id INT,name VARCHAR(255)); INSERT INTO vessels (id,name) VALUES (1,'VesselA'),(2,'VesselB'),(3,'VesselC'); CREATE TABLE safety_records (id INT,vessel_id INT,inspection_date DATE,result ENUM('PASS','FAIL')); INSERT INTO safety_records (id,vessel_id,inspection_date,result) VALUES (1,1,'2021-05-05','FAIL'),(2,2,'2021-08-01','FAIL'),(3,3,'2021-09-15','PASS'),(4,1,'2020-02-12','FAIL'),(5,2,'2020-05-19','PASS');
SELECT vessel_id, COUNT(*) as fails_count FROM safety_records WHERE result = 'FAIL' AND inspection_date >= DATE_SUB(CURDATE(), INTERVAL 2 YEAR) GROUP BY vessel_id ORDER BY fails_count ASC;
What is the number of public schools in each city in the state of New York, including their type and number of students?
CREATE TABLE cities(id INT,name TEXT,state TEXT); INSERT INTO cities VALUES (1,'City A','New York'); INSERT INTO cities VALUES (2,'City B','New York'); INSERT INTO cities VALUES (3,'City C','New York'); CREATE TABLE schools(id INT,city_id INT,type TEXT,students_count INT); INSERT INTO schools VALUES (1,1,'Elementary',500); INSERT INTO schools VALUES (2,1,'Middle',600); INSERT INTO schools VALUES (3,2,'Elementary',450); INSERT INTO schools VALUES (4,2,'High',800); INSERT INTO schools VALUES (5,3,'Middle',700);
SELECT c.name, s.type, COUNT(*) as school_count, SUM(s.students_count) as total_students FROM cities c JOIN schools s ON c.id = s.city_id WHERE c.state = 'New York' GROUP BY c.name, s.type;
How many members have a fitness band and live in Canada?
CREATE TABLE Members (MemberID INT,Age INT,Gender VARCHAR(10),Country VARCHAR(20),HasFitnessBand BOOLEAN); INSERT INTO Members (MemberID,Age,Gender,Country,HasFitnessBand) VALUES (1,35,'Male','Canada',true),(2,28,'Female','USA',false),(3,42,'Male','Canada',true);
SELECT COUNT(*) FROM Members WHERE Country = 'Canada' AND HasFitnessBand = true;
What is the maximum grant amount given for women-led agricultural innovation projects in Rwanda?
CREATE TABLE agricultural_innovation_projects (id INT,country VARCHAR(20),grant_amount DECIMAL(10,2),gender VARCHAR(10)); INSERT INTO agricultural_innovation_projects (id,country,grant_amount,gender) VALUES (1,'Rwanda',8000.00,'Women'),(2,'Rwanda',6000.00,'Men');
SELECT MAX(grant_amount) FROM agricultural_innovation_projects WHERE country = 'Rwanda' AND gender = 'Women';
What is the total amount of water consumption for the top 5 households with the highest water consumption?
CREATE TABLE household_water_consumption (id INT,household INT,water_consumption FLOAT); INSERT INTO household_water_consumption (id,household,water_consumption) VALUES (1,1001,500),(2,1002,600),(3,1003,700),(4,1004,800),(5,1005,900),(6,1006,400);
SELECT SUM(water_consumption) FROM (SELECT household, water_consumption FROM household_water_consumption ORDER BY water_consumption DESC LIMIT 5) subquery;
Show mammal species with populations greater than 100
CREATE TABLE animals (id INT PRIMARY KEY,name VARCHAR(50),species VARCHAR(50),population INT); INSERT INTO animals (id,name,species,population) VALUES (1,'Giraffe','Mammal',500); CREATE VIEW mammals AS SELECT * FROM animals WHERE species = 'Mammal';
SELECT species, population FROM mammals WHERE population > 100;
What is the total amount of assets for financial institutions in Q3 2022 owned by women?
CREATE TABLE financial_institutions(id INT,institution_name VARCHAR(50),quarter INT,year INT,assets INT,owner_gender VARCHAR(10)); INSERT INTO financial_institutions VALUES (1,'ABC Bank',3,2022,5000000,'Female'); INSERT INTO financial_institutions VALUES (2,'XYZ Finance',2,2022,6000000,'Male'); INSERT INTO financial_institutions VALUES (3,'LMN Invest',1,2022,7000000,'Female'); INSERT INTO financial_institutions VALUES (4,'STU Capital',4,2022,8000000,'Male');
SELECT SUM(assets) FROM financial_institutions WHERE quarter = 3 AND year = 2022 AND owner_gender = 'Female';
What are the top 5 source IPs that generated the most failed login attempts in the last month?
CREATE TABLE ip_failures (ip text,attempts integer,timestamp timestamp); INSERT INTO ip_failures (ip,attempts,timestamp) VALUES ('192.168.0.1',10,'2022-01-01 10:00:00'),('192.168.0.2',20,'2022-01-02 11:00:00'),('8.8.8.8',30,'2022-01-03 12:00:00'),('192.168.0.3',40,'2022-01-04 13:00:00'),('192.168.0.4',50,'2022-01-05 14:00:00'),('192.168.0.5',60,'2022-01-06 15:00:00');
SELECT ip, SUM(attempts) as total_attempts FROM ip_failures WHERE timestamp >= DATEADD(month, -1, CURRENT_TIMESTAMP) GROUP BY ip ORDER BY total_attempts DESC LIMIT 5;
Display the average launch year in the satellite_database table
CREATE TABLE satellite_database (id INT,name VARCHAR(50),type VARCHAR(50),orbit_type VARCHAR(50),country VARCHAR(50),launch_date DATE);
SELECT AVG(YEAR(launch_date)) as average_launch_year FROM satellite_database;
What is the average depth and temperature of sensors in the Pacific Ocean?
CREATE TABLE sensors (id INT,type VARCHAR(255),location VARCHAR(255),depth FLOAT,temperature FLOAT,pressure FLOAT,last_updated DATE); CREATE TABLE ocean_regions (id INT,region VARCHAR(255));
SELECT AVG(s.depth), AVG(s.temperature) FROM sensors s INNER JOIN ocean_regions o ON s.location = o.region WHERE o.region = 'Pacific Ocean';
What is the total biomass (in tons) of fish species in the fish_biomass_data table not included in the protected_species table?
CREATE TABLE fish_biomass_data (species VARCHAR(50),biomass INT); INSERT INTO fish_biomass_data (species,biomass) VALUES ('Tilapia',500),('Salmon',750),('Catfish',600); CREATE TABLE protected_species (species VARCHAR(50)); INSERT INTO protected_species (species) VALUES ('Shark'),('Tuna'),('Dolphin');
SELECT SUM(fb.biomass) as total_biomass FROM fish_biomass_data fb WHERE fb.species NOT IN (SELECT ps.species FROM protected_species ps);
How many players are there in total, and how many of them play VR games?
CREATE TABLE Players (PlayerID INT,Age INT,Gender VARCHAR(10),VRGamePlayer BOOLEAN); INSERT INTO Players (PlayerID,Age,Gender,VRGamePlayer) VALUES (1,25,'Male',true),(2,30,'Female',false),(3,22,'Male',true);
SELECT COUNT(*), SUM(VRGamePlayer) FROM Players;
What is the total number of media ethics violations in the US and Canada?
CREATE TABLE violations (id INT,country VARCHAR(50),violation_type VARCHAR(50),date DATE); INSERT INTO violations (id,country,violation_type,date) VALUES (1,'USA','Plagiarism','2022-01-01'); INSERT INTO violations (id,country,violation_type,date) VALUES (2,'Canada','Libel','2022-01-02');
SELECT country, COUNT(*) FROM violations WHERE (country = 'USA' OR country = 'Canada') GROUP BY country;
How many military bases are located in 'Asia'?
CREATE TABLE MilitaryBases (id INT,name VARCHAR(100),location VARCHAR(100)); INSERT INTO MilitaryBases (id,name,location) VALUES (1,'Base1','North America'); INSERT INTO MilitaryBases (id,name,location) VALUES (2,'Base2','Asia');
SELECT COUNT(*) FROM MilitaryBases WHERE location = 'Asia';
Add new analysis record for artifact 321
CREATE TABLE artifact_analysis (id INT PRIMARY KEY,artifact_id INT,analysis_type VARCHAR(50),result TEXT);
INSERT INTO artifact_analysis (id, artifact_id, analysis_type, result) VALUES (1, 321, 'Radiocarbon dating', '2500 BC ± 50 years');
What is the minimum oxygen level in farms with a stocking density above 50 for any fish species?
CREATE TABLE Farm (FarmID int,FarmName varchar(50),OxygenLevel numeric); INSERT INTO Farm (FarmID,FarmName,OxygenLevel) VALUES (1,'Farm A',7); INSERT INTO Farm (FarmID,FarmName,OxygenLevel) VALUES (2,'Farm B',6); CREATE TABLE FishStock (FishStockID int,FishSpecies varchar(50),FarmID int,StockingDensity numeric); INSERT INTO FishStock (FishStockID,FishSpecies,FarmID,StockingDensity) VALUES (1,'Tilapia',1,25); INSERT INTO FishStock (FishStockID,FishSpecies,FarmID,StockingDensity) VALUES (2,'Tilapia',2,30); INSERT INTO FishStock (FishStockID,FishSpecies,FarmID,StockingDensity) VALUES (3,'Salmon',1,55);
SELECT MIN(OxygenLevel) FROM Farm WHERE FarmID IN (SELECT FarmID FROM FishStock WHERE StockingDensity > 50 GROUP BY FarmID HAVING COUNT(DISTINCT FishSpecies) > 1);
Delete all orders made by a customer from India.
CREATE TABLE customers (customer_id INT PRIMARY KEY,name VARCHAR(255),email VARCHAR(255),country VARCHAR(255)); CREATE TABLE orders (order_id INT PRIMARY KEY,product_id INT,customer_id INT,FOREIGN KEY (product_id) REFERENCES products(product_id),FOREIGN KEY (customer_id) REFERENCES customers(customer_id)); INSERT INTO customers (customer_id,name,email,country) VALUES (1,'Archana','[email protected]','India'),(2,'Maria','[email protected]','Brazil'),(3,'Jessica','[email protected]','USA'); INSERT INTO orders (order_id,product_id,customer_id) VALUES (1,1,1),(2,2,2),(3,3,3);
DELETE FROM orders WHERE customer_id IN (SELECT customer_id FROM customers WHERE country = 'India');
What is the total number of smart city devices in cities with a population greater than 500,000?
CREATE TABLE City (id INT,name VARCHAR(255),population INT,smart_city_devices INT); INSERT INTO City (id,name,population,smart_city_devices) VALUES (1,'Tokyo',9000000,500); INSERT INTO City (id,name,population,smart_city_devices) VALUES (2,'Berlin',3500000,300);
SELECT COUNT(smart_city_devices) FROM City WHERE population > 500000;
What is the total number of emergency incidents reported by neighborhood in the city of Los Angeles?
CREATE TABLE emergency_incidents (id INT,neighborhood VARCHAR(255),incident_type VARCHAR(255),reported_date DATE);
SELECT neighborhood, COUNT(*) as total_incidents FROM emergency_incidents GROUP BY neighborhood;
How many players have played the game 'Puzzle Pioneers' and achieved a score between 500 and 1500?
CREATE TABLE Puzzle_Pioneers (player_id INT,player_name VARCHAR(50),score INT); INSERT INTO Puzzle_Pioneers (player_id,player_name,score) VALUES (1,'Alex Brown',700),(2,'Bella Johnson',1600),(3,'Charlie Lee',400);
SELECT COUNT(DISTINCT player_id) FROM Puzzle_Pioneers WHERE score BETWEEN 500 AND 1500;
Calculate the average research grant amount for each college in the Colleges table.
CREATE TABLE Colleges (CollegeID INT,CollegeName VARCHAR(50),AverageGrantAmount DECIMAL(10,2));
SELECT CollegeName, AVG(rg.Amount) AS AvgGrantAmount FROM Colleges c JOIN ResearchGrants rg ON c.CollegeID = rg.CollegeID GROUP BY CollegeName;
What is the average salary of workers per manufacturing site, ranked by the highest average salary?
CREATE TABLE sites (site_id INT,site_name VARCHAR(50),country VARCHAR(50),worker_count INT);CREATE TABLE worker_salaries (worker_id INT,site_id INT,salary DECIMAL(10,2));
SELECT site_name, AVG(salary) as avg_salary FROM worker_salaries ws JOIN sites s ON ws.site_id = s.site_id GROUP BY site_id ORDER BY avg_salary DESC;
What is the total CO2 emission from Arctic research stations in 2021, grouped by country?
CREATE TABLE Co2Emissions (Station VARCHAR(255),Country VARCHAR(255),Date DATE,Emission FLOAT); INSERT INTO Co2Emissions (Station,Country,Date,Emission) VALUES ('StationA','Norway','2021-01-01',10.5),('StationB','Finland','2021-01-01',12.3);
SELECT Country, SUM(Emission) FROM Co2Emissions WHERE YEAR(Date) = 2021 GROUP BY Country;
How many fish escape incidents were reported in India in 2019?
CREATE TABLE indian_farms (id INT,name TEXT,country TEXT,latitude DECIMAL(9,6),longitude DECIMAL(9,6)); INSERT INTO indian_farms (id,name,country,latitude,longitude) VALUES (1,'Farm E','India',20.123456,78.123456),(2,'Farm F','India',21.123456,79.123456); CREATE TABLE escape_incidents_india (id INT,farm_id INT,year INT,escaped_fish INT); INSERT INTO escape_incidents_india (id,farm_id,year,escaped_fish) VALUES (1,1,2019,10),(2,1,2020,15),(3,2,2019,20),(4,2,2020,25);
SELECT COUNT(*) FROM escape_incidents_india WHERE farm_id IN (SELECT id FROM indian_farms WHERE country = 'India') AND year = 2019;
List all cybersecurity incidents in the 'MiddleEast' schema.
CREATE SCHEMA MiddleEast; CREATE TABLE CyberSecurityIncidents (id INT,name VARCHAR(255),description TEXT,date DATE); INSERT INTO CyberSecurityIncidents (id,name,description,date) VALUES (1,'Shamoon','A destructive malware attack targeted at Saudi Aramco in 2012.','2012-08-15'); INSERT INTO CyberSecurityIncidents (id,name,description,date) VALUES (2,'APT33','Iran-linked threat group involved in cyber espionage and sabotage activities.','2017-01-01');
SELECT * FROM MiddleEast.CyberSecurityIncidents;
What is the average annual income for financially capable individuals in North America?
CREATE TABLE financial_capability (id INT,individual_id INT,annual_income DECIMAL(10,2),financially_capable BOOLEAN,country VARCHAR(50));
SELECT AVG(annual_income) FROM financial_capability WHERE financially_capable = TRUE AND country LIKE 'North America%';
What were the total donations in Q4 2021 by city?
CREATE TABLE donations (id INT,donation_date DATE,city TEXT,amount DECIMAL(10,2)); INSERT INTO donations (id,donation_date,city,amount) VALUES (16,'2021-10-01','New York',100.00),(17,'2021-11-15','Los Angeles',250.50),(18,'2021-12-31','Chicago',150.25);
SELECT city, SUM(amount) FROM donations WHERE donation_date BETWEEN '2021-10-01' AND '2021-12-31' GROUP BY city;
What is the minimum age of sea ice in the Beaufort Sea in 2021?
CREATE TABLE sea_ice_age (sea VARCHAR(50),year INT,age INT);
SELECT MIN(age) FROM sea_ice_age WHERE sea = 'Beaufort Sea' AND year = 2021;
What is the total budget spent on policy advocacy efforts for students with speech and language impairments from 2017-2020?
CREATE TABLE PolicyAdvocacyBudget (ProgramID INT,ProgramName VARCHAR(50),Year INT,Budget DECIMAL(10,2),DisabilityType VARCHAR(50));
SELECT SUM(Budget) FROM PolicyAdvocacyBudget WHERE DisabilityType = 'speech and language impairment' AND Year BETWEEN 2017 AND 2020;
What was the maximum daily revenue for each restaurant in Q2 2023?
CREATE TABLE daily_revenue (restaurant_name TEXT,daily_revenue NUMERIC,date DATE); INSERT INTO daily_revenue (restaurant_name,daily_revenue,date) VALUES ('Farm-to-Table Fusion',1800,'2023-04-01'),('Farm-to-Table Fusion',2000,'2023-04-02'),('Local Harvest Café',1300,'2023-04-01'),('Local Harvest Café',1400,'2023-04-02');
SELECT restaurant_name, MAX(daily_revenue) as max_daily_revenue FROM daily_revenue WHERE date BETWEEN '2023-04-01' AND '2023-06-30' GROUP BY restaurant_name;
What is the most common genre played by players in the 'player_preferences' table?
CREATE TABLE player_preferences (player_id INT,genre VARCHAR(50)); INSERT INTO player_preferences (player_id,genre) VALUES (1,'FPS'),(2,'RPG'),(3,'FPS'),(4,'Simulation');
SELECT genre, COUNT(*) as play_count FROM player_preferences GROUP BY genre ORDER BY play_count DESC LIMIT 1;
Who are the top 3 countries with the most national security budget?
CREATE TABLE National_Security_Budget (Country VARCHAR(255),Budget INT); INSERT INTO National_Security_Budget (Country,Budget) VALUES ('USA',8000000000),('China',4000000000),('Russia',3000000000),('India',2500000000),('Germany',2000000000);
SELECT Country, Budget FROM National_Security_Budget ORDER BY Budget DESC LIMIT 3;
What is the total budget for disability accommodations in each state?
CREATE TABLE disability_accommodations_state (accom_id INT,accom_name TEXT,budget DECIMAL(10,2),state_id INT);CREATE TABLE states (state_id INT,state_name TEXT);
SELECT s.state_name, SUM(da.budget) AS total_budget FROM disability_accommodations_state da INNER JOIN states s ON da.state_id = s.state_id GROUP BY s.state_name;
What is the earliest and latest time a train has arrived at a station, for each station, in the last month?
CREATE TABLE train_trips (id INT,station_id INT,trip_time TIME); INSERT INTO train_trips (id,station_id,trip_time) VALUES (1,1,'08:00:00'),(2,2,'09:00:00'),(3,1,'17:00:00');
SELECT MIN(trip_time) as earliest_time, MAX(trip_time) as latest_time, station_id FROM train_trips WHERE trip_time >= DATEADD(day, -30, GETDATE()) GROUP BY station_id;
What is the total number of donations made by repeat donors in the San Francisco region in 2021?
CREATE TABLE Donors (DonorID INT,DonorName TEXT,Region TEXT,DonationCount INT); INSERT INTO Donors (DonorID,DonorName,Region,DonationCount) VALUES (1,'James Smith','San Francisco',2),(2,'Sophia Johnson','San Francisco',1);
SELECT SUM(DonationCount) FROM Donors WHERE Region = 'San Francisco' AND DonationCount > 1;
What was the total value of military equipment sales to South East Asia in Q1 2021?
CREATE TABLE military_sales (id INT,quarter INT,region VARCHAR(50),year INT,value FLOAT); INSERT INTO military_sales (id,quarter,region,year,value) VALUES (1,1,'South East Asia',2021,2000000);
SELECT SUM(value) FROM military_sales WHERE quarter = 1 AND region = 'South East Asia' AND year = 2021;
Find artists who have created more than 10 pieces of art in the last year.
CREATE TABLE artists (id INT,name TEXT,city TEXT,country TEXT);CREATE TABLE art_pieces (id INT,title TEXT,medium TEXT,artist_id INT,creation_date DATE);
SELECT a.name, COUNT(ap.id) as num_pieces FROM artists a JOIN art_pieces ap ON a.id = ap.artist_id WHERE ap.creation_date >= DATEADD(year, -1, GETDATE()) GROUP BY a.name HAVING COUNT(ap.id) > 10;
What is the total number of tourists who visited Japan and France in 2020?
CREATE TABLE tourism_stats (country VARCHAR(20),year INT,tourists INT); INSERT INTO tourism_stats (country,year,tourists) VALUES ('Japan',2020,12000),('Japan',2021,15000),('France',2020,18000),('France',2021,20000);
SELECT SUM(tourists) FROM tourism_stats WHERE country IN ('Japan', 'France') AND year = 2020;
Who is the most targeted user by phishing attacks in the last month?
CREATE TABLE phishing_attacks (id INT,user TEXT,timestamp TIMESTAMP); INSERT INTO phishing_attacks (id,user,timestamp) VALUES (1,'user1','2021-01-01 12:00:00'),(2,'user2','2021-01-15 14:30:00'),(3,'user1','2021-02-01 10:15:00'),(4,'user3','2021-02-04 11:20:00'),(5,'user2','2021-02-04 18:30:00');
SELECT user, COUNT(*) AS phishing_count FROM phishing_attacks WHERE timestamp >= NOW() - INTERVAL '1 month' GROUP BY user ORDER BY phishing_count DESC LIMIT 1;
What is the earliest case opening date for each attorney?
CREATE TABLE cases (case_id INT PRIMARY KEY,attorney_id INT,client_id INT,case_opened_date DATE);
SELECT attorney_id, MIN(case_opened_date) FROM cases GROUP BY attorney_id;
What is the average distance traveled by astrophysics research on Mars?
CREATE TABLE astrophysics_research (research_id INT,location VARCHAR(50),distance FLOAT); INSERT INTO astrophysics_research (research_id,location,distance) VALUES (1,'Mars',50.3),(2,'Venus',10.2),(3,'Mars',40.1),(4,'Jupiter',70.5),(5,'Mars',60.0);
SELECT AVG(distance) FROM astrophysics_research WHERE location = 'Mars';
List the programs and their respective budgets for 2022.
CREATE TABLE Programs (ProgramID INT,Name TEXT,Budget FLOAT); INSERT INTO Programs (ProgramID,Name,Budget) VALUES (1,'Education',15000.00),(2,'Health',20000.00);
SELECT Name, Budget FROM Programs WHERE YEAR(StartDate) = 2022;
Identify the lowest-rated sustainable makeup products with a recyclable package?
CREATE TABLE Makeup_Sustainability(Product VARCHAR(30),Rating DECIMAL(3,2),Package_Recyclable BOOLEAN); INSERT INTO Makeup_Sustainability(Product,Rating,Package_Recyclable) VALUES('Lipstick A',3.2,true),('Mascara B',4.1,true),('Eyeshadow C',2.9,true),('Blush D',3.8,false),('Eyeliner E',4.5,false),('Foundation F',3.6,true);
SELECT Product, Rating FROM Makeup_Sustainability WHERE Package_Recyclable = true ORDER BY Rating ASC LIMIT 2;
What is the number of public transportation projects, categorized by type, that were completed in Latin American countries since 2000?
CREATE TABLE Projects (ProjectID INT,Type VARCHAR(50),Country VARCHAR(50),Year INT,CompletionStatus VARCHAR(50));
SELECT Projects.Type, COUNT(*) AS ProjectCount FROM Projects WHERE Projects.Country IN ('Argentina', 'Bolivia', 'Brazil', 'Chile', 'Colombia', 'CostaRica', 'Cuba', 'DominicanRepublic', 'Ecuador', 'ElSalvador', 'Guatemala', 'Guyana', 'Haiti', 'Honduras', 'Mexico', 'Nicaragua', 'Panama', 'Paraguay', 'Peru', 'Suriname', 'Uruguay', 'Venezuela') AND Projects.Year >= 2000 AND Projects.CompletionStatus = 'Completed' GROUP BY Projects.Type;
What is the total budget allocated for public safety in the city of Houston, including all departments, for the fiscal year 2024?
CREATE TABLE city_budget (city VARCHAR(20),department VARCHAR(20),budget INT); INSERT INTO city_budget (city,department,budget) VALUES ('Houston','Police',7000000);
SELECT SUM(budget) FROM city_budget WHERE city = 'Houston' AND department LIKE '%Safety%' AND fiscal_year = 2024;
find total carbon sequestration by tree species
CREATE SCHEMA forestry; CREATE TABLE trees (id INT,species VARCHAR(50),carbon FLOAT); INSERT INTO trees (id,species,carbon) VALUES (1,'oak',4.2),(2,'pine',3.8),(3,'eucalyptus',5.0),(4,'oak',4.5),(5,'maple',3.5);
SELECT species, SUM(carbon) FROM forestry.trees GROUP BY species;
What is the total number of eco-friendly tours in New Zealand and South Africa?
CREATE TABLE eco_tours_nz_sa (id INT,country VARCHAR(20),tours INT); INSERT INTO eco_tours_nz_sa (id,country,tours) VALUES (1,'New Zealand',120),(2,'New Zealand',130),(3,'South Africa',140);
SELECT SUM(tours) FROM eco_tours_nz_sa WHERE country IN ('New Zealand', 'South Africa');
What is the total number of military equipment sales in the Asia-Pacific region for the year 2020?
CREATE TABLE military_sales (id INT,region VARCHAR(255),year INT,total_sales DECIMAL(10,2)); INSERT INTO military_sales (id,region,year,total_sales) VALUES (1,'Asia-Pacific',2020,500000.00),(2,'Europe',2020,600000.00);
SELECT SUM(total_sales) FROM military_sales WHERE region = 'Asia-Pacific' AND year = 2020;
What is the total investment in renewable energy projects in the US?
CREATE TABLE projects (id INT,country VARCHAR(50),sector VARCHAR(50),investment FLOAT); INSERT INTO projects (id,country,sector,investment) VALUES (1,'US','Renewable Energy',5000000);
SELECT SUM(investment) FROM projects WHERE country = 'US' AND sector = 'Renewable Energy';
What are the names of the military aircraft manufactured by companies located in France?
CREATE TABLE MilitaryAircraft (MilitaryAircraftID INT,AircraftName VARCHAR(50),ManufacturerID INT,Type VARCHAR(50));
SELECT AircraftName FROM MilitaryAircraft JOIN AircraftManufacturers ON MilitaryAircraft.ManufacturerID = AircraftManufacturers.ID WHERE Type = 'Military' AND Country = 'France';
List the top 3 cities with the highest total sales of edibles in Washington state.
CREATE TABLE edibles_sales (product VARCHAR(20),city VARCHAR(20),state VARCHAR(20),total_sales INT); INSERT INTO edibles_sales (product,city,state,total_sales) VALUES ('Gummies','Seattle','Washington',600); INSERT INTO edibles_sales (product,city,state,total_sales) VALUES ('Chocolates','Seattle','Washington',400); INSERT INTO edibles_sales (product,city,state,total_sales) VALUES ('Brownies','Seattle','Washington',300); INSERT INTO edibles_sales (product,city,state,total_sales) VALUES ('Cookies','Spokane','Washington',500); INSERT INTO edibles_sales (product,city,state,total_sales) VALUES ('Capsules','Spokane','Washington',400);
SELECT city, SUM(total_sales) AS total_sales FROM edibles_sales WHERE state = 'Washington' AND product IN ('Gummies', 'Chocolates', 'Brownies', 'Cookies', 'Capsules') GROUP BY city ORDER BY total_sales DESC LIMIT 3;
What is the percentage of female-identifying artists in our organization?
CREATE TABLE artists (id INT,gender VARCHAR(50)); INSERT INTO artists (id,gender) VALUES (1,'Female'),(2,'Male'),(3,'Non-binary'),(4,'Female');
SELECT (COUNT(*) FILTER (WHERE gender = 'Female')) * 100.0 / COUNT(*) FROM artists;
What is the average room revenue per night for 'Hotel Carlton'?
CREATE TABLE room_revenue (hotel_id INT,revenue_per_night INT,night DATE); INSERT INTO room_revenue (hotel_id,revenue_per_night,night) VALUES (4,250,'2022-02-01'),(4,300,'2022-02-02'),(4,200,'2022-02-03'); CREATE TABLE hotels (hotel_id INT,name VARCHAR(50)); INSERT INTO hotels (hotel_id,name) VALUES (4,'Hotel Carlton');
SELECT AVG(revenue_per_night) FROM room_revenue JOIN hotels ON room_revenue.hotel_id = hotels.hotel_id WHERE hotels.name = 'Hotel Carlton';
What is the distribution of spacecraft manufacturing costs by year?
CREATE TABLE SpacecraftManufacturing (id INT,year INT,cost FLOAT);
SELECT year, AVG(cost) as avg_cost, STDDEV(cost) as stddev_cost FROM SpacecraftManufacturing GROUP BY year;
What is the maximum distance covered by each member in the past week, grouped by age?
CREATE TABLE member_age_data(id INT,age INT,last_workout_date DATE); INSERT INTO member_age_data(id,age,last_workout_date) VALUES (1,30,'2022-01-14'),(2,40,'2022-02-15'),(3,25,'2022-02-16'),(4,50,'2022-02-17'),(5,35,'2022-02-18'),(6,45,'2022-02-19'),(7,28,'2022-02-20'),(8,55,'2022-02-21'),(9,32,'2022-02-22'),(10,22,'2022-02-23'),(11,29,'2022-02-24'),(12,52,'2022-02-25'); CREATE TABLE workout_distance(member_id INT,distance INT,workout_date DATE); INSERT INTO workout_distance(member_id,distance,workout_date) VALUES (1,5,'2022-01-14'),(2,7,'2022-02-15'),(3,6,'2022-02-16'),(4,8,'2022-02-17'),(5,9,'2022-02-18'),(6,10,'2022-02-19'),(7,11,'2022-02-20'),(8,12,'2022-02-21'),(9,13,'2022-02-22'),(10,14,'2022-02-23'),(11,15,'2022-02-24'),(12,16,'2022-02-25');
SELECT age, MAX(distance) FROM (SELECT member_id, age, distance FROM member_age_data JOIN workout_distance ON member_age_data.id = workout_distance.member_id WHERE workout_distance.workout_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 WEEK) GROUP BY member_id, age) subquery GROUP BY age;
List all carbon offset programs in the United States and Canada
CREATE TABLE carbon_offset (country TEXT,program TEXT); INSERT INTO carbon_offset (country,program) VALUES ('United States','Program A'),('United States','Program B'),('Canada','Program C'),('Canada','Program D');
SELECT program FROM carbon_offset WHERE country IN ('United States', 'Canada');
List the top 3 countries with the highest increase in corn yield between 2019 and 2021?
CREATE TABLE CornYield (country TEXT,year INTEGER,corn_yield INTEGER); INSERT INTO CornYield (country,year,corn_yield) VALUES ('Mexico',2019,80),('Mexico',2021,95),('Brazil',2019,120),('Brazil',2021,145),('India',2019,100),('India',2021,130);
SELECT country, (LAG(corn_yield, 1, 0) OVER (PARTITION BY country ORDER BY year) - corn_yield) AS yield_difference FROM CornYield WHERE year = 2021 ORDER BY yield_difference DESC LIMIT 3;
List the virtual tours in Japan with more than 1000 reviews.
CREATE TABLE virtual_tours (tour_id INT,name TEXT,country TEXT,review_count INT); INSERT INTO virtual_tours VALUES (1,'Virtual Tokyo Tour','Japan',1200),(2,'Japanese Garden Tour','Japan',800);
SELECT name, review_count FROM virtual_tours WHERE country = 'Japan' AND review_count > 1000;
Find suppliers who have not delivered products in the last 6 months.
CREATE TABLE suppliers(id INT,name TEXT,location TEXT);CREATE TABLE products(id INT,supplier_id INT,product_name TEXT,delivery_date DATE);INSERT INTO suppliers(id,name,location) VALUES (1,'Supplier C','City C'),(2,'Supplier D','City D'),(3,'Supplier E','City E'); INSERT INTO products(id,supplier_id,product_name,delivery_date) VALUES (1,1,'Product 4','2021-07-15'),(2,1,'Product 5','2021-06-01'),(3,2,'Product 6','2021-08-05'),(4,3,'Product 7','2021-02-20');
SELECT s.* FROM suppliers s LEFT JOIN products p ON s.id = p.supplier_id WHERE p.delivery_date < DATE_SUB(CURRENT_DATE, INTERVAL 6 MONTH) OR p.delivery_date IS NULL;
Which funding sources supported the Music in the Park events in 2020?
CREATE TABLE Events (id INT PRIMARY KEY,name VARCHAR(20),year INT,funding_source VARCHAR(30)); INSERT INTO Events (id,name,year,funding_source) VALUES (1,'Music in the Park',2020,'Government Grant'); INSERT INTO Events (id,name,year,funding_source) VALUES (2,'Art Exhibition',2019,'Private Donation');
SELECT funding_source FROM Events WHERE name = 'Music in the Park' AND year = 2020;
How many diabetes screening tests were conducted in Mumbai, India in 2019?
CREATE TABLE DiabetesScreening (ID INT,Test INT,Location VARCHAR(50),Year INT); INSERT INTO DiabetesScreening (ID,Test,Location,Year) VALUES (1,500,'Mumbai',2019); INSERT INTO DiabetesScreening (ID,Test,Location,Year) VALUES (2,300,'Mumbai',2019);
SELECT SUM(Test) FROM DiabetesScreening WHERE Location = 'Mumbai' AND Year = 2019;
What is the average number of international tourists in the first quarter of each year?
CREATE TABLE tourism_stats (country VARCHAR(50),visitors INT,year INT,quarter INT); INSERT INTO tourism_stats (country,visitors,year,quarter) VALUES ('Spain',15,2020,1),('Germany',18,2020,1),('Spain',16,2021,1),('Germany',19,2021,1);
SELECT AVG(visitors) as avg_visitors FROM tourism_stats WHERE quarter = 1;
List the names of games that are played by more than 5000 players and their respective number of players.
CREATE TABLE GameLibrary (GameID INT,PlayerID INT); INSERT INTO GameLibrary (GameID,PlayerID) VALUES (1,1),(1,2),(1,3),(1,4),(1,5),(2,1),(2,2),(2,6),(2,7),(2,8),(3,2),(3,3),(3,4),(3,8),(3,9),(4,1),(4,5),(4,6),(4,9),(5,1),(5,2),(5,3),(5,4),(5,5),(5,6),(5,7),(5,8),(5,9);
SELECT GameDesign.GameTitle, COUNT(GameLibrary.PlayerID) AS Players FROM GameLibrary INNER JOIN GameDesign ON GameLibrary.GameID = GameDesign.GameID GROUP BY GameLibrary.GameID HAVING Players > 5000;
What is the year-over-year growth in network infrastructure investment for the region of Quebec, Canada?
CREATE TABLE network_investments (investment_id INT,investment_amount FLOAT,region VARCHAR(20),investment_date DATE);
SELECT (SUM(CASE WHEN YEAR(investment_date) = YEAR(CURRENT_DATE) - 1 THEN investment_amount ELSE 0 END) - SUM(CASE WHEN YEAR(investment_date) = YEAR(CURRENT_DATE) - 2 THEN investment_amount ELSE 0 END)) * 100.0 / SUM(CASE WHEN YEAR(investment_date) = YEAR(CURRENT_DATE) - 2 THEN investment_amount ELSE 0 END) as yoy_growth FROM network_investments WHERE region = 'Quebec' AND YEAR(investment_date) >= YEAR(CURRENT_DATE) - 2;
What is the average price of vegetables in the 'farmers_market' table that are in season?
CREATE TABLE farmers_market (id INT,type VARCHAR(10),name VARCHAR(20),price DECIMAL(5,2),is_in_season BOOLEAN);
SELECT AVG(price) FROM farmers_market WHERE type = 'vegetable' AND is_in_season = TRUE;
Find the total number of investigative articles published in 'articles' table, grouped by the region in 'regions' table.
CREATE TABLE articles (article_id INT,author_id INT,title VARCHAR(100),pub_date DATE,article_type VARCHAR(50)); CREATE TABLE regions (region_id INT,region_name VARCHAR(50));
SELECT regions.region_name, COUNT(articles.article_id) FROM articles INNER JOIN regions ON articles.region_id = regions.region_id WHERE articles.article_type = 'Investigative' GROUP BY regions.region_name;
What is the minimum revenue per OTA booking in the APAC region in 2021?
CREATE TABLE ota_bookings_3 (booking_id INT,ota_name TEXT,region TEXT,booking_amount DECIMAL(10,2)); INSERT INTO ota_bookings_3 (booking_id,ota_name,region,booking_amount) VALUES (1,'Booking.com','APAC',200.50),(2,'Expedia','APAC',150.25),(3,'Agoda','APAC',300.00),(4,'Expedia','APAC',50.00);
SELECT MIN(booking_amount) FROM ota_bookings_3 WHERE region = 'APAC' AND YEAR(booking_date) = 2021;
How many fans attended the games in each city?
CREATE TABLE teams (team_id INT,team_name VARCHAR(50),city VARCHAR(50));CREATE TABLE games (game_id INT,team_id INT,city VARCHAR(50),attendees INT); INSERT INTO teams (team_id,team_name,city) VALUES (1,'Atlanta Hawks','Atlanta'),(2,'Boston Celtics','Boston'); INSERT INTO games (game_id,team_id,city,attendees) VALUES (1,1,'Atlanta',15000),(2,1,'Atlanta',16000),(3,2,'Boston',18000);
SELECT city, SUM(attendees) FROM games GROUP BY city;
What is the total quantity of sativa strains sold in the month of June 2021 across all dispensaries?
CREATE TABLE DispensarySales (dispensary_id INT,strain_type TEXT,quantity_sold INT,sale_date DATE);
SELECT SUM(quantity_sold) FROM DispensarySales WHERE strain_type = 'sativa' AND sale_date >= '2021-06-01' AND sale_date <= '2021-06-30';
List all traditional art pieces in the Middle East that have been donated by individuals, along with their donation value and donor information.
CREATE TABLE Donors(DonorID INT,DonorName VARCHAR(100),DonationType VARCHAR(50),DonationValue DECIMAL(10,2),Region VARCHAR(50)); CREATE TABLE ArtPieces(ArtPieceID INT,ArtPieceName VARCHAR(100),DonorID INT);
SELECT Donors.DonorName, ArtPieces.ArtPieceName, Donors.DonationValue FROM Donors INNER JOIN ArtPieces ON Donors.DonorID = ArtPieces.DonorID WHERE Donors.DonationType = 'Individual' AND Donors.Region = 'Middle East';
What's the regulatory status of decentralized applications in the USA?
CREATE TABLE decentralized_applications (id INT,name VARCHAR(255),country VARCHAR(255),regulatory_status VARCHAR(255)); INSERT INTO decentralized_applications (id,name,country,regulatory_status) VALUES (1,'App 1','USA','Approved'),(2,'App 2','USA','Under Review'),(3,'App 3','Canada','Approved');
SELECT regulatory_status FROM decentralized_applications WHERE country = 'USA';
What is the total investment in renewable energy by country in 2022?
CREATE TABLE investments (investment_id INT,investor_name VARCHAR(255),investment_amount INT,investment_year INT,sector VARCHAR(255),country VARCHAR(255)); INSERT INTO investments (investment_id,investor_name,investment_amount,investment_year,sector,country) VALUES (1,'Green Impact Fund',100000,2022,'Renewable Energy','USA'),(2,'Sustainable Capital',150000,2022,'Renewable Energy','Canada'),(3,'Eco Invest',75000,2022,'Renewable Energy','Mexico');
SELECT country, SUM(investment_amount) as total_investment FROM investments WHERE investment_year = 2022 AND sector = 'Renewable Energy' GROUP BY country;
What is the average age of players who use VR technology, and how many distinct game titles do they play?
CREATE TABLE Players (PlayerID INT,Age INT,VRUser CHAR(1)); INSERT INTO Players (PlayerID,Age,VRUser) VALUES (1,25,'Y'),(2,30,'N'),(3,22,'Y'),(4,35,'N'); CREATE TABLE GameLibrary (GameID INT,PlayerID INT); INSERT INTO GameLibrary (GameID,PlayerID) VALUES (1,1),(2,1),(3,2),(4,3),(5,3),(1,4); CREATE TABLE GameDesign (GameID INT,Title VARCHAR(20)); INSERT INTO GameDesign (GameID,Title) VALUES (1,'RacingGame'),(2,'RPG'),(3,'Shooter'),(4,'Puzzle'),(5,'Strategy'); CREATE TABLE VRGame (GameID INT,VRGame CHAR(1)); INSERT INTO VRGame (GameID) VALUES (1),(3);
SELECT AVG(Players.Age), COUNT(DISTINCT GameDesign.Title) FROM Players INNER JOIN GameLibrary ON Players.PlayerID = GameLibrary.PlayerID INNER JOIN GameDesign ON GameLibrary.GameID = GameDesign.GameID INNER JOIN VRGame ON GameDesign.GameID = VRGame.GameID WHERE Players.VRUser = 'Y';
Which climate mitigation projects have the same funding amount as the project with the highest funding in South America?
CREATE TABLE climate_mitigation_projects (id INT,name VARCHAR(255),location VARCHAR(255),funding FLOAT); INSERT INTO climate_mitigation_projects (id,name,location,funding) VALUES (1,'Project F','South America',8000000); INSERT INTO climate_mitigation_projects (id,name,location,funding) VALUES (2,'Project G','South America',5000000);
SELECT * FROM climate_mitigation_projects WHERE funding = (SELECT MAX(funding) FROM climate_mitigation_projects WHERE location = 'South America');
Identify the top 3 countries with the highest number of factories adhering to fair labor practices.
CREATE TABLE Country (id INT,name VARCHAR(255),factories INT); INSERT INTO Country (id,name,factories) VALUES (1,'USA',50),(2,'China',80),(3,'India',30);
SELECT name, factories FROM Country ORDER BY factories DESC LIMIT 3;
What is the total revenue for heritage hotel rooms?
CREATE TABLE hotel_rooms (room_id INT,room_type VARCHAR(20),price DECIMAL(5,2),is_heritage BOOLEAN); INSERT INTO hotel_rooms (room_id,room_type,price,is_heritage) VALUES (1,'Standard',100,FALSE),(2,'Deluxe',150,FALSE),(3,'Heritage Standard',120,TRUE),(4,'Heritage Deluxe',180,TRUE);
SELECT SUM(price) FROM hotel_rooms WHERE is_heritage = TRUE;
What is the average funding received by biotech startups in Australia?
CREATE SCHEMA if not exists biotech;CREATE TABLE if not exists biotech.startups (id INT PRIMARY KEY,name VARCHAR(100),country VARCHAR(50),funding FLOAT);INSERT INTO biotech.startups (id,name,country,funding) VALUES (1,'StartupA','Australia',3000000.0),(2,'StartupB','Australia',1500000.0),(3,'StartupC','Canada',800000.0);
SELECT AVG(funding) FROM biotech.startups WHERE country = 'Australia';
Which stations had more than 200 entries and exits in the last week, and the difference between entries and exits?
CREATE TABLE stations (station_id INT,station_name VARCHAR(20)); CREATE TABLE entries (entry_id INT,station_id INT,entry_date DATE); CREATE TABLE exits (exit_id INT,station_id INT,exit_date DATE);
SELECT s.station_name, e.entry_date, e.entry_count, x.exit_count, e.entry_count - x.exit_count as difference FROM (SELECT station_id, COUNT(*) as entry_count FROM entries WHERE entry_date BETWEEN CURRENT_DATE - INTERVAL '7 days' AND CURRENT_DATE GROUP BY station_id HAVING COUNT(*) > 200) e JOIN (SELECT station_id, COUNT(*) as exit_count FROM exits WHERE exit_date BETWEEN CURRENT_DATE - INTERVAL '7 days' AND CURRENT_DATE GROUP BY station_id HAVING COUNT(*) > 200) x ON e.station_id = x.station_id JOIN stations s ON e.station_id = s.station_id;
Which marine protected areas have ocean acidification monitoring stations?
CREATE TABLE marine_protected_areas (name varchar(255),acidification_station boolean); INSERT INTO marine_protected_areas (name,acidification_station) VALUES ('Galapagos Marine Reserve',true),('Great Barrier Reef',false),('Palau National Marine Sanctuary',true);
SELECT name FROM marine_protected_areas WHERE acidification_station = true;
What is the total number of successful and failed aid deliveries for each organization?
CREATE TABLE aid_deliveries (delivery_id INT,organization VARCHAR(50),delivery_status VARCHAR(10)); INSERT INTO aid_deliveries (delivery_id,organization,delivery_status) VALUES (1,'Org A','successful'),(2,'Org B','failed'),(3,'Org A','successful'),(4,'Org C','successful'),(5,'Org B','failed'),(6,'Org A','successful'); CREATE TABLE organizations (org_id INT,name VARCHAR(50)); INSERT INTO organizations (org_id,name) VALUES (1,'Org A'),(2,'Org B'),(3,'Org C');
SELECT o.name, SUM(CASE WHEN ad.delivery_status = 'successful' THEN 1 ELSE 0 END) AS num_successful, SUM(CASE WHEN ad.delivery_status = 'failed' THEN 1 ELSE 0 END) AS num_failed FROM aid_deliveries ad JOIN organizations o ON ad.organization = o.name GROUP BY o.name
What is the average age of attendees for each program type, and what is the total funding received by each program type, grouped by program type?
CREATE TABLE programs (program_id INT,program_name VARCHAR(50),program_type VARCHAR(20)); CREATE TABLE attendee_demographics (attendee_id INT,age INT,program_id INT); CREATE TABLE funding (funding_id INT,program_id INT,funding_amount DECIMAL(10,2)); INSERT INTO programs (program_id,program_name,program_type) VALUES (1,'Art Education','Education'),(2,'Music Education','Education'),(3,'Theater Performance','Performance'); INSERT INTO attendee_demographics (attendee_id,age,program_id) VALUES (1,25,1),(2,35,2),(3,45,3); INSERT INTO funding (funding_id,program_id,funding_amount) VALUES (1,1,5000),(2,2,3000),(3,3,8000);
SELECT program_type, AVG(ad.age) AS avg_age, SUM(f.funding_amount) AS total_funding FROM programs p INNER JOIN attendee_demographics ad ON p.program_id = ad.program_id INNER JOIN funding f ON p.program_id = f.program_id GROUP BY program_type;
Find the number of vessels in the "Vessels" table
CREATE TABLE Vessels (Id INT PRIMARY KEY,Name VARCHAR(100),Type VARCHAR(50),Year INT); INSERT INTO Vessels (Id,Name,Type,Year) VALUES (1,'Manta Ray','Research Vessel',2015),(2,'Ocean Explorer','Exploration Vessel',2018),(3,'Marine Life','Conservation Vessel',2012);
SELECT COUNT(*) FROM Vessels;
What are the most common types of cybersecurity incidents in the technology sector in the past month and their total number of occurrences?
CREATE TABLE sector_incidents (id INT,incident_type VARCHAR(255),sector VARCHAR(255),incident_date DATE,affected_assets INT); INSERT INTO sector_incidents (id,incident_type,sector,incident_date,affected_assets) VALUES (1,'Phishing','Technology','2022-03-15',25);
SELECT incident_type, SUM(affected_assets) as total_occurrences FROM sector_incidents WHERE sector = 'Technology' AND incident_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH) GROUP BY incident_type ORDER BY total_occurrences DESC;
What is the average age of archaeologists from Asian countries?
CREATE TABLE Archaeologists (ArchaeologistID INT,Name TEXT,Age INT,Country TEXT); INSERT INTO Archaeologists (ArchaeologistID,Name,Age,Country) VALUES (1,'Ali',35,'Egypt'); INSERT INTO Archaeologists (ArchaeologistID,Name,Age,Country) VALUES (2,'Jiang',42,'China'); INSERT INTO Archaeologists (ArchaeologistID,Name,Age,Country) VALUES (3,'Sophia',31,'Greece'); INSERT INTO Archaeologists (ArchaeologistID,Name,Age,Country) VALUES (4,'Hana',45,'Japan');
SELECT AVG(Age) AS AvgAge FROM Archaeologists WHERE Country IN ('China', 'India', 'Japan', 'Indonesia', 'Malaysia');
Who are the astronauts with the most spacewalks for each space agency?
CREATE TABLE Astronauts (id INT,name VARCHAR(255),gender VARCHAR(10),agency VARCHAR(255),spacewalks INT); INSERT INTO Astronauts (id,name,gender,agency,spacewalks) VALUES (1,'Anousheh Ansari','Female','Private',0),(2,'Peggy Whitson','Female','NASA',10),(3,'Robert Curbeam','Male','NASA',7);
SELECT agency, name, spacewalks, RANK() OVER (PARTITION BY agency ORDER BY spacewalks DESC) as spacewalk_rank FROM Astronauts WHERE spacewalks > 0;
How many clinics in California offer the Moderna vaccine?
CREATE TABLE clinic_vaccines (clinic_id INT,vaccine_name VARCHAR(255),state VARCHAR(255)); CREATE TABLE clinics (clinic_id INT,clinic_name VARCHAR(255)); INSERT INTO clinic_vaccines (clinic_id,vaccine_name,state) VALUES (1,'Moderna','California'); INSERT INTO clinics (clinic_id,clinic_name) VALUES (1,'Clinic A');
SELECT COUNT(*) FROM clinic_vaccines v INNER JOIN clinics c ON v.clinic_id = c.clinic_id WHERE v.vaccine_name = 'Moderna' AND v.state = 'California';
Count the number of unsuccessful spacecraft launches
CREATE TABLE launches (id INT,launch_status VARCHAR(50),launch_date DATE);
SELECT COUNT(*) FROM launches WHERE launch_status = 'Unsuccessful';
How many employees work in each store?
CREATE TABLE stores (store_id INT,store_name VARCHAR(255)); CREATE TABLE employees (employee_id INT,name VARCHAR(255),store_id INT,salary DECIMAL(5,2)); INSERT INTO stores (store_id,store_name) VALUES (1,'Store A'),(2,'Store B'),(3,'Store C'); INSERT INTO employees (employee_id,name,store_id,salary) VALUES (1,'John Doe',1,50000.00),(2,'Jane Smith',1,45000.00),(3,'Maria Garcia',2,40000.00);
SELECT s.store_name, COUNT(e.employee_id) as employee_count FROM stores s JOIN employees e ON s.store_id = e.store_id GROUP BY s.store_name;
What is the total amount of research grants awarded to the Physics department in the years 2019 and 2020?
CREATE TABLE grant (id INT,department VARCHAR(50),amount INT,grant_date DATE); INSERT INTO grant (id,department,amount,grant_date) VALUES (1,'Physics',50000,'2019-12-31'),(2,'Physics',75000,'2020-04-15'),(3,'Mechanical Engineering',60000,'2019-12-31');
SELECT SUM(amount) FROM grant WHERE department = 'Physics' AND (YEAR(grant_date) = 2019 OR YEAR(grant_date) = 2020);
Find the number of clinical trials conducted in each region and the percentage of successful trials in 2020.
CREATE TABLE clinical_trials (region VARCHAR(50),trial_status VARCHAR(50),year INT); INSERT INTO clinical_trials (region,trial_status,year) VALUES ('North America','Success',2020),('Europe','Success',2020),('Asia','Failed',2020),('South America','Success',2020),('Africa','Failed',2020),('Australia','Success',2020);
SELECT region, COUNT(*) as total_trials, (COUNT(*) FILTER (WHERE trial_status = 'Success')) * 100.0 / COUNT(*) as success_percentage FROM clinical_trials WHERE year = 2020 GROUP BY region;
What is the average fuel consumption per day for all tanker ships?
CREATE TABLE tanker_ships (id INT,name TEXT,fuel_capacity INT); CREATE TABLE fuel_consumption (id INT,ship_id INT,date DATE,consumption INT); INSERT INTO tanker_ships (id,name,fuel_capacity) VALUES (1,'MV Titan',500000),(2,'MV Olympic',600000); INSERT INTO fuel_consumption (id,ship_id,date,consumption) VALUES (1,1,'2023-01-01',10000),(2,1,'2023-01-02',11000),(3,2,'2023-01-01',12000),(4,2,'2023-01-02',13000);
SELECT AVG(fc.consumption / DATEDIFF(fc.date, fc.date - INTERVAL 1 DAY)) AS avg_fuel_consumption FROM fuel_consumption fc JOIN tanker_ships ts ON fc.ship_id = ts.id;
Calculate the total revenue for the Midwest region.
CREATE TABLE sales (id INT,location VARCHAR(20),quantity INT,price DECIMAL(5,2)); INSERT INTO sales (id,location,quantity,price) VALUES (1,'Northeast',50,12.99),(2,'Midwest',75,19.99),(3,'West',35,14.49);
SELECT SUM(quantity * price) FROM sales WHERE location = 'Midwest';
What is the average number of points scored by Stephen Curry in the NBA regular season?
CREATE TABLE nba_points (player_name VARCHAR(50),team VARCHAR(50),season YEAR,points INT); INSERT INTO nba_points (player_name,team,season,points) VALUES ('Stephen Curry','Golden State Warriors',2022,31);
SELECT AVG(points) FROM nba_points WHERE player_name = 'Stephen Curry';
What is the mental health score of the student with the highest ID?
CREATE TABLE students (student_id INT,mental_health_score INT); INSERT INTO students (student_id,mental_health_score) VALUES (1,80),(2,60),(3,90),(4,70),(5,50);
SELECT mental_health_score FROM students WHERE student_id = (SELECT MAX(student_id) FROM students);
Delete all maritime law violations that occurred in the Southern Hemisphere more than 3 years ago.
CREATE TABLE maritime_law_violations (id INT,violation VARCHAR(50),location VARCHAR(50),date DATE);
DELETE FROM maritime_law_violations WHERE location LIKE 'Southern Hemisphere%' AND date < NOW() - INTERVAL 3 YEAR;
What is the total biomass of fish in Tanks with a depth greater than 3 meters?
CREATE TABLE Tanks (tank_id INT,tank_depth FLOAT,fish_species VARCHAR(20),biomass FLOAT); INSERT INTO Tanks (tank_id,tank_depth,fish_species,biomass) VALUES (1,2.5,'Salmon',12.5),(2,4.2,'Trout',10.8),(3,3.1,'Tilapia',8.7);
SELECT SUM(biomass) as total_biomass FROM Tanks WHERE tank_depth > 3.0;
Update records in landfill_capacity where country is 'India' and year is 2024
CREATE TABLE landfill_capacity (id INT,country VARCHAR(20),year INT,capacity INT);
WITH data_to_update AS (UPDATE landfill_capacity SET capacity = capacity * 1.03 WHERE country = 'India' AND year = 2024 RETURNING *) UPDATE landfill_capacity SET capacity = (SELECT capacity FROM data_to_update) WHERE id IN (SELECT id FROM data_to_update);
What is the distribution of accidents by aircraft model for each airline?
CREATE TABLE AircraftAccidentsByModel (id INT,airline VARCHAR(50),airline_type VARCHAR(50),accident_year INT); INSERT INTO AircraftAccidentsByModel (id,airline,airline_type,accident_year) VALUES (1,'Delta','737',2015),(2,'Delta','757',2017),(3,'United','747',2013),(4,'United','777',2018),(5,'Southwest','737',2016),(6,'Southwest','738',2019);
SELECT airline, airline_type, accident_year, COUNT(*) as total_accidents FROM AircraftAccidentsByModel GROUP BY airline, airline_type, accident_year ORDER BY airline, airline_type, accident_year;
How many marine farms are located in the Pacific Ocean, using data from the marine_farms table?
CREATE TABLE marine_farms (farm_id INT,farm_name VARCHAR(255),location VARCHAR(255)); INSERT INTO marine_farms (farm_id,farm_name,location) VALUES (1,'Pacific Aquaculture','Pacific Ocean'),(2,'Atlantic Aquaculture','Atlantic Ocean'),(3,'Mediterranean Aquaculture','Mediterranean Sea');
SELECT COUNT(*) FROM marine_farms WHERE location = 'Pacific Ocean';
What is the total data usage for each state in the mobile_subscribers table?
CREATE TABLE mobile_subscribers (subscriber_id INT,data_usage FLOAT,state VARCHAR(20)); INSERT INTO mobile_subscribers (subscriber_id,data_usage,state) VALUES (1,3.5,'California'),(2,4.2,'Texas'),(3,2.8,'California'),(4,5.1,'Florida');
SELECT state, SUM(data_usage) FROM mobile_subscribers GROUP BY state;