instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
Find the number of tourists who visited 'New Zealand' attractions more than twice in the last year.
CREATE TABLE attractions (id INT,name TEXT,country TEXT); CREATE TABLE visits (id INT,attraction_id INT,visitor_id INT,visit_date DATE);
SELECT COUNT(DISTINCT visitor_id) FROM (SELECT visitor_id, attraction_id FROM attractions JOIN visits ON attractions.id = visits.attraction_id WHERE country = 'New Zealand' AND visit_date > (CURRENT_DATE - INTERVAL '1 year') GROUP BY visitor_id, attraction_id HAVING COUNT(*) > 2);
Delete all records from the conservation_efforts table where the project status is 'unsuccessful'
CREATE TABLE conservation_efforts (id INT,species_id INT,project_status VARCHAR(20));
DELETE FROM conservation_efforts WHERE project_status = 'unsuccessful';
What was the change in virtual tourism revenue between Q2 and Q3 2022, for each region in the world?
CREATE TABLE tourism_revenue (region VARCHAR(50),revenue FLOAT,quarter INT,year INT); INSERT INTO tourism_revenue (region,revenue,quarter,year) VALUES ('Americas',4000000,2,2022),('Americas',4500000,3,2022),('Asia',3000000,2,2022),('Asia',3200000,3,2022),('Europe',5000000,2,2022),('Europe',5300000,3,2022);
SELECT region, (q3_revenue - q2_revenue) as revenue_change FROM (SELECT region, SUM(CASE WHEN quarter = 2 THEN revenue ELSE 0 END) as q2_revenue, SUM(CASE WHEN quarter = 3 THEN revenue ELSE 0 END) as q3_revenue FROM tourism_revenue GROUP BY region) as subquery;
How many members have enrolled in the last 30 days?
CREATE TABLE memberships (id INT,member_type VARCHAR(50),region VARCHAR(50),enrollment_date DATE);
SELECT COUNT(*) FROM memberships WHERE enrollment_date >= CURRENT_DATE - INTERVAL '30' DAY;
What is the adoption rate of each smart city technology in the 'SmartCityTechAdoption' table?
CREATE TABLE SmartCityTechAdoption (id INT,city VARCHAR(50),technology VARCHAR(50),adoption_rate FLOAT);
SELECT technology, AVG(adoption_rate) as avg_adoption_rate FROM SmartCityTechAdoption GROUP BY technology;
How many public participations occurred in each region?
CREATE TABLE region_data (region VARCHAR(255),participations INT); INSERT INTO region_data VALUES ('Northeast',250),('Midwest',300),('South',375),('West',225);
SELECT region, SUM(participations) FROM region_data GROUP BY region;
How many unique strains are available in CO dispensaries that have 'organic' in their name?
CREATE TABLE strains (id INT,name TEXT,dispensary_id INT); INSERT INTO strains (id,name,dispensary_id) VALUES (1,'Strain A',1),(2,'Strain B',1),(3,'Strain C',2); CREATE TABLE dispensaries (id INT,name TEXT,state TEXT); INSERT INTO dispensaries (id,name,state) VALUES (1,'Organic Dispensary','Colorado'),(2,'Dispensary X','Colorado');
SELECT COUNT(DISTINCT s.name) FROM strains s JOIN dispensaries d ON s.dispensary_id = d.id WHERE d.state = 'Colorado' AND d.name LIKE '%organic%';
What is the average daily gas production, in cubic feet, for all wells in the Marcellus Shale, for the last 6 months?
CREATE TABLE GasProduction (ProductionID INT,Location VARCHAR(20),ProductionMonth DATE,GasProduction INT); INSERT INTO GasProduction (ProductionID,Location,ProductionMonth,GasProduction) VALUES (1,'Marcellus Shale','2022-06-01',1200000),(2,'Marcellus Shale','2022-05-01',1100000),(3,'Barnett Shale','2022-04-01',1000000);
SELECT AVG(GasProduction) FROM GasProduction WHERE Location = 'Marcellus Shale' AND ProductionMonth >= DATEADD(month, -6, GETDATE());
What is the total duration of cardio workouts for members with a smartwatch?
CREATE TABLE Members (MemberID INT,HasSmartwatch BOOLEAN); CREATE TABLE Workouts (WorkoutID INT,MemberID INT,WorkoutDate DATE,Duration INT,WorkoutType VARCHAR(10));
SELECT SUM(Duration) FROM Workouts INNER JOIN Members ON Workouts.MemberID = Members.MemberID WHERE Members.HasSmartwatch = TRUE AND WorkoutType = 'cardio';
Update the quantity of dysprosium produced on January 1, 2017 in the production table
CREATE TABLE production (id INT PRIMARY KEY,element VARCHAR(10),quantity INT,production_date DATE);
UPDATE production SET quantity = 250 WHERE element = 'dysprosium' AND production_date = '2017-01-01';
How many investments have been made in the renewable energy sector with a risk assessment score greater than 70?
CREATE TABLE investments (id INT,sector VARCHAR(255),risk_assessment_score INT); INSERT INTO investments (id,sector,risk_assessment_score) VALUES (1,'Renewable Energy',75),(2,'Renewable Energy',80),(3,'Healthcare',60);
SELECT COUNT(*) FROM investments WHERE sector = 'Renewable Energy' AND risk_assessment_score > 70;
Find the average price of all products that are ethically sourced from the 'Product' table
CREATE TABLE Product (product_id INT PRIMARY KEY,product_name VARCHAR(50),price DECIMAL(5,2),is_ethically_sourced BOOLEAN);
SELECT AVG(price) FROM Product WHERE is_ethically_sourced = TRUE;
What is the percentage of hybrid vehicles sold in Canada in 2019?
CREATE TABLE Vehicle_Sales (id INT,vehicle_type TEXT,quantity INT,year INT,country TEXT); INSERT INTO Vehicle_Sales (id,vehicle_type,quantity,year,country) VALUES (1,'Electric',800,2019,'Canada'); INSERT INTO Vehicle_Sales (id,vehicle_type,quantity,year,country) VALUES (2,'Hybrid',1200,2019,'Canada');
SELECT (SUM(quantity) FILTER (WHERE vehicle_type = 'Hybrid')::FLOAT / SUM(quantity)) * 100.0 FROM Vehicle_Sales WHERE year = 2019 AND country = 'Canada';
What is the average distance each marathoner ran in the Olympics?
CREATE TABLE olympic_marathon (athlete VARCHAR(50),distance INT); INSERT INTO olympic_marathon (athlete,distance) VALUES ('Eliud Kipchoge',42195),('Feyisa Lilesa',42320),('Galen Rupp',42200);
SELECT AVG(distance) AS avg_distance FROM olympic_marathon;
Identify the most endangered species in the Antarctic Ocean
CREATE TABLE endangered_species (species_name TEXT,conservation_status TEXT,habitat TEXT); INSERT INTO endangered_species (species_name,conservation_status,habitat) VALUES ('Leopard Seal','Vulnerable','Antarctic Ocean'),('Crabeater Seal','Near Threatened','Antarctic Ocean'),('Hourglass Dolphin','Critically Endangered','Antarctic Ocean');
SELECT species_name, conservation_status FROM endangered_species WHERE habitat = 'Antarctic Ocean' ORDER BY conservation_status DESC LIMIT 1;
What is the distance from a given stop to every other stop in a city?
CREATE TABLE stops (id INT,name VARCHAR(255),lat DECIMAL(9,6),lon DECIMAL(9,6),city VARCHAR(255)); INSERT INTO stops (id,name,lat,lon,city) VALUES (1,'Central Station',40.7128,-74.0060,'NYC'),(2,'Times Square',40.7590,-73.9844,'NYC'),(3,'Eiffel Tower',48.8582,2.2945,'Paris'),(4,'Big Ben',51.5008,-0.1246,'London'),(5,'Sydney Opera House',-33.8568,151.2153,'Sydney');
SELECT s1.name as Start, s2.name as End, ROUND(ST_Distance_Sphere(POINT(s2.lon, s2.lat), POINT(s1.lon, s1.lat)), 2) as Distance FROM stops s1 JOIN stops s2 ON s1.city = s2.city WHERE s1.id <> s2.id;
Update the name of the inmate with ID 1 to 'John Doe' in the prison table.
CREATE TABLE prison (id INT,name TEXT,security_level TEXT,age INT); INSERT INTO prison (id,name,security_level,age) VALUES (1,'Jane Smith','low_security',45);
UPDATE prison SET name = 'John Doe' WHERE id = 1;
What is the total research grant amount awarded to female graduate students per department?
CREATE TABLE grad_students (student_id INT,student_name VARCHAR(50),gender VARCHAR(10),department VARCHAR(50)); INSERT INTO grad_students (student_id,student_name,gender,department) VALUES (1,'Alice','Female','Computer Science'),(2,'Bob','Male','Physics'); CREATE TABLE research_grants (grant_id INT,student_id INT,grant_amount DECIMAL(10,2)); INSERT INTO research_grants (grant_id,student_id,grant_amount) VALUES (1,1,15000),(2,2,20000);
SELECT department, SUM(grant_amount) as total_grant_amount FROM research_grants rg JOIN grad_students gs ON rg.student_id = gs.student_id WHERE gs.gender = 'Female' GROUP BY department;
Delete records of donors who have not donated more than $1000 in the 'africa' region.
CREATE TABLE donors (id INT,name TEXT,region TEXT,donation_amount FLOAT); INSERT INTO donors (id,name,region,donation_amount) VALUES (1,'John Doe','Africa',500.00),(2,'Jane Smith','Africa',3000.00);
DELETE FROM donors WHERE region = 'Africa' AND donation_amount < 1000;
What is the maximum emission level of ChemicalB in 2022?
CREATE TABLE chemical (chemical_id INT,name TEXT); INSERT INTO chemical (chemical_id,name) VALUES (1,'ChemicalA'),(2,'ChemicalB'),(3,'ChemicalC'); CREATE TABLE emission_log (log_id INT,chemical_id INT,emission_amount INT,emission_date DATE); INSERT INTO emission_log (log_id,chemical_id,emission_amount,emission_date) VALUES (1,1,50,'2022-01-01'),(2,1,45,'2022-01-02'),(3,2,60,'2022-01-01'),(4,2,65,'2022-01-02'),(5,3,70,'2022-01-01'),(6,3,75,'2022-01-02');
SELECT MAX(emission_log.emission_amount) FROM emission_log JOIN chemical ON emission_log.chemical_id = chemical.chemical_id WHERE chemical.name = 'ChemicalB' AND YEAR(emission_date) = 2022;
Get the total number of volunteer hours served
CREATE TABLE Volunteers(id INT PRIMARY KEY AUTO_INCREMENT,volunteer_name VARCHAR(255),hours_served INT,volunteer_date DATE) INSERT INTO Volunteers (volunteer_name,hours_served,volunteer_date) VALUES ('Juanita Flores',12,'2022-01-01') INSERT INTO Volunteers (volunteer_name,hours_served,volunteer_date) VALUES ('Mohammed Ahmed',15,'2022-02-15') INSERT INTO Volunteers (volunteer_name,hours_served,volunteer_date) VALUES ('Priya Shah',10,'2022-03-30') INSERT INTO Volunteers (volunteer_name,hours_served,volunteer_date) VALUES ('Samir Singh',20,'2022-04-10')
SELECT SUM(hours_served) FROM Volunteers
List all climate adaptation projects and their respective funding allocations for the year 2019.
CREATE TABLE climate_adaptation (project_id INT,project_name TEXT,allocation DECIMAL(10,2),year INT); INSERT INTO climate_adaptation (project_id,project_name,allocation,year) VALUES (4,'Flood Resistance D',8000000,2019),(5,'Drought Resilience E',9000000,2019),(6,'Coastal Protection F',11000000,2019);
SELECT project_name, allocation FROM climate_adaptation WHERE year = 2019;
Insert a new record into the 'decentralized_apps' table with 'app_id' 1001, 'app_name' 'Balancer', 'category' 'DEX', 'platform' 'Ethereum' and 'launch_date' '2020-02-01'
CREATE TABLE decentralized_apps (app_id INT,app_name VARCHAR(50),category VARCHAR(50),platform VARCHAR(50),launch_date DATE);
INSERT INTO decentralized_apps (app_id, app_name, category, platform, launch_date) VALUES (1001, 'Balancer', 'DEX', 'Ethereum', '2020-02-01');
What is the average word count for articles published in the "technology" section in 2017?
CREATE TABLE tech_articles (id INT,article_id INT,tech_topic TEXT,word_count INT); CREATE VIEW tech_summary AS SELECT a.id,a.title,a.section,a.publish_date,AVG(ta.word_count) as avg_word_count FROM website_articles a JOIN tech_articles ta ON a.id = ta.article_id WHERE a.section = 'technology' GROUP BY a.id;
SELECT AVG(avg_word_count) FROM tech_summary WHERE publish_date BETWEEN '2017-01-01' AND '2017-12-31';
What is the number of users registered in each day of the week?
CREATE TABLE user_registrations (registration_date DATE); INSERT INTO user_registrations (registration_date) VALUES ('2021-01-01'),('2021-01-15'),('2021-02-10'),('2021-03-01'),('2021-04-05'),('2021-05-12'),('2021-06-08'),('2021-07-02'),('2021-08-04'),('2021-09-07'),('2021-10-01'),('2021-11-05'),('2021-12-10');
SELECT EXTRACT(DAY FROM registration_date) AS day, COUNT(*) FROM user_registrations GROUP BY day;
How many crimes were reported in District1 of CityZ in 2019?
CREATE TABLE crimes_4 (id INT,city VARCHAR(50),district VARCHAR(50),year INT,crime_count INT); INSERT INTO crimes_4 (id,city,district,year,crime_count) VALUES (1,'CityZ','District1',2019,42),(2,'CityZ','District1',2018,36),(3,'CityAA','District2',2019,44);
SELECT SUM(crime_count) FROM crimes_4 WHERE city = 'CityZ' AND district = 'District1' AND year = 2019;
What is the sum of the total square footage of properties in the 'sustainable_urbanism' view that are located in the city of 'San Francisco'?
CREATE VIEW sustainable_urbanism AS SELECT properties.id,properties.city,SUM(properties.square_footage) as total_square_footage FROM properties JOIN sustainable_developments ON properties.id = sustainable_developments.id GROUP BY properties.id,properties.city; INSERT INTO properties (id,city,square_footage) VALUES (1,'Austin',1800.0),(2,'San Francisco',2200.0),(3,'Seattle',1500.0); INSERT INTO sustainable_developments (id,property_name,low_income_area) VALUES (1,'Green Heights',true),(2,'Eco Estates',false),(3,'Solar Vista',true);
SELECT SUM(total_square_footage) FROM sustainable_urbanism WHERE city = 'San Francisco';
List the names and total costs of all projects that started before 2017 and were completed after 2016.
CREATE TABLE Projects (ProjectID INT,Name VARCHAR(255),StartDate DATE,EndDate DATE,TotalCost DECIMAL(10,2));
SELECT Name, SUM(TotalCost) as TotalCost FROM Projects WHERE StartDate < '2017-01-01' AND EndDate > '2016-12-31' GROUP BY Name;
What was the minimum delivery time for shipments from China to the United States in February 2021?
CREATE TABLE deliveries (id INT,shipment_id INT,delivered_at TIMESTAMP); INSERT INTO deliveries (id,shipment_id,delivered_at) VALUES (1,1,'2021-02-01 12:30:00'),(2,2,'2021-02-28 09:15:00'); CREATE TABLE shipments (id INT,origin VARCHAR(255),destination VARCHAR(255),shipped_at TIMESTAMP); INSERT INTO shipments (id,origin,destination,shipped_at) VALUES (1,'China','United States','2021-01-31 23:59:00'),(2,'China','United States','2021-02-27 23:59:00');
SELECT MIN(TIMESTAMPDIFF(MINUTE, shipped_at, delivered_at)) FROM deliveries D JOIN shipments S ON D.shipment_id = S.id WHERE S.origin = 'China' AND S.destination = 'United States' AND shipped_at >= '2021-02-01' AND shipped_at < '2021-03-01';
What is the average financial wellbeing score of customers in 'TX'?
CREATE TABLE customer_data (id INT,name VARCHAR(20),state VARCHAR(2),score INT); INSERT INTO customer_data (id,name,state,score) VALUES (1,'JohnDoe','CA',75),(2,'JaneDoe','NY',80),(3,'MikeSmith','TX',85),(4,'SaraLee','TX',90);
SELECT AVG(score) FROM customer_data WHERE state = 'TX';
What is the total number of transactions on the Algorand network in the past week?
CREATE TABLE algorand_transactions (transaction_id INT,timestamp TIMESTAMP);
SELECT COUNT(transaction_id) FROM algorand_transactions WHERE timestamp >= NOW() - INTERVAL '1 week';
What is the average delivery time for each route in the route optimization data?
CREATE TABLE route_optimization (id INT,route_id INT,delivery_time INT,distance FLOAT); INSERT INTO route_optimization (id,route_id,delivery_time,distance) VALUES [(1,1001,120,50.0),(2,1002,90,40.0),(3,1003,150,60.0),(4,1004,180,70.0),(5,1005,80,30.0),(6,1006,130,55.0),(7,1007,110,45.0),(8,1008,160,65.0),(9,1009,70,25.0),(10,1010,140,50.0)];
SELECT route_id, AVG(delivery_time) AS avg_delivery_time FROM route_optimization GROUP BY route_id;
How many vessels have traveled between the Port of Mumbai and the Port of Shanghai in the last 6 months?
CREATE TABLE Routes (route_id INT,departure_port VARCHAR(20),arrival_port VARCHAR(20)); CREATE TABLE VesselTravel (vessel_id INT,route INT,departure_date DATE,travel_time INT); INSERT INTO Routes (route_id,departure_port,arrival_port) VALUES (1,'Los Angeles','Tokyo'),(2,'Rotterdam','New York'),(3,'Santos','Hong Kong'),(4,'Mumbai','Shanghai'); INSERT INTO VesselTravel (vessel_id,route,departure_date,travel_time) VALUES (1,1,'2021-01-01',14),(2,1,'2021-02-01',15),(3,1,'2021-03-01',16),(4,4,'2021-04-01',15),(5,4,'2021-05-01',16),(6,4,'2021-06-01',17),(7,4,'2021-07-01',18);
SELECT COUNT(DISTINCT vessel_id) as num_vessels FROM VesselTravel JOIN Routes ON VesselTravel.route = Routes.route_id WHERE Routes.departure_port = 'Mumbai' AND Routes.arrival_port = 'Shanghai' AND VesselTravel.departure_date >= DATEADD(month, -6, GETDATE());
What is the percentage of employees who have completed harassment prevention training, by race?
CREATE TABLE Employees (EmployeeID INT,Race VARCHAR(50)); CREATE TABLE TrainingPrograms (ProgramID INT,ProgramName VARCHAR(50),Completed DATE); CREATE TABLE EmployeeTraining (EmployeeID INT,ProgramID INT);
SELECT e.Race, COUNT(DISTINCT e.EmployeeID) * 100.0 / (SELECT COUNT(DISTINCT EmployeeID) FROM Employees) AS Percentage FROM Employees e INNER JOIN EmployeeTraining et ON e.EmployeeID = et.EmployeeID INNER JOIN TrainingPrograms tp ON et.ProgramID = tp.ProgramID WHERE tp.ProgramName = 'Harassment Prevention Training' GROUP BY e.Race;
What is the total budget for all heritage sites in Africa and how much has been spent on each one?
CREATE TABLE heritage_sites (id INT,site_name TEXT,location TEXT,budget INT); INSERT INTO heritage_sites (id,site_name,location,budget) VALUES (1,'Pyramids of Giza','Egypt',1000000),(2,'Tiwi Islands Sacred Sites','Australia',500000);
SELECT SUM(budget), site_name FROM heritage_sites WHERE location LIKE '%%Africa%%' GROUP BY site_name;
Insert a new mobile plan for the 'Telco Inc.' company.
CREATE TABLE mobile_plans (plan_id INT,plan_name VARCHAR(255),company_name VARCHAR(255),data_limit INT,monthly_cost DECIMAL(10,2));
INSERT INTO mobile_plans (plan_id, plan_name, company_name, data_limit, monthly_cost) VALUES (5, 'Unlimited Data', 'Telco Inc.', 10000, 100.00);
List all climate communication projects in Europe that started after 2012.
CREATE TABLE climate_projects (project_id INT,project_name TEXT,location TEXT,project_type TEXT,start_year INT); INSERT INTO climate_projects (project_id,project_name,location,project_type,start_year) VALUES (1,'Communication 1','France','climate communication',2013),(2,'Mitigation 1','Germany','climate mitigation',2015),(3,'Adaptation 1','Spain','climate adaptation',2010);
SELECT * FROM climate_projects WHERE project_type = 'climate communication' AND location LIKE 'Europe%' AND start_year > 2012;
Delete all intelligence operations in the operations table that were conducted before the year 2000.
CREATE TABLE operations (name TEXT,description TEXT,year INT); INSERT INTO operations (name,description,year) VALUES ('Operation Desert Storm','Military intervention in Iraq.',1991),('Operation Enduring Freedom','Military intervention in Afghanistan.',2001),('Operation Just Cause','Military intervention in Panama.',1989);
DELETE FROM operations WHERE year < 2000;
Insert a new record for 'Metal' with a recycling rate of 60% in 'recycling_rates' table for Q4 2022.
CREATE TABLE recycling_rates (quarter TEXT,material TEXT,rate DECIMAL(3,2)); INSERT INTO recycling_rates (quarter,material,rate) VALUES ('Q1 2021','plastic',0.30),('Q1 2021','paper',0.45),('Q2 2022','plastic',0.31),('Q2 2022','paper',0.46),('Q3 2022','plastic',0.32),('Q3 2022','paper',0.47),('Q4 2022','plastic',NULL),('Q4 2022','paper',NULL);
INSERT INTO recycling_rates (quarter, material, rate) VALUES ('Q4 2022', 'Metal', 0.60);
Find the number of routes that offer only one fare type.
CREATE TABLE RouteFares (RouteID int,FareType varchar(50)); INSERT INTO RouteFares VALUES (1,'Standard'); INSERT INTO RouteFares VALUES (1,'Discounted'); INSERT INTO RouteFares VALUES (2,'Standard'); INSERT INTO RouteFares VALUES (3,'Standard'); INSERT INTO RouteFares VALUES (3,'Discounted'); INSERT INTO RouteFares VALUES (4,'Premium'); INSERT INTO RouteFares VALUES (5,'Standard');
SELECT RouteID FROM RouteFares GROUP BY RouteID HAVING COUNT(DISTINCT FareType) = 1;
Count the number of vessels with safety records violating regulatory compliance
CREATE TABLE Vessels (Id INT,Name VARCHAR(50),Compliance INT); INSERT INTO Vessels (Id,Name,Compliance) VALUES (1,'Vessel1',1),(2,'Vessel2',0),(3,'Vessel3',1),(4,'Vessel4',0);
SELECT COUNT(*) FROM Vessels WHERE Compliance = 0;
What is the average temperature increase in Southeast Asia from 2000 to 2020, rounded to one decimal place, for regions where the number of weather stations is greater than 50?
CREATE TABLE weather_stations (id INT,region VARCHAR(255),num_stations INT,avg_temp FLOAT,year INT); INSERT INTO weather_stations (id,region,num_stations,avg_temp,year) VALUES (1,'Southeast Asia',55,26.3,2000);
SELECT ROUND(AVG(avg_temp), 1) FROM weather_stations WHERE region = 'Southeast Asia' AND num_stations > 50 AND year BETWEEN 2000 AND 2020;
How many members are on each committee?
CREATE TABLE CityCommittees (CommitteeID INT PRIMARY KEY,CommitteeName VARCHAR(50),CommitteeDescription VARCHAR(255)); CREATE TABLE CommitteeMembers (MemberID INT PRIMARY KEY,FirstName VARCHAR(50),LastName VARCHAR(50),CommitteeID INT,FOREIGN KEY (CommitteeID) REFERENCES CityCommittees(CommitteeID)); INSERT INTO CityCommittees (CommitteeID,CommitteeName,CommitteeDescription) VALUES (1,'Public Works Committee','Committee responsible for overseeing city public works'),(2,'Health Committee','Committee responsible for overseeing city health'); INSERT INTO CommitteeMembers (MemberID,FirstName,LastName,CommitteeID) VALUES (1,'Jane','Smith',1),(2,'Michael','Johnson',1),(3,'Sarah','Lee',2);
SELECT CommitteeName, COUNT(*) AS NumberOfMembers FROM CommitteeMembers JOIN CityCommittees ON CommitteeMembers.CommitteeID = CityCommittees.CommitteeID GROUP BY CommitteeName;
What is the average sustainability score of attractions in Canada?
CREATE TABLE Country (Country_ID INT PRIMARY KEY,Country_Name VARCHAR(100)); INSERT INTO Country (Country_ID,Country_Name) VALUES (1,'Canada'); CREATE TABLE Attraction (Attraction_ID INT PRIMARY KEY,Attraction_Name VARCHAR(100),Country_ID INT,Sustainability_Score INT,FOREIGN KEY (Country_ID) REFERENCES Country(Country_ID)); INSERT INTO Attraction (Attraction_ID,Attraction_Name,Country_ID,Sustainability_Score) VALUES (1,'CN Tower',1,85),(2,'Niagara Falls',1,80);
SELECT AVG(Sustainability_Score) FROM Attraction WHERE Country_ID = (SELECT Country_ID FROM Country WHERE Country_Name = 'Canada');
List all workforce development programs and their respective budgets, sorted by budget in descending order.
CREATE TABLE workforce_programs (program_id INT,name TEXT,budget FLOAT); INSERT INTO workforce_programs (program_id,name,budget) VALUES (1,'Apprenticeship Initiative',50000.00),(2,'Skills Training Program',75000.00),(3,'Youth Employment Scheme',120000.00);
SELECT * FROM workforce_programs ORDER BY budget DESC;
Increase the price of all VIP tickets for a specific event by 10%.
CREATE TABLE ticket_types (type_id INT,event_id INT,description VARCHAR(50),price DECIMAL(5,2)); INSERT INTO ticket_types VALUES (1,1,'VIP',100);
UPDATE ticket_types tt SET tt.price = tt.price * 1.1 WHERE tt.type_id = 1 AND tt.event_id = 1;
What is the minimum and maximum number of members in unions in the transportation industry?
CREATE TABLE union_transportation (union_id INT,union_name TEXT,industry TEXT,members INT); INSERT INTO union_transportation (union_id,union_name,industry,members) VALUES (1,'Union S','Transportation',8000),(2,'Union T','Transportation',12000),(3,'Union U','Aerospace',9000);
SELECT MIN(members), MAX(members) FROM union_transportation WHERE industry = 'Transportation';
What is the total capacity of factories located in Texas?
CREATE TABLE factory (id INT,name VARCHAR(255),location VARCHAR(255),capacity INT,renewable_energy BOOLEAN); INSERT INTO factory (id,name,location,capacity,renewable_energy) VALUES (1,'Factory A','Los Angeles',1000,TRUE); INSERT INTO factory (id,name,location,capacity,renewable_energy) VALUES (2,'Factory B','Houston',1500,FALSE); INSERT INTO factory (id,name,location,capacity,renewable_energy) VALUES (3,'Factory C','Denver',800,TRUE);
SELECT SUM(capacity) FROM factory WHERE location = 'Houston';
How many crimes were reported in Oakland in the last month?
CREATE TABLE oakland_crimes (id INT,crime_date DATE,crime_type VARCHAR(20)); INSERT INTO oakland_crimes (id,crime_date,crime_type) VALUES (1,'2022-02-01','Theft'),(2,'2022-02-15','Vandalism');
SELECT COUNT(*) FROM oakland_crimes WHERE crime_date >= DATEADD(month, -1, GETDATE());
Insert a new record into the flu_cases table with a case number of 7007 from the country of Nigeria.
CREATE TABLE flu_cases (id INT,country VARCHAR(255),case_number INT);
INSERT INTO flu_cases (id, country, case_number) VALUES (7, 'Nigeria', 7007);
Which genetic research projects are using biosensor technology?
CREATE SCHEMA if not exists genetics; CREATE TABLE if not exists genetics.projects(project_id INT PRIMARY KEY,name VARCHAR(100),technology VARCHAR(50)); CREATE TABLE if not exists genetics.biosensors(biosensor_id INT PRIMARY KEY,project_id INT,name VARCHAR(100),FOREIGN KEY (project_id) REFERENCES genetics.projects(project_id)); INSERT INTO genetics.projects (project_id,name,technology) VALUES (1,'ProjectX','Genetic Engineering'); INSERT INTO genetics.biosensors (biosensor_id,project_id) VALUES (1,1); INSERT INTO genetics.biosensors (biosensor_id,project_id) VALUES (2,2);
SELECT p.name FROM genetics.projects p JOIN genetics.biosensors b ON p.project_id = b.project_id WHERE p.technology = 'biosensor';
What is the maximum speed of electric vehicles in 'vehicle_sales' table?
CREATE TABLE vehicle_sales (id INT,vehicle_type VARCHAR(20),avg_speed FLOAT,sales INT); INSERT INTO vehicle_sales (id,vehicle_type,avg_speed,sales) VALUES (1,'Tesla Model 3',80.0,50000),(2,'Nissan Leaf',70.0,40000),(3,'Chevrolet Bolt',75.0,30000);
SELECT MAX(avg_speed) FROM vehicle_sales WHERE vehicle_type LIKE '%electric%';
What is the combined capacity of all renewable energy farms (wind and solar) in the 'East' region as of 2022-02-15?
CREATE TABLE wind_farms (id INT,name VARCHAR(50),region VARCHAR(50),capacity FLOAT,efficiency FLOAT); INSERT INTO wind_farms (id,name,region,capacity,efficiency) VALUES (1,'Windfarm B','East',140.5,0.32); CREATE TABLE solar_farms (id INT,name VARCHAR(50),region VARCHAR(50),capacity FLOAT,efficiency FLOAT); INSERT INTO solar_farms (id,name,region,capacity,efficiency) VALUES (1,'Solarfarm B','East',210.4,0.35);
SELECT SUM(capacity) AS total_capacity FROM wind_farms WHERE region = 'East' UNION SELECT SUM(capacity) AS total_capacity FROM solar_farms WHERE region = 'East';
Display the number of concerts by country and artist.
CREATE TABLE CountryArtistConcerts (Country VARCHAR(50),Artist VARCHAR(50),ConcertID INT); INSERT INTO CountryArtistConcerts (Country,Artist,ConcertID) VALUES ('USA','Taylor Swift',1); INSERT INTO CountryArtistConcerts (Country,Artist,ConcertID) VALUES ('USA','BTS',2); INSERT INTO CountryArtistConcerts (Country,Artist,ConcertID) VALUES ('Japan','BTS',3);
SELECT Country, Artist, COUNT(DISTINCT ConcertID) AS ConcertCount FROM CountryArtistConcerts GROUP BY Country, Artist;
What was the market share of a specific drug, 'DrugY', in a specific region, 'North', in the year 2020?
CREATE TABLE market_share (drug_name VARCHAR(50),year INT,region VARCHAR(50),market_share FLOAT); INSERT INTO market_share (drug_name,year,region,market_share) VALUES ('DrugX',2020,'North',0.3),('DrugX',2020,'South',0.25),('DrugX',2020,'East',0.35),('DrugY',2020,'North',0.4),('DrugY',2020,'South',0.45),('DrugY',2020,'East',0.5);
SELECT market_share as drug_market_share FROM market_share WHERE drug_name = 'DrugY' AND region = 'North' AND year = 2020;
Find the average capacity of renewable energy projects in Canada.
CREATE TABLE renewable_projects (id INT PRIMARY KEY,project_name VARCHAR(255),project_location VARCHAR(255),project_type VARCHAR(255),capacity_mw FLOAT); CREATE VIEW canada_projects AS SELECT * FROM renewable_projects WHERE project_location = 'Canada';
SELECT AVG(capacity_mw) FROM canada_projects;
Update the title of all AI safety research papers with 'SafeAI' in the title.
CREATE TABLE ai_safety_papers (year INT,paper_title VARCHAR(255),author_name VARCHAR(255)); INSERT INTO ai_safety_papers (year,paper_title,author_name) VALUES ('2018','SafeAI: A Framework for Safe Artificial Intelligence','John Doe');
UPDATE ai_safety_papers SET paper_title = REPLACE(paper_title, 'SafeAI', 'Safe and Trustworthy AI') WHERE paper_title LIKE '%SafeAI%';
What is the total funding received by research grants in the 'Machine Learning' category in 2021?
CREATE TABLE Grants (ID INT,Category VARCHAR(50),Amount FLOAT,Year INT); INSERT INTO Grants (ID,Category,Amount,Year) VALUES (1,'Machine Learning',700000,2021),(2,'AI',500000,2020);
SELECT SUM(Amount) FROM Grants WHERE Category = 'Machine Learning' AND Year = 2021;
Find the maximum ticket price for country concerts.
CREATE TABLE ConcertTickets (ticket_id INT,genre VARCHAR(20),price DECIMAL(5,2));
SELECT MAX(price) FROM ConcertTickets WHERE genre = 'country';
What is the maximum number of disaster preparedness trainings held in the state of Florida in a single year?
CREATE TABLE DisasterPreparedness (id INT,state VARCHAR(20),year INT,training_count INT);
SELECT MAX(training_count) FROM DisasterPreparedness WHERE state = 'Florida' GROUP BY year;
Which vessels were at the Port of Hamburg in the last week?
CREATE TABLE vessels (vessel_id INT,vessel_name VARCHAR(50),status VARCHAR(50)); CREATE TABLE vessel_movements (movement_id INT,vessel_id INT,port_id INT,movement_date DATE); CREATE TABLE ports (port_id INT,port_name VARCHAR(50),country VARCHAR(50));
SELECT V.vessel_name FROM vessel_movements VM JOIN vessels V ON VM.vessel_id = V.vessel_id JOIN ports P ON VM.port_id = P.port_id WHERE P.port_name = 'Port of Hamburg' AND VM.movement_date >= CURDATE() - INTERVAL 7 DAY;
Update records in the "labor_rights_advocacy" table by setting the "advocacy_type" column to "strike" for the row where the "advocacy_id" is 3
CREATE TABLE labor_rights_advocacy (advocacy_id INT,advocacy_type VARCHAR(10),year INT); INSERT INTO labor_rights_advocacy (advocacy_id,advocacy_type,year) VALUES (1,'lobbying',2021); INSERT INTO labor_rights_advocacy (advocacy_id,advocacy_type,year) VALUES (2,'protest',2022); INSERT INTO labor_rights_advocacy (advocacy_id,advocacy_type,year) VALUES (3,'picketing',2023);
UPDATE labor_rights_advocacy SET advocacy_type = 'strike' WHERE advocacy_id = 3;
What is the maximum temperature in 'Southwest' Africa in the last week, along with the time it occurred?
CREATE TABLE temperature_data (temperature FLOAT,time DATETIME,region VARCHAR(20)); INSERT INTO temperature_data (temperature,time,region) VALUES (35.2,'2022-06-01 12:00:00','Southwest Africa');
SELECT MAX(temperature) as max_temp, time FROM temperature_data WHERE region = 'Southwest Africa' AND time >= DATE_SUB(CURRENT_DATE, INTERVAL 1 WEEK) GROUP BY time LIMIT 1
How many satellites were launched by each country in the satellite_launches table?
CREATE TABLE satellite_launches (country VARCHAR(30),launch_year INT,satellites INT); INSERT INTO satellite_launches VALUES ('USA',1958,1),('USSR',1957,1),('USA',1959,3),('USSR',1960,4),('USA',1961,4),('USSR',1962,3);
SELECT country, COUNT(satellites) OVER (PARTITION BY country) FROM satellite_launches;
What is the total quantity of recycled materials used in accessories production in Italy?
CREATE TABLE Accessories (id INT,name VARCHAR(255),material VARCHAR(255),quantity INT,country VARCHAR(255)); INSERT INTO Accessories (id,name,material,quantity,country) VALUES (1,'Bag','Recycled Nylon',1000,'Italy'); INSERT INTO Accessories (id,name,material,quantity,country) VALUES (2,'Belt','Recycled Leather',500,'Italy');
SELECT SUM(quantity) FROM Accessories WHERE country = 'Italy' AND material LIKE '%Recycled%'
What is the minimum funding amount for companies founded by minorities, in each industry category?
CREATE TABLE company (id INT,name TEXT,founder TEXT,industry TEXT,funding FLOAT); INSERT INTO company (id,name,founder,industry,funding) VALUES (1,'Acme Inc','Minority','Tech',2000000);
SELECT industry, MIN(funding) FROM company WHERE founder LIKE '%Minority%' GROUP BY industry;
What is the total budget allocated to education and health programs in the city of New York?
CREATE TABLE education_programs (name VARCHAR(255),city VARCHAR(255),budget DECIMAL(10,2)); INSERT INTO education_programs (name,city,budget) VALUES ('NYC Public Schools','New York',12000000.00),('CUNY','New York',3000000.00); CREATE TABLE health_programs (name VARCHAR(255),city VARCHAR(255),budget DECIMAL(10,2)); INSERT INTO health_programs (name,city,budget) VALUES ('NYC Health + Hospitals','New York',8000000.00);
SELECT SUM(budget) FROM ( SELECT budget FROM education_programs WHERE city = 'New York' UNION ALL SELECT budget FROM health_programs WHERE city = 'New York' ) AS combined_budgets;
What was the total fare collected from the Red Line on January 3rd, 2022?
CREATE TABLE routes (route_name VARCHAR(255),line_color VARCHAR(255)); INSERT INTO routes (route_name,line_color) VALUES ('Red Line','Red'),('Blue Line','Blue'); CREATE TABLE fares (route_name VARCHAR(255),fare_amount DECIMAL(5,2),collection_date DATE); INSERT INTO fares (route_name,fare_amount,collection_date) VALUES ('Red Line',3.50,'2022-01-03'),('Blue Line',2.75,'2022-01-03');
SELECT SUM(fare_amount) FROM fares INNER JOIN routes ON fares.route_name = routes.route_name WHERE routes.line_color = 'Red' AND fares.collection_date = '2022-01-03';
What is the total quantity of Terbium exported by India to all countries from 2018 to 2020?
CREATE TABLE Terbium_Exports (id INT PRIMARY KEY,year INT,importing_country VARCHAR(20),quantity INT); INSERT INTO Terbium_Exports (id,year,importing_country,quantity) VALUES (1,2018,'USA',50),(2,2019,'USA',60),(3,2020,'USA',70),(4,2018,'Canada',40),(5,2019,'Canada',45),(6,2020,'Canada',50),(7,2018,'Mexico',30),(8,2019,'Mexico',35),(9,2020,'Mexico',40),(10,2018,'India',20),(11,2019,'India',25),(12,2020,'India',30);
SELECT SUM(quantity) FROM Terbium_Exports WHERE exporting_country = 'India' AND year BETWEEN 2018 AND 2020;
Delete investments with an ESG score lower than 3 in the healthcare sector.
CREATE TABLE investments (investment_id INT,sector VARCHAR(50),esg_score INT,investment_date DATE); INSERT INTO investments (investment_id,sector,esg_score,investment_date) VALUES (1,'Healthcare',4,'2022-01-01'),(2,'Healthcare',2,'2022-02-01'),(3,'Healthcare',5,'2022-03-01'),(4,'Healthcare',3,'2022-04-01'),(5,'Healthcare',1,'2022-05-01');
DELETE FROM investments WHERE sector = 'Healthcare' AND esg_score < 3;
What was the average donation amount in each quarter of 2021?
CREATE TABLE Donations (id INT,donation_amount DECIMAL(10,2),transaction_date DATE); INSERT INTO Donations (id,donation_amount,transaction_date) VALUES (1,500,'2021-01-01'),(2,300,'2021-04-15'),(3,700,'2021-07-03'),(4,800,'2021-10-17'),(5,600,'2021-12-02');
SELECT DATE_FORMAT(transaction_date, '%Y-%m') as quarter, AVG(donation_amount) as avg_donation_amount FROM Donations GROUP BY quarter;
Which are the top 5 venues by total value of works exhibited?
CREATE TABLE exhibitions_history (exhibition_history_id INT PRIMARY KEY,work_id INT,exhibition_id INT,sale_price FLOAT,FOREIGN KEY (work_id) REFERENCES works(work_id),FOREIGN KEY (exhibition_id) REFERENCES exhibitions(exhibition_id));
SELECT e.location, SUM(eh.sale_price) AS total_value FROM exhibitions e JOIN exhibitions_history eh ON e.exhibition_id = eh.exhibition_id GROUP BY e.location ORDER BY total_value DESC LIMIT 5;
What is the average budget for climate mitigation projects in Africa?
CREATE TABLE climate_mitigation_projects (project_id INT,project_name VARCHAR(255),location VARCHAR(255),budget DECIMAL(10,2)); INSERT INTO climate_mitigation_projects (project_id,project_name,location,budget) VALUES (1,'Carbon Capture in South Africa','South Africa',4000000.00),(2,'Forest Conservation in Morocco','Morocco',3000000.00),(3,'Clean Transportation in Egypt','Egypt',5000000.00);
SELECT AVG(budget) FROM climate_mitigation_projects WHERE location = 'Africa';
What is the maximum visitor count of a museum?
CREATE TABLE museum_visitors(id INT,museum_name TEXT,country TEXT,visitor_count INT); INSERT INTO museum_visitors (id,museum_name,country,visitor_count) VALUES (1,'British Museum','UK',2000),(2,'Louvre Museum','France',3000),(3,'Metropolitan Museum of Art','USA',4000);
SELECT MAX(visitor_count) FROM museum_visitors;
Identify the top 5 countries with the most returning visitors.
CREATE TABLE Visitors (id INT,country VARCHAR(50),visit_date DATE);
SELECT country, COUNT(DISTINCT id) AS num_returning_visitors FROM Visitors GROUP BY country ORDER BY num_returning_visitors DESC LIMIT 5;
What is the total revenue for each menu category in Location1?
CREATE TABLE menu_engineering(menu_item VARCHAR(255),category VARCHAR(255),location VARCHAR(255),revenue INT); INSERT INTO menu_engineering(menu_item,category,location,revenue) VALUES ('Burger','Meat','Location1',5000),('Fries','Sides','Location1',1000),('Salad','Vegetables','Location1',2000);
SELECT category, SUM(revenue) FROM menu_engineering WHERE location = 'Location1' GROUP BY category;
What are the details of the teachers who have attended professional development workshops in the last year?
CREATE TABLE teachers (id INT,name VARCHAR(255),last_workshop_date DATE); INSERT INTO teachers (id,name,last_workshop_date) VALUES (1,'Teacher A','2021-06-01'),(2,'Teacher B','2020-12-15'),(3,'Teacher C',NULL);
SELECT id, name, last_workshop_date FROM teachers WHERE last_workshop_date >= DATEADD(year, -1, GETDATE());
Find the number of financial institutions offering financial capability programs in the South American region.
CREATE TABLE financial_institutions (institution_id INT,institution_name TEXT,region TEXT,offers_financial_capability BOOLEAN);
SELECT COUNT(institution_id) FROM financial_institutions WHERE region = 'South American' AND offers_financial_capability = TRUE;
List all EVs with total sales greater than 20000
CREATE TABLE ev_data (id INT PRIMARY KEY,model VARCHAR(100),manufacturer VARCHAR(100),year INT,total_sales INT);
SELECT * FROM ev_data WHERE total_sales > 20000;
What is the percentage of mobile and broadband subscribers who are using the latest network technology?
CREATE TABLE mobile_subscribers(id INT,name VARCHAR(50),has_latest_network_technology BOOLEAN); CREATE TABLE broadband_subscribers(id INT,name VARCHAR(50),has_latest_network_technology BOOLEAN);
SELECT 'mobile' as type, AVG(has_latest_network_technology) * 100.0 as pct_latest_mobile FROM mobile_subscribers UNION ALL SELECT 'broadband' as type, AVG(has_latest_network_technology) * 100.0 as pct_latest_broadband FROM broadband_subscribers;
What is the maximum number of employees in each department in the 'Transportation' agency?
CREATE SCHEMA Government;CREATE TABLE Government.Agency (name VARCHAR(255),budget INT);CREATE TABLE Government.Department (name VARCHAR(255),agency VARCHAR(255),employees INT,budget INT);
SELECT agency, MAX(employees) FROM Government.Department WHERE agency IN (SELECT name FROM Government.Agency WHERE budget > 2000000) GROUP BY agency;
What is the total cost of ingredients for each dish in the dinner menu?
CREATE TABLE DinnerIngredients (id INT,dish_id INT,ingredient_id INT,cost INT);
SELECT d.name, SUM(di.cost) FROM DinnerIngredients di INNER JOIN DinnerMenu d ON di.dish_id = d.id GROUP BY d.name;
How many vegan meals are served in the school_cafeteria per day according to the meal_schedule table?
CREATE TABLE meal_schedule (meal_name TEXT,vegan_meal BOOLEAN,servings_per_day INTEGER); INSERT INTO meal_schedule (meal_name,vegan_meal,servings_per_day) VALUES ('Veggie Wrap',true,150),('Chicken Sandwich',false,200),('Lentil Soup',true,120);
SELECT SUM(servings_per_day) FROM meal_schedule WHERE vegan_meal = true;
What is the average number of experiments conducted per mission by SpaceX in the astrobiology_experiments and mission_data tables?
CREATE TABLE astrobiology_experiments (experiment_id INT,name VARCHAR(100),spacecraft VARCHAR(100),launch_date DATE,experiments_conducted INT); CREATE TABLE mission_data (mission_id INT,name VARCHAR(100),organization VARCHAR(100),launch_date DATE,mission_cost FLOAT);
SELECT AVG(experiments_conducted/1.0) FROM astrobiology_experiments, mission_data WHERE astrobiology_experiments.spacecraft = mission_data.name AND mission_data.organization = 'SpaceX';
What is the percentage of videos with captions from indigenous creators in North America and Oceania, in the last year?
CREATE TABLE videos (id INT,title VARCHAR(50),has_captions BOOLEAN,creator_name VARCHAR(50),creator_region VARCHAR(50)); INSERT INTO videos (id,title,has_captions,creator_name,creator_region) VALUES (1,'Video1',true,'Maria Garcia','North America'),(2,'Video2',false,'David Kim','Oceania'),(3,'Video3',true,'Emily Chen','North America'),(4,'Video4',true,'James Thompson','Oceania');
SELECT creator_region, 100.0 * COUNT(CASE WHEN has_captions = true THEN 1 END) / COUNT(*) as pct FROM videos WHERE creator_region IN ('North America', 'Oceania') AND post_date >= NOW() - INTERVAL 365 DAY AND creator_name IN (SELECT name FROM creators WHERE is_indigenous = true) GROUP BY creator_region;
What is the average word count for articles about underrepresented communities in the past month?
CREATE TABLE Articles (article_id INT,title VARCHAR(255),topic VARCHAR(255),word_count INT,publication_date DATE); INSERT INTO Articles (article_id,title,topic,word_count,publication_date) VALUES (1,'Article1','underrepresented communities',800,'2022-05-01'),(2,'Article2','media literacy',1200,'2022-03-15'),(3,'Article3','disinformation detection',900,'2022-04-20');
SELECT AVG(word_count) FROM Articles WHERE topic = 'underrepresented communities' AND publication_date >= DATE_SUB(CURDATE(), INTERVAL 1 MONTH);
Find the top 5 clients with the highest account balance across all regions.
CREATE TABLE clients (client_id INT,name VARCHAR(50),region VARCHAR(20),account_balance DECIMAL(10,2)); INSERT INTO clients (client_id,name,region,account_balance) VALUES (1,'John Smith','West',30000.00),(2,'Jane Doe','Northeast',22000.00),(3,'Mike Johnson','West',35000.00),(4,'Sara Jones','Southeast',12000.00),(5,'William Brown','Northeast',25000.00),(6,'Emily Davis','Southeast',40000.00),(7,'Olivia Thompson','Northwest',50000.00),(8,'James Wilson','Southwest',28000.00);
SELECT client_id, name, account_balance FROM clients ORDER BY account_balance DESC LIMIT 5;
Show the number of job applications submitted by gender from the "applications" and "applicant" tables
CREATE TABLE applications (id INT,application_id INT,submission_date DATE); CREATE TABLE applicant (id INT,application_id INT,gender TEXT);
SELECT applicant.gender, COUNT(*) as count FROM applications JOIN applicant ON applications.application_id = applicant.application_id GROUP BY applicant.gender;
Insert a new record in the "accessibility_features" table for "Closed Captioning" with a description of "Closed captions for hearing-impaired users" and platform as "Television"
CREATE TABLE accessibility_features (name TEXT,description TEXT,platform TEXT);
INSERT INTO accessibility_features (name, description, platform) VALUES ('Closed Captioning', 'Closed captions for hearing-impaired users', 'Television');
What is the count of new hires who identify as non-binary in Q3 2022?
CREATE TABLE Employees (EmployeeID INT,Gender VARCHAR(20),HireDate DATE); INSERT INTO Employees (EmployeeID,Gender,HireDate) VALUES (1,'Non-binary','2022-07-15'); INSERT INTO Employees (EmployeeID,Gender,HireDate) VALUES (2,'Male','2022-08-01');
SELECT COUNT(*) FROM Employees WHERE Gender = 'Non-binary' AND HireDate BETWEEN '2022-07-01' AND '2022-09-30';
Create a view named "student_count_by_gender" that shows the total number of male and female students in each department
CREATE TABLE departments (department_id INT,department_name VARCHAR(20)); INSERT INTO departments (department_id,department_name) VALUES (1,'Computer Science'),(2,'Mathematics'),(3,'Physics'); CREATE TABLE students (student_id INT,name VARCHAR(50),gender VARCHAR(10),department_VARCHAR(20),enrollment_date DATE);
CREATE VIEW student_count_by_gender AS SELECT d.department_name, SUM(CASE WHEN s.gender = 'Male' THEN 1 ELSE 0 END) AS male_count, SUM(CASE WHEN s.gender = 'Female' THEN 1 ELSE 0 END) AS female_count FROM departments d LEFT JOIN students s ON d.department_name = s.department GROUP BY d.department_name;
How many items were sold per month in the 'Accessories' category?
CREATE TABLE monthly_sales (id INT PRIMARY KEY,sale_date DATE,product_category VARCHAR(255),quantity INT); INSERT INTO monthly_sales (id,sale_date,product_category,quantity) VALUES (1,'2021-12-01','Accessories',15); INSERT INTO monthly_sales (id,sale_date,product_category,quantity) VALUES (2,'2021-12-05','Accessories',8);
SELECT MONTH(sale_date) as sale_month, SUM(quantity) as total_quantity_sold FROM monthly_sales WHERE product_category = 'Accessories' GROUP BY sale_month;
What is the average cost of public transportation improvements in 'Chicago' that were completed in 2019?
CREATE TABLE public_transportation (id INT,project_name TEXT,location TEXT,cost INT,completion_date DATE); INSERT INTO public_transportation (id,project_name,location,cost,completion_date) VALUES (1,'Chicago L Line','Chicago',30000000,'2019-03-23'); INSERT INTO public_transportation (id,project_name,location,cost,completion_date) VALUES (2,'Chicago Subway Extension','Chicago',40000000,'2019-11-08');
SELECT AVG(cost) FROM public_transportation WHERE location = 'Chicago' AND YEAR(completion_date) = 2019;
How many energy storage projects were announced in India in 2022?
CREATE TABLE EnergyStorageProjects (Country VARCHAR(255),Year INT,Project VARCHAR(255),Status VARCHAR(255)); INSERT INTO EnergyStorageProjects (Country,Year,Project,Status) VALUES ('India',2022,'Project A','Completed'),('India',2022,'Project B','In Progress'),('India',2022,'Project C','Announced'),('India',2022,'Project D','Cancelled'),('India',2022,'Project E','Announced'),('India',2022,'Project F','In Progress');
SELECT COUNT(*) AS NumberOfProjects FROM EnergyStorageProjects WHERE Country = 'India' AND Year = 2022 AND Status = 'Announced';
Which artist has the largest artwork in the database?
CREATE TABLE Artworks (ArtworkID INT,Title VARCHAR(50),Gallery VARCHAR(50),ArtistID INT,Size INT); INSERT INTO Artworks (ArtworkID,Title,Gallery,ArtistID,Size) VALUES (1,'Starry Night','ImpressionistGallery',1,100); INSERT INTO Artworks (ArtworkID,Title,Gallery,ArtistID,Size) VALUES (2,'Sunflowers','ImpressionistGallery',1,200); INSERT INTO Artworks (ArtworkID,Title,Gallery,ArtistID,Size) VALUES (3,'Untitled','ContemporaryArt',2,150); INSERT INTO Artworks (ArtworkID,Title,Gallery,ArtistID,Size) VALUES (4,'Untitled2','ContemporaryArt',2,50); INSERT INTO Artworks (ArtworkID,Title,Gallery,ArtistID,Size) VALUES (5,'Untitled3','ContemporaryArt',3,300);
SELECT ArtistID, MAX(Size) as MaxSize FROM Artworks GROUP BY ArtistID;
Update product transparency ratings based on a weighted average
CREATE TABLE products(product_id INT,transparency_rating INT,production_process_rating INT,supply_chain_rating INT,labor_practices_rating INT); INSERT INTO products(product_id,transparency_rating,production_process_rating,supply_chain_rating,labor_practices_rating) VALUES (1,80,85,90,70),(2,85,90,80,95),(3,90,80,85,90),(4,75,85,90,80);
UPDATE products SET transparency_rating = (production_process_rating + supply_chain_rating + labor_practices_rating) / 3 WHERE product_id = 1;
What is the minimum duration of space missions led by astronauts from Russia?
CREATE TABLE space_missions(id INT,mission_name VARCHAR(50),leader_name VARCHAR(50),leader_country VARCHAR(50),duration INT); INSERT INTO space_missions VALUES(1,'Vostok 1','Yuri Gagarin','Russia',108.),(2,'Soyuz 11','Vladimir Shatalov','Russia',241.);
SELECT MIN(duration) FROM space_missions WHERE leader_country = 'Russia';
What is the average retail price per gram of Sativa strains sold in California dispensaries in Q1 2022?
CREATE TABLE strains (type VARCHAR(10),price DECIMAL(5,2)); INSERT INTO strains (type,price) VALUES ('Sativa',12.50),('Sativa',15.00),('Indica',10.50);
SELECT AVG(price) FROM strains WHERE type = 'Sativa' AND price IS NOT NULL;
What is the maximum and minimum number of games released per year for the 'Puzzle' genre?
CREATE TABLE puzzle_games (puzzle_games_id INT,game_id INT,genre VARCHAR(50),year INT,sales DECIMAL(10,2)); INSERT INTO puzzle_games VALUES (1,1,'Puzzle',2018,5000.00),(2,2,'Puzzle',2019,6000.00),(3,3,'Puzzle',2020,7000.00),(4,4,'Puzzle',2021,8000.00),(5,5,'Puzzle',2018,4000.00),(6,6,'Puzzle',2019,3000.00);
SELECT genre, MIN(year) as min_year, MAX(year) as max_year, MIN(sales) as min_sales, MAX(sales) as max_sales FROM puzzle_games WHERE genre = 'Puzzle' GROUP BY genre;
Identify the renewable energy projects that do not intersect with carbon offset initiatives in South America.
CREATE TABLE renewable_energy (project_id INT,project_name TEXT,location TEXT); CREATE TABLE carbon_offsets (project_id INT,initiative_name TEXT,location TEXT); INSERT INTO renewable_energy (project_id,project_name,location) VALUES (1,'Solar Field One','South America'),(2,'Wind Farm Two','North America'); INSERT INTO carbon_offsets (project_id,initiative_name,location) VALUES (1,'Tropical Forest Protection','South America'),(3,'Ocean Current Capture','Europe');
SELECT project_name FROM renewable_energy WHERE project_id NOT IN (SELECT project_id FROM carbon_offsets WHERE renewable_energy.location = carbon_offsets.location);