instruction stringlengths 0 1.06k | input stringlengths 11 5.3k | response stringlengths 2 4.44k |
|---|---|---|
Find the number of tourists who traveled to Africa but not to Egypt or Morocco in 2023. | CREATE TABLE africa_visitors (id INT,country VARCHAR(10),arrival_date DATE); INSERT INTO africa_visitors (id,country,arrival_date) VALUES (1,'South Africa','2023-01-01'); INSERT INTO africa_visitors (id,country,arrival_date) VALUES (2,'Egypt','2023-02-15'); INSERT INTO africa_visitors (id,country,arrival_date) VALUES (3,'Morocco','2023-03-20'); INSERT INTO africa_visitors (id,country,arrival_date) VALUES (4,'Tanzania','2023-04-01'); | SELECT COUNT(*) FROM africa_visitors WHERE country NOT IN ('Egypt', 'Morocco'); |
Which forest types in the 'forest_management' table have more than 50% of their area under sustainable management practices? | CREATE TABLE forest_management (id INT,forest_type VARCHAR(255),sustainable_management_area FLOAT); INSERT INTO forest_management (id,forest_type,sustainable_management_area) VALUES (1,'Temperate',0.6),(2,'Tropical',0.4),(3,'Boreal',0.55); | SELECT forest_type FROM forest_management WHERE sustainable_management_area > 0.5; |
List all autonomous driving research projects and their respective start dates | CREATE TABLE autonomous_driving_research (project_name VARCHAR(100),start_date DATE); | SELECT * FROM autonomous_driving_research; |
Update the amount of funding for the 'Indigenous Art' program in 'WA' to $220,000.00. | CREATE TABLE Funding (id INT,state VARCHAR(2),program VARCHAR(20),amount FLOAT); INSERT INTO Funding (id,state,program,amount) VALUES (1,'CA','Native Art',150000.00),(2,'NM','Pueblo Heritage',200000.00),(3,'CA','Tribal Music',120000.00),(4,'WA','Indigenous Art',200000.00); | UPDATE Funding SET amount = 220000.00 WHERE state = 'WA' AND program = 'Indigenous Art'; |
What is the most spoken indigenous language in the Americas, and how many native speakers does it have? | CREATE TABLE languages (name VARCHAR(255),native_speakers INT,continent VARCHAR(255)); INSERT INTO languages (name,native_speakers,continent) VALUES ('Quechua',8000000,'America'); INSERT INTO languages (name,native_speakers,continent) VALUES ('Guarani',5000000,'America'); | SELECT name, native_speakers FROM languages WHERE continent = 'America' AND native_speakers = (SELECT MAX(native_speakers) FROM languages WHERE continent = 'America'); |
What is the latest medical test result for each astronaut? | CREATE TABLE MedicalData (BadgeID INT,MedicalTest VARCHAR(255),Result FLOAT,TestDate DATE); INSERT INTO MedicalData (BadgeID,MedicalTest,Result,TestDate) VALUES (3,'Bone Density',0.96,'2022-09-05'); INSERT INTO MedicalData (BadgeID,MedicalTest,Result,TestDate) VALUES (4,'Blood Pressure',110,'2022-08-17'); | SELECT Astronauts.Name, MedicalData.MedicalTest, MAX(TestDate), MedicalData.Result FROM Astronauts INNER JOIN MedicalData ON Astronauts.BadgeID = MedicalData.BadgeID GROUP BY Astronauts.Name, MedicalData.MedicalTest, MedicalData.Result; |
Identify the average age of patients with anxiety | CREATE TABLE patients (patient_id INT,condition VARCHAR(20),age INT); INSERT INTO patients (patient_id,condition,age) VALUES (1,'anxiety',25); | SELECT AVG(age) FROM patients WHERE condition = 'anxiety'; |
Average daily usage of autonomous transit in Melbourne | CREATE TABLE melbourne_autonomous_transit (transit_id INT,usage_count INT,usage_date DATE); | SELECT AVG(usage_count) AS avg_daily_usage FROM melbourne_autonomous_transit; |
What is the total number of products that contain at least one ingredient sourced from a specific country for cruelty-free products in the database? | CREATE TABLE Ingredient_Source_CF (id INT,product VARCHAR(255),ingredient VARCHAR(255),sourcing_country VARCHAR(255),cruelty_free BOOLEAN); INSERT INTO Ingredient_Source_CF (id,product,ingredient,sourcing_country,cruelty_free) VALUES (1,'Lush Soak Stimulant Bath Bomb','Sodium Bicarbonate','England',true),(2,'The Body Shop Born Lippy Strawberry Lip Balm','Caprylic/Capric Triglyceride','Brazil',true),(3,'Estee Lauder Advanced Night Repair','Water','France',false),(4,'Lush Soak Stimulant Bath Bomb','Citric Acid','Spain',true),(5,'The Body Shop Tea Tree Skin Clearing Facial Wash','Salicylic Acid','Germany',true); | SELECT sourcing_country, COUNT(DISTINCT product) as total_products FROM Ingredient_Source_CF WHERE cruelty_free = true GROUP BY sourcing_country HAVING COUNT(DISTINCT product) > 0; |
What is the average depth of the Mediterranean Sea? | CREATE TABLE sea_depths (sea VARCHAR(255),depth INT); INSERT INTO sea_depths (sea,depth) VALUES ('Mediterranean',1500),('Caribbean',1000),('Red',2000),('Black',2200); | SELECT AVG(depth) FROM sea_depths WHERE sea = 'Mediterranean'; |
What is the percentage of visitors to New York City from each country? | CREATE TABLE if not exists VisitorsByCity (City VARCHAR(50),Country VARCHAR(50),Visitors INT); INSERT INTO VisitorsByCity (City,Country,Visitors) VALUES ('New York City','Canada',12000),('New York City','Mexico',15000),('New York City','Brazil',10000),('New York City','United Kingdom',18000),('New York City','Germany',14000); | SELECT a.Country, (a.Visitors::FLOAT / SUM(a.Visitors) OVER (PARTITION BY a.City) * 100) AS Percentage FROM VisitorsByCity a WHERE a.City = 'New York City'; |
What is the total number of factories in the automotive industry in Japan and South Korea? | CREATE TABLE auto_industry (id INT,factory_name VARCHAR(100),location VARCHAR(50),supplier_id INT,industry VARCHAR(50)); INSERT INTO auto_industry (id,factory_name,location,supplier_id,industry) VALUES (1,'Toyota','Japan',1,'Automotive'); INSERT INTO auto_industry (id,factory_name,location,supplier_id,industry) VALUES (2,'Hyundai','South Korea',2,'Automotive'); | SELECT COUNT(ai.id) as total_factories FROM auto_industry ai WHERE ai.location IN ('Japan', 'South Korea') AND ai.industry = 'Automotive'; |
List the names and prices of menu items that are not offered at any restaurant located in 'New York'. | CREATE TABLE restaurants (restaurant_id INT,name VARCHAR(255),cuisine VARCHAR(255),location VARCHAR(255)); INSERT INTO restaurants (restaurant_id,name,cuisine,location) VALUES (1,'Big Burger','American','New York'); INSERT INTO restaurants (restaurant_id,name,cuisine,location) VALUES (2,'Sushi Hana','Japanese','California'); INSERT INTO restaurants (restaurant_id,name,cuisine,location) VALUES (3,'Taco Time','Mexican','Texas'); CREATE TABLE menu_items (menu_item_id INT,name VARCHAR(255),price DECIMAL(5,2),restaurant_id INT); INSERT INTO menu_items (menu_item_id,name,price,restaurant_id) VALUES (1,'Big Burger',12.99,1); INSERT INTO menu_items (menu_item_id,name,price,restaurant_id) VALUES (2,'Chicken Teriyaki',15.99,2); INSERT INTO menu_items (menu_item_id,name,price,restaurant_id) VALUES (3,'Garden Salad',7.99,1); INSERT INTO menu_items (menu_item_id,name,price,restaurant_id) VALUES (4,'Sushi Roll',18.99,2); INSERT INTO menu_items (menu_item_id,name,price,restaurant_id) VALUES (5,'Taco',6.99,3); INSERT INTO menu_items (menu_item_id,name,price,restaurant_id) VALUES (6,'Nachos',8.99,3); INSERT INTO menu_items (menu_item_id,name,price,restaurant_id) VALUES (7,'Pizza',10.99,NULL); | SELECT name, price FROM menu_items WHERE menu_item_id NOT IN (SELECT menu_items.restaurant_id FROM menu_items JOIN restaurants ON menu_items.restaurant_id = restaurants.restaurant_id WHERE restaurants.location = 'New York') AND restaurant_id IS NULL; |
What is the total number of hospital beds and their distribution per hospital? | use rural_health; CREATE TABLE hospital_beds (id int,hospital_id int,available_beds int); INSERT INTO hospital_beds (id,hospital_id,available_beds) VALUES (1,1,50); INSERT INTO hospital_beds (id,hospital_id,available_beds) VALUES (2,1,25); INSERT INTO hospital_beds (id,hospital_id,available_beds) VALUES (3,2,30); | SELECT hospital_id, SUM(available_beds) as total_beds, AVG(available_beds) as avg_beds FROM rural_health.hospital_beds GROUP BY hospital_id; |
Identify the number of drought-affected regions in the 'drought_impact' table | CREATE TABLE drought_impact (region_id INT,drought_status VARCHAR(50)); | SELECT COUNT(*) as num_drought_affected_regions FROM drought_impact WHERE drought_status = 'affected'; |
Find the maximum loading capacity for vessels in the 'Passenger' category | CREATE TABLE Vessels (VesselID INT,Category VARCHAR(50),LoadingCapacity FLOAT); INSERT INTO Vessels (VesselID,Category,LoadingCapacity) VALUES (1,'Cargo',60000),(2,'Passenger',3500),(3,'Cargo',45000),(4,'Passenger',2800); | SELECT MAX(LoadingCapacity) FROM Vessels WHERE Category = 'Passenger'; |
What is the distribution of community health workers by state? | CREATE TABLE CommunityHealthWorker (WorkerID INT,State VARCHAR(25)); INSERT INTO CommunityHealthWorker (WorkerID,State) VALUES (1,'NY'),(2,'CA'),(3,'TX'); | SELECT State, COUNT(*) as NumWorkers FROM CommunityHealthWorker GROUP BY State; |
What is the maximum amount of gold mined in a day from the mines in the Australian continent? | CREATE TABLE GoldMined (MineID INT,MineType VARCHAR(15),MinedDate DATE,GoldAmount INT); | SELECT MAX(GoldAmount) FROM GoldMined WHERE MineType = 'Gold' AND Continent = 'Australia'; |
Delete all records from the 'cultural_competency' table where 'hospital_name' is 'Johnson Medical Center' | CREATE TABLE cultural_competency (id INT,hospital_name VARCHAR(255),cultural_competency_score INT); | DELETE FROM cultural_competency WHERE hospital_name = 'Johnson Medical Center'; |
What is the success rate of therapy sessions conducted by therapists with at least 5 years of experience? | CREATE TABLE therapists (therapist_id INT,experience INT,name VARCHAR(50)); INSERT INTO therapists (therapist_id,experience,name) VALUES (1,7,'Alice'); CREATE TABLE treatments (treatment_id INT,therapist_id INT,patient_id INT,therapy_type VARCHAR(50),duration INT,success BOOLEAN); INSERT INTO treatments (treatment_id,therapist_id,patient_id,therapy_type,duration,success) VALUES (1,1,1,'CBT',12,TRUE); | SELECT COUNT(treatments.treatment_id) / COUNT(DISTINCT therapists.therapist_id) FROM therapists JOIN treatments ON therapists.therapist_id = treatments.therapist_id WHERE therapists.experience >= 5 AND treatments.success = TRUE; |
What is the average claim amount for policyholders residing in New York? | CREATE TABLE policyholders (id INT,age INT,gender VARCHAR(10),policy_type VARCHAR(20),premium FLOAT,state VARCHAR(20)); INSERT INTO policyholders (id,age,gender,policy_type,premium,state) VALUES (1,32,'Female','Comprehensive',1200.00,'New York'),(2,41,'Male','Third-Party',800.00,'California'); CREATE TABLE claims (id INT,policyholder_id INT,claim_amount FLOAT,claim_date DATE); INSERT INTO claims (id,policyholder_id,claim_amount,claim_date) VALUES (1,1,500.00,'2021-01-01'),(2,2,1000.00,'2021-02-01'),(3,1,300.00,'2021-03-01'); | SELECT AVG(claim_amount) FROM claims JOIN policyholders ON claims.policyholder_id = policyholders.id WHERE policyholders.state = 'New York'; |
How many professional development courses were completed by teachers in each department? | CREATE TABLE teachers (teacher_id INT,teacher_name VARCHAR(50),department VARCHAR(20),course_completed INT); INSERT INTO teachers (teacher_id,teacher_name,department,course_completed) VALUES (1,'Mr. Doe','Math',3),(2,'Ms. Smith','English',5),(3,'Mrs. Johnson','Science',4); | SELECT department, SUM(course_completed) FROM teachers GROUP BY department; |
What is the total recycling rate in the United States? | CREATE TABLE recycling_rates (state VARCHAR(2),recycling_rate DECIMAL(4,2)); INSERT INTO recycling_rates (state,recycling_rate) VALUES ('US',35.01),('CA',50.03),('NY',25.10); | SELECT SUM(recycling_rate) FROM recycling_rates WHERE state = 'US'; |
What is the maximum power consumption (in kWh) by a machine in the 'tooling' category in the 'plant2'? | CREATE TABLE machines (machine_id INT,plant VARCHAR(10),category VARCHAR(10),power_consumption FLOAT); INSERT INTO machines (machine_id,plant,category,power_consumption) VALUES (1,'plant1','molding',5.6),(2,'plant2','tooling',7.3),(3,'plant1','tooling',6.2); | SELECT MAX(power_consumption) FROM machines WHERE plant = 'plant2' AND category = 'tooling'; |
How many users in each country have interacted with a post in the last week? | CREATE TABLE interactions (id INT,post_id INT,user_id INT); INSERT INTO interactions (id,post_id,user_id) VALUES (1,1,1),(2,1,2),(3,2,3),(4,2,4); CREATE TABLE users (id INT,country VARCHAR(255)); INSERT INTO users (id,country) VALUES (1,'China'),(2,'Mexico'),(3,'Egypt'),(4,'Vietnam'); | SELECT users.country, COUNT(DISTINCT users.id) FROM interactions INNER JOIN users ON interactions.user_id = users.id WHERE interactions.id >= DATE_SUB(CURRENT_DATE, INTERVAL 1 WEEK) GROUP BY users.country; |
How many sustainable tourism certifications were granted in Canada? | CREATE TABLE Certifications (id INT,country TEXT,year INT,certifications INT); INSERT INTO Certifications (id,country,year,certifications) VALUES (1,'Canada',2018,300),(2,'Canada',2019,350),(3,'Canada',2020,400); | SELECT SUM(certifications) FROM Certifications WHERE country = 'Canada'; |
What is the percentage of patients who have had a follow-up appointment within 60 days of their initial appointment, grouped by the physician who saw them and the type of appointment? | CREATE TABLE Appointments (AppointmentID INT,PatientID INT,Physician VARCHAR(255),AppointmentType VARCHAR(255),Date DATE); INSERT INTO Appointments (AppointmentID,PatientID,Physician,AppointmentType,Date) VALUES (1,1,'Dr. Smith','Check-up','2021-09-01'); | SELECT Physician, AppointmentType, (SUM(FollowUpAppointments) / SUM(TotalAppointments)) * 100.0 FROM (SELECT Physician, AppointmentType, COUNT(*) AS TotalAppointments, SUM(CASE WHEN DATEDIFF(day, Appointments.Date, FollowUpAppointments.Date) <= 60 THEN 1 ELSE 0 END) AS FollowUpAppointments FROM Appointments LEFT JOIN Appointments AS FollowUpAppointments ON Appointments.PatientID = FollowUpAppointments.PatientID WHERE FollowUpAppointments.Date IS NOT NULL GROUP BY Physician, AppointmentType) AS Subquery GROUP BY Physician, AppointmentType; |
What was the total revenue for each dispensary in Nevada in Q4 2022? | CREATE TABLE Dispensaries (id INT,name TEXT,state TEXT);CREATE TABLE Sales (id INT,dispensary_id INT,revenue DECIMAL,sale_date DATE); INSERT INTO Dispensaries (id,name,state) VALUES (1,'Dispensary A','Nevada'); INSERT INTO Sales (id,dispensary_id,revenue,sale_date) VALUES (1,1,5000,'2022-10-01'); | SELECT d.name, SUM(s.revenue) FROM Dispensaries d INNER JOIN Sales s ON d.id = s.dispensary_id WHERE d.state = 'Nevada' AND s.sale_date BETWEEN '2022-10-01' AND '2022-12-31' GROUP BY d.name; |
Find the total number of concerts in each country for the 'Rock' genre. | CREATE TABLE Concerts (ConcertId INT,Venue VARCHAR(255),Country VARCHAR(255),Genre VARCHAR(255),Attendees INT); INSERT INTO Concerts (ConcertId,Venue,Country,Genre,Attendees) VALUES (1,'Wembley Stadium','UK','Rock',50000),(2,'Stade de France','France','Rock',60000),(3,'MetLife Stadium','USA','Rock',40000),(4,'Estadio Azteca','Mexico','Rock',70000),(5,'ANZ Stadium','Australia','Rock',30000); | SELECT Country, Genre, SUM(Attendees) AS TotalConcerts FROM Concerts WHERE Genre = 'Rock' GROUP BY Country; |
What are the maximum and minimum speeds reached during autonomous driving research? | CREATE TABLE AutonomousDrivingData (TestID INT,Vehicle VARCHAR(20),MaxSpeed FLOAT,MinSpeed FLOAT); | SELECT MAX(MaxSpeed) AS MaxReached, MIN(MinSpeed) AS MinReached FROM AutonomousDrivingData; |
List the menu items and their total sales from the sales_fact table, ordered by total sales in descending order. | CREATE TABLE menu_item_dim (menu_item_id INT,menu_item_name VARCHAR,menu_category VARCHAR,menu_price DECIMAL); | SELECT m.menu_item_name, SUM(sf.sale_quantity * sf.sale_price) as total_sales FROM sales_fact sf JOIN menu_item_dim m ON sf.menu_item_id = m.menu_item_id GROUP BY m.menu_item_name ORDER BY total_sales DESC; |
What is the average number of crimes committed per day in the "downtown" neighborhood in the last month? | CREATE TABLE Crimes (id INT,date DATE,neighborhood VARCHAR(20)); | SELECT neighborhood, AVG(COUNT(*)) as avg_crimes FROM Crimes WHERE neighborhood = 'downtown' AND date >= DATE_SUB(CURDATE(), INTERVAL 1 MONTH) GROUP BY neighborhood; |
Insert a new claim record for policy type 'Travel'. | CREATE TABLE Policy (PolicyID INT,PolicyType VARCHAR(50)); INSERT INTO Policy VALUES (1,'Auto'),(2,'Home'),(3,'Life'),(4,'Travel'); CREATE TABLE Claims (ClaimID INT,PolicyID INT,ClaimAmount DECIMAL(10,2)); | INSERT INTO Claims (ClaimID, PolicyID, ClaimAmount) VALUES (6, 4, 800.00); |
what is the total number of autonomous vehicles in the world? | CREATE TABLE autonomous_vehicles (vehicle_id INT,model VARCHAR(255),manufacturer VARCHAR(255),state VARCHAR(255)); | SELECT COUNT(*) FROM autonomous_vehicles; |
Find the total number of employees from underrepresented communities in the 'hr', 'operations', and 'it' departments. | CREATE TABLE employees (id INT,name VARCHAR(50),community VARCHAR(50),department VARCHAR(50),role VARCHAR(50)); INSERT INTO employees (id,name,community,department,role) VALUES (1,'John Doe','majority','hr','employee'),(2,'Jane Smith','majority','hr','manager'),(3,'Bob Johnson','majority','operations','employee'),(4,'Alice','underrepresented','it','employee'),(5,'Eli','underrepresented','research','employee'); | SELECT COUNT(*) FROM employees WHERE department IN ('hr', 'operations', 'it') AND community = 'underrepresented'; |
Determine the number of safety incidents per vessel | VESSEL(vessel_id,safety_record_id); SAFETY_INCIDENT(safety_record_id,incident_type) | SELECT v.vessel_id, COUNT(si.safety_record_id) AS num_of_incidents FROM VESSEL v JOIN SAFETY_INCIDENT si ON v.safety_record_id = si.safety_record_id GROUP BY v.vessel_id; |
Find the average property price for each city in the database. | CREATE TABLE properties (id INT,price FLOAT,city VARCHAR(20)); INSERT INTO properties (id,price,city) VALUES (1,500000,'New York'),(2,600000,'Los Angeles'),(3,700000,'New York'); | SELECT city, AVG(price) FROM properties GROUP BY city; |
What are the total sales for each brand in the last 6 months? | CREATE TABLE Brands (Brand_ID INT,Brand_Name TEXT,Country TEXT); INSERT INTO Brands (Brand_ID,Brand_Name,Country) VALUES (1,'Lush','UK'),(2,'The Body Shop','France'),(3,'Estée Lauder','USA'); CREATE TABLE Sales (Sale_ID INT,Brand_ID INT,Sale_Date DATE,Sale_Amount INT); INSERT INTO Sales (Sale_ID,Brand_ID,Sale_Date,Sale_Amount) VALUES (1,1,'2022-01-01',1500),(2,1,'2022-02-01',2000),(3,2,'2022-01-15',1200),(4,2,'2022-03-01',1800),(5,3,'2022-02-15',3000),(6,3,'2022-04-01',2500),(7,1,'2022-03-15',1800),(8,2,'2022-04-15',2200); | SELECT B.Brand_Name, SUM(S.Sale_Amount) AS Total_Sales FROM Brands B INNER JOIN Sales S ON B.Brand_ID = S.Brand_ID WHERE S.Sale_Date >= DATE_SUB(CURRENT_DATE, INTERVAL 6 MONTH) GROUP BY B.Brand_Name; |
Delete the record with id 2 from the investment_data table. | CREATE TABLE investment_data (id INT,investment_amount FLOAT,strategy VARCHAR(50),region VARCHAR(50)); INSERT INTO investment_data (id,investment_amount,strategy,region) VALUES (1,250000.00,'Renewable energy','Americas'); INSERT INTO investment_data (id,investment_amount,strategy,region) VALUES (2,500000.00,'Green energy','Asia-Pacific'); INSERT INTO investment_data (id,investment_amount,strategy,region) VALUES (3,300000.00,'Sustainable agriculture','Europe'); | DELETE FROM investment_data WHERE id = 2; |
What is the biomass trend for a specific fish species? | CREATE TABLE fish_species (id INT,name VARCHAR(50),average_length DECIMAL(5,2)); CREATE TABLE fish_weights (id INT,fish_species_id INT,date DATE,weight DECIMAL(10,2)); INSERT INTO fish_species (id,name,average_length) VALUES (1,'Salmon',70.0),(2,'Tilapia',25.0); INSERT INTO fish_weights (id,fish_species_id,date,weight) VALUES (1,1,'2022-01-01',50.0),(2,1,'2022-01-02',52.0); | SELECT fw.date, fw.weight FROM fish_weights fw WHERE fw.fish_species_id = 1 ORDER BY fw.date; |
Which online travel agency received the highest number of bookings for the 'EMEA' region in Q3 2022? | CREATE TABLE bookings (id INT,hotel_id INT,otan_code TEXT,region TEXT,quarter INT,bookings INT); | SELECT otan_code, MAX(bookings) OVER (PARTITION BY region, quarter) as max_bookings FROM bookings WHERE region = 'EMEA' AND quarter = 3; |
What is the total number of likes on all posts in the 'travel' category on LinkedIn? | CREATE TABLE post_likes (like_id INT,post_id INT,platform VARCHAR(20)); INSERT INTO post_likes (like_id,post_id,platform) VALUES (1,1,'LinkedIn'),(2,2,'LinkedIn'),(3,1,'LinkedIn'); CREATE TABLE post_data (post_id INT,category VARCHAR(50),platform VARCHAR(20)); INSERT INTO post_data (post_id,category,platform) VALUES (1,'travel','LinkedIn'),(2,'technology','LinkedIn'); | SELECT SUM(post_likes.like_id) FROM post_likes INNER JOIN post_data ON post_likes.post_id = post_data.post_id WHERE post_data.category = 'travel' AND post_data.platform = 'LinkedIn'; |
Get the top 3 beauty brands with the most sustainable practices and their average customer satisfaction ratings | CREATE TABLE brand_info (brand VARCHAR(255),is_sustainable BOOLEAN,customer_satisfaction DECIMAL(2,1)); INSERT INTO brand_info (brand,is_sustainable,customer_satisfaction) VALUES ('Brand A',TRUE,4.3),('Brand B',FALSE,4.6); | SELECT brand, AVG(customer_satisfaction) FROM brand_info WHERE is_sustainable = TRUE GROUP BY brand ORDER BY AVG(customer_satisfaction) DESC LIMIT 3; |
What is the average duration of songs in the Top 50 most streamed songs of 2022, for artists from Asia or Oceania? | CREATE TABLE Streams (stream_id INT,song_id INT,streams INT,stream_date DATE); INSERT INTO Streams (stream_id,song_id,streams,stream_date) VALUES (1,1,1000,'2022-01-01'),(2,2,2000,'2022-01-02'),(3,3,3000,'2022-01-03'); CREATE TABLE Songs (song_id INT,song_name TEXT,duration INT,release_year INT,artist_continent TEXT); INSERT INTO Songs (song_id,song_name,duration,release_year,artist_continent) VALUES (1,'Rather Be',205,2014,'UK'),(2,'Shape of You',198,2017,'UK'),(3,'Watermelon Sugar',245,2020,'USA'),(4,'Bamboléo',180,1987,'Spain'),(5,'Te Bubalo',160,2021,'Australia'); | SELECT AVG(s.duration) FROM Songs s JOIN (SELECT song_id, COUNT(*) AS streams FROM Streams WHERE stream_date >= '2022-01-01' GROUP BY song_id ORDER BY streams DESC LIMIT 50) t ON s.song_id = t.song_id WHERE s.artist_continent IN ('Asia', 'Oceania'); |
What is the percentage of teachers who have attended a workshop on teacher professional development by gender? | CREATE TABLE Teachers (TeacherID INT,Age INT,Gender VARCHAR(10),WorkshopAttended VARCHAR(20)); INSERT INTO Teachers (TeacherID,Age,Gender,WorkshopAttended) VALUES (1,45,'Female','Teacher Professional Development'); INSERT INTO Teachers (TeacherID,Age,Gender,WorkshopAttended) VALUES (2,35,'Male','No'); INSERT INTO Teachers (TeacherID,Age,Gender,WorkshopAttended) VALUES (3,50,'Female','Yes'); INSERT INTO Teachers (TeacherID,Age,Gender,WorkshopAttended) VALUES (4,40,'Male','Teacher Professional Development'); | SELECT Gender, (COUNT(*) FILTER (WHERE WorkshopAttended = 'Teacher Professional Development')) * 100.0 / COUNT(*) FROM Teachers GROUP BY Gender; |
What's the average budget of movies released between 2018 and 2020? | CREATE TABLE movie (movie_id INT,title VARCHAR(50),release_year INT,budget INT); INSERT INTO movie (movie_id,title,release_year,budget) VALUES (1,'Movie 1',2019,500000),(2,'Movie 2',2018,700000),(3,'Movie 3',2020,800000); | SELECT AVG(budget) FROM movie WHERE release_year BETWEEN 2018 AND 2020; |
What is the average investment for completed agricultural innovation projects in Asia? | CREATE TABLE AgriculturalInnovation (ProjectID INT,ProjectName VARCHAR(50),Location VARCHAR(50),Investment FLOAT,CompletionDate DATE); INSERT INTO AgriculturalInnovation (ProjectID,ProjectName,Location,Investment,CompletionDate) VALUES (1,'Precision Farming Project','China',120000.00,'2020-12-31'),(2,'Vertical Farming Project','Japan',180000.00,'2019-12-31'); | SELECT AVG(Investment) FROM AgriculturalInnovation WHERE Location = 'Asia' AND CompletionDate IS NOT NULL; |
What is the maximum playtime in a single session? | 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 MAX(playtime) FROM player_sessions; |
How many artifacts are there in each material category in 'Collection Z'? | CREATE TABLE Collection_Z (Artifact_ID INT,Material VARCHAR(255)); INSERT INTO Collection_Z (Artifact_ID,Material) VALUES (1,'Metal'),(2,'Ceramic'),(3,'Metal'); | SELECT Material, COUNT(*) FROM Collection_Z GROUP BY Material; |
What is the average dissolved oxygen level in Carp Farms in the Asian region? | CREATE TABLE Carp_Farms (Farm_ID INT,Farm_Name TEXT,Region TEXT,Dissolved_Oxygen FLOAT); INSERT INTO Carp_Farms (Farm_ID,Farm_Name,Region,Dissolved_Oxygen) VALUES (1,'Farm D','Asian',7.5); INSERT INTO Carp_Farms (Farm_ID,Farm_Name,Region,Dissolved_Oxygen) VALUES (2,'Farm E','Asian',8.0); INSERT INTO Carp_Farms (Farm_ID,Farm_Name,Region,Dissolved_Oxygen) VALUES (3,'Farm F','European',8.5); | SELECT AVG(Dissolved_Oxygen) FROM Carp_Farms WHERE Region = 'Asian'; |
How many climate-related projects were funded by multilateral development banks in each continent? | CREATE TABLE project_funding (project VARCHAR(50),bank VARCHAR(50),continent VARCHAR(50)); INSERT INTO project_funding VALUES ('ProjectA','World Bank','Asia'); | SELECT continent, COUNT(DISTINCT project) FROM project_funding WHERE bank IN ('World Bank', 'Asian Development Bank', 'African Development Bank') GROUP BY continent |
Get creative AI applications using the 'Deep Learning' technology | CREATE TABLE creative_apps_2 (id INT,name VARCHAR(255),type VARCHAR(255),technology VARCHAR(255)); INSERT INTO creative_apps_2 (id,name,type,technology) VALUES (1,'DeepArt','Art Generation','Deep Learning'),(2,'DeepSpeech','Speech Recognition','Deep Learning'); | SELECT * FROM creative_apps_2 WHERE technology = 'Deep Learning'; |
What is the average size of green-certified buildings in Portland? | CREATE TABLE green_buildings (id INT,size FLOAT,city TEXT,state TEXT,is_green_certified BOOLEAN); | SELECT AVG(size) FROM green_buildings WHERE city = 'Portland' AND is_green_certified = TRUE; |
How many policyholders have a policy with a premium over $2000? | CREATE TABLE policyholder_2 (policyholder_id INT,policy_type VARCHAR(20),premium FLOAT); INSERT INTO policyholder_2 (policyholder_id,policy_type,premium) VALUES (1,'Home',2500.00),(2,'Auto',1000.00),(3,'Life',2200.00),(4,'Home',1800.00); | SELECT COUNT(*) FROM (SELECT * FROM policyholder_2 WHERE premium > 2000) AS high_premium; |
What is the average daily maintenance duration for trains and buses? | CREATE TABLE maintenance_schedule (schedule_id INT,schedule_date DATE,mode_id INT,duration_minutes INT); INSERT INTO maintenance_schedule VALUES (1,'2023-01-01',1,120); INSERT INTO maintenance_schedule VALUES (2,'2023-01-01',2,90); | SELECT AVG(duration_minutes) as avg_maintenance_duration FROM maintenance_schedule WHERE mode_id IN (1, 2); |
Update 'games' score to 80 where player_id is 6 | CREATE TABLE games (id INT,player_id INT,score INT); | UPDATE games SET score = 80 WHERE player_id = 6; |
What is the total number of labor rights violations for unions in the tech industry, and how many unions are there in this industry? | CREATE TABLE union_tech (union_id INT,union_name TEXT,industry TEXT,violations INT); INSERT INTO union_tech (union_id,union_name,industry,violations) VALUES (1,'Union I','Tech',20),(2,'Union J','Tech',30),(3,'Union K','Tech',10); | SELECT industry, COUNT(*), SUM(violations) FROM union_tech WHERE industry = 'Tech' GROUP BY industry; |
Find the average number of charging points per charging station | CREATE TABLE charging_stations_extended (id INT PRIMARY KEY,name VARCHAR(255),location VARCHAR(255),num_charging_points INT,num_stations INT); | CREATE VIEW charging_stations_averages AS SELECT name, AVG(num_charging_points / num_stations) as avg_charging_points_per_station FROM charging_stations_extended GROUP BY name; |
What is the average value of assets for clients in the 'Europe' region? | CREATE TABLE clients (client_id INT,region VARCHAR(20),currency VARCHAR(10)); INSERT INTO clients (client_id,region,currency) VALUES (1,'Europe','EUR'),(2,'Asia','USD'); CREATE TABLE assets (asset_id INT,client_id INT,value INT); INSERT INTO assets (asset_id,client_id,value) VALUES (1,1,5000),(2,1,7000),(3,2,3000); | SELECT AVG(value) FROM assets INNER JOIN clients ON assets.client_id = clients.client_id WHERE clients.region = 'Europe'; |
How many drought impact assessments were conducted in Australia in 2019? | CREATE TABLE drought_impact_assessments (country VARCHAR(20),year INT,num_assessments INT); INSERT INTO drought_impact_assessments (country,year,num_assessments) VALUES ('Australia',2019,150); | SELECT num_assessments FROM drought_impact_assessments WHERE country = 'Australia' AND year = 2019; |
What is the distribution of player levels in the game, grouped by platform? | CREATE TABLE GamePlatform (PlayerID INT,GameID INT,Platform VARCHAR(20)); INSERT INTO GamePlatform (PlayerID,GameID,Platform) VALUES (1,1001,'PC'),(2,1002,'PS5'),(3,1001,'XBOX'); CREATE TABLE PlayerLevel (PlayerID INT,Level INT); INSERT INTO PlayerLevel (PlayerID,Level) VALUES (1,5),(2,8),(3,5); | SELECT Platform, Level, COUNT(*) as LevelCount, AVG(Level) as AvgLevel FROM PlayerLevel JOIN GamePlatform ON PlayerLevel.PlayerID = GamePlatform.PlayerID GROUP BY Platform, Level ORDER BY Platform, Level; |
Get the urban agriculture systems in Europe. | CREATE TABLE AgricultureSystems (id INT,name VARCHAR(50),location VARCHAR(50),type VARCHAR(50)); INSERT INTO AgricultureSystems (id,name,location,type) VALUES (1,'Rooftop Gardens','Europe','Urban Agriculture'); | SELECT * FROM AgricultureSystems WHERE location = 'Europe' AND type = 'Urban Agriculture'; |
List the faculty members in the History department who have not been awarded any grants? | CREATE TABLE faculty (id INT,name VARCHAR(50),department VARCHAR(50),grant_amount DECIMAL(10,2)); INSERT INTO faculty (id,name,department,grant_amount) VALUES (1,'Ivy','History',NULL),(2,'Jack','History',100000.00); | SELECT name FROM faculty WHERE department = 'History' AND grant_amount IS NULL; |
Find the top 2 restaurants with the highest total revenue for each cuisine type, partitioned by cuisine type. | CREATE TABLE Restaurants (RestaurantID int,Name varchar(50),CuisineType varchar(50),Location varchar(50),TotalRevenue numeric(12,2)); INSERT INTO Restaurants (RestaurantID,Name,CuisineType,Location,TotalRevenue) VALUES (1,'Asian Fusion','Asian','New York',500000),(2,'Bella Italia','Italian','Los Angeles',750000),(3,'Sushi House','Japanese','San Francisco',600000),(4,'Thai Express','Asian','Chicago',450000),(5,'Taste of India','Indian','Houston',800000),(6,'Ramen Republic','Asian','Seattle',300000); | SELECT RestaurantID, Name, CuisineType, TotalRevenue, ROW_NUMBER() OVER (PARTITION BY CuisineType ORDER BY TotalRevenue DESC) as Rank FROM Restaurants; |
What is the maximum snow depth recorded in the Arctic Research Station 4 and 5? | CREATE TABLE Arctic_Research_Station_4 (date DATE,snow_depth FLOAT); CREATE TABLE Arctic_Research_Station_5 (date DATE,snow_depth FLOAT); | SELECT MAX(snow_depth) FROM Arctic_Research_Station_4; SELECT MAX(snow_depth) FROM Arctic_Research_Station_5; SELECT GREATEST(MAX(snow_depth), MAX(snow_depth)) FROM Arctic_Research_Station_4, Arctic_Research_Station_5; |
What is the total donation amount by each program in 2021? | CREATE TABLE donations (id INT,program_id INT,donation_date DATE,amount DECIMAL(10,2)); INSERT INTO donations (id,program_id,donation_date,amount) VALUES (1,1,'2021-02-15',500.00),(2,1,'2021-03-10',1000.00),(3,2,'2021-02-25',800.00),(4,3,'2021-01-05',1500.00); | SELECT program_id, SUM(amount) as total_donation, YEAR(donation_date) as year FROM donations GROUP BY program_id, year HAVING year = 2021; |
How many defense projects were ongoing in Asia as of 2019? | CREATE TABLE defense_projects (id INT,region VARCHAR(50),start_year INT,end_year INT); INSERT INTO defense_projects (id,region,start_year,end_year) VALUES (1,'Asia',2017,2020); INSERT INTO defense_projects (id,region,start_year,end_year) VALUES (2,'Asia',2018,2021); INSERT INTO defense_projects (id,region,start_year,end_year) VALUES (3,'Asia',2019,2022); | SELECT COUNT(*) FROM defense_projects WHERE region = 'Asia' AND end_year >= 2019; |
Which AI safety researcher has the highest number of publications in safety_researchers_data? | CREATE TABLE safety_researchers_data (researcher_id INTEGER,researcher_name TEXT,publication_count INTEGER); | SELECT researcher_name, MAX(publication_count) as max_publications FROM safety_researchers_data GROUP BY researcher_name ORDER BY max_publications DESC LIMIT 1; |
List the top 10 states with the highest percentage of government-funded schools that meet or exceed the national average test scores. | CREATE TABLE schools (school_id INT,school_name VARCHAR(255),state VARCHAR(255),test_scores INT); | SELECT state, PERCENTAGE FROM (SELECT state, COUNT(*) * 100.0 / (SELECT COUNT(*) FROM schools WHERE test_scores >= (SELECT AVG(test_scores) FROM schools)) AS PERCENTAGE FROM schools WHERE test_scores >= (SELECT AVG(test_scores) FROM schools) GROUP BY state ORDER BY PERCENTAGE DESC) AS top_states LIMIT 10; |
What is the average methane concentration in the Arctic Ocean in 2020? | CREATE TABLE arctic_ocean_gas (gas VARCHAR(50),year INT,concentration FLOAT); | SELECT AVG(concentration) FROM arctic_ocean_gas WHERE gas = 'methane' AND year = 2020; |
Who are the top 5 police officers with the most traffic citations issued? | CREATE TABLE officers (officer_id INT,name VARCHAR(255),rank VARCHAR(255)); INSERT INTO officers (officer_id,name,rank) VALUES (1,'Kevin Smith','Sergeant'),(2,'Emily Chen','Officer'),(3,'Daniel Kim','Lieutenant'); CREATE TABLE traffic_citations (citation_id INT,officer_id INT,date DATE); INSERT INTO traffic_citations (citation_id,officer_id,date) VALUES (1,1,'2022-01-01'),(2,2,'2022-01-02'),(3,1,'2022-01-03'),(4,3,'2022-01-04'); | SELECT officer_id, name, COUNT(*) as total_citations FROM traffic_citations tc JOIN officers o ON tc.officer_id = o.officer_id GROUP BY officer_id, name ORDER BY total_citations DESC LIMIT 5; |
What is the number of donations by each donor in Q1 2022? | CREATE TABLE DonationsQ1 (DonationID INT,DonorID INT,DonationDate DATE,DonationAmount DECIMAL); INSERT INTO DonationsQ1 (DonationID,DonorID,DonationDate,DonationAmount) SELECT DonationID,DonorID,DonationDate,DonationAmount FROM Donations WHERE DonationDate BETWEEN '2022-01-01' AND '2022-03-31'; | SELECT D.DonorName, COUNT(DQ1.DonationID) as Q1DonationCount FROM DonationsQ1 DQ1 JOIN Donors D ON DQ1.DonorID = D.DonorID GROUP BY D.DonorName; |
How many artworks have been created by female artists in the last 50 years? | CREATE TABLE artists (id INT,name TEXT,gender TEXT,birth_year INT); CREATE TABLE artworks (id INT,title TEXT,artist_id INT,creation_year INT); INSERT INTO artists (id,name,gender,birth_year) VALUES (1,'Claude Monet','Male',1840),(2,'Camille Pissarro','Male',1830),(3,'Marie Bracquemond','Female',1840); INSERT INTO artworks (id,title,artist_id,creation_year) VALUES (1,'Water Lilies',1,1905),(2,'The Boulevard Montmartre at Night',2,1897),(3,'The Garden',3,1888); | SELECT COUNT(*) FROM artworks a INNER JOIN artists ar ON a.artist_id = ar.id WHERE ar.gender = 'Female' AND a.creation_year >= YEAR(CURRENT_DATE) - 50; |
How many patients from the USA have been treated with Cognitive Behavioral Therapy (CBT) in the past year? | CREATE TABLE patients (patient_id INT,patient_name TEXT,country TEXT,treatment_start DATE); INSERT INTO patients (patient_id,patient_name,country,treatment_start) VALUES (1,'John Doe','USA','2021-06-15'),(2,'Jane Smith','Canada','2021-04-20'); CREATE TABLE treatments (treatment_id INT,patient_id INT,treatment_type TEXT,treatment_date DATE); INSERT INTO treatments (treatment_id,patient_id,treatment_type,treatment_date) VALUES (1,1,'CBT','2021-06-16'),(2,1,'Medication','2021-06-16'),(3,2,'CBT','2021-04-21'); | SELECT COUNT(DISTINCT p.patient_id) FROM patients p INNER JOIN treatments t ON p.patient_id = t.patient_id WHERE p.country = 'USA' AND t.treatment_type = 'CBT' AND t.treatment_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR); |
What is the number of natural disasters in Small Island Developing States (SIDS) between 2000 and 2020, and the total number of people affected by them? | CREATE TABLE NaturalDisastersData (country VARCHAR(50),year INT,disaster_type VARCHAR(50),people_affected INT); | SELECT COUNT(*), SUM(people_affected) FROM NaturalDisastersData WHERE country LIKE 'Small Island%' AND year BETWEEN 2000 AND 2020 AND disaster_type = 'natural'; |
What is the total number of volunteers who participated in projects in Africa in 2021? | CREATE TABLE volunteers (id INT PRIMARY KEY,project VARCHAR(50),location VARCHAR(50),year INT,number INT); INSERT INTO volunteers (id,project,location,year,number) VALUES (1,'Project A','North America',2020,20),(2,'Project B','Latin America',2020,30),(3,'Project A','North America',2021,25),(4,'Project B','Latin America',2021,35),(5,'Project C','Europe',2021,40),(6,'Project D','Africa',2021,50); | SELECT SUM(number) FROM volunteers WHERE location = 'Africa' AND year = 2021; |
What is the total number of construction workers in New York state? | CREATE TABLE construction_workers (id INT,name VARCHAR(50),age INT,state VARCHAR(50)); INSERT INTO construction_workers (id,name,age,state) VALUES (1,'John Doe',35,'New York'); INSERT INTO construction_workers (id,name,age,state) VALUES (2,'Jane Smith',40,'New York'); | SELECT COUNT(*) FROM construction_workers WHERE state = 'New York' |
Show the total amount of funding for programs in 'Theater' and 'Music' categories, excluding programs with a budget over $75,000. | CREATE TABLE Programs (id INT,name TEXT,category TEXT,budget INT); INSERT INTO Programs (id,name,category,budget) VALUES (1,'Dance Performance','Theater',50000),(2,'Film Festival','Music',75000),(3,'Photography Exhibition','Visual Arts',100000); | SELECT SUM(budget) FROM Programs WHERE category IN ('Theater', 'Music') AND budget <= 75000; |
Calculate the moving average of the number of security incidents per day for the last 30 days. | CREATE TABLE SecurityIncidents (Id INT,Timestamp DATETIME,IncidentCount INT); INSERT INTO SecurityIncidents (Id,Timestamp,IncidentCount) VALUES (1,'2022-01-01',10),(2,'2022-01-02',15),(3,'2022-01-03',20); | SELECT Timestamp, AVG(IncidentCount) OVER (ORDER BY Timestamp ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as MovingAverage FROM SecurityIncidents WHERE Timestamp >= DATE_SUB(CURRENT_TIMESTAMP, INTERVAL 30 DAY); |
What is the minimum monthly bill for prepaid mobile customers in the "suburban" region? | CREATE TABLE prepaid_plans (id INT,plan_name VARCHAR(20),region VARCHAR(10),monthly_bill INT); INSERT INTO prepaid_plans (id,plan_name,region,monthly_bill) VALUES (1,'Basic','suburban',30),(2,'Plus','suburban',40),(3,'Premium','suburban',50); | SELECT MIN(monthly_bill) FROM prepaid_plans WHERE region = 'suburban'; |
What is the total savings of customers who live in 'Texas' or 'California'? | CREATE TABLE savings (customer_id INT,name TEXT,state TEXT,savings DECIMAL(10,2)); INSERT INTO savings (customer_id,name,state,savings) VALUES (9,'Ella Green','Texas',11000.00),(10,'Liam White','California',12000.00); | SELECT SUM(savings) FROM savings WHERE state IN ('Texas', 'California'); |
What is the total amount of research grants awarded to the Chemistry department? | CREATE TABLE grants(id INT,department TEXT,amount FLOAT); INSERT INTO grants(id,department,amount) VALUES (1,'Chemistry',100000.0),(2,'Physics',75000.0); | SELECT SUM(amount) FROM grants WHERE department = 'Chemistry'; |
How many people in New York voted in the last election? | CREATE TABLE voters (name TEXT,state TEXT,voted INTEGER); INSERT INTO voters (name,state,voted) VALUES ('Person1','New York',1),('Person2','New York',0),('Person3','New York',1),('Person4','New York',1),('Person5','New York',0); | SELECT SUM(voted) as total_voters FROM voters WHERE state = 'New York'; |
What is the total number of employees across all mining operations, grouped by their job titles? | CREATE TABLE mining_operations (id INT,name VARCHAR(50),location VARCHAR(50)); INSERT INTO mining_operations (id,name,location) VALUES (1,'Goldmine 1','USA'),(2,'Silvermine 2','Canada'); CREATE TABLE employees (id INT,name VARCHAR(50),job_title VARCHAR(50),operation_id INT); INSERT INTO employees (id,name,job_title,operation_id) VALUES (1,'John Doe','Engineer',1),(2,'Jane Smith','Manager',2); | SELECT e.job_title, COUNT(e.id) FROM employees e INNER JOIN mining_operations m ON e.operation_id = m.id GROUP BY e.job_title; |
What is the average quantity of ingredients in dishes with meat? | CREATE TABLE Dishes (dish_id INT,dish_name VARCHAR(50),has_meat BOOLEAN,quantity INT); INSERT INTO Dishes (dish_id,dish_name,has_meat,quantity) VALUES (1,'Quinoa Salad',false,5),(2,'Cheeseburger',true,3),(3,'Veggie Burger',false,4),(4,'BBQ Ribs',true,6),(5,'Tofu Stir Fry',false,7); | SELECT AVG(quantity) FROM Dishes WHERE has_meat = true; |
What is the total number of hotels and their average rating for each city in the hotel_data table? | CREATE TABLE hotel_data (hotel_id INT,hotel_name TEXT,city TEXT,country TEXT,stars INT); INSERT INTO hotel_data (hotel_id,hotel_name,city,country,stars) VALUES (1,'Park Hotel','Zurich','Switzerland',5),(2,'Four Seasons','Montreal','Canada',5),(3,'The Plaza','New York','USA',4); | SELECT city, AVG(stars) as avg_rating, COUNT(DISTINCT hotel_id) as hotel_count FROM hotel_data GROUP BY city; |
List all creative AI application titles and descriptions published since 2020 by authors from India or Japan. | CREATE TABLE creative_ai (id INT,author VARCHAR(50),country VARCHAR(50),title VARCHAR(100),description TEXT,publication_date DATE); INSERT INTO creative_ai (id,author,country,title,description,publication_date) VALUES (1,'Charlie Davis','India','AI-Generated Art','Description A','2021-02-01'),(2,'Emma White','Japan','AI Music Composition','Description B','2020-12-15'); | SELECT title, description FROM creative_ai WHERE (country = 'India' OR country = 'Japan') AND publication_date >= '2020-01-01'; |
Update the number of likes on a post | CREATE TABLE posts (id INT,user_id INT,post_text TEXT); CREATE TABLE users (id INT,privacy_setting VARCHAR(20)); CREATE TABLE post_likes (id INT,post_id INT,likes INT); INSERT INTO users (id,privacy_setting) VALUES (1,'medium'),(2,'high'),(3,'low'); INSERT INTO posts (id,user_id,post_text) VALUES (1,1,'Hello World!'),(2,2,'Goodbye World!'),(3,3,'This is a private post.'); INSERT INTO post_likes (id,post_id,likes) VALUES (1,1,10),(2,2,5),(3,3,15); | UPDATE post_likes SET likes = 12 WHERE post_id = 1; |
What is the minimum number of likes for a post that has at least one like in the 'social_media' table? | CREATE TABLE social_media (user_id INT,post_id INT,post_date DATE,likes INT); | SELECT MIN(likes) FROM social_media WHERE likes > 0; |
Delete all records for Tank2 that have a feeding frequency of more than 5 times per day. | CREATE TABLE Tank2 (species VARCHAR(20),feeding_frequency INT); INSERT INTO Tank2 (species,feeding_frequency) VALUES ('Tilapia',4),('Tilapia',6),('Trout',5),('Trout',3); | DELETE FROM Tank2 WHERE feeding_frequency > 5; |
Who are the top 3 actors with the highest number of movies in the 'Sci-Fi' genre? | CREATE TABLE movies (id INT,title VARCHAR(100),genre VARCHAR(50),release_year INT,actor_id INT); INSERT INTO movies (id,title,genre,release_year,actor_id) VALUES (1,'Movie1','Sci-Fi',2020,101); INSERT INTO movies (id,title,genre,release_year,actor_id) VALUES (2,'Movie2','Sci-Fi',2019,102); INSERT INTO movies (id,title,genre,release_year,actor_id) VALUES (3,'Movie3','Sci-Fi',2018,101); INSERT INTO movies (id,title,genre,release_year,actor_id) VALUES (4,'Movie4','Sci-Fi',2021,103); | SELECT actor_id, COUNT(*) AS num_movies FROM movies WHERE genre = 'Sci-Fi' GROUP BY actor_id ORDER BY num_movies DESC LIMIT 3; |
Calculate the number of unique users who planted each crop type in the past month. | CREATE TABLE users (user_id INT,name VARCHAR(255)); CREATE TABLE planting_records (record_id INT,user_id INT,crop_type VARCHAR(255),planting_date DATE); | SELECT s.crop_type, COUNT(DISTINCT u.user_id) as num_unique_users FROM users u INNER JOIN planting_records s ON u.user_id = s.user_id INNER JOIN (SELECT crop_type, MAX(planting_date) as max_planting_date FROM planting_records WHERE planting_date >= DATE_SUB(CURDATE(), INTERVAL 1 MONTH) GROUP BY crop_type) md ON s.crop_type = md.crop_type AND s.planting_date = md.max_planting_date GROUP BY s.crop_type; |
Which public consultations in the education domain have received the least feedback in the last 3 months? | CREATE TABLE consultation (id INT,name VARCHAR(255),domain VARCHAR(255),start_date DATE); INSERT INTO consultation (id,name,domain,start_date) VALUES (1,'Teacher Training','Education','2022-01-01'); INSERT INTO consultation (id,name,domain,start_date) VALUES (2,'School Lunch Program','Education','2022-05-15'); INSERT INTO consultation (id,name,domain,start_date) VALUES (3,'Standardized Testing','Education','2022-04-01'); | SELECT c.name FROM consultation c WHERE c.domain = 'Education' AND c.start_date >= DATEADD(month, -3, GETDATE()) GROUP BY c.name ORDER BY COUNT(*) ASC; |
What is the total revenue generated by each genre in the last quarter? | CREATE TABLE Genres (GenreId INT,GenreName VARCHAR(255)); CREATE TABLE Sales (SaleId INT,GenreId INT,SaleDate DATE,Revenue DECIMAL(10,2)); INSERT INTO Genres (GenreId,GenreName) VALUES (1,'Pop'),(2,'Rock'),(3,'Jazz'); INSERT INTO Sales (SaleId,GenreId,SaleDate,Revenue) VALUES (1,1,'2022-01-01',100),(2,2,'2022-01-05',150),(3,3,'2022-01-10',75); | SELECT G.GenreName, SUM(S.Revenue) AS TotalRevenue FROM Genres G INNER JOIN Sales S ON G.GenreId = S.GenreId WHERE S.SaleDate >= DATE_SUB(CURDATE(), INTERVAL 3 MONTH) GROUP BY G.GenreName; |
Insert a new record for 'Startup D' with a funding amount of 30000000, located in 'Brazil'. | CREATE TABLE biotech_startups (id INT,name VARCHAR(100),location VARCHAR(100),funding FLOAT); | INSERT INTO biotech_startups (name, location, funding) VALUES ('Startup D', 'Brazil', 30000000); |
Which mining sites have experienced a significant increase in resource depletion over the past year? | CREATE TABLE mining_sites (id INT,name VARCHAR(255),resources_remaining INT); INSERT INTO mining_sites (id,name,resources_remaining) VALUES (1,'Site A',10000),(2,'Site B',12000),(3,'Site C',8000); CREATE TABLE resource_depletion (site_id INT,date DATE,resources_depleted INT); INSERT INTO resource_depletion (site_id,date,resources_depleted) VALUES (1,'2021-01-01',500),(1,'2021-02-01',600),(2,'2021-01-01',400),(2,'2021-02-01',700),(3,'2021-01-01',800),(3,'2021-02-01',900); | SELECT ms.name, (ms.resources_remaining - SUM(rd.resources_depleted)) AS resources_remaining_diff FROM mining_sites ms JOIN resource_depletion rd ON ms.id = rd.site_id WHERE rd.date BETWEEN '2021-01-01' AND '2021-12-31' GROUP BY ms.name HAVING resources_remaining_diff < 0; |
Find the total number of cases for each case type, ordered by the total count in descending order. | CREATE TABLE cases (case_id INT,case_type VARCHAR(20),case_date DATE); INSERT INTO cases (case_id,case_type,case_date) VALUES (1,'Civil','2022-01-10'),(2,'Criminal','2022-01-12'),(3,'Civil','2022-01-15'),(4,'Juvenile','2022-01-17'),(5,'Civil','2022-01-18'); | SELECT case_type, COUNT(*) as total_count FROM cases GROUP BY case_type ORDER BY total_count DESC; |
What is the total investment in the 'Technology' industry for projects started on or before 2021? | CREATE TABLE EconomicDiversification (id INT,project_id INT,business_name VARCHAR(50),industry VARCHAR(50),investment DECIMAL(10,2),start_date DATE,end_date DATE); INSERT INTO EconomicDiversification (id,project_id,business_name,industry,investment,start_date,end_date) VALUES (1,1,'Green Energy Solutions','Renewable Energy',75000.00,'2021-04-01','2022-03-31'); INSERT INTO EconomicDiversification (id,project_id,business_name,industry,investment,start_date,end_date) VALUES (2,2,'Local Food Market','Technology',35000.00,'2021-01-01','2023-12-31'); | SELECT industry, SUM(investment) FROM EconomicDiversification WHERE start_date <= '2021-12-31' AND industry = 'Technology' GROUP BY industry; |
Get the number of locations with water usage less than 1000 cubic meters in the year 2019 | CREATE TABLE water_usage (id INT PRIMARY KEY,year INT,location VARCHAR(50),usage FLOAT); INSERT INTO water_usage (id,year,location,usage) VALUES (1,2019,'Atlanta',1234.56),(2,2019,'Denver',897.45),(3,2019,'Boston',987.65),(4,2019,'Seattle',789.12),(5,2019,'Portland',567.89); | SELECT COUNT(*) FROM water_usage WHERE year = 2019 AND usage < 1000; |
What is the total revenue for OTA bookings from 'Middle East'? | CREATE TABLE ota_bookings (booking_id INT,hotel_name TEXT,region TEXT,revenue FLOAT); INSERT INTO ota_bookings (booking_id,hotel_name,region,revenue) VALUES (1,'Hotel H','Middle East',500),(2,'Hotel I','Middle East',700),(3,'Hotel J','Middle East',400); | SELECT SUM(revenue) FROM ota_bookings WHERE region = 'Middle East'; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.