instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
What is the total number of mobile and broadband subscribers for each technology type?
CREATE TABLE mobile_subscribers (subscriber_id INT,technology VARCHAR(20)); CREATE TABLE broadband_subscribers (subscriber_id INT,technology VARCHAR(20)); INSERT INTO mobile_subscribers (subscriber_id,technology) VALUES (1,'4G'),(2,'5G'),(3,'3G'); INSERT INTO broadband_subscribers (subscriber_id,technology) VALUES (4,'Fiber'),(5,'Cable'),(6,'DSL');
SELECT 'Mobile' as source, technology, COUNT(*) as total FROM mobile_subscribers GROUP BY technology UNION ALL SELECT 'Broadband' as source, technology, COUNT(*) as total FROM broadband_subscribers GROUP BY technology;
List the total number of workouts and unique members who participated in Pilates classes, broken down by age group (18-24, 25-34, 35-44, 45-54, 55+).
CREATE TABLE workouts (id INT,member_id INT,workout_type VARCHAR(20),workout_date DATE,member_age INT);
SELECT CASE WHEN member_age BETWEEN 18 AND 24 THEN '18-24' WHEN member_age BETWEEN 25 AND 34 THEN '25-34' WHEN member_age BETWEEN 35 AND 44 THEN '35-44' WHEN member_age BETWEEN 45 AND 54 THEN '45-54' ELSE '55+' END as age_group, COUNT(DISTINCT member_id) as total_members, COUNT(*) as total_workouts FROM workouts WHERE workout_type = 'Pilates' GROUP BY age_group;
List all suppliers from 'EcoVillage' who do not provide vegan ingredients.
CREATE TABLE Suppliers (supplier_id INT,supplier_name VARCHAR(50),location VARCHAR(50),vegan BOOLEAN); INSERT INTO Suppliers (supplier_id,supplier_name,location,vegan) VALUES (1,'Farm Fresh','EcoVillage',false),(2,'GreenGrocer','EcoVillage',true),(3,'Harvest House','EcoVillage',false);
SELECT supplier_name FROM Suppliers WHERE location = 'EcoVillage' AND vegan = false
What is the average lifespan for each country in the European Union?
CREATE TABLE lifespan (country TEXT,lifespan INT); INSERT INTO lifespan (country,lifespan) VALUES ('France',82),('Germany',81),('Italy',83);
SELECT country, AVG(lifespan) AS avg_lifespan FROM lifespan GROUP BY country;
What is the total number of cultural competency trainings conducted in each quarter?
CREATE TABLE trainings (training_id INT,quarter INT,training_type VARCHAR(50),trainings_conducted INT); INSERT INTO trainings (training_id,quarter,training_type,trainings_conducted) VALUES (1,1,'Cultural Competency',10),(2,2,'Cultural Competency',15),(3,3,'Cultural Competency',12),(4,4,'Cultural Competency',8),(5,1,'Health Equity',7),(6,2,'Health Equity',9),(7,3,'Health Equity',11),(8,4,'Health Equity',14);
SELECT training_type, quarter, SUM(trainings_conducted) as total_trainings_conducted FROM trainings GROUP BY training_type, quarter;
List all space missions that were successful in 2020.
CREATE TABLE SpaceMissions (mission_id INT,year INT,success BOOLEAN); INSERT INTO SpaceMissions (mission_id,year,success) VALUES (1,2020,true),(2,2020,false),(3,2019,true),(4,2021,true),(5,2018,false),(6,2020,true);
SELECT mission_id FROM SpaceMissions WHERE year = 2020 AND success = true;
What is the total revenue for classical concerts?
CREATE TABLE concerts (id INT,type VARCHAR(10),price DECIMAL(5,2),tickets_sold INT); INSERT INTO concerts (id,type,price,tickets_sold) VALUES (1,'classical',50.00,100),(2,'pop',30.00,200),(3,'classical',60.00,150);
SELECT SUM(price * tickets_sold) FROM concerts WHERE type = 'classical';
How many policies were issued per month in 'Miami' for the year 2022?
CREATE TABLE Policyholders (PolicyholderID INT,City VARCHAR(20),IssueDate DATE); INSERT INTO Policyholders (PolicyholderID,City,IssueDate) VALUES (1,'Miami','2022-01-15'),(2,'Miami','2022-02-20'),(3,'Miami','2022-03-25');
SELECT DATE_FORMAT(IssueDate, '%Y-%m') AS Month, COUNT(*) as NumberOfPolicies FROM Policyholders WHERE City = 'Miami' AND YEAR(IssueDate) = 2022 GROUP BY Month;
What is the average number of employees in the 'agricultural_farms' table per region?
CREATE TABLE agricultural_farms (id INT,name VARCHAR(30),num_employees INT,region VARCHAR(20));
SELECT region, AVG(num_employees) FROM agricultural_farms GROUP BY region;
How many dams in total were constructed in Canada and the USA before 1970?
CREATE TABLE dams (id INT,name TEXT,country TEXT,build_year INT); INSERT INTO dams (id,name,country,build_year) VALUES (1,'CN-AB Hydro Dam','CA',1965); INSERT INTO dams (id,name,country,build_year) VALUES (2,'US-OR Columbia River Dam','US',1968);
SELECT COUNT(*) FROM dams WHERE (country = 'CA' OR country = 'US') AND build_year < 1970;
Find the average age of employees in each department.
CREATE TABLE Employees (EmployeeID INT,Department VARCHAR(20),Age INT); INSERT INTO Employees (EmployeeID,Department,Age) VALUES (1,'IT',30),(2,'IT',35),(3,'HR',40),(4,'Sales',45),(5,'Sales',50);
SELECT Department, AVG(Age) FROM Employees GROUP BY Department;
What are the names and discovery dates of exoplanets discovered by the Kepler mission?
CREATE TABLE exoplanets (exoplanet_id INT,exoplanet_name VARCHAR(100),mission_name VARCHAR(100),discovery_date DATE);
SELECT exoplanet_name, discovery_date FROM exoplanets WHERE mission_name = 'Kepler';
What is the average ticket price for each sport in the 'ticket_sales' table?
CREATE TABLE ticket_sales (id INT PRIMARY KEY,event_id INT,sport VARCHAR(50),tickets_sold INT,price DECIMAL(5,2)); CREATE TABLE events (id INT PRIMARY KEY,name VARCHAR(100),date DATE,location VARCHAR(100));
SELECT t.sport, AVG(t.price) as avg_price FROM ticket_sales t JOIN events e ON t.event_id = e.id GROUP BY t.sport;
What is the average area of fields?
CREATE TABLE fields (id INT,field_name VARCHAR(255),area FLOAT,soil_type VARCHAR(255)); INSERT INTO fields (id,field_name,area,soil_type) VALUES (1,'field1',10.5,'loamy'),(2,'field2',12.3,'sandy'),(3,'field3',8.9,'loamy');
SELECT AVG(area) FROM fields;
Count the number of cases in the 'Civil Litigation' category
CREATE TABLE cases (case_id INT,category VARCHAR(50),billing_amount INT); INSERT INTO cases (case_id,category,billing_amount) VALUES (1,'Personal Injury',5000),(2,'Civil Litigation',7000);
SELECT COUNT(*) FROM cases WHERE category = 'Civil Litigation';
What is the average speed of all vessels in the 'vessel_performance' table?
CREATE TABLE vessel_performance (vessel_id INT,speed FLOAT,timestamp TIMESTAMP);
SELECT AVG(speed) FROM vessel_performance;
Calculate the average age difference between athletes in basketball and football.
CREATE TABLE athletes(athlete_id INT,name VARCHAR(50),age INT,sport VARCHAR(20));
SELECT AVG(basketball_age - football_age) AS avg_age_difference FROM (SELECT AVG(age) AS basketball_age FROM athletes WHERE sport = 'basketball') AS basketball, (SELECT AVG(age) AS football_age FROM athletes WHERE sport = 'football') AS football;
Insert new emergency calls in 'Seattle' for October 2021
CREATE TABLE emergency_calls(id INT,location VARCHAR(20),month_year DATE,emergency_type VARCHAR(20));
INSERT INTO emergency_calls(id, location, month_year, emergency_type) VALUES (1, 'Seattle', '2021-10-01', 'medical'), (2, 'Seattle', '2021-10-02', 'fire'), (3, 'Seattle', '2021-10-03', 'police');
Circular economy initiatives in South Africa since 2017.
CREATE TABLE circular_economy (country VARCHAR(50),year INT,initiative VARCHAR(100)); INSERT INTO circular_economy (country,year,initiative) VALUES ('South Africa',2017,'Waste-to-Energy Project'),('South Africa',2018,'Recycling Plant Expansion'),('South Africa',2019,'Composting Program'),('South Africa',2020,'Product Reuse Program'),('South Africa',2021,'Sustainable Packaging Initiative');
SELECT * FROM circular_economy WHERE country = 'South Africa' ORDER BY year;
What is the total number of tickets sold for each day of the week?
CREATE TABLE ticket_sales (sale_date DATE,quantity INT,price DECIMAL(10,2));
SELECT DATE_FORMAT(sale_date, '%W') as day_of_week, SUM(quantity * price) as total_revenue FROM ticket_sales GROUP BY day_of_week;
How many traditional art events have been added in each country in the past two years?
CREATE TABLE TraditionalArtEvents (ID INT,Art VARCHAR(50),Country VARCHAR(50),YearAdded INT,Events INT); INSERT INTO TraditionalArtEvents (ID,Art,Country,YearAdded,Events) VALUES (1,'Kathak','India',2021,20); INSERT INTO TraditionalArtEvents (ID,Art,Country,YearAdded,Events) VALUES (2,'Hula','Hawaii',2022,15);
SELECT Country, YearAdded, COUNT(*) OVER (PARTITION BY Country, YearAdded - YearAdded % 2 ORDER BY YearAdded) AS EventsAddedInPeriod FROM TraditionalArtEvents;
List the top 10 most productive faculty members in terms of number of publications in the last 3 years, along with their respective departments.
CREATE TABLE faculty (faculty_id INT,name VARCHAR(50),department VARCHAR(50)); CREATE TABLE publications (publication_id INT,faculty_id INT,pub_date DATE);
SELECT f.name, f.department, COUNT(p.publication_id) AS num_publications FROM faculty f INNER JOIN publications p ON f.faculty_id = p.faculty_id WHERE p.pub_date BETWEEN DATE_SUB(NOW(), INTERVAL 3 YEAR) AND NOW() GROUP BY f.faculty_id, f.name, f.department ORDER BY num_publications DESC LIMIT 10;
What's the total number of players who play adventure games in Europe?
CREATE TABLE Players (PlayerID INT,Age INT,Gender VARCHAR(10),Location VARCHAR(20)); INSERT INTO Players (PlayerID,Age,Gender,Location) VALUES (1,22,'Female','France'); INSERT INTO Players (PlayerID,Age,Gender,Location) VALUES (2,35,'Male','Germany'); CREATE TABLE Games (GameID INT,GameName VARCHAR(20),Genre VARCHAR(20)); INSERT INTO Games (GameID,GameName,Genre) VALUES (1,'Mystery Explorer','Adventure');
SELECT COUNT(*) FROM Players INNER JOIN (SELECT DISTINCT PlayerID FROM Games WHERE Genre = 'Adventure') AS AdventurePlayers ON Players.PlayerID = AdventurePlayers.PlayerID WHERE Players.Location = 'Europe';
What is the average monthly data usage for each mobile plan in the European region, for the first quarter of 2022?
CREATE TABLE mobile_plans (plan_id INT,plan_name VARCHAR(50),monthly_cost DECIMAL(5,2)); CREATE TABLE subscribers (subscriber_id INT,plan_id INT,region VARCHAR(50)); CREATE TABLE sales (sale_id INT,subscriber_id INT,sale_date DATE,data_usage DECIMAL(5,2));
SELECT m.plan_name, AVG(s.data_usage) AS avg_data_usage FROM mobile_plans m JOIN subscribers s ON m.plan_id = s.plan_id JOIN sales ON s.subscriber_id = sales.subscriber_id WHERE s.region = 'Europe' AND QUARTER(sale_date) = 1 GROUP BY m.plan_name;
What is the total mass of operational Mars rovers and landers?
CREATE SCHEMA space; USE space; CREATE TABLE rover (name VARCHAR(50),type VARCHAR(50),mass FLOAT); INSERT INTO rover (name,type,mass) VALUES ('Curiosity','Rover',899000),('Perseverance','Rover',1025000),('Spirit','Rover',185000),('Opportunity','Rover',174000),('Viking 1','Lander',576000),('Viking 2','Lander',576000);
SELECT SUM(mass) FROM space.rover WHERE type = 'Rover' AND name IN ('Curiosity', 'Perseverance', 'Spirit', 'Opportunity') OR type = 'Lander' AND name IN ('Viking 1', 'Viking 2');
Show the total revenue for each mobile plan type
CREATE TABLE mobile_plans (plan_type VARCHAR(10),monthly_rate INT,additional_fees INT);
SELECT plan_type, (monthly_rate + additional_fees) AS total_revenue FROM mobile_plans;
What is the ranking of hotel types by average rating, for hotels in the 'south_america_hotels' view?
CREATE VIEW south_america_hotels AS SELECT * FROM hotels WHERE continent = 'South America'; CREATE VIEW hotel_ratings AS SELECT hotel_id,AVG(rating) as avg_rating FROM hotel_reviews GROUP BY hotel_id;
SELECT type, ROW_NUMBER() OVER (ORDER BY avg_rating DESC) as ranking FROM south_america_hotels JOIN hotel_ratings ON south_america_hotels.id = hotel_ratings.hotel_id GROUP BY type;
How many trees were planted in South America for climate change mitigation?
CREATE TABLE TreesPlanted (Id INT,Location VARCHAR(50),Purpose VARCHAR(50),NumberPlanted INT);
SELECT SUM(NumberPlanted) FROM TreesPlanted WHERE Purpose = 'climate change mitigation' AND Location = 'South America';
List all countries, their total production, and the number of active wells in each country, for countries with at least one active well in 2022.
CREATE TABLE countries (country_id INT,country_name TEXT); CREATE TABLE wells (well_id INT,country_id INT,well_name TEXT,production_qty INT,start_date DATE,end_date DATE); INSERT INTO countries (country_id,country_name) VALUES (1,'Country A'),(2,'Country B'); INSERT INTO wells (well_id,country_id,well_name,production_qty,start_date,end_date) VALUES (1,1,'Well A',500,'2020-01-01','2022-02-28'),(2,1,'Well B',700,'2021-01-01','2023-01-01'),(3,2,'Well C',300,'2022-01-01','2024-01-01');
SELECT c.country_name, SUM(w.production_qty) AS total_production, COUNT(w.well_id) AS active_wells FROM countries c INNER JOIN wells w ON c.country_id = w.country_id WHERE w.start_date <= '2022-01-01' AND w.end_date >= '2022-01-01' GROUP BY c.country_name;
What is the average safety rating for luxury vehicles in the luxuryvehicles schema?
CREATE TABLE LuxuryVehicles (id INT,make VARCHAR(50),model VARCHAR(50),safetyrating INT); CREATE TABLE Vehicles (id INT,make VARCHAR(50),model VARCHAR(50),PRIMARY KEY (id)); CREATE TABLE Luxury (id INT,vehicle_id INT,PRIMARY KEY (id),FOREIGN KEY (vehicle_id) REFERENCES Vehicles(id));
SELECT AVG(safetyrating) FROM luxuryvehicles JOIN Luxury ON luxuryvehicles.id = Luxury.vehicle_id;
What is the number of cases handled by attorneys with the last name 'Williams'?
CREATE TABLE attorneys (id INT,first_name VARCHAR,last_name VARCHAR,department VARCHAR); CREATE TABLE cases (id INT,attorney_id INT,outcome VARCHAR); INSERT INTO attorneys (id,first_name,last_name,department) VALUES (1,'Maria','Garcia','Civil'),(2,'Juan','Williams','Criminal'),(3,'Carlos','Rodriguez','Family'),(4,'Laura','Williams','Immigration'); INSERT INTO cases (id,attorney_id,outcome) VALUES (1,1,'Favorable'),(2,2,'Unfavorable'),(3,3,'Favorable'),(4,4,'Favorable');
SELECT COUNT(*) FROM attorneys a JOIN cases c ON a.id = c.attorney_id WHERE a.last_name = 'Williams';
Show the number of employees hired in each location, ordered by the number of hires.
CREATE TABLE Employees (EmployeeID INT,HireDate DATE,Location VARCHAR(50)); INSERT INTO Employees (EmployeeID,HireDate,Location) VALUES (1,'2018-01-01','NYC'),(2,'2020-03-15','LA'),(3,'2019-08-25','NYC'),(4,'2019-11-04','NYC'),(5,'2020-02-16','LA');
SELECT Location, COUNT(*) FROM Employees GROUP BY Location ORDER BY COUNT(*) DESC;
List the top 5 threat actors with the highest number of successful attacks in the last quarter, partitioned by their attack type.
CREATE TABLE threat_actors (threat_actor_id INT,attack_type VARCHAR(20),success_count INT,last_updated DATETIME); INSERT INTO threat_actors (threat_actor_id,attack_type,success_count,last_updated) VALUES (1,'Malware',10,'2022-01-01'),(2,'Phishing',15,'2022-01-05'),(3,'SQL Injection',20,'2022-01-03'),(4,'Cross-Site Scripting',12,'2022-01-04'),(5,'Malware',18,'2022-01-02');
SELECT attack_type, threat_actor_id, success_count FROM (SELECT attack_type, threat_actor_id, success_count, ROW_NUMBER() OVER (PARTITION BY attack_type ORDER BY success_count DESC) rn FROM threat_actors WHERE last_updated >= DATEADD(quarter, -1, GETDATE())) t WHERE rn <= 5;
What is the average price per MWh for solar energy in India?
CREATE TABLE energy_prices (country VARCHAR(50),technology VARCHAR(50),year INT,price_per_mwh FLOAT); INSERT INTO energy_prices (country,technology,year,price_per_mwh) VALUES ('India','Solar',2018,50),('India','Solar',2019,55),('India','Solar',2020,60),('India','Solar',2021,65);
SELECT AVG(price_per_mwh) FROM energy_prices WHERE country = 'India' AND technology = 'Solar';
What is the number of students who have accessed mental health resources in each country?
CREATE TABLE student_mental_health_resources (student_id INT,country VARCHAR(20),resource_id VARCHAR(5)); INSERT INTO student_mental_health_resources (student_id,country,resource_id) VALUES (1,'Canada','R101'),(2,'USA','R201'),(3,'Canada','R102'),(4,'Mexico','R301'),(5,'USA','R202'),(6,'Canada','R103'),(7,'Mexico','R302');
SELECT country, COUNT(*) FROM student_mental_health_resources GROUP BY country;
Delete records of subscribers with speed below 50Mbps in California.
CREATE TABLE broadband_subscribers (subscriber_id INT,speed FLOAT,state VARCHAR(255)); INSERT INTO broadband_subscribers (subscriber_id,speed,state) VALUES (1,150,'California'),(2,200,'California'),(3,40,'California'),(4,120,'California');
DELETE FROM broadband_subscribers WHERE speed < 50 AND state = 'California';
Add a new record to the 'solar_panels' table with id 1001, manufacturer 'SunPower', installed_year 2015, and capacity 350
CREATE TABLE solar_panels (id INT PRIMARY KEY,manufacturer VARCHAR(50),installed_year INT,capacity FLOAT);
INSERT INTO solar_panels (id, manufacturer, installed_year, capacity) VALUES (1001, 'SunPower', 2015, 350);
Which students have enrolled in online courses?
CREATE TABLE students (id INT,name VARCHAR(255)); CREATE TABLE courses (id INT,name VARCHAR(255),is_online BOOLEAN); CREATE TABLE enrollments (id INT,student_id INT,course_id INT); INSERT INTO students (id,name) VALUES (1,'Student A'),(2,'Student B'),(3,'Student C'); INSERT INTO courses (id,name,is_online) VALUES (1,'Open Pedagogy 101',TRUE),(2,'Math',FALSE),(3,'Science',FALSE); INSERT INTO enrollments (id,student_id,course_id) VALUES (1,1,1),(2,2,1),(3,3,1),(4,1,2),(5,2,3);
SELECT s.name AS student_name FROM students s JOIN enrollments e ON s.id = e.student_id JOIN courses c ON e.course_id = c.id WHERE c.is_online = TRUE;
Find the investment strategies with a risk level lower than the average risk level.
CREATE TABLE investment_strategies (id INT,strategy VARCHAR(50),risk_level INT); INSERT INTO investment_strategies (id,strategy,risk_level) VALUES (1,'Impact Bonds',30),(2,'Green Equity Funds',20),(3,'Sustainable Real Estate',40);
SELECT strategy, risk_level FROM investment_strategies WHERE risk_level < (SELECT AVG(risk_level) FROM investment_strategies);
Which museums had the highest and lowest attendance in 2021?
CREATE TABLE museums (id INT,name VARCHAR(255),location VARCHAR(255),attendance INT); INSERT INTO museums (id,name,location,attendance) VALUES (1,'Museum1','CityA',10000),(2,'Museum2','CityB',15000),(3,'Museum3','CityC',5000);
SELECT name, attendance FROM museums WHERE YEAR(location) = 2021 ORDER BY attendance LIMIT 1; SELECT name, attendance FROM museums WHERE YEAR(location) = 2021 ORDER BY attendance DESC LIMIT 1;
How many electric vehicles were sold in the European Union in 2021?
CREATE TABLE Vehicle_Sales (Sale_ID INT,Vehicle_ID INT,Country VARCHAR(50),Year INT,Quantity INT); INSERT INTO Vehicle_Sales (Sale_ID,Vehicle_ID,Country,Year,Quantity) VALUES (1,1,'Germany',2021,500),(2,2,'France',2021,300),(3,3,'Italy',2020,400),(4,4,'Spain',2021,600),(5,5,'United Kingdom',2021,700),(6,1,'Germany',2020,400);
SELECT SUM(Quantity) FROM Vehicle_Sales WHERE Year = 2021 AND Vehicle_ID IN (SELECT Vehicle_ID FROM Vehicles WHERE Electric = TRUE) AND Country LIKE '%European Union%';
What is the total number of players who play VR games and their average hours played, grouped by country?
CREATE TABLE players (id INT,age INT,country VARCHAR(255),hours_played DECIMAL(5,2)); INSERT INTO players (id,age,country,hours_played) VALUES (1,25,'India',10.5),(2,30,'USA',12.0),(3,35,'Mexico',8.5); CREATE TABLE games (id INT,name VARCHAR(255),category VARCHAR(255)); INSERT INTO games (id,name,category) VALUES (1,'GameA','VR'),(2,'GameB','Non-VR'),(3,'GameC','VR'); CREATE TABLE player_games (player_id INT,game_id INT,hours_played DECIMAL(5,2)); INSERT INTO player_games (player_id,game_id,hours_played) VALUES (1,1,10.5),(2,1,12.0),(3,1,8.5);
SELECT p.country, COUNT(p.id) as num_players, AVG(p.hours_played) as avg_hours_played FROM players p JOIN player_games pg ON p.id = pg.player_id JOIN games g ON pg.game_id = g.id WHERE g.category = 'VR' GROUP BY p.country;
Identify the mental health condition with the highest improvement rate for patients in Oceania, along with the associated treatment approach.
CREATE TABLE improvements (id INT,condition TEXT,approach TEXT,region TEXT,improvement FLOAT); INSERT INTO improvements (id,condition,approach,region,improvement) VALUES (1,'Depression','CBT','Oceania',0.8),(2,'Anxiety','DBT','Oceania',0.7),(3,'PTSD','EMDR','Oceania',0.9),(4,'Depression','Medication','Oceania',0.6);
SELECT condition, approach, MAX(improvement) as max_improvement FROM improvements WHERE region = 'Oceania' GROUP BY condition, approach;
What is the conservation status of the species with the lowest oxygen minimum zone value?
CREATE TABLE marine_species (id INT PRIMARY KEY,name VARCHAR(255),conservation_status VARCHAR(255)); INSERT INTO marine_species (id,name,conservation_status) VALUES (1,'Leatherback Sea Turtle','Vulnerable'); CREATE TABLE oceanography (id INT PRIMARY KEY,species_id INT,oxygen_minimum_zone INT); INSERT INTO oceanography (id,species_id,oxygen_minimum_zone) VALUES (1,1,200);
SELECT m.name, m.conservation_status FROM marine_species m JOIN (SELECT species_id, MIN(oxygen_minimum_zone) AS min_zone FROM oceanography GROUP BY species_id) o ON m.id = o.species_id WHERE o.min_zone = 200;
Get the 'id' of models that use 'algorithmA'.
CREATE TABLE model_algorithm (id INT,model_name TEXT,algorithm TEXT); INSERT INTO model_algorithm (id,model_name,algorithm) VALUES (1,'modelA','algorithmA'),(2,'modelB','algorithmB');
SELECT id FROM model_algorithm WHERE algorithm = 'algorithmA';
Who are the top 3 music artists with the highest number of streams in Brazil?
CREATE TABLE music_streams (artist_name VARCHAR(255),country VARCHAR(50),streams INT); INSERT INTO music_streams (artist_name,country,streams) VALUES ('Artist4','Brazil',1000000),('Artist5','Brazil',1200000),('Artist6','Brazil',900000);
SELECT artist_name, SUM(streams) as total_streams FROM music_streams WHERE country = 'Brazil' GROUP BY artist_name ORDER BY total_streams DESC LIMIT 3;
Which climate mitigation project has the highest allocation?
CREATE TABLE climate_mitigation_projects (project_id INTEGER,project_name TEXT,allocation INTEGER); INSERT INTO climate_mitigation_projects (project_id,project_name,allocation) VALUES (1,'Carbon Capture',8000000);
SELECT project_name, allocation FROM climate_mitigation_projects ORDER BY allocation DESC LIMIT 1;
How many times has each wildlife species been observed in mangrove forests since 2015?
CREATE TABLE mangrove_wildlife (id INT,species VARCHAR(50),year INT,region VARCHAR(20));
SELECT species, region, COUNT(*) as total_observations FROM mangrove_wildlife WHERE region = 'Mangrove' AND year >= 2015 GROUP BY species, region;
What is the biomass of seafood species at risk in the Black Sea?
CREATE TABLE seafoodspecies (species VARCHAR(30),biomass FLOAT,location VARCHAR(20)); INSERT INTO seafoodspecies (species,biomass,location) VALUES ('Tuna',12000,'Black Sea'),('Mackerel',15000,'Black Sea');
SELECT biomass FROM seafoodspecies WHERE species IN ('Tuna', 'Mackerel') AND location = 'Black Sea';
Find the percentage of global Dysprosium production in 2020 from the 'supply_chain' table.
CREATE TABLE supply_chain (country VARCHAR(50),element VARCHAR(10),year INT,production INT); INSERT INTO supply_chain (country,element,year,production) VALUES ('China','Dysprosium',2020,2000),('Malaysia','Dysprosium',2020,1500),('Australia','Dysprosium',2020,1000),('India','Dysprosium',2020,500),('Russia','Dysprosium',2020,1200),('USA','Dysprosium',2020,1800);
SELECT 100.0 * SUM(production) / (SELECT SUM(production) FROM supply_chain WHERE element = 'Dysprosium' AND year = 2020) as percentage FROM supply_chain WHERE element = 'Dysprosium' AND year = 2020;
How many workout sessions did each member have in January 2023?
CREATE TABLE members (member_id INT,name VARCHAR(50),gender VARCHAR(10),dob DATE); INSERT INTO members (member_id,name,gender,dob) VALUES (1,'Jamie Park','Non-binary','2005-07-23'); INSERT INTO members (member_id,name,gender,dob) VALUES (2,'Kai Chen','Male','1999-10-11'); CREATE TABLE workout_sessions (session_id INT,member_id INT,session_date DATE); INSERT INTO workout_sessions (session_id,member_id,session_date) VALUES (1,1,'2023-01-02'); INSERT INTO workout_sessions (session_id,member_id,session_date) VALUES (2,1,'2023-01-10'); INSERT INTO workout_sessions (session_id,member_id,session_date) VALUES (3,2,'2023-01-15'); INSERT INTO workout_sessions (session_id,member_id,session_date) VALUES (4,1,'2023-01-25');
SELECT member_id, COUNT(*) AS sessions_in_jan_2023 FROM workout_sessions WHERE MONTH(session_date) = 1 AND YEAR(session_date) = 2023 GROUP BY member_id;
What is the difference in scores between consecutive players in the 'RPG' game category, ordered by score?
CREATE TABLE RPGScores (PlayerID int,PlayerName varchar(50),Game varchar(50),Score int); INSERT INTO RPGScores (PlayerID,PlayerName,Game,Score) VALUES (1,'Player1','Game2',1000),(2,'Player2','Game2',1200),(3,'Player3','Game2',1400),(4,'Player4','Game2',1600);
SELECT Game, Score, LEAD(Score) OVER (PARTITION BY Game ORDER BY Score) as NextScore, LEAD(Score) OVER (PARTITION BY Game ORDER BY Score) - Score as ScoreDifference FROM RPGScores WHERE Game = 'Game2' ORDER BY Score;
How many students with hearing impairments have not utilized sign language interpreters in the past year?
CREATE TABLE students (id INT,name TEXT,disability TEXT,sign_language_interpreter BOOLEAN); INSERT INTO students (id,name,disability,sign_language_interpreter) VALUES (1,'John Doe','hearing impairment',true); INSERT INTO students (id,name,disability,sign_language_interpreter) VALUES (2,'Jane Smith','learning disability',false);
SELECT COUNT(*) FROM students WHERE disability = 'hearing impairment' AND sign_language_interpreter = false AND date >= DATE_SUB(NOW(), INTERVAL 1 YEAR);
What is the percentage of tourists who prefer sustainable modes of transport?
CREATE TABLE Tourists (country TEXT,transport TEXT); INSERT INTO Tourists (country,transport) VALUES ('Italy','Train'),('France','Plane'),('Spain','Bus'),('Greece','Car'),('Portugal','Train'),('Germany','Bike');
SELECT COUNT(CASE WHEN transport IN ('Train', 'Bike') THEN 1 ELSE NULL END) / COUNT(*) FROM Tourists;
What is the total revenue for each salesperson, ordered by total revenue in descending order?
CREATE TABLE salesperson (salesperson_id INT,name VARCHAR(50),revenue DECIMAL(10,2)); INSERT INTO salesperson VALUES (1,'John Doe',5000.00),(2,'Jane Smith',6000.00),(3,'Alice Johnson',7000.00);
SELECT name, SUM(revenue) as total_revenue FROM salesperson GROUP BY name ORDER BY total_revenue DESC;
What is the waste generation trend in 'waste_generation' table for the US?
CREATE TABLE waste_generation (country VARCHAR(50),year INT,population INT,waste_amount INT);
SELECT year, AVG(waste_amount) as avg_waste_amount FROM waste_generation WHERE country = 'US' GROUP BY year;
What is the average distance of autonomous taxi rides in Berlin?
CREATE TABLE taxi_rides (id INT,distance FLOAT,type VARCHAR(20),city VARCHAR(20)); INSERT INTO taxi_rides (id,distance,type,city) VALUES (1,5.3,'Autonomous','Berlin');
SELECT AVG(distance) FROM taxi_rides WHERE type = 'Autonomous' AND city = 'Berlin';
Update all records in the soil_moisture_irrigation_system table with a moisture level of 60 where system_id is 10 and moisture level is less than 60
CREATE TABLE soil_moisture_irrigation_system (system_id INT,moisture DECIMAL(3,1),system_timestamp DATETIME);
UPDATE soil_moisture_irrigation_system SET moisture = 60 WHERE system_id = 10 AND moisture < 60;
Which vessels had the most total cargo weight in February 2021?
CREATE TABLE vessels (id INT,name VARCHAR(255)); INSERT INTO vessels (id,name) VALUES (1,'Vessel_A'),(2,'Vessel_B'),(3,'Vessel_C'); CREATE TABLE cargo (vessel_id INT,weight INT,month VARCHAR(9)); INSERT INTO cargo (vessel_id,weight,month) VALUES (1,5000,'February 2021'),(1,4000,'February 2021'),(2,3000,'February 2021'),(3,6000,'February 2021'),(3,7000,'February 2021');
SELECT v.name, SUM(c.weight) as total_weight FROM cargo c JOIN vessels v ON c.vessel_id = v.id WHERE c.month = 'February 2021' GROUP BY v.name ORDER BY total_weight DESC;
What is the maximum number of mental health parity cases reported in a single day?
CREATE TABLE MentalHealthParity (Id INT,Region VARCHAR(20),ReportDate DATE); INSERT INTO MentalHealthParity (Id,Region,ReportDate) VALUES (1,'Southwest','2020-01-01'),(2,'Northeast','2019-12-31'),(3,'Southwest','2020-06-15'),(4,'Northeast','2020-01-10'),(5,'Southwest','2020-06-15');
SELECT ReportDate, COUNT(*) as CountOfCases FROM MentalHealthParity GROUP BY ReportDate ORDER BY CountOfCases DESC LIMIT 1;
What is the total number of Shariah-compliant and socially responsible loans issued in 2022?
CREATE TABLE loans (id INT,loan_type VARCHAR,date DATE); INSERT INTO loans (id,loan_type,date) VALUES (1,'Shariah-compliant','2022-01-05'),(2,'socially responsible','2022-02-07'),(3,'Shariah-compliant','2022-03-03'),(4,'socially responsible','2022-04-30');
SELECT COUNT(*) FROM loans WHERE EXTRACT(YEAR FROM date) = 2022 AND (loan_type = 'Shariah-compliant' OR loan_type = 'socially responsible');
What is the total number of mental health parity cases reported in the Northeast and Midwest regions?
CREATE TABLE mental_health_parity (region VARCHAR(20),case_count INT); INSERT INTO mental_health_parity (region,case_count) VALUES ('Northeast',200),('Southeast',150),('Midwest',180),('Southwest',250),('West',220);
SELECT SUM(case_count) FROM mental_health_parity WHERE region IN ('Northeast', 'Midwest');
Get the number of organic products sold in the USA
CREATE TABLE sales (id INT,product_id INT,country VARCHAR(255),quantity INT); CREATE TABLE products (id INT,name VARCHAR(255),is_organic BOOLEAN);
SELECT COUNT(*) FROM sales s INNER JOIN products p ON s.product_id = p.id WHERE p.is_organic = TRUE AND s.country = 'USA';
What is the name and birthplace of the artist with the most artwork in the 'Post-Impressionist' period?
CREATE TABLE Artworks (ArtworkID INT,ArtistID INT,Title VARCHAR(255),Period VARCHAR(255)); INSERT INTO Artworks VALUES (1,1,'The Starry Night','Post-Impressionist'); CREATE TABLE Artists (ArtistID INT,Name VARCHAR(255),Birthplace VARCHAR(255)); INSERT INTO Artists VALUES (1,'Vincent van Gogh','Netherlands');
SELECT Artists.Name, Artists.Birthplace FROM Artists INNER JOIN (SELECT ArtistID, COUNT(*) AS ArtworkCount FROM Artworks WHERE Period = 'Post-Impressionist' GROUP BY ArtistID) SubQuery ON Artists.ArtistID = SubQuery.ArtistID ORDER BY ArtworkCount DESC LIMIT 1;
Calculate the percentage of female faculty members per department, in descending order of percentage.
CREATE TABLE faculties (faculty_id INT,name VARCHAR(255),dept_id INT,gender VARCHAR(10));CREATE TABLE departments (dept_id INT,dept_name VARCHAR(255));
SELECT dept_name, COUNT(*) * 100.0 / (SELECT COUNT(*) FROM faculties WHERE dept_id = f.dept_id) AS percentage FROM faculties f JOIN departments d ON f.dept_id = d.dept_id WHERE gender = 'female' GROUP BY dept_name ORDER BY percentage DESC;
How many resources were depleted in each mining operation in the last quarter?
CREATE TABLE mining_operations (operation_id INT,operation_name VARCHAR(50),resource_type VARCHAR(50),depletion_date DATE,quantity INT); INSERT INTO mining_operations (operation_id,operation_name,resource_type,depletion_date,quantity) VALUES (1,'Operation A','Coal','2022-01-01',100),(2,'Operation B','Iron','2022-02-15',200),(3,'Operation C','Gold','2022-03-30',150);
SELECT operation_name, resource_type, SUM(quantity) AS total_depleted FROM mining_operations WHERE depletion_date >= DATE_SUB(CURDATE(), INTERVAL 3 MONTH) GROUP BY operation_name, resource_type;
What is the minimum balance for customers in the East region?
CREATE TABLE customers (id INT,name VARCHAR(50),region VARCHAR(50),balance DECIMAL(10,2)); INSERT INTO customers (id,name,region,balance) VALUES (1,'John Doe','East',5000.00),(2,'Jane Smith','East',7000.00),(3,'Alice Johnson','East',2000.00);
SELECT MIN(balance) FROM customers WHERE region = 'East';
Identify AI models with inconsistent safety and fairness scores.
CREATE TABLE ai_models (model_name TEXT,safety_score INTEGER,fairness_score INTEGER); INSERT INTO ai_models (model_name,safety_score,fairness_score) VALUES ('ModelX',85,90),('ModelY',70,75),('ModelZ',95,80);
SELECT model_name FROM ai_models WHERE safety_score < 80 AND fairness_score < 80;
Find the number of visitors who have visited the museum more than once in the last month.
CREATE TABLE Visitor_Log (Visitor_ID INT,Visit_Date DATE); INSERT INTO Visitor_Log (Visitor_ID,Visit_Date) VALUES (1001,'2022-01-01'),(1002,'2022-01-02'),(1003,'2022-01-03'),(1001,'2022-01-04');
SELECT COUNT(DISTINCT Visitor_ID) FROM Visitor_Log WHERE Visitor_ID IN (SELECT Visitor_ID FROM Visitor_Log GROUP BY Visitor_ID HAVING COUNT(DISTINCT Visit_Date) > 1) AND Visit_Date >= DATE_SUB(CURDATE(), INTERVAL 1 MONTH);
What is the average playtime for all players?
CREATE TABLE player_sessions (id INT,player_name TEXT,playtime INT); INSERT INTO player_sessions (id,player_name,playtime) VALUES (1,'Olivia',120); INSERT INTO player_sessions (id,player_name,playtime) VALUES (2,'Olivia',150); INSERT INTO player_sessions (id,player_name,playtime) VALUES (3,'William',200);
SELECT AVG(playtime) FROM player_sessions;
What is the maximum and minimum number of building permits issued per month in the last year?
CREATE TABLE Permits (PermitID int,Type varchar(20),Date date); INSERT INTO Permits (PermitID,Type,Date) VALUES (1,'Residential','2021-01-01'); INSERT INTO Permits (PermitID,Type,Date) VALUES (2,'Commercial','2021-01-10'); INSERT INTO Permits (PermitID,Type,Date) VALUES (3,'Residential','2021-02-15');
SELECT MIN(Count) AS MinCount, MAX(Count) AS MaxCount FROM (SELECT COUNT(*) AS Count FROM Permits WHERE Date >= DATE_SUB(CURDATE(), INTERVAL 1 YEAR) GROUP BY DATE_FORMAT(Date, '%Y-%m')) AS PermitCounts;
Delete the sales record for DrugA in 2019.
CREATE TABLE drug_sales (sale_id INT,drug_name VARCHAR(255),year INT,sales INT); INSERT INTO drug_sales (sale_id,drug_name,year,sales) VALUES (1,'DrugA',2018,5000000),(2,'DrugB',2019,7000000),(3,'DrugC',2020,8000000);
DELETE FROM drug_sales WHERE drug_name = 'DrugA' AND year = 2019;
Which team has the most fans?
CREATE TABLE fans (fan_id INT,team_id INT,gender VARCHAR(50)); INSERT INTO fans VALUES (1,1,'Female'),(2,1,'Male'),(3,2,'Female'),(4,2,'Female'),(5,3,'Male');
SELECT te.team_name, COUNT(f.fan_id) as num_fans FROM fans f JOIN teams te ON f.team_id = te.team_id GROUP BY te.team_id ORDER BY num_fans DESC LIMIT 1;
List the usernames and number of posts for users who have posted more than 50 times on a specific hashtag (#Travel)
CREATE TABLE users (user_id INT,username VARCHAR(50)); CREATE TABLE posts (post_id INT,user_id INT,hashtags VARCHAR(50)); INSERT INTO users (user_id,username) VALUES (1,'user1'),(2,'user2'),(3,'user3'); INSERT INTO posts (post_id,user_id,hashtags) VALUES (1,1,'#Travel'),(2,1,'#Food'),(3,2,'#Travel'),(4,3,'#Travel'),(5,3,'#Music');
SELECT users.username, COUNT(posts.post_id) AS post_count FROM users INNER JOIN posts ON users.user_id = posts.user_id WHERE FIND_IN_SET('#Travel', posts.hashtags) > 0 GROUP BY users.username HAVING post_count > 50;
Find the ratio of R&D expenditures between 'AstraZeneca' and 'Novartis'.
CREATE TABLE rd_expenditures (company TEXT,year INT,amount FLOAT); INSERT INTO rd_expenditures (company,year,amount) VALUES ('AstraZeneca',2020,22000000),('Novartis',2020,16000000);
SELECT (SELECT SUM(amount) FROM rd_expenditures WHERE company = 'AstraZeneca' AND year = 2020) / (SELECT SUM(amount) FROM rd_expenditures WHERE company = 'Novartis' AND year = 2020);
What is the total amount of humanitarian assistance provided by each organization in 2020?
CREATE TABLE HumanitarianAssistance (Organization VARCHAR(50),Year INT,Amount DECIMAL(10,2)); INSERT INTO HumanitarianAssistance (Organization,Year,Amount) VALUES ('UNHCR',2020,1500000),('WFP',2020,2000000),('RedCross',2020,1200000),('CARE',2020,1800000);
SELECT Organization, SUM(Amount) AS TotalAssistance FROM HumanitarianAssistance WHERE Year = 2020 GROUP BY Organization;
What is the total property size for properties in each city?
CREATE TABLE properties (property_id INT,city VARCHAR(50),size INT); INSERT INTO properties (property_id,city,size) VALUES (1,'Portland',1500),(2,'Seattle',1200),(3,'Portland',1800),(4,'Oakland',1000);
SELECT city, SUM(size) FROM properties GROUP BY city;
Which properties are part of both affordable housing and inclusive housing programs?
CREATE TABLE Property (id INT PRIMARY KEY,address VARCHAR(255),city VARCHAR(255),state VARCHAR(255),zip INT,co_owners INT,sustainable_features VARCHAR(255),price INT); CREATE TABLE AffordableHousing (id INT PRIMARY KEY,property_id INT,program_name VARCHAR(255),beds INT,square_feet INT); CREATE TABLE InclusiveHousing (id INT PRIMARY KEY,property_id INT,policy_type VARCHAR(255),start_date DATE,end_date DATE);
SELECT Property.address, Property.city, Property.state, Property.zip, Property.co_owners, Property.sustainable_features, Property.price FROM Property INNER JOIN AffordableHousing ON Property.id = AffordableHousing.property_id INNER JOIN InclusiveHousing ON Property.id = InclusiveHousing.property_id;
What is the number of graduate students from African countries who have published 2 or more academic papers in the last 3 years?
CREATE TABLE grad_students (id INT,name VARCHAR(50),country VARCHAR(50));CREATE TABLE papers (id INT,paper_id INT,title VARCHAR(100),year INT,author_id INT);
SELECT COUNT(DISTINCT gs.id) FROM grad_students gs JOIN papers p ON gs.id = p.author_id WHERE gs.country IN (SELECT name FROM countries WHERE region = 'Africa') AND p.year BETWEEN YEAR(CURRENT_DATE) - 3 AND YEAR(CURRENT_DATE) GROUP BY gs.id HAVING COUNT(DISTINCT p.paper_id) >= 2;
What is the name and type of all satellites launched by spacecraft that were launched after the year 2010?
CREATE TABLE Spacecraft (id INT,name VARCHAR(50),country VARCHAR(50),launch_date DATE); INSERT INTO Spacecraft (id,name,country,launch_date) VALUES (1,'Falcon 9','USA','2010-06-04'); INSERT INTO Spacecraft (id,name,country,launch_date) VALUES (2,'Soyuz-FG','Russia','2001-11-02'); INSERT INTO Spacecraft (id,name,country,launch_date) VALUES (3,'Long March 3B','China','1996-02-19'); CREATE TABLE Satellites (id INT,name VARCHAR(50),type VARCHAR(50),spacecraft_id INT); INSERT INTO Satellites (id,name,type,spacecraft_id) VALUES (1,'TESS','Observation',1); INSERT INTO Satellites (id,name,type,spacecraft_id) VALUES (2,'MetOp-C','Weather',2); INSERT INTO Satellites (id,name,type,spacecraft_id) VALUES (3,'Chinasat 18','Communication',3);
SELECT s.name, s.type FROM Satellites s JOIN Spacecraft sp ON s.spacecraft_id = sp.id WHERE sp.launch_date > '2010-01-01';
Which employee has been involved in the most maintenance activities, and what is their total involvement in terms of maintenance hours?
CREATE TABLE Employees (EmployeeID INT,FirstName VARCHAR(50),LastName VARCHAR(50));CREATE TABLE Maintenance (MaintenanceID INT,EmployeeID INT,MaintenanceType VARCHAR(50),MaintenanceHours DECIMAL(10,2));CREATE VIEW EmployeeMaintenance AS SELECT EmployeeID,FirstName,LastName,ROW_NUMBER() OVER (PARTITION BY EmployeeID ORDER BY MaintenanceHours DESC) AS MaintenanceRank FROM Employees E JOIN Maintenance M ON E.EmployeeID = M.EmployeeID;
SELECT FirstName, LastName, MaintenanceRank, SUM(MaintenanceHours) AS TotalMaintenanceHours FROM EmployeeMaintenance GROUP BY FirstName, LastName, MaintenanceRank ORDER BY TotalMaintenanceHours DESC FETCH FIRST 1 ROW ONLY;
What is the total fare collected for buses in the city of London in the past week?
CREATE TABLE buses (id INT,city VARCHAR(20)); INSERT INTO buses (id,city) VALUES (1,'London'),(2,'Manchester'); CREATE TABLE bus_fares (id INT,bus_id INT,fare DECIMAL(5,2),fare_date DATE); INSERT INTO bus_fares (id,bus_id,fare,fare_date) VALUES (1,1,3.50,'2022-01-01'),(2,1,3.75,'2022-01-03'),(3,2,2.00,'2022-01-05');
SELECT SUM(bf.fare) FROM bus_fares bf JOIN buses b ON bf.bus_id = b.id WHERE b.city = 'London' AND bf.fare_date >= DATEADD(week, -1, GETDATE());
What was the number of disaster response operations in Pakistan in 2018?
CREATE TABLE disaster_response (disaster_name VARCHAR(255),country VARCHAR(255),operation_start_date DATE,operation_end_date DATE); INSERT INTO disaster_response (disaster_name,country,operation_start_date,operation_end_date) VALUES ('Flood','Pakistan','2018-01-01','2018-04-30'),('Earthquake','Pakistan','2018-10-01','2018-12-31');
SELECT COUNT(*) FROM disaster_response WHERE country = 'Pakistan' AND YEAR(operation_start_date) = 2018 AND YEAR(operation_end_date) = 2018;
Calculate the average patient wait time, partitioned by clinic location, in the "rural_clinics" table with patient wait time data.
CREATE TABLE rural_clinics (clinic_location VARCHAR(255),patient_wait_time INT); INSERT INTO rural_clinics (clinic_location,patient_wait_time) VALUES ('Location1',15),('Location1',20),('Location2',10),('Location2',12),('Location3',25),('Location3',30);
SELECT clinic_location, AVG(patient_wait_time) OVER (PARTITION BY clinic_location) FROM rural_clinics;
What is the total number of points scored by the 'Golden State Warriors' and 'Los Angeles Lakers' in the 'NBA'?
CREATE TABLE teams (team_id INT,team_name TEXT,league TEXT); INSERT INTO teams (team_id,team_name,league) VALUES (1,'Golden State Warriors','NBA'),(2,'Los Angeles Lakers','NBA'); CREATE TABLE games (game_id INT,team_id INT,points INT); INSERT INTO games (game_id,team_id,points) VALUES (1,1,110),(2,1,105),(3,2,120),(4,2,130);
SELECT SUM(points) FROM games WHERE team_id IN (SELECT team_id FROM teams WHERE team_name IN ('Golden State Warriors', 'Los Angeles Lakers')) AND league = 'NBA';
Update the city name to 'San Francisco' for records in the 'green_buildings' table with a 'certification_date' earlier than 2010
CREATE TABLE green_buildings (property_id INT,address VARCHAR(255),city VARCHAR(255),state VARCHAR(255),certification_date DATE);
UPDATE green_buildings SET city = 'San Francisco' WHERE certification_date < '2010-01-01';
What is the most common mode of transportation for international tourists?
CREATE TABLE transportation (id INT,mode VARCHAR(50),tourists INT); INSERT INTO transportation (id,mode,tourists) VALUES (1,'Plane',15000),(2,'Train',3000),(3,'Car',5000),(4,'Bus',2000),(5,'Bike',100);
SELECT mode, RANK() OVER (ORDER BY tourists DESC) as rank FROM transportation;
Update military_bases table, set status to 'active' where base_name is 'Ramstein'
CREATE TABLE military_bases (id INT PRIMARY KEY,base_name VARCHAR(100),status VARCHAR(20)); INSERT INTO military_bases (id,base_name,status) VALUES (1,'Ramstein','inactive');
UPDATE military_bases SET status = 'active' WHERE base_name = 'Ramstein';
Sum of well completion costs for wells in the Caspian Sea.
CREATE TABLE well_completion_costs (id INT,well_name VARCHAR(50),location VARCHAR(50),cost FLOAT); INSERT INTO well_completion_costs (id,well_name,location,cost) VALUES (1,'Well A','Caspian Sea',5000000),(2,'Well B','Caspian Sea',7000000);
SELECT SUM(cost) FROM well_completion_costs WHERE location = 'Caspian Sea';
What is the average age of all female authors who have published a book in the last 5 years?
CREATE TABLE Authors (AuthorID INT,Name VARCHAR(50),Age INT,Gender VARCHAR(10),LastBookPublished DATE);
SELECT AVG(Age) FROM Authors WHERE Gender = 'Female' AND LastBookPublished >= DATEADD(year, -5, GETDATE());
What is the maximum construction cost of public works projects in the 'Africa' continent?
CREATE TABLE Projects (id INT,name TEXT,country TEXT,cost FLOAT); INSERT INTO Projects (id,name,country,cost) VALUES (1,'ProjectA','CountryX',2000000.00),(2,'ProjectB','CountryY',2500500.75),(3,'ProjectC','CountryZ',1800000.50),(4,'ProjectD','CountryA',3000000.00); CREATE TABLE Countries (id INT,name TEXT,continent TEXT); INSERT INTO Countries (id,name,continent) VALUES (1,'CountryX','Africa'),(2,'CountryY','Africa'),(3,'CountryZ','Europe'),(4,'CountryA','Africa');
SELECT MAX(cost) FROM Projects INNER JOIN Countries ON Projects.country = Countries.name WHERE Countries.continent = 'Africa';
Find the top 3 locations with the highest average project cost in the 'public_works' table, partitioned by year.
CREATE TABLE public_works (id INT,name VARCHAR(50),location VARCHAR(50),year INT,cost FLOAT);
SELECT location, AVG(cost) as avg_cost, ROW_NUMBER() OVER (PARTITION BY year ORDER BY AVG(cost) DESC) as rn FROM public_works GROUP BY location, year ORDER BY year, avg_cost DESC LIMIT 3;
List the machines in the Manufacturing department that were purchased after January 1, 2019 and their purchase prices.
CREATE TABLE Machines (MachineID INT,MachineType VARCHAR(50),Manufacturer VARCHAR(50),PurchaseDate DATE,PurchasePrice DECIMAL(10,2),Department VARCHAR(50)); INSERT INTO Machines (MachineID,MachineType,Manufacturer,PurchaseDate,PurchasePrice,Department) VALUES (1,'CNC','ABC Machining','2018-01-01',150000.00,'Manufacturing'); INSERT INTO Machines (MachineID,MachineType,Manufacturer,PurchaseDate,PurchasePrice,Department) VALUES (2,'Robot','XYZ Automation','2019-06-15',200000.00,'Manufacturing');
SELECT MachineType, PurchasePrice FROM Machines WHERE Department = 'Manufacturing' AND PurchaseDate > '2019-01-01';
Which countries have exceeded their historical emissions targets as of 2020? (alternative)
CREATE TABLE country_targets (country TEXT,year INT,emissions_target FLOAT); INSERT INTO country_targets (country,year,emissions_target) VALUES ('Canada',2020,500000);
SELECT country FROM country_targets WHERE year = 2020 AND emissions_target < (SELECT emissions FROM country_emissions WHERE country = country_targets.country AND year = 2020);
Who are the top 3 most prolific female artists in the 21st century?
CREATE TABLE Artworks (artwork_id INT,name VARCHAR(255),artist_id INT,date_sold DATE,price DECIMAL(10,2)); CREATE TABLE Artists (artist_id INT,name VARCHAR(255),gender VARCHAR(255));
SELECT Artists.name, COUNT(Artworks.artwork_id) as count FROM Artists INNER JOIN Artworks ON Artists.artist_id = Artworks.artist_id WHERE Artists.gender = 'Female' AND YEAR(Artworks.date_sold) >= 2000 GROUP BY Artists.name ORDER BY count DESC LIMIT 3;
What is the average playtime per day for each player in 'player_daily_playtime_v2'?
CREATE TABLE player_daily_playtime_v2 (player_id INT,play_date DATE,playtime INT); INSERT INTO player_daily_playtime_v2 (player_id,play_date,playtime) VALUES (4,'2021-02-01',150),(4,'2021-02-02',250),(4,'2021-02-03',350),(5,'2021-02-01',450),(5,'2021-02-02',550),(5,'2021-02-03',650);
SELECT player_id, AVG(playtime) FROM player_daily_playtime_v2 GROUP BY player_id;
What is the maximum number of workers in each union by industry in California?
CREATE TABLE unions (id INT,name VARCHAR(255),state VARCHAR(255)); CREATE TABLE union_industry (id INT,union_id INT,industry VARCHAR(255),workers INT); INSERT INTO unions (id,name,state) VALUES (1,'LiUNA','California'); INSERT INTO union_industry (id,union_id,industry,workers) VALUES (1,1,'Construction',300);
SELECT ui.industry, MAX(ui.workers) as max_workers FROM union_industry ui JOIN unions u ON ui.union_id = u.id WHERE u.state = 'California' GROUP BY ui.industry;
What is the minimum age of adult elephants in the 'African Savanna' sanctuary?
CREATE TABLE elephants (elephant_id INT,elephant_name VARCHAR(50),age INT,weight FLOAT,sanctuary VARCHAR(50)); INSERT INTO elephants (elephant_id,elephant_name,age,weight,sanctuary) VALUES (1,'Elephant_1',12,3000,'African Savanna'); INSERT INTO elephants (elephant_id,elephant_name,age,weight,sanctuary) VALUES (2,'Elephant_2',8,2500,'African Savanna');
SELECT MIN(age) FROM elephants WHERE sanctuary = 'African Savanna' AND age >= 18;
What is the average age of employees in the IT department who have completed technical training?
CREATE TABLE Employees (EmployeeID INT,Department VARCHAR(20),Age INT,TechnicalTraining BOOLEAN); INSERT INTO Employees (EmployeeID,Department,Age,TechnicalTraining) VALUES (1,'IT',30,1),(2,'HR',35,0),(3,'IT',28,1);
SELECT Department, AVG(Age) FROM Employees WHERE Department = 'IT' AND TechnicalTraining = 1 GROUP BY Department;
What is the maximum sustainable yield of salmon in the Pacific Ocean off the coast of British Columbia, Canada?
CREATE TABLE pacificsalmon (country VARCHAR(20),location VARCHAR(30),max_sustainable_yield FLOAT); INSERT INTO pacificsalmon (country,location,max_sustainable_yield) VALUES ('Canada','British Columbia',50000),('USA','Washington',40000);
SELECT max_sustainable_yield FROM pacificsalmon WHERE country = 'Canada' AND location = 'British Columbia';