instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
What are the names and ranks of the highest-ranking personnel in each service?
CREATE TABLE MilitaryPersonnel (id INT,name VARCHAR(100),rank VARCHAR(50),service VARCHAR(50)); INSERT INTO MilitaryPersonnel (id,name,rank,service) VALUES (1,'John Doe','Colonel','Air Force'); INSERT INTO MilitaryPersonnel (id,name,rank,service) VALUES (2,'Jane Smith','Captain','Navy'); INSERT INTO MilitaryPersonnel (id,name,rank,service) VALUES (3,'Robert Johnson','General','Army'); INSERT INTO MilitaryPersonnel (id,name,rank,service) VALUES (4,'Emily Davis','Lieutenant General','Marines');
SELECT name, rank, service FROM MilitaryPersonnel WHERE rank IN (SELECT MAX(rank) FROM MilitaryPersonnel GROUP BY service);
Calculate the percentage of cargo weight that is container cargo for each flag state.
CREATE TABLE FLAG_STATE_CARGO (ID INT,FLAG_STATE_ID INT,CARGO_TYPE VARCHAR(50),WEIGHT INT); INSERT INTO FLAG_STATE_CARGO VALUES (1,1,'Container',1000000); INSERT INTO FLAG_STATE_CARGO VALUES (2,2,'Bulk',5000000);
SELECT F.NAME AS FLAG_STATE, ROUND(100.0 * SUM(CASE WHEN FSC.CARGO_TYPE = 'Container' THEN FSC.WEIGHT ELSE 0 END) / SUM(FSC.WEIGHT), 2) AS PERCENTAGE FROM FLAG_STATE_CARGO FSC JOIN FLAG_STATES F ON FSC.FLAG_STATE_ID = F.ID GROUP BY F.ID, F.NAME
What is the average playtime for female players in RPG games?
CREATE TABLE PlayerInfo (PlayerID INT,Gender VARCHAR(50),GameType VARCHAR(50)); INSERT INTO PlayerInfo (PlayerID,Gender,GameType) VALUES (1,'Female','RPG'),(2,'Male','FPS'),(3,'Female','RPG'),(4,'Non-binary','Simulation'); CREATE TABLE PlayerActivity (PlayerID INT,GameID INT,Playtime FLOAT); INSERT INTO PlayerActivity (PlayerID,GameID,Playtime) VALUES (1,1,50.5),(2,2,60.2),(3,1,75.1),(4,3,80.5);
SELECT AVG(Playtime) as AvgPlaytime FROM PlayerActivity INNER JOIN PlayerInfo ON PlayerActivity.PlayerID = PlayerInfo.PlayerID WHERE Gender = 'Female' AND GameType = 'RPG';
Update the city of an exhibition
CREATE TABLE exhibitions (exhibition_id INT PRIMARY KEY,exhibition_name VARCHAR(255),city VARCHAR(255),country VARCHAR(255));
UPDATE exhibitions SET city = 'New York' WHERE exhibition_id = 123;
List all clients who have not paid any billing amount?
CREATE TABLE clients (client_id INT,name VARCHAR(50)); CREATE TABLE cases (case_id INT,client_id INT,billing_amount DECIMAL(10,2)); INSERT INTO clients (client_id,name) VALUES (1,'Smith'),(2,'Johnson'),(3,'Williams'),(4,'Brown'); INSERT INTO cases (case_id,client_id,billing_amount) VALUES (1,1,3000.00),(2,NULL,6000.00),(3,3,7000.00),(4,4,NULL);
SELECT clients.name FROM clients LEFT JOIN cases ON clients.client_id = cases.client_id WHERE cases.client_id IS NULL;
What's the total funding spent on climate communication campaigns by each continent?
CREATE TABLE climate_communication_campaigns(campaign_id INT,campaign_name TEXT,location TEXT,amount_funded FLOAT);
SELECT CONCAT(SUBSTRING(location, 1, 2), ': ', SUM(amount_funded)) FROM climate_communication_campaigns WHERE sector = 'climate communication' GROUP BY SUBSTRING(location, 1, 2);
What is the total number of volunteers and total volunteer hours for each country, sorted by the total number of volunteers in descending order?
CREATE TABLE Volunteers (VolunteerID INT,VolunteerName TEXT,Country TEXT); CREATE TABLE VolunteerHours (VolunteerID INT,Hours INT);
SELECT V.Country, COUNT(V.VolunteerID) as TotalVolunteers, SUM(VH.Hours) as TotalHours FROM Volunteers V JOIN VolunteerHours VH ON V.VolunteerID = VH.VolunteerID GROUP BY V.Country ORDER BY TotalVolunteers DESC;
List all movies and TV shows with a runtime greater than the average movie runtime.
CREATE TABLE Movies (id INT,title VARCHAR(255),runtime INT); CREATE TABLE TVShows (id INT,title VARCHAR(255),runtime INT);
SELECT Movies.title UNION SELECT TVShows.title FROM Movies, TVShows WHERE Movies.runtime > (SELECT AVG(runtime) FROM Movies) OR TVShows.runtime > (SELECT AVG(runtime) FROM Movies);
What is the total capacity of all cargo ships owned by Acme Corp?
CREATE TABLE ships (id INT,name VARCHAR(255),capacity INT); INSERT INTO ships (id,name,capacity) VALUES (1,'ship1',5000),(2,'ship2',7000);
SELECT SUM(capacity) FROM ships WHERE name LIKE 'Acme%';
List all autonomous buses and their quantities in the public_transportation table.
CREATE TABLE public_transportation (id INT,vehicle_type VARCHAR(20),quantity INT); INSERT INTO public_transportation (id,vehicle_type,quantity) VALUES (1,'autonomous_bus',200),(2,'manual_bus',800),(3,'tram',1000);
SELECT vehicle_type, quantity FROM public_transportation WHERE vehicle_type = 'autonomous_bus';
Insert new records into the community_engagement table with the following data: (1, 'Bangkok', 'Thai', 'workshops', 150, '2022-09-10') and (2, 'Delhi', 'Hindi', 'festivals', 200, '2022-11-15').
community_engagement (id,city,language,event_type,participants,event_date)
INSERT INTO community_engagement (id, city, language, event_type, participants, event_date) VALUES (1, 'Bangkok', 'Thai', 'workshops', 150, '2022-09-10'), (2, 'Delhi', 'Hindi', 'festivals', 200, '2022-11-15');
What is the minimum donation amount and the number of donors who made donations equal to the minimum amount?
CREATE TABLE Donors (DonorID INT,DonorName TEXT,DonationAmount DECIMAL(10,2)); INSERT INTO Donors (DonorID,DonorName,DonationAmount) VALUES (1,'John Doe',50.00); INSERT INTO Donors (DonorID,DonorName,DonationAmount) VALUES (2,'Jane Smith',100.00); INSERT INTO Donors (DonorID,DonorName,DonationAmount) VALUES (3,'Bob Johnson',50.00);
SELECT MIN(DonationAmount), COUNT(*) FROM Donors GROUP BY DonationAmount HAVING DonationAmount = (SELECT MIN(DonationAmount) FROM Donors);
What is the maximum package weight sent from each warehouse?
CREATE TABLE warehouse (id INT,location VARCHAR(255)); INSERT INTO warehouse (id,location) VALUES (1,'Chicago'),(2,'Houston'); CREATE TABLE packages (id INT,warehouse_id INT,weight FLOAT); INSERT INTO packages (id,warehouse_id,weight) VALUES (1,1,50.3),(2,1,30.1),(3,2,70.0),(4,2,100.0);
SELECT warehouse_id, MAX(weight) as max_weight FROM packages GROUP BY warehouse_id;
How many electric vehicles were sold in California in 2022?
CREATE TABLE electric_vehicles (id INT,year INT,state VARCHAR(255),sales INT); INSERT INTO electric_vehicles (id,year,state,sales) VALUES (1,2020,'California',50000),(2,2021,'California',60000),(4,2022,'California',80000),(5,2022,'Texas',90000);
SELECT SUM(sales) FROM electric_vehicles WHERE state = 'California' AND year = 2022;
What is the total budget for all resilience projects in the infrastructure development database?
CREATE TABLE if not exists Projects (id INT,name VARCHAR(50),type VARCHAR(50),budget DECIMAL(10,2)); INSERT INTO Projects (id,name,type,budget) VALUES (1,'Seawall','Resilience',5000000.00),(2,'Floodgate','Resilience',3000000.00),(3,'Bridge','Transportation',8000000.00);
SELECT SUM(budget) FROM Projects WHERE type = 'Resilience';
What is the total number of heritage sites per region?
CREATE TABLE Regions (RegionID INT,RegionName VARCHAR(50)); CREATE TABLE HeritageSites (SiteID INT,SiteName VARCHAR(50),RegionID INT); INSERT INTO Regions VALUES (1,'RegionA'),(2,'RegionB'),(3,'RegionC'); INSERT INTO HeritageSites VALUES (1,'SiteA',1),(2,'SiteB',1),(3,'SiteC',2),(4,'SiteD',3),(5,'SiteE',3);
SELECT R.RegionName, COUNT(HS.SiteID) AS TotalSites FROM Regions R JOIN HeritageSites HS ON R.RegionID = HS.RegionID GROUP BY R.RegionName;
How many components were launched by each supplier in the first half of 2020?
CREATE TABLE SatelliteComponents (ComponentID INT,ComponentName VARCHAR(20),Supplier VARCHAR(20),ComponentType VARCHAR(20),LaunchDate DATE); INSERT INTO SatelliteComponents (ComponentID,ComponentName,Supplier,ComponentType,LaunchDate) VALUES (1,'Star Tracker','Honeywell','Attitude Control','2018-04-01'); INSERT INTO SatelliteComponents (ComponentID,ComponentName,Supplier,ComponentType,LaunchDate) VALUES (2,'S-Band Transponder','EMS Technologies','Communication','2019-07-15'); INSERT INTO SatelliteComponents (ComponentID,ComponentName,Supplier,ComponentType,LaunchDate) VALUES (3,'Xenon Ion Propulsion System','Busek','Propulsion','2021-02-09'); INSERT INTO SatelliteComponents (ComponentID,ComponentName,Supplier,ComponentType,LaunchDate) VALUES (4,'Solar Array','Solar Space Technologies','Power','2020-06-05');
SELECT Supplier, COUNT(*) FROM SatelliteComponents WHERE LaunchDate BETWEEN '2020-01-01' AND '2020-06-30' GROUP BY Supplier;
What is the average age of policyholders with health insurance policies in California?
CREATE TABLE policyholders (id INT,state VARCHAR(2),policy_type VARCHAR(20),age INT); INSERT INTO policyholders (id,state,policy_type,age) VALUES (1,'CA','Life',35),(2,'CA','Health',45),(3,'CA','Health',55);
SELECT AVG(age) FROM policyholders WHERE state = 'CA' AND policy_type = 'Health';
What is the average budget allocation per department in the Education sector, ordered from highest to lowest?
CREATE TABLE Education_Budget(Department VARCHAR(255),Allocation INT); INSERT INTO Education_Budget VALUES ('Primary Education',5000000),('Secondary Education',7000000),('Higher Education',9000000);
SELECT Department, AVG(Allocation) as Avg_Allocation FROM Education_Budget GROUP BY Department ORDER BY Avg_Allocation DESC;
What is the average price per gram of all cannabis products sold in Denver in 2021?
CREATE TABLE sales (id INT,product TEXT,price_per_gram DECIMAL,city TEXT,sale_date DATE); INSERT INTO sales (id,product,price_per_gram,city,sale_date) VALUES (1,'Blue Dream',10.0,'Denver','2021-01-01'),(2,'Gelato',15.0,'Denver','2021-01-01');
SELECT AVG(price_per_gram) FROM sales WHERE city = 'Denver' AND sale_date >= '2021-01-01' AND sale_date < '2022-01-01';
What is the minimum market price of Lanthanum in Vietnam for 2018?
CREATE TABLE Lanthanum_Market_Prices (id INT,year INT,country VARCHAR(255),market_price FLOAT);
SELECT MIN(market_price) FROM Lanthanum_Market_Prices WHERE year = 2018 AND country = 'Vietnam';
What is the most common age group for mental health conditions in Japan?
CREATE TABLE mental_health_conditions (id INT PRIMARY KEY,patient_id INT,age_group VARCHAR(50),country VARCHAR(50),condition VARCHAR(50));
SELECT age_group FROM mental_health_conditions WHERE country = 'Japan' GROUP BY age_group ORDER BY COUNT(*) DESC LIMIT 1;
What is the total amount of grants awarded to non-profit organizations working on criminal justice reform in New York in the last 3 years?
CREATE TABLE grants (id INT,year INT,organization VARCHAR(50),state VARCHAR(50),type VARCHAR(50)); INSERT INTO grants (id,year,organization,state,type) VALUES (1,2019,'JusticeReformNY','New York','Grant'),(2,2020,'LegalAidNY','California','Grant'),(3,2021,'EmpowerJustice','New York','Donation'),(4,2018,'JusticeForAll','Texas','Grant'),(5,2019,'CriminalJusticeUSA','New York','Grant');
SELECT SUM(amount) FROM (SELECT id, year, CASE WHEN type = 'Grant' THEN amount END AS amount FROM grants WHERE state = 'New York' AND type = 'Grant' AND year BETWEEN 2019 AND 2021) AS subquery;
What is the average number of workplace safety incidents for each union in the education industry, grouped by union name?
CREATE TABLE union_education (union_id INT,union_name TEXT,industry TEXT,incidents INT); INSERT INTO union_education (union_id,union_name,industry,incidents) VALUES (1,'Union X','Education',20),(2,'Union Y','Education',15),(3,'Union Z','Healthcare',10);
SELECT union_name, AVG(incidents) FROM union_education WHERE industry = 'Education' GROUP BY union_name;
What's the percentage of total donations received each month?
CREATE TABLE MonthlyDonations (Id INT,DonationDate DATE,Amount DECIMAL(10,2)); INSERT INTO MonthlyDonations VALUES (1,'2022-01-01',100.00),(2,'2022-02-01',200.00);
SELECT EXTRACT(MONTH FROM DonationDate) as Month, SUM(Amount) as TotalDonations, (SUM(Amount) / (SELECT SUM(Amount) FROM MonthlyDonations) * 100) as Percentage FROM MonthlyDonations GROUP BY Month;
List all disaster types and their respective average preparedness scores, for the last 3 months, from 'DisasterPreparedness' table.
CREATE TABLE DisasterPreparedness (id INT,month INT,year INT,disasterType VARCHAR(30),score INT);
SELECT disasterType, AVG(score) FROM DisasterPreparedness WHERE year = YEAR(CURRENT_DATE) AND month BETWEEN MONTH(CURRENT_DATE) - 2 AND MONTH(CURRENT_DATE) GROUP BY disasterType;
What is the minimum GPA of graduate students in the 'math' program?
CREATE TABLE student (id INT,program TEXT,gpa REAL); INSERT INTO student (id,program,gpa) VALUES (1,'math',3.8),(2,'math',3.9),(3,'math',4.0);
SELECT MIN(gpa) FROM student WHERE program = 'math';
What is the total sales amount for a specific drug across different regions in a given year?
CREATE TABLE sales_data (drug_name TEXT,sale_amount INTEGER,sale_year INTEGER,region TEXT); INSERT INTO sales_data (drug_name,sale_amount,sale_year,region) VALUES ('DrugC',1200,2020,'North'),('DrugC',1500,2020,'South'),('DrugD',2000,2020,'East'),('DrugD',1800,2020,'West');
SELECT SUM(sale_amount) FROM sales_data WHERE drug_name = 'DrugC' AND sale_year = 2020;
How many veterans found employment in the defense industry in 2019?
CREATE TABLE veteran_employment (employee_id INT,industry VARCHAR(255),date DATE); INSERT INTO veteran_employment (employee_id,industry,date) VALUES (1,'defense','2019-09-01'); INSERT INTO veteran_employment (employee_id,industry,date) VALUES (2,'non-defense','2019-12-05');
SELECT COUNT(*) FROM veteran_employment WHERE industry = 'defense' AND date BETWEEN '2019-01-01' AND '2019-12-31';
How many space missions were conducted by 'NASA' in the year 2019?
CREATE TABLE SpaceExploration(mission VARCHAR(20),mission_year INT,company VARCHAR(20)); INSERT INTO SpaceExploration VALUES('Mission A',2019,'NASA'),('Mission B',2020,'SpaceX');
SELECT COUNT(*) FROM SpaceExploration WHERE mission_year=2019 AND company='NASA';
Update the description of the ethic with ethic_id 1 in the 'media_ethics' table
CREATE TABLE media_ethics (ethic_id INT PRIMARY KEY,ethic_name VARCHAR(255),description TEXT,source VARCHAR(255));
UPDATE media_ethics SET description = 'The right to access and distribute information without interference from government or other powers.' WHERE ethic_id = 1;
Find the number of fraudulent transactions and their total value, excluding transactions with a value less than 1000, for each employee in the sales department.
CREATE TABLE transactions (transaction_id INT,employee_id INT,transaction_type VARCHAR(20),transaction_value DECIMAL(10,2),is_fraudulent BOOLEAN);
SELECT employee_id, COUNT(*) as fraud_count, SUM(transaction_value) as total_fraud_value FROM transactions WHERE transaction_type = 'Sales' AND is_fraudulent = TRUE AND transaction_value >= 1000 GROUP BY employee_id;
What is the average cost of group therapy sessions in France?
CREATE TABLE therapy_sessions (id INT,session_name TEXT,cost INT,country TEXT);
SELECT AVG(cost) FROM therapy_sessions WHERE session_name = 'Group Therapy' AND country = 'France';
What is the total CO2 emissions for each year in the diamond mining industry?
CREATE TABLE environmental_impact (id INT,mine_id INT,year INT,co2_emissions INT,water_usage INT); INSERT INTO environmental_impact (id,mine_id,year,co2_emissions,water_usage) VALUES (7,7,2021,40000,900000); INSERT INTO environmental_impact (id,mine_id,year,co2_emissions,water_usage) VALUES (8,8,2021,45000,1000000);
SELECT YEAR(e.year) AS year, SUM(e.co2_emissions) AS total_co2_emissions FROM environmental_impact e JOIN mines m ON e.mine_id = m.id WHERE m.mineral = 'Diamond' GROUP BY YEAR(e.year);
List all the video contents with a diversity score greater than 8.5.
CREATE TABLE MediaContent (ContentID INT PRIMARY KEY,ContentName VARCHAR(50),ContentType VARCHAR(30),DiversityScore DECIMAL(5,2),MediaPlatform VARCHAR(30)); INSERT INTO MediaContent (ContentID,ContentName,ContentType,DiversityScore,MediaPlatform) VALUES (1,'Content 1','Video',8.5,'Platform A'),(2,'Content 2','Podcast',7.2,'Platform B');
SELECT * FROM MediaContent WHERE ContentType = 'Video' AND DiversityScore > 8.5;
Count the number of whale sightings in the Pacific Ocean in 2022.
CREATE TABLE whale_sightings (id INTEGER,species TEXT,sighting_date DATE,location TEXT); INSERT INTO whale_sightings (id,species,sighting_date,location) VALUES (1,'Blue Whale','2022-01-01','Pacific Ocean'); INSERT INTO whale_sightings (id,species,sighting_date,location) VALUES (2,'Gray Whale','2022-03-15','Pacific Ocean');
SELECT COUNT(*) FROM whale_sightings WHERE sighting_date >= '2022-01-01' AND sighting_date < '2023-01-01' AND location = 'Pacific Ocean';
What is the maximum fairness score for models trained on the 'african_census' dataset?
CREATE TABLE african_census (model_name TEXT,fairness_score FLOAT); INSERT INTO african_census (model_name,fairness_score) VALUES ('model1',0.95),('model2',0.85),('model3',0.90);
SELECT MAX(fairness_score) FROM african_census;
What is the total weight of packages shipped to Australia from any country in Oceania in the last month?
CREATE TABLE package_destinations (id INT,package_weight FLOAT,shipped_from VARCHAR(20),shipped_to VARCHAR(20),shipped_date DATE); INSERT INTO package_destinations (id,package_weight,shipped_from,shipped_to,shipped_date) VALUES (1,2.3,'New Zealand','Australia','2022-01-15');
SELECT SUM(package_weight) FROM package_destinations WHERE shipped_to = 'Australia' AND shipped_from LIKE 'Oceania%' AND shipped_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH);
What is the average life expectancy in each continent?
CREATE TABLE life_expectancy(id INT,country TEXT,continent TEXT,expectancy FLOAT);
SELECT continent, AVG(expectancy) FROM life_expectancy GROUP BY continent;
What is the maximum impact score achieved by a company in the healthcare sector?
CREATE TABLE company_impact (id INT,name VARCHAR(50),sector VARCHAR(20),impact_score FLOAT); INSERT INTO company_impact (id,name,sector,impact_score) VALUES (1,'Company X','Healthcare',90.0),(2,'Company Y','Finance',85.0),(3,'Company Z','Healthcare',92.5);
SELECT MAX(impact_score) FROM company_impact WHERE sector = 'Healthcare';
How many season tickets have been sold in the Pacific Division?
CREATE TABLE teams (team_id INT,division VARCHAR(50)); CREATE TABLE ticket_sales (id INT,team_id INT,num_tickets INT);
SELECT SUM(ticket_sales.num_tickets) FROM ticket_sales JOIN teams ON ticket_sales.team_id = teams.team_id WHERE teams.division = 'Pacific';
What is the percentage of cases in the access to justice database that were resolved through mediation in the last quarter?
CREATE TABLE access_to_justice_cases (id INT,resolution_type VARCHAR(20),resolution_date DATE);
SELECT (COUNT(*) FILTER (WHERE resolution_type = 'mediation')) * 100.0 / COUNT(*) FROM access_to_justice_cases WHERE resolution_date >= DATE_SUB(CURRENT_DATE, INTERVAL 3 MONTHS);
What is the average mass of different types of space debris?
CREATE TABLE space_objects (id INT,name VARCHAR(255),mass FLOAT,type VARCHAR(255)); INSERT INTO space_objects (id,name,mass,type) VALUES (1,'Object 1',1000.0,'Rocket Stage'),(2,'Object 2',20.0,'Fractured Debris'),(3,'Object 3',1500.0,'Dead Satellite');
SELECT type, AVG(mass) FROM space_objects GROUP BY type;
What's the average rating of music artists from Asia?
CREATE TABLE MusicArtists (id INT,name VARCHAR(100),country VARCHAR(50),rating FLOAT);
SELECT AVG(rating) FROM MusicArtists WHERE country = 'Asia';
Delete all green buildings in the green_buildings table associated with the 'Boston' city
CREATE TABLE green_buildings (id INT,name TEXT,certification_level TEXT,city TEXT);
WITH cte AS (DELETE FROM green_buildings WHERE city = 'Boston') SELECT * FROM cte;
Add a new column endangered to the species table and update values
CREATE TABLE species(id INT,name VARCHAR(255),common_name VARCHAR(255),population INT,endangered BOOLEAN);
ALTER TABLE species ADD COLUMN endangered BOOLEAN;
What is the minimum mental health score by ethnicity?
CREATE TABLE Ethnicities (EthnicityID INT,Ethnicity VARCHAR(50)); CREATE TABLE MentalHealthScores (MH_ID INT,EthnicityID INT,MentalHealthScore INT); INSERT INTO Ethnicities (EthnicityID,Ethnicity) VALUES (1,'Hispanic'),(2,'African American'),(3,'Asian'),(4,'Caucasian'); INSERT INTO MentalHealthScores (MH_ID,EthnicityID,MentalHealthScore) VALUES (1,1,70),(2,1,75),(3,2,80),(4,2,85),(5,3,90),(6,3,95),(7,4,65),(8,4,70);
SELECT e.Ethnicity, MIN(mhs.MentalHealthScore) as Min_Score FROM MentalHealthScores mhs JOIN Ethnicities e ON mhs.EthnicityID = e.EthnicityID GROUP BY e.Ethnicity;
What is the total number of marine species in the Southern Ocean that are affected by maritime safety issues?
CREATE TABLE marine_species (id INT,name TEXT,ocean TEXT,affected_by_safety_issues BOOLEAN); INSERT INTO marine_species (id,name,ocean,affected_by_safety_issues) VALUES (1,'Krill','Southern',TRUE),(2,'Blue Whale','Atlantic',FALSE),(3,'Penguin','Southern',TRUE);
SELECT COUNT(*) FROM marine_species WHERE ocean = 'Southern' AND affected_by_safety_issues = TRUE;
Which spacecraft have been launched by the European Space Agency?
CREATE TABLE Spacecraft (id INT,name VARCHAR(255),manufacturer VARCHAR(255),type VARCHAR(255),launch_date DATE); INSERT INTO Spacecraft (id,name,manufacturer,type,launch_date) VALUES (3,'Galileo Orbiter','ESA','Robotic','1989-10-18'); INSERT INTO Spacecraft (id,name,manufacturer,type,launch_date) VALUES (4,'Rosetta','ESA','Robotic','2004-03-02');
SELECT name FROM Spacecraft WHERE manufacturer = 'ESA';
What was the maximum labor cost for each month in Oregon in 2022?
CREATE TABLE Labor_OR (labor_id INT,labor_cost FLOAT,labor_state VARCHAR(20),labor_date DATE); INSERT INTO Labor_OR (labor_id,labor_cost,labor_state,labor_date) VALUES (1,300,'Oregon','2022-01-01'),(2,350,'Oregon','2022-01-15'),(3,400,'Oregon','2022-03-01');
SELECT labor_date, MAX(labor_cost) OVER (PARTITION BY EXTRACT(MONTH FROM labor_date)) AS max_labor_cost FROM Labor_OR WHERE labor_state = 'Oregon' AND labor_date >= '2022-01-01' AND labor_date < '2023-01-01' ORDER BY labor_date;
What is the minimum dissolved oxygen level in the Indian Ocean?
CREATE TABLE location (location_id INT,location_name TEXT); INSERT INTO location (location_id,location_name) VALUES (1,'Indian Ocean'); CREATE TABLE measurement (measurement_id INT,location_id INT,dissolved_oxygen FLOAT); INSERT INTO measurement (measurement_id,location_id,dissolved_oxygen) VALUES (1,1,6.5),(2,1,6.8),(3,1,6.9),(4,1,7.1),(5,1,7.2);
SELECT MIN(dissolved_oxygen) FROM measurement WHERE location_id = (SELECT location_id FROM location WHERE location_name = 'Indian Ocean');
List the top 3 countries with the most aircraft accidents in 2020.
CREATE TABLE Aircraft_Accidents (aircraft_model VARCHAR(255),accident_date DATE,country VARCHAR(255)); INSERT INTO Aircraft_Accidents (aircraft_model,accident_date,country) VALUES ('Boeing 737','2020-01-01','USA'),('Airbus A320','2020-02-01','France'),('Boeing 747','2020-03-01','UK'),('Boeing 737','2020-04-01','Canada'),('Airbus A320','2020-05-01','Germany');
SELECT country, COUNT(*) AS num_accidents FROM Aircraft_Accidents WHERE YEAR(accident_date) = 2020 GROUP BY country ORDER BY num_accidents DESC LIMIT 3;
How many mobile subscribers are there in each country?
CREATE TABLE mobile_subscribers (subscriber_id INT,home_location VARCHAR(50)); INSERT INTO mobile_subscribers (subscriber_id,home_location) VALUES (1,'USA'),(2,'Mexico'),(3,'Canada'),(4,'USA'),(5,'Canada');
SELECT home_location, COUNT(*) FROM mobile_subscribers GROUP BY home_location;
Delete the supplier with id 2
CREATE TABLE suppliers (id INT PRIMARY KEY,name TEXT,location TEXT,sustainability_rating REAL);
DELETE FROM suppliers WHERE id = 2;
List the names and locations of mines that have mined any type of metal.
CREATE TABLE mine (id INT,name VARCHAR(50),location VARCHAR(50));CREATE TABLE coal_mine (mine_id INT,amount INT);CREATE TABLE iron_mine (mine_id INT,amount INT);CREATE TABLE gold_mine (mine_id INT,amount INT);CREATE TABLE silver_mine (mine_id INT,amount INT);
SELECT m.name, m.location FROM mine m LEFT JOIN coal_mine c ON m.id = c.mine_id LEFT JOIN iron_mine i ON m.id = i.mine_id LEFT JOIN gold_mine g ON m.id = g.mine_id LEFT JOIN silver_mine s ON m.id = s.mine_id WHERE c.mine_id IS NOT NULL OR i.mine_id IS NOT NULL OR g.mine_id IS NOT NULL OR s.mine_id IS NOT NULL;
What is the average rating of products sold by vendors from Asia?
CREATE TABLE vendors(vendor_id INT,vendor_name TEXT,country TEXT); INSERT INTO vendors(vendor_id,vendor_name,country) VALUES (1,'VendorA','India'),(2,'VendorB','China'),(3,'VendorC','Japan'); CREATE TABLE products(product_id INT,product_name TEXT,rating INT); INSERT INTO products(product_id,product_name,rating) VALUES (1,'ProductA',4),(2,'ProductB',5),(3,'ProductC',3);
SELECT AVG(products.rating) FROM products JOIN vendors ON products.vendor_id = vendors.vendor_id WHERE vendors.country = 'Asia';
Update the TotalEngagement column in the ExhibitionAnalytics table for the 'Ancient Art' exhibition to 300.
CREATE TABLE ExhibitionAnalytics (ExhibitionID INT,ExhibitionName VARCHAR(50),TotalVisitors INT,TotalEngagement INT);
UPDATE ExhibitionAnalytics SET TotalEngagement = 300 WHERE ExhibitionName = 'Ancient Art';
What is the total quantity of recycled materials used in garment production?
CREATE TABLE GarmentProduction (garmentID INT,material VARCHAR(20),year INT,quantity INT); INSERT INTO GarmentProduction (garmentID,material,year,quantity) VALUES (1,'Recycled Polyester',2020,12000),(2,'Organic Cotton',2020,15000),(3,'Recycled Denim',2019,8000),(4,'Recycled Polyester',2019,9000),(5,'Recycled Cotton',2020,10000);
SELECT SUM(quantity) FROM GarmentProduction WHERE material LIKE '%Recycled%';
List the voyages with their start and end ports and the time difference between arrivals.
CREATE TABLE Voyage (VoyageID INT,VesselID INT,StartPortID INT,EndPortID INT,StartDate DATETIME,EndDate DATETIME); INSERT INTO Voyage (VoyageID,VesselID,StartPortID,EndPortID,StartDate,EndDate) VALUES (1,1,1,2,'2022-01-01 08:00:00','2022-01-02 10:00:00'); INSERT INTO Voyage (VoyageID,VesselID,StartPortID,EndPortID,StartDate,EndDate) VALUES (2,2,2,1,'2022-01-03 12:00:00','2022-01-04 14:00:00');
SELECT v1.VesselID, p1.PortName AS StartPort, p2.PortName AS EndPort, DATEDIFF(HOUR, v1.StartDate, v1.EndDate) AS TimeDifference FROM Voyage v1 JOIN Port p1 ON v1.StartPortID = p1.PortID JOIN Port p2 ON v1.EndPortID = p2.PortID;
Which buses have not had a safety inspection in the last 6 months?
CREATE TABLE Buses (id INT,model VARCHAR(255),last_inspection DATETIME);
SELECT B.id, B.model FROM Buses B LEFT JOIN (SELECT bus_id, MAX(last_inspection) as max_inspection FROM Buses GROUP BY bus_id) BI ON B.id = BI.bus_id WHERE B.last_inspection < BI.max_inspection - INTERVAL 6 MONTH;
What was the maximum number of likes received by posts in Spanish?
CREATE TABLE posts (id INT,user_id INT,post_text VARCHAR(255),likes INT,language VARCHAR(10)); INSERT INTO posts (id,user_id,post_text,likes,language) VALUES (1,1,'Hola!',20,'es'),(2,2,'Hello!',15,'en'),(3,3,'Bonjour!',25,'fr'),(4,4,'Olá!',18,'pt');
SELECT MAX(likes) FROM posts WHERE language = 'es';
List all mental health parity laws in Massachusetts.
CREATE TABLE MentalHealthParity (id INT,law_name TEXT,state TEXT); INSERT INTO MentalHealthParity (id,law_name,state) VALUES (1,'Parity Act 2020','Massachusetts'); INSERT INTO MentalHealthParity (id,law_name,state) VALUES (2,'Equity Act 2018','Massachusetts');
SELECT * FROM MentalHealthParity WHERE state = 'Massachusetts';
What is the average gas production in the 'Africa' region for the year 2020? (Assuming gas production values are stored in a separate column)
CREATE TABLE production (production_id INT,location VARCHAR(255),year INT,gas_production FLOAT); INSERT INTO production (production_id,location,year,gas_production) VALUES (1,'Nigeria',2020,5000000),(2,'Algeria',2020,4000000),(3,'Egypt',2019,3000000);
SELECT AVG(gas_production) FROM production WHERE location LIKE '%Africa%' AND year = 2020;
Show the number of employees hired in each month of the year, broken down by department.
CREATE TABLE employees (id INT,name VARCHAR(50),department VARCHAR(50),hire_date DATE); INSERT INTO employees (id,name,department,hire_date) VALUES (1,'John Doe','IT','2021-03-01'),(2,'Jane Smith','Marketing','2021-07-15'),(3,'Mike Johnson','IT','2021-02-12'),(4,'Sara Connor','Marketing','2021-10-04');
SELECT department, DATE_TRUNC('month', hire_date) AS hire_month, COUNT(*) AS num_hires FROM employees GROUP BY department, hire_month;
Update the vessel's safety record with the latest inspection date and score.
CREATE TABLE vessels (id INT,name VARCHAR(255),safety_record JSON); CREATE TABLE inspections (vessel_id INT,inspection_date DATE,score INT); INSERT INTO vessels VALUES (1,'Vessel A','{"inspection_date": "2021-01-01","score": 90}'::JSON),(2,'Vessel B','{"inspection_date": "2021-02-01","score": 85}'::JSON); INSERT INTO inspections VALUES (1,'2021-03-01',95),(2,'2021-04-01',90);
UPDATE vessels v SET safety_record = jsonb_set(v.safety_record, '{inspection_date, score}', jsonb_build_object('inspection_date', (SELECT i.inspection_date FROM inspections i WHERE i.vessel_id = v.id ORDER BY i.inspection_date DESC LIMIT 1), 'score', (SELECT i.score FROM inspections i WHERE i.vessel_id = v.id ORDER BY i.inspection_date DESC LIMIT 1))) WHERE id IN (SELECT i.vessel_id FROM inspections i);
How many news articles were published per month in 2021 in the 'news' schema?
CREATE TABLE news.articles (article_id INT,title VARCHAR(100),publish_date DATE); INSERT INTO news.articles (article_id,title,publish_date) VALUES (1,'Article 1','2021-01-01'),(2,'Article 2','2021-02-01');
SELECT MONTH(publish_date), COUNT(*) FROM news.articles WHERE YEAR(publish_date) = 2021 GROUP BY MONTH(publish_date);
What is the total weight of indoor grown cannabis sold by dispensaries in Colorado in 2021?
CREATE TABLE Dispensaries (id INT,dispensary_name VARCHAR(255),state VARCHAR(255),income DECIMAL(10,2)); INSERT INTO Dispensaries (id,dispensary_name,state,income) VALUES (1,'Green Earth Dispensary','Colorado',125000.00); CREATE TABLE Cannabis_Sales (id INT,dispensary_id INT,sale_year INT,sale_weight DECIMAL(10,2),sale_type VARCHAR(255)); INSERT INTO Cannabis_Sales (id,dispensary_id,sale_year,sale_weight,sale_type) VALUES (1,1,2021,500.00,'Indoor');
SELECT SUM(sale_weight) FROM Dispensaries d JOIN Cannabis_Sales s ON d.id = s.dispensary_id WHERE d.state = 'Colorado' AND s.sale_year = 2021 AND s.sale_type = 'Indoor';
What is the total waste generation in kg for the region 'Greater Toronto' for the year 2021?
CREATE TABLE waste_generation (region VARCHAR(50),year INT,waste_kg FLOAT); INSERT INTO waste_generation (region,year,waste_kg) VALUES ('Greater Toronto',2021,123456.78);
SELECT SUM(waste_kg) FROM waste_generation WHERE region = 'Greater Toronto' AND year = 2021;
Find the maximum construction cost for pipelines in 'Alberta'
CREATE TABLE pipelines (id INT,name VARCHAR(50),location VARCHAR(50),construction_cost DECIMAL(10,2)); INSERT INTO pipelines (id,name,location,construction_cost) VALUES (1,'Alberta Clipper Pipeline','Alberta',1500000000.00);
SELECT MAX(construction_cost) FROM pipelines WHERE location = 'Alberta';
How many subscribers are using premium voice plans in each state?
CREATE TABLE voice_plans (plan_id int,plan_cost float,plan_type varchar(10)); INSERT INTO voice_plans (plan_id,plan_cost,plan_type) VALUES (1,30,'basic'),(2,50,'premium'); CREATE TABLE voice_subscribers (subscriber_id int,voice_plan varchar(10),state varchar(20)); INSERT INTO voice_subscribers (subscriber_id,voice_plan,state) VALUES (1,'basic','WA'),(2,'premium','NY'),(3,'basic','IL');
SELECT state, COUNT(*) as num_premium_subscribers FROM voice_subscribers sub INNER JOIN voice_plans plan ON sub.voice_plan = plan.plan_type WHERE plan_type = 'premium' GROUP BY state;
What is the total number of electric and autonomous vehicles in the electricautonomousvehicles schema?
CREATE TABLE ElectricAutonomousVehicles (id INT,make VARCHAR(50),model VARCHAR(50),electric BOOLEAN,autonomous BOOLEAN);
SELECT COUNT(*) FROM electricautonomousvehicles.ElectricAutonomousVehicles WHERE electric = TRUE OR autonomous = TRUE;
How many players are there in the "EpicRacers" table, grouped by their preferred gaming platform (PC, Console, Mobile)?
CREATE TABLE EpicRacers (PlayerID INT,Name VARCHAR(50),Platform VARCHAR(10)); INSERT INTO EpicRacers (PlayerID,Name,Platform) VALUES (1,'John','PC'),(2,'Amy','Console'),(3,'Mike','Mobile'),(4,'Linda','PC'),(5,'Sam','Console');
SELECT Platform, COUNT(PlayerID) FROM EpicRacers GROUP BY Platform;
Which teams have no ticket sales in the last month?
CREATE TABLE Teams (TeamID INT,TeamName VARCHAR(50)); INSERT INTO Teams (TeamID,TeamName) VALUES (1,'Red Dragons'),(2,'Blue Warriors'); CREATE TABLE TicketSales (SaleID INT,TeamID INT,SaleDate DATE); INSERT INTO TicketSales (SaleID,TeamID,SaleDate) VALUES (1,1,'2022-01-10'),(2,1,'2022-03-05'),(3,2,'2022-02-20'),(4,2,'2022-04-10'),(5,2,'2022-05-12');
SELECT T.TeamName FROM Teams T LEFT JOIN TicketSales TS ON T.TeamID = TS.TeamID WHERE TS.SaleDate IS NULL OR TS.SaleDate < DATE_SUB(CURDATE(), INTERVAL 1 MONTH) GROUP BY T.TeamName;
Reveal vessels with decreasing violations.
CREATE TABLE VesselInspections2 (ID INT,Vessel VARCHAR(50),InspectionDate DATE,ViolationCount INT); INSERT INTO VesselInspections2 (ID,Vessel,InspectionDate,ViolationCount) VALUES (1,'SS Freedom','2020-01-01',3),(2,'SS Liberty','2020-01-02',2),(3,'SS Eagle','2020-01-03',4),(4,'SS Freedom','2020-01-04',2);
SELECT Vessel, ViolationCount, LAG(ViolationCount) OVER (PARTITION BY Vessel ORDER BY InspectionDate) as PreviousViolationCount FROM VesselInspections2;
What is the total number of properties in areas with affordable housing and sustainability ratings above 70?
CREATE TABLE properties (id INT,affordability VARCHAR(20),sustainability_rating FLOAT); INSERT INTO properties (id,affordability,sustainability_rating) VALUES (1,'affordable',80.5),(2,'unaffordable',60.0);
SELECT COUNT(*) FROM properties WHERE affordability = 'affordable' AND sustainability_rating > 70;
Update the room prices for the 'Sustainable Hotel' in France by 10% for 2023.
CREATE TABLE room_prices (hotel_id INT,year INT,price INT); INSERT INTO room_prices (hotel_id,year,price) VALUES (1,2022,150); INSERT INTO room_prices (hotel_id,year,price) VALUES (1,2023,150);
UPDATE room_prices SET price = price * 1.1 WHERE hotel_id = 1 AND year = 2023;
What is the total volume of timber harvested in tropical rainforests in 2020?
CREATE TABLE forests (id INT,name VARCHAR(255),location VARCHAR(255),biome VARCHAR(255),area FLOAT,elevation_range VARCHAR(255)); INSERT INTO forests (id,name,location,biome,area,elevation_range) VALUES (1,'Amazon Rainforest','South America','Tropical Rainforest',6700000,'0 - 300 m'); CREATE TABLE timber_harvest (id INT,forest_id INT,year INT,volume FLOAT); INSERT INTO timber_harvest (id,forest_id,year,volume) VALUES (1,1,2020,15000);
SELECT SUM(volume) FROM timber_harvest WHERE forest_id IN (SELECT id FROM forests WHERE biome = 'Tropical Rainforest') AND year = 2020;
Find employees who have the same first name as their department head.
CREATE TABLE Employees (EmployeeID INT,FirstName VARCHAR(50),LastName VARCHAR(50),Department VARCHAR(50),ManagerID INT,ManagerFirstName VARCHAR(50),ManagerLastName VARCHAR(50)); INSERT INTO Employees (EmployeeID,FirstName,LastName,Department,ManagerID,ManagerFirstName,ManagerLastName) VALUES (1,'Jose','Garcia','Marketing',2,'John','Doe'),(2,'John','Doe','IT',NULL,'John','Doe'),(3,'Alice','Williams','Marketing',1,'John','Doe'),(4,'Charlie','Brown','HR',NULL,'Sara','Lee'),(5,'Denise','Davis','Marketing',1,'John','Doe');
SELECT E1.FirstName FROM Employees E1 INNER JOIN Employees E2 ON E1.ManagerID = E2.EmployeeID WHERE E1.FirstName = E2.FirstName AND E1.Department = E2.Department;
How many climate adaptation projects were implemented in Small Island Developing States (SIDS) in the last 3 years?
CREATE TABLE climate_adaptation_projects (project VARCHAR(50),location VARCHAR(50),year INT); INSERT INTO climate_adaptation_projects (project,location,year) VALUES ('Sea Level Rise Mitigation','Maldives',2019),('Water Management','Barbados',2020),('Disaster Risk Reduction','Cape Verde',2021),('Coastal Protection','Marshall Islands',2021); CREATE TABLE sids (location VARCHAR(50),sids_status VARCHAR(50)); INSERT INTO sids (location,sids_status) VALUES ('Maldives','SIDS'),('Barbados','SIDS'),('Cape Verde','SIDS'),('Marshall Islands','SIDS');
SELECT COUNT(*) FROM climate_adaptation_projects cp INNER JOIN sids s ON cp.location = s.location WHERE s.sids_status = 'SIDS' AND cp.year BETWEEN 2019 AND 2021;
Show the daily number of posts in the 'social_media' table for the top 5 regions with the most posts.
CREATE TABLE social_media(user_id INT,user_name VARCHAR(50),region VARCHAR(50),post_date DATE,likes INT);
SELECT post_date, region, COUNT(*) as daily_posts FROM (SELECT region, post_date, user_id FROM social_media GROUP BY region, post_date, user_id ORDER BY region, COUNT(*) DESC LIMIT 5) as top_regions GROUP BY post_date, region;
Identify companies with no diversity metrics recorded
CREATE TABLE diversity (company_name VARCHAR(255),gender_distribution VARCHAR(50),ethnicity_distribution VARCHAR(50)); INSERT INTO diversity (company_name,gender_distribution,ethnicity_distribution) VALUES ('Acme Inc','50/50','Diverse'),('Beta Corp','60/40','Not Diverse'),('Charlie LLC',NULL,NULL);
SELECT company_name FROM diversity WHERE gender_distribution IS NULL AND ethnicity_distribution IS NULL;
How many teachers have completed professional development courses in the last 6 months?
CREATE TABLE teachers (teacher_id INT,teacher_name VARCHAR(50)); INSERT INTO teachers (teacher_id,teacher_name) VALUES (1,'Alice'),(2,'Bob'),(3,'Charlie'); CREATE TABLE professional_development_courses (course_id INT,course_name VARCHAR(50),completion_date DATE); INSERT INTO professional_development_courses (course_id,course_name,completion_date) VALUES (1,'Python','2023-01-01'),(2,'R','2023-02-15'),(3,'JavaScript','2023-04-20');
SELECT COUNT(DISTINCT teachers.teacher_id) as num_teachers FROM teachers JOIN professional_development_courses ON teachers.teacher_id = professional_development_courses.teacher_id WHERE professional_development_courses.completion_date >= DATEADD(month, -6, GETDATE());
What is the total number of medals won by athletes in the 'Athletes' table who are from the United States, grouped by the type of medal?
CREATE TABLE athletes (athlete_id INT,name VARCHAR(50),nationality VARCHAR(50),age INT,medal VARCHAR(10),event VARCHAR(50)); INSERT INTO athletes (athlete_id,name,nationality,age,medal,event) VALUES (1,'Michael Phelps','United States',35,'Gold','Swimming');
SELECT medal, SUM(1) as total_medals FROM athletes WHERE nationality = 'United States' GROUP BY medal;
List all users and their respective number of posts, ordered by the user_id in ascending order.
CREATE TABLE user_details (user_id INT,num_posts INT); INSERT INTO user_details (user_id,num_posts) VALUES (1,25),(2,32),(3,18),(4,45);
SELECT user_id, num_posts FROM user_details ORDER BY user_id ASC;
How many aircraft maintenance requests were made in the Middle East in Q3 2021, with a priority level of 'Urgent'?
CREATE TABLE AircraftMaintenance (id INT,region VARCHAR(20),priority VARCHAR(10),request_date DATE); INSERT INTO AircraftMaintenance (id,region,priority,request_date) VALUES (1,'Middle East','Urgent','2021-09-15');
SELECT COUNT(*) as urgent_requests FROM AircraftMaintenance WHERE region = 'Middle East' AND priority = 'Urgent' AND request_date BETWEEN '2021-07-01' AND '2021-09-30';
What is the total number of visitors for each destination in the international_visitors table?
CREATE TABLE destinations (destination_id INT,name VARCHAR(50),country_id INT); INSERT INTO destinations (destination_id,name,country_id) VALUES (3,'Milford Sound',1); INSERT INTO destinations (destination_id,name,country_id) VALUES (4,'Prambanan Temple',2);
SELECT d.name, SUM(i.num_visitors) as total_visitors FROM destinations d INNER JOIN international_visitors i ON d.destination_id = i.country_id GROUP BY d.name;
Delete all albums released before the year 2000.
CREATE TABLE albums (id INT,title TEXT,release_date DATE); INSERT INTO albums (id,title,release_date) VALUES (1,'Millennium','1999-12-31'),(2,'Hybrid Theory','2000-01-02');
DELETE FROM albums WHERE release_date < '2000-01-01';
How many farms are in each state of the USA?
CREATE TABLE farm (id INT,farm_name VARCHAR(255),state VARCHAR(255),country VARCHAR(255)); INSERT INTO farm (id,farm_name,state,country) VALUES (1,'Farm 1','California','USA'); INSERT INTO farm (id,farm_name,state,country) VALUES (2,'Farm 2','Texas','USA');
SELECT state, COUNT(*) AS num_farms FROM farm WHERE country = 'USA' GROUP BY state;
Identify the top 2 cities with the highest number of virtual tours in the US.
CREATE TABLE tour_bookings(id INT,city TEXT,booking_date DATE,booking_type TEXT); INSERT INTO tour_bookings (id,city,booking_date,booking_type) VALUES (1,'New York','2022-04-01','virtual'),(2,'Los Angeles','2022-04-02','virtual'),(3,'Chicago','2022-04-03','in-person');
SELECT city, COUNT(*) AS num_virtual_tours FROM tour_bookings WHERE booking_type = 'virtual' GROUP BY city ORDER BY num_virtual_tours DESC LIMIT 2;
Add a new network tower to the network_towers table
CREATE TABLE network_towers (tower_id INT,location VARCHAR(50),latitude DECIMAL(9,6),longitude DECIMAL(9,6),installed_date DATE);
INSERT INTO network_towers (tower_id, location, latitude, longitude, installed_date) VALUES (54321, 'City Center', 40.7128, -74.0060, '2021-12-15');
What is the average heart rate of members aged 25-30 who use our wearable devices, grouped by gender?
CREATE TABLE members (id INT,age INT,gender VARCHAR(10)); CREATE TABLE wearables (id INT,member_id INT,heart_rate INT);
SELECT gender, AVG(heart_rate) FROM members INNER JOIN wearables ON members.id = wearables.member_id WHERE members.age BETWEEN 25 AND 30 GROUP BY gender;
What was the average travel expenditure for US tourists visiting Costa Rica in 2019?
CREATE TABLE tourists (id INT,country VARCHAR(255),destination VARCHAR(255),year INT,expenditure DECIMAL(10,2)); INSERT INTO tourists (id,country,destination,year,expenditure) VALUES (1,'USA','Costa Rica',2019,1500),(2,'USA','Costa Rica',2019,1800),(3,'USA','Costa Rica',2019,1200),(4,'USA','Costa Rica',2018,1300),(5,'Canada','Costa Rica',2019,1000);
SELECT AVG(expenditure) FROM tourists WHERE country = 'USA' AND destination = 'Costa Rica' AND year = 2019;
List the number of wells in each country, sorted by the number of wells in descending order.
CREATE TABLE wells (well_id INT,well_name VARCHAR(255),location VARCHAR(255),country VARCHAR(255)); INSERT INTO wells (well_id,well_name,location,country) VALUES (1,'Well A','North Sea','UK'),(2,'Well B','North Sea','Norway'),(3,'Well C','Gulf of Mexico','USA'),(4,'Well D','South China Sea','Vietnam');
SELECT country, COUNT(*) AS num_wells FROM wells GROUP BY country ORDER BY num_wells DESC;
Which countries have the most wind power projects?
CREATE TABLE project_wind (project_name TEXT,country TEXT); INSERT INTO project_wind (project_name,country) VALUES ('Project A','Country A'),('Project B','Country A'),('Project C','Country B'),('Project D','Country C'),('Project E','Country D'),('Project F','Country D');
SELECT country, COUNT(*) FROM project_wind GROUP BY country ORDER BY COUNT(*) DESC;
What is the maximum health equity metric by region?
CREATE TABLE health_equity_metrics (region VARCHAR(10),metric INT); INSERT INTO health_equity_metrics (region,metric) VALUES ('North',90),('South',85),('East',95),('West',88);
SELECT region, MAX(metric) OVER (PARTITION BY 1) as max_metric FROM health_equity_metrics;
Display the total number of marine species in the Pacific Ocean.
CREATE TABLE marine_species_2 (name TEXT,location TEXT,num_individuals INT); INSERT INTO marine_species_2 (name,location,num_individuals) VALUES ('Clownfish','Indian Ocean','10000'),('Dolphin','Pacific Ocean','20000');
SELECT SUM(num_individuals) FROM marine_species_2 WHERE location = 'Pacific Ocean';
What are the total rare earth element reserves for each country?
CREATE TABLE country_reserves (country VARCHAR(50),reserves INT); INSERT INTO country_reserves (country,reserves) VALUES ('China',44000),('USA',1300),('Australia',3800),('India',674),('Brazil',220);
SELECT country, SUM(reserves) FROM country_reserves GROUP BY country;
What is the total number of vessels operating in the Pacific and Atlantic Oceans?
CREATE TABLE vessels_2 (vessel_id INT,name VARCHAR(255),operating_region VARCHAR(255));
SELECT COUNT(*) FROM vessels_2 WHERE operating_region IN ('Pacific', 'Atlantic');
What is the total number of cybersecurity incidents and the average severity for each department, partitioned by month and ordered by total number of cybersecurity incidents in descending order?
CREATE TABLE cybersecurity_incident (id INT,department_id INT,severity INT,incident_date DATE); INSERT INTO cybersecurity_incident (id,department_id,severity,incident_date) VALUES (1,1,8,'2021-03-15'); INSERT INTO cybersecurity_incident (id,department_id,severity,incident_date) VALUES (2,2,5,'2022-01-10'); CREATE TABLE department (id INT,name VARCHAR(255)); INSERT INTO department (id,name) VALUES (1,'IT'); INSERT INTO department (id,name) VALUES (2,'Security');
SELECT d.name as department, DATEPART(YEAR, incident_date) as year, DATEPART(MONTH, incident_date) as month, COUNT(ci.id) as total_cybersecurity_incidents, AVG(ci.severity) as avg_severity, ROW_NUMBER() OVER (PARTITION BY d.name ORDER BY COUNT(ci.id) DESC) as rank FROM cybersecurity_incident ci JOIN department d ON ci.department_id = d.id GROUP BY d.name, DATEPART(YEAR, incident_date), DATEPART(MONTH, incident_date) ORDER BY total_cybersecurity_incidents DESC;
Show the total fare collected per route and day of the week in the 'payment' and 'route' tables
CREATE SCHEMA IF NOT EXISTS public_transport;CREATE TABLE IF NOT EXISTS public_transport.payment (payment_id SERIAL PRIMARY KEY,passenger_id INTEGER,route_id INTEGER,fare DECIMAL,payment_date DATE);CREATE TABLE IF NOT EXISTS public_transport.route (route_id INTEGER PRIMARY KEY,route_name TEXT);INSERT INTO public_transport.payment (passenger_id,route_id,fare,payment_date) VALUES (1,101,2.50,'2021-10-01'),(2,102,4.00,'2021-10-02'),(3,101,2.00,'2021-10-03');INSERT INTO public_transport.route (route_id,route_name) VALUES (101,'Route A'),(102,'Route B');
SELECT EXTRACT(DOW FROM payment_date) AS day_of_week, route_id, SUM(fare) FROM public_transport.payment JOIN public_transport.route ON payment.route_id = route.route_id GROUP BY EXTRACT(DOW FROM payment_date), route_id;