instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
How many days on average does it take for a returned item to be restocked in the Tokyo warehouse?
CREATE TABLE return_data (return_id INT,item_id INT,return_date DATE); INSERT INTO return_data (return_id,item_id,return_date) VALUES (1,1,'2022-01-01'),(2,2,'2022-02-01'),(3,3,'2022-03-01'),(4,4,'2022-04-01'),(5,5,'2022-05-01'); CREATE TABLE restock_data (restock_id INT,item_id INT,restock_date DATE); INSERT INTO restock_data (restock_id,item_id,restock_date) VALUES (1,1,'2022-01-05'),(2,2,'2022-02-03'),(3,3,'2022-03-08'),(4,4,'2022-04-10'),(5,5,'2022-05-15');
SELECT AVG(DATEDIFF(day, return_date, restock_date)) FROM return_data JOIN restock_data ON return_data.item_id = restock_data.item_id WHERE restock_data.restock_location = 'Tokyo';
Insert a new record in the customer_usage table for a customer with id 1001, who used 500 MB of data on 2023-03-01
CREATE TABLE customer_usage (usage_id INT,customer_id INT,usage_date DATE,data_usage DECIMAL(5,2));
INSERT INTO customer_usage (usage_id, customer_id, usage_date, data_usage) VALUES ((SELECT MAX(usage_id) FROM customer_usage) + 1, 1001, '2023-03-01', 500.00);
What is the average acreage of urban farms in New York and Los Angeles?
CREATE TABLE urban_farms (id INT,city VARCHAR(20),acreage DECIMAL(5,2)); INSERT INTO urban_farms (id,city,acreage) VALUES (1,'NY',1.25),(2,'LA',2.50),(3,'NY',1.75),(4,'LA',3.00);
SELECT AVG(acreage) FROM urban_farms WHERE city IN ('NY', 'LA');
What is the total budget spent on AI projects by organizations in the top 3 regions with the most organizations working on AI projects?
CREATE TABLE ai_projects_region (organization_name TEXT,region TEXT); INSERT INTO ai_projects_region (organization_name,region) VALUES ('TechCorp','Asia-Pacific'),('InnoTech','North America'),('GreenAI','Europe'),('AIforGood','Africa'),('Tech4Good','North America'); CREATE TABLE ai_projects_budget (organization_name TEXT,budget INTEGER); INSERT INTO ai_projects_budget (organization_name,budget) VALUES ('TechCorp',1500000),('InnoTech',2000000),('GreenAI',1000000),('AIforGood',1200000),('Tech4Good',1800000);
SELECT SUM(budget) FROM ai_projects_budget INNER JOIN ai_projects_region ON ai_projects_budget.organization_name = ai_projects_region.organization_name WHERE region IN (SELECT region FROM (SELECT region, COUNT(*) as organization_count FROM ai_projects_region GROUP BY region ORDER BY organization_count DESC LIMIT 3) subquery);
What is the average age of patients who have received treatment for depression or anxiety in the patient_demographics table, grouped by their gender?
CREATE TABLE patient_demographics (patient_id INT,age INT,gender VARCHAR(255),condition VARCHAR(255));
SELECT gender, AVG(age) FROM patient_demographics WHERE condition IN ('depression', 'anxiety') GROUP BY gender;
What is the total amount of climate finance invested in renewable energy projects in Africa since 2010?
CREATE TABLE climate_finance (id INT PRIMARY KEY,project_id INT,year INT,region VARCHAR(255),sector VARCHAR(255),amount DECIMAL(10,2));
SELECT SUM(amount) FROM climate_finance WHERE sector = 'Renewable Energy' AND year >= 2010 AND region = 'Africa';
What is the average response time to citizen complaints per day, with the fastest response time first?
CREATE TABLE Daily_Response(Day DATE,Response_Time INT); INSERT INTO Daily_Response VALUES ('2022-01-01',2),('2022-01-01',5),('2022-01-02',3),('2022-01-03',4),('2022-01-03',6);
SELECT Day, AVG(Response_Time) as Avg_Response_Time FROM Daily_Response GROUP BY Day ORDER BY Avg_Response_Time ASC;
What is the total installed capacity and number of renewable energy projects for each energy type in a specific city and state, ordered by the total capacity in descending order?
CREATE TABLE renewable_energy_projects (id INT,name VARCHAR(50),city VARCHAR(50),state VARCHAR(50),country VARCHAR(50),energy_type VARCHAR(50),capacity_mw FLOAT,PRIMARY KEY (id));
SELECT city, state, energy_type, SUM(capacity_mw) as total_capacity, COUNT(*) as project_count, ROW_NUMBER() OVER (ORDER BY SUM(capacity_mw) DESC) as ranking FROM renewable_energy_projects WHERE city = 'CityName' AND state = 'StateName' GROUP BY energy_type;
Which recycling facilities can handle e-waste and glass in Jakarta and Nairobi?
CREATE TABLE RecyclingFacilities (RFID INT,Location VARCHAR(50),Type VARCHAR(50),Capacity INT); INSERT INTO RecyclingFacilities (RFID,Location,Type,Capacity) VALUES (9,'Jakarta','E-waste',6000); INSERT INTO RecyclingFacilities (RFID,Location,Type,Capacity) VALUES (10,'Jakarta','Glass',7000); INSERT INTO RecyclingFacilities (RFID,Location,Type,Capacity) VALUES (11,'Nairobi','E-waste',8000); INSERT INTO RecyclingFacilities (RFID,Location,Type,Capacity) VALUES (12,'Nairobi','Glass',9000);
SELECT R.Location, R.Type FROM RecyclingFacilities R WHERE R.Location IN ('Jakarta', 'Nairobi') AND R.Type IN ('E-waste', 'Glass') GROUP BY R.Location, R.Type;
Find the maximum fare for bus routes serving the 'North' district.
CREATE TABLE BusRoutes (RouteID INT,District VARCHAR(20),Fare DECIMAL(5,2)); INSERT INTO BusRoutes (RouteID,District,Fare) VALUES (1,'North',1.50),(2,'South',2.00),(3,'East',1.25),(4,'North',2.50),(5,'West',1.75);
SELECT MAX(Fare) FROM BusRoutes WHERE District = 'North';
What is the maximum quantity of each type of meat product sold in each country?
CREATE TABLE Countries (CountryID INT,CountryName VARCHAR(50));CREATE TABLE Products (ProductID INT,ProductName VARCHAR(50),ProductType VARCHAR(50),QuantitySold INT); INSERT INTO Countries VALUES (1,'USA'),(2,'Canada'); INSERT INTO Products VALUES (1,'Chicken','Meat',100),(2,'Beef','Meat',150),(3,'Fish','Meat',200),(4,'Soy Milk','Dairy',50);
SELECT c.CountryName, p.ProductType, MAX(p.QuantitySold) as MaxQuantitySold FROM Countries c JOIN Products p ON c.CountryID = 1 GROUP BY c.CountryName, p.ProductType;
How many mining operations are located in Country G?
CREATE TABLE location (id INT,name TEXT,country TEXT); INSERT INTO location (id,name,country) VALUES (1,'Operation A','Country G'); INSERT INTO location (id,name,country) VALUES (2,'Operation B','Country H');
SELECT COUNT(*) FROM location WHERE country = 'Country G';
Find the total number of rural infrastructure projects and community development initiatives in 'RuralDev' database.
CREATE TABLE rural_infrastructure_count (id INT,name VARCHAR(255)); INSERT INTO rural_infrastructure_count (id,name) VALUES (1,'Water Supply System'),(2,'Solar Farm'),(3,'School'); CREATE TABLE community_initiatives_count (id INT,name VARCHAR(255)); INSERT INTO community_initiatives_count (id,name) VALUES (1,'Youth Skills Training'),(2,'Women Empowerment Program');
SELECT COUNT(*) FROM rural_infrastructure_count; SELECT COUNT(*) FROM community_initiatives_count;
What is the total revenue generated from members in the "Young Adults" demographic segment for the year 2020?
CREATE SCHEMA fitness; CREATE TABLE membership (member_id INT,demographic_segment VARCHAR(20)); CREATE TABLE revenue (member_id INT,revenue DECIMAL(10,2),transaction_date DATE); INSERT INTO membership (member_id,demographic_segment) VALUES (1,'Young Adults'),(2,'Seniors'); INSERT INTO revenue (member_id,revenue,transaction_date) VALUES (1,500,'2020-01-01'),(1,600,'2020-02-01'),(2,300,'2020-01-01');
SELECT SUM(revenue) FROM revenue INNER JOIN membership ON revenue.member_id = membership.member_id WHERE membership.demographic_segment = 'Young Adults' AND YEAR(transaction_date) = 2020;
Count of sites in 'asia_pacific_archaeology' with 'radiocarbon_dating'?
CREATE TABLE asia_pacific_archaeology (site_id INT,radiocarbon_dating BOOLEAN);
SELECT COUNT(*) FROM asia_pacific_archaeology WHERE radiocarbon_dating = TRUE;
List the names and locations of all female healthcare workers.
CREATE TABLE healthcare_workers (id INT,name VARCHAR(50),age INT,gender VARCHAR(10),location VARCHAR(50)); INSERT INTO healthcare_workers (id,name,age,gender,location) VALUES (1,'John Doe',35,'Male','New York'); INSERT INTO healthcare_workers (id,name,age,gender,location) VALUES (2,'Jane Smith',32,'Female','California');
SELECT name, location FROM healthcare_workers WHERE gender = 'Female';
What is the distribution of ethical AI initiatives by region and budget?
CREATE TABLE Ethical_AI_Region (region VARCHAR(255),initiative VARCHAR(255),budget INT); INSERT INTO Ethical_AI_Region (region,initiative,budget) VALUES ('Asia','Transparency',500000),('Africa','Accountability',300000),('South America','Fairness',200000),('Europe','Explainability',400000),('North America','Privacy',600000);
SELECT region, initiative, AVG(budget) as avg_budget FROM Ethical_AI_Region GROUP BY region, initiative;
Calculate the average carbon offset per project in the 'Europe' region
CREATE TABLE carbon_offset_projects (id INT,project_name VARCHAR(100),region VARCHAR(50),carbon_offset FLOAT);
SELECT AVG(carbon_offset) FROM carbon_offset_projects WHERE region = 'Europe';
What is the total production volume of rare earth elements in China for the year 2020?
CREATE TABLE production (id INT,mine_id INT,year INT,product TEXT,production_volume INT); INSERT INTO production (id,mine_id,year,product,production_volume) VALUES (1,1,2020,'Rare Earth Elements',5000);
SELECT SUM(production_volume) FROM production WHERE year = 2020 AND product = 'Rare Earth Elements' AND mine_id IN (SELECT id FROM mines WHERE location = 'China');
Add a new student named "Jamie" with a major in "Computer Science" and a GPA of 3.8 to the "students" table.
CREATE TABLE students (student_id INT,name VARCHAR(255),major VARCHAR(255),gpa DECIMAL(3,2));
INSERT INTO students (name, major, gpa) VALUES ('Jamie', 'Computer Science', 3.8);
Identify menu items ordered less frequently than 10% of the most ordered item.
CREATE TABLE orders_summary (menu_id INT,quantity INT); INSERT INTO orders_summary (menu_id,quantity) VALUES (1,100),(2,90),(3,80),(4,70),(5,60);
SELECT m.menu_name FROM menus m JOIN orders_summary os ON m.menu_id = os.menu_id WHERE os.quantity < (SELECT 0.1 * quantity FROM orders_summary WHERE quantity = (SELECT MAX(quantity) FROM orders_summary));
List all mental health parity violations in California in the past month.
CREATE TABLE MentalHealthParity (ID INT,Violation VARCHAR(255),State VARCHAR(255),Date DATE); INSERT INTO MentalHealthParity VALUES (1,'Non-compliance with mental health coverage','California','2022-01-15'); INSERT INTO MentalHealthParity VALUES (2,'Lack of mental health coverage parity','California','2022-02-28');
SELECT * FROM MentalHealthParity WHERE State = 'California' AND Date >= DATEADD(month, -1, GETDATE());
What are the top 5 countries with the highest number of military innovation patents since 2010?
CREATE TABLE military_innovation (id INT,country VARCHAR(50),patent VARCHAR(50),date DATE); INSERT INTO military_innovation (id,country,patent,date) VALUES (1,'USA','Stealth Technology','2015-01-01'); INSERT INTO military_innovation (id,country,patent,date) VALUES (2,'China','Drone Technology','2018-05-23'); INSERT INTO military_innovation (id,country,patent,date) VALUES (3,'Russia','Cyber Warfare','2016-12-12'); INSERT INTO military_innovation (id,country,patent,date) VALUES (4,'France','AI in Military','2017-07-04');
SELECT country, COUNT(*) as patents_since_2010 FROM military_innovation WHERE date >= '2010-01-01' GROUP BY country ORDER BY patents_since_2010 DESC LIMIT 5;
Which container vessels have had the most collisions in the past 3 years?
CREATE TABLE vessel (id INT,type VARCHAR(50),name VARCHAR(50));CREATE TABLE incident (id INT,vessel_id INT,incident_date DATE,incident_type VARCHAR(50));
SELECT v.name, COUNT(i.id) as collision_count FROM vessel v INNER JOIN incident i ON v.id = i.vessel_id WHERE v.type = 'container' AND i.incident_type = 'collision' AND i.incident_date >= DATE(NOW(), INTERVAL -3 YEAR) GROUP BY v.name ORDER BY collision_count DESC;
What was the total community development expenditure by the US government in H1 2016?
CREATE TABLE community_development (government VARCHAR(50),half INT,expenditure FLOAT); INSERT INTO community_development (government,half,expenditure) VALUES ('US Federal Government',1,2000000),('US State Government',1,1500000),('US Local Government',1,1000000),('German Federal Government',1,1200000),('German State Government',1,800000);
SELECT SUM(expenditure) as total_expenditure FROM community_development WHERE government = 'US Federal Government' AND half = 1;
What is the average age of community health workers with high cultural competency?
CREATE TABLE community_health_workers (id INT,age INT,cultural_competency VARCHAR(20)); INSERT INTO community_health_workers (id,age,cultural_competency) VALUES (1,35,'High'),(2,40,'Medium'),(3,30,'Low'),(4,45,'High'),(5,50,'High');
SELECT AVG(age) FROM community_health_workers WHERE cultural_competency = 'High';
How many pallets are stored in the warehouse with the most pallets?
CREATE TABLE Inventory (id INT,warehouse_id INT,pallets INT); INSERT INTO Inventory (id,warehouse_id,pallets) VALUES (1,1,100),(2,1,200),(3,2,150); CREATE TABLE Warehouses (id INT,name VARCHAR(50),city VARCHAR(50),country VARCHAR(50)); INSERT INTO Warehouses (id,name,city,country) VALUES (1,'Warehouse A','City A','Country A'),(2,'Warehouse B','City B','Country B');
SELECT SUM(i.pallets) FROM Inventory i JOIN (SELECT MAX(total_pallets) AS max_pallets FROM (SELECT w.id, SUM(i.pallets) AS total_pallets FROM Inventory i JOIN Warehouses w ON i.warehouse_id = w.id GROUP BY w.id) subquery) subquery2 ON i.pallets = subquery2.max_pallets;
What is the total waste generation by material type in 2020 for California?
CREATE TABLE waste_generation(year INT,state VARCHAR(20),material VARCHAR(20),amount INT); INSERT INTO waste_generation VALUES (2018,'California','Plastic',5000),(2018,'California','Paper',8000),(2019,'California','Plastic',5500),(2019,'California','Paper',8500),(2020,'California','Plastic',6000),(2020,'California','Paper',9000);
SELECT SUM(amount) as total_waste, material FROM waste_generation WHERE year = 2020 AND state = 'California' GROUP BY material;
What is the difference in average rating between hotel virtual tours in Paris and Rome?
CREATE TABLE hotel_virtual_tours (hotel_id INT,city VARCHAR(50),rating FLOAT); INSERT INTO hotel_virtual_tours (hotel_id,city,rating) VALUES (1,'Paris',4.6),(2,'Paris',4.5),(3,'Rome',4.4),(4,'Rome',4.3);
SELECT city, AVG(rating) as avg_rating FROM hotel_virtual_tours GROUP BY city; SELECT (PARIS_AVG_RATING - ROME_AVG_RATING) as rating_difference;
What is the maximum number of marine research stations in the Indian Ocean?
CREATE TABLE indian_ocean_research_stations (id INT,country TEXT,num_stations INT); INSERT INTO indian_ocean_research_stations (id,country,num_stations) VALUES (1,'India',15),(2,'Indonesia',20);
SELECT MAX(num_stations) FROM indian_ocean_research_stations;
Query the NewHiresByQuarter view
SELECT * FROM NewHiresByQuarter;
SELECT * FROM NewHiresByQuarter;
What is the total number of posts in each content category?
CREATE TABLE content_categories (id INT,content_category VARCHAR(255)); CREATE TABLE posts_extended (id INT,content_category_id INT,content TEXT); INSERT INTO content_categories (id,content_category) VALUES (1,'AI'),(2,'Data Science'),(3,'Machine Learning'); INSERT INTO posts_extended (id,content_category_id,content) VALUES (1,1,'Hello'),(2,1,'World'),(3,2,'AI');
SELECT content_categories.content_category, COUNT(posts_extended.id) FROM content_categories JOIN posts_extended ON posts_extended.content_category_id = content_categories.id GROUP BY content_categories.content_category;
What is the average ticket price by team and ticket type?
CREATE TABLE teams (team_id INT,team_name VARCHAR(50)); INSERT INTO teams (team_id,team_name) VALUES (1,'TeamA'),(2,'TeamB'); CREATE TABLE ticket_sales (team_id INT,ticket_type VARCHAR(50),price DECIMAL(5,2)); INSERT INTO ticket_sales (team_id,ticket_type,price) VALUES (1,'VIP',100.00),(1,'Regular',60.00),(2,'VIP',120.00),(2,'Regular',70.00);
SELECT t.team_name, ticket_type, AVG(ticket_sales.price) as avg_price FROM ticket_sales JOIN teams ON ticket_sales.team_id = teams.team_id GROUP BY t.team_name, ticket_type;
What is the success rate of rural infrastructure projects, defined as the percentage of projects that were completed on time and within budget, in the last 3 years?
CREATE TABLE projects (id INT,name VARCHAR(50),budget INT,completion_date DATE,planned_completion_date DATE);
SELECT 100.0 * AVG(CASE WHEN budget = actual_spent AND completion_date <= planned_completion_date THEN 1 ELSE 0 END) as success_rate FROM (SELECT id, budget, completion_date, planned_completion_date, SUM(cost) as actual_spent FROM projects WHERE date(completion_date) >= date('now','-3 years') GROUP BY id) subquery;
What is the maximum productivity for mines located in 'Africa'?
CREATE TABLE mine_productivity (mine_name TEXT,extraction_tons INTEGER,workforce_size INTEGER,productivity_tons_per_worker FLOAT,location TEXT); INSERT INTO mine_productivity (mine_name,extraction_tons,workforce_size,productivity_tons_per_worker,location) VALUES ('Golden Ridge Mine',3500,200,17.5,'North America'),('Silver Peak Mine',2800,150,18.67,'North America'),('Emerald Paradise Mine',2200,250,8.8,'Asia'),('Ruby Desert Mine',4500,300,15,'Africa');
SELECT MAX(productivity_tons_per_worker) as max_productivity FROM mine_productivity WHERE location = 'Africa';
What's the total number of workers in the mining industry, categorized by their gender?
CREATE TABLE workforce (id INT PRIMARY KEY,name VARCHAR(50),gender VARCHAR(50),role VARCHAR(50)); INSERT INTO workforce (id,name,gender,role) VALUES (1,'John Doe','Male','Miner'),(2,'Jane Smith','Female','Engineer'),(3,'Alberto Garcia','Male','Manager'),(4,'Sandra Rodriguez','Female','Miner'),(5,'David Kim','Male','Engineer');
SELECT gender, COUNT(*) as total_workers FROM workforce GROUP BY gender;
How many esports events were held in Tokyo, Japan in 2020?
CREATE TABLE EsportsEvents (EventID INT,City VARCHAR(50),Country VARCHAR(50),Year INT); INSERT INTO EsportsEvents (EventID,City,Country,Year) VALUES (1,'Los Angeles','USA',2019),(2,'Paris','France',2019),(3,'Tokyo','Japan',2020),(4,'Seoul','South Korea',2018);
SELECT COUNT(*) FROM EsportsEvents WHERE City = 'Tokyo' AND Year = 2020;
What is the average calorie count for dishes in the Asian cuisine category?
CREATE TABLE cuisine (id INT,name VARCHAR(255)); INSERT INTO cuisine (id,name) VALUES (1,'Asian'),(2,'Italian'),(3,'Mexican'); CREATE TABLE dishes (id INT,name VARCHAR(255),cuisine_id INT,calories INT); INSERT INTO dishes (id,name,cuisine_id,calories) VALUES (1,'Pad Thai',1,600),(2,'Fried Rice',1,700),(3,'Pizza',2,1200),(4,'Tacos',3,800);
SELECT AVG(calories) FROM dishes WHERE cuisine_id = (SELECT id FROM cuisine WHERE name = 'Asian');
Identify the most experienced employees in each department.
CREATE TABLE employee (id INT,name VARCHAR(50),department VARCHAR(20),hire_date DATE);CREATE VIEW experienced_employees_by_dept AS SELECT department,id,name,DATEDIFF(CURDATE(),hire_date) as work_experience FROM employee WHERE department IN ('Manufacturing','Design');
SELECT department, id, name, work_experience, RANK() OVER (PARTITION BY department ORDER BY work_experience DESC) as experience_rank FROM experienced_employees_by_dept WHERE experience_rank = 1;
Find the total weight of organic products supplied by the top 2 suppliers.
CREATE TABLE suppliers (id INT,name VARCHAR(255),country VARCHAR(255)); CREATE TABLE products (id INT,name VARCHAR(255),organic BOOLEAN,weight FLOAT,supplier_id INT);
SELECT s.name, SUM(p.weight) FROM suppliers s INNER JOIN products p ON s.id = p.supplier_id WHERE p.organic = 't' GROUP BY s.name ORDER BY SUM(p.weight) DESC LIMIT 2;
How many people have access to clean water in Latin America?
CREATE TABLE water (country VARCHAR(255),region VARCHAR(255),access INT); INSERT INTO water (country,region,access) VALUES ('Country A','Latin America',500000),('Country B','Latin America',600000);
SELECT SUM(access) FROM water WHERE region = 'Latin America';
Which renewable energy projects have a capacity greater than 150 MW?
CREATE TABLE wind_farms (id INT,name TEXT,region TEXT,capacity_mw FLOAT); INSERT INTO wind_farms (id,name,region,capacity_mw) VALUES (1,'Windfarm A','west',150.5); INSERT INTO wind_farms (id,name,region,capacity_mw) VALUES (2,'Windfarm B','east',120.2); CREATE TABLE solar_power_plants (id INT,name TEXT,region TEXT,capacity_mw FLOAT); INSERT INTO solar_power_plants (id,name,region,capacity_mw) VALUES (1,'Solar Plant A','north',125.8); INSERT INTO solar_power_plants (id,name,region,capacity_mw) VALUES (2,'Solar Plant B','south',180.3);
SELECT name, capacity_mw FROM wind_farms WHERE capacity_mw > 150 UNION ALL SELECT name, capacity_mw FROM solar_power_plants WHERE capacity_mw > 150;
How many dams were built in Texas between 2010 and 2020?
CREATE TABLE dams (dam_name TEXT,dam_year INT,dam_state TEXT); INSERT INTO dams (dam_name,dam_year,dam_state) VALUES ('D1',2015,'Texas'),('D2',2018,'Texas'),('D3',2008,'Texas'),('D4',2012,'Texas'),('D5',2020,'Texas');
SELECT COUNT(*) FROM dams WHERE dam_year BETWEEN 2010 AND 2020 AND dam_state = 'Texas';
What is the average severity score of vulnerabilities detected in the healthcare sector?
CREATE TABLE vulnerabilities (id INT,sector VARCHAR(255),severity FLOAT); INSERT INTO vulnerabilities (id,sector,severity) VALUES (1,'healthcare',7.5),(2,'finance',5.2),(3,'healthcare',8.1);
SELECT AVG(severity) FROM vulnerabilities WHERE sector = 'healthcare';
Insert a new restorative justice program into the 'programs' table
CREATE TABLE programs (id INT,name VARCHAR(50),location VARCHAR(50),type VARCHAR(50),start_date DATE,end_date DATE);
INSERT INTO programs (id, name, location, type, start_date, end_date) VALUES (103, 'Victim-Offender Mediation', 'San Francisco, CA', 'Restorative Justice', '2023-01-01', '2023-12-31');
What is the total revenue generated from art sales in each quarter?
CREATE TABLE ArtSales (SaleID INT,SaleDate DATE,Revenue INT); INSERT INTO ArtSales (SaleID,SaleDate,Revenue) VALUES (1,'2022-01-01',1000),(2,'2022-02-01',2000),(3,'2022-03-01',3000),(4,'2022-04-01',1500),(5,'2022-05-01',2500),(6,'2022-06-01',3500),(7,'2022-07-01',1700),(8,'2022-08-01',2700),(9,'2022-09-01',3700),(10,'2022-10-01',2200),(11,'2022-11-01',3200),(12,'2022-12-01',4200);
SELECT QUARTER(SaleDate) as Quarter, SUM(Revenue) as TotalRevenue FROM ArtSales GROUP BY Quarter;
What is the total funding for startups founded by a person from the LGBTQ+ community?
CREATE TABLE startup_founders (id INT PRIMARY KEY,name VARCHAR(255),sexual_orientation VARCHAR(50),industry VARCHAR(255),total_funding FLOAT);
SELECT SUM(total_funding) FROM startup_founders WHERE sexual_orientation = 'LGBTQ+';
How many properties are there in each borough of NYC that have green roofs?
CREATE TABLE nyc_real_estate(id INT,borough VARCHAR(50),green_roof BOOLEAN); INSERT INTO nyc_real_estate VALUES (1,'Manhattan',true);
SELECT borough, COUNT(*) FROM nyc_real_estate WHERE green_roof = true GROUP BY borough;
Who are the top 5 users who spent the most time reading articles about 'politics'?
CREATE TABLE users (id INT,name TEXT,time_spent_reading INT); CREATE TABLE user_activity (user_id INT,article_id INT,start_time DATETIME,end_time DATETIME); CREATE TABLE articles (id INT,title TEXT,category TEXT);
SELECT name FROM (SELECT user_id, SUM(TIMESTAMPDIFF(MINUTE, start_time, end_time)) AS time_spent_reading FROM user_activity JOIN articles ON user_activity.article_id = articles.id WHERE articles.category = 'politics' GROUP BY user_id ORDER BY time_spent_reading DESC LIMIT 5) AS subquery JOIN users ON subquery.user_id = users.id;
Display the "country" and "region" columns from the "peacekeeping_ops" table, showing only records where the "region" column is 'Europe'
CREATE TABLE peacekeeping_ops (id INT,country VARCHAR(50),region VARCHAR(50)); INSERT INTO peacekeeping_ops (id,country,region) VALUES (1,'Nigeria','Africa'),(2,'Ukraine','Europe'),(3,'Iraq','Middle East');
SELECT country, region FROM peacekeeping_ops WHERE region = 'Europe';
What is the total number of properties with a green certification in the green_certified_properties view?
CREATE VIEW green_certified_properties AS SELECT * FROM properties WHERE has_green_certification = TRUE;
SELECT COUNT(*) FROM green_certified_properties;
What is the total number of clients from 'Asia' who have had 'civil law' cases?
CREATE TABLE Clients (ClientID int,Age int,Gender varchar(10),Region varchar(50)); INSERT INTO Clients (ClientID,Age,Gender,Region) VALUES (11,35,'Female','Asia'); CREATE TABLE Cases (CaseID int,ClientID int,Category varchar(50)); INSERT INTO Cases (CaseID,ClientID,Category) VALUES (1101,11,'Civil Law');
SELECT COUNT(DISTINCT C.ClientID) as TotalClients FROM Clients C INNER JOIN Cases CA ON C.ClientID = CA.ClientID WHERE C.Region = 'Asia' AND CA.Category = 'Civil Law';
What is the total CO2 emissions from manufacturing cosmetics in the last 12 months?
CREATE TABLE manufacturing_emissions (emission_id INT,product_id INT,co2_emissions FLOAT,emission_date DATE);
SELECT SUM(co2_emissions) FROM manufacturing_emissions WHERE emission_date BETWEEN DATE_SUB(CURRENT_DATE, INTERVAL 12 MONTH) AND CURRENT_DATE;
Display the names of all climate finance recipients who received funding in both 2019 and 2020.
CREATE TABLE climate_finance_2019 (recipient_name TEXT,funding_year INTEGER); INSERT INTO climate_finance_2019 (recipient_name,funding_year) VALUES ('Recipient A',2019),('Recipient B',2019),('Recipient A',2020); CREATE TABLE climate_finance_2020 (recipient_name TEXT,funding_year INTEGER); INSERT INTO climate_finance_2020 (recipient_name,funding_year) VALUES ('Recipient A',2020),('Recipient C',2020);
SELECT recipient_name FROM climate_finance_2019 WHERE funding_year = 2019 INTERSECT SELECT recipient_name FROM climate_finance_2020 WHERE funding_year = 2020;
What is the number of artworks in the artworks table, grouped by country, excluding those from the United States?
CREATE TABLE artworks (artwork_id INT,artwork_name TEXT,artist_name TEXT,country TEXT); CREATE TABLE country_continent (country TEXT,continent TEXT);
SELECT country, COUNT(artwork_id) FROM artworks JOIN country_continent ON artworks.country = country_continent.country WHERE country != 'United States' GROUP BY country;
What is the average transaction amount by client in the Latin America region in Q2 2022?
CREATE TABLE clients (client_id INT,name VARCHAR(50),region VARCHAR(50)); INSERT INTO clients VALUES (1,'John Doe','Latin America'),(2,'Jane Smith','North America'),(3,'Alice Johnson','Latin America'); CREATE TABLE transactions (transaction_id INT,client_id INT,transaction_date DATE,transaction_amount DECIMAL(10,2)); INSERT INTO transactions VALUES (1,1,'2022-04-01',100.00),(2,1,'2022-05-01',200.00),(3,2,'2022-04-15',150.00),(4,3,'2022-05-01',50.00);
SELECT c.region, AVG(t.transaction_amount) FROM clients c JOIN transactions t ON c.client_id = t.client_id WHERE c.region = 'Latin America' AND t.transaction_date BETWEEN '2022-04-01' AND '2022-06-30' GROUP BY c.region;
What is the total value of artworks in the modern art section of the museums in Tokyo?
CREATE TABLE tokyo_art(id INT,museum VARCHAR(30),section VARCHAR(30),value INT); INSERT INTO tokyo_art VALUES (1,'Tokyo National Museum','Modern Art',1000000); INSERT INTO tokyo_art VALUES (2,'Mori Art Museum','Modern Art',2000000);
SELECT SUM(value) FROM tokyo_art WHERE museum IN (SELECT museum FROM tokyo_art WHERE section = 'Modern Art') AND section = 'Modern Art';
How many subway trips were taken in Berlin in the last week?
CREATE TABLE subway_trips (trip_id INT,trip_date DATE,station_id INT); CREATE TABLE subway_stations (station_id INT,station_name VARCHAR(255),city VARCHAR(255));
SELECT COUNT(*) FROM subway_trips JOIN subway_stations ON subway_trips.station_id = subway_stations.station_id WHERE subway_stations.city = 'Berlin' AND subway_trips.trip_date >= DATEADD(WEEK, -1, GETDATE());
Calculate the average number of hospital beds per rural healthcare facility in Brazil and Mexico.
CREATE TABLE healthcare_facilities (facility_id INT,country VARCHAR(20),num_beds INT); INSERT INTO healthcare_facilities (facility_id,country,num_beds) VALUES (1,'Brazil',50),(2,'Mexico',75);
SELECT AVG(num_beds) FROM healthcare_facilities WHERE country IN ('Brazil', 'Mexico');
What is the distribution of fans by gender for each team?
CREATE TABLE fan_demographics (fan_id INT,gender VARCHAR(255),team_id INT); INSERT INTO fan_demographics (fan_id,gender,team_id) VALUES (1,'Male',1),(2,'Female',2),(3,'Male',1),(4,'Male',3),(5,'Female',2); CREATE TABLE teams (team_id INT,team_name VARCHAR(255)); INSERT INTO teams (team_id,team_name) VALUES (1,'Knicks'),(2,'Lakers'),(3,'Chelsea');
SELECT t.team_name, f.gender, COUNT(f.fan_id) fan_count FROM fan_demographics f JOIN teams t ON f.team_id = t.team_id GROUP BY t.team_name, f.gender;
How many sustainable building projects were completed in New York in 2021?
CREATE TABLE sustainable_projects (id INT,project_name TEXT,state TEXT,completion_year INT,is_sustainable BOOLEAN); INSERT INTO sustainable_projects (id,project_name,state,completion_year,is_sustainable) VALUES (1,'Solar Park','New York',2021,true),(2,'Wind Farm','California',2020,true),(3,'Green Apartments','New York',2021,true),(4,'Eco-Hotel','Florida',2020,false);
SELECT COUNT(*) FROM sustainable_projects WHERE state = 'New York' AND completion_year = 2021 AND is_sustainable = true;
Find the number of employees of different genders and ethnicities in each department of the company.
CREATE TABLE department (name VARCHAR(255)); CREATE TABLE employee (id INT,name VARCHAR(255),gender VARCHAR(50),ethnicity VARCHAR(50),department_id INT);
SELECT department.name AS department, gender, ethnicity, COUNT(*) AS employee_count FROM department INNER JOIN employee ON department.id = employee.department_id GROUP BY department.name, gender, ethnicity;
Identify the species with a decrease in timber production between 2018 and 2019, and order them by the largest decrease first.
CREATE TABLE species_timber_2 (species_id INT,species_name VARCHAR(50),year INT,volume INT); INSERT INTO species_timber_2 (species_id,species_name,year,volume) VALUES (1,'Oak',2018,1000),(2,'Pine',2018,2000),(3,'Maple',2018,3000),(4,'Birch',2018,4000),(1,'Oak',2019,900),(2,'Pine',2019,2200),(3,'Maple',2019,3300),(4,'Birch',2019,4200);
SELECT species_name, (LAG(volume, 1) OVER (PARTITION BY species_name ORDER BY year)) - volume AS volume_decrease FROM species_timber_2 WHERE year = 2019 GROUP BY species_name, volume ORDER BY volume_decrease DESC;
What are the unique hobbies of users who have followed accounts about mental health advocacy but have not engaged with posts about mindfulness.
CREATE TABLE user_activity (user_id INT,activity_type VARCHAR(50),hobby VARCHAR(50)); INSERT INTO user_activity (user_id,activity_type,hobby) VALUES (1,'followed_account','yoga'),(2,'engaged_post','cooking'),(3,'followed_account','hiking'),(4,'engaged_post','painting'),(5,'followed_account','meditation'),(6,'engaged_post','gardening');
SELECT hobby FROM user_activity WHERE activity_type = 'followed_account' AND user_id NOT IN (SELECT user_id FROM user_activity WHERE activity_type = 'engaged_post' AND post_topic = 'mindfulness');
Update the production budget of all movies released in 2010 by 15%
CREATE TABLE movies (id INT PRIMARY KEY,title VARCHAR(100),release_year INT,genre VARCHAR(50),production_budget INT);
UPDATE movies SET production_budget = production_budget * 1.15 WHERE release_year = 2010;
Add a new offense record into the "offenses" table
CREATE TABLE offenses (id INT,victim_id INT,offense_type VARCHAR(50),date_of_offense DATE);
INSERT INTO offenses (id, victim_id, offense_type, date_of_offense) VALUES (2003, 1002, 'Assault', '2021-09-25');
What are the names of mining companies with the highest and lowest labor productivity?
CREATE TABLE Companies (CompanyID INT,CompanyName VARCHAR(50),LaborProductivity DECIMAL(5,2)); INSERT INTO Companies (CompanyID,CompanyName,LaborProductivity) VALUES (1,'ABC Mining',15.5),(2,'XYZ Excavations',12.3),(3,'MNO Drilling',18.7),(4,'PQR Quarrying',10.1);
SELECT CompanyName FROM Companies WHERE LaborProductivity = (SELECT MAX(LaborProductivity) FROM Companies) OR LaborProductivity = (SELECT MIN(LaborProductivity) FROM Companies);
What was the average food safety score for restaurants in New York in 2021?
CREATE TABLE restaurant_inspections (restaurant_name VARCHAR(255),location VARCHAR(255),score INTEGER,inspection_date DATE); INSERT INTO restaurant_inspections (restaurant_name,location,score,inspection_date) VALUES ('Restaurant A','New York',90,'2021-01-01'),('Restaurant B','New York',85,'2021-02-01');
SELECT AVG(score) FROM restaurant_inspections WHERE location = 'New York' AND YEAR(inspection_date) = 2021;
What is the average number of posts per day for users over 40 years old in the 'social_media' database?
CREATE TABLE users (id INT,name VARCHAR(50),gender VARCHAR(10),age INT,location VARCHAR(50),posts INT); CREATE TABLE posts (id INT,user_id INT,content TEXT,timestamp TIMESTAMP);
SELECT AVG(COUNT(posts.id)/86400) AS avg_posts_per_day FROM posts JOIN users ON posts.user_id = users.id WHERE users.age > 40;
List the top 3 producing wells in the North Sea, partitioned by year.
CREATE TABLE well_production (well_name VARCHAR(20),production_qty FLOAT,production_date DATE); INSERT INTO well_production (well_name,production_qty,production_date) VALUES ('Well A',1000,'2020-01-01'); INSERT INTO well_production (well_name,production_qty,production_date) VALUES ('Well B',1500,'2020-01-01'); INSERT INTO well_production (well_name,production_qty,production_date) VALUES ('Well C',1200,'2020-01-01');
SELECT well_name, production_qty, production_date, RANK() OVER (PARTITION BY EXTRACT(YEAR FROM production_date) ORDER BY production_qty DESC) as rank FROM well_production WHERE well_name LIKE 'Well%' AND production_date BETWEEN '2020-01-01' AND '2021-12-31' AND location = 'North Sea' ORDER BY production_date, rank;
What is the total revenue for Latin music on streaming platforms since 2015?
CREATE TABLE music_genres (genre_id INT,genre VARCHAR(255)); CREATE TABLE platforms (platform_id INT,platform_name VARCHAR(255)); CREATE TABLE revenue (genre_id INT,platform_id INT,revenue INT,year INT); INSERT INTO music_genres (genre_id,genre) VALUES (1,'Latin'); INSERT INTO platforms (platform_id,platform_name) VALUES (1,'Spotify'); INSERT INTO revenue (genre_id,platform_id,revenue,year) VALUES (1,1,1000000,2015);
SELECT SUM(revenue) FROM revenue JOIN music_genres ON revenue.genre_id = music_genres.genre_id JOIN platforms ON revenue.platform_id = platforms.platform_id WHERE music_genres.genre = 'Latin' AND revenue.year >= 2015;
What is the maximum budget for accommodations for students with physical disabilities in the Southwest?
CREATE TABLE Accommodations (ID INT,Type VARCHAR(50),Cost FLOAT,Disability VARCHAR(50),Region VARCHAR(50)); INSERT INTO Accommodations (ID,Type,Cost,Disability,Region) VALUES (1,'Wheelchair Accessibility',2000.0,'Physical Disability','Southwest'),(2,'Adaptive Equipment',2500.0,'Physical Disability','Southwest'),(3,'Sign Language Interpretation',1500.0,'Physical Disability','Southwest');
SELECT MAX(Cost) FROM Accommodations WHERE Disability = 'Physical Disability' AND Region = 'Southwest';
How many maintenance requests have been submitted for each vehicle type?
CREATE TABLE vehicle_types (vehicle_type_id INT,vehicle_type VARCHAR(255)); CREATE TABLE maintenance_requests (request_id INT,vehicle_type_id INT,request_date DATE);
SELECT vt.vehicle_type, COUNT(mr.request_id) as num_requests FROM vehicle_types vt INNER JOIN maintenance_requests mr ON vt.vehicle_type_id = mr.vehicle_type_id GROUP BY vt.vehicle_type;
List all volunteers who have not been assigned to a project in Asia.
CREATE TABLE Volunteers (VolunteerID INT,VolunteerName TEXT); INSERT INTO Volunteers (VolunteerID,VolunteerName) VALUES (1,'Alice'),(2,'Bob'); CREATE TABLE Assignments (AssignmentID INT,VolunteerID INT,ProjectID INT,ProjectCountry TEXT); INSERT INTO Assignments (AssignmentID,VolunteerID,ProjectID,ProjectCountry) VALUES (1,1,1,'Japan'),(2,2,2,'China');
SELECT Volunteers.VolunteerName FROM Volunteers LEFT JOIN Assignments ON Volunteers.VolunteerID = Assignments.VolunteerID WHERE Assignments.ProjectCountry IS NULL OR Assignments.ProjectCountry != 'Asia';
Update the conservation status of the species with the highest sea surface temperature to 'Critically Endangered'.
CREATE TABLE marine_species (id INT PRIMARY KEY,name VARCHAR(255),conservation_status VARCHAR(255)); INSERT INTO marine_species (id,name,conservation_status) VALUES (1,'Whale Shark','Endangered'); CREATE TABLE oceanography (id INT PRIMARY KEY,species_id INT,sea_surface_temperature INT); INSERT INTO oceanography (id,species_id,sea_surface_temperature) VALUES (1,1,30);
UPDATE marine_species m SET m.conservation_status = 'Critically Endangered' FROM oceanography o WHERE m.id = o.species_id AND o.sea_surface_temperature = (SELECT MAX(sea_surface_temperature) FROM oceanography);
Which antidepressants are most commonly prescribed in Australia?
CREATE TABLE prescriptions (id INT PRIMARY KEY,patient_id INT,drug VARCHAR(50),country VARCHAR(50),prescription_date DATE);
SELECT drug FROM prescriptions WHERE country = 'Australia' AND drug LIKE '%antidepressant%' GROUP BY drug ORDER BY COUNT(*) DESC;
Insert a new student 'Pascale' from 'RainbowSchool' district into the 'Student' table.
CREATE TABLE Student (StudentID INT,Name VARCHAR(20),District VARCHAR(20));
INSERT INTO Student (StudentID, Name, District) VALUES (3, 'Pascale', 'RainbowSchool');
What is the total revenue of OTA bookings from APAC region in 2021?
CREATE TABLE ota_bookings (booking_id INT,ota_name TEXT,region TEXT,booking_amount DECIMAL(10,2)); INSERT INTO ota_bookings (booking_id,ota_name,region,booking_amount) VALUES (1,'Booking.com','APAC',200.50),(2,'Expedia','NA',150.25),(3,'Agoda','APAC',300.00);
SELECT SUM(booking_amount) FROM ota_bookings WHERE region = 'APAC' AND YEAR(booking_date) = 2021;
How many news articles are there in each news category?
CREATE TABLE News (news_id INT,title TEXT,category TEXT); INSERT INTO News (news_id,title,category) VALUES (1,'Article1','Politics'),(2,'Article2','Sports'),(3,'Article3','Politics'); CREATE TABLE Categories (category_id INT,category_name TEXT); INSERT INTO Categories (category_id,category_name) VALUES (1,'Politics'),(2,'Sports'),(3,'Culture');
SELECT c.category_name, COUNT(n.news_id) as num_articles FROM News n INNER JOIN Categories c ON n.category = c.category_name GROUP BY c.category_name;
Insert new legal aid providers into the 'legal_aid' table that do not already exist in the 'providers_history' table?
CREATE TABLE legal_aid (provider_id INT,provider VARCHAR(255),location VARCHAR(255)); CREATE TABLE providers_history (provider_id INT,provider VARCHAR(255),location VARCHAR(255));
INSERT INTO legal_aid (provider_id, provider, location) SELECT provider_id, provider, location FROM (SELECT ROW_NUMBER() OVER (ORDER BY provider) AS provider_id, provider, location FROM (VALUES ('1001', 'Advocacy Inc.', 'NY'), ('1002', 'Justice League', 'CA')) AS t(provider_id, provider, location) EXCEPT SELECT provider_id, provider, location FROM providers_history) AS x WHERE provider_id NOT IN (SELECT provider_id FROM providers_history);
What is the total revenue generated by bookings for hotels in the 'Boutique' category?
CREATE TABLE Bookings (booking_id INT,hotel_id INT,booking_date DATE,revenue FLOAT,channel VARCHAR(50)); INSERT INTO Bookings (booking_id,hotel_id,booking_date,revenue,channel) VALUES (1,1,'2022-01-01',200.0,'Direct'),(2,1,'2022-01-03',150.0,'OTA'),(3,2,'2022-01-05',300.0,'Direct'),(8,8,'2022-04-01',250.0,'Direct'),(9,9,'2022-04-05',350.0,'Direct'); CREATE TABLE Hotels (hotel_id INT,hotel_name VARCHAR(100),category VARCHAR(50)); INSERT INTO Hotels (hotel_id,hotel_name,category) VALUES (1,'Hotel A','Boutique'),(2,'Hotel B','Boutique'),(8,'Hotel H','Boutique'),(9,'Hotel I','Boutique');
SELECT SUM(revenue) FROM Bookings INNER JOIN Hotels ON Bookings.hotel_id = Hotels.hotel_id WHERE category = 'Boutique';
What is the average flight time for each aircraft model in the North region?
CREATE TABLE Flight_Data (aircraft_model VARCHAR(255),region VARCHAR(255),flight_time INT); INSERT INTO Flight_Data (aircraft_model,region,flight_time) VALUES ('B737','North',200),('A320','South',220),('B737','North',210);
SELECT aircraft_model, AVG(flight_time) FROM Flight_Data WHERE region = 'North' GROUP BY aircraft_model;
What is the average age of policyholders who have a car make of 'Tesla' in the 'Auto' table?
CREATE TABLE Auto (policyholder_id INT,car_make VARCHAR(20));
SELECT AVG(age) FROM Policyholders INNER JOIN Auto ON Policyholders.id = Auto.policyholder_id WHERE car_make = 'Tesla';
Delete all artists who have not sold more than 1000 tickets for any concert.
CREATE SCHEMA if not exists music_schema;CREATE TABLE if not exists artists (id INT,name VARCHAR);CREATE TABLE if not exists concert_attendance (artist_id INT,concert_id INT,tickets_sold INT);INSERT INTO artists (id,name) VALUES (1,'Artist A'),(2,'Artist B'),(3,'Artist C');INSERT INTO concert_attendance (artist_id,concert_id,tickets_sold) VALUES (1,1,1500),(2,2,500),(3,3,1200),(1,4,2000),(2,5,0),(3,6,2500);
DELETE FROM music_schema.artists a USING music_schema.concert_attendance ca WHERE a.id = ca.artist_id AND ca.tickets_sold <= 1000;
Add new ethical manufacturing record with ID 3, name 'Ethical Manufacturer C', region 'Central'
CREATE SCHEMA manufacturing;CREATE TABLE ethical_manufacturers (id INT PRIMARY KEY,name TEXT,region TEXT);INSERT INTO ethical_manufacturers (id,name,region) VALUES (1,'Ethical Manufacturer A','North'); INSERT INTO ethical_manufacturers (id,name,region) VALUES (2,'Ethical Manufacturer B','South');
INSERT INTO ethical_manufacturers (id, name, region) VALUES (3, 'Ethical Manufacturer C', 'Central');
Insert new high scores
CREATE TABLE high_scores (id INT,username VARCHAR(255),game VARCHAR(255),score INT);
WITH cte AS (VALUES (1, 'player1', 'Game1', 1000), (2, 'player2', 'Game2', 1500), (3, 'player3', 'Game3', 2000)) INSERT INTO high_scores (id, username, game, score) SELECT * FROM cte;
What is the earliest excavation start date for the 'Iron Age' culture?
CREATE TABLE ExcavationSites (id INT,site VARCHAR(20),location VARCHAR(30),start_date DATE,end_date DATE); INSERT INTO ExcavationSites (id,site,location,start_date,end_date) VALUES (1,'BronzeAge','UK','2000-01-01','2005-12-31'),(2,'IronAge','Germany','1994-01-01','1997-12-31');
SELECT MIN(start_date) FROM ExcavationSites WHERE site = 'IronAge';
List the clinical trials conducted in Africa.
CREATE TABLE clinical_trials (trial_id INT,trial_name VARCHAR(255),location VARCHAR(255)); INSERT INTO clinical_trials (trial_id,trial_name,location) VALUES (1,'TrialA','America'),(2,'TrialB','Africa'),(3,'TrialC','Europe');
SELECT trial_name FROM clinical_trials WHERE location = 'Africa';
What is the average safety score for models trained on the 'South America' or 'Africa' regions?
CREATE TABLE model_safety (model_id INT,safety_score FLOAT,region_id INT); CREATE TABLE regions (region_id INT,region_name VARCHAR(50)); INSERT INTO regions (region_id,region_name) VALUES (1,'North America'),(2,'Europe'),(3,'Asia'),(4,'South America'),(5,'Africa');
SELECT AVG(ms.safety_score) FROM model_safety ms JOIN regions r ON ms.region_id = r.region_id WHERE r.region_name IN ('South America', 'Africa');
List all marine conservation projects and their budgets in Africa.
CREATE TABLE conservation_projects (name VARCHAR(255),location VARCHAR(255),budget FLOAT); INSERT INTO conservation_projects (name,location,budget) VALUES ('Coral Reef Restoration','Kenya',500000),('Mangrove Forest Protection','Tanzania',750000);
SELECT name, budget FROM conservation_projects WHERE location LIKE 'Africa%';
What is the maximum production volume for silver mines in Mexico?
CREATE TABLE mines (id INT,name TEXT,location TEXT,production_volume INT); INSERT INTO mines (id,name,location,production_volume) VALUES (1,'Mexican Silver Mine','Mexico',10000); INSERT INTO mines (id,name,location,production_volume) VALUES (2,'Silver Ridge','USA',12000);
SELECT MAX(production_volume) FROM mines WHERE location = 'Mexico' AND mineral = 'silver';
What was the average delay for defense projects in 2020?
CREATE SCHEMA if not exists defense_projects;CREATE TABLE if not exists defense_project_delays(project_name text,delay_year integer,delay_duration integer);INSERT INTO defense_project_delays(project_name,delay_year,delay_duration) VALUES('F-35',2020,2),('Joint Light Tactical Vehicle',2020,3),('Global Hawk',2020,1);
SELECT AVG(delay_duration) FROM defense_project_delays WHERE delay_year = 2020;
List the chemical_ids and total production quantities for chemicals produced in Argentina
CREATE TABLE chemical_production (id INT PRIMARY KEY,chemical_id VARCHAR(10),quantity INT,country VARCHAR(50)); INSERT INTO chemical_production (id,chemical_id,quantity,country) VALUES (1,'XY987',700,'Brazil'),(2,'GH247',600,'India'),(3,'XY987',300,'Australia'),(4,'GH247',500,'India'),(5,'GH247',800,'Brazil'),(6,'XY987',200,'Chile'),(7,'LM345',150,'Argentina'),(8,'XY987',400,'Argentina');
SELECT chemical_id, SUM(quantity) FROM chemical_production WHERE country = 'Argentina' GROUP BY chemical_id;
What is the number of employees in the "mining_operations" table, who are working in the "safety" department and have an age greater than 30?
CREATE TABLE mining_operations (id INT,name VARCHAR(50),department VARCHAR(50),age INT);
SELECT COUNT(*) FROM mining_operations WHERE department = 'safety' AND age > 30;
Delete all customers with loyalty points less than 100
CREATE TABLE customers (customer_id INT,name VARCHAR(50),email VARCHAR(50),loyalty_points INT);
DELETE FROM customers WHERE loyalty_points < 100;
How many timber production sites are there in each country, and what is their total area in hectares?
CREATE TABLE timber_production (id INT,country VARCHAR(255),site_name VARCHAR(255),area FLOAT); INSERT INTO timber_production (id,country,site_name,area) VALUES (1,'Canada','Site A',50000.0),(2,'Canada','Site B',60000.0),(3,'Brazil','Site C',70000.0),(4,'Brazil','Site D',80000.0);
SELECT country, COUNT(*), SUM(area) FROM timber_production GROUP BY country;
Identify teachers who have not completed any professional development courses in the past year.
CREATE TABLE teachers (teacher_id INT,teacher_name VARCHAR(50),last_pd_course_date DATE); CREATE TABLE professional_development_courses (course_id INT,course_name VARCHAR(50),course_date DATE);
SELECT teacher_id, teacher_name FROM teachers LEFT JOIN professional_development_courses ON teachers.teacher_id = professional_development_courses.teacher_id WHERE professional_development_courses.course_date IS NULL OR professional_development_courses.course_date < DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR);
Which countries produced more than 100,000 units of any REE in 2019?
CREATE TABLE production (country VARCHAR(255),year INT,element VARCHAR(10),quantity INT); INSERT INTO production (country,year,element,quantity) VALUES ('China',2019,'Nd',120000),('China',2019,'Pr',130000),('China',2019,'Dy',140000),('Australia',2019,'Nd',50000);
SELECT country, element, quantity FROM production WHERE year = 2019 AND quantity > 100000;
What's the total amount donated by first-time donors in Q1 2021?
CREATE TABLE donations (id INT,donor_id INT,donation_date DATE,amount DECIMAL(10,2)); INSERT INTO donations (id,donor_id,donation_date,amount) VALUES (1,1001,'2021-01-15',50.00),(2,1002,'2021-03-30',100.00),(3,1001,'2021-04-10',75.00);
SELECT SUM(amount) FROM donations WHERE donor_id NOT IN (SELECT donor_id FROM donations WHERE donation_date < '2021-01-01') AND donation_date < '2021-04-01';
List unique investors who have invested in companies based in the United Kingdom and Australia.
CREATE TABLE company (id INT,name TEXT,country TEXT); INSERT INTO company (id,name,country) VALUES (1,'Acme Inc','USA'),(2,'Beta Corp','UK'),(3,'Gamma PLC','Australia'); CREATE TABLE investment (investor_id INT,company_id INT); INSERT INTO investment (investor_id,company_id) VALUES (1,1),(2,2),(3,3),(4,3);
SELECT DISTINCT investor_id FROM investment WHERE company_id IN (SELECT id FROM company WHERE country IN ('UK', 'Australia'))