instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
Identify the number of rural hospitals that have increased their bed count by at least 10% in the past year.
CREATE TABLE hospitals (id INT,beds INT,location VARCHAR(20),year INT,increase BOOLEAN); INSERT INTO hospitals (id,beds,location,year,increase) VALUES (1,50,'rural',2021,true),(2,200,'urban',2021,false),(3,75,'rural',2020,false);
SELECT COUNT(*) FROM hospitals WHERE location LIKE '%rural%' AND increase = true AND year = YEAR(GETDATE()) - 1 AND beds * 1.1 <= (SELECT beds FROM hospitals WHERE location = 'rural' AND year = YEAR(GETDATE()) - 2);
Show the number of green bond issuances for each country and the total value of green bonds issued for each country.
CREATE TABLE green_bonds (id INT,issuer_country VARCHAR(255),issue_year INT,value FLOAT); INSERT INTO green_bonds (id,issuer_country,issue_year,value) VALUES (1,'USA',2017,3000000),(2,'China',2018,4000000),(3,'Germany',2017,2000000),(4,'USA',2018,5000000),(5,'India',2019,1000000),(6,'Brazil',2019,2000000),(7,'Canada',2018,1500000);
SELECT issuer_country, COUNT(*) as num_issuances, SUM(value) as total_value FROM green_bonds GROUP BY issuer_country;
What is the average budget allocated to cybersecurity operations in Asia?
CREATE TABLE cybersecurity_budget (id INT,year INT,amount INT,country TEXT); INSERT INTO cybersecurity_budget (id,year,amount,country) VALUES (1,2020,5000000,'China'),(2,2020,6000000,'Japan'),(3,2019,4000000,'India');
SELECT AVG(amount) FROM cybersecurity_budget WHERE country IN ('China', 'Japan', 'India') AND year = 2020;
Find the number of unique artists per concert.
CREATE TABLE ArtistConcert (ConcertID INT,Artist VARCHAR(50)); INSERT INTO ArtistConcert (ConcertID,Artist) VALUES (1,'Taylor Swift'); INSERT INTO ArtistConcert (ConcertID,Artist) VALUES (1,'Ed Sheeran'); INSERT INTO ArtistConcert (ConcertID,Artist) VALUES (2,'BTS');
SELECT ConcertID, COUNT(DISTINCT Artist) AS ArtistCount FROM ArtistConcert GROUP BY ConcertID;
What was the total number of volunteers who engaged in environmental programs in 2022?
CREATE TABLE EnvironmentalPrograms (Volunteer VARCHAR(50),Program VARCHAR(50),VolunteerDate DATE); INSERT INTO EnvironmentalPrograms (Volunteer,Program,VolunteerDate) VALUES ('Jamal Williams','Tree Planting','2022-03-12'),('Priya Patel','Beach Cleanup','2022-08-01');
SELECT Program, COUNT(DISTINCT Volunteer) as TotalVolunteers FROM EnvironmentalPrograms WHERE VolunteerDate BETWEEN '2022-01-01' AND '2022-12-31' AND Program LIKE '%Environment%' GROUP BY Program;
What is the average salary of employees who have completed training on unconscious bias?
CREATE TABLE Employees (EmployeeID INT,Gender VARCHAR(10),Department VARCHAR(20),Salary FLOAT,Training VARCHAR(50)); INSERT INTO Employees (EmployeeID,Gender,Department,Salary,Training) VALUES (1,'Male','IT',75000,'Unconscious Bias'),(2,'Female','IT',70000,'Diversity and Inclusion'),(3,'Male','HR',60000,'Unconscious Bias'),(4,'Female','HR',65000,'Unconscious Bias');
SELECT AVG(Salary) FROM Employees WHERE Training = 'Unconscious Bias';
What is the total training cost for the first half of 2022?
CREATE TABLE Trainings (TrainingID int,TrainingDate date,Cost decimal(10,2)); INSERT INTO Trainings (TrainingID,TrainingDate,Cost) VALUES (1,'2022-01-15',500.00),(2,'2022-04-01',1000.00),(3,'2022-07-01',300.00);
SELECT SUM(Cost) FROM Trainings WHERE TrainingDate BETWEEN '2022-01-01' AND '2022-06-30';
Which diversity programs are currently being participated in by employees in the HR department?
CREATE TABLE Employees (Employee_ID INT,First_Name VARCHAR(20),Last_Name VARCHAR(20),Department VARCHAR(20),Salary DECIMAL(10,2),Date_Hired DATE); CREATE TABLE Diversity_Programs (Program_ID INT,Program_Name VARCHAR(50),Participant_ID INT,Date_Started DATE,Date_Ended DATE);
SELECT dp.Program_Name FROM Diversity_Programs dp JOIN Employees e ON dp.Participant_ID = e.Employee_ID WHERE e.Department = 'HR' AND dp.Date_Ended IS NULL;
What is the average budget allocated for ethical AI research by country?
CREATE TABLE Country (CountryID INT PRIMARY KEY,CountryName VARCHAR(100),Budget DECIMAL(10,2)); INSERT INTO Country (CountryID,CountryName,Budget) VALUES (1,'USA',5000000.00),(2,'Canada',3000000.00),(3,'Mexico',1000000.00);
SELECT AVG(Budget) as AvgBudget, CountryName FROM Country GROUP BY CountryName;
Delete the record for the 'bus' service on January 3, 2022 from the 'revenue' table.
CREATE TABLE revenue (service text,date date,amount int); INSERT INTO revenue (service,date,amount) VALUES ('subway','2022-01-01',5000),('bus','2022-01-02',6000),('subway','2022-01-03',7000);
DELETE FROM revenue WHERE service = 'bus' AND date = '2022-01-03';
What is the earliest and latest time a 'train' departs from a station on the 'NQRW' line?
CREATE TABLE station (id INT,name TEXT,line TEXT); INSERT INTO station (id,name,line) VALUES (1,'Times Square','NQRW'),(2,'34th Street','BDFM'); CREATE TABLE train_schedule (id INT,station_id INT,train_type TEXT,departure_time TIME); INSERT INTO train_schedule (id,station_id,train_type,departure_time) VALUES (1,1,'N','06:00:00'),(2,1,'Q','06:02:00'),(3,1,'R','06:04:00'),(4,1,'W','06:06:00'),(5,2,'N','06:01:00'),(6,2,'Q','06:03:00'),(7,2,'R','06:05:00'),(8,2,'W','06:07:00');
SELECT MIN(departure_time) as earliest_departure, MAX(departure_time) as latest_departure FROM train_schedule WHERE station_id = 1 AND train_type = 'N' OR station_id = 2 AND train_type = 'N';
What is the fare for 'adult' passengers in the 'blue' line?
CREATE TABLE fares (line VARCHAR(10),passenger_type VARCHAR(10),fare FLOAT); INSERT INTO fares (line,passenger_type,fare) VALUES ('red','adult',2.50),('red','child',1.50),('blue','adult',3.00),('blue','child',2.00),('green','adult',3.50),('green','child',2.50);
SELECT fare FROM fares WHERE line = 'blue' AND passenger_type = 'adult';
What is the maximum fare for a bus in the 'south' region?
CREATE TABLE Buses (id INT,region VARCHAR(10)); INSERT INTO Buses (id,region) VALUES (1,'west'),(2,'east'),(3,'south'); CREATE TABLE Fares (id INT,bus_id INT,fare DECIMAL(5,2)); INSERT INTO Fares (id,bus_id,fare) VALUES (1,1,5.00),(2,1,5.00),(3,2,4.50),(4,3,6.00);
SELECT MAX(Fares.fare) FROM Fares INNER JOIN Buses ON Fares.bus_id = Buses.id WHERE Buses.region = 'south';
What is the total distance traveled for all buses in the London transit system in the past week?
CREATE TABLE london_buses (bus_id INT,daily_distance FLOAT,date DATE);
SELECT SUM(daily_distance) FROM london_buses WHERE date >= DATE_SUB(NOW(), INTERVAL 1 WEEK);
List the top 3 most popular garment sizes, based on quantity sold, for each gender, from the 'sales_data' view.
CREATE VIEW sales_data AS SELECT o.order_id,c.customer_gender,g.garment_size,g.garment_type,g.price,g.quantity FROM orders o JOIN customers c ON o.customer_id = c.customer_id JOIN order_items oi ON o.order_id = oi.order_id JOIN garments g ON oi.garment_id = g.garment_id;
SELECT customer_gender, garment_size, SUM(quantity) AS total_quantity FROM sales_data GROUP BY customer_gender, garment_size HAVING total_quantity IN (SELECT MAX(total_quantity) FROM (SELECT customer_gender, garment_size, SUM(quantity) AS total_quantity FROM sales_data GROUP BY customer_gender, garment_size) sub WHERE sub.customer_gender = sales_data.customer_gender) LIMIT 3;
What is the average account balance for clients in the Islamic Banking segment?
CREATE TABLE islamic_banking_clients (client_id INT,segment VARCHAR(20),account_balance DECIMAL(10,2)); INSERT INTO islamic_banking_clients (client_id,segment,account_balance) VALUES (1,'Islamic Banking',15000.00),(2,'Conventional Banking',20000.00),(3,'Islamic Banking',12000.00);
SELECT AVG(account_balance) FROM islamic_banking_clients WHERE segment = 'Islamic Banking';
Find the top 3 countries with the highest total donation amount.
CREATE TABLE donor_data (id INT,donor_country VARCHAR,total_donation_amount DECIMAL);
SELECT donor_country, SUM(total_donation_amount) as total_donation_amount FROM donor_data GROUP BY donor_country ORDER BY total_donation_amount DESC LIMIT 3;
What is the maximum weight of packages shipped from the Mexico City warehouse to each destination province?
CREATE TABLE Packages (id INT,warehouse_id INT,destination_province TEXT,weight FLOAT); INSERT INTO Packages (id,warehouse_id,destination_province,weight) VALUES (13,19,'BC',92.5),(14,19,'ON',110.2),(15,19,'QC',76.8); CREATE TABLE Warehouses (id INT,name TEXT,city TEXT,state TEXT); INSERT INTO Warehouses (id,name,city,state) VALUES (19,'Mexico City Warehouse','Mexico City','MX');
SELECT destination_province, MAX(weight) FROM Packages JOIN Warehouses ON Packages.warehouse_id = Warehouses.id WHERE Warehouses.name = 'Mexico City Warehouse' GROUP BY destination_province;
What is the maximum budget for a genetic research project in the 'GeneticResearch' schema?
CREATE SCHEMA GeneticResearch; CREATE TABLE project_budgets (project_name VARCHAR(50),budget DECIMAL(10,2)); INSERT INTO project_budgets VALUES ('Project1',600000),('Project2',900000);
SELECT MAX(budget) FROM GeneticResearch.project_budgets;
What is the average income of residents in each city in the state of California, grouped by city and ordered by average income in descending order?
CREATE TABLE cities (id INT PRIMARY KEY,name TEXT,state TEXT); INSERT INTO cities (id,name,state) VALUES (1,'Los Angeles','California'),(2,'San Diego','California'),(3,'San Jose','California'); CREATE TABLE incomes (id INT PRIMARY KEY,city_id INT,income INT); INSERT INTO incomes (id,city_id,income) VALUES (1,1,50000),(2,1,70000),(3,2,45000),(4,2,60000),(5,3,48000),(6,3,52000);
SELECT c.name, AVG(i.income) FROM cities c JOIN incomes i ON c.id = i.city_id WHERE c.state = 'California' GROUP BY c.name ORDER BY AVG(i.income) DESC;
What is the count of initiatives for each department that have a budget greater than the average budget for all initiatives in the "initiatives" table?
CREATE TABLE department (id INT,name TEXT);CREATE TABLE initiatives (id INT,department_id INT,budget INT);
SELECT department.name, COUNT(initiatives.id) FROM department JOIN initiatives ON department.id = initiatives.department_id WHERE initiatives.budget > (SELECT AVG(budget) FROM initiatives) GROUP BY department.name;
Delete faculty members who have been with the university for less than 5 years.
CREATE TABLE faculty (id INT PRIMARY KEY,name VARCHAR(50),department VARCHAR(50),years_of_service INT);
DELETE FROM faculty WHERE years_of_service < 5;
Determine the average engagement time for virtual tours in each city.
CREATE TABLE virtual_tours (tour_id INT,city TEXT,engagement_time FLOAT); INSERT INTO virtual_tours (tour_id,city,engagement_time) VALUES (1,'Tokyo',15.5),(2,'Tokyo',12.3),(3,'Osaka',18.1);
SELECT city, AVG(engagement_time) FROM virtual_tours GROUP BY city;
What is the virtual tour engagement rate for the top 2 countries with the highest engagement rates, ordered by engagement rate in descending order?
CREATE TABLE virtual_tours (tour_id INT,hotel_name TEXT,country TEXT,engagement_rate FLOAT); INSERT INTO virtual_tours (tour_id,hotel_name,country,engagement_rate) VALUES (1,'Hotel A','USA',0.06),(2,'Hotel B','Canada',0.08),(3,'Hotel C','Mexico',0.05),(4,'Hotel D','USA',0.07);
SELECT country, engagement_rate FROM (SELECT country, engagement_rate, RANK() OVER (ORDER BY engagement_rate DESC) as rank FROM virtual_tours) as subquery WHERE rank <= 2 ORDER BY engagement_rate DESC;
Delete all records from the 'species' table where the 'region' column is 'Antarctica'
CREATE TABLE species (id INT PRIMARY KEY,species_name VARCHAR(255),region VARCHAR(255)); INSERT INTO species (id,species_name,region) VALUES (1,'penguin','Antarctica'),(2,'seal','Arctic');
DELETE FROM species WHERE region = 'Antarctica';
List the species in the 'arctic_biodiversity' table and their conservation status from the 'iucn_greenlist' table, if available.
CREATE TABLE arctic_biodiversity (species_id INT,species_name VARCHAR(255),population INT,region VARCHAR(255)); CREATE TABLE iucn_greenlist (species_id INT,conservation_status VARCHAR(255));
SELECT a.species_name, g.conservation_status FROM arctic_biodiversity a LEFT JOIN iucn_greenlist g ON a.species_id = g.species_id;
What is the average population of cities with a UNESCO World Heritage designation, ordered by designation date?
CREATE TABLE cities (name VARCHAR(255),population INT,designation_date DATE); INSERT INTO cities (name,population,designation_date) VALUES ('Paris',2141000,'1991-09-16'); INSERT INTO cities (name,population,designation_date) VALUES ('Rio de Janeiro',6727000,'2012-07-01');
SELECT AVG(population) FROM (SELECT population, ROW_NUMBER() OVER (ORDER BY designation_date) rn FROM cities WHERE name IN (SELECT name FROM heritagesites)) t WHERE rn % 2 = 1;
What is the average age of patients who received psychodynamic therapy?
CREATE TABLE patients (patient_id INT,age INT,treatment VARCHAR(20)); INSERT INTO patients (patient_id,age,treatment) VALUES (1,32,'psychodynamic therapy'),(2,45,'psychodynamic therapy'),(3,50,'CBT');
SELECT AVG(age) FROM patients WHERE treatment = 'psychodynamic therapy';
What are the names and budgets of all public works projects in California, along with the name of the engineer in charge, sorted by budget in descending order?
CREATE TABLE public_works_projects (project_id INT,name VARCHAR(50),budget DECIMAL(10,2),state VARCHAR(2)); CREATE TABLE project_engineers (engineer_id INT,project_id INT,name VARCHAR(50));
SELECT pwp.name, pwp.budget, pe.name AS engineer_name FROM public_works_projects pwp INNER JOIN project_engineers pe ON pwp.project_id = pe.project_id WHERE pwp.state = 'CA' ORDER BY pwp.budget DESC;
Update the number of tourists who visited Egypt in 2022 due to the increase in travel after the pandemic.
CREATE TABLE tourism_stats (country VARCHAR(255),year INT,visitors INT,continent VARCHAR(255)); INSERT INTO tourism_stats (country,year,visitors,continent) VALUES ('Egypt',2022,3000000,'Africa');
UPDATE tourism_stats SET visitors = 4000000 WHERE country = 'Egypt' AND year = 2022;
How many access to justice cases were resolved through mediation in New York in 2020?
CREATE TABLE cases (case_id INT,resolution_type VARCHAR(20),resolution_date DATE,city VARCHAR(20)); INSERT INTO cases (case_id,resolution_type,resolution_date,city) VALUES (1,'Mediation','2020-01-01','New York'); INSERT INTO cases (case_id,resolution_type,resolution_date,city) VALUES (2,'Litigation','2019-01-01','Los Angeles');
SELECT COUNT(*) FROM cases WHERE resolution_type = 'Mediation' AND resolution_date BETWEEN '2020-01-01' AND '2020-12-31' AND city = 'New York';
How many legal aid clinics are there in each state in the justice_schemas.legal_aid_clinics table, including the District of Columbia?
CREATE TABLE justice_schemas.legal_aid_clinics (id INT PRIMARY KEY,clinic_name TEXT,state TEXT);
SELECT state, COUNT(*) FROM justice_schemas.legal_aid_clinics GROUP BY state;
How many legal aid clinics are there in the state of New York, and how many clients have they served in the past year?
CREATE TABLE legal_aid_clinics (clinic_id INT,state VARCHAR(255),clients_served INT); INSERT INTO legal_aid_clinics (clinic_id,state,clients_served) VALUES (1,'New York',500); INSERT INTO legal_aid_clinics (clinic_id,state,clients_served) VALUES (2,'California',700);
SELECT state, COUNT(clinic_id) as num_clinics, SUM(clients_served) as total_clients_served FROM legal_aid_clinics WHERE state = 'New York' AND YEAR(date_served) = YEAR(CURRENT_DATE()) - 1 GROUP BY state;
Which marine species were observed in the Southern Ocean in the last 30 days?
CREATE TABLE marine_species_observations (species_name TEXT,observation_date DATE,location TEXT); INSERT INTO marine_species_observations VALUES ('Krill','2023-02-10','Southern Ocean'),('Blue Whale','2023-01-25','Southern Ocean'),('Krill','2023-03-01','Southern Ocean');
SELECT species_name FROM marine_species_observations WHERE observation_date >= DATEADD(day, -30, CURRENT_DATE) AND location = 'Southern Ocean' GROUP BY species_name;
What is the average weight of locally sourced fruits in the dessert menu?
CREATE TABLE DessertIngredients (ingredient VARCHAR(50),source VARCHAR(20),weight DECIMAL(5,2)); INSERT INTO DessertIngredients (ingredient,source,weight) VALUES ('Strawberries','Local',2.00),('Blueberries','Local',1.50),('Bananas','Local',3.00);
SELECT AVG(weight) FROM DessertIngredients WHERE source = 'Local';
What is the minimum production volume in 'Asia' for the year 2017?'
CREATE TABLE mines (id INT,name TEXT,location TEXT,production_volume INT,product TEXT,year INT); INSERT INTO mines (id,name,location,production_volume,product,year) VALUES (1,'Emerald Explorer Mine','Asia',1000,'Emerald',2017); INSERT INTO mines (id,name,location,production_volume,product,year) VALUES (2,'Sapphire Summit Mine','Asia',1500,'Sapphire',2017);
SELECT MIN(production_volume) FROM mines WHERE location = 'Asia' AND year = 2017;
Delete the environmental impact stats for the 'Turquoise Trail' mine in Inner Mongolia, China from the "environmental_impact" table
CREATE TABLE environmental_impact (mine_id INT,year INT,co2_emissions INT,water_consumption INT,waste_generation INT);
DELETE FROM environmental_impact WHERE mine_id = 10 AND year = 2020;
What is the number of accidents in mining operations in India and Argentina, and the total number of employees in those operations?
CREATE TABLE mining_operations (id INT,country VARCHAR(20),operation_name VARCHAR(30),accidents INT,total_employees INT); INSERT INTO mining_operations (id,country,operation_name,accidents,total_employees) VALUES (1,'India','Operation P',5,150); INSERT INTO mining_operations (id,country,operation_name,accidents,total_employees) VALUES (2,'India','Operation Q',3,200); INSERT INTO mining_operations (id,country,operation_name,accidents,total_employees) VALUES (3,'Argentina','Operation R',4,120);
SELECT country, SUM(accidents) AS total_accidents, SUM(total_employees) AS total_employees FROM mining_operations WHERE country IN ('India', 'Argentina') GROUP BY country;
What is the percentage of total revenue from streaming and concert ticket sales for Pop music in 2018?
CREATE TABLE StreamingRevenue (id INT,year INT,genre VARCHAR(50),revenue FLOAT); CREATE TABLE ConcertTicketSales (id INT,year INT,genre VARCHAR(50),revenue FLOAT);
SELECT (SUM(sr.revenue) + SUM(cts.revenue)) / (SELECT SUM(revenue) FROM (SELECT revenue FROM StreamingRevenue WHERE year = 2018 UNION ALL SELECT revenue FROM ConcertTicketSales WHERE year = 2018) t) FROM StreamingRevenue sr JOIN ConcertTicketSales cts ON sr.genre = cts.genre WHERE sr.year = 2018 AND sr.genre = 'Pop';
Update the age for audience member with id 1 to 40
CREATE TABLE audience (id INT,age INT,gender VARCHAR(10)); INSERT INTO audience (id,age,gender) VALUES (1,35,'Female');
UPDATE audience SET age = 40 WHERE id = 1;
What is the total number of articles published per day for a specific author?
CREATE TABLE articles (article_id INT,author VARCHAR(50),title VARCHAR(100),category VARCHAR(50),publication_date DATE);
SELECT publication_date, COUNT(article_id) AS articles_per_day FROM articles WHERE author = 'John Doe' GROUP BY publication_date ORDER BY publication_date;
Find the number of unique donors who made donations in both January and February in the 'Donations' table.
CREATE TABLE Donations (DonationID INT,DonorID INT,DonationDate DATE);
SELECT COUNT(DISTINCT DonorID) AS UniqueDonors FROM Donations WHERE EXTRACT(MONTH FROM DonationDate) IN (1, 2) GROUP BY DonorID HAVING COUNT(DISTINCT EXTRACT(MONTH FROM DonationDate)) = 2;
What are the deep-sea expeditions that overlap with marine protected areas?
CREATE TABLE Expeditions (id INT PRIMARY KEY,name VARCHAR(50),location VARCHAR(50),start_date DATE,end_date DATE); CREATE TABLE Protected_Areas (id INT PRIMARY KEY,name VARCHAR(50),location VARCHAR(50),size FLOAT,protection_level VARCHAR(50));
SELECT Expeditions.name FROM Expeditions INNER JOIN Protected_Areas ON Expeditions.location = Protected_Areas.location WHERE Expeditions.start_date <= Protected_Areas.protection_level AND Expeditions.end_date >= Protected_Areas.protection_level;
What is the average performance score for each game genre?
CREATE TABLE game_genre_performance (game_id INT,game_genre VARCHAR(255),performance_score INT); INSERT INTO game_genre_performance (game_id,game_genre,performance_score) VALUES (1,'RPG',85),(2,'Strategy',90),(3,'RPG',80);
SELECT game_genre, AVG(performance_score) as avg_score FROM game_genre_performance GROUP BY game_genre;
What is the percentage of users who have reached level 10 in "Cosmic Explorers" for each continent?
CREATE TABLE PlayerProgress (PlayerID INT,GameName VARCHAR(20),Level INT,Completion BOOLEAN,PlayerContinent VARCHAR(30)); INSERT INTO PlayerProgress (PlayerID,GameName,Level,Completion,PlayerContinent) VALUES (1,'Cosmic Explorers',10,true,'North America'),(2,'Cosmic Explorers',10,true,'Europe'),(3,'Cosmic Explorers',10,false,'North America'),(4,'Cosmic Explorers',10,true,'South America'),(5,'Cosmic Explorers',10,false,'Europe'),(6,'Cosmic Explorers',10,true,'Asia'),(7,'Cosmic Explorers',10,false,'Asia'),(8,'Cosmic Explorers',10,true,'Africa');
SELECT PlayerContinent, COUNT(*) FILTER (WHERE Completion) * 100.0 / SUM(COUNT(*)) OVER (PARTITION BY PlayerContinent) AS pct_completion FROM PlayerProgress WHERE GameName = 'Cosmic Explorers' AND Level = 10 GROUP BY PlayerContinent;
List all the unique soil types and corresponding satellite image acquisition dates for 'Field2'?
CREATE TABLE Field2 (soil_type VARCHAR(50),image_date DATETIME); INSERT INTO Field2 (soil_type,image_date) VALUES ('Loamy','2021-07-05 14:30:00'),('Sandy','2021-07-06 09:15:00');
SELECT DISTINCT soil_type, image_date FROM Field2;
What percentage of renewable energy projects in 2020 were completed by companies based in India?
CREATE TABLE projects_company_location (project_id INT,completion_year INT,company_location VARCHAR(50)); INSERT INTO projects_company_location (project_id,completion_year,company_location) VALUES (1,2020,'India'),(2,2019,'Australia'),(3,2020,'US'),(4,2018,'India'),(5,2020,'Germany'),(6,2017,'Brazil');
SELECT (COUNT(*) FILTER (WHERE company_location = 'India' AND completion_year = 2020)) * 100.0 / COUNT(*) FROM projects_company_location;
What are the total sales for each product category in descending order?
CREATE TABLE sales(product_id INT,quarter INT,sales INT); INSERT INTO sales(product_id,quarter,sales) VALUES (1,1,100),(1,2,120),(2,1,75),(2,2,90); CREATE TABLE products(product_id INT,category TEXT);
SELECT category, SUM(sales) AS total_sales FROM sales JOIN products ON sales.product_id = products.product_id GROUP BY category ORDER BY total_sales DESC;
What is the average price of vegan products in the USA?
CREATE TABLE vendors (vendor_id INT,vendor_name TEXT,country TEXT);CREATE TABLE products (product_id INT,product_name TEXT,price DECIMAL,vegan BOOLEAN,vendor_id INT); INSERT INTO vendors (vendor_id,vendor_name,country) VALUES (1,'VendorA','USA'),(2,'VendorB','Canada'); INSERT INTO products (product_id,product_name,price,vegan,vendor_id) VALUES (1,'ProductA',25.99,true,1),(2,'ProductB',18.49,false,1),(3,'ProductC',22.99,true,2);
SELECT AVG(price) FROM products JOIN vendors ON products.vendor_id = vendors.vendor_id WHERE vegan = true AND country = 'USA';
How many countries have launched a spacecraft?
CREATE TABLE Country_Spacecraft (Country VARCHAR(50),Spacecraft_Name VARCHAR(100)); INSERT INTO Country_Spacecraft (Country,Spacecraft_Name) VALUES ('USA','Crew Dragon'),('Russia','Soyuz');
SELECT COUNT(DISTINCT Country) FROM Country_Spacecraft;
Find the total number of medical issues reported by female astronauts
CREATE TABLE Medical_Records(astronaut_id INT,year INT,medical_issues INT); CREATE TABLE Astronauts(astronaut_id INT,astronaut_name VARCHAR(30),gender VARCHAR(6)); INSERT INTO Medical_Records(astronaut_id,year,medical_issues) VALUES (1,2016,2),(1,2017,0),(1,2018,3),(2,2016,1),(2,2017,1),(2,2018,2),(3,2016,0),(3,2017,0),(3,2018,1); INSERT INTO Astronauts(astronaut_id,astronaut_name,gender) VALUES (1,'Neil Armstrong','male'),(2,'Buzz Aldrin','male'),(3,'Mary Jackson','female');
SELECT SUM(Medical_Records.medical_issues) FROM Medical_Records INNER JOIN Astronauts ON Medical_Records.astronaut_id = Astronauts.astronaut_id WHERE Astronauts.gender = 'female';
Update the 'battery_range' to 300 for 'ElectricCar' with 'vehicle_id' 1 in the 'Vehicles' table
CREATE TABLE Vehicles (vehicle_id INT,vehicle_type VARCHAR(20),battery_range INT); INSERT INTO Vehicles (vehicle_id,vehicle_type,battery_range) VALUES (1,'ElectricCar',200),(2,'HybridTruck',500),(3,'ElectricTruck',150);
UPDATE Vehicles SET battery_range = 300 WHERE vehicle_id = 1 AND vehicle_type = 'ElectricCar';
What is the number of electric trams in service in Istanbul in 2021?
CREATE TABLE electric_trams (tram_id INT,service_date DATE,in_service INT); INSERT INTO electric_trams (tram_id,service_date,in_service) VALUES (1,'2021-01-01',1),(2,'2021-01-02',1),(3,'2021-01-03',0);
SELECT COUNT(*) FROM electric_trams WHERE in_service = 1 AND service_date BETWEEN '2021-01-01' AND '2021-12-31';
What is the total number of trips taken on public transportation in Tokyo and Seoul?
CREATE TABLE public_transportation (trip_id INT,city VARCHAR(20),trips INT); INSERT INTO public_transportation (trip_id,city,trips) VALUES (1,'Tokyo',500000),(2,'Tokyo',600000),(3,'Seoul',400000),(4,'Seoul',300000);
SELECT city, SUM(trips) FROM public_transportation GROUP BY city;
What is the percentage of workplaces with successful collective bargaining in the manufacturing sector?
CREATE TABLE workplaces (id INT,name TEXT,location TEXT,sector TEXT,total_employees INT,union_members INT,successful_cb BOOLEAN,cb_year INT);
SELECT (COUNT(*) * 100.0 / (SELECT COUNT(*) FROM workplaces WHERE sector = 'manufacturing')) AS percentage FROM workplaces WHERE sector = 'manufacturing' AND successful_cb = TRUE;
What is the average speed of vehicles in 'Auto Show' table grouped by vehicle type?
CREATE TABLE Auto_Show (show_id INT,vehicle_type VARCHAR(20),avg_speed FLOAT);
SELECT vehicle_type, AVG(avg_speed) FROM Auto_Show GROUP BY vehicle_type;
Delete all records related to vessels that have not complied with emission regulations in the Port of Los Angeles in 2021.
CREATE TABLE vessels (id INT,name TEXT,type TEXT,emission_compliance BOOLEAN); INSERT INTO vessels (id,name,type,emission_compliance) VALUES (1,'Vessel C','Cargo',false); INSERT INTO vessels (id,name,type,emission_compliance) VALUES (2,'Vessel D','Tanker',true); CREATE TABLE port_visits (id INT,vessel_id INT,port_name TEXT,visit_date DATE); INSERT INTO port_visits (id,vessel_id,port_name,visit_date) VALUES (1,1,'Los Angeles','2021-03-15'); INSERT INTO port_visits (id,vessel_id,port_name,visit_date) VALUES (2,2,'Los Angeles','2021-07-22');
DELETE FROM vessels WHERE id NOT IN (SELECT vessel_id FROM port_visits WHERE port_name = 'Los Angeles' AND visit_date BETWEEN '2021-01-01' AND '2021-12-31' AND id IN (SELECT id FROM vessels WHERE emission_compliance = true));
Show vessels that have transported only one type of cargo.
CREATE TABLE Vessel_Cargo (Vessel_ID INT,Cargo_Type VARCHAR(255),Region VARCHAR(255)); INSERT INTO Vessel_Cargo (Vessel_ID,Cargo_Type,Region) VALUES (1,'Grain','Pacific'),(2,'Containers','Atlantic'),(3,'Oil','Pacific'),(4,'Vehicles','Atlantic'),(5,'Coal','Indian'),(6,'Grain','Pacific'),(7,'Oil','Arctic');
SELECT Vessel_ID FROM (SELECT Vessel_ID, COUNT(DISTINCT Cargo_Type) AS num_cargo_types FROM Vessel_Cargo GROUP BY Vessel_ID) WHERE num_cargo_types = 1;
What is the average speed of all vessels that have a maximum speed greater than 25 knots?
CREATE TABLE vessels (vessel_id INT,vessel_name VARCHAR(50),max_speed DECIMAL(5,2)); INSERT INTO vessels (vessel_id,vessel_name,max_speed) VALUES (1,'Ocean Wave',30.5),(2,'Marine Star',24.3),(3,'River Queen',15.6);
SELECT AVG(max_speed) FROM vessels WHERE max_speed > 25;
Find the maximum age of visitors who attended exhibitions in Tokyo?
CREATE TABLE Exhibitions (exhibition_id INT,city VARCHAR(20)); INSERT INTO Exhibitions (exhibition_id,city) VALUES (1,'New York'),(2,'Los Angeles'),(3,'Chicago'),(4,'Paris'),(5,'Tokyo'); CREATE TABLE Visitors (visitor_id INT,exhibition_id INT,age INT); INSERT INTO Visitors (visitor_id,exhibition_id,age) VALUES (1,1,30),(2,1,35),(3,2,25),(4,2,28),(5,3,40),(6,3,45),(8,5,50),(9,5,55);
SELECT MAX(age) FROM Visitors v JOIN Exhibitions e ON v.exhibition_id = e.exhibition_id WHERE e.city = 'Tokyo';
How many visitors attended the Art of the Renaissance exhibition in the first week of January 2022?
CREATE TABLE exhibitions (exhibition_id INT,name VARCHAR(255)); INSERT INTO exhibitions (exhibition_id,name) VALUES (1,'Art of the Renaissance'); CREATE TABLE visitors (visitor_id INT,exhibition_id INT,visit_date DATE); INSERT INTO visitors (visitor_id,exhibition_id,visit_date) VALUES (1,1,'2022-01-01'),(2,1,'2022-01-02'),(3,1,'2022-01-03'),(4,1,'2022-01-05');
SELECT COUNT(visitor_id) as num_visitors FROM visitors WHERE exhibition_id = 1 AND visit_date >= '2022-01-01' AND visit_date <= '2022-01-07';
What was the total number of community events attended by visitors in each age group?
CREATE TABLE visitor_attendance (visitor_id INT,age_group VARCHAR(10),event_name VARCHAR(50)); INSERT INTO visitor_attendance (visitor_id,age_group,event_name) VALUES (1,'Adult','Art Festival'),(2,'Child','Art Exhibition'),(3,'Senior','History Day');
SELECT age_group, COUNT(*) as num_events FROM visitor_attendance GROUP BY age_group;
Identify the water conservation initiatives in Texas.
CREATE TABLE water_conservation_initiatives(state VARCHAR(20),initiative VARCHAR(50)); INSERT INTO water_conservation_initiatives(state,initiative) VALUES ('Texas','Rainwater harvesting'),('Texas','Greywater recycling'),('Texas','Smart irrigation systems');
SELECT initiative FROM water_conservation_initiatives WHERE state = 'Texas';
What is the average water consumption per residential user in the last month?
CREATE TABLE user_water_consumption (user_id INT,user_category VARCHAR(20),consumption FLOAT,consumption_date DATE); INSERT INTO user_water_consumption (user_id,user_category,consumption,consumption_date) VALUES (1,'residential',150,'2022-03-01'),(2,'commercial',250,'2022-03-01'),(3,'residential',160,'2022-03-02'),(4,'commercial',240,'2022-03-02');
SELECT AVG(consumption) FROM user_water_consumption WHERE user_category = 'residential' AND consumption_date >= DATEADD(month, -1, GETDATE());
What is the average safety score for creative AI applications by region?
CREATE TABLE CreativeAI (app_name TEXT,region TEXT,safety_score FLOAT); INSERT INTO CreativeAI (app_name,region,safety_score) VALUES ('App1','NA',85.0),('App2','NA',92.0),('App3','EU',88.0),('App4','ASIA',90.0);
SELECT region, AVG(safety_score) avg_safety_score FROM CreativeAI GROUP BY region;
What is the average cost of rural infrastructure projects in the province of Balochistan, Pakistan, by project type and year?
CREATE TABLE projects_pakistan_balochistan (project_id INT,province TEXT,project_type TEXT,year INT,cost FLOAT); INSERT INTO projects_pakistan_balochistan (project_id,province,project_type,year,cost) VALUES (1,'Balochistan','Roads',2018,600000),(2,'Balochistan','Bridges',2019,800000),(3,'Balochistan','Irrigation',2020,700000);
SELECT project_type, year, AVG(cost) as avg_cost FROM projects_pakistan_balochistan WHERE province = 'Balochistan' GROUP BY project_type, year;
What is the number of women-led agricultural businesses in the 'business_data' table?
CREATE TABLE business_data (business_id INT,business_name VARCHAR(50),gender VARCHAR(10)); INSERT INTO business_data (business_id,business_name,gender) VALUES (1,'Green Acres','female'),(2,'Brown Farms','male'),(3,'Eco Harvest','non-binary');
SELECT COUNT(business_id) FROM business_data WHERE gender = 'female';
What is the total number of satellites launched by SpaceX and ROSCOSMOS?
CREATE TABLE spacex_satellites (satellite_id INT,name VARCHAR(255),launch_date DATE);CREATE TABLE roscosmos_satellites (satellite_id INT,name VARCHAR(255),launch_date DATE);
SELECT COUNT(*) FROM spacex_satellites WHERE name = 'SpaceX';SELECT COUNT(*) FROM roscosmos_satellites WHERE name = 'ROSCOSMOS';
What is the total number of animals that have been released into 'protected' habitats, and the average weight of those animals?
CREATE TABLE habitats (habitat_id INT,habitat_name VARCHAR(50),habitat_status VARCHAR(50)); INSERT INTO habitats (habitat_id,habitat_name,habitat_status) VALUES (1,'Habitat A','protected'),(2,'Habitat B','unprotected'); CREATE TABLE animal_habitats (animal_id INT,habitat_id INT,animal_weight FLOAT); INSERT INTO animal_habitats (animal_id,habitat_id,animal_weight) VALUES (101,1,25.5),(102,2,15.2); CREATE TABLE animals (animal_id INT,animal_name VARCHAR(50)); INSERT INTO animals (animal_id,animal_name) VALUES (101,'Dog'),(102,'Cat');
SELECT COUNT(*), AVG(animal_habitats.animal_weight) FROM animal_habitats INNER JOIN animals ON animal_habitats.animal_id = animals.animal_id INNER JOIN habitats ON animal_habitats.habitat_id = habitats.habitat_id WHERE habitats.habitat_status = 'protected';
Insert a new record for a salmon farm in the Arctic Ocean with an ID of 5 and a water temperature of 5.2 degrees Celsius in February.
CREATE TABLE ArcticSalmonFarms (ID INT,Name TEXT,Location TEXT,WaterTemp DECIMAL(5,2));
INSERT INTO ArcticSalmonFarms (ID, Name, Location, WaterTemp) VALUES (5, 'Farm H', 'Arctic Ocean', 5.2);
What is the maximum dissolved oxygen level for Salmon farms in the Pacific Ocean?
CREATE TABLE Farm (FarmID int,FarmName varchar(50),Location varchar(50),WaterTemperature numeric,DissolvedOxygenLevel numeric); INSERT INTO Farm (FarmID,FarmName,Location,WaterTemperature,DissolvedOxygenLevel) VALUES (1,'Farm A','Pacific Ocean',15,8.5); INSERT INTO Farm (FarmID,FarmName,Location,WaterTemperature,DissolvedOxygenLevel) VALUES (2,'Farm B','Atlantic Ocean',18,7.8); INSERT INTO Farm (FarmID,FarmName,Location,WaterTemperature,DissolvedOxygenLevel) VALUES (3,'Farm C','Pacific Ocean',14,8.3); INSERT INTO Farm (FarmID,FarmName,Location,WaterTemperature,DissolvedOxygenLevel) VALUES (4,'Farm D','Indian Ocean',20,6.9);
SELECT MAX(DissolvedOxygenLevel) FROM Farm WHERE Location = 'Pacific Ocean' AND FishSpecies = 'Salmon';
Insert a new event 'Painting Class' in the 'Art' category with funding of 8000
CREATE TABLE Events (EventID INT,Category VARCHAR(50),FundingReceived DECIMAL(10,2));
INSERT INTO Events (EventID, Category, FundingReceived) VALUES (3, 'Art', 8000);
Hourly revenue for a specific movie?
CREATE TABLE Movie_Revenue (id INT,movie_title VARCHAR(100),revenue_time TIME,revenue DECIMAL(10,2));
SELECT revenue_time, SUM(revenue) FROM Movie_Revenue WHERE movie_title = 'Spider-Man: No Way Home' GROUP BY revenue_time;
What is the total revenue generated by music albums released in the year 2019?
CREATE TABLE albums (id INT,title TEXT,release_year INT,revenue INT); INSERT INTO albums (id,title,release_year,revenue) VALUES (1,'Album 1',2018,5000000),(2,'Album 2',2019,7000000),(3,'Album 3',2017,6000000),(4,'Album 4',2019,8000000);
SELECT SUM(albums.revenue) FROM albums WHERE albums.release_year = 2019;
What is the average square footage of green-certified buildings in the Northeast, ranked by the highest average?
CREATE TABLE Buildings (BuildingID int,Region varchar(20),GreenCertified bit,SquareFootage decimal(10,2)); INSERT INTO Buildings (BuildingID,Region,GreenCertified,SquareFootage) VALUES (1,'Northeast',1,50000.00),(2,'Midwest',0,75000.00),(3,'Northeast',1,60000.00);
SELECT AVG(SquareFootage) as Avg_SqFt, Region FROM Buildings WHERE Region = 'Northeast' AND GreenCertified = 1 GROUP BY Region ORDER BY Avg_SqFt DESC;
List all clients with a first name starting with 'J'
CREATE TABLE clients (client_id INT,first_name VARCHAR(50),last_name VARCHAR(50)); INSERT INTO clients (client_id,first_name,last_name) VALUES (1,'John','Doe'),(2,'Jane','Smith');
SELECT * FROM clients WHERE first_name LIKE 'J%';
What is the total billing amount for cases handled by attorneys in the 'New York' office?
CREATE TABLE attorneys (attorney_id INT,name TEXT,office TEXT); INSERT INTO attorneys (attorney_id,name,office) VALUES (1,'Smith','New York'),(2,'Johnson','Los Angeles'),(3,'Williams','New York'); CREATE TABLE cases (case_id INT,attorney_id INT,billing_amount INT); INSERT INTO cases (case_id,attorney_id,billing_amount) VALUES (1,1,5000),(2,2,6000),(3,3,3000),(4,3,4000);
SELECT SUM(billing_amount) FROM cases INNER JOIN attorneys ON cases.attorney_id = attorneys.attorney_id WHERE attorneys.office = 'New York';
How many climate finance projects were completed in '2020' from the 'finance_projects' table?
CREATE TABLE finance_projects (id INT PRIMARY KEY,name VARCHAR(255),location VARCHAR(255),description TEXT,start_date DATE,end_date DATE,budget FLOAT); INSERT INTO finance_projects (id,name,location,description,start_date,end_date,budget) VALUES (1,'Green Bonds Issuance','London','Financing green infrastructure projects','2017-01-01','2019-12-31',5000000),(2,'Climate Fundraising Event','Paris','Fundraising event for climate change','2020-01-01','2020-12-31',800000);
SELECT COUNT(*) FROM finance_projects WHERE end_date >= '2020-01-01' AND start_date <= '2020-12-31';
Rank drugs based on the total number of clinical trials since 2010.
CREATE TABLE clinical_trials (drug_name TEXT,year INTEGER,trial_count INTEGER);
SELECT drug_name, SUM(trial_count) OVER (PARTITION BY drug_name ORDER BY SUM(trial_count) DESC) AS total_trials FROM clinical_trials WHERE year >= 2010 GROUP BY 1 ORDER BY 2;
What are the total sales figures for 'Humira' in all regions, excluding Japan?
CREATE TABLE drug_sales (drug_name TEXT,region TEXT,revenue FLOAT); INSERT INTO drug_sales (drug_name,region,revenue) VALUES ('Humira','US',4000000),('Humira','Japan',1000000),('Humira','EU',3000000);
SELECT SUM(revenue) FROM drug_sales WHERE drug_name = 'Humira' AND region NOT IN ('Japan');
How many startups were founded by women in each country in 2021?
CREATE TABLE startups(id INT,name TEXT,country TEXT,founder_gender TEXT,founding_year INT); INSERT INTO startups(id,name,country,founder_gender,founding_year) VALUES (1,'StartupA','USA','Female',2021),(2,'StartupB','Canada','Male',2020),(3,'StartupC','USA','Female',2021),(4,'StartupD','Mexico','Female',2019),(5,'StartupE','Brazil','Male',2020);
SELECT country, founder_gender, COUNT(*) as num_startups FROM startups WHERE founding_year = 2021 GROUP BY country, founder_gender;
Add a new crop 'amaranth' to farm 'Nourishing Harvest' with yield 50 in 2023
CREATE TABLE farms (id INT,name TEXT,location TEXT,size FLOAT); INSERT INTO farms (id,name,location,size) VALUES (1,'Nourishing Harvest','Mexico',120.0); CREATE TABLE crops (id INT,farm_id INT,crop TEXT,yield INT,year INT);
INSERT INTO crops (id, farm_id, crop, yield, year) VALUES (5, (SELECT id FROM farms WHERE name = 'Nourishing Harvest'), 'amaranth', 50, 2023);
Which support programs were offered in a specific state in the past 6 months?
CREATE TABLE SupportPrograms (ProgramID INT,ProgramName VARCHAR(50),State VARCHAR(50)); INSERT INTO SupportPrograms (ProgramID,ProgramName,State) VALUES (1,'Tutoring','New York'); INSERT INTO SupportPrograms (ProgramID,ProgramName,State) VALUES (2,'Mentoring','California');
SELECT ProgramName FROM SupportPrograms WHERE State = 'New York' AND Date BETWEEN DATEADD(month, -6, GETDATE()) AND GETDATE();
What is the average depth of all marine protected areas, grouped by region?
CREATE TABLE marine_protected_areas (id INT,name VARCHAR(255),depth FLOAT,area_size INT,region VARCHAR(255)); INSERT INTO marine_protected_areas (id,name,depth,area_size,region) VALUES (1,'Galapagos Islands',2000,15000,'South America'); INSERT INTO marine_protected_areas (id,name,depth,area_size,region) VALUES (2,'Great Barrier Reef',100,344400,'Australia'); INSERT INTO marine_protected_areas (id,name,depth,area_size,region) VALUES (3,'Palau Protected Areas',250,193000,'Micronesia');
SELECT region, AVG(depth) FROM marine_protected_areas GROUP BY region;
What is the maximum sea surface temperature in the 'Indian' gyre?
CREATE TABLE gyres (name TEXT,max_temp REAL); INSERT INTO gyres (name,max_temp) VALUES ('North Atlantic',21.5),('South Atlantic',20.3),('Indian',28.2),('North Pacific',16.1),('South Pacific',19.9);
SELECT max_temp FROM gyres WHERE name = 'Indian';
Identify the number of wildlife species present in each forest type.
CREATE TABLE forestry.wildlife (species VARCHAR(50),forest_type VARCHAR(50)); INSERT INTO forestry.wildlife (species,forest_type) VALUES ('Bear','Temperate Rainforest'),('Deer','Temperate Deciduous Forest'),('Moose','Boreal Forest');
SELECT forest_type, COUNT(species) FROM forestry.wildlife GROUP BY forest_type;
List all wildlife species observed in subtropical forests since 2016, along with the number of times each species has been observed.
CREATE TABLE subtropical_wildlife (id INT,species VARCHAR(50),year INT,region VARCHAR(20));
SELECT species, region, COUNT(*) as total_observations FROM subtropical_wildlife WHERE region = 'Subtropical' AND year >= 2016 GROUP BY species, region;
Which cruelty-free certified products use ingredients sourced from Canada?
CREATE TABLE products (product_id INT,product_name TEXT,is_cruelty_free BOOLEAN); CREATE TABLE ingredient_sources (ingredient_id INT,product_id INT,source_country TEXT);
SELECT products.product_name FROM products INNER JOIN ingredient_sources ON products.product_id = ingredient_sources.product_id WHERE products.is_cruelty_free = TRUE AND ingredient_sources.source_country = 'Canada';
Which ingredients were sourced from Brazil and used in products launched after 2019-01-01?
CREATE TABLE ingredients (ingredient_id INT,ingredient_name TEXT,sourcing_country TEXT); CREATE TABLE products (product_id INT,product_name TEXT,launch_date DATE); CREATE TABLE product_ingredients (product_id INT,ingredient_id INT);
SELECT ingredient_name FROM ingredients JOIN product_ingredients ON ingredients.ingredient_id = product_ingredients.ingredient_id JOIN products ON product_ingredients.product_id = products.product_id WHERE sourcing_country = 'Brazil' AND launch_date > '2019-01-01';
Update 'Sonia Gupta''s favorite product to 'Vegan Mascara' in the 'India' table?
CREATE TABLE consumer_preferences (consumer_id INT,country VARCHAR(50),favorite_product VARCHAR(100)); INSERT INTO consumer_preferences (consumer_id,country,favorite_product) VALUES (1,'United States','Nourishing Face Cream'),(2,'India','Hydrating Face Mask');
UPDATE consumer_preferences SET favorite_product = 'Vegan Mascara' WHERE consumer_id = 2 AND country = 'India';
What is the percentage of vegan haircare products in the overall haircare product sales?
CREATE TABLE haircare_sales (product_vegan BOOLEAN,sales_quantity INT); INSERT INTO haircare_sales (product_vegan,sales_quantity) VALUES (TRUE,300),(FALSE,700);
SELECT (SUM(CASE WHEN product_vegan = TRUE THEN sales_quantity ELSE 0 END) / SUM(sales_quantity)) * 100 AS vegan_percentage FROM haircare_sales;
What is the total number of police officers and firefighters in the city of New York?
CREATE TABLE nyc_police_officers (id INT,officer_name VARCHAR(255),officer_type VARCHAR(255)); INSERT INTO nyc_police_officers (id,officer_name,officer_type) VALUES (1,'James Brown','Detective'); CREATE TABLE nyc_firefighters (id INT,firefighter_name VARCHAR(255),firefighter_type VARCHAR(255)); INSERT INTO nyc_firefighters (id,firefighter_name,firefighter_type) VALUES (1,'Sarah Johnson','Fire Captain');
SELECT COUNT(*) FROM nyc_police_officers UNION ALL SELECT COUNT(*) FROM nyc_firefighters;
List countries involved in peacekeeping operations?
CREATE TABLE IF NOT EXISTS peacekeeping_operations (id INT PRIMARY KEY,country VARCHAR(255));
SELECT DISTINCT country FROM peacekeeping_operations;
How many customers have a balance greater than $1000 in their investment accounts?
CREATE TABLE investment_accounts (account_id INT,customer_id INT,balance DECIMAL(10,2)); INSERT INTO investment_accounts (account_id,customer_id,balance) VALUES (1,1,1500.00),(2,1,500.00),(3,2,800.00);
SELECT COUNT(DISTINCT customers.customer_id) FROM customers JOIN investment_accounts ON customers.customer_id = investment_accounts.customer_id WHERE investment_accounts.balance > 1000;
Update the risk level to 'high' for customers living in the North region with an age greater than 50.
CREATE TABLE Customers (CustomerID int,Name varchar(50),Age int,PostalCode varchar(10),Region varchar(50),RiskLevel varchar(10)); INSERT INTO Customers (CustomerID,Name,Age,PostalCode,Region,RiskLevel) VALUES (1,'Jane Smith',55,'D4E5F6','North','medium');
UPDATE Customers SET RiskLevel = 'high' WHERE Age > 50 AND Region = 'North';
Which ports have handled cargo with a weight above a certain threshold?
CREATE TABLE ports (id INT,name VARCHAR(255),location VARCHAR(255),operated_by VARCHAR(255)); CREATE TABLE cargo (id INT,port_id INT,weight INT); INSERT INTO ports (id,name,location,operated_by) VALUES (1,'Port A','New York','Company A'),(2,'Port B','Los Angeles','Company B'); INSERT INTO cargo (id,port_id,weight) VALUES (1,1,5000),(2,1,7000),(3,2,3000);
SELECT ports.name FROM ports INNER JOIN cargo ON ports.id = cargo.port_id WHERE cargo.weight > 5000;
What is the maximum waste generated by a factory in the 'electronics' department?
CREATE TABLE factories (factory_id INT,department VARCHAR(20),waste_generated_kg INT); INSERT INTO factories VALUES (1,'textiles',500),(2,'metalwork',300),(3,'textiles',700),(4,'electronics',400),(5,'textiles',600),(6,'electronics',800),(7,'textiles',900),(8,'metalwork',1000),(9,'electronics',1100),(10,'metalwork',1200);
SELECT department, MAX(waste_generated_kg) FROM factories WHERE department = 'electronics' GROUP BY department;
What is the total number of employees working in factories that have a production output above 5000 units and are located in the United States?
CREATE TABLE factories (factory_id INT,name VARCHAR(100),location VARCHAR(100),production_output INT); CREATE TABLE employees (employee_id INT,factory_id INT,name VARCHAR(100),position VARCHAR(100)); INSERT INTO factories (factory_id,name,location,production_output) VALUES (1,'ABC Factory','New York',5500),(2,'XYZ Factory','California',4000),(3,'LMN Factory','Texas',6000); INSERT INTO employees (employee_id,factory_id,name,position) VALUES (1,1,'John Doe','Engineer'),(2,1,'Jane Smith','Manager'),(3,2,'Mike Johnson','Operator'),(4,3,'Sara Brown','Engineer');
SELECT COUNT(*) FROM factories INNER JOIN employees ON factories.factory_id = employees.factory_id WHERE factories.production_output > 5000 AND factories.location LIKE '%United States%';
What is the average number of rural health clinics per state in Africa, and how many states have more than 50 rural health clinics?
CREATE TABLE rural_health_clinics (clinic_id INT,clinic_name VARCHAR(100),state VARCHAR(50),num_staff INT); INSERT INTO rural_health_clinics (clinic_id,clinic_name,state,num_staff) VALUES (1,'Clinic A','Nigeria',40),(2,'Clinic B','Nigeria',50),(3,'Clinic C','Kenya',35),(4,'Clinic D','Kenya',60);
SELECT AVG(num_staff) AS avg_rural_clinics_per_state, COUNT(*) FILTER (WHERE num_staff > 50) AS states_with_more_than_50_clinics FROM ( SELECT state, COUNT(*) AS num_staff FROM rural_health_clinics GROUP BY state ) subquery;
What was the total amount of social impact investments made by 'Green Capital' in Q1 2021?
CREATE TABLE investments (id INT,investor VARCHAR(255),amount FLOAT,date DATE); INSERT INTO investments (id,investor,amount,date) VALUES (1,'Green Capital',50000,'2021-01-15'); INSERT INTO investments (id,investor,amount,date) VALUES (2,'Green Capital',75000,'2021-01-20');
SELECT SUM(amount) FROM investments WHERE investor = 'Green Capital' AND date BETWEEN '2021-01-01' AND '2021-03-31';