instruction stringlengths 0 1.06k | input stringlengths 11 5.3k | response stringlengths 2 4.44k |
|---|---|---|
Add a new excavation site "Chan Chan" in Peru to the excavations table. | artifacts(artifact_id,name,description,date_found,excavation_site_id); excavations(excavation_site_id,name,location,start_date,end_date) | INSERT INTO excavations (excavation_site_id, name, location, start_date, end_date) |
What is the total amount of resources depleted by each mining site, and which sites have depleted more than 50% of their total resources? | CREATE TABLE mining_sites (id INT,site_name TEXT,total_resources_available INT);CREATE TABLE resources_depleted (site_id INT,amount_depleted INT); | SELECT s.site_name, SUM(r.amount_depleted) as total_depleted, s.total_resources_available FROM mining_sites s JOIN resources_depleted r ON s.id = r.site_id GROUP BY s.site_name HAVING SUM(r.amount_depleted) / s.total_resources_available > 0.5; |
How many building permits were issued per month in the last year? | CREATE TABLE building_permits (permit_id SERIAL PRIMARY KEY,issue_date DATE); INSERT INTO building_permits (issue_date) VALUES ('2021-01-01'),('2021-01-10'),('2022-02-01'); | SELECT TO_CHAR(issue_date, 'Month') AS month, COUNT(permit_id) AS permits_issued FROM building_permits WHERE issue_date >= NOW() - INTERVAL '1 year' GROUP BY month ORDER BY TO_DATE(month, 'Month') ASC; |
Identify the number of exits that occurred through mergers and acquisitions (M&A) for startups in the e-commerce industry, grouped by the year of exit. | CREATE TABLE exits (id INT,startup_id INT,exit_type TEXT,exit_year INT); CREATE TABLE startups (id INT,name TEXT,industry TEXT); INSERT INTO exits (id,startup_id,exit_type,exit_year) VALUES (1,1,'M&A',2017),(2,2,'IPO',2018),(3,3,'M&A',2019); INSERT INTO startups (id,name,industry) VALUES (1,'EcomStartupA','E-commerce'),(2,'TechStartupB','Technology'),(3,'EcomStartupC','E-commerce'); | SELECT e.exit_year, COUNT(*) as num_ma_exits FROM exits e INNER JOIN startups s ON e.startup_id = s.id WHERE s.industry = 'E-commerce' AND e.exit_type = 'M&A' GROUP BY e.exit_year; |
Delete the 'gene_expression' table if it has no records | CREATE TABLE gene_expression (id INT PRIMARY KEY,gene_id INT,expression_level REAL); | DELETE FROM gene_expression WHERE (SELECT COUNT(*) FROM gene_expression) = 0; |
What are the names, locations, and lengths of railways constructed before 1930, excluding those in the United States? | CREATE TABLE railways (id INT,name TEXT,location TEXT,length INT,type TEXT,year INT); INSERT INTO railways (id,name,location,length,type,year) VALUES (1,'Trans-Siberian','Russia',9289,'Rail',1916); INSERT INTO railways (id,name,location,length,type,year) VALUES (2,'Eurasian Land Bridge','China,Kazakhstan,Russia,Mongolia,Germany',10139,'Rail',2013); | SELECT name, location, length FROM railways WHERE year < 1930 AND location NOT LIKE '%United States%'; |
How many companies are there in each sector? | CREATE TABLE companies (id INT,sector VARCHAR(20)); INSERT INTO companies (id,sector) VALUES (1,'technology'),(2,'finance'),(3,'technology'),(4,'healthcare'); | SELECT sector, COUNT(*) FROM companies GROUP BY sector; |
What is the total revenue for each menu category in the first week of January 2022? | CREATE TABLE menu_sales_5 (menu_category VARCHAR(255),sale_date DATE,revenue INT); INSERT INTO menu_sales_5 (menu_category,sale_date,revenue) VALUES ('Appetizers','2022-01-01',500),('Appetizers','2022-01-02',700),('Entrees','2022-01-01',700),('Entrees','2022-01-02',800); | SELECT menu_category, SUM(revenue) FROM menu_sales_5 WHERE sale_date BETWEEN '2022-01-01' AND '2022-01-07' GROUP BY menu_category; |
How many public services were delivered in District A and B in Q2 of 2021? | CREATE TABLE PublicServices (District VARCHAR(10),Quarter INT,Year INT,ServiceCount INT); INSERT INTO PublicServices VALUES ('District A',2,2021,1200),('District A',3,2021,1500),('District B',2,2021,900),('District B',3,2021,1100); | SELECT SUM(ServiceCount) FROM PublicServices WHERE District IN ('District A', 'District B') AND Quarter = 2 AND Year = 2021; |
What is the total biomass of fish species in the Pacific and Atlantic oceans? | CREATE TABLE fish_species (id INT,species VARCHAR(20),biomass DECIMAL(10,2)); INSERT INTO fish_species (id,species,biomass) VALUES (1,'Salmon',5000.5),(2,'Tuna',7000.3); CREATE TABLE ocean (id INT,name VARCHAR(20),fish_id INT); INSERT INTO ocean (id,name,fish_id) VALUES (1,'Pacific',1),(2,'Atlantic',2); | SELECT SUM(fs.biomass) FROM fish_species fs INNER JOIN ocean o ON fs.id = o.fish_id WHERE o.name IN ('Pacific', 'Atlantic'); |
What is the total installed capacity (MW) of solar farms in Spain and Italy, grouped by country? | CREATE TABLE solar_farms (id INT,name TEXT,country TEXT,capacity FLOAT); INSERT INTO solar_farms (id,name,country,capacity) VALUES (1,'La Florida','Spain',150.2),(2,'Montalto','Italy',120.1),(3,'El Romero','Chile',246.6); | SELECT country, SUM(capacity) FROM solar_farms WHERE country IN ('Spain', 'Italy') GROUP BY country; |
Which regions have the most and least renewable energy projects in the projects and regions tables? | CREATE TABLE projects(id INT,project_name VARCHAR(50),project_type VARCHAR(50),country VARCHAR(50),region_id INT);CREATE TABLE regions(id INT,region_name VARCHAR(50),country VARCHAR(50)); | SELECT r.region_name, COUNT(p.id) AS num_projects FROM projects p INNER JOIN regions r ON p.region_id = r.id GROUP BY r.region_name ORDER BY num_projects DESC, region_name; |
How many renewable energy projects are there in the state of New York? | CREATE TABLE projects (state VARCHAR(30),project_type VARCHAR(30)); INSERT INTO projects (state,project_type) VALUES ('New York','Solar'),('New York','Wind'),('New York','Hydro'),('New York','Geothermal'); | SELECT COUNT(*) FROM projects WHERE state = 'New York'; |
What was the average number of hours volunteered by each volunteer in 2021? | CREATE TABLE VolunteerHours (Volunteer VARCHAR(50),Hours INT,VolunteerDate DATE); INSERT INTO VolunteerHours (Volunteer,Hours,VolunteerDate) VALUES ('John Smith',15,'2021-06-12'),('Jane Doe',10,'2021-10-03'); | SELECT Volunteer, AVG(Hours) as AvgHours FROM VolunteerHours WHERE VolunteerDate BETWEEN '2021-01-01' AND '2021-12-31' GROUP BY Volunteer; |
What is the maximum biomass of Trout farmed in Canadian flow-through systems? | CREATE TABLE canadian_farms (farmer_id INT,fish_species TEXT,farming_method TEXT,biomass FLOAT); INSERT INTO canadian_farms (farmer_id,fish_species,farming_method,biomass) VALUES (1,'Trout','Flow-through',150.5),(2,'Salmon','Recirculating aquaculture systems',300.1),(3,'Trout','Ponds',120.9); | SELECT MAX(biomass) FROM canadian_farms WHERE fish_species = 'Trout' AND farming_method = 'Flow-through'; |
How many mobile subscribers have each mobile device model? | CREATE TABLE mobile_subscribers_devices (subscriber_id INT,name VARCHAR(255),device_model VARCHAR(255)); INSERT INTO mobile_subscribers_devices (subscriber_id,name,device_model) VALUES (1,'John Doe','iPhone 12'),(2,'Jane Doe','iPhone 12'),(3,'Maria Garcia','Samsung Galaxy S21'); | SELECT device_model, COUNT(*) FROM mobile_subscribers_devices GROUP BY device_model; |
Identify the court locations and case numbers of all cases that were dismissed due to lack of evidence in the last 3 years. | CREATE TABLE CourtCases (Id INT,CourtLocation VARCHAR(50),CaseNumber INT,Disposition VARCHAR(50),DismissalDate DATE); INSERT INTO CourtCases (Id,CourtLocation,CaseNumber,Disposition,DismissalDate) VALUES (1,'NY Supreme Court',12345,'Dismissed','2021-02-15'),(2,'TX District Court',67890,'Proceeding','2020-12-21'),(3,'CA Superior Court',23456,'Dismissed','2019-08-01'); | SELECT CourtLocation, CaseNumber FROM CourtCases WHERE Disposition = 'Dismissed' AND DismissalDate >= DATEADD(year, -3, GETDATE()) AND Disposition = 'Dismissed'; |
Calculate the average accommodation cost for students with visual impairments in the "accommodations" table | CREATE TABLE accommodations (id INT,student_id INT,accommodation_type VARCHAR(255),cost FLOAT); INSERT INTO accommodations (id,student_id,accommodation_type,cost) VALUES (1,123,'visual_aids',250.0),(2,456,'visual_aids',250.0),(3,789,'large_print_materials',120.0); | SELECT AVG(cost) FROM accommodations WHERE accommodation_type = 'visual_aids'; |
Delete all attractions in Sydney with a rating below 3.5. | CREATE TABLE attractions (id INT,name VARCHAR(50),city VARCHAR(20),rating FLOAT); INSERT INTO attractions (id,name,city,rating) VALUES (1,'Opera House','Sydney',4.6),(2,'Bridge','Sydney',3.8),(3,'Tower','New York',4.8); | DELETE FROM attractions WHERE city = 'Sydney' AND rating < 3.5; |
What is the number of employees in the 'technology' industry? | CREATE TABLE if not exists employment (id INT,industry VARCHAR,number_of_employees INT); INSERT INTO employment (id,industry,number_of_employees) VALUES (1,'manufacturing',5000),(2,'technology',8000),(3,'healthcare',7000); | SELECT SUM(number_of_employees) FROM employment WHERE industry = 'technology'; |
What is the total water usage for residential and industrial purposes in Illinois in the year 2022? | CREATE TABLE WaterUsageMetrics (UsageID INT PRIMARY KEY,Location VARCHAR(255),Usage INT,UsageType VARCHAR(255),Timestamp DATETIME); INSERT INTO WaterUsageMetrics (UsageID,Location,Usage,UsageType,Timestamp) VALUES (1,'Illinois',500,'Residential','2022-01-01 00:00:00'),(2,'Illinois',800,'Industrial','2022-01-01 00:00:00'); | SELECT UsageType, SUM(Usage) FROM WaterUsageMetrics WHERE Location = 'Illinois' AND YEAR(Timestamp) = 2022 GROUP BY UsageType HAVING UsageType IN ('Residential', 'Industrial'); |
What is the minimum speed of vessels with 'CMA' prefix that had any accidents in the South China Sea in 2016? | CREATE TABLE Vessels (ID INT,Name TEXT,Speed FLOAT,Accidents INT,Prefix TEXT,Year INT);CREATE VIEW South_China_Sea_Vessels AS SELECT * FROM Vessels WHERE Region = 'South China Sea'; | SELECT MIN(Speed) FROM South_China_Sea_Vessels WHERE Prefix = 'CMA' AND Accidents > 0; |
Find the total number of community policing events in 2020, grouped by quarter | CREATE TABLE community_policing (id INT,event_date DATE,event_type VARCHAR(20)); INSERT INTO community_policing (id,event_date,event_type) VALUES (1,'2020-01-01','Meeting'),(2,'2020-01-15','Patrol'),(3,'2020-04-01','Meeting'),(4,'2020-07-01','Workshop'); | SELECT EXTRACT(QUARTER FROM event_date) as quarter, COUNT(*) as total_events FROM community_policing WHERE event_date BETWEEN '2020-01-01' AND '2020-12-31' AND event_type = 'Community Policing' GROUP BY EXTRACT(QUARTER FROM event_date); |
What is the average number of publications per year for graduate students in the Biology department? | CREATE TABLE graduate_students (id INT,name VARCHAR(50),department VARCHAR(50),enrollment_date DATE); CREATE TABLE publications (id INT,student_id INT,title VARCHAR(100),publication_date DATE); | SELECT student_id, AVG(DATEDIFF(publication_date, enrollment_date)/365) AS avg_publications_per_year FROM graduate_students gs JOIN publications p ON gs.id = p.student_id WHERE department = 'Biology' GROUP BY student_id; |
Which mines have a higher total production compared to the mine with id 2? | CREATE TABLE mining_operations (id INT,mine_name VARCHAR(255),location VARCHAR(255),extraction_type VARCHAR(255),production INT); INSERT INTO mining_operations (id,mine_name,location,extraction_type,production) VALUES (1,'Copper Mine','Arizona,USA','Open Pit',12000),(2,'Gold Mine','Ontario,Canada','Underground',5000),(3,'Iron Mine','Minnesota,USA','Open Pit',32000),(4,'Gold Mine 2','Quebec,Canada','Underground',6000),(5,'Emerald Mine','Boyaca,Colombia','Open Pit',3000); | SELECT mine_name, SUM(production) as total_production FROM mining_operations WHERE SUM(production) > (SELECT SUM(production) FROM mining_operations WHERE id = 2) GROUP BY mine_name; |
What's the average age of players who prefer RPG games? | CREATE TABLE player_demographics (player_id INT,age INT,favorite_genre VARCHAR(20)); INSERT INTO player_demographics (player_id,age,favorite_genre) VALUES (1,25,'Action'),(2,30,'RPG'),(3,22,'Action'),(4,35,'Simulation'); | SELECT AVG(age) FROM player_demographics WHERE favorite_genre = 'RPG'; |
List all chemical batches that have been produced using an unapproved chemical compound in the past month. | CREATE TABLE chemical_batches (batch_id INT,compound_id INT,production_date DATE); CREATE TABLE chemical_compounds (compound_id INT,approved_flag BOOLEAN); | SELECT chemical_batches.batch_id FROM chemical_batches INNER JOIN chemical_compounds ON chemical_batches.compound_id = chemical_compounds.compound_id WHERE chemical_compounds.approved_flag = FALSE AND chemical_batches.production_date > DATEADD(month, -1, GETDATE()); |
What is the average age of players who have played more than 200 games? | CREATE TABLE Players (PlayerID INT,PlayerName VARCHAR(50),Age INT,Country VARCHAR(50),GamesPlayed INT); INSERT INTO Players (PlayerID,PlayerName,Age,Country,GamesPlayed) VALUES (1,'John Doe',25,'USA',100); INSERT INTO Players (PlayerID,PlayerName,Age,Country,GamesPlayed) VALUES (2,'Jane Smith',30,'Canada',200); INSERT INTO Players (PlayerID,PlayerName,Age,Country,GamesPlayed) VALUES (3,'Taro Yamada',24,'Japan',250); INSERT INTO Players (PlayerID,PlayerName,Age,Country,GamesPlayed) VALUES (4,'Sachiko Tanaka',28,'Japan',150); | SELECT AVG(Age) FROM Players WHERE GamesPlayed > 200; |
What is the total waste generated by residential sectors in the city of San Francisco in 2020? | CREATE TABLE waste_generation (id INT,sector VARCHAR(20),location VARCHAR(20),amount DECIMAL(10,2),date DATE); INSERT INTO waste_generation (id,sector,location,amount,date) VALUES (1,'residential','San Francisco',500,'2020-01-01'); | SELECT SUM(amount) FROM waste_generation WHERE sector = 'residential' AND location = 'San Francisco' AND date = '2020-01-01'; |
What is the average fine amount for cases that went to trial? | CREATE TABLE cases (id INT,trial_date DATE,fine_amount DECIMAL(10,2)); INSERT INTO cases (id,trial_date,fine_amount) VALUES (1,'2021-03-23',5000),(2,'2021-04-15',10000); | SELECT AVG(fine_amount) FROM cases WHERE trial_date IS NOT NULL; |
What is the average media literacy score for content creators in the United States, grouped by age? | CREATE TABLE content_creators (creator_id INT,age INT,country VARCHAR(50),media_literacy_score INT); INSERT INTO content_creators (creator_id,age,country,media_literacy_score) VALUES (1,25,'USA',85),(2,32,'Canada',80),(3,45,'USA',90); | SELECT age, AVG(media_literacy_score) as avg_score FROM content_creators WHERE country = 'USA' GROUP BY age; |
Determine the percentage of consumers who dislike a specific product. | CREATE TABLE ConsumerPreference (id INT,consumer_id INT,product_id INT,preference VARCHAR(255)); INSERT INTO ConsumerPreference (id,consumer_id,product_id,preference) VALUES (1,1,1,'Likes'),(2,1,2,'Likes'),(3,2,1,'Dislikes'),(4,2,2,'Likes'),(5,3,1,'Likes'),(6,3,2,'Dislikes'),(7,4,1,'Likes'),(8,4,2,'Likes'),(9,5,1,'Likes'),(10,5,2,'Dislikes'),(11,6,1,'Dislikes'),(12,6,2,'Dislikes'); | SELECT product_id, ROUND(100.0 * SUM(CASE WHEN preference = 'Dislikes' THEN 1 ELSE 0 END) / COUNT(*), 2) as preference_percentage FROM ConsumerPreference GROUP BY product_id HAVING product_id = 2; |
What is the average rating of hotels in the europe schema? | CREATE SCHEMA europe; CREATE TABLE europe.hotels (hotel_id INT,hotel_name VARCHAR(50),rating DECIMAL(2,1),price INT); | SELECT AVG(rating) FROM europe.hotels; |
How many primary and secondary schools are there in Afghanistan, ordered by school type? | CREATE TABLE Afghanistan (id INT,name TEXT,type TEXT,location TEXT); INSERT INTO Afghanistan (id,name,type,location) VALUES (1,'School A','Primary','Kabul'); INSERT INTO Afghanistan (id,name,type,location) VALUES (2,'School B','Secondary','Kandahar'); INSERT INTO Afghanistan (id,name,type,location) VALUES (3,'School C','Primary','Herat'); | SELECT type, COUNT(*) AS school_count FROM Afghanistan GROUP BY type ORDER BY type; |
What are the national security budgets for the last 5 years? | CREATE TABLE national_security_budgets (id INT,year INT,budget DECIMAL(10,2)); INSERT INTO national_security_budgets (id,year,budget) VALUES (1,2018,6000000000),(2,2019,7000000000),(3,2020,8000000000),(4,2021,9000000000); | SELECT year, budget FROM national_security_budgets; |
What are the names and ranks of military personnel with a security clearance level of 'Top Secret' or higher in the 'Special Forces' division? | CREATE TABLE Personnel (id INT,name VARCHAR(50),rank VARCHAR(20),department VARCHAR(20),division VARCHAR(20)); INSERT INTO Personnel (id,name,rank,department,division) VALUES (1,'John Doe','Captain','Intelligence','Special Forces'),(2,'Jane Smith','Lieutenant','Intelligence','Special Forces'),(3,'Alice Johnson','Colonel','Military','Army'),(4,'Bob Brown','Petty Officer','Navy','Navy'); CREATE TABLE ClearanceLevels (id INT,level VARCHAR(20)); INSERT INTO ClearanceLevels (id,level) VALUES (1,'Secret'),(2,'Top Secret'),(3,'Confidential'),(4,'Top Secret Plus'); CREATE TABLE PersonnelClearances (personnel_id INT,clearance_id INT); INSERT INTO PersonnelClearances (personnel_id,clearance_id) VALUES (1,2),(2,4),(3,1),(4,1); | SELECT p.name, p.rank FROM Personnel p INNER JOIN PersonnelClearances pc ON p.id = pc.personnel_id INNER JOIN ClearanceLevels cl ON pc.clearance_id = cl.id WHERE p.division = 'Special Forces' AND cl.level IN ('Top Secret', 'Top Secret Plus'); |
What is the average temperature of the reactors in the past week? | CREATE TABLE ReactorTemperatures (ReactorID INT,Temperature DECIMAL(5,2),Timestamp DATETIME); | SELECT AVG(Temperature) FROM ReactorTemperatures WHERE Timestamp BETWEEN DATE_SUB(CURRENT_DATE(), INTERVAL 1 WEEK) AND CURRENT_DATE(); |
What is the infection rate of TB in Texas compared to California? | CREATE TABLE infections (id INT,disease TEXT,location TEXT,cases INT); INSERT INTO infections (id,disease,location,cases) VALUES (1,'TB','Texas',50); INSERT INTO infections (id,disease,location,cases) VALUES (2,'TB','California',75); | SELECT (infections.cases/populations.population)*100000 AS 'TX infection rate', (infections.cases/populations.population)*100000 AS 'CA infection rate' FROM infections INNER JOIN populations ON 1=1 WHERE infections.disease = 'TB' AND infections.location IN ('Texas', 'California'); |
How many suppliers are there for each material type in the 'Asia-Pacific' region? | CREATE TABLE TextileSourcing (SupplierID INT,Material VARCHAR(255),Region VARCHAR(255)); INSERT INTO TextileSourcing (SupplierID,Material,Region) VALUES (1,'Cotton','Asia-Pacific'),(2,'Polyester','Asia-Pacific'),(3,'Wool','Oceania'),(4,'Silk','Asia-Pacific'),(5,'Linen','Europe'); | SELECT Material, COUNT(*) FROM TextileSourcing WHERE Region = 'Asia-Pacific' GROUP BY Material; |
Which systems have been offline for more than 5 days in the 'Finance' department? | CREATE TABLE system_status (system_id INT PRIMARY KEY,status_date DATE,is_online BOOLEAN,department VARCHAR(50)); INSERT INTO system_status (system_id,status_date,is_online,department) VALUES (1,'2022-04-01',TRUE,'Finance'),(2,'2022-04-10',FALSE,'Finance'),(3,'2022-04-15',FALSE,'Finance'),(4,'2022-04-20',FALSE,'Finance'); | SELECT system_id, status_date FROM system_status WHERE is_online = FALSE AND department = 'Finance' AND status_date < DATE_SUB(CURRENT_DATE, INTERVAL 5 DAY); |
Calculate the total population of caribou and musk oxen in each Arctic country. | CREATE TABLE Biodiversity (id INT PRIMARY KEY,species VARCHAR(255),location VARCHAR(255),population INT); INSERT INTO Biodiversity (id,species,location,population) VALUES (1,'caribou','Canada',30000); INSERT INTO Biodiversity (id,species,location,population) VALUES (2,'musk oxen','Greenland',15000); | SELECT location, SUM(CASE WHEN species IN ('caribou', 'musk oxen') THEN population ELSE 0 END) as total_population FROM Biodiversity GROUP BY location; |
List all missions that have utilized jet engines, and provide the number of aircraft and satellites associated with each mission type. | CREATE TABLE Mission_Engines (Mission_ID INT,Engine_ID INT,FOREIGN KEY (Mission_ID) REFERENCES Satellites(Satellite_ID),FOREIGN KEY (Engine_ID) REFERENCES Engines(Engine_ID)); INSERT INTO Mission_Engines (Mission_ID,Engine_ID) VALUES (1,1); INSERT INTO Mission_Engines (Mission_ID,Engine_ID) VALUES (2,2); | SELECT S.Mission_Type, E.Fuel_Type, COUNT(DISTINCT S.Satellite_ID) AS Satellites_Count, COUNT(DISTINCT A.Aircraft_ID) AS Aircraft_Count FROM Satellites S INNER JOIN Mission_Engines ME ON S.Satellite_ID = ME.Mission_ID INNER JOIN Engines E ON ME.Engine_ID = E.Engine_ID LEFT JOIN Aircraft A ON E.Manufacturer_ID = A.Manufacturer_ID WHERE E.Fuel_Type = 'Jet' GROUP BY S.Mission_Type, E.Fuel_Type; |
Update the team name for the given team id | CREATE TABLE teams (id INT,name VARCHAR(50),sport VARCHAR(50)); INSERT INTO teams (id,name,sport) VALUES (1,'Red Bulls','Soccer'),(2,'Lakers','Basketball'); | UPDATE teams SET name = 'New York Red Bulls' WHERE id = 1; |
Which countries have the most vessels in the vessels table? | CREATE TABLE vessels (id INT,name VARCHAR(255),country VARCHAR(255),capacity INT); | SELECT country, COUNT(*) as vessel_count FROM vessels GROUP BY country ORDER BY vessel_count DESC; |
Show recycling rates for the 'Northwest' region's cities. | CREATE TABLE Cities (id INT,city VARCHAR(255),region VARCHAR(255)); INSERT INTO Cities (id,city,region) VALUES (1,'Portland','Northwest'),(2,'Seattle','Northwest'),(3,'Eugene','Northwest'); CREATE TABLE RecyclingRates (id INT,city VARCHAR(255),recycling_rate FLOAT); INSERT INTO RecyclingRates (id,city,recycling_rate) VALUES (1,'Portland',60.5),(2,'Seattle',65.3),(3,'Eugene',55.1); | SELECT Cities.city, AVG(RecyclingRates.recycling_rate) FROM Cities JOIN RecyclingRates ON Cities.city = RecyclingRates.city WHERE Cities.region = 'Northwest' GROUP BY Cities.city; |
What is the total production of gadolinium in India and Pakistan combined for the last 5 years? | CREATE TABLE gadolinium_production (year INT,country TEXT,production_quantity INT); INSERT INTO gadolinium_production (year,country,production_quantity) VALUES (2017,'India',1200),(2018,'India',1500),(2019,'India',1700),(2020,'India',2000),(2021,'India',2200),(2017,'Pakistan',800),(2018,'Pakistan',900),(2019,'Pakistan',1000),(2020,'Pakistan',1200),(2021,'Pakistan',1400); | SELECT SUM(production_quantity) FROM gadolinium_production WHERE country IN ('India', 'Pakistan') AND year >= 2017 AND year <= 2021; |
How many unique visitors attended events at Library A in 2022? | CREATE TABLE LibraryA (id INT,name VARCHAR(255),visitor_id INT,event_date DATE); INSERT INTO LibraryA (id,name,visitor_id,event_date) VALUES (1,'Library A',1,'2022-01-10'),(2,'Library A',2,'2022-01-10'),(3,'Library A',3,'2022-03-15'); | SELECT COUNT(DISTINCT visitor_id) FROM LibraryA WHERE YEAR(event_date) = 2022; |
List the names of all machines that were purchased in the year 2020 and are located in the 'Warehouse' facility. | CREATE TABLE Machines (MachineID INT,MachineName VARCHAR(50),PurchaseDate DATE,Location VARCHAR(50)); INSERT INTO Machines (MachineID,MachineName,PurchaseDate,Location) VALUES (1,'MachineA','2019-01-01','Warehouse'),(2,'MachineB','2020-05-15','Factory'),(3,'MachineC','2021-03-03','Warehouse'); | SELECT MachineName FROM Machines WHERE PurchaseDate BETWEEN '2020-01-01' AND '2020-12-31' AND Location = 'Warehouse'; |
Find the average temperature in Greenland's Scoresby Sund | CREATE TABLE TemperatureData (location VARCHAR(50),year INT,temperature FLOAT); INSERT INTO TemperatureData (location,year,temperature) VALUES ('Scoresby Sund',2000,0.5),('Scoresby Sund',2001,1.3),('Scoresby Sund',2002,0.9); | SELECT location, AVG(temperature) FROM TemperatureData GROUP BY location; |
What is the total playtime of player 'Olivia'? | 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',100); | SELECT SUM(playtime) FROM player_sessions WHERE player_name = 'Olivia'; |
Insert a new research grant record | CREATE TABLE ResearchGrants (GrantID INT,ProfessorID INT,Title VARCHAR(50),Amount DECIMAL(10,2)); | INSERT INTO ResearchGrants (GrantID, ProfessorID, Title, Amount) VALUES (1, 1001, 'New Grant', 50000.00); |
How many items are made from recycled materials? | CREATE TABLE items (id INT,name VARCHAR(50),material VARCHAR(50)); INSERT INTO items (id,name,material) VALUES (1,'Tote Bag','recycled cotton'),(2,'Hoodie','organic cotton'),(3,'Backpack','recycled polyester'); | SELECT COUNT(*) FROM items WHERE material LIKE '%recycled%'; |
What are the average points scored by players from the United Kingdom in each season? | CREATE TABLE players (player_id INT,name TEXT,nationality TEXT,points INT,season INT); INSERT INTO players (player_id,name,nationality,points,season) VALUES (1,'Charlie Brown','United Kingdom',400,2018),(2,'David Wilson','United Kingdom',500,2019); | SELECT season, AVG(points) FROM players WHERE nationality = 'United Kingdom' GROUP BY season; |
What is the total spending by players from Asia in the 'gaming_facts' table? | CREATE TABLE gaming_facts (player_id INT,country VARCHAR(50),total_spending FLOAT); INSERT INTO gaming_facts (player_id,country,total_spending) VALUES (1,'USA',450.25),(2,'Canada',520.35),(3,'China',420.65),(4,'Japan',375.89); | SELECT SUM(total_spending) as total_asia_spending FROM gaming_facts WHERE country IN ('China', 'Japan'); |
What is the maximum safe temperature for each chemical used in a specific product? | CREATE TABLE Chemicals (id INT,name VARCHAR(255),max_safe_temp FLOAT); CREATE TABLE Products (id INT,product_name VARCHAR(255),chemical_id INT); | SELECT Products.product_name, Chemicals.name, Chemicals.max_safe_temp FROM Products INNER JOIN Chemicals ON Products.chemical_id = Chemicals.id WHERE Products.product_name = 'Solvents'; |
What was the maximum flight time for aircrafts manufactured by 'Boeing' in the year 2018? | CREATE SCHEMA Boeing; CREATE TABLE Boeing.FlightTime (flight_time INT,year INT); INSERT INTO Boeing.FlightTime (flight_time,year) VALUES (120,2020),(150,2019),(180,2018),(130,2017); | SELECT MAX(flight_time) FROM Boeing.FlightTime WHERE year = 2018; |
List the names of all the crops grown in the 'agroecological' farming systems. | CREATE TABLE crops (id INT,name VARCHAR(20),farming_system VARCHAR(20)); | SELECT crops.name FROM crops WHERE crops.farming_system = 'agroecological'; |
What is the total number of animals in the entire database, and how many different species are there? | CREATE TABLE animal_species (species VARCHAR(255),animal_count INT); INSERT INTO animal_species (species,animal_count) VALUES ('Lion',1200),('Tiger',1500),('Jaguar',1800),('Grizzly Bear',900),('Elephant',2000),('Giraffe',1700); | SELECT SUM(animal_count) as total_count FROM animal_species; SELECT COUNT(DISTINCT species) as num_species FROM animal_species; |
What is the average nitrogen, phosphorus, and potassium levels for each crop type in the past month? | CREATE TABLE crop_nutrients (id INT,crop_id INT,type VARCHAR(255),nitrogen FLOAT,phosphorus FLOAT,potassium FLOAT,timestamp DATETIME); | SELECT type, AVG(nitrogen) as avg_nitrogen, AVG(phosphorus) as avg_phosphorus, AVG(potassium) as avg_potassium FROM crop_nutrients WHERE timestamp >= DATE_SUB(CURRENT_TIMESTAMP, INTERVAL 1 MONTH) GROUP BY type; |
What is the total number of games played by players from each country, and how many countries are represented? | CREATE TABLE Players (PlayerID INT,Age INT,Country VARCHAR(20)); INSERT INTO Players (PlayerID,Age,Country) VALUES (1,25,'USA'),(2,30,'Canada'),(3,22,'Mexico'),(4,35,'Brazil'); CREATE TABLE GameLibrary (GameID INT,PlayerID INT,Country VARCHAR(20)); INSERT INTO GameLibrary (GameID,PlayerID,Country) VALUES (1,1,'USA'),(2,1,'USA'),(3,2,'Canada'),(4,3,'Mexico'),(5,3,'Mexico'),(6,4,'Brazil'); | SELECT Country, COUNT(DISTINCT GameLibrary.PlayerID) AS GamesPlayed FROM GameLibrary GROUP BY Country; SELECT COUNT(DISTINCT Country) FROM GameLibrary; |
Insert a new hotel with sustainable practices into the hotels table | CREATE TABLE hotels (id INT PRIMARY KEY,name VARCHAR(255),country VARCHAR(255)); CREATE TABLE sustainable_practices (id INT PRIMARY KEY,hotel_id INT,practice VARCHAR(255)); INSERT INTO hotels (id,name,country) VALUES (1,'Eco-Friendly Hotel','Sweden'); INSERT INTO sustainable_practices (id,hotel_id,practice) VALUES (1,1,'Recycling program'); | INSERT INTO hotels (id, name, country) VALUES (2, 'Sustainable Resort', 'Costa Rica'); INSERT INTO sustainable_practices (id, hotel_id, practice) VALUES (2, 2, 'Solar power'); |
What is the maximum number of papers published by a graduate student in the Electrical Engineering department? | CREATE TABLE graduate_students (id INT,name VARCHAR(50),department VARCHAR(50),num_papers INT); INSERT INTO graduate_students (id,name,department,num_papers) VALUES (1,'Eve','Electrical Engineering',8); INSERT INTO graduate_students (id,name,department,num_papers) VALUES (2,'Frank','Mechanical Engineering',5); | SELECT MAX(num_papers) FROM graduate_students WHERE department = 'Electrical Engineering'; |
Show the number of unique chemicals produced in 2020 | CREATE TABLE yearly_production (chemical VARCHAR(20),year INT); INSERT INTO yearly_production (chemical,year) VALUES ('Eco-friendly Polymer',2019),('Nano Polymer',2019),('Smart Polymer',2019),('Carbon Nanotube',2019),('Graphene',2019),('Buckyball',2019),('Eco-friendly Polymer',2020),('Nano Polymer',2020),('Smart Polymer',2020),('Carbon Nanotube',2020),('Graphene',2020),('Buckyball',2020); | SELECT COUNT(DISTINCT chemical) FROM yearly_production WHERE year = 2020; |
How many accessible taxi trips were there in the 'east' region in January 2022? | CREATE TABLE taxi_trips (trip_id INT,region_id INT,trip_date DATE,is_accessible BOOLEAN); INSERT INTO taxi_trips (trip_id,region_id,trip_date,is_accessible) VALUES (1,1,'2022-01-01',true),(2,2,'2022-01-02',false),(3,3,'2022-01-03',true),(4,2,'2022-01-04',false); | SELECT COUNT(*) FROM taxi_trips t WHERE t.region_id = (SELECT region_id FROM regions WHERE region_name = 'east') AND t.trip_date BETWEEN '2022-01-01' AND '2022-01-31' AND t.is_accessible = true; |
What is the latest processing time for satellite images? | CREATE TABLE satellite_images (id INT,image_url VARCHAR(255),location VARCHAR(255),processing_time DATETIME); INSERT INTO satellite_images (id,image_url,location,processing_time) VALUES (1,'image1.jpg','field1','2022-01-01 12:00:00'),(2,'image2.jpg','field2','2022-01-01 13:00:00'); | SELECT MAX(processing_time) FROM satellite_images; |
Calculate the total revenue generated by each artist on a daily basis. | CREATE TABLE artists (artist_id INT,artist_name VARCHAR(255)); CREATE TABLE songs (song_id INT,title VARCHAR(255),genre_id INT,release_date DATE,artist_id INT); CREATE TABLE streams (stream_id INT,song_id INT,user_id INT,stream_date DATE,revenue DECIMAL(10,2)); | SELECT a.artist_name, stream_date, SUM(s.revenue) as daily_revenue FROM artists a JOIN songs s ON a.artist_id = s.artist_id JOIN streams st ON s.song_id = st.song_id GROUP BY a.artist_name, stream_date; |
Update the donation amount to 200.00 for donor 'Carlos Garcia' from Mexico in the year 2020. | CREATE TABLE Donors (id INT,name TEXT,country TEXT,donation_amount DECIMAL(10,2),donation_date DATE); INSERT INTO Donors (id,name,country,donation_amount,donation_date) VALUES (1,'John Doe','India',100.00,'2021-01-01'); INSERT INTO Donors (id,name,country,donation_amount,donation_date) VALUES (2,'Jane Smith','India',200.00,'2021-04-15'); INSERT INTO Donors (id,name,country,donation_amount,donation_date) VALUES (3,'Alice Johnson','Australia',150.00,'2021-05-05'); INSERT INTO Donors (id,name,country,donation_amount,donation_date) VALUES (4,'Carlos Garcia','Mexico',250.00,'2020-07-10'); | UPDATE Donors SET donation_amount = 200.00 WHERE name = 'Carlos Garcia' AND country = 'Mexico' AND YEAR(donation_date) = 2020; |
What is the average sustainability score for each textile material? | CREATE TABLE TextileSources (SourceID INT,Country VARCHAR(255),Material VARCHAR(255),SustainabilityScore INT); INSERT INTO TextileSources (SourceID,Country,Material,SustainabilityScore) VALUES (1,'India','Cotton',85),(2,'Brazil','Rayon',70); | SELECT Material, AVG(SustainabilityScore) AS AvgSustainabilityScore FROM TextileSources GROUP BY Material; |
Calculate the year-over-year growth in sales for each garment, partitioned by category and ordered by date. | CREATE TABLE sales (garment VARCHAR(50),category VARCHAR(50),quantity INT,sale_date DATE); INSERT INTO sales (garment,category,quantity,sale_date) VALUES ('Shirt','Tops',15,'2021-01-05'),('Pants','Bottoms',20,'2021-01-05'),('Dress','Tops',30,'2021-01-10'),('Shirt','Tops',20,'2022-01-05'),('Pants','Bottoms',25,'2022-01-05'),('Dress','Tops',40,'2022-01-10'); | SELECT garment, category, sale_date, (quantity - LAG(quantity) OVER (PARTITION BY category, garment ORDER BY sale_date)) * 100.0 / LAG(quantity) OVER (PARTITION BY category, garment ORDER BY sale_date) as yoy_growth FROM sales; |
Identify the number of employees who have not received diversity and inclusion training, and list them by their last name in ascending order. | CREATE TABLE Employees (EmployeeID INT,LastName VARCHAR(50),Training VARCHAR(50)); CREATE TABLE Training (TrainingID INT,TrainingName VARCHAR(50)); | SELECT e.LastName, COUNT(*) AS NoTrainingCount FROM Employees e LEFT JOIN Training t ON e.Training = t.TrainingName WHERE t.Training IS NULL GROUP BY e.LastName ORDER BY LastName ASC; |
Which countries have implemented the most maritime safety measures in the past 5 years? | CREATE TABLE maritime_safety_measures (country VARCHAR(255),year INT,measure_type VARCHAR(255)); | SELECT country, COUNT(*) FROM maritime_safety_measures WHERE year BETWEEN 2016 AND 2021 GROUP BY country ORDER BY COUNT(*) DESC; |
What is the total number of military vehicles in service with the Australian Army, along with their types and ages? | CREATE TABLE military_vehicles (vehicle_id INT,army_branch VARCHAR(255),vehicle_type VARCHAR(255),acquisition_date DATE); INSERT INTO military_vehicles (vehicle_id,army_branch,vehicle_type,acquisition_date) VALUES (1,'Australian Army','Armored Personnel Carrier','2015-01-01'); INSERT INTO military_vehicles (vehicle_id,army_branch,vehicle_type,acquisition_date) VALUES (2,'Australian Army','Tank','2018-05-15'); | SELECT vehicle_type, DATEDIFF(CURDATE(), acquisition_date) AS age_in_days FROM military_vehicles WHERE army_branch = 'Australian Army'; |
Insert a new record into the 'production_data' table with ID '001', mine_id 'Mine_003', production_rate '1500', and production_year '2020' | CREATE TABLE production_data (id VARCHAR(10),mine_id VARCHAR(10),production_rate INT,production_year INT); | INSERT INTO production_data (id, mine_id, production_rate, production_year) VALUES ('001', 'Mine_003', 1500, 2020); |
What is the maximum depth in the oceanography table? | CREATE TABLE oceanography (id INT,location TEXT,depth FLOAT); INSERT INTO oceanography (id,location,depth) VALUES (1,'Mariana Trench',10994.0),(2,'Southern Ocean',7280.0),(3,'Pacific Ocean',3600.0); | SELECT MAX(depth) FROM oceanography; |
What is the average research funding for astrophysics research conducted in 'North America'? | CREATE TABLE ResearchFunding (id INT,research_type VARCHAR(50),location VARCHAR(50),funding DECIMAL(10,2)); INSERT INTO ResearchFunding (id,research_type,location,funding) VALUES (1,'Astrophysics','North America',5000000.00),(2,'Particle Physics','Europe',4000000.00); | SELECT AVG(funding) FROM ResearchFunding WHERE research_type = 'Astrophysics' AND location = 'North America'; |
What is the total number of accommodations provided in the Fall semester, and the total number of accommodations provided in the Spring semester? | CREATE TABLE FallAccommodations (AccommodationDate DATE); INSERT INTO FallAccommodations (AccommodationDate) VALUES ('2022-08-01'),('2022-09-01'),('2022-10-01'); CREATE TABLE SpringAccommodations (AccommodationDate DATE); INSERT INTO SpringAccommodations (AccommodationDate) VALUES ('2023-01-01'),('2023-02-01'),('2023-03-01'); | SELECT COUNT(*) FROM FallAccommodations WHERE EXTRACT(MONTH FROM AccommodationDate) BETWEEN 8 AND 12 UNION SELECT COUNT(*) FROM SpringAccommodations WHERE EXTRACT(MONTH FROM AccommodationDate) BETWEEN 1 AND 6; |
What is the average age of players who play VR games and are from the United States? | CREATE TABLE Players (PlayerID INT,Age INT,Country VARCHAR(50)); INSERT INTO Players (PlayerID,Age,Country) VALUES (1,25,'USA'),(2,30,'Canada'),(3,22,'USA'),(4,35,'Mexico'); CREATE TABLE GameLibrary (GameID INT,GameName VARCHAR(50),GameType VARCHAR(50)); INSERT INTO GameLibrary (GameID,GameName,GameType) VALUES (1,'GameA','VR'),(2,'GameB','Non-VR'),(3,'GameC','VR'); CREATE TABLE PlayerGameLibrary (PlayerID INT,GameID INT); INSERT INTO PlayerGameLibrary (PlayerID,GameID) VALUES (1,1),(2,2),(3,1),(4,3); | SELECT AVG(Players.Age) FROM Players JOIN PlayerGameLibrary ON Players.PlayerID = PlayerGameLibrary.PlayerID JOIN GameLibrary ON PlayerGameLibrary.GameID = GameLibrary.GameID WHERE Players.Country = 'USA' AND GameLibrary.GameType = 'VR'; |
What is the average distance of space debris generated by ROSCOSMOS from the Earth's center? | CREATE TABLE space_debris (id INT,name VARCHAR(50),type VARCHAR(50),source VARCHAR(50),location POINT); | SELECT AVG(DISTANCE(location, POINT(0, 0))) as average_distance FROM space_debris WHERE source = 'ROSCOSMOS'; |
Which items in the inventory have a quantity lower than the average quantity of items in the inventory? | CREATE TABLE inventory (item_id VARCHAR(10),item_name VARCHAR(20),quantity INT); INSERT INTO inventory (item_id,item_name,quantity) VALUES ('I001','Apples',100),('I002','Bananas',200),('I003','Cherries',150),('I004','Dates',50),('I005','Elderberries',75); | SELECT i.item_name, i.quantity FROM inventory i WHERE i.quantity < (SELECT AVG(quantity) FROM inventory); |
List the risk ratings for all companies in the 'finance' sector, in descending order. | CREATE TABLE companies_risk (id INT,sector VARCHAR(20),risk_rating VARCHAR(10)); INSERT INTO companies_risk (id,sector,risk_rating) VALUES (1,'finance','low'),(2,'finance','medium'),(3,'technology','high'); | SELECT sector, risk_rating FROM companies_risk WHERE sector = 'finance' ORDER BY risk_rating DESC; |
How many garments were manufactured for the 'Fall 2021' and 'Winter 2021' collections? | CREATE TABLE garment_manufacturing (collection VARCHAR(20),quantity INT); INSERT INTO garment_manufacturing (collection,quantity) VALUES ('Fall 2021',4000),('Winter 2021',5000); | SELECT collection, SUM(quantity) FROM garment_manufacturing WHERE collection IN ('Fall 2021', 'Winter 2021') GROUP BY collection; |
What is the average funding amount for startups founded by women, in the software industry, and have had at least one investment round? | CREATE TABLE company (id INT,name TEXT,industry TEXT,founder_gender TEXT); INSERT INTO company (id,name,industry,founder_gender) VALUES (1,'Acme Inc','Software','Female'); CREATE TABLE investment_rounds (id INT,company_id INT,funding_amount INT); INSERT INTO investment_rounds (id,company_id,funding_amount) VALUES (1,1,500000); | SELECT AVG(funding_amount) FROM company JOIN investment_rounds ON company.id = investment_rounds.company_id WHERE industry = 'Software' AND founder_gender = 'Female'; |
List the names of all countries that have a coastline along the Indian Ocean and have not enacted policies for marine conservation. | CREATE TABLE countries (id INT,name VARCHAR(255),coastline VARCHAR(50),policies VARCHAR(255)); INSERT INTO countries (id,name,coastline,policies) VALUES (1,'India','Indian Ocean','Yes'),(2,'Pakistan','Indian Ocean','No'); | SELECT name FROM countries WHERE coastline = 'Indian Ocean' AND policies = 'No'; |
What is the percentage of hotels that adopted AI in the last year? | CREATE TABLE ai_adoption_annually (hotel_id INT,hotel_name VARCHAR(255),ai_adopted INT,adoption_year INT); | SELECT (COUNT(CASE WHEN adoption_year = YEAR(GETDATE()) - 1 THEN 1 END) * 100.0 / COUNT(*)) FROM ai_adoption_annually; |
How many sustainable building permits have been issued in the West this year? | CREATE TABLE West_SBP (permit_id INT,location VARCHAR(20),permit_date DATE,is_sustainable INT); INSERT INTO West_SBP VALUES (2001,'CA','2022-02-15',1),(2002,'WA','2022-04-20',1),(2003,'OR','2022-06-05',0); | SELECT COUNT(permit_id) FROM West_SBP WHERE is_sustainable = 1 AND YEAR(permit_date) = YEAR(CURRENT_DATE()); |
Who is the top donor in India? | CREATE TABLE Donors (donor_id INT,donor_name TEXT,total_donated DECIMAL,country TEXT); | SELECT donor_name, total_donated FROM Donors WHERE country = 'India' ORDER BY total_donated DESC LIMIT 1; |
What is the total energy consumption (in TWh) for residential buildings in the United States, categorized by energy source, for the year 2020? | CREATE TABLE residential_buildings (id INT,country VARCHAR(2),energy_consumption FLOAT); INSERT INTO residential_buildings (id,country,energy_consumption) VALUES (1,'USA',900000),(2,'USA',1100000),(3,'USA',700000),(4,'USA',1300000); CREATE TABLE energy_source (id INT,source VARCHAR(20),residential_buildings_id INT); INSERT INTO energy_source (id,source,residential_buildings_id) VALUES (1,'Solar',1),(2,'Wind',2),(3,'Natural Gas',3),(4,'Coal',4); | SELECT e.source, SUM(rb.energy_consumption) as total_energy_consumption FROM residential_buildings rb JOIN energy_source e ON rb.id = e.residential_buildings_id WHERE rb.country = 'USA' AND YEAR(rb.timestamp) = 2020 GROUP BY e.source; |
Which products have been shipped to more than 50 customers? | CREATE TABLE Shipments (ShipmentId INT,WarehouseId INT,ProductId INT,Quantity INT,CustomerId INT); INSERT INTO Shipments (ShipmentId,WarehouseId,ProductId,Quantity,CustomerId) VALUES (5,3,3,1,101); INSERT INTO Shipments (ShipmentId,WarehouseId,ProductId,Quantity,CustomerId) VALUES (6,3,4,2,102); INSERT INTO Shipments (ShipmentId,WarehouseId,ProductId,Quantity,CustomerId) VALUES (7,4,3,3,103); | SELECT ProductId, COUNT(DISTINCT CustomerId) AS CustomerCount FROM Shipments GROUP BY ProductId HAVING CustomerCount > 50; |
What are the top 2 mobile subscribers in each country with the most calls? | CREATE TABLE mobile_subscribers (subscriber_id INT,country VARCHAR(50),calls INT); INSERT INTO mobile_subscribers (subscriber_id,country,calls) VALUES (1,'USA',200),(2,'Canada',300),(3,'Mexico',150),(4,'Brazil',400),(5,'USA',500),(6,'Canada',600),(7,'Germany',250),(8,'France',350); CREATE TABLE country_codes (country VARCHAR(50),code CHAR(2)); INSERT INTO country_codes (country,code) VALUES ('USA','US'),('Canada','CA'),('Mexico','MX'),('Brazil','BR'),('Germany','DE'),('France','FR'); | SELECT ms1.country, ms1.subscriber_id, ms1.calls FROM mobile_subscribers ms1 JOIN ( SELECT country, SUBSTRING(GROUP_CONCAT(subscriber_id ORDER BY calls DESC), 1, 2) AS top_subscribers FROM mobile_subscribers GROUP BY country ) ms2 ON ms1.country = ms2.country AND FIND_IN_SET(ms1.subscriber_id, ms2.top_subscribers) ORDER BY ms1.country; |
What is the average Gadolinium production for the top 2 producers in 2020 and 2021? | CREATE TABLE gadolinium_production (id INT,year INT,producer VARCHAR(255),gadolinium_prod FLOAT); INSERT INTO gadolinium_production (id,year,producer,gadolinium_prod) VALUES (1,2020,'China',123.4),(2,2020,'USA',234.5),(3,2020,'Australia',345.6),(4,2021,'China',456.7),(5,2021,'USA',567.8),(6,2021,'Australia',678.9); | SELECT AVG(gadolinium_prod) FROM (SELECT * FROM gadolinium_production WHERE year IN (2020, 2021) AND producer IN ('China', 'USA') ORDER BY gadolinium_prod DESC) WHERE rownum <= 2; |
Find total donations for each disaster type. | CREATE TABLE Donations (DonationID INT,DisasterType VARCHAR(25),Amount DECIMAL(10,2)); INSERT INTO Donations (DonationID,DisasterType,Amount) VALUES (1,'Earthquake',100.00),(2,'Flood',150.00); | SELECT DisasterType, SUM(Amount) as TotalDonations FROM Donations GROUP BY DisasterType; |
What is the minimum and maximum price of Cerium produced in each country during the last 3 years? | CREATE TABLE Cerium_Production (year INT,country TEXT,price FLOAT); INSERT INTO Cerium_Production (year,country,price) VALUES (2019,'China',20); INSERT INTO Cerium_Production (year,country,price) VALUES (2019,'China',25); INSERT INTO Cerium_Production (year,country,price) VALUES (2019,'USA',30); INSERT INTO Cerium_Production (year,country,price) VALUES (2020,'China',22); INSERT INTO Cerium_Production (year,country,price) VALUES (2020,'China',27); INSERT INTO Cerium_Production (year,country,price) VALUES (2020,'USA',32); INSERT INTO Cerium_Production (year,country,price) VALUES (2021,'China',24); INSERT INTO Cerium_Production (year,country,price) VALUES (2021,'China',29); INSERT INTO Cerium_Production (year,country,price) VALUES (2021,'USA',35); | SELECT country, MIN(price) as min_price, MAX(price) as max_price FROM Cerium_Production WHERE year BETWEEN 2019 AND 2021 GROUP BY country; |
What is the average quantity of 'Veggie Skewers' sold per day? | CREATE TABLE Daily_Menu_Sales(Date DATE,Menu_Item VARCHAR(30),Quantity INT); INSERT INTO Daily_Menu_Sales(Date,Menu_Item,Quantity) VALUES('2022-01-01','Veggie Skewers',10),('2022-01-02','Veggie Skewers',15); | SELECT AVG(Quantity) as Average_Quantity FROM Daily_Menu_Sales WHERE Menu_Item = 'Veggie Skewers'; |
How many policies were issued in the last quarter in New York? | CREATE TABLE policies (id INT,policyholder_id INT,policy_type TEXT,issue_date DATE,expiry_date DATE); INSERT INTO policies (id,policyholder_id,policy_type,issue_date,expiry_date) VALUES (1,3,'Life','2021-01-01','2022-01-01'),(2,4,'Health','2021-02-01','2022-02-01'),(3,5,'Auto','2021-03-01','2022-03-01'); | SELECT COUNT(policies.id) FROM policies WHERE policies.issue_date >= '2021-04-01' AND policies.issue_date < '2021-07-01' AND policies.state = 'New York'; |
Insert new record '2022-04-01' for 'community_policing' table | CREATE TABLE community_policing (id INT,date DATE,outreach_hours INT,PRIMARY KEY(id)); | INSERT INTO community_policing (id, date, outreach_hours) VALUES (2, '2022-04-01', 3); |
What was the maximum and minimum investment in rural infrastructure for each year? | CREATE TABLE RuralInfrastructure (year INT,location VARCHAR(50),investment FLOAT); | SELECT year, MAX(investment) as max_investment, MIN(investment) as min_investment FROM RuralInfrastructure GROUP BY year; |
Find the total number of news articles that contain the word 'politics' in the title. | CREATE TABLE news_agency (name VARCHAR(255),location VARCHAR(255));CREATE TABLE article (id INT,title VARCHAR(255),agency VARCHAR(255)); INSERT INTO news_agency (name,location) VALUES ('ABC News','New York'),('CNN','Atlanta'),('Fox News','New York'); INSERT INTO article (id,title,agency) VALUES (1,'Politics Update','CNN'),(2,'Local News','Fox News'),(3,'Politics and Economy','ABC News'); | SELECT COUNT(*) FROM article WHERE title LIKE '%politics%'; |
What is the minimum salary for educators in the 'school_database' database? | CREATE TABLE educators (id INT,name VARCHAR(50),salary DECIMAL(10,2)); INSERT INTO educators (id,name,salary) VALUES (1,'Dave',60000.00),(2,'Eve',65000.00),(3,'Frank',55000.00); | SELECT MIN(salary) FROM educators WHERE name = 'educator'; |
What is the average number of daily smart contract deployments on the Stellar network in 2022? | CREATE TABLE stellar_smart_contracts (contract_address VARCHAR(42),creation_timestamp TIMESTAMP); | SELECT AVG(num_deployments) AS avg_daily_deployments FROM (SELECT DATE_FORMAT(creation_timestamp, '%Y-%m-%d') AS tx_date, COUNT(*) AS num_deployments FROM stellar_smart_contracts WHERE creation_timestamp >= '2022-01-01 00:00:00' AND creation_timestamp < '2023-01-01 00:00:00' GROUP BY tx_date) subquery; |
Find the difference between the highest and lowest water consumption per household in the city of Los Angeles. | CREATE TABLE water_consumption (household_id INT,consumption FLOAT,city VARCHAR(50)); INSERT INTO water_consumption (household_id,consumption,city) VALUES (1,12.5,'Los Angeles'),(2,13.7,'Los Angeles'),(3,11.0,'Los Angeles'); | SELECT city, MAX(consumption) - MIN(consumption) AS diff FROM water_consumption WHERE city = 'Los Angeles' GROUP BY city; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.