instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
What is the minimum price of paintings sold by African artists in the last 15 years?
CREATE TABLE ArtWork (id INT,title VARCHAR(255),type VARCHAR(255),price DECIMAL(10,2),sale_year INT,artist_continent VARCHAR(255)); INSERT INTO ArtWork (id,title,type,price,sale_year,artist_continent) VALUES (1,'Painting1','Painting',500,2006,'Africa');
SELECT MIN(price) FROM ArtWork WHERE type = 'Painting' AND artist_continent = 'Africa' AND sale_year >= 2006;
How many language preservation grants worth over $70,000 were issued in Africa?
CREATE TABLE GrantsAfrica (id INT,name TEXT,type TEXT,amount INT,region TEXT); INSERT INTO GrantsAfrica (id,name,type,amount,region) VALUES (1,'Grant 1','Language',75000,'Africa'),(2,'Grant 2','Heritage',60000,'Africa'),(3,'Grant 3','Language',80000,'Africa');
SELECT COUNT(*) FROM GrantsAfrica WHERE type = 'Language' AND amount > 70000 AND region = 'Africa'
Which traditional Japanese art forms have more than 500 active practitioners?
CREATE TABLE art_forms (id INT,name TEXT,type TEXT,num_practitioners INT); INSERT INTO art_forms (id,name,type,num_practitioners) VALUES (1,'Ukiyo-e','Printmaking',400),(2,'Kabuki','Theater',600),(3,'Ikebana','Flower Arrangement',700);
SELECT name FROM art_forms WHERE type = 'Printmaking' OR type = 'Theater' OR type = 'Flower Arrangement' HAVING num_practitioners > 500;
List the top 3 therapists with the most group therapy sessions in the therapy_sessions table.
CREATE TABLE therapy_sessions (session_id INT,patient_id INT,therapist_id INT,session_date DATE,session_duration TIME,session_type VARCHAR(255));
SELECT therapist_id, COUNT(*) as session_count FROM therapy_sessions WHERE session_type = 'group therapy' GROUP BY therapist_id ORDER BY session_count DESC LIMIT 3;
What is the average water quality index for water treatment plants in Texas, categorized by plant type and water source?
CREATE TABLE Plants (id INT,state VARCHAR(2),plant_type VARCHAR(10),water_source VARCHAR(10),water_quality_index FLOAT); INSERT INTO Plants (id,state,plant_type,water_source,water_quality_index) VALUES (1,'TX','Surface','River',80),(2,'TX','Ground','Well',85),(3,'TX','Surface','Lake',75);
SELECT plant_type, water_source, AVG(water_quality_index) FROM Plants WHERE state = 'TX' GROUP BY plant_type, water_source;
Identify the destinations with the highest number of repeat visitors from the US.
CREATE TABLE RepeatTravelers (Visitor VARCHAR(20),Destination VARCHAR(20),VisitCount INT); INSERT INTO RepeatTravelers (Visitor,Destination,VisitCount) VALUES ('David','Paris',3),('Ella','London',4),('Fiona','Paris',2);
SELECT Destination, AVG(VisitCount) AS AvgVisitCount FROM RepeatTravelers WHERE Visitor LIKE '%USA%' GROUP BY Destination ORDER BY AvgVisitCount DESC;
How many legal aid clinics and community mediation centers are there in total, and what is the sum of cases handled by each type of center, for centers located in the state of California?
CREATE TABLE LegalAidClinics (ClinicName text,State text,NumCases int); INSERT INTO LegalAidClinics VALUES ('Clinic1','CA',30,'2022-01-01'),('Clinic2','CA',25,'2022-01-01'); CREATE TABLE CommunityMediationCenters (CenterName text,State text,NumCases int); INSERT INTO CommunityMediationCenters VALUES ('CM1','CA',22,'2022-01-01'),('CM2','CA',28,'2022-01-01');
SELECT State, 'Legal Aid Clinics' AS CenterType, COUNT(*) AS NumCenters, SUM(NumCases) AS TotalCases FROM LegalAidClinics WHERE State = 'CA' UNION ALL SELECT State, 'Community Mediation Centers', COUNT(*), SUM(NumCases) FROM CommunityMediationCenters WHERE State = 'CA';
What is the maximum population of any marine species in the Atlantic ocean?
CREATE TABLE marine_species (id INT,name TEXT,population INT,location TEXT); INSERT INTO marine_species (id,name,population,location) VALUES (1,'Dolphin',50,'Atlantic'); INSERT INTO marine_species (id,name,population,location) VALUES (2,'Turtle',25,'Atlantic'); INSERT INTO marine_species (id,name,population,location) VALUES (3,'Shark',100,'Pacific');
SELECT MAX(population) FROM marine_species WHERE location = 'Atlantic';
Update the name of language with ID 3 to 'Italian' and ID 4 to 'Russian'
CREATE TABLE Languages (LanguageID int,LanguageName varchar(50)); INSERT INTO Languages (LanguageID,LanguageName) VALUES (1,'English'),(2,'Spanish'),(3,'French'),(4,'German');
UPDATE Languages SET LanguageName = CASE LanguageID WHEN 3 THEN 'Italian' WHEN 4 THEN 'Russian' ELSE LanguageName END;
Update the quantity of 'Fighter Jet' sales records in 'Africa' to 15 for the year '2025'
CREATE TABLE military_sales (id INT PRIMARY KEY,region VARCHAR(20),year INT,equipment_name VARCHAR(30),quantity INT,value FLOAT); INSERT INTO military_sales (id,region,year,equipment_name,quantity,value) VALUES (1,'Africa',2025,'Fighter Jet',10,6000000),(2,'Africa',2025,'Helicopter',15,9000000),(3,'Africa',2025,'Tank',20,13000000);
UPDATE military_sales SET quantity = 15 WHERE region = 'Africa' AND equipment_name = 'Fighter Jet' AND year = 2025;
What is the average cost of air defense systems sold by ApexCorp in the Asia-Pacific region?
CREATE TABLE IF NOT EXISTS air_defense_sales (system_id int,cost float,company varchar(30),region varchar(30)); INSERT INTO air_defense_sales (system_id,cost,company,region) VALUES (1,5000000,'ApexCorp','Asia-Pacific'),(2,6000000,'ApexCorp','Asia-Pacific'),(3,4500000,'ApexCorp','Asia-Pacific');
SELECT AVG(cost) FROM air_defense_sales WHERE company = 'ApexCorp' AND region = 'Asia-Pacific';
What is the earliest start date of defense project negotiations with Saudi Arabia?
CREATE TABLE DefenseProjectTimelines (id INT PRIMARY KEY,project_name VARCHAR(50),negotiation_start_date DATE,negotiation_end_date DATE,country VARCHAR(50)); INSERT INTO DefenseProjectTimelines (id,project_name,negotiation_start_date,negotiation_end_date,country) VALUES (1,'S-400 Missile Defense System','2016-01-01','2018-01-01','Saudi Arabia'),(2,'AK-12 Assault Rifle','2017-01-01','2019-01-01','Saudi Arabia');
SELECT MIN(negotiation_start_date) FROM DefenseProjectTimelines WHERE country = 'Saudi Arabia';
What is the total amount of minerals extracted by each mining company in each state?
CREATE TABLE mineral_extraction (company VARCHAR(255),state VARCHAR(255),year INT,total_tons FLOAT); INSERT INTO mineral_extraction (company,state,year,total_tons) VALUES ('STU Mining','New Mexico',2017,50000),('STU Mining','New Mexico',2018,55000),('VWX Mining','Texas',2017,60000),('VWX Mining','Texas',2018,65000);
SELECT company, state, SUM(total_tons) as total_tons FROM mineral_extraction GROUP BY company, state;
What is the percentage of women and non-binary individuals in leadership roles in the mining industry?
CREATE TABLE workers (id INT,role TEXT,gender TEXT); INSERT INTO workers (id,role,gender) VALUES (1,'Manager','Male'),(2,'Engineer','Female'),(3,'Operator','Non-binary'),(4,'Manager','Female'),(5,'Engineer','Non-binary'),(6,'Operator','Male');
SELECT (COUNT(*) FILTER (WHERE (role = 'Manager' AND gender IN ('Female', 'Non-binary')))) * 100.0 / COUNT(*) FROM workers WHERE role = 'Manager';
Find the top 3 recipients by total donations?
CREATE TABLE Donations (DonationID int,Recipient varchar(50),Amount decimal(10,2)); INSERT INTO Donations (DonationID,Recipient,Amount) VALUES (1,'UNICEF',500),(2,'Red Cross',750),(3,'Greenpeace',300),(4,'Red Cross',800),(5,'UNICEF',900),(6,'Doctors Without Borders',600);
SELECT Recipient, SUM(Amount) as TotalDonated FROM Donations GROUP BY Recipient ORDER BY TotalDonated DESC LIMIT 3;
What is the total number of players and esports events?
CREATE TABLE Players (PlayerID INT,Age INT,Gender VARCHAR(10),Country VARCHAR(50)); INSERT INTO Players (PlayerID,Age,Gender,Country) VALUES (1,25,'Male','USA'); INSERT INTO Players (PlayerID,Age,Gender,Country) VALUES (2,30,'Female','Canada'); CREATE TABLE EsportsEvents (EventID INT,PlayerID INT,EventName VARCHAR(50)); INSERT INTO EsportsEvents (EventID,PlayerID,EventName) VALUES (1,1,'GameX Championship'); INSERT INTO EsportsEvents (EventID,PlayerID,EventName) VALUES (2,2,'CyberSport Cup');
SELECT COUNT(Players.PlayerID) + COUNT(EsportsEvents.EventID) FROM Players;
How many IoT devices are active in the 'Asia' region?
CREATE TABLE IoTDevices (device_id INT,device_type VARCHAR(20),region VARCHAR(10),active BOOLEAN); INSERT INTO IoTDevices (device_id,device_type,region,active) VALUES (1,'Soil Moisture Sensor','West',TRUE); INSERT INTO IoTDevices (device_id,device_type,region,active) VALUES (2,'Soil Moisture Sensor','East',TRUE); INSERT INTO IoTDevices (device_id,device_type,region,active) VALUES (3,'Soil Moisture Sensor','North',FALSE); INSERT INTO IoTDevices (device_id,device_type,region,active) VALUES (4,'Soil Moisture Sensor','South',TRUE); INSERT INTO IoTDevices (device_id,device_type,region,active) VALUES (5,'Soil Moisture Sensor','Asia',TRUE);
SELECT COUNT(*) FROM IoTDevices WHERE region = 'Asia' AND active = TRUE;
How many public schools are there in the state of Texas?
CREATE TABLE schools (state VARCHAR(20),city VARCHAR(20),school_name VARCHAR(30),type VARCHAR(20)); INSERT INTO schools VALUES ('Texas','Houston','Houston High School','Public'),('Texas','Dallas','Dallas High School','Public');
SELECT COUNT(*) FROM schools WHERE state = 'Texas' AND type = 'Public';
What is the average budget for public schools in each region?
CREATE TABLE Schools (Region VARCHAR(20),School VARCHAR(20),Budget DECIMAL(10,2)); INSERT INTO Schools (Region,School,Budget) VALUES ('Northeast','SchoolA',15000.00),('West','SchoolB',20000.00),('Southeast','SchoolC',18000.00);
SELECT AVG(Budget) FROM Schools GROUP BY Region;
What is the total number of public parks in the city of Philadelphia?
CREATE TABLE parks (park_id INT,park_city TEXT,park_type TEXT); INSERT INTO parks (park_id,park_city,park_type) VALUES (1,'Philadelphia','public'),(2,'Philadelphia','private'),(3,'New York','public');
SELECT COUNT(*) FROM parks WHERE park_city = 'Philadelphia' AND park_type = 'public';
Update the green space percentage for the GreenVille area in the SustainableUrbanism table.
CREATE TABLE SustainableUrbanism (area TEXT,green_space_percentage FLOAT,public_transportation_score INT,walkability_score INT); INSERT INTO SustainableUrbanism (area,green_space_percentage,public_transportation_score,walkability_score) VALUES ('Eastside',0.3,8,9),('Westside',0.5,7,8),('GreenVille',0.4,8,8);
UPDATE SustainableUrbanism SET green_space_percentage = 0.5 WHERE area = 'GreenVille';
What is the maximum property price in the sustainable_communities table?
CREATE TABLE sustainable_communities (id INT,property_price FLOAT); INSERT INTO sustainable_communities (id,property_price) VALUES (1,700000),(2,800000),(3,900000);
SELECT MAX(property_price) FROM sustainable_communities;
What is the minimum square footage of an inclusive housing unit in the city of Miami?
CREATE TABLE housing (id INT,city VARCHAR(20),size INT,inclusive BOOLEAN); INSERT INTO housing (id,city,size,inclusive) VALUES (1,'Miami',800,TRUE),(2,'Miami',1000,FALSE),(3,'Miami',1200,TRUE);
SELECT MIN(size) FROM housing WHERE city = 'Miami' AND inclusive = TRUE;
Identify menu items that have not been inspected in the last 30 days
CREATE TABLE menu_items (id INT,name VARCHAR(255),restaurant_id INT); INSERT INTO menu_items (id,name,restaurant_id) VALUES (1,'Burger',1),(2,'Pizza',1),(3,'Pasta',2),(4,'Salad',2); CREATE TABLE food_safety_inspections (id INT,menu_item_id INT,score INT,inspection_date DATE); INSERT INTO food_safety_inspections (id,menu_item_id,score,inspection_date) VALUES (1,1,95,'2022-01-01'),(2,1,90,'2022-02-01'),(3,2,98,'2022-01-01'),(4,2,92,'2022-02-01'),(5,3,88,'2022-01-01'),(6,3,90,'2022-02-01'),(7,4,95,'2022-01-01'),(8,4,92,'2022-02-01');
SELECT mi.name FROM menu_items mi LEFT JOIN food_safety_inspections fsi ON mi.id = fsi.menu_item_id WHERE fsi.inspection_date IS NULL OR fsi.inspection_date < NOW() - INTERVAL '30 days';
List all menu items and their prices for 'Sustainable Seafood Restaurant'.
CREATE TABLE Menu (Restaurant VARCHAR(255),Item VARCHAR(255),Price DECIMAL(5,2)); INSERT INTO Menu (Restaurant,Item,Price) VALUES ('Vegan Bistro','Tofu Stir Fry',12.99),('Vegan Bistro','Quinoa Salad',10.99),('Sustainable Seafood Restaurant','Grilled Salmon',19.99),('Sustainable Seafood Restaurant','Lobster Bisque',7.99);
SELECT Item, Price FROM Menu WHERE Restaurant = 'Sustainable Seafood Restaurant';
What is the maximum altitude reached by a SpaceX Falcon 9 rocket?
CREATE TABLE RocketAltitudes (rocket TEXT,altitude FLOAT); INSERT INTO RocketAltitudes (rocket,altitude) VALUES ('Falcon 9',700.0),('Falcon 9',800.0),('Falcon 9',900.0),('Falcon Heavy',2500.0);
SELECT MAX(altitude) FROM RocketAltitudes WHERE rocket = 'Falcon 9';
What is the total cost of satellite launches for each country?
CREATE TABLE satellites (country VARCHAR(50),num_satellites INT,cost INT); INSERT INTO satellites (country,num_satellites,cost) VALUES ('USA',1800,4000000000),('China',400,1000000000),('Russia',300,1500000000);
SELECT country, SUM(cost) as total_cost FROM satellites GROUP BY country;
Add a new column 'assists' to the 'athlete_stats' table
CREATE TABLE athlete_stats (athlete_id INT PRIMARY KEY,name VARCHAR(100),sport VARCHAR(50),team VARCHAR(50),games_played INT,goals_scored INT);
ALTER TABLE athlete_stats ADD COLUMN assists INT;
Update the ticket_price of seat_section 'General' in the 'ticket_sales' table to $100
CREATE TABLE ticket_sales (seat_section VARCHAR(10),ticket_price DECIMAL(5,2)); INSERT INTO ticket_sales (seat_section,ticket_price) VALUES ('General',75.00),('VIP',100.00);
UPDATE ticket_sales SET ticket_price = 100.00 WHERE seat_section = 'General';
Update the speed of electric trains in New York to reflect the latest measurements.
CREATE TABLE public.trains (id SERIAL PRIMARY KEY,name TEXT,speed FLOAT,city TEXT); INSERT INTO public.trains (name,speed,city) VALUES ('Electric Train 1',85.2,'New York'),('Electric Train 2',88.9,'New York');
UPDATE public.trains SET speed = 86.1 WHERE city = 'New York' AND name LIKE 'Electric Train%';
What is the maximum number of passengers carried by a public bus in Sydney?
CREATE TABLE passengers (id INT PRIMARY KEY,type VARCHAR(20),capacity INT,city VARCHAR(20));
SELECT MAX(capacity) FROM passengers WHERE type = 'Public Bus' AND city = 'Sydney';
What is the ratio of electric cars to electric bikes in Seoul?
CREATE TABLE electric_vehicles (vehicle_id INT,type VARCHAR(20),city VARCHAR(20)); INSERT INTO electric_vehicles (vehicle_id,type,city) VALUES (1,'Car','Seoul'),(2,'Car','Seoul'),(3,'Bike','Seoul'),(4,'Bike','Seoul');
SELECT city, COUNT(*) FILTER (WHERE type = 'Car') * 1.0 / COUNT(*) FILTER (WHERE type = 'Bike') AS car_to_bike_ratio FROM electric_vehicles WHERE city = 'Seoul' GROUP BY city;
What are the total sales for each product category in Q2 of 2022?
CREATE TABLE sales (sale_id INT,product_id INT,sale_date DATE,sale_amount DECIMAL(10,2));
SELECT product_id, SUM(sale_amount) FROM sales WHERE sale_date BETWEEN '2022-04-01' AND '2022-06-30' GROUP BY product_id;
What are the top 3 autonomous vehicles with the highest safety ratings in the 'auto_show' table?
CREATE TABLE auto_show (id INT,vehicle_name VARCHAR(50),safety_rating INT);
SELECT vehicle_name, safety_rating FROM (SELECT vehicle_name, safety_rating, ROW_NUMBER() OVER (ORDER BY safety_rating DESC) as safety_rank FROM auto_show WHERE vehicle_name LIKE '%Autonomous%') AS auton_ranks WHERE safety_rank <= 3;
What is the safety rating of the most recent vehicle manufactured by BMW?
CREATE TABLE Vehicles (id INT,make VARCHAR(255),model VARCHAR(255),safety_rating FLOAT,manufacturing_date DATE); INSERT INTO Vehicles (id,make,model,safety_rating,manufacturing_date) VALUES (1,'Toyota','Corolla',4.2,'2017-01-01'); INSERT INTO Vehicles (id,make,model,safety_rating,manufacturing_date) VALUES (2,'BMW','3 Series',4.8,'2022-01-01');
SELECT safety_rating FROM Vehicles WHERE make = 'BMW' ORDER BY manufacturing_date DESC LIMIT 1;
Add new cargo type 'Grains' to vessel with ID 2.
CREATE TABLE vessels (id INT,name VARCHAR(255)); INSERT INTO vessels (id,name) VALUES (1,'VesselA'),(2,'VesselB'),(3,'VesselC'); CREATE TABLE cargo (id INT,vessel_id INT,cargo_type VARCHAR(255)); INSERT INTO cargo (id,vessel_id,cargo_type) VALUES (1,1,'Fuel'),(2,1,'Containers');
INSERT INTO cargo (id, vessel_id, cargo_type) VALUES (3, 2, 'Grains');
How many accidents were reported for vessels with more than 5000 tons cargo capacity?
CREATE TABLE vessels (id INT,name VARCHAR(255),cargo_capacity INT); INSERT INTO vessels (id,name,cargo_capacity) VALUES (1,'Vessel_A',6000),(2,'Vessel_B',4000),(3,'Vessel_C',5500); CREATE TABLE accidents (id INT,vessel_id INT,date DATE); INSERT INTO accidents (id,vessel_id,date) VALUES (1,1,'2021-02-12'),(2,1,'2021-04-01'),(3,2,'2021-01-15'),(4,3,'2021-03-20');
SELECT COUNT(a.vessel_id) as accidents_count FROM accidents a JOIN vessels v ON a.vessel_id = v.id WHERE v.cargo_capacity > 5000;
What is the average speed of Taiwanese-flagged vessels traveling to Port H in Q1 2022?
CREATE TABLE Vessels (id INT,name TEXT,speed FLOAT,flag_country TEXT,arrive_port TEXT,arrive_date DATE); INSERT INTO Vessels (id,name,speed,flag_country,arrive_port,arrive_date) VALUES (1,'Vessel1',21.5,'Taiwan','Port H','2022-01-15'); INSERT INTO Vessels (id,name,speed,flag_country,arrive_port,arrive_date) VALUES (2,'Vessel2',23.0,'Taiwan','Port H','2022-02-01');
SELECT AVG(speed) FROM Vessels WHERE flag_country = 'Taiwan' AND arrive_port = 'Port H' AND EXTRACT(YEAR FROM arrive_date) = 2022 AND EXTRACT(QUARTER FROM arrive_date) = 1;
What is the total investment in circular economy initiatives in North America in USD?
CREATE TABLE circular_investments (year INT,region TEXT,investment FLOAT); INSERT INTO circular_investments (year,region,investment) VALUES (2018,'Latin America',1500000),(2018,'North America',2500000),(2019,'Latin America',1800000),(2019,'North America',3000000);
SELECT SUM(investment) FROM circular_investments WHERE region = 'North America';
Delete records of users who joined after Jan 5, 2022 from the "Members" table
CREATE TABLE Members (Id INT PRIMARY KEY,FirstName VARCHAR(50),LastName VARCHAR(50),JoinDate DATETIME,LastLogin DATETIME);
DELETE FROM Members WHERE JoinDate > '2022-01-05';
Delete all records in the ai_safety table where the algorithm column is 'DeepLearning' and the risk_level is 'high'
CREATE TABLE ai_safety (algorithm TEXT,risk_level TEXT,dataset TEXT,last_updated TIMESTAMP);
DELETE FROM ai_safety WHERE algorithm = 'DeepLearning' AND risk_level = 'high';
How many AI safety research papers were published by each author?
CREATE TABLE SafetyPapers (id INT,author VARCHAR(255),title VARCHAR(255));
SELECT author, COUNT(*) FROM SafetyPapers GROUP BY author;
How many community development initiatives were completed in Brazil between 2015 and 2019?
CREATE TABLE community_development_initiatives (id INT,initiative_name VARCHAR(50),country VARCHAR(50),completion_year INT); INSERT INTO community_development_initiatives (id,initiative_name,country,completion_year) VALUES (1,'Fome Zero','Brazil',2003),(2,'Bolsa Família','Brazil',2015),(3,'Minha Casa,Minha Vida','Brazil',2019);
SELECT COUNT(*) FROM community_development_initiatives WHERE country = 'Brazil' AND completion_year BETWEEN 2015 AND 2019;
How many rural infrastructure projects were completed in 2020?
CREATE TABLE rural_infrastructure (id INT,project_name VARCHAR(255),sector VARCHAR(255),location VARCHAR(255),start_date DATE,end_date DATE); INSERT INTO rural_infrastructure (id,project_name,sector,location,start_date,end_date) VALUES (1,'Rural Road Project','Infrastructure','Village C,Country Z','2020-01-01','2020-12-31');
SELECT COUNT(*) FROM rural_infrastructure WHERE YEAR(end_date) = 2020;
Delete all records from the 'maintenance_records' table where the 'aircraft_model' is '787' and 'manufacturing_year' is greater than 2015
CREATE TABLE maintenance_records (id INT PRIMARY KEY,aircraft_model VARCHAR(50),manufacturing_year INT,total_maintenance_hours INT);
DELETE FROM maintenance_records WHERE aircraft_model = '787' AND manufacturing_year > 2015;
What is the average size (in square kilometers) of habitats for animals in the 'habitats' table that are not birds?
CREATE TABLE habitats (id INT,animal_type VARCHAR(50),size_km FLOAT); INSERT INTO habitats (id,animal_type,size_km) VALUES (1,'Mammal',45.1),(2,'Reptile',25.1),(3,'Bird',12.5);
SELECT AVG(size_km) FROM habitats WHERE animal_type != 'Bird';
Compare the number of building permits for residential and commercial types in California and Florida with a size between 1500 and 4000 square feet in 2020
CREATE TABLE BuildingPermits (ID INT PRIMARY KEY,State VARCHAR(20),City VARCHAR(20),Type VARCHAR(20),Size INT,Date DATE,Year INT); INSERT INTO BuildingPermits (ID,State,City,Type,Size,Date,Year) VALUES (5,'California','San Diego','Residential',1500,'2020-01-02',2020),(6,'California','San Francisco','Commercial',5000,'2020-03-15',2020),(7,'Florida','Miami','Residential',2500,'2020-06-01',2020),(8,'Florida','Orlando','Commercial',3500,'2020-09-01',2020);
SELECT Type, COUNT(*) FROM BuildingPermits WHERE State IN ('California', 'Florida') AND Size BETWEEN 1500 AND 4000 AND Year = 2020 GROUP BY Type;
Delete all records for production sites located in Japan from the production_sites table.
CREATE TABLE production_sites(id INT,site_name TEXT,location TEXT); INSERT INTO production_sites (id,site_name,location) VALUES (1,'Site A','Japan'),(2,'Site B','Canada'),(3,'Site C','USA');
DELETE FROM production_sites WHERE location = 'Japan';
Delete all climate finance records related to 'fossil fuel divestment' in Europe.
CREATE TABLE climate_finance (id INT,initiative VARCHAR(255),location VARCHAR(255),funding FLOAT); INSERT INTO climate_finance (id,initiative,location,funding) VALUES (1,'Coal Divestment Campaign','Europe',2000000);
DELETE FROM climate_finance WHERE initiative LIKE '%fossil fuel divestment%' AND location = 'Europe';
Who is the manufacturer of the drug with the highest sales?
CREATE TABLE sales_data (drug_name TEXT,manufacturer TEXT,sales INTEGER);
SELECT manufacturer FROM sales_data WHERE sales = (SELECT MAX(sales) FROM sales_data);
Calculate the average funding amount for companies founded in the last decade
CREATE TABLE company_founding (company_name VARCHAR(255),foundation_year INT); INSERT INTO company_founding (company_name,foundation_year) VALUES ('Tech Titan Inc',2011),('Innovate Inc',2015),('GreenTech LLC',2018),('Delta Co',2016); CREATE TABLE funding (company_name VARCHAR(255),funding_amount INT); INSERT INTO funding (company_name,funding_amount) VALUES ('Tech Titan Inc',500000),('Innovate Inc',750000),('GreenTech LLC',600000),('Delta Co',400000);
SELECT AVG(funding_amount) FROM funding JOIN company_founding ON funding.company_name = company_founding.company_name WHERE foundation_year >= 2011 AND foundation_year <= 2021;
Delete funding_rounds records for company_id 103
CREATE TABLE companies (id INT PRIMARY KEY,name VARCHAR(255)); CREATE TABLE funding_rounds (id INT PRIMARY KEY,company_id INT,round_type VARCHAR(255),raised_amount DECIMAL(10,2));
DELETE FROM funding_rounds WHERE company_id = 103;
What is the number of companies founded by immigrants each year?
CREATE TABLE founders (founder_id INT,company_id INT,immigrant BOOLEAN); CREATE TABLE companies (company_id INT,founding_year INT); INSERT INTO founders (founder_id,company_id,immigrant) VALUES (1,1,true),(2,2,false),(3,3,true),(4,4,false); INSERT INTO companies (company_id,founding_year) VALUES (1,2018),(2,2017),(3,2019),(4,2018);
SELECT founding_year, COUNT(f.founder_id) as num_immigrant_founded_companies FROM founders f JOIN companies c ON f.company_id = c.company_id WHERE f.immigrant = true GROUP BY founding_year;
Show decentralized applications and their respective developers who have worked together on more than 2 projects.
CREATE TABLE DApps (DAppId INT,DAppName VARCHAR(50),DeveloperId INT); CREATE TABLE Developers (DeveloperId INT,DeveloperName VARCHAR(50)); INSERT INTO DApps (DAppId,DAppName,DeveloperId) VALUES (1,'App1',1); INSERT INTO DApps (DAppId,DAppName,DeveloperId) VALUES (2,'App2',1); INSERT INTO DApps (DAppId,DAppName,DeveloperId) VALUES (3,'App3',1); INSERT INTO DApps (DAppId,DAppName,DeveloperId) VALUES (4,'App4',2); INSERT INTO DApps (DAppId,DAppName,DeveloperId) VALUES (5,'App5',2); INSERT INTO DApps (DAppId,DAppName,DeveloperId) VALUES (6,'App6',3); INSERT INTO Developers (DeveloperId,DeveloperName) VALUES (1,'James'); INSERT INTO Developers (DeveloperId,DeveloperName) VALUES (2,'Kim'); INSERT INTO Developers (DeveloperId,DeveloperName) VALUES (3,'Lena');
SELECT d1.DAppName, d2.DeveloperName FROM DApps d1 INNER JOIN DApps d2 ON d1.DeveloperId = d2.DeveloperId WHERE d1.DAppId <> d2.DAppId GROUP BY d1.DAppName, d2.DeveloperName HAVING COUNT(*) > 2;
Which species have a population growth rate higher than the average for protected areas?
CREATE TABLE species (id INT,name VARCHAR(50),population DECIMAL(5,2),protected_area_id INT,growth_rate DECIMAL(5,2)); INSERT INTO species (id,name,population,protected_area_id,growth_rate) VALUES (1,'Species 1',500.00,1,0.05),(2,'Species 2',800.00,1,0.03),(3,'Species 3',1200.00,2,0.07),(4,'Species 4',700.00,2,0.02); CREATE TABLE protected_areas (id INT,name VARCHAR(50)); INSERT INTO protected_areas (id,name) VALUES (1,'Area 1'),(2,'Area 2');
SELECT s.name, s.growth_rate FROM species s INNER JOIN protected_areas pa ON s.protected_area_id = pa.id GROUP BY s.name, s.growth_rate HAVING s.growth_rate > (SELECT AVG(s.growth_rate) FROM species s INNER JOIN protected_areas pa ON s.protected_area_id = pa.id);
What is the average response time for emergencies in each district for the past month?
CREATE TABLE districts (district_id INT,district_name VARCHAR(255)); INSERT INTO districts (district_id,district_name) VALUES (1,'Central'),(2,'North'),(3,'South'),(4,'East'),(5,'West'); CREATE TABLE emergencies (emergency_id INT,district_id INT,response_time INT,emergency_date DATE);
SELECT d.district_name, AVG(e.response_time) FROM districts d INNER JOIN emergencies e ON d.district_id = e.district_id WHERE e.emergency_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH) GROUP BY d.district_name;
What is the maximum number of artworks an artist has donated to a museum?
CREATE TABLE donations (id INT,artist VARCHAR(100),museum VARCHAR(50),artworks INT); INSERT INTO donations (id,artist,museum,artworks) VALUES (1,'Mohamed','Metropolitan Museum',15),(2,'Sophia','Louvre Museum',20),(3,'Juan','Metropolitan Museum',10);
SELECT MAX(artworks) FROM donations;
How many military innovation projects were initiated in 2019?
CREATE TABLE military_innovation (id INT,year INT,projects INT); INSERT INTO military_innovation (id,year,projects) VALUES (1,2017,50),(2,2018,55),(3,2019,60),(4,2020,65),(5,2021,70);
SELECT SUM(projects) FROM military_innovation WHERE year = 2019;
List the top 5 countries with the highest military spending as a percentage of their GDP in the year 2020.
CREATE TABLE military_expenditure (country TEXT,year INT,amount INT,gdp INT); INSERT INTO military_expenditure (country,year,amount,gdp) VALUES ('USA',2020,731000,21433227);
SELECT country, (amount / gdp) * 100 AS military_spending_percentage FROM military_expenditure WHERE year = 2020 ORDER BY military_spending_percentage DESC LIMIT 5;
What was the maximum total funding for excavation sites in Asia?
CREATE TABLE excavation_sites (id INT,site_name VARCHAR(50),location VARCHAR(50),total_funding DECIMAL(10,2));
SELECT MAX(total_funding) as max_funding FROM excavation_sites WHERE location LIKE 'Asia%'
Which artifacts were discovered before 2000 in the 'Pompeii' excavation site?
CREATE TABLE ExcavationSites (site_id INT,site_name VARCHAR(50)); CREATE TABLE Artifacts (artifact_id INT,site_id INT,discovered_year INT); INSERT INTO ExcavationSites (site_id,site_name) VALUES (1,'Pompeii'); INSERT INTO Artifacts (artifact_id,site_id,discovered_year) VALUES (1,1,1998),(2,1,2005),(3,1,1999),(4,1,1987);
SELECT Artifacts.artifact_id, Artifacts.site_id, Artifacts.discovered_year FROM Artifacts INNER JOIN ExcavationSites ON Artifacts.site_id = ExcavationSites.site_id WHERE ExcavationSites.site_name = 'Pompeii' AND Artifacts.discovered_year < 2000;
What is the average age of patients who have been diagnosed with diabetes in the rural health clinic located in Texas?
CREATE TABLE rural_clinic (clinic_id INT,location VARCHAR(20),capacity INT); INSERT INTO rural_clinic (clinic_id,location,capacity) VALUES (1,'Texas',50); CREATE TABLE patient (patient_id INT,clinic_id INT,age INT,diagnosis VARCHAR(20)); INSERT INTO patient (patient_id,clinic_id,age,diagnosis) VALUES (1,1,45,'diabetes'),(2,1,60,'asthma'),(3,1,30,'diabetes');
SELECT AVG(age) FROM patient WHERE diagnosis = 'diabetes' AND clinic_id = 1;
What is the maximum age of patients diagnosed with Hypertension?
CREATE TABLE Patients (PatientID INT,Age INT,Gender VARCHAR(10),Diagnosis VARCHAR(20),Location VARCHAR(20)); INSERT INTO Patients (PatientID,Age,Gender,Diagnosis,Location) VALUES (1,35,'Male','Asthma','Texas'); INSERT INTO Patients (PatientID,Age,Gender,Diagnosis,Location) VALUES (2,42,'Female','Asthma','Texas'); INSERT INTO Patients (PatientID,Age,Gender,Diagnosis,Location) VALUES (3,50,'Male','Diabetes','Urban'); INSERT INTO Patients (PatientID,Age,Gender,Diagnosis,Location) VALUES (4,60,'Female','Hypertension','Rural');
SELECT MAX(Age) FROM Patients WHERE Diagnosis = 'Hypertension';
What is the name and region of the rural health department with the lowest patient-to-physician ratio?
CREATE TABLE departments (name VARCHAR(255),patient_count INT,physician_count INT); INSERT INTO departments (name,patient_count,physician_count) VALUES (1,100,50),(2,150,75);
SELECT name, region, patient_count, physician_count, (patient_count / NULLIF(physician_count, 0)) AS patient_physician_ratio FROM departments ORDER BY patient_physician_ratio ASC LIMIT 1;
How many 'diversity and inclusion' initiatives were implemented by companies in the 'finance' sector in 2022?
CREATE TABLE initiatives_companies (id INT,company_sector VARCHAR(20),initiative VARCHAR(30),implementation_year INT); INSERT INTO initiatives_companies (id,company_sector,initiative,implementation_year) VALUES (1,'finance','diversity and inclusion',2022),(2,'technology','climate change',2020),(3,'finance','sustainability',2019);
SELECT COUNT(*) FROM initiatives_companies WHERE company_sector = 'finance' AND initiative = 'diversity and inclusion' AND implementation_year = 2022;
What is the total investment in the 'Green Energy' sector?
CREATE TABLE sector_investments (sector VARCHAR(20),investment_amount FLOAT); INSERT INTO sector_investments (sector,investment_amount) VALUES ('Healthcare',300000),('Finance',500000),('Green Energy',700000),('Affordable Housing',400000);
SELECT SUM(investment_amount) FROM sector_investments WHERE sector = 'Green Energy';
List all intelligence operations in the Middle East and their corresponding budgets.
CREATE TABLE IntelligenceOperations (OperationID INT,Operation TEXT,Region TEXT,Budget INT); INSERT INTO IntelligenceOperations (OperationID,Operation,Region,Budget) VALUES (1,'Operation Desert Storm','Middle East',80000000); INSERT INTO IntelligenceOperations (OperationID,Operation,Region,Budget) VALUES (2,'Operation Enduring Freedom','Middle East',120000000);
SELECT Operation, Budget FROM IntelligenceOperations WHERE Region = 'Middle East';
List the programs that have more than 50 participants and their total budget.
CREATE TABLE programs (id INT,name TEXT,participants INT,budget INT); INSERT INTO programs (id,name,participants,budget) VALUES (1,'Education',60,10000),(2,'Health',40,12000),(3,'Environment',70,8000);
SELECT name, SUM(budget) AS total_budget FROM programs WHERE participants > 50 GROUP BY name;
What is the minimum donation amount received in the month of August?
CREATE TABLE Donations (DonationID INT,DonorID INT,DonationDate DATE,DonationAmount DECIMAL); INSERT INTO Donations (DonationID,DonorID,DonationDate,DonationAmount) VALUES (1,1,'2022-08-01',200.00),(2,2,'2022-08-15',150.00),(3,3,'2022-07-01',250.00);
SELECT MIN(DonationAmount) FROM Donations WHERE MONTH(DonationDate) = 8;
What is the average age of teachers who have completed professional development courses in the last 5 years?
CREATE TABLE Teacher (TeacherID INT,Age INT,CompletedProfessionalDevelopment YEAR); INSERT INTO Teacher (TeacherID,Age,CompletedProfessionalDevelopment) VALUES (1,35,2021); INSERT INTO Teacher (TeacherID,Age,CompletedProfessionalDevelopment) VALUES (2,40,2020); CREATE VIEW ProfessionalDevelopmentLast5Years AS SELECT * FROM Teacher WHERE CompletedProfessionalDevelopment >= YEAR(CURRENT_DATE) - 5;
SELECT AVG(Age) FROM ProfessionalDevelopmentLast5Years;
What is the difference between the average salary for employees who identify as male and female?
SAME AS ABOVE
SELECT AVG(Employees.Salary) - (SELECT AVG(Employees.Salary) FROM Employees WHERE Gender = 'Male') AS Difference FROM Employees WHERE Gender = 'Female';
Insert a new wind energy production record for Quebec in the year 2026 with 6000 MWh
CREATE TABLE wind_energy (id INT,region VARCHAR(50),year INT,production FLOAT);
INSERT INTO wind_energy (id, region, year, production) VALUES (2, 'Quebec', 2026, 6000);
What is the average energy consumption per capita by country in 2021?
CREATE TABLE EnergyConsumptionPerCapita (Country VARCHAR(255),Year INT,Consumption FLOAT); INSERT INTO EnergyConsumptionPerCapita (Country,Year,Consumption) VALUES ('US',2021,10000),('Canada',2021,9000),('UK',2021,8000),('Germany',2021,7000),('Australia',2021,12000),('Japan',2021,6000),('India',2021,3000);
SELECT Country, AVG(Consumption) AS AverageConsumptionPerCapita FROM EnergyConsumptionPerCapita WHERE Year = 2021 GROUP BY Country;
What is the maximum power usage for industrial buildings in California?
CREATE TABLE power_usage (id INT PRIMARY KEY,building_type VARCHAR(255),usage FLOAT,location VARCHAR(255)); INSERT INTO power_usage (id,building_type,usage,location) VALUES (1,'Residential',500.0,'California'); INSERT INTO power_usage (id,building_type,usage,location) VALUES (2,'Commercial',1000.0,'Texas'); INSERT INTO power_usage (id,building_type,usage,location) VALUES (3,'Industrial',2000.0,'California');
SELECT building_type, MAX(usage) FROM power_usage WHERE building_type = 'Industrial' AND location = 'California';
What is the minimum oil production for wells in Alberta?
CREATE TABLE exploration_data (data_id INT,well_id INT,date DATE,gas_production FLOAT,oil_production FLOAT); INSERT INTO exploration_data (data_id,well_id,date,gas_production,oil_production) VALUES (1,1,'2020-01-01',50.3,150.2),(2,2,'2020-02-15',60.1,200.5),(3,3,'2019-12-10',45.8,175.3),(4,5,'2020-03-10',35.8,100.3),(5,6,'2020-04-05',40.1,125.0);
SELECT well_id, MIN(oil_production) FROM exploration_data WHERE location = 'Alberta' GROUP BY well_id;
What was the total gas production in the North Sea for 2019 and 2020?
CREATE TABLE production (id INT,year INT,region VARCHAR(255),gas_production DECIMAL(5,2)); INSERT INTO production (id,year,region,gas_production) VALUES (1,2018,'North Sea',200.0),(2,2019,'North Sea',250.0),(3,2020,'North Sea',300.0);
SELECT SUM(CASE WHEN year IN (2019, 2020) AND region = 'North Sea' THEN gas_production ELSE 0 END) as total_gas_production FROM production;
How many tennis matches were played on grass courts in the 'tennis_tournaments' table?
CREATE TABLE tennis_tournaments (player VARCHAR(50),court VARCHAR(50),matches INT); INSERT INTO tennis_tournaments (player,court,matches) VALUES ('Novak Djokovic','Grass',5),('Roger Federer','Grass',6),('Rafael Nadal','Grass',3);
SELECT SUM(matches) FROM tennis_tournaments WHERE court = 'Grass';
What is the average distance (in meters) scored by each player in their last 5 three-point shots?
CREATE TABLE players (id INT,name TEXT,distance_last_3p FLOAT); INSERT INTO players (id,name,distance_last_3p) VALUES (1,'John Doe',8.5),(2,'Jane Smith',9.2);
SELECT name, AVG(distance_last_3p) OVER (PARTITION BY name ORDER BY name ROWS BETWEEN UNBOUNDED PRECEDING AND 4 PRECEDING) as avg_distance FROM players;
What is the total number of fans who attended the football matches of 'Manchester United' in the year 2020?
CREATE TABLE matches (team TEXT,year INTEGER,fans_attended INTEGER); INSERT INTO matches (team,year,fans_attended) VALUES ('Manchester United',2020,50000); INSERT INTO matches (team,year,fans_attended) VALUES ('Manchester United',2020,55000);
SELECT SUM(fans_attended) FROM matches WHERE team = 'Manchester United' AND year = 2020;
How many 'lightrail' vehicles were serviced in February 2022?
CREATE TABLE public.vehicle (vehicle_id SERIAL PRIMARY KEY,vehicle_type VARCHAR(20),station_id INTEGER,FOREIGN KEY (station_id) REFERENCES public.station(station_id)); INSERT INTO public.vehicle (vehicle_type,station_id) VALUES ('lightrail',1),('lightrail',2); CREATE TABLE public.service (service_id SERIAL PRIMARY KEY,service_type VARCHAR(20),service_date DATE,vehicle_id INTEGER,FOREIGN KEY (vehicle_id) REFERENCES public.vehicle(vehicle_id)); INSERT INTO public.service (service_type,service_date,vehicle_id) VALUES ('routine maintenance','2022-02-03',1),('repair','2022-02-15',2);
SELECT COUNT(*) FROM public.service INNER JOIN public.vehicle ON public.service.vehicle_id = public.vehicle.vehicle_id WHERE vehicle_type = 'lightrail' AND service_date >= '2022-02-01' AND service_date <= '2022-02-28'
What is the total fare revenue of buses in New York on a given day?
CREATE TABLE bus_rides (id INT,route_id INT,timestamp TIMESTAMP,fare DECIMAL); CREATE VIEW daily_bus_revenue AS SELECT route_id,SUM(fare) as daily_revenue FROM bus_rides WHERE DATE(timestamp) = '2023-03-16' GROUP BY route_id;
SELECT SUM(daily_revenue) as total_daily_revenue FROM daily_bus_revenue JOIN bus_stops ON daily_bus_revenue.route_id = bus_stops.id WHERE location LIKE 'New York%';
What is the total number of bus trips in London with a bike rack?
CREATE TABLE bus_trips (trip_id INT,has_bike_rack BOOLEAN,city VARCHAR(50)); INSERT INTO bus_trips (trip_id,has_bike_rack,city) VALUES (1,true,'London'),(2,false,'London'),(3,true,'London');
SELECT COUNT(*) FROM bus_trips WHERE has_bike_rack = true AND city = 'London';
What are the advertising impressions for posts in a specific time range?
CREATE TABLE ads (id INT PRIMARY KEY,post_id INT,impressions INT,timestamp TIMESTAMP); INSERT INTO ads (id,post_id,impressions,timestamp) VALUES (1,1,500,'2022-01-01 10:00:00'); INSERT INTO ads (id,post_id,impressions,timestamp) VALUES (2,2,750,'2022-01-02 11:00:00');
SELECT p.content, a.impressions FROM posts p INNER JOIN ads a ON p.id = a.post_id WHERE a.timestamp BETWEEN '2022-01-01 00:00:00' AND '2022-01-07 23:59:59';
Who are the top 5 users with the most followers, and what is their location?
CREATE TABLE user_data (user_id INT,name VARCHAR(50),followers INT,location VARCHAR(50)); INSERT INTO user_data (user_id,name,followers,location) VALUES (1,'Alice',10000,'New York'),(2,'Bob',15000,'California'),(3,'Charlie',12000,'Texas'),(4,'David',8000,'Florida'),(5,'Eve',9000,'Illinois');
SELECT name, location FROM (SELECT name, location, ROW_NUMBER() OVER (ORDER BY followers DESC) AS rank FROM user_data) AS user_ranks WHERE rank <= 5;
Add a new customer record for 'Alexei' from 'Russia' with size '42' to the 'customers' table
CREATE TABLE customers (id INT PRIMARY KEY,name VARCHAR(50),country VARCHAR(50),size INT);
INSERT INTO customers (id, name, country, size) VALUES (1, 'Alexei', 'Russia', 42);
What is the total quantity of sustainable fabrics sourced from each country in the past year?
CREATE TABLE TextileVendors (VendorID INT,VendorName TEXT,Country TEXT); CREATE TABLE FabricSourcing (SourcingID INT,VendorID INT,FabricType TEXT,Quantity INT,SourcingDate DATE); INSERT INTO TextileVendors VALUES (1,'VendorA','India'),(2,'VendorB','Bangladesh'),(3,'VendorC','China'); INSERT INTO FabricSourcing VALUES (1,1,'SustainableFabric1',50,'2022-01-01'),(2,2,'SustainableFabric2',30,'2022-02-01'),(3,3,'SustainableFabric3',40,'2022-03-01');
SELECT v.Country, SUM(fs.Quantity) AS TotalQuantity FROM TextileVendors v JOIN FabricSourcing fs ON v.VendorID = fs.VendorID WHERE fs.SourcingDate >= DATEADD(YEAR, -1, CURRENT_DATE) AND fs.FabricType IN ('SustainableFabric1', 'SustainableFabric2', 'SustainableFabric3') GROUP BY v.Country;
Which sustainable fabrics are used in the production of women's clothing?
CREATE TABLE Fabrics (Fabric_ID INT,Fabric_Name TEXT,Sustainable BOOLEAN); INSERT INTO Fabrics (Fabric_ID,Fabric_Name,Sustainable) VALUES (1,'Organic Cotton',true),(2,'Polyester',false),(3,'Hemp',true),(4,'Viscose',false); CREATE TABLE Women_Clothing (Clothing_ID INT,Fabric_ID INT); INSERT INTO Women_Clothing (Clothing_ID,Fabric_ID) VALUES (1,1),(2,3),(3,4);
SELECT Fabrics.Fabric_Name FROM Fabrics INNER JOIN Women_Clothing ON Fabrics.Fabric_ID = Women_Clothing.Fabric_ID WHERE Fabrics.Sustainable = true;
What is the median financial capability score for women-led businesses in South America?
CREATE TABLE financial_capability (id INT,business_id INT,gender VARCHAR(255),region VARCHAR(255),score FLOAT);
SELECT MEDIAN(score) FROM financial_capability WHERE gender = 'female' AND region = 'South America';
Which program had the highest total impact score in 2019?
CREATE TABLE programs (program_id INT,impact_score INT,program_year INT); INSERT INTO programs (program_id,impact_score,program_year) VALUES (1,85,2019),(2,78,2019),(3,91,2018);
SELECT program_id, MAX(impact_score) FROM programs WHERE program_year = 2019 GROUP BY program_id;
Identify the number of genetically modified ingredients in dishes served at 'Green Leaf'?
CREATE TABLE dishes_gm (dish_id INT,name VARCHAR(50),gm_ingredients INT); INSERT INTO dishes_gm VALUES (1,'Tofu Stir Fry',0); INSERT INTO dishes_gm VALUES (2,'Chickpea Salad',0); CREATE TABLE served_at (dish_id INT,location VARCHAR(50)); INSERT INTO served_at VALUES (1,'Green Leaf'); INSERT INTO served_at VALUES (2,'Green Leaf');
SELECT COUNT(dg.gm_ingredients) FROM dishes_gm dg JOIN served_at sa ON dg.dish_id = sa.dish_id WHERE sa.location = 'Green Leaf';
How many bioprocess engineering projects were completed in Q1 of 2022, grouped by their completion status and project category?
CREATE TABLE bioprocess_engineering (id INT PRIMARY KEY,project_name VARCHAR(255),completion_status VARCHAR(255),project_category VARCHAR(255),completion_date DATE);
SELECT completion_status, project_category, COUNT(*) FROM bioprocess_engineering WHERE completion_date BETWEEN '2022-01-01' AND '2022-03-31' GROUP BY completion_status, project_category;
List all states and their respective percentage of total government spending on education.
CREATE TABLE government_spending (state VARCHAR(20),category VARCHAR(20),amount INT); INSERT INTO government_spending (state,category,amount) VALUES ('New York','Education',120000000),('California','Education',180000000),('Texas','Education',150000000),('Florida','Education',100000000),('Illinois','Education',110000000);
SELECT state, ROUND(100.0*SUM(CASE WHEN category = 'Education' THEN amount ELSE 0 END)/SUM(amount), 1) AS education_percentage FROM government_spending GROUP BY state;
Update the name of the government program in the state of California with the ID of 3 to 'Program X'.
CREATE TABLE programs (id INT,name VARCHAR(255),budget FLOAT,state VARCHAR(255)); INSERT INTO programs (id,name,budget,state) VALUES (1,'Program A',2.5,'Florida'),(2,'Program B',1.2,'Florida'),(3,'Program C',1.8,'California');
UPDATE programs SET name = 'Program X' WHERE id = 3 AND state = 'California';
Find the top 5 cities with the highest average energy consumption per building in the 'GreenBuildings' schema.
CREATE TABLE GreenBuildings.CityEnergy (city VARCHAR(50),avg_energy_per_building FLOAT); INSERT INTO GreenBuildings.CityEnergy (city,avg_energy_per_building) VALUES ('NYC',1100.5),('LA',1300.2),('SF',1000.7),('Chicago',1400.3),('Houston',1500.0),('Denver',1200.4);
SELECT city, AVG(energy_consumption) AS avg_energy_per_building FROM GreenBuildings.Buildings GROUP BY city ORDER BY avg_energy_per_building DESC LIMIT 5;
How many mental health parity complaints were received by region in the last year?
CREATE TABLE MentalHealthParity (ComplaintID INT,Region VARCHAR(255),Date DATE); INSERT INTO MentalHealthParity (ComplaintID,Region,Date) VALUES (1,'Northeast','2021-01-01'),(2,'Southeast','2021-02-15'),(3,'Midwest','2021-03-05'),(4,'West','2021-04-10');
SELECT Region, COUNT(*) as ComplaintCount FROM MentalHealthParity WHERE Date >= DATEADD(year, -1, GETDATE()) GROUP BY Region;
What is the maximum number of virtual tours engaged with in a single day for hotels in New York City, USA?
CREATE TABLE virtual_tours (id INT,hotel_id INT,engagement_count INT,engagement_date DATE); CREATE TABLE hotels (id INT,name TEXT,city TEXT,country TEXT);
SELECT MAX(engagement_count) FROM virtual_tours vt INNER JOIN hotels h ON vt.hotel_id = h.id WHERE h.city = 'New York City' AND h.country = 'USA';
what is the average temperature change per decade in the arctic
CREATE TABLE temperature_data (measurement_id INT PRIMARY KEY,measurement_date DATE,temperature REAL); INSERT INTO temperature_data (measurement_id,measurement_date,temperature) VALUES (1,'2010-01-01',12.3),(2,'2000-01-01',10.2);
SELECT (EXTRACT(YEAR FROM measurement_date) - 2000) / 10 * 10 AS decade, AVG(temperature) FROM temperature_data GROUP BY decade;
What is the average age of patients who received CBT treatment in California?
CREATE TABLE patients (id INT,name TEXT,age INT,state TEXT);CREATE TABLE treatments (id INT,patient_id INT,therapy TEXT);INSERT INTO patients (id,name,age,state) VALUES (1,'John Doe',35,'California');INSERT INTO treatments (id,patient_id,therapy) VALUES (1,1,'CBT');
SELECT AVG(patients.age) FROM patients INNER JOIN treatments ON patients.id = treatments.patient_id WHERE patients.state = 'California' AND treatments.therapy = 'CBT';
What is the minimum number of sessions completed by a volunteer in the volunteers table who is over 30 years old?
CREATE TABLE volunteers (id INT,name VARCHAR(50),age INT,sessions_completed INT);
SELECT MIN(sessions_completed) FROM volunteers WHERE age > 30;
Calculate the total biomass of marine species in 'OceanMappingProjectA' and 'OceanMappingProjectB'
CREATE TABLE SpeciesBiomass (species VARCHAR(255),biomass FLOAT); INSERT INTO SpeciesBiomass (species,biomass) VALUES ('Coral',250.0),('Starfish',150.0),('Jellyfish',300.0); CREATE TABLE OceanMappingProjects (species VARCHAR(255),project VARCHAR(255)); INSERT INTO OceanMappingProjects (species,project) VALUES ('Coral','OceanMappingProjectA'),('Starfish','OceanMappingProjectA'),('Jellyfish','OceanMappingProjectB');
SELECT SUM(biomass) FROM SpeciesBiomass INNER JOIN OceanMappingProjects ON SpeciesBiomass.species = OceanMappingProjects.species WHERE OceanMappingProjects.project IN ('OceanMappingProjectA', 'OceanMappingProjectB');