instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
Find the top 3 suppliers with the highest revenue this year
CREATE TABLE supplier_sales (sale_date DATE,supplier_id INT,sale_revenue DECIMAL(10,2));
SELECT supplier_id, SUM(sale_revenue) as annual_revenue FROM supplier_sales WHERE sale_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR) GROUP BY supplier_id ORDER BY annual_revenue DESC LIMIT 3;
Return the name of the athlete who has jumped the highest in the high jump
CREATE TABLE athletes (athlete_name VARCHAR(255),sport VARCHAR(255)); INSERT INTO athletes (athlete_name,sport) VALUES ('Mutaz Essa Barshim','Athletics'); INSERT INTO athletes (athlete_name,sport) VALUES ('Bohdan Bondarenko','Athletics'); CREATE TABLE high_jumps (athlete_name VARCHAR(255),height FLOAT); INSERT INTO high_jumps (athlete_name,height) VALUES ('Mutaz Essa Barshim',2.43); INSERT INTO high_jumps (athlete_name,height) VALUES ('Bohdan Bondarenko',2.42);
SELECT athlete_name FROM high_jumps WHERE height = (SELECT MAX(height) FROM high_jumps);
What's the release year and rating for the K-pop song with the highest rating?
CREATE TABLE k_pop_songs(song_id INT,release_year INT,rating DECIMAL(2,1)); INSERT INTO k_pop_songs(song_id,release_year,rating) VALUES (1,2021,4.5),(2,2021,4.7),(3,2020,4.8),(4,2022,5.0);
SELECT release_year, MAX(rating) FROM k_pop_songs;
Update the 'sequestration' value for the record with id 2 in the 'carbon_sequestration' table to 900 metric tons.
CREATE TABLE carbon_sequestration (id INT,location VARCHAR(255),sequestration FLOAT); INSERT INTO carbon_sequestration (id,location,sequestration) VALUES (1,'Location1',1200),(2,'Location2',800),(3,'Location3',1500);
UPDATE carbon_sequestration SET sequestration = 900 WHERE id = 2;
What is the average depth of all marine protected areas in the Pacific region?"
CREATE TABLE marine_protected_areas (area_name TEXT,region TEXT,avg_depth REAL); CREATE TABLE pacific_region (region_name TEXT,region_description TEXT);
SELECT AVG(mpa.avg_depth) FROM marine_protected_areas mpa INNER JOIN pacific_region pr ON mpa.region = pr.region_name;
Identify suppliers who have not been certified in the last 2 years and provide their names and the number of products they supply.
CREATE TABLE suppliers(id INT PRIMARY KEY,name VARCHAR(50),certified_date DATE); INSERT INTO suppliers(id,name,certified_date) VALUES (1,'Supplier One','2021-01-01'),(2,'Supplier Two','2022-06-15'),(3,'Supplier Three','2020-08-08'),(4,'Supplier Four','2023-02-28'),(5,'Supplier Five','2021-05-15'); CREATE TABLE inventory(id INT PRIMARY KEY,product VARCHAR(50),supplier_id INT,FOREIGN KEY (supplier_id) REFERENCES suppliers(id)); INSERT INTO inventory(id,product,supplier_id) VALUES (1,'Product A',1),(2,'Product B',2),(3,'Product C',3),(4,'Product D',3),(5,'Product E',4),(6,'Product F',5);
SELECT s.name, COUNT(i.id) AS product_count FROM suppliers s LEFT JOIN inventory i ON s.id = i.supplier_id WHERE s.certified_date IS NULL OR s.certified_date < DATE_SUB(CURRENT_DATE, INTERVAL 2 YEAR) GROUP BY s.name;
What is the total carbon footprint of all accommodations in Africa?
CREATE TABLE if NOT EXISTS accommodations (id INT,name TEXT,country TEXT,carbon_footprint INT); INSERT INTO accommodations (id,name,country,carbon_footprint) VALUES (1,'Eco Lodge','Africa',50),(2,'Green Resort','Africa',75);
SELECT SUM(carbon_footprint) FROM accommodations WHERE country = 'Africa';
What is the difference in total runs scored between the top and bottom scorers in each cricket season?
CREATE TABLE cricket_teams (id INT,team VARCHAR(50),season INT,runs INT); INSERT INTO cricket_teams (id,team,season,runs) VALUES (1,'Mumbai Indians',2022,2301),(2,'Chennai Super Kings',2022,2182);
SELECT season, MAX(runs) - MIN(runs) FROM cricket_teams GROUP BY season;
Delete the record of the vessel 'Endeavour' if it didn't transport any cargo in the last month.
CREATE TABLE Vessels (ID INT,Name VARCHAR(255),CargoQuantity INT,LastCargoArrival DATETIME); INSERT INTO Vessels (ID,Name,CargoQuantity,LastCargoArrival) VALUES (1,'Endeavour',0,'2022-01-01'),(2,'Pioneer',100,'2022-02-01');
DELETE FROM Vessels WHERE Name = 'Endeavour' AND CargoQuantity = 0 AND LastCargoArrival < DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH);
What is the total number of emergency calls in each borough?
CREATE TABLE borough (id INT,name TEXT); INSERT INTO borough (id,name) VALUES (1,'Manhattan'),(2,'Brooklyn'),(3,'Queens'),(4,'Bronx'),(5,'Staten Island'); CREATE TABLE emergency_calls (id INT,borough_id INT,call_time TIMESTAMP);
SELECT b.name, COUNT(ec.id) FROM borough b LEFT JOIN emergency_calls ec ON b.id = ec.borough_id GROUP BY b.id;
List all decentralized applications in the 'Polygon' network that were launched between 2022-01-01 and 2022-12-31.
CREATE TABLE polygon_dapps (id INT,name VARCHAR(255),network VARCHAR(255),launch_date DATE); INSERT INTO polygon_dapps (id,name,network,launch_date) VALUES (1,'Dapp3','polygon','2022-03-01'),(2,'Dapp4','polygon','2021-12-31');
SELECT * FROM polygon_dapps WHERE network = 'polygon' AND launch_date BETWEEN '2022-01-01' AND '2022-12-31';
What is the average rainfall per farm?
CREATE TABLE weather_data (id INT PRIMARY KEY,farm_id INT,date DATE,temperature FLOAT,rainfall FLOAT); INSERT INTO weather_data (id,farm_id,date,temperature,rainfall) VALUES (4,3,'2019-05-01',21.6,16.2); INSERT INTO weather_data (id,farm_id,date,temperature,rainfall) VALUES (5,3,'2019-05-02',24.1,13.5);
SELECT farm_id, AVG(rainfall) FROM weather_data GROUP BY farm_id;
Show the total number of products in each product category that are not made from recycled materials.
CREATE TABLE Products_By_Category (product_category VARCHAR(255),product_id INT); INSERT INTO Products_By_Category (product_category,product_id) VALUES ('Clothing',100),('Electronics',101),('Food',102),('Clothing',103),('Furniture',104);
SELECT product_category, COUNT(*) as non_recycled_count FROM Products_By_Category LEFT JOIN Supplier_Products ON Products_By_Category.product_id = Supplier_Products.product_id WHERE Supplier_Products.is_recycled IS NULL GROUP BY product_category;
What is the average project timeline for sustainable building practices in the northeast region?
CREATE TABLE timelines (state VARCHAR(255),practice VARCHAR(255),timeline INT);
SELECT AVG(timeline) FROM timelines WHERE state IN ('Connecticut', 'Maine', 'Massachusetts', 'New Hampshire', 'New Jersey', 'New York', 'Pennsylvania', 'Rhode Island', 'Vermont') AND practice IN ('Green Roofs', 'Solar Panels', 'Rainwater Harvesting');
Find the total number of social impact investments and total funds invested in the Education sector for each gender, excluding investments made before 2020 and only considering investments made by Indian investors.
CREATE TABLE Investors (InvestorID INT,Gender VARCHAR(10),InvestorCountry VARCHAR(20)); INSERT INTO Investors VALUES (1,'Male','India'),(2,'Female','Brazil'); CREATE TABLE Investments (InvestmentID INT,InvestorID INT,Sector VARCHAR(20),FundsInvested DECIMAL(10,2),InvestmentDate DATE); INSERT INTO Investments VALUES (1,1,'Education',500.00,'2021-01-01'),(2,1,'Education',200.00,'2019-01-01'),(3,2,'Education',350.00,'2021-02-01'),(4,2,'Education',150.00,'2019-01-01');
SELECT i.Gender, COUNT(Investments.InvestmentID) AS TotalInvestments, SUM(Investments.FundsInvested) AS TotalFundsInvested FROM Investors i INNER JOIN Investments ON i.InvestorID = Investments.InvestorID WHERE Investments.Sector = 'Education' AND Investments.InvestmentDate >= '2020-01-01' AND i.InvestorCountry = 'India' GROUP BY i.Gender;
Count the number of pollution control initiatives in the Caribbean Sea that have been implemented since 2015.
CREATE TABLE pollution_control_initiatives (id INT,name TEXT,location TEXT,year INT); INSERT INTO pollution_control_initiatives (id,name,location,year) VALUES (1,'Coral Reef Protection Program','Caribbean Sea',2017),(2,'Ocean Plastic Reduction Project','Caribbean Sea',2016),(3,'Marine Life Restoration Effort','Atlantic Ocean',2015);
SELECT COUNT(*) FROM pollution_control_initiatives WHERE location = 'Caribbean Sea' AND year >= 2015;
What is the total population of all marine species in the Southern Ocean with a conservation status of 'Critically Endangered'?
CREATE TABLE species (id INT,name VARCHAR(255),conservation_status VARCHAR(255),population INT,ocean VARCHAR(255)); INSERT INTO species (id,name,conservation_status,population,ocean) VALUES (1,'Blue Whale','Endangered',1000,'Atlantic'); INSERT INTO species (id,name,conservation_status,population,ocean) VALUES (2,'Dolphin','Least Concern',50000,'Pacific'); INSERT INTO species (id,name,conservation_status,population,ocean) VALUES (3,'Clownfish','Vulnerable',30000,'Indian'); INSERT INTO species (id,name,conservation_status,population,ocean) VALUES (4,'Krill','Critically Endangered',2000,'Southern');
SELECT SUM(population) as total_population FROM species WHERE conservation_status = 'Critically Endangered' AND ocean = 'Southern';
What was the R&D expenditure for each drug in Q1 2022?
CREATE TABLE rd_expenditure (expenditure_id INT,drug_id INT,quarter INT,year INT,amount DECIMAL(10,2));
SELECT d.drug_name, SUM(r.amount) as total_expenditure FROM rd_expenditure r JOIN drugs d ON r.drug_id = d.drug_id WHERE r.quarter = 1 AND r.year = 2022 GROUP BY d.drug_name;
Calculate the average temperature for each crop type in the month of July for 2021.
CREATE TABLE sensor_data (id INT,crop_type VARCHAR(255),temperature INT,humidity INT,measurement_date DATE); INSERT INTO sensor_data (id,crop_type,temperature,humidity,measurement_date) VALUES (1,'Corn',22,55,'2021-07-01'); INSERT INTO sensor_data (id,crop_type,temperature,humidity,measurement_date) VALUES (2,'Cotton',28,65,'2021-07-03');
SELECT crop_type, AVG(temperature) as avg_temperature FROM sensor_data WHERE measurement_date BETWEEN '2021-07-01' AND '2021-07-31' GROUP BY crop_type;
Calculate the percentage change in mining operation costs from 2018 to 2020
CREATE TABLE operation_costs(year INT,operation VARCHAR(20),costs INT); INSERT INTO operation_costs VALUES (2018,'mining',5000000),(2019,'mining',5200000),(2020,'mining',5400000);
SELECT (SUM(costs) * 100.0 / (SELECT SUM(costs) FROM operation_costs WHERE year = 2018) - 100.0) as percentage_change FROM operation_costs WHERE year = 2020 AND operation = 'mining';
Insert data into the excavation sites table
CREATE TABLE ExcavationSites (SiteID INT PRIMARY KEY,SiteName VARCHAR(255),Country VARCHAR(255),StartDate DATE,EndDate DATE); INSERT INTO ExcavationSites (SiteID,SiteName,Country,StartDate,EndDate) VALUES (1,'Pompeii','Italy','79-08-24','79-10-01');
INSERT INTO ExcavationSites (SiteID, SiteName, Country, StartDate, EndDate) VALUES (1, 'Pompeii', 'Italy', '79-08-24', '79-10-01');
What is the total weight of all metal artifacts in the 'Metal_Artifacts' table?
CREATE TABLE Metal_Artifacts (id INT,artifact_name VARCHAR(50),artifact_type VARCHAR(50),weight INT); INSERT INTO Metal_Artifacts (id,artifact_name,artifact_type,weight) VALUES (1,'Bronze Sword','Metal',2000),(2,'Iron Spear','Metal',3000),(3,'Gold Mask','Metal',1000);
SELECT SUM(weight) FROM Metal_Artifacts WHERE artifact_type = 'Metal';
What is the average age of patients diagnosed with diabetes in rural areas, grouped by state?
CREATE TABLE rural_patients (id INT,state VARCHAR(2),age INT,diagnosis VARCHAR(10)); INSERT INTO rural_patients (id,state,age,diagnosis) VALUES (1,'AL',65,'diabetes'); CREATE TABLE states (state_abbr VARCHAR(2),state_name VARCHAR(20)); INSERT INTO states (state_abbr,state_name) VALUES ('AL','Alabama');
SELECT r.state, AVG(r.age) FROM rural_patients r JOIN states s ON r.state = s.state_abbr WHERE r.diagnosis = 'diabetes' GROUP BY r.state;
What was the total revenue by program category in Q2 2021?
CREATE TABLE Revenue (program_category VARCHAR(50),date DATE,revenue DECIMAL(10,2)); INSERT INTO Revenue (program_category,date,revenue) VALUES ('Dance','2021-04-01',15000.00),('Theater','2021-04-01',20000.00),('Music','2021-04-01',12000.00),('Art','2021-04-01',18000.00),('Dance','2021-07-01',17000.00),('Theater','2021-07-01',22000.00),('Music','2021-07-01',13000.00),('Art','2021-07-01',19000.00);
SELECT SUM(revenue) AS total_revenue, program_category FROM Revenue WHERE date BETWEEN '2021-04-01' AND '2021-06-30' GROUP BY program_category;
What is the total REE production by mine name for 2020?
CREATE TABLE mines (id INT,name TEXT,location TEXT,annual_production INT); INSERT INTO mines (id,name,location,annual_production) VALUES (1,'Mine A','Country X',1500),(2,'Mine B','Country Y',2000),(3,'Mine C','Country Z',1750);
SELECT name, SUM(annual_production) as total_production FROM mines WHERE YEAR(timestamp) = 2020 GROUP BY name;
What is the total cargo weight for vessels in the Mediterranean sea?
CREATE TABLE cargos(id INT,vessel_id INT,cargo_weight FLOAT); CREATE TABLE vessel_locations(id INT,vessel_id INT,location VARCHAR(50),timestamp TIMESTAMP);
SELECT SUM(cargo_weight) FROM cargos JOIN vessel_locations ON cargos.vessel_id = vessel_locations.vessel_id WHERE location LIKE '%Mediterranean%'
What is the maximum ridership for routes that have a frequency of less than once per hour?
CREATE TABLE RouteRidership (RouteID int,AnnualPassengers int,Frequency int); INSERT INTO RouteRidership (RouteID,AnnualPassengers,Frequency) VALUES (1,80000,30),(2,60000,45),(3,40000,60),(4,90000,20);
SELECT MAX(AnnualPassengers) FROM RouteRidership WHERE Frequency < 60;
List all regulatory frameworks in the blockchain domain that have been implemented so far this decade.
CREATE TABLE RegulatoryFrameworks (framework_id INT,framework_name TEXT,implementation_year INT); INSERT INTO RegulatoryFrameworks (framework_id,framework_name,implementation_year) VALUES (1,'Framework1',2020),(2,'Framework2',2021),(3,'Framework3',2022);
SELECT framework_name FROM RegulatoryFrameworks WHERE RegulatoryFrameworks.implementation_year >= 2010 AND RegulatoryFrameworks.implementation_year < 2030;
What is the average years of experience for attorneys specialized in Immigration Law?
CREATE TABLE Attorneys (AttorneyID INT,YearsOfExperience INT,Specialization VARCHAR(20),Gender VARCHAR(10),OfficeLocation VARCHAR(20)); INSERT INTO Attorneys (AttorneyID,YearsOfExperience,Specialization,Gender,OfficeLocation) VALUES (3,15,'Immigration Law','Non-binary','Chicago'); INSERT INTO Attorneys (AttorneyID,YearsOfExperience,Specialization,Gender,OfficeLocation) VALUES (4,9,'Immigration Law','Female','Miami');
SELECT Specialization, AVG(YearsOfExperience) as AverageExperience FROM Attorneys WHERE Specialization = 'Immigration Law';
What is the average housing affordability score and total property price for properties in the "AffordableCity" schema, grouped by property type?
CREATE TABLE Property (id INT,property_type VARCHAR(20),price FLOAT,affordability_score INT,city VARCHAR(20)); INSERT INTO Property (id,property_type,price,affordability_score,city) VALUES (1,'Apartment',500000,85,'AffordableCity'),(2,'House',700000,70,'AffordableCity'),(3,'Condo',300000,90,'AffordableCity');
SELECT Property.property_type, AVG(Property.affordability_score) AS avg_affordability_score, SUM(Property.price) AS total_price FROM Property WHERE Property.city = 'AffordableCity' GROUP BY Property.property_type;
How many players play each game?
CREATE TABLE Players (PlayerID INT,Age INT,Game VARCHAR(10)); INSERT INTO Players (PlayerID,Age,Game) VALUES (1,25,'Game1'),(2,30,'Game1'),(3,35,'Game2');
SELECT Game, COUNT(*) FROM Players GROUP BY Game;
Determine the average number of publications per author in the Humanities department.
CREATE TABLE publication (id INT,author VARCHAR(50),department VARCHAR(30),year INT,title VARCHAR(100)); INSERT INTO publication (id,author,department,year,title) VALUES (1,'Jasmine','Humanities',2019,'Critical Theory'),(2,'Kai','Humanities',2018,'Literary Analysis');
SELECT department, AVG(num_publications) as avg_publications FROM (SELECT department, author, COUNT(*) as num_publications FROM publication GROUP BY department, author) AS subquery GROUP BY department;
How many creative_ai_applications are there for each application_type?
CREATE TABLE creative_ai_applications (application_id INTEGER,application_type TEXT,application_description TEXT);
SELECT application_type, COUNT(*) as count FROM creative_ai_applications GROUP BY application_type;
How much climate finance has been allocated for mitigation projects in Africa?
CREATE TABLE climate_finance (region VARCHAR(50),amount FLOAT,sector VARCHAR(50)); INSERT INTO climate_finance (region,amount,sector) VALUES ('Asia',6000000,'Mitigation'),('Africa',4000000,'Mitigation'),('Europe',7000000,'Adaptation');
SELECT SUM(amount) FROM climate_finance WHERE region = 'Africa' AND sector = 'Mitigation';
What is the total number of union members in the 'healthcare' industry?
CREATE TABLE union_members (id INT,name VARCHAR(50),union_id INT,industry VARCHAR(20)); INSERT INTO union_members (id,name,union_id,industry) VALUES (1,'John Doe',123,'construction'),(2,'Jane Smith',456,'retail'),(3,'Mike Johnson',789,'healthcare');
SELECT COUNT(*) FROM union_members WHERE industry = 'healthcare';
What are the total oil production figures for offshore rigs in the Gulf of Mexico and the North Sea?
CREATE TABLE offshore_oil_production (rig_name TEXT,location TEXT,oil_production INTEGER); INSERT INTO offshore_oil_production (rig_name,location,oil_production) VALUES ('Rig1','Gulf of Mexico',150000),('Rig2','Gulf of Mexico',180000),('Rig3','North Sea',200000),('Rig4','North Sea',170000);
SELECT oil_production FROM offshore_oil_production WHERE location IN ('Gulf of Mexico', 'North Sea')
Find the change in biosensor production between 2021 and 2022 in Japan.
CREATE TABLE biosensor_production (id INT,year INT,location TEXT,quantity INT); INSERT INTO biosensor_production (id,year,location,quantity) VALUES (1,2021,'Japan',800),(2,2022,'Japan',950),(3,2021,'USA',1200);
SELECT location, (SELECT quantity FROM biosensor_production WHERE location = 'Japan' AND year = 2022) - (SELECT quantity FROM biosensor_production WHERE location = 'Japan' AND year = 2021) as change FROM biosensor_production WHERE location = 'Japan';
Insert a new investment round into the "investment_rounds" table for 'Lima Inc.' with a Series C round, $12M raised, and round date 2020-11-25
CREATE TABLE investment_rounds (id INT,company_name VARCHAR(100),round_type VARCHAR(50),raised_amount FLOAT,round_date DATE);
INSERT INTO investment_rounds (id, company_name, round_type, raised_amount, round_date) VALUES (8, 'Lima Inc.', 'Series C', 12000000, '2020-11-25');
What was the average sales revenue for 'DrugE' in 2020?
CREATE TABLE drug_e_sales (quarter INTEGER,year INTEGER,revenue INTEGER); INSERT INTO drug_e_sales (quarter,year,revenue) VALUES (1,2020,550000),(2,2020,600000),(3,2020,700000),(4,2020,800000);
SELECT AVG(revenue) FROM drug_e_sales WHERE year = 2020 AND drug_name = 'DrugE';
Who are the journalists with the highest and lowest salaries?
CREATE TABLE journalist_salaries (name VARCHAR(50),gender VARCHAR(10),salary DECIMAL(10,2)); INSERT INTO journalist_salaries (name,gender,salary) VALUES ('Fiona Chen','Female',80000.00),('George Harris','Male',90000.00),('Heidi Martinez','Female',70000.00),('Ivan Thompson','Male',100000.00),('Jasmine Brown','Female',60000.00);
SELECT name, salary FROM journalist_salaries ORDER BY salary DESC LIMIT 1;
Calculate the average funding amount for companies founded in the last 5 years
CREATE TABLE company_founding (company_name VARCHAR(255),foundation_year INT); INSERT INTO company_founding (company_name,foundation_year) VALUES ('Acme Inc',2018),('Beta Corp',2015),('Charlie LLC',2019),('Delta Co',2016); CREATE TABLE funding (company_name VARCHAR(255),funding_amount INT); INSERT INTO funding (company_name,funding_amount) VALUES ('Acme Inc',500000),('Beta Corp',750000),('Charlie LLC',600000),('Delta Co',400000);
SELECT AVG(funding_amount) FROM funding JOIN company_founding ON funding.company_name = company_founding.company_name WHERE foundation_year >= YEAR(CURDATE()) - 5;
What is the total revenue for each game genre in the last quarter, sorted by total revenue.
CREATE TABLE games(id INT,name VARCHAR(50),genre VARCHAR(50),revenue FLOAT); CREATE TABLE transactions(id INT,game_id INT,transaction_date DATE,amount FLOAT);
SELECT genres.genre, SUM(transactions.amount) as total_revenue FROM games JOIN transactions ON games.name = transactions.game_name JOIN (SELECT DISTINCT game_name, genre FROM games) genres ON games.genre = genres.genre WHERE transaction_date >= DATE_SUB(CURRENT_DATE, INTERVAL 3 MONTH) GROUP BY genres.genre ORDER BY total_revenue DESC;
What is the average maintenance cost for military equipment in the last 3 months?
CREATE TABLE Equipment_Maintenance (id INT,equipment_id INT,maintenance_date DATE,cost FLOAT); INSERT INTO Equipment_Maintenance (id,equipment_id,maintenance_date,cost) VALUES (1,101,'2022-01-01',5000),(2,102,'2022-01-05',7000),(3,101,'2022-04-01',6000);
SELECT AVG(cost) FROM Equipment_Maintenance WHERE maintenance_date BETWEEN DATE_SUB(CURRENT_DATE, INTERVAL 3 MONTH) AND CURRENT_DATE;
What is the range of labor hours for producing each product type?
CREATE TABLE Products (ProductID INT,ProductType VARCHAR(50)); INSERT INTO Products (ProductID,ProductType) VALUES (1,'ProductTypeA'),(2,'ProductTypeA'),(3,'ProductTypeB'),(4,'ProductTypeB'),(5,'ProductTypeC'),(6,'ProductTypeC'); CREATE TABLE LaborHours (HourID INT,LaborHours DECIMAL(5,2),ProductID INT); INSERT INTO LaborHours (HourID,LaborHours,ProductID) VALUES (1,5.50,1),(2,6.60,1),(3,7.70,2),(4,8.80,2),(5,9.90,3),(6,10.00,3),(7,11.11,4),(8,12.12,4),(9,13.13,5),(10,14.14,5);
SELECT ProductType, MAX(LaborHours) - MIN(LaborHours) as LaborHoursRange FROM Products p JOIN LaborHours lh ON p.ProductID = lh.ProductID GROUP BY ProductType;
List all clinical trials with the number of participants, sorted by trial start date in descending order, excluding trials with a status of 'Suspended' or 'Terminated'.
CREATE TABLE clinical_trials (trial_id INT,trial_name VARCHAR(255),status VARCHAR(255),start_date DATE); INSERT INTO clinical_trials (trial_id,trial_name,status,start_date) VALUES (1,'TrialE','Completed','2022-01-01'),(2,'TrialF','Suspended','2022-02-01'),(3,'TrialG','Recruiting','2022-03-01'),(4,'TrialH','Terminated','2022-04-01'); CREATE TABLE trial_participants (participant_id INT,trial_id INT); INSERT INTO trial_participants (participant_id,trial_id) VALUES (1,1),(2,1),(3,3),(4,4);
SELECT ct.trial_name, COUNT(tp.participant_id) as num_participants, ct.start_date FROM clinical_trials ct JOIN trial_participants tp ON ct.trial_id = tp.trial_id WHERE ct.status NOT IN ('Suspended', 'Terminated') GROUP BY ct.trial_name, ct.start_date ORDER BY ct.start_date DESC;
Delete digital assets with a market cap below $100M from the database.
CREATE SCHEMA if not exists blockchain; CREATE TABLE if not exists blockchain.digital_assets (asset_id INT AUTO_INCREMENT,asset_name VARCHAR(255),market_cap DECIMAL(18,2),PRIMARY KEY (asset_id)); INSERT INTO blockchain.digital_assets (asset_name,market_cap) VALUES ('Bitcoin',80000000000.00),('Ethereum',32000000000.00);
DELETE FROM blockchain.digital_assets WHERE market_cap < 100000000;
Delete a tour operator that violates sustainable tourism principles
CREATE TABLE operator_sustainability (id INT PRIMARY KEY,operator_id INT,sustainable BOOLEAN);
DELETE FROM operator_sustainability WHERE operator_id = 1 AND sustainable = false;
What is the number of cases in the 'Family' category?
CREATE TABLE cases (case_id INT,category TEXT); INSERT INTO cases (case_id,category) VALUES (1,'Civil'),(2,'Civil'),(3,'Criminal'),(4,'Family'),(5,'Family');
SELECT COUNT(*) FROM cases WHERE category = 'Family';
Get the latest military equipment maintenance record for each type of equipment
CREATE TABLE equipment_maintenance (id INT,equipment_type VARCHAR(255),maintenance_date DATE);
SELECT equipment_type, MAX(maintenance_date) FROM equipment_maintenance GROUP BY equipment_type;
What is the maximum budget allocated to public schools in the state of California?
CREATE TABLE public_schools (school_name TEXT,state TEXT,budget INTEGER); INSERT INTO public_schools (school_name,state,budget) VALUES ('School A','CA',8000000),('School B','CA',9000000),('School C','NY',7000000);
SELECT MAX(budget) FROM public_schools WHERE state = 'CA';
Get the percentage of products manufactured using recycled materials for each product category
CREATE TABLE recycled_materials (recycled_material_id INT,recycled_material_name VARCHAR(255),product_category VARCHAR(255)); INSERT INTO recycled_materials (recycled_material_id,recycled_material_name,product_category) VALUES (1,'Material X','Category X'),(2,'Material Y','Category X'),(3,'Material Z','Category Y'),(4,'Material W','Category Y'); CREATE TABLE production (production_id INT,product_id INT,recycled_material_id INT,production_quantity INT); INSERT INTO production (production_id,product_id,recycled_material_id,production_quantity) VALUES (1,1,1,100),(2,1,2,200),(3,2,1,250),(4,2,2,300),(5,3,3,350),(6,3,4,400),(7,4,3,450),(8,4,4,500);
SELECT product_category, SUM(production_quantity) as total_production_quantity, SUM(CASE WHEN recycled_material_id IS NOT NULL THEN production_quantity ELSE 0 END) as recycled_production_quantity, (SUM(CASE WHEN recycled_material_id IS NOT NULL THEN production_quantity ELSE 0 END) / SUM(production_quantity)) * 100 as recycled_percentage FROM production JOIN recycled_materials ON production.recycled_material_id = recycled_materials.recycled_material_id GROUP BY product_category;
Which marine species are affected by pollution in the Mediterranean Sea?
CREATE TABLE PollutionSources (ID INT,Source VARCHAR(255),Location VARCHAR(255)); INSERT INTO PollutionSources (ID,Source,Location) VALUES (2,'Factory Waste','Mediterranean Sea'); CREATE TABLE SpeciesAffected (ID INT,Species VARCHAR(255),Location VARCHAR(255)); INSERT INTO SpeciesAffected (ID,Species,Location) VALUES (1,'Turtle','Mediterranean Sea');
SELECT s.Species FROM SpeciesAffected s INNER JOIN PollutionSources p ON s.Location = p.Location WHERE p.Source = 'Factory Waste';
What's the number of users who logged in for the first time in the last week in the 'gaming' schema?
CREATE TABLE users (id INT,username VARCHAR(50),last_login TIMESTAMP);
SELECT COUNT(*) FROM users WHERE last_login >= DATE_SUB(NOW(), INTERVAL 1 WEEK) AND last_login < NOW();
Insert a new record into the 'digital_divide' table with an id of 4, a problem of 'Lack of digital resources in schools', and a description of 'Many schools do not have access to digital resources'
CREATE TABLE digital_divide (id INT PRIMARY KEY,problem VARCHAR(50),description TEXT); INSERT INTO digital_divide (id,problem,description) VALUES (1,'Lack of internet access','High-speed internet unavailable in many rural areas'),(2,'Expensive devices','Cost of devices is a barrier for low-income households'),(3,'Literacy and skills','Limited computer literacy and digital skills');
INSERT INTO digital_divide (id, problem, description) VALUES (4, 'Lack of digital resources in schools', 'Many schools do not have access to digital resources');
What is the number of performances in each category that had more than 500 attendees in Chicago?
CREATE TABLE chicago_events(id INT,category VARCHAR(30),attendees INT); INSERT INTO chicago_events VALUES (1,'Theater',600); INSERT INTO chicago_events VALUES (2,'Concert',400);
SELECT category, COUNT(*) FROM chicago_events WHERE attendees > 500 GROUP BY category;
Which fields have nitrogen_level greater than 4.5 and temperature lower than 25.0?
CREATE TABLE Fields (id INT PRIMARY KEY,name VARCHAR(255),acres FLOAT,location VARCHAR(255)); INSERT INTO Fields (id,name,acres,location) VALUES (1,'FieldA',5.6,'US-MN'),(2,'FieldB',3.2,'US-CA'); CREATE TABLE Satellite_Imagery (id INT PRIMARY KEY,location VARCHAR(255),nitrogen_level FLOAT); INSERT INTO Satellite_Imagery (id,location,nitrogen_level) VALUES (1,'US-MN',3.5),(2,'US-CA',4.1); CREATE TABLE IoT_Sensors (id INT PRIMARY KEY,Field_id INT,temperature FLOAT,humidity FLOAT); INSERT INTO IoT_Sensors (id,Field_id,temperature,humidity) VALUES (1,1,20.5,60.3),(2,2,25.3,70.2);
SELECT Fields.name FROM Fields INNER JOIN Satellite_Imagery ON Fields.location = Satellite_Imagery.location INNER JOIN IoT_Sensors ON Fields.id = IoT_Sensors.Field_id WHERE Satellite_Imagery.nitrogen_level > 4.5 AND IoT_Sensors.temperature < 25.0;
What is the minimum fairness score for each type of AI model?
CREATE TABLE ai_model (id INT,name VARCHAR(255),type VARCHAR(255),fairness_score FLOAT); INSERT INTO ai_model (id,name,type,fairness_score) VALUES (1,'AdaNet','Supervised Learning',0.85),(2,'DeepDetect','Deep Learning',0.90),(3,'XGBoost','Supervised Learning',0.95);
SELECT type, MIN(fairness_score) as min_fairness FROM ai_model GROUP BY type;
Calculate the total Terbium production by year for the top 3 producers, and rank them by production volume.
CREATE TABLE terbium_producers (producer_id INT,name VARCHAR(255),year INT,terbium_production INT); INSERT INTO terbium_producers (producer_id,name,year,terbium_production) VALUES (1,'Canada',2015,120),(2,'Mexico',2015,110),(3,'USA',2015,100),(4,'Canada',2016,130),(5,'Mexico',2016,120),(6,'USA',2016,110),(7,'Canada',2017,140),(8,'Mexico',2017,130),(9,'USA',2017,120);
SELECT name, year, SUM(terbium_production) AS total_production, RANK() OVER (PARTITION BY year ORDER BY SUM(terbium_production) DESC) AS production_rank FROM terbium_producers GROUP BY name, year ORDER BY year, total_production DESC;
What is the number of hotels in 'Cape Town' with virtual tours and an AI concierge?
CREATE TABLE hotels (hotel_id INT,name TEXT,city TEXT,country TEXT,virtual_tour BOOLEAN,ai_concierge BOOLEAN);
SELECT city, COUNT(*) as num_hotels FROM hotels WHERE city = 'Cape Town' AND virtual_tour = TRUE AND ai_concierge = TRUE GROUP BY city;
List all auto shows in Europe and the number of electric vehicles exhibited in each one.
CREATE TABLE AutoShows (Id INT,Name VARCHAR(100),Location VARCHAR(100),StartDate DATE,EndDate DATE); CREATE TABLE Exhibits (Id INT,AutoShowId INT,VehicleId INT,VehicleType VARCHAR(50)); CREATE TABLE Vehicles (Id INT,Name VARCHAR(100),Type VARCHAR(50)); INSERT INTO AutoShows (Id,Name,Location,StartDate,EndDate) VALUES (1,'Paris Motor Show','Paris','2021-10-17','2021-10-24'); INSERT INTO Exhibits (Id,AutoShowId,VehicleId,VehicleType) VALUES (1,1,1,'Electric'); INSERT INTO Exhibits (Id,AutoShowId,VehicleId,VehicleType) VALUES (2,1,2,'Electric');
SELECT AutoShows.Name, COUNT(Exhibits.VehicleId) FROM AutoShows INNER JOIN Exhibits ON AutoShows.Id = Exhibits.AutoShowId INNER JOIN Vehicles ON Exhibits.VehicleId = Vehicles.Id WHERE Vehicles.Type = 'Electric' AND AutoShows.Location LIKE 'Europe%' GROUP BY AutoShows.Name;
List the countries with more than 20000 kg of imported cargo in March 2021.
CREATE TABLE imports (id INT,cargo_weight INT,country VARCHAR(20),shipment_date DATE); INSERT INTO imports (id,cargo_weight,country,shipment_date) VALUES (1,25000,'Germany','2021-03-03'); INSERT INTO imports (id,cargo_weight,country,shipment_date) VALUES (2,18000,'Germany','2021-03-05'); INSERT INTO imports (id,cargo_weight,country,shipment_date) VALUES (3,22000,'Indonesia','2021-03-07');
SELECT country FROM imports WHERE shipment_date >= '2021-03-01' AND shipment_date < '2021-04-01' GROUP BY country HAVING SUM(cargo_weight) > 20000;
Update the "production_data" table to set the "productivity_score" to 88 for all records where the "mine_name" is 'Iron Ore Inc.'
CREATE TABLE production_data (record_id INT PRIMARY KEY,mine_name VARCHAR(20),productivity_score INT); INSERT INTO production_data (record_id,mine_name,productivity_score) VALUES (1,'Platinum Plus',88),(2,'Iron Ore Inc.',82),(3,'Golden Nuggets',85),(4,'Iron Ore Inc.',83);
UPDATE production_data SET productivity_score = 88 WHERE mine_name = 'Iron Ore Inc.';
How many sustainable sourcing records are there for 'Pizza Palace'?
CREATE TABLE sustainable_sourcing (restaurant_name VARCHAR(255),sourcing_record VARCHAR(255)); INSERT INTO sustainable_sourcing (restaurant_name,sourcing_record) VALUES ('Pizza Palace','Organic Tomatoes'),('Pizza Palace','Local Cheese'),('Pizza Palace','Fair Trade Pepperoni');
SELECT COUNT(*) FROM sustainable_sourcing WHERE restaurant_name = 'Pizza Palace';
Insert new safety inspection records for vessels with the specified details.
CREATE TABLE SafetyInspections (InspectionID INT,VesselID INT,InspectionDate DATE);
INSERT INTO SafetyInspections (InspectionID, VesselID, InspectionDate) VALUES (3, 1, '2021-06-01'), (4, 4, '2021-07-01');
What is the recycling rate in percentage for each state in the USA in 2019?
CREATE TABLE recycling_rates (state VARCHAR(50),year INT,recycling_rate FLOAT); INSERT INTO recycling_rates (state,year,recycling_rate) VALUES ('Alabama',2019,15.2),('Alaska',2019,20.5),('Arizona',2019,25.0),('Arkansas',2019,12.7),('California',2019,50.1);
SELECT state, recycling_rate FROM recycling_rates WHERE year = 2019 AND state IN ('Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California');
Insert records of artworks by underrepresented artists into the 'Artwork' table.
CREATE TABLE Artwork (artwork_id INT,artwork_name VARCHAR(255),artist_id INT); INSERT INTO Artwork (artwork_id,artwork_name,artist_id) VALUES (1,'The Sun Rises',4),(2,'Moon Dance',5);
INSERT INTO Artwork (artwork_id, artwork_name, artist_id) VALUES (3, ' Ancestral Wisdom', 6), (4, 'Resilience', 7);
What is the total number of records for each data type across all departments?
CREATE TABLE data_types_summary (dept_name TEXT,column_name TEXT,data_type TEXT,record_count INTEGER); INSERT INTO data_types_summary (dept_name,column_name,data_type,record_count) VALUES ('Human Services Department','age','INTEGER',60),('Human Services Department','gender','TEXT',60),('Human Services Department','income','FLOAT',60),('Education Department','school_name','TEXT',45),('Education Department','student_count','INTEGER',45);
SELECT column_name, data_type, SUM(record_count) FROM data_types_summary GROUP BY column_name, data_type;
What is the total budget for ethical AI initiatives by companies in the non-profit sector?
CREATE TABLE ngo_tech (name TEXT,budget INTEGER); INSERT INTO ngo_tech (name,budget) VALUES ('AIforGood',400000),('EthicsNG',500000),('Tech4Change',600000);
SELECT SUM(budget) FROM ngo_tech WHERE name IN ('AIforGood', 'EthicsNG', 'Tech4Change') AND sector = 'non-profit';
Which cultivators have supplied a dispensary with a strain containing 'Gelato' in its name?
CREATE TABLE cultivators (id INT,name TEXT,state TEXT); CREATE TABLE strains (id INT,name TEXT,cultivator_id INT); CREATE TABLE inventory (id INT,strain_id INT,dispensary_id INT); INSERT INTO cultivators (id,name,state) VALUES (1,'Emerald Family Farms','California'),(2,'Good Chemistry','Colorado'); INSERT INTO strains (id,name,cultivator_id) VALUES (1,'Gelato 33',1),(2,'Gelato Cake',1),(3,'Sunset Sherbet',2); INSERT INTO inventory (id,strain_id,dispensary_id) VALUES (1,1,1),(2,3,1);
SELECT DISTINCT c.name FROM cultivators c JOIN strains s ON c.id = s.cultivator_id JOIN inventory i ON s.id = i.strain_id WHERE i.dispensary_id = 1 AND s.name LIKE '%Gelato%';
Calculate the average daily transaction amount for the past week for customers from Canada
CREATE TABLE transactions (id INT,customer_id INT,transaction_date DATE,amount FLOAT); CREATE TABLE customers (id INT,name VARCHAR(50),country VARCHAR(50)); INSERT INTO transactions (id,customer_id,transaction_date,amount) VALUES (1,1,'2022-02-01',1000.00),(2,2,'2022-02-02',2000.00),(3,1,'2022-02-03',1500.00),(4,2,'2022-02-04',3000.00),(5,1,'2022-02-05',500.00),(6,3,'2022-02-01',100.00),(7,3,'2022-02-03',200.00),(8,4,'2022-02-05',50.00),(9,4,'2022-02-06',75.00); INSERT INTO customers (id,name,country) VALUES (1,'Jacob Smith','Canada'),(2,'Emily Chen','China'),(3,'Carlos Alvarez','Mexico'),(4,'Nina Patel','Canada');
SELECT AVG(amount) FROM transactions t JOIN customers c ON t.customer_id = c.id WHERE t.transaction_date BETWEEN DATE_SUB(CURDATE(), INTERVAL 7 DAY) AND CURDATE() AND c.country = 'Canada';
What is the total number of building permits issued in Texas in Q2 2022 grouped by permit type?
CREATE TABLE Building_Permits_TX (id INT,permit_type VARCHAR(255),state VARCHAR(255),quarter VARCHAR(255)); INSERT INTO Building_Permits_TX (id,permit_type,state,quarter) VALUES (1,'Residential','Texas','Q2 2022'); INSERT INTO Building_Permits_TX (id,permit_type,state,quarter) VALUES (2,'Commercial','Texas','Q2 2022'); INSERT INTO Building_Permits_TX (id,permit_type,state,quarter) VALUES (3,'Residential','Texas','Q2 2022');
SELECT permit_type, COUNT(*) FROM Building_Permits_TX WHERE state = 'Texas' AND quarter = 'Q2 2022' GROUP BY permit_type;
List the total quantity of each fertilizer used in the past month, along with its corresponding unit price and total cost.
CREATE TABLE fertilizer (id INT,name VARCHAR(255),unit_price DECIMAL(10,2)); CREATE TABLE inventory (id INT,fertilizer_id INT,quantity INT,timestamp TIMESTAMP); INSERT INTO fertilizer VALUES (1,'Urea',450),(2,'Ammonium Nitrate',300); INSERT INTO inventory VALUES (1,1,1000,'2022-03-01 10:00:00'),(2,2,800,'2022-03-01 10:00:00');
SELECT f.name, SUM(i.quantity) as total_quantity, f.unit_price, SUM(i.quantity * f.unit_price) as total_cost FROM fertilizer f INNER JOIN inventory i ON f.id = i.fertilizer_id WHERE i.timestamp BETWEEN DATE_SUB(NOW(), INTERVAL 1 MONTH) AND NOW() GROUP BY f.name;
What is the total energy storage capacity (in GWh) in Texas, grouped by technology?
CREATE TABLE EnergyStorage (id INT,state VARCHAR(50),technology VARCHAR(50),capacity FLOAT); INSERT INTO EnergyStorage (id,state,technology,capacity) VALUES (1,'Texas','Batteries',12.3),(2,'Texas','Pumped Hydro',18.7),(3,'California','Batteries',21.5);
SELECT technology, SUM(capacity) FROM EnergyStorage WHERE state = 'Texas' GROUP BY technology;
Calculate the average fuel consumption per hour for the vessel 'Blue Whale' in the 'Tankers' fleet in the past week.
CREATE TABLE Vessels (id INT,name VARCHAR(255)); INSERT INTO Vessels (id,name) VALUES (1,'Blue Whale'); CREATE TABLE FuelConsumption (vessel_id INT,fuel_consumption INT,timestamp TIMESTAMP); INSERT INTO FuelConsumption (vessel_id,fuel_consumption,timestamp) VALUES (1,500,'2022-07-01 10:00:00'),(1,800,'2022-07-01 22:00:00');
SELECT AVG(fuel_consumption / DATEDIFF(HOUR, LAG(timestamp) OVER (PARTITION BY vessel_id ORDER BY timestamp), timestamp)) as avg_fuel_consumption_per_hour FROM FuelConsumption WHERE vessel_id = 1 AND timestamp >= DATEADD(week, -1, GETDATE());
Delete records from field_sensors table where sensor_type is 'moisture' and value is below 20.
CREATE TABLE field_sensors (field_id INT,sensor_type VARCHAR(20),value FLOAT,timestamp TIMESTAMP); INSERT INTO field_sensors (field_id,sensor_type,value,timestamp) VALUES (10,'moisture',18.5,'2023-02-25 10:00:00'),(10,'moisture',22.0,'2023-02-25 11:00:00');
DELETE FROM field_sensors WHERE sensor_type = 'moisture' AND value < 20;
What is the total number of water_aid_amount records for agency_id 4 in the water_aid table?
CREATE TABLE water_aid (id INT PRIMARY KEY,agency_id INT,water_aid_amount INT); INSERT INTO water_aid (id,agency_id,water_aid_amount) VALUES (1,1,100000); INSERT INTO water_aid (id,agency_id,water_aid_amount) VALUES (2,2,200000); INSERT INTO water_aid (id,agency_id,water_aid_amount) VALUES (3,3,300000); INSERT INTO water_aid (id,agency_id,water_aid_amount) VALUES (4,4,400000);
SELECT SUM(water_aid_amount) FROM water_aid WHERE agency_id = 4;
What is the average number of vehicles registered per month in the 'vehicle_registrations' table since 2018?
CREATE TABLE vehicle_registrations (registration_date DATE,is_ev BOOLEAN,PRIMARY KEY (registration_date,is_ev)); INSERT INTO vehicle_registrations (registration_date,is_ev) VALUES ('2018-01-01',true); INSERT INTO vehicle_registrations (registration_date,is_ev) VALUES ('2018-01-05',false);
SELECT AVG(registrations_per_month) FROM (SELECT EXTRACT(MONTH FROM registration_date) AS month, COUNT(*) AS registrations_per_month FROM vehicle_registrations WHERE registration_date >= '2018-01-01' GROUP BY month) subquery;
What is the total risk score of threats detected in the 'Sales' department in Q1 2022?
CREATE TABLE threats (id INT,department VARCHAR(20),risk_score FLOAT,detection_date DATE); INSERT INTO threats (id,department,risk_score,detection_date) VALUES (1,'Sales',15.5,'2022-01-15'); INSERT INTO threats (id,department,risk_score,detection_date) VALUES (2,'Marketing',12.2,'2022-02-07'); INSERT INTO threats (id,department,risk_score,detection_date) VALUES (3,'Sales',18.1,'2022-03-20');
SELECT SUM(risk_score) FROM threats WHERE department = 'Sales' AND detection_date >= '2022-01-01' AND detection_date < '2022-04-01';
What is the minimum distance covered by users in the 'Intermediate' workout group?
CREATE TABLE run_data (id INT,user_id INT,distance FLOAT); INSERT INTO run_data (id,user_id,distance) VALUES (1,17,4.5); INSERT INTO run_data (id,user_id,distance) VALUES (2,18,6.2); CREATE TABLE workout_groups (id INT,user_id INT,group_label VARCHAR(10)); INSERT INTO workout_groups (id,user_id,group_label) VALUES (1,17,'Intermediate'); INSERT INTO workout_groups (id,user_id,group_label) VALUES (2,18,'Advanced');
SELECT MIN(distance) FROM run_data JOIN workout_groups ON run_data.user_id = workout_groups.user_id WHERE group_label = 'Intermediate';
What is the name, type, and cost of the equipment with a cost greater than the average cost plus one standard deviation of all equipment?
CREATE TABLE equipment (id INT,name VARCHAR(50),type VARCHAR(50),cost DECIMAL(5,2)); INSERT INTO equipment (id,name,type,cost) VALUES (1,'Equipment1','Sequencer',50000.00); INSERT INTO equipment (id,name,type,cost) VALUES (2,'Equipment2','Microscope',20000.00);
SELECT name, type, cost FROM equipment WHERE cost > (SELECT AVG(cost) FROM equipment) + (SELECT STDDEV(cost) FROM equipment);
How many socially responsible lending applications were rejected in Q2 2021?
CREATE TABLE lending_applications (id INT,application_date DATE,approved BOOLEAN); INSERT INTO lending_applications (id,application_date,approved) VALUES (1,'2021-04-02',FALSE),(2,'2021-05-15',TRUE),(3,'2021-06-01',FALSE);
SELECT COUNT(*) as num_rejected FROM lending_applications WHERE approved = FALSE AND application_date >= '2021-04-01' AND application_date < '2021-07-01';
What are the mines with labor turnover rates higher than 0.08?
CREATE TABLE labor_force (mine_name VARCHAR(255),employee_count INT,turnover_rate FLOAT); INSERT INTO labor_force (mine_name,employee_count,turnover_rate) VALUES ('Green Valley',250,0.09); INSERT INTO labor_force (mine_name,employee_count,turnover_rate) VALUES ('Blue Hills',300,0.07);
SELECT mine_name FROM labor_force WHERE turnover_rate > 0.08;
What is the number of vessels inspected in the Caribbean sea?
CREATE TABLE vessels (name VARCHAR(255),type VARCHAR(255),flag_state VARCHAR(255)); CREATE TABLE inspections (inspection_id INT,vessel_name VARCHAR(255),inspection_date DATE,region VARCHAR(255)); CREATE TABLE caribbean_sea (name VARCHAR(255),region_type VARCHAR(255)); INSERT INTO vessels (name,type,flag_state) VALUES ('VESSEL1','Cargo','Italy'),('VESSEL2','Passenger','Spain'); INSERT INTO inspections (inspection_id,vessel_name,inspection_date,region) VALUES (1,'VESSEL1','2022-01-01','Caribbean Sea'),(2,'VESSEL3','2022-02-01','Caribbean Sea'); INSERT INTO caribbean_sea (name,region_type) VALUES ('VESSEL1','Caribbean Sea');
SELECT COUNT(*) FROM inspections i INNER JOIN caribbean_sea cs ON i.region = cs.region;
What is the earliest launched spacecraft in the database?
CREATE TABLE spacecraft_launch_dates (spacecraft_name TEXT,launch_date DATE); INSERT INTO spacecraft_launch_dates (spacecraft_name,launch_date) VALUES ('Voyager 1','1977-09-05'),('Voyager 2','1977-08-20'),('Cassini','1997-10-15');
SELECT spacecraft_name, MIN(launch_date) as earliest_launch_date FROM spacecraft_launch_dates;
How many smart contracts were deployed in each month of 2022?
CREATE TABLE smart_contracts (contract_address VARCHAR(42),deployment_date DATE); INSERT INTO smart_contracts (contract_address,deployment_date) VALUES ('0x123','2022-01-01'),('0x456','2022-01-15'),('0x789','2022-02-01'),('0xabc','2022-02-15'),('0xdef','2022-03-01');
SELECT EXTRACT(MONTH FROM deployment_date) AS month, COUNT(*) FROM smart_contracts GROUP BY month ORDER BY month;
What is the average age of artists who have created artworks in the 'painting' category?
CREATE TABLE artists (id INT,name TEXT,birthdate DATE); INSERT INTO artists (id,name,birthdate) VALUES (1,'Sarah Johnson','1900-01-01'),(2,'Maria Rodriguez','1980-05-05'),(3,'Yumi Lee','1968-11-11');
SELECT AVG(YEAR(CURRENT_DATE) - YEAR(birthdate)) as avg_age FROM artists JOIN artworks ON artists.id = artworks.artist WHERE category = 'painting';
List all satellites launched in the year 2014
CREATE TABLE satellite_deployment (id INT PRIMARY KEY,name VARCHAR(255),country VARCHAR(255),launch_date DATE); INSERT INTO satellite_deployment (id,name,country,launch_date) VALUES (1,'Sentinel-1A','Europe','2014-04-03'),(2,'TechSat','United States','2022-09-01');
SELECT name FROM satellite_deployment WHERE YEAR(launch_date) = 2014;
What is the most recent funding date for each biotech startup?
CREATE SCHEMA if not exists fundings;CREATE TABLE if not exists fundings.dates (id INT,startup_id INT,funding_date DATE); INSERT INTO fundings.dates (id,startup_id,funding_date) VALUES (1,1,'2021-06-01'),(2,2,'2022-02-14'),(3,1,'2021-12-15'),(4,3,'2022-08-05');
SELECT d.startup_id, MAX(d.funding_date) max_funding_date FROM fundings.dates d GROUP BY d.startup_id;
Calculate the total CO2 emissions reduction achieved by renewable energy projects since 2010
CREATE TABLE co2_emissions_reduction (project_id INT,project_name VARCHAR(255),co2_reduction FLOAT,reduction_year INT);
SELECT SUM(co2_reduction) FROM co2_emissions_reduction WHERE reduction_year >= 2010;
What is the total number of employee hours worked in each department in the last month?
CREATE TABLE employee_hours (employee_id INT,department VARCHAR(20),hours_worked INT,work_date DATE); INSERT INTO employee_hours (employee_id,department,hours_worked,work_date) VALUES (1,'mining',8,'2021-01-15'),(2,'geology',7,'2021-01-20'),(3,'engineering',9,'2021-03-01'),(4,'administration',6,'2020-12-14'),(5,'mining',10,'2021-02-15'),(6,'geology',8,'2021-02-20');
SELECT department, SUM(hours_worked) FROM employee_hours WHERE work_date BETWEEN DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH) AND CURRENT_DATE GROUP BY department
What is the total funding received by biotech startups located in Europe?
CREATE TABLE startups (id INT,name VARCHAR(50),location VARCHAR(50),funding FLOAT); INSERT INTO startups (id,name,location,funding) VALUES (1,'Genomic Solutions','USA',5000000),(2,'BioTech Innovations','Europe',7000000);
SELECT SUM(funding) FROM startups WHERE location = 'Europe';
What is the average donation amount by donor type?
CREATE SCHEMA if not exists arts_culture;CREATE TABLE if not exists arts_culture.donors (donor_id INT PRIMARY KEY,name VARCHAR(255),type VARCHAR(255),donation DECIMAL(10,2));INSERT INTO arts_culture.donors (donor_id,name,type,donation) VALUES (1,'John Doe','Individual',50.00),(2,'Jane Smith','Individual',100.00),(3,'Google Inc.','Corporation',5000.00);
SELECT type, AVG(donation) as avg_donation FROM arts_culture.donors GROUP BY type;
Delete all records from 'OrganicProducts' view
CREATE VIEW OrganicProducts AS SELECT * FROM Products WHERE is_organic = TRUE; INSERT INTO Products (id,name,is_organic) VALUES (1,'Product1',TRUE),(2,'Product2',FALSE),(3,'Product3',TRUE);
DELETE FROM OrganicProducts;
What is the average mass of spacecraft manufactured by 'Galactic Inc.'?
CREATE TABLE spacecraft(id INT,name VARCHAR(50),manufacturer VARCHAR(50),mass FLOAT); INSERT INTO spacecraft VALUES(1,'Voyager 1','Galactic Inc.',770.),(2,'Voyager 2','Galactic Inc.',778.);
SELECT AVG(mass) FROM spacecraft WHERE manufacturer = 'Galactic Inc.'
What is the energy efficiency of the top 5 countries in Europe?
CREATE TABLE energy_efficiency (id INT,country VARCHAR(255),efficiency FLOAT); INSERT INTO energy_efficiency (id,country,efficiency) VALUES (1,'Germany',0.35),(2,'France',0.32),(3,'United Kingdom',0.31),(4,'Italy',0.29),(5,'Spain',0.28);
SELECT country, efficiency FROM energy_efficiency ORDER BY efficiency DESC LIMIT 5;
What is the most recent flight for each aircraft model in the FlightLogs table?
CREATE TABLE FlightLogs (flight_id INT,aircraft_model VARCHAR(50),flight_date DATE); INSERT INTO FlightLogs (flight_id,aircraft_model,flight_date) VALUES (1,'B747','2022-01-01'),(2,'A320','2021-05-01'),(3,'B747','2022-03-01');
SELECT aircraft_model, MAX(flight_date) AS most_recent_flight FROM FlightLogs GROUP BY aircraft_model;
What is the total number of mental health parity violations by provider?
CREATE TABLE MentalHealthParityViolations (ViolationID INT,ProviderID INT); INSERT INTO MentalHealthParityViolations (ViolationID,ProviderID) VALUES (1,1),(2,1),(3,2),(4,3),(5,1);
SELECT ProviderID, COUNT(*) FROM MentalHealthParityViolations GROUP BY ProviderID;
Identify the 5-year return on investment (ROI) for gender lens investing funds.
CREATE TABLE fund (id INT,name VARCHAR(50),strategy VARCHAR(20),roi DECIMAL(5,2),year INT); INSERT INTO fund (id,name,strategy,roi,year) VALUES (1,'Gender Equality Fund','gender lens investing',12.5,2017); INSERT INTO fund (id,name,strategy,roi,year) VALUES (2,'Sustainable Impact Fund','gender lens investing',8.2,2018);
SELECT roi FROM fund WHERE strategy = 'gender lens investing' AND year BETWEEN 2016 AND 2020;
What is the number of visitors who have attended more than three events in the last year?
ALTER TABLE Visitors ADD COLUMN last_event_date DATE,event_count INT;
SELECT COUNT(*) FROM Visitors WHERE last_event_date >= DATEADD(year, -1, CURRENT_DATE) GROUP BY Visitors.id HAVING COUNT(*) > 3;
Update the price of all vegetarian dishes by 10% in the Texas region.
CREATE TABLE Menu (menu_id INT PRIMARY KEY,menu_item VARCHAR(255),category VARCHAR(255),price DECIMAL(5,2),region VARCHAR(255));
UPDATE Menu SET price = price * 1.10 WHERE category = 'Vegetarian' AND region = 'Texas';