instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
What is the maximum water temperature in the 'Indian Ocean' region?
CREATE TABLE water_temperature (id INT,farm_id INT,region TEXT,temperature FLOAT); INSERT INTO water_temperature (id,farm_id,region,temperature) VALUES (1,1,'Indian Ocean',29.2),(2,1,'Indian Ocean',29.3),(3,2,'Atlantic Ocean',28.1);
SELECT MAX(water_temperature.temperature) FROM water_temperature WHERE water_temperature.region = 'Indian Ocean';
What are the names of customers who have invested in the healthcare sector but not in the technology sector?
CREATE TABLE Customers (CustomerID INT,Name VARCHAR(50));CREATE TABLE Investments (CustomerID INT,InvestmentType VARCHAR(10),Sector VARCHAR(10));INSERT INTO Customers VALUES (1,'John Doe'),(2,'Jane Smith'),(3,'Bob Johnson');INSERT INTO Investments VALUES (1,'Stocks','Healthcare'),(2,'Stocks','Technology'),(2,'Stocks','Healthcare'),(3,'Stocks','Healthcare'),(4,1,'Real Estate');
SELECT DISTINCT c.Name FROM Customers c INNER JOIN Investments i ON c.CustomerID = i.CustomerID WHERE i.Sector = 'Healthcare' AND c.CustomerID NOT IN (SELECT CustomerID FROM Investments WHERE Sector = 'Technology');
What is the total number of patients served by rural healthcare centers in India, excluding those served in the state of Tamil Nadu?
CREATE TABLE healthcare_centers_india (name TEXT,location TEXT,patients_served INT); INSERT INTO healthcare_centers_india (name,location,patients_served) VALUES ('HC A','Rural Tamil Nadu',100),('HC B','Rural Karnataka',200),('HC C','Rural Andhra Pradesh',150);
SELECT SUM(patients_served) as total_patients FROM healthcare_centers_india WHERE location NOT LIKE 'Rural Tamil Nadu%';
What is the average budget for support programs by disability type?
CREATE TABLE support_programs (program_id INT,program_name VARCHAR(50),budget INT,disability_type VARCHAR(50)); INSERT INTO support_programs (program_id,program_name,budget,disability_type) VALUES (1,'Assistive Technology',50000,'Physical');
SELECT disability_type, AVG(budget) as avg_budget FROM support_programs GROUP BY disability_type;
Find the total number of AI safety projects in Southeast Asia.
CREATE TABLE southeast_asian_countries (country TEXT); INSERT INTO southeast_asian_countries VALUES ('Indonesia'),('Malaysia'),('Philippines'),('Thailand'),('Vietnam'); CREATE TABLE ai_safety_projects (project_name TEXT,funding INTEGER,country TEXT);
SELECT COUNT(*) FROM ai_safety_projects WHERE country IN (SELECT * FROM southeast_asian_countries);
What is the total revenue generated by Latin music festivals in South America in 2024?
CREATE TABLE Festivals (id INT,name VARCHAR(50),country VARCHAR(50),year INT,revenue INT,genre VARCHAR(50)); INSERT INTO Festivals (id,name,country,year,revenue,genre) VALUES (1,'Rock in Rio','Brazil',2024,8000000,'Latin'),(2,'Lollapalooza','Argentina',2024,7000000,'Latin'),(3,'Vive Latino','Mexico',2024,6000000,'Latin');
SELECT SUM(revenue) FROM Festivals WHERE country IN ('Brazil', 'Argentina', 'Mexico') AND genre = 'Latin' AND year = 2024;
What is the average mental health parity score for patients in each community health worker's region?
CREATE TABLE CommunityHealthWorkers (CHW_ID INT,Region VARCHAR(50)); INSERT INTO CommunityHealthWorkers (CHW_ID,Region) VALUES (1,'North'),(2,'South'),(3,'East'),(4,'West'); CREATE TABLE MentalHealthScores (Patient_ID INT,CHW_ID INT,Parity_Score INT); INSERT INTO MentalHealthScores (Patient_ID,CHW_ID,Parity_Score) VALUES (1,1,80),(2,1,85),(3,2,70),(4,2,75),(5,3,90),(6,3,95),(7,4,60),(8,4,65);
SELECT c.Region, AVG(m.Parity_Score) as Avg_Parity_Score FROM MentalHealthScores m JOIN CommunityHealthWorkers c ON m.CHW_ID = c.CHW_ID GROUP BY c.Region;
What is the most common age range of players who play 'RPG' games?
CREATE TABLE Players (PlayerID INT,Age INT,GameGenre VARCHAR(20));INSERT INTO Players (PlayerID,Age,GameGenre) VALUES (1,25,'RPG'),(2,24,'RPG'),(3,30,'FPS');
SELECT Age, COUNT(PlayerID) FROM Players WHERE GameGenre = 'RPG' GROUP BY Age ORDER BY COUNT(PlayerID) DESC LIMIT 1;
What is the maximum and minimum size of protected habitats in square kilometers for each region?
CREATE TABLE Habitats (id INT,animal_id INT,size FLOAT,region VARCHAR(255)); INSERT INTO Habitats (id,animal_id,size,region) VALUES (1,1,5.6,'Africa'),(2,2,3.2,'Asia'),(3,3,7.8,'Africa');
SELECT region, MIN(size) AS min_size, MAX(size) AS max_size FROM Habitats WHERE size IS NOT NULL GROUP BY region;
Who are the top 5 countries with the most satellites in orbit?
CREATE TABLE satellites (id INT,country VARCHAR(50),launch_date DATETIME); INSERT INTO satellites (id,country,launch_date) VALUES (1,'USA','2000-01-01'),(2,'Russia','2001-01-01'),(3,'China','2002-01-01'),(4,'Japan','2003-01-01'),(5,'India','2004-01-01'),(6,'Germany','2005-01-01'),(7,'France','2006-01-01'),(8,'UK','2007-01-01'); CREATE TABLE launches (id INT,satellite_id INT,country VARCHAR(50),launch_date DATETIME); INSERT INTO launches (id,satellite_id,country,launch_date) VALUES (1,1,'USA','2000-01-01'),(2,2,'Russia','2001-01-01'),(3,3,'China','2002-01-01'),(4,4,'Japan','2003-01-01'),(5,5,'India','2004-01-01'),(6,6,'Germany','2005-01-01'),(7,7,'France','2006-01-01'),(8,8,'UK','2007-01-01');
SELECT country, COUNT(s.id) as total_satellites FROM satellites s JOIN launches l ON s.id = l.satellite_id GROUP BY country ORDER BY total_satellites DESC LIMIT 5;
How many FOIA requests were submitted in each department for the year 2020?
CREATE TABLE department (id INT,name VARCHAR(255)); INSERT INTO department (id,name) VALUES (1,'Justice'); INSERT INTO department (id,name) VALUES (2,'Interior'); CREATE TABLE foia (id INT,department_id INT,date DATE); INSERT INTO foia (id,department_id,date) VALUES (1,1,'2020-01-01'); INSERT INTO foia (id,department_id,date) VALUES (2,1,'2020-02-01'); INSERT INTO foia (id,department_id,date) VALUES (3,2,'2019-01-01');
SELECT department.name, COUNT(foia.id) as num_foia_requests FROM department JOIN foia ON department.id = foia.department_id WHERE YEAR(foia.date) = 2020 GROUP BY department.name;
Which biotech startups received funding in Canada and have a female founder?
CREATE TABLE funding(startup VARCHAR(50),country VARCHAR(20),founder_gender VARCHAR(10));INSERT INTO funding(startup,country,founder_gender) VALUES('StartupA','Canada','Female'),('StartupB','US','Male'),('StartupC','Canada','Female');
SELECT startup FROM funding WHERE country = 'Canada' AND founder_gender = 'Female';
Which causes received the most funding in Q1 2022?
CREATE TABLE Donations (DonationID INT,DonationDate DATE,DonationAmount DECIMAL,CauseID INT);
SELECT C.CauseName, SUM(D.DonationAmount) as Q1Funding FROM Donations D JOIN Causes C ON D.CauseID = C.CauseID WHERE D.DonationDate BETWEEN '2022-01-01' AND '2022-03-31' GROUP BY C.CauseName ORDER BY Q1Funding DESC;
Which countries had the highest sales revenue for a specific drug in 2020?
CREATE TABLE sales (id INT PRIMARY KEY,drug_id INT,country VARCHAR(255),year INT,revenue DECIMAL(10,2)); CREATE TABLE drugs (id INT PRIMARY KEY,name VARCHAR(255),manufacturer VARCHAR(255),approval_date DATE);
SELECT country, SUM(revenue) as total_sales FROM sales JOIN drugs ON sales.drug_id = drugs.id WHERE drugs.name = 'Specific Drug' AND year = 2020 GROUP BY country ORDER BY total_sales DESC LIMIT 5;
What is the total weight of organic apples and bananas shipped from Costa Rica to New York in the first quarter of 2022?
CREATE TABLE shipments(id INT,product VARCHAR(20),weight FLOAT,country VARCHAR(20),date DATE); INSERT INTO shipments(id,product,weight,country,date) VALUES (1,'apples',500,'Costa Rica','2022-01-05'); INSERT INTO shipments(id,product,weight,country,date) VALUES (2,'bananas',800,'Costa Rica','2022-01-07');
SELECT SUM(weight) FROM shipments WHERE product IN ('apples', 'bananas') AND country = 'Costa Rica' AND date BETWEEN '2022-01-01' AND '2022-03-31' AND product LIKE 'organic%';
Calculate the average energy consumption for each manufacturing process
CREATE TABLE manufacturing_processes (process_id INT,process_name VARCHAR(255),energy_consumption INT); INSERT INTO manufacturing_processes (process_id,process_name,energy_consumption) VALUES (1,'Process A',1000),(2,'Process B',1500),(3,'Process C',2000),(4,'Process D',2500);
SELECT process_name, AVG(energy_consumption) as avg_energy_consumption FROM manufacturing_processes GROUP BY process_name;
Who has the highest number of gym check-ins in the past week?
CREATE TABLE gym_checkins (id INT,user_id INT,checkin_date DATE); INSERT INTO gym_checkins (id,user_id,checkin_date) VALUES (1,33,'2022-09-12'),(2,33,'2022-09-10'),(3,55,'2022-08-15');
SELECT user_id, COUNT(*) as checkin_count FROM gym_checkins WHERE checkin_date >= CURDATE() - INTERVAL 7 DAY GROUP BY user_id ORDER BY checkin_count DESC LIMIT 1;
Which countries have the most excavation sites in the 'pre-Columbian' era?
CREATE TABLE eras (era_id INT,era_name TEXT); INSERT INTO eras (era_id,era_name) VALUES (1,'pre-Columbian'); CREATE TABLE excavation_sites (site_id INT,site_name TEXT,country TEXT,era_id INT); INSERT INTO excavation_sites (site_id,site_name,country,era_id) VALUES (1,'Mayan Ruins','Mexico',1),(2,'Inca Trail','Peru',1),(3,'Teotihuacan','Mexico',1);
SELECT country, COUNT(site_id) as site_count FROM excavation_sites WHERE era_id = 1 GROUP BY country ORDER BY site_count DESC;
What is the average military spending for countries involved in defense diplomacy?
CREATE TABLE defense_diplomacy (id INT,country VARCHAR,military_spending FLOAT);
SELECT country, AVG(military_spending) FROM defense_diplomacy GROUP BY country;
What is the average ticket price by seating section?
CREATE TABLE seating_sections (seating_section_id INT,seating_section_name VARCHAR(50),avg_price DECIMAL(10,2));
SELECT s.seating_section_name, AVG(t.revenue/t.quantity) as avg_price FROM tickets t JOIN seating_sections s ON t.seating_section_id = s.seating_section_id GROUP BY s.seating_section_name;
What are the unique chemical substance IDs and their corresponding substance names from the chemical_substance_info table, ordered by the substance ID in ascending order?
CREATE TABLE chemical_substance_info (substance_id INT,substance_name TEXT); INSERT INTO chemical_substance_info (substance_id,substance_name) VALUES (101,'CompoundX'),(102,'SolutionY'),(103,'MixtureZ');
SELECT substance_id, substance_name FROM chemical_substance_info ORDER BY substance_id ASC;
Identify the idle wells in the Gulf of Mexico
CREATE TABLE wells (id INT,well_name VARCHAR(100),location VARCHAR(50),status VARCHAR(20)); INSERT INTO wells VALUES (1,'Well A','North Sea','Producing'); INSERT INTO wells VALUES (2,'Well B','Gulf of Mexico','Abandoned'); INSERT INTO wells VALUES (3,'Well C','Gulf of Mexico','Producing'); INSERT INTO wells VALUES (4,'Well D','North Sea','Producing'); INSERT INTO wells VALUES (5,'Well E','North Sea','Idle'); INSERT INTO wells VALUES (6,'Well F','Gulf of Mexico','Idle');
SELECT well_name FROM wells WHERE location = 'Gulf of Mexico' AND status = 'Idle';
What is the maximum number of posts in a single day for users in the social_media schema?
CREATE TABLE users (id INT,name VARCHAR(50),posts_count INT); CREATE TABLE posts (id INT,user_id INT,post_text VARCHAR(255),post_date DATE);
SELECT MAX(post_count) FROM (SELECT user_id, COUNT(*) AS post_count FROM posts GROUP BY user_id, post_date) AS post_counts;
Insert a new textile supplier 'Sustainable Textiles Inc.' from 'Bangladesh' into the 'Supplier' table
CREATE TABLE Supplier (id INT PRIMARY KEY,name VARCHAR(50),country VARCHAR(50),sustainability_score INT);
INSERT INTO Supplier (id, name, country, sustainability_score) VALUES (15, 'Sustainable Textiles Inc.', 'Bangladesh', 80);
How many supplies were sent to each region in 2021?
CREATE TABLE regions (id INT,name VARCHAR(255)); CREATE TABLE supplies (id INT,region_id INT,sent_date DATE,quantity INT);
SELECT regions.name, COUNT(supplies.id) FROM supplies JOIN regions ON supplies.region_id = regions.id WHERE supplies.sent_date BETWEEN '2021-01-01' AND '2021-12-31' GROUP BY supplies.region_id;
List all unique donors who have donated more than $500.00.
CREATE TABLE donors (id INT,name TEXT,donation DECIMAL); INSERT INTO donors (id,name,donation) VALUES (1,'John Doe',500.00),(2,'Jane Smith',1000.00),(3,'Mike Johnson',750.00);
SELECT DISTINCT name FROM donors WHERE donation > 500.00;
List the names and total number of campaigns for public awareness campaigns related to depression in the last 5 years, ordered by the number of campaigns in descending order.
CREATE TABLE campaigns (campaign_id INT,name TEXT,condition TEXT,start_date DATE,end_date DATE); INSERT INTO campaigns (campaign_id,name,condition,start_date,end_date) VALUES (1,'Break the Stigma','Depression','2018-01-01','2018-12-31'); INSERT INTO campaigns (campaign_id,name,condition,start_date,end_date) VALUES (2,'Uplift','Depression','2019-06-01','2019-12-31');
SELECT name, COUNT(*) as total FROM campaigns WHERE condition = 'Depression' AND start_date >= DATEADD(year, -5, GETDATE()) GROUP BY name ORDER BY total DESC;
What is the maximum duration of a space mission led by 'Space Riders Inc.'?
CREATE TABLE space_missions (id INT,mission_name VARCHAR(255),astronaut_name VARCHAR(255),duration INT); INSERT INTO space_missions (id,mission_name,astronaut_name,duration) VALUES (1,'Apollo 11','Neil Armstrong',195),(2,'Apollo 12','Jane Foster',244),(3,'Ares 3','Mark Watney',568); CREATE TABLE mission_contractors (id INT,mission_name VARCHAR(255),contractor VARCHAR(255)); INSERT INTO mission_contractors (id,mission_name,contractor) VALUES (1,'Apollo 11','NASA'),(2,'Apollo 12','Space Riders Inc.'),(3,'Ares 3','Space Riders Inc.');
SELECT MAX(space_missions.duration) FROM space_missions JOIN mission_contractors ON space_missions.mission_name = mission_contractors.mission_name WHERE mission_contractors.contractor = 'Space Riders Inc.';
List the freight forwarders with more than 10% of their shipments delayed by more than 5 days in the last 6 months?
CREATE TABLE Forwarders (id INT,name VARCHAR(255)); CREATE TABLE Shipments (id INT,forwarder_id INT,shipped_date DATE,delivered_date DATE,delay INT);
SELECT f.name, COUNT(s.id) AS total_shipments, SUM(CASE WHEN s.delay > 5 THEN 1 ELSE 0 END) AS delayed_shipments, 100.0 * SUM(CASE WHEN s.delay > 5 THEN 1 ELSE 0 END) / COUNT(s.id) AS pct_delayed_shipments FROM Forwarders f JOIN Shipments s ON f.id = s.forwarder_id WHERE shipped_date >= DATEADD(month, -6, GETDATE()) GROUP BY f.id HAVING pct_delayed_shipments > 10.0;
What is the average water temperature for each month in 2021 for the Tilapia farm?
CREATE TABLE FarmTemperature (farm_id INT,date DATE,temperature DECIMAL(5,2)); INSERT INTO FarmTemperature (farm_id,date,temperature) VALUES (1,'2021-01-01',25.2),(1,'2021-01-02',25.4);
SELECT AVG(temperature) avg_temp, EXTRACT(MONTH FROM date) month FROM FarmTemperature WHERE farm_id = 1 AND YEAR(date) = 2021 GROUP BY month;
How many events had more than 50 attendees from each city in the 'events' table?
CREATE TABLE events (id INT PRIMARY KEY,event_name VARCHAR(100),event_city VARCHAR(50),num_attendees INT);
SELECT event_city, COUNT(id) AS num_events_with_50_plus_attendees FROM events WHERE num_attendees > 50 GROUP BY event_city;
Insert a new record into the marine_protected_areas table with the name 'Coral Sea', depth 1000.0, and location 'Pacific Ocean'
CREATE TABLE marine_protected_areas (name VARCHAR(255),depth FLOAT,location VARCHAR(255)); INSERT INTO marine_protected_areas (name,depth,location) VALUES ('Galapagos Islands',2000.0,'Pacific Ocean'),('Great Barrier Reef',500.0,'Pacific Ocean');
INSERT INTO marine_protected_areas (name, depth, location) VALUES ('Coral Sea', 1000.0, 'Pacific Ocean');
Update the safety rating of all records related to shampoo products with the word 'sulfate' in their ingredient list to 3.
CREATE TABLE cosmetics_ingredients (product VARCHAR(255),ingredient VARCHAR(255),safety_rating INTEGER); CREATE TABLE cosmetics (product VARCHAR(255),product_category VARCHAR(255)); CREATE TABLE ingredients (ingredient VARCHAR(255),chemical_class VARCHAR(255)); CREATE VIEW sulfate_shampoo AS SELECT * FROM cosmetics_ingredients JOIN cosmetics ON cosmetics_ingredients.product = cosmetics.product JOIN ingredients ON cosmetics_ingredients.ingredient = ingredients.ingredient WHERE ingredients.chemical_class = 'Sulfates' AND cosmetics.product_category = 'Shampoos';
UPDATE cosmetics_ingredients SET safety_rating = 3 WHERE product IN (SELECT product FROM sulfate_shampoo);
Delete all records for tram vehicle maintenance older than 3 years.
CREATE TABLE vehicles (vehicle_id INT,vehicle_type TEXT); INSERT INTO vehicles (vehicle_id,vehicle_type) VALUES (1,'Tram'),(2,'Bus'),(3,'Train'); CREATE TABLE maintenance (maintenance_id INT,vehicle_id INT,maintenance_date DATE); INSERT INTO maintenance (maintenance_id,vehicle_id,maintenance_date) VALUES (1,1,'2017-01-01'),(2,1,'2018-01-01'),(3,2,'2019-01-01'),(4,1,'2021-01-01');
DELETE FROM maintenance WHERE vehicle_id IN (SELECT vehicle_id FROM vehicles WHERE vehicle_type = 'Tram') AND maintenance_date < DATE_SUB(CURRENT_DATE, INTERVAL 3 YEAR);
What is the total amount of humanitarian aid distributed in Asia by type of disaster, ordered from the highest to the lowest?
CREATE TABLE aid_distribution_asia (family_id INT,region VARCHAR(20),disaster_type VARCHAR(20),amount_aid FLOAT); INSERT INTO aid_distribution_asia (family_id,region,disaster_type,amount_aid) VALUES (1,'Asia','Flood',5000),(2,'Asia','Earthquake',7000),(3,'Asia','Flood',6000),(4,'Asia','Tsunami',8000),(5,'Asia','Tornado',9000); CREATE TABLE disaster_type (disaster_type VARCHAR(20) PRIMARY KEY); INSERT INTO disaster_type (disaster_type) VALUES ('Flood'),('Earthquake'),('Tsunami'),('Tornado');
SELECT disaster_type, SUM(amount_aid) as total_aid FROM aid_distribution_asia JOIN disaster_type ON aid_distribution_asia.disaster_type = disaster_type.disaster_type GROUP BY disaster_type ORDER BY total_aid DESC;
Get the total value of construction projects in each city in California, grouped by city
CREATE TABLE construction_projects_2 (project_id INT,city VARCHAR(20),state VARCHAR(20),value DECIMAL(10,2)); INSERT INTO construction_projects_2 (project_id,city,state,value) VALUES (1,'San Francisco','CA',1000000.00),(2,'Los Angeles','CA',2000000.00),(3,'San Diego','CA',1500000.00);
SELECT city, SUM(value) FROM construction_projects_2 WHERE state = 'CA' GROUP BY city;
Find the top 3 donors who have made the largest cumulative donations, and show their donation amounts and rank.
CREATE TABLE Donations (DonationID int,DonorID int,DonationDate date,DonationAmount decimal(10,2)); INSERT INTO Donations (DonationID,DonorID,DonationDate,DonationAmount) VALUES (1,1,'2020-01-01',1000.00),(2,1,'2020-02-01',1500.00),(3,2,'2020-01-01',2000.00),(4,2,'2020-02-01',1000.00),(5,3,'2020-01-01',3000.00),(6,3,'2020-02-01',2000.00),(7,3,'2020-03-01',2000.00);
SELECT DonorID, DonationAmount, ROW_NUMBER() OVER (ORDER BY SUM(DonationAmount) DESC) as DonorRank FROM Donations GROUP BY DonorID ORDER BY DonorRank ASC;
How many size 36 garments for women's wear were sold in the last month?
CREATE TABLE SalesData (SaleID INT,ProductID INT,SaleDate DATE,QuantitySold INT,Gender TEXT,Size INT); INSERT INTO SalesData (SaleID,ProductID,SaleDate,QuantitySold,Gender,Size) VALUES (1,1001,'2022-01-01',25,'Women',14),(2,1002,'2022-02-10',30,'Men',32),(3,1003,'2022-03-20',20,'Men',30),(4,1004,'2022-04-01',15,'Women',36);
SELECT COUNT(*) FROM SalesData WHERE Gender = 'Women' AND Size = 36 AND SaleDate >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH);
How many biotech startups are located in each country?
CREATE SCHEMA if not exists biotech;CREATE TABLE if not exists biotech.startups (id INT,name VARCHAR(255),country VARCHAR(255)); INSERT INTO biotech.startups (id,name,country) VALUES (1,'Genetix','USA'),(2,'BioSense','Canada'),(3,'BioEngine','USA');
SELECT country, COUNT(*) num_startups FROM biotech.startups GROUP BY country;
What is the total waste generated in the residential sector?
CREATE TABLE waste_generation (sector VARCHAR(20),waste_quantity INT); INSERT INTO waste_generation (sector,waste_quantity) VALUES ('residential',1500),('commercial',2000),('industrial',3000);
SELECT waste_quantity FROM waste_generation WHERE sector = 'residential';
List all the unique mining sites located in the African continent.
CREATE TABLE mining_sites (site_id INT,site_name TEXT,location TEXT);
SELECT DISTINCT site_name FROM mining_sites WHERE location LIKE 'Africa%';
What is the total duration of security incidents related to 'unpatched systems' in the last month?
CREATE TABLE incident_duration (id INT,incident_type VARCHAR(255),incident_time TIMESTAMP,duration INT);
SELECT SUM(duration) as total_duration FROM incident_duration WHERE incident_type = 'unpatched systems' AND incident_time >= DATE_SUB(CURRENT_TIMESTAMP, INTERVAL 1 MONTH);
What is the total quantity of sustainable fabric sourced from each country?
CREATE TABLE fabric_source (source_id INT,country VARCHAR(255),fabric_type VARCHAR(255),quantity INT,is_sustainable BOOLEAN); INSERT INTO fabric_source (source_id,country,fabric_type,quantity,is_sustainable) VALUES (1,'USA','Organic Cotton',500,true),(2,'China','Recycled Polyester',800,true),(3,'India','Conventional Cotton',300,false);
SELECT country, SUM(quantity) FROM fabric_source WHERE is_sustainable = true GROUP BY country;
What is the difference between the total contract values for the defense projects with General Atomics and Aerojet Rocketdyne?
CREATE TABLE general_atomics_contracts (contract_id INT,project_id INT,contract_value DECIMAL(10,2)); CREATE TABLE aerojet_rocketry_contracts (contract_id INT,project_id INT,contract_value DECIMAL(10,2));
SELECT (SELECT SUM(contract_value) FROM general_atomics_contracts) - (SELECT SUM(contract_value) FROM aerojet_rocketry_contracts) as difference;
What are the average CO2 emissions and energy efficiency scores for projects that use wind energy?
CREATE TABLE projects (id INT PRIMARY KEY,name VARCHAR(255),location VARCHAR(255),capacity FLOAT,renewable_energy_source VARCHAR(255)); CREATE TABLE sustainability_reports (id INT PRIMARY KEY,project_id INT,report_date DATE,co2_emissions INT,energy_efficiency_score INT);
SELECT s.project_id, AVG(s.co2_emissions) as avg_co2, AVG(s.energy_efficiency_score) as avg_efficiency FROM sustainability_reports s JOIN projects p ON s.project_id = p.id WHERE p.renewable_energy_source = 'Wind' GROUP BY s.project_id;
How many employees have been trained in diversity and inclusion in each department?
CREATE TABLE Employees (EmployeeID INT,Gender VARCHAR(10),HireDate DATE,Department VARCHAR(50),Training VARCHAR(50)); INSERT INTO Employees (EmployeeID,Gender,HireDate,Department,Training) VALUES (1,'Male','2020-01-01','HR','Diversity and Inclusion'); INSERT INTO Employees (EmployeeID,Gender,HireDate,Department,Training) VALUES (2,'Female','2019-01-01','IT','Cybersecurity'); INSERT INTO Employees (EmployeeID,Gender,HireDate,Department,Training) VALUES (3,'Male','2020-05-01','IT','Cloud Computing'); INSERT INTO Employees (EmployeeID,Gender,HireDate,Department,Training) VALUES (4,'Female','2018-01-01','Sales','Sales Techniques'); INSERT INTO Employees (EmployeeID,Gender,HireDate,Department,Training) VALUES (5,'Male','2019-06-01','Finance','Diversity and Inclusion');
SELECT Department, COUNT(*) as Num_Trained_Employees FROM Employees WHERE Training = 'Diversity and Inclusion' GROUP BY Department;
What is the minimum production quantity of Gadolinium since 2015?
CREATE TABLE production (year INT,element VARCHAR(10),quantity INT); INSERT INTO production (year,element,quantity) VALUES (2015,'Gadolinium',5000),(2016,'Gadolinium',5500);
SELECT MIN(quantity) FROM production WHERE element = 'Gadolinium' AND year >= 2015
How many public hospitals are there in the city of San Francisco?
CREATE TABLE hospital_data (hospital_id INT,hospital_name TEXT,type TEXT,city TEXT); INSERT INTO hospital_data (hospital_id,hospital_name,type,city) VALUES (1,'Hospital A','Public','San Francisco'),(2,'Hospital B','Private','San Francisco'),(3,'Hospital C','Public','Los Angeles'),(4,'Hospital D','Private','Los Angeles');
SELECT COUNT(*) FROM hospital_data WHERE type = 'Public' AND city = 'San Francisco';
Which factories have produced the most garments using sustainable practices?
CREATE TABLE SustainableFactories (id INT,factory_name TEXT,num_garments INT); INSERT INTO SustainableFactories (id,factory_name,num_garments) VALUES (1,'Eco-Friendly Factory 1',500),(2,'Sustainable Factory 2',700),(3,'Green Factory 3',800),(4,'Sustainable Factory 4',600);
SELECT factory_name, SUM(num_garments) FROM SustainableFactories GROUP BY factory_name ORDER BY SUM(num_garments) DESC;
What's the viewership trend for TV shows by genre in Q1 and Q4?
CREATE TABLE TV_VIEWERS (id INT,title VARCHAR(100),genre VARCHAR(50),viewers INT,view_date DATE); INSERT INTO TV_VIEWERS (id,title,genre,viewers,view_date) VALUES (1,'The Mandalorian','Sci-fi',5000,'2022-01-01'),(2,'Breaking Bad','Drama',6000,'2021-12-31'),(3,'Friends','Comedy',4000,'2021-12-31');
SELECT genre, EXTRACT(QUARTER FROM view_date) as quarter, AVG(viewers) as avg_viewers FROM TV_VIEWERS GROUP BY genre, quarter;
How many streams does each artist have on average per day?
CREATE TABLE Artists (artist_id INT,artist VARCHAR(255)); CREATE TABLE Streams (stream_id INT,artist_id INT,stream_date DATE,streams INT); INSERT INTO Artists (artist_id,artist) VALUES (1,'Taylor Swift'),(2,'BTS'),(3,'Drake'); INSERT INTO Streams (stream_id,artist_id,stream_date,streams) VALUES (1,1,'2021-01-01',100000),(2,2,'2021-02-15',120000),(3,3,'2021-03-30',90000);
SELECT artist, AVG(streams / NULLIF(DATEDIFF(day, stream_date, LEAD(stream_date) OVER (PARTITION BY artist_id ORDER BY stream_date)), 0)) as avg_daily_streams FROM Streams JOIN Artists ON Streams.artist_id = Artists.artist_id GROUP BY artist;
What are the total sales of artwork created by artists from Europe?
CREATE TABLE Artists (ArtistID int,Name varchar(50),Nationality varchar(50)); INSERT INTO Artists VALUES (1,'Pablo Picasso','Spanish'); INSERT INTO Artists VALUES (2,'Andy Warhol','American'); INSERT INTO Artists VALUES (3,'Mohammed Ali','Egyptian'); INSERT INTO Artists VALUES (4,'Anju Jain','Indian'); INSERT INTO Artists VALUES (5,'Francois Dubois','French'); CREATE TABLE Artworks (ArtworkID int,Title varchar(50),ArtistID int,Sales int); INSERT INTO Artworks VALUES (1,'Guernica',1,5000000); INSERT INTO Artworks VALUES (2,'Campbell Soup Can',2,1000000); INSERT INTO Artworks VALUES (3,'Great Pyramid',3,2000000); INSERT INTO Artworks VALUES (4,'Buddha Statue',4,3000000); INSERT INTO Artworks VALUES (5,'Mona Lisa',5,8000000);
SELECT SUM(Artworks.Sales) FROM Artworks JOIN Artists ON Artworks.ArtistID = Artists.ArtistID WHERE Artists.Nationality = 'French';
Delete all records with a success status of false from the 'agricultural_innovation' table.
CREATE SCHEMA if not exists rural_development; use rural_development; CREATE TABLE IF NOT EXISTS agricultural_innovation (id INT,name VARCHAR(255),cost FLOAT,success BOOLEAN,PRIMARY KEY (id)); INSERT INTO agricultural_innovation (id,name,cost,success) VALUES (1,'Precision Agriculture',300000.00,true),(2,'Drought Resistant Crops',450000.00,false);
DELETE FROM agricultural_innovation WHERE success = false;
What is the total price of vegetarian dishes served in the Chicago region?
CREATE TABLE Dishes (dish_id INT,dish_name VARCHAR(50),is_vegetarian BOOLEAN,price DECIMAL(5,2),region VARCHAR(50)); INSERT INTO Dishes (dish_id,dish_name,is_vegetarian,price,region) VALUES (1,'Quinoa Salad',true,12.99,'Chicago'),(2,'Cheeseburger',false,9.99,'NY'),(3,'Veggie Burger',true,10.99,'LA'),(4,'BBQ Ribs',false,14.99,'Chicago'),(5,'Tofu Stir Fry',true,11.99,'NY');
SELECT SUM(price) FROM Dishes WHERE is_vegetarian = true AND region = 'Chicago';
What is the difference in price between the most expensive and least expensive product in each category?
CREATE TABLE products (product_id INT,category VARCHAR(20),price DECIMAL(5,2)); INSERT INTO products (product_id,category,price) VALUES (1,'Natural',25.99),(2,'Organic',30.49),(3,'Natural',19.99),(4,'Conventional',15.99);
SELECT category, MAX(price) - MIN(price) as price_difference FROM products GROUP BY category;
What is the average speed of public buses in Berlin?
CREATE TABLE berlin_buses (bus_id INT,speed FLOAT,location VARCHAR(20));
SELECT AVG(speed) FROM berlin_buses;
What is the percentage of virtual tours with 3D or VR capabilities?
CREATE TABLE virtual_tours (tour_id INT,tour_name TEXT,city TEXT,has_3D_VR BOOLEAN); INSERT INTO virtual_tours (tour_id,tour_name,city,has_3D_VR) VALUES (1,'Museum Tour','New York',true),(2,'Historical Site Tour','Paris',false);
SELECT (COUNT(*) * 100.0 / (SELECT COUNT(*) FROM virtual_tours)) AS percentage FROM virtual_tours WHERE has_3D_VR = true;
What is the average donation amount by age group?
CREATE TABLE Donors (DonorID INT,DonorAge INT,DonationAmount DECIMAL); INSERT INTO Donors (DonorID,DonorAge,DonationAmount) VALUES (1,35,500.00),(2,42,350.00),(3,28,700.00);
SELECT AVG(DonationAmount) as AverageDonation, FLOOR(DonorAge / 10) * 10 as AgeGroup FROM Donors GROUP BY AgeGroup;
Find all destinations in the Sustainable_Tourism table with CO2 emissions higher than the average.
CREATE TABLE Sustainable_Tourism (Destination VARCHAR(50),CO2_Emissions INT,Water_Usage INT); INSERT INTO Sustainable_Tourism (Destination,CO2_Emissions,Water_Usage) VALUES ('Bali',120,3500),('Kyoto',80,2000),('Rio de Janeiro',150,4000),('Cairo',200,5000);
SELECT Destination FROM Sustainable_Tourism WHERE CO2_Emissions > (SELECT AVG(CO2_Emissions) FROM Sustainable_Tourism);
What is the total number of matches played in the RugbyMatches table, for matches where the home team won by more than 10 points?
CREATE TABLE RugbyMatches (MatchID INT,HomeTeam VARCHAR(50),AwayTeam VARCHAR(50),HomeScore INT,AwayScore INT);
SELECT COUNT(*) FROM RugbyMatches WHERE HomeScore > AwayScore + 10;
What is the average water usage per day at each mine site in January 2020, only showing sites with usage over 5000 liters per day?
CREATE TABLE Water_Usage (Id INT,Mine_Site VARCHAR(50),Usage INT,Date DATE); INSERT INTO Water_Usage (Id,Mine_Site,Usage,Date) VALUES (1,'SiteA',5200,'2020-01-01'); INSERT INTO Water_Usage (Id,Mine_Site,Usage,Date) VALUES (2,'SiteB',5600,'2020-01-02');
SELECT Mine_Site, AVG(Usage) as Average_Water_Usage FROM Water_Usage WHERE Date >= '2020-01-01' AND Date < '2020-02-01' GROUP BY Mine_Site HAVING Average_Water_Usage > 5000;
Find the defense contractors with the lowest number of awarded contracts in the last 5 years.
CREATE TABLE contractors(id INT,company VARCHAR(50),num_contracts INT,contract_date DATE);
SELECT company, num_contracts FROM (SELECT company, COUNT(*) AS num_contracts FROM contractors WHERE contract_date >= DATE(NOW()) - INTERVAL 5 YEAR GROUP BY company ORDER BY num_contracts ASC) AS bottom_contractors;
What are the total donations and volunteer hours for programs in the education sector?
CREATE TABLE program_data (program_id INT,sector TEXT,donation DECIMAL(10,2),volunteer_hours INT); INSERT INTO program_data (program_id,sector,donation,volunteer_hours) VALUES (1,'education',1500.00,500),(2,'health',2000.00,300),(3,'education',1000.00,700);
SELECT SUM(donation) as total_donations, SUM(volunteer_hours) as total_volunteer_hours FROM program_data WHERE sector = 'education';
What is the average number of labor rights violation incidents per month in the past year for each state in the US?
CREATE TABLE labor_violations_us (id INT,report_date DATE,state TEXT,incident_count INT); INSERT INTO labor_violations_us (id,report_date,state,incident_count) VALUES (1,'2022-01-01','California',25); INSERT INTO labor_violations_us (id,report_date,state,incident_count) VALUES (2,'2022-02-01','Texas',30);
SELECT state, AVG(incident_count) as avg_incidents FROM labor_violations_us WHERE report_date >= DATE_TRUNC('year', NOW() - INTERVAL '1 year') GROUP BY state;
Calculate the percentage of orders that were takeout in the month of February 2022.
CREATE TABLE orders (id INT,order_type TEXT,order_date DATE);
SELECT (COUNT(*) * 100.0 / (SELECT COUNT(*) FROM orders WHERE order_date BETWEEN '2022-02-01' AND '2022-02-28')) as pct_takeout FROM orders WHERE order_type = 'takeout' AND order_date BETWEEN '2022-02-01' AND '2022-02-28';
Which artists have created more than 10 works in the 'Surrealism' category?
CREATE TABLE Artists (ArtistID INT PRIMARY KEY,Name TEXT); CREATE TABLE Artworks (ArtworkID INT PRIMARY KEY,Title TEXT,ArtistID INT,Category TEXT,Quantity INT);
SELECT Artists.Name FROM Artists INNER JOIN Artworks ON Artists.ArtistID = Artworks.ArtistID WHERE Artworks.Category = 'Surrealism' GROUP BY Artists.Name HAVING SUM(Artworks.Quantity) > 10;
List the top 5 customers by spending on sustainable ingredients in the last 30 days?
CREATE TABLE customers (customer_id INT,customer_name VARCHAR(255)); CREATE TABLE menu_items (menu_item_id INT,menu_category VARCHAR(255),item_name VARCHAR(255),is_sustainable BOOLEAN); CREATE TABLE orders (order_id INT,customer_id INT,menu_item_id INT,order_date DATE,order_price INT);
SELECT c.customer_name, SUM(o.order_price) as total_spend FROM customers c JOIN orders o ON c.customer_id = o.customer_id JOIN menu_items mi ON o.menu_item_id = mi.menu_item_id WHERE mi.is_sustainable = TRUE AND o.order_date BETWEEN DATEADD(day, -30, GETDATE()) AND GETDATE() GROUP BY c.customer_name ORDER BY total_spend DESC LIMIT 5;
What was the total revenue for the month of January 2022 across all restaurants?
CREATE TABLE restaurant_sales (restaurant_id INT,sale_date DATE,revenue DECIMAL(10,2)); INSERT INTO restaurant_sales (restaurant_id,sale_date,revenue) VALUES (1,'2022-01-01',5000.00),(1,'2022-01-02',6000.00),(2,'2022-01-01',4000.00);
SELECT SUM(revenue) FROM restaurant_sales WHERE EXTRACT(MONTH FROM sale_date) = 1 AND EXTRACT(YEAR FROM sale_date) = 2022;
What is the maximum water consumption by each industrial sector in 2021, if the consumption data is not available?
CREATE TABLE industrial_sectors (id INT,sector VARCHAR(255)); INSERT INTO industrial_sectors (id,sector) VALUES (1,'Manufacturing'),(2,'Mining'),(3,'Construction'); CREATE TABLE water_consumption (year INT,sector_id INT,consumption INT); INSERT INTO water_consumption (year,sector_id,consumption) VALUES (2020,1,10000),(2020,2,15000),(2020,3,12000);
SELECT i.sector, MAX(COALESCE(w.consumption, 0)) as max_consumption FROM industrial_sectors i LEFT JOIN water_consumption w ON i.id = w.sector_id AND w.year = 2021 GROUP BY i.sector;
What is the total number of professional development courses completed by teachers in each school, grouped by course type?
CREATE TABLE teacher_pd (teacher_id INT,school_id INT,course_id INT,course_type VARCHAR(255)); CREATE TABLE courses (course_id INT,course_name VARCHAR(255),course_type VARCHAR(255)); CREATE TABLE schools (school_id INT,school_name VARCHAR(255));
SELECT s.school_name, c.course_type, COUNT(DISTINCT t.teacher_id, t.course_id) as num_courses FROM teacher_pd t INNER JOIN schools s ON t.school_id = s.school_id INNER JOIN courses c ON t.course_id = c.course_id GROUP BY s.school_name, c.course_type;
How many sustainable hotels are there in Japan and how many awards have they won in total?
CREATE TABLE hotels (id INT,name VARCHAR(50),country VARCHAR(50),sustainable BOOLEAN); INSERT INTO hotels (id,name,country,sustainable) VALUES (1,'Eco Hotel','Japan',TRUE),(2,'Green Hotel','USA',TRUE),(3,'Classic Hotel','Japan',FALSE); CREATE TABLE hotel_awards (id INT,hotel_id INT,award VARCHAR(50)); INSERT INTO hotel_awards (id,hotel_id,award) VALUES (1,1,'Green Flag'),(2,1,'Eco Certificate'),(3,2,'Green Globe');
SELECT COUNT(DISTINCT hotels.id), SUM(hotel_awards.count) FROM hotels JOIN (SELECT hotel_id, COUNT(*) AS count FROM hotel_awards GROUP BY hotel_id) AS hotel_awards ON hotels.id = hotel_awards.hotel_id WHERE hotels.country = 'Japan' AND hotels.sustainable = TRUE;
List the policy names and their corresponding policy owners for policies that have not been reviewed in the past 6 months, based on the PolicyReview table.
CREATE TABLE PolicyReview (policy_id INT,policy_name VARCHAR(50),policy_owner VARCHAR(50),last_reviewed DATETIME);
SELECT policy_name, policy_owner FROM PolicyReview WHERE last_reviewed < DATEADD(month, -6, GETDATE());
Which movies have the lowest IMDb rating per genre, sorted by release year?
CREATE TABLE movie_ratings (id INT,title VARCHAR(255),release_year INT,genre VARCHAR(255),imdb_rating DECIMAL(3,2)); INSERT INTO movie_ratings (id,title,release_year,genre,imdb_rating) VALUES (1,'Movie1',2018,'Action',5.2),(2,'Movie2',2019,'Comedy',5.5),(3,'Movie3',2017,'Drama',6.0),(4,'Movie4',2018,'Animation',4.8),(5,'Movie5',2019,'Documentary',5.3);
SELECT genre, title, release_year, MIN(imdb_rating) AS lowest_imdb_rating FROM movie_ratings GROUP BY genre ORDER BY release_year, lowest_imdb_rating;
What is the average health equity metric score for mental health facilities in Texas?
CREATE TABLE mental_health_facilities (id INT,name VARCHAR,state VARCHAR,health_equity_score INT); INSERT INTO mental_health_facilities (id,name,state,health_equity_score) VALUES (1,'Facility One','Texas',75); INSERT INTO mental_health_facilities (id,name,state,health_equity_score) VALUES (2,'Facility Two','Texas',80);
SELECT state, AVG(health_equity_score) as avg_score FROM mental_health_facilities WHERE state = 'Texas' GROUP BY state;
What is the total budget allocated to public libraries in each state with a population greater than 5 million?
CREATE SCHEMA Government;CREATE TABLE Government.State (name VARCHAR(255),population INT);CREATE TABLE Government.Library (name VARCHAR(255),state VARCHAR(255),budget INT);
SELECT state, SUM(budget) FROM Government.Library WHERE state IN (SELECT name FROM Government.State WHERE population > 5000000) GROUP BY state;
Update the price of all eco-friendly jeans to $65.99.
CREATE TABLE inventory (id INT,item_name VARCHAR(255),category VARCHAR(255),price DECIMAL(5,2),is_eco_friendly BOOLEAN); INSERT INTO inventory (id,item_name,category,price,is_eco_friendly) VALUES (1,'Straight Jeans','Bottoms',59.99,true),(2,'Skinny Jeans','Bottoms',49.99,false);
UPDATE inventory SET price = 65.99 WHERE is_eco_friendly = true;
What is the total cargo weight carried by vessels that have visited the Port of Singapore in the last month, and what is the average cargo weight per vessel for these vessels?
CREATE TABLE vessels (id INT,name TEXT,cargo_weight INT,visit_date DATE,visit_port TEXT);
SELECT AVG(cargo_weight), SUM(cargo_weight) FROM vessels WHERE visit_date >= DATEADD(month, -1, GETDATE()) AND visit_port = 'Singapore';
What is the number of employees by department and gender?
CREATE TABLE Employees (EmployeeID int,FirstName varchar(50),LastName varchar(50),Department varchar(50),Gender varchar(50),Salary decimal(10,2)); INSERT INTO Employees (EmployeeID,FirstName,LastName,Department,Gender,Salary) VALUES (1,'John','Doe','IT','Male',75000); INSERT INTO Employees (EmployeeID,FirstName,LastName,Department,Gender,Salary) VALUES (2,'Jane','Doe','HR','Female',80000);
SELECT Department, Gender, COUNT(*) as TotalEmployees FROM Employees GROUP BY Department, Gender;
Find the total number of hybrid vehicles sold in 2020
CREATE TABLE sales (id INT,vehicle_type VARCHAR(20),year INT,quantity INT); INSERT INTO sales (id,vehicle_type,year,quantity) VALUES (1,'hybrid',2018,3000),(2,'hybrid',2019,4500),(3,'hybrid',2020,6000),(4,'ev',2018,1000),(5,'ev',2019,2000),(6,'ev',2020,5000);
SELECT SUM(quantity) FROM sales WHERE vehicle_type = 'hybrid' AND year = 2020;
Find the average age of readers who prefer sports news in the Asia-Pacific region, grouped by their country.
CREATE TABLE asia_pacific_readers (id INT,age INT,country VARCHAR(255),news_preference VARCHAR(255)); INSERT INTO asia_pacific_readers (id,age,country,news_preference) VALUES (1,35,'Japan','sports'),(2,45,'Australia','politics');
SELECT r.country, AVG(r.age) FROM asia_pacific_readers r JOIN countries c ON r.country = c.country WHERE r.news_preference = 'sports' AND c.region = 'Asia-Pacific' GROUP BY r.country;
Who are the top 2 intelligence agency directors in India and their respective agencies?
CREATE TABLE intelligence_agencies (id INT,agency_name VARCHAR(255),director_name VARCHAR(255)); INSERT INTO intelligence_agencies (id,agency_name,director_name) VALUES (1,'RAW','Samant Goel'); INSERT INTO intelligence_agencies (id,agency_name,director_name) VALUES (2,'IB','Arvind Kumar');
SELECT agency_name, director_name FROM intelligence_agencies WHERE agency_name IN ('RAW', 'IB') LIMIT 2;
How many user accounts were created in the 'Asia-Pacific' region in the last month?
CREATE TABLE user_accounts (id INT,username VARCHAR(255),region VARCHAR(255),account_created DATETIME); INSERT INTO user_accounts (id,username,region,account_created) VALUES (1,'jdoe','Asia-Pacific','2022-01-05'),(2,'jsmith','Europe','2022-01-06');
SELECT COUNT(*) FROM user_accounts WHERE region = 'Asia-Pacific' AND account_created >= DATE_SUB(NOW(), INTERVAL 1 MONTH);
What is the average response time for the three types of incidents with the shortest average response time?
CREATE TABLE EmergencyResponse (Id INT,Incident VARCHAR(20),ResponseTime INT,City VARCHAR(20),State VARCHAR(20)); CREATE VIEW EmergencyResponseView AS SELECT Incident,ResponseTime,ROW_NUMBER() OVER (PARTITION BY Incident ORDER BY ResponseTime) as Rank FROM EmergencyResponse;
SELECT e.Incident, AVG(e.ResponseTime) as AvgResponseTime FROM EmergencyResponseView e WHERE e.Rank <= 3 GROUP BY e.Incident;
What is the average price of menu items for each cuisine type?
CREATE TABLE MenuItems (MenuItemID int,RestaurantID int,CuisineType varchar(255),Price decimal(5,2)); INSERT INTO MenuItems (MenuItemID,RestaurantID,CuisineType,Price) VALUES (1,1,'Italian',12.99),(2,2,'Mexican',8.99),(3,3,'Chinese',10.99);
SELECT R.CuisineType, AVG(MI.Price) as AvgPrice FROM Restaurants R INNER JOIN MenuItems MI ON R.RestaurantID = MI.RestaurantID GROUP BY R.CuisineType;
Find the total number of players who have played both "Arena Shooter" and "Battle Royale" games.
CREATE TABLE Game (id INT,name VARCHAR(255)); INSERT INTO Game (id,name) VALUES (1,'Arena Shooter'),(2,'Battle Royale');
SELECT COUNT(DISTINCT PlayerId) FROM (SELECT PlayerId FROM GamePlayer G1 WHERE G1.name = 'Arena Shooter' INTERSECT SELECT PlayerId FROM GamePlayer G2 WHERE G2.name = 'Battle Royale') AS Subquery;
What are the names of exhibitions about the Aztec Civilization held at sites in the United States?
CREATE TABLE Exhibition (ExhibitionID INT PRIMARY KEY,Title VARCHAR(50),SiteID INT,StartDate DATE,EndDate DATE,Civilization VARCHAR(50)); INSERT INTO Exhibition (ExhibitionID,Title,SiteID,StartDate,EndDate,Civilization) VALUES (3,'Aztec Empire: Myth and Reality',3,'2005-01-01','2005-12-31','Aztec Civilization');
SELECT Title FROM Exhibition WHERE SiteID IN (SELECT SiteID FROM Site WHERE Country = 'United States') AND Civilization = 'Aztec Civilization';
What is the average fare for each route in the 'route' table?
CREATE TABLE route (id INT,name TEXT,length FLOAT,fare FLOAT); INSERT INTO route (id,name,length,fare) VALUES (1,'Central Line',25.3,3.5),(2,'Circle Line',22.8,4.2),(3,'Jubilee Line',36.2,5.0);
SELECT name, AVG(fare) as avg_fare FROM route GROUP BY name;
Add new strain 'OG Kush' to 'strains' table
CREATE TABLE strains (strain_id INT,strain_name VARCHAR(50));
INSERT INTO strains (strain_name) VALUES ('OG Kush');
Determine the minimum temperature recorded for each crop variety in the past month
CREATE TABLE crop (id INT,variety VARCHAR(255),farm_id INT);CREATE TABLE temperature (id INT,crop_id INT,measurement DATE,temp INT);
SELECT variety, MIN(temp) FROM (SELECT temp, crop_id, variety FROM temperature JOIN crop ON temperature.crop_id = crop.id) AS subquery GROUP BY variety WHERE measurement >= DATEADD(month, -1, GETDATE());
What is the maximum order quantity for eco-friendly packaging materials?
CREATE TABLE EcoPackaging (id INT,material VARCHAR(50),order_quantity INT); INSERT INTO EcoPackaging (id,material,order_quantity) VALUES (1,'Recycled Cardboard Boxes',500),(2,'Biodegradable Bags',2000),(3,'Plant-Based Packing Peanuts',1000);
SELECT MAX(order_quantity) FROM EcoPackaging;
List marine species with populations greater than 1000 in the Arctic.
CREATE TABLE marine_species (id INT PRIMARY KEY,species VARCHAR(255),population INT,habitat VARCHAR(255)); INSERT INTO marine_species (id,species,population,habitat) VALUES (1,'polar_bear',25000,'Arctic');
SELECT species FROM marine_species WHERE habitat = 'Arctic' AND population > 1000;
What is the number of shipments with a weight greater than 200 kg that were sent to 'Oceania' in the last month?
CREATE TABLE shipments (id INT,shipped_date DATE,destination VARCHAR(20),weight INT); INSERT INTO shipments (id,shipped_date,destination,weight) VALUES (1,'2022-02-15','Oceania',250),(2,'2022-03-10','Oceania',180),(3,'2022-03-03','Oceania',300);
SELECT COUNT(*) FROM shipments WHERE shipped_date >= DATEADD(month, -1, GETDATE()) AND destination = 'Oceania' AND weight > 200;
What is the average environmental impact score and total number of mining sites for each region?
CREATE TABLE regions (id INT,name VARCHAR(50)); CREATE TABLE mining_sites (id INT,region_id INT,name VARCHAR(50),location VARCHAR(50),environmental_impact_score DECIMAL(5,2));
SELECT r.name AS region, AVG(ms.environmental_impact_score) AS avg_score, COUNT(ms.id) AS total_sites FROM regions r INNER JOIN mining_sites ms ON r.id = ms.region_id GROUP BY r.name;
Find the average CO2 emissions per MWh for each country in Europe.
CREATE TABLE europe_country (name VARCHAR(50),co2_emission_mwh DECIMAL(5,2)); INSERT INTO europe_country (name,co2_emission_mwh) VALUES ('France',120.9),('Germany',320.9),('Spain',230.5);
SELECT name, AVG(co2_emission_mwh) OVER (PARTITION BY name) AS avg_emission FROM europe_country WHERE name IN ('France', 'Germany', 'Spain');
Update the name of the Tokyo museum to 'Tokyo National Museum'.
CREATE TABLE museums (id INT,name TEXT,city TEXT); INSERT INTO museums (id,name,city) VALUES (1,'Tokyo Museum','Tokyo');
UPDATE museums SET name = 'Tokyo National Museum' WHERE name = 'Tokyo Museum' AND city = 'Tokyo';
What is the total amount of water saved through conservation efforts in each region of Africa, for the years 2018 and 2019, and what was the total amount of water consumption during those years?
CREATE TABLE africa_water_conservation (region VARCHAR(255),year INT,saved FLOAT,total FLOAT); INSERT INTO africa_water_conservation (region,year,saved,total) VALUES ('West Africa',2018,1000000,5000000),('West Africa',2019,1200000,6000000),('East Africa',2018,800000,4000000),('East Africa',2019,900000,4500000),('North Africa',2018,1500000,7000000),('North Africa',2019,1600000,7500000);
SELECT region, SUM(saved) as total_saved, SUM(total) as total_consumption, 100.0 * SUM(saved) / SUM(total) as savings_percentage FROM africa_water_conservation WHERE year IN (2018, 2019) GROUP BY region;
What is the total quantity of assistance provided by each organization in 'disaster_response' table, regardless of type?
CREATE TABLE disaster_response (id INT,organization VARCHAR(50),location VARCHAR(50),assistance_type VARCHAR(50),quantity INT); INSERT INTO disaster_response (id,organization,location,assistance_type,quantity) VALUES (1,'WFP','Syria','Food',5000),(2,'UNWRA','Gaza','Food',3000),(3,'IFRC','Syria','Shelter',2000);
SELECT organization, SUM(quantity) FROM disaster_response GROUP BY organization;
What is the average revenue per sustainable tour in Australia?
CREATE TABLE australia_sustainable_tours (id INT,type VARCHAR(255),revenue FLOAT); INSERT INTO australia_sustainable_tours (id,type,revenue) VALUES (1,'Sustainable',900.00),(2,'Sustainable',1000.00);
SELECT AVG(revenue) FROM australia_sustainable_tours WHERE type = 'Sustainable';
What is the total amount of charitable giving for each region?
CREATE TABLE Donations (DonID INT,DonDate DATE,OrgID INT,Region VARCHAR(255),Amount INT); INSERT INTO Donations (DonID,DonDate,OrgID,Region,Amount) VALUES (1,'2021-01-01',1,'North',500),(2,'2021-02-15',2,'South',700),(3,'2021-03-30',3,'East',900),(4,'2021-04-10',1,'North',600),(5,'2021-05-22',2,'South',800),(6,'2021-06-05',3,'East',1000);
SELECT Region, SUM(Amount) as TotalDonations FROM Donations GROUP BY Region;
Find the number of marine protected areas in the Pacific Ocean with an average depth greater than 1000 meters.
CREATE TABLE pacific_marine_protected_areas (id INT,name TEXT,region TEXT,avg_depth FLOAT); INSERT INTO pacific_marine_protected_areas (id,name,region,avg_depth) VALUES (1,'Marianas Trench Marine National Monument','Pacific',10991.0),(2,'Deep Sea Coral Reserve','Pacific',1500.0);
SELECT COUNT(*) FROM pacific_marine_protected_areas WHERE region = 'Pacific' AND avg_depth > 1000;