instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
Find the number of support programs each student is enrolled in, ordered by the number of enrollments in descending order.
CREATE TABLE Student (StudentID INT,StudentName VARCHAR(50)); INSERT INTO Student (StudentID,StudentName) VALUES (1,'John Doe'); INSERT INTO Student (StudentID,StudentName) VALUES (2,'Jane Smith'); CREATE TABLE SupportProgram (ProgramID INT,ProgramName VARCHAR(50),StudentID INT); INSERT INTO SupportProgram (ProgramID,P...
SELECT StudentID, COUNT(*) AS Enrollments FROM SupportProgram GROUP BY StudentID ORDER BY Enrollments DESC;
How many 'productA' items were sold in 'regionB'?
CREATE TABLE IF NOT EXISTS sales (id INT,product VARCHAR(50),region VARCHAR(50),quantity INT); INSERT INTO sales (id,product,region,quantity) VALUES (1,'productA','regionB',100),(2,'productB','regionC',50);
SELECT SUM(quantity) FROM sales WHERE product = 'productA' AND region = 'regionB';
Which stations on the Green Line have more than 300 docks available for bike return?
CREATE TABLE GREEN_LINE (station_name TEXT,num_docks_available INT); INSERT INTO GREEN_LINE (station_name,num_docks_available) VALUES ('Government Center',400),('Park Street',350),('North Station',500);
SELECT station_name FROM GREEN_LINE WHERE num_docks_available > 300;
List all green building types and the number of each type constructed in a specific year, for buildings in New York City.
CREATE TABLE GreenBuildingTypes (TypeID INT,TypeName VARCHAR(50));CREATE TABLE GreenBuildings (BuildingID INT,TypeID INT,YearBuilt INT,CityID INT);
SELECT GreenBuildingTypes.TypeName, COUNT(GreenBuildings.BuildingID) FROM GreenBuildingTypes INNER JOIN GreenBuildings ON GreenBuildingTypes.TypeID = GreenBuildings.TypeID WHERE GreenBuildings.YearBuilt = 2020 AND GreenBuildings.CityID = 1 GROUP BY GreenBuildingTypes.TypeName;
What is the minimum age of community health workers who identify as LGBTQ+ in California?
CREATE TABLE CommunityHealthWorkers (ID INT,Gender VARCHAR(10),Age INT,State VARCHAR(50),LGBTQ BOOLEAN); INSERT INTO CommunityHealthWorkers (ID,Gender,Age,State,LGBTQ) VALUES (1,'Female',45,'California',FALSE); INSERT INTO CommunityHealthWorkers (ID,Gender,Age,State,LGBTQ) VALUES (2,'Male',50,'California',FALSE); INSER...
SELECT MIN(Age) FROM CommunityHealthWorkers WHERE LGBTQ = TRUE AND State = 'California';
Show the total number of research grants awarded to each gender, sorted by the total amount.
CREATE TABLE grant (id INT,researcher VARCHAR(50),gender VARCHAR(10),department VARCHAR(30),amount FLOAT,date DATE); INSERT INTO grant (id,researcher,gender,department,amount,date) VALUES (1,'Tanvi','Female','Physics',200000.00,'2021-01-01'),(2,'Umair','Male','Physics',150000.00,'2020-07-14');
SELECT gender, SUM(amount) as total_amount FROM grant GROUP BY gender ORDER BY total_amount DESC;
What is the average fare for each route segment in the 'route_segments' table?
CREATE TABLE route_segments (route_id INT,segment_id INT,start_station VARCHAR(255),end_station VARCHAR(255),fare FLOAT);
SELECT route_id, segment_id, AVG(fare) as avg_fare FROM route_segments GROUP BY route_id, segment_id;
What was the total cost of all sustainable building projects in 2020?
CREATE TABLE sustainable_projects (project_id INT,project_name VARCHAR(100),project_cost FLOAT,year INT); INSERT INTO sustainable_projects (project_id,project_name,project_cost,year) VALUES (1,'Green Skyscraper',5000000,2020),(2,'Eco-Friendly Townhomes',3000000,2019),(3,'Solar Power Plant',8000000,2020);
SELECT SUM(project_cost) FROM sustainable_projects WHERE year = 2020;
What is the total number of transactions and their corresponding value for the Ethereum network, grouped by day for the past week?
CREATE TABLE ethereum_transactions (transaction_time TIMESTAMP,transaction_value INT);
SELECT DATE(transaction_time) AS transaction_day, SUM(transaction_value) AS total_transaction_value, COUNT(*) AS total_transactions FROM ethereum_transactions WHERE transaction_time >= DATE_SUB(CURRENT_TIMESTAMP(), INTERVAL 7 DAY) GROUP BY transaction_day;
What is the total number of restorative justice programs implemented in Canada between 2015 and 2018?
CREATE TABLE restorative_justice_canada (id INT,program_name VARCHAR(50),start_date DATE,end_date DATE,country VARCHAR(50)); INSERT INTO restorative_justice_canada (id,program_name,start_date,end_date,country) VALUES (1,'Restorative Canada','2015-01-01','2018-12-31','Canada'),(2,'Justice Heals','2016-01-01','2017-12-31...
SELECT SUM(id) FROM restorative_justice_canada WHERE country = 'Canada' AND start_date >= '2015-01-01' AND end_date <= '2018-12-31';
Find the average number of daily followers gained by users with the "influencer" role in Q2 2021.
CREATE TABLE users (id INT,username VARCHAR(255),role VARCHAR(255),followers INT,created_at TIMESTAMP);
SELECT AVG(followers_gained_per_day) FROM (SELECT DATEDIFF('2021-04-01', created_at) / 30.4375 AS followers_gained_per_day FROM users WHERE role = 'influencer') AS subquery;
What are the names of volunteers who have donated more than $200 in total, and have participated in the 'Education' program?
CREATE TABLE volunteer_donations (volunteer_id INT,donation DECIMAL(10,2)); INSERT INTO volunteer_donations (volunteer_id,donation) VALUES (1,100.00),(1,200.00),(2,150.00),(3,50.00),(4,300.00);
SELECT DISTINCT volunteers.name FROM volunteers JOIN volunteer_programs ON volunteers.id = volunteer_programs.volunteer_id JOIN volunteer_donations ON volunteers.id = volunteer_donations.volunteer_id WHERE volunteer_programs.program_id = 1 AND (SELECT SUM(donation) FROM volunteer_donations WHERE volunteer_id = voluntee...
Show the change in wind energy production for each project in Germany between 2019 and 2020.
CREATE TABLE project (name VARCHAR(50),country VARCHAR(50),year INT,wind_energy_production DECIMAL(5,2)); INSERT INTO project (name,country,year,wind_energy_production) VALUES ('Project A','Germany',2019,500.2),('Project A','Germany',2020,522.1),('Project B','Germany',2019,600.5),('Project B','Germany',2020,615.3);
SELECT name, (LEAD(wind_energy_production, 1, 0) OVER (PARTITION BY name ORDER BY year) - wind_energy_production) AS change FROM project WHERE country = 'Germany';
Find the number of mental health facilities that provide linguistically and culturally competent services in California.
CREATE TABLE MentalHealthFacilities (ID INT,Name VARCHAR(100),LinguisticCompetency BOOLEAN,CulturalCompetency BOOLEAN,State VARCHAR(50)); INSERT INTO MentalHealthFacilities (ID,Name,LinguisticCompetency,CulturalCompetency,State) VALUES (1,'Facility1',TRUE,TRUE,'California'); INSERT INTO MentalHealthFacilities (ID,Name,...
SELECT COUNT(*) FROM MentalHealthFacilities WHERE LinguisticCompetency = TRUE AND CulturalCompetency = TRUE AND State = 'California';
Find the total calories for all dishes that are both vegan and gluten-free.
CREATE TABLE Dishes (DishID INT,DishName VARCHAR(50),Type VARCHAR(20),Calories INT); INSERT INTO Dishes (DishID,DishName,Type,Calories) VALUES (1,'Quinoa Salad','Vegan',400),(2,'Chickpea Curry','Vegan',600),(3,'Beef Stew','Non-vegan',1200),(4,'Veggie Burger','Vegan',500),(5,'Chicken Stir Fry','Non-vegan',800),(6,'Lenti...
SELECT SUM(Calories) FROM Dishes WHERE Type = 'Vegan' AND Type = 'Gluten-free';
What is the maximum word count for news reports in the "news_reports" table published in 2021?
CREATE TABLE news_reports (id INT,title VARCHAR(100),publication_date DATE,word_count INT); INSERT INTO news_reports (id,title,publication_date,word_count) VALUES (1,'Climate Change Impact','2022-03-01',1500),(2,'Political Turmoil in Europe','2021-12-15',2000),(3,'Technology Advancements in Healthcare','2022-06-20',120...
SELECT MAX(word_count) FROM news_reports WHERE YEAR(publication_date) = 2021;
List all news articles published by "The Guardian" that have a word count greater than 1000.
CREATE TABLE news_articles (title VARCHAR(100),publication VARCHAR(50),word_count INT); INSERT INTO news_articles (title,publication,word_count) VALUES ('How to reduce your carbon footprint','The Guardian',1200),('Interview with local artist','The Guardian',800),('New study reveals ocean pollution','The Guardian',1500)...
SELECT title FROM news_articles WHERE publication = 'The Guardian' AND word_count > 1000;
What is the top 5 most data-intensive days for mobile subscribers in the current month?
CREATE TABLE mobile_data_usage (usage_id INT,subscriber_id INT,data_usage FLOAT,usage_date DATE); INSERT INTO mobile_data_usage (usage_id,subscriber_id,data_usage,usage_date) VALUES (1,1,200,'2022-03-01'),(2,2,150,'2022-03-02'),(3,3,250,'2022-03-03'),(4,4,300,'2022-03-04'),(5,5,400,'2022-03-05'),(6,1,220,'2022-03-06');
SELECT usage_date, SUM(data_usage) AS total_data_usage FROM mobile_data_usage WHERE usage_date >= DATE_SUB(CURDATE(), INTERVAL DAY(CURDATE()) DAY) GROUP BY usage_date ORDER BY total_data_usage DESC LIMIT 5;
How many Shariah-compliant loans were issued in each month of 2022?
CREATE TABLE shariah_compliant_loans (id INT,customer_name VARCHAR(50),amount DECIMAL(10,2),issue_date DATE); INSERT INTO shariah_compliant_loans (id,customer_name,amount,issue_date) VALUES (1,'Ahmed',5000,'2022-01-01'),(2,'Fatima',3000,'2022-02-14'),(3,'Hamza',7000,'2022-03-31');
SELECT MONTH(issue_date), COUNT(*) FROM shariah_compliant_loans WHERE issue_date BETWEEN '2022-01-01' AND '2022-12-31' GROUP BY MONTH(issue_date);
What is the average age of patients who have completed the therapy program?
CREATE TABLE patients (id INT,name TEXT,age INT,therapy_completion BOOLEAN);
SELECT AVG(age) FROM patients WHERE therapy_completion = TRUE;
What is the average age of female farmers who have participated in community development initiatives in Nigeria?
CREATE TABLE nigeria_farmers (farmer_id INT,name VARCHAR(50),age INT,gender VARCHAR(10),participation BOOLEAN); INSERT INTO nigeria_farmers (farmer_id,name,age,gender,participation) VALUES (1,'Ada',45,'female',true),(2,'Bola',30,'male',false),(3,'Chidinma',50,'female',true);
SELECT AVG(age) FROM nigeria_farmers WHERE gender = 'female' AND participation = true;
What is the average virtual tour engagement duration in Mumbai, India?
CREATE TABLE virtual_tours (tour_id INT,hotel_name VARCHAR(255),city VARCHAR(255),country VARCHAR(255),duration INT); INSERT INTO virtual_tours (tour_id,hotel_name,city,country,duration) VALUES (1,'Hotel Taj Mahal Palace','Mumbai','India',180),(2,'Hotel Trident','Mumbai','India',210);
SELECT AVG(duration) FROM virtual_tours WHERE city = 'Mumbai' AND country = 'India';
Who are the top 5 customers with the highest total spending on cannabis products in Michigan dispensaries in the last quarter?
CREATE TABLE customers (id INT,name TEXT,state TEXT);CREATE TABLE orders (id INT,customer_id INT,item_type TEXT,price DECIMAL,order_date DATE);
SELECT c.name, SUM(o.price) as total_spending FROM customers c INNER JOIN orders o ON c.id = o.customer_id WHERE c.state = 'Michigan' AND o.order_date >= DATE_SUB(CURRENT_DATE, INTERVAL 3 MONTH) GROUP BY c.name ORDER BY total_spending DESC LIMIT 5;
What is the number of cases opened by each attorney?
CREATE TABLE attorneys (attorney_id INT,attorney_name TEXT); INSERT INTO attorneys (attorney_id,attorney_name) VALUES (1,'John Doe'),(2,'Jane Smith'); CREATE TABLE cases (case_id INT,attorney_id INT,open_date DATE); INSERT INTO cases (case_id,attorney_id,open_date) VALUES (1,1,'2021-01-01'),(2,1,'2021-02-01'),(3,2,'202...
SELECT a.attorney_name, COUNT(*) as cases_opened FROM attorneys a JOIN cases c ON a.attorney_id = c.attorney_id GROUP BY a.attorney_name;
How many community engagement events occurred for each heritage site category?
CREATE TABLE SiteCategories (CategoryID INT,Category VARCHAR(50)); CREATE TABLE CommunityEvents (EventID INT,EventName VARCHAR(50),CategoryID INT,EventYear INT); INSERT INTO SiteCategories VALUES (1,'Historic Building'),(2,'National Park'),(3,'Archaeological Site'); INSERT INTO CommunityEvents VALUES (1,'Cultural Festi...
SELECT SiteCategories.Category, COUNT(CommunityEvents.EventID) AS EventCount FROM SiteCategories INNER JOIN CommunityEvents ON SiteCategories.CategoryID = CommunityEvents.CategoryID GROUP BY SiteCategories.Category;
List the top 3 mining sites with the highest environmental impact score and their location.
CREATE TABLE MiningSites (SiteID INT,SiteName VARCHAR(50),Location VARCHAR(50),OpenDate DATE,EnvironmentalImpactScore INT);
SELECT SiteName, Location, EnvironmentalImpactScore FROM MiningSites WHERE SiteID IN (SELECT SiteID FROM (SELECT SiteID, RANK() OVER(ORDER BY EnvironmentalImpactScore DESC) as rnk FROM MiningSites) tmp WHERE rnk <= 3) ORDER BY EnvironmentalImpactScore DESC;
Delete a mediation session from the 'mediation_sessions' table
CREATE TABLE mediation_sessions (session_id INT PRIMARY KEY,session_date DATE,session_time TIME,location VARCHAR(255),facilitator_id INT,case_number INT);
DELETE FROM mediation_sessions WHERE session_id = 4002 AND case_number = 2022001;
List all military exercises that took place in the Arctic region since 2017.
CREATE TABLE military_exercises (id INT,name TEXT,region TEXT,year INT);INSERT INTO military_exercises (id,name,region,year) VALUES (1,'Arctic Edge','Arctic',2017);INSERT INTO military_exercises (id,name,region,year) VALUES (2,'Northern Edge','Arctic',2019);
SELECT name FROM military_exercises WHERE region = 'Arctic' AND year >= 2017;
List the offshore wind farms in Germany and Denmark that started operation after 2010.
CREATE TABLE offshore_wind_farms (id INT,name TEXT,country TEXT,start_date DATE); INSERT INTO offshore_wind_farms (id,name,country,start_date) VALUES (1,'Gode Wind 1 and 2','Germany','2014-01-01');
SELECT name, country, start_date FROM offshore_wind_farms WHERE country IN ('Germany', 'Denmark') AND start_date >= '2010-01-01';
How many community events were held in Los Angeles in 2021?
CREATE TABLE Community_Events (id INT,location VARCHAR(20),event_date DATE); INSERT INTO Community_Events (id,location,event_date) VALUES (1,'Los Angeles','2021-02-15'),(2,'New York','2020-09-01');
SELECT COUNT(*) FROM Community_Events WHERE location = 'Los Angeles' AND event_date BETWEEN '2021-01-01' AND '2021-12-31'
Which agroecology projects have the highest and lowest total funding?
CREATE TABLE agroecology_projects (id INT,name TEXT,total_funding FLOAT); INSERT INTO agroecology_projects (id,name,total_funding) VALUES (1,'Project 1',50000.0),(2,'Project 2',25000.0),(3,'Project 3',75000.0);
SELECT name, total_funding FROM (SELECT name, total_funding, ROW_NUMBER() OVER (ORDER BY total_funding DESC) as rank FROM agroecology_projects) as ranked_projects WHERE rank = 1 OR rank = (SELECT COUNT(*) FROM agroecology_projects) ORDER BY total_funding;
What is the maximum number of emergency responses and disaster recovery efforts in a single day in each district, separated by type and sorted by maximum number of responses/efforts in descending order?
CREATE TABLE Districts (DId INT,Name VARCHAR(50)); CREATE TABLE EmergencyResponses (ResponseId INT,DId INT,Type VARCHAR(50),Date DATE,Time TIME); CREATE TABLE DisasterRecovery (RecoveryId INT,DId INT,Type VARCHAR(50),Date DATE,Time TIME);
SELECT D.Name, ER.Type, MAX(COUNT(*)) AS MaxResponses FROM Districts D LEFT JOIN EmergencyResponses ER ON D.DId = ER.DId WHERE ER.Time BETWEEN '00:00:00' AND '23:59:59' GROUP BY D.Name, ER.Type UNION SELECT D.Name, DR.Type, MAX(COUNT(*)) AS MaxEfforts FROM Districts D LEFT JOIN DisasterRecovery DR ON D.DId = DR.DId WHE...
What is the total revenue for virtual reality games in 2020 and 2021?
CREATE TABLE Games (GameID INT,GameType VARCHAR(20),Revenue INT,ReleaseYear INT); INSERT INTO Games (GameID,GameType,Revenue,ReleaseYear) VALUES (1,'VR',5000000,2020),(2,'Non-VR',7000000,2021),(3,'VR',6000000,2020),(4,'Non-VR',8000000,2021),(5,'VR',9000000,2020);
SELECT GameType, ReleaseYear, SUM(Revenue) as TotalRevenue FROM Games WHERE GameType = 'VR' GROUP BY GameType, ReleaseYear
Calculate the percentage of candidates from underrepresented racial groups who were offered a job.
CREATE TABLE candidate_demographics (id INT,candidate_id INT,race VARCHAR(255),offered_job BOOLEAN); INSERT INTO candidate_demographics (id,candidate_id,race,offered_job) VALUES (1,1001,'Hispanic',true),(2,1002,'African American',false),(3,1003,'Asian',true),(4,1004,'Hispanic',false);
SELECT COUNT(*) * 100.0 / (SELECT COUNT(*) FROM candidate_demographics WHERE race IN ('Hispanic', 'African American')) as percentage FROM candidate_demographics WHERE offered_job = true AND race IN ('Hispanic', 'African American');
What is the combined sales revenue for the drugs 'DrugA' and 'DrugB' in Q2 2020?
CREATE TABLE drug_sales (drug VARCHAR(50),quarter VARCHAR(5),year INT,revenue INT); INSERT INTO drug_sales (drug,quarter,year,revenue) VALUES ('DrugA','Q2',2020,30000),('DrugB','Q2',2020,40000),('DrugC','Q2',2020,50000);
SELECT SUM(revenue) FROM drug_sales WHERE drug IN ('DrugA', 'DrugB') AND quarter = 'Q2' AND year = 2020;
Delete the record for the community health worker who is 30 years old.
CREATE TABLE community_health_workers (worker_id INT,age INT,ethnicity VARCHAR(255)); INSERT INTO community_health_workers (worker_id,age,ethnicity) VALUES (1,35,'Hispanic'),(2,40,'African American'),(3,30,'Asian'),(4,45,'Caucasian');
DELETE FROM community_health_workers WHERE age = 30;
Determine the number of network infrastructure investments made by each country in the Africa region over the past year.
CREATE TABLE investments (id INT,country VARCHAR(20),investment_date DATE); INSERT INTO investments (id,country,investment_date) VALUES (1,'Kenya','2022-01-01'),(2,'Nigeria','2022-03-15'),(3,'Kenya','2022-04-05'),(4,'Egypt','2021-09-01');
SELECT country, COUNT(*) as num_investments FROM investments WHERE region = 'Africa' AND investment_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR) GROUP BY country;
Update the "age" field to 35 for all records in the "audience_demographics" table where "country" is "Brazil" and "gender" is "Female"
CREATE TABLE audience_demographics (id INT PRIMARY KEY,age INT,country VARCHAR(255),gender VARCHAR(255));
UPDATE audience_demographics SET age = 35 WHERE country = 'Brazil' AND gender = 'Female';
Who are the engineers in the aircraft manufacturing department with IDs lower than 5?
CREATE TABLE Employees (EmployeeID INT,FirstName VARCHAR(50),LastName VARCHAR(50),Position VARCHAR(50),Department VARCHAR(50)); INSERT INTO Employees (EmployeeID,FirstName,LastName,Position,Department) VALUES (3,'Sara','Ali','Engineer','Aircraft Manufacturing');
SELECT EmployeeID, FirstName, LastName FROM Employees WHERE Department = 'Aircraft Manufacturing' AND Position = 'Engineer' AND EmployeeID < 5;
What is the average number of hours volunteered per volunteer each year?
CREATE TABLE volunteer_hours (id INT,volunteer_id INT,year INT,num_hours INT); INSERT INTO volunteer_hours (id,volunteer_id,year,num_hours) VALUES (1,1,2019,100),(2,1,2020,150),(3,2,2019,75),(4,2,2020,200),(5,3,2019,125),(6,3,2020,175);
SELECT year, AVG(num_hours) as avg_hours_per_volunteer FROM volunteer_hours GROUP BY year;
What is the maximum and minimum monthly data usage for each country?
CREATE TABLE mobile_subscribers (subscriber_id INT,home_location VARCHAR(50),monthly_data_usage DECIMAL(10,2)); INSERT INTO mobile_subscribers (subscriber_id,home_location,monthly_data_usage) VALUES (1,'USA',3.5),(2,'Mexico',4.2),(3,'Canada',2.8),(4,'USA',4.5),(5,'Canada',3.2);
SELECT home_location, MAX(monthly_data_usage) AS max_data_usage, MIN(monthly_data_usage) AS min_data_usage FROM mobile_subscribers GROUP BY home_location;
Which country has the most esports event organizers?
CREATE TABLE EventOrganizers (OrganizerID INT,OrgName VARCHAR(50),Country VARCHAR(50)); INSERT INTO EventOrganizers (OrganizerID,OrgName,Country) VALUES (1,'ESL','Germany'),(2,'DreamHack','Sweden'),(3,'MLG','USA');
SELECT Country, COUNT(*) as EventOrganizerCount FROM EventOrganizers GROUP BY Country ORDER BY EventOrganizerCount DESC LIMIT 1;
What is the average response time for medical emergencies, broken down by response team, where the average response time is greater than 15 minutes?
CREATE TABLE EmergencyResponse (Id INT,IncidentId INT,ResponseTeam VARCHAR(50),ResponseTime INT,IncidentType VARCHAR(50)); CREATE VIEW EmergencyResponse_Team AS SELECT ResponseTeam,AVG(ResponseTime) as AvgResponseTime FROM EmergencyResponse WHERE IncidentType = 'Medical' GROUP BY ResponseTeam;
SELECT ert.ResponseTeam, AVG(ert.AvgResponseTime) as AvgResponseTime FROM EmergencyResponse_Team ert WHERE ert.AvgResponseTime > 15 GROUP BY ert.ResponseTeam;
List all the farms in the Western region that have a higher yield per acre for corn compared to the average yield per acre for corn in the entire database.
CREATE TABLE Farm (id INT,name TEXT,crop TEXT,yield_per_acre FLOAT,region TEXT); INSERT INTO Farm (id,name,crop,yield_per_acre,region) VALUES (1,'Smith Farm','Corn',150,'Midwest'),(2,'Jones Farm','Soybeans',80,'Midwest'),(3,'Brown Farm','Corn',200,'Western'),(4,'Green Farm','Potatoes',200,'Northeast'),(5,'White Farm','...
SELECT * FROM Farm WHERE region = 'Western' AND crop = 'Corn' AND yield_per_acre > (SELECT avg_yield FROM Average WHERE crop = 'Corn');
How many climate mitigation projects were completed in North America before 2015?
CREATE TABLE climate_project (project_id INT,project_name TEXT,project_type TEXT,start_date DATE); INSERT INTO climate_project (project_id,project_name,project_type,start_date) VALUES (1,'North American Wind Farm','Mitigation','2012-01-01');
SELECT COUNT(*) FROM climate_project WHERE project_type = 'Mitigation' AND start_date < DATEADD(year, -3, '2015-01-01');
Show the attorney_name and attorney_email for all attorneys in the 'attorneys' table
CREATE TABLE attorneys (attorney_id INT,attorney_name VARCHAR(50),attorney_email VARCHAR(50),attorney_phone VARCHAR(15)); INSERT INTO attorneys (attorney_id,attorney_name,attorney_email,attorney_phone) VALUES (3,'Sara White','sara.white@lawfirm.com','555-555-2121');
SELECT attorney_name, attorney_email FROM attorneys;
List the top 3 regions with the highest water usage in the past month.
CREATE TABLE water_usage (region VARCHAR(255),usage FLOAT,date DATE); INSERT INTO water_usage (region,usage,date) VALUES ('New York',5000,'2022-05-01'); INSERT INTO water_usage (region,usage,date) VALUES ('Los Angeles',7000,'2022-05-01');
SELECT region, usage FROM (SELECT region, usage, ROW_NUMBER() OVER (ORDER BY usage DESC) as rank FROM water_usage WHERE date >= '2022-05-01' GROUP BY region, usage) subquery WHERE rank <= 3;
Insert a new exit strategy into the "exit_strategies" table for 'India Inc.' with an acquisition price of $50M on 2021-10-01
CREATE TABLE exit_strategies (id INT,company_name VARCHAR(100),exit_type VARCHAR(50),acquisition_price FLOAT,exit_date DATE);
INSERT INTO exit_strategies (id, company_name, exit_type, acquisition_price, exit_date) VALUES (7, 'India Inc.', 'Acquisition', 50000000, '2021-10-01');
Update soil moisture records for a specific sensor_id if the moisture level is below a specified threshold.
CREATE TABLE sensor_data (sensor_id INT,crop_type VARCHAR(255),soil_moisture DECIMAL(5,2),record_date DATE);
UPDATE sensor_data SET soil_moisture = 50 WHERE sensor_id = 2 AND soil_moisture < 20.0;
Identify cultural competency training programs offered by community health workers in NY and CA.
CREATE TABLE community_health_workers (worker_id INT,name VARCHAR(50),state VARCHAR(2),training_programs VARCHAR(100)); INSERT INTO community_health_workers (worker_id,name,state,training_programs) VALUES (1,'Jane Doe','NY','Cultural Competency,First Aid'); INSERT INTO community_health_workers (worker_id,name,state,tra...
SELECT state, training_programs FROM community_health_workers WHERE state IN ('NY', 'CA') AND training_programs LIKE '%Cultural Competency%';
What is the percentage change in international visitor numbers for each destination in Europe compared to the same quarter last year?
CREATE TABLE european_tourism (destination VARCHAR(255),year INT,quarter INT,visitors INT); INSERT INTO european_tourism (destination,year,quarter,visitors) VALUES ('Barcelona',2021,1,800000); INSERT INTO european_tourism (destination,year,quarter,visitors) VALUES ('Barcelona',2021,2,900000); INSERT INTO european_touri...
SELECT destination, year, quarter, visitors, NTILE(4) OVER (ORDER BY visitors) as quartile, (visitors - LAG(visitors) OVER (PARTITION BY destination ORDER BY year, quarter))*100.0 / LAG(visitors) OVER (PARTITION BY destination ORDER BY year, quarter) as pct_change FROM european_tourism;
Find the total value of artworks created in the Impressionist period.
CREATE TABLE ArtWorks (ArtworkID int,Title varchar(100),Value int,Period varchar(100));
SELECT SUM(Value) FROM ArtWorks WHERE Period = 'Impressionist'
Create a table named "stations" with columns "station_id", "name", "latitude", and "longitude".
CREATE TABLE stations (station_id INT,name VARCHAR(255),latitude FLOAT,longitude FLOAT);
CREATE TABLE stations (station_id INT, name VARCHAR(255), latitude FLOAT, longitude FLOAT);
What is the total biomass of marine life species in the 'MarineLife' schema's cold-water regions?
CREATE SCHEMA MarineLife; CREATE TABLE Species (id INT,name TEXT,biomass FLOAT); CREATE SCHEMA Geography; CREATE TABLE Habitats (id INT,species_id INT,region_type TEXT);
SELECT SUM(s.biomass) FROM MarineLife.Species s JOIN MarineLife.Habitats h ON s.id = h.species_id WHERE h.region_type = 'cold-water';
What is the total value of transactions for socially responsible lending accounts in the 'social_responsibility' schema's 'transactions' table, excluding transactions made within the last 30 days?
CREATE TABLE social_responsibility.transactions (transaction_id INT,account_number INT,transaction_amount DECIMAL(10,2),transaction_date DATE); INSERT INTO social_responsibility.transactions (transaction_id,account_number,transaction_amount,transaction_date) VALUES (1,1001,100.00,'2022-01-01'),(2,1002,200.00,'2022-01-1...
SELECT SUM(transaction_amount) FROM social_responsibility.transactions WHERE account_number IN (SELECT account_number FROM social_responsibility.accounts WHERE is_socially_responsible = true) AND transaction_date < NOW() - INTERVAL '30 days';
What is the average recycling rate for each material type in the 'recycling_rates' table?
CREATE TABLE recycling_rates (id INT,material VARCHAR(20),rate FLOAT); INSERT INTO recycling_rates (id,material,rate) VALUES (1,'cotton',0.75),(2,'wool',0.60),(3,'polyester',0.50),(4,'silk',0.80);
SELECT material, AVG(rate) FROM recycling_rates GROUP BY material;
What is the total amount of research grants awarded to graduate students in each department?
CREATE TABLE Students (StudentID int,Department varchar(50)); INSERT INTO Students (StudentID,Department) VALUES (5,'Physics'); CREATE TABLE Grants (GrantID int,StudentID int,Department varchar(50),Amount int); INSERT INTO Grants (GrantID,StudentID,Department,Amount) VALUES (7,5,'Physics',3000); INSERT INTO Grants (Gra...
SELECT Students.Department, SUM(Grants.Amount) FROM Students INNER JOIN Grants ON Students.StudentID = Grants.StudentID GROUP BY Students.Department;
Count the number of clinical trials conducted in Germany and Japan before 2010, grouped by trial phase.
CREATE TABLE clinical_trials (trial_name TEXT,country TEXT,trial_phase TEXT,trial_date DATE); INSERT INTO clinical_trials (trial_name,country,trial_phase,trial_date) VALUES ('Trial1','Germany','Phase1','2008-03-23'),('Trial2','Japan','Phase3','2006-07-09'),('Trial3','Germany','Phase2','2009-11-17'),('Trial4','Japan','P...
SELECT trial_phase, COUNT(*) FROM clinical_trials WHERE country IN ('Germany', 'Japan') AND trial_date < '2010-01-01' GROUP BY trial_phase;
Show the number of public events and the number of attendees for each event in the city of San Francisco.
CREATE TABLE events (id INT,event_name VARCHAR(255),event_type VARCHAR(255),city_id INT);CREATE TABLE attendees (id INT,event_id INT,attendee_name VARCHAR(255));
SELECT e.event_name, COUNT(a.id) as num_attendees FROM events e INNER JOIN attendees a ON e.id = a.event_id WHERE e.city_id = (SELECT id FROM cities WHERE city_name = 'San Francisco') GROUP BY e.id;
What is the maximum weight of packages shipped to 'Sydney' from the 'Melbourne' warehouse in April 2021?
CREATE TABLE warehouse (id INT,name VARCHAR(20)); CREATE TABLE shipment (id INT,warehouse_id INT,delivery_location VARCHAR(20),shipped_date DATE,weight FLOAT); INSERT INTO warehouse (id,name) VALUES (1,'Seattle'),(2,'NY'),(3,'LA'),(4,'Paris'),(5,'London'),(6,'Melbourne'); INSERT INTO shipment (id,warehouse_id,delivery_...
SELECT MAX(weight) AS max_weight FROM shipment WHERE warehouse_id = 6 AND delivery_location = 'Sydney' AND shipped_date >= '2021-04-01' AND shipped_date < '2021-05-01';
How many victims of crime are recorded in the 'crime_victims' table by gender?
CREATE TABLE crime_victims (id INT,gender TEXT,age INT,crime_type TEXT);
SELECT gender, COUNT(*) FROM crime_victims GROUP BY gender;
find the total sales of skincare products in the first quarter of 2021 for each brand
CREATE TABLE BrandSkincareSales (sale_id INT,product_name TEXT,brand TEXT,sale_amount FLOAT,sale_date DATE); INSERT INTO BrandSkincareSales (sale_id,product_name,brand,sale_amount,sale_date) VALUES (1,'Cleanser','Brand A',50.00,'2021-01-01'); INSERT INTO BrandSkincareSales (sale_id,product_name,brand,sale_amount,sale_d...
SELECT brand, SUM(sale_amount) AS total_sales FROM BrandSkincareSales WHERE sale_date BETWEEN '2021-01-01' AND '2021-03-31' GROUP BY brand;
What are the top 3 blockchains with the most digital assets?
CREATE TABLE blockchains (id INT,name VARCHAR(255),num_assets INT); INSERT INTO blockchains (id,name,num_assets) VALUES (1,'Bitcoin',1000),(2,'Ethereum',5000),(3,'Ripple',2000),(4,'Binance Smart Chain',3000),(5,'Cardano',4000);
SELECT name, num_assets FROM blockchains ORDER BY num_assets DESC LIMIT 3;
What is the total number of volunteers and total donation amount for each program in Philippines?
CREATE TABLE Donations (id INT,donation_amount DECIMAL(10,2),donation_date DATE,program VARCHAR(50),country VARCHAR(50)); CREATE TABLE Volunteers (id INT,volunteer_name VARCHAR(50),program VARCHAR(50),country VARCHAR(50)); INSERT INTO Donations (id,donation_amount,donation_date,program,country) VALUES (1,100.00,'2021-0...
SELECT p.program, COUNT(DISTINCT v.volunteer_name) as num_volunteers, SUM(d.donation_amount) as total_donations FROM Donations d INNER JOIN Volunteers v ON d.program = v.program INNER JOIN Programs p ON d.program = p.program WHERE d.country = 'Philippines' GROUP BY p.program;
What is the total number of farmers in the 'agricultural_farms' table per certification level?
CREATE TABLE agricultural_farms (id INT,name VARCHAR(30),num_employees INT,certification_level VARCHAR(10));
SELECT certification_level, COUNT(*) FROM agricultural_farms GROUP BY certification_level;
What is the total quantity of sustainable fabric sourced from India in 2022?
CREATE TABLE sourcing (year INT,country VARCHAR(20),fabric_type VARCHAR(20),quantity INT); INSERT INTO sourcing (year,country,fabric_type,quantity) VALUES (2022,'India','sustainable',3000),(2022,'India','regular',5000);
SELECT SUM(quantity) FROM sourcing WHERE year = 2022 AND country = 'India' AND fabric_type = 'sustainable';
What is the total quantity of product 'Eco-friendly Tote Bag' manufactured by factories in Canada?
CREATE TABLE factories (id INT,name VARCHAR(255),country VARCHAR(255)); INSERT INTO factories (id,name,country) VALUES (1,'Eco-friendly Goods Inc','Canada'); CREATE TABLE products (id INT,name VARCHAR(255),quantity INT); INSERT INTO products (id,name,quantity) VALUES (1,'Eco-friendly Tote Bag',2000); CREATE TABLE manuf...
SELECT SUM(products.quantity) as total_quantity FROM products INNER JOIN manufacturing ON products.id = manufacturing.product_id INNER JOIN factories ON manufacturing.factory_id = factories.id WHERE factories.country = 'Canada' AND products.name = 'Eco-friendly Tote Bag';
How many Rare Earth Elements does Malaysia have in their inventory?
CREATE TABLE inventory (country VARCHAR(255),element VARCHAR(255),quantity INT); INSERT INTO inventory (country,element,quantity) VALUES ('Malaysia','Samarium',1000),('Malaysia','Gadolinium',1500),('Malaysia','Ytterbium',2000);
SELECT SUM(quantity) as total_quantity FROM inventory WHERE country = 'Malaysia';
What is the total budget allocated for rural health programs in the last 5 years?
CREATE TABLE budget (id INT,year INT,program VARCHAR(30),amount INT); INSERT INTO budget (id,year,program,amount) VALUES (1,2017,'rural health',5000000);
SELECT SUM(amount) FROM budget WHERE program = 'rural health' AND year BETWEEN 2017 AND 2021;
Identify mines that have reduced their workforce in the last quarter.
CREATE TABLE mine_workforce_history (mine_id INT,change_date DATE,num_employees INT); INSERT INTO mine_workforce_history (mine_id,change_date,num_employees) VALUES (1,'2021-01-01',500),(1,'2021-04-01',450),(2,'2021-01-01',450),(2,'2021-04-01',450),(3,'2021-01-01',400),(3,'2021-04-01',350);
SELECT mine_id, change_date, num_employees, LAG(num_employees) OVER (PARTITION BY mine_id ORDER BY change_date) as prev_quarter_employees, num_employees - LAG(num_employees) OVER (PARTITION BY mine_id ORDER BY change_date) as employess_change FROM mine_workforce_history WHERE num_employees < LAG(num_employees) OVER (PA...
What is the maximum number of hours worked per week by workers in the 'retail' sector, including overtime?
CREATE TABLE if not exists work_hours (id INT PRIMARY KEY,worker_id INT,sector VARCHAR(255),hours_per_week INT); INSERT INTO work_hours (id,worker_id,sector,hours_per_week) VALUES (1,101,'retail',40),(2,102,'retail',45),(3,103,'manufacturing',50);
SELECT MAX(hours_per_week) FROM work_hours WHERE sector = 'retail';
What is the ratio of safe AI algorithms to unsafe AI algorithms developed by women and non-binary individuals?
CREATE TABLE safe_ai_algorithms (algorithm_id INT,algorithm_name TEXT,is_safe BOOLEAN,developer_gender TEXT); INSERT INTO safe_ai_algorithms (algorithm_id,algorithm_name,is_safe,developer_gender) VALUES (1,'Safe AI',true,'Female'),(2,'Unsafe AI',false,'Non-binary'),(3,'Safe AI',true,'Non-binary');
SELECT developer_gender, SUM(is_safe) as num_safe, COUNT(*) as num_total, 1.0 * SUM(is_safe) / COUNT(*) as ratio FROM safe_ai_algorithms GROUP BY developer_gender;
Which sustainable building practices were implemented in projects located in 'West Coast' region between 2018 and 2020?
CREATE TABLE Sustainable_Practices (project_id INT,practice VARCHAR(255),region VARCHAR(255),completion_date DATE); INSERT INTO Sustainable_Practices (project_id,practice,region,completion_date) VALUES (1,'Solar Panels','West Coast','2019-04-15'); INSERT INTO Sustainable_Practices (project_id,practice,region,completion...
SELECT practice FROM Sustainable_Practices WHERE region = 'West Coast' AND completion_date BETWEEN '2018-01-01' AND '2020-12-31';
How many public works projects have been completed in each country, and which ones are they?
CREATE TABLE PublicWorksProjects (ProjectID INT,Name VARCHAR(255),Location VARCHAR(255),Status VARCHAR(255)); INSERT INTO PublicWorksProjects VALUES (1,'Water Treatment Plant','Colorado','Completed'); INSERT INTO PublicWorksProjects VALUES (2,'Sewer System Upgrade','California','In Progress'); INSERT INTO PublicWorksPr...
SELECT Location, COUNT(*) as NumberOfProjects, STRING_AGG(Name, ', ') as CompletedProjects FROM PublicWorksProjects WHERE Status = 'Completed' GROUP BY Location;
List the unique algorithmic fairness categories and corresponding descriptions, ordered by category in ascending order.
CREATE TABLE fairness_categories (category_id INT,category VARCHAR(50),description TEXT); INSERT INTO fairness_categories (category_id,category,description) VALUES (1,'Racial','Fairness related to race and ethnicity'),(2,'Gender','Fairness related to gender and gender identity'),(3,'Age','Fairness related to age'),(4,'...
SELECT DISTINCT category, description FROM fairness_categories ORDER BY category ASC;
What is the average water consumption for organic cotton production in Southeast Asia?
CREATE TABLE water_consumption (region VARCHAR(50),water_consumption INT); INSERT INTO water_consumption (region,water_consumption) VALUES ('North America',2000),('South America',2500),('Southeast Asia',1700),('Europe',1800),('Africa',2200);
SELECT region, AVG(water_consumption) FROM water_consumption WHERE region = 'Southeast Asia';
Identify the number of species in the 'endangered_species' table.
CREATE TABLE endangered_species (name VARCHAR(255),status VARCHAR(50));
SELECT COUNT(*) FROM endangered_species;
What is the total number of public transportation users in the cities of New York and Boston?
CREATE TABLE TransitUsersNew (id INT,city VARCHAR(50),usage INT); INSERT INTO TransitUsersNew (id,city,usage) VALUES (1,'New York',5000); INSERT INTO TransitUsersNew (id,city,usage) VALUES (2,'Boston',3000);
SELECT SUM(usage) FROM TransitUsersNew WHERE city IN ('New York', 'Boston');
Insert a new record with sensor type 'moisture' and a value of 45.3 in field 5 at 2023-02-18 10:00:00.
CREATE TABLE field_sensors (field_id INT,sensor_type VARCHAR(20),value FLOAT,timestamp TIMESTAMP);
INSERT INTO field_sensors (field_id, sensor_type, value, timestamp) VALUES (5, 'moisture', 45.3, '2023-02-18 10:00:00');
Show the number of engines produced by each manufacturer
CREATE TABLE rocket_engines (engine_name VARCHAR(20),manufacturer VARCHAR(20),thrust INT,fuel_type VARCHAR(10)); INSERT INTO rocket_engines (engine_name,manufacturer,thrust,fuel_type) VALUES ('RS-25','Pratt & Whitney',1890000,'Liquid'),('Merlin','SpaceX',845000,'Liquid'),('RD-180','NPO Energomash',1888000,'Liquid');
SELECT manufacturer, COUNT(*) FROM rocket_engines GROUP BY manufacturer;
What is the total funding received by biotech startups, grouped by the industry sector they operate in.
CREATE TABLE startups (id INT,name TEXT,industry TEXT,funding FLOAT); INSERT INTO startups (id,name,industry,funding) VALUES (1,'Genetech','Pharmaceuticals',50000000); INSERT INTO startups (id,name,industry,funding) VALUES (2,'BioSteward','Bioinformatics',75000000);
SELECT industry, SUM(funding) FROM startups GROUP BY industry;
Identify the vessels that have visited the port of 'Tianjin' but have not carried any cargo.
CREATE TABLE ports (id INT,name VARCHAR(50),location VARCHAR(50),un_code VARCHAR(10)); CREATE TABLE vessels (id INT,name VARCHAR(50),type VARCHAR(50),year_built INT,port_id INT); CREATE TABLE captains (id INT,name VARCHAR(50),age INT,license_number VARCHAR(20),vessel_id INT); CREATE TABLE cargo (id INT,description VARC...
SELECT DISTINCT vessels.name FROM vessels LEFT JOIN cargo ON vessels.id = cargo.vessel_id WHERE cargo.vessel_id IS NULL AND vessels.port_id IN (SELECT id FROM ports WHERE name = 'Tianjin');
What is the average carbon intensity of the power sector in the South Asian region for the years 2018 to 2020?
CREATE TABLE power_sector (country VARCHAR(50),region VARCHAR(50),year INT,carbon_intensity FLOAT); INSERT INTO power_sector (country,region,year,carbon_intensity) VALUES ('India','South Asia',2018,0.75); INSERT INTO power_sector (country,region,year,carbon_intensity) VALUES ('India','South Asia',2019,0.70); INSERT INT...
SELECT region, AVG(carbon_intensity) FROM power_sector WHERE region = 'South Asia' AND year BETWEEN 2018 AND 2020 GROUP BY region;
Find the number of animals in each status category, ordered by the number of animals in each category in descending order
CREATE TABLE animals (id INT,name VARCHAR(50),status VARCHAR(20)); INSERT INTO animals (id,name,status) VALUES (1,'Tiger','Endangered'); INSERT INTO animals (id,name,status) VALUES (2,'Elephant','Vulnerable'); INSERT INTO animals (id,name,status) VALUES (3,'Rhino','Critically Endangered'); INSERT INTO animals (id,name,...
SELECT status, COUNT(*) FROM animals GROUP BY status ORDER BY COUNT(*) DESC;
What is the average age of policyholders with auto insurance policies in Texas?
CREATE TABLE policyholders (id INT,state VARCHAR(2),policy_type VARCHAR(20),age INT); INSERT INTO policyholders (id,state,policy_type,age) VALUES (1,'TX','Auto',30),(2,'TX','Health',40),(3,'TX','Auto',50);
SELECT AVG(age) FROM policyholders WHERE state = 'TX' AND policy_type = 'Auto';
What are the top 10 most common donor locations, along with the number of donors from each?
CREATE TABLE locations (location_id INT,location TEXT); INSERT INTO locations (location_id,location) VALUES (1,'New York'),(2,'Los Angeles'),(3,'Toronto'),(4,'Mumbai'),(5,'London');
SELECT l.location, COUNT(dn.donor_id) as donor_count FROM donors dn JOIN locations l ON SUBSTRING_INDEX(dn.address, ' ', 1) = l.location GROUP BY l.location ORDER BY donor_count DESC LIMIT 10;
How many military equipment incidents occurred in each month in 2021?
CREATE TABLE military_equipment_incidents (incident_date DATE,incident_type VARCHAR(255)); INSERT INTO military_equipment_incidents (incident_date,incident_type) VALUES ('2021-01-01','Malfunction'),('2021-01-15','Collision'),('2021-03-20','Theft'),('2021-04-01','Malfunction'),('2021-05-01','Collision'),('2021-05-15','T...
SELECT DATE_TRUNC('month', incident_date) AS month, COUNT(*) as num_incidents FROM military_equipment_incidents WHERE incident_date BETWEEN '2021-01-01' AND '2021-12-31' GROUP BY month ORDER BY month;
List all clients who have not paid their bills in full.
CREATE TABLE clients (client_id INT,name TEXT); CREATE TABLE bills (bill_id INT,client_id INT,amount DECIMAL(10,2),paid BOOLEAN);
SELECT c.client_id, c.name FROM clients c JOIN bills b ON c.client_id = b.client_id WHERE b.paid = FALSE;
Delete records in the menu_engineering table where the sales_volume is greater than 100
CREATE TABLE menu_engineering (item_name VARCHAR(50),sales_volume INT);
DELETE FROM menu_engineering WHERE sales_volume > 100;
What is the total installed renewable energy capacity in Africa and South America as of 2020?
CREATE TABLE RenewableCapacity (Continent TEXT,Year INT,Capacity NUMBER); INSERT INTO RenewableCapacity (Continent,Year,Capacity) VALUES ('Africa',2020,120000),('South America',2020,180000); CREATE TABLE FossilFuelCapacity (Continent TEXT,Year INT,Capacity NUMBER); INSERT INTO FossilFuelCapacity (Continent,Year,Capacit...
SELECT RenewableCapacity.Continent, SUM(RenewableCapacity.Capacity) AS Total_Renewable_Capacity FROM RenewableCapacity WHERE RenewableCapacity.Continent IN ('Africa', 'South America') AND RenewableCapacity.Year = 2020 GROUP BY RenewableCapacity.Continent;
What is the total number of workplace safety incidents reported in the year 2020?
CREATE TABLE Workplace_Safety_Incidents (id INT,union VARCHAR(255),incident_type VARCHAR(255),reported_date DATE); INSERT INTO Workplace_Safety_Incidents (id,union,incident_type,reported_date) VALUES (1,'Union A','Chemical Spill','2020-01-05');
SELECT COUNT(*) FROM Workplace_Safety_Incidents WHERE YEAR(reported_date) = 2020;
What is the maximum number of shares held by a single customer for the 'AAPL' stock?
CREATE TABLE holdings (holding_id INT,customer_id INT,ticker VARCHAR(10),shares INT); INSERT INTO holdings (holding_id,customer_id,ticker,shares) VALUES (1,1,'AAPL',100),(2,1,'MSFT',75),(3,2,'AAPL',150),(4,3,'JPM',200),(5,4,'AAPL',250),(6,5,'TSLA',50);
SELECT MAX(shares) FROM holdings WHERE ticker = 'AAPL';
How many 'railroad_sections' are there in 'Suburban' locations?
CREATE TABLE railroad_sections (id INT,section_name VARCHAR(50),location VARCHAR(50)); INSERT INTO railroad_sections (id,section_name,location) VALUES (1,'Section 1','Urban'),(2,'Section 2','Suburban'),(3,'Section 3','Rural');
SELECT COUNT(*) FROM railroad_sections WHERE location = 'Suburban';
Which biotech startups have received funding in Australia?
CREATE TABLE startups (id INT,name VARCHAR(100),location VARCHAR(50),industry VARCHAR(50),funding FLOAT); INSERT INTO startups (id,name,location,industry,funding) VALUES (1,'StartupA','AU','Biotech',1000000.0); INSERT INTO startups (id,name,location,industry,funding) VALUES (2,'StartupB','CA','Software',2000000.0); INS...
SELECT name FROM startups WHERE location = 'AU' AND industry = 'Biotech';
What is the average data usage for mobile subscribers in each country?
CREATE TABLE mobile_subscribers (subscriber_id INT,country VARCHAR(50),data_usage INT); INSERT INTO mobile_subscribers (subscriber_id,country,data_usage) VALUES (1,'China',100),(2,'Brazil',150),(3,'Indonesia',200),(4,'Russia',250),(5,'China',50),(6,'Brazil',75),(7,'Indonesia',125),(8,'Russia',175);
SELECT country, AVG(data_usage) AS avg_data_usage FROM mobile_subscribers GROUP BY country;
What is the average sentiment score for articles published in a specific language, grouped by day?
CREATE TABLE Sentiments (id INT PRIMARY KEY,sentiment FLOAT); INSERT INTO Sentiments (id,sentiment) VALUES (1,0.5),(2,0.7),(3,0.6); CREATE TABLE Articles (id INT PRIMARY KEY,title TEXT,language_id INT,sentiment_id INT,FOREIGN KEY (language_id) REFERENCES Languages(id),FOREIGN KEY (sentiment_id) REFERENCES Sentiments(id...
SELECT l.language, DATE_FORMAT(a.date, '%Y-%m-%d') as date, AVG(s.sentiment) as avg_sentiment FROM Articles a JOIN Languages l ON a.language_id = l.id JOIN Sentiments s ON a.sentiment_id = s.id GROUP BY l.language, date;
What is the total quantity of all items shipped from warehouse 'LAX' and 'NYC'?
CREATE TABLE shipments (shipment_id INT,item_code VARCHAR(5),warehouse_id VARCHAR(5),quantity INT); CREATE TABLE warehouses (warehouse_id VARCHAR(5),city VARCHAR(5),state VARCHAR(3)); INSERT INTO shipments VALUES (1,'AAA','LAX',200),(2,'BBB','NYC',300),(3,'AAA','LAX',100),(4,'CCC','NYC',50),(5,'BBB','LAX',150); INSERT ...
SELECT SUM(quantity) FROM shipments JOIN warehouses ON shipments.warehouse_id = warehouses.warehouse_id WHERE warehouses.city IN ('LAX', 'NYC');
List policy types and their respective average claim amounts.
CREATE TABLE PolicyTypes (PolicyTypeID int,PolicyType varchar(20)); CREATE TABLE Claims (ClaimID int,PolicyTypeID int,ClaimAmount decimal); INSERT INTO PolicyTypes (PolicyTypeID,PolicyType) VALUES (1,'Home'); INSERT INTO PolicyTypes (PolicyTypeID,PolicyType) VALUES (2,'Auto'); INSERT INTO Claims (ClaimID,PolicyTypeID,C...
SELECT PolicyTypes.PolicyType, AVG(Claims.ClaimAmount) FROM PolicyTypes INNER JOIN Claims ON PolicyTypes.PolicyTypeID = Claims.PolicyTypeID GROUP BY PolicyTypes.PolicyType;
How many creative AI applications have been developed in Africa?
CREATE TABLE ai_applications (app_id INT,name TEXT,country TEXT,category TEXT); INSERT INTO ai_applications (app_id,name,country,category) VALUES (1,'ArtBot','Nigeria','Creative'),(2,'MusicGen','South Africa','Creative'),(3,'DataViz','US','Analytical'),(4,'ChatAssist','Canada','Assistive');
SELECT COUNT(*) FROM ai_applications WHERE country IN (SELECT country FROM ai_applications WHERE category = 'Creative') AND category = 'Creative';
Delete all records in the military_innovations table where the innovation_name contains 'cyber'
CREATE TABLE military_innovations (innovation_id INT,innovation_name VARCHAR(50),innovation_year INT,innovation_description TEXT);
DELETE FROM military_innovations WHERE innovation_name LIKE '%cyber%';