instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
What is the name and ID of the longest dam in the 'Dams' table?
CREATE TABLE Dams (ID INT,Name VARCHAR(50),Location VARCHAR(50),Length FLOAT,YearBuilt INT); INSERT INTO Dams (ID,Name,Location,Length,YearBuilt) VALUES (1,'Hoover Dam','Nevada/Arizona border',247.0,1936); INSERT INTO Dams (ID,Name,Location,Length,YearBuilt) VALUES (2,'Oroville Dam','Butte County,CA',2302.0,1968);
SELECT Name, ID FROM Dams WHERE Length = (SELECT MAX(Length) FROM Dams);
What is the most popular sustainable fashion trend among customers of different sizes in Australia?
CREATE TABLE SustainableTrends (id INT,trend VARCHAR(255),sustainability_score INT); INSERT INTO SustainableTrends (id,trend,sustainability_score) VALUES (1,'Organic Cotton T-Shirt',90),(2,'Recycled Polyester Hoodie',80),(3,'Bamboo Viscose Pants',85); CREATE TABLE CustomerSizes (id INT,size VARCHAR(255),country VARCHAR...
SELECT st.trend, c.size, MAX(c.percentage) AS popularity FROM SustainableTrends st CROSS JOIN CustomerSizes c WHERE c.country = 'Australia' GROUP BY st.trend, c.size;
Which players have the highest number of wins in multiplayer matches?
CREATE TABLE Matches (MatchID int,PlayerID int,Game varchar(255),MatchResult varchar(255)); INSERT INTO Matches VALUES (1,1,'CS:GO','Win'),(2,2,'CS:GO','Loss'),(3,1,'Dota 2','Win'),(4,3,'Dota 2','Win');
SELECT PlayerID, COUNT(*) as Wins FROM Matches WHERE MatchResult = 'Win' GROUP BY PlayerID ORDER BY Wins DESC;
Which volunteers have donated the most money?
CREATE TABLE Volunteers (VolunteerID int,Name varchar(50),Donation decimal(10,2)); INSERT INTO Volunteers (VolunteerID,Name,Donation) VALUES (1,'John Doe',100.00),(2,'Jane Smith',200.00),(3,'Mike Johnson',50.00);
SELECT Name, SUM(Donation) as TotalDonations FROM Volunteers GROUP BY Name ORDER BY TotalDonations DESC
How many units of organic cotton garments were sold by each store in the 'West' region in Q3 of 2021?
CREATE TABLE Stores (id INT,name VARCHAR(255),region VARCHAR(255)); INSERT INTO Stores (id,name,region) VALUES (1,'Store A','West'),(2,'Store B','West'),(3,'Store C','East'),(4,'Store D','East'); CREATE TABLE Organic_Cotton_Sales (id INT,store_id INT,quarter INT,year INT,units INT); INSERT INTO Organic_Cotton_Sales (id...
SELECT s.name, SUM(o.units) FROM Organic_Cotton_Sales o JOIN Stores s ON o.store_id = s.id WHERE o.quarter = 3 AND o.year = 2021 AND s.region = 'West' GROUP BY s.name;
Insert a new drug with a given code and name into the drug table
CREATE TABLE drug (drug_code CHAR(5),drug_name VARCHAR(100));
INSERT INTO drug (drug_code, drug_name) VALUES ('DR003', 'DrugC');
Identify the departments with the highest and lowest number of employees
CREATE TABLE Departments (id INT,department_name VARCHAR(50),employee_id INT); CREATE TABLE Employees (id INT,salary DECIMAL(10,2));
SELECT department_name, COUNT(*) AS employees_count FROM Departments JOIN Employees ON Departments.employee_id = Employees.id GROUP BY department_name ORDER BY employees_count DESC, department_name LIMIT 1; SELECT department_name, COUNT(*) AS employees_count FROM Departments JOIN Employees ON Departments.employee_id = ...
What is the total donation amount per month in 2021?
CREATE TABLE donations (id INT,donation_amount DECIMAL(10,2),donation_date DATE); INSERT INTO donations (id,donation_amount,donation_date) VALUES (1,50.00,'2021-01-01'); INSERT INTO donations (id,donation_amount,donation_date) VALUES (2,100.00,'2021-02-01');
SELECT DATE_FORMAT(donation_date, '%Y-%m') as month, SUM(donation_amount) as total_donations FROM donations WHERE donation_date >= '2021-01-01' AND donation_date < '2022-01-01' GROUP BY month;
What is the maximum explanation score for each model, and how many times does each model achieve that score?
CREATE TABLE explainability_audits (id INT,model_id INT,explanation_score INT,created_at DATETIME); INSERT INTO explainability_audits (id,model_id,explanation_score,created_at) VALUES (1,1,7,'2021-01-01'); INSERT INTO explainability_audits (id,model_id,explanation_score,created_at) VALUES (2,2,8,'2021-01-02'); INSERT I...
SELECT model_id, MAX(explanation_score) as max_explanation_score, COUNT(*) as count FROM explainability_audits GROUP BY model_id;
Which wildlife habitats in 'North America' have an area larger than 700?
CREATE TABLE wildlife_habitats (id INT,name VARCHAR(50),area FLOAT,region VARCHAR(50)); INSERT INTO wildlife_habitats (id,name,area,region) VALUES (1,'Habitat 1',800.0,'North America'),(2,'Habitat 2',600.0,'South America');
SELECT name FROM wildlife_habitats WHERE area > 700 AND region = 'North America';
How many renewable energy projects are in Canada with an installed capacity greater than 500?
CREATE TABLE renewable_projects (id INT,project_name VARCHAR(100),country VARCHAR(50),capacity FLOAT); INSERT INTO renewable_projects (id,project_name,country,capacity) VALUES (1,'Solar Farm Canada','Canada',789.12),(2,'Wind Farm Canada','Canada',1500.78),(3,'Hydro Plant Canada','Canada',450.34);
SELECT COUNT(*) FROM renewable_projects WHERE country = 'Canada' AND capacity > 500;
How many volunteers were engaged in each program in 2020, sorted by the highest number of volunteers?
CREATE TABLE VolunteerPrograms (VolunteerID INT,ProgramID INT,VolunteerDate DATE); INSERT INTO VolunteerPrograms (VolunteerID,ProgramID,VolunteerDate) VALUES (1,1,'2020-01-01'),(2,1,'2020-02-01'),(3,2,'2020-03-01');
SELECT Programs.ProgramName, COUNT(DISTINCT VolunteerPrograms.VolunteerID) as VolunteerCount FROM Programs INNER JOIN VolunteerPrograms ON Programs.ProgramID = VolunteerPrograms.ProgramID WHERE YEAR(VolunteerPrograms.VolunteerDate) = 2020 GROUP BY Programs.ProgramName ORDER BY VolunteerCount DESC;
List all users who signed up using email
CREATE TABLE users (id INT PRIMARY KEY,name VARCHAR(50),email VARCHAR(50),signup_date DATE,signup_source VARCHAR(20));
SELECT * FROM users WHERE signup_source = 'email';
Insert a new marine species 'Giant Squid' in the 'Pacific Ocean' and return the ID of the inserted record.
CREATE TABLE marine_species (species_id SERIAL PRIMARY KEY,species_name VARCHAR(50),ocean_name VARCHAR(50),sighting_date DATE);
INSERT INTO marine_species (species_name, ocean_name, sighting_date) VALUES ('Giant Squid', 'Pacific Ocean', '2022-08-01') RETURNING species_id;
What is the minimum depth of all stations in the Deep Ocean Exploration database?
CREATE TABLE DeepOceanExploration (id INT,name TEXT,latitude REAL,longitude REAL,depth REAL); INSERT INTO DeepOceanExploration (id,name,latitude,longitude,depth) VALUES (1,'Station 1',15.4948,-61.3704,6000); INSERT INTO DeepOceanExploration (id,name,latitude,longitude,depth) VALUES (2,'Station 2',44.6419,-63.5742,5500)...
SELECT MIN(depth) FROM DeepOceanExploration;
What is the maximum total assets value for clients with a primary residence in California in Q4 2022?
CREATE TABLE clients (client_id INT,name VARCHAR(50),total_assets DECIMAL(10,2),primary_residence VARCHAR(50));CREATE TABLE transactions (transaction_id INT,client_id INT,transaction_date DATE);
SELECT MAX(total_assets) FROM clients c INNER JOIN transactions t ON c.client_id = t.client_id WHERE c.primary_residence = 'California' AND t.transaction_date BETWEEN '2022-10-01' AND '2022-12-31'
What is the difference in total runs scored between the home and away games for each team in the 2021 MLB season?
CREATE TABLE mlb_season (team_id INT,team_name VARCHAR(50),games_played INT,runs_home INT,runs_away INT); INSERT INTO mlb_season (team_id,team_name,games_played,runs_home,runs_away) VALUES (1,'Los Angeles Dodgers',162,834,653);
SELECT team_name, (runs_home - runs_away) as diff FROM mlb_season;
What is the average age of users who liked articles related to climate change?
CREATE TABLE articles (id INT,title TEXT,category TEXT,likes INT); INSERT INTO articles (id,title,category,likes) VALUES (1,'Climate Crisis Explained','climate_change',1500); CREATE TABLE users (id INT,name TEXT,age INT); INSERT INTO users (id,name,age) VALUES (1,'John Doe',35),(2,'Jane Smith',42);
SELECT AVG(age) FROM users JOIN (SELECT user_id FROM article_likes WHERE article_category = 'climate_change') AS liked_articles ON users.id = liked_articles.user_id;
Count the number of players in each position group in the NHL.
CREATE TABLE nhl_player_positions (id INT,name VARCHAR(100),position VARCHAR(50)); INSERT INTO nhl_player_positions (id,name,position) VALUES (1,'Alex Ovechkin','Left Wing'),(2,'Connor McDavid','Center'),(3,'Sidney Crosby','Center'),(4,'Patrick Kane','Right Wing'),(5,'Victor Hedman','Defenseman'),(6,'Andrei Vasilevskiy...
SELECT position, COUNT(*) FROM nhl_player_positions GROUP BY position;
What is the total number of multimodal trips taken in New York City?
CREATE TABLE multimodal_trips (id INT,trips INT,city VARCHAR(50));
SELECT SUM(trips) FROM multimodal_trips WHERE city = 'New York City';
What is the total number of carbon offset programs in the carbon_offset_programs table?
CREATE TABLE carbon_offset_programs (program_id INT,program_name TEXT,start_year INT);
SELECT COUNT(*) FROM carbon_offset_programs;
What is the average quantity of eco-friendly materials sourced from South America?
CREATE TABLE sourcing (id INT,region TEXT,quantity INT); INSERT INTO sourcing (id,region,quantity) VALUES (1,'Asia',1200),(2,'Europe',800),(3,'Africa',700),(4,'South America',900),(5,'North America',1100);
SELECT AVG(quantity) FROM sourcing WHERE region = 'South America';
What was the total number of public services delivered in Q1, Q2, and Q3 of 2021?
CREATE TABLE PublicServices (Quarter INT,Year INT,ServiceCount INT); INSERT INTO PublicServices VALUES (1,2021,1200),(2,2021,1500),(3,2021,1300);
SELECT SUM(ServiceCount) FROM PublicServices WHERE Year = 2021 AND Quarter IN (1, 2, 3);
How many startups in the transportation sector were founded by a person from Oceania?
CREATE TABLE companies (id INT,name TEXT,industry TEXT,founder_region TEXT); INSERT INTO companies (id,name,industry,founder_region) VALUES (1,'TransportOceania','Transportation','Oceania'); INSERT INTO companies (id,name,industry,founder_region) VALUES (2,'GreenTechMale','GreenTech','Europe');
SELECT COUNT(*) FROM companies WHERE industry = 'Transportation' AND founder_region = 'Oceania';
What is the total duration (in minutes) of all yoga classes taken by users with the first name 'Amy'?
CREATE TABLE yoga_classes (class_id INT,user_id INT,duration INT,first_name VARCHAR(10));
SELECT SUM(duration) FROM yoga_classes WHERE first_name = 'Amy';
What is the revenue generated by each category of menu items last month?
CREATE TABLE MenuCategory (MenuItemID INT,MenuCategory VARCHAR(50)); INSERT INTO MenuCategory (MenuItemID,MenuCategory) VALUES (1,'Salads'),(2,'Sandwiches'),(3,'Desserts'); CREATE TABLE SalesData (SaleID INT,MenuItemID INT,SaleAmount DECIMAL(5,2),SaleDate DATE); INSERT INTO SalesData (SaleID,MenuItemID,SaleAmount,SaleD...
SELECT MenuCategory, SUM(SaleAmount) FROM SalesData INNER JOIN MenuCategory ON SalesData.MenuItemID = MenuCategory.MenuItemID WHERE SaleDate BETWEEN DATEADD(month, -1, GETDATE()) AND GETDATE() GROUP BY MenuCategory;
Delete all smart_city_sensors records with a 'sensor_type' of 'temperature' and a 'reading' value greater than 40.
CREATE TABLE smart_city_sensors (sensor_id INT,sensor_type VARCHAR(255),reading DECIMAL(5,2)); INSERT INTO smart_city_sensors (sensor_id,sensor_type,reading) VALUES (1,'temperature',35.50),(2,'humidity',60.00),(3,'temperature',45.25),(4,'pressure',1013.25);
DELETE FROM smart_city_sensors WHERE sensor_type = 'temperature' AND reading > 40;
What is the total funding received by companies founded by individuals from rural areas in the agriculture industry?
CREATE TABLE companies (id INT,name TEXT,industry TEXT,founding_date DATE,founder_location TEXT); INSERT INTO companies (id,name,industry,founding_date,founder_location) VALUES (1,'AgriFuture','Agriculture','2016-01-01','Rural');
SELECT SUM(funding_amount) FROM funding_records JOIN companies ON funding_records.company_id = companies.id WHERE companies.industry = 'Agriculture' AND companies.founder_location = 'Rural';
Show the number of social media posts related to disinformation, grouped by platform, for the month of January 2021.
CREATE TABLE social_media_posts (id INT,platform VARCHAR(50),content TEXT,post_date DATE); INSERT INTO social_media_posts (id,platform,content,post_date) VALUES (1,'Twitter','Disinformation tweet','2021-01-01'),(2,'Facebook','Disinformation post','2021-01-02'),(3,'Twitter','Another disinformation tweet','2021-01-03');
SELECT platform, COUNT(*) as post_count FROM social_media_posts WHERE post_date >= '2021-01-01' AND post_date < '2021-02-01' AND content LIKE '%disinformation%' GROUP BY platform;
Find dishes that contain both tomatoes and onions as ingredients.
CREATE TABLE ingredients (id INT,name VARCHAR(255)); INSERT INTO ingredients (id,name) VALUES (1,'Tomatoes'),(2,'Onions'),(3,'Garlic'),(4,'Cheese'),(5,'Tofu'),(6,'Chicken'),(7,'Beef'),(8,'Tomato Sauce'),(9,'Onion Rings'); CREATE TABLE dish_ingredients (dish_id INT,ingredient_id INT); INSERT INTO dish_ingredients (dish_...
SELECT dish_ingredients.dish_id FROM dish_ingredients INNER JOIN ingredients ON dish_ingredients.ingredient_id = ingredients.id WHERE ingredients.name IN ('Tomatoes', 'Onions') GROUP BY dish_ingredients.dish_id HAVING COUNT(DISTINCT ingredients.name) = 2;
What is the average visitor count for exhibitions?
CREATE TABLE Exhibitions (id INT,name TEXT,visitor_count INT); INSERT INTO Exhibitions (id,name,visitor_count) VALUES (1,'Dinosaurs',1000),(2,'Egypt',800);
SELECT AVG(visitor_count) FROM Exhibitions;
Delete a restorative justice circle from the 'circles' table
CREATE TABLE circles (circle_id INT PRIMARY KEY,circle_date DATE,circle_time TIME,location VARCHAR(255),facilitator_id INT,case_number INT);
DELETE FROM circles WHERE circle_id = 9002 AND case_number = 2022003;
What is the total number of shelters and their capacities in Australia and Canada?
CREATE TABLE shelters (id INT,country VARCHAR(20),name VARCHAR(50),capacity INT); INSERT INTO shelters (id,country,name,capacity) VALUES (1,'Australia','Shelter1',100),(2,'Australia','Shelter2',150),(3,'Canada','Shelter3',200),(4,'Canada','Shelter4',250);
SELECT SUM(capacity) as total_capacity, country FROM shelters GROUP BY country;
How many female and male faculty members are there in the English department?
CREATE TABLE faculty (faculty_id INT,name VARCHAR(50),department VARCHAR(50),gender VARCHAR(10)); INSERT INTO faculty VALUES (1,'Jane Smith','English','Female');
SELECT department, gender, COUNT(*) as count FROM faculty GROUP BY department, gender HAVING department = 'English';
Which programs had the highest increase in total expenses compared to the same quarter last year?
CREATE TABLE programs (id INT,program_name VARCHAR(50),quarter INT,year INT,expenses DECIMAL(10,2)); INSERT INTO programs (id,program_name,quarter,year,expenses) VALUES (1,'Education',1,2021,15000.00),(2,'Health',2,2021,20000.00),(3,'Education',1,2022,17000.00),(4,'Health',2,2022,25000.00);
SELECT program_name, (expenses - (SELECT expenses FROM programs p2 WHERE p2.program_name = programs.program_name AND p2.quarter = programs.quarter AND p2.year = programs.year - 1)) AS difference INTO tmp_table FROM programs ORDER BY difference DESC LIMIT 1; SELECT program_name, difference FROM tmp_table; DROP TABLE tmp...
Count the number of startups founded by immigrants
CREATE TABLE startup (id INT,name TEXT,founding_year INT,founder_immigrant TEXT); INSERT INTO startup (id,name,founding_year,founder_immigrant) VALUES (1,'Acme Inc',2010,'Yes'); INSERT INTO startup (id,name,founding_year,founder_immigrant) VALUES (2,'Beta Corp',2015,'No');
SELECT COUNT(*) FROM startup WHERE founder_immigrant = 'Yes';
How many countries have launched satellites into space?
CREATE TABLE satellites (id INT,country VARCHAR(255)); INSERT INTO satellites (id,country) VALUES (1,'USA'),(2,'Russia'),(3,'China'),(4,'India'),(5,'Japan'),(6,'Germany'),(7,'Italy');
SELECT COUNT(DISTINCT country) FROM satellites;
What is the average duration of successful community development programs in Asia, rounded to the nearest week?
CREATE TABLE community_development (id INT,project_status TEXT,start_date DATE,end_date DATE,country TEXT); INSERT INTO community_development (id,project_status,start_date,end_date,country) VALUES (1,'successful','2016-01-01','2017-01-01','China'),(2,'unsuccessful','2015-01-01','2015-12-31','India'),(3,'successful','20...
SELECT ROUND(AVG(DATEDIFF(end_date, start_date))/7) FROM community_development WHERE project_status = 'successful' AND country IN ('Asia');
What is the average food safety score for each restaurant in the 'San Francisco' region?
CREATE TABLE food_safety_inspections(restaurant VARCHAR(255),region VARCHAR(255),score DECIMAL(3,1)); INSERT INTO food_safety_inspections VALUES ('Restaurant A','San Francisco',92.5),('Restaurant B','San Francisco',87.6),('Restaurant C','San Francisco',95.3);
SELECT region, AVG(score) FROM food_safety_inspections WHERE region = 'San Francisco' GROUP BY region;
Who are the top 5 most streamed K-pop songs in the United States?
CREATE TABLE music_streaming (id INT,user_id INT,artist VARCHAR(50),song VARCHAR(50),genre VARCHAR(20),streamed_on DATE,streams INT); CREATE VIEW song_streams AS SELECT song,streamed_on,SUM(streams) AS total_streams FROM music_streaming GROUP BY song,streamed_on;
SELECT song, total_streams FROM song_streams WHERE genre = 'K-pop' AND user_id IN (SELECT id FROM users WHERE country = 'United States') ORDER BY total_streams DESC LIMIT 5;
What is the average number of publications per faculty member by department?
CREATE TABLE department (id INT,name TEXT); CREATE TABLE faculty (id INT,department_id INT,publications INT);
SELECT d.name, AVG(f.publications) FROM department d JOIN faculty f ON d.id = f.department_id GROUP BY d.name;
How many high-value assets (value > 10000) does each client own?
CREATE TABLE clients (client_id INT,currency VARCHAR(10)); INSERT INTO clients (client_id,currency) VALUES (1,'USD'),(2,'EUR'); CREATE TABLE assets (asset_id INT,client_id INT,value INT); INSERT INTO assets (asset_id,client_id,value) VALUES (1,1,5000),(2,1,7000),(3,2,30000);
SELECT assets.client_id, COUNT(*) FROM assets WHERE assets.value > 10000 GROUP BY assets.client_id;
List the names of the top 5 impact investors in the European Union by total investment.
CREATE TABLE impact_investors (id INT,name TEXT,region TEXT,investment FLOAT); INSERT INTO impact_investors (id,name,region,investment) VALUES (1,'Sustainable Impact Fund','European Union',5000000.0),(2,'Green Investment Group','European Union',3500000.0);
SELECT name FROM impact_investors WHERE region = 'European Union' ORDER BY investment DESC LIMIT 5;
What is the total number of accidents reported for vessels flying the flag of Norway in the Arctic Ocean?
CREATE TABLE Accidents (AccidentID INT,VesselFlag VARCHAR(50),IncidentLocation VARCHAR(50),IncidentYear INT); INSERT INTO Accidents VALUES (1,'Norway','Arctic Ocean',2021),(2,'Marshall Islands','Atlantic Ocean',2020),(3,'Canada','Arctic Ocean',2019);
SELECT COUNT(*) FROM Accidents WHERE VesselFlag = 'Norway' AND IncidentLocation = 'Arctic Ocean';
List the faculty members who have not published any papers, in alphabetical order.
CREATE TABLE faculties (faculty_id INT,name VARCHAR(255),dept_id INT,num_publications INT);
SELECT name FROM faculties WHERE num_publications = 0 ORDER BY name ASC;
What was the average number of refugee camps built per year by org_type "Non-governmental" between 2015 and 2020?
CREATE TABLE refugee_camps (id INT,build_year INT,org_type VARCHAR(20)); INSERT INTO refugee_camps (id,build_year,org_type) VALUES (1,2015,'Non-governmental'),(2,2017,'Governmental'),(3,2019,'Non-governmental'),(4,2020,'Non-governmental');
SELECT AVG(build_year) FROM (SELECT build_year, YEAR(CURRENT_DATE) - build_year AS year_diff FROM refugee_camps WHERE org_type = 'Non-governmental') AS subquery HAVING year_diff BETWEEN 1 AND 6;
What is the total funding received by research projects in the Engineering department, broken down by year?
CREATE TABLE research_projects (id INT,title VARCHAR(255),department VARCHAR(100),funding DECIMAL(10,2),start_date DATE); INSERT INTO research_projects (id,title,department,funding,start_date) VALUES (1,'Robotics Project','Engineering',50000.00,'2019-01-01'),(2,'Automation Project','Engineering',75000.00,'2020-01-01'),...
SELECT YEAR(start_date) as year, SUM(funding) as total_funding FROM research_projects WHERE department = 'Engineering' GROUP BY year;
How many unique fans attended cricket games in the last year, broken down by team and gender?
CREATE TABLE cricket_attendance (fan_id INT,game_date DATE,team VARCHAR(50),gender VARCHAR(50)); INSERT INTO cricket_attendance (fan_id,game_date,team,gender) VALUES (1,'2022-01-01','Mumbai Indians','Male'),(2,'2022-01-02','Chennai Super Kings','Female'),(3,'2022-01-03','Delhi Capitals','Male'),(4,'2022-01-04','Royal C...
SELECT team, gender, COUNT(DISTINCT fan_id) FROM cricket_attendance WHERE game_date >= DATE_SUB(CURDATE(), INTERVAL 1 YEAR) GROUP BY team, gender;
List all threats and their severity
CREATE TABLE threats (threat_id INT,type VARCHAR(255),description VARCHAR(255),severity VARCHAR(255));
SELECT * FROM threats;
How many rural infrastructure projects were completed in the last 5 years in Eastern Europe, broken down by year?
CREATE TABLE rural_infrastructure (id INT,project_status TEXT,completion_date DATE,country TEXT); INSERT INTO rural_infrastructure (id,project_status,completion_date,country) VALUES (1,'completed','2018-03-15','Poland'),(2,'in_progress','2019-12-31','Romania'),(3,'completed','2020-08-01','Hungary');
SELECT YEAR(completion_date) AS "Completion Year", COUNT(*) FROM rural_infrastructure WHERE project_status = 'completed' AND country IN ('Eastern Europe') AND completion_date >= DATE_SUB(NOW(), INTERVAL 5 YEAR) GROUP BY YEAR(completion_date);
How many users registered for virtual tours of cultural heritage sites in the last month?
CREATE TABLE user (id INT,name TEXT,reg_date DATE); CREATE TABLE tour_registration (user_id INT,tour_id INT,registration_date DATE); INSERT INTO user (id,name,reg_date) VALUES (1,'John Doe','2022-05-15'); INSERT INTO tour_registration (user_id,tour_id,registration_date) VALUES (1,1,'2022-05-25');
SELECT COUNT(*) as num_users FROM user JOIN tour_registration ON user.id = tour_registration.user_id WHERE tour_registration.registration_date >= DATEADD(month, -1, GETDATE());
What is the total amount donated by all donors from the United States?
CREATE TABLE Donors (DonorID int,DonorName varchar(50),Country varchar(50)); INSERT INTO Donors (DonorID,DonorName,Country) VALUES (1,'John Doe','United States'); INSERT INTO Donors (DonorID,DonorName,Country) VALUES (2,'Jane Smith','Canada'); CREATE TABLE Donations (DonationID int,DonorID int,DonationAmount decimal(10...
SELECT SUM(Donations.DonationAmount) FROM Donations INNER JOIN Donors ON Donations.DonorID = Donors.DonorID WHERE Donors.Country = 'United States';
List all investment strategies with a risk level above 30 and their associated sectors.
CREATE TABLE investment_strategies (id INT,strategy VARCHAR(50),risk_level INT,sector VARCHAR(20)); INSERT INTO investment_strategies (id,strategy,risk_level,sector) VALUES (1,'Impact Bonds',30,'social impact'),(2,'Green Equity Funds',20,'environment'),(3,'Sustainable Real Estate',40,'real estate');
SELECT strategy, risk_level, sector FROM investment_strategies WHERE risk_level > 30;
What is the total environmental impact score for each racial group, by mineral type, in 2020?
CREATE TABLE RacialImpact (race VARCHAR(50),year INT,mineral VARCHAR(50),score INT); INSERT INTO RacialImpact (race,year,mineral,score) VALUES ('African American',2020,'Gold',90),('Hispanic',2020,'Silver',120),('Asian',2020,'Iron',150);
SELECT context.race, context.mineral, SUM(context.score) as total_score FROM context WHERE context.year = 2020 GROUP BY context.race, context.mineral;
What is the distribution of incident types by region?
CREATE TABLE security_incidents (id INT,incident_date DATE,region VARCHAR(255),incident_type VARCHAR(255)); INSERT INTO security_incidents (id,incident_date,region,incident_type) VALUES (1,'2022-01-05','APAC','Phishing'),(2,'2022-02-10','EMEA','Malware'),(3,'2022-03-15','AMER','SQL Injection'),(4,'2022-04-20','APAC','C...
SELECT region, incident_type, COUNT(*) as incidents_per_region_incident_type FROM security_incidents GROUP BY region, incident_type;
Update the budget for the 'solar_power' project in the 'rural_infrastructure' table to 175000.
CREATE TABLE rural_infrastructure (id INT,project_name VARCHAR(255),budget INT);
UPDATE rural_infrastructure SET budget = 175000 WHERE project_name = 'solar_power';
Calculate the total number of rural development initiatives in Southeast Asia that have a focus on women's empowerment.
CREATE TABLE initiatives (id INT,name TEXT,location TEXT,focus TEXT); INSERT INTO initiatives (id,name,location,focus) VALUES (1,'Microfinance Program','Southeast Asia','Women Empowerment'),(2,'Education Program','Southeast Asia','Youth Development');
SELECT COUNT(DISTINCT initiatives.id) FROM initiatives WHERE initiatives.location = 'Southeast Asia' AND initiatives.focus = 'Women Empowerment';
Show the average ocean temperature for each month in the 'ocean_temperature_data' table.
CREATE TABLE ocean_temperature_data (data_id INT,date DATE,temperature FLOAT);
SELECT EXTRACT(MONTH FROM date), AVG(temperature) FROM ocean_temperature_data GROUP BY EXTRACT(MONTH FROM date);
What is the average investment in green technology projects in the Middle East?
CREATE TABLE green_technology_projects (id INT,region VARCHAR(50),investment FLOAT); INSERT INTO green_technology_projects (id,region,investment) VALUES (1,'Middle East',200000); INSERT INTO green_technology_projects (id,region,investment) VALUES (2,'Middle East',225000);
SELECT AVG(investment) FROM green_technology_projects WHERE region = 'Middle East';
List all suppliers from 'ethical_suppliers' view
CREATE TABLE suppliers (id INT PRIMARY KEY,name VARCHAR(50),country VARCHAR(50),industry VARCHAR(50),ethical_rating INT); INSERT INTO suppliers (id,name,country,industry,ethical_rating) VALUES (1,'Supplier A','USA','Electronics',90),(2,'Supplier B','China','Textiles',70),(3,'Supplier C','India','Machinery',85); CREATE ...
SELECT * FROM ethical_suppliers;
Find the number of unique types of meat products supplied by each supplier?
CREATE TABLE Suppliers(SupplierID INT,Name VARCHAR(50),Type VARCHAR(50));CREATE TABLE MeatProducts(ProductID INT,SupplierID INT,ProductName VARCHAR(50),Quantity INT);INSERT INTO Suppliers VALUES (1,'Supplier A','Meat Supplier'),(2,'Supplier B','Meat Supplier'),(3,'Supplier C','Fruit Supplier');INSERT INTO MeatProducts ...
SELECT s.Name, COUNT(DISTINCT m.ProductName) FROM Suppliers s JOIN MeatProducts m ON s.SupplierID = m.SupplierID GROUP BY s.Name;
List all clinical trials that were conducted in Germany since 2015.
CREATE TABLE clinical_trials (trial_id INT,country VARCHAR(255),start_date DATE); INSERT INTO clinical_trials (trial_id,country,start_date) VALUES (1,'Germany','2016-01-01'),(2,'France','2015-06-15'),(3,'Germany','2017-09-25');
SELECT trial_id, country FROM clinical_trials WHERE country = 'Germany' AND start_date >= '2015-01-01';
What is the total quantity of resources depleted from gold mining in Australia and South Africa?
CREATE TABLE resource_depletion (id INT,location VARCHAR(50),operation_type VARCHAR(50),monthly_resource_depletion INT); INSERT INTO resource_depletion (id,location,operation_type,monthly_resource_depletion) VALUES (1,'Australia','Gold',500),(2,'South Africa','Gold',700),(3,'Canada','Diamond',600);
SELECT SUM(CASE WHEN operation_type = 'Gold' THEN monthly_resource_depletion ELSE 0 END) as total_gold_depletion FROM resource_depletion WHERE location IN ('Australia', 'South Africa');
How many artists in the database are from Asia?
CREATE TABLE artists (id INT,name TEXT,country TEXT); INSERT INTO artists (id,name,country) VALUES (1,'Artist A','China'),(2,'Artist B','Japan'),(3,'Artist C','France');
SELECT COUNT(*) FROM artists WHERE country IN ('China', 'Japan', 'India', 'Korea');
Which athletes are older than 30 years old in the athlete_demographics table?
CREATE TABLE athlete_demographics (id INT,name VARCHAR(50),age INT,sport VARCHAR(50));
SELECT name FROM athlete_demographics WHERE age > 30;
What is the average age of patients with diabetes in the Northern rural areas of Canada?
CREATE TABLE patients (id INT,age INT,has_diabetes BOOLEAN); INSERT INTO patients (id,age,has_diabetes) VALUES (1,50,true),(2,60,false); CREATE TABLE locations (id INT,region VARCHAR,is_rural BOOLEAN); INSERT INTO locations (id,region,is_rural) VALUES (1,'Northern',true),(2,'Southern',false);
SELECT AVG(patients.age) FROM patients INNER JOIN locations ON patients.id = locations.id WHERE patients.has_diabetes = true AND locations.region = 'Northern';
What is the minimum age of policyholders in Florida with 'Auto' policy_type?
INSERT INTO policyholders (id,name,age,gender,policy_type,state) VALUES (4,'Sara Connor',28,'Female','Auto','Florida');
SELECT MIN(age) FROM policyholders WHERE state = 'Florida' AND policy_type = 'Auto';
Show the total number of marine species in the North Pacific Ocean
CREATE TABLE marine_species (species_name TEXT,ocean TEXT,population INTEGER); INSERT INTO marine_species (species_name,ocean,population) VALUES ('Pacific Salmon','North Pacific Ocean',5000000),('Sea Otter','North Pacific Ocean',100000);
SELECT SUM(population) FROM marine_species WHERE ocean = 'North Pacific Ocean';
How many legal technology patents were granted to women-led teams in the last 5 years?
CREATE TABLE Patents (PatentID INT,Year INT,TeamLead GENDER,Technology VARCHAR(20)); INSERT INTO Patents (PatentID,Year,TeamLead,Technology) VALUES (1,2018,'Female','Artificial Intelligence'),(2,2019,'Male','Blockchain'),(3,2020,'Female','Natural Language Processing');
SELECT COUNT(*) FROM Patents WHERE TeamLead = 'Female' AND Year BETWEEN 2017 AND 2022;
Which forests have an average tree height over 45 meters?
CREATE TABLE forests (id INT,name VARCHAR(255),hectares FLOAT,country VARCHAR(255)); INSERT INTO forests (id,name,hectares,country) VALUES (1,'Boreal Forest',1200000.0,'Canada'),(2,'Amazon Rainforest',5500000.0,'Brazil'),(3,'Daintree Rainforest',120000.0,'Australia'); CREATE TABLE trees (id INT,species VARCHAR(255),hei...
SELECT forests.name FROM forests INNER JOIN avg_tree_height ON forests.id = avg_tree_height.forest_id WHERE avg_tree_height.avg_height > 45;
Delete all posts from user 'Charlie' before 2020-01-01.
CREATE TABLE posts (id INT,user_id INT,post_date DATE); INSERT INTO posts (id,user_id,post_date) VALUES (1,1,'2019-12-31'); INSERT INTO posts (id,user_id,post_date) VALUES (2,3,'2020-01-02'); INSERT INTO posts (id,user_id,post_date) VALUES (3,3,'2020-01-03');
DELETE FROM posts WHERE user_id = (SELECT id FROM users WHERE name = 'Charlie') AND post_date < '2020-01-01';
Which sustainable sourcing practices were implemented in Texas in Q1 2022?
CREATE TABLE sustainable_sourcing (practice VARCHAR(255),location VARCHAR(255),quarter INT,year INT); INSERT INTO sustainable_sourcing (practice,location,quarter,year) VALUES ('Organic meat','Texas',1,2022),('Seasonal ingredients','Texas',1,2022);
SELECT DISTINCT practice FROM sustainable_sourcing WHERE location = 'Texas' AND quarter = 1 AND year = 2022;
List all exploration projects in the Caribbean that started before 2015.
CREATE TABLE exploration_projects_caribbean (id INT,location VARCHAR(20),start_date DATE);
SELECT * FROM exploration_projects_caribbean WHERE location LIKE 'Caribbean%' AND start_date < '2015-01-01';
List all marine species that are found in more than one ocean basin
CREATE TABLE species (id INT,name VARCHAR(255),habitat VARCHAR(255)); CREATE TABLE ocean_basin (id INT,name VARCHAR(255)); CREATE TABLE species_ocean_basin (species_id INT,ocean_basin_id INT);
SELECT species.name FROM species JOIN species_ocean_basin ON species.id = species_ocean_basin.species_id JOIN ocean_basin ON species_ocean_basin.ocean_basin_id = ocean_basin.id GROUP BY species.name HAVING COUNT(DISTINCT ocean_basin.name) > 1;
How many clean energy policy trends were recorded in '2016' and '2017'?
CREATE SCHEMA policy_trends; CREATE TABLE clean_energy_trends (year INT,num_trends INT); INSERT INTO clean_energy_trends (year,num_trends) VALUES (2015,12),(2016,18),(2017,22),(2018,27),(2019,31);
SELECT SUM(num_trends) FROM policy_trends.clean_energy_trends WHERE year IN (2016, 2017);
What are the total budgets for public services in 2022, excluding the education and healthcare services?
CREATE TABLE budget_2022 (service TEXT,budget INTEGER); INSERT INTO budget_2022 (service,budget) VALUES ('Education',1500000),('Healthcare',1200000),('Police',1000000),('Transportation',800000);
SELECT SUM(budget) FROM budget_2022 WHERE service NOT IN ('Education', 'Healthcare');
Which online travel agencies offer virtual tours in the African region?
CREATE TABLE virtual_tours_4 (tour_id INT,tour_name TEXT,date DATE,engagement INT,ota_id INT); INSERT INTO virtual_tours_4 (tour_id,tour_name,date,engagement,ota_id) VALUES (1,'Tour C','2022-01-01',100,1),(2,'Tour D','2022-01-05',150,2); CREATE TABLE online_travel_agencies_4 (ota_id INT,ota_name TEXT); INSERT INTO onli...
SELECT ota_name FROM online_travel_agencies_4 INNER JOIN virtual_tours_4 ON online_travel_agencies_4.ota_id = virtual_tours_4.ota_id WHERE region = 'Africa';
Add a new program named "Green Thumbs" to the Programs table.
CREATE TABLE Programs (ProgramID int,ProgramName varchar(50));
INSERT INTO Programs (ProgramID, ProgramName) VALUES (3, 'Green Thumbs');
What is the difference in price between the most and least expensive foundations?
CREATE TABLE products (product_id INT,price DECIMAL(5,2),product_type TEXT); INSERT INTO products (product_id,price,product_type) VALUES (1,25.99,'Foundation'),(2,15.49,'Eyeshadow'),(3,34.99,'Foundation');
SELECT MAX(price) - MIN(price) FROM products WHERE product_type = 'Foundation';
Identify the top 2 most frequently accessed bus stops along route 101?
CREATE TABLE stop_sequence (stop_id INT,stop_sequence INT,route_id INT); INSERT INTO stop_sequence (stop_id,stop_sequence,route_id) VALUES (1001,1,101),(1002,2,101),(1003,3,101),(1004,4,101),(1005,5,101),(1006,6,101),(1007,7,101),(1008,8,101),(1009,9,101),(1010,10,101);
SELECT stop_sequence, stop_id, COUNT(*) as access_count FROM stop_sequence WHERE route_id = 101 GROUP BY stop_sequence ORDER BY access_count DESC LIMIT 2;
What is the average waste generation volume for mines with more than 3 inspections in the year 2020?
CREATE TABLE Inspection (id INT PRIMARY KEY,mine_id INT,inspector_id INT,year INT,date DATE,FOREIGN KEY (mine_id) REFERENCES Mine(id));
SELECT AVG(wg.waste_volume) as avg_waste_volume FROM Waste_Generation wg JOIN Mine m ON wg.mine_id = m.id JOIN Inspection i ON m.id = i.mine_id WHERE i.year = 2020 GROUP BY m.id HAVING COUNT(i.id) > 3;
What is the total funding received by arts organizations in the South region?
CREATE TABLE funding (funding_id INT,organization_id INT,source VARCHAR(50),amount INT); CREATE TABLE organizations (organization_id INT,region VARCHAR(50));
SELECT SUM(f.amount) as total_funding FROM funding f JOIN organizations o ON f.organization_id = o.organization_id WHERE o.region = 'South';
Which technology for social good initiatives have a budget greater than $600000?
CREATE TABLE tech_for_social_good_budget (initiative_id INT,initiative_name VARCHAR(255),region VARCHAR(255),budget DECIMAL(10,2)); INSERT INTO tech_for_social_good_budget (initiative_id,initiative_name,region,budget) VALUES (1,'Smart city project','Asia',1000000),(2,'Green technology initiative','Europe',800000),(3,'A...
SELECT initiative_name FROM tech_for_social_good_budget WHERE budget > 600000;
Update the price of the 'Tofu Stir Fry' dish to $12.50 in the 'Asian Fusion' restaurant.
CREATE TABLE menu_engineering(dish VARCHAR(255),category VARCHAR(255),price DECIMAL(5,2),restaurant VARCHAR(255));
UPDATE menu_engineering SET price = 12.50 WHERE dish = 'Tofu Stir Fry' AND restaurant = 'Asian Fusion';
What is the maximum medical score for each astronaut during their missions?
CREATE TABLE astronaut_medical (id INT,astronaut VARCHAR,mission VARCHAR,medical_score INT);
SELECT astronaut, MAX(medical_score) as max_medical_score FROM astronaut_medical GROUP BY astronaut;
How many renewable energy facilities are located in the Asia-Pacific region, and what is their total capacity in MW?
CREATE TABLE renewable_facilities (region VARCHAR(50),capacity NUMERIC,technology VARCHAR(50)); INSERT INTO renewable_facilities (region,capacity,technology) VALUES ('Asia-Pacific',500,'Solar'),('Asia-Pacific',600,'Wind'),('Europe',400,'Hydro'),('Africa',300,'Geothermal');
SELECT region, SUM(capacity) as total_capacity FROM renewable_facilities WHERE region = 'Asia-Pacific' GROUP BY region;
Rank the top 5 customers by their total spending on sustainable products in descending order.
CREATE TABLE customers (id INT,name VARCHAR(255),city VARCHAR(255),state VARCHAR(255)); INSERT INTO customers (id,name,city,state) VALUES (1,'John Doe','San Francisco','CA'),(2,'Jane Smith','Los Angeles','CA'),(3,'Alice Johnson','San Jose','CA'); CREATE TABLE purchases (id INT,customer_id INT,product_id INT,purchase_da...
SELECT c.name, SUM(p.price * p.quantity_sold) as total_spent FROM purchases p JOIN customers c ON p.customer_id = c.id JOIN products pr ON p.product_id = pr.id WHERE pr.is_sustainable = TRUE GROUP BY c.name ORDER BY total_spent DESC LIMIT 5;
What is the total amount of research grants awarded to non-binary faculty members in the 'faculty' and 'research_grants' tables?
CREATE TABLE faculty (id INT,name VARCHAR(255),gender VARCHAR(10),department VARCHAR(255)); INSERT INTO faculty (id,name,gender,department) VALUES (1,'Alex','Non-binary','Physics'),(2,'Bob','Male','Mathematics'),(3,'Charlie','Male','Chemistry'),(4,'Diana','Female','Biology');
SELECT SUM(rg.amount) FROM research_grants rg JOIN faculty f ON rg.department = f.department WHERE f.gender = 'Non-binary';
What is the minimum sequencing cost for a unique client in the last 3 months?
CREATE TABLE GeneSequencing (client_id INT,sequencing_date DATE,sequencing_cost FLOAT); INSERT INTO GeneSequencing (client_id,sequencing_date,sequencing_cost) VALUES (1,'2022-01-10',4500.50),(2,'2022-03-15',6200.75),(3,'2022-02-28',3000.20),(4,'2022-06-20',5800.00),(5,'2022-12-27',7000.00);
SELECT MIN(sequencing_cost) FROM GeneSequencing WHERE sequencing_date >= DATE_SUB(CURRENT_DATE, INTERVAL 3 MONTH) GROUP BY client_id;
Who are the top 3 artists with the highest art sales?
CREATE TABLE Artist (ArtistID INT,ArtistName VARCHAR(50),TotalSales DECIMAL(10,2)); INSERT INTO Artist (ArtistID,ArtistName,TotalSales) VALUES (1,'ArtistA',5000),(2,'ArtistB',7000),(3,'ArtistC',6000),(4,'ArtistD',8000),(5,'ArtistE',4000);
SELECT ArtistName, TotalSales FROM (SELECT ArtistName, TotalSales, ROW_NUMBER() OVER (ORDER BY TotalSales DESC) as Rank FROM Artist) AS Subquery WHERE Rank <= 3;
How many space missions were launched by India in total?
CREATE SCHEMA SpaceMissions;CREATE TABLE IndianMissions (MissionID INT,Country VARCHAR(50),LaunchYear INT);INSERT INTO IndianMissions VALUES (1,'India',2000),(2,'India',2005),(3,'India',2010),(4,'India',2015),(5,'India',2020);
SELECT COUNT(*) FROM IndianMissions WHERE Country = 'India';
List the names of all autonomous driving research studies that have been completed.
CREATE TABLE ResearchStudies (Id INT,Name TEXT,Location TEXT,StartDate DATE,EndDate DATE); INSERT INTO ResearchStudies (Id,Name,Location,StartDate,EndDate) VALUES (1,'Self-Driving Cars in California','California','2015-01-01','2016-01-01'),(2,'Autonomous Vehicle Testing in Texas','Texas','2016-06-15','2018-06-15'),(3,'...
SELECT Name FROM ResearchStudies WHERE EndDate IS NOT NULL;
What is the maximum number of crimes committed per day in the "south" district, for the month of July?
CREATE TABLE crimes (id INT,crime_date DATE,district VARCHAR(20),crime_count INT);
SELECT MAX(crime_count) FROM crimes WHERE district = 'south' AND EXTRACT(MONTH FROM crime_date) = 7;
What is the average energy efficiency of buildings in the United Kingdom?
CREATE TABLE building_efficiency (id INT,country VARCHAR(255),efficiency FLOAT);
SELECT AVG(efficiency) FROM building_efficiency WHERE country = 'United Kingdom';
What is the total number of animals in the 'community_education' view that are native to Oceania or Europe?
CREATE TABLE animal_population (animal VARCHAR(50),continent VARCHAR(50),population INT); INSERT INTO animal_population (animal,continent,population) VALUES ('Kakapo','Oceania',200),('Quokka','Oceania',10000),('Iberian Lynx','Europe',400); CREATE VIEW community_education AS SELECT animal,CONCAT('South ',continent) AS c...
SELECT animal FROM community_education WHERE continent = 'South Oceania' UNION ALL SELECT animal FROM community_education WHERE continent = 'South Europe';
What is the total number of fire incidents in the Bronx borough in the last 6 months?
CREATE TABLE boroughs (id INT,name TEXT); INSERT INTO boroughs (id,name) VALUES (1,'Bronx'),(2,'Manhattan'),(3,'Queens'); CREATE TABLE fire_incidents (id INT,borough_id INT,incidents INT,incident_date DATE); INSERT INTO fire_incidents (id,borough_id,incidents,incident_date) VALUES (1,1,3,'2023-01-01'),(2,1,4,'2023-02-1...
SELECT SUM(incidents) FROM fire_incidents WHERE borough_id = 1 AND incident_date >= DATE_SUB(CURDATE(), INTERVAL 6 MONTH);
What is the total number of mobile subscribers and the total mobile data usage in TB for the Caribbean region in 2021?
CREATE TABLE subscribers (id INT,service VARCHAR(10),region VARCHAR(20)); INSERT INTO subscribers (id,service,region) VALUES (1,'mobile','Caribbean'),(2,'broadband','Caribbean'); CREATE TABLE usage (subscriber_id INT,data_usage FLOAT,year INT); INSERT INTO usage (subscriber_id,data_usage,year) VALUES (1,12500,2021),(1,...
SELECT subscribers.region, COUNT(subscribers.id) AS total_customers, SUM(usage.data_usage/1024/1024/1024) AS total_usage FROM subscribers JOIN usage ON subscribers.id = usage.subscriber_id WHERE subscribers.service = 'mobile' AND subscribers.region = 'Caribbean' AND usage.year = 2021;
Identify top 5 cities with the most auto shows
CREATE TABLE AutoShows (City VARCHAR(50),State VARCHAR(50),Country VARCHAR(50),Year INT,Attendees INT); INSERT INTO AutoShows (City,State,Country,Year,Attendees) VALUES ('Las Vegas','NV','USA',2022,400000);
SELECT City, COUNT(*) as num_of_auto_shows FROM AutoShows GROUP BY City ORDER BY num_of_auto_shows DESC LIMIT 5;
What is the average number of construction labor hours per week in the United States and Canada, broken down by occupation?
CREATE TABLE labor_hours (id INT,country VARCHAR(50),occupation VARCHAR(50),hours DECIMAL(10,2)); INSERT INTO labor_hours (id,country,occupation,hours) VALUES (1,'USA','Carpenter',40.00),(2,'Canada','Carpenter',38.00),(3,'USA','Electrician',42.00),(4,'Canada','Electrician',40.00);
SELECT lh.country, lh.occupation, AVG(lh.hours) as avg_hours FROM labor_hours lh WHERE lh.country IN ('USA', 'Canada') GROUP BY lh.country, lh.occupation;
How many cultural events were held in 2022?
CREATE TABLE events (id INT,year INT,event_type VARCHAR(10)); INSERT INTO events (id,year,event_type) VALUES (1,2022,'Art Exhibition'),(2,2022,'Theater Performance'),(3,2021,'Music Concert'),(4,2022,'Dance Recital');
SELECT COUNT(*) FROM events WHERE year = 2022;