instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
How many renewable energy projects were completed in Texas between 2015 and 2018?
CREATE TABLE projects (id INT,state VARCHAR(50),project_type VARCHAR(50),completion_year INT); INSERT INTO projects (id,state,project_type,completion_year) VALUES (1,'Texas','Solar',2016),(2,'Texas','Wind',2017),(3,'California','Geothermal',2015),(4,'Texas','Wind',2018),(5,'Texas','Solar',2015);
SELECT COUNT(*) FROM projects WHERE state = 'Texas' AND project_type IN ('Solar', 'Wind') AND completion_year BETWEEN 2015 AND 2018;
Find the bank with the lowest average loan amount for socially responsible lending, along with their average loan amount?
CREATE TABLE SOCIALLY_RESPONSIBLE_LOANS (BANK_NAME VARCHAR(50),AMOUNT NUMBER(12,2)); INSERT INTO SOCIALLY_RESPONSIBLE_LOANS VALUES ('Bank C',20000); INSERT INTO SOCIALLY_RESPONSIBLE_LOANS VALUES ('Bank D',25000); INSERT INTO SOCIALLY_RESPONSIBLE_LOANS VALUES ('Bank C',30000); INSERT INTO SOCIALLY_RESPONSIBLE_LOANS VALUES ('Bank E',15000);
SELECT BANK_NAME, AVG(AMOUNT) AVERAGE_LOAN FROM SOCIALLY_RESPONSIBLE_LOANS GROUP BY BANK_NAME HAVING COUNT(*) = (SELECT MIN(COUNT(*)) FROM SOCIALLY_RESPONSIBLE_LOANS GROUP BY BANK_NAME);
Delete the environmental impact stats for the 'Ruby Rise' mine in South Africa from the "environmental_impact" table
CREATE TABLE environmental_impact (mine_id INT,year INT,co2_emissions INT,water_consumption INT,waste_generation INT);
DELETE FROM environmental_impact WHERE mine_id = 5 AND year = 2020;
Insert a new record in the "accidents" table for vessel 107 with date 2018-12-31, description "Collision", and severity 5
CREATE TABLE accidents (id INT,vessel_id INT,date DATE,description TEXT,severity INT);
INSERT INTO accidents (id, vessel_id, date, description, severity) VALUES (NULL, 107, '2018-12-31', 'Collision', 5);
Find the number of volunteers who joined in Q2 2021 and the number of hours they contributed in their first month.
CREATE TABLE Volunteers (VolunteerID int,VolunteerName varchar(50),JoinDate date,FirstMonthEndDate date,TotalHours int); INSERT INTO Volunteers VALUES (1,'Jane Doe','2021-04-15','2021-05-31',20);
SELECT COUNT(DISTINCT VolunteerID), SUM(TotalHours) FROM Volunteers WHERE JoinDate BETWEEN '2021-04-01' AND '2021-06-30' AND FirstMonthEndDate = DATE_ADD(JoinDate, INTERVAL 1 MONTH)
What is the percentage of funding for workshops and classes from foundation sources?
CREATE TABLE funding_sources (id INT,name VARCHAR(255),type VARCHAR(255)); INSERT INTO funding_sources (id,name,type) VALUES (1,'Foundation','foundation'),(2,'Private','private'),(3,'Corporate','corporate'); CREATE TABLE workshops (id INT,name VARCHAR(255),funding_source_id INT); INSERT INTO workshops (id,name,funding_source_id) VALUES (1,'WorkshopA',1),(2,'WorkshopB',2),(3,'WorkshopC',3); CREATE TABLE classes (id INT,name VARCHAR(255),funding_source_id INT); INSERT INTO classes (id,name,funding_source_id) VALUES (1,'ClassA',1),(2,'ClassB',2),(3,'ClassC',3);
SELECT (COUNT(CASE WHEN f.name = 'Foundation' AND t.type IN ('workshops', 'classes') THEN 1 END) * 100.0 / COUNT(*)) AS foundation_funding_percentage FROM funding_sources f JOIN workshops w ON f.id = w.funding_source_id JOIN classes c ON f.id = c.funding_source_id JOIN (VALUES ('workshops'), ('classes')) AS t(type) ON TRUE
What is the average age of male patients in the 'Asian' ethnicity group?
CREATE TABLE patients (id INT,name VARCHAR(50),age INT,gender VARCHAR(10),ethnicity VARCHAR(50)); INSERT INTO patients (id,name,age,gender,ethnicity) VALUES (1,'John Doe',45,'Male','Asian'),(2,'Jane Smith',35,'Female','African American'),(3,'Alice Johnson',50,'Female','Hispanic'),(4,'Bob Lee',60,'Male','Asian');
SELECT AVG(age) FROM patients WHERE gender = 'Male' AND ethnicity = 'Asian';
What is the total number of security incidents reported in the Sales department in the last month?
CREATE TABLE security_incidents (id INT,date DATE,department VARCHAR(255)); INSERT INTO security_incidents (id,date,department) VALUES (1,'2022-02-01','IT'),(2,'2022-02-05','HR'),(3,'2022-01-07','IT'),(4,'2022-02-10','Sales');
SELECT COUNT(*) FROM security_incidents WHERE department = 'Sales' AND date >= DATEADD(month, -1, GETDATE());
Who is responsible for monitoring ocean floor mapping in the Arctic region?
CREATE TABLE ocean_floor_map (map_id INT,map_name VARCHAR(50),region VARCHAR(50),agency VARCHAR(50));
SELECT agency FROM ocean_floor_map WHERE region = 'Arctic';
How many products are certified cruelty-free in each country?
CREATE TABLE products (product_id INT,country VARCHAR(20),certified_cruelty_free BOOLEAN); INSERT INTO products (product_id,country,certified_cruelty_free) VALUES (1,'USA',true),(2,'Canada',false),(3,'USA',true);
SELECT country, COUNT(*) FROM products WHERE certified_cruelty_free = true GROUP BY country;
What is the average salary of workers in the manufacturing industry by job role in Canada, for roles with more than 500 employees?
CREATE TABLE workers (id INT,name VARCHAR(50),country VARCHAR(50),job_role VARCHAR(50),salary DECIMAL(10,2),employees INT);
SELECT job_role, AVG(salary) as avg_salary FROM workers WHERE country = 'Canada' GROUP BY job_role HAVING employees > 500;
What is the average cost of naval military technology developed in the 'military_technology' table for the year 2020?
CREATE TABLE military_technology (id INT,technology_name TEXT,type TEXT,development_cost FLOAT,development_year INT); INSERT INTO military_technology (id,technology_name,type,development_cost,development_year) VALUES (1,'Stealth Bomber','Aircraft',50000000,2019),(2,'Submarine','Naval',300000000,2020),(3,'Cybersecurity Software','Software',5000000,2019);
SELECT AVG(development_cost) FROM military_technology WHERE type = 'Naval' AND development_year = 2020;
What is the total revenue for each dessert?
CREATE TABLE desserts (dessert VARCHAR(255),revenue DECIMAL(10,2)); INSERT INTO desserts VALUES ('Cake',3000.00),('Ice Cream',2500.00),('Cake',1000.00);
SELECT dessert, SUM(revenue) FROM desserts GROUP BY dessert;
Which electric vehicle models are most popular in Berlin?
CREATE TABLE electric_vehicles (vehicle_id INT,vehicle_model VARCHAR(50),total_sold INT,city VARCHAR(50)); INSERT INTO electric_vehicles (vehicle_id,vehicle_model,total_sold,city) VALUES (1,'Tesla Model 3',1200,'Berlin'),(2,'Nissan Leaf',800,'Berlin');
SELECT vehicle_model, SUM(total_sold) FROM electric_vehicles WHERE city = 'Berlin' GROUP BY vehicle_model ORDER BY SUM(total_sold) DESC;
What is the total number of military personnel in the 'army' branch, per country?
CREATE TABLE military_personnel (country VARCHAR(50),branch VARCHAR(50),number INT); INSERT INTO military_personnel (country,branch,number) VALUES ('USA','Army',470000),('Russia','Army',350000),('China','Army',1700000);
SELECT country, SUM(number) as total_army_personnel FROM military_personnel WHERE branch = 'Army' GROUP BY country;
Delete records in the player_achievements table where the achievement_id is greater than 3
CREATE TABLE player_achievements (achievement_id INT,achievement_name VARCHAR(30));
DELETE FROM player_achievements WHERE achievement_id > 3;
What is the average monthly data usage for postpaid mobile customers in the Midwest region, grouped by their billing tier?
CREATE TABLE postpaid_mobile (customer_id INT,data_usage FLOAT,billing_tier VARCHAR(20),region VARCHAR(20));
SELECT billing_tier, AVG(data_usage) FROM postpaid_mobile WHERE region = 'Midwest' AND type = 'postpaid' GROUP BY billing_tier;
What is the maximum daily wastewater discharge for industrial use in each state of the US, for the year 2020, categorized by industry?
CREATE TABLE us_industrial_wastewater (state VARCHAR(255),year INT,industry VARCHAR(255),discharge FLOAT); INSERT INTO us_industrial_wastewater (state,year,industry,discharge) VALUES ('California',2020,'Manufacturing',1200000),('California',2020,'Agriculture',800000),('California',2020,'Mining',500000),('Texas',2020,'Manufacturing',1500000),('Texas',2020,'Agriculture',900000),('Texas',2020,'Mining',700000);
SELECT state, industry, MAX(discharge) as max_daily_discharge FROM us_industrial_wastewater WHERE year = 2020 GROUP BY state, industry;
Identify the month with the most consumer preferences collected in 2022.
CREATE TABLE ConsumerPreference (product_id INT,consumer_id INT,preference_rating INT,preference_date DATE); INSERT INTO ConsumerPreference (product_id,consumer_id,preference_rating,preference_date) VALUES (1,101,4,'2022-05-01'); INSERT INTO ConsumerPreference (product_id,consumer_id,preference_rating,preference_date) VALUES (2,101,5,'2022-05-02'); INSERT INTO ConsumerPreference (product_id,consumer_id,preference_rating,preference_date) VALUES (3,103,3,'2022-03-02');
SELECT EXTRACT(MONTH FROM preference_date) as month, COUNT(*) as num_preferences FROM ConsumerPreference WHERE preference_date >= '2022-01-01' AND preference_date <= '2022-12-31' GROUP BY month ORDER BY num_preferences DESC LIMIT 1;
Insert data into 'events' table from a CSV file
CREATE TABLE events (name VARCHAR(255),date DATE,attendance INT);
INSERT INTO events (name, date, attendance) SELECT * FROM csv_file('events.csv') AS t(name VARCHAR(255), date DATE, attendance INT);
How many games did the 'Boston Celtics' play in the 'NBA' in the year 2020?
CREATE TABLE teams (team_id INT,team_name TEXT,league TEXT); INSERT INTO teams (team_id,team_name,league) VALUES (1,'Boston Celtics','NBA'); CREATE TABLE games (game_id INT,team_id INT,season_year INT,wins INT,losses INT); INSERT INTO games (game_id,team_id,season_year,wins,losses) VALUES (1,1,2020,43,29),(2,1,2019,48,34);
SELECT COUNT(game_id) FROM games WHERE team_id = (SELECT team_id FROM teams WHERE team_name = 'Boston Celtics') AND season_year = 2020;
What is the total number of schools in each country?
CREATE TABLE Countries (CountryID INT,CountryName VARCHAR(100)); INSERT INTO Countries (CountryID,CountryName) VALUES (1,'Afghanistan'),(2,'Albania'); CREATE TABLE Schools (SchoolID INT,SchoolName VARCHAR(100),CountryID INT); INSERT INTO Schools (SchoolID,SchoolName,CountryID) VALUES (1,'School1',1),(2,'School2',1),(3,'School3',2);
SELECT CountryName, COUNT(*) as TotalSchools FROM Schools JOIN Countries ON Schools.CountryID = Countries.CountryID GROUP BY CountryName;
What is the average calorie intake per meal for each country in the 'nutrition' table, ordered by average calorie intake in descending order, and limited to the top 2 countries?
CREATE TABLE nutrition (country VARCHAR(255),calories INT,meal_time TIME); INSERT INTO nutrition (country,calories,meal_time) VALUES ('USA',800,'Breakfast'),('USA',1200,'Lunch'),('USA',500,'Dinner'),('India',500,'Breakfast'),('India',700,'Lunch'),('India',600,'Dinner'),('Canada',600,'Breakfast'),('Canada',800,'Lunch'),('Canada',400,'Dinner');
SELECT country, AVG(calories) as avg_calories FROM nutrition GROUP BY country ORDER BY avg_calories DESC LIMIT 2;
Determine the total financial capability training hours for employees in microfinance organizations in Asia
CREATE TABLE AsiaMicrofinance (id INT,employee_id INT,training_hours INT); INSERT INTO AsiaMicrofinance (id,employee_id,training_hours) VALUES (1,1,25),(2,2,35);
SELECT SUM(training_hours) FROM AsiaMicrofinance;
List all satellites with their launch dates and countries of origin.
CREATE TABLE Satellites (SatelliteID INT,Name VARCHAR(50),LaunchDate DATETIME,CountryOfOrigin VARCHAR(50)); INSERT INTO Satellites (SatelliteID,Name,LaunchDate,CountryOfOrigin) VALUES (1,'Sat1','2020-01-01','USA'),(2,'Sat2','2019-05-15','Germany');
SELECT Name, LaunchDate, CountryOfOrigin FROM Satellites;
How many wildlife species are present in each forest type?
CREATE TABLE ForestTypes (id INT,name VARCHAR(255)); INSERT INTO ForestTypes (id,name) VALUES (1,'Coniferous'),(2,'Deciduous'),(3,'Mixed'); CREATE TABLE Wildlife (id INT,forest_type_id INT,species VARCHAR(255)); INSERT INTO Wildlife (id,forest_type_id,species) VALUES (1,1,'Squirrel'),(2,1,'Deer'),(3,2,'Raccoon'),(4,2,'Bear'),(5,3,'Fox'),(6,3,'Owl');
SELECT f.forest_type_id, f.name AS forest_type_name, COUNT(w.id) AS species_count FROM ForestTypes f LEFT JOIN Wildlife w ON f.id = w.forest_type_id GROUP BY f.id;
Identify the top 3 cruelty-free certified cosmetic products with the highest sales volume that contain 'rose' as an ingredient in the Canadian market.
CREATE TABLE ingredients (ingredient_id INT,product_id INT,ingredient_name VARCHAR(50)); INSERT INTO ingredients (ingredient_id,product_id,ingredient_name) VALUES (1,1,'aloe vera'),(2,2,'lavender'),(3,4,'rose'),(4,5,'rose'); CREATE TABLE products (product_id INT,product_name VARCHAR(100),sales INT,certification VARCHAR(20)); INSERT INTO products (product_id,product_name,sales,certification) VALUES (1,'Lipstick A',6000,'cruelty-free'),(2,'Mascara B',7000,'not_certified'),(4,'Lotion D',9000,'cruelty-free'),(5,'Serum E',10000,'cruelty-free'); CREATE TABLE countries (country_code CHAR(2),country_name VARCHAR(50)); INSERT INTO countries (country_code,country_name) VALUES ('CA','Canada');
SELECT products.product_name, products.sales FROM ingredients JOIN products ON ingredients.product_id = products.product_id JOIN countries ON products.country_code = countries.country_code WHERE ingredients.ingredient_name = 'rose' AND products.certification = 'cruelty-free' AND countries.country_name = 'Canada' ORDER BY products.sales DESC LIMIT 3;
What is the total cost of each space mission and the average cost of all space missions?
CREATE TABLE SpaceMissionCosts (id INT,mission VARCHAR(255),cost INT); INSERT INTO SpaceMissionCosts (id,mission,cost) VALUES (1,'Apollo 11',25500000); INSERT INTO SpaceMissionCosts (id,mission,cost) VALUES (2,'Apollo 13',35500000);
SELECT mission, cost FROM SpaceMissionCosts; SELECT AVG(cost) as avg_cost FROM SpaceMissionCosts;
What is the total amount donated by individual donors who have donated more than once in the last 12 months, and their names?
CREATE TABLE donors(id INT,name TEXT,total_donation FLOAT);CREATE TABLE donations(id INT,donor_id INT,amount FLOAT,donation_date DATE);
SELECT d.name, SUM(donations.amount) as total_donation FROM donations JOIN donors ON donations.donor_id = donors.id WHERE donations.donation_date BETWEEN DATE_SUB(CURDATE(), INTERVAL 12 MONTH) AND CURDATE() GROUP BY donors.id HAVING COUNT(donations.id) > 1;
Insert a new record for 'Sophia Kim' with a salary of $90,000 in the 'gas' industry in British Columbia, Canada.
CREATE TABLE workers (id INT,name VARCHAR(50),industry VARCHAR(50),salary FLOAT,country VARCHAR(50)); INSERT INTO workers (id,name,industry,salary,country) VALUES (1,'John Doe','oil',60000,'Canada'); INSERT INTO workers (id,name,industry,salary,country) VALUES (2,'Jane Smith','gas',65000,'Canada'); INSERT INTO workers (id,name,industry,salary,country) VALUES (3,'Mike Johnson','gas',70000,'Canada'); CREATE TABLE provinces (id INT,name VARCHAR(50),country VARCHAR(50)); INSERT INTO provinces (id,name,country) VALUES (1,'Alberta','Canada'); INSERT INTO provinces (id,name,country) VALUES (2,'British Columbia','Canada');
INSERT INTO workers (name, industry, salary, country) VALUES ('Sophia Kim', 'gas', 90000, 'Canada');
What is the total number of workouts for each user in the 'workout_data' table?
CREATE TABLE workout_data (user_id INT,workout_type VARCHAR(20),duration INT); INSERT INTO workout_data (user_id,workout_type,duration) VALUES (1,'Running',30),(1,'Cycling',60),(2,'Yoga',45),(3,'Pilates',50);
SELECT user_id, COUNT(*) as total_workouts FROM workout_data GROUP BY user_id;
What is the market share of drug 'ABC-456' in Canada in Q4 2021?
CREATE TABLE market_share (drug_name TEXT,region TEXT,market_share FLOAT,quarter INT,year INT); INSERT INTO market_share (drug_name,region,market_share,quarter,year) VALUES ('XYZ-123','USA',0.50,4,2021),('ABC-456','Canada',0.60,4,2021),('DEF-789','USA',0.40,4,2021);
SELECT market_share FROM market_share WHERE drug_name = 'ABC-456' AND region = 'Canada' AND quarter = 4 AND year = 2021;
Find the average water temperature for fish species in the Arctic Ocean with a maximum size over 100 cm.
CREATE TABLE oceans (id INT,name VARCHAR(50)); CREATE TABLE species (id INT,ocean_id INT,name VARCHAR(50),max_size FLOAT,avg_temp FLOAT); INSERT INTO oceans VALUES (1,'Arctic Ocean'); INSERT INTO species VALUES (1,1,'Greenland Shark',180,-0.5),(2,1,'Beluga Whale',150,-1.5),(3,1,'Narwhal',120,-1.8);
SELECT AVG(s.avg_temp) as avg_temp FROM species s INNER JOIN oceans o ON s.ocean_id = o.id WHERE o.name = 'Arctic Ocean' AND s.max_size > 100;
Update the device model for user 'Oliver Kim' to 'Polar Vantage M'
CREATE TABLE wearable_device (user_id INT,name VARCHAR(50),device_model VARCHAR(50)); INSERT INTO wearable_device (user_id,name,device_model) VALUES (5,'Oliver Kim','Fitbit Charge 4');
WITH updated_device AS (UPDATE wearable_device SET device_model = 'Polar Vantage M' WHERE name = 'Oliver Kim' RETURNING *) SELECT * FROM updated_device;
Find the total cost of road projects in California
CREATE TABLE Road_Projects (project_id int,project_name varchar(255),state varchar(255),cost decimal(10,2));
SELECT SUM(cost) FROM Road_Projects WHERE state = 'California';
Insert a new record into the 'conservation_efforts' table
CREATE TABLE conservation_efforts (id INT PRIMARY KEY,location VARCHAR(50),start_date DATE,end_date DATE,effort_description VARCHAR(255));
INSERT INTO conservation_efforts (id, location, start_date, end_date, effort_description) VALUES (1, 'Coral Reef Restoration', '2022-01-01', '2025-12-31', 'Restoring and preserving coral reefs in the Caribbean.');
List the total display duration for each artist from Mexico who have exhibited at 'Artistic Wonders' gallery, ordered by total display duration from highest to lowest.
CREATE TABLE Artists (ArtistID INT,ArtistName VARCHAR(50),Nationality VARCHAR(50),ActiveYears INT,Gender VARCHAR(10));CREATE TABLE Paintings (PaintingID INT,PaintingName VARCHAR(50),ArtistID INT,DisplayStart DATE,DisplayEnd DATE);CREATE TABLE Gallery (GalleryID INT,GalleryName VARCHAR(50),City VARCHAR(50));INSERT INTO Artists VALUES (1,'Claude Monet','French',67,'Male'); INSERT INTO Paintings VALUES (1,'Water Lilies',1,'2020-01-01','2021-12-31'); INSERT INTO Gallery VALUES (1,'Artistic Wonders','Paris');
SELECT Artists.ArtistName, SUM(DATEDIFF(DisplayEnd, DisplayStart)) AS TotalDisplayDays FROM Paintings JOIN Artists ON Paintings.ArtistID = Artists.ArtistID JOIN Gallery ON Paintings.GalleryID = Gallery.GalleryID WHERE GalleryName = 'Artistic Wonders' AND Nationality = 'Mexico' GROUP BY Artists.ArtistName ORDER BY TotalDisplayDays DESC;
Identify traditional art forms that were listed in the database after the year 2000, and their respective artists.
CREATE TABLE traditional_arts (art_id INT,art_name TEXT,art_type TEXT,artist TEXT,listed_year INT); INSERT INTO traditional_arts (art_id,art_name,art_type,artist,listed_year) VALUES (1,'Thangka Painting','Painting','Sonam',2005),(2,'Talavera Pottery','Pottery','Rafael',2002);
SELECT art_name, artist FROM traditional_arts WHERE listed_year > 2000;
What is the minimum number of likes on posts in the "Science" category from creators who identify as LGBTQ+?
CREATE TABLE Posts (id INT,title VARCHAR(255),content_creator_name VARCHAR(100),content_creator_identity VARCHAR(50),category VARCHAR(50),likes INT); INSERT INTO Posts (id,title,content_creator_name,content_creator_identity,category,likes) VALUES (1,'Post1','Creator1','LGBTQ+','Science',10),(2,'Post2','Creator2','Straight','Science',15),(3,'Post3','Creator3','LGBTQ+','History',20);
SELECT MIN(likes) FROM Posts WHERE content_creator_identity = 'LGBTQ+' AND category = 'Science';
List all athletes who have participated in a specific sport and have an age above the average age.
CREATE TABLE athletes (id INT,name VARCHAR(50),age INT,sport VARCHAR(50),country VARCHAR(50)); INSERT INTO athletes (id,name,age,sport,country) VALUES (1,'John Doe',30,'Basketball','USA'),(2,'Jane Smith',25,'Basketball','Canada'),(3,'Pedro Martinez',35,'Soccer','Mexico'),(4,'Sophia Rodriguez',28,'Soccer','Brazil'),(5,'Michael Johnson',32,'Athletics','USA');
SELECT * FROM athletes WHERE sport = 'Basketball' AND age > (SELECT AVG(age) FROM athletes WHERE sport = 'Basketball');
How many exhibitions are there in the "Modern Art" category?
CREATE TABLE Exhibitions (ExhibitionID INT,ExhibitionName VARCHAR(255),Category VARCHAR(255)); INSERT INTO Exhibitions (ExhibitionID,ExhibitionName,Category) VALUES (1,'Contemporary Art Exhibition','Modern Art'),(2,'Modern Art Exhibition','Modern Art');
SELECT COUNT(DISTINCT ExhibitionName) FROM Exhibitions WHERE Category = 'Modern Art';
What is the average oil production per well in the Permian Basin for 2019?
CREATE TABLE permian_basin_oil_production (well VARCHAR(255),year INT,production FLOAT);
SELECT AVG(production) FROM permian_basin_oil_production WHERE well LIKE '%Permian Basin%' AND year = 2019;
Identify users who have a higher heart rate on Monday than on any other day of the week.
CREATE TABLE HeartRates (user_id INT,workout_date DATE,heart_rate INT); INSERT INTO HeartRates (user_id,workout_date,heart_rate) VALUES (1,'2022-01-01',80),(1,'2022-01-02',90),(2,'2022-01-01',70),(2,'2022-01-02',80);
SELECT user_id FROM HeartRates WHERE EXTRACT(DAYOFWEEK FROM workout_date) = 2 AND heart_rate > (SELECT MAX(heart_rate) FROM HeartRates WHERE user_id = HeartRates.user_id AND EXTRACT(DAYOFWEEK FROM workout_date) NOT IN (2)) GROUP BY user_id HAVING COUNT(*) > 0;
What is the average weight of fish in the 'Indian Ocean'?
CREATE TABLE Farm (id INT,farm_name TEXT,region TEXT,species TEXT,weight FLOAT,age INT); INSERT INTO Farm (id,farm_name,region,species,weight,age) VALUES (1,'OceanPacific','Pacific','Tilapia',500.3,2),(2,'SeaBreeze','Atlantic','Salmon',300.1,1),(3,'OceanPacific','Pacific','Tilapia',600.5,3),(4,'FarmX','Atlantic','Salmon',700.2,4),(5,'SeaBreeze','Atlantic','Tilapia',400,2),(6,'AquaFarm','Indian Ocean','Tuna',900,5);
SELECT AVG(weight) FROM Farm WHERE region = 'Indian Ocean';
What is the maximum number of members in a union in France?
CREATE TABLE UnionMembers (id INT,union_name VARCHAR(50),country VARCHAR(50),member_count INT); INSERT INTO UnionMembers (id,union_name,country,member_count) VALUES (1,'United Steelworkers','USA',200000),(2,'UNITE HERE','USA',300000),(3,'TUC','UK',6000000),(4,'CUPE','Canada',650000),(5,'USW','Canada',120000),(6,'CGT','France',670000),(7,'CFDT','France',630000);
SELECT MAX(member_count) as max_members FROM UnionMembers WHERE country = 'France';
Find the total revenue and quantity of ethically sourced products sold in 2021
CREATE TABLE retail_sales (sale_id INT,product_id INT,quantity INT,revenue FLOAT,is_ethically_sourced BOOLEAN,sale_date DATE);
SELECT SUM(revenue) as total_revenue, SUM(quantity) as total_quantity FROM retail_sales WHERE is_ethically_sourced = TRUE AND sale_date BETWEEN '2021-01-01' AND '2021-12-31';
Generate a view to display the top 3 countries with the most user posts in descending order.
CREATE TABLE users (user_id INT,country VARCHAR(50)); CREATE TABLE posts (post_id INT,user_id INT,content TEXT,post_time TIMESTAMP);
CREATE VIEW top_posting_countries AS SELECT u.country, COUNT(p.post_id) AS post_count FROM users u JOIN posts p ON u.user_id = p.user_id GROUP BY u.country ORDER BY post_count DESC LIMIT 3;
What is the minimum age of patients with heart disease in Mexico?
CREATE TABLE patient_mexico (id INT,age INT,diagnosis TEXT); INSERT INTO patient_mexico (id,age,diagnosis) VALUES (1,50,'Heart Disease');
SELECT MIN(age) FROM patient_mexico WHERE diagnosis = 'Heart Disease';
What is the total revenue for all jazz albums sold on the 'streaming' platform?
CREATE TABLE artists (id INT,name TEXT,genre TEXT); CREATE TABLE albums (id INT,title TEXT,artist_id INT,platform TEXT); CREATE TABLE sales (id INT,album_id INT,quantity INT,revenue DECIMAL); CREATE VIEW jazz_albums AS SELECT a.id,a.title,a.artist_id,a.platform FROM albums a JOIN artists ar ON a.artist_id = ar.id WHERE ar.genre = 'jazz'; CREATE VIEW jazz_sales AS SELECT s.id,sa.album_id,s.quantity,s.revenue FROM sales s JOIN jazz_albums ja ON s.album_id = ja.id;
SELECT SUM(revenue) FROM jazz_sales WHERE platform = 'streaming';
What is the average response time of the police department in Los Angeles, and how many calls did they receive?
CREATE TABLE calls (id INT,city VARCHAR(255),date DATETIME,type VARCHAR(255),description TEXT,response_time INT); INSERT INTO calls (id,city,date,type,description,response_time) VALUES (1,'Los Angeles','2022-01-01 12:00:00','Emergency','Fire',10),(2,'Los Angeles','2022-01-02 13:00:00','Non-emergency','Noise complaint',20);
SELECT AVG(response_time) FROM calls WHERE city = 'Los Angeles'; SELECT COUNT(*) FROM calls WHERE city = 'Los Angeles';
Identify the defense contractors with the highest total maintenance request count for a specific time period, in this case, January 2021.
CREATE TABLE contractor_maintenance(contractor_id INT,request_date DATE,request_type VARCHAR(20)); INSERT INTO contractor_maintenance(contractor_id,request_date,request_type) VALUES (1,'2021-01-01','equipment_inspection'),(1,'2021-01-10','equipment_repair'),(2,'2021-01-05','parts_replacement'),(2,'2021-01-15','equipment_inspection'),(3,'2021-01-20','parts_replacement');
SELECT contractor_id, COUNT(*) as total_requests FROM contractor_maintenance WHERE request_date BETWEEN '2021-01-01' AND '2021-01-31' GROUP BY contractor_id ORDER BY total_requests DESC LIMIT 1;
How many deep-sea species were discovered in the Indian Ocean in the last 5 years?
CREATE TABLE deep_sea_species (id INT,name TEXT,location TEXT,year INT,discovered BOOLEAN); INSERT INTO deep_sea_species (id,name,location,year,discovered) VALUES (1,'Species A','Indian Ocean',2018,TRUE),(2,'Species B','Indian Ocean',2017,TRUE),(3,'Species C','Atlantic Ocean',2020,TRUE);
SELECT COUNT(*) FROM deep_sea_species WHERE location = 'Indian Ocean' AND discovered = TRUE AND year >= 2016;
List the names of artists who created the most number of artworks in the 'Pop Art' movement.
CREATE TABLE Artists (id INT,artist_name VARCHAR(50)); CREATE TABLE Artworks (id INT,artist_id INT,movement VARCHAR(20));
SELECT artist_name FROM Artists JOIN (SELECT artist_id, COUNT(*) AS num_of_artworks FROM Artworks WHERE movement = 'Pop Art' GROUP BY artist_id ORDER BY num_of_artworks DESC LIMIT 1) AS subquery ON Artists.id = subquery.artist_id;
List all satellites launched between 2012-01-01 and 2014-12-31
CREATE TABLE satellites (id INT,name TEXT,country TEXT,launch_date DATE); INSERT INTO satellites (id,name,country,launch_date) VALUES (1,'Sentinel-1A','France','2012-04-03'); INSERT INTO satellites (id,name,country,launch_date) VALUES (2,'Sentinel-1B','France','2014-04-22'); INSERT INTO satellites (id,name,country,launch_date) VALUES (3,'USA-202','USA','2011-03-24');
SELECT * FROM satellites WHERE launch_date BETWEEN '2012-01-01' AND '2014-12-31';
What is the total amount of climate finance provided by Germany between 2010 and 2015?
CREATE TABLE climate_finance (country VARCHAR(30),year INT,amount FLOAT); INSERT INTO climate_finance VALUES ('Germany',2010,1200.56),('Germany',2011,1500.23),('Germany',2012,1800.98),('Germany',2013,2000.11),('Germany',2014,2500.30),('Germany',2015,3000.87);
SELECT SUM(amount) FROM climate_finance WHERE country = 'Germany' AND year BETWEEN 2010 AND 2015;
What is the total waste generated by each factory?
CREATE TABLE waste (factory_id INT,date DATE,waste_quantity INT); INSERT INTO waste (factory_id,date,waste_quantity) VALUES (1,'2021-01-01',50),(1,'2021-01-02',60),(2,'2021-01-01',40),(2,'2021-01-02',45);
SELECT f.name, SUM(w.waste_quantity) FROM waste w JOIN factories f ON w.factory_id = f.id GROUP BY f.name;
What is the total number of plots in the 'plots' table, where the plot is used for agroecology or urban agriculture?
CREATE TABLE plots (id INT,type TEXT); INSERT INTO plots (id,type) VALUES (1,'Urban'); INSERT INTO plots (id,type) VALUES (2,'Agroecological');
SELECT COUNT(*) FROM plots WHERE type IN ('Agroecological', 'Urban');
What is the average wildlife species count per protected area?
CREATE TABLE protected_areas (id INT,name VARCHAR(255),area FLOAT); INSERT INTO protected_areas (id,name,area) VALUES (1,'Area A',500.0),(2,'Area B',700.0); CREATE TABLE species_count (id INT,area_id INT,species_count INT); INSERT INTO species_count (id,area_id,species_count) VALUES (1,1,30),(2,1,40),(3,2,50);
SELECT AVG(species_count) FROM species_count JOIN protected_areas ON species_count.area_id = protected_areas.id;
Update population of 'Mammoth' in animals table by 15%
CREATE TABLE animals (id INT PRIMARY KEY,species VARCHAR(50),population INT,region VARCHAR(50)); INSERT INTO animals (id,species,population,region) VALUES (1,'Mammoth',2500,'Arctic');
WITH cte AS (UPDATE animals SET population = population * 1.15 WHERE species = 'Mammoth') SELECT * FROM animals;
Which animal has the smallest population in the 'community_education' region?
CREATE TABLE community_education (id INT,region VARCHAR(50),animal_name VARCHAR(50),population INT); INSERT INTO community_education (id,region,animal_name,population) VALUES (1,'Community Education','Lion',1000),(2,'Community Education','Giraffe',1500);
SELECT animal_name, MIN(population) FROM community_education WHERE region = 'Community Education';
What is the average salary of employees hired in Q2 of 2022?
CREATE TABLE salaries_q2_2022 (id INT,employee_id INT,department VARCHAR(50),salary FLOAT,hire_date DATE); INSERT INTO salaries_q2_2022 (id,employee_id,department,salary,hire_date) VALUES (1,15,'IT',80000.0,'2022-04-03'),(2,16,'IT',85000.0,'2022-06-14'),(3,17,'HR',90000.0,'2022-05-25'),(4,18,'HR',95000.0,'2022-07-30');
SELECT AVG(salary) FROM salaries_q2_2022 WHERE EXTRACT(QUARTER FROM hire_date) = 2;
Which animals are present in both 'National Park B' and 'Conservation Area C'?
CREATE TABLE Habitats (HabitatID INT,HabitatName TEXT,Location TEXT); INSERT INTO Habitats (HabitatID,HabitatName,Location) VALUES (2,'National Park B','Country B'); INSERT INTO Habitats (HabitatID,HabitatName,Location) VALUES (3,'Conservation Area C','Country C'); CREATE TABLE AnimalHabitats (AnimalID INT,HabitatID INT); INSERT INTO AnimalHabitats (AnimalID,HabitatID) VALUES (1,2); INSERT INTO AnimalHabitats (AnimalID,HabitatID) VALUES (1,3);
SELECT AnimalID FROM AnimalHabitats WHERE HabitatID = 2 INTERSECT SELECT AnimalID FROM AnimalHabitats WHERE HabitatID = 3;
Delete the record for attendee_id 1001
CREATE TABLE attendees (attendee_id INT PRIMARY KEY,first_name VARCHAR(50),last_name VARCHAR(50),email VARCHAR(100),phone_number VARCHAR(15),date_of_birth DATE);
DELETE FROM attendees WHERE attendee_id = 1001;
What is the maximum funding round size in the clean energy sector?
CREATE TABLE company (id INT,name TEXT,industry TEXT); INSERT INTO company (id,name,industry) VALUES (1,'CleanEnergy','Clean Energy'); INSERT INTO company (id,name,industry) VALUES (2,'TechBoost','Technology'); CREATE TABLE funding_round (company_id INT,round_size INT); INSERT INTO funding_round (company_id,round_size) VALUES (1,5000000); INSERT INTO funding_round (company_id,round_size) VALUES (2,7000000);
SELECT MAX(funding_round.round_size) FROM company INNER JOIN funding_round ON company.id = funding_round.company_id WHERE company.industry = 'Clean Energy';
What are the total sales for each game category, and which category has the highest sales, considering only games released after 2015?
CREATE TABLE games (game_id INT,game_name VARCHAR(50),release_year INT,category VARCHAR(50),price DECIMAL(5,2),sales INT); INSERT INTO games VALUES (1,'GameA',2014,'Action',59.99,15000); INSERT INTO games VALUES (2,'GameB',2016,'RPG',49.99,20000); INSERT INTO games VALUES (3,'GameC',2015,'Strategy',39.99,12000);
SELECT category, SUM(sales) as total_sales FROM games WHERE release_year > 2015 GROUP BY category ORDER BY total_sales DESC;
What is the total water usage by each state?
CREATE TABLE state_water_usage (state VARCHAR(255),usage INT); INSERT INTO state_water_usage (state,usage) VALUES ('California',10000),('Texas',8000),('Florida',7000);
SELECT state, SUM(usage) FROM state_water_usage GROUP BY state;
Find the number of packages shipped to California from January 1, 2021 to January 10, 2021
CREATE TABLE Warehouse (id INT,location VARCHAR(50),packages INT); INSERT INTO Warehouse (id,location,packages) VALUES (1,'California',500),(2,'Texas',300),(3,'New York',400);
SELECT SUM(packages) FROM Warehouse WHERE location = 'California' AND timestamp BETWEEN '2021-01-01' AND '2021-01-10';
Number of community health workers by ethnicity in Texas?
CREATE TABLE CommunityHealthWorker (ID INT,State VARCHAR(50),Ethnicity VARCHAR(50)); INSERT INTO CommunityHealthWorker (ID,State,Ethnicity) VALUES (1,'Texas','Hispanic'),(2,'Texas','African American'),(3,'Texas','Asian'),(4,'Texas','White');
SELECT Ethnicity, COUNT(*) as CHWCount FROM CommunityHealthWorker WHERE State = 'Texas' GROUP BY Ethnicity;
What is the average ticket price for cultural events in each city?
CREATE TABLE CulturalEvents (id INT,city VARCHAR(50),date DATE,ticket_price DECIMAL(5,2)); INSERT INTO CulturalEvents (id,city,date,ticket_price) VALUES (1,'New York','2022-01-01',50.00),(2,'Los Angeles','2022-01-02',60.00),(3,'New York','2022-01-03',40.00);
SELECT city, AVG(ticket_price) FROM CulturalEvents GROUP BY city;
Create a table named 'volunteer_events'
CREATE TABLE volunteer_events (id INT PRIMARY KEY,name VARCHAR(255),location VARCHAR(255),description TEXT,start_date DATETIME,end_date DATETIME);
CREATE TABLE volunteer_events (id INT PRIMARY KEY, name VARCHAR(255), location VARCHAR(255), description TEXT, start_date DATETIME, end_date DATETIME);
What is the average number of hours played per day for players who play VR games?
CREATE TABLE PlayerHours (PlayerID INT,Game VARCHAR(10),Hours DECIMAL(3,2)); INSERT INTO PlayerHours (PlayerID,Game,Hours) VALUES (1,'VR',3.5);
SELECT AVG(Hours) FROM PlayerHours WHERE Game = 'VR';
What is the average temperature recorded by the soil moisture sensor in the 'sensor_data_2022' table for vineyards located in California?
CREATE TABLE sensor_data_2022 (location VARCHAR(50),sensor_type VARCHAR(50),temperature FLOAT,reading_date DATE); INSERT INTO sensor_data_2022 (location,sensor_type,temperature,reading_date) VALUES ('Vineyard in California','Soil Moisture',23.5,'2022-06-01'); INSERT INTO sensor_data_2022 (location,sensor_type,temperature,reading_date) VALUES ('Vineyard in California','Soil Moisture',24.3,'2022-06-02');
SELECT AVG(temperature) FROM sensor_data_2022 WHERE location = 'Vineyard in California' AND sensor_type = 'Soil Moisture';
Identify the top 3 cities with the highest number of COVID-19 cases in the state of California.
CREATE TABLE public.covid_data (id SERIAL PRIMARY KEY,city TEXT,cases INTEGER); INSERT INTO public.covid_data (city,cases) VALUES ('San Francisco',1000),('Los Angeles',2000),('San Diego',1500),('San Jose',1200),('Sacramento',800);
SELECT city, cases FROM public.covid_data ORDER BY cases DESC LIMIT 3;
Update the status of all traffic violations that occurred more than 1 year ago in the city of Chicago to 'expired'.
CREATE TABLE traffic_violations(id INT,violation_number INT,violation_date DATE,city VARCHAR(50));CREATE TABLE violation_status(id INT,violation_number INT,violation_status VARCHAR(50));
UPDATE violation_status SET violation_status = 'expired' WHERE violation_number IN (SELECT tv.violation_number FROM traffic_violations tv WHERE tv.violation_date < NOW() - INTERVAL 1 YEAR AND tv.city = 'Chicago');
How many hospitals are there in New York?
CREATE TABLE Hospital (HospitalName TEXT,State TEXT); INSERT INTO Hospital VALUES ('Bellevue Hospital','New York'),('Mount Sinai Hospital','New York');
SELECT COUNT(*) FROM Hospital WHERE State = 'New York';
Get the top 3 donors by total donation amount
CREATE TABLE donations (id INT,donor_id INT,amount DECIMAL(10,2)); INSERT INTO donations (id,donor_id,amount) VALUES (1,1,1000.00); INSERT INTO donations (id,donor_id,amount) VALUES (2,1,2000.00); INSERT INTO donations (id,donor_id,amount) VALUES (3,2,3000.00);
SELECT donor_id, SUM(amount) as total_donations FROM donations GROUP BY donor_id ORDER BY total_donations DESC LIMIT 3;
What is the total amount of funding received by visual arts programs in the last quarter?
CREATE TABLE visual_arts_programs (program_id INT,program_name VARCHAR(50)); CREATE TABLE program_funding (program_id INT,source_id INT,amount DECIMAL(5,2)); CREATE TABLE funding_sources (source_id INT,source_name VARCHAR(50)); INSERT INTO visual_arts_programs (program_id,program_name) VALUES (1,'Painting Classes'),(2,'Sculpture Workshops'),(3,'Photography Course'); INSERT INTO funding_sources (source_id,source_name) VALUES (1,'Arts Council'),(2,'Local Grants'),(3,'Private Donors'); INSERT INTO program_funding (program_id,source_id,amount) VALUES (1,1,5000),(1,2,3000),(2,1,7000),(2,3,12000),(3,2,8000),(3,3,10000);
SELECT AVG(p.amount) as avg_funding FROM program_funding p INNER JOIN visual_arts_programs v ON p.program_id = v.program_id INNER JOIN funding_sources fs ON p.source_id = fs.source_id WHERE v.program_name IN ('Painting Classes', 'Sculpture Workshops', 'Photography Course') AND p.amount IS NOT NULL AND fs.source_name IN ('Arts Council', 'Local Grants', 'Private Donors') AND p.program_id IS NOT NULL AND v.program_id IS NOT NULL AND fs.source_id IS NOT NULL AND p.program_id = v.program_id AND p.source_id = fs.source_id AND v.program_id = p.program_id AND fs.source_id = p.source_id AND p.amount > 0 AND fs.source_name != '';
What are the average speeds of electric vehicles in the NYC taxi fleet?
CREATE TABLE taxi (taxi_id INT,vehicle_type VARCHAR(20),avg_speed FLOAT); INSERT INTO taxi (taxi_id,vehicle_type,avg_speed) VALUES (1,'Tesla',25.6),(2,'Nissan Leaf',22.3),(3,'Chevy Bolt',23.7);
SELECT avg(avg_speed) FROM taxi WHERE vehicle_type LIKE 'Electric%';
How many containers were shipped from the Port of Singapore to South America in the past year, grouped by the month of shipment?
CREATE TABLE ports (id INT,name TEXT,location TEXT); INSERT INTO ports (id,name,location) VALUES (1,'Port of Singapore','Singapore'); CREATE TABLE shipments (id INT,container_count INT,departure_port_id INT,arrival_region TEXT,shipment_date DATE); INSERT INTO shipments (id,container_count,departure_port_id,arrival_region,shipment_date) VALUES (1,30,1,'South America','2022-02-03');
SELECT departure_port_id, arrival_region, MONTH(shipment_date) AS month, SUM(container_count) FROM shipments WHERE departure_port_id = (SELECT id FROM ports WHERE name = 'Port of Singapore') AND arrival_region = 'South America' AND shipment_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR) GROUP BY month;
What is the average mental health score of students in each district who have participated in at least 3 professional development courses?
CREATE TABLE student_mental_health (student_id INT,district_id INT,mental_health_score INT,date DATE); CREATE TABLE professional_development_courses (course_id INT,student_id INT,course_name VARCHAR(100),date DATE); CREATE TABLE districts (district_id INT,district_name VARCHAR(100));
SELECT d.district_name, AVG(smh.mental_health_score) as avg_mental_health_score FROM student_mental_health smh JOIN districts d ON smh.district_id = d.district_id JOIN (SELECT student_id, COUNT(*) as num_courses FROM professional_development_courses GROUP BY student_id HAVING num_courses >= 3) pdc ON smh.student_id = pdc.student_id GROUP BY d.district_name;
What is the total amount of funding from private sources for music events?
CREATE TABLE funding (id INT,source TEXT,category TEXT,amount INT); INSERT INTO funding VALUES (1,'Private','Music',10000);
SELECT SUM(funding.amount) FROM funding WHERE funding.source = 'Private' AND funding.category = 'Music';
Delete all records from the 'warehouse' table where the city is 'Cairo'.
CREATE TABLE warehouse (id INT PRIMARY KEY,name VARCHAR(50),city VARCHAR(50));
DELETE FROM warehouse WHERE city = 'Cairo';
How many individuals have completed a restorative justice program in the past year, broken down by the type of program and the number of prior offenses?
CREATE TABLE restorative_justice_programs (id INT,program_type TEXT,num_prior_offenses INT,completion_date DATE);
SELECT program_type, num_prior_offenses, COUNT(*) FROM restorative_justice_programs WHERE completion_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR) GROUP BY program_type, num_prior_offenses;
What is the collective bargaining success rate for private sector unions in the last 12 months?
CREATE TABLE unions (id INT,union_name VARCHAR(255),sector VARCHAR(255)); INSERT INTO unions (id,union_name,sector) VALUES (1,'United Steelworkers','Private'),(2,'American Federation of State,County and Municipal Employees','Public'); CREATE TABLE negotiations (id INT,union_id INT,success BOOLEAN,negotiation_date DATE); INSERT INTO negotiations (id,union_id,success,negotiation_date) VALUES (1,1,true,'2022-01-01'),(2,1,false,'2021-12-01');
SELECT u.union_name, AVG(n.success) as success_rate FROM unions u JOIN negotiations n ON u.id = n.union_id WHERE u.sector = 'Private' AND n.negotiation_date >= DATE(NOW()) - INTERVAL 12 MONTH GROUP BY u.union_name;
Identify the dish with the highest price
CREATE TABLE dishes (dish_id INT,dish_name VARCHAR(255),price DECIMAL(5,2)); INSERT INTO dishes (dish_id,dish_name,price) VALUES (1,'Margherita Pizza',12.99),(2,'Chicken Alfredo',15.99),(3,'Caesar Salad',9.99);
SELECT dish_name, price FROM dishes ORDER BY price DESC LIMIT 1;
Create a table named 'player_achievements'
CREATE TABLE player_achievements (player_id INT,achievement_name VARCHAR(255),achievement_date DATE);
CREATE TABLE player_achievements (player_id INT, achievement_name VARCHAR(255), achievement_date DATE);
What is the average portfolio value for customers in each age group (e.g., 18-24, 25-34, 35-44, etc.)?
CREATE TABLE customers (customer_id INT,name VARCHAR(50),age INT,gender VARCHAR(10),risk_score INT,portfolio_value DECIMAL(10,2)); INSERT INTO customers (customer_id,name,age,gender,risk_score,portfolio_value) VALUES (1,'John Doe',35,'Male',5,50000.00),(2,'Jane Smith',45,'Female',7,75000.00),(3,'Bob Johnson',28,'Male',3,60000.00),(4,'Alice Williams',32,'Female',6,80000.00);
SELECT AVG(portfolio_value) as avg_portfolio_value, FLOOR((age-1)/10)*10 as age_group FROM customers GROUP BY age_group;
Create a table named 'farm_locations'
CREATE TABLE farm_locations (location_id INT PRIMARY KEY,location_name VARCHAR(255),country VARCHAR(255),ocean VARCHAR(255));
CREATE TABLE farm_locations (location_id INT PRIMARY KEY, location_name VARCHAR(255), country VARCHAR(255), ocean VARCHAR(255));
What is the total number of education programs and their respective budgets?
CREATE TABLE education_programs (program_id INT,program_name VARCHAR(20),budget INT); INSERT INTO education_programs (program_id,program_name,budget) VALUES (1,'Community Outreach',15000); INSERT INTO education_programs (program_id,program_name,budget) VALUES (2,'School Visits',20000);
SELECT COUNT(*), SUM(budget) FROM education_programs;
Which suppliers provided raw materials for the 'High-Efficiency Solar Panel Production' process in the past month?
CREATE TABLE suppliers (supplier_id INT,name TEXT); CREATE TABLE raw_materials (raw_material_id INT,name TEXT,supplier_id INT,delivery_date DATE); CREATE TABLE process_raw_materials (process_id INT,raw_material_id INT);
SELECT DISTINCT suppliers.name FROM suppliers INNER JOIN process_raw_materials ON suppliers.supplier_id = (SELECT supplier_id FROM raw_materials WHERE raw_materials.raw_material_id = process_raw_materials.raw_material_id) INNER JOIN raw_materials ON process_raw_materials.raw_material_id = raw_materials.raw_material_id WHERE process_raw_materials.process_id = (SELECT process_id FROM manufacturing_processes WHERE name = 'High-Efficiency Solar Panel Production') AND raw_materials.delivery_date > DATEADD(month, -1, GETDATE());
What is the total number of farms owned by women in the 'agriculture_database'?
CREATE TABLE farmers (id INT,name VARCHAR(50),gender VARCHAR(10),age INT,farm_size FLOAT); INSERT INTO farmers (id,name,gender,age,farm_size) VALUES (1,'Jane','Female',45,200.5),(2,'Alice','Female',34,150.3),(3,'Bob','Male',50,350.7);
SELECT COUNT(*) FROM farmers WHERE gender = 'Female';
Count of 'metal' artifacts from 'african_excavations' per site
CREATE TABLE african_excavations (id INT,site_name VARCHAR(50),artifact_name VARCHAR(50),weight INT,material VARCHAR(20));
SELECT site_name, COUNT(*) FROM african_excavations WHERE material = 'metal' GROUP BY site_name;
What is the total number of articles published by each author in a specific month of a specific year?
CREATE TABLE articles (article_id INT,author VARCHAR(50),title VARCHAR(100),category VARCHAR(50),word_count INT,publication_date DATE);
SELECT author, EXTRACT(MONTH FROM publication_date) AS month, COUNT(article_id) AS articles_in_month FROM articles WHERE EXTRACT(YEAR FROM publication_date) = 2022 AND EXTRACT(MONTH FROM publication_date) = 12 GROUP BY author, month;
What is the name of the author who has published the least articles?
CREATE TABLE authors_articles (author_id INT,article_id INT); INSERT INTO authors_articles (author_id,article_id) VALUES (1,1),(1,2),(2,3);CREATE TABLE authors (id INT,name VARCHAR(50)); INSERT INTO authors (id,name) VALUES (1,'Alice'),(2,'Bob');
SELECT authors.name FROM authors JOIN (SELECT author_id, COUNT(*) as article_count FROM authors_articles GROUP BY author_id ORDER BY article_count ASC LIMIT 1) as article_counts ON authors.id = article_counts.author_id;
What was the total waste produced by the 'West Coast' plant in 2020?
CREATE TABLE waste (plant varchar(10),year int,waste_amount int); INSERT INTO waste (plant,year,waste_amount) VALUES ('North Plant',2020,150),('North Plant',2019,140),('West Plant',2020,200),('West Plant',2019,180);
SELECT SUM(waste_amount) FROM waste WHERE plant = 'West Plant' AND year = 2020;
What is the average funding round size for startups founded by Latinx individuals?
CREATE TABLE company (id INT,name TEXT,founding_year INT,founder_gender TEXT,founder_ethnicity TEXT); INSERT INTO company (id,name,founding_year,founder_gender,founder_ethnicity) VALUES (1,'TechFuturo',2018,'male','Latinx'); INSERT INTO company (id,name,founding_year,founder_gender,founder_ethnicity) VALUES (2,'EcoVida',2020,'female','Latinx'); CREATE TABLE funding_round (company_id INT,round_amount INT); INSERT INTO funding_round (company_id,round_amount) VALUES (1,3000000); INSERT INTO funding_round (company_id,round_amount) VALUES (2,6000000);
SELECT AVG(funding_round.round_amount) FROM company JOIN funding_round ON company.id = funding_round.company_id WHERE company.founder_ethnicity = 'Latinx';
Insert a new healthcare facility into the facility table.
CREATE TABLE facility (id INT,name VARCHAR(50),type VARCHAR(50),capacity INT);
INSERT INTO facility (id, name, type, capacity) VALUES (3, 'New Hope Clinic', 'Community Health Center', 150);
How many skincare products contain natural ingredients and were sold in the US?
CREATE TABLE skincare (id INT,name VARCHAR(255),natural_ingredients BOOLEAN,country VARCHAR(255),sales INT); INSERT INTO skincare (id,name,natural_ingredients,country,sales) VALUES (1,'Cleanser',true,'USA',100),(2,'Toner',false,'Canada',50),(3,'Moisturizer',true,'USA',200);
SELECT COUNT(*) FROM skincare WHERE natural_ingredients = true AND country = 'USA';
Find the top 5 busiest subway stations in terms of unique users in the last week.
CREATE TABLE station_usage (station_name VARCHAR(255),user_id INT,usage_date DATE); INSERT INTO station_usage (station_name,user_id,usage_date) VALUES ('Times Square',1,'2022-03-29'),('Grand Central',2,'2022-03-28'),('Times Square',3,'2022-03-27'),('Union Station',4,'2022-03-26'),('Union Station',5,'2022-03-25'),('Times Square',6,'2022-03-24'),('Grand Central',7,'2022-03-23');
SELECT station_name, COUNT(DISTINCT user_id) AS unique_users FROM station_usage WHERE usage_date >= DATEADD(day, -7, CURRENT_DATE) GROUP BY station_name ORDER BY unique_users DESC LIMIT 5
What is the total number of streams for electronic music on TikTok, grouped by week?
CREATE TABLE WeeklyStreams (StreamID INT,TrackID INT,PlatformID INT,Date DATE,Streams INT); INSERT INTO WeeklyStreams (StreamID,TrackID,PlatformID,Date,Streams) VALUES (1,1,4,'2022-01-01',100);
SELECT EXTRACT(WEEK FROM Date) as Week, EXTRACT(YEAR FROM Date) as Year, SUM(Streams) as TotalStreams FROM WeeklyStreams JOIN Tracks ON WeeklyStreams.TrackID = Tracks.TrackID JOIN StreamingPlatforms ON WeeklyStreams.PlatformID = StreamingPlatforms.PlatformID WHERE Genre = 'Electronic' AND PlatformName = 'TikTok' GROUP BY Week, Year;