instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
Which program had the most unique donors in Q1 2022?
CREATE TABLE Q1Donors (DonorID INT,Program VARCHAR(30)); INSERT INTO Q1Donors (DonorID,Program) VALUES (1,'Environment'),(2,'Education'),(3,'Environment'),(4,'Health'),(5,'Education');
SELECT Program, COUNT(DISTINCT DonorID) FROM Q1Donors WHERE Program IN ('Environment', 'Education', 'Health') GROUP BY Program ORDER BY COUNT(DISTINCT DonorID) DESC LIMIT 1;
What is the minimum lead time for warehouse transfers in the New York warehouse?
CREATE TABLE WarehouseTransfers (id INT,source_warehouse_id INT,destination_warehouse_id INT,lead_time INT); INSERT INTO WarehouseTransfers (id,source_warehouse_id,destination_warehouse_id,lead_time) VALUES (1,6,7,3),(2,6,7,5),(3,8,6,4); CREATE TABLE Warehouses (id INT,name TEXT,city TEXT,state TEXT); INSERT INTO Warehouses (id,name,city,state) VALUES (6,'New York Warehouse','New York','NY'),(7,'Chicago Warehouse','Chicago','IL'),(8,'Denver Warehouse','Denver','CO');
SELECT MIN(lead_time) FROM WarehouseTransfers JOIN Warehouses ON WarehouseTransfers.source_warehouse_id = Warehouses.id WHERE Warehouses.name = 'New York Warehouse';
What is the total number of packages shipped to the Midwest from all warehouses?
CREATE TABLE midwest_states (state_id INT,state_name VARCHAR(50)); INSERT INTO midwest_states (state_id,state_name) VALUES (1,'Illinois'),(2,'Indiana'),(3,'Iowa'),(4,'Kansas'),(5,'Michigan'),(6,'Minnesota'),(7,'Missouri'),(8,'Nebraska'),(9,'Ohio'),(10,'Wisconsin'); CREATE TABLE packages (package_id INT,package_weight INT,warehouse_id INT,recipient_state VARCHAR(50)); INSERT INTO packages (package_id,package_weight,warehouse_id,recipient_state) VALUES (1,5,1,'California'),(2,3,2,'Texas'),(3,4,3,'Illinois');
SELECT COUNT(package_id) FROM packages WHERE recipient_state IN (SELECT state_name FROM midwest_states);
Which startups in the 'StartupFunding' table received funding in 2020 or later and have a budget greater than $500,000?
CREATE SCHEMA BiotechStartups; CREATE TABLE StartupFunding (startup_name VARCHAR(50),funding_year INT,funding DECIMAL(10,2)); INSERT INTO StartupFunding VALUES ('StartupA',2019,500000),('StartupB',2020,750000);
SELECT startup_name FROM BiotechStartups.StartupFunding WHERE funding_year >= 2020 AND funding > 500000;
What are the names of journals where at least one professor from the Physics department has published?
CREATE TABLE Publications (PublicationID INT,Author VARCHAR(50),Journal VARCHAR(50),Year INT); INSERT INTO Publications (PublicationID,Author,Journal,Year) VALUES (1,'Alice','Journal of Physics',2020); INSERT INTO Publications (PublicationID,Author,Journal,Year) VALUES (2,'Bob','Journal of Chemistry',2019); INSERT INTO Publications (PublicationID,Author,Journal,Year) VALUES (3,'Carla','Journal of Physics',2021); INSERT INTO Professors (ProfessorID,Name,Department) VALUES (1,'Alice','Physics'); INSERT INTO Professors (ProfessorID,Name,Department) VALUES (2,'Bob','Chemistry');
SELECT Journal FROM Publications WHERE Author IN (SELECT Name FROM Professors WHERE Department = 'Physics');
Find the number of wind turbines installed in Germany in the year 2020.
CREATE TABLE renewable_energy (id INT,type TEXT,country TEXT,installation_year INT); INSERT INTO renewable_energy (id,type,country,installation_year) VALUES (1,'Wind Turbine','Germany',2020),(2,'Solar Panel','France',2019),(3,'Wind Turbine','Germany',2018);
SELECT COUNT(*) FROM renewable_energy WHERE type = 'Wind Turbine' AND country = 'Germany' AND installation_year = 2020;
Retrieve the project names and their costs for green building projects in the GreenBuildings schema
CREATE SCHEMA GreenBuildings; USE GreenBuildings; CREATE TABLE GreenBuildingProjects (id INT,project_name VARCHAR(100),cost DECIMAL(10,2)); INSERT INTO GreenBuildingProjects (id,project_name,cost) VALUES (1,'Solar Panel Installation',150000.00),(2,'Wind Turbine Installation',200000.00);
SELECT project_name, cost FROM GreenBuildings.GreenBuildingProjects;
Create a cross join table for mental health parity and community health workers
CREATE TABLE mental_health_parity (id INT PRIMARY KEY,state VARCHAR(2),year INT,accessibility FLOAT,quality FLOAT); CREATE TABLE community_health_workers (id INT PRIMARY KEY,state VARCHAR(2),year INT,workers_per_capita FLOAT,supervision_hours INT);
CREATE TABLE if not exists mental_health_parity_community_workers AS SELECT * FROM mental_health_parity CROSS JOIN community_health_workers WHERE FALSE;
Insert data into "hotel_sustainability" table with values "1", "Green Hotel", "Paris", "Recycling, Solar Power"
CREATE TABLE hotel_sustainability (hotel_id integer,name text,location text,sustainable_practices text);
INSERT INTO hotel_sustainability (hotel_id, name, location, sustainable_practices) VALUES (1, 'Green Hotel', 'Paris', 'Recycling, Solar Power');
List the names of all museums in Canada with a rating greater than 4.0 and having virtual tours.
CREATE TABLE museums (museum_id INT,name VARCHAR(255),country VARCHAR(255),rating FLOAT,virtual_tour BOOLEAN); INSERT INTO museums (museum_id,name,country,rating,virtual_tour) VALUES (1,'Royal Ontario Museum','Canada',4.4,TRUE),(2,'Montreal Museum of Fine Arts','Canada',4.1,FALSE),(3,'Vancouver Art Gallery','Canada',4.6,TRUE);
SELECT name FROM museums WHERE country = 'Canada' AND rating > 4.0 AND virtual_tour = TRUE;
What is the average revenue of virtual tours in 'Spain'?
CREATE TABLE virtual_tours (id INT,name TEXT,country TEXT,revenue FLOAT); INSERT INTO virtual_tours (id,name,country,revenue) VALUES (1,'Virtual Barcelona Tour','Spain',2000);
SELECT AVG(revenue) FROM virtual_tours WHERE country = 'Spain';
What is the maximum number of virtual tours taken by a single user in the UK?
CREATE TABLE virtual_tour_data (user_id INT,hotel_id INT,tour_date DATE); INSERT INTO virtual_tour_data (user_id,hotel_id,tour_date) VALUES (1,10,'2022-01-01'),(2,11,'2022-01-03'),(3,12,'2022-01-05'),(4,10,'2022-01-07'),(5,10,'2022-01-09'); CREATE TABLE hotels (hotel_id INT,hotel_name TEXT,country TEXT); INSERT INTO hotels (hotel_id,hotel_name,country) VALUES (10,'Royal Park Hotel','UK'),(11,'The Ritz London','UK'),(12,'Hotel de Crillon','France');
SELECT MAX(vt.user_tours) FROM (SELECT user_id, COUNT(DISTINCT hotel_id) as user_tours FROM virtual_tour_data WHERE country = 'UK' GROUP BY user_id) as vt;
What is the most recent exhibition for each artist?
CREATE TABLE artist_exhibitions (artist_id INT,exhibition_id INT,exhibition_title VARCHAR(255),exhibition_location VARCHAR(255),exhibition_start_date DATE); INSERT INTO artist_exhibitions (artist_id,exhibition_id,exhibition_title,exhibition_location,exhibition_start_date) VALUES (1,3,'Da Vinci Masterpieces','Metropolitan Museum','2024-01-01'); INSERT INTO artist_exhibitions (artist_id,exhibition_id,exhibition_title,exhibition_location,exhibition_start_date) VALUES (2,4,'Van Gogh and Expressionism','Museum of Modern Art','2025-01-01');
SELECT artist_id, exhibition_id, exhibition_title, exhibition_location, exhibition_start_date, ROW_NUMBER() OVER (PARTITION BY artist_id ORDER BY exhibition_start_date DESC) as rank FROM artist_exhibitions;
Update the language column of the record with id 4 in the heritage_sites table to 'French'.
CREATE TABLE heritage_sites (id INT,name VARCHAR(50),language VARCHAR(50)); INSERT INTO heritage_sites (id,name,language) VALUES (1,'Mesa Verde','English'),(2,'Old Quebec','French'),(3,'Chichen Itza','Mayan'),(4,'Angkor Wat','Khmer');
UPDATE heritage_sites SET language = 'French' WHERE id = 4;
What are the names of the heritage sites that were added to the list in the last 5 years, along with the year they were added?
CREATE TABLE UNESCO_Heritage_Sites (id INT,site VARCHAR(100),year INT); INSERT INTO UNESCO_Heritage_Sites (id,site,year) VALUES (1,'Colosseum',1980),(2,'Great Wall',1987),(3,'Alhambra',1984);
SELECT site, year FROM UNESCO_Heritage_Sites WHERE year >= YEAR(CURRENT_DATE) - 5;
Delete all records in the flights table where the carrier is WU"
CREATE TABLE flights (id INT PRIMARY KEY,carrier VARCHAR(3),flight_number INT,origin VARCHAR(3),destination VARCHAR(3),scheduled_departure TIMESTAMP,scheduled_arrival TIMESTAMP);
DELETE FROM flights WHERE carrier = 'WU';
How many marine species have been observed in the Indian Ocean, and what percentage of those are coral reef-dwelling species?
CREATE TABLE marine_species (id INT,name VARCHAR(100),region VARCHAR(50),coral_reef_dweller BOOLEAN,biomass FLOAT);
SELECT COUNT(ms.id) as total_species, 100.0 * SUM(CASE WHEN ms.coral_reef_dweller THEN 1 ELSE 0 END) / COUNT(ms.id) as coral_reef_percentage FROM marine_species ms WHERE ms.region = 'Indian Ocean';
List all the pollution control initiatives from the 'PollutionProjects' table
CREATE TABLE PollutionProjects (id INT PRIMARY KEY,name VARCHAR(255),location VARCHAR(255),start_date DATE,end_date DATE);
SELECT name FROM PollutionProjects;
What is the maximum average depth for ocean floor mapping project sites in the 'MarineResearch' schema?
CREATE SCHEMA MarineResearch; CREATE TABLE OceanFloorMapping (site_id INT,location VARCHAR(255),avg_depth DECIMAL(5,2)); INSERT INTO OceanFloorMapping (site_id,location,avg_depth) VALUES (1,'SiteA',3500.50),(2,'SiteB',4600.25),(3,'SiteC',2100.00);
SELECT MAX(avg_depth) FROM MarineResearch.OceanFloorMapping;
Update the names of all news agencies from country X to their official English names.
CREATE TABLE news_agencies (id INT,name TEXT,country TEXT); INSERT INTO news_agencies (id,name,country) VALUES (1,'Agency 1','Country X'); CREATE TABLE articles (id INT,title TEXT,agency_id INT); INSERT INTO articles (id,title,agency_id) VALUES (1,'Article 1',1);
UPDATE news_agencies SET name = CASE WHEN country = 'Country X' THEN 'Official English Name 1' ELSE name END;
What is the total monthly revenue of the 'Organic' product category?
CREATE TABLE Sales (SaleID INT,Product VARCHAR(50),Category VARCHAR(50),SaleDate DATE); INSERT INTO Sales (SaleID,Product,Category,SaleDate) VALUES (1,'Orange','Organic','2022-01-05'),(2,'Banana','Organic','2022-01-10');
SELECT SUM(SaleDate >= '2022-01-01' AND SaleDate < '2022-02-01') FROM Sales WHERE Category = 'Organic';
How many mining-related accidents happened in Ontario or British Columbia?
CREATE TABLE accident (id INT,location VARCHAR(50),type VARCHAR(20)); INSERT INTO accident (id,location,type) VALUES (1,'Ontario','mining'),(2,'British Columbia','drilling'),(3,'Alberta','extraction'),(4,'Quebec','prospecting');
SELECT COUNT(*) FROM accident WHERE location IN ('Ontario', 'British Columbia') AND type LIKE '%mining%';
What are the total amounts of copper and gold extracted by each company?
CREATE TABLE company (id INT,name VARCHAR(255));CREATE TABLE copper_extraction (company_id INT,amount INT);CREATE TABLE gold_extraction (company_id INT,amount INT);
SELECT c.name, SUM(ce.amount) as total_copper, SUM(ge.amount) as total_gold FROM company c LEFT JOIN copper_extraction ce ON c.id = ce.company_id LEFT JOIN gold_extraction ge ON c.id = ge.company_id GROUP BY c.name;
What is the maximum environmental impact score for a mine site in Q1 2023?
CREATE TABLE environmental_impact_q1_2023 (site_id INT,impact_score INT,impact_date DATE); INSERT INTO environmental_impact_q1_2023 (site_id,impact_score,impact_date) VALUES (5,70,'2023-01-15'),(5,75,'2023-02-20'),(5,80,'2023-03-31');
SELECT MAX(impact_score) FROM environmental_impact_q1_2023 WHERE impact_date BETWEEN '2023-01-01' AND '2023-03-31';
What is the total CO2 emission in the 'environmental_impact' table for the years 2018 and 2019?
CREATE TABLE environmental_impact (id INT,year INT,co2_emission FLOAT); INSERT INTO environmental_impact (id,year,co2_emission) VALUES (1,2018,12000.00); INSERT INTO environmental_impact (id,year,co2_emission) VALUES (2,2019,15000.00); INSERT INTO environmental_impact (id,year,co2_emission) VALUES (3,2020,18000.00);
SELECT SUM(co2_emission) FROM environmental_impact WHERE year IN (2018, 2019);
What is the distribution of articles by date for a specific news agency?
CREATE TABLE article_dates (id INT PRIMARY KEY,article_id INT,date DATE,FOREIGN KEY (article_id) REFERENCES articles(id));
SELECT date, COUNT(*) as total_articles FROM article_dates JOIN articles ON article_dates.article_id = articles.id WHERE articles.agency_id = 1 GROUP BY date;
What is the average ocean acidification level in each ocean?
CREATE TABLE ocean_acidification_data (location text,level decimal); INSERT INTO ocean_acidification_data (location,level) VALUES ('Pacific Ocean',8.2),('Atlantic Ocean',8.3),('Indian Ocean',8.1);
SELECT location, AVG(level) FROM ocean_acidification_data GROUP BY location;
Get the last session date of each player in 'game_sessions' table.
CREATE TABLE game_sessions (SessionID INT,PlayerID INT,SessionDate DATE); INSERT INTO game_sessions (SessionID,PlayerID,SessionDate) VALUES (1,1,'2021-06-01'); INSERT INTO game_sessions (SessionID,PlayerID,SessionDate) VALUES (2,2,'2021-06-10');
SELECT PlayerID, MAX(SessionDate) AS LastSessionDate FROM game_sessions GROUP BY PlayerID;
Identify the percentage of IoT devices with firmware version 3.x.x in the 'Asia' region.
CREATE TABLE IoTDevices (region VARCHAR(255),device_id INT,firmware_version VARCHAR(255)); INSERT INTO IoTDevices (region,device_id,firmware_version) VALUES ('Asia',1001,'3.4.5'),('Asia',1002,'3.5.1'),('Asia',1003,'3.4.8'),('Asia',1004,'3.6.0'),('Europe',1005,'2.3.2'),('Europe',1006,'2.5.1');
SELECT (COUNT(*) * 100.0 / (SELECT COUNT(*) FROM IoTDevices WHERE region = 'Asia')) AS Percentage FROM IoTDevices WHERE region = 'Asia' AND firmware_version LIKE '3.%';
What is the maximum temperature recorded for crop 'Rice'?
CREATE TABLE WeatherData (crop_type VARCHAR(20),temperature FLOAT,record_date DATE); INSERT INTO WeatherData (crop_type,temperature,record_date) VALUES ('Corn',22.5,'2022-01-01'); INSERT INTO WeatherData (crop_type,temperature,record_date) VALUES ('Rice',30.1,'2022-01-05');
SELECT MAX(temperature) FROM WeatherData WHERE crop_type = 'Rice';
How many public transport trips were taken in London, Paris, and Berlin for the last month, by hour?
CREATE TABLE Trips (City VARCHAR(50),TripDate DATE,Hour INT,NumberOfTrips INT); INSERT INTO Trips (City,TripDate,Hour,NumberOfTrips) VALUES ('London','2022-04-11',1,500),('London','2022-04-11',2,600),('London','2022-04-11',3,700),('Paris','2022-04-11',1,400),('Paris','2022-04-11',2,550),('Paris','2022-04-11',3,600),('Berlin','2022-04-11',1,300),('Berlin','2022-04-11',2,450),('Berlin','2022-04-11',3,500);
SELECT City, DATE_PART('hour', TripDate) as Hour, SUM(NumberOfTrips) as TotalTrips FROM Trips WHERE City IN ('London', 'Paris', 'Berlin') AND TripDate >= DATEADD(day, -30, CURRENT_DATE) GROUP BY City, Hour;
What is the average property tax for single-family homes in each neighborhood?
CREATE TABLE Neighborhoods (NeighborhoodID INT,Name VARCHAR(50),AveragePropertyTax FLOAT);CREATE TABLE Properties (PropertyID INT,NeighborhoodID INT,PropertyType VARCHAR(50),PropertyTax FLOAT);
SELECT N.Name, AVG(P.PropertyTax) as AvgPropertyTax FROM Properties P JOIN Neighborhoods N ON P.NeighborhoodID = N.NeighborhoodID WHERE P.PropertyType = 'Single-Family' GROUP BY N.Name;
What are the top 5 product categories with the highest average sales price across all stores?
CREATE TABLE stores (store_id INT,store_name VARCHAR(255));CREATE TABLE products (product_id INT,product_category VARCHAR(255),price DECIMAL(10,2));
SELECT product_category, AVG(price) as avg_price FROM products JOIN stores ON products.store_id = stores.store_id GROUP BY product_category ORDER BY avg_price DESC LIMIT 5;
List the number of space missions launched by each country, grouped by the continent where the country is located, and show the total number of missions for each continent.
CREATE TABLE Space_Missions (id INT,mission_name VARCHAR(255),country VARCHAR(255),launch_date DATE); CREATE TABLE Countries (id INT,country VARCHAR(255),continent VARCHAR(255));
SELECT c.continent, COUNT(sm.country) as total_missions FROM Space_Missions sm JOIN Countries c ON sm.country = c.country GROUP BY c.continent;
What is the count of missions involving a spacecraft with model Y, grouped by year?
CREATE TABLE MissionSpacecraft (id INT,mission_year INT,spacecraft_model VARCHAR(20));
SELECT mission_year, COUNT(*) FROM MissionSpacecraft WHERE spacecraft_model = 'Y' GROUP BY mission_year;
Compare the number of electric and autonomous vehicles in New York and Los Angeles.
CREATE TABLE if not exists UsEvaCount(state CHAR(2),city CHAR(10),ev_count INT,av_count INT); INSERT INTO UsEvaCount(state,city,ev_count,av_count) VALUES ('NY','NewYork',1200,500),('NY','NewYork',1250,550),('NY','LosAngeles',1500,600),('NY','LosAngeles',1450,650);
SELECT city, ev_count, av_count FROM UsEvaCount WHERE state IN ('NY') AND city IN ('NewYork', 'LosAngeles') GROUP BY city;
Identify policyholders who have not submitted any claims in the last 6 months.
CREATE TABLE Policy (PolicyNumber INT,PolicyholderName VARCHAR(50)); CREATE TABLE Claim (ClaimID INT,PolicyNumber INT,ClaimDate DATE); INSERT INTO Policy VALUES (1,'John Doe'),(2,'Jane Smith'); INSERT INTO Claim VALUES (1,1,'2021-01-01'),(2,1,'2021-02-01'),(3,2,'2021-04-01');
SELECT PolicyNumber, PolicyholderName FROM Policy WHERE PolicyNumber NOT IN (SELECT PolicyNumber FROM Claim WHERE ClaimDate > DATEADD(month, -6, GETDATE()));
What is the average number of workplace safety incidents for each union in the healthcare industry?
CREATE TABLE union_healthcare (union_id INT,union_name TEXT,industry TEXT,incidents INT); INSERT INTO union_healthcare (union_id,union_name,industry,incidents) VALUES (1,'Union X','Healthcare',20),(2,'Union Y','Healthcare',15),(3,'Union Z','Education',10);
SELECT AVG(incidents) FROM union_healthcare WHERE industry = 'Healthcare';
What is the average salary of female members in the 'construction' industry with a membership duration greater than 5 years?
CREATE TABLE union_members (id INT,gender VARCHAR(10),industry VARCHAR(20),salary INT,membership_duration INT); INSERT INTO union_members (id,gender,industry,salary,membership_duration) VALUES (1,'Female','Construction',50000,6);
SELECT AVG(salary) FROM union_members WHERE gender = 'Female' AND industry = 'Construction' AND membership_duration > 5;
What is the average salary of workers in the 'Finance' industry who are not part of a union?
CREATE TABLE workers (id INT,industry VARCHAR(255),salary FLOAT,union_member BOOLEAN); INSERT INTO workers (id,industry,salary,union_member) VALUES (1,'Manufacturing',50000.0,true),(2,'Finance',70000.0,false),(3,'Retail',30000.0,false);
SELECT AVG(salary) FROM workers WHERE industry = 'Finance' AND union_member = false;
What is the total capacity of all vessels?
CREATE TABLE Vessels (ID VARCHAR(20),Name VARCHAR(20),Type VARCHAR(20),Capacity INT); INSERT INTO Vessels VALUES ('V024','Vessel X','Cargo',12000),('V025','Vessel Y','Cargo',15000),('V026','Vessel Z','Passenger',2000);
SELECT SUM(Capacity) FROM Vessels;
Find the unique languages spoken by visitors aged between 30 and 50 from South America.
CREATE TABLE visitors (id INT,name VARCHAR(100),country VARCHAR(50),age INT,language VARCHAR(50)); INSERT INTO visitors (id,name,country,age,language) VALUES (1,'Jose Garcia','Brazil',40,'Portuguese'),(2,'Maria Rodriguez','Argentina',35,'Spanish');
SELECT DISTINCT language FROM visitors WHERE age BETWEEN 30 AND 50 AND country LIKE 'South%';
What is the number of unique visitors from each country?
CREATE TABLE Countries (id INT,name VARCHAR(20)); ALTER TABLE Visitors ADD COLUMN country_id INT;
SELECT Countries.name, COUNT(DISTINCT Visitors.id) FROM Visitors JOIN Countries ON Visitors.country_id = Countries.id GROUP BY Countries.name;
What is the average recycling rate in South America?
CREATE TABLE recycling_rates (country VARCHAR(50),recycling_rate DECIMAL(5,2)); INSERT INTO recycling_rates (country,recycling_rate) VALUES ('Brazil',50.0),('Argentina',40.0),('Colombia',35.0);
SELECT AVG(recycling_rate) FROM recycling_rates WHERE country IN ('Brazil', 'Argentina', 'Colombia', 'Peru', 'Chile');
Find the average daily water consumption in cubic meters for 'Los Angeles' during the drought of 2016
CREATE TABLE drought_info (region VARCHAR(50),start_date DATE,end_date DATE); INSERT INTO drought_info (region,start_date,end_date) VALUES ('Los Angeles','2016-01-01','2016-12-31'); CREATE TABLE daily_consumption (region VARCHAR(50),date DATE,consumption FLOAT); INSERT INTO daily_consumption (region,date,consumption) VALUES ('Los Angeles','2016-01-01',1200),('Los Angeles','2016-01-02',1100),('Los Angeles','2016-01-03',1300);
SELECT AVG(consumption) FROM daily_consumption WHERE region = 'Los Angeles' AND date BETWEEN '2016-01-01' AND '2016-12-31';
How many water treatment facilities are there in each country, and what is their distribution by continent?
CREATE TABLE facilities (id INT,facility_name VARCHAR(50),country VARCHAR(50),total_employees INT); INSERT INTO facilities (id,facility_name,country,total_employees) VALUES (1,'Water Treatment Plant 1','Brazil',25); INSERT INTO facilities (id,facility_name,country,total_employees) VALUES (2,'Water Treatment Plant 2','India',30);
SELECT country, COUNT(*) as facility_count, CONTINENT(location) as continent FROM facilities JOIN countries ON facilities.country = countries.country_name GROUP BY country, continent;
What is the explainability score for each AI algorithm, partitioned by algorithm type, ordered by score in descending order?
CREATE TABLE ai_algorithms_explainability (algorithm_id INT,algorithm_name VARCHAR(50),explainability_score DECIMAL(5,2)); INSERT INTO ai_algorithms_explainability (algorithm_id,algorithm_name,explainability_score) VALUES (1,'Decision Tree',0.93),(2,'Logistic Regression',0.91),(3,'K-Nearest Neighbors',0.87),(4,'Naive Bayes',0.85);
SELECT algorithm_name, AVG(explainability_score) as avg_explainability_score FROM ai_algorithms_explainability GROUP BY algorithm_name ORDER BY avg_explainability_score DESC;
Update the name of the project to 'Solar Irrigation' in the 'rural_projects' table
CREATE TABLE rural_projects (id INT,project_name VARCHAR(255),country VARCHAR(255));
UPDATE rural_projects SET project_name = 'Solar Irrigation' WHERE id = 1;
What was the sum of agricultural innovation metrics reported in Senegal in 2020?
CREATE TABLE Metrics (id INT,metric_id INT,metric_type VARCHAR(20),country VARCHAR(20),report_date DATE); INSERT INTO Metrics (id,metric_id,metric_type,country,report_date) VALUES (1,5001,'Agricultural Innovation','Senegal','2020-01-01'),(2,5002,'Economic Diversification','Senegal','2020-02-15'),(3,5003,'Agricultural Innovation','Senegal','2020-03-31');
SELECT SUM(CASE WHEN metric_type = 'Agricultural Innovation' THEN 1 ELSE 0 END) FROM Metrics WHERE country = 'Senegal' AND YEAR(report_date) = 2020;
Remove all records for aircraft models that were never involved in a safety incident from the flight_safety table
CREATE TABLE flight_safety (id INT PRIMARY KEY,aircraft_model VARCHAR(100),manufacturer VARCHAR(100),severity VARCHAR(50),report_date DATE);
DELETE FROM flight_safety WHERE aircraft_model NOT IN (SELECT aircraft_model FROM flight_safety GROUP BY aircraft_model HAVING COUNT(*) > 0);
What is the average age of all active astronauts by country of origin?
CREATE TABLE Astronauts (AstronautID INT,CountryOfOrigin VARCHAR(50),Active BOOLEAN,Age INT);
SELECT CountryOfOrigin, AVG(Age) AS AvgAge FROM Astronauts WHERE Active = TRUE GROUP BY CountryOfOrigin;
Count the number of distinct animal types in the 'animal_population' table.
CREATE TABLE animal_population (animal_id INT,animal_type VARCHAR(10),age INT); INSERT INTO animal_population (animal_id,animal_type,age) VALUES (1,'lion',3); INSERT INTO animal_population (animal_id,animal_type,age) VALUES (2,'tiger',4); INSERT INTO animal_population (animal_id,animal_type,age) VALUES (3,'lion',5);
SELECT COUNT(DISTINCT animal_type) FROM animal_population;
What is the total number of animals adopted by each community?
CREATE TABLE CommunityEducation(Community VARCHAR(20),AnimalsAdopted INT); INSERT INTO CommunityEducation VALUES ('CommunityA',35),('CommunityB',28),('CommunityC',42);
SELECT Community, SUM(AnimalsAdopted) FROM CommunityEducation GROUP BY Community;
Count the number of aquatic farms in each country from the 'farms' table.
CREATE TABLE farms (id INT PRIMARY KEY,name VARCHAR(50),species VARCHAR(50),country VARCHAR(50),size INT); INSERT INTO farms (id,name,species,country,size) VALUES (1,'Farm A','Salmon','Norway',500),(2,'Farm B','Tilapia','Egypt',250),(3,'Farm C','Cod','Canada',800),(4,'Farm D','Prawns','India',300);
SELECT country, COUNT(*) FROM farms GROUP BY country;
Determine the maximum sustainable yield of Catfish in the Pacific Ocean in 2024.
CREATE TABLE msy (species VARCHAR(255),msy_value FLOAT,year INT,region VARCHAR(255),PRIMARY KEY (species,year,region)); INSERT INTO msy (species,msy_value,year,region) VALUES ('Catfish',22000,2024,'Pacific Ocean'),('Tuna',35000,2024,'Pacific Ocean'),('Salmon',18000,2024,'Atlantic Ocean');
SELECT msy_value FROM msy WHERE species = 'Catfish' AND year = 2024 AND region = 'Pacific Ocean';
What is the average stocking density of Tilapia in freshwater farms in Indonesia?
CREATE TABLE freshwater_farms (farmer_id INT,fish_species TEXT,stocking_density FLOAT); INSERT INTO freshwater_farms (farmer_id,fish_species,stocking_density) VALUES (1,'Tilapia',1.5),(2,'Catfish',2.0),(3,'Tilapia',2.5);
SELECT AVG(stocking_density) FROM freshwater_farms WHERE fish_species = 'Tilapia' AND country = 'Indonesia';
What was the total attendance at dance programs by age group in 2020?
CREATE TABLE Attendance (id INT,age_group VARCHAR(10),program VARCHAR(20),attendance INT); INSERT INTO Attendance (id,age_group,program,attendance) VALUES (1,'5-10','Dance',50),(2,'11-15','Dance',75),(3,'16-20','Dance',100);
SELECT program, age_group, SUM(attendance) as total_attendance FROM Attendance WHERE program = 'Dance' AND YEAR(event_date) = 2020 GROUP BY program, age_group;
What is the average price per gram of concentrates for each producer in California?
CREATE TABLE Producers (ProducerID INT,Name VARCHAR(100),State VARCHAR(100)); CREATE TABLE Products (ProductID INT,ProductName VARCHAR(100),ProducerID INT,PricePerGram DECIMAL(5,2),Type VARCHAR(100));
SELECT P.Name, AVG(P.PricePerGram) as AvgPricePerGram FROM Products P JOIN Producers PR ON P.ProducerID = PR.ProducerID WHERE PR.State = 'California' AND P.Type = 'Concentrates' GROUP BY P.Name;
How many cases were handled by attorneys who identify as Latinx and have more than 5 years of experience?
CREATE TABLE attorneys (id INT,name VARCHAR(50),years_of_experience INT,ethnicity VARCHAR(50)); INSERT INTO attorneys (id,name,years_of_experience,ethnicity) VALUES (1,'John Doe',12,'White'); INSERT INTO attorneys (id,name,years_of_experience,ethnicity) VALUES (2,'Jane Smith',3,'White'); INSERT INTO attorneys (id,name,years_of_experience,ethnicity) VALUES (3,'Carlos Rodriguez',7,'Latinx'); INSERT INTO attorneys (id,name,years_of_experience,ethnicity) VALUES (4,'Maria Garcia',12,'Latinx');
SELECT COUNT(*) FROM attorneys WHERE ethnicity = 'Latinx' AND years_of_experience > 5;
Update the safety protocol for 'Product K' from 'Protocol 4' to 'Protocol 7' in the safety_protocols table.
CREATE TABLE chemical_products (id INT,name TEXT); CREATE TABLE safety_protocols (id INT,product_id INT,protocol TEXT);
UPDATE safety_protocols SET protocol = 'Protocol 7' WHERE product_id = (SELECT id FROM chemical_products WHERE name = 'Product K') AND protocol = 'Protocol 4';
What is the production cost of each chemical product, grouped by the manufacturer?
CREATE TABLE ChemicalProducts (ProductID INT,ProductName TEXT,Manufacturer TEXT,ProductionCost DECIMAL(5,2)); INSERT INTO ChemicalProducts (ProductID,ProductName,Manufacturer,ProductionCost) VALUES (1,'Product A','Manufacturer X',50.5),(2,'Product B','Manufacturer Y',75.3),(3,'Product C','Manufacturer X',25.5),(4,'Product D','Manufacturer Z',150.3);
SELECT Manufacturer, SUM(ProductionCost) AS TotalProductionCost FROM ChemicalProducts GROUP BY Manufacturer;
What is the number of 'climate communication' campaigns launched in 'Europe' in '2022' from the 'communication' table?
CREATE TABLE communication (region VARCHAR(255),campaigns INT,year INT);
SELECT COUNT(*) FROM communication WHERE region = 'Europe' AND year = 2022;
What is the total funding allocated for climate change adaptation projects in 2018 and 2020?
CREATE TABLE climate_adaptation_funding(project_id INT,year INT,amount FLOAT); INSERT INTO climate_adaptation_funding (project_id,year,amount) VALUES (30,2018,75000.0),(31,2019,90000.0),(32,2020,60000.0);
SELECT SUM(amount) FROM climate_adaptation_funding WHERE year IN (2018, 2020);
Find the drugs and their respective total sales for rare diseases indication with sales greater than the average sales for infectious diseases.
CREATE TABLE sales (id INT,drug_id INT,quarter INT,year INT,revenue FLOAT); INSERT INTO sales (id,drug_id,quarter,year,revenue) VALUES (1,1,1,2022,1500000); CREATE TABLE drugs (id INT,name VARCHAR(50),company VARCHAR(50),indication VARCHAR(50)); INSERT INTO drugs (id,name,company,indication) VALUES (1,'DrugA','ABC Corp','Rare_Diseases');
SELECT s.drug_id, d.name, SUM(s.revenue) as total_sales FROM sales s JOIN drugs d ON s.drug_id = d.id WHERE d.indication = 'Rare_Diseases' GROUP BY s.drug_id HAVING total_sales > (SELECT AVG(s2.revenue) FROM sales s2 JOIN drugs d2 ON s2.drug_id = d2.id WHERE d2.indication = 'Infectious_Diseases')
What is the total number of healthcare providers by type?
CREATE TABLE providers (provider_id INT,provider_type VARCHAR(20)); INSERT INTO providers (provider_id,provider_type) VALUES (1,'Physician'),(2,'Nurse Practitioner'),(3,'Physician Assistant');
SELECT provider_type, COUNT(*) as total_providers FROM providers GROUP BY provider_type;
Delete all records from the "company_profiles" table where the company's founding year is before 2000
CREATE TABLE company_profiles (company_name VARCHAR(255),founding_year INT,diversity_metric FLOAT);
DELETE FROM company_profiles WHERE founding_year < 2000;
Drop the disability accommodations table
CREATE TABLE disability_accommodations (id INT PRIMARY KEY,student_id INT,accommodation_type VARCHAR(255),start_date DATE,end_date DATE);
DROP TABLE disability_accommodations;
How many marine species are endemic to the Coral Triangle?
CREATE TABLE marine_species (id INT,species VARCHAR(255),endemic_coral_triangle BOOLEAN); INSERT INTO marine_species (id,species,endemic_coral_triangle) VALUES (1,'Clownfish',TRUE);
SELECT COUNT(*) FROM marine_species WHERE endemic_coral_triangle = TRUE
How many smart contracts were deployed each month in 2023?
CREATE TABLE smart_contracts (contract_address VARCHAR(42),deployment_date DATE); INSERT INTO smart_contracts (contract_address,deployment_date) VALUES ('0x123','2023-01-01'),('0x456','2023-01-15'),('0x789','2023-02-01'),('0xabc','2023-02-15'),('0xdef','2023-03-01');
SELECT EXTRACT(MONTH FROM deployment_date) AS month, COUNT(*) FROM smart_contracts GROUP BY month ORDER BY month;
Update carbon sequestration data for India in 2021
CREATE TABLE carbon_sequestration (country_code CHAR(3),year INT,sequestration FLOAT); INSERT INTO carbon_sequestration (country_code,year,sequestration) VALUES ('IND',2021,1.2),('IND',2020,1.1),('CHN',2021,4.1),('CHN',2020,3.9);
UPDATE carbon_sequestration SET sequestration = 1.3 WHERE country_code = 'IND' AND year = 2021;
What is the total volume of timber sold by each salesperson, broken down by month?
CREATE TABLE salesperson (salesperson_id INT,name TEXT,region TEXT); INSERT INTO salesperson (salesperson_id,name,region) VALUES (1,'John Doe','North'),(2,'Jane Smith','South'); CREATE TABLE timber_sales (sales_id INT,salesperson_id INT,volume REAL,sale_date DATE); INSERT INTO timber_sales (sales_id,salesperson_id,volume,sale_date) VALUES (1,1,120,'2021-01-01'),(2,1,150,'2021-02-01'),(3,2,180,'2021-01-01');
SELECT salesperson_id, DATE_PART('month', sale_date) as month, SUM(volume) as total_volume FROM timber_sales JOIN salesperson ON timber_sales.salesperson_id = salesperson.salesperson_id GROUP BY salesperson_id, month ORDER BY salesperson_id, month;
How many products are sourced from fair-trade suppliers?
CREATE TABLE products (product_id INT PRIMARY KEY,fair_trade BOOLEAN); INSERT INTO products (product_id,fair_trade) VALUES (1,true),(2,false),(3,true),(4,false);
SELECT COUNT(*) FROM products WHERE fair_trade = true;
What is the average weight of ingredients for a given product?
CREATE TABLE ingredients (ingredient_id INT,product_id INT,weight FLOAT); INSERT INTO ingredients VALUES (1,1,2.5),(2,1,3.5),(3,2,1.5),(4,2,4.5);
SELECT AVG(weight) FROM ingredients WHERE product_id = 1;
What is the percentage of cruelty-free haircare products in the European market?
CREATE TABLE products(product_id INT,product_name VARCHAR(50),is_cruelty_free BOOLEAN,product_category VARCHAR(50)); INSERT INTO products VALUES (5,'Argan Oil Shampoo',TRUE,'Haircare'); INSERT INTO products VALUES (6,'Keratin Conditioner',FALSE,'Haircare'); CREATE TABLE sales(product_id INT,sale_date DATE,quantity INT,country VARCHAR(50)); INSERT INTO sales VALUES (5,'2021-03-25',20,'DE'); INSERT INTO sales VALUES (6,'2021-03-26',10,'FR');
SELECT ROUND(COUNT(CASE WHEN products.is_cruelty_free THEN 1 END)/COUNT(*) * 100, 2) as percentage FROM products JOIN sales ON products.product_id = sales.product_id WHERE products.product_category = 'Haircare' AND sales.country = 'Europe';
List all disaster types and their respective average preparedness scores, for the year 2017, from the 'DisasterPreparedness' table.
CREATE TABLE DisasterPreparedness (id INT,year INT,disasterType VARCHAR(30),score INT);
SELECT disasterType, AVG(score) FROM DisasterPreparedness WHERE year = 2017 GROUP BY disasterType;
What is the percentage of crimes reported in the city of Miami that were violent crimes in the year 2019?
CREATE TABLE crimes (id INT,city VARCHAR(20),year INT,violent_crime BOOLEAN); INSERT INTO crimes (id,city,year,violent_crime) VALUES (1,'Miami',2019,true),(2,'Miami',2019,false),(3,'Miami',2019,true);
SELECT (COUNT(*) FILTER (WHERE violent_crime)) * 100.0 / COUNT(*) FROM crimes WHERE city = 'Miami' AND year = 2019;
What is the total number of military equipment types maintained by each division?
CREATE TABLE division (division_id INT,division_name VARCHAR(50)); INSERT INTO division (division_id,division_name) VALUES (1,'Aviation'),(2,'Ground'),(3,'Naval'); CREATE TABLE equipment (equipment_id INT,equipment_name VARCHAR(50),division_id INT); INSERT INTO equipment (equipment_id,equipment_name,division_id) VALUES (1,'F-16 Fighting Falcon',1),(2,'M1 Abrams',2),(3,'USS Gerald R. Ford',3);
SELECT division_id, COUNT(DISTINCT equipment_name) as total_equipment_types FROM equipment GROUP BY division_id;
Rank the cargoes by their quantities in descending order, partitioned by the vessel they belong to.
CREATE TABLE Cargo (CargoID INT,CargoName VARCHAR(50),Quantity INT,VesselID INT); INSERT INTO Cargo (CargoID,CargoName,Quantity,VesselID) VALUES (1,'Electronics',5000,1); INSERT INTO Cargo (CargoID,CargoName,Quantity,VesselID) VALUES (2,'Clothing',3000,2); CREATE TABLE Vessel (VesselID INT,VesselName VARCHAR(50),GrossTonnage INT); INSERT INTO Vessel (VesselID,VesselName,GrossTonnage) VALUES (1,'Ever Ace',235000); INSERT INTO Vessel (VesselID,VesselName,GrossTonnage) VALUES (2,'Algeciras',128000);
SELECT CargoName, Quantity, RANK() OVER (PARTITION BY VesselID ORDER BY Quantity DESC) AS Rank FROM Cargo;
What is the average weight of cargo for vessels in the 'Tanker' type that were built after 2000?
CREATE TABLE ships (id INT,name VARCHAR(50),type VARCHAR(50),year_built INT,max_capacity INT,port_id INT); CREATE TABLE cargos (id INT,description VARCHAR(50),weight FLOAT,port_id INT,ship_id INT); CREATE VIEW ship_cargo AS SELECT s.name AS ship_name,c.description AS cargo_description,c.weight FROM ships s JOIN cargos c ON s.id = c.ship_id;
SELECT AVG(c.weight) AS avg_weight FROM ships s JOIN cargos c ON s.id = c.ship_id WHERE s.type = 'Tanker' AND s.year_built > 2000;
What is the total amount spent on raw materials for the 'textile' industry for the entire year of 2021?
CREATE TABLE expenses (expense_id INT,date DATE,category VARCHAR(20),amount FLOAT); INSERT INTO expenses (expense_id,date,category,amount) VALUES (1,'2021-01-01','textile',2500),(2,'2021-05-15','tooling',1500),(3,'2021-12-31','textile',5000);
SELECT SUM(amount) FROM expenses WHERE category = 'textile' AND date BETWEEN '2021-01-01' AND '2021-12-31';
Identify the excavation site with the least number of bone fragments.
CREATE TABLE SiteN (site_id INT,site_name VARCHAR(20),artifact_type VARCHAR(20),quantity INT); INSERT INTO SiteN (site_id,site_name,artifact_type,quantity) VALUES (1,'SiteN','Bone Fragments',5),(2,'SiteO','Pottery',20),(3,'SiteP','Bone Fragments',15);
SELECT site_name FROM SiteN WHERE artifact_type = 'Bone Fragments' GROUP BY site_name HAVING SUM(quantity) = (SELECT MIN(quantity) FROM (SELECT SUM(quantity) as quantity FROM SiteN WHERE artifact_type = 'Bone Fragments' GROUP BY site_name) as subquery);
What is the total number of patients diagnosed with 'Anxiety' or 'Depression' in 'RuralHealthFacility8'?
CREATE TABLE RuralHealthFacility8 (id INT,name TEXT,diagnosis TEXT); INSERT INTO RuralHealthFacility8 (id,name,diagnosis) VALUES (1,'Ivan Purple','Anxiety'),(2,'Judy Orange','Depression');
SELECT COUNT(*) FROM RuralHealthFacility8 WHERE diagnosis IN ('Anxiety', 'Depression');
How many unique social causes has investor ABC supported?
CREATE TABLE investor_activities (investor VARCHAR(20),cause VARCHAR(30)); INSERT INTO investor_activities (investor,cause) VALUES ('XYZ','climate change'),('XYZ','poverty reduction'),('ABC','climate change');
SELECT COUNT(DISTINCT cause) FROM investor_activities WHERE investor = 'ABC';
List all social impact investments in the Agriculture sector with ESG scores above 85, ordered by investment date and ESG score, including only investments made by French investors.
CREATE TABLE SocialImpactInvestments (InvestmentID INT,InvestmentDate DATE,Sector VARCHAR(20),ESGScore INT,InvestorCountry VARCHAR(20)); INSERT INTO SocialImpactInvestments VALUES (1,'2021-01-01','Agriculture',86,'France'),(2,'2021-02-01','Healthcare',75,'Germany'),(3,'2021-03-01','Agriculture',82,'France');
SELECT * FROM SocialImpactInvestments WHERE Sector = 'Agriculture' AND ESGScore > 85 AND InvestorCountry = 'France' ORDER BY InvestmentDate, ESGScore DESC;
How many unique volunteers participated in programs in New York?
CREATE TABLE VolunteerEvents (EventID INT,EventName TEXT,Location TEXT,EventType TEXT); INSERT INTO VolunteerEvents (EventID,EventName,Location,EventType) VALUES (1,'Tutoring Session','Texas','Education'),(2,'Coding Workshop','New York','Education'); CREATE TABLE VolunteerHours (HourID INT,VolunteerID INT,EventID INT,Hours INT,HourDate DATE); INSERT INTO VolunteerHours (HourID,VolunteerID,EventID,Hours,HourDate) VALUES (1,1,1,5,'2022-01-01'),(2,2,1,6,'2022-01-01');
SELECT COUNT(DISTINCT VolunteerID) FROM VolunteerHours JOIN VolunteerEvents ON VolunteerHours.EventID = VolunteerEvents.EventID WHERE VolunteerEvents.Location = 'New York';
How many professional development courses did each teacher complete, ordered by the number of courses completed?
CREATE TABLE teacher_pd (teacher_id INT,course_id INT); INSERT INTO teacher_pd (teacher_id,course_id) VALUES (1,1001),(2,1002),(3,1003),(4,1004),(5,1005),(1,1006),(2,1007);
SELECT teacher_id, COUNT(course_id) as num_courses FROM teacher_pd GROUP BY teacher_id ORDER BY num_courses DESC;
How many solar energy projects have been completed in Germany and Spain?
CREATE TABLE solar_projects (country VARCHAR(20),completed BOOLEAN); INSERT INTO solar_projects (country,completed) VALUES ('Germany',true),('Germany',true),('Spain',true),('Spain',true),('Spain',true);
SELECT COUNT(*) FROM solar_projects WHERE country IN ('Germany', 'Spain') AND completed = true;
Insert a new record into the "carbon_prices" table for the date 2022-02-01 with a price of 25.25
CREATE TABLE carbon_prices (id INT,date DATE,price FLOAT);
INSERT INTO carbon_prices (id, date, price) VALUES (1, '2022-02-01', 25.25);
Insert new records into the 'renewable_energy_production' table for wind and solar production in 'Texas' and 'California'
CREATE TABLE renewable_energy_production (id INT PRIMARY KEY,source VARCHAR(255),state VARCHAR(255),production_gwh FLOAT);
INSERT INTO renewable_energy_production (source, state, production_gwh) VALUES ('wind', 'Texas', 50), ('solar', 'Texas', 75), ('wind', 'California', 60), ('solar', 'California', 80);
What are the names of cricket players who have scored a century in Australia?
CREATE TABLE Matches (MatchID INT,Team1 VARCHAR(50),Team2 VARCHAR(50),Venue VARCHAR(50),Country VARCHAR(50)); INSERT INTO Matches (MatchID,Team1,Team2,Venue,Country) VALUES (1,'Australia','India','Melbourne Cricket Ground','Australia'); CREATE TABLE Players (PlayerID INT,Name VARCHAR(50),Team VARCHAR(50),Country VARCHAR(50)); INSERT INTO Players (PlayerID,Name,Team,Country) VALUES (1,'Virat Kohli','India','India'); CREATE TABLE Scores (ScoreID INT,Player VARCHAR(50),Runs INT,MatchID INT); INSERT INTO Scores (ScoreID,Player,Runs,MatchID) VALUES (1,'Virat Kohli',100,1);
SELECT DISTINCT P.Name FROM Players P INNER JOIN Scores S ON P.PlayerID = S.Player WHERE S.Runs = 100 AND S.MatchID IN (SELECT MatchID FROM Matches WHERE Venue = 'Melbourne Cricket Ground' AND Country = 'Australia');
List the number of advocacy campaigns and their total budget for each year.
CREATE TABLE years (id INT,name VARCHAR(255)); CREATE TABLE campaigns (id INT,year_id INT,name VARCHAR(255),budget FLOAT);
SELECT y.name as year_name, COUNT(campaigns.id) as campaign_count, SUM(campaigns.budget) as total_budget FROM years y LEFT JOIN campaigns ON y.id = campaigns.year_id GROUP BY y.id;
What is the rank of each volunteer by age within their skill?
CREATE TABLE volunteers (id INT,name TEXT,age INT,gender TEXT,skill TEXT,location TEXT); INSERT INTO volunteers (id,name,age,gender,skill,location) VALUES (1,'John Doe',30,'Male','Medical','New York'); INSERT INTO volunteers (id,name,age,gender,skill,location) VALUES (2,'Jane Smith',28,'Female','Engineering','Los Angeles');
SELECT *, RANK() OVER (PARTITION BY skill ORDER BY age) as rank FROM volunteers;
How many technology accessibility projects were launched in total?
CREATE TABLE acc_proj (name TEXT,launch_year INTEGER,accessible TEXT); INSERT INTO acc_proj (name,launch_year,accessible) VALUES ('AccProj1',2021,'yes'),('AccProj2',2022,'no'),('AccProj3',2022,'yes');
SELECT COUNT(*) FROM acc_proj WHERE accessible = 'yes';
How many trains in Tokyo have a delay greater than 5 minutes?
CREATE TABLE trains (id INT,city VARCHAR(50),delay TIME); INSERT INTO trains (id,city,delay) VALUES (1,'Tokyo','00:07'),(2,'Tokyo','00:03'),(3,'Paris','00:10'),(4,'Paris','00:02');
SELECT COUNT(*) FROM trains WHERE city = 'Tokyo' AND delay > '00:05:00';
What is the total amount spent on recycled materials in the last 6 months?
CREATE TABLE expenses(expense_id INT,date DATE,material VARCHAR(20),amount DECIMAL(5,2)); INSERT INTO expenses(expense_id,date,material,amount) VALUES(1,'2022-01-01','recycled cotton',100.00),(2,'2022-01-15','recycled polyester',150.00),(3,'2022-02-01','recycled cotton',200.00);
SELECT SUM(amount) FROM expenses WHERE material IN ('recycled cotton', 'recycled polyester') AND date >= DATE_SUB(CURRENT_DATE, INTERVAL 6 MONTH);
What is the maximum financial capability score in Africa?
CREATE TABLE financial_capability (client_id INT,country VARCHAR(50),score DECIMAL(3,2)); INSERT INTO financial_capability (client_id,country,score) VALUES (1,'South Africa',82.7),(2,'Egypt',78.4),(3,'Nigeria',88.3);
SELECT MAX(score) FROM financial_capability WHERE country = 'Africa';
Delete all records of product Z from the Food table.
CREATE TABLE Food (FoodID varchar(10),FoodName varchar(20)); INSERT INTO Food VALUES ('Z','Product Z');
DELETE FROM Food WHERE FoodID = 'Z';
Find the top 2 most expensive fruits in the "Produce_2022" table
CREATE TABLE Produce_2022 (id INT,name VARCHAR(50),type VARCHAR(20),price DECIMAL(5,2)); INSERT INTO Produce_2022 (id,name,type,price) VALUES (1,'Mangoes','Organic',2.49),(2,'Pineapples','Organic',3.59),(3,'Avocados','Organic',1.99),(4,'Strawberries','Organic',4.99);
SELECT name, price FROM Produce_2022 WHERE type = 'Organic' AND name LIKE 'Fruits' ORDER BY price DESC LIMIT 2;
What is the minimum and maximum serving size for vegan meals in the United States?
CREATE TABLE MealSizes(id INT,name TEXT,serving_size INT,is_vegan BOOLEAN,country TEXT); INSERT INTO MealSizes(id,name,serving_size,is_vegan,country) VALUES (1,'Vegan Pizza',250,TRUE,'USA'),(2,'Chickpea Curry',380,TRUE,'USA');
SELECT MIN(serving_size), MAX(serving_size) FROM MealSizes WHERE is_vegan = TRUE AND country = 'USA';
What is the maximum delivery time for packages shipped from the Mumbai warehouse in Q4 2021?
CREATE TABLE deliveries (id INT,delivery_time FLOAT,warehouse VARCHAR(20),quarter INT); INSERT INTO deliveries (id,delivery_time,warehouse,quarter) VALUES (1,10.0,'Mumbai',4),(2,15.0,'Delhi',1),(3,12.0,'Mumbai',4); CREATE TABLE warehouses (id INT,name VARCHAR(20)); INSERT INTO warehouses (id,name) VALUES (1,'Mumbai'),(2,'Delhi');
SELECT MAX(delivery_time) FROM deliveries d JOIN warehouses w ON d.warehouse = w.name WHERE w.name = 'Mumbai' AND d.quarter = 4;