instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
What is the average rating of movies produced in the US and released between 2010 and 2015?
CREATE TABLE movies (id INT,title VARCHAR(255),rating FLOAT,release_year INT,country VARCHAR(50)); INSERT INTO movies (id,title,rating,release_year,country) VALUES (1,'Movie1',7.5,2010,'USA'),(2,'Movie2',8.2,2012,'USA'),(3,'Movie3',6.8,2015,'USA');
SELECT AVG(rating) FROM movies WHERE release_year BETWEEN 2010 AND 2015 AND country = 'USA';
Update the completion year of Project B in Canada to 2017.
CREATE TABLE smart_city_projects (id INT,name TEXT,country TEXT,completion_year INT); INSERT INTO smart_city_projects (id,name,country,completion_year) VALUES (1,'Project A','Canada',2016),(2,'Project B','Canada',NULL),(3,'Project C','USA',2018);
UPDATE smart_city_projects SET completion_year = 2017 WHERE name = 'Project B' AND country = 'Canada';
List all the unique network technologies invested in by the company.
CREATE TABLE network_investments (id INT,location VARCHAR(50),network_tech VARCHAR(30)); INSERT INTO network_investments (id,location,network_tech) VALUES (1,'City A','4G');
SELECT DISTINCT network_tech FROM network_investments;
Update the 'end_date' of the 'Missile Defense System' project for 'Purple Enterprises' to 2023-06-30 if the current end_date is before 2023-06-30.
CREATE TABLE PurpleEnterprisesProjects(id INT,contractor VARCHAR(255),project VARCHAR(255),start_date DATE,end_date DATE);INSERT INTO PurpleEnterprisesProjects(id,contractor,project,start_date,end_date) VALUES (1,'Purple Enterprises','Missile Defense System','2021-01-01','2022-12-31');
UPDATE PurpleEnterprisesProjects SET end_date = '2023-06-30' WHERE contractor = 'Purple Enterprises' AND project = 'Missile Defense System' AND end_date < '2023-06-30';
What is the total donation amount for each department in Q1 of 2023?
CREATE TABLE Donors (DonorID INT,DonorName VARCHAR(50)); INSERT INTO Donors (DonorID,DonorName) VALUES (1,'John Smith'),(2,'Jane Doe'); CREATE TABLE Donations (DonationID INT,DonorID INT,DonationDate DATE,Amount DECIMAL(10,2),Department VARCHAR(50)); INSERT INTO Donations (DonationID,DonorID,DonationDate,Amount,Department) VALUES (1,1,'2023-01-05',200.00,'Education'),(2,1,'2023-01-10',300.00,'Health'),(3,2,'2023-01-15',400.00,'Education');
SELECT Department, SUM(Amount) as TotalDonation FROM Donations WHERE QUARTER(DonationDate) = 1 AND Year(DonationDate) = 2023 GROUP BY Department;
What is the total number of AI-powered solutions implemented in hotels with a virtual tour engagement score of at least 75 in EMEA?
CREATE TABLE hotels (hotel_id INT,hotel_name TEXT,region TEXT); CREATE TABLE ai_solutions (solution_id INT,hotel_id INT,implemented_date DATE); CREATE TABLE virtual_tours (tour_id INT,hotel_id INT,engagement_score INT); INSERT INTO hotels (hotel_id,hotel_name,region) VALUES (1,'Scandinavian Retreat','EMEA'),(2,'Mediterranean Palace','EMEA'); INSERT INTO ai_solutions (solution_id,hotel_id,implemented_date) VALUES (1,1,'2021-02-01'),(2,1,'2021-03-01'),(1,2,'2021-01-01'),(2,2,'2021-02-01'); INSERT INTO virtual_tours (tour_id,hotel_id,engagement_score) VALUES (1,1,80),(2,1,85),(1,2,70),(2,2,90);
SELECT COUNT(DISTINCT ai_solutions.solution_id) AS total_solutions FROM ai_solutions INNER JOIN hotels ON ai_solutions.hotel_id = hotels.hotel_id INNER JOIN virtual_tours ON hotels.hotel_id = virtual_tours.hotel_id WHERE hotels.region = 'EMEA' AND virtual_tours.engagement_score >= 75;
Find all products that were discontinued before being sold in a sustainable package.
CREATE TABLE products (id INT,name TEXT,discontinued DATE,sustainable_package BOOLEAN);
SELECT name FROM products WHERE discontinued < (SELECT MIN(date) FROM sustainable_packages) AND sustainable_package = FALSE;
Update the salaries of all employees in the 'IT' department to 80,000.
CREATE TABLE Employees (EmployeeID INT,Department VARCHAR(255),Gender VARCHAR(255),Salary DECIMAL(10,2)); INSERT INTO Employees (EmployeeID,Department,Gender,Salary) VALUES (1,'IT','Male',75000.00),(2,'Diversity and Inclusion','Female',68000.00),(3,'HR','Male',65000.00);
UPDATE Employees SET Salary = 80000.00 WHERE Department = 'IT';
What is the maximum number of visitors allowed per day in Yellowstone National Park?
CREATE TABLE national_parks (id INT,name TEXT,daily_visitor_limit INT); INSERT INTO national_parks (id,name,daily_visitor_limit) VALUES (1,'Yellowstone National Park',9000);
SELECT MAX(daily_visitor_limit) FROM national_parks WHERE name = 'Yellowstone National Park';
What is the total number of artists who have created works in the 'drawing' medium?
CREATE TABLE works (id INT,artist_id INT,medium TEXT); INSERT INTO works (id,artist_id,medium) VALUES (1,1,'painting'),(2,2,'drawing'),(3,3,'sculpture'),(4,4,'drawing'),(5,5,'painting');
SELECT COUNT(DISTINCT artist_id) FROM works WHERE medium = 'drawing';
Who are the top 5 'DeFi' platforms with the highest daily transaction volume on the 'ETH' network in the last 30 days?
CREATE TABLE daily_transaction_volume (date DATE,platform_id INT,volume DECIMAL(10,2)); INSERT INTO daily_transaction_volume (date,platform_id,volume) VALUES ('2022-01-01',1,5000),('2022-01-02',1,5500),('2022-01-03',1,6000),('2022-01-01',2,3000),('2022-01-02',2,3500),('2022-01-03',2,4000); CREATE TABLE deFi_platforms (platform_id INT,platform_name VARCHAR(255),network VARCHAR(50)); INSERT INTO deFi_platforms (platform_id,platform_name,network) VALUES (1,'Uniswap','ETH'),(2,'Aave','ETH'),(3,'Compound','ETH');
SELECT dp.platform_name, SUM(dt.volume) as total_volume FROM daily_transaction_volume dt JOIN deFi_platforms dp ON dt.platform_id = dp.platform_id WHERE dt.date >= CURDATE() - INTERVAL 30 DAY GROUP BY dp.platform_name ORDER BY total_volume DESC LIMIT 5;
What is the maximum wildlife habitat size in pine forests?
CREATE TABLE pine_forests (id INT,area FLOAT); INSERT INTO pine_forests VALUES (1,22.33),(2,44.55),(3,66.77);
SELECT MAX(area) FROM pine_forests;
List all heritage sites with more than 5 traditional art pieces, their respective art piece counts, and the average value.
CREATE TABLE HeritageSites (SiteID INT,Name VARCHAR(50),Location VARCHAR(50),ArtPieceID INT); INSERT INTO HeritageSites VALUES (1,'Taj Mahal','India',101),(2,'Machu Picchu','Peru',201),(3,'Angkor Wat','Cambodia',301); CREATE TABLE ArtPieces (ArtPieceID INT,Name VARCHAR(50),Type VARCHAR(50),Value INT); INSERT INTO ArtPieces VALUES (101,'Painting 1','Traditional',1000),(201,'Sculpture 1','Traditional',2000),(301,'Painting 2','Traditional',3000);
SELECT hs.Name AS HeritageSite, COUNT(ap.ArtPieceID) AS ArtPieceCount, AVG(ap.Value) AS AvgValue FROM HeritageSites hs JOIN ArtPieces ap ON hs.ArtPieceID = ap.ArtPieceID WHERE ap.Type = 'Traditional' GROUP BY hs.Name HAVING COUNT(ap.ArtPieceID) > 5 ORDER BY AvgValue DESC;
Create a view named 'demographics_summary' based on the 'member_demographics' table
CREATE TABLE member_demographics (member_id INT,age INT,gender VARCHAR(10),city VARCHAR(50),state VARCHAR(20),country VARCHAR(50));
CREATE VIEW demographics_summary AS SELECT country, gender, city, COUNT(*) as member_count FROM member_demographics GROUP BY country, gender, city;
What are the case numbers and types of Restorative Justice interventions for cases with victims from South Asia in New York?
CREATE TABLE victims (id INT,name VARCHAR(255),age INT,gender VARCHAR(10),ethnicity VARCHAR(50)); INSERT INTO victims (id,name,age,gender,ethnicity) VALUES (1,'Raj Patel',42,'Male','South Asian'); INSERT INTO victims (id,name,age,gender,ethnicity) VALUES (2,'Priya Kapoor',36,'Female','South Asian'); CREATE TABLE restorative_justice (case_id INT,type VARCHAR(50),facilitator VARCHAR(255),victim_id INT); INSERT INTO restorative_justice (case_id,type,facilitator,victim_id) VALUES (1,'Restorative Circles','Susan Kim',1); INSERT INTO restorative_justice (case_id,type,facilitator,victim_id) VALUES (2,'Victim-Offender Mediation','Michael Chen',2); CREATE TABLE cases (id INT,victim_id INT,case_number VARCHAR(50),location VARCHAR(100)); INSERT INTO cases (id,victim_id,case_number,location) VALUES (1,1,'2021-CJR-0001','New York'); INSERT INTO cases (id,victim_id,case_number,location) VALUES (2,2,'2022-CJR-0002','New York');
SELECT c.case_number, rj.type FROM cases c JOIN restorative_justice rj ON c.id = rj.case_id WHERE c.victim_id IN (SELECT id FROM victims WHERE ethnicity = 'South Asian') AND rj.location = 'New York';
Calculate the average speed of autonomous buses in London
CREATE TABLE bus_trips (id INT,bus_type VARCHAR(50),bus_start_location VARCHAR(50),bus_end_location VARCHAR(50),distance FLOAT,travel_time FLOAT);
SELECT AVG(distance / travel_time) AS avg_speed FROM bus_trips WHERE bus_type = 'autonomous' AND bus_start_location = 'London';
Find the team with the highest total number of training hours in the 'workforce_training' table.
CREATE TABLE workforce_training (team VARCHAR(50),total_hours FLOAT); INSERT INTO workforce_training (team,total_hours) VALUES ('engineering',12.3),('production',14.7),('maintenance',NULL);
SELECT team, MAX(total_hours) OVER () AS max_total_hours FROM workforce_training WHERE total_hours IS NOT NULL;
What is the average account balance of customers who have invested in the real estate sector?
CREATE TABLE Customers (CustomerID INT,Name VARCHAR(50),AccountBalance DECIMAL(18,2));CREATE TABLE Investments (CustomerID INT,InvestmentType VARCHAR(10),Sector VARCHAR(10));INSERT INTO Customers VALUES (1,'John Doe',25000.00),(2,'Jane Smith',30000.00),(3,'Bob Johnson',40000.00);INSERT INTO Investments VALUES (1,'Stocks','Real Estate'),(2,'Stocks','Real Estate'),(3,'Stocks','Healthcare');
SELECT AVG(c.AccountBalance) FROM Customers c INNER JOIN Investments i ON c.CustomerID = i.CustomerID WHERE i.Sector = 'Real Estate';
What was the average cost of agricultural innovation projects in Rwanda in 2020?'
CREATE TABLE agricultural_innovation_projects (id INT,country VARCHAR(255),year INT,cost FLOAT); INSERT INTO agricultural_innovation_projects (id,country,year,cost) VALUES (1,'Rwanda',2020,30000.00),(2,'Rwanda',2020,35000.00);
SELECT AVG(cost) FROM agricultural_innovation_projects WHERE country = 'Rwanda' AND year = 2020;
Retrieve the policy numbers, policyholder names, car models, and policy effective dates for policyholders who own a 'Ford' or 'Subaru' vehicle and live in 'Texas'
CREATE TABLE policyholders (policy_number INT,policyholder_name VARCHAR(50),car_make VARCHAR(20),car_model VARCHAR(20),policyholder_state VARCHAR(20),policy_effective_date DATE);
SELECT policy_number, policyholder_name, car_model, policy_effective_date FROM policyholders WHERE (car_make = 'Ford' OR car_make = 'Subaru') AND policyholder_state = 'Texas';
What are the average consumer ratings for cruelty-free cosmetics products in the skincare category?
CREATE TABLE cosmetics_products(product_id INT,product_name VARCHAR(100),category VARCHAR(50),cruelty_free BOOLEAN,consumer_rating FLOAT);
SELECT AVG(consumer_rating) FROM cosmetics_products WHERE category = 'skincare' AND cruelty_free = TRUE;
How many mental health facilities are there in each state?
CREATE TABLE mental_health_facilities (facility_id INT,name VARCHAR(50),state VARCHAR(25)); INSERT INTO mental_health_facilities (facility_id,name,state) VALUES (1,'Example MHF','California'); INSERT INTO mental_health_facilities (facility_id,name,state) VALUES (2,'Another MHF','New York'); INSERT INTO mental_health_facilities (facility_id,name,state) VALUES (3,'Third MHF','Texas');
SELECT state, COUNT(*) FROM mental_health_facilities GROUP BY state;
What is the percentage of organic hair care products in France?
CREATE TABLE products (product_id INT,name VARCHAR(100),is_organic BOOLEAN,category VARCHAR(50),country VARCHAR(50)); INSERT INTO products (product_id,name,is_organic,category,country) VALUES (1,'Shampoo',true,'Hair Care','France'); INSERT INTO products (product_id,name,is_organic,category,country) VALUES (2,'Conditioner',false,'Hair Care','France');
SELECT (COUNT(*) * 100.0 / (SELECT COUNT(*) FROM products WHERE category = 'Hair Care' AND country = 'France')) AS percentage FROM products WHERE is_organic = true AND category = 'Hair Care' AND country = 'France';
Show the number of citizens who have provided feedback in the last 3 months
CREATE TABLE citizen_feedback (citizen_id INT,feedback TEXT,feedback_date DATE);
SELECT COUNT(*) FROM citizen_feedback WHERE feedback_date >= DATE_SUB(CURRENT_DATE, INTERVAL 3 MONTH);
How many countries have marine protected areas in the Arctic Ocean?
CREATE TABLE marine_protected_areas (area_name TEXT,location TEXT,country TEXT); INSERT INTO marine_protected_areas (area_name,location,country) VALUES ('Norwegian Arctic National Park','Arctic Ocean','Norway'),('Canadian Arctic Archipelago Park','Arctic Ocean','Canada');
SELECT COUNT(DISTINCT country) FROM marine_protected_areas WHERE location = 'Arctic Ocean';
Retrieve the product names and their suppliers for all products made in 'Brazil'.
CREATE TABLE products (product_id INT,product_name TEXT,supplier_id INT,manufacturer_country TEXT); INSERT INTO products (product_id,product_name,supplier_id,manufacturer_country) VALUES (1,'Product X',1001,'Brazil'),(2,'Product Y',1002,'Argentina'),(3,'Product Z',1003,'Brazil');
SELECT product_name, supplier_id FROM products WHERE manufacturer_country = 'Brazil';
What is the maximum budget for peacekeeping operations in Oceania in 2018?
CREATE TABLE PeacekeepingOperations (id INT PRIMARY KEY,operation VARCHAR(100),location VARCHAR(50),year INT,budget INT); INSERT INTO PeacekeepingOperations (id,operation,location,year,budget) VALUES (3,'Pacific Partnership','Papua New Guinea',2018,45678901);
SELECT MAX(budget) FROM PeacekeepingOperations WHERE location LIKE '%Oceania%' AND year = 2018;
What is the total production of soybean crops by continent?
CREATE TABLE Continent (id INT,name VARCHAR(255)); INSERT INTO Continent (id,name) VALUES (1,'Africa'),(2,'Asia'),(3,'Europe'),(4,'North America'),(5,'South America'); CREATE TABLE Crop (id INT,name VARCHAR(255),continent_id INT,production INT); INSERT INTO Crop (id,name,continent_id,production) VALUES (1,'Soybean',2,1000),(2,'Rice',3,1500),(3,'Soybean',5,800);
SELECT SUM(Crop.production) FROM Crop INNER JOIN Continent ON Crop.continent_id = Continent.id WHERE Crop.name = 'Soybean';
What is the average depth of all marine species in the Pacific basin, grouped by species name?
CREATE TABLE marine_species_avg_depths (name VARCHAR(255),basin VARCHAR(255),depth FLOAT); INSERT INTO marine_species_avg_depths (name,basin,depth) VALUES ('Species1','Atlantic',123.45),('Species2','Pacific',567.89),('Species3','Indian',345.67),('Species4','Atlantic',789.10);
SELECT name, AVG(depth) as avg_depth FROM marine_species_avg_depths WHERE basin = 'Pacific' GROUP BY name;
What is the maximum price of samarium produced in China?
CREATE TABLE samarium_production (country VARCHAR(255),price DECIMAL(10,2)); INSERT INTO samarium_production (country,price) VALUES ('China',70.50);
SELECT MAX(price) FROM samarium_production WHERE country = 'China';
Minimum weight of 'ceramic' artifacts in 'asia_artifacts'
CREATE TABLE asia_artifacts (id INT,site_name VARCHAR(50),artifact_name VARCHAR(50),period VARCHAR(20),weight INT);
SELECT MIN(weight) FROM asia_artifacts WHERE artifact_name = 'ceramic';
Update the area of study for researcher 'John Smith' to 'Climate Change'.
CREATE TABLE researchers (id INT PRIMARY KEY,name VARCHAR(100),affiliation VARCHAR(100),area_of_study VARCHAR(100)); INSERT INTO researchers (id,name,affiliation,area_of_study) VALUES (1,'John Smith','Arctic Institute','Biodiversity');
UPDATE researchers SET area_of_study = 'Climate Change' WHERE name = 'John Smith';
How many security incidents were there in the education sector in the last quarter?
CREATE TABLE security_incidents (id INT,sector VARCHAR(20),date DATE); INSERT INTO security_incidents (id,sector,date) VALUES (1,'education','2022-03-01'),(2,'education','2022-05-15');
SELECT COUNT(*) FROM security_incidents WHERE sector = 'education' AND date >= DATEADD(quarter, -1, GETDATE());
What is the maximum revenue generated in a single day for each game?
CREATE TABLE DailyRevenue (Date date,GameID int,Revenue int); INSERT INTO DailyRevenue (Date,GameID,Revenue) VALUES ('2022-01-01',1,2000),('2022-01-02',1,3000),('2022-01-01',2,2500),('2022-01-02',2,3500),('2022-01-01',3,1500),('2022-01-02',3,2500);
SELECT G.GameName, MAX(DR.Revenue) as MaxRevenue FROM DailyRevenue DR JOIN Games G ON DR.GameID = G.GameID GROUP BY G.GameName;
Which countries had the highest sustainable fashion metrics in the past year?
CREATE TABLE country_metric (id INT,country TEXT,metric FLOAT,date DATE);
SELECT country, AVG(metric) FROM country_metric WHERE date >= DATE_SUB(CURDATE(), INTERVAL 1 YEAR) GROUP BY country ORDER BY AVG(metric) DESC;
How many infectious disease reports were made by medical facilities in Texas?
CREATE TABLE facility (name TEXT,state TEXT,type TEXT);
SELECT COUNT(*) FROM (SELECT f.name, f.state, f.type FROM facility f JOIN report r ON f.name = r.facility_name WHERE f.state = 'Texas' AND r.disease_type = 'infectious') AS subquery;
Insert a new record of a donation made by 'Bob Johnson' for $1000 on 2023-01-01.
CREATE TABLE Donors (donor_id INT,donor_name TEXT,donation_amount DECIMAL,donation_date DATE);
INSERT INTO Donors (donor_id, donor_name, donation_amount, donation_date) VALUES (NULL, 'Bob Johnson', 1000, '2023-01-01');
Which OTAs in Australia have the highest number of hotel listings with AI-powered services?
CREATE TABLE ota_hotel (ota_id INT,ota_name TEXT,region TEXT,ai_powered TEXT,hotel_listings INT); INSERT INTO ota_hotel (ota_id,ota_name,region,ai_powered,hotel_listings) VALUES (1,'TravelEase','Australia','yes',1000),(2,'VoyagePlus','Australia','no',800),(3,'ExploreNow','Australia','yes',1200);
SELECT ota_name, MAX(hotel_listings) FROM ota_hotel WHERE region = 'Australia' AND ai_powered = 'yes' GROUP BY ota_name
Find the difference in budget allocation between police and transportation from 2021 to 2022.
CREATE TABLE budget_2021 (service TEXT,budget INTEGER); INSERT INTO budget_2021 (service,budget) VALUES ('Police',1000000),('Transportation',800000);
SELECT (COALESCE(SUM(budget_2022.budget), 0) - COALESCE(SUM(budget_2021.budget), 0)) FROM budget_2022 FULL OUTER JOIN budget_2021 ON budget_2022.service = budget_2021.service WHERE service IN ('Police', 'Transportation');
Update the "offenders" table to change the offense from "burglary" to "robbery" for the offender with id 3
CREATE TABLE offenders (id INT,first_name VARCHAR(20),last_name VARCHAR(20),offense VARCHAR(20),state VARCHAR(20)); INSERT INTO offenders (id,first_name,last_name,offense,state) VALUES (1,'John','Doe','theft','NY'); INSERT INTO offenders (id,first_name,last_name,offense,state) VALUES (2,'Jane','Doe','murder','CA'); INSERT INTO offenders (id,first_name,last_name,offense,state) VALUES (3,'Bob','Smith','burglary','TX');
UPDATE offenders SET offense = 'robbery' WHERE id = 3;
What is the average attendance at events in Canada and the United States?
CREATE TABLE Events (EventID INT,Name TEXT,Attendance INT);CREATE TABLE EventLocations (EventID INT,Country TEXT);
SELECT AVG(Events.Attendance) FROM Events INNER JOIN EventLocations ON Events.EventID = EventLocations.EventID WHERE EventLocations.Country IN ('Canada', 'United States');
Create a view to show the total number of autonomous vehicles in each city
CREATE TABLE autonomous_vehicles (id INT PRIMARY KEY,city VARCHAR(255),type VARCHAR(255),num_vehicles INT);
CREATE VIEW autonomous_vehicles_by_city AS SELECT city, SUM(num_vehicles) as total_autonomous_vehicles FROM autonomous_vehicles WHERE type = 'Autonomous' GROUP BY city;
How many technology accessibility assessments were conducted in Q2 2021?
CREATE TABLE tech_accessibility_assessments (id INT,assessment_date DATE); INSERT INTO tech_accessibility_assessments (id,assessment_date) VALUES (1,'2021-04-15'),(2,'2021-06-30'),(3,'2021-02-28');
SELECT COUNT(*) FROM tech_accessibility_assessments WHERE assessment_date BETWEEN '2021-04-01' AND '2021-06-30';
How many security incidents were there in Q2 2022 that originated from India?
CREATE TABLE SecurityIncidents (id INT,incident_name VARCHAR(255),country VARCHAR(255),date DATE); INSERT INTO SecurityIncidents (id,incident_name,country,date) VALUES (2,'Ransomware Attack','India','2022-04-15');
SELECT COUNT(*) FROM SecurityIncidents WHERE country = 'India' AND date >= '2022-04-01' AND date < '2022-07-01';
What is the minimum water usage for mining operations in Asia?
CREATE TABLE MiningOperations (OperationID INT,MineName VARCHAR(50),Location VARCHAR(50),WaterUsage INT); INSERT INTO MiningOperations (OperationID,MineName,Location,WaterUsage) VALUES (1,'Ruby Mine','India',3000),(2,'Sapphire Mine','Thailand',4000),(3,'Emerald Mine','China',5000);
SELECT MIN(WaterUsage) FROM MiningOperations WHERE Location LIKE 'Asia%';
Delete companies with ESG rating below 70.
CREATE TABLE companies (id INT,sector TEXT,ESG_rating FLOAT); INSERT INTO companies (id,sector,ESG_rating) VALUES (1,'technology',78.2),(2,'finance',82.5),(3,'technology',64.6);
DELETE FROM companies WHERE ESG_rating < 70;
What are the top 3 genres by average revenue from concert ticket sales?
CREATE TABLE concerts (id INT,artist VARCHAR(50),genre VARCHAR(50),tickets_sold INT,revenue DECIMAL(10,2)); INSERT INTO concerts (id,artist,genre,tickets_sold,revenue) VALUES (1,'Taylor Swift','Pop',15000,2500000); INSERT INTO concerts (id,artist,genre,tickets_sold,revenue) VALUES (2,'BTS','K-Pop',20000,3000000); INSERT INTO concerts (id,artist,genre,tickets_sold,revenue) VALUES (3,'Metallica','Rock',12000,1800000); INSERT INTO concerts (id,artist,genre,tickets_sold,revenue) VALUES (4,'Adele','Pop',18000,2700000);
SELECT genre, AVG(revenue) as avg_revenue FROM concerts GROUP BY genre ORDER BY avg_revenue DESC LIMIT 3;
Delete ocean floor mapping projects that were completed before 2010
CREATE TABLE ocean_floor_mapping_projects (id INT PRIMARY KEY,project_name VARCHAR(255),start_date DATE,end_date DATE,budget FLOAT);
DELETE FROM ocean_floor_mapping_projects WHERE end_date < '2010-01-01';
Identify heritage sites in India with an average visitor count greater than 150 and at least 3 associated events in the last 2 years.
CREATE TABLE HeritageSites (id INT,name VARCHAR(255),country VARCHAR(255),UNIQUE (id)); CREATE TABLE Events (id INT,name VARCHAR(255),heritage_site_id INT,year INT,UNIQUE (id),FOREIGN KEY (heritage_site_id) REFERENCES HeritageSites(id)); CREATE TABLE VisitorStatistics (id INT,heritage_site_id INT,year INT,visitor_count INT,PRIMARY KEY (id),FOREIGN KEY (heritage_site_id) REFERENCES HeritageSites(id));
SELECT hs.name FROM HeritageSites hs JOIN Events e ON hs.id = e.heritage_site_id JOIN VisitorStatistics vs ON hs.id = vs.heritage_site_id WHERE hs.country = 'India' GROUP BY hs.name HAVING COUNT(DISTINCT e.id) >= 3 AND AVG(vs.visitor_count) > 150 AND e.year BETWEEN 2020 AND 2022;
Update the fare for 'Light Rail' rides
CREATE TABLE fares (ride_type TEXT,fare DECIMAL(5,2)); CREATE TABLE light_rail_fares AS SELECT * FROM fares WHERE ride_type = 'Light Rail';
UPDATE light_rail_fares SET fare = 2.00 WHERE ride_type = 'Light Rail';
What is the average response time for emergency calls in the 'county' schema in Q2 2022?
CREATE SCHEMA if not exists county; CREATE TABLE if not exists county.emergency_responses (id INT,response_time TIME,call_date DATE); INSERT INTO county.emergency_responses (id,response_time,call_date) VALUES (1,'01:34:00','2022-04-25'),(2,'02:15:00','2022-06-12'),(3,'01:52:00','2022-07-03');
SELECT AVG(TIME_TO_SEC(response_time)) FROM county.emergency_responses WHERE QUARTER(call_date) = 2 AND YEAR(call_date) = 2022;
What was the minimum military spending by a country in the European Union in 2020?
CREATE TABLE eu_military_spending (id INT,country VARCHAR(255),year INT,spending FLOAT); INSERT INTO eu_military_spending (id,country,year,spending) VALUES (1,'Germany',2020,55.0),(2,'France',2020,50.0),(3,'United Kingdom',2020,52.0),(4,'Italy',2020,47.0),(5,'Spain',2020,43.0);
SELECT MIN(spending) FROM eu_military_spending WHERE year = 2020;
What is the maximum number of vulnerabilities reported per day in the last month?
CREATE TABLE vulnerabilities (id INT,reported_date DATE,num_vulnerabilities INT); INSERT INTO vulnerabilities (id,reported_date,num_vulnerabilities) VALUES (1,'2021-10-01',5); INSERT INTO vulnerabilities (id,reported_date,num_vulnerabilities) VALUES (2,'2021-10-03',7); INSERT INTO vulnerabilities (id,reported_date,num_vulnerabilities) VALUES (3,'2021-11-05',3);
SELECT reported_date, num_vulnerabilities FROM vulnerabilities WHERE reported_date >= DATE_SUB(CURDATE(), INTERVAL 1 MONTH) AND num_vulnerabilities = (SELECT MAX(num_vulnerabilities) FROM vulnerabilities WHERE reported_date >= DATE_SUB(CURDATE(), INTERVAL 1 MONTH));
Delete startups that have no funding records.
CREATE TABLE startups (id INT,name TEXT,location TEXT,founder_gender TEXT,funding_amount INT); INSERT INTO startups (id,name,location,founder_gender,funding_amount) VALUES (1,'Startup A','USA','male',3000000); INSERT INTO startups (id,name,location,founder_gender,funding_amount) VALUES (2,'Startup B','Canada','female',NULL);
DELETE FROM startups WHERE funding_amount IS NULL;
What is the number of research stations in the Arctic Circle?
CREATE TABLE research_stations (name TEXT,location TEXT); INSERT INTO research_stations (name,location) VALUES ('Norilsk Research Station','Arctic Circle'),('Abisko Research Station','Arctic Circle');
SELECT COUNT(*) FROM research_stations WHERE location = 'Arctic Circle';
Add a new 'Bike Share' station in 'Central Park'
CREATE TABLE bike_stations (station_id INT PRIMARY KEY,station_name TEXT,location TEXT);
INSERT INTO bike_stations (station_id, station_name, location) VALUES (1, 'Bike Share', 'Central Park');
Update the production rate for well_id 1 to 1100.
CREATE TABLE wells (well_id INT,well_type VARCHAR(10),location VARCHAR(20),production_rate FLOAT); INSERT INTO wells (well_id,well_type,location,production_rate) VALUES (1,'offshore','Gulf of Mexico',1000),(2,'onshore','Texas',800),(3,'offshore','North Sea',1200);
UPDATE wells SET production_rate = 1100 WHERE well_id = 1;
What is the total number of properties in each city in the state of California?
CREATE TABLE properties (id INT,city VARCHAR(255)); INSERT INTO properties (id,city) VALUES (1,'San Francisco'),(2,'Los Angeles'),(3,'San Diego'),(4,'San Jose'),(5,'San Francisco');
SELECT city, COUNT(*) FROM properties GROUP BY city;
What was the average fare per trip for each vehicle type in the first quarter of 2022?
CREATE TABLE trip (trip_id INT,vehicle_id INT,route_id INT,fare FLOAT); INSERT INTO trip (trip_id,vehicle_id,route_id,fare) VALUES (1,1,1,3.5),(2,1,2,4.0),(3,2,1,3.5),(4,2,2,4.0),(5,3,1,2.5),(6,3,2,3.0); CREATE TABLE vehicle (vehicle_id INT,type TEXT); INSERT INTO vehicle (vehicle_id,type) VALUES (1,'Bus'),(2,'Tram'),(3,'Trolleybus');
SELECT vehicle.type, AVG(trip.fare) as avg_fare FROM trip JOIN vehicle ON trip.vehicle_id = vehicle.vehicle_id WHERE trip.trip_id BETWEEN 1 AND (SELECT MAX(trip_id) FROM trip WHERE trip.trip_date < '2022-04-01' AND EXTRACT(MONTH FROM trip.trip_date) < 4) GROUP BY vehicle.type;
Insert new records into 'ethical_manufacturing'
CREATE TABLE ethical_manufacturing (id INT PRIMARY KEY,company VARCHAR(50),location VARCHAR(50),ethical_rating FLOAT); WITH ins AS (VALUES (1,'GreenTech','USA',4.2),(2,'EcoInnovations','Canada',4.6)) INSERT INTO ethical_manufacturing (id,company,location,ethical_rating) SELECT * FROM ins;
WITH ins AS (VALUES (1, 'GreenTech', 'USA', 4.2), (2, 'EcoInnovations', 'Canada', 4.6)) INSERT INTO ethical_manufacturing (id, company, location, ethical_rating) SELECT * FROM ins;
What is the minimum number of hearings for a case in the state of New York in the year 2021?
CREATE TABLE case_hearings (hearing_id INT,case_id INT,state VARCHAR(20),year INT); INSERT INTO case_hearings (hearing_id,case_id,state,year) VALUES (1,1,'New York',2021),(2,1,'New York',2021),(3,2,'New York',2022);
SELECT MIN(count) FROM (SELECT case_id, COUNT(*) as count FROM case_hearings WHERE state = 'New York' AND year = 2021 GROUP BY case_id) as subquery;
Get the total number of trips made by electric buses and autonomous taxis in Tokyo and Seoul.
CREATE TABLE tokyo_ev_trips (vehicle_id INT,trips INT,type VARCHAR(20)); CREATE TABLE seoul_ev_trips (vehicle_id INT,trips INT,type VARCHAR(20)); INSERT INTO tokyo_ev_trips (vehicle_id,trips,type) VALUES (1,10,'Bus'),(2,20,'Car'),(3,30,'Taxi'); INSERT INTO seoul_ev_trips (vehicle_id,trips,type) VALUES (4,40,'Bus'),(5,50,'Car'),(6,60,'Taxi');
SELECT SUM(trips) FROM tokyo_ev_trips WHERE type IN ('Bus', 'Taxi') UNION ALL SELECT SUM(trips) FROM seoul_ev_trips WHERE type IN ('Bus', 'Taxi');
Update the donation amount to 150.00 for donor 'Alice Johnson' from Australia.
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',500.00,'2021-05-05'); INSERT INTO Donors (id,name,country,donation_amount,donation_date) VALUES (4,'Bob Brown','India',300.00,'2021-07-10');
UPDATE Donors SET donation_amount = 150.00 WHERE name = 'Alice Johnson' AND country = 'Australia';
Update the compliance status for a record in the regulatory_compliance table
CREATE TABLE regulatory_compliance (compliance_id INT,regulation_name VARCHAR(50),compliance_status VARCHAR(50),compliance_date DATE);
UPDATE regulatory_compliance SET compliance_status = 'Non-Compliant' WHERE compliance_id = 22222;
Delete all records from the DonorPrograms table where the program ID is not in the Education or Health categories.
CREATE TABLE DonorPrograms (DonorID INT,ProgramID INT); INSERT INTO DonorPrograms (DonorID,ProgramID) VALUES (1,101),(1,102),(2,102),(3,103),(3,104); CREATE TABLE ProgramCategories (CategoryID INT,Category TEXT); INSERT INTO ProgramCategories (CategoryID,Category) VALUES (1,'Education'),(2,'Health'),(3,'Environment'),(4,'Other'); CREATE TABLE Programs (ProgramID INT,CategoryID INT); INSERT INTO Programs (ProgramID,CategoryID) VALUES (101,1),(102,2),(103,3),(104,4);
DELETE DP FROM DonorPrograms DP WHERE DP.ProgramID NOT IN (SELECT P.ProgramID FROM Programs P INNER JOIN ProgramCategories PC ON P.CategoryID = PC.CategoryID WHERE PC.Category IN ('Education', 'Health'));
What are the mining operations with the oldest equipment?
CREATE TABLE MiningOperations (OperationID INT,EquipmentAge INT);
SELECT OperationID FROM MiningOperations WHERE ROW_NUMBER() OVER(ORDER BY EquipmentAge DESC) <= 3;
What is the total number of volunteers who participated in 'disaster response' activities in 'Asia'?
CREATE TABLE region (region_id INT,name VARCHAR(50)); INSERT INTO region (region_id,name) VALUES (1,'Asia'),(2,'South America'); CREATE TABLE activity (activity_id INT,name VARCHAR(50)); INSERT INTO activity (activity_id,name) VALUES (1,'Disaster response'),(2,'Community development'),(3,'Refugee support'); CREATE TABLE volunteers (volunteer_id INT,name VARCHAR(50),region_id INT,activity_id INT); INSERT INTO volunteers (volunteer_id,name,region_id,activity_id) VALUES (1,'Volunteer A',1,1),(2,'Volunteer B',1,1),(3,'Volunteer C',2,1),(4,'Volunteer D',2,2);
SELECT COUNT(*) FROM volunteers WHERE region_id = 1 AND activity_id = 1;
What are the total sales for organic products?
CREATE TABLE if not exists sales (id INT PRIMARY KEY,product_id INT,purchase_date DATE,quantity INT,price DECIMAL(5,2)); INSERT INTO sales (id,product_id,purchase_date,quantity,price) VALUES (4,3,'2022-03-01',1,9.99); CREATE TABLE if not exists product (id INT PRIMARY KEY,name TEXT,brand_id INT,is_organic BOOLEAN,price DECIMAL(5,2)); INSERT INTO product (id,name,brand_id,is_organic,price) VALUES (3,'Organic Moisturizer',2,true,9.99); CREATE TABLE if not exists brand (id INT PRIMARY KEY,name TEXT,category TEXT,country TEXT); INSERT INTO brand (id,name,category,country) VALUES (2,'Ecco Verde','Cosmetics','Austria');
SELECT SUM(quantity * price) FROM sales JOIN product ON sales.product_id = product.id WHERE product.is_organic = true;
Show the top 3 countries with the most companies founded
CREATE TABLE company_founding (company_name VARCHAR(255),founder_country VARCHAR(50)); INSERT INTO company_founding (company_name,founder_country) VALUES ('Acme Inc','USA'),('Beta Corp','Canada'),('Charlie LLC','USA'),('Delta Co','Mexico');
SELECT founder_country, COUNT(*) AS company_count FROM company_founding GROUP BY founder_country ORDER BY company_count DESC LIMIT 3;
What was the total sales revenue for each drug in 2020?
CREATE TABLE drug_sales (drug_name TEXT,quantity INTEGER,sale_price NUMERIC(10,2),year INTEGER); INSERT INTO drug_sales (drug_name,quantity,sale_price,year) VALUES ('DrugA',1200,120.50,2020),('DrugA',1500,122.00,2019),('DrugB',1400,150.75,2020),('DrugB',1600,145.00,2019);
SELECT drug_name, SUM(quantity * sale_price) as total_sales_revenue FROM drug_sales WHERE year = 2020 GROUP BY drug_name;
What was the total number of crimes reported in each borough for each month in the past year?
CREATE TABLE boroughs (borough_name VARCHAR(255)); INSERT INTO boroughs (borough_name) VALUES ('Bronx'),('Brooklyn'),('Manhattan'),('Queens'),('Staten Island'); CREATE TABLE crime_data (crime_date DATE,borough_name VARCHAR(255),crime_count INT);
SELECT b.borough_name, EXTRACT(MONTH FROM cd.crime_date) as month, SUM(cd.crime_count) as total_crimes FROM boroughs b JOIN crime_data cd ON b.borough_name = cd.borough_name WHERE cd.crime_date >= CURDATE() - INTERVAL 1 YEAR GROUP BY b.borough_name, month;
Show the number of workplace safety incidents per month, for the past year, for workplaces without a union, partitioned by employer.
CREATE TABLE safety_incidents (id INT,workplace INT,employer INT,incident_date DATE); INSERT INTO safety_incidents (id,workplace,employer,incident_date) VALUES (1,1,1,'2022-06-15'); INSERT INTO safety_incidents (id,workplace,employer,incident_date) VALUES (2,2,2,'2022-07-01'); INSERT INTO safety_incidents (id,workplace,employer,incident_date) VALUES (3,1,1,'2022-08-10');
SELECT employer, DATE_FORMAT(incident_date, '%Y-%m') as month, COUNT(*) as num_incidents FROM safety_incidents si INNER JOIN workplaces w ON si.workplace = w.id WHERE w.union_affiliation IS NULL GROUP BY employer, month ORDER BY STR_TO_DATE(month, '%Y-%m');
What is the maximum 'resilience_score' of bridges in the 'Europe' region that were built after 2000?
CREATE TABLE bridges (id INT,name TEXT,region TEXT,resilience_score FLOAT,year_built INT); INSERT INTO bridges (id,name,region,resilience_score,year_built) VALUES (1,'Golden Gate Bridge','West Coast',85.2,1937),(2,'Brooklyn Bridge','East Coast',76.3,1883),(3,'Bay Bridge','West Coast',90.1,1936),(4,'Chenab Bridge','South Asia',89.6,2010),(5,'Maputo Bay Bridge','Africa',72.8,1982),(6,'Sydney Harbour Bridge','Oceania',87.3,1932),(7,'Millau Viaduct','Europe',95.1,2004);
SELECT MAX(resilience_score) FROM bridges WHERE region = 'Europe' AND year_built > 2000;
How many cybersecurity incidents were reported in Asia in the last 3 years?
CREATE TABLE cybersecurity_incidents (region VARCHAR(50),year INT,num_incidents INT); INSERT INTO cybersecurity_incidents (region,year,num_incidents) VALUES ('Asia',2019,5000),('Asia',2020,6000),('Asia',2021,7000);
SELECT SUM(num_incidents) FROM cybersecurity_incidents WHERE region = 'Asia' AND year BETWEEN 2019 AND 2021;
What is the maximum amount of humanitarian assistance provided by any country in the year 2020?
CREATE TABLE humanitarian_assistance (country VARCHAR(50),year INT,amount FLOAT); INSERT INTO humanitarian_assistance (country,year,amount) VALUES ('USA',2020,3000000000),('China',2020,1000000000),('Japan',2020,2000000000),('India',2020,1500000000);
SELECT MAX(amount) FROM humanitarian_assistance WHERE year = 2020;
What is the maximum price of properties in the city of Istanbul, Turkey that are co-owned?
CREATE TABLE istanbul_real_estate(id INT,city VARCHAR(50),price DECIMAL(10,2),co_owned BOOLEAN); INSERT INTO istanbul_real_estate VALUES (1,'Istanbul',700000,true);
SELECT MAX(price) FROM istanbul_real_estate WHERE city = 'Istanbul' AND co_owned = true;
What is the success rate of medication treatments for patients with depression?
CREATE TABLE treatments (id INT,patient_id INT,medication VARCHAR(50),start_date DATE,end_date DATE,success BOOLEAN); CREATE VIEW depression_medications AS SELECT * FROM treatments WHERE condition = 'depression';
SELECT AVG(success) FROM depression_medications WHERE end_date IS NOT NULL;
What is the average energy efficiency score for renewable energy projects in each country?
CREATE TABLE Renewable_Energy_Projects (Project_ID INT,Country VARCHAR(50),Energy_Efficiency_Score FLOAT); INSERT INTO Renewable_Energy_Projects (Project_ID,Country,Energy_Efficiency_Score) VALUES (1,'USA',85.0),(2,'China',90.0),(3,'India',80.0),(4,'Germany',95.0),(5,'Brazil',88.0);
SELECT Country, AVG(Energy_Efficiency_Score) FROM Renewable_Energy_Projects GROUP BY Country;
Update the points scored by athletes in specific games
CREATE TABLE athletes (athlete_id INT,name VARCHAR(50),sport VARCHAR(50)); INSERT INTO athletes (athlete_id,name,sport) VALUES (1,'John Doe','Basketball'),(2,'Jane Smith','Soccer'); CREATE TABLE games (game_id INT,athlete_id INT,points INT); INSERT INTO games (game_id,athlete_id,points) VALUES (1,1,20),(2,1,30),(3,2,5);
UPDATE games SET points = CASE WHEN game_id = 1 THEN 25 WHEN game_id = 2 THEN 35 ELSE points END;
What is the visitor count by age group for the 'Art' department?
CREATE TABLE visitors (id INT,age_group TEXT,department TEXT); INSERT INTO visitors (id,age_group,department) VALUES (1,'0-17','Art'),(2,'18-25','Art');
SELECT department, age_group, COUNT(*) FROM visitors WHERE department = 'Art' GROUP BY department, age_group;
Insert a record with FieldID 101, Yield 35.6, and HarvestDate 2022-08-01 into the "HarvestYield" table
CREATE TABLE PrecisionAgriculture.HarvestYield (FieldID INT,Yield FLOAT,HarvestDate DATE);
INSERT INTO PrecisionAgriculture.HarvestYield (FieldID, Yield, HarvestDate) VALUES (101, 35.6, '2022-08-01');
What is the total energy consumption in terawatt-hours (TWh) for the United Kingdom and South Korea?
CREATE TABLE energy_consumption (country VARCHAR(50),consumption_twh INT); INSERT INTO energy_consumption (country,consumption_twh) VALUES ('United Kingdom',306.2),('South Korea',644.8);
SELECT SUM(consumption_twh) FROM energy_consumption WHERE country IN ('United Kingdom', 'South Korea');
Who are the top 5 donors by total donation amount?
CREATE TABLE Donations (DonationID INT,DonorID INT,DonationAmount DECIMAL(10,2)); INSERT INTO Donations (DonationID,DonorID,DonationAmount) VALUES (1,1,100.00),(2,1,200.00),(3,2,150.00);
SELECT DonorID, SUM(DonationAmount) AS TotalDonated FROM Donations GROUP BY DonorID ORDER BY TotalDonated DESC LIMIT 5;
Who are the bottom 2 brands in terms of sustainable material usage?
CREATE TABLE Brands (brand_id INT,brand_name VARCHAR(50)); CREATE TABLE Brand_Materials (brand_id INT,material_id INT,quantity INT); CREATE TABLE Materials (material_id INT,material_name VARCHAR(50),is_sustainable BOOLEAN); INSERT INTO Brands (brand_id,brand_name) VALUES (1,'EcoFabric'),(2,'GreenThreads'),(3,'SustainableStyle'),(4,'FairFashion'),(5,'BambooBrand'); INSERT INTO Materials (material_id,material_name,is_sustainable) VALUES (1,'Organic Cotton',true),(2,'Synthetic Fiber',false),(3,'Recycled Plastic',true),(4,'Bamboo Fiber',true); INSERT INTO Brand_Materials (brand_id,material_id,quantity) VALUES (1,1,600),(1,2,300),(2,1,800),(2,3,700),(3,1,400),(3,2,500),(4,4,1000),(5,2,1500);
SELECT brand_name, SUM(quantity) as total_quantity FROM Brands b INNER JOIN Brand_Materials bm ON b.brand_id = bm.brand_id INNER JOIN Materials m ON bm.material_id = m.material_id WHERE m.is_sustainable = false GROUP BY brand_name ORDER BY total_quantity ASC LIMIT 2;
What is the distribution of community health worker demographics by state?
CREATE TABLE CommunityHealthWorkerDemographics (WorkerID INT,State VARCHAR(2),Age INT,Gender VARCHAR(10)); INSERT INTO CommunityHealthWorkerDemographics (WorkerID,State,Age,Gender) VALUES (1,'NY',35,'Female'),(2,'CA',45,'Male'),(3,'TX',50,'Female');
SELECT State, COUNT(*) AS TotalWorkers, AVG(Age) AS AvgAge, COUNT(DISTINCT Gender) AS DistinctGenders FROM CommunityHealthWorkerDemographics GROUP BY State;
What is the maximum production quantity of Lanthanum in 2018?
CREATE TABLE production (year INT,element VARCHAR(10),quantity INT); INSERT INTO production (year,element,quantity) VALUES (2018,'Lanthanum',11000);
SELECT MAX(quantity) FROM production WHERE element = 'Lanthanum' AND year = 2018
What is the total manufacturing cost for each garment type?
CREATE TABLE garments (garment_id INT,garment_type VARCHAR(30),manufacturing_cost DECIMAL(10,2)); CREATE TABLE orders (order_id INT,garment_id INT,quantity INT);
SELECT garment_type, SUM(manufacturing_cost * quantity) AS total_cost FROM garments INNER JOIN orders ON garments.garment_id = orders.garment_id GROUP BY garment_type;
What is the average investment return for clients from the US and Canada?
CREATE TABLE clients (client_id INT,name TEXT,country TEXT,investment_return FLOAT); INSERT INTO clients (client_id,name,country,investment_return) VALUES (1,'John Doe','USA',0.07),(2,'Jane Smith','Canada',0.05);
SELECT AVG(investment_return) as avg_return FROM clients WHERE country IN ('USA', 'Canada');
Calculate the average salary for each job position from the 'salary' and 'position' tables
CREATE TABLE salary (id INT,employee_id INT,amount DECIMAL(5,2)); CREATE TABLE position (id INT,title VARCHAR(50),department_id INT,salary INT);
SELECT position.title, AVG(salary.amount) FROM position INNER JOIN salary ON position.id = salary.employee_id GROUP BY position.title;
Delete all copper mines in Australia with productivity below 1000?
CREATE TABLE mine (id INT,name TEXT,location TEXT,mineral TEXT,productivity INT); INSERT INTO mine (id,name,location,mineral,productivity) VALUES (1,'Olympic Dam','Australia','Copper',1200),(2,'Mount Isa','Australia','Copper',1500);
DELETE FROM mine WHERE mineral = 'Copper' AND location = 'Australia' AND productivity < 1000;
What is the total number of building permits issued, in each month, for the past year?
CREATE TABLE BuildingPermits (PermitIssueDate DATE);
SELECT DATEPART(YEAR, PermitIssueDate) as Year, DATEPART(MONTH, PermitIssueDate) as Month, COUNT(*) as PermitCount FROM BuildingPermits WHERE PermitIssueDate >= DATEADD(YEAR, -1, GETDATE()) GROUP BY DATEPART(YEAR, PermitIssueDate), DATEPART(MONTH, PermitIssueDate) ORDER BY Year, Month;
What is the minimum temperature recorded in the Arctic per season?
CREATE TABLE weather_data (id INT,date DATE,temp FLOAT);
SELECT MIN(temp) FROM weather_data WHERE date >= DATE_SUB(CURDATE(), INTERVAL 12 MONTH) GROUP BY QUARTER(date);
How many mobile subscribers use each technology type in each region, excluding subscribers with incomplete data?
CREATE TABLE mobile_subscribers (subscriber_id INT,technology VARCHAR(20),region VARCHAR(50),complete_data BOOLEAN); INSERT INTO mobile_subscribers (subscriber_id,technology,region,complete_data) VALUES (1,'4G','North',true),(2,'5G','North',false),(3,'3G','South',true),(4,'5G','East',true),(5,'5G','North',true);
SELECT technology, region, COUNT(*) AS subscribers FROM mobile_subscribers WHERE complete_data = true GROUP BY technology, region;
Get the number of REO types produced in each mine in 2022 from the reo_production table
CREATE TABLE reo_production (id INT PRIMARY KEY,reo_type VARCHAR(50),mine_name VARCHAR(50),production_year INT);
SELECT mine_name, COUNT(DISTINCT reo_type) FROM reo_production WHERE production_year = 2022 GROUP BY mine_name;
Find the total number of public transportation trips in the last month in Sydney?
CREATE TABLE public_transportation_trips (id INT,trip_date DATE,city VARCHAR(20),trips INT); INSERT INTO public_transportation_trips (id,trip_date,city,trips) VALUES (1,'2022-01-01','Sydney',500),(2,'2022-01-02','Sydney',600),(3,'2022-01-03','Sydney',700);
SELECT SUM(trips) FROM public_transportation_trips WHERE city = 'Sydney' AND trip_date >= DATEADD(day, -30, CURRENT_TIMESTAMP);
What is the maximum community service hours imposed in a single case involving a juvenile?
CREATE TABLE cases (id INT,case_type VARCHAR(20),offender_age INT,community_service_hours INT); INSERT INTO cases (id,case_type,offender_age,community_service_hours) VALUES (1,'Misdemeanor',16,50),(2,'Misdemeanor',17,100),(3,'Felony',21,200),(4,'Juvenile',14,150);
SELECT MAX(community_service_hours) FROM cases WHERE case_type = 'Juvenile';
Find the average horsepower of sports cars.
CREATE TABLE Cars (Id INT,Name VARCHAR(255),Type VARCHAR(255),Horsepower INT); INSERT INTO Cars (Id,Name,Type,Horsepower) VALUES (1,'Model S','Sedan',450),(2,'Model X','SUV',550),(3,'Model 3','Sports Car',350);
SELECT AVG(Horsepower) FROM Cars WHERE Type = 'Sports Car';
What is the average recycling rate for metal and glass in region X?
CREATE TABLE recycling (district TEXT,material TEXT,recycling_rate FLOAT); INSERT INTO recycling (district,material,recycling_rate) VALUES ('Region X','Metal',0.35),('Region X','Glass',0.43);
SELECT AVG(recycling_rate) FROM recycling WHERE district = 'Region X' AND material IN ('Metal', 'Glass');
Count the number of first-time visitors from different countries by exhibition.
CREATE TABLE visitor_locations (id INT,visitor_id INT,country TEXT,exhibition_id INT); INSERT INTO visitor_locations (id,visitor_id,country,exhibition_id) VALUES (1,1,'USA',1),(2,2,'Canada',1);
SELECT exhibition_id, country, COUNT(DISTINCT visitor_id) FROM visitor_locations GROUP BY exhibition_id, country;
What is the average sustainable sourcing score for each supplier?
CREATE TABLE supplier_scores (supplier_id INT,score INT); INSERT INTO supplier_scores (supplier_id,score) VALUES (1,85); INSERT INTO supplier_scores (supplier_id,score) VALUES (2,92); INSERT INTO supplier_scores (supplier_id,score) VALUES (3,78);
SELECT AVG(score) as avg_score FROM supplier_scores;