instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
Who are the donors that have donated the same amount as or more than the average donation amount for recipients?
CREATE TABLE Donors (Id INT,Name VARCHAR(50),Age INT,Amount DECIMAL(10,2)); INSERT INTO Donors (Id,Name,Age,Amount) VALUES (1,'Ella Davis',45,1200.00),(2,'Avery Thompson',50,1500.00),(3,'Scarlett White',55,1800.00); CREATE TABLE Recipients (Id INT,Name VARCHAR(50),Age INT,Amount DECIMAL(10,2)); INSERT INTO Recipients (Id,Name,Age,Amount) VALUES (1,'Mental Health Support',60,1000.00),(2,'Disaster Relief',65,1300.00),(3,'Climate Change Action',70,1600.00);
SELECT Name FROM Donors WHERE Amount >= (SELECT AVG(Amount) FROM Recipients);
What is the average energy consumption for buildings owned by 'GreenCorp' and 'EcoInnovations'?
CREATE TABLE GreenBuildings (id INT,name TEXT,owner TEXT,energy_consumption FLOAT); INSERT INTO GreenBuildings (id,name,owner,energy_consumption) VALUES (1,'EcoTower','ACME Inc',1500.0),(2,'GreenSpire','GreenCorp',1200.0),(3,'GreenVista','ACME Inc',1300.0),(4,'GreenPlaza','EcoInnovations',1000.0);
SELECT AVG(energy_consumption) FROM GreenBuildings WHERE owner IN ('GreenCorp', 'EcoInnovations');
Find the user with the highest financial wellbeing score in the FinancialWellbeing table.
CREATE TABLE FinancialWellbeing (userID VARCHAR(20),wellbeingScore INT); INSERT INTO FinancialWellbeing (userID,wellbeingScore) VALUES ('Ahmed',6),('Sara',8),('Mohammed',7);
SELECT userID, MAX(wellbeingScore) FROM FinancialWellbeing;
Delete the record for donor_id 2001
CREATE TABLE donors (donor_id INT PRIMARY KEY,first_name VARCHAR(50),last_name VARCHAR(50),email VARCHAR(100),donation_amount DECIMAL(10,2),donation_date DATE);
DELETE FROM donors WHERE donor_id = 2001;
What are the most common types of artwork?
CREATE TABLE ArtTypes (TypeID int,Name varchar(50)); CREATE TABLE ArtPieces (ArtPieceID int,Title varchar(50),YearCreated int,TypeID int);
SELECT ArtTypes.Name, COUNT(ArtPieces.ArtPieceID) AS ArtPiecesCount FROM ArtTypes INNER JOIN ArtPieces ON ArtTypes.TypeID = ArtPieces.TypeID GROUP BY ArtTypes.Name ORDER BY ArtPiecesCount DESC;
What is the average citizen satisfaction score for 2021, by service category?
CREATE TABLE Satisfaction (Year INT,Category TEXT,Score INT); INSERT INTO Satisfaction (Year,Category,Score) VALUES (2021,'Healthcare',8),(2021,'Education',7),(2021,'Transportation',6);
SELECT Category, AVG(Score) FROM Satisfaction WHERE Year = 2021 GROUP BY Category;
How many pregnant women in the state of California have received adequate prenatal care?
CREATE TABLE prenatal_care (patient_id INT,state TEXT,pregnant INT,adequate_care INT); INSERT INTO prenatal_care (patient_id,state,pregnant,adequate_care) VALUES (1,'California',1,1);
SELECT COUNT(*) FROM prenatal_care WHERE state = 'California' AND pregnant = 1 AND adequate_care = 1;
What is the average time between bus stops for each route?
CREATE TABLE bus_stops (stop_id INT,route_id INT,stop_sequence INT,stop_time TIME); INSERT INTO bus_stops (stop_id,route_id,stop_sequence,stop_time) VALUES (1,1,1,'00:05:00'),(2,1,2,'00:10:00'),(3,1,3,'00:15:00'),(4,2,1,'00:03:00'),(5,2,2,'00:08:00'),(6,2,3,'00:13:00');
SELECT route_id, AVG(TIMESTAMPDIFF(SECOND, LAG(stop_time) OVER (PARTITION BY route_id ORDER BY stop_sequence), stop_time)) AS avg_time_between_stops FROM bus_stops GROUP BY route_id;
What is the prevalence of heart disease in each age group, and what is the total population in each age group?
CREATE TABLE patients (id INT,name TEXT,age INT,has_heart_disease BOOLEAN); INSERT INTO patients (id,name,age,has_heart_disease) VALUES (1,'John Doe',65,true),(2,'Jane Smith',45,false),(3,'Bob Johnson',35,false);
SELECT FLOOR(patients.age / 10) * 10 AS age_group, COUNT(patients.id), SUM(CASE WHEN patients.has_heart_disease = true THEN 1 ELSE 0 END) FROM patients GROUP BY age_group;
What are the names and wheelchair accessibility statuses of properties in the city of Denver that have not been sold in the past year?
CREATE TABLE properties (property_id INT,name VARCHAR(255),city VARCHAR(255),wheelchair_accessible BOOLEAN,sold_date DATE); INSERT INTO properties (property_id,name,city,wheelchair_accessible,sold_date) VALUES (1,'The Accessible Abode','Denver',true,'2020-01-01'),(2,'The Pet-friendly Pad','Denver',false,'2022-01-01'),(3,'The Wheelchair Wonders','Denver',true,NULL);
SELECT name, wheelchair_accessible FROM properties WHERE city = 'Denver' AND sold_date IS NULL OR sold_date < DATEADD(year, -1, GETDATE());
How many security incidents occurred in each region, in the last year?
CREATE TABLE security_incidents (id INT,timestamp TIMESTAMP,region VARCHAR(255),incident_type VARCHAR(255)); INSERT INTO security_incidents (id,timestamp,region,incident_type) VALUES (1,'2021-01-01 10:00:00','North America','malware'),(2,'2021-01-02 12:30:00','Europe','phishing'),(3,'2021-01-03 08:15:00','Asia','ddos');
SELECT region, COUNT(*) as incident_count FROM security_incidents WHERE timestamp >= DATE_SUB(CURRENT_TIMESTAMP(), INTERVAL 1 YEAR) GROUP BY region;
How many criminal cases were open in the state of California on January 1, 2020 that were resolved by a judge who is a member of a racial or ethnic minority?
CREATE TABLE cases (case_id INT,judge_race VARCHAR(20),state VARCHAR(20),open_date DATE); INSERT INTO cases (case_id,judge_race,state,open_date) VALUES (1,'White','California','2019-01-01'),(2,'Black','California','2020-01-01'),(3,'Asian','California','2019-01-01');
SELECT COUNT(*) FROM cases WHERE state = 'California' AND open_date < '2020-01-01' AND judge_race NOT IN ('White', 'Hispanic');
What are the names of all countries that have manufactured aircraft?
CREATE TABLE AircraftModels (model_id INT,name VARCHAR(50),manufacturer VARCHAR(50),country VARCHAR(50)); INSERT INTO AircraftModels (model_id,name,manufacturer,country) VALUES (1,'Air1','AvionicCorp','USA'),(2,'Air2','AeroCanada','Canada'),(3,'Air3','EuroJet','France'),(4,'Air4','AvionicCorp','Mexico');
SELECT DISTINCT country FROM AircraftModels;
How many schools have been built per region in 2020 and 2021?
CREATE TABLE schools_region (id INT PRIMARY KEY,school_name TEXT,school_type TEXT,region TEXT,built_date DATE); INSERT INTO schools_region (id,school_name,school_type,region,built_date) VALUES (1,'Primary School','Public','Asia','2020-01-01');
SELECT region, COUNT(*) as schools_built FROM schools_region WHERE built_date >= '2020-01-01' AND built_date < '2022-01-01' GROUP BY region;
Create a table for innovation trends
CREATE TABLE innovation_trends (trend_id INT,trend_name VARCHAR(50),description VARCHAR(200));
CREATE TABLE innovation_trends (trend_id INT, trend_name VARCHAR(50), description VARCHAR(200));
Find the first treatment date for each patient who started therapy in '2023'
CREATE TABLE patient_info_2023 (patient_id INT,first_treatment_date DATE); INSERT INTO patient_info_2023 (patient_id,first_treatment_date) VALUES (5,'2023-02-03'),(6,'2023-01-15'),(7,'2023-06-28'),(8,NULL); CREATE TABLE therapy_sessions_2023 (patient_id INT,session_date DATE); INSERT INTO therapy_sessions_2023 (patient_id,session_date) VALUES (5,'2023-02-03'),(7,'2023-06-28'),(7,'2023-06-30');
SELECT patient_id, MIN(session_date) AS first_treatment_date FROM therapy_sessions_2023 WHERE patient_id IN (SELECT patient_id FROM patient_info_2023 WHERE first_treatment_date IS NULL OR first_treatment_date = '2023-01-01') GROUP BY patient_id;
What is the minimum ticket price for Latin music concerts?
CREATE TABLE ConcertTickets (ticket_id INT,genre VARCHAR(20),price DECIMAL(5,2));
SELECT MIN(price) FROM ConcertTickets WHERE genre = 'Latin';
What is the total cost of construction materials in the West, partitioned by month?
CREATE TABLE West_Materials (location VARCHAR(20),material VARCHAR(30),cost FLOAT,order_date DATE); INSERT INTO West_Materials VALUES ('CA','Concrete',1200,'2022-01-05'),('WA','Cement',900,'2022-02-10'),('OR','Insulation',700,'2022-03-15');
SELECT location, material, SUM(cost) OVER (PARTITION BY EXTRACT(MONTH FROM order_date)) as total_cost FROM West_Materials;
What are the names and positions of intelligence agents who work for the external_intelligence agency, listed in the intelligence_agents table?
CREATE TABLE intelligence_agents (id INT,name VARCHAR(50),position VARCHAR(50),agency VARCHAR(50));
SELECT name, position FROM intelligence_agents WHERE agency = 'external_intelligence';
What is the average CO2 emission of green buildings in Europe?
CREATE TABLE Green_Buildings (id INT,region VARCHAR(20),CO2_emission FLOAT); INSERT INTO Green_Buildings (id,region,CO2_emission) VALUES (1,'Europe',45.2),(2,'Asia',56.3),(3,'Africa',33.9);
SELECT AVG(CO2_emission) FROM Green_Buildings WHERE region = 'Europe';
What is the total depth of all marine species in the Indian basin, grouped by species name?
CREATE TABLE marine_species_total_depths (name VARCHAR(255),basin VARCHAR(255),depth FLOAT); INSERT INTO marine_species_total_depths (name,basin,depth) VALUES ('Species1','Atlantic',123.45),('Species2','Pacific',567.89),('Species3','Indian',345.67),('Species4','Atlantic',789.10);
SELECT name, SUM(depth) as total_depth FROM marine_species_total_depths WHERE basin = 'Indian' GROUP BY name;
List all records from the "vessel_performance" table.
CREATE TABLE vessel_performance (id INT PRIMARY KEY,vessel_id INT,max_speed FLOAT,avg_speed FLOAT,fuel_efficiency FLOAT);
SELECT * FROM vessel_performance;
What is the species name and corresponding management location for all species with a population over 700?
CREATE TABLE Species (id INT PRIMARY KEY,name VARCHAR(255),population INT); CREATE TABLE ResourceManagement (id INT PRIMARY KEY,location VARCHAR(255),manager VARCHAR(255));
SELECT Species.name, ResourceManagement.location FROM Species INNER JOIN ResourceManagement ON 1=1 WHERE Species.population > 700;
What is the name of the supplier with a sustainability score greater than 85?
CREATE TABLE suppliers (id INT PRIMARY KEY,name VARCHAR(255),location VARCHAR(255),sustainability_score INT); INSERT INTO suppliers (id,name,location,sustainability_score) VALUES (1,'Supplier X','Paris',86);
SELECT name FROM suppliers WHERE sustainability_score > 85;
Who is the top ethical labor practice certifier in the United States?
CREATE TABLE certifications (id INT,certifier_name VARCHAR(50),country VARCHAR(50),total_certified INT); INSERT INTO certifications (id,certifier_name,country,total_certified) VALUES (1,'Fair Trade USA','USA',3000),(2,'Ethical Trade','UK',2500),(3,'Business Social Compliance Initiative','Germany',2000);
SELECT certifier_name, total_certified FROM certifications WHERE country = 'USA' AND total_certified = (SELECT MAX(total_certified) FROM certifications WHERE country = 'USA');
What is the maximum delivery time for orders shipped to Australia?
CREATE TABLE orders (id INT,delivery_time INT,country VARCHAR(50)); INSERT INTO orders (id,delivery_time,country) VALUES (1,5,'Australia'),(2,3,'Canada'),(3,7,'Australia');
SELECT MAX(delivery_time) FROM orders WHERE country = 'Australia';
What is the average coal production per machine in Queensland, Australia, that has produced more than 5000 tons in a year?
CREATE TABLE mine_equipment (id INT,state VARCHAR(50),machine_type VARCHAR(50),production INT); INSERT INTO mine_equipment (id,state,machine_type,production) VALUES (1,'Queensland','Coal Machine',5500); INSERT INTO mine_equipment (id,state,machine_type,production) VALUES (2,'Queensland','Coal Machine',6000);
SELECT AVG(production) FROM mine_equipment WHERE state = 'Queensland' AND production > 5000;
What is the trend of explainability scores for AI algorithms in the explainable AI dataset over time?
CREATE TABLE explainable_ai (id INT,timestamp TIMESTAMP,algorithm VARCHAR,explainability FLOAT);
SELECT algorithm, timestamp, AVG(explainability) OVER (PARTITION BY algorithm ORDER BY timestamp RANGE BETWEEN INTERVAL '1 day' PRECEDING AND CURRENT ROW) FROM explainable_ai;
What is the average property price in each neighborhood for co-owned properties?
CREATE TABLE neighborhoods (neighborhood_id INT,name VARCHAR(255));CREATE TABLE properties (property_id INT,neighborhood_id INT,price INT,coowners INT); INSERT INTO neighborhoods (neighborhood_id,name) VALUES (1,'Central Park'),(2,'SoHo'); INSERT INTO properties (property_id,neighborhood_id,price,coowners) VALUES (1,1,500000,2),(2,1,600000,1),(3,2,800000,4);
SELECT neighborhoods.name, AVG(properties.price) as avg_price FROM properties JOIN neighborhoods ON properties.neighborhood_id = neighborhoods.neighborhood_id WHERE properties.coowners > 1 GROUP BY neighborhoods.name;
What is the most expensive vegetarian menu item in the Central region?
CREATE TABLE menu (menu_id INT,menu_name TEXT,menu_type TEXT,price DECIMAL,daily_sales INT,region TEXT); CREATE VIEW vegetarian_menu AS SELECT * FROM menu WHERE menu_type = 'vegetarian';
SELECT menu_name, MAX(price) FROM vegetarian_menu WHERE region = 'Central';
What is the maximum number of wins for a player in "Shooter Game 2022"?
CREATE TABLE Matches (MatchID INT,PlayerID INT,Game VARCHAR(50),Wins INT); INSERT INTO Matches (MatchID,PlayerID,Game,Wins) VALUES (1,1,'Shooter Game 2022',45),(2,1,'Shooter Game 2022',52),(3,2,'Shooter Game 2022',60),(4,3,'Racing Simulator 2022',30);
SELECT MAX(Wins) FROM Matches WHERE Game = 'Shooter Game 2022';
What is the average retail price of all drugs in Spain?
CREATE TABLE drugs (drug_id INT,drug_name TEXT,manufacturer TEXT,retail_price DECIMAL); INSERT INTO drugs (drug_id,drug_name,manufacturer,retail_price) VALUES (1,'DrugA','ManuA',100.00),(2,'DrugB','ManuB',150.00);
SELECT AVG(retail_price) FROM drugs WHERE manufacturer = 'ManuA' AND country = 'Spain';
What was the average retail sales revenue per 'Pant' item in Japan in 2021?
CREATE TABLE RetailSales (id INT,garment_type VARCHAR(20),country VARCHAR(20),revenue DECIMAL(10,2),year INT); INSERT INTO RetailSales (id,garment_type,country,revenue,year) VALUES (1,'Dress','Japan',75.50,2021),(2,'Shirt','Japan',120.00,2021),(3,'Pant','Japan',100.00,2021),(4,'Jacket','Japan',150.00,2021),(5,'Shirt','Japan',50.00,2021),(6,'Dress','Japan',60.00,2021);
SELECT AVG(revenue) as avg_revenue_per_item FROM RetailSales WHERE garment_type = 'Pant' AND country = 'Japan' AND year = 2021;
How many fish were removed from the Tilapia farm each month in 2021?
CREATE TABLE FarmStock (farm_id INT,date DATE,action VARCHAR(10),quantity INT); INSERT INTO FarmStock (farm_id,date,action,quantity) VALUES (1,'2021-01-01','added',300),(1,'2021-01-05','removed',50);
SELECT EXTRACT(MONTH FROM date) month, SUM(quantity) quantity FROM FarmStock WHERE farm_id = 1 AND YEAR(date) = 2021 AND action = 'removed' GROUP BY month;
How many shows were released in each country, and what is the total runtime for each country?
CREATE TABLE shows (id INT,title VARCHAR(100),genre VARCHAR(50),country VARCHAR(50),release_year INT,runtime INT);
SELECT country, COUNT(*), SUM(runtime) FROM shows GROUP BY country;
What is the distribution of player levels in "EpicQuest" for players from different countries, grouped by region?
CREATE TABLE epicquest_players_by_country (player_id INT,level INT,region VARCHAR(20),country VARCHAR(20)); INSERT INTO epicquest_players_by_country (player_id,level,region,country) VALUES (1,25,'North America','USA'),(2,30,'Europe','Germany'),(3,22,'Asia','Japan'),(4,35,'North America','Canada'),(5,18,'Europe','France'),(6,28,'Asia','South Korea');
SELECT region, AVG(level) AS avg_level, MIN(level) AS min_level, MAX(level) AS max_level FROM epicquest_players_by_country GROUP BY region;
What is the date of the next art exhibition in New York?
CREATE TABLE Exhibitions (name VARCHAR(255),city VARCHAR(255),date DATE); INSERT INTO Exhibitions (name,city,date) VALUES ('Modern Art','New York','2023-03-01'),('Contemporary Art','Los Angeles','2023-04-01'),('Classic Art','New York','2023-03-15'),('Impressionism','Paris','2023-05-01');
SELECT MIN(date) FROM Exhibitions WHERE date > CURDATE() AND city = 'New York';
Insert a new donor 'Ali Ahmed' from 'Pakistan' into the 'donor_demographics' table.
CREATE TABLE donor_demographics (donor_id INTEGER,donor_name TEXT,age INTEGER,location TEXT); INSERT INTO donor_demographics (donor_id,donor_name,age,location) VALUES (1,'John Smith',35,'New York'),(2,'Jane Doe',28,'San Francisco');
INSERT INTO donor_demographics (donor_id, donor_name, age, location) VALUES (3, 'Ali Ahmed', 45, 'Pakistan');
What is the total number of workers in unions advocating for labor rights in California and Texas?
CREATE TABLE unions (id INT,state VARCHAR(2),workers INT); INSERT INTO unions (id,state,workers) VALUES (1,'CA',5000),(2,'TX',7000);
SELECT SUM(workers) FROM unions WHERE state IN ('CA', 'TX') AND issue = 'labor_rights';
Calculate the average impurity level for each REO type in 2023 from the reo_production table
CREATE TABLE reo_production (id INT PRIMARY KEY,reo_type VARCHAR(50),impurity_level FLOAT,production_year INT);
SELECT reo_type, AVG(impurity_level) FROM reo_production WHERE production_year = 2023 GROUP BY reo_type;
What is the most recent temperature reading for each sensor in the 'sensor_data' table?
CREATE TABLE sensor_data (sensor_id INT,temperature FLOAT,reading_time TIMESTAMP); INSERT INTO sensor_data (sensor_id,temperature,reading_time) VALUES (1,23.5,'2022-01-01 10:00:00'),(2,25.3,'2022-01-01 10:00:00');
SELECT sensor_id, temperature, reading_time FROM (SELECT sensor_id, temperature, reading_time, ROW_NUMBER() OVER (PARTITION BY sensor_id ORDER BY reading_time DESC) rn FROM sensor_data) t WHERE rn = 1;
Add new record to military_equipment table, including 'M1 Abrams' as equipment_name, 'USA' as origin, 'Tank' as type
CREATE TABLE military_equipment (id INT PRIMARY KEY,equipment_name VARCHAR(100),origin VARCHAR(50),type VARCHAR(50));
INSERT INTO military_equipment (equipment_name, origin, type) VALUES ('M1 Abrams', 'USA', 'Tank');
Show the genetic research studies and their methods from the 'genetic_research' table where the study is related to 'genetic mutations' or 'DNA sequencing' ordered by the study name in descending order.
CREATE TABLE genetic_research (id INT,study_name VARCHAR(50),method VARCHAR(50),data TEXT); INSERT INTO genetic_research (id,study_name,method,data) VALUES (1,'Mutation Study 1','Genetic mutation analysis','ACTG...'); INSERT INTO genetic_research (id,study_name,method,data) VALUES (2,'Sequencing Study 2','RNA sequencing','AGU...');
SELECT study_name, method FROM genetic_research WHERE method LIKE '%genetic mutation%' OR method LIKE '%DNA sequencing%' ORDER BY study_name DESC;
How many albums were sold by female R&B artists between 2000 and 2009?
CREATE TABLE artists (artist_id INT,artist_name VARCHAR(255),genre VARCHAR(255),gender VARCHAR(10)); CREATE TABLE albums (album_id INT,album_name VARCHAR(255),release_year INT,artist_id INT,sales INT); INSERT INTO artists (artist_id,artist_name,genre,gender) VALUES (1,'Beyoncé','R&B','Female'); INSERT INTO albums (album_id,album_name,release_year,artist_id,sales) VALUES (1,'Dangerously in Love',2003,1,5000000);
SELECT SUM(albums.sales) FROM albums JOIN artists ON albums.artist_id = artists.artist_id WHERE artists.genre = 'R&B' AND artists.gender = 'Female' AND albums.release_year BETWEEN 2000 AND 2009;
Who are the top 5 actors with the highest number of movies produced in the African film industry?
CREATE TABLE movies (id INT,title VARCHAR(255),production_country VARCHAR(50),actor_name VARCHAR(255)); INSERT INTO movies (id,title,production_country,actor_name) VALUES (1,'MovieE','Nigeria','ActorX'),(2,'MovieF','South Africa','ActorY'),(3,'MovieG','Egypt','ActorZ'),(4,'MovieH','Nigeria','ActorX'),(5,'MovieI','Kenya','ActorW');
SELECT actor_name, COUNT(*) as movie_count FROM movies WHERE production_country IN ('Nigeria', 'South Africa', 'Egypt', 'Kenya') GROUP BY actor_name ORDER BY movie_count DESC LIMIT 5;
What is the average expenditure per visitor for countries that have implemented carbon neutrality practices?
CREATE TABLE carbon_neutral_countries (id INT,country VARCHAR(50),start_date DATE,end_date DATE); INSERT INTO carbon_neutral_countries (id,country,start_date,end_date) VALUES (1,'Costa Rica','2019-01-01','2025-12-31');
SELECT AVG(t2.total_expenditure/t2.international_visitors) as avg_expenditure, cnc.country FROM carbon_neutral_countries cnc JOIN tourism_spending t2 ON cnc.country = t2.country GROUP BY cnc.country;
What are the building permits for the city of Denver in the month of July 2020?
CREATE TABLE building_permits (permit_id INT,permit_date DATE,city TEXT,state TEXT); INSERT INTO building_permits VALUES (1,'2020-01-01','Chicago','Illinois'),(2,'2019-12-15','New York','New York'),(3,'2020-06-20','Houston','Texas'),(4,'2021-02-03','Chicago','Illinois'),(5,'2020-07-10','Denver','Colorado'),(6,'2020-07-25','Denver','Colorado');
SELECT permit_id, permit_date, city, state FROM building_permits WHERE city = 'Denver' AND EXTRACT(MONTH FROM permit_date) = 7 AND EXTRACT(YEAR FROM permit_date) = 2020;
Show veteran employment statistics for the last 3 months, grouped by month
CREATE TABLE veteran_employment (id INT,veteran_status VARCHAR(50),employment_date DATE);
SELECT MONTH(employment_date) AS month, COUNT(*) AS total FROM veteran_employment WHERE employment_date >= DATE_SUB(NOW(), INTERVAL 3 MONTH) GROUP BY month;
What was the total construction cost for infrastructure projects in New York from 2017 to 2019, broken down by project type?
CREATE TABLE InfrastructureCostsNY (State TEXT,Year INTEGER,ProjectType TEXT,ConstructionCost REAL); INSERT INTO InfrastructureCostsNY (State,Year,ProjectType,ConstructionCost) VALUES ('New York',2017,'Bridge',1750000.0),('New York',2017,'Highway',2350000.0),('New York',2017,'Tunnel',3250000.0),('New York',2018,'Bridge',1850000.0),('New York',2018,'Highway',2450000.0),('New York',2018,'Tunnel',3350000.0),('New York',2019,'Bridge',1700000.0),('New York',2019,'Highway',2300000.0),('New York',2019,'Tunnel',3200000.0);
SELECT Year, ProjectType, SUM(ConstructionCost) as TotalCost FROM InfrastructureCostsNY WHERE State = 'New York' GROUP BY Year, ProjectType;
Which country has the highest production volume?
CREATE TABLE production_countries (country_id INT PRIMARY KEY,country_name TEXT,production_volume INT,production_sustainability_score INT); INSERT INTO production_countries (country_id,country_name,production_volume,production_sustainability_score) VALUES (1,'China',1000,50),(2,'Bangladesh',800,40),(3,'India',900,55);
SELECT country_name, production_volume FROM production_countries ORDER BY production_volume DESC LIMIT 1;
Insert new records for visitor demographics
CREATE TABLE VisitorDemographics (visitor_id INT,age INT,gender VARCHAR(50),country VARCHAR(100));
INSERT INTO VisitorDemographics (visitor_id, age, gender, country)
Count policyholders by gender and age group
CREATE TABLE policyholders (policyholder_id INT,first_name VARCHAR(20),last_name VARCHAR(20),email VARCHAR(30),date_of_birth DATE,gender ENUM('M','F')); INSERT INTO policyholders (policyholder_id,first_name,last_name,email,date_of_birth,gender) VALUES (1,'John','Doe','johndoe@example.com','1985-05-15','M'),(2,'Jane','Doe','janedoe@example.com','1990-08-08','F'),(3,'Bob','Smith','bobsmith@example.com','1976-11-12','M'),(4,'Alice','Johnson','alicejohnson@example.com','1982-02-23','F');
SELECT FLOOR(DATEDIFF(CURDATE(), date_of_birth)/365) AS age_group, gender, COUNT(*) AS num_policyholders FROM policyholders GROUP BY age_group, gender;
What is the number of articles published by media outlets A and B in each language, and the percentage of articles published in each language?
CREATE TABLE media_outlets (id INT,outlet_name VARCHAR(50),language VARCHAR(50)); INSERT INTO media_outlets (id,outlet_name,language) VALUES (1,'OutletA','English'),(2,'OutletB','Spanish'),(3,'OutletA','French');
SELECT language, COUNT(*) as num_articles, (COUNT(*) * 100.0 / (SELECT COUNT(*) FROM media_outlets) ) as percentage FROM media_outlets WHERE outlet_name IN ('OutletA', 'OutletB') GROUP BY language;
What is the average monthly data usage for postpaid mobile subscribers in the last 12 months, partitioned by region?
CREATE TABLE subscribers (subscriber_id INT,data_usage FLOAT,plan_type VARCHAR(10),region VARCHAR(20)); INSERT INTO subscribers (subscriber_id,data_usage,plan_type,region) VALUES (1,8.5,'postpaid','Northeast'); INSERT INTO subscribers (subscriber_id,data_usage,plan_type,region) VALUES (2,12.3,'postpaid','Southeast');
SELECT region, AVG(data_usage) OVER (PARTITION BY region ORDER BY region ROWS BETWEEN 11 PRECEDING AND CURRENT ROW) as avg_data_usage FROM subscribers WHERE plan_type = 'postpaid' AND subscriber_id IN (SELECT subscriber_id FROM subscribers WHERE plan_type = 'postpaid' ORDER BY subscriber_id DESC LIMIT 12);
List all companies that have not had a series B funding round
CREATE TABLE investment_rounds (company_id INT,round_name TEXT,funding_amount INT); INSERT INTO investment_rounds (company_id,round_name,funding_amount) VALUES (1,'Series A',5000000); INSERT INTO investment_rounds (company_id,round_name,funding_amount) VALUES (1,'Series C',15000000); INSERT INTO investment_rounds (company_id,round_name,funding_amount) VALUES (2,'Series B',10000000);
SELECT company_id, name FROM company c LEFT JOIN (SELECT company_id FROM investment_rounds WHERE round_name = 'Series B') ir ON c.id = ir.company_id WHERE ir.company_id IS NULL;
Identify the solar power plant with the highest energy production in a given year.
CREATE TABLE solar_plants (name VARCHAR(50),location VARCHAR(50),capacity FLOAT,primary key (name)); INSERT INTO solar_plants (name,location,capacity) VALUES ('Plant X','California',120),('Plant Y','Arizona',180),('Plant Z','Nevada',210); CREATE TABLE solar_production (solar_plant VARCHAR(50),date DATE,energy_production FLOAT,primary key (solar_plant,date),foreign key (solar_plant) references solar_plants(name)); INSERT INTO solar_production (solar_plant,date,energy_production) VALUES ('Plant X','2021-01-01',1500),('Plant X','2021-01-02',1600),('Plant Y','2021-01-01',2200),('Plant Y','2021-01-02',2500),('Plant Z','2021-01-01',3000),('Plant Z','2021-01-02',3100);
SELECT solar_plant, MAX(energy_production) as max_production FROM solar_production WHERE date BETWEEN '2021-01-01' AND '2021-12-31' GROUP BY solar_plant, EXTRACT(YEAR FROM date) ORDER BY max_production DESC LIMIT 1
What is the total number of packages shipped to each country?
CREATE TABLE country_shipments (shipment_id INT,country VARCHAR(20),package_count INT); INSERT INTO country_shipments (shipment_id,country,package_count) VALUES (1,'USA',3),(2,'Canada',2),(3,'Mexico',1),(4,'USA',1),(5,'Canada',1),(6,'USA',1);
SELECT country, SUM(package_count) FROM country_shipments GROUP BY country;
What is the total number of donation hours for the environmental program?
CREATE TABLE Donations (id INT,donor_name VARCHAR(255),contact_info VARCHAR(255),program VARCHAR(255),hours INT); INSERT INTO Donations (id,donor_name,contact_info,program,hours) VALUES (1,'Daniel Kim','danielkim@example.com','Environmental',20),(2,'Elena Thompson','elenathompson@example.com','Environmental',15),(3,'Felipe Rodriguez','feliperodriguez@example.com','Education',30);
SELECT SUM(hours) FROM Donations WHERE program = 'Environmental';
What is the total production of Dysprosium in the 'North America' region for each year?
CREATE TABLE production(year INT,region VARCHAR(20),element VARCHAR(10),quantity INT); INSERT INTO production VALUES(2018,'North America','Dysprosium',1500),(2019,'North America','Dysprosium',1800),(2020,'North America','Dysprosium',2000);
SELECT year, SUM(quantity) FROM production WHERE element = 'Dysprosium' AND region = 'North America' GROUP BY year
Insert a new record for vessel 'VesselI' with a speed of 16.5 knots, located near the coast of Greece on October 1, 2021.
CREATE TABLE vessel_performance (id INT PRIMARY KEY,name VARCHAR(50),type VARCHAR(50),speed FLOAT,location VARCHAR(50),timestamp DATETIME);
INSERT INTO vessel_performance (name, type, speed, location, timestamp) VALUES ('VesselI', 'Cargo', 16.5, 'Greece Coast', '2021-10-01 10:00:00');
What is the average consumer rating for cruelty-free cosmetic products?
CREATE TABLE cosmetics (product_id INT,product_name TEXT,cruelty_free BOOLEAN,consumer_rating FLOAT); INSERT INTO cosmetics VALUES (1,'Lipstick A',true,4.6),(2,'Foundation B',false,4.3),(3,'Mascara C',true,4.7),(4,'Eyeshadow D',true,4.5),(5,'Blush E',false,4.4);
SELECT AVG(consumer_rating) as avg_rating FROM cosmetics WHERE cruelty_free = true;
How many ethical AI research papers have been published per year in the last 5 years?
CREATE TABLE ai_research (publication_year INT,num_papers INT); INSERT INTO ai_research (publication_year,num_papers) VALUES (2018,325),(2019,456),(2020,578),(2021,701);
SELECT publication_year, num_papers, COUNT(*) OVER (PARTITION BY publication_year) AS papers_per_year FROM ai_research;
What is the ratio of unions with collective bargaining agreements to total unions in the Northeast region?
CREATE TABLE collective_bargaining (bargaining_id INT,union_name VARCHAR(50),contract_start_date DATE,contract_end_date DATE,region VARCHAR(50));CREATE TABLE union_membership (member_id INT,name VARCHAR(50),union_name VARCHAR(50),membership_start_date DATE,region VARCHAR(50));CREATE VIEW union_region AS SELECT DISTINCT union_name,region FROM collective_bargaining UNION SELECT DISTINCT union_name,region FROM union_membership;CREATE VIEW northeast_unions AS SELECT union_name FROM union_membership WHERE region = 'Northeast';
SELECT COUNT(*) * 100.0 / (SELECT COUNT(*) FROM union_region) as ratio FROM northeast_unions nu WHERE EXISTS (SELECT 1 FROM collective_bargaining cb WHERE cb.union_name = nu.union_name);
What is the average speed of 'VesselB' during its journeys in the Atlantic ocean?
CREATE TABLE vessel_position (vessel_name TEXT,speed_knots INTEGER,region TEXT); INSERT INTO vessel_position (vessel_name,speed_knots,region) VALUES ('VesselB',15,'Atlantic ocean'); INSERT INTO vessel_position (vessel_name,speed_knots,region) VALUES ('VesselB',18,'Atlantic ocean');
SELECT AVG(speed_knots) FROM vessel_position WHERE vessel_name = 'VesselB' AND region = 'Atlantic ocean';
Determine the total number of tuberculosis cases reported in each country, for the year 2019.
CREATE TABLE tb_cases (country VARCHAR(50),year INTEGER,num_cases INTEGER); INSERT INTO tb_cases (country,year,num_cases) VALUES ('United States',2019,9000),('Mexico',2019,15000),('Brazil',2019,20000),('Canada',2019,12000),('Argentina',2019,18000),('Chile',2019,10000);
SELECT country, SUM(num_cases) as total_tb_cases FROM tb_cases WHERE year = 2019 GROUP BY country;
Find the average water_usage in the residential table for the month of August 2022, excluding any customers with a water_usage of 0.
CREATE TABLE residential (customer_id INT,water_usage FLOAT,usage_date DATE); INSERT INTO residential (customer_id,water_usage,usage_date) VALUES (1,150.5,'2022-08-01'),(2,0,'2022-08-02'),(3,800.4,'2022-08-03');
SELECT AVG(water_usage) FROM residential WHERE usage_date BETWEEN '2022-08-01' AND '2022-08-31' AND water_usage > 0;
What is the average age of players who prefer sports games, and what is the average age of players who prefer puzzle games?
CREATE TABLE Players (PlayerID int,Age int,Gender varchar(10),GamePreference varchar(20)); INSERT INTO Players (PlayerID,Age,Gender,GamePreference) VALUES (3,35,'Non-binary','Sports'); INSERT INTO Players (PlayerID,Age,Gender,GamePreference) VALUES (4,28,'Female','Puzzle');
SELECT GamePreference, AVG(Age) AS AvgAge FROM Players WHERE GamePreference IN ('Sports', 'Puzzle') GROUP BY GamePreference;
What is the total number of cybersecurity incidents reported in North America in 2021?
CREATE TABLE cybersecurity_incidents (region VARCHAR(50),year INT,num_incidents INT); INSERT INTO cybersecurity_incidents (region,year,num_incidents) VALUES ('North America',2019,4000),('North America',2020,5000),('North America',2021,6000);
SELECT SUM(num_incidents) FROM cybersecurity_incidents WHERE region = 'North America' AND year = 2021;
What is the percentage of teachers who have completed at least one professional development course in the last 6 months?
CREATE TABLE teachers (id INT,name VARCHAR(255)); CREATE TABLE courses (id INT,name VARCHAR(255),start_date DATE); CREATE TABLE teacher_courses (teacher_id INT,course_id INT,completed DATE);
SELECT 100.0 * COUNT(DISTINCT tc.teacher_id) / (SELECT COUNT(DISTINCT t.id) FROM teachers t) as pct_completed FROM teacher_courses tc JOIN courses c ON tc.course_id = c.id WHERE c.start_date >= DATE_SUB(CURRENT_DATE, INTERVAL 6 MONTH);
What's the total number of workers in the mining industry across all regions?
CREATE TABLE mining_workforce (region VARCHAR(20),num_workers INT); INSERT INTO mining_workforce (region,num_workers) VALUES ('West',1200),('East',1500),('North',1700),('South',1300);
SELECT SUM(num_workers) FROM mining_workforce;
What is the total waste generation by material type in New York City in 2021?
CREATE TABLE waste_generation(city VARCHAR(20),material VARCHAR(20),quantity INT); INSERT INTO waste_generation VALUES('New York City','Plastic',15000),('New York City','Paper',20000),('New York City','Glass',10000);
SELECT material, SUM(quantity) as total_waste FROM waste_generation WHERE city = 'New York City' AND YEAR(event_date) = 2021 GROUP BY material;
What is the average transaction amount for clients in the Northern region?
CREATE TABLE clients (client_id INT,name VARCHAR(50),region VARCHAR(20)); CREATE TABLE transactions (transaction_id INT,client_id INT,amount DECIMAL(10,2)); INSERT INTO clients (client_id,name,region) VALUES (1,'John Doe','Northern'),(2,'Jane Smith','Southern'); INSERT INTO transactions (transaction_id,client_id,amount) VALUES (1,1,1000.00),(2,1,2000.00),(3,2,500.00);
SELECT AVG(t.amount) FROM clients c INNER JOIN transactions t ON c.client_id = t.client_id WHERE c.region = 'Northern';
What is the average gold grade for each rock type at sample ID 1001?
CREATE TABLE Drill_Core (ID int,Sample_ID int,Depth decimal(10,2),Rock_Type varchar(50),Assay_Date date,Gold_Grade decimal(10,2)); INSERT INTO Drill_Core (ID,Sample_ID,Depth,Rock_Type,Assay_Date,Gold_Grade) VALUES (1,1001,1.23,'Quartz','2022-02-18',12.5),(2,1001,1.89,'Mica','2022-02-18',2.3),(3,1001,2.34,'Feldspar','2022-02-18',4.8),(4,1001,2.91,'Quartz','2022-02-18',14.1),(5,1001,3.45,'Mica','2022-02-18',1.9),(6,1001,4.02,'Feldspar','2022-02-18',4.5);
SELECT Sample_ID, Rock_Type, AVG(Gold_Grade) as Avg_Gold_Grade FROM Drill_Core WHERE Sample_ID = 1001 GROUP BY Sample_ID, Rock_Type;
What is the number of educational programs provided by each organization, for refugees in South Asia, in the last 2 years, and the total number of beneficiaries?
CREATE TABLE educational_programs (program_id INT,organization_id INT,location VARCHAR(255),start_date DATE,end_date DATE,beneficiaries INT); INSERT INTO educational_programs VALUES (1,1,'Country A','2020-01-01','2021-12-31',500); INSERT INTO educational_programs VALUES (2,1,'Country A','2021-01-01','2022-12-31',700); INSERT INTO educational_programs VALUES (3,2,'Country B','2021-01-01','2022-12-31',1000); INSERT INTO educational_programs VALUES (4,2,'Country B','2020-01-01','2021-12-31',800);
SELECT organization_id, COUNT(*) as number_of_programs, SUM(beneficiaries) as total_beneficiaries FROM educational_programs WHERE location IN ('Country A', 'Country B') AND start_date >= DATE_SUB(CURRENT_DATE, INTERVAL 2 YEAR) GROUP BY organization_id;
Which regions have the highest and lowest broadband subscriber churn rates?
CREATE TABLE subscriber_churn (churn_id INT,churn_date DATE,subscriber_id INT,region VARCHAR(50),churn_reason VARCHAR(50));
SELECT region, COUNT(churn_id) as churn_count FROM subscriber_churn WHERE YEAR(churn_date) = YEAR(current_date) - 1 GROUP BY region ORDER BY churn_count ASC, churn_count DESC LIMIT 1;
What is the average listening duration for each genre?
CREATE TABLE ListeningData (listen_id INT,listen_date DATE,song_id INT,genre VARCHAR(255),duration DECIMAL(5,2)); INSERT INTO ListeningData (listen_id,listen_date,song_id,genre,duration) VALUES (1,'2020-01-01',1,'Pop',3.5),(2,'2020-01-02',2,'Rock',4.0),(3,'2020-01-03',3,'Pop',3.2);
SELECT genre, AVG(duration) as avg_duration FROM ListeningData GROUP BY genre;
Add a new community with 1700 members?
CREATE TABLE Community (name VARCHAR(255),members INT);
INSERT INTO Community (name, members) VALUES ('La Rinconada', 1700);
What is the oldest satellite still in orbit?
CREATE TABLE satellites (satellite_id INT,name VARCHAR(255),launch_country VARCHAR(255),launch_date DATE,orbit_status VARCHAR(255));
SELECT name, launch_date FROM satellites WHERE orbit_status = 'in orbit' ORDER BY launch_date ASC LIMIT 1;
Identify the top 2 insurance types with the highest average claim amount in the state of New York.
CREATE TABLE Claim_Amount_State (Policy_Type VARCHAR(20),State VARCHAR(20),Claim_Amount INT); INSERT INTO Claim_Amount_State (Policy_Type,State,Claim_Amount) VALUES ('Life','New York',30000),('Health','New York',7000),('Auto','New York',8000),('Life','New York',25000),('Health','New York',8000);
SELECT Policy_Type, AVG(Claim_Amount) AS Average_Claim_Amount FROM Claim_Amount_State WHERE State = 'New York' GROUP BY Policy_Type ORDER BY Average_Claim_Amount DESC LIMIT 2;
Create a view for sustainable urbanism initiatives by year
CREATE TABLE SustainableUrbanismByYear (id INT PRIMARY KEY,city VARCHAR(50),state VARCHAR(50),initiative VARCHAR(100),year INT); INSERT INTO SustainableUrbanismByYear (id,city,state,initiative,year) VALUES (1,'Seattle','WA','Green Roofs Initiative',2022),(2,'Austin','TX','Urban Forest Plan',2022);
CREATE VIEW SustainableUrbanismByYearView AS SELECT * FROM SustainableUrbanismByYear WHERE state IN ('WA', 'TX');
What are the names and lengths of all bridges, including those that have not been affected by any disaster?
CREATE TABLE Bridge (id INT,city_id INT,name VARCHAR,length FLOAT,completion_date DATE); INSERT INTO Bridge (id,city_id,name,length,completion_date) VALUES (1,1,'George Washington Bridge',4760,'1931-10-25'); INSERT INTO Bridge (id,city_id,name,length,completion_date) VALUES (2,2,'Golden Gate Bridge',2737,'1937-05-27'); INSERT INTO Bridge (id,city_id,name,length,completion_date) VALUES (3,3,'Lake Pontchartrain Causeway',38400,'1956-08-30');
SELECT b.name, b.length FROM Bridge b LEFT JOIN Disaster d ON b.id = d.bridge_id WHERE d.id IS NULL;
Find the top 5 virtual tours by total revenue, for tours priced above the average.
CREATE TABLE VirtualTours (TourID int,TourName varchar(255),Price float,Revenue float); INSERT INTO VirtualTours (TourID,TourName,Price,Revenue) VALUES (1,'Tour A',10,500),(2,'Tour B',15,800),(3,'Tour C',20,1200),(4,'Tour D',5,300),(5,'Tour E',25,1500);
SELECT TourName, Revenue FROM (SELECT TourName, Price, Revenue, AVG(Price) OVER () as AvgPrice, RANK() OVER (ORDER BY Revenue DESC) as RevenueRank FROM VirtualTours) as Subquery WHERE Subquery.Price > Subquery.AvgPrice AND Subquery.RevenueRank <= 5;
What is the maximum calories burned for any workout in the 'Strength' category?
CREATE TABLE Workouts (WorkoutID INT,WorkoutName VARCHAR(20),Category VARCHAR(10)); INSERT INTO Workouts (WorkoutID,WorkoutName,Category) VALUES (1,'Treadmill','Cardio'),(2,'Yoga','Strength'),(3,'Cycling','Cardio'); CREATE TABLE CaloriesBurned (WorkoutID INT,CaloriesBurned INT); INSERT INTO CaloriesBurned (WorkoutID,CaloriesBurned) VALUES (1,300),(2,150),(3,400),(4,500);
SELECT MAX(CaloriesBurned) FROM Workouts INNER JOIN CaloriesBurned ON Workouts.WorkoutID = CaloriesBurned.WorkoutID WHERE Workouts.Category = 'Strength';
What are the names and dates of all excavation sites in France and Germany?
CREATE TABLE ExcavationSites (SiteID INT,SiteName TEXT,Country TEXT); INSERT INTO ExcavationSites (SiteID,SiteName,Country) VALUES (1,'Pompeii','Italy'),(2,'Herculaneum','Italy'),(3,'Gournay-sur-Aronde','France'),(4,'Manching','Germany');
SELECT SiteName, Date FROM ExcavationSites INNER JOIN Dates ON ExcavationSites.SiteID = Dates.SiteID WHERE Country IN ('France', 'Germany');
How many dance performances were held in the fall season of 2021?
CREATE TABLE performances (id INT,performance_date DATE,performance_type VARCHAR(50)); INSERT INTO performances (id,performance_date,performance_type) VALUES (1,'2021-09-01','Dance'),(2,'2021-12-31','Theater');
SELECT COUNT(*) FROM performances WHERE performance_type = 'Dance' AND performance_date BETWEEN '2021-09-01' AND '2021-12-31';
How many unique strains were produced by each cultivator in Colorado in 2022, and what are their average potencies?
CREATE TABLE cultivators (id INT,name TEXT,state TEXT); INSERT INTO cultivators (id,name,state) VALUES (1,'Cultivator X','Colorado'); INSERT INTO cultivators (id,name,state) VALUES (2,'Cultivator Y','Colorado'); CREATE TABLE strains (cultivator_id INT,name TEXT,year INT,potency INT); INSERT INTO strains (cultivator_id,name,year,potency) VALUES (1,'Strain A',2022,25); INSERT INTO strains (cultivator_id,name,year,potency) VALUES (1,'Strain B',2022,23); INSERT INTO strains (cultivator_id,name,year,potency) VALUES (2,'Strain C',2022,28);
SELECT c.name as cultivator_name, COUNT(DISTINCT s.name) as unique_strains, AVG(s.potency) as average_potency FROM cultivators c INNER JOIN strains s ON c.id = s.cultivator_id WHERE c.state = 'Colorado' AND s.year = 2022 GROUP BY c.name;
Insert a new record for a chemical compound with id 101, name 'Ethyl Acetate', and safety_rating 8
CREATE TABLE chemical_compounds (id INT PRIMARY KEY,name VARCHAR(255),safety_rating INT);
INSERT INTO chemical_compounds (id, name, safety_rating) VALUES (101, 'Ethyl Acetate', 8);
What is the average wellbeing score for athletes in each team?
CREATE TABLE teams (id INT,name VARCHAR(255)); INSERT INTO teams (id,name) VALUES (1,'Team A'),(2,'Team B'),(3,'Team C'),(4,'Team D'); CREATE TABLE athletes (id INT,team_id INT,wellbeing_score INT); INSERT INTO athletes (id,team_id,wellbeing_score) VALUES (1,1,80),(2,2,85),(3,1,75),(4,3,90);
SELECT t.name, AVG(a.wellbeing_score) as avg_wellbeing_score FROM athletes a JOIN teams t ON a.team_id = t.id GROUP BY t.name;
What is the maximum cargo weight handled by vessels that have visited 'Port B'?
CREATE TABLE ports (port_id INT,port_name TEXT,country TEXT); INSERT INTO ports (port_id,port_name,country) VALUES (1,'Port A','USA'),(2,'Port B','Canada'); CREATE TABLE shipments (shipment_id INT,vessel_id INT,port_id INT,cargo_weight INT); INSERT INTO shipments (shipment_id,vessel_id,port_id,cargo_weight) VALUES (1,1,1,5000),(2,2,1,5500),(3,1,2,4000),(4,2,2,4500);
SELECT MAX(cargo_weight) FROM shipments JOIN ports ON shipments.port_id = ports.port_id WHERE ports.port_name = 'Port B';
What is the maximum production volume for zinc mines in South Africa?
CREATE TABLE mines (id INT,name TEXT,location TEXT,production_volume INT); INSERT INTO mines (id,name,location,production_volume) VALUES (1,'South African Zinc Mine 1','South Africa',11000); INSERT INTO mines (id,name,location,production_volume) VALUES (2,'South African Zinc Mine 2','South Africa',9000);
SELECT MAX(production_volume) FROM mines WHERE location = 'South Africa' AND mineral = 'zinc';
What are the top 3 drugs by sales in the US and the EU?
CREATE TABLE drug_sales (drug_name TEXT,region TEXT,revenue FLOAT); INSERT INTO drug_sales (drug_name,region,revenue) VALUES ('DrugA','US',5000000),('DrugB','EU',6000000),('DrugC','US',7000000),('DrugD','EU',8000000);
SELECT drug_name, SUM(revenue) FROM drug_sales WHERE region IN ('US', 'EU') GROUP BY drug_name ORDER BY SUM(revenue) DESC LIMIT 3;
Update the savings of customer '123' to '6000'?
CREATE TABLE savings (customer_id INT,name TEXT,state TEXT,savings DECIMAL(10,2)); INSERT INTO savings (customer_id,name,state,savings) VALUES (123,'Jane Doe','California',5000.00);
UPDATE savings SET savings = 6000 WHERE customer_id = 123;
What is the average price of vegetarian dishes in the lunch category?
CREATE TABLE menu (item_id INT,name TEXT,category TEXT,is_vegetarian BOOLEAN,price FLOAT); INSERT INTO menu (item_id,name,category,is_vegetarian,price) VALUES (1,'Chickpea Curry','Lunch',true,10.5),(2,'Chicken Tikka Masala','Lunch',false,13.0),(3,'Quinoa Salad','Starters',true,7.5);
SELECT AVG(price) as avg_vegetarian_price FROM menu WHERE is_vegetarian = true AND category = 'Lunch';
What is the name and type of all military technologies developed in 'Africa' in the 'Technologies' table?
CREATE TABLE Technologies (id INT,name VARCHAR(50),type VARCHAR(50),continent VARCHAR(50)); INSERT INTO Technologies (id,name,type,continent) VALUES (1,'Stealth Drone','Unmanned Aerial Vehicle','Africa'); INSERT INTO Technologies (id,name,type,continent) VALUES (2,'Artificial Intelligence','Software','Asia');
SELECT name, type FROM Technologies WHERE continent = 'Africa';
Find the top 3 countries with the most IoT devices in agriculture
CREATE TABLE country_iot (country VARCHAR(50),num_devices INT); INSERT INTO country_iot (country,num_devices) VALUES ('United States',5000),('India',3000),('China',7000),('Brazil',4000),('Germany',2000);
SELECT country, num_devices FROM country_iot ORDER BY num_devices DESC LIMIT 3;
What is the average response time for medical emergencies in the Boyle Heights district in 2021?
CREATE TABLE districts (id INT,name TEXT); INSERT INTO districts (id,name) VALUES (1,'Boyle Heights'),(2,'East LA'),(3,'Downtown LA'); CREATE TABLE medical_emergencies (id INT,district_id INT,response_time INT,incident_date DATE); INSERT INTO medical_emergencies (id,district_id,response_time,incident_date) VALUES (1,1,7,'2021-01-01'),(2,1,8,'2021-02-15'),(3,1,6,'2021-03-10');
SELECT AVG(response_time) FROM medical_emergencies WHERE district_id = 1 AND YEAR(incident_date) = 2021;
Insert a new record in the 'Faculty_Members' table with the following details: Faculty_ID = 45, First_Name = 'Órla', Last_Name = 'Ní Dhúill', Title = 'Associate Professor', Department = 'Computer Science', Hire_Date = '2020-07-01', Salary = 85000
CREATE TABLE Faculty_Members (Faculty_ID INT,First_Name VARCHAR(50),Last_Name VARCHAR(50),Title VARCHAR(20),Department VARCHAR(50),Hire_Date DATE,Salary DECIMAL(10,2));
INSERT INTO Faculty_Members (Faculty_ID, First_Name, Last_Name, Title, Department, Hire_Date, Salary) VALUES (45, 'Órla', 'Ní Dhúill', 'Associate Professor', 'Computer Science', '2020-07-01', 85000);
What is the maximum orbit altitude for SpaceX's Starlink satellites?
CREATE TABLE SatelliteOrbits (id INT,satellite_name VARCHAR(100),company VARCHAR(100),orbit_altitude FLOAT); INSERT INTO SatelliteOrbits (id,satellite_name,company,orbit_altitude) VALUES (1,'Starlink 1','SpaceX',550); INSERT INTO SatelliteOrbits (id,satellite_name,company,orbit_altitude) VALUES (2,'Starlink 2','SpaceX',560);
SELECT MAX(orbit_altitude) FROM SatelliteOrbits WHERE satellite_name LIKE '%Starlink%' AND company = 'SpaceX';
Delete records from the "shipments" table where the "status" column is "delayed" and the "delivery_date" is older than 30 days
CREATE TABLE shipments (id INT PRIMARY KEY,freight_forwarder VARCHAR(50),warehouse VARCHAR(50),status VARCHAR(20),delivery_date DATE);
DELETE s FROM shipments s INNER JOIN (SELECT id, delivery_date FROM shipments WHERE status = 'delayed' AND delivery_date < NOW() - INTERVAL 30 DAY) d ON s.id = d.id;
Identify the top 3 states with the highest water usage in the US?
CREATE TABLE us_water_usage (id INT,year INT,state TEXT,usage FLOAT);
SELECT state, RANK() OVER (ORDER BY usage DESC) as rank FROM us_water_usage GROUP BY state HAVING rank <= 3;