instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
What is the maximum number of AI-powered features in hotels in Europe?
CREATE TABLE hotel_features (id INT,hotel_name TEXT,location TEXT,ai_features INT); INSERT INTO hotel_features (id,hotel_name,location,ai_features) VALUES (1,'Hotel A','Asia',5),(2,'Hotel B','Europe',7),(3,'Hotel C','Americas',3),(4,'Hotel D','Africa',6),(5,'Hotel E','Europe',8),(6,'Hotel F','Asia',4);
SELECT MAX(ai_features) FROM hotel_features WHERE location = 'Europe';
Identify the menu items that have a higher than average revenue for their respective cuisine category.
CREATE TABLE menu_items (menu_item_id INT,restaurant_id INT,name VARCHAR(255),revenue DECIMAL(10,2),cuisine VARCHAR(255));
SELECT m.name, AVG(o.revenue) OVER (PARTITION BY m.cuisine) AS avg_revenue FROM menu_items m JOIN orders o ON m.menu_item_id = o.menu_item_id WHERE m.revenue > AVG(o.revenue) OVER (PARTITION BY m.cuisine);
Which cause area received the most donations in 2021?
CREATE TABLE donations (id INT,donor_id INT,donation_amount DECIMAL(10,2),donation_date DATE,cause_area VARCHAR(50)); INSERT INTO donations (id,donor_id,donation_amount,donation_date,cause_area) VALUES (1,1,500.00,'2021-01-01','Healthcare'); INSERT INTO donations (id,donor_id,donation_amount,donation_date,cause_area) VALUES (2,2,1000.00,'2021-03-31','Environment'); INSERT INTO donations (id,donor_id,donation_amount,donation_date,cause_area) VALUES (3,3,1500.00,'2021-12-31','Education');
SELECT cause_area, SUM(donation_amount) as total_donation FROM donations WHERE YEAR(donation_date) = 2021 GROUP BY cause_area ORDER BY total_donation DESC LIMIT 1;
What is the percentage of employees who identify as Indigenous in the Finance department?
CREATE TABLE Employees (EmployeeID INT,Gender VARCHAR(20),Department VARCHAR(20)); INSERT INTO Employees (EmployeeID,Gender,Department) VALUES (1,'Male','IT'),(2,'Female','IT'),(3,'Indigenous','Finance'),(4,'Transgender Male','Marketing'),(5,'Lesbian','Marketing');
SELECT (COUNT(*) / (SELECT COUNT(*) FROM Employees WHERE Department = 'Finance')) * 100 FROM Employees WHERE Department = 'Finance' AND Gender = 'Indigenous';
List the defense diplomacy events between Middle Eastern and European countries in the past 3 years.
CREATE TABLE defense_diplomacy(country1 VARCHAR(50),country2 VARCHAR(50),year INT,event VARCHAR(255)); INSERT INTO defense_diplomacy(country1,country2,year,event) VALUES('Saudi Arabia','France',2019,'Joint military exercise'),('Israel','Germany',2021,'Defense technology cooperation'),('UAE','Italy',2020,'Military equipment purchase'),('Iran','Spain',2018,'Diplomatic visit by defense minister'),('Qatar','UK',2019,'Joint naval exercise');
SELECT country1, country2, event FROM defense_diplomacy WHERE (country1 IN ('Saudi Arabia', 'Israel', 'UAE', 'Iran', 'Qatar') AND country2 IN ('France', 'Germany', 'Italy', 'Spain', 'UK')) OR (country1 IN ('France', 'Germany', 'Italy', 'Spain', 'UK') AND country2 IN ('Saudi Arabia', 'Israel', 'UAE', 'Iran', 'Qatar')) AND year BETWEEN 2018 AND 2021;
What is the total number of volunteers who signed up in 'Brazil' in the year 2021?
CREATE TABLE Volunteers (VolunteerID int,VolunteerName varchar(100),Country varchar(50),SignupDate date); INSERT INTO Volunteers (VolunteerID,VolunteerName,Country,SignupDate) VALUES (1,'Jane Doe','Brazil','2021-01-01');
SELECT COUNT(*) FROM Volunteers WHERE Country = 'Brazil' AND YEAR(SignupDate) = 2021;
Delete all records from the 'machinery' table where the 'manufacturer' is 'Caterpillar'
CREATE TABLE machinery (id INT PRIMARY KEY,name VARCHAR(50),type VARCHAR(50),manufacturer VARCHAR(50)); INSERT INTO machinery (id,name,type,manufacturer) VALUES (1,'Bulldozer','Heavy','Caterpillar'); INSERT INTO machinery (id,name,type,manufacturer) VALUES (2,'Excavator','Heavy','Komatsu'); INSERT INTO machinery (id,name,type,manufacturer) VALUES (3,'Drill','Light','Caterpillar');
DELETE FROM machinery WHERE manufacturer = 'Caterpillar';
What is the total number of hybrid vehicles sold in the US and Canada?
CREATE TABLE RegionalSales (id INT,vehicle_type VARCHAR(50),quantity INT,region VARCHAR(50)); INSERT INTO RegionalSales (id,vehicle_type,quantity,region) VALUES (1,'Hybrid',12000,'US'),(2,'Hybrid',8000,'Canada'),(3,'Electric',15000,'US'),(4,'Electric',9000,'Canada');
SELECT SUM(quantity) FROM RegionalSales WHERE vehicle_type = 'Hybrid' AND (region = 'US' OR region = 'Canada');
How many circular economy initiatives were launched in Germany between 2017 and 2020?
CREATE TABLE circular_economy_initiatives(year INT,country VARCHAR(20),initiative VARCHAR(50)); INSERT INTO circular_economy_initiatives VALUES (2017,'Germany','Initiative A'),(2018,'Germany','Initiative B'),(2019,'Germany','Initiative C'),(2020,'Germany','Initiative D');
SELECT COUNT(*) as total_initiatives FROM circular_economy_initiatives WHERE country = 'Germany' AND year BETWEEN 2017 AND 2020;
What is the minimum sleep duration for users with a heart rate above 80 BPM who live in the Midwest?
CREATE TABLE sleep (id INT,user_id INT,duration INT,heart_rate INT,region VARCHAR(10)); INSERT INTO sleep (id,user_id,duration,heart_rate,region) VALUES (1,1,360,75,'Midwest'),(2,2,420,65,'South'),(3,3,480,90,'Midwest'),(4,1,450,80,'Midwest'),(5,2,300,70,'South');
SELECT MIN(duration) FROM sleep WHERE heart_rate > 80 AND region = 'Midwest';
What is the number of accessible technology initiatives in South America?
CREATE TABLE accessible_tech (region VARCHAR(20),initiatives INT); INSERT INTO accessible_tech (region,initiatives) VALUES ('Africa',50),('Asia',75),('South America',100);
SELECT initiatives FROM accessible_tech WHERE region = 'South America';
What is the most common make of electric vehicle sold in China?
CREATE TABLE SalesData (id INT,year INT,country VARCHAR(50),vehicle_make VARCHAR(50),vehicle_model VARCHAR(50),quantity INT);
SELECT vehicle_make, MAX(quantity) FROM SalesData WHERE year >= 2015 AND country = 'China' AND vehicle_type = 'Electric' GROUP BY vehicle_make;
What is the total installed capacity of wind energy in Mexico, ranked by capacity, for the top 5 states?
CREATE TABLE wind_energy_capacity_mx (state VARCHAR(50),capacity INT); INSERT INTO wind_energy_capacity_mx (state,capacity) VALUES ('Oaxaca',2000),('Tamaulipas',1500),('Jalisco',1200),('Veracruz',1000),('Yucatan',800);
SELECT state, capacity, RANK() OVER (ORDER BY capacity DESC) as capacity_rank FROM wind_energy_capacity_mx WHERE state IN ('Oaxaca', 'Tamaulipas', 'Jalisco', 'Veracruz', 'Yucatan') ORDER BY capacity_rank;
How many cases were opened in 'january' 2020?
CREATE TABLE cases (case_id INT,case_open_date DATE);
SELECT COUNT(*) FROM cases WHERE case_open_date BETWEEN '2020-01-01' AND '2020-01-31';
Update the email address of donor with DonorID 1 in the Donors table.
CREATE TABLE Donors (DonorID int,FirstName varchar(50),LastName varchar(50),Email varchar(50)); INSERT INTO Donors (DonorID,FirstName,LastName,Email) VALUES (1,'John','Doe','[email protected]');
UPDATE Donors SET Email = '[email protected]' WHERE DonorID = 1;
Update the CO2 emissions of buildings in the 'smart_cities' schema with IDs 1, 3, and 5 to the new_emissions value.
CREATE TABLE smart_cities.buildings (id INT,city VARCHAR(255),co2_emissions INT); CREATE VIEW smart_cities.buildings_view AS SELECT id,city,co2_emissions FROM smart_cities.buildings;
UPDATE smart_cities.buildings SET co2_emissions = new_emissions FROM ( SELECT id, 800 as new_emissions FROM generate_series(1, 5) as seq WHERE seq % 2 = 1 ) AS subquery WHERE smart_cities.buildings.id = subquery.id;
Delete all records of dispensary sales in 2023 that are priced above the average price
CREATE TABLE dispensaries (id INT,name TEXT,state TEXT); CREATE TABLE sales (dispensary_id INT,strain_id INT,quantity INT,price DECIMAL(10,2),sale_date DATE); INSERT INTO dispensaries (id,name,state) VALUES (1,'Dispensary A','Arizona'); INSERT INTO sales (dispensary_id,strain_id,quantity,price,sale_date) VALUES (1,1,10,50,'2023-01-01'); INSERT INTO sales (dispensary_id,strain_id,quantity,price,sale_date) VALUES (1,2,15,60,'2023-01-15');
DELETE FROM sales WHERE (dispensary_id, price, sale_date) IN (SELECT dispensary_id, AVG(price), sale_date FROM sales WHERE sale_date BETWEEN '2023-01-01' AND '2023-12-31' GROUP BY dispensary_id, sale_date HAVING price > AVG(price));
Find the maximum sales revenue for a drug in France and Italy, for each drug.
CREATE TABLE sales_revenue (drug_name TEXT,country TEXT,sales_revenue NUMERIC,month DATE); INSERT INTO sales_revenue (drug_name,country,sales_revenue,month) VALUES ('Drug1','France',250000,'2020-03-01'),('Drug2','Italy',300000,'2020-02-01'),('Drug3','France',150000,'2020-01-01'),('Drug4','Italy',200000,'2020-03-01'),('Drug5','France',350000,'2020-02-01');
SELECT drug_name, MAX(sales_revenue) FROM sales_revenue WHERE country IN ('France', 'Italy') GROUP BY drug_name;
Identify the number of accommodations provided for students in each age group, and the percentage of total accommodations for each age group?
CREATE TABLE students (student_id INT,student_name VARCHAR(255),age INT); CREATE TABLE accommodations (accommodation_id INT,student_id INT,accommodation_date DATE);
SELECT s.age, COUNT(a.accommodation_id) as accommodations_count, ROUND(COUNT(a.accommodation_id) * 100.0 / (SELECT COUNT(*) FROM accommodations) , 2) as percentage_of_total FROM students s JOIN accommodations a ON s.student_id = a.student_id GROUP BY s.age;
Calculate the average length of fish for each species that weigh more than 150kg in the 'HeavyFish' table
CREATE TABLE HeavyFish (id INT,species VARCHAR(255),weight FLOAT,length FLOAT); INSERT INTO HeavyFish (id,species,weight,length) VALUES (1,'Shark',350.5,250.3); INSERT INTO HeavyFish (id,species,weight,length) VALUES (2,'Marlin',200.3,300.6); INSERT INTO HeavyFish (id,species,weight,length) VALUES (3,'Swordfish',250.8,280.5); INSERT INTO HeavyFish (id,species,weight,length) VALUES (4,'Tuna',180.2,200.7);
SELECT species, AVG(length) FROM HeavyFish WHERE weight > 150 GROUP BY species;
What is the total depth of marine protected areas in the Arctic?
CREATE TABLE marine_protected_areas (name VARCHAR(255),area_id INT,depth FLOAT,size INT,country VARCHAR(255)); INSERT INTO marine_protected_areas (name,area_id,depth,size,country) VALUES ('Norwegian Arctic Archipelago',23,300,196000,'Norway'),('Gulf of Leptev Sea',24,400,320000,'Russia');
SELECT SUM(depth) FROM marine_protected_areas WHERE country = 'Arctic';
Delete retailers that have not made a purchase in the last year
CREATE TABLE retailers(retailer_id INT,name TEXT,last_purchase_date DATE); INSERT INTO retailers(retailer_id,name,last_purchase_date) VALUES (101,'Retailer A','2021-12-01'),(102,'Retailer B','2022-02-15'),(103,'Retailer C',NULL),(104,'Retailer D','2022-03-01');
DELETE FROM retailers WHERE last_purchase_date < (CURRENT_DATE - INTERVAL '1 year');
How many cases were handled by attorneys who have the word 'junior' in their job title?
CREATE TABLE attorneys (attorney_id INT,job_title VARCHAR(20)); INSERT INTO attorneys (attorney_id,job_title) VALUES (1,'Senior Attorney'),(2,'Junior Attorney'),(3,'Associate'); CREATE TABLE cases (case_id INT,attorney_id INT); INSERT INTO cases (case_id,attorney_id) VALUES (1,1),(2,2),(3,3);
SELECT COUNT(*) FROM attorneys INNER JOIN cases ON attorneys.attorney_id = cases.attorney_id WHERE attorneys.job_title LIKE '%junior%';
Delete cultural sites in Rio de Janeiro that have been closed.
CREATE TABLE cultural_site (site_id INT,name TEXT,city TEXT,country TEXT,is_open BOOLEAN); INSERT INTO cultural_site (site_id,name,city,country,is_open) VALUES (3,'Rio Cultural Center','Rio de Janeiro','Brazil',false);
DELETE FROM cultural_site WHERE city = 'Rio de Janeiro' AND is_open = false;
Which programs received donations within the last month but have no reported volunteer hours?
CREATE TABLE Programs (ProgramID INT,ProgramName TEXT); CREATE TABLE Donations (DonationID INT,DonorID INT,ProgramID INT,DonationDate DATE); CREATE TABLE VolunteerHours (ProgramID INT,VolunteerHours INT); INSERT INTO Programs (ProgramID,ProgramName) VALUES (1,'Food Security'),(2,'Climate Change'); INSERT INTO Donations (DonationID,DonorID,ProgramID,DonationDate) VALUES (1,1,1,'2023-01-15'); INSERT INTO VolunteerHours (ProgramID,VolunteerHours) VALUES (2,50);
SELECT p.ProgramName FROM Programs p LEFT JOIN Donations d ON p.ProgramID = d.ProgramID LEFT JOIN VolunteerHours v ON p.ProgramID = v.ProgramID WHERE d.DonationDate >= DATE_SUB(CURDATE(), INTERVAL 1 MONTH) AND v.ProgramID IS NULL;
How many streams did BTS get from Spotify?
CREATE TABLE artists (id INT,name TEXT,genre TEXT,country TEXT); CREATE TABLE streams (id INT,song_id INT,artist_id INT,platform TEXT,streams INT); CREATE TABLE songs (id INT,title TEXT,artist_id INT); INSERT INTO artists (id,name,genre,country) VALUES (1,'Taylor Swift','Country Pop','USA'),(2,'Eminem','Hip Hop','USA'),(3,'BTS','KPop','South Korea'); INSERT INTO streams (id,song_id,artist_id,platform,streams) VALUES (1,1,1,'Spotify',10000000),(2,2,2,'Spotify',5000000),(3,3,3,'Spotify',20000000),(4,4,3,'Apple Music',15000000);
SELECT SUM(streams) FROM streams WHERE artist_id = (SELECT id FROM artists WHERE name = 'BTS' AND platform = 'Spotify');
What is the maximum amount of Shariah-compliant loans issued in a single month?
CREATE TABLE shariah_loans (id INT,client_name VARCHAR(50),issue_date DATE,amount FLOAT);
SELECT MAX(amount) FROM (SELECT DATE_TRUNC('month', issue_date) as month, SUM(amount) as amount FROM shariah_loans GROUP BY month) subquery;
What is the total waste generation by material type in the city of Mumbai in 2019?
CREATE TABLE waste_generation (city VARCHAR(255),year INT,material_type VARCHAR(255),amount INT); INSERT INTO waste_generation (city,year,material_type,amount) VALUES ('Mumbai',2019,'Plastic',2000),('Mumbai',2019,'Paper',3000),('Mumbai',2019,'Glass',1500);
SELECT material_type, SUM(amount) FROM waste_generation WHERE city = 'Mumbai' AND year = 2019 GROUP BY material_type;
How many times is 'chicken' mentioned in the meal_descriptions table?
CREATE TABLE meal_descriptions (description_id INT,meal_id INT,description TEXT); INSERT INTO meal_descriptions (description_id,meal_id,description) VALUES (1,1,'Healthy quinoa salad with chicken'),(2,2,'Spicy lentil soup with vegetables'),(3,3,'Rich and creamy chickpea curry'),(4,4,'Tofu stir fry with bell peppers'),(5,5,'Grilled chicken salad with vinaigrette'),(6,6,'Beef tacos with salsa');
SELECT COUNT(*) FROM meal_descriptions WHERE description LIKE '%chicken%';
What is the most common age range of visitors to exhibitions in London?
CREATE TABLE Visitors (VisitorID INT,Age INT,City VARCHAR(255)); CREATE TABLE Visits (VisitID INT,VisitorID INT,ExhibitionID INT);
SELECT City, NTILE(4) OVER(ORDER BY Age) as AgeRange FROM Visitors WHERE City = 'London';
How many genetic research studies were conducted in Canada by year?
CREATE SCHEMA if not exists research;CREATE TABLE if not exists research.studies(id INT,title VARCHAR(255),year INT,country VARCHAR(255),category VARCHAR(255)); INSERT INTO research.studies VALUES (1,'StudyA',2020,'Canada','Genetics'); INSERT INTO research.studies VALUES (2,'StudyB',2019,'Canada','Genetics'); INSERT INTO research.studies VALUES (3,'StudyC',2020,'USA','Bioprocess');
SELECT year, COUNT(*) FROM research.studies WHERE country = 'Canada' AND category = 'Genetics' GROUP BY year;
Determine the percentage of menu items prepared with seasonal ingredients and the average CO2 emissions.
CREATE TABLE menus (menu_item_name VARCHAR(255),daily_sales INT,co2_emissions INT,is_seasonal BOOLEAN);
SELECT menu_item_name, AVG(co2_emissions) as avg_co2, (SUM(CASE WHEN is_seasonal THEN 1 ELSE 0 END) * 100.0 / COUNT(*)) as seasonal_percentage FROM menus GROUP BY menu_item_name;
What is the average safety rating for all autonomous vehicles, grouped by manufacturer?
CREATE TABLE AutonomousVehicles (ID INT,Manufacturer VARCHAR(255),SafetyRating FLOAT); INSERT INTO AutonomousVehicles (ID,Manufacturer,SafetyRating) VALUES (1,'Wayve',4.3),(2,'Nuro',4.5),(3,'Tesla',4.1),(4,'Cruise',4.7),(5,'Zoox',4.6);
SELECT Manufacturer, AVG(SafetyRating) as Avg_Safety_Rating FROM AutonomousVehicles GROUP BY Manufacturer;
What is the average production quantity of Neodymium in 2020, grouped by mine location?
CREATE TABLE mines (id INT,location VARCHAR(50),Neodymium_prod FLOAT); INSERT INTO mines (id,location,Neodymium_prod) VALUES (1,'Bayan Obo',12000.0),(2,'Mount Weld',3500.0),(3,'Thunder Bay',4500.0);
SELECT location, AVG(Neodymium_prod) FROM mines WHERE YEAR(datetime) = 2020 AND Neodymium_prod IS NOT NULL GROUP BY location;
What is the total number of veteran employment in 2022 for each country?
CREATE TABLE veteran_employment (country VARCHAR(255),num_veterans INT,employment_year INT); INSERT INTO veteran_employment (country,num_veterans,employment_year) VALUES ('USA',2000000,2021),('Canada',150000,2021),('UK',1200000,2021),('Australia',55000,2021),('Germany',800000,2021),('USA',2100000,2022),('Canada',160000,2022),('UK',1250000,2022),('Australia',58000,2022),('Germany',850000,2022);
SELECT country, SUM(num_veterans) as total_num_veterans FROM veteran_employment WHERE employment_year = 2022 GROUP BY country ORDER BY total_num_veterans DESC;
What is the total number of military vehicles produced by companies based in the Asia-Pacific region in the 'military_vehicles' table?
CREATE TABLE military_vehicles (company VARCHAR(50),region VARCHAR(50),production_year INT,quantity INT); INSERT INTO military_vehicles (company,region,production_year,quantity) VALUES ('Company A','Asia-Pacific',2010,500),('Company B','Asia-Pacific',2015,700),('Company C','Europe',2012,600),('Company D','Americas',2018,800);
SELECT SUM(quantity) FROM military_vehicles WHERE region = 'Asia-Pacific';
What is the total amount of socially responsible loans issued by each bank in a specific region?
CREATE TABLE banks (bank_id INT,bank_name VARCHAR(50),total_assets FLOAT,region_id INT);CREATE TABLE loans (loan_id INT,bank_id INT,loan_amount FLOAT,socially_responsible BOOLEAN);
SELECT b.bank_name, SUM(l.loan_amount) as total_loans FROM banks b INNER JOIN loans l ON b.bank_id = l.bank_id WHERE b.region_id = 1 AND l.socially_responsible = TRUE GROUP BY b.bank_name;
How many marine research vessels does the "Ocean Explorers" organization have in total?
CREATE TABLE marine_research_vessels (org_name TEXT,vessel_name TEXT,vessel_type TEXT); INSERT INTO marine_research_vessels (org_name,vessel_name,vessel_type) VALUES ('Ocean Explorers','Sea Surveyor','Research Vessel'),('Ocean Explorers','Ocean Odyssey','Research Vessel'),('Ocean Adventures','Marine Marvel','Research Vessel');
SELECT COUNT(*) FROM marine_research_vessels WHERE org_name = 'Ocean Explorers';
What is the average mental health parity violation fine amount by state and year?
CREATE TABLE violations (violation_id INT,violation_date DATE,violation_details VARCHAR(255),fine_amount INT);
SELECT EXTRACT(YEAR FROM violation_date) as year, state_id, AVG(fine_amount) as avg_fine_amount FROM violations GROUP BY year, state_id;
Find the number of animals by species in the 'animal_population' table
CREATE TABLE animal_population (species VARCHAR(50),animal_count INT);
SELECT species, SUM(animal_count) FROM animal_population GROUP BY species;
What is the average price per night for 'budget' hotels in 'Tokyo' on 'Expedia'?
CREATE TABLE BudgetPrices (hotel_id INT,ota TEXT,city TEXT,hotel_class TEXT,price_per_night FLOAT); INSERT INTO BudgetPrices (hotel_id,ota,city,hotel_class,price_per_night) VALUES (1,'Expedia','Tokyo','budget',80),(2,'Expedia','Tokyo','budget',85),(3,'Expedia','Tokyo','non-budget',120);
SELECT AVG(price_per_night) FROM BudgetPrices WHERE ota = 'Expedia' AND city = 'Tokyo' AND hotel_class = 'budget';
What is the minimum age of visitors who attended exhibitions in Rio de Janeiro or Sao Paulo?
CREATE TABLE Exhibitions (exhibition_id INT,city VARCHAR(20),country VARCHAR(20)); INSERT INTO Exhibitions (exhibition_id,city,country) VALUES (1,'Rio de Janeiro','Brazil'),(2,'Sao Paulo','Brazil'); CREATE TABLE Visitors (visitor_id INT,exhibition_id INT,age INT); INSERT INTO Visitors (visitor_id,exhibition_id,age) VALUES (1,1,15),(2,1,18),(3,2,20),(4,2,25);
SELECT MIN(age) FROM Visitors v JOIN Exhibitions e ON v.exhibition_id = e.exhibition_id WHERE e.city IN ('Rio de Janeiro', 'Sao Paulo');
List all records from the ocean acidification view
CREATE TABLE ocean_acidification (id INT PRIMARY KEY,location VARCHAR(255),pH DECIMAL(3,2),timestamp TIMESTAMP); INSERT INTO ocean_acidification (id,location,pH,timestamp) VALUES (1,'Pacific Ocean',7.8,'2021-08-01 12:00:00'),(2,'Atlantic Ocean',8.0,'2021-08-02 15:30:00'); CREATE VIEW ocean_acidification_view AS SELECT * FROM ocean_acidification;
SELECT * FROM ocean_acidification_view;
How many restorative justice programs were launched in each year?
CREATE TABLE justice_programs (program_id INT,program_name VARCHAR(50),launch_date DATE,program_type VARCHAR(50)); INSERT INTO justice_programs (program_id,program_name,launch_date,program_type) VALUES (1,'Youth Restorative Justice Program','2018-01-01','Restorative Justice'),(2,'Community Healing Initiative','2019-07-01','Restorative Justice'),(3,'Criminal Justice Reform Task Force','2020-04-15','Criminal Justice'),(4,'Legal Technology Innovation Lab','2021-10-01','Legal Technology');
SELECT EXTRACT(YEAR FROM launch_date) as year, COUNT(*) as num_programs FROM justice_programs WHERE program_type = 'Restorative Justice' GROUP BY year;
Insert a new record for a song by artist 'BTS' from genre 'K-Pop' released in 2022
CREATE TABLE songs (song_name VARCHAR(255),artist VARCHAR(255),genre VARCHAR(255),release_year INT); INSERT INTO songs (song_name,artist,genre,release_year) VALUES ('Dynamite','BTS','K-Pop',2020),('Butter','BTS','K-Pop',2021);
INSERT INTO songs (song_name, artist, genre, release_year) VALUES ('Yet To Come', 'BTS', 'K-Pop', 2022);
What is the minimum energy consumption of a building in the 'carbon_offsets' schema?
CREATE TABLE carbon_offsets.building_energy_consumption (building VARCHAR(50),consumption FLOAT); INSERT INTO carbon_offsets.building_energy_consumption (building,consumption) VALUES ('Sequoia Building',123.5),('Redwood Building',234.6),('Pine Building',345.7);
SELECT MIN(consumption) FROM carbon_offsets.building_energy_consumption;
List the top 3 heritage sites with the highest visitor count in the Asia-Pacific region.
CREATE TABLE HeritageSites (site_name VARCHAR(50),country VARCHAR(50),visitors INT); INSERT INTO HeritageSites (site_name,country,visitors) VALUES ('Angkor Wat','Cambodia',2000000),('Great Wall','China',10000000),('Taj Mahal','India',8000000),('Sydney Opera House','Australia',3000000),('Petra','Jordan',600000);
SELECT site_name, visitors FROM HeritageSites WHERE country IN ('Cambodia', 'China', 'India', 'Australia', 'Jordan') AND region = 'Asia-Pacific' ORDER BY visitors DESC LIMIT 3;
What is the minimum investment in a single company in the 'Healthcare' sector in the year 2019?
CREATE TABLE investments (id INT,company_id INT,sector VARCHAR(255),year INT,amount FLOAT); INSERT INTO investments (id,company_id,sector,year,amount) VALUES (1,1,'Healthcare',2019,400000.0); INSERT INTO investments (id,company_id,sector,year,amount) VALUES (2,2,'Healthcare',2019,500000.0); INSERT INTO investments (id,company_id,sector,year,amount) VALUES (3,3,'Healthcare',2019,600000.0);
SELECT MIN(amount) FROM investments WHERE sector = 'Healthcare' AND year = 2019;
How many sustainable tourism initiatives were implemented in North America in 2021?
CREATE TABLE sustainable_tourism_initiatives (country VARCHAR(255),year INT,num_initiatives INT); INSERT INTO sustainable_tourism_initiatives (country,year,num_initiatives) VALUES ('Canada',2021,30),('USA',2021,40),('Mexico',2021,50);
SELECT SUM(num_initiatives) FROM sustainable_tourism_initiatives WHERE country IN ('Canada', 'USA', 'Mexico') AND year = 2021;
What is the most recent launch date for satellites manufactured by China National Space Administration (CNSA)?
CREATE TABLE Satellite (id INT,name VARCHAR(255),manufacturer_id INT,launch_date DATE); INSERT INTO Satellite (id,name,manufacturer_id,launch_date) VALUES (1,'GOES-R',1,'2016-11-19'); INSERT INTO Satellite (id,name,manufacturer_id,launch_date) VALUES (2,'Sentinel-2B',2,'2017-03-07'); INSERT INTO Satellite (id,name,manufacturer_id,launch_date) VALUES (3,'GSAT-19',3,'2017-06-28'); CREATE TABLE Manufacturer (id INT,name VARCHAR(255),country VARCHAR(255),year_founded INT); INSERT INTO Manufacturer (id,name,country,year_founded) VALUES (1,'Boeing','USA',1916); INSERT INTO Manufacturer (id,name,country,year_founded) VALUES (2,'Airbus','Europe',1970); INSERT INTO Manufacturer (id,name,country,year_founded) VALUES (3,'China National Space Administration','China',1993);
SELECT MAX(launch_date) FROM Satellite s JOIN Manufacturer m ON s.manufacturer_id = m.id WHERE m.name = 'China National Space Administration';
What is the average revenue generated by hotels in each country?
CREATE TABLE hotels (hotel_id INT,hotel_name TEXT,country TEXT,revenue FLOAT); INSERT INTO hotels (hotel_id,hotel_name,country,revenue) VALUES (1,'Hotel X','USA',1000000),(2,'Hotel Y','Canada',800000),(3,'Hotel Z','Mexico',700000),(4,'Hotel A','USA',1200000),(5,'Hotel B','Canada',900000);
SELECT country, AVG(revenue) as avg_revenue FROM hotels GROUP BY country;
What is the name of the hospital with the smallest budget in New York?
CREATE TABLE hospitals (name TEXT,budget INTEGER,beds INTEGER,state TEXT); INSERT INTO hospitals (name,budget,beds,state) VALUES ('HospitalA',500000,75,'New York'),('HospitalB',400000,60,'New York'),('HospitalC',600000,50,'New York'),('HospitalD',300000,80,'New York'),('HospitalE',700000,100,'New York');
SELECT name FROM hospitals WHERE state = 'New York' ORDER BY budget ASC LIMIT 1;
Find the top 3 countries with the highest average ticket sales for football matches.
CREATE TABLE teams (team_id INT,team_name VARCHAR(100),country VARCHAR(50)); INSERT INTO teams (team_id,team_name,country) VALUES (1,'Barcelona','Spain'),(2,'Bayern Munich','Germany'); CREATE TABLE matches (match_id INT,team_home_id INT,team_away_id INT,tickets_sold INT); INSERT INTO matches (match_id,team_home_id,team_away_id,tickets_sold) VALUES (1,1,2,5000),(2,2,1,6000);
SELECT country, AVG(tickets_sold) as avg_sales FROM matches m JOIN teams t1 ON m.team_home_id = t1.team_id JOIN teams t2 ON m.team_away_id = t2.team_id GROUP BY country ORDER BY avg_sales DESC LIMIT 3;
What is the total square footage of sustainable urbanism projects in the state of California?
CREATE TABLE projects (id INT,state VARCHAR(20),size INT,sustainable BOOLEAN); INSERT INTO projects (id,state,size,sustainable) VALUES (1,'California',2000,TRUE),(2,'California',3000,FALSE),(3,'New York',2500,TRUE);
SELECT SUM(size) FROM projects WHERE state = 'California' AND sustainable = TRUE;
Find the total biomass of fish species in the Pacific Ocean that are above the average biomass.
CREATE TABLE pacific_fish (id INT,species VARCHAR(255),biomass FLOAT); INSERT INTO pacific_fish (id,species,biomass) VALUES (1,'Tuna',200.0),(2,'Salmon',150.0),(3,'Cod',120.0);
SELECT SUM(biomass) FROM pacific_fish WHERE biomass > (SELECT AVG(biomass) FROM pacific_fish);
Summarize the total fuel consumption by each vessel in a given month
VESSEL(vessel_id,vessel_name); TRIP(voyage_id,trip_date,vessel_id,fuel_consumption)
SELECT v.vessel_id, v.vessel_name, DATEPART(year, t.trip_date) AS year, DATEPART(month, t.trip_date) AS month, SUM(t.fuel_consumption) AS total_fuel_consumption FROM VESSEL v JOIN TRIP t ON v.vessel_id = t.vessel_id WHERE t.trip_date BETWEEN '2022-01-01' AND '2022-12-31' GROUP BY v.vessel_id, v.vessel_name, DATEPART(year, t.trip_date), DATEPART(month, t.trip_date);
How many users from India have updated their profile information in the last week?
CREATE TABLE users (id INT,country VARCHAR(255),last_update DATE);
SELECT COUNT(*) FROM users WHERE country = 'India' AND last_update >= DATE_SUB(CURDATE(), INTERVAL 1 WEEK);
What is the average environmental impact assessment rating per mine type?
CREATE TABLE ratings (id INT,mine_type VARCHAR(20),assessment_rating FLOAT); INSERT INTO ratings (id,mine_type,assessment_rating) VALUES (1,'Open-pit',80),(2,'Underground',85),(3,'Open-pit',82),(4,'Underground',88),(5,'Open-pit',83),(6,'Underground',87);
SELECT mine_type, AVG(assessment_rating) AS avg_rating FROM ratings GROUP BY mine_type ORDER BY avg_rating DESC;
What is the average subscription fee for 'Fiber' technology in the 'subscriber_tech' table?
CREATE TABLE subscriber_tech (subscriber_id INT,subscription_start_date DATE,technology VARCHAR(50),subscription_fee DECIMAL(10,2)); INSERT INTO subscriber_tech (subscriber_id,subscription_start_date,technology,subscription_fee) VALUES (1,'2020-01-01','Fiber',50.00),(2,'2019-06-15','Cable',40.00),(5,'2021-02-20','LTE',30.00),(6,'2022-03-15','LTE',25.00),(7,'2020-06-01','Fiber',60.00);
SELECT AVG(subscription_fee) as avg_fee FROM subscriber_tech WHERE technology = 'Fiber';
Which R&D sites have the highest total R&D expenditure for oncology drugs?
CREATE TABLE rd_expenditure (rd_site TEXT,therapeutic_area TEXT,expenditure INTEGER); INSERT INTO rd_expenditure (rd_site,therapeutic_area,expenditure) VALUES ('SiteA','oncology',50000000),('SiteB','oncology',60000000),('SiteC','oncology',45000000),('SiteD','oncology',70000000),('SiteE','oncology',55000000);
SELECT rd_site, SUM(expenditure) as total_expenditure FROM rd_expenditure WHERE therapeutic_area = 'oncology' GROUP BY rd_site ORDER BY total_expenditure DESC;
What are the total donation amounts by program category?
CREATE TABLE donations (id INT,program_category VARCHAR(255),amount DECIMAL(10,2)); INSERT INTO donations (id,program_category,amount) VALUES (1,'Education',5000),(2,'Health',7000),(3,'Education',3000),(4,'Health',8000),(5,'Environment',6000);
SELECT program_category, SUM(amount) AS total_donation FROM donations GROUP BY program_category;
Add a new donor, DonorI from Oceania with a donation of 2750.00
CREATE TABLE Donors (DonorID INT,DonorName TEXT,Continent TEXT,Amount DECIMAL(10,2)); INSERT INTO Donors (DonorID,DonorName,Continent,Amount) VALUES (1,'DonorD','Africa',1200.00),(2,'DonorE','Europe',2200.00);
INSERT INTO Donors (DonorName, Continent, Amount) VALUES ('DonorI', 'Oceania', 2750.00);
How many wells were drilled in the Gulf of Mexico before 2010, and what is the total amount of oil they produced?
CREATE TABLE gulf_of_mexico (id INT,well_name VARCHAR(255),drill_date DATE,production_oil INT);
SELECT COUNT(*) as total_wells, SUM(production_oil) as total_oil_produced FROM gulf_of_mexico WHERE drill_date < '2010-01-01';
What is the number of mining accidents caused by 'explosions' in the 'Europe' region, in the last 5 years?
CREATE TABLE accidents (id INT,site_name VARCHAR(50),date DATE,accident_type VARCHAR(50)); INSERT INTO accidents (id,site_name,date,accident_type) VALUES (1,'Site X','2018-03-15','Explosion');
SELECT COUNT(*) AS accidents_count FROM accidents WHERE site_name LIKE 'Europe' AND accident_type = 'Explosion' AND date >= DATE_SUB(CURDATE(), INTERVAL 5 YEAR);
What is the total budget for climate finance sources used for projects in North America, and the number of unique sources?
CREATE TABLE climate_finance(project_name TEXT,region TEXT,source TEXT,budget FLOAT); INSERT INTO climate_finance(project_name,region,source,budget) VALUES ('Project V','Canada','Government Grant',500000.00),('Project W','USA','Private Investment',600000.00),('Project X','Canada','Carbon Tax',700000.00);
SELECT SUM(budget), COUNT(DISTINCT source) FROM climate_finance WHERE region = 'North America';
List the defense projects and their respective start and end dates, along with the contract negotiation status, that have a geopolitical risk score above 6, ordered by the geopolitical risk score in descending order, for projects in the Asia region.
CREATE TABLE DefenseProjects (project_id INT,project_name VARCHAR(50),start_date DATE,end_date DATE,negotiation_status VARCHAR(50),geopolitical_risk_score INT,project_region VARCHAR(50)); INSERT INTO DefenseProjects (project_id,project_name,start_date,end_date,negotiation_status,geopolitical_risk_score,project_region) VALUES (5,'Project D','2022-02-01','2024-12-31','Negotiating',8,'Asia'),(6,'Project E','2021-06-15','2023-05-01','Completed',5,'Asia'),(7,'Project F','2022-07-22','2027-06-30','Planning',7,'Europe');
SELECT project_name, start_date, end_date, negotiation_status, geopolitical_risk_score FROM DefenseProjects WHERE geopolitical_risk_score > 6 AND project_region = 'Asia' ORDER BY geopolitical_risk_score DESC;
Determine the average food safety inspection scores for restaurants in each city.
CREATE TABLE restaurants (id INT,name VARCHAR(255),city VARCHAR(255),score INT); INSERT INTO restaurants (id,name,city,score) VALUES (1,'Restaurant A','City A',90),(2,'Restaurant B','City B',85),(3,'Restaurant C','City A',95);
SELECT city, AVG(score) FROM restaurants GROUP BY city;
How many times was 'Pre-rolls' product sold in 'Sunshine' dispensary in April 2022?
CREATE TABLE products (product_id INT,name VARCHAR(255)); INSERT INTO products (product_id,name) VALUES (1,'Pre-rolls'); CREATE TABLE dispensaries (dispensary_id INT,name VARCHAR(255)); INSERT INTO dispensaries (dispensary_id,name) VALUES (3,'Sunshine'); CREATE TABLE sales (sale_id INT,product_id INT,dispensary_id INT,quantity INT,sale_date DATE); INSERT INTO sales (sale_id,product_id,dispensary_id,quantity,sale_date) VALUES (10,1,3,4,'2022-04-15');
SELECT SUM(quantity) FROM sales WHERE product_id = (SELECT product_id FROM products WHERE name = 'Pre-rolls') AND dispensary_id = (SELECT dispensary_id FROM dispensaries WHERE name = 'Sunshine') AND sale_date BETWEEN '2022-04-01' AND '2022-04-30';
What is the average number of building permits issued per year in the city of New York?
CREATE TABLE building_permits (permit_id INT,city VARCHAR(20),year INT,permits_issued INT); INSERT INTO building_permits (permit_id,city,year,permits_issued) VALUES (1,'Seattle',2020,5000),(2,'Seattle',2019,4500),(3,'New York',2020,7000),(4,'Los Angeles',2020,6000);
SELECT city, AVG(permits_issued) FROM building_permits WHERE city = 'New York' GROUP BY city;
Update the is_electric column to false for all records in the shared_bikes table in New York.
CREATE TABLE shared_bikes (bike_id INT,city VARCHAR(20),is_electric BOOLEAN); INSERT INTO shared_bikes (bike_id,city,is_electric) VALUES (1,'New York',true),(2,'Chicago',true),(3,'New York',false);
UPDATE shared_bikes SET is_electric = false WHERE city = 'New York';
What is the average number of streams per day for each song?
CREATE TABLE DailyStreams (StreamID int,SongID int,StreamCount int,StreamDate date); INSERT INTO DailyStreams (StreamID,SongID,StreamCount,StreamDate) VALUES (1,1,1000,'2023-02-01'),(2,2,2000,'2023-02-02'),(3,3,1500,'2023-02-03');
SELECT Songs.SongName, AVG(DailyStreams.StreamCount) as AverageStreamsPerDay FROM Songs INNER JOIN DailyStreams ON Songs.SongID = DailyStreams.SongID GROUP BY Songs.SongName;
How many patients with PTSD were treated in Germany in the last 6 months?
CREATE TABLE patients (patient_id INT,has_ptsd BOOLEAN,treatment_date DATE,country VARCHAR(50)); INSERT INTO patients (patient_id,has_ptsd,treatment_date,country) VALUES (1,TRUE,'2022-01-01','Germany'),(2,FALSE,'2021-12-25','Germany'),(3,TRUE,'2022-03-15','Canada');
SELECT COUNT(*) FROM patients WHERE has_ptsd = TRUE AND treatment_date >= '2021-07-01' AND country = 'Germany';
List the top 3 countries with the highest average fish stock levels.
CREATE TABLE FarmLocation (LocationID INT,FarmName VARCHAR(50),Country VARCHAR(50),AvgStockLevel DECIMAL(5,2)); INSERT INTO FarmLocation (LocationID,FarmName,Country,AvgStockLevel) VALUES (1,'FishFirst Farm','United States',450.00); INSERT INTO FarmLocation (LocationID,FarmName,Country,AvgStockLevel) VALUES (2,'Seafood Surprise','Canada',500.00); INSERT INTO FarmLocation (LocationID,FarmName,Country,AvgStockLevel) VALUES (3,'Ocean Oasis','Australia',300.00);
SELECT Country, AvgStockLevel FROM FarmLocation ORDER BY AvgStockLevel DESC LIMIT 3;
What is the total number of 'strength' workouts for each day of the week in January 2022?
CREATE TABLE workouts (id INT,workout_date DATE,activity_type VARCHAR(50),duration INT); INSERT INTO workouts (id,workout_date,activity_type,duration) VALUES (1,'2022-01-01','strength',60),(2,'2022-01-02','cardio',45),(3,'2022-01-03','strength',75),(4,'2022-01-04','yoga',60),(5,'2022-01-05','strength',90),(6,'2022-01-06','cardio',45),(7,'2022-01-07','strength',80),(8,'2022-01-08','yoga',50);
SELECT DATE_FORMAT(workout_date, '%W') AS day_of_week, COUNT(*) AS total_workouts FROM workouts WHERE activity_type = 'strength' AND DATE_FORMAT(workout_date, '%Y-%m') = '2022-01' GROUP BY day_of_week;
Display the total number of security incidents and their respective resolution times for each category in the last quarter.
CREATE TABLE incident_resolution (id INT,timestamp TIMESTAMP,category VARCHAR(255),incident_type VARCHAR(255),resolution_time INT); INSERT INTO incident_resolution (id,timestamp,category,incident_type,resolution_time) VALUES (1,'2022-04-01 10:00:00','Phishing','Insider Threats',120),(2,'2022-04-01 10:00:00','Malware','Insider Threats',240);
SELECT category, incident_type, SUM(resolution_time) as total_resolution_time, COUNT(*) as incident_count FROM incident_resolution WHERE timestamp >= DATE_SUB(CURRENT_TIMESTAMP, INTERVAL 3 MONTH) GROUP BY category, incident_type;
What is the total weight of shipments from a given country to each continent?
CREATE TABLE shipments (id INT,origin_country VARCHAR(255),destination_continent VARCHAR(255),weight FLOAT); INSERT INTO shipments (id,origin_country,destination_continent,weight) VALUES (1,'India','Asia',800.0),(2,'India','Europe',900.0); CREATE TABLE countries (country VARCHAR(255),continent VARCHAR(255)); INSERT INTO countries (country,continent) VALUES ('India','Asia');
SELECT origin_country, destination_continent, SUM(weight) as total_weight FROM shipments JOIN countries ON origin_country = country GROUP BY origin_country, destination_continent;
Delete all records in the satellite_deployment table where satellite_type is 'LEO' and country is 'USA'
CREATE TABLE satellite_deployment (id INT,satellite_name VARCHAR(255),satellite_type VARCHAR(255),country VARCHAR(255),launch_date DATE);
DELETE FROM satellite_deployment WHERE satellite_type = 'LEO' AND country = 'USA';
What is the average watch time of news videos in the DACH region (Germany, Austria, Switzerland)?
CREATE TABLE countries (id INT,name VARCHAR(50),region VARCHAR(50)); INSERT INTO countries (id,name,region) VALUES (1,'Germany','DACH'),(2,'Austria','DACH'),(3,'Switzerland','DACH'); CREATE TABLE videos (id INT,type VARCHAR(50)); INSERT INTO videos (id,type) VALUES (1,'News'),(2,'Entertainment'); CREATE TABLE user_video_view (user_id INT,video_id INT,watch_time INT);
SELECT AVG(uvv.watch_time) as avg_watch_time FROM user_video_view uvv JOIN videos v ON uvv.video_id = v.id JOIN (SELECT id FROM countries WHERE region = 'DACH') c ON 1=1 WHERE v.type = 'News';
What is the average water usage in the commercial sector over the past two years?
CREATE TABLE water_usage (year INT,sector VARCHAR(20),usage INT); INSERT INTO water_usage (year,sector,usage) VALUES (2020,'residential',12000),(2020,'commercial',15000),(2020,'industrial',20000),(2021,'residential',11000),(2021,'commercial',14000),(2021,'industrial',18000);
SELECT AVG(usage) FROM water_usage WHERE sector = 'commercial' AND year IN (2020, 2021);
Add a new 'team' record for 'San Francisco Green'
CREATE TABLE teams (id INT PRIMARY KEY,name VARCHAR(50),city VARCHAR(50),mascot VARCHAR(50));
INSERT INTO teams (id, name, city, mascot) VALUES (101, 'San Francisco Green', 'San Francisco', 'Green Dragons');
Identify the top 2 aquaculture farms with the highest biomass of fish in a given year?
CREATE TABLE Farm (FarmID INT,FarmName VARCHAR(255)); CREATE TABLE Stock (StockID INT,FarmID INT,FishSpecies VARCHAR(255),Weight DECIMAL(10,2),StockDate DATE); INSERT INTO Farm (FarmID,FarmName) VALUES (1,'Farm A'),(2,'Farm B'),(3,'Farm C'),(4,'Farm D'); INSERT INTO Stock (StockID,FarmID,FishSpecies,Weight,StockDate) VALUES (1,1,'Tilapia',5.5,'2022-01-01'),(2,1,'Salmon',12.3,'2022-01-02'),(3,2,'Tilapia',6.0,'2022-01-03'),(4,2,'Catfish',8.2,'2022-01-04');
SELECT FarmName, SUM(Weight) OVER (PARTITION BY FarmID) as TotalBiomass, RANK() OVER (ORDER BY SUM(Weight) DESC) as Rank FROM Stock JOIN Farm ON Stock.FarmID = Farm.FarmID WHERE DATE_TRUNC('year', StockDate) = 2022 GROUP BY FarmName, TotalBiomass HAVING Rank <= 2;
What is the daily revenue for 'Restaurant D'?
CREATE TABLE sales (id INT,restaurant_id INT,sales DECIMAL(5,2)); INSERT INTO sales (id,restaurant_id,sales) VALUES (1,1,100.00),(2,1,200.00),(3,2,150.00),(4,3,50.00),(5,4,300.00);
SELECT SUM(sales) FROM sales WHERE restaurant_id = 4 GROUP BY DATE(time);
Identify the total number of volunteers and their assigned programs by city from 'volunteers' and 'program_assignments' tables
CREATE TABLE volunteers (volunteer_id INT,volunteer_name TEXT,city TEXT); CREATE TABLE program_assignments (program_id INT,program_name TEXT,volunteer_id INT);
SELECT volunteers.city, COUNT(DISTINCT volunteers.volunteer_id) as total_volunteers, COUNT(program_assignments.program_id) as assigned_programs FROM volunteers LEFT JOIN program_assignments ON volunteers.volunteer_id = program_assignments.volunteer_id GROUP BY volunteers.city;
What is the total number of security incidents in the last quarter for the HR department?
CREATE TABLE incidents (id INT,department VARCHAR(255),incident_date DATE); INSERT INTO incidents (id,department,incident_date) VALUES (1,'HR','2022-01-15'),(2,'IT','2022-02-20'),(3,'HR','2022-03-05'); SELECT CURDATE(),DATE_SUB(CURDATE(),INTERVAL 3 MONTH) INTO @current_date,@start_date; SELECT COUNT(*) FROM incidents WHERE department = 'HR' AND incident_date BETWEEN @start_date AND @current_date;
SELECT COUNT(*) FROM incidents WHERE department = 'HR' AND incident_date BETWEEN DATE_SUB(CURDATE(), INTERVAL 3 MONTH) AND CURDATE();
Count the number of companies founded by underrepresented minorities
CREATE TABLE company_founding (company_name VARCHAR(255),founder_minority VARCHAR(10)); INSERT INTO company_founding VALUES ('Acme Inc','Yes'); INSERT INTO company_founding VALUES ('Beta Corp','No'); INSERT INTO company_founding VALUES ('Charlie LLC','Yes'); INSERT INTO company_founding VALUES ('Delta Co','No');
SELECT COUNT(*) FROM company_founding WHERE company_founding.founder_minority = 'Yes';
Show yield data for the past harvest season
CREATE TABLE yield_data (harvest_date DATE,crop_type TEXT,yield_per_acre FLOAT); INSERT INTO yield_data (harvest_date,crop_type,yield_per_acre) VALUES ('2021-11-01','Corn',180),('2021-11-01','Soybeans',60),('2021-12-01','Corn',190);
SELECT yield_per_acre FROM yield_data WHERE harvest_date >= DATE(NOW()) - INTERVAL 1 YEAR;
Delete the construction labor record for worker with ID 5678
CREATE TABLE construction_labor (worker_id INT,hours_worked INT);
DELETE FROM construction_labor WHERE worker_id = 5678;
What is the maximum depth recorded for any underwater canyon?
CREATE TABLE underwater_canyons (canyon_name TEXT,max_depth_m INT); INSERT INTO underwater_canyons (canyon_name,max_depth_m) VALUES ('Milwaukee Deep',8380),('Sirena Deep',9816),('Tonga Trench',10882);
SELECT MAX(max_depth_m) FROM underwater_canyons;
What is the average number of streams per user in each country?
CREATE TABLE country_streams (stream_id INT,country VARCHAR(255),user_id INT,streams_amount INT);
SELECT country, AVG(streams_amount) FROM country_streams GROUP BY country;
What is the maximum and minimum number of attendees at cultural events in each state, grouped by state?
CREATE TABLE cultural_events (id INT,name VARCHAR(255),state VARCHAR(255),attendance INT);
SELECT state, MAX(attendance) AS max_attendance, MIN(attendance) AS min_attendance FROM cultural_events GROUP BY state;
Show average age of athletes by sport
athlete_demographics
SELECT sport, AVG(age) as avg_age FROM athlete_demographics GROUP BY sport;
Get the number of fair-trade coffee beans imported from Colombia in 2020.
CREATE TABLE FairTradeCoffee (id INT,origin VARCHAR(50),year INT,quantity INT); INSERT INTO FairTradeCoffee (id,origin,year,quantity) VALUES (1,'Colombia',2019,1000),(2,'Colombia',2020,1500),(3,'Ethiopia',2019,800),(4,'Ethiopia',2020,1200);
SELECT COUNT(*) FROM FairTradeCoffee WHERE origin = 'Colombia' AND year = 2020;
What is the percentage of total donations made by each cause in Latin America?
CREATE TABLE cause_percentage (cause VARCHAR(50),country VARCHAR(50),donation DECIMAL(10,2)); INSERT INTO cause_percentage (cause,country,donation) VALUES ('Global Health','Brazil',3000.00),('Education','Argentina',4000.00),('Environment','Mexico',5000.00),('Animal Welfare','Colombia',6000.00);
SELECT cause, (SUM(donation) / (SELECT SUM(donation) FROM cause_percentage WHERE country IN ('Brazil', 'Argentina', 'Mexico', 'Colombia'))) * 100 AS percentage FROM cause_percentage WHERE country IN ('Brazil', 'Argentina', 'Mexico', 'Colombia') GROUP BY cause;
Find the number of unique users who have streamed or downloaded music by the artist 'Taylor Swift'.
CREATE TABLE users (id INT,name TEXT); CREATE TABLE user_actions (id INT,user_id INT,action TEXT,album_id INT,platform TEXT); CREATE TABLE albums (id INT,title TEXT,artist_id INT,platform TEXT); CREATE TABLE artists (id INT,name TEXT); CREATE VIEW taylor_swift_users AS SELECT DISTINCT user_id FROM user_actions JOIN albums a ON user_actions.album_id = a.id JOIN artists ar ON a.artist_id = ar.id WHERE ar.name = 'Taylor Swift';
SELECT COUNT(DISTINCT user_id) FROM taylor_swift_users;
What are the sales figures for each country?
CREATE TABLE sales_data (sale_id INT,product VARCHAR(255),country VARCHAR(255),sales FLOAT); INSERT INTO sales_data (sale_id,product,country,sales) VALUES (1,'ProductA','USA',4000),(2,'ProductB','Brazil',5000),(3,'ProductC','India',6000),(4,'ProductD','China',7000);
SELECT country, SUM(sales) FROM sales_data GROUP BY country;
Add a new program with program_id 201 and a budget of 12000 starting from 2022-01-01.
CREATE TABLE Programs (program_id INT,budget DECIMAL(10,2),start_date DATE);
INSERT INTO Programs (program_id, budget, start_date) VALUES (201, 12000, '2022-01-01');
Find the difference between the maximum and minimum age of readers who prefer political news in Australia.
CREATE TABLE readers (id INT,age INT,gender VARCHAR(10),country VARCHAR(50),news_preference VARCHAR(50)); INSERT INTO readers (id,age,gender,country,news_preference) VALUES (1,50,'Male','Australia','Political'),(2,30,'Female','Australia','Political');
SELECT MAX(age) - MIN(age) diff FROM readers WHERE country = 'Australia' AND news_preference = 'Political';
What is the average time between inspections per vessel?
CREATE TABLE vessels (id INT,name VARCHAR(255),imo INT); CREATE TABLE inspections (id INT,vessel_id INT,inspection_date DATE);
SELECT v.name, AVG(DATEDIFF(i2.inspection_date, i.inspection_date)) as avg_time_between_inspections FROM inspections i JOIN inspections i2 ON i.vessel_id = i2.vessel_id AND i.id < i2.id JOIN vessels v ON i.vessel_id = v.id GROUP BY v.name;
How many medical checkups did astronauts from India have before their space missions?
CREATE TABLE Astronauts (AstronautID INT,Name VARCHAR(50),Nationality VARCHAR(50));CREATE TABLE MedicalCheckups (CheckupID INT,AstronautID INT,Date DATE); INSERT INTO Astronauts (AstronautID,Name,Nationality) VALUES (1,'Rajesh Kumar','India'),(2,'Kavita Patel','India'); INSERT INTO MedicalCheckups (CheckupID,AstronautID,Date) VALUES (1,1,'2022-01-01'),(2,1,'2022-02-01'),(3,2,'2022-03-01');
SELECT COUNT(m.CheckupID) FROM MedicalCheckups m INNER JOIN Astronauts a ON m.AstronautID = a.AstronautID WHERE a.Nationality = 'India';
Find the top 3 countries with the most digital assets issued.
CREATE TABLE digital_assets (id INT,name VARCHAR,issue_country VARCHAR); INSERT INTO digital_assets (id,name,issue_country) VALUES (1,'CryptoCoin','United States'),(2,'DigiToken','Japan'),(3,'BitAsset','China'),(4,'EtherCoin','China'),(5,'RippleToken','India'),(6,'LiteCoin','Canada'),(7,'MoneroCoin','Germany');
SELECT issue_country, COUNT(*) as num_assets FROM digital_assets GROUP BY issue_country ORDER BY num_assets DESC LIMIT 3;