instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
How many international visitors arrived in Antarctica in the last 6 months?
CREATE TABLE international_visitors (id INT,name VARCHAR,country VARCHAR,arrival_date DATE); INSERT INTO international_visitors (id,name,country,arrival_date) VALUES (1,'James Smith','USA','2022-03-01');
SELECT COUNT(*) FROM international_visitors WHERE country = 'Antarctica' AND arrival_date >= DATEADD(month, -6, CURRENT_DATE);
What is the average cost of road construction projects in New York that were completed between 2010 and 2015?
CREATE TABLE projects (project_id INT,project_name VARCHAR(50),state VARCHAR(50),start_year INT,end_year INT,cost INT);
SELECT AVG(projects.cost) FROM projects WHERE projects.state = 'New York' AND projects.start_year BETWEEN 2010 AND 2015 AND projects.end_year BETWEEN 2010 AND 2015;
List all autonomous driving research projects and their respective end dates
CREATE TABLE autonomous_driving_research (project_name VARCHAR(100),start_date DATE,end_date DATE);
SELECT * FROM autonomous_driving_research;
What is the total area of each crop type?
CREATE TABLE crop (id INT,type VARCHAR(20),area FLOAT); INSERT INTO crop (id,type,area) VALUES (1,'Corn',1234.56),(2,'Soybean',2345.67),(3,'Wheat',3456.78);
SELECT type, SUM(area) AS total_area FROM crop GROUP BY type;
What are the total clinical trial costs for drug 'DrugX' in the Southeast Asia region?
CREATE TABLE clinical_trials (drug_name TEXT,region TEXT,cost FLOAT); INSERT INTO clinical_trials (drug_name,region,cost) VALUES ('DrugX','Southeast Asia',1200000),('DrugY','North America',1500000),('DrugX','Europe',1800000);
SELECT SUM(cost) AS total_cost FROM clinical_trials WHERE drug_name = 'DrugX' AND region = 'Southeast Asia';
List the total number of pollution control initiatives implemented in each region.
CREATE TABLE PollutionControl (id INT,initiative VARCHAR(50),region VARCHAR(20)); INSERT INTO PollutionControl (id,initiative,region) VALUES (1,'Ocean Cleanup','Arctic'),(2,'Plastic Reduction','Atlantic'),(3,'Carbon Capture','Global');
SELECT region, COUNT(*) as total_initiatives FROM PollutionControl GROUP BY region;
Show the number of artworks by each artist
CREATE TABLE ArtWorks (ID INT PRIMARY KEY,Title TEXT,Artist TEXT,Year INT);
SELECT Artist, COUNT(*) FROM ArtWorks GROUP BY Artist;
Provide the number of AI safety incidents grouped by their severity level and AI application area.
CREATE TABLE ai_safety_incidents (incident_id INT,severity_level VARCHAR(20),ai_application_area VARCHAR(50));
SELECT severity_level, ai_application_area, COUNT(*) FROM ai_safety_incidents GROUP BY severity_level, ai_application_area;
Find the average number of accessible technology patents per inventor in 'patents' table.
CREATE TABLE patents (inventor_name VARCHAR(50),inventor_gender VARCHAR(50),patent_name VARCHAR(50),technology_accessibility INTEGER);
SELECT AVG(technology_accessibility) FROM patents GROUP BY inventor_name;
Update policyholder 'John Doe's age to 36.
CREATE TABLE policyholders (id INT,name TEXT,age INT,gender TEXT,state TEXT); INSERT INTO policyholders (id,name,age,gender,state) VALUES (1,'John Doe',35,'Male','California'); INSERT INTO policyholders (id,name,age,gender,state) VALUES (2,'Jane Smith',42,'Female','California');
UPDATE policyholders SET age = 36 WHERE name = 'John Doe';
What is the number of flights per year for each aircraft model in the FlightLogs table?
CREATE TABLE FlightLogs (flight_id INT,aircraft_model VARCHAR(50),flight_year INT,flight_speed FLOAT); INSERT INTO FlightLogs (flight_id,aircraft_model,flight_year,flight_speed) VALUES (1,'B747',2022,850.0),(2,'A320',2021,800.0),(3,'B747',2022,900.0);
SELECT aircraft_model, flight_year, COUNT(*) AS flights_per_year FROM FlightLogs GROUP BY aircraft_model, flight_year;
What is the approval date for DrugC?
CREATE TABLE drug_approval (drug VARCHAR(255),approval_date DATE); INSERT INTO drug_approval (drug,approval_date) VALUES ('DrugC','2021-06-15'),('DrugD','2022-08-30');
SELECT approval_date FROM drug_approval WHERE drug = 'DrugC';
Delete all records in the 'oil_field' table where the 'operator' is 'Zeta Inc.' and the 'region' is 'Africa'
CREATE TABLE oil_field (id INT PRIMARY KEY,name TEXT,operator TEXT,region TEXT);
DELETE FROM oil_field WHERE operator = 'Zeta Inc.' AND region = 'Africa';
What is the total quantity of cargo handled by ports in the Asia Pacific region?
CREATE TABLE ports (port_id INT,port_name TEXT,region TEXT); INSERT INTO ports VALUES (1,'Port A','Asia Pacific'),(2,'Port B','Americas'); CREATE TABLE cargo (cargo_id INT,port_id INT,cargo_quantity INT); INSERT INTO cargo VALUES (1,1,500),(2,1,700),(3,2,600);
SELECT SUM(cargo_quantity) FROM cargo INNER JOIN ports ON cargo.port_id = ports.port_id WHERE ports.region = 'Asia Pacific';
Insert new humanitarian aid records for disaster_id 304, 305, and 306, country_name 'Syria', 'Yemen', and 'Myanmar', aid_amount 80000, 90000, and 70000, and aid_date '2021-12-31', '2022-01-01', and '2022-01-02' respectively
CREATE TABLE humanitarian_aid (disaster_id INT,country_name VARCHAR(50),aid_amount INT,aid_date DATE);
INSERT INTO humanitarian_aid (disaster_id, country_name, aid_amount, aid_date) VALUES (304, 'Syria', 80000, '2021-12-31'), (305, 'Yemen', 90000, '2022-01-01'), (306, 'Myanmar', 70000, '2022-01-02');
Update the primary investigator for clinical trial 'Trial123' in the 'clinical_trial_data' table.
CREATE TABLE clinical_trial_data (clinical_trial_id VARCHAR(255),drug_name VARCHAR(255),primary_investigator VARCHAR(255),start_date DATE,end_date DATE);
UPDATE clinical_trial_data SET primary_investigator = 'New PI' WHERE clinical_trial_id = 'Trial123';
What is the average time (in days) between order placements for 'CustomerX'?
CREATE TABLE Orders (OrderID INT,CustomerID VARCHAR(20),OrderDate DATE); INSERT INTO Orders (OrderID,CustomerID,OrderDate) VALUES (1,'X','2022-01-01'),(2,'X','2022-01-05'),(3,'X','2022-01-10');
SELECT AVG(DATEDIFF(dd, LAG(Orders.OrderDate) OVER (PARTITION BY Orders.CustomerID ORDER BY Orders.OrderDate), Orders.OrderDate)) AS AverageTimeBetweenOrders FROM Orders WHERE Orders.CustomerID = 'X';
What is the total revenue of all fair trade products imported to Spain?
CREATE TABLE imports (id INT,product TEXT,revenue FLOAT,is_fair_trade BOOLEAN,country TEXT); INSERT INTO imports (id,product,revenue,is_fair_trade,country) VALUES (1,'Coffee',500.0,true,'Spain'); INSERT INTO imports (id,product,revenue,is_fair_trade,country) VALUES (2,'Chocolate',700.0,false,'Spain');
SELECT SUM(revenue) FROM imports WHERE is_fair_trade = true AND country = 'Spain';
List all the countries with their corresponding marine pollution index
CREATE TABLE country (id INT,name VARCHAR(255)); CREATE TABLE pollution (id INT,country VARCHAR(255),index INT); INSERT INTO country (id,name) VALUES (1,'Canada'); INSERT INTO country (id,name) VALUES (2,'Mexico'); INSERT INTO pollution (id,country,index) VALUES (1,'Canada',45); INSERT INTO pollution (id,country,index) VALUES (2,'Mexico',78);
SELECT country.name, pollution.index FROM country INNER JOIN pollution ON country.name = pollution.country;
What is the total number of songs in the R&B genre?
CREATE TABLE songs (id INT,name VARCHAR(255),genre VARCHAR(255));
SELECT COUNT(*) as total_songs FROM songs WHERE genre = 'R&B';
What is the total number of packages shipped to Australia in the last month?
CREATE TABLE packages (id INT,shipped_date DATE); INSERT INTO packages (id,shipped_date) VALUES (1,'2022-01-01'),(2,'2022-01-15');
SELECT COUNT(*) FROM packages WHERE shipped_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH) AND destination = 'Australia';
What is the minimum number of posts made by a user who has made at least one post in the 'social_media' table?
CREATE TABLE social_media (user_id INT,post_id INT);
SELECT MIN(COUNT(*)) FROM social_media GROUP BY user_id HAVING COUNT(*) > 0;
Which is the most populated city in Africa?
CREATE TABLE City (CityName VARCHAR(50),Country VARCHAR(50),Population INT,Continent VARCHAR(50)); INSERT INTO City (CityName,Country,Population,Continent) VALUES ('Cairo','Egypt',20500000,'Africa'),('Lagos','Nigeria',21000000,'Africa');
SELECT CityName, Population FROM City WHERE Continent = 'Africa' ORDER BY Population DESC LIMIT 1;
What is the total revenue for all customers in the Southeast region?
CREATE TABLE customers (customer_id INT,name VARCHAR(50),region VARCHAR(50)); INSERT INTO customers (customer_id,name,region) VALUES (1,'John Doe','Southeast'),(2,'Jane Smith','Northeast'); CREATE TABLE sales (sale_id INT,customer_id INT,revenue DECIMAL(10,2)); INSERT INTO sales (sale_id,customer_id,revenue) VALUES (1,1,500.00),(2,1,750.00),(3,2,300.00);
SELECT SUM(sales.revenue) FROM sales JOIN customers ON sales.customer_id = customers.customer_id WHERE customers.region = 'Southeast';
What is the average donation amount for one-time donors in the 'q1' quarter?
CREATE TABLE Donations (id INT,donor_type VARCHAR(10),donation_amount DECIMAL(10,2),donation_date DATE); INSERT INTO Donations (id,donor_type,donation_amount,donation_date) VALUES (1,'one-time',50.00,'2022-01-01'); INSERT INTO Donations (id,donor_type,donation_amount,donation_date) VALUES (2,'recurring',25.00,'2022-01-15');
SELECT AVG(donation_amount) FROM Donations WHERE donor_type = 'one-time' AND QUARTER(donation_date) = 1;
Identify mines with a significant increase in gold production compared to the previous day.
CREATE TABLE daily_mine_gold_production (mine_id INT,production_date DATE,gold_production FLOAT); INSERT INTO daily_mine_gold_production (mine_id,production_date,gold_production) VALUES (1,'2021-01-01',100),(1,'2021-01-02',110),(1,'2021-01-03',140),(1,'2021-01-04',150),(2,'2021-01-01',140),(2,'2021-01-02',150),(2,'2021-01-03',160),(2,'2021-01-04',180);
SELECT mine_id, production_date, gold_production, LAG(gold_production) OVER (PARTITION BY mine_id ORDER BY production_date) as prev_day_production, gold_production - LAG(gold_production) OVER (PARTITION BY mine_id ORDER BY production_date) as production_change FROM daily_mine_gold_production WHERE gold_production > 1.2 * LAG(gold_production) OVER (PARTITION BY mine_id ORDER BY production_date);
What is the total number of factories that have implemented waste reduction initiatives, by country?
CREATE TABLE WasteReductionFactories (id INT,country VARCHAR(50),num_factories INT);
SELECT country, SUM(num_factories) as total_factories FROM WasteReductionFactories GROUP BY country;
Calculate the total number of employees in each department, excluding contractors
CREATE TABLE department_employees (id INT,department VARCHAR(255),gender VARCHAR(6),employment_status VARCHAR(255),count INT);
SELECT department, SUM(count) as total_employees FROM department_employees WHERE employment_status != 'Contractor' GROUP BY department;
What was the average CO2 emission for jean production by country in 2020?
CREATE TABLE co2_emission (garment_type VARCHAR(20),country VARCHAR(20),year INT,co2_emission FLOAT); INSERT INTO co2_emission (garment_type,country,year,co2_emission) VALUES ('jeans','Italy',2020,15.5),('jeans','China',2020,25.2),('jeans','India',2020,18.8);
SELECT AVG(co2_emission) FROM co2_emission WHERE garment_type = 'jeans' AND year = 2020;
What is the total number of articles published per day for a journalist from India?
CREATE TABLE articles (article_id INT,author VARCHAR(50),title VARCHAR(100),category VARCHAR(50),publication_date DATE,author_country VARCHAR(50));
SELECT publication_date, COUNT(article_id) AS articles_per_day FROM articles WHERE author_country = 'India' GROUP BY publication_date ORDER BY publication_date;
How many customers have made transactions over $1000 in total?
CREATE TABLE transactions (transaction_id INT,customer_id INT,amount DECIMAL(10,2)); INSERT INTO transactions (transaction_id,customer_id,amount) VALUES (1,1,50.00),(2,1,100.00),(3,2,75.00),(4,3,1200.00); CREATE TABLE customers (customer_id INT,name VARCHAR(50),region VARCHAR(50)); INSERT INTO customers (customer_id,name,region) VALUES (1,'John Doe','East'),(2,'Jane Smith','West'),(3,'Mike Johnson','East');
SELECT COUNT(DISTINCT c.customer_id) FROM transactions t JOIN customers c ON t.customer_id = c.customer_id WHERE t.amount > 1000.00;
List all events and their attendance numbers, sorted by the event type and year, for events held in Europe and Asia.
CREATE TABLE events (id INT,name VARCHAR(50),year INT,location VARCHAR(50),type VARCHAR(20)); INSERT INTO events (id,name,year,location,type) VALUES (1,'Event1',2015,'Paris','Art'),(2,'Event2',2016,'London','Music'),(3,'Event3',2017,'Beijing','Theater'),(4,'Event4',2018,'Tokyo','Art');
SELECT type, year, COUNT(*) as attendance_count FROM events WHERE location IN ('Europe', 'Asia') GROUP BY type, year ORDER BY type, year;
What is the average data usage per mobile customer in the city of Chicago, split by postpaid and prepaid plans and by device type?
CREATE TABLE mobile_customers (customer_id INT,data_usage FLOAT,city VARCHAR(20),plan_type VARCHAR(10),device_type VARCHAR(10));
SELECT plan_type, device_type, AVG(data_usage) FROM mobile_customers WHERE city = 'Chicago' GROUP BY plan_type, device_type;
What is the number of community policing events held in the state of New York, grouped by city?
CREATE TABLE community_policing (id INT,city VARCHAR(20),state VARCHAR(20),year INT,events INT);
SELECT city, COUNT(*) FROM community_policing WHERE state = 'New York' GROUP BY city;
What is the minimum capacity of renewable energy projects in a given state?
CREATE TABLE State (state_id INT,state_name VARCHAR(50)); CREATE TABLE Project (project_id INT,project_name VARCHAR(50),project_capacity INT,state_id INT);
SELECT State.state_name, MIN(Project.project_capacity) as min_capacity FROM State JOIN Project ON State.state_id = Project.state_id GROUP BY State.state_name;
How many legal aid clinics are there in rural areas of Illinois and Michigan?
CREATE TABLE legal_clinics (clinic_id INT,location VARCHAR(20),state VARCHAR(20)); INSERT INTO legal_clinics (clinic_id,location,state) VALUES (1,'Rural','Illinois'),(2,'Urban','Illinois'),(3,'Rural','Michigan');
SELECT COUNT(*) FROM legal_clinics WHERE state IN ('Illinois', 'Michigan') AND location = 'Rural';
How many marine life research stations and pollution control initiatives are there in total?
CREATE TABLE marine_life_research_stations (id INT,name VARCHAR(255),region VARCHAR(255)); CREATE TABLE pollution_control_initiatives (id INT,name VARCHAR(255),region VARCHAR(255));
SELECT SUM(cnt) FROM (SELECT COUNT(*) cnt FROM marine_life_research_stations UNION ALL SELECT COUNT(*) FROM pollution_control_initiatives) x;
What is the number of community health centers in urban areas with a rating of 4 or higher?
CREATE TABLE community_health_centers (id INT,name TEXT,location TEXT,rating INT); INSERT INTO community_health_centers (id,name,location,rating) VALUES (1,'Community Health Center 1','urban',5),(2,'Community Health Center 2','rural',3),(3,'Community Health Center 3','urban',4);
SELECT COUNT(*) FROM community_health_centers WHERE location = 'urban' AND rating >= 4;
What is the total revenue for each track?
CREATE TABLE TrackRevenue (TrackID INT,Revenue DECIMAL(10,2)); INSERT INTO TrackRevenue (TrackID,Revenue) VALUES (1,1.25),(2,1.50),(3,0.99),(4,2.00);
SELECT TrackID, Revenue, ROW_NUMBER() OVER (ORDER BY Revenue DESC) AS 'Revenue Rank' FROM TrackRevenue;
What is the average carbon offsetting per project in South America?
CREATE TABLE project (id INT,name TEXT,location TEXT,carbon_offset INT); INSERT INTO project (id,name,location,carbon_offset) VALUES (1,'Solar Farm','South America',5000);
SELECT AVG(carbon_offset) FROM project WHERE location = 'South America';
What is the average number of years of experience for instructors in the 'Physical Therapy' department?
CREATE TABLE Instructors (Id INT,Name VARCHAR(50),Department VARCHAR(50),YearsOfExperience INT); INSERT INTO Instructors (Id,Name,Department,YearsOfExperience) VALUES (1,'Maria Garcia','Physical Therapy',12);
SELECT AVG(YearsOfExperience) AS AvgYearsOfExperience FROM Instructors WHERE Department = 'Physical Therapy';
What is the total CO2 emissions of the transportation sector in each European country?
CREATE TABLE co2_emissions (country VARCHAR(20),sector VARCHAR(20),emissions FLOAT); INSERT INTO co2_emissions (country,sector,emissions) VALUES ('Germany','transportation',200.0),('France','transportation',150.0),('Germany','transportation',220.0);
SELECT country, SUM(emissions) FROM co2_emissions WHERE sector = 'transportation' GROUP BY country;
What's the maximum and minimum ESG score of companies based in the UK?
CREATE TABLE companies (id INT,country VARCHAR(30),ESG_score FLOAT); INSERT INTO companies (id,country,ESG_score) VALUES (1,'UK',71.5),(2,'UK',82.3),(3,'UK',75.6),(4,'France',79.9);
SELECT MAX(ESG_score), MIN(ESG_score) FROM companies WHERE country = 'UK';
What is the percentage of fraudulent transactions for each day in February 2022?
CREATE TABLE transactions (transaction_id INT,transaction_date DATE,is_fraud BOOLEAN); INSERT INTO transactions (transaction_id,transaction_date,is_fraud) VALUES (1,'2022-02-01',FALSE),(2,'2022-02-01',TRUE),(3,'2022-02-02',FALSE);
SELECT transaction_date, 100.0 * SUM(CASE WHEN is_fraud THEN 1 ELSE 0 END) / COUNT(*) as fraud_percentage FROM transactions WHERE transaction_date >= '2022-02-01' AND transaction_date < '2022-03-01' GROUP BY transaction_date ORDER BY transaction_date;
What is the maximum range of electric vehicles in the vehicle_test_data table for each make and model?
CREATE TABLE vehicle_test_data (id INT,make VARCHAR(20),model VARCHAR(20),range DECIMAL(5,2)); INSERT INTO vehicle_test_data (id,make,model,range) VALUES (1,'Tesla','Model 3',322.3),(2,'Ford','Mustang Mach-E',230.8),(3,'Chevrolet','Bolt',259.0),(4,'Tesla','Model S',373.1),(5,'Ford','F-150 Lightning',300.0);
SELECT make, model, MAX(range) FROM vehicle_test_data GROUP BY make, model;
List all green building materials and the number of each material used in a specific city.
CREATE TABLE GreenBuildingMaterials (MaterialID INT,MaterialName VARCHAR(50));CREATE TABLE GreenBuildingMaterialsUsage (UsageID INT,MaterialID INT,CityID INT);
SELECT GreenBuildingMaterials.MaterialName, COUNT(GreenBuildingMaterialsUsage.UsageID) FROM GreenBuildingMaterials INNER JOIN GreenBuildingMaterialsUsage ON GreenBuildingMaterials.MaterialID = GreenBuildingMaterialsUsage.MaterialID WHERE GreenBuildingMaterialsUsage.CityID = 1 GROUP BY GreenBuildingMaterials.MaterialName;
Delete the "OceanCurrents" view
CREATE VIEW OceanCurrents AS SELECT * FROM Currents WHERE Type = 'Ocean';
DROP VIEW OceanCurrents;
What is the percentage of companies in the 'Healthcare' sector with an ESG score below 60?
CREATE TABLE companies (id INT,name VARCHAR(255),esg_score DECIMAL(3,2),sector VARCHAR(255));
SELECT (COUNT(*) FILTER (WHERE esg_score < 60)) * 100.0 / COUNT(*) AS percentage FROM companies WHERE sector = 'Healthcare';
What is the total number of births in the state of Texas in the year 2020?
CREATE TABLE births (id INT,state TEXT,year INT,num_births INT); INSERT INTO births (id,state,year,num_births) VALUES (1,'Texas',2020,400000),(2,'Texas',2019,390000),(3,'California',2020,500000);
SELECT SUM(num_births) FROM births WHERE state = 'Texas' AND year = 2020;
Show the total revenue for each game genre in the last quarter, excluding canceled transactions, grouped by genre.
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,status VARCHAR(50));
SELECT genres.genre, SUM(transactions.amount) as total_revenue FROM games JOIN transactions ON games.name = transactions.game_id JOIN (SELECT DISTINCT game_name, genre FROM games) genres ON games.genre = genres.genre WHERE transactions.transaction_date >= DATE_SUB(CURRENT_DATE, INTERVAL 3 MONTH) AND transactions.status = 'completed' GROUP BY genres.genre;
What is the total number of facilities in City A?
CREATE TABLE hospitals (id INT,name TEXT,location TEXT,type TEXT); INSERT INTO hospitals (id,name,location,type) VALUES (1,'Hospital A','City A','General'); INSERT INTO hospitals (id,name,location,type) VALUES (2,'Hospital B','City B','Pediatric'); CREATE TABLE clinics (id INT,name TEXT,location TEXT,type TEXT); INSERT INTO clinics (id,name,location,type) VALUES (1,'Clinic C','City C','Dental'); INSERT INTO clinics (id,name,location,type) VALUES (2,'Clinic D','City A','General'); CREATE TABLE long_term_care (id INT,name TEXT,location TEXT,type TEXT); INSERT INTO long_term_care (id,name,location,type) VALUES (1,'LT Care A','City A','Nursing'); INSERT INTO long_term_care (id,name,location,type) VALUES (2,'LT Care B','City B','Assisted Living');
SELECT type FROM hospitals WHERE location = 'City A' UNION SELECT type FROM clinics WHERE location = 'City A' UNION SELECT type FROM long_term_care WHERE location = 'City A';
What was the average donation amount for each program type in 2022?
CREATE TABLE Donations (DonationID INT,DonationAmount DECIMAL(10,2),DonationDate DATE,ProgramID INT); INSERT INTO Donations (DonationID,DonationAmount,DonationDate,ProgramID) VALUES (1,500.00,'2022-01-05',1); INSERT INTO Donations (DonationID,DonationAmount,DonationDate,ProgramID) VALUES (2,300.00,'2022-02-10',2); INSERT INTO Donations (DonationID,DonationAmount,DonationDate,ProgramID) VALUES (3,250.00,'2022-03-15',1); CREATE TABLE Programs (ProgramID INT,ProgramType TEXT); INSERT INTO Programs (ProgramID,ProgramType) VALUES (1,'Education'); INSERT INTO Programs (ProgramID,ProgramType) VALUES (2,'Environment');
SELECT ProgramType, AVG(DonationAmount) as AverageDonation FROM Donations INNER JOIN Programs ON Donations.ProgramID = Programs.ProgramID GROUP BY ProgramType;
How many products have been recalled in each country for safety reasons, in the last year?
CREATE TABLE Product_Safety_Records (id INT,product_id INT,inspection_date DATE,result VARCHAR(255)); CREATE TABLE Recalls (id INT,product_id INT,recall_date DATE,reason VARCHAR(255),country VARCHAR(255));
SELECT r.country, COUNT(DISTINCT r.id) as number_of_recalls FROM Recalls r JOIN Product_Safety_Records psr ON r.product_id = psr.product_id WHERE r.recall_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR) GROUP BY r.country;
How many medical camps were organized in Asia in 2019 and 2020?
CREATE TABLE medical_camps (id INT PRIMARY KEY,location VARCHAR(50),year INT,number INT); INSERT INTO medical_camps (id,location,year,number) VALUES (1,'Africa',2018,10),(2,'Asia',2018,15),(3,'Africa',2019,12),(4,'Asia',2019,20),(5,'Africa',2020,14),(6,'Asia',2020,25);
SELECT SUM(number) FROM medical_camps WHERE location = 'Asia' AND year IN (2019, 2020);
Which beauty products are not eco-friendly and not rated above 4.0?
CREATE TABLE Products (product_id INT,product_name VARCHAR(100),eco_friendly BOOLEAN,rating FLOAT); INSERT INTO Products (product_id,product_name,eco_friendly,rating) VALUES (1,'Lipstick A',FALSE,4.2),(2,'Lipstick B',TRUE,3.9),(3,'Lipstick C',FALSE,4.5);
SELECT product_name FROM Products WHERE eco_friendly = FALSE AND rating <= 4.0;
How many medical supplies were delivered to Colombia in Q1 2022?
CREATE TABLE medical_supplies (id INT,quantity INT,country TEXT,quarter INT,year INT); INSERT INTO medical_supplies (id,quantity,country,quarter,year) VALUES (1,500,'Colombia',1,2022),(2,700,'Colombia',2,2022),(3,600,'Colombia',3,2022),(4,800,'Colombia',4,2022);
SELECT SUM(quantity) FROM medical_supplies WHERE country = 'Colombia' AND quarter = 1 AND year = 2022;
List REE market trends for each year since 2018?
CREATE TABLE trends (year INT,market_trend VARCHAR(255)); INSERT INTO trends (year,market_trend) VALUES (2018,'Increase'),(2019,'Decrease'),(2020,'Increase'),(2021,'Stable'),(2022,'Increase');
SELECT year, market_trend FROM trends;
What is the maximum salary of construction workers per state?
CREATE TABLE WorkerSalaries (WorkerID int,Name varchar(50),State varchar(25),Salary decimal(10,2)); INSERT INTO WorkerSalaries (WorkerID,Name,State,Salary) VALUES (7,'John Doe','NY',60000.00),(8,'Jane Smith','CA',70000.00),(9,'Mike Johnson','TX',65000.00);
SELECT State, MAX(Salary) AS MaxSalary FROM WorkerSalaries GROUP BY State;
Count the number of articles written by each author, grouped by author country.
CREATE TABLE authors (id INT PRIMARY KEY,name TEXT,country TEXT); CREATE TABLE articles (id INT PRIMARY KEY,title TEXT,author_id INT); INSERT INTO authors (id,name,country) VALUES (1,'John Doe','USA'),(2,'Jane Smith','Canada'),(3,'Maria Garcia','Mexico'); INSERT INTO articles (id,title,author_id) VALUES (1,'Article 1',1),(2,'Article 2',1),(3,'Article 3',3);
SELECT au.country, COUNT(a.id) FROM articles a JOIN authors au ON a.author_id = au.id GROUP BY au.country;
Insert a new fashion trend 'Color Blocking' into the 'trends' table
CREATE TABLE trends (id INT PRIMARY KEY,trend_name VARCHAR(50));
INSERT INTO trends (id, trend_name) VALUES (1, 'Color Blocking');
What is the maximum salary in the 'manufacturing' industry?
CREATE TABLE if not exists salaries5 (id INT,industry TEXT,region TEXT,salary REAL);INSERT INTO salaries5 (id,industry,region,salary) VALUES (1,'manufacturing','east',60000),(2,'retail','west',50000);
SELECT MAX(salary) FROM salaries5 WHERE industry = 'manufacturing';
display the names of researchers who published more than 10 articles on climate change
CREATE TABLE researchers (researcher_id INT PRIMARY KEY,researcher_name TEXT); CREATE TABLE publications (publication_id INT PRIMARY KEY,researcher_id INT,title TEXT,topic TEXT); INSERT INTO researchers (researcher_id,researcher_name) VALUES (1,'Dr. Jane Smith'); INSERT INTO publications (publication_id,researcher_id,title,topic) VALUES (1,1,'Climate Change Impact','climate change');
SELECT r.researcher_name FROM researchers r INNER JOIN publications p ON r.researcher_id = p.researcher_id WHERE p.topic = 'climate change' GROUP BY r.researcher_id HAVING COUNT(p.publication_id) > 10;
Update the "country" to 'Germany' for the record in the "tech_for_good" table where the "tool_name" is 'GreenTech'
CREATE TABLE tech_for_good (tool_name VARCHAR(255),country VARCHAR(255),date DATE,effectiveness_score INT); INSERT INTO tech_for_good (tool_name,country,date,effectiveness_score) VALUES ('EcoTech','Brazil','2022-04-01',5),('GreenTech','Argentina','2022-05-01',4),('Tech4Good','Colombia','2022-06-01',6);
UPDATE tech_for_good SET country = 'Germany' WHERE tool_name = 'GreenTech';
What is the change in pollution level between consecutive years for each ocean region?
CREATE TABLE pollution_changes (id INT,region TEXT,year INT,level FLOAT); INSERT INTO pollution_changes (id,region,year,level) VALUES (1,'Atlantic',2020,8.4),(2,'Pacific',2020,9.1),(3,'Indian',2020,7.7);
SELECT region, EXTRACT(YEAR FROM incident_date) AS year, LAG(level) OVER (PARTITION BY region ORDER BY year) - level AS change FROM pollution_changes, (SELECT GENERATE_SERIES(2019, 2022, 1) AS incident_date) AS seq WHERE seq.incident_date = pollution_changes.year;
What are the titles and creation years of all artworks with 'landscape' in the title and created before 1900?
CREATE TABLE Artworks (artwork_id INT,title TEXT,creation_year INT); INSERT INTO Artworks (artwork_id,title,creation_year) VALUES (1,'The Hay Wain',1821),(2,'The Fighting Temeraire',1839);
SELECT title, creation_year FROM Artworks WHERE title LIKE '%landscape%' AND creation_year < 1900;
Count the number of startups founded by persons with disabilities each year
CREATE TABLE diversity (company_id INT,founder_disability TEXT); INSERT INTO diversity (company_id,founder_disability) VALUES (1,'Hearing Impairment'); INSERT INTO diversity (company_id,founder_disability) VALUES (2,'Mental Health Condition');
SELECT founding_year, COUNT(*) FROM company c INNER JOIN diversity d ON c.id = d.company_id WHERE founder_disability IS NOT NULL GROUP BY founding_year;
How many unique vehicles have been used in each route over the last 30 days?
CREATE TABLE vehicle_routes (vehicle_id INT,route_id INT,date DATE); INSERT INTO vehicle_routes (vehicle_id,route_id,date) VALUES (101,101,'2022-01-01'),(102,101,'2022-01-02'),(103,102,'2022-01-01'),(104,102,'2022-01-02'),(105,103,'2022-01-01'),(106,103,'2022-01-02');
SELECT route_id, COUNT(DISTINCT vehicle_id) FROM vehicle_routes WHERE date >= CURDATE() - INTERVAL 30 DAY GROUP BY route_id;
What is the total revenue for each category of dishes in Australia?
CREATE TABLE sales (id INT,dish_id INT,date DATE,quantity INT,price DECIMAL(5,2));CREATE VIEW dishes_view AS SELECT d.id,d.name,c.category FROM dishes d JOIN categories c ON d.category_id = c.id;
SELECT c.category, SUM(s.quantity * s.price) AS total_revenue FROM sales s JOIN dishes_view d ON s.dish_id = d.id JOIN categories c ON d.category = c.id WHERE c.country = 'Australia' GROUP BY c.category;
Identify bioprocess engineers with more than 5 years of experience.
CREATE TABLE engineers (id INT,name VARCHAR(50),specialty VARCHAR(50),location VARCHAR(50),years_of_experience INT);
SELECT name FROM engineers WHERE specialty = 'bioprocess' AND years_of_experience > 5;
What is the total revenue generated by theater performances in the past two years?
CREATE TABLE Events (event_name TEXT,year INT,revenue INT); INSERT INTO Events (event_name,year,revenue) VALUES ('Theater Performance',2020,10000),('Theater Performance',2021,12000);
SELECT SUM(revenue) FROM Events WHERE event_name = 'Theater Performance' AND year IN (2020, 2021);
Which excavation sites in Egypt have yielded gold artifacts?
CREATE TABLE Sites (SiteID int,SiteName text,Location text); CREATE TABLE Artifacts (ArtifactID int,ArtifactName text,SiteID int,Material text);
SELECT Sites.SiteName FROM Sites INNER JOIN Artifacts ON Sites.SiteID = Artifacts.SiteID WHERE Material = 'Gold';
Delete records of soldiers who were dismissed for misconduct from the soldiers_discharge_data table
CREATE TABLE soldiers_discharge_data (soldier_id INT,name VARCHAR(50),rank VARCHAR(50),discharge_type VARCHAR(50),discharge_date DATE);
DELETE FROM soldiers_discharge_data WHERE discharge_type = 'misconduct';
What is the total revenue generated from memberships by gender?
CREATE TABLE Members (MemberID INT,Gender VARCHAR(10),MembershipType VARCHAR(20),MembershipFee DECIMAL(5,2)); INSERT INTO Members (MemberID,Gender,MembershipType,MembershipFee) VALUES (1,'Male','Premium',50.00),(2,'Female','Basic',30.00),(3,'Non-binary','Premium',50.00);
SELECT Gender, SUM(MembershipFee) AS TotalRevenue FROM Members GROUP BY Gender;
Find the number of satellites in the space_debris table, grouped by country order by the count in descending order
CREATE TABLE space_debris (id INT,name VARCHAR(50),type VARCHAR(50),country VARCHAR(50),launch_date DATE);
SELECT country, COUNT(*) as satellite_count FROM space_debris GROUP BY country ORDER BY satellite_count DESC;
What is the total quantity of fair trade products, pivoted by quarter?
CREATE TABLE sales (sale_id INT,product_id INT,quantity INT,sale_date DATE,is_fair_trade BOOLEAN); INSERT INTO sales (sale_id,product_id,quantity,sale_date,is_fair_trade) VALUES (1,1,20,'2021-01-01',true); CREATE TABLE products (product_id INT,product_name VARCHAR(255)); INSERT INTO products (product_id,product_name) VALUES (1,'Fair Trade Coffee');
SELECT EXTRACT(QUARTER FROM sale_date) AS quarter, is_fair_trade, SUM(quantity) AS total_quantity FROM sales JOIN products ON sales.product_id = products.product_id WHERE is_fair_trade = true GROUP BY quarter, is_fair_trade;
Update the plastic recycling rate for Europe in 2018 to 0.62.
CREATE TABLE recycling_rates (year INT,region TEXT,plastic_rate FLOAT,paper_rate FLOAT); INSERT INTO recycling_rates (year,region,plastic_rate,paper_rate) VALUES (2018,'Asia',0.35,0.60),(2018,'Europe',NULL,0.75);
UPDATE recycling_rates SET plastic_rate = 0.62 WHERE year = 2018 AND region = 'Europe';
What is the total carbon offset of buildings in a given neighborhood?
CREATE TABLE Neighborhood (neighborhood_id INT,neighborhood_name VARCHAR(50)); CREATE TABLE Building (building_id INT,building_name VARCHAR(50),building_type VARCHAR(50),carbon_offset INT,neighborhood_id INT);
SELECT SUM(Building.carbon_offset) as total_carbon_offset FROM Building JOIN Neighborhood ON Building.neighborhood_id = Neighborhood.neighborhood_id WHERE Neighborhood.neighborhood_name = 'NeighborhoodName';
What is the maximum daily transaction volume for any digital asset in the 'developed_markets' schema?
CREATE SCHEMA developed_markets; CREATE TABLE developed_markets.digital_assets (asset_name VARCHAR(10),daily_transaction_volume BIGINT); INSERT INTO developed_markets.digital_assets (asset_name,daily_transaction_volume) VALUES ('AssetG',12000000),('AssetH',11000000),('AssetI',10000000),('AssetJ',9000000),('AssetK',8000000);
SELECT MAX(daily_transaction_volume) FROM developed_markets.digital_assets;
Find the average age of male policyholders.
CREATE TABLE Policyholders (id INT,first_name VARCHAR(50),last_name VARCHAR(50),dob DATE,gender VARCHAR(10),address VARCHAR(255),city VARCHAR(50),state VARCHAR(50),zip_code VARCHAR(10)); INSERT INTO Policyholders (id,first_name,last_name,dob,gender,address,city,state,zip_code) VALUES (1003,'Mike','Johnson','1965-02-12','Male','789 Elm St','Bigtown','CA','90123'); INSERT INTO Policyholders (id,first_name,last_name,dob,gender,address,city,state,zip_code) VALUES (1004,'Sara','Williams','1998-09-08','Female','321 Maple Ave','Smalltown','TX','78901');
SELECT id, first_name, last_name, DATEDIFF(CURDATE(), dob)/365.25 AS age, gender FROM Policyholders WHERE gender = 'Male';
Display the number of employees and their positions in the 'employees' table for unions with names starting with 'A'
CREATE TABLE labor_unions (id INT,union_name VARCHAR(50),members INT); CREATE TABLE employees (id INT,union_id INT,name VARCHAR(50),position VARCHAR(50));
SELECT e.name, e.position FROM employees e JOIN labor_unions l ON e.union_id = l.id WHERE l.union_name LIKE 'A%';
Display the names and maximum depths of all underwater trenches.
CREATE TABLE underwater_trenches (trench_name TEXT,max_depth_m INT); INSERT INTO underwater_trenches (trench_name,max_depth_m) VALUES ('Mariana Trench',10994),('Tonga Trench',10882),('Kermadec Trench',10047);
SELECT trench_name, max_depth_m FROM underwater_trenches;
What is the maximum number of followers for users who have posted about veganism in the last month?
CREATE TABLE users (id INT,followers INT); CREATE TABLE posts (id INT,user_id INT,content TEXT,created_at DATETIME);
SELECT MAX(users.followers) FROM users INNER JOIN posts ON users.id = posts.user_id WHERE posts.content LIKE '%veganism%' AND posts.created_at >= DATE_SUB(NOW(), INTERVAL 1 MONTH);
Calculate the total production cost for recycled polyester garments.
CREATE TABLE recycled_polyester_garments (id INT,production_cost DECIMAL); INSERT INTO recycled_polyester_garments (id,production_cost) VALUES (1,32.50),(2,35.00),(3,37.50);
SELECT SUM(production_cost) FROM recycled_polyester_garments;
Find the mining operations that have a higher than average number of employees, and also have an environmental impact score above the average.
CREATE TABLE mining_operations (id INT,name VARCHAR(50),num_employees INT,environmental_impact_score INT);
SELECT name FROM mining_operations WHERE num_employees > (SELECT AVG(num_employees) FROM mining_operations) AND environmental_impact_score > (SELECT AVG(environmental_impact_score) FROM mining_operations);
What is the average price of Fair Trade certified products sold by vendors in California?
CREATE TABLE Vendors (VendorID INT,VendorName VARCHAR(50),State VARCHAR(50)); INSERT INTO Vendors (VendorID,VendorName,State) VALUES (1,'VendorA','California'); CREATE TABLE Products (ProductID INT,ProductName VARCHAR(50),Price DECIMAL(5,2),IsFairTrade BOOLEAN); INSERT INTO Products (ProductID,ProductName,Price,IsFairTrade) VALUES (1,'Product1',15.99,true),(2,'Product2',12.49,false)
SELECT AVG(Price) FROM Products JOIN Vendors ON Products.VendorID = Vendors.VendorID WHERE Vendors.State = 'California' AND IsFairTrade = true;
Delete the records of players who have not played any games in the last 6 months.
CREATE TABLE GameSessions (SessionID INT,PlayerID INT,SessionDate DATE); INSERT INTO GameSessions (SessionID,PlayerID,SessionDate) VALUES (1,1,'2021-01-01'),(2,2,'2021-06-01'),(3,3,'2021-03-01'),(4,5,'2021-02-01');
DELETE FROM GameSessions WHERE PlayerID IN (SELECT PlayerID FROM GameSessions WHERE SessionDate < DATE_SUB(CURDATE(), INTERVAL 6 MONTH));
Show the average age of fans who purchased VIP tickets
CREATE TABLE fan_demographics (fan_id INT,age INT,ticket_type VARCHAR(10));
SELECT AVG(age) FROM fan_demographics WHERE ticket_type = 'VIP';
How many building permits were issued in 'California' and 'Texas' between 2018 and 2020?
CREATE TABLE building_permits (state TEXT,year INT,permits_issued INT); INSERT INTO building_permits (state,year,permits_issued) VALUES ('California',2018,1200),('California',2019,1500),('California',2020,1700),('Texas',2018,2000),('Texas',2019,2500),('Texas',2020,2700);
SELECT SUM(permits_issued) FROM building_permits WHERE state IN ('California', 'Texas') AND year BETWEEN 2018 AND 2020;
What is the enrollment rate of graduate students in STEM programs per continent?
CREATE TABLE students (id INT,name VARCHAR(100),field_of_study VARCHAR(50),country VARCHAR(50),continent VARCHAR(50)); INSERT INTO students VALUES (1,'Avery Johnson','Physics','Canada','North America');
SELECT continent, COUNT(*) FROM students WHERE field_of_study IN ('Computer Science', 'Mathematics', 'Engineering', 'Physics') GROUP BY continent;
What is the average severity of security incidents in each region for the last year?
CREATE TABLE security_incidents (id INT,region VARCHAR(50),severity INT,incident_date DATE); INSERT INTO security_incidents (id,region,severity,incident_date) VALUES (1,'North America',7,'2022-01-01'),(2,'Europe',6,'2022-01-02'),(3,'Asia',8,'2022-01-03'); CREATE TABLE regions (id INT,name VARCHAR(50)); INSERT INTO regions (id,name) VALUES (1,'North America'),(2,'Europe'),(3,'Asia'),(4,'South America'),(5,'Africa');
SELECT r.name, AVG(si.severity) as average_severity FROM security_incidents si JOIN regions r ON si.region = r.name WHERE si.incident_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR) GROUP BY r.name;
List all exits that happened in Q1 2018
CREATE TABLE exits (id INT,startup_id INT,exit_date DATE,exit_type TEXT);
SELECT * FROM exits WHERE exit_date BETWEEN '2018-01-01' AND '2018-03-31';
What is the 'total_area' planted with 'vegetables' in the 'farm_plots' table?
CREATE TABLE farm_plots (id INT,farm_id INT,plot_number INT,crop VARCHAR(50),total_area FLOAT);
SELECT SUM(total_area) FROM farm_plots WHERE crop = 'vegetables';
What is the average salary of male and female employees, partitioned by job title?
CREATE TABLE Employees (EmployeeID INT,Gender VARCHAR(10),JobTitle VARCHAR(50),Salary INT); INSERT INTO Employees (EmployeeID,Gender,JobTitle,Salary) VALUES (1,'Male','Manager',70000),(2,'Female','Manager',65000),(3,'Male','Developer',60000),(4,'Female','Developer',62000);
SELECT JobTitle, AVG(CASE WHEN Gender = 'Male' THEN Salary ELSE NULL END) AS Avg_Male_Salary, AVG(CASE WHEN Gender = 'Female' THEN Salary ELSE NULL END) AS Avg_Female_Salary FROM Employees GROUP BY JobTitle;
Show the UNION of 'sports_team_a_fans' and 'sports_team_b_fans' tables
CREATE TABLE sports_team_a_fans (fan_id INT,age INT,gender VARCHAR(10),favorite_player VARCHAR(20)); INSERT INTO sports_team_a_fans (fan_id,age,gender,favorite_player) VALUES (1,25,'Female','Player A'),(2,35,'Male','Player B'),(3,45,'Non-binary','Player C'); CREATE TABLE sports_team_b_fans (fan_id INT,age INT,gender VARCHAR(10),favorite_player VARCHAR(20)); INSERT INTO sports_team_b_fans (fan_id,age,gender,favorite_player) VALUES (4,30,'Male','Player D'),(5,40,'Female','Player E'),(6,50,'Non-binary','Player F');
SELECT * FROM sports_team_a_fans UNION SELECT * FROM sports_team_b_fans;
What is the total number of comments on posts related to mental health, published by users in Japan, in the month of February 2022?
CREATE TABLE posts (post_id INT,user_id INT,followers INT,post_date DATE,content TEXT); CREATE TABLE comments (comment_id INT,post_id INT,user_id INT,comment_date DATE,comment_text TEXT);
SELECT SUM(c.comments) FROM posts p JOIN comments c ON p.post_id = c.post_id WHERE p.content LIKE '%mental health%' AND p.country = 'Japan' AND p.post_date >= '2022-02-01' AND p.post_date < '2022-03-01';
What is the suicide rate in New Zealand?
CREATE TABLE Suicide (ID INT,Country VARCHAR(100),Year INT,SuicideRate FLOAT); INSERT INTO Suicide (ID,Country,Year,SuicideRate) VALUES (1,'New Zealand',2020,12);
SELECT SuicideRate FROM Suicide WHERE Country = 'New Zealand' AND Year = 2020;
What was the total waste generation by material type in 2020 for New York City?
CREATE TABLE waste_generation (city VARCHAR(255),material VARCHAR(255),year INT,quantity INT); INSERT INTO waste_generation (city,material,year,quantity) VALUES ('New York City','Plastic',2020,15000),('New York City','Paper',2020,20000),('New York City','Glass',2020,10000),('New York City','Metal',2020,12000);
SELECT material, SUM(quantity) FROM waste_generation WHERE city = 'New York City' AND year = 2020 GROUP BY material;
What is the average daily delay for each subway line?
CREATE TABLE delays (route_id INT,delay DECIMAL(3,2),date DATE); INSERT INTO delays (route_id,delay,date) VALUES (1,3.1,'2022-02-01'),(1,4.2,'2022-02-02'),(2,2.9,'2022-02-01'),(2,3.0,'2022-02-02'); CREATE TABLE subway_routes (id INT,name VARCHAR(50),type VARCHAR(10)); INSERT INTO subway_routes (id,name,type) VALUES (1,'Green Line','Subway'),(2,'Red Line','Subway');
SELECT r.name, AVG(d.delay) AS avg_delay FROM delays d JOIN subway_routes r ON d.route_id = r.id GROUP BY r.name;
Which programs had the highest and lowest donation amounts in H2 2021?
CREATE TABLE program_donations (donation_id INT,program_id INT,donor_id INT,donation_amount FLOAT,donation_date DATE); INSERT INTO program_donations (donation_id,program_id,donor_id,donation_amount,donation_date) VALUES (1,1,1,200,'2021-07-01'); INSERT INTO program_donations (donation_id,program_id,donor_id,donation_amount,donation_date) VALUES (2,2,2,50,'2021-10-03');
SELECT program_id, donation_amount FROM (SELECT program_id, donation_amount, ROW_NUMBER() OVER (ORDER BY donation_amount DESC) AS high_donation, ROW_NUMBER() OVER (ORDER BY donation_amount ASC) AS low_donation FROM program_donations WHERE EXTRACT(YEAR FROM donation_date) = 2021 AND EXTRACT(MONTH FROM donation_date) BETWEEN 7 AND 12) AS subquery WHERE high_donation = 1 OR low_donation = 1;
What is the average length of all tunnels in the "tunnels" table, grouped by the type of tunnel material?
CREATE TABLE IF NOT EXISTS public.tunnels (id SERIAL PRIMARY KEY,name TEXT,length REAL,material TEXT); INSERT INTO public.tunnels (name,length,material) SELECT 'Tunnel001',500.0,'Concrete' FROM generate_series(1,10); INSERT INTO public.tunnels (name,length,material) SELECT 'Tunnel002',700.0,'Steel' FROM generate_series(1,10); INSERT INTO public.tunnels (name,length,material) SELECT 'Tunnel003',300.0,'Concrete' FROM generate_series(1,10);
SELECT material, AVG(length) FROM public.tunnels GROUP BY material;