instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
What is the maximum data usage for broadband subscribers in a specific region?
CREATE TABLE broadband_subscribers (subscriber_id INT,region VARCHAR(50),data_usage INT);
SELECT region, MAX(data_usage) FROM broadband_subscribers GROUP BY region;
How many donors are there in the 'donors' table with a donation amount greater than $500?
CREATE TABLE donors (id INT,name TEXT,age INT,donation FLOAT); INSERT INTO donors (id,name,age,donation) VALUES (1,'John Doe',35,500.00); INSERT INTO donors (id,name,age,donation) VALUES (2,'Jane Smith',45,750.00); INSERT INTO donors (id,name,age,donation) VALUES (3,'Bob Johnson',25,600.00);
SELECT COUNT(*) FROM donors WHERE donation > 500.00;
List all players who have not played any games yet
CREATE TABLE Players (PlayerID INT,PlayerName VARCHAR(50),GameType VARCHAR(50)); INSERT INTO Players (PlayerID,PlayerName,GameType) VALUES (1,'John Doe',NULL); INSERT INTO Players (PlayerID,PlayerName,GameType) VALUES (2,'Jane Smith','RPG');
SELECT PlayerName FROM Players WHERE GameType IS NULL;
What is the total revenue for each game in the "Gaming" category?
CREATE TABLE Games (GameID int,GameName varchar(50),Category varchar(50),Revenue decimal(10,2));
SELECT Category, SUM(Revenue) OVER(PARTITION BY Category) as TotalRevenue FROM Games;
What is the average age of players who play games on mobile devices in the USA?
CREATE TABLE Players (PlayerID INT,Age INT,Gender VARCHAR(10),Country VARCHAR(20),Mobile BOOLEAN); INSERT INTO Players (PlayerID,Age,Gender,Country,Mobile) VALUES (1,25,'Male','USA',TRUE),(2,30,'Female','Canada',FALSE),(3,35,'Female','Mexico',TRUE);
SELECT AVG(Age) FROM Players WHERE Country = 'USA' AND Mobile = TRUE;
What is the total number of players who have adopted VR technology, grouped by their countries?
CREATE TABLE players (id INT,name VARCHAR(20),country VARCHAR(20),has_vr_tech BOOLEAN); INSERT INTO players (id,name,country,has_vr_tech) VALUES (1,'Ibrahim','Egypt',true),(2,'Fatima','Saudi Arabia',false),(3,'Pablo','Mexico',true),(4,'Maria','Brazil',true),(5,'Xiuying','China',false);
SELECT players.country, COUNT(*) AS num_players FROM players WHERE players.has_vr_tech = true GROUP BY players.country;
Calculate the total irrigated area (in hectares) for each crop variety
CREATE TABLE crop (id INT,name VARCHAR(50),irrigated_area FLOAT); INSERT INTO crop (id,name,irrigated_area) VALUES (1,'Corn',250.5),(2,'Soybean',300.2),(3,'Cotton',180.9);
SELECT name, SUM(irrigated_area) as total_irrigated_area FROM crop GROUP BY name;
What is the maximum Yttrium production in 2018?
CREATE TABLE yttrium_production (country VARCHAR(50),year INT,quantity INT); INSERT INTO yttrium_production (country,year,quantity) VALUES ('Russia',2018,2500),('China',2018,2200),('United States',2018,1800),('Australia',2018,1500),('Canada',2018,1200);
SELECT MAX(quantity) FROM yttrium_production WHERE year = 2018;
What is the minimum co-ownership percentage for properties with more than one co-owner in the co_ownership_agreements table?
CREATE TABLE co_ownership_agreements (agreement_id INT,property_id INT,co_owner_id INT,co_ownership_percentage FLOAT); INSERT INTO co_ownership_agreements (agreement_id,property_id,co_owner_id,co_ownership_percentage) VALUES (1,101,1,50.0),(2,101,2,50.0),(3,102,1,75.0),(4,102,2,25.0);
SELECT MIN(co_ownership_percentage) FROM co_ownership_agreements WHERE property_id IN (SELECT property_id FROM co_ownership_agreements GROUP BY property_id HAVING COUNT(DISTINCT co_owner_id) > 1);
What is the minimum energy efficiency rating for commercial buildings in the city of Chicago?
CREATE TABLE commercial_buildings (id INT,building_id VARCHAR(255),city VARCHAR(255),energy_efficiency_rating INT);
SELECT MIN(energy_efficiency_rating) FROM commercial_buildings WHERE city = 'Chicago';
Update the revenue date for a restaurant
CREATE TABLE revenue (restaurant_id INT,revenue_date DATE,total_revenue DECIMAL(10,2));
UPDATE revenue SET revenue_date = '2022-04-15' WHERE restaurant_id = 678;
Find the total sales of vendors located in the Midwest region.
CREATE TABLE vendors (vendor_id INT,vendor_name TEXT,region TEXT); INSERT INTO vendors (vendor_id,vendor_name,region) VALUES (1,'Green Vendors','Midwest'); CREATE TABLE sales (sale_id INT,sale_date DATE,vendor_id INT,amount DECIMAL(5,2)); INSERT INTO sales (sale_id,sale_date,vendor_id,amount) VALUES (1,'2022-01-01',1,12000);
SELECT SUM(amount) FROM sales JOIN vendors ON sales.vendor_id = vendors.vendor_id WHERE vendors.region = 'Midwest';
Which retailers in Asia do not carry any vegan products?
CREATE TABLE retailers (id INT,name TEXT,country TEXT); INSERT INTO retailers (id,name,country) VALUES (1,'Retailer A','Asia'),(2,'Retailer B','Asia'),(3,'Retailer C','North America'),(4,'Retailer D','Asia'); CREATE TABLE products (id INT,name TEXT,is_vegan BOOLEAN); INSERT INTO products (id,name,is_vegan) VALUES (1,'Product X',true),(2,'Product Y',false),(3,'Product Z',true),(4,'Product W',false); CREATE TABLE retailer_products (retailer_id INT,product TEXT,quantity INT); INSERT INTO retailer_products (retailer_id,product,quantity) VALUES (1,'Product X',100),(1,'Product Z',50),(2,'Product Y',150),(3,'Product W',80),(4,'Product X',120),(4,'Product Z',70);
SELECT retailers.name FROM retailers LEFT JOIN retailer_products ON retailers.id = retailer_products.retailer_id LEFT JOIN products ON retailer_products.product = products.name WHERE products.is_vegan IS NULL AND retailers.country = 'Asia';
Add a new team with the following details to the 'teams' table: 'Team New York', 'Eastern Conference', 'NBA'
CREATE TABLE teams (team_id INT PRIMARY KEY,team_name VARCHAR(50),conference VARCHAR(50),league VARCHAR(50));
INSERT INTO teams (team_name, conference, league) VALUES ('Team New York', 'Eastern Conference', 'NBA');
What is the minimum number of days taken to resolve a security incident for each country?
CREATE TABLE country_incident_resolution (country VARCHAR(255),resolution_days INT); INSERT INTO country_incident_resolution (country,resolution_days) VALUES ('Brazil',25),('Russia',30),('India',40),('China',50),('South Africa',10);
SELECT country, MIN(resolution_days) as min_resolution_days FROM country_incident_resolution GROUP BY country;
Identify the garment types that were sold in both the 'GarmentSales' table and the 'GarmentProduction' table.
CREATE TABLE GarmentProduction (garment_type VARCHAR(50)); INSERT INTO GarmentProduction (garment_type) VALUES ('T-Shirt'),('Jeans'),('Hoodie'); CREATE TABLE GarmentSales (garment_type VARCHAR(50)); INSERT INTO GarmentSales (garment_type) VALUES ('T-Shirt'),('Jackets');
SELECT garment_type FROM GarmentProduction WHERE garment_type IN (SELECT garment_type FROM GarmentSales);
What was the total quantity of garments produced in each country by garment type in 2021?
CREATE TABLE garment_production_2021 AS SELECT * FROM garment_production WHERE production_date BETWEEN '2021-01-01' AND '2021-12-31'; ALTER TABLE garment_production_2021 ADD COLUMN country_region VARCHAR(50); UPDATE garment_production_2021 SET country_region = CASE WHEN country = 'Brazil' THEN 'South America' WHEN country = 'India' THEN 'Asia' WHEN country = 'USA' THEN 'North America' WHEN country = 'Italy' THEN 'Europe' ELSE country_region END;
SELECT country_region, garment_type, SUM(quantity) FROM garment_production_2021 GROUP BY country_region, garment_type;
Delete all records of unions with less than 3000 workers in New York.
CREATE TABLE unions (id INT,state VARCHAR(2),workers INT,issue VARCHAR(14)); INSERT INTO unions (id,state,workers,issue) VALUES (1,'NY',4000,'workplace_safety'),(2,'NY',2000,'labor_rights');
DELETE FROM unions WHERE state = 'NY' AND workers < 3000;
List the collective number of workplace safety incidents for unions headquartered in North America.
CREATE TABLE UnionSafety (UnionName VARCHAR(50),HeadquarterCountry VARCHAR(50),Incidents INT); INSERT INTO UnionSafety (UnionName,HeadquarterCountry,Incidents) VALUES ('UnionK','USA',120),('UnionL','Canada',80),('UnionM','Mexico',90);
SELECT SUM(Incidents) FROM UnionSafety WHERE HeadquarterCountry IN ('USA', 'Canada', 'Mexico')
Which countries have the least number of electric vehicle charging stations in the 'charging_stations' table?
CREATE TABLE charging_stations (id INT PRIMARY KEY,country VARCHAR(50),num_stations INT);
SELECT country, COUNT(*) as num_stations FROM charging_stations GROUP BY country ORDER BY num_stations ASC LIMIT 5;
What is the maximum speed of vessels with a safety record below average in the Pacific Ocean?
CREATE TABLE vessels (id INT,name TEXT,type TEXT,speed FLOAT,safety_score FLOAT);CREATE TABLE regions (id INT,name TEXT); INSERT INTO vessels (id,name,type,speed,safety_score) VALUES (1,'VesselC','Tanker',12.3,7.5); INSERT INTO regions (id,name) VALUES (1,'Pacific');
SELECT MAX(v.speed) FROM vessels v JOIN regions r ON v.speed < (SELECT AVG(speed) FROM vessels WHERE regions.name = 'Pacific') AND v.region_id = r.id AND r.name = 'Pacific';
Compare the landfill capacity of 'Ontario' and 'Quebec'
CREATE TABLE landfill_capacity (id INT,region VARCHAR(20),capacity INT); INSERT INTO landfill_capacity (id,region,capacity) VALUES (1,'Ontario',400000),(2,'Quebec',500000);
SELECT region, capacity FROM landfill_capacity WHERE region IN ('Ontario', 'Quebec');
What is the average recycling rate in percentage for the year 2019 for countries in Europe with a population greater than 10 million?
CREATE TABLE recycling_rates(country VARCHAR(20),year INT,population INT,recycling_rate FLOAT); INSERT INTO recycling_rates(country,year,population,recycling_rate) VALUES ('Germany',2019,83,68.5),('France',2019,67,58.7),('United Kingdom',2019,66,45.2),('Italy',2019,60,54.3),('Spain',2019,47,42.1),('Poland',2019,38,34.5),('Romania',2019,19,21.6),('Netherlands',2019,17,72.8),('Belgium',2019,11,66.4),('Greece',2019,11,30.5);
SELECT AVG(recycling_rate) FROM recycling_rates WHERE year = 2019 AND population > 10000000 GROUP BY year HAVING COUNT(country) > 3;
What is the landfill capacity growth rate for Landfill A from 2018 to 2020?
CREATE TABLE landfill_capacity (id INT,name VARCHAR(50),year INT,capacity INT); INSERT INTO landfill_capacity (id,name,year,capacity) VALUES (1,'Landfill A',2018,5000000),(2,'Landfill A',2019,5200000),(3,'Landfill A',2020,5500000),(4,'Landfill B',2018,4000000),(5,'Landfill B',2019,4200000),(6,'Landfill B',2020,4500000);
SELECT ((capacity - (SELECT capacity FROM landfill_capacity l2 WHERE l2.name = 'Landfill A' AND l2.year = 2018)) / (SELECT capacity FROM landfill_capacity l3 WHERE l3.name = 'Landfill A' AND l3.year = 2018)) * 100 FROM landfill_capacity WHERE name = 'Landfill A' AND year = 2020;
What is the recycling rate for each material type in 2021?
CREATE TABLE recycling_rates (material VARCHAR(255),recycling_rate DECIMAL(5,4),year INT); INSERT INTO recycling_rates (material,recycling_rate,year) VALUES ('Plastic',0.35,2021),('Glass',0.65,2021),('Paper',0.75,2021);
SELECT material, recycling_rate FROM recycling_rates WHERE year = 2021;
List the unique 'Workout' types offered at each studio, excluding 'Boxing' workouts.
CREATE TABLE Studios (studio VARCHAR(50)); INSERT INTO Studios (studio) VALUES ('Boston'),('Seattle'),('New York'); CREATE TABLE Workouts (studio VARCHAR(50),workout VARCHAR(50)); INSERT INTO Workouts (studio,workout) VALUES ('Boston','Yoga'),('Boston','Pilates'),('Seattle','Cycling'),('Seattle','Yoga'),('New York','Cycling'),('New York','Boxing');
SELECT DISTINCT studio, workout FROM Workouts WHERE workout != 'Boxing';
What is the minimum water pH by region and season?
CREATE TABLE Region (id INT PRIMARY KEY,name VARCHAR(50)); CREATE TABLE WaterQuality (region_id INT,date DATE,pH DECIMAL(3,2),FOREIGN KEY (region_id) REFERENCES Region(id));
SELECT Region.name, DATE_FORMAT(WaterQuality.date, '%Y-%m') AS month, MIN(WaterQuality.pH) FROM Region INNER JOIN WaterQuality ON Region.id = WaterQuality.region_id GROUP BY Region.name, MONTH(WaterQuality.date), YEAR(WaterQuality.date);
What are the unique types of events funded by the "Government" funding source?
CREATE TABLE Events (event_id INT,event_type VARCHAR(20),funding_source VARCHAR(20)); INSERT INTO Events (event_id,event_type,funding_source) VALUES (1,'Concert','Government'),(2,'Theater','Private'),(3,'Exhibition','Corporate');
SELECT DISTINCT event_type FROM Events WHERE funding_source = 'Government';
How many construction workers were employed in each state for non-green building projects in 2020?
CREATE TABLE employment_non_green_data (state VARCHAR(255),employees INT,year INT); INSERT INTO employment_non_green_data (state,employees,year) VALUES ('California',40000,2020),('Texas',35000,2020),('New York',45000,2020);
SELECT state, employees FROM employment_non_green_data WHERE year = 2020;
List all suppliers and the number of strains they provide, including those with no strains.
CREATE TABLE Suppliers (id INT,name TEXT); INSERT INTO Suppliers (id,name) VALUES (1,'Supplier A'),(2,'Supplier B'),(3,'Supplier C'); CREATE TABLE Supplies (supplier_id INT,strain_id INT); INSERT INTO Supplies (supplier_id,strain_id) VALUES (1,1),(1,2),(2,3),(2,4),(3,5);
SELECT Suppliers.name, COALESCE(COUNT(Supplies.supplier_id), 0) as strain_count FROM Suppliers LEFT JOIN Supplies ON Suppliers.id = Supplies.supplier_id GROUP BY Suppliers.name;
What are the total sales for each product category in the state of Oregon, ordered from highest to lowest total sales?
CREATE TABLE Categories (CategoryID int,CategoryName varchar(255),CategoryDescription varchar(255)); INSERT INTO Categories (CategoryID,CategoryName,CategoryDescription) VALUES (1,'Flower','Cannabis flower products'); INSERT INTO Categories (CategoryID,CategoryName,CategoryDescription) VALUES (2,'Concentrates','Cannabis concentrate products'); CREATE TABLE Sales2 (SaleID2 int,CategoryID int,SalesAmount decimal(10,2)); INSERT INTO Sales2 (SaleID2,CategoryID,SalesAmount) VALUES (1,1,6000); INSERT INTO Sales2 (SaleID2,CategoryID,SalesAmount) VALUES (2,2,4000);
SELECT Categories.CategoryName, SUM(Sales2.SalesAmount) AS TotalSales FROM Categories INNER JOIN Sales2 ON Categories.CategoryID = Sales2.CategoryID WHERE Categories.State = 'Oregon' GROUP BY Categories.CategoryName ORDER BY TotalSales DESC;
How many cases were handled by each attorney in the technology industry?
CREATE TABLE attorneys (attorney_id INT,cases_handled INT); INSERT INTO attorneys (attorney_id,cases_handled) VALUES (1,20),(2,15),(3,30); CREATE TABLE clients (client_id INT,attorney_id INT,industry VARCHAR(255)); INSERT INTO clients (client_id,attorney_id,industry) VALUES (1,1,'technology'),(2,1,'technology'),(3,2,'finance'),(4,3,'technology'),(5,3,'technology');
SELECT attorneys.attorney_id, SUM(clients.cases_handled) FROM attorneys INNER JOIN clients ON attorneys.attorney_id = clients.attorney_id WHERE clients.industry = 'technology' GROUP BY attorneys.attorney_id;
Identify the climate mitigation initiatives in Europe that received the highest and lowest funding from public sources.
CREATE TABLE climate_mitigation_europe (initiative VARCHAR(50),funding DECIMAL(10,2),funding_source VARCHAR(50)); INSERT INTO climate_mitigation_europe (initiative,funding,funding_source) VALUES ('Carbon Capture and Storage',5000000,'Public'),('Green Building Design',1000000,'Public'),('Smart Grid Development',2000000,'Public');
SELECT initiative, MAX(funding) AS max_funding, MIN(funding) AS min_funding FROM climate_mitigation_europe WHERE funding_source = 'Public' AND region = 'Europe' GROUP BY initiative;
What is the total number of projects in the 'climate_mitigation' table?
CREATE TABLE climate_mitigation (project_id INT,project_name VARCHAR(255),location VARCHAR(255),start_date DATE,end_date DATE);
SELECT COUNT(*) FROM climate_mitigation;
How many infectious disease outbreaks were reported in the state of New York in the year 2021?
CREATE TABLE public.outbreaks (id SERIAL PRIMARY KEY,state TEXT,year INTEGER,disease TEXT); INSERT INTO public.outbreaks (state,year,disease) VALUES ('New York',2021,'COVID-19'),('California',2021,'Monkeypox'),('Florida',2021,'Dengue');
SELECT COUNT(*) FROM public.outbreaks WHERE state = 'New York' AND year = 2021;
What is the total number of hospital beds in private hospitals located in New York?
CREATE TABLE hospitals (name VARCHAR(255),city VARCHAR(255),num_beds INT,type VARCHAR(255)); INSERT INTO hospitals (name,city,num_beds,type) VALUES ('General Hospital','New York',500,'Public'); INSERT INTO hospitals (name,city,num_beds,type) VALUES ('Mount Sinai Hospital','New York',1200,'Private');
SELECT SUM(num_beds) FROM hospitals WHERE city = 'New York' AND type = 'Private';
Which state started their policies the earliest?
CREATE TABLE policies (id INT,state TEXT,policy_name TEXT,start_date DATE,end_date DATE,description TEXT); INSERT INTO policies (id,state,policy_name,start_date,end_date,description) VALUES (1,'NY','Mask mandate','2020-04-15','2021-06-01','Masks required in public'); INSERT INTO policies (id,state,policy_name,start_date,end_date,description) VALUES (2,'CA','Social distancing','2020-03-20','2021-05-31','Maintain 6 feet distance');
SELECT state, MIN(start_date) as earliest_start_date FROM policies GROUP BY state ORDER BY earliest_start_date;
Which industries have the least number of companies founded in a given year?
CREATE TABLE Company (id INT,name VARCHAR(50),industry VARCHAR(50),founding_year INT); INSERT INTO Company (id,name,industry,founding_year) VALUES (1,'LegalTech','Legal',2013); INSERT INTO Company (id,name,industry,founding_year) VALUES (2,'MobiHealth','Healthcare',2014); INSERT INTO Company (id,name,industry,founding_year) VALUES (3,'NewsToday','News',2015); INSERT INTO Company (id,name,industry,founding_year) VALUES (4,'PetCare','Pets',2013);
SELECT industry, founding_year, COUNT(*) as company_count FROM Company GROUP BY industry, founding_year ORDER BY company_count ASC;
What is the maximum number of funding rounds for companies founded by women in the healthtech sector?
CREATE TABLE company (id INT,name TEXT,industry TEXT,founding_date DATE,founder_gender TEXT); CREATE TABLE investment_rounds (id INT,company_id INT,funding_round INT,funding_amount INT);
SELECT MAX(investment_rounds.funding_round) FROM company JOIN investment_rounds ON company.id = investment_rounds.company_id WHERE company.founder_gender = 'Female' AND company.industry = 'Healthtech';
Delete smart contracts associated with digital asset 'CryptoPet' from the 'SmartContracts' table
CREATE TABLE SmartContracts (hash VARCHAR(128),name VARCHAR(64),digital_asset VARCHAR(64),creator VARCHAR(128),timestamp TIMESTAMP); CREATE TABLE DigitalAssets (name VARCHAR(64),symbol VARCHAR(8),total_supply DECIMAL(20,8),platform VARCHAR(64),project_url VARCHAR(128));
DELETE FROM SmartContracts WHERE digital_asset = 'CryptoPet';
Find the difference in the number of trees between the tree species with the highest and lowest carbon sequestration rates in the private_lands schema.
CREATE TABLE private_lands.carbon_sequestration (species VARCHAR(255),sequestration_rate DECIMAL(5,2));
SELECT species_high.species AS high_species, species_low.species AS low_species, species_high.sequestration_rate - species_low.sequestration_rate AS difference FROM (SELECT species, MAX(sequestration_rate) AS sequestration_rate FROM private_lands.carbon_sequestration GROUP BY species) AS species_high FULL OUTER JOIN (SELECT species, MIN(sequestration_rate) AS sequestration_rate FROM private_lands.carbon_sequestration GROUP BY species) AS species_low ON species_high.sequestration_rate = species_low.sequestration_rate;
Find all products that are not cruelty-free
Products (product_id,name,rating,cruelty_free)
SELECT * FROM Products WHERE cruelty_free = 'no'
Which brands have certifications related to cruelty-free, vegan, or organic products?
CREATE TABLE brands (brand_name VARCHAR(50),is_cruelty_free BOOLEAN,is_vegan BOOLEAN,is_organic BOOLEAN); INSERT INTO brands (brand_name,is_cruelty_free,is_vegan,is_organic) VALUES ('Lush',TRUE,TRUE,FALSE),('The Body Shop',TRUE,FALSE,FALSE),('Estée Lauder',FALSE,FALSE,FALSE),('Urban Decay',TRUE,TRUE,FALSE),('Maybelline',FALSE,FALSE,FALSE),('Kat Von D',TRUE,TRUE,FALSE),('Tarte',TRUE,TRUE,TRUE);
SELECT brand_name, 'Cruelty-free' as certification FROM brands WHERE is_cruelty_free = TRUE UNION SELECT brand_name, 'Vegan' as certification FROM brands WHERE is_vegan = TRUE UNION SELECT brand_name, 'Organic' as certification FROM brands WHERE is_organic = TRUE;
Show the number of organic skincare products sold per month, displayed as pivoted data.
CREATE TABLE product_labels_v4 (brand VARCHAR(20),product_name VARCHAR(20),product_subcategory VARCHAR(20),product_label VARCHAR(20),sale_date DATE,sale_count INT); INSERT INTO product_labels_v4 VALUES ('Skincare BrandC','Cleanser','Skincare','Organic','2021-01-01',20),('Skincare BrandC','Toner','Skincare','Organic','2021-01-15',30),('Skincare BrandD','Serum','Skincare','Organic','2021-04-01',40),('Skincare BrandD','Moisturizer','Skincare','Organic','2021-07-01',50);
SELECT EXTRACT(MONTH FROM sale_date) AS month, brand, SUM(CASE WHEN product_subcategory = 'Cleanser' THEN sale_count ELSE 0 END) AS Cleanser, SUM(CASE WHEN product_subcategory = 'Toner' THEN sale_count ELSE 0 END) AS Toner, SUM(CASE WHEN product_subcategory = 'Serum' THEN sale_count ELSE 0 END) AS Serum, SUM(CASE WHEN product_subcategory = 'Moisturizer' THEN sale_count ELSE 0 END) AS Moisturizer FROM product_labels_v4 WHERE product_subcategory IN ('Cleanser', 'Toner', 'Serum', 'Moisturizer') AND product_label = 'Organic' GROUP BY EXTRACT(MONTH FROM sale_date), brand;
What are the top 3 beauty brands with the most sustainable packaging in the natural segment?
CREATE TABLE packaging_sustainability (product_id INT,brand_id INT,sustainability_score INT,is_natural BOOLEAN); CREATE TABLE brands (brand_id INT,brand_name VARCHAR(255)); INSERT INTO packaging_sustainability (product_id,brand_id,sustainability_score,is_natural) VALUES (1,1,90,true),(2,2,80,false),(3,3,85,true); INSERT INTO brands (brand_id,brand_name) VALUES (1,'Green Beauty'),(2,'Luxury Brands'),(3,'Natural Beauty');
SELECT brand_name, AVG(sustainability_score) AS avg_sustainability_score FROM packaging_sustainability INNER JOIN brands ON packaging_sustainability.brand_id = brands.brand_id WHERE is_natural = true GROUP BY brand_name ORDER BY avg_sustainability_score DESC LIMIT 3;
What is the average response time for fire calls in 2021 and 2022?
CREATE TABLE fire_calls (call_id INT,call_date DATE,response_time INT); INSERT INTO fire_calls (call_id,call_date,response_time) VALUES (1,'2021-01-01',15),(2,'2022-02-03',12);
SELECT AVG(response_time) FROM fire_calls WHERE call_date BETWEEN '2021-01-01' AND '2022-12-31';
What is the total number of crimes reported in each city?
CREATE TABLE CrimeStatistics (id INT,city VARCHAR(255),crime_type VARCHAR(50),reported_date DATE); CREATE VIEW CityCrimeCount AS SELECT city,COUNT(*) as total FROM CrimeStatistics GROUP BY city;
SELECT city, SUM(total) FROM CityCrimeCount GROUP BY city;
How many times has the 'Las Meninas' painting been displayed in the last 2 years?
CREATE TABLE artworks (id INT,name TEXT,museum_id INT,display_date DATE); INSERT INTO artworks (id,name,museum_id,display_date) VALUES (1,'Las Meninas',1,'2020-01-01'),(2,'Mona Lisa',1,'2020-02-01'),(3,'Guernica',2,'2022-03-15'),(4,'Las Meninas',1,'2022-04-01'),(5,'The Persistence of Memory',3,'2022-05-01');
SELECT name, COUNT(*) AS display_count FROM artworks WHERE name = 'Las Meninas' AND display_date >= DATE_SUB(CURRENT_DATE, INTERVAL 2 YEAR) GROUP BY name;
What is the total number of veteran and non-veteran job applicants for each job category?
CREATE TABLE JobApplicants (ApplicantID int,JobCategory varchar(50),JobLocation varchar(50),ApplicantType varchar(50)); INSERT INTO JobApplicants (ApplicantID,JobCategory,JobLocation,ApplicantType) VALUES (1,'Software Engineer','California','Veteran'),(2,'Project Manager','California','Non-Veteran'),(3,'Data Analyst','California','Veteran'),(4,'Software Engineer','California','Non-Veteran'),(5,'Project Manager','California','Veteran');
SELECT JobCategory, COUNT(*) FILTER (WHERE ApplicantType = 'Veteran') as VeteranApplicants, COUNT(*) FILTER (WHERE ApplicantType = 'Non-Veteran') as NonVeteranApplicants FROM JobApplicants GROUP BY JobCategory;
How many customers have opened an account in the past month?
CREATE TABLE accounts (account_id INT,customer_id INT,account_type TEXT,open_date DATE); INSERT INTO accounts VALUES (1,1,'Checking','2022-02-03'); INSERT INTO accounts VALUES (2,2,'Savings','2022-02-12'); INSERT INTO accounts VALUES (3,4,'Checking','2022-01-20');
SELECT COUNT(*) as new_customers FROM accounts WHERE open_date >= DATEADD(month, -1, GETDATE());
Update fraud alerts for transactions over $500
CREATE TABLE transactions (id INT PRIMARY KEY,customer_id INT,amount DECIMAL(10,2),transaction_date DATE); CREATE TABLE fraud_alerts (id INT PRIMARY KEY,transaction_id INT,alert_reason VARCHAR(50)); INSERT INTO transactions (id,customer_id,amount,transaction_date) VALUES (1,1,500.00,'2022-01-01'); INSERT INTO transactions (id,customer_id,amount,transaction_date) VALUES (2,2,750.00,'2022-01-02');
UPDATE transactions t SET t.amount = t.amount * 0.95 WHERE t.amount > 500; INSERT INTO fraud_alerts (id, transaction_id, alert_reason) SELECT t.id, t.id, 'High amount' FROM transactions t WHERE t.amount > 500;
What is the maximum credit limit for customers in Florida?
CREATE TABLE customer (customer_id INT,name VARCHAR(255),state VARCHAR(255),credit_limit DECIMAL(10,2)); INSERT INTO customer (customer_id,name,state,credit_limit) VALUES (1,'John Doe','Florida',12000.00),(2,'Jane Smith','Florida',18000.00);
SELECT MAX(credit_limit) FROM customer WHERE state = 'Florida';
Count the number of rural healthcare facilities in Mexico and Brazil that have a pharmacy on-site.
CREATE TABLE healthcare_facilities (facility_id INT,country VARCHAR(20),has_pharmacy BOOLEAN); INSERT INTO healthcare_facilities (facility_id,country,has_pharmacy) VALUES (1,'Mexico',TRUE),(2,'Brazil',FALSE);
SELECT COUNT(*) FROM healthcare_facilities WHERE country IN ('Mexico', 'Brazil') AND has_pharmacy = TRUE;
Find the names and states of rural hospitals that have more than 50 beds.
CREATE TABLE rural_hospitals (name TEXT,state TEXT,num_beds INTEGER); INSERT INTO rural_hospitals (name,state,num_beds) VALUES ('Hospital A','CA',50),('Hospital B','CA',75),('Hospital C','TX',40),('Hospital D','NY',60);
SELECT name, state FROM rural_hospitals WHERE num_beds > 50;
Show all intelligence operations in the 'Africa' schema.
CREATE SCHEMA Africa; CREATE TABLE IntelligenceOperations (id INT,name VARCHAR(255),location VARCHAR(255),date DATE); INSERT INTO IntelligenceOperations (id,name,location,date) VALUES (1,'Operation Flintlock','Niger','2023-02-01'); INSERT INTO IntelligenceOperations (id,name,location,date) VALUES (2,'Operation Juniper Shield','Somalia','2022-10-15');
SELECT * FROM Africa.IntelligenceOperations;
Find the top 3 countries with the highest average donation amount in 2022?
CREATE TABLE Donations (id INT,user_id INT,country VARCHAR(50),amount DECIMAL(10,2),donation_date DATE); INSERT INTO Donations (id,user_id,country,amount,donation_date) VALUES (1,1001,'USA',50.00,'2021-01-05'); INSERT INTO Donations (id,user_id,country,amount,donation_date) VALUES (2,1002,'Canada',75.00,'2021-01-10'); INSERT INTO Donations (id,user_id,country,amount,donation_date) VALUES (3,1003,'Mexico',100.00,'2022-03-15');
SELECT country, AVG(amount) as avg_donation FROM Donations WHERE donation_date >= '2022-01-01' AND donation_date < '2023-01-01' GROUP BY country ORDER BY avg_donation DESC LIMIT 3;
How many students in the "Lifelong Learning" program have submitted an assignment in the past week?
CREATE TABLE lifelong_learning_students (id INT,name VARCHAR(50),program VARCHAR(50),last_assignment DATE);
SELECT COUNT(*) FROM lifelong_learning_students WHERE last_assignment >= DATE_SUB(CURDATE(), INTERVAL 1 WEEK);
Show all students with 'mental_health_concerns' in the 'students' table
CREATE TABLE students (student_id INT,name VARCHAR(50),mental_health_concerns VARCHAR(20));
SELECT * FROM students WHERE mental_health_concerns IS NOT NULL;
What is the number of professional development workshops attended by teachers in each district, grouped by subject area?
CREATE TABLE districts (district_id INT,district_name TEXT); INSERT INTO districts (district_id,district_name) VALUES (1,'Urban'),(2,'Suburban'),(3,'Rural'); CREATE TABLE teachers (teacher_id INT,teacher_name TEXT,district_id INT); INSERT INTO teachers (teacher_id,teacher_name,district_id) VALUES (1,'Ms. Doe',1),(2,'Mr. Smith',2),(3,'Ms. Johnson',3),(4,'Mr. Williams',1); CREATE TABLE professional_development (program_id INT,program_name TEXT,program_subject TEXT,teacher_id INT); INSERT INTO professional_development (program_id,program_name,program_subject,teacher_id) VALUES (1,'Python for Educators','Computer Science',1),(2,'Data Science for Teachers','Data Science',2),(3,'Inclusive Teaching','Diversity & Inclusion',3),(4,'Open Pedagogy','Pedagogy',4),(5,'Diversity and Inclusion','Diversity & Inclusion',1),(6,'Curriculum Design','Curriculum',2),(7,'Culturally Responsive Teaching','Diversity & Inclusion',3),(8,'Project Based Learning','Pedagogy',4);
SELECT d.district_name, p.program_subject, COUNT(pd.program_id) as num_programs FROM districts d JOIN teachers t ON d.district_id = t.district_id JOIN professional_development pd ON t.teacher_id = pd.teacher_id JOIN (SELECT program_subject FROM professional_development GROUP BY program_subject) p ON pd.program_subject = p.program_subject GROUP BY d.district_name, p.program_subject;
Insert new records for a 'grid' table: China, 1000, AC
CREATE TABLE grid (country VARCHAR(20),capacity INT,transmission_type VARCHAR(20));
INSERT INTO grid (country, capacity, transmission_type) VALUES ('China', 1000, 'AC');
List all energy efficiency projects in California and their total budgets.
CREATE TABLE energy_efficiency_projects (project_name VARCHAR(50),state VARCHAR(20),budget DECIMAL(10,2)); INSERT INTO energy_efficiency_projects (project_name,state,budget) VALUES ('Project A','California',50000.00),('Project B','California',75000.00),('Project C','New York',60000.00);
SELECT eep.project_name, SUM(eep.budget) FROM energy_efficiency_projects eep WHERE eep.state = 'California' GROUP BY eep.project_name;
Update the 'efficiency_improvement' value to 0.15 in the 'energy_efficiency' table where the 'sector' is 'Industry'
CREATE TABLE energy_efficiency (id INT PRIMARY KEY,sector VARCHAR(255),efficiency_improvement FLOAT,country VARCHAR(255));
UPDATE energy_efficiency SET efficiency_improvement = 0.15 WHERE sector = 'Industry';
What is the total capacity of energy storage technologies in Texas as of 2023-01-01?
CREATE TABLE energy_storage (id INT,location VARCHAR(50),technology VARCHAR(50),capacity FLOAT,efficiency FLOAT); INSERT INTO energy_storage (id,location,technology,capacity,efficiency) VALUES (1,'California','Batteries',500.0,0.9),(2,'California','Pumped Hydro',1500.0,0.8),(3,'Texas','Batteries',700.0,0.95),(4,'Texas','Compressed Air',1200.0,0.88);
SELECT SUM(capacity) FROM energy_storage WHERE location = 'Texas' AND start_date <= '2023-01-01';
Who had the most assists for the Celtics in the 2018-2019 season?
CREATE TABLE teams (team_name VARCHAR(255),season_start_year INT,season_end_year INT); INSERT INTO teams (team_name,season_start_year,season_end_year) VALUES ('Celtics',2018,2019); CREATE TABLE players (player_name VARCHAR(255),team_name VARCHAR(255),assists INT);
SELECT player_name, MAX(assists) FROM players WHERE team_name = 'Celtics' AND season_start_year = 2018 AND season_end_year = 2019 GROUP BY player_name;
How many disaster response projects were carried out in Asia in the year 2020?
CREATE TABLE projects (id INT,name TEXT,location TEXT,start_date DATE,end_date DATE); INSERT INTO projects (id,name,location,start_date,end_date) VALUES (1,'Disaster Relief Project','Asia','2020-01-01','2020-12-31'),(2,'Community Development Project','Africa','2019-01-01','2020-12-31'),(3,'Healthcare Project','Europe','2018-01-01','2018-12-31');
SELECT COUNT(*) FROM projects WHERE location = 'Asia' AND YEAR(start_date) = 2020 AND YEAR(end_date) = 2020;
List all technology for social good initiatives in Asia, ordered by their year of establishment.
CREATE TABLE social_good (initiative VARCHAR(50),year INT); INSERT INTO social_good (initiative,year) VALUES ('Eco-friendly app',2018),('Online education platform',2020),('Accessible software',2015);
SELECT initiative FROM social_good WHERE year IN (SELECT year FROM social_good WHERE region = 'Asia') ORDER BY year;
What is the total number of ethical AI initiatives in Asia and Europe?
CREATE TABLE ethical_ai_initiatives (initiative_id INT,region VARCHAR(20),funds DECIMAL(10,2)); INSERT INTO ethical_ai_initiatives (initiative_id,region,funds) VALUES (1,'Asia',50000.00),(2,'Europe',100000.00),(3,'Asia',75000.00),(4,'Europe',25000.00);
SELECT SUM(funds) FROM ethical_ai_initiatives WHERE region IN ('Asia', 'Europe');
Update the 'FairTrade' status of all manufacturers in the 'Asia' region 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','No'),(2,'GreenYarns','Asia','No'),(3,'SustainableTextiles','Africa','Yes'),(4,'EcoWeaves','Europe','Yes');
UPDATE Manufacturers SET FairTrade = 'Yes' WHERE Region = 'Asia';
Which countries have the highest number of fair trade certified factories?
CREATE TABLE FairTradeFactories (id INT,country VARCHAR);
SELECT country, COUNT(*) as factory_count FROM FairTradeFactories GROUP BY country ORDER BY factory_count DESC LIMIT 5;
Count the number of transactions for socially responsible lending initiatives in the United States over the past month.
CREATE TABLE srl_transactions (id INT,initiative_type VARCHAR(255),transaction_date DATE);
SELECT COUNT(*) FROM srl_transactions WHERE initiative_type = 'socially responsible lending' AND transaction_date >= DATEADD(month, -1, GETDATE());
Update the bank name to 'GreenLend' for record with id 1 in the 'loans' table.
CREATE TABLE loans (id INT,bank VARCHAR(20),amount DECIMAL(10,2),is_socially_responsible BOOLEAN); INSERT INTO loans (id,bank,amount,is_socially_responsible) VALUES (1,'BlueBank',1000.00,true),(2,'GreenLend',1500.00,false),(3,'BlueBank',2000.00,true);
UPDATE loans SET bank = 'GreenLend' WHERE id = 1;
What is the average program impact score for each program type, sorted by the average impact score in descending order?
CREATE TABLE Programs (ProgramType TEXT,ImpactScore DECIMAL(3,2)); CREATE TABLE ImpactData (ProgramID TEXT,ProgramType TEXT,ImpactScore DECIMAL(3,2));
SELECT ProgramType, AVG(ImpactScore) as AvgImpactScore FROM ImpactData ID JOIN Programs P ON ID.ProgramType = P.ProgramType GROUP BY ProgramType ORDER BY AvgImpactScore DESC;
Who is the lead researcher for the biotech startup that received the most funding in the last 3 years?
CREATE TABLE company (id INT PRIMARY KEY,name VARCHAR(255),industry VARCHAR(255),funding FLOAT,startup_date DATE); CREATE TABLE research (id INT PRIMARY KEY,company_id INT,title VARCHAR(255),lead_researcher VARCHAR(255),start_date DATE); INSERT INTO company (id,name,industry,funding,startup_date) VALUES (1,'BioGen','Biotechnology',70000000,'2015-01-01'),(2,'BioSense','Biosensor Technology',20000000,'2018-01-01'),(3,'BioStart','Biotech Startup',80000000,'2020-01-01'); INSERT INTO research (id,company_id,title,lead_researcher,start_date) VALUES (1,3,'Genetic Research','Charlie','2021-01-01');
SELECT lead_researcher FROM research r JOIN company c ON r.company_id = c.id WHERE c.startup_date >= DATE_SUB(CURDATE(), INTERVAL 3 YEAR) AND c.funding = (SELECT MAX(funding) FROM company c WHERE c.startup_date >= DATE_SUB(CURDATE(), INTERVAL 3 YEAR));
What is the minimum investment in renewable energy projects in 'Country I' for each project type?
CREATE TABLE RenewableEnergyInvestments (ProjectID INT,ProjectType VARCHAR(255),Country VARCHAR(255),Investment FLOAT); INSERT INTO RenewableEnergyInvestments (ProjectID,ProjectType,Country,Investment) VALUES (1,'Wind','Country I',500000.0);
SELECT ProjectType, MIN(Investment) FROM RenewableEnergyInvestments WHERE Country = 'Country I' GROUP BY ProjectType;
How many patients have been treated for mental health conditions by health equity metric score quartile?
CREATE TABLE patients (patient_id INT,mental_health_condition VARCHAR(10),health_equity_metric_score INT); INSERT INTO patients (patient_id,mental_health_condition,health_equity_metric_score) VALUES (1,'Anxiety',75),(2,'Depression',80),(3,'Bipolar',60),(4,'PTSD',90),(5,'Anxiety',70);
SELECT AVG(health_equity_metric_score), NTILE(4) OVER (ORDER BY health_equity_metric_score) AS quartile FROM patients WHERE mental_health_condition = 'Anxiety' GROUP BY quartile;
What is the mental health score difference between urban, suburban, and rural areas?
CREATE TABLE Areas (AreaID INT,Area VARCHAR(50)); CREATE TABLE MentalHealthScores (MH_ID INT,AreaID INT,MentalHealthScore INT); INSERT INTO Areas (AreaID,Area) VALUES (1,'Urban'),(2,'Suburban'),(3,'Rural'); INSERT INTO MentalHealthScores (MH_ID,AreaID,MentalHealthScore) VALUES (1,1,85),(2,1,90),(3,2,75),(4,2,70),(5,3,80),(6,3,85),(7,1,65),(8,1,70),(9,2,80),(10,2,85);
SELECT a.Area, AVG(mhs.MentalHealthScore) as Avg_Score FROM MentalHealthScores mhs JOIN Areas a ON mhs.AreaID = a.AreaID GROUP BY a.Area;
What is the maximum duration of a virtual tour in 'Mexico' hotels?
CREATE TABLE virtual_tours (tour_id INT,hotel_id INT,date DATE,duration INT); INSERT INTO virtual_tours (tour_id,hotel_id,date,duration) VALUES (9,9,'2022-03-02',20),(10,9,'2022-03-05',25),(11,10,'2022-03-03',30); CREATE TABLE hotels (hotel_id INT,country VARCHAR(50)); INSERT INTO hotels (hotel_id,country) VALUES (9,'Mexico'),(10,'Brazil');
SELECT MAX(duration) FROM virtual_tours JOIN hotels ON virtual_tours.hotel_id = hotels.hotel_id WHERE hotels.country = 'Mexico';
Which hotels in the 'luxury' segment have the highest guest satisfaction ratings?
CREATE TABLE hotels (hotel_id INT,segment VARCHAR(20),guest_rating FLOAT);
SELECT hotel_id, segment, AVG(guest_rating) as avg_rating FROM hotels WHERE segment = 'luxury' GROUP BY hotel_id ORDER BY avg_rating DESC;
Update the CO2 emission value of the 'Canada' country to 580 in the 'emissions' table for the year 2010.
CREATE TABLE emissions (country VARCHAR(255),year INT,co2_emission FLOAT); INSERT INTO emissions (country,year,co2_emission) VALUES ('Canada',2010,550.0),('US',2010,5200.0),('Russia',2010,1900.0);
UPDATE emissions SET co2_emission = 580 WHERE country = 'Canada' AND year = 2010;
What is the number of species recorded in the 'biodiversity' table with a population greater than 15000?
CREATE TABLE biodiversity (id INT,species VARCHAR(255),population INT); INSERT INTO biodiversity (id,species,population) VALUES (1,'Polar Bear',5000),(2,'Arctic Fox',10000),(3,'Caribou',20000);
SELECT COUNT(DISTINCT species) FROM biodiversity WHERE population > 15000;
Which language families are at risk, with fewer than 10,000 speakers, and the total number of languages in each family?
CREATE TABLE Languages (id INT,name VARCHAR(255),language_family VARCHAR(255),num_speakers INT,UNIQUE(id));
SELECT Languages.language_family, COUNT(Languages.id) as num_languages FROM Languages WHERE Languages.num_speakers < 10000 GROUP BY Languages.language_family HAVING num_languages > 2;
Who are the therapists in Texas that have treated more than 5 patients with anxiety disorder?
CREATE TABLE patients (patient_id INT,patient_name TEXT,condition TEXT,therapist_id INT); CREATE TABLE therapists (therapist_id INT,therapist_name TEXT,state TEXT); INSERT INTO patients (patient_id,patient_name,condition,therapist_id) VALUES (1,'Oliver Brown','Anxiety Disorder',1); INSERT INTO patients (patient_id,patient_name,condition,therapist_id) VALUES (2,'Grace Johnson','Anxiety Disorder',1); INSERT INTO patients (patient_id,patient_name,condition,therapist_id) VALUES (3,'Mia Lee','Depression',1); INSERT INTO therapists (therapist_id,therapist_name,state) VALUES (1,'Dr. Emily Davis','Texas'); INSERT INTO therapists (therapist_id,therapist_name,state) VALUES (2,'Dr. Richard Garcia','Texas');
SELECT therapists.therapist_name FROM therapists JOIN (SELECT therapist_id FROM patients GROUP BY therapist_id HAVING COUNT(*) > 5) AS patient_counts ON therapists.therapist_id = patient_counts.therapist_id WHERE therapists.state = 'Texas' AND therapists.therapist_name IN (SELECT therapists.therapist_name FROM therapists JOIN patients ON therapists.therapist_id = patients.therapist_id WHERE patients.condition = 'Anxiety Disorder');
Insert a new record in the 'projects' table with id 7, name 'Green Transportation Initiative', description 'New green transportation project', start_date '2022-04-01', and end_date '2025-03-31'
CREATE TABLE projects (id INT,name VARCHAR(50),description TEXT,start_date DATE,end_date DATE);
INSERT INTO projects (id, name, description, start_date, end_date) VALUES (7, 'Green Transportation Initiative', 'New green transportation project', '2022-04-01', '2025-03-31');
Show the 3 most expensive projects in 'Railway Construction'.
CREATE TABLE project_info (id INT,name VARCHAR(50),category VARCHAR(50),cost INT); INSERT INTO project_info (id,name,category,cost) VALUES (1,'Test1','Railway Construction',7000000);
SELECT * FROM (SELECT * FROM project_info WHERE category = 'Railway Construction' ORDER BY cost DESC) subquery LIMIT 3;
Insert new records into the 'defendants' table with defendant_id 3001, 3002, first_name 'Aria', 'Asim', last_name 'Gupta'
CREATE TABLE defendants (defendant_id INT,first_name VARCHAR(20),last_name VARCHAR(20));
INSERT INTO defendants (defendant_id, first_name, last_name) VALUES (3001, 'Aria', 'Gupta'), (3002, 'Asim', 'Gupta');
What is the total number of court cases heard in the county of Los Angeles for the year 2020?
CREATE TABLE court_cases (id INT,county VARCHAR(255),year INT,number_of_cases INT); INSERT INTO court_cases (id,county,year,number_of_cases) VALUES (1,'Los Angeles',2020,5000),(2,'Los Angeles',2019,4000),(3,'Orange County',2020,3000);
SELECT SUM(number_of_cases) FROM court_cases WHERE county = 'Los Angeles' AND year = 2020;
Delete marine debris records from the marine_debris table that were recorded before 2010.
CREATE TABLE marine_debris (id INT,debris_type VARCHAR(255),debris_date DATE); INSERT INTO marine_debris (id,debris_type,debris_date) VALUES (1,'Fishing Net','2005-01-01'),(2,'Plastic Bottle','2015-01-01');
DELETE FROM marine_debris WHERE debris_date < '2010-01-01';
What is the frequency of news content for each country in the media_content table?
CREATE TABLE media_content (id INT,country VARCHAR(50),genre VARCHAR(50),frequency INT); INSERT INTO media_content (id,country,genre,frequency) VALUES (1,'USA','News - Print',50),(2,'Canada','News - Online',100),(3,'Mexico','News - TV',150);
SELECT country, genre, SUM(frequency) FROM media_content WHERE genre LIKE 'News%' GROUP BY country, genre;
How many 'Seasonal Vegetable' dishes were sold each day?
CREATE TABLE Daily_Sales(Date DATE,Menu_Item VARCHAR(30),Quantity INT); INSERT INTO Daily_Sales(Date,Menu_Item,Quantity) VALUES('2022-01-01','Seasonal Vegetables',10),('2022-01-02','Seasonal Vegetables',15);
SELECT Date, Menu_Item, SUM(Quantity) as Total_Quantity FROM Daily_Sales WHERE Menu_Item = 'Seasonal Vegetables' GROUP BY Date, Menu_Item;
List all defense projects with their contract values
CREATE TABLE Projects (ProjectID INT,ProjectName VARCHAR(100),ContractID INT); INSERT INTO Projects (ProjectID,ProjectName,ContractID) VALUES (1,'Tank Production',1),(2,'Missile Production',2); CREATE TABLE Contracts (ContractID INT,ContractValue DECIMAL(10,2)); INSERT INTO Contracts (ContractID,ContractValue) VALUES (1,500000),(2,750000);
SELECT Projects.ProjectName, Contracts.ContractValue FROM Projects INNER JOIN Contracts ON Projects.ContractID = Contracts.ContractID;
What is the total amount donated by each donor, ordered from highest to lowest?
CREATE TABLE Donors (DonorID INT,DonorName VARCHAR(50),TotalDonation DECIMAL(10,2)); INSERT INTO Donors VALUES (1,'John Doe',5000.00),(2,'Jane Smith',3500.00),(3,'Mike Johnson',2000.00);
SELECT DonorName, TotalDonation FROM Donors ORDER BY TotalDonation DESC;
Determine the average KDA ratio by champion in LoL
CREATE TABLE lolgames (game_id INT,champion VARCHAR(50),kills INT,deaths INT,assists INT); INSERT INTO lolgames (game_id,champion,kills,deaths,assists) VALUES (1,'Ashe',10,4,6);
SELECT champion, (SUM(kills) + SUM(assists)) / NULLIF(SUM(deaths), 0) as avg_kda_ratio FROM lolgames GROUP BY champion
Retrieve the average game duration for each game in the 'GameSessions' table
CREATE TABLE GameSessions (GameID INT,SessionDuration TIME);
SELECT GameID, AVG(SessionDuration) as AverageSessionDuration FROM GameSessions GROUP BY GameID;
Calculate the average temperature and humidity for farms in the 'Asia' region.
CREATE TABLE weather_data (id INT,farm_id INT,date DATE,temperature FLOAT,humidity FLOAT); INSERT INTO weather_data (id,farm_id,date,temperature,humidity) VALUES (1,1,'2018-01-01',20.0,60.0); INSERT INTO weather_data (id,farm_id,date,temperature,humidity) VALUES (2,2,'2018-01-02',18.0,70.0); INSERT INTO weather_data (id,farm_id,date,temperature,humidity) VALUES (3,3,'2018-01-03',22.0,55.0);
SELECT w.farm_id, AVG(temperature) AS avg_temp, AVG(humidity) AS avg_humidity FROM weather_data w JOIN farm_info f ON w.farm_id = f.farm_id WHERE f.location LIKE 'Asia%' GROUP BY w.farm_id;
List the top 5 countries with the highest average temperature in July.
CREATE TABLE WeatherData (country VARCHAR(255),date DATE,temperature INT); INSERT INTO WeatherData (country,date,temperature) VALUES ('France','2022-07-01',25),('France','2022-07-02',26),('Germany','2022-07-01',23),('Germany','2022-07-02',24),('Spain','2022-07-01',28),('Spain','2022-07-02',29),('Italy','2022-07-01',27),('Italy','2022-07-02',26),('Sweden','2022-07-01',20),('Sweden','2022-07-02',21);
SELECT country, AVG(temperature) as Avg_Temperature FROM WeatherData WHERE date BETWEEN '2022-07-01' AND '2022-07-31' GROUP BY country ORDER BY Avg_Temperature DESC LIMIT 5;
What is the average temperature recorded in the 'sensors' table for the 'Spring' season?
CREATE TABLE sensors (id INT,location VARCHAR(255),temperature FLOAT,reading_date DATE); INSERT INTO sensors (id,location,temperature,reading_date) VALUES (1,'Field1',22,'2021-03-01'); INSERT INTO sensors (id,location,temperature,reading_date) VALUES (2,'Field2',25,'2021-03-15');
SELECT AVG(temperature) FROM sensors WHERE reading_date BETWEEN (SELECT MIN(reading_date) FROM sensors WHERE EXTRACT(MONTH FROM reading_date) IN (3,4,5)) AND (SELECT MAX(reading_date) FROM sensors WHERE EXTRACT(MONTH FROM reading_date) IN (3,4,5))
What is the minimum rainfall recorded in Field13 and Field14 in the year 2021?
CREATE TABLE Field13 (date DATE,rain_mm FLOAT); INSERT INTO Field13 VALUES ('2021-01-01',10),('2021-01-02',5); CREATE TABLE Field14 (date DATE,rain_mm FLOAT); INSERT INTO Field14 VALUES ('2021-01-01',8),('2021-01-02',3);
SELECT LEAST(f13.rain_mm, f14.rain_mm) as min_rainfall FROM Field13 f13 INNER JOIN Field14 f14 ON f13.date = f14.date WHERE EXTRACT(YEAR FROM f13.date) = 2021;
List all the unique services offered by the department of transportation in the city of XYZ?
CREATE TABLE department_services (service_id INT,department TEXT,city TEXT,service TEXT); INSERT INTO department_services (service_id,department,city,service) VALUES (1,'Transportation','XYZ','Bus'),(2,'Transportation','XYZ','Train'),(3,'Utilities','XYZ','Water'),(4,'Utilities','ABC','Electricity');
SELECT DISTINCT service FROM department_services WHERE department = 'Transportation' AND city = 'XYZ';
What was the average response time for citizen feedback records in 2022, and how many records were responded to within 48 hours?
CREATE TABLE FeedbackResponse (Year INT,ResponseTime FLOAT,RespondedWithin48Hours INT); INSERT INTO FeedbackResponse (Year,ResponseTime,RespondedWithin48Hours) VALUES (2022,3.2,1),(2022,4.7,1),(2022,2.8,0),(2022,1.9,1);
SELECT AVG(ResponseTime), SUM(RespondedWithin48Hours) FROM FeedbackResponse WHERE Year = 2022;
Count the number of rare earth elements extracted by companies from Oceania in 2022?
CREATE TABLE rare_earth_elements_2 (element TEXT); INSERT INTO rare_earth_elements_2 VALUES ('Terbium'),('Holmium'),('Erbium'); CREATE TABLE extraction_data_2 (year INT,company_name TEXT,element TEXT,quantity INT); INSERT INTO extraction_data_2 (year,company_name,element,quantity) VALUES (2022,'EFG Mining','Terbium',1200),(2022,'HIJ Mining','Holmium',900),(2022,'KLM Mining','Erbium',1800),(2022,'NOP Mining','Terbium',1500); CREATE TABLE mining_locations_2 (company_name TEXT,region TEXT); INSERT INTO mining_locations_2 (company_name,region) VALUES ('EFG Mining','Oceania'),('HIJ Mining','Antarctica'),('KLM Mining','Oceania'),('NOP Mining','Oceania');
SELECT COUNT(DISTINCT element) as total_elements FROM extraction_data_2 WHERE year = 2022 AND company_name IN (SELECT company_name FROM mining_locations_2 WHERE region = 'Oceania');