instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
How many users from each age group have joined the gym in the last 6 months, for users aged 19-25 and 36-46?
CREATE TABLE membership_data (id INT,user_id INT,join_date DATE); CREATE TABLE user_profile (id INT,user_id INT,age INT,city VARCHAR(50)); INSERT INTO membership_data (id,user_id,join_date) VALUES (5,4,'2021-02-15'),(6,5,'2021-03-05'),(7,6,'2021-01-01'),(8,7,'2021-04-10'),(9,8,'2021-05-15'); INSERT INTO user_profile (i...
SELECT CASE WHEN age BETWEEN 19 AND 25 THEN '19-25' WHEN age BETWEEN 36 AND 46 THEN '36-46' END as age_group, COUNT(*) as user_count FROM membership_data m JOIN user_profile u ON m.user_id = u.user_id WHERE m.join_date >= DATE_SUB(CURRENT_DATE, INTERVAL 6 MONTH) AND (age BETWEEN 19 AND 25 OR age BETWEEN 36 AND 46) GROU...
What is the total revenue for 'natural' products in Q3 2022?
CREATE TABLE cosmetics_sales (product_type VARCHAR(50),revenue FLOAT,quarter INT,year INT); INSERT INTO cosmetics_sales (product_type,revenue,quarter,year) VALUES ('natural',3500.00,3,2022),('organic',2000.00,3,2022);
SELECT SUM(revenue) FROM cosmetics_sales WHERE product_type = 'natural' AND quarter = 3 AND year = 2022;
What is the average emergency response time in Houston?
CREATE TABLE houston_emergency_responses (id INT,response_time INT,location VARCHAR(20)); INSERT INTO houston_emergency_responses (id,response_time,location) VALUES (1,120,'Houston'),(2,90,'Houston');
SELECT AVG(response_time) FROM houston_emergency_responses WHERE location = 'Houston';
What is the number of employees from underrepresented racial groups in the 'Employees' table?
CREATE TABLE Employees (id INT,name TEXT,race TEXT);INSERT INTO Employees (id,name,race) VALUES (1,'John Smith','White'),(2,'Jane Doe','Black'),(3,'Mary Johnson','Hispanic'),(4,'James Brown','Asian');
SELECT COUNT(*) FROM Employees WHERE race IN ('Black', 'Hispanic', 'Asian');
What is the average range for electric sedans in the "ev_sedans" view?
CREATE VIEW ev_sedans AS SELECT * FROM green_vehicles WHERE type = 'Electric' AND category = 'Sedan';
SELECT AVG(range) FROM ev_sedans;
What is the minimum bioprocess engineering cost for projects in Italy?
CREATE TABLE costs (id INT,project VARCHAR(50),country VARCHAR(50),cost FLOAT); INSERT INTO costs (id,project,country,cost) VALUES (1,'Bioprocess1','Italy',50000); INSERT INTO costs (id,project,country,cost) VALUES (2,'Bioprocess2','Italy',60000); INSERT INTO costs (id,project,country,cost) VALUES (3,'Bioprocess3','Ita...
SELECT MIN(cost) FROM costs WHERE country = 'Italy';
List all news topics and the number of related articles published in the last month, sorted by the number of articles in descending order in the "InvestigativeJournalism" and "NewsReporting" databases.
CREATE TABLE NewsTopics (TopicID INT,Topic VARCHAR(255)); CREATE TABLE Articles (ArticleID INT,TopicID INT,PublishDate DATE); INSERT INTO NewsTopics (TopicID,Topic) VALUES (1,'corruption'),(2,'environment'),(3,'human rights'); INSERT INTO Articles (ArticleID,TopicID,PublishDate) VALUES (1,1,'2022-01-01'),(2,2,'2022-02-...
SELECT NewsTopics.Topic, COUNT(Articles.ArticleID) AS ArticleCount FROM NewsTopics INNER JOIN Articles ON NewsTopics.TopicID = Articles.TopicID WHERE Articles.PublishDate >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH) GROUP BY NewsTopics.Topic ORDER BY ArticleCount DESC;
What are the names of all fish species?
CREATE TABLE fish_species (species_id INT PRIMARY KEY,species_name VARCHAR(50),conservation_status VARCHAR(20))
SELECT species_name FROM fish_species
What are the top 2 most popular sustainable clothing items among customers in Europe?
CREATE TABLE SustainableClothing (clothing_id INT,clothing_name VARCHAR(50),price DECIMAL(5,2),quantity INT); CREATE TABLE ClothingSales (sale_id INT,clothing_id INT,sale_country VARCHAR(50)); INSERT INTO SustainableClothing (clothing_id,clothing_name,price,quantity) VALUES (1,'Organic Cotton Shirt',25.00,100),(2,'Recy...
SELECT clothing_name, SUM(quantity) FROM SustainableClothing INNER JOIN ClothingSales ON SustainableClothing.clothing_id = ClothingSales.clothing_id WHERE sale_country = 'Europe' GROUP BY clothing_name ORDER BY SUM(quantity) DESC LIMIT 2;
List the names of farmers who grow corn as a crop in the 'rural_development' database.
CREATE TABLE farmers (farmer_id INT,name TEXT,location TEXT,crops TEXT); INSERT INTO farmers (farmer_id,name,location,crops) VALUES (1,'James Johnson','Villageville','Corn,Wheat'),(2,'Emily Brown','Farmland','Soybean,Rice');
SELECT name FROM farmers WHERE 'Corn' = ANY (STRING_TO_ARRAY(crops, ', '));
Find the total investment in agricultural innovation projects in Southeast Asia, excluding Singapore and Indonesia.
CREATE TABLE Investments (id INT,project_name TEXT,location TEXT,investment FLOAT); INSERT INTO Investments (id,project_name,location,investment) VALUES (1,'AgriTech Asia','Southeast Asia',500000); INSERT INTO Investments (id,project_name,location,investment) VALUES (2,'Smart Farm SEA','Singapore',300000); INSERT INTO ...
SELECT SUM(investment) FROM Investments WHERE location NOT IN ('Singapore', 'Indonesia') AND location LIKE '%Southeast Asia%';
What is the success rate of biotech startups founded in the last 5 years, based on their total funding, number of employees, and industry sector?
CREATE TABLE biotech_startups (id INT PRIMARY KEY,name VARCHAR(255),total_funding DECIMAL(10,2),employees INT,founding_year INT,country VARCHAR(255),industry_sector VARCHAR(255));
SELECT ROUND((SUM(CASE WHEN total_funding > 1000000 AND employees > 50 AND industry_sector = 'Healthcare' THEN 1 ELSE 0 END)/COUNT(*))*100,2) AS success_rate FROM biotech_startups WHERE founding_year BETWEEN 2017 AND 2022;
What is the total number of articles published by 'The Guardian' and 'The New York Times'?
CREATE TABLE the_guardian (article_id INT,title TEXT,publish_date DATE,source TEXT); INSERT INTO the_guardian (article_id,title,publish_date,source) VALUES (1,'Article Title 1','2022-01-01','The Guardian'),(2,'Article Title 2','2022-01-02','The Guardian'); CREATE TABLE the_new_york_times (article_id INT,title TEXT,publ...
SELECT COUNT(*) FROM (SELECT * FROM the_guardian UNION ALL SELECT * FROM the_new_york_times) AS combined
What is the maximum number of community development initiatives in the 'rural_development' schema's 'community_development' table, broken down by the sector they focus on, for initiatives implemented in the last 2 years?
CREATE TABLE community_development (initiative_id INT,sector VARCHAR(255),implementation_date DATE);
SELECT sector, MAX(number_of_initiatives) FROM (SELECT sector, COUNT(*) AS number_of_initiatives FROM community_development WHERE implementation_date >= DATE_SUB(CURRENT_DATE, INTERVAL 2 YEAR) GROUP BY sector) AS subquery GROUP BY sector;
What is the average sea level rise, grouped by year and continent?
CREATE TABLE sea_level_rise_2 (id INT,year INT,rise FLOAT,continent VARCHAR(255)); INSERT INTO sea_level_rise_2 (id,year,rise,continent) VALUES (1,2000,1.5,'Africa'); INSERT INTO sea_level_rise_2 (id,year,rise,continent) VALUES (2,2005,1.8,'Antarctica'); INSERT INTO sea_level_rise_2 (id,year,rise,continent) VALUES (3,2...
SELECT year, continent, AVG(rise) FROM sea_level_rise_2 GROUP BY year, continent;
What is the count of IoT sensors in "ES-Andalucia" and "FR-Nouvelle Aquitaine"?
CREATE TABLE Sensor (id INT,sensor_id INT,location VARCHAR(255)); INSERT INTO Sensor (id,sensor_id,location) VALUES (1,1009,'ES-Andalucia');
SELECT COUNT(DISTINCT sensor_id) FROM Sensor WHERE location IN ('ES-Andalucia', 'FR-Nouvelle Aquitaine');
What is the total revenue for each menu category in a specific country?
CREATE TABLE menus (menu_id INT,category VARCHAR(255)); INSERT INTO menus VALUES (1,'Appetizers'); INSERT INTO menus VALUES (2,'Entrees'); INSERT INTO menus VALUES (3,'Desserts'); CREATE TABLE sales (sale_id INT,menu_id INT,quantity INT,country VARCHAR(255),price DECIMAL(10,2));
SELECT m.category, SUM(s.price * s.quantity) as total_revenue FROM menus m INNER JOIN sales s ON m.menu_id = s.menu_id WHERE s.country = 'USA' GROUP BY m.category;
List all the cities in Texas and the number of polling stations in each one.
CREATE TABLE cities (id INT,city_name VARCHAR(255),state VARCHAR(255));CREATE TABLE polling_stations (id INT,station_name VARCHAR(255),city_id INT);
SELECT c.city_name, COUNT(ps.id) as num_stations FROM cities c LEFT JOIN polling_stations ps ON c.id = ps.city_id WHERE c.state = 'Texas' GROUP BY c.id;
What is the total number of visitors for all exhibitions in Los Angeles?
CREATE TABLE Exhibitions (id INT PRIMARY KEY,title VARCHAR(100),start_date DATE,end_date DATE,location VARCHAR(100)); INSERT INTO Exhibitions (id,title,start_date,end_date,location) VALUES (1,'Picasso: The Line','2022-02-01','2022-05-01','New York'); INSERT INTO Exhibitions (id,title,start_date,end_date,location) VALUE...
SELECT SUM(Attendance.visitor_count) as total_visitors FROM Attendance JOIN Exhibitions ON Attendance.exhibition_id = Exhibitions.id WHERE Exhibitions.location = 'Los Angeles';
What is the total number of infectious diseases reported in each country?
CREATE TABLE infectious_diseases_global (id INT,country VARCHAR(50),disease VARCHAR(50)); INSERT INTO infectious_diseases_global (id,country,disease) VALUES (1,'Country A','Disease A'),(2,'Country A','Disease B'),(3,'Country B','Disease A');
SELECT country, COUNT(DISTINCT disease) FROM infectious_diseases_global GROUP BY country;
How many safety incidents occurred in Q3 2020 for each facility?
CREATE TABLE SafetyIncidents (ID INT,IncidentDate DATE,FacilityID INT); INSERT INTO SafetyIncidents (ID,IncidentDate,FacilityID) VALUES (1,'2020-09-15',100),(2,'2020-07-21',100),(3,'2020-10-03',101),(4,'2020-08-01',101);
SELECT FacilityID, DATE_FORMAT(IncidentDate, '%Y-%m') as Month, COUNT(*) as IncidentCount FROM SafetyIncidents WHERE IncidentDate >= '2020-07-01' AND IncidentDate < '2020-10-01' GROUP BY FacilityID, Month;
Get the 'algorithm' and 'recall' values for records with 'precision' >= 0.9 in the 'evaluation_data3' table
CREATE TABLE evaluation_data3 (id INT,algorithm VARCHAR(20),precision DECIMAL(3,2),recall DECIMAL(3,2)); INSERT INTO evaluation_data3 (id,algorithm,precision,recall) VALUES (1,'Random Forest',0.92,0.85),(2,'XGBoost',0.95,0.93),(3,'Naive Bayes',0.88,0.89);
SELECT algorithm, recall FROM evaluation_data3 WHERE precision >= 0.9;
Find the total number of visitors from Indigenous communities who engaged with digital exhibits in 2021?
CREATE TABLE Communities (id INT,community_type VARCHAR(30)); INSERT INTO Communities (id,community_type) VALUES (1,'Indigenous'),(2,'Settler'),(3,'Immigrant'); CREATE TABLE DigitalEngagement (id INT,visitor_id INT,community_id INT,year INT); INSERT INTO DigitalEngagement (id,visitor_id,community_id,year) VALUES (1,201...
SELECT COUNT(DISTINCT DigitalEngagement.visitor_id) FROM DigitalEngagement INNER JOIN Communities ON DigitalEngagement.community_id = Communities.id WHERE Communities.community_type = 'Indigenous' AND DigitalEngagement.year = 2021;
What is the average number of employees in the healthcare sector?
CREATE TABLE companies (id INT,sector VARCHAR(255),employees INT); INSERT INTO companies (id,sector,employees) VALUES (1,'healthcare',4500),(2,'technology',5500),(3,'healthcare',6000);
SELECT AVG(employees) FROM companies WHERE sector = 'healthcare';
Which circular economy initiatives have the highest recycling rates?
CREATE TABLE circular_initiatives (id INT,initiative_name VARCHAR(50),recycling_rate FLOAT);
SELECT initiative_name, recycling_rate FROM circular_initiatives ORDER BY recycling_rate DESC LIMIT 1;
Create a view to display the top 3 countries by music streaming
CREATE TABLE music_streaming (user_id INT,song_id INT,timestamp TIMESTAMP,country VARCHAR(255)); INSERT INTO music_streaming (user_id,song_id,timestamp,country) VALUES (1,123,'2022-01-01 10:00:00','USA'); INSERT INTO music_streaming (user_id,song_id,timestamp,country) VALUES (2,456,'2022-01-01 11:00:00','Canada');
CREATE VIEW top_3_countries AS SELECT country, COUNT(*) as play_count FROM music_streaming GROUP BY country ORDER BY play_count DESC LIMIT 3;
Calculate the veteran employment rate by state for the last quarter
CREATE TABLE veteran_employment (state VARCHAR(2),employment_date DATE,employment_rate FLOAT); INSERT INTO veteran_employment (state,employment_date,employment_rate) VALUES ('CA','2022-01-01',0.95),('NY','2022-01-01',0.94);
SELECT state, AVG(employment_rate) AS avg_employment_rate FROM veteran_employment WHERE employment_date >= DATE_SUB(CURDATE(), INTERVAL 3 MONTH) GROUP BY state;
Delete all records of workplaces in New York with safety violations.
CREATE TABLE workplaces (id INT,name TEXT,state TEXT,safety_violation BOOLEAN); INSERT INTO workplaces (id,name,state,safety_violation) VALUES (1,'XYZ Company','New York',true);
DELETE FROM workplaces WHERE state = 'New York' AND safety_violation = true;
How many products have been sold in each region, sorted by sales?
CREATE TABLE sales (product_id INT,quantity INT,region TEXT); INSERT INTO sales (product_id,quantity,region) VALUES (1,500,'Europe'),(2,250,'North America'),(3,750,'Asia');
SELECT region, SUM(quantity) AS total_sales, ROW_NUMBER() OVER (ORDER BY total_sales DESC) AS rn FROM sales GROUP BY region;
Determine the number of consecutive days with rain for each location.
CREATE TABLE WeatherData (Location VARCHAR(20),Rain BOOLEAN,Date DATE); INSERT INTO WeatherData (Location,Rain,Date) VALUES ('Seattle',TRUE,'2022-01-01'),('Seattle',TRUE,'2022-01-02'),('New York',FALSE,'2022-01-01'),('New York',TRUE,'2022-01-02');
SELECT Location, COUNT(*) AS ConsecutiveRainDays FROM (SELECT Location, Rain, Date, ROW_NUMBER() OVER (PARTITION BY Location ORDER BY Date) - ROW_NUMBER() OVER (ORDER BY Location, Date) AS Grp FROM WeatherData) a GROUP BY Location, Grp HAVING COUNT(*) > 1 ORDER BY Location;
Get the top 2 countries with the most music streams in the last month.
CREATE TABLE music_streams (song VARCHAR(255),country VARCHAR(255),streams INT,stream_date DATE); INSERT INTO music_streams (song,country,streams,stream_date) VALUES ('Song1','Country1',100000,'2022-01-01'),('Song2','Country2',150000,'2022-01-02'),('Song3','Country3',120000,'2022-01-03'),('Song4','Country1',110000,'202...
SELECT country, SUM(streams) as total_streams FROM music_streams GROUP BY country ORDER BY total_streams DESC LIMIT 2;
How many indigenous food systems have a reported annual income greater than $50,000?
CREATE TABLE indigenous_food_systems (system_id INT,system_name TEXT,annual_income FLOAT); INSERT INTO indigenous_food_systems (system_id,system_name,annual_income) VALUES (1,'Acorn Farming',45000),(2,'Maple Syrup Production',62000),(3,'Bison Ranching',80000);
SELECT COUNT(*) FROM indigenous_food_systems WHERE annual_income > 50000;
What is the total number of visitors who attended exhibitions in the 'Art' category, and the number of days each exhibition in this category was open to the public?
CREATE TABLE Exhibitions (id INT,name VARCHAR(20),category VARCHAR(20),visitors INT,start_date DATE,end_date DATE); INSERT INTO Exhibitions VALUES (1,'Exhibition A','Art',3000,'2022-01-01','2022-03-31'),(2,'Exhibition B','Science',2000,'2022-02-01','2022-04-30'),(3,'Exhibition C','Art',4000,'2022-03-01','2022-05-31'),(...
SELECT E.category, E.name, SUM(E.visitors) AS total_visitors, DATEDIFF(E.end_date, E.start_date) + 1 AS days_open FROM Exhibitions E WHERE E.category = 'Art' GROUP BY E.category, E.name;
List all unique cargo types being transported by vessels in the Pacific region.
CREATE TABLE Vessel_Cargo (Vessel_ID INT,Cargo_Type VARCHAR(255),Region VARCHAR(255)); INSERT INTO Vessel_Cargo (Vessel_ID,Cargo_Type,Region) VALUES (1,'Grain','Pacific'),(2,'Containers','Atlantic'),(3,'Oil','Pacific'),(4,'Vehicles','Atlantic'),(5,'Coal','Indian');
SELECT DISTINCT Cargo_Type FROM Vessel_Cargo WHERE Region = 'Pacific';
Identify the number of farmers practicing organic farming methods in Oceania and South America in 2022.
CREATE TABLE Organic_Farming (Farmer_ID INT,Region VARCHAR(20),Farming_Method VARCHAR(20),Year INT); INSERT INTO Organic_Farming (Farmer_ID,Region,Farming_Method,Year) VALUES (901,'Oceania','Organic',2022),(902,'South America','Organic',2022);
SELECT COUNT(DISTINCT Farmer_ID) FROM Organic_Farming WHERE Region IN ('Oceania', 'South America') AND Year = 2022 AND Farming_Method = 'Organic';
What is the total population of animals in the wildlife_habitat table?
CREATE TABLE wildlife_habitat (id INT,species VARCHAR(255),population INT); INSERT INTO wildlife_habitat (id,species,population) VALUES (1,'Bear',35),(2,'Deer',78),(3,'Raccoon',42);
SELECT SUM(population) FROM wildlife_habitat;
What is the average production quantity for wells in the 'onshore' category?
CREATE TABLE wells (id INT,name VARCHAR(255),category VARCHAR(255),production_quantity INT); INSERT INTO wells (id,name,category,production_quantity) VALUES (1,'Well A','onshore',1000),(2,'Well B','offshore',2000),(3,'Well C','onshore',1500);
SELECT AVG(production_quantity) FROM wells WHERE category = 'onshore';
What is the total funding raised by startups with at least one founder from a rural area in the agricultural technology sector?
CREATE TABLE startups(id INT,name TEXT,industry TEXT,founder_location TEXT,funding FLOAT); INSERT INTO startups(id,name,industry,founder_location,funding) VALUES (1,'RuralTech','Agricultural Technology','Rural',7000000);
SELECT SUM(funding) FROM startups WHERE industry = 'Agricultural Technology' AND founder_location = 'Rural';
What is the average budget of cities in California?
CREATE TABLE Cities (CityID int,CityName varchar(255),State varchar(255),Budget decimal(10,2)); INSERT INTO Cities (CityID,CityName,State,Budget) VALUES (1,'Los Angeles','California',12000000.00),(2,'San Francisco','California',10000000.00);
SELECT AVG(Budget) FROM Cities WHERE State = 'California';
What is the earliest excavation date for 'Site F'?
CREATE TABLE excavation_sites (site_id INT,site_name TEXT,excavation_date DATE); INSERT INTO excavation_sites (site_id,site_name,excavation_date) VALUES (1,'Site A','2015-01-01'),(2,'Site B','2012-05-05'),(3,'Site C','2018-10-10'),(4,'Site D','2009-08-08'),(5,'Site E','2011-02-14'),(6,'Site F','2005-06-20');
SELECT MIN(excavation_date) FROM excavation_sites WHERE site_name = 'Site F';
List all the drought-affected counties in each state in 2019, along with their water consumption.
CREATE TABLE drought_impact (county VARCHAR(30),state VARCHAR(20),year INT,impact BOOLEAN); CREATE TABLE water_consumption (county VARCHAR(30),state VARCHAR(20),year INT,consumption FLOAT);
SELECT d.county, d.state, w.consumption FROM drought_impact d INNER JOIN water_consumption w ON d.county=w.county AND d.state=w.state WHERE d.year=2019 AND d.impact=TRUE;
What is the daily trading volume for each digital asset on a specific date?
CREATE TABLE digital_assets (id INT,name VARCHAR(255),daily_trading_volume DECIMAL(10,2)); INSERT INTO digital_assets (id,name,daily_trading_volume) VALUES (1,'Asset1',5000),(2,'Asset2',3000),(3,'Asset3',2000),(4,'Asset4',1000),(5,'Asset5',500);
SELECT name, daily_trading_volume AS Daily_Trading_Volume FROM digital_assets WHERE daily_trading_volume = (SELECT daily_trading_volume FROM digital_assets WHERE name = 'Asset2' AND daily_trading_volume IS NOT NULL ORDER BY daily_trading_volume DESC LIMIT 1);
What are the top 5 most popular hashtags used in posts from users in the United States?
CREATE TABLE users (id INT,country VARCHAR(255)); INSERT INTO users (id,country) VALUES (1,'USA'),(2,'Canada'),(3,'Mexico'); CREATE TABLE posts (id INT,user_id INT,hashtags VARCHAR(255)); INSERT INTO posts (id,user_id,hashtags) VALUES (1,1,'#socialmedia1,#trend1'),(2,1,'#socialmedia2,#trend2'),(3,2,'#socialmedia3,#tren...
SELECT user_id, SUBSTRING_INDEX(SUBSTRING_INDEX(hashtags, ',', 5), ',', -1) as top_5_hashtags FROM posts WHERE user_id IN (SELECT id FROM users WHERE country = 'USA') GROUP BY user_id;
What is the total number of disaster relief projects carried out in Asia?
CREATE TABLE projects (id INT,name TEXT,category TEXT,location TEXT,start_date DATE,end_date DATE); INSERT INTO projects (id,name,category,location,start_date,end_date) VALUES (1,'Refugee Support Project','Refugee','Africa','2020-01-01','2020-12-31'),(2,'Disaster Relief Project','Disaster','Asia','2019-01-01','2020-12-...
SELECT COUNT(*) FROM projects WHERE category = 'Disaster' AND location = 'Asia';
What is the number of peacekeeping operations participated in by each country by year?
CREATE TABLE if not exists peacekeeping_by_year (year INT,country TEXT,operation TEXT,troops INT); INSERT INTO peacekeeping_by_year (year,country,operation,troops) VALUES (2015,'Country A','Peacekeeping Operation 1',200); INSERT INTO peacekeeping_by_year (year,country,operation,troops) VALUES (2016,'Country A','Peaceke...
SELECT year, country, SUM(troops) as total_troops FROM peacekeeping_by_year GROUP BY year, country;
List the vessels with the highest cargo weight in the Indian Ocean in Q1 2021.
CREATE TABLE vessels(id INT,name VARCHAR(100),region VARCHAR(50));CREATE TABLE shipments(id INT,vessel_id INT,cargo_weight FLOAT,ship_date DATE);
SELECT v.name FROM vessels v JOIN (SELECT vessel_id, MAX(cargo_weight) AS max_weight FROM shipments WHERE ship_date BETWEEN '2021-01-01' AND '2021-03-31' GROUP BY vessel_id) s ON v.id = s.vessel_id WHERE v.region = 'Indian Ocean' ORDER BY max_weight DESC;
Display the number of unique policies and total claims amount for each policy type.
CREATE TABLE Claims (ClaimID INT,PolicyID INT,ClaimAmount DECIMAL(10,2)); CREATE TABLE Policy (PolicyID INT,PolicyType VARCHAR(20)); INSERT INTO Claims (ClaimID,PolicyID,ClaimAmount) VALUES (1,1,1500.00),(2,2,250.00),(3,3,500.00),(4,1,1000.00); INSERT INTO Policy (PolicyID,PolicyType) VALUES (1,'Homeowners'),(2,'Auto')...
SELECT Policy.PolicyType, COUNT(DISTINCT Policy.PolicyID) AS UniquePolicies, SUM(Claims.ClaimAmount) AS TotalClaimsAmount FROM Policy LEFT JOIN Claims ON Policy.PolicyID = Claims.PolicyID GROUP BY Policy.PolicyType;
What is the minimum recycling rate for glass in Q2 2022 for each state?
CREATE TABLE recycling_rates(quarter INT,state VARCHAR(255),plastic_recycling FLOAT,paper_recycling FLOAT,glass_recycling FLOAT); INSERT INTO recycling_rates VALUES (2,'California',0.5,0.6,0.4),(2,'Texas',0.4,0.5,0.3);
SELECT MIN(glass_recycling) AS min_glass_recycling, state FROM recycling_rates WHERE quarter = 2 GROUP BY state;
What is the total revenue generated from circular supply chain products in the current quarter?
CREATE TABLE revenue (revenue_id INT,product_origin VARCHAR(50),revenue DECIMAL(10,2)); INSERT INTO revenue (revenue_id,product_origin,revenue) VALUES (1,'Circular Supply Chain',5000),(2,'Linear Supply Chain',7000),(3,'Circular Supply Chain',8000);
SELECT SUM(revenue) FROM revenue WHERE product_origin = 'Circular Supply Chain' AND revenue_date >= DATEADD(quarter, DATEDIFF(quarter, 0, CURRENT_DATE), 0);
How many space missions were launched by each country in the space_missions table?
CREATE TABLE space_missions (country VARCHAR(30),launch_year INT,mission_name VARCHAR(50)); INSERT INTO space_missions VALUES ('USA',2005,'New Horizons'),('China',2003,'Shenzhou 5'),('India',2014,'Mangalyaan'),('USA',2011,'Juno'),('Russia',2013,'Mars Orbiter');
SELECT country, COUNT(mission_name) OVER (PARTITION BY country) FROM space_missions;
What is the average number of hours played per week for players in the game "World of Warcraft" who are above level 60?
CREATE TABLE players (id INT,name VARCHAR(50),game_id INT,level INT,hours_played_per_week INT); INSERT INTO players (id,name,game_id,level,hours_played_per_week) VALUES (1,'Player1',1,55,25),(2,'Player2',1,65,30),(3,'Player3',1,45,20);
SELECT AVG(hours_played_per_week) FROM players WHERE game_id = 1 AND level > 60;
Which bridges have more than two inspections and were inspected in 2022?
CREATE TABLE Bridges (id INT,name VARCHAR(255),type VARCHAR(255),location VARCHAR(255)); INSERT INTO Bridges (id,name,type,location) VALUES (1,'Golden Gate','Suspension','San Francisco'); INSERT INTO Bridges (id,name,type,location) VALUES (2,'Brooklyn','Cable-stayed','New York'); CREATE TABLE Inspections (id INT,bridge...
SELECT b.name FROM Bridges b JOIN Inspections i ON b.id = i.bridge_id WHERE YEAR(i.inspection_date) = 2022 GROUP BY b.name HAVING COUNT(i.id) > 2;
Update the fish stock data for farm A to 5000
CREATE TABLE fish_stock (id INT,farm_name VARCHAR(50),fish_count INT); INSERT INTO fish_stock (id,farm_name,fish_count) VALUES (1,'Farm A',3000); INSERT INTO fish_stock (id,farm_name,fish_count) VALUES (2,'Farm B',4000);
UPDATE fish_stock SET fish_count = 5000 WHERE farm_name = 'Farm A';
What is the average number of cases mediated per mediator in 2020?
CREATE TABLE mediators (id INT,name VARCHAR(255),cases_mediated INT,year INT); INSERT INTO mediators (id,name,cases_mediated,year) VALUES (1,'Alex',22,2020),(2,'Taylor',30,2020),(3,'Jamie',40,2020);
SELECT AVG(cases_mediated) FROM mediators WHERE year = 2020;
Identify the number of smart city technology adoptions per year
CREATE TABLE smart_city_projects (id INT,project_name VARCHAR(100),start_date DATE);
SELECT EXTRACT(YEAR FROM start_date) AS year, COUNT(*) AS adoptions FROM smart_city_projects GROUP BY year;
Count the number of drilling rigs owned by BP, Shell, and Total.
CREATE TABLE DrillingRigs (RigID INT,RigName VARCHAR(50),Manufacturer VARCHAR(50),Status VARCHAR(50),Location VARCHAR(50)); INSERT INTO DrillingRigs (RigID,RigName,Manufacturer,Status,Location) VALUES (1,'Titan','Acme','Active','Gulf of Mexico'); INSERT INTO DrillingRigs (RigID,RigName,Manufacturer,Status,Location) VAL...
SELECT Manufacturer, COUNT(*) AS Rig_Count FROM DrillingRigs WHERE Manufacturer IN ('BP', 'Shell', 'Total') GROUP BY Manufacturer;
Identify the number of customers in Asia who bought recycled paper products in Q1 2022?
CREATE TABLE Customers (customerID INT,customerName VARCHAR(50),country VARCHAR(50)); CREATE TABLE Purchases (purchaseID INT,customerID INT,productID INT,purchaseDate DATE); CREATE TABLE Products (productID INT,productName VARCHAR(50),recycled BOOLEAN,productType VARCHAR(50));
SELECT COUNT(DISTINCT C.customerID) FROM Customers C JOIN Purchases P ON C.customerID = P.customerID JOIN Products PR ON P.productID = PR.productID WHERE C.country = 'Asia' AND PR.recycled = TRUE AND PR.productType = 'paper' AND P.purchaseDate BETWEEN '2022-01-01' AND '2022-03-31';
What is the total spending on rural infrastructure projects in Latin America in the last 10 years?
CREATE TABLE project (project_id INT,name VARCHAR(50),location VARCHAR(50),spending FLOAT,launch_date DATE); CREATE TABLE location (location_id INT,name VARCHAR(50),continent_id INT); CREATE TABLE continent (continent_id INT,name VARCHAR(50),description TEXT); INSERT INTO continent (continent_id,name,description) VALUE...
SELECT SUM(p.spending) FROM project p JOIN location l ON p.location = l.name WHERE l.continent_id = 2 AND p.launch_date >= DATE_SUB(CURRENT_DATE(), INTERVAL 10 YEAR);
Who are the attorneys who have not handled any 'Criminal' cases?
CREATE TABLE Attorneys (AttorneyID INT,Name VARCHAR(50)); INSERT INTO Attorneys (AttorneyID,Name) VALUES (1,'Jose Garcia'),(2,'Lee Kim'),(3,'Pierre Laurent'); CREATE TABLE Cases (CaseID INT,AttorneyID INT,Category VARCHAR(50)); INSERT INTO Cases (CaseID,AttorneyID,Category) VALUES (1,1,'Family'),(2,1,'Civil'),(3,2,'Fam...
SELECT Name FROM Attorneys WHERE AttorneyID NOT IN (SELECT AttorneyID FROM Cases WHERE Category = 'Criminal');
Find the names of the attendees who have visited musical and theater events in any location.
CREATE TABLE Events (event_id INT,event_type VARCHAR(50),location VARCHAR(50)); CREATE TABLE Attendance (attendee_id INT,event_id INT); INSERT INTO Events (event_id,event_type,location) VALUES (1,'Musical','Chicago'),(2,'Theater','Los Angeles'),(3,'Musical','San Francisco'); INSERT INTO Attendance (attendee_id,event_id...
SELECT attendee_id FROM Attendance A WHERE EXISTS (SELECT 1 FROM Events E WHERE (E.event_type = 'Musical' OR E.event_type = 'Theater') AND A.event_id = E.event_id)
Delete records with landfill capacity above 60000 in 'landfill_capacity' table for 2020.
CREATE TABLE landfill_capacity (year INT,location TEXT,capacity INT); INSERT INTO landfill_capacity (year,location,capacity) VALUES (2019,'SiteA',60000),(2019,'SiteB',45000),(2019,'SiteC',52000),(2020,'SiteA',62000),(2020,'SiteB',46000),(2020,'SiteC',53000),(2021,'SiteA',64000),(2021,'SiteB',47000),(2021,'SiteC',54000)...
DELETE FROM landfill_capacity WHERE year = 2020 AND capacity > 60000;
List all hydro projects in Canada and their capacities (in MW)
CREATE TABLE project (id INT,name TEXT,country TEXT,type TEXT,capacity INT); INSERT INTO project (id,name,country,type,capacity) VALUES (20,'Niagara Falls','Canada','Hydro',2400),(21,'Alberta Wind','Canada','Wind',450),(22,'Churchill Falls','Canada','Hydro',5428);
SELECT * FROM project WHERE country = 'Canada' AND type = 'Hydro';
List all policyholders who have not filed a claim in the last 365 days.
CREATE TABLE Policyholders (PolicyholderID INT,LastClaimDate DATE); INSERT INTO Policyholders (PolicyholderID,LastClaimDate) VALUES (1,'2021-02-01'),(2,'2022-02-15'),(3,NULL);
SELECT PolicyholderID, LastClaimDate FROM Policyholders WHERE LastClaimDate IS NULL OR LastClaimDate < DATE_SUB(CURRENT_DATE(), INTERVAL 365 DAY);
What is the average dissolved oxygen level (mg/L) for fish farms located in the Pacific Ocean?
CREATE TABLE fish_farms (id INT,name TEXT,location TEXT,dissolved_oxygen_level FLOAT); INSERT INTO fish_farms (id,name,location,dissolved_oxygen_level) VALUES (1,'Farm A','Pacific Ocean',6.5),(2,'Farm B','Atlantic Ocean',7.0);
SELECT AVG(dissolved_oxygen_level) FROM fish_farms WHERE location = 'Pacific Ocean';
What is the average healthcare spending per patient in rural New Mexico?
CREATE TABLE healthcare_spending (patient_id INT,year INT,amount DECIMAL(10,2)); INSERT INTO healthcare_spending (patient_id,year,amount) VALUES (1,2021,5000.50);
SELECT AVG(amount) FROM healthcare_spending WHERE patient_id = 1 AND year = 2021 AND location = 'rural New Mexico';
What is the minimum quantity of goods, in metric tons, shipped from Japan to South Korea via the Sea of Japan?
CREATE TABLE shipping_routes (id INT,departure_country VARCHAR(50),arrival_country VARCHAR(50),departure_region VARCHAR(50),arrival_region VARCHAR(50),transportation_method VARCHAR(50),quantity FLOAT); INSERT INTO shipping_routes (id,departure_country,arrival_country,departure_region,arrival_region,transportation_metho...
SELECT MIN(quantity) FROM shipping_routes WHERE departure_country = 'Japan' AND arrival_country = 'South Korea' AND departure_region = 'Sea of Japan' AND arrival_region = 'Sea of Japan' AND transportation_method = 'Ship';
How many cases were won by attorneys with a success rate higher than 70%?
CREATE TABLE Cases (CaseID INT,AttorneyID INT,CaseOutcome VARCHAR(10)); INSERT INTO Cases (CaseID,AttorneyID,CaseOutcome) VALUES (1,1,'Won'),(2,2,'Lost'),(3,3,'Won'),(4,1,'Won'),(5,2,'Won'); CREATE TABLE AttorneySuccessRates (AttorneyID INT,SuccessRate DECIMAL(3,2)); INSERT INTO AttorneySuccessRates (AttorneyID,Success...
SELECT COUNT(*) FROM Cases INNER JOIN AttorneySuccessRates ON Cases.AttorneyID = AttorneySuccessRates.AttorneyID WHERE SuccessRate > 0.7;
Delete water conservation records for cities in Idaho and Montana.
CREATE TABLE conservation(city TEXT,savings INTEGER); INSERT INTO conservation(city,savings) VALUES ('Boise',70),('Coeur d''Alene',65),('Missoula',80),('Billings',75);
DELETE FROM conservation WHERE city IN ('Coeur d''Alene', 'Billings');
What are the total number of satellites deployed by each country in 2020?
CREATE TABLE Satellites (Id INT,Name VARCHAR(50),LaunchYear INT,Country VARCHAR(50)); INSERT INTO Satellites (Id,Name,LaunchYear,Country) VALUES (1,'Sat1',2018,'USA'),(2,'Sat2',2019,'USA'),(3,'Sat3',2020,'USA'),(4,'Sat4',2020,'China'),(5,'Sat5',2020,'Russia'),(6,'Sat6',2018,'Germany'),(7,'Sat7',2019,'India');
SELECT Country, COUNT(*) FROM Satellites WHERE LaunchYear = 2020 GROUP BY Country;
What is the total number of female directors in movies and TV shows in Spain?
CREATE TABLE movies (id INT,title VARCHAR(255),release_year INT,views INT,country VARCHAR(50),director VARCHAR(50)); INSERT INTO movies (id,title,release_year,views,country,director) VALUES (1,'Movie1',2010,10000,'Spain','DirectorA'),(2,'Movie2',2015,15000,'Spain','DirectorB'),(3,'Movie3',2020,20000,'Spain','DirectorC'...
SELECT COUNT(*) FROM movies m JOIN directors d ON m.director = d.name WHERE d.gender = 'Female' AND m.country = 'Spain' UNION SELECT COUNT(*) FROM tv_shows t JOIN directors d ON t.director = d.name WHERE d.gender = 'Female' AND t.country = 'Spain';
What is the average number of community volunteers in education programs?
CREATE TABLE volunteers (id INT,program_id INT,num_volunteers INT); INSERT INTO volunteers (id,program_id,num_volunteers) VALUES (1,1,50),(2,2,25);
SELECT AVG(num_volunteers) FROM volunteers;
What is the name and position of the top 3 military personnel with the highest security clearance levels?
CREATE TABLE MilitaryPersonnel (PersonnelID INT,PersonnelName TEXT,Position TEXT,ClearanceLevel INT); INSERT INTO MilitaryPersonnel (PersonnelID,PersonnelName,Position,ClearanceLevel) VALUES (1,'James Brown','General',5); INSERT INTO MilitaryPersonnel (PersonnelID,PersonnelName,Position,ClearanceLevel) VALUES (2,'Emily...
SELECT PersonnelName, Position FROM MilitaryPersonnel ORDER BY ClearanceLevel DESC LIMIT 3;
What is the average ticket price for basketball games in the 'sports_events' table?
CREATE TABLE sports_events (event_id INT,event_name VARCHAR(50),sport VARCHAR(20),location VARCHAR(50),date DATE,ticket_price DECIMAL(5,2),num_tickets INT);
SELECT AVG(ticket_price) FROM sports_events WHERE sport = 'Basketball';
What is the total mineral extraction in Australia by year?
CREATE TABLE mineral_extraction (id INT,mine_id INT,year INT,quantity INT);CREATE TABLE mine (id INT,name VARCHAR(255),location VARCHAR(255)); INSERT INTO mine (id,name,location) VALUES (1,'Australian Gold','Australia'); INSERT INTO mineral_extraction (id,mine_id,year,quantity) VALUES (1,1,2019,1000);
SELECT year, SUM(quantity) as total_mineral_extraction FROM mineral_extraction JOIN mine ON mineral_extraction.mine_id = mine.id WHERE mine.location = 'Australia' GROUP BY year;
Update the "humidity" values in the "sensor_data" table where the "location" is 'Greenhouse 1'
CREATE TABLE sensor_data (id INT PRIMARY KEY,location VARCHAR(255),humidity FLOAT,temperature FLOAT);
UPDATE sensor_data SET humidity = 50 WHERE location = 'Greenhouse 1';
How many policy advocacy events were held virtually in the year 2020?
CREATE TABLE Policy_Advocacy_Events (event_id INT,year INT,type VARCHAR(255),format VARCHAR(255)); INSERT INTO Policy_Advocacy_Events VALUES (1,2020,'Webinar','Virtual');
SELECT COUNT(*) FROM Policy_Advocacy_Events WHERE format = 'Virtual' AND year = 2020;
What are the total calories burned by users in New York?
CREATE TABLE user_locations (user_id INT,city VARCHAR(20)); INSERT INTO user_locations (user_id,city) VALUES (101,'New York'),(102,'Los Angeles'),(103,'Chicago'),(104,'Houston'); CREATE TABLE workout_data (user_id INT,calories INT); INSERT INTO workout_data (user_id,calories) VALUES (101,300),(101,400),(102,250),(103,5...
SELECT SUM(calories) as total_calories FROM workout_data JOIN user_locations ON workout_data.user_id = user_locations.user_id WHERE user_locations.city = 'New York';
Delete all copper mines in Canada.
CREATE TABLE mines (id INT,name TEXT,location TEXT,production_volume INT,mineral TEXT); INSERT INTO mines (id,name,location,production_volume,mineral) VALUES (1,'Canadian Copper Mine 1','Canada',7000,'copper'); INSERT INTO mines (id,name,location,production_volume,mineral) VALUES (2,'Canadian Copper Mine 2','Canada',80...
DELETE FROM mines WHERE location = 'Canada' AND mineral = 'copper';
What is the total funding allocated for climate adaptation projects in Sub-Saharan Africa for the year 2022?
CREATE TABLE climate_finance (year INT,region VARCHAR(50),funding_type VARCHAR(50),amount INT); INSERT INTO climate_finance (year,region,funding_type,amount) VALUES (2022,'Sub-Saharan Africa','climate adaptation',15000000);
SELECT SUM(amount) FROM climate_finance WHERE region = 'Sub-Saharan Africa' AND year = 2022 AND funding_type = 'climate adaptation';
Calculate the local economic impact by country?
CREATE TABLE local_businesses (business_id INT,business_name VARCHAR(50),country VARCHAR(30)); CREATE TABLE hotel_business_partnerships (partnership_id INT,hotel_id INT,business_id INT); INSERT INTO local_businesses (business_id,business_name,country) VALUES (1,'Green Groceries','USA'),(2,'Eco-friendly Tours','Brazil')...
SELECT country, SUM(price) FROM local_businesses JOIN hotel_business_partnerships ON local_businesses.business_id = hotel_business_partnerships.business_id JOIN hotel_rooms ON hotel_business_partnerships.hotel_id = hotel_rooms.hotel_id WHERE hotel_rooms.is_eco_friendly = TRUE GROUP BY country;
List all financial transactions with a category of 'Zakat' in January 2022.
CREATE TABLE financial_transactions (transaction_id INT,amount DECIMAL(10,2),category VARCHAR(255),transaction_date DATE); INSERT INTO financial_transactions (transaction_id,amount,category,transaction_date) VALUES (1,200,'Zakat','2022-01-05'); INSERT INTO financial_transactions (transaction_id,amount,category,transact...
SELECT * FROM financial_transactions WHERE category = 'Zakat' AND transaction_date BETWEEN '2022-01-01' AND '2022-01-31';
What is the total inventory cost for each menu item category in the current quarter?
CREATE TABLE Inventory (inventory_id INT PRIMARY KEY,menu_item VARCHAR(50),inventory_quantity INT,inventory_cost DECIMAL(5,2),inventory_date DATE); CREATE TABLE Menu (menu_item VARCHAR(50) PRIMARY KEY,menu_item_category VARCHAR(50));
SELECT menu_item_category, SUM(inventory_cost * inventory_quantity) FROM Inventory i JOIN Menu m ON i.menu_item = m.menu_item WHERE i.inventory_date >= DATEADD(quarter, DATEDIFF(quarter, 0, GETDATE()), 0) GROUP BY menu_item_category;
How many local businesses in Spain have benefited from sustainable tourism initiatives?
CREATE TABLE local_businesses (business_id INT,business_name TEXT,country TEXT,sustainable_initiative BOOLEAN); INSERT INTO local_businesses (business_id,business_name,country,sustainable_initiative) VALUES (1,'La Ribera Market','Spain',TRUE); INSERT INTO local_businesses (business_id,business_name,country,sustainable_...
SELECT COUNT(*) FROM local_businesses WHERE country = 'Spain' AND sustainable_initiative = TRUE;
Display the name and description of all regulatory records created in the year 2021
CREATE TABLE countries (id INT,name VARCHAR(10)); INSERT INTO countries (id,name) VALUES (1,'FR'),(2,'DE'); CREATE TABLE regulations (id INT,country VARCHAR(10),quarter DATE,description VARCHAR(50),creation_date DATE); INSERT INTO regulations (id,country,quarter,description,creation_date) VALUES (1,'FR','2021-01-01','S...
SELECT countries.name, regulations.description FROM countries INNER JOIN regulations ON countries.name = regulations.country WHERE YEAR(creation_date) = 2021;
List the names of all programs with no associated donations.
CREATE TABLE Programs (id INT,name TEXT); INSERT INTO Programs (id,name) VALUES (1,'Youth Education'),(2,'Women Empowerment'),(3,'Clean Water'),(4,'Refugee Support'); CREATE TABLE Donations (id INT,program INT,amount DECIMAL(10,2)); INSERT INTO Donations (id,program,amount) VALUES (1,1,100),(2,2,150),(3,3,75);
SELECT Programs.name FROM Programs LEFT JOIN Donations ON Programs.id = Donations.program WHERE Donations.program IS NULL;
Update the yield of the 'Blue Dream' strain to 0.85.
CREATE TABLE strains (id INT,name TEXT,category TEXT,yield FLOAT); INSERT INTO strains (id,name,category,yield) VALUES (1,'Purple Kush','Indica',0.5),(2,'Northern Lights','Indica',0.6),(3,'Granddaddy Purple','Indica',0.7),(4,'Sour Diesel','Sativa',0.6),(5,'Blue Dream','Hybrid',0.9),(6,'Green Crack','Sativa',0.8);
UPDATE strains SET yield = 0.85 WHERE name = 'Blue Dream';
How many events happened in each city?
CREATE TABLE Events (id INT,city VARCHAR(50),event_date DATE); INSERT INTO Events (id,city,event_date) VALUES (1,'Los Angeles','2021-06-01'),(2,'New York','2021-07-01'),(3,'Houston','2021-05-15'),(4,'Los Angeles','2021-07-15');
SELECT city, COUNT(*) as event_count FROM Events GROUP BY city;
What is the average pollution level for the Arctic Ocean?
CREATE TABLE PollutionData (ID INT,Location VARCHAR(20),Pollutant VARCHAR(20),Level INT); INSERT INTO PollutionData (ID,Location,Pollutant,Level) VALUES (1,'Arctic','Nitrate',10); INSERT INTO PollutionData (ID,Location,Pollutant,Level) VALUES (2,'Atlantic','Phosphate',15);
SELECT AVG(Level) FROM PollutionData WHERE Location = 'Arctic';
Find the user who has posted the most ads in a specific city in the past month.
CREATE TABLE users (id INT,name VARCHAR(255),city VARCHAR(255)); CREATE TABLE posts (id INT,user_id INT,post_type VARCHAR(255),post_date DATETIME); CREATE TABLE ads (id INT,post_id INT);
SELECT u.name, COUNT(a.id) AS ad_count FROM users u JOIN posts p ON u.id = p.user_id AND p.post_type = 'ad' JOIN ads a ON p.id = a.post_id WHERE u.city = 'New York' AND p.post_date > DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH) GROUP BY u.name ORDER BY ad_count DESC LIMIT 1;
Show all 'warehouse_location' and their corresponding 'warehouse_size' from the 'warehouse_management' table
CREATE TABLE warehouse_management (warehouse_id INT,warehouse_location VARCHAR(50),warehouse_size INT); INSERT INTO warehouse_management (warehouse_id,warehouse_location,warehouse_size) VALUES (1,'Atlanta',5000),(2,'Dallas',6000),(3,'Seattle',4000);
SELECT warehouse_location, warehouse_size FROM warehouse_management;
What is the total biomass of fish in the Atlantic Ocean by country?
CREATE TABLE atlantic_countries (country VARCHAR(255),id INTEGER); INSERT INTO atlantic_countries (country,id) VALUES ('Spain',1),('Norway',2); CREATE TABLE fish_biomass_atlantic (country_id INTEGER,value FLOAT);
SELECT a.country, SUM(fb.value) FROM fish_biomass_atlantic fb JOIN atlantic_countries a ON fb.country_id = a.id GROUP BY a.country;
How many times has each artist performed at music festivals?
CREATE TABLE artist_festivals (artist_id INT,festival_name VARCHAR(30)); INSERT INTO artist_festivals (artist_id,festival_name) VALUES (1,'Coachella'),(2,'Osheaga'),(3,'Bonnaroo'),(1,'Lollapalooza'),(2,'Glastonbury');
SELECT artist_id, COUNT(DISTINCT festival_name) as festival_count FROM artist_festivals GROUP BY artist_id;
What is the average cost of materials for water treatment plants constructed in California since 2010, ordered by the date of construction?
CREATE TABLE water_treatment_plants (id INT,location VARCHAR(255),construction_date DATE,material_cost FLOAT); INSERT INTO water_treatment_plants (id,location,construction_date,material_cost) VALUES (1,'California','2010-01-01',5000000),(2,'California','2011-01-01',5500000),(3,'California','2012-01-01',6000000);
SELECT AVG(material_cost) FROM water_treatment_plants WHERE location = 'California' AND construction_date >= '2010-01-01' GROUP BY construction_date ORDER BY construction_date;
Find the average sustainability score of suppliers in each country and the number of suppliers in those countries.
CREATE TABLE suppliers (id INT PRIMARY KEY,name VARCHAR(100),location VARCHAR(100),sustainability_score INT); INSERT INTO suppliers (id,name,location,sustainability_score) VALUES (1,'Supplier A','Country A',85),(2,'Supplier B','Country A',90),(3,'Supplier C','Country B',70),(4,'Supplier D','Country B',75),(5,'Supplier ...
SELECT s.location, AVG(s.sustainability_score) avg_score, COUNT(s.id) supplier_count FROM suppliers s GROUP BY s.location;
What is the average monthly mobile data usage in South Korea for the last 12 months?
CREATE TABLE korea_data (user_id INT,data_usage FLOAT,month INT); INSERT INTO korea_data (user_id,data_usage,month) VALUES (1,4.5,1),(2,3.9,2),(3,4.2,3),(4,4.8,4),(5,3.7,5),(6,3.6,6),(7,4.1,7),(8,4.3,8),(9,3.8,9),(10,4.0,10),(11,4.4,11),(12,3.5,12);
SELECT AVG(data_usage) as avg_data_usage FROM korea_data WHERE month BETWEEN 1 AND 12;
Add the artist_id column to the "art_exhibitions" table with data type INT.
CREATE TABLE art_exhibitions (exhibition_id INT,exhibition_name VARCHAR(50),start_date DATE,end_date DATE,location VARCHAR(50),artist_id INT);
ALTER TABLE art_exhibitions ADD artist_id INT;
List all mechanical failures of aircraft manufactured in Brazil.
CREATE TABLE Incidents (IncidentID INT,ReportDate DATE,Location VARCHAR(50),Type VARCHAR(50),Description TEXT,Manufacturer VARCHAR(50)); INSERT INTO Incidents (IncidentID,ReportDate,Location,Type,Description,Manufacturer) VALUES (3,'2021-05-12','Flight','Mechanical Failure','Flap system malfunction','Embraer');
SELECT IncidentID, ReportDate, Location FROM Incidents WHERE Type = 'Mechanical Failure' AND Manufacturer = 'Embraer';
What is the average subscription fee for mobile subscribers per month?
CREATE TABLE mobile_subscriber (subscriber_id INT,subscription_start_date DATE,subscription_fee DECIMAL(10,2)); INSERT INTO mobile_subscriber (subscriber_id,subscription_start_date,subscription_fee) VALUES (1,'2020-01-01',30.00),(2,'2019-06-15',40.00),(3,'2021-02-20',35.00); CREATE TABLE subscription_duration (subscrib...
SELECT AVG(subscription_fee / DATEDIFF(subscription_end_date, subscription_start_date)) as avg_fee_per_month FROM mobile_subscriber JOIN subscription_duration ON mobile_subscriber.subscriber_id = subscription_duration.subscriber_id;
Update the production budget for the movie "MovieA" to 18000000.
CREATE TABLE movies (id INT,title VARCHAR(100),genre VARCHAR(50),release_year INT,production_budget INT); INSERT INTO movies (id,title,genre,release_year,production_budget) VALUES (1,'MovieA','Action',2005,15000000); INSERT INTO movies (id,title,genre,release_year,production_budget) VALUES (2,'MovieB','Action',2002,200...
UPDATE movies SET production_budget = 18000000 WHERE title = 'MovieA';
What is the average age of tugboats in the 'tugboat' table?
CREATE TABLE tugboat (id INT,name VARCHAR(50),year_built INT,PRIMARY KEY (id));
SELECT AVG(year_built) FROM tugboat;