instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
What is the total amount donated by new donors in H2 2019?
CREATE TABLE Donors (DonorID int,DonationDate date,DonationAmount numeric);
SELECT SUM(DonationAmount) FROM (SELECT DonationAmount FROM Donors WHERE DonationDate BETWEEN '2019-07-01' AND '2019-12-31' AND DonorID NOT IN (SELECT DonorID FROM Donors WHERE DonationDate < '2019-07-01')) AS NewDonors;
Which customers have not placed an order in the last 3 months?
CREATE TABLE customers (customer_id INT,customer_name VARCHAR(255)); CREATE TABLE orders (order_id INT,customer_id INT,order_date DATE); INSERT INTO customers (customer_id,customer_name) VALUES (1,'John Doe'),(2,'Jane Smith'); INSERT INTO orders (order_id,customer_id,order_date) VALUES (1,1,'2022-01-01'),(2,1,'2022-02-01'),(3,2,'2022-03-01');
SELECT c.customer_name FROM customers c LEFT JOIN orders o ON c.customer_id = o.customer_id WHERE o.order_date < DATE_SUB(CURDATE(), INTERVAL 3 MONTH) IS NULL;
Who are the top 3 customers with the highest quantity of sustainable garments purchased?
CREATE TABLE customer_purchases(customer_id INT,garment_id INT,quantity INT,sustainable BOOLEAN); INSERT INTO customer_purchases(customer_id,garment_id,quantity,sustainable) VALUES (101,1,2,true),(102,2,1,false),(101,3,3,true);
SELECT customer_id, SUM(quantity) as total_quantity FROM customer_purchases WHERE sustainable = true GROUP BY customer_id ORDER BY total_quantity DESC LIMIT 3;
What is the total quantity of recycled polyester used by brands with a 'fair trade' certification?
CREATE TABLE brands (brand_id INT,brand_name TEXT,country TEXT,certification TEXT); INSERT INTO brands (brand_id,brand_name,country,certification) VALUES (1,'EcoBrand','Germany','fair trade'),(2,'GreenFashion','France','organic'),(3,'SustainableStyle','USA','fair trade'); CREATE TABLE material_usage (brand_id INT,material_type TEXT,quantity INT,co2_emissions INT); INSERT INTO material_usage (brand_id,material_type,quantity,co2_emissions) VALUES (1,'recycled_polyester',1200,2000),(1,'organic_cotton',800,1000),(3,'recycled_polyester',1500,2500);
SELECT SUM(mu.quantity) AS total_quantity FROM brands b JOIN material_usage mu ON b.brand_id = mu.brand_id WHERE b.certification = 'fair trade' AND mu.material_type = 'recycled_polyester';
What is the total investment in climate mitigation projects in Sub-Saharan Africa in 2020?
CREATE TABLE climate_mitigation_projects (project_id INT,location VARCHAR(50),investment_amount FLOAT,investment_year INT); INSERT INTO climate_mitigation_projects (project_id,location,investment_amount,investment_year) VALUES (1,'Nigeria',8000000,2020),(2,'Kenya',6000000,2020),(3,'South Africa',9000000,2020),(4,'Tanzania',7000000,2020),(5,'Ghana',5000000,2020);
SELECT SUM(investment_amount) FROM climate_mitigation_projects WHERE location LIKE 'Sub-Saharan Africa' AND investment_year = 2020;
List all the record labels and their respective countries that have signed more than 10 new artists in any quarter of 2021.
CREATE TABLE RecordLabels (LabelName TEXT,Country TEXT,Quarter TEXT(2),Year INTEGER,NewArtists INTEGER); INSERT INTO RecordLabels (LabelName,Country,Quarter,Year,NewArtists) VALUES ('Label1','USA','Q1',2021,12),('Label2','Canada','Q2',2021,15),('Label3','UK','Q3',2021,8),('Label4','Germany','Q4',2021,11);
SELECT LabelName, Country FROM RecordLabels WHERE Year = 2021 GROUP BY LabelName, Country HAVING SUM(NewArtists) > 10;
Insert a new record in the table "deep_sea_exploration" with values 'Indian Ocean', 6000, '2022-03-04'
CREATE TABLE deep_sea_exploration (id INT,location VARCHAR(50),depth INT,date DATE);
INSERT INTO deep_sea_exploration (location, depth, date) VALUES ('Indian Ocean', 6000, '2022-03-04');
What is the minimum age of all animals in the 'animal_population' table?
CREATE TABLE animal_population (animal_id INT,animal_type VARCHAR(10),age INT); INSERT INTO animal_population (animal_id,animal_type,age) VALUES (1,'zebra',7); INSERT INTO animal_population (animal_id,animal_type,age) VALUES (2,'monkey',3); INSERT INTO animal_population (animal_id,animal_type,age) VALUES (3,'zebra',5);
SELECT MIN(age) FROM animal_population;
What is the distribution of space debris by location?
CREATE TABLE space_debris (debris_id INT,name VARCHAR(255),type VARCHAR(255),location POINT); INSERT INTO space_debris (debris_id,name,type,location) VALUES (1,'Defunct Satellite','Satellite',ST_POINT(0,0));
SELECT type, ST_X(location) as longitude, ST_Y(location) as latitude, COUNT(*) as count FROM space_debris GROUP BY type, ST_X(location), ST_Y(location);
Which clinics in Texas need to increase their pediatric vaccine stock?
CREATE TABLE clinics (clinic_id INT,clinic_name TEXT,state TEXT); INSERT INTO clinics (clinic_id,clinic_name,state) VALUES (1,'Rural Health Clinic','Texas');
SELECT clinic_name FROM clinics WHERE state = 'Texas' AND clinic_id NOT IN (SELECT clinic_id FROM vaccine_stocks WHERE vaccine_type = 'Pediatric' AND quantity >= 500);
Identify the agricultural innovation metrics that have the lowest average score in Central America and the Caribbean.
CREATE TABLE innovation_metrics (id INT,name TEXT,score INT,region TEXT); INSERT INTO innovation_metrics (id,name,score,region) VALUES (1,'Soil Monitoring',7,'Central America'),(2,'Irrigation',6,'Caribbean'),(3,'Crop Yield',8,'Central America'),(4,'Livestock Management',9,'Caribbean');
SELECT name, AVG(score) as avg_score FROM innovation_metrics WHERE region IN ('Central America', 'Caribbean') GROUP BY name ORDER BY avg_score LIMIT 1;
What are the total sales for approved drugs with a manufacturing cost of less than $100 per unit?
CREATE TABLE drug_approval (drug_name TEXT,approval_status TEXT); INSERT INTO drug_approval (drug_name,approval_status) VALUES ('DrugA','approved'),('DrugB','approved'),('DrugC','pending'),('DrugD','approved'); CREATE TABLE manufacturing_costs (drug_name TEXT,cost_per_unit INTEGER); INSERT INTO manufacturing_costs (drug_name,cost_per_unit) VALUES ('DrugA',85),('DrugB',98),('DrugC',120),('DrugD',76); CREATE TABLE drug_sales (drug_name TEXT,sales INTEGER); INSERT INTO drug_sales (drug_name,sales) VALUES ('DrugA',25000000),('DrugB',30000000),('DrugC',0),('DrugD',22000000);
SELECT SUM(sales) FROM drug_sales INNER JOIN drug_approval ON drug_sales.drug_name = drug_approval.drug_name INNER JOIN manufacturing_costs ON drug_sales.drug_name = manufacturing_costs.drug_name WHERE drug_approval.approval_status = 'approved' AND manufacturing_costs.cost_per_unit < 100;
Update the temperature for the record with date '2022-02-02' in the AquaticFarm table to 22.5 degrees.
CREATE TABLE AquaticFarm (date DATE,temperature FLOAT); INSERT INTO AquaticFarm (date,temperature) VALUES ('2022-02-01',21.0),('2022-02-02',22.0),('2022-02-03',23.0);
UPDATE AquaticFarm SET temperature = 22.5 WHERE date = '2022-02-02';
What are the total CVE scores and number of scans for each system in the Security department in the last month, and which systems were scanned the most?
CREATE TABLE systems (system_id INT,system_name VARCHAR(255),department VARCHAR(255));CREATE TABLE cve_scores (system_id INT,score INT,scan_date DATE);CREATE TABLE scan_dates (scan_date DATE,system_id INT);
SELECT s.system_name, SUM(c.score) as total_score, COUNT(sd.scan_date) as scan_count, ROW_NUMBER() OVER (ORDER BY COUNT(sd.scan_date) DESC) as scan_rank FROM systems s INNER JOIN cve_scores c ON s.system_id = c.system_id INNER JOIN scan_dates sd ON s.system_id = sd.system_id WHERE s.department = 'Security' AND sd.scan_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH) GROUP BY s.system_name ORDER BY scan_count DESC;
What is the total number of criminal cases filed in each county in Texas in the last 5 years?
CREATE TABLE criminal_cases (case_id INT,filing_date DATE,county VARCHAR(50)); INSERT INTO criminal_cases (case_id,filing_date,county) VALUES (1,'2020-01-01','Harris'),(2,'2019-02-01','Dallas'),(3,'2018-03-01','Travis');
SELECT county, COUNT(*) FILTER (WHERE filing_date >= NOW() - INTERVAL '5 years') AS total_cases FROM criminal_cases GROUP BY county;
What is the balance for the savings account with the highest balance?
CREATE TABLE savings (account_number INT,customer_name VARCHAR(50),balance DECIMAL(10,2),is_shariah_compliant BOOLEAN); INSERT INTO savings (account_number,customer_name,balance,is_shariah_compliant) VALUES (1,'Ahmed',5000,true),(2,'Sara',7000,false),(3,'Mohammed',8000,true);
SELECT MAX(balance) FROM savings;
Delete all emergency records with a response time greater than 60 minutes in the 'Northside' district.
CREATE TABLE districts (district_id INT,district_name TEXT);CREATE TABLE emergencies (emergency_id INT,district_id INT,response_time INT);
DELETE e FROM emergencies e INNER JOIN districts d ON e.district_id = d.district_id WHERE d.district_name = 'Northside' AND e.response_time > 60;
What is the maximum sustainable sourcing score for 'Asian' menu items?
CREATE TABLE MenuItems (category VARCHAR(20),sourcing_score FLOAT); INSERT INTO MenuItems (category,sourcing_score) VALUES ('Asian',9.5),('Asian',10.0),('Asian',9.2);
SELECT MAX(sourcing_score) FROM MenuItems WHERE category = 'Asian';
What is the total claim amount for each risk level?
CREATE TABLE Claims (Claim_Amount NUMERIC,Risk_Level TEXT); INSERT INTO Claims (Claim_Amount,Risk_Level) VALUES (2500,'High'),(3000,'Very High'),(2000,'Medium'),(1500,'Low');
SELECT Risk_Level, SUM(Claim_Amount) FROM Claims GROUP BY Risk_Level;
Update the price of the 'Quinoa Salad' in Restaurant A to $15.49.
CREATE TABLE menu (restaurant_id INT,item_name TEXT,item_type TEXT,price DECIMAL); INSERT INTO menu (restaurant_id,item_name,item_type,price) VALUES (1,'Spaghetti','Entree',12.99),(1,'Quinoa Salad','Entree',14.99),(1,'Garden Burger','Entree',13.49);
UPDATE menu SET price = 15.49 WHERE restaurant_id = 1 AND item_name = 'Quinoa Salad';
List the top 10 miners with the highest transaction fees earned in the EFG blockchain.
CREATE TABLE EFG_transaction (transaction_hash VARCHAR(255),block_number INT,transaction_index INT,from_address VARCHAR(255),to_address VARCHAR(255),value DECIMAL(18,2),gas_price DECIMAL(18,2),gas_limit INT,timestamp TIMESTAMP,miner VARCHAR(255));
SELECT miner, SUM(gas_price * gas_limit) AS total_fees_earned FROM EFG_transaction GROUP BY miner ORDER BY total_fees_earned DESC LIMIT 10;
Calculate the average age of digital assets (in days) grouped by their asset type.
CREATE TABLE digital_assets (asset_id INT PRIMARY KEY,name VARCHAR(255),creation_date DATETIME,asset_type VARCHAR(50)); INSERT INTO digital_assets (asset_id,name,creation_date,asset_type) VALUES (1,'Asset1','2022-01-01 10:00:00','TypeA'),(2,'Asset2','2022-01-02 11:00:00','TypeB'),(3,'Asset3','2022-01-03 12:00:00','TypeA');
SELECT asset_type, AVG(DATEDIFF(CURRENT_DATE, creation_date)) AS avg_age_days FROM digital_assets GROUP BY asset_type;
What is the sum of transportation emissions for all products in the Transportation_Emissions view?
CREATE VIEW Transportation_Emissions AS SELECT product_id,product_name,transportation_emissions FROM Products; INSERT INTO Products (product_id,product_name,transportation_emissions,production_emissions,packaging_emissions) VALUES (501,'Backpack',4,6,1); INSERT INTO Products (product_id,product_name,transportation_emissions,production_emissions,packaging_emissions) VALUES (502,'Notebook',2,3,0); INSERT INTO Products (product_id,product_name,transportation_emissions,production_emissions,packaging_emissions) VALUES (503,'Pen',1,1,0);
SELECT SUM(transportation_emissions) FROM Transportation_Emissions;
What's the total production budget for the superhero genre?
CREATE TABLE movies(movie_id INT,title VARCHAR(50),genre VARCHAR(20),release_year INT,budget INT,gross INT); INSERT INTO movies(movie_id,title,genre,release_year,budget,gross) VALUES (1,'Avatar','Sci-Fi',2009,237000000,2787965087),(2,'Avengers: Endgame','Superhero',2019,356000000,2797800564),(3,'Titanic','Romance',1997,200000000,2187454640),(4,'The Avengers','Superhero',2012,220000000,1518812988),(5,'Batman v Superman','Superhero',2016,250000000,873434451);
SELECT SUM(budget) FROM movies WHERE genre = 'Superhero';
What is the total energy generation from solar and wind in the province of Alberta for the year 2022?
CREATE TABLE energy_generation (province VARCHAR(20),energy_source VARCHAR(20),generation INT,year INT); INSERT INTO energy_generation (province,energy_source,generation,year) VALUES ('Alberta','Solar',1500,2022),('Alberta','Wind',3500,2022);
SELECT SUM(generation) FROM energy_generation WHERE province = 'Alberta' AND (energy_source = 'Solar' OR energy_source = 'Wind') AND year = 2022;
List the names of countries that have both eco-friendly hotels and cultural heritage sites, but no virtual tours or museums.
CREATE TABLE eco_hotels (hotel_id INT,country VARCHAR(20),name VARCHAR(50)); INSERT INTO eco_hotels (hotel_id,country,name) VALUES (1,'India','Green Resort'),(2,'Mexico','Eco Retreat'),(3,'Nepal','Sustainable Suites'); CREATE TABLE cultural_sites (site_id INT,country VARCHAR(20),type VARCHAR(20)); INSERT INTO cultural_sites (site_id,country,type) VALUES (1,'India','heritage'),(2,'Mexico','heritage'),(3,'Nepal','heritage'); CREATE TABLE virtual_tours (tour_id INT,country VARCHAR(20),type VARCHAR(20)); INSERT INTO virtual_tours (tour_id,country,type) VALUES (1,'India','virtual'),(2,'Mexico','virtual'); CREATE TABLE museums (museum_id INT,country VARCHAR(20),type VARCHAR(20)); INSERT INTO museums (museum_id,country,type) VALUES (1,'India','museum'),(2,'Mexico','museum');
(SELECT country FROM eco_hotels WHERE name IS NOT NULL) INTERSECT (SELECT country FROM cultural_sites WHERE type = 'heritage') EXCEPT (SELECT country FROM (SELECT * FROM virtual_tours WHERE type = 'virtual' UNION ALL SELECT * FROM museums WHERE type = 'museum') AS combined_data);
What is the minimum biomass of fish for each species in the Asia-Pacific region?
CREATE TABLE fish_stock (id INT,species VARCHAR,biomass FLOAT,country VARCHAR); INSERT INTO fish_stock (id,species,biomass,country) VALUES (1,'Tilapia',500.0,'Indonesia'),(2,'Salmon',800.0,'Norway'),(3,'Trout',300.0,'New Zealand'),(4,'Bass',700.0,'USA'),(5,'Tilapia',600.0,'Thailand');
SELECT species, MIN(biomass) FROM fish_stock WHERE country IN ('Indonesia', 'Thailand', 'New Zealand') GROUP BY species;
What is the name of the author who has published the most 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 DESC LIMIT 1) as article_counts ON authors.id = article_counts.author_id;
List the regions where mobile subscribers are not compliant with regulatory data retention policies.
CREATE TABLE mobile_subscribers (subscriber_id INT,region VARCHAR(50),compliant BOOLEAN); INSERT INTO mobile_subscribers (subscriber_id,region,compliant) VALUES (1,'North',true),(2,'North',false),(3,'South',true),(4,'East',true);
SELECT region FROM mobile_subscribers WHERE compliant = false;
What is the total number of hours played by all esports players in 'CS:GO' tournaments?
CREATE TABLE esports_players (player_id INT,player_name TEXT,hours_played INT,game TEXT); INSERT INTO esports_players (player_id,player_name,hours_played,game) VALUES (1,'FalleN',1200,'CS:GO'),(2,'s1mple',1500,'CS:GO'),(3,'ZywOo',1800,'CS:GO'); CREATE TABLE games (game_id INT,game TEXT,genre TEXT); INSERT INTO games (game_id,game_name,genre) VALUES (1,'League of Legends','MOBA'),(2,'CS:GO','FPS'),(3,'Dota 2','MOBA');
SELECT SUM(esports_players.hours_played) FROM esports_players JOIN games ON esports_players.game = games.game WHERE games.game = 'CS:GO';
Identify teachers who have not attended any professional development in the last 6 months.
CREATE TABLE Teachers (id INT,name VARCHAR(20)); INSERT INTO Teachers (id,name) VALUES (1,'Jane Doe'),(2,'Robert Smith'),(3,'Alice Johnson'); CREATE TABLE ProfessionalDevelopment (teacher_id INT,attended_date DATE); INSERT INTO ProfessionalDevelopment (teacher_id,attended_date) VALUES (1,'2022-01-01'),(2,'2022-02-15'),(3,'2021-06-20'),(4,'2022-06-01');
SELECT t.name FROM Teachers t LEFT JOIN ProfessionalDevelopment pd ON t.id = pd.teacher_id WHERE pd.teacher_id IS NULL OR pd.attended_date < DATE_SUB(CURRENT_DATE, INTERVAL 6 MONTH);
What is the average size of customers in the 'sustainable_fashion_customers' table?
CREATE TABLE sustainable_fashion_customers (id INT,customer_name VARCHAR(30),size VARCHAR(10)); INSERT INTO sustainable_fashion_customers (id,customer_name,size) VALUES (1,'Alice','M'),(2,'Bob','L'),(3,'Charlie','S');
SELECT AVG(CASE WHEN size = 'S' THEN 0 WHEN size = 'M' THEN 1 WHEN size = 'L' THEN 2 ELSE 3 END) AS avg_size FROM sustainable_fashion_customers;
What is the total installed capacity of solar plants in the 'solar_plants' table, and what is the average installed capacity of these solar plants, grouped by state?
CREATE TABLE solar_plants (id INT,state VARCHAR(255),name VARCHAR(255),capacity FLOAT,start_date DATE,end_date DATE); INSERT INTO solar_plants (id,state,name,capacity,start_date,end_date) VALUES (6,'California','Solar Plant D',40.0,'2021-01-01','2026-12-31'),(7,'Nevada','Solar Plant E',50.0,'2022-01-01','2027-12-31');
SELECT state, SUM(capacity) as total_capacity, AVG(capacity) as avg_capacity FROM solar_plants GROUP BY state;
What was the average price of Dysprosium in Q1 2022 by week?
CREATE TABLE dysprosium_prices (price_id INT,date DATE,dysprosium_price FLOAT); INSERT INTO dysprosium_prices (price_id,date,dysprosium_price) VALUES (1,'2022-01-01',120),(2,'2022-01-08',122),(3,'2022-01-15',125),(4,'2022-01-22',128),(5,'2022-01-29',130);
SELECT AVG(dysprosium_price) FROM (SELECT dysprosium_price, DATE_TRUNC('week', date) AS week FROM dysprosium_prices WHERE date BETWEEN '2022-01-01' AND '2022-03-31' GROUP BY week, dysprosium_price ORDER BY week, dysprosium_price) AS subquery WHERE PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY dysprosium_price) = dysprosium_price;
How many cultural competency trainings have been conducted in each state?
CREATE TABLE Trainings (Training_ID INT,Training_Name VARCHAR(50),Training_Location VARCHAR(50),Training_Date DATE); INSERT INTO Trainings (Training_ID,Training_Name,Training_Location,Training_Date) VALUES (1,'Cultural Competency','California','2021-01-01'); INSERT INTO Trainings (Training_ID,Training_Name,Training_Location,Training_Date) VALUES (2,'Cultural Competency','New York','2021-02-15');
SELECT Training_Location, COUNT(*) FROM Trainings WHERE Training_Name = 'Cultural Competency' GROUP BY Training_Location;
How many crimes were reported in 'Central Park' in the last 30 days?
CREATE TABLE crimes (id INT,date DATE,location VARCHAR(20),reported BOOLEAN); INSERT INTO crimes (id,date,location,reported) VALUES (1,'2022-01-01','Central Park',TRUE),(2,'2022-01-05','Northside',TRUE),(3,'2022-01-10','Central Park',FALSE),(4,'2022-01-15','Central Park',TRUE),(5,'2022-01-20','Central Park',TRUE);
SELECT COUNT(*) FROM crimes WHERE location = 'Central Park' AND date >= DATE_SUB(CURRENT_DATE, INTERVAL 30 DAY);
How many startups in the healthcare sector received funding in each quarter of 2019?
CREATE TABLE company (id INT,name TEXT,industry TEXT,funding_quarter INT,funding_year INT); INSERT INTO company (id,name,industry,funding_quarter,funding_year) VALUES (1,'HealPro','Healthcare',3,2019),(2,'CareEasy','Healthcare',1,2019);
SELECT funding_quarter, COUNT(*) FROM company WHERE industry = 'Healthcare' AND funding_year = 2019 GROUP BY funding_quarter;
What is the minimum and maximum size of properties in the city of Tokyo, Japan that are affordable?
CREATE TABLE tokyo_real_estate(id INT,city VARCHAR(50),size INT,price DECIMAL(10,2),affordable BOOLEAN); INSERT INTO tokyo_real_estate VALUES (1,'Tokyo',50,200000,true);
SELECT MIN(size), MAX(size) FROM tokyo_real_estate WHERE city = 'Tokyo' AND affordable = true;
Which suppliers have provided fabrics for products with sales volumes greater than 500 and their average sustainability scores?
CREATE TABLE suppliers (id INT PRIMARY KEY,name VARCHAR(255),sustainability_score INT); INSERT INTO suppliers (id,name,sustainability_score) VALUES (1,'Supplier A',80); INSERT INTO suppliers (id,name,sustainability_score) VALUES (2,'Supplier B',85); CREATE TABLE fabrics (id INT PRIMARY KEY,supplier_id INT,name VARCHAR(255),country_of_origin VARCHAR(255),sustainability_score INT); INSERT INTO fabrics (id,supplier_id,name,country_of_origin,sustainability_score) VALUES (1,1,'Fabric A','Country A',70); INSERT INTO fabrics (id,supplier_id,name,country_of_origin,sustainability_score) VALUES (2,2,'Fabric B','Country B',75); CREATE TABLE products (id INT PRIMARY KEY,name VARCHAR(255),fabric_id INT,sales_volume INT); INSERT INTO products (id,name,fabric_id,sales_volume) VALUES (1,'Product A',1,600); INSERT INTO products (id,name,fabric_id,sales_volume) VALUES (2,'Product B',2,550);
SELECT s.name AS supplier_name, AVG(f.sustainability_score) AS avg_sustainability_score FROM suppliers s INNER JOIN fabrics f ON s.id = f.supplier_id INNER JOIN products p ON f.id = p.fabric_id WHERE p.sales_volume > 500 GROUP BY s.name;
Identify the dish with the lowest calorie count and more than 5 reviews?
CREATE TABLE dishes (dish_id INT,name VARCHAR(255),calories INT,reviews INT); INSERT INTO dishes (dish_id,name,calories,reviews) VALUES (1,'Pizza',300,7),(2,'Pasta',400,3),(3,'Salad',200,8),(4,'Burger',500,10),(5,'Sushi',250,6);
SELECT name FROM (SELECT name, calories, ROW_NUMBER() OVER (ORDER BY calories ASC) rn FROM dishes WHERE reviews > 5) t WHERE rn = 1;
Calculate the revenue generated from sustainable tourism activities in Canada in 2021.
CREATE TABLE sustainable_revenue (activity_id INT,activity_name TEXT,country TEXT,year INT,revenue INT); INSERT INTO sustainable_revenue (activity_id,activity_name,country,year,revenue) VALUES (1,'Whale Watching','Canada',2021,7000),(2,'Polar Bear Tour','Canada',2021,9000);
SELECT SUM(revenue) FROM sustainable_revenue WHERE country = 'Canada' AND year = 2021 AND activity_name IN ('Whale Watching', 'Polar Bear Tour');
Add a new event to the "events" table that took place in Mexico
CREATE TABLE events (id INT PRIMARY KEY,name VARCHAR(100),event_date DATE,country VARCHAR(50));
INSERT INTO events (id, name, event_date, country) VALUES (1, 'Día de los Muertos Festival', '2022-11-01', 'Mexico');
What is the percentage of garments produced in each country using circular economy principles?
CREATE TABLE Circular_Economy_Garments_Country (id INT,country VARCHAR,quantity INT);
SELECT country, (SUM(quantity) * 100.0 / (SELECT SUM(quantity) FROM Circular_Economy_Garments_Country)) AS percentage FROM Circular_Economy_Garments_Country GROUP BY country;
Show vessels with the most frequent safety inspection failures in the last two years.
CREATE TABLE vessels (id INT,name VARCHAR(255)); INSERT INTO vessels (id,name) VALUES (1,'VesselA'),(2,'VesselB'),(3,'VesselC'); CREATE TABLE safety_records (id INT,vessel_id INT,inspection_date DATE,result ENUM('PASS','FAIL')); INSERT INTO safety_records (id,vessel_id,inspection_date,result) VALUES (1,1,'2021-05-05','FAIL'),(2,2,'2021-08-01','FAIL'),(3,3,'2021-09-15','PASS'),(4,1,'2020-02-12','FAIL'),(5,2,'2020-05-19','PASS');
SELECT vessel_id, COUNT(*) as fails_count FROM safety_records WHERE result = 'FAIL' AND inspection_date >= DATE_SUB(CURDATE(), INTERVAL 2 YEAR) GROUP BY vessel_id ORDER BY fails_count DESC;
What's the average budget of movies produced in 2021?
CREATE TABLE movies (id INT,title VARCHAR(100),release_year INT,budget INT); INSERT INTO movies (id,title,release_year,budget) VALUES (1,'Movie1',2021,5000000); INSERT INTO movies (id,title,release_year,budget) VALUES (2,'Movie2',2021,7000000); INSERT INTO movies (id,title,release_year,budget) VALUES (3,'Movie3',2020,8000000);
SELECT AVG(budget) FROM movies WHERE release_year = 2021;
What is the distribution of users by age group and preferred news language?
CREATE TABLE users (id INT,age_group VARCHAR(20),language VARCHAR(20),preference VARCHAR(20));
SELECT age_group, language, COUNT(*) FROM users GROUP BY age_group, language;
What is the average number of virtual tours conducted per month by each guide in Paris, France, for the year 2022, if the number of tours is greater than or equal to 10?
CREATE TABLE Guides (id INT,name TEXT,country TEXT,city TEXT);CREATE TABLE VirtualTours (id INT,guide_id INT,date DATE);
SELECT AVG(number_of_tours) FROM (SELECT guide_id, COUNT(*) AS number_of_tours FROM VirtualTours JOIN Guides ON VirtualTours.guide_id = Guides.id WHERE Guides.city = 'Paris' AND Guides.country = 'France' AND YEAR(VirtualTours.date) = 2022 GROUP BY guide_id HAVING COUNT(*) >= 10) AS Subquery
List the top 5 graduate students with the highest number of research publications in the Mathematics department, sorted by the number of publications in descending order.
CREATE TABLE math_students (student_id INT,student_name VARCHAR(50),publications INT,department VARCHAR(50)); INSERT INTO math_students (student_id,student_name,publications,department) VALUES (1,'Fatima Ahmed',12,'Mathematics'),(2,'Brian Chen',5,'Mathematics'),(3,'Carla Gonzales',8,'Mathematics'),(4,'Daniel Lee',6,'Mathematics'),(5,'Elizabeth Kim',10,'Mathematics'),(6,'Fernando Nguyen',7,'Mathematics');
SELECT student_id, student_name, publications FROM (SELECT student_id, student_name, publications, ROW_NUMBER() OVER (PARTITION BY department ORDER BY publications DESC) as rank FROM math_students WHERE department = 'Mathematics') as top5 WHERE rank <= 5;
What is the maximum heart rate for each member?
CREATE TABLE member_heart_rate (member_id INT,heart_rate INT); INSERT INTO member_heart_rate (member_id,heart_rate) VALUES (1,180),(2,170),(3,160),(4,190),(5,150);
SELECT member_id, MAX(heart_rate) AS max_heart_rate FROM member_heart_rate GROUP BY member_id;
Update 'chemical_name' to 'Potassium Carbonate' for records in 'chemical_usage' table where 'id' is 1
CREATE TABLE chemical_usage (id INT,chemical_name VARCHAR(50),usage_quantity INT,usage_date DATE);
UPDATE chemical_usage SET chemical_name = 'Potassium Carbonate' WHERE id = 1;
What is the average daily transaction volume for the top 3 digital assets by market capitalization in the 'emerging_markets' schema?
CREATE SCHEMA emerging_markets; CREATE TABLE emerging_markets.digital_assets (asset_name VARCHAR(10),market_cap BIGINT,daily_transaction_volume BIGINT); INSERT INTO emerging_markets.digital_assets (asset_name,market_cap,daily_transaction_volume) VALUES ('AssetX',20000000,10000000),('AssetY',15000000,7000000),('AssetZ',10000000,5000000),('AssetW',5000000,3000000),('AssetV',3000000,2000000);
SELECT AVG(daily_transaction_volume) FROM (SELECT daily_transaction_volume FROM emerging_markets.digital_assets ORDER BY market_cap DESC FETCH NEXT 3 ROWS ONLY) t;
What is the percentage of donations made by first-time donors in the last month?
CREATE TABLE donations (id INT,donor_id INT,is_first_time_donor BOOLEAN,amount DECIMAL(10,2),donation_date DATE);
SELECT 100.0 * SUM(CASE WHEN is_first_time_donor THEN amount ELSE 0 END) / SUM(amount) as pct_first_time_donors
Which drugs were approved in the second half of 2021?
CREATE TABLE drug_approval (drug VARCHAR(255),approval_date DATE); INSERT INTO drug_approval (drug,approval_date) VALUES ('DrugC','2021-06-15'),('DrugD','2022-08-30'),('DrugE','2021-12-31'),('DrugF','2021-01-01');
SELECT drug FROM drug_approval WHERE approval_date BETWEEN '2021-07-01' AND '2021-12-31';
What is the minimum funding round size in the fintech sector?
CREATE TABLE company (id INT,name TEXT,industry TEXT); INSERT INTO company (id,name,industry) VALUES (1,'FintechInnovations','Fintech'); 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,2000000); INSERT INTO funding_round (company_id,round_size) VALUES (2,7000000);
SELECT MIN(funding_round.round_size) FROM company INNER JOIN funding_round ON company.id = funding_round.company_id WHERE company.industry = 'Fintech';
What is the minimum depth of all marine protected areas in the Indian Ocean?
CREATE TABLE marine_protected_areas (id INT,name VARCHAR(255),location VARCHAR(255),depth FLOAT); INSERT INTO marine_protected_areas (id,name,location,depth) VALUES (1,'MPA 1','Pacific Ocean',123.4),(2,'MPA 2','Indian Ocean',50.0),(3,'MPA 3','Indian Ocean',75.0);
SELECT MIN(depth) FROM marine_protected_areas WHERE location = 'Indian Ocean';
Show the number of mobile and broadband subscribers in the Africa region
CREATE TABLE africa_subscribers (subscriber_id INT,subscriber_type VARCHAR(10),country VARCHAR(10));
SELECT subscriber_type, COUNT(*), country FROM africa_subscribers GROUP BY subscriber_type, country;
What is the total quantity of Terbium (Tb) and Gadolinium (Gd) supplied by each supplier in 2020, ordered by supplier name?
CREATE TABLE supplier_data (supplier VARCHAR(25),element VARCHAR(2),quantity INT,year INT); INSERT INTO supplier_data VALUES ('SupplierX','Tb',250,2020),('SupplierY','Gd',350,2020),('SupplierX','Gd',150,2020);
SELECT supplier, SUM(quantity) AS total_quantity FROM supplier_data WHERE element IN ('Tb', 'Gd') AND year = 2020 GROUP BY supplier ORDER BY supplier;
What is the average response time for emergency incidents in each region?
CREATE TABLE emergency_responses (id INT,region TEXT,incident_type TEXT,response_time INT); INSERT INTO emergency_responses (id,region,incident_type,response_time) VALUES (1,'Region 1','Fire',8),(2,'Region 1','Medical',10),(3,'Region 2','Fire',7),(4,'Region 2','Medical',9),(5,'Region 3','Fire',9),(6,'Region 3','Medical',11);
SELECT region, AVG(response_time) AS avg_response_time FROM emergency_responses GROUP BY region;
Update the 'production_figures' table and set the 'yearly_production' to null for any record where 'country' is 'Brazil'
CREATE TABLE production_figures (field_id INT PRIMARY KEY,country VARCHAR(50),year INT,yearly_production FLOAT);
UPDATE production_figures SET yearly_production = NULL WHERE country = 'Brazil';
What is the total billing amount for each attorney by region?
CREATE TABLE Attorneys (AttorneyID INT,Name VARCHAR(100),Region VARCHAR(50)); INSERT INTO Attorneys (AttorneyID,Name,Region) VALUES (5,'Davis','Northeast'),(6,'Miller','Midwest'),(7,'Thomas','South'),(8,'Garcia','West');
SELECT A.Region, A.AttorneyID, SUM(P.BillingAmount) AS Total_Billing_Amount FROM Attorneys A INNER JOIN Precedents P ON A.AttorneyID = P.CaseID GROUP BY A.Region, A.AttorneyID;
Display the names and funding amounts for startups that received funding on or after January 1, 2022 from the funding table
CREATE TABLE funding (id INT,startup_name VARCHAR(50),funding_amount INT,date DATE); INSERT INTO funding (id,startup_name,funding_amount,date) VALUES ('Startup A',1000000,'2022-01-01'); INSERT INTO funding (id,startup_name,funding_amount,date) VALUES ('Startup B',2000000,'2022-02-01');
SELECT startup_name, funding_amount FROM funding WHERE date >= '2022-01-01';
What is the total landfill capacity in cubic meters for each country?
CREATE TABLE LandfillCapacity (country VARCHAR(50),year INT,capacity FLOAT); INSERT INTO LandfillCapacity (country,year,capacity) VALUES ('CountryA',2018,5000000.0),('CountryA',2019,5500000.0),('CountryA',2020,6000000.0),('CountryB',2018,4000000.0),('CountryB',2019,4500000.0),('CountryB',2020,5000000.0);
SELECT country, SUM(capacity) FROM LandfillCapacity WHERE year = 2020 GROUP BY country;
What is the regulatory status of digital asset 'Ripple' in the United States?
CREATE TABLE regulatory_frameworks (asset_id INT PRIMARY KEY,country TEXT,status TEXT); INSERT INTO regulatory_frameworks (asset_id,country,status) VALUES (3,'United States','Under Review');
SELECT status FROM regulatory_frameworks WHERE asset_id = 3 AND country = 'United States';
Find the average energy consumption rating for hotels in Australia and New Zealand.
CREATE TABLE Energy_Ratings (hotel_id INT,hotel_name VARCHAR(50),country VARCHAR(50),energy_rating FLOAT); INSERT INTO Energy_Ratings (hotel_id,hotel_name,country,energy_rating) VALUES (1,'Hotel Sydney','Australia',3.7),(2,'Hotel Melbourne','Australia',4.1),(3,'Hotel Auckland','New Zealand',4.5);
SELECT AVG(energy_rating) FROM Energy_Ratings WHERE country IN ('Australia', 'New Zealand') GROUP BY country;
Show the indigenous farmers' details and their organic produce.
CREATE TABLE Indigenous_Farmers (id INT PRIMARY KEY,name VARCHAR(50),age INT,location VARCHAR(50),tribe VARCHAR(50)); INSERT INTO Indigenous_Farmers (id,name,age,location,tribe) VALUES (1,'Nina Sanchez',40,'Brazilian Rainforest','Yanomami'); INSERT INTO Indigenous_Farmers (id,name,age,location,tribe) VALUES (2,'Ali El-Kareem',50,'Jordanian Desert','Bedouin'); CREATE TABLE Indigenous_Produce (id INT PRIMARY KEY,product_name VARCHAR(50),price DECIMAL(5,2),farmer_id INT,location VARCHAR(50),organic_certified BOOLEAN); INSERT INTO Indigenous_Produce (id,product_name,price,farmer_id,location,organic_certified) VALUES (1,'Bananas',0.75,1,'Brazilian Rainforest',true); INSERT INTO Indigenous_Produce (id,product_name,price,farmer_id,location,organic_certified) VALUES (2,'Dates',1.25,2,'Jordanian Desert',true);
SELECT if.name, if.location, ip.product_name, ip.price FROM Indigenous_Farmers if INNER JOIN Indigenous_Produce ip ON if.id = ip.farmer_id WHERE ip.organic_certified = true;
What was the average speed for each vessel type in May 2021?
CREATE TABLE vessels (id INT,type VARCHAR(255)); INSERT INTO vessels (id,type) VALUES (1,'Tanker'),(2,'Bulk Carrier'),(3,'Container Ship'); CREATE TABLE speed (vessel_id INT,speed INT,month VARCHAR(9)); INSERT INTO speed (vessel_id,speed,month) VALUES (1,15,'May 2021'),(1,16,'May 2021'),(2,12,'May 2021'),(2,13,'May 2021'),(3,18,'May 2021'),(3,19,'May 2021');
SELECT v.type, AVG(s.speed) as avg_speed FROM speed s JOIN vessels v ON s.vessel_id = v.id WHERE s.month = 'May 2021' GROUP BY v.type;
Which organizations have been involved in more than 10 humanitarian assistance missions?
CREATE TABLE humanitarian_assistance (org_name VARCHAR(255),mission_id INT);
SELECT org_name, COUNT(*) FROM humanitarian_assistance GROUP BY org_name HAVING COUNT(*) > 10;
What is the maximum wave height recorded in the Indian and Southern Oceans?
CREATE TABLE wave_height (ocean TEXT,height FLOAT); INSERT INTO wave_height (ocean,height) VALUES ('Atlantic',30.0),('Pacific',25.0),('Indian',28.0),('Southern',32.0);
SELECT MAX(height) FROM wave_height WHERE ocean IN ('Indian', 'Southern');
What is the total amount of prize money awarded at esports events in the US?
CREATE TABLE EsportsPrizes (EventID INT,Country VARCHAR(20),PrizeMoney DECIMAL(10,2)); INSERT INTO EsportsPrizes (EventID,Country,PrizeMoney) VALUES (1,'US',50000.00);
SELECT SUM(PrizeMoney) FROM EsportsPrizes WHERE Country = 'US';
What is the average prize pool for esports events in North America?
CREATE TABLE esports_event (event_id INT,event_name VARCHAR(50),game_title VARCHAR(50),prize_pool INT,region VARCHAR(20)); INSERT INTO esports_event (event_id,event_name,game_title,prize_pool,region) VALUES (1,'Worlds','League of Legends',2500000,'North America'); INSERT INTO esports_event (event_id,event_name,game_title,prize_pool,region) VALUES (2,'The International','Dota 2',40000000,'Europe');
SELECT AVG(prize_pool) FROM esports_event WHERE region = 'North America';
Which chemical manufacturers have updated their safety protocols in the past month?
CREATE TABLE chemical_manufacturers (manufacturer_id INT,name VARCHAR(255),last_updated_safety DATE); INSERT INTO chemical_manufacturers (manufacturer_id,name,last_updated_safety) VALUES (1,'ManufacturerA','2021-01-15'),(2,'ManufacturerB','2021-02-10'),(3,'ManufacturerC','2021-03-01');
SELECT name FROM chemical_manufacturers WHERE last_updated_safety BETWEEN DATEADD(month, -1, GETDATE()) AND GETDATE()
List all the races in the 2021 swimming season with their corresponding winners
CREATE TABLE races (race_id INT,race_name VARCHAR(255)); INSERT INTO races VALUES (1,'Race 1'); INSERT INTO races VALUES (2,'Race 2'); CREATE TABLE results (race_id INT,winner_id INT,season VARCHAR(10)); INSERT INTO results VALUES (1,1,'2021'); INSERT INTO results VALUES (2,2,'2021'); CREATE TABLE swimmers (swimmer_id INT,swimmer_name VARCHAR(255)); INSERT INTO swimmers VALUES (1,'Swimmer 1'); INSERT INTO swimmers VALUES (2,'Swimmer 2');
SELECT races.race_name, swimmers.swimmer_name as winner FROM races JOIN results ON races.race_id = results.race_id JOIN swimmers ON results.winner_id = swimmers.swimmer_id WHERE races.season = '2021';
Insert a new record with the date 2022-01-01 and a price of 24.75 into the "carbon_prices" table
CREATE TABLE carbon_prices (id INT,date DATE,price FLOAT);
INSERT INTO carbon_prices (id, date, price) VALUES (1, '2022-01-01', 24.75);
Calculate the average funding amount for startups
CREATE TABLE funding_records (id INT PRIMARY KEY,startup_id INT,amount DECIMAL(10,2),funding_date DATE);
SELECT AVG(amount) FROM funding_records;
What is the total number of military bases located in the United States and Canada, and the number of personnel stationed in each?
CREATE TABLE military_bases (id INT,name TEXT,country TEXT); INSERT INTO military_bases (id,name,country) VALUES (1,'Fort Bragg','USA'),(2,'CFB Trenton','Canada');
SELECT m.country, m.name, COUNT(p.id) as personnel_count FROM military_bases m LEFT JOIN base_personnel p ON m.id = p.base_id GROUP BY m.country, m.name;
What was the total revenue for the past 7 days?
CREATE TABLE daily_revenue (sale_date DATE,revenue DECIMAL(10,2)); INSERT INTO daily_revenue (sale_date,revenue) VALUES ('2022-01-01',5000.00),('2022-01-02',6000.00),('2022-01-03',4000.00),('2022-01-04',7000.00),('2022-01-05',8000.00),('2022-01-06',3000.00),('2022-01-07',9000.00);
SELECT SUM(revenue) FROM daily_revenue WHERE sale_date BETWEEN DATEADD(day, -6, CURRENT_DATE) AND CURRENT_DATE;
Who is the data analyst for climate finance?
CREATE TABLE staff (id INT PRIMARY KEY,name VARCHAR(255),role VARCHAR(255),department VARCHAR(255)); INSERT INTO staff (id,name,role,department) VALUES (1,'Eve','Data Manager','climate_adaptation'),(2,'Frank','Project Manager','climate_mitigation'),(3,'Grace','Data Analyst','climate_finance'),(4,'Hugo','Data Scientist','climate_communication');
SELECT name FROM staff WHERE role = 'Data Analyst' AND department = 'climate_finance';
What is the name and country of the developers who created digital assets with a total supply greater than 10 million?
CREATE TABLE developers (developer_id INT,name VARCHAR(255),country VARCHAR(255)); CREATE TABLE digital_assets (asset_id INT,name VARCHAR(255),total_supply INT,developer_id INT); INSERT INTO developers (developer_id,name,country) VALUES (1,'Alice','USA'),(2,'Bob','Canada'),(3,'Charlie','India'),(4,'Dave','Brazil'); INSERT INTO digital_assets (asset_id,name,total_supply,developer_id) VALUES (1,'CryptoCoin',21000000,1),(2,'DecentralizedApp',1000000,2),(3,'SmartContract',500000,3),(4,'DataToken',100000000,1),(5,'AnotherAsset',5000000,4);
SELECT d.name, d.country FROM digital_assets da JOIN developers d ON da.developer_id = d.developer_id WHERE da.total_supply > 10000000;
How many citizen feedback records were created in January 2022?
CREATE TABLE feedback (id INT,created_at DATETIME); INSERT INTO feedback (id,created_at) VALUES (1,'2022-01-01 12:34:56'),(2,'2022-01-15 10:20:34'),(3,'2022-02-20 16:45:01');
SELECT COUNT(*) FROM feedback WHERE created_at BETWEEN '2022-01-01' AND '2022-01-31';
What was the average age of attendees at the art_exhibit in 2021?
CREATE TABLE art_exhibit (id INT,attendee_age INT,visit_date DATE); INSERT INTO art_exhibit (id,attendee_age,visit_date) VALUES (1,34,'2021-06-01'),(2,45,'2021-06-02'),(3,28,'2021-06-03');
SELECT AVG(attendee_age) FROM art_exhibit WHERE YEAR(visit_date) = 2021;
What is the maximum installed capacity of a wind energy project in Spain?
CREATE TABLE wind_projects (id INT,country VARCHAR(20),installed_capacity FLOAT); INSERT INTO wind_projects (id,country,installed_capacity) VALUES (1,'Spain',75.0),(2,'Spain',85.2),(3,'Spain',95.3),(4,'Canada',65.0);
SELECT MAX(installed_capacity) FROM wind_projects WHERE country = 'Spain';
What is the earliest date a 'subway' station was cleaned?
CREATE TABLE public.cleaning (cleaning_id SERIAL PRIMARY KEY,cleaning_type VARCHAR(20),cleaning_date DATE,station_id INTEGER,FOREIGN KEY (station_id) REFERENCES public.station(station_id)); INSERT INTO public.cleaning (cleaning_type,cleaning_date,station_id) VALUES ('routine cleaning','2022-03-03',1),('deep cleaning','2022-03-15',2);
SELECT MIN(cleaning_date) FROM public.cleaning INNER JOIN public.station ON public.cleaning.station_id = public.station.station_id WHERE route_type = 'subway'
Which programs had the most significant increase in funding between 2020 and 2021?
CREATE TABLE funding (id INT,program_id INT,source VARCHAR(255),amount DECIMAL(10,2),date DATE);
SELECT f1.program_id, p.name, f1.source, (f1.amount - f2.amount) AS funding_increase FROM funding f1 INNER JOIN funding f2 ON f1.program_id = f2.program_id AND f1.date = '2021-12-31' AND f2.date = '2020-12-31' INNER JOIN programs p ON f1.program_id = p.id ORDER BY funding_increase DESC LIMIT 1;
How many national security meetings were held in H1 of 2019?
CREATE TABLE national_security_meetings (id INT,meeting_date DATE,purpose VARCHAR(255)); INSERT INTO national_security_meetings (id,meeting_date,purpose) VALUES (1,'2019-01-10','Intelligence Sharing'),(2,'2019-04-20','Cybersecurity Threat Analysis');
SELECT COUNT(*) FROM national_security_meetings WHERE meeting_date BETWEEN '2019-01-01' AND '2019-06-30';
What is the maximum amount donated by a single donor?
CREATE TABLE Donors (DonorID INT,DonorName TEXT,AmountDonated DECIMAL); INSERT INTO Donors (DonorID,DonorName,AmountDonated) VALUES (1,'John Doe',500.00),(2,'Jane Smith',300.00),(3,'Bob Johnson',700.00);
SELECT MAX(AmountDonated) FROM Donors;
Add a new wheelchair-accessible train station in Chicago
CREATE TABLE train_stations (station_id INT,city VARCHAR(50),accessible BOOLEAN); INSERT INTO train_stations (station_id,city,accessible) VALUES (1,'New York',true),(2,'New York',false),(3,'New York',true),(4,'Boston',true),(5,'Boston',true);
INSERT INTO train_stations (station_id, city, accessible) VALUES (6, 'Chicago', true);
What are the names of all the actors who have acted in a movie with a rating greater than or equal to 9?
CREATE TABLE movies_actors (id INT,movie_id INT,actor_name VARCHAR(255),rating FLOAT); INSERT INTO movies_actors (id,movie_id,actor_name,rating) VALUES (1,1,'ActorA',7.5),(2,2,'ActorB',8.2),(3,3,'ActorC',9.0),(4,4,'ActorD',6.5),(5,5,'ActorA',9.5);
SELECT DISTINCT actor_name FROM movies_actors WHERE id IN (SELECT movie_id FROM movies WHERE rating >= 9);
Get the average population of 'tiger' and 'lion' species in the 'animal_population' table
CREATE TABLE animal_population (species VARCHAR(10),population INT); INSERT INTO animal_population (species,population) VALUES ('tiger',2000),('lion',1500),('tiger',2500),('elephant',5000);
SELECT AVG(population) FROM animal_population WHERE species IN ('tiger', 'lion');
What is the average fine for traffic violations in the city of San Francisco?
CREATE TABLE traffic_violations (id INT,city VARCHAR(255),amount FLOAT); INSERT INTO traffic_violations (id,city,amount) VALUES (1,'San Francisco',150.0),(2,'San Francisco',200.0),(3,'Oakland',120.0);
SELECT AVG(amount) FROM traffic_violations WHERE city = 'San Francisco';
What is the total area of marine protected areas in the Caribbean?
CREATE TABLE Marine_Protected_Areas (id INT PRIMARY KEY,name VARCHAR(255),country VARCHAR(255),area_size FLOAT); INSERT INTO Marine_Protected_Areas (id,name,country,area_size) VALUES (1,'Bonaire National Marine Park','Netherlands',2700);
SELECT SUM(area_size) FROM Marine_Protected_Areas WHERE country = 'Netherlands';
How many cultural events were attended by visitors from a specific region?
CREATE TABLE cultural_events (id INT,name TEXT,location TEXT,start_date DATE,end_date DATE);CREATE TABLE visitors (id INT,name TEXT,region TEXT);CREATE TABLE event_attendance (id INT,visitor_id INT,event_id INT);
SELECT c.location, COUNT(e.id) as num_events FROM cultural_events c JOIN event_attendance ea ON c.id = ea.event_id JOIN visitors v ON ea.visitor_id = v.id WHERE v.region = 'North America' GROUP BY c.location;
Create a view with the total number of electric vehicle charging stations by country
CREATE TABLE charging_stations (id INT PRIMARY KEY,station_name VARCHAR(255),location VARCHAR(255),num_charging_ports INT,country VARCHAR(255));
CREATE VIEW total_charging_stations AS SELECT country, COUNT(*) as total_stations FROM charging_stations GROUP BY country;
Identify the sites that have the highest total quantity of materials used, in the last six months.
CREATE TABLE materials (material_id INT,site_id INT,quantity INT,material_date DATE);
SELECT site_id, SUM(quantity) as total_quantity FROM materials WHERE material_date >= DATEADD(month, -6, CURRENT_DATE) GROUP BY site_id ORDER BY total_quantity DESC;
What is the average number of hours served per volunteer in Germany, for volunteers who have served more than 10 hours?
CREATE TABLE volunteers (volunteer_id int,hours_served int,country varchar(50)); INSERT INTO volunteers (volunteer_id,hours_served,country) VALUES (1,15,'Germany'),(2,5,'Germany'),(3,25,'Germany');
SELECT AVG(hours_served) FROM volunteers WHERE country = 'Germany' GROUP BY volunteer_id HAVING COUNT(volunteer_id) > 10;
What is the total revenue for each cuisine type?
CREATE TABLE revenue (restaurant_id INT,cuisine VARCHAR(255),revenue FLOAT); INSERT INTO revenue (restaurant_id,cuisine,revenue) VALUES (1,'Italian',5000),(1,'Mexican',7000),(2,'Italian',6000),(2,'Chinese',8000);
SELECT cuisine, SUM(revenue) as total_revenue FROM revenue GROUP BY cuisine;
Delete records in the "SmartBuildings" table where the "city" is "Austin"
CREATE TABLE SmartBuildings (id INT,city VARCHAR(20),type VARCHAR(20),capacity INT); INSERT INTO SmartBuildings (id,city,type,capacity) VALUES (1,'Austin','Solar',500),(2,'Seattle','Wind',600),(3,'Austin','Geothermal',400);
DELETE FROM SmartBuildings WHERE city = 'Austin';
Display the average resilience score and length for each type of infrastructure in the Resilience_Length_By_Type view
CREATE VIEW Resilience_Length_By_Type AS SELECT project_id,project_name,project_type,resilience_score,length FROM Infrastructure_Data JOIN Resilience_Scores ON Infrastructure_Data.project_id = Resilience_Scores.project_id WHERE year >= 2015; CREATE TABLE Infrastructure_Types (project_type VARCHAR(255),type_description VARCHAR(255));
SELECT project_type, AVG(resilience_score), AVG(length) FROM Resilience_Length_By_Type JOIN Infrastructure_Types ON Resilience_Length_By_Type.project_type = Infrastructure_Types.project_type GROUP BY project_type;
What is the minimum year of creation for Indigenous artworks?
CREATE TABLE artworks (id INT,name VARCHAR(255),year INT,artist_name VARCHAR(255),artist_birthplace VARCHAR(255),category VARCHAR(255)); INSERT INTO artworks (id,name,year,artist_name,artist_birthplace,category) VALUES (1,'Painting',1920,'John','England','painting'),(2,'Sculpture',1930,'Sara','France','sculpture'),(3,'Print',1940,'Alex','Germany','print'),(4,'Painting',1955,'Maria','Spain','Indigenous'),(5,'Ceremony Object',1890,'Anonymous','Peru','Indigenous');
SELECT MIN(year) FROM artworks WHERE category = 'Indigenous';
How many climate communication campaigns were conducted in Small Island Developing States (SIDS) in the year 2020?
CREATE TABLE climate_communication (year INT,region VARCHAR(255),count INT); INSERT INTO climate_communication (year,region,count) VALUES (2020,'Small Island Developing States',120); INSERT INTO climate_communication (year,region,count) VALUES (2019,'Small Island Developing States',100);
SELECT count FROM climate_communication WHERE year = 2020 AND region = 'Small Island Developing States';
What is the distribution of post likes for each user in the 'likes' schema?
CREATE SCHEMA likes;CREATE TABLE likes.post_likes (user_id INT,like_count INT);
SELECT user_id, AVG(like_count) FROM likes.post_likes GROUP BY user_id;