instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
What is the minimum explainability score for AI models used in education in Brazil?
CREATE TABLE ai_models (model_id INT,model_name TEXT,explainability_score DECIMAL(3,2),domain TEXT,country TEXT); INSERT INTO ai_models (model_id,model_name,explainability_score,domain,country) VALUES (1,'ExplainableBoosting',4.65,'Education','Brazil'),(2,'XGBoost',4.35,'Finance','Brazil'),(3,'TabTransformer',4.55,'Education','Brazil');
SELECT MIN(explainability_score) as min_explainability_score FROM ai_models WHERE domain = 'Education' AND country = 'Brazil';
How many autonomous driving research papers were published per month in 2021?
CREATE TABLE ResearchPapers (ID INT,Title TEXT,Author TEXT,PublicationDate DATE); INSERT INTO ResearchPapers (ID,Title,Author,PublicationDate) VALUES (1,'Deep Learning for Autonomous Driving','John Doe','2021-03-15'); INSERT INTO ResearchPapers (ID,Title,Author,PublicationDate) VALUES (2,'Reinforcement Learning in Autonomous Vehicles','Jane Smith','2021-07-22');
SELECT COUNT(*) FROM ResearchPapers WHERE YEAR(PublicationDate) = 2021 GROUP BY MONTH(PublicationDate);
How many community development projects were carried out in 'community_development' table, grouped by 'project_type'?
CREATE TABLE community_development (id INT,project_type VARCHAR(50),location VARCHAR(50),start_date DATE,end_date DATE); INSERT INTO community_development (id,project_type,location,start_date,end_date) VALUES (1,'Education','Afghanistan','2020-01-01','2020-12-31'),(2,'Health','Nigeria','2020-01-01','2020-12-31');
SELECT project_type, COUNT(*) FROM community_development GROUP BY project_type;
What is the maximum cargo weight (in metric tons) for each port?
CREATE TABLE ports (port_id INT,port_name VARCHAR(50),country VARCHAR(50)); INSERT INTO ports VALUES (1,'Tanjung Priok','Indonesia'); INSERT INTO ports VALUES (2,'Belawan','Indonesia'); CREATE TABLE cargo (cargo_id INT,port_id INT,weight_ton FLOAT); INSERT INTO cargo VALUES (1,1,5000); INSERT INTO cargo VALUES (2,1,7000); INSERT INTO cargo VALUES (3,2,3000); INSERT INTO cargo VALUES (4,2,4000);
SELECT ports.port_name, MAX(cargo.weight_ton) FROM cargo JOIN ports ON cargo.port_id = ports.port_id GROUP BY ports.port_name;
What was the average donation amount in 2021 by quarter?
CREATE TABLE donations (id INT,amount DECIMAL,donation_date DATE);
SELECT DATE_FORMAT(donation_date, '%Y-%V') as quarter, AVG(amount) as avg_donation_amount FROM donations WHERE donation_date >= '2021-01-01' AND donation_date < '2022-01-01' GROUP BY quarter;
What is the minimum dissolved oxygen level recorded in the Arctic Ocean?
CREATE TABLE ocean_properties (location VARCHAR(255),dissolved_oxygen FLOAT); INSERT INTO ocean_properties (location,dissolved_oxygen) VALUES ('Arctic Ocean',5.6),('Antarctic Ocean',6.2);
SELECT MIN(dissolved_oxygen) FROM ocean_properties WHERE location = 'Arctic Ocean';
Find the top 5 most reviewed eco-friendly hotels globally, and display their hotel_id, hotel_name, and review_count.
CREATE TABLE hotel_reviews(review_id INT,hotel_id INT,hotel_name TEXT,review_count INT); INSERT INTO hotel_reviews(review_id,hotel_id,hotel_name,review_count) VALUES (1,1,'Hotel Eco Ville',250),(2,2,'Eco Chateau',300),(3,3,'Green Provence Hotel',350),(4,4,'Eco Hotel Roma',280),(5,5,'Green Palace Hotel',400),(6,6,'Eco Paradise Hotel',320),(7,7,'Hotel Verde',260);
SELECT hotel_id, hotel_name, review_count FROM (SELECT hotel_id, hotel_name, review_count, ROW_NUMBER() OVER (ORDER BY review_count DESC) rn FROM hotel_reviews WHERE hotel_name LIKE 'Eco%' OR hotel_name LIKE 'Green%') subquery WHERE rn <= 5;
Identify cities with music festivals having the highest number of artists who have had over 1,000,000 listens?
CREATE TABLE Artists (ArtistID INT PRIMARY KEY,ArtistName VARCHAR(100),Age INT,Gender VARCHAR(10),Genre VARCHAR(50)); CREATE TABLE Songs (SongID INT PRIMARY KEY,SongName VARCHAR(100),Genre VARCHAR(50),Listens INT,ArtistID INT,CONSTRAINT FK_Artists FOREIGN KEY (ArtistID) REFERENCES Artists(ArtistID)); CREATE TABLE Festivals (FestivalID INT PRIMARY KEY,FestivalName VARCHAR(100),City VARCHAR(50),TotalTicketSales INT); CREATE VIEW TotalListens AS SELECT ArtistID,SUM(Listens) as TotalListens FROM Songs GROUP BY ArtistID; CREATE VIEW ArtistFestivals AS SELECT ArtistID,FestivalID FROM Artists INNER JOIN TotalListens ON Artists.ArtistID = TotalListens.ArtistID WHERE TotalListens > 1000000; CREATE VIEW FestivalCities AS SELECT City,COUNT(ArtistFestivals.ArtistID) as NumberOfArtists FROM Festivals INNER JOIN ArtistFestivals ON Festivals.FestivalID = ArtistFestivals.FestivalID GROUP BY City;
SELECT City, MAX(NumberOfArtists) as HighestNumberOfArtists FROM FestivalCities GROUP BY City;
Which countries have the least number of impact investing organizations?
CREATE TABLE impact_investing_orgs (name TEXT,country TEXT); INSERT INTO impact_investing_orgs (name,country) VALUES ('Acme Impact','USA'),('GreenTech Initiatives','Canada'),('EcoVentures','USA'),('Global Philanthropic','UK'),('Sustainable Development Foundation','Brazil'),('Green Initiatives','India');
SELECT country, COUNT(*) as org_count FROM impact_investing_orgs GROUP BY country ORDER BY org_count ASC;
What is the total number of volunteers and total donation amount for the state of New York?
CREATE TABLE Donors (DonorID INT,Name TEXT,State TEXT,DonationAmount DECIMAL); INSERT INTO Donors (DonorID,Name,State,DonationAmount) VALUES (1,'John Doe','New York',50.00),(2,'Jane Smith','Texas',100.00); CREATE TABLE Volunteers (VolunteerID INT,Name TEXT,State TEXT,LastContactDate DATE); INSERT INTO Volunteers (VolunteerID,Name,State,LastContactDate) VALUES (1,'James Johnson','New York','2021-08-01'),(2,'Sarah Lee','Texas','2021-09-15');
SELECT COUNT(DISTINCT Donors.DonorID) AS TotalVolunteers, SUM(Donors.DonationAmount) AS TotalDonations FROM Donors WHERE Donors.State = 'New York';
How many IoT devices are present in total?
CREATE TABLE IoTDevices (device_id INT,device_type VARCHAR(20),region VARCHAR(10)); INSERT INTO IoTDevices (device_id,device_type,region) VALUES (1,'Soil Moisture Sensor','West'); INSERT INTO IoTDevices (device_id,device_type,region) VALUES (2,'Light Sensor','East'); INSERT INTO IoTDevices (device_id,device_type,region) VALUES (3,'Temperature Sensor','North');
SELECT COUNT(*) FROM IoTDevices;
Which causes received the most funding in the past year, including the total amount donated, for donors from Australia?
CREATE TABLE causes (cause_id INT,cause TEXT,created_at TIMESTAMP); INSERT INTO causes (cause_id,cause,created_at) VALUES (1,'Education','2020-01-01 00:00:00'),(2,'Health','2019-01-01 00:00:00'),(3,'Environment','2021-01-01 00:00:00'); CREATE TABLE donations (donation_id INT,donor_id INT,cause INT,amount DECIMAL(10,2),donor_country TEXT); INSERT INTO donations (donation_id,donor_id,cause,amount,donor_country) VALUES (1,1,1,500.00,'Australia'),(2,2,1,300.00,'USA'),(3,3,2,750.00,'Canada'),(4,4,2,250.00,'Australia'),(5,5,3,600.00,'USA');
SELECT c.cause, SUM(d.amount) as total_donated FROM donations d JOIN causes c ON d.cause = c.cause WHERE c.created_at >= DATEADD(year, -1, CURRENT_TIMESTAMP) AND d.donor_country = 'Australia' GROUP BY c.cause ORDER BY total_donated DESC;
Count the number of engines produced by 'Rolls-Royce' and 'CFM International'.
CREATE TABLE Engine_Manufacturers (manufacturer VARCHAR(255),engine_model VARCHAR(255),quantity INT); INSERT INTO Engine_Manufacturers (manufacturer,engine_model,quantity) VALUES ('Pratt & Whitney','PW1000G',500),('Rolls-Royce','Trent XWB',600),('General Electric','GE9X',700),('Rolls-Royce','Trent 700',800),('CFM International','CFM56',900);
SELECT manufacturer, SUM(quantity) FROM Engine_Manufacturers WHERE manufacturer IN ('Rolls-Royce', 'CFM International') GROUP BY manufacturer;
What is the total number of properties co-owned by 'Alice' in all cities?
CREATE TABLE co_ownership (id INT,property_id INT,owner TEXT,city TEXT,size INT); INSERT INTO co_ownership (id,property_id,owner,city,size) VALUES (1,101,'Alice','Austin',1200),(2,104,'Alice','Seattle',800),(3,105,'Alice','Portland',1000);
SELECT COUNT(DISTINCT property_id) FROM co_ownership WHERE owner = 'Alice';
What is the average age of patients who received therapy in Spanish in mental health centers located in Miami?
CREATE TABLE mental_health_center (center_id INT,name VARCHAR(255),location VARCHAR(255)); INSERT INTO mental_health_center (center_id,name,location) VALUES (1,'Mental Health Center 1','Miami'),(2,'Mental Health Center 2','Miami'),(3,'Mental Health Center 3','New York'); CREATE TABLE patient (patient_id INT,center_id INT,age INT,language VARCHAR(255)); CREATE TABLE therapy_session (session_id INT,patient_id INT,session_language VARCHAR(255));
SELECT AVG(patient.age) FROM patient JOIN therapy_session ON patient.patient_id = therapy_session.patient_id JOIN mental_health_center ON patient.center_id = mental_health_center.center_id WHERE mental_health_center.location = 'Miami' AND therapy_session.session_language = 'Spanish';
Delete wells drilled before 2021 in the Amazon Basin.
CREATE TABLE wells (well_name TEXT,drilling_date DATE,production_qty INT); INSERT INTO wells (well_name,drilling_date,production_qty) VALUES ('Well K','2020-12-19',4000),('Well L','2021-04-25',4200);
DELETE FROM wells WHERE drilling_date < '2021-01-01';
Which gallery had the highest total revenue in 2021?
CREATE TABLE GalleryRevenue (Gallery VARCHAR(255),ArtWork VARCHAR(255),Year INT,Revenue DECIMAL(10,2)); INSERT INTO GalleryRevenue (Gallery,ArtWork,Year,Revenue) VALUES ('Gallery 1','Artwork 1',2021,500.00),('Gallery 1','Artwork 2',2021,400.00),('Gallery 2','Artwork 3',2021,750.00),('Gallery 2','Artwork 4',2021,1000.00);
SELECT Gallery, SUM(Revenue) as TotalRevenue FROM GalleryRevenue WHERE Year = 2021 GROUP BY Gallery ORDER BY TotalRevenue DESC LIMIT 1;
List the top 10 smart city projects with the highest annual carbon offsets
CREATE TABLE smart_cities_carbon_offsets (id INT,project_id INT,annual_carbon_offsets INT);
SELECT smart_cities.project_name, smart_cities_carbon_offsets.annual_carbon_offsets FROM smart_cities JOIN smart_cities_carbon_offsets ON smart_cities.id = smart_cities_carbon_offsets.project_id ORDER BY annual_carbon_offsets DESC LIMIT 10;
What is the total number of network infrastructure investments in each country?
CREATE TABLE network_investments (investment_id int,investment_amount float,country varchar(20)); INSERT INTO network_investments (investment_id,investment_amount,country) VALUES (1,1000000,'USA'),(2,2000000,'Canada'),(3,1500000,'Mexico'); CREATE TABLE network_upgrades (upgrade_id int,upgrade_date date,investment_id int); INSERT INTO network_upgrades (upgrade_id,upgrade_date,investment_id) VALUES (1,'2021-01-01',1),(2,'2021-02-01',2),(3,'2021-03-01',3);
SELECT country, COUNT(*) as num_investments FROM network_investments GROUP BY country;
What is the maximum budget allocated for technology for social good projects in Europe?
CREATE TABLE tech_for_social_good (project_id INT,region VARCHAR(20),budget DECIMAL(10,2)); INSERT INTO tech_for_social_good (project_id,region,budget) VALUES (1,'Europe',45000.00),(2,'North America',55000.00),(3,'Europe',60000.00);
SELECT MAX(budget) FROM tech_for_social_good WHERE region = 'Europe';
What is the total number of unique wallet addresses that have interacted with decentralized finance (DeFi) protocols on the Binance Smart Chain network, and what is the average number of interactions per address?
CREATE TABLE binance_smart_chain_wallets (wallet_address VARCHAR(255),interaction_count INT);
SELECT COUNT(DISTINCT wallet_address) as total_wallets, AVG(interaction_count) as avg_interactions FROM binance_smart_chain_wallets WHERE interaction_count > 0;
What is the minimum and maximum number of patients served per rural health center in South America, and how many of these centers serve more than 40000 patients?
CREATE TABLE rural_health_centers (center_id INT,center_name VARCHAR(100),country VARCHAR(50),num_patients INT); INSERT INTO rural_health_centers (center_id,center_name,country,num_patients) VALUES (1,'Center A','Brazil',45000),(2,'Center B','Brazil',38000),(3,'Center C','Argentina',52000),(4,'Center D','Argentina',59000);
SELECT MIN(num_patients) AS min_patients_per_center, MAX(num_patients) AS max_patients_per_center, COUNT(*) FILTER (WHERE num_patients > 40000) AS centers_with_more_than_40000_patients FROM rural_health_centers WHERE country IN (SELECT name FROM countries WHERE continent = 'South America');
Calculate the average length for vessels in each country.
CREATE TABLE VesselCountry (VesselCountryID INT,VesselCountry VARCHAR(50)); INSERT INTO VesselCountry (VesselCountryID,VesselCountry) VALUES (1,'USA'); INSERT INTO VesselCountry (VesselCountryID,VesselCountry) VALUES (2,'Netherlands');
SELECT v.VesselCountry, AVG(v.Length) as AverageLength FROM Vessel v JOIN Port p ON v.PortID = p.PortID JOIN VesselCountry vc ON p.Country = vc.VesselCountry GROUP BY v.VesselCountry;
What is the total revenue of organic skincare products?
CREATE TABLE Products (id INT,category TEXT,price DECIMAL(5,2),is_organic BOOLEAN); INSERT INTO Products (id,category,price,is_organic) VALUES (1,'Cleanser',19.99,true),(2,'Toner',14.99,false);
SELECT SUM(price) FROM Products WHERE is_organic = true AND category = 'Skincare';
List all financial capability programs offered by providers in Japan?
CREATE TABLE financial_capability_programs (provider VARCHAR(50),program VARCHAR(50),country VARCHAR(50)); INSERT INTO financial_capability_programs (provider,program,country) VALUES ('Bank G','Financial Literacy for Seniors','Japan'),('Credit Union H','Youth Financial Education','India');
SELECT DISTINCT provider, program FROM financial_capability_programs WHERE country = 'Japan';
What is the most played game genre among players from Japan?
CREATE TABLE Games (GameID INT,GameName VARCHAR(20),Genre VARCHAR(20)); INSERT INTO Games (GameID,GameName,Genre) VALUES (1,'Fortnite','Battle Royale'),(2,'Minecraft','Sandbox'),(3,'Super Mario Odyssey','Platformer'),(4,'Final Fantasy XV','RPG'); CREATE TABLE Players_Games (PlayerID INT,GameID INT); INSERT INTO Players_Games (PlayerID,GameID) VALUES (1,1),(2,2),(3,3),(4,3),(5,4); CREATE TABLE Players (PlayerID INT,Age INT,Gender VARCHAR(10),Country VARCHAR(20)); INSERT INTO Players (PlayerID,Age,Gender,Country) VALUES (1,25,'Male','USA'),(2,30,'Female','Japan'),(3,15,'Male','Japan'),(4,35,'Female','Mexico'),(5,45,'Male','Japan');
SELECT Genre, COUNT(*) AS Popularity FROM Players INNER JOIN Players_Games ON Players.PlayerID = Players_Games.PlayerID INNER JOIN Games ON Players_Games.GameID = Games.GameID WHERE Players.Country = 'Japan' GROUP BY Genre ORDER BY Popularity DESC LIMIT 1;
How many 'retail' workers are there in total, and what is the average wage for this sector?
CREATE TABLE worker_data (id INT,sector VARCHAR(20),wage FLOAT); INSERT INTO worker_data (id,sector,wage) VALUES (1,'retail',15.50),(2,'retail',16.25),(3,'manufacturing',20.00),(4,'manufacturing',18.75);
SELECT COUNT(*), AVG(wage) FROM worker_data WHERE sector = 'retail';
What is the average quantity of sustainable materials used in projects located in California?
CREATE TABLE project (id INT PRIMARY KEY,name VARCHAR(255),location VARCHAR(255),start_date DATE,end_date DATE,sustainability_rating FLOAT); CREATE TABLE sustainable_material (id INT PRIMARY KEY,project_id INT,material_name VARCHAR(255),quantity INT);
SELECT AVG(sm.quantity) as avg_quantity FROM project p INNER JOIN sustainable_material sm ON p.id = sm.project_id WHERE p.location = 'California';
Delete the Batik traditional art?
CREATE TABLE TraditionalArt (name VARCHAR(255),artists_count INT); INSERT INTO TraditionalArt (name,artists_count) VALUES ('Batik',135);
DELETE FROM TraditionalArt WHERE name = 'Batik';
How many satellite images were processed for the "field1" location?
CREATE TABLE satellite_images (id INT,image_url VARCHAR(255),location VARCHAR(255),processing_time DATETIME); INSERT INTO satellite_images (id,image_url,location,processing_time) VALUES (1,'image1.jpg','field1','2022-01-01 12:00:00'),(2,'image2.jpg','field2','2022-01-01 13:00:00');
SELECT COUNT(*) FROM satellite_images WHERE location = 'field1';
Find the total number of shared bikes and e-scooters in Madrid and Barcelona?
CREATE TABLE spain_ride_sharing (id INT,vehicle VARCHAR(20),city VARCHAR(20)); INSERT INTO spain_ride_sharing (id,vehicle,city) VALUES (1,'bike','Madrid'),(2,'e-scooter','Madrid'),(3,'bike','Barcelona'),(4,'e-scooter','Barcelona');
SELECT COUNT(*) FROM spain_ride_sharing WHERE city IN ('Madrid', 'Barcelona') AND vehicle IN ('bike', 'e-scooter');
How many female faculty members are there in the Engineering school?
CREATE TABLE faculty (id INT,gender VARCHAR(6),school VARCHAR(10)); INSERT INTO faculty (id,gender,school) VALUES (1,'male','Arts'),(2,'female','Engineering');
SELECT COUNT(*) FROM faculty WHERE gender = 'female' AND school = 'Engineering';
Find suppliers that deliver to specific regions and their average delivery time.
CREATE TABLE DeliveryRegions (SupplierID INT,Region VARCHAR(50)); INSERT INTO DeliveryRegions (SupplierID,Region) VALUES (1,'East Coast'); INSERT INTO DeliveryRegions (SupplierID,Region) VALUES (2,'West Coast'); CREATE TABLE DeliveryTimes (DeliveryID INT,SupplierID INT,DeliveryTime INT); INSERT INTO DeliveryTimes (DeliveryID,SupplierID,DeliveryTime) VALUES (1,1,5); INSERT INTO DeliveryTimes (DeliveryID,SupplierID,DeliveryTime) VALUES (2,2,7);
SELECT DR.SupplierID, DR.Region, AVG(DT.DeliveryTime) as AverageDeliveryTime FROM DeliveryRegions DR INNER JOIN DeliveryTimes DT ON DR.SupplierID = DT.SupplierID WHERE DR.Region IN ('East Coast', 'West Coast') GROUP BY DR.SupplierID, DR.Region;
Who are the clients with a billing amount greater than $5000 in the 'Personal Injury' category?
CREATE TABLE Clients (ClientID INT,Name VARCHAR(50),Category VARCHAR(50),BillingAmount DECIMAL(10,2)); INSERT INTO Clients (ClientID,Name,Category,BillingAmount) VALUES (1,'John Doe','Personal Injury',5000.00),(2,'Jane Smith','Personal Injury',3000.00);
SELECT Name FROM Clients WHERE Category = 'Personal Injury' AND BillingAmount > 5000;
What is the maximum number of followers for users from Germany who have posted about #music in the last month?
CREATE TABLE users (id INT,country VARCHAR(255),followers INT); CREATE TABLE posts (id INT,user_id INT,hashtags VARCHAR(255),post_date DATE);
SELECT MAX(users.followers) FROM users INNER JOIN posts ON users.id = posts.user_id WHERE users.country = 'Germany' AND hashtags LIKE '%#music%' AND post_date >= DATE_SUB(CURDATE(), INTERVAL 1 MONTH);
What are the military technologies related to encryption in the 'military_tech' table?
CREATE TABLE military_tech (tech VARCHAR(255)); INSERT INTO military_tech (tech) VALUES ('encryption_algorithm'),('cipher_machine'),('secure_communications'),('biometric_access'),('laser_weapon');
SELECT tech FROM military_tech WHERE tech LIKE '%encryption%';
What is the total capacity of hospitals and clinics in each state?
CREATE TABLE hospitals (id INT,name TEXT,state TEXT,capacity INT); INSERT INTO hospitals (id,name,state,capacity) VALUES (1,'Hospital A','NY',200),(2,'Hospital B','NY',300),(3,'Clinic C','NY',50),(4,'Hospital D','CA',250),(5,'Clinic E','CA',40);
SELECT state, SUM(capacity) FROM hospitals GROUP BY state;
What is the profit margin for each supplier's items?
CREATE TABLE inventory(item_id INT,supplier_id INT,quantity INT,cost_price DECIMAL); CREATE TABLE menu_items(menu_item_id INT,name TEXT,supplier_id INT,type TEXT,price DECIMAL);
SELECT suppliers.name, SUM((menu_items.price - inventory.cost_price) * inventory.quantity) / SUM(menu_items.price * inventory.quantity) as profit_margin FROM inventory JOIN menu_items ON inventory.item_id = menu_items.menu_item_id JOIN suppliers ON menu_items.supplier_id = suppliers.supplier_id GROUP BY suppliers.name;
Update the circular_economy table to set waste_reduction to 20 for all materials with type as 'Natural Fibers'
CREATE TABLE circular_economy (id INT PRIMARY KEY,material_name VARCHAR(255),type VARCHAR(255),waste_reduction INT); INSERT INTO circular_economy (id,material_name,type,waste_reduction) VALUES (1,'Cotton','Natural Fibers',15),(2,'Hemp','Natural Fibers',10),(3,'Silk','Natural Fibers',12);
UPDATE circular_economy SET waste_reduction = 20 WHERE type = 'Natural Fibers';
What is the average quantity of product 3 in inventory?
CREATE TABLE inventory (id INT PRIMARY KEY,product_id INT,size VARCHAR(10),quantity INT); INSERT INTO inventory (id,product_id,size,quantity) VALUES (1,1,'S',20),(2,1,'M',30),(3,3,'L',25),(4,3,'XL',10);
SELECT AVG(quantity) FROM inventory WHERE product_id = 3;
What is the name and age of the youngest person who received medical assistance in Afghanistan in 2022?
CREATE TABLE medical_assistance (id INT,name TEXT,age INT,country TEXT,year INT); INSERT INTO medical_assistance (id,name,age,country,year) VALUES (1,'Zainab Khan',25,'Afghanistan',2022),(2,'Hamid Karzai',30,'Afghanistan',2022),(3,'Najibullah Ahmadzai',35,'Afghanistan',2022);
SELECT name, age FROM medical_assistance WHERE country = 'Afghanistan' AND year = 2022 ORDER BY age LIMIT 1;
How many vehicles were serviced in the Bronx garage on December 15th, 2021?
CREATE TABLE garages (garage_id INT,garage_name VARCHAR(255)); INSERT INTO garages (garage_id,garage_name) VALUES (1,'Bronx'); CREATE TABLE service (service_id INT,garage_id INT,service_date DATE); INSERT INTO service (service_id,garage_id,service_date) VALUES (1,1,'2021-12-15');
SELECT COUNT(*) FROM service WHERE garage_id = 1 AND service_date = '2021-12-15';
How many employees have been hired in the last 6 months in the Sales department?
CREATE TABLE Employees (EmployeeID INT,HireDate DATE,Department VARCHAR(20)); INSERT INTO Employees (EmployeeID,HireDate,Department) VALUES (1,'2022-01-01','Sales'),(2,'2022-02-15','IT'),(3,'2021-07-01','HR');
SELECT COUNT(*) FROM Employees WHERE Department = 'Sales' AND HireDate >= DATE_SUB(CURDATE(), INTERVAL 6 MONTH);
What is the average score of students who have completed the online_course for the data_science course?
CREATE TABLE online_course (id INT,student_id INT,course_name VARCHAR(50),score INT,completed BOOLEAN);
SELECT AVG(score) FROM online_course WHERE course_name = 'data_science' AND completed = TRUE;
What is the maximum soil moisture level recorded for vineyards in the past week?
CREATE TABLE vineyard_soil_moisture (vineyard_name VARCHAR(30),record_date DATE,soil_moisture INT); INSERT INTO vineyard_soil_moisture (vineyard_name,record_date,soil_moisture) VALUES ('Vineyard A','2022-05-01',60),('Vineyard B','2022-05-01',65),('Vineyard C','2022-05-01',70);
SELECT MAX(soil_moisture) as max_soil_moisture FROM vineyard_soil_moisture WHERE record_date >= DATEADD(week, -1, GETDATE());
Find the average speed of vessels that traveled to both Japan and South Korea
CREATE TABLE VESSEL_TRAVEL (id INT,vessel_name VARCHAR(50),destination VARCHAR(50),speed FLOAT);
SELECT AVG(speed) FROM (SELECT speed FROM VESSEL_TRAVEL WHERE destination = 'Japan' INTERSECT SELECT speed FROM VESSEL_TRAVEL WHERE destination = 'South Korea') AS SubQuery;
What is the minimum and maximum water pH for each tank in the 'tank_data' table?
CREATE TABLE tank_data (tank_id INT,species VARCHAR(255),water_ph DECIMAL(5,2)); INSERT INTO tank_data (tank_id,species,water_ph) VALUES (1,'Tilapia',7.5),(2,'Salmon',6.0),(3,'Tilapia',7.8),(4,'Catfish',7.2),(5,'Salmon',6.5);
SELECT tank_id, MIN(water_ph) as min_ph, MAX(water_ph) as max_ph FROM tank_data GROUP BY tank_id;
List all farms in the 'farms' table that use recirculating aquaculture systems (RAS).
CREATE TABLE farms (id INT,name TEXT,ras BOOLEAN); INSERT INTO farms (id,name,ras) VALUES (1,'Farm A',TRUE); INSERT INTO farms (id,name,ras) VALUES (2,'Farm B',FALSE); INSERT INTO farms (id,name,ras) VALUES (3,'Farm C',TRUE); INSERT INTO farms (id,name,ras) VALUES (4,'Farm D',FALSE);
SELECT name FROM farms WHERE ras = TRUE;
What is the difference in mental health scores between the student with the highest grade and the student with the lowest grade?
CREATE TABLE students (id INT,name VARCHAR(50),grade FLOAT,mental_health_score INT); INSERT INTO students (id,name,grade,mental_health_score) VALUES (1,'John Doe',85.5,70); INSERT INTO students (id,name,grade,mental_health_score) VALUES (2,'Jane Smith',68.0,85);
SELECT (SELECT mental_health_score FROM students WHERE id = (SELECT id FROM students WHERE grade = (SELECT MAX(grade) FROM students))) - (SELECT mental_health_score FROM students WHERE id = (SELECT id FROM students WHERE grade = (SELECT MIN(grade) FROM students)));
Determine the rank of each team based on their total ticket sales.
CREATE TABLE teams (team_id INT,team_name VARCHAR(100)); INSERT INTO teams (team_id,team_name) VALUES (1,'Barcelona'),(2,'Bayern Munich'); 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 team_name, RANK() OVER (ORDER BY total_sales DESC) as team_rank FROM (SELECT team_home_id, SUM(tickets_sold) as total_sales FROM matches GROUP BY team_home_id UNION ALL SELECT team_away_id, SUM(tickets_sold) as total_sales FROM matches GROUP BY team_away_id) total_sales JOIN teams t ON total_sales.team_home_id = t.team_id OR total_sales.team_away_id = t.team_id;
What is the average salary difference between male and female employees in the same department and location?
CREATE TABLE Employees (EmployeeID INT,FirstName VARCHAR(50),LastName VARCHAR(50),Department VARCHAR(50),Location VARCHAR(50),Position VARCHAR(50),Salary DECIMAL(10,2),Gender VARCHAR(50)); INSERT INTO Employees (EmployeeID,FirstName,LastName,Department,Location,Position,Salary,Gender) VALUES (1,'John','Doe','IT','New York','Developer',80000.00,'Male'),(2,'Jane','Doe','IT','New York','Developer',75000.00,'Female');
SELECT AVG(Salary) FROM Employees WHERE Gender = 'Male' INTERSECT SELECT AVG(Salary) FROM Employees WHERE Gender = 'Female';
Display the policy type and average claim amount for policies with more than one claim in the state of California
CREATE TABLE claims (claim_id INT,policy_id INT,claim_amount DECIMAL(10,2),policy_state VARCHAR(2));
SELECT policy_type, AVG(claim_amount) FROM claims WHERE policy_state = 'CA' GROUP BY policy_type HAVING COUNT(policy_id) > 1;
How many donations were made in January 2021?
CREATE TABLE donations (id INT,donation_date DATE); INSERT INTO donations (id,donation_date) VALUES (1,'2021-01-01'),(2,'2021-01-15'),(3,'2021-02-01');
SELECT COUNT(*) FROM donations WHERE donation_date BETWEEN '2021-01-01' AND '2021-01-31';
What is the total number of transactions for each decentralized application on the Solana network?
CREATE TABLE dapp (dapp_name VARCHAR(50)); CREATE TABLE dapp_transactions (dapp_name VARCHAR(50),tx_hash VARCHAR(64));
SELECT dapp.dapp_name, COUNT(dapp_tx.tx_hash) as tx_count FROM dapp LEFT JOIN dapp_transactions dapp_tx ON dapp.dapp_name = dapp_tx.dapp_name GROUP BY dapp.dapp_name;
How many concerts were sold out in 2021 for artists who identify as non-binary?
CREATE TABLE concert_events (event_id INT,artist_id INT,event_date DATE,event_location VARCHAR(255),sold_out BOOLEAN); INSERT INTO concert_events (event_id,artist_id,event_date,event_location,sold_out) VALUES (1,1,'2022-01-01','NYC',FALSE); CREATE TABLE artist_demographics (artist_id INT,artist_name VARCHAR(255),gender VARCHAR(50)); INSERT INTO artist_demographics (artist_id,artist_name,gender) VALUES (1,'Jane Doe','non-binary');
SELECT COUNT(*) FROM concert_events ce JOIN artist_demographics ad ON ce.artist_id = ad.artist_id WHERE ce.sold_out = TRUE AND ad.gender = 'non-binary' AND ce.event_date BETWEEN '2021-01-01' AND '2021-12-31';
Who are the top 3 investigative journalists in terms of article views, and what are their respective total views?
CREATE TABLE journalists (id INT,name VARCHAR(30)); CREATE TABLE articles (id INT,journalist_id INT,views INT,category VARCHAR(20)); INSERT INTO journalists VALUES (1,'Jane Doe'); INSERT INTO articles VALUES (1,1,1000,'investigative');
SELECT journalists.name, SUM(articles.views) AS total_views FROM journalists INNER JOIN articles ON journalists.id = articles.journalist_id WHERE articles.category = 'investigative' GROUP BY journalists.name ORDER BY total_views DESC LIMIT 3;
What is the average design pressure for all dams in the database?
CREATE TABLE Dams (id INT,name VARCHAR(100),design_pressure FLOAT); INSERT INTO Dams (id,name,design_pressure) VALUES (1,'Hoover Dam',4500),(2,'Glen Canyon Dam',2000),(3,'Oroville Dam',3500);
SELECT AVG(design_pressure) FROM Dams;
What is the total number of tickets sold for basketball games and the average ticket price?
CREATE TABLE events (event_id INT,name VARCHAR(255),city VARCHAR(255),sport VARCHAR(255),price DECIMAL(5,2)); INSERT INTO events (event_id,name,city,sport,price) VALUES (1,'Basketball Game','California','Basketball',120.50),(2,'Baseball Game','New York','Baseball',50.00),(3,'Soccer Game','California','Soccer',30.00),(4,'Basketball Game','New York','Basketball',150.00); INSERT INTO ticket_sales (sale_id,event_id,quantity) VALUES (1,1,1000),(2,1,500),(3,2,750),(4,3,1500),(5,4,2000);
SELECT sport, COUNT(event_id), AVG(price) FROM events JOIN ticket_sales ON events.event_id = ticket_sales.event_id WHERE sport = 'Basketball' GROUP BY sport;
What is the total length of highways in India?
CREATE TABLE Highway (id INT,name VARCHAR(50),length FLOAT,country VARCHAR(50)); INSERT INTO Highway (id,name,length,country) VALUES (1,'Golden Quadrilateral',5846,'India');
SELECT SUM(length) FROM Highway WHERE country = 'India';
Insert new disaster preparedness data for district 5 neighborhoods
CREATE TABLE districts (id INT,name VARCHAR(255)); INSERT INTO districts (id,name) VALUES (5,'Riverview'); CREATE TABLE neighborhoods (id INT,district_id INT,name VARCHAR(255)); INSERT INTO neighborhoods (id,district_id,name) VALUES (501,5,'Northriver'); INSERT INTO neighborhoods (id,district_id,name) VALUES (502,5,'Southriver'); CREATE TABLE disaster_preparedness (id INT,neighborhood_id INT,supplies_stock INT);
INSERT INTO disaster_preparedness (id, neighborhood_id, supplies_stock) VALUES (5001, 501, 100), (5002, 501, 200), (5003, 502, 150);
Remove permit 2021-003 from the database
CREATE TABLE building_permits (permit_number TEXT,contractor TEXT); INSERT INTO building_permits (permit_number,contractor) VALUES ('2021-003','Contractor B');
WITH cte AS (DELETE FROM building_permits WHERE permit_number = '2021-003') SELECT * FROM cte;
How many fish were added to each farm in the last week of October 2021, ordered by the number of fish added?
CREATE TABLE FarmStock (farm_id INT,stock_change INT,stock_date DATE); INSERT INTO FarmStock (farm_id,stock_change,stock_date) VALUES (1,300,'2021-10-25'),(1,250,'2021-10-30'),(2,100,'2021-10-24');
SELECT farm_id, SUM(stock_change) as total_stock_change FROM FarmStock WHERE stock_date >= '2021-10-25' AND stock_date < '2021-11-01' GROUP BY farm_id ORDER BY SUM(stock_change) DESC;
What is the median property price for properties in the city of Portland with a walkability score of 80 or above?
CREATE TABLE properties (id INT,price FLOAT,city VARCHAR(20),walkability_score INT); INSERT INTO properties (id,price,city,walkability_score) VALUES (1,750000,'Portland',85),(2,850000,'Portland',75),(3,650000,'Portland',90),(4,950000,'Seattle',60),(5,550000,'Portland',80);
SELECT AVG(price) FROM (SELECT price FROM properties WHERE city = 'Portland' AND walkability_score >= 80 ORDER BY price LIMIT 2 OFFSET 1) AS subquery;
How many countries have marine protected areas in the ocean?
CREATE TABLE countries (country_id INT,name VARCHAR(255),marine_protected_area BOOLEAN); INSERT INTO countries (country_id,name,marine_protected_area) VALUES (1,'Australia',TRUE),(2,'Canada',FALSE),(3,'France',TRUE);
SELECT COUNT(*) FROM countries WHERE marine_protected_area = TRUE;
Show the energy efficiency statistics of the top 3 countries in Asia
CREATE TABLE energy_efficiency_stats (country VARCHAR(255),year INT,energy_efficiency_index FLOAT);
SELECT country, energy_efficiency_index FROM energy_efficiency_stats WHERE country IN (SELECT country FROM (SELECT country, AVG(energy_efficiency_index) as avg_efficiency FROM energy_efficiency_stats WHERE country IN ('Asia') GROUP BY country ORDER BY avg_efficiency DESC LIMIT 3) as temp) ORDER BY energy_efficiency_index DESC;
Calculate the percentage of mental health providers who speak a language other than English, by region.
CREATE TABLE MentalHealthProviders (ProviderID INT,Region VARCHAR(255),Language VARCHAR(255)); INSERT INTO MentalHealthProviders (ProviderID,Region,Language) VALUES (1,'North','English'),(2,'South','Spanish'),(3,'East','Mandarin'),(4,'West','English');
SELECT Region, COUNT(*) * 100.0 / (SELECT COUNT(*) FROM MentalHealthProviders WHERE Language <> 'English') as Percentage FROM MentalHealthProviders WHERE Language <> 'English' GROUP BY Region;
Get the total score of each player in the last week
game_stats(player_id,game_id,score,date_played)
SELECT player_id, SUM(score) as total_score FROM game_stats WHERE date_played >= CURDATE() - INTERVAL 1 WEEK GROUP BY player_id;
Which regions have more than 10 sustainable urbanism projects?
CREATE TABLE projects (id INT,region VARCHAR(50),type VARCHAR(50),budget INT); INSERT INTO projects (id,region,type,budget) VALUES (1,'Cascadia','sustainable urbanism',2000000),(2,'Pacific Northwest','sustainable urbanism',3000000),(3,'Cascadia','affordable housing',1000000);
SELECT region FROM projects WHERE type = 'sustainable urbanism' GROUP BY region HAVING COUNT(*) > 10;
What is the total donation amount by volunteers in Mexico, for each program, in the fiscal year 2022?
CREATE TABLE donations (id INT,donor_name VARCHAR(50),donation_amount DECIMAL(10,2),donation_date DATE,is_volunteer BOOLEAN,program_name VARCHAR(50)); INSERT INTO donations (id,donor_name,donation_amount,donation_date,is_volunteer,program_name) VALUES (1,'Carlos Hernandez',100.00,'2022-04-01',true,'Program A'),(2,'Ana Garcia',200.00,'2022-07-01',true,'Program B'),(3,'Luis Rodriguez',150.00,'2022-10-01',false,'Program C'),(4,'Mariana Sanchez',50.00,'2022-01-01',true,'Program A'); CREATE TABLE programs (id INT,program_name VARCHAR(50)); INSERT INTO programs (id,program_name) VALUES (1,'Program A'),(2,'Program B'),(3,'Program C');
SELECT p.program_name, DATE_FORMAT(d.donation_date, '%Y-%V') AS fiscal_year, SUM(d.donation_amount) FROM donations d JOIN programs p ON d.program_name = p.program_name WHERE d.is_volunteer = true AND d.donor_country = 'Mexico' GROUP BY p.program_name, fiscal_year;
List all sustainable tourism initiatives in North America
CREATE TABLE initiatives (id INT,country VARCHAR(255),initiative_name VARCHAR(255),initiative_type VARCHAR(255)); INSERT INTO initiatives (id,country,initiative_name,initiative_type) VALUES (1,'USA','National Parks Conservation','Environment'),(2,'Canada','Wildlife Protection Program','Animal Welfare'),(3,'Mexico','Sustainable Tourism Certification','Tourism'),(4,'USA','Green Cities Initiative','Urban Development');
SELECT country, initiative_name, initiative_type FROM initiatives WHERE country IN ('USA', 'Canada', 'Mexico');
What is the total amount donated by individuals in the city of Seattle?
CREATE TABLE donors (id INT,name TEXT,city TEXT,amount DECIMAL(10,2)); INSERT INTO donors (id,name,city,amount) VALUES (1,'Anna','Seattle',500.00),(2,'Brendan','New York',300.00);
SELECT SUM(amount) FROM donors WHERE city = 'Seattle';
Show community engagement programs in Africa.
CREATE TABLE community_engagement (id INT,program VARCHAR(50),region VARCHAR(50)); INSERT INTO community_engagement (id,program,region) VALUES (1,'Cultural Festival','Africa'),(2,'Art Exhibition','Europe');
SELECT * FROM community_engagement WHERE region = 'Africa';
What was the total contract value for arms reduction negotiations?
CREATE TABLE negotiations(id INT,negotiation VARCHAR(50),contractor VARCHAR(50),amount NUMERIC);
SELECT SUM(amount) FROM negotiations WHERE negotiation = 'Arms Reduction';
What is the average review score for hotels in Paris, France?
CREATE TABLE hotels (id INT,name TEXT,city TEXT,country TEXT,review_score FLOAT); INSERT INTO hotels (id,name,city,country,review_score) VALUES (1,'Hotel Ritz','Paris','France',4.8);
SELECT AVG(review_score) FROM hotels WHERE city = 'Paris' AND country = 'France';
What is the total revenue generated by organizations working on technology for social good in the first quarter of 2021?
CREATE TABLE Revenue (id INT,organization VARCHAR(50),revenue DECIMAL(5,2),month VARCHAR(10),year INT); INSERT INTO Revenue (id,organization,revenue,month,year) VALUES (1,'Equal Tech',15000.00,'January',2021),(2,'Tech Learning',20000.00,'February',2021),(3,'Global Connect',10000.00,'March',2021);
SELECT SUM(revenue) FROM Revenue WHERE organization IN (SELECT DISTINCT organization FROM Revenue WHERE category = 'Social Good') AND month IN ('January', 'February', 'March') AND year = 2021;
Who are the policyholders in 'CA' with the highest claim amount?
CREATE TABLE Policyholders (PolicyID INT,PolicyholderName TEXT,State TEXT); INSERT INTO Policyholders (PolicyID,PolicyholderName,State) VALUES (1,'Maria Garcia','CA'),(2,'James Lee','NY'); CREATE TABLE Claims (ClaimID INT,PolicyID INT,ClaimAmount INT); INSERT INTO Claims (ClaimID,PolicyID,ClaimAmount) VALUES (1,1,10000),(2,1,7000),(3,2,3000);
SELECT PolicyholderName, MAX(ClaimAmount) AS MaxClaimAmount FROM Policyholders INNER JOIN Claims ON Policyholders.PolicyID = Claims.PolicyID WHERE Policyholders.State = 'CA' GROUP BY PolicyholderName;
What is the minimum production in the 'gold' mine?
CREATE TABLE production_by_mine (id INT,mine VARCHAR(20),min_production DECIMAL(10,2)); INSERT INTO production_by_mine (id,mine,min_production) VALUES (1,'gold',900.00),(2,'silver',700.00),(3,'coal',800.00);
SELECT MIN(min_production) FROM production_by_mine WHERE mine = 'gold';
Find the total number of members who joined in 2020 and the number of workout sessions they had.
CREATE TABLE members_2020 (id INT,name VARCHAR(50),country VARCHAR(50),joined DATE); INSERT INTO members_2020 (id,name,country,joined) VALUES (1,'John Doe','USA','2020-01-01'); INSERT INTO members_2020 (id,name,country,joined) VALUES (2,'Jane Smith','Canada','2019-06-15'); INSERT INTO members_2020 (id,name,country,joined) VALUES (3,'Pedro Alvarez','Mexico','2021-02-20'); CREATE TABLE workout_sessions_2020 (id INT,member_id INT,activity VARCHAR(50),duration INT); INSERT INTO workout_sessions_2020 (id,member_id,activity,duration) VALUES (1,1,'Running',60); INSERT INTO workout_sessions_2020 (id,member_id,activity,duration) VALUES (2,1,'Cycling',45); INSERT INTO workout_sessions_2020 (id,member_id,activity,duration) VALUES (3,2,'Yoga',90);
SELECT m.id, COUNT(ws.id) as total_sessions FROM members_2020 m INNER JOIN workout_sessions_2020 ws ON m.id = ws.member_id GROUP BY m.id;
Update the 'FairTrade' status of the manufacturer 'GreenYarns' to 'Yes'.
CREATE TABLE Manufacturers (ManufacturerID INT,ManufacturerName VARCHAR(50),Region VARCHAR(50),FairTrade VARCHAR(5)); INSERT INTO Manufacturers (ManufacturerID,ManufacturerName,Region,FairTrade) VALUES (1,'EcoFriendlyFabrics','Europe','Yes'),(2,'GreenYarns','Asia','No');
UPDATE Manufacturers SET FairTrade = 'Yes' WHERE ManufacturerName = 'GreenYarns';
What is the average distance from Earth for astrophysics research on Venus?
CREATE TABLE astrophysics_research (research_id INT,location VARCHAR(50),distance FLOAT); INSERT INTO astrophysics_research (research_id,location,distance) VALUES (1,'Mars',50.3),(2,'Venus',10.2),(3,'Mars',40.1),(4,'Jupiter',70.5),(5,'Mars',60.0),(6,'Venus',11.5),(7,'Venus',12.1);
SELECT AVG(distance) FROM astrophysics_research WHERE location = 'Venus';
What is the maximum account balance for customers in each country?
CREATE TABLE customers (id INT,name VARCHAR(50),age INT,account_balance DECIMAL(10,2),country VARCHAR(50)); INSERT INTO customers (id,name,age,account_balance,country) VALUES (1,'Jane Smith',50,10000.00,'United States'),(2,'Marie Jones',45,20000.00,'Canada');
SELECT country, MAX(account_balance) as max_account_balance FROM customers GROUP BY country;
What is the average calorie count for organic dishes served in cafes located in the US?
CREATE TABLE cafe (cafe_id INT,name VARCHAR(50),country VARCHAR(50)); INSERT INTO cafe VALUES (1,'Cafe Central','USA'); INSERT INTO cafe VALUES (2,'Green Cafe','USA'); CREATE TABLE dishes (dish_id INT,name VARCHAR(50),type VARCHAR(20),calorie_count INT); INSERT INTO dishes VALUES (1,'Quinoa Salad','organic',350); INSERT INTO dishes VALUES (2,'Chickpea Curry','organic',500);
SELECT AVG(d.calorie_count) FROM dishes d JOIN cafe c ON d.name = c.name WHERE c.country = 'USA' AND d.type = 'organic';
List the top 2 carbon offset initiatives by number of participants in descending order.
CREATE TABLE carbon_offset_initiatives (initiative_id INT,initiative_name VARCHAR(100),participants INT); INSERT INTO carbon_offset_initiatives (initiative_id,initiative_name,participants) VALUES (1,'Tree Planting',5000),(2,'Energy Efficiency Program',7000),(3,'Public Transportation',6000);
SELECT initiative_name, participants FROM (SELECT initiative_name, participants, ROW_NUMBER() OVER (ORDER BY participants DESC) rn FROM carbon_offset_initiatives) WHERE rn <= 2
What is the total number of policy impact records for 'City N' and 'City O'?
CREATE TABLE policy_impact (city VARCHAR(255),policy_id INT,impact TEXT); INSERT INTO policy_impact
SELECT COUNT(*) FROM policy_impact WHERE (city = 'City N' OR city = 'City O')
Delete all records from the "marine_species" table where the "conservation_status" is "Least Concern"
CREATE TABLE marine_species (id INT PRIMARY KEY,species_name VARCHAR(255),conservation_status VARCHAR(255)); INSERT INTO marine_species (id,species_name,conservation_status) VALUES (1,'Blue Whale','Vulnerable'); INSERT INTO marine_species (id,species_name,conservation_status) VALUES (2,'Dolphin','Least Concern');
DELETE FROM marine_species WHERE conservation_status = 'Least Concern';
List all the initiatives related to technology accessibility in the education sector.
CREATE TABLE Initiatives (InitiativeID INT,InitiativeName VARCHAR(50),Sector VARCHAR(50)); INSERT INTO Initiatives (InitiativeID,InitiativeName,Sector) VALUES (1,'Accessible Coding Curriculum','Education'); INSERT INTO Initiatives (InitiativeID,InitiativeName,Sector) VALUES (2,'Digital Literacy for All','Healthcare');
SELECT InitiativeName FROM Initiatives WHERE Sector = 'Education';
What is the average temperature recorded for each month in 2020 across all arctic weather stations?
CREATE TABLE WeatherStation (ID INT,Name TEXT,Location TEXT,Country TEXT); INSERT INTO WeatherStation (ID,Name,Location,Country) VALUES (1,'Station1','Location1','Canada'); INSERT INTO WeatherStation (ID,Name,Location,Country) VALUES (2,'Station2','Location2','Russia'); CREATE TABLE Temperature (ID INT,WeatherStationID INT,Date DATE,Temperature FLOAT); INSERT INTO Temperature (ID,WeatherStationID,Date,Temperature) VALUES (1,1,'2020-01-01',-10.0);
SELECT AVG(Temperature) as Avg_Temperature, DATE_FORMAT(Date, '%M') as Month FROM Temperature JOIN WeatherStation ON Temperature.WeatherStationID = WeatherStation.ID WHERE Country IN ('Canada', 'Russia') AND Date LIKE '2020-%' GROUP BY Month;
What was the minimum temperature recorded in 'Winter' for each location?
CREATE TABLE sensors (id INT,location VARCHAR(255),temperature FLOAT,reading_date DATE); INSERT INTO sensors (id,location,temperature,reading_date) VALUES (1,'Field1',-5,'2021-12-01'); INSERT INTO sensors (id,location,temperature,reading_date) VALUES (2,'Field2',-3,'2022-01-15'); INSERT INTO sensors (id,location,temperature,reading_date) VALUES (3,'Field1',-6,'2022-02-01');
SELECT location, MIN(temperature) FROM sensors WHERE reading_date BETWEEN '2021-12-01' AND '2022-02-28' GROUP BY location
What is the total amount of education aid sent to South Sudan in the past year?
CREATE TABLE education_aid (id INT,location VARCHAR(50),aid_type VARCHAR(50),amount FLOAT,date DATE); INSERT INTO education_aid (id,location,aid_type,amount,date) VALUES (1,'South Sudan','education',300000,'2022-02-01');
SELECT SUM(amount) as total_education_aid FROM education_aid WHERE location = 'South Sudan' AND date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR);
What is the total fare collected for each route by time of day?
CREATE TABLE route (route_id INT,name VARCHAR(255)); CREATE TABLE trip (trip_id INT,route_id INT,fare DECIMAL(10,2),departure_time TIME); INSERT INTO route (route_id,name) VALUES (1,'Route A'),(2,'Route B'); INSERT INTO trip (trip_id,route_id,fare,departure_time) VALUES (1,1,2.00,'06:00:00'),(2,1,3.00,'07:00:00'),(3,2,4.00,'08:00:00'),(4,2,5.00,'09:00:00');
SELECT EXTRACT(HOUR FROM departure_time) AS hour_of_day, route.route_id, route.name, SUM(fare) AS total_fare FROM trip JOIN route ON trip.route_id = route.route_id GROUP BY hour_of_day, route.route_id;
How many cruelty-free certifications does each brand have, ordered by the number of certifications?
CREATE TABLE brands (brand_id INT,brand VARCHAR(255),cruelty_free BOOLEAN); INSERT INTO brands (brand_id,brand,cruelty_free) VALUES (1,'Loreal',FALSE),(2,'The Body Shop',TRUE),(3,'Estee Lauder',FALSE),(4,'Urban Decay',TRUE);
SELECT brand, SUM(cruelty_free) as certifications FROM brands GROUP BY brand ORDER BY certifications DESC;
How many underwater volcanoes are there in the Atlantic Ocean as of 2020?
CREATE TABLE volcanoes (id INT,ocean VARCHAR(50),year INT,num_volcanoes INT); INSERT INTO volcanoes (id,ocean,year,num_volcanoes) VALUES (1,'Atlantic Ocean',2018,120),(2,'Atlantic Ocean',2019,125),(3,'Atlantic Ocean',2020,NULL);
SELECT num_volcanoes FROM volcanoes WHERE ocean = 'Atlantic Ocean' AND year = 2020;
What was the percentage of attendees under 18 years old at the 'Youth Arts Showcase' in Chicago?
CREATE TABLE age_distribution (event_name VARCHAR(50),city VARCHAR(50),age_group VARCHAR(10),attendees INT); INSERT INTO age_distribution (event_name,city,age_group,attendees) VALUES ('Youth Arts Showcase','Chicago','Under 18',200);
SELECT (attendees * 100.0 / (SELECT SUM(attendees) FROM age_distribution WHERE event_name = 'Youth Arts Showcase' AND city = 'Chicago')) AS percentage FROM age_distribution WHERE event_name = 'Youth Arts Showcase' AND city = 'Chicago' AND age_group = 'Under 18';
What is the average flight safety record per airline in the Asia-Pacific region?
CREATE TABLE Flight_Safety (ID INT,Airline VARCHAR(50),Region VARCHAR(50),Safety_Record INT); INSERT INTO Flight_Safety (ID,Airline,Region,Safety_Record) VALUES (1,'Air China','Asia-Pacific',98),(2,'Singapore Airlines','Asia-Pacific',99),(3,'Qantas','Asia-Pacific',99.5),(4,'Japan Airlines','Asia-Pacific',98.5),(5,'Garuda Indonesia','Asia-Pacific',97);
SELECT Region, AVG(Safety_Record) FROM Flight_Safety WHERE Region = 'Asia-Pacific' GROUP BY Region;
What is the average energy efficiency rating of buildings in each state?
CREATE TABLE Buildings (building_id INT,state VARCHAR(20),energy_efficiency_rating FLOAT); INSERT INTO Buildings (building_id,state,energy_efficiency_rating) VALUES (1,'California',85.2),(2,'Oregon',82.7),(3,'California',87.9),(4,'Oregon',89.1);
SELECT state, AVG(energy_efficiency_rating) FROM Buildings GROUP BY state;
How many football games had more than 10000 attendees?
CREATE TABLE attendance (id INT,game_id INT,attendees INT); INSERT INTO attendance (id,game_id,attendees) VALUES (1,1,12000); INSERT INTO attendance (id,game_id,attendees) VALUES (2,2,9000);
SELECT COUNT(*) FROM attendance WHERE attendees > 10000 AND game_id IN (SELECT id FROM games WHERE sport = 'Football');
Delete vessels with no safety inspection records from the vessel_details table
CREATE TABLE vessel_details (vessel_id INT,vessel_name VARCHAR(50)); CREATE TABLE safety_records (vessel_id INT,inspection_status VARCHAR(10));
DELETE FROM vessel_details WHERE vessel_id NOT IN (SELECT vessel_id FROM safety_records);
Find the minimum depth of the Atlantic Ocean
CREATE TABLE ocean_floors (ocean TEXT,trench_name TEXT,minimum_depth INTEGER); INSERT INTO ocean_floors (ocean,trench_name,minimum_depth) VALUES ('Pacific Ocean','Mariana Trench',10994),('Atlantic Ocean','Puerto Rico Trench',8380),('Indian Ocean','Java Trench',7290);
SELECT MIN(minimum_depth) FROM ocean_floors WHERE ocean = 'Atlantic Ocean';
What is the total runtime of movies and TV shows produced in Canada, and how many unique directors are there?
CREATE TABLE media_content (id INT,title VARCHAR(255),release_year INT,runtime INT,genre VARCHAR(255),format VARCHAR(50),country VARCHAR(255),director VARCHAR(255));
SELECT country, SUM(runtime) AS total_runtime, COUNT(DISTINCT director) AS unique_directors FROM media_content WHERE country = 'Canada' GROUP BY country;
What is the total donation amount per organization in the 'philanthropy.organizations' table?
CREATE TABLE philanthropy.organizations (organization_id INT,organization_name TEXT,total_donations DECIMAL);
SELECT organization_id, SUM(d.amount) FROM philanthropy.donations d JOIN philanthropy.organizations o ON d.organization_id = o.organization_id GROUP BY organization_id;