instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
What is the minimum age of male 'service' union members?
CREATE TABLE service_union_members (member_id INT,gender VARCHAR(10),union VARCHAR(20),age INT); INSERT INTO service_union_members (member_id,gender,union,age) VALUES (1,'Male','Service',25); INSERT INTO service_union_members (member_id,gender,union,age) VALUES (2,'Female','Service',30);
SELECT MIN(age) FROM service_union_members WHERE gender = 'Male';
List the number of mobile and broadband subscribers in each region for the most recent month.
CREATE TABLE mobile_subscribers (subscriber_id INT,region_id INT,join_date DATE); INSERT INTO mobile_subscribers (subscriber_id,region_id,join_date) VALUES (1,1,'2021-01-01'),(2,2,'2021-03-01'),(3,3,'2021-02-01'),(4,4,'2021-04-01'); CREATE TABLE broadband_subscribers (subscriber_id INT,region_id INT,join_date DATE); INSERT INTO broadband_subscribers (subscriber_id,region_id,join_date) VALUES (5,1,'2021-01-15'),(6,2,'2021-03-15'),(7,3,'2021-02-15'),(8,4,'2021-04-15');
SELECT r.region_name, COUNT(m.subscriber_id) AS mobile_count, COUNT(b.subscriber_id) AS broadband_count FROM regions r LEFT JOIN mobile_subscribers m ON r.region_id = m.region_id LEFT JOIN broadband_subscribers b ON r.region_id = b.region_id WHERE MONTH(m.join_date) = MONTH(CURRENT_DATE()) AND YEAR(m.join_date) = YEAR(CURRENT_DATE()) GROUP BY r.region_id;
List the number of support programs offered by each department, excluding any duplicate program names.
CREATE TABLE support_programs (program_name VARCHAR(50),department VARCHAR(50)); INSERT INTO support_programs VALUES ('Tutoring','Science'),('Writing Center','English'),('Tutoring','Science'),('Accessibility Services','General');
SELECT department, COUNT(DISTINCT program_name) FROM support_programs GROUP BY department;
What is the total number of security incidents and vulnerabilities for each system in the last month?
CREATE TABLE security_incidents (id INT,system VARCHAR(255),timestamp DATETIME); CREATE TABLE vulnerabilities (id INT,system VARCHAR(255),timestamp DATETIME);
SELECT system, COUNT(security_incidents.id) + COUNT(vulnerabilities.id) as total_issues FROM security_incidents RIGHT JOIN vulnerabilities ON security_incidents.system = vulnerabilities.system WHERE security_incidents.timestamp >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH) OR vulnerabilities.timestamp >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH) GROUP BY system;
List all suppliers located in the USA with a sustainability rating above 4.0.
CREATE TABLE suppliers (supplier_id INT,name VARCHAR(255),location VARCHAR(255),sustainability_rating FLOAT); INSERT INTO suppliers (supplier_id,name,location,sustainability_rating) VALUES (1,'Blue Manufacturing','USA',4.2),(2,'Green Assembly','Canada',4.8),(3,'Fair Tech','Mexico',4.5),(4,'Eco Supplies','USA',4.7),(5,'Sustainable Logistics','USA',4.3),(6,'Green Materials','Canada',4.6);
SELECT s.name, s.sustainability_rating FROM suppliers s WHERE s.location = 'USA' AND s.sustainability_rating > 4.0;
What are the details of the top 2 most critical vulnerabilities in software products used in the education sector?
CREATE TABLE sector_vulnerabilities (id INT,cve_id VARCHAR(255),sector VARCHAR(255),severity VARCHAR(255),publish_date DATE,description TEXT); INSERT INTO sector_vulnerabilities (id,cve_id,sector,severity,publish_date,description) VALUES (1,'CVE-2022-1234','Education','CRITICAL','2022-02-20','Description of CVE-2022-1234');
SELECT * FROM sector_vulnerabilities WHERE sector = 'Education' AND severity = 'CRITICAL' LIMIT 2;
What is the total number of satellites deployed by SpaceX and Rocket Lab?
CREATE TABLE spacex_satellites (satellite_id INT,company VARCHAR(20)); INSERT INTO spacex_satellites (satellite_id,company) VALUES (1,'SpaceX'),(2,'SpaceX'),(3,'SpaceX'); CREATE TABLE rocket_lab_satellites (satellite_id INT,company VARCHAR(20)); INSERT INTO rocket_lab_satellites (satellite_id,company) VALUES (4,'Rocket Lab'),(5,'Rocket Lab');
SELECT COUNT(*) FROM spacex_satellites JOIN rocket_lab_satellites ON FALSE;
Determine the number of oil spills that have occurred in the Niger Delta and the Caspian Sea.
CREATE TABLE oil_spills_data(spill_name VARCHAR(255),location VARCHAR(255),year INT,volume INT);INSERT INTO oil_spills_data(spill_name,location,year,volume) VALUES('Santa Barbara Oil Spill','Pacific Ocean',1969,80000),('Deepwater Horizon Oil Spill','Gulf of Mexico',2010,4000000),('Ixtoc I Oil Spill','Gulf of Mexico',1979,3000000),('Montara Oil Spill','Timor Sea',2009,30000),('Kursk Oil Spill','Barents Sea',2000,10000),('Niger Delta Oil Spill','Niger Delta',2011,50000);
SELECT location, COUNT(*) AS number_of_spills FROM oil_spills_data WHERE location IN ('Niger Delta', 'Caspian Sea') GROUP BY location;
What is the average temperature recorded in the 'arctic_weather' table for each month in 2020, grouped by month and region?
CREATE TABLE arctic_weather (date DATE,temperature FLOAT,region VARCHAR(255)); INSERT INTO arctic_weather (date,temperature,region) VALUES ('2020-01-01',-15.0,'North'),('2020-01-02',-16.5,'North');
SELECT m.month, r.region, AVG(a.temperature) FROM (SELECT EXTRACT(MONTH FROM date) AS month, region FROM arctic_weather WHERE date BETWEEN '2020-01-01' AND '2020-12-31') m INNER JOIN arctic_weather a ON m.month = EXTRACT(MONTH FROM a.date) AND m.region = a.region GROUP BY m.month, r.region;
Update the conservation_status of a specific marine species in the marine_species table.
CREATE TABLE marine_species (id INT PRIMARY KEY,name VARCHAR(255),conservation_status VARCHAR(255));
UPDATE marine_species SET conservation_status = 'endangered' WHERE id = 1 AND name = 'Blue Whale';
Create a table named "hotels" with columns "hotel_id", "name", "location", and "stars".
CREATE TABLE hotels (hotel_id INT,name VARCHAR(50),location VARCHAR(50),stars INT);
CREATE TABLE hotels (hotel_id INT, name VARCHAR(50), location VARCHAR(50), stars INT);
What is the total budget allocated to each habitat preservation project?
CREATE TABLE habitat_projects (project_id INT,project_name VARCHAR(50));CREATE TABLE budget_allocations (allocation_id INT,project_id INT,allocation_amount DECIMAL(10,2)); INSERT INTO habitat_projects (project_id,project_name) VALUES (1,'Habitat Project A'),(2,'Habitat Project B'),(3,'Habitat Project C'); INSERT INTO budget_allocations (allocation_id,project_id,allocation_amount) VALUES (101,1,5000.00),(102,2,7500.00),(103,3,10000.00);
SELECT p.project_name, SUM(ba.allocation_amount) AS total_budget FROM habitat_projects p JOIN budget_allocations ba ON p.project_id = ba.project_id GROUP BY p.project_name;
Identify the top 5 athletes in terms of their performance in the wellbeing program across all teams.
CREATE TABLE Athletes (Team VARCHAR(50),Athlete VARCHAR(50),Performance DECIMAL(5,2)); INSERT INTO Athletes (Team,Athlete,Performance) VALUES ('Team A','Athlete 1',85.25),('Team A','Athlete 2',88.75),('Team A','Athlete 3',90.00),('Team B','Athlete 4',82.50),('Team B','Athlete 5',86.25),('Team B','Athlete 6',92.50),('Team C','Athlete 7',78.00),('Team C','Athlete 8',89.25),('Team C','Athlete 9',91.50),('Team D','Athlete 10',87.50),('Team D','Athlete 11',93.75),('Team D','Athlete 12',84.00);
SELECT Athlete, Performance FROM (SELECT Athlete, Performance, ROW_NUMBER() OVER (ORDER BY Performance DESC) AS Rank FROM Athletes) WHERE Rank <= 5;
What is the safety score for each creative AI application in North America?
CREATE TABLE CreativeAI (id INT,application VARCHAR(255),safety_score DECIMAL(5,2),region VARCHAR(255)); INSERT INTO CreativeAI (id,application,safety_score,region) VALUES (1,'Artistic Image Generation',85.67,'North America'),(2,'Automated Journalism',91.23,'Europe'),(3,'Music Composition',88.98,'Asia');
SELECT application, safety_score FROM CreativeAI WHERE region = 'North America';
Calculate the average funding amount for each company founded by women
CREATE TABLE company_founding(id INT PRIMARY KEY,company_name VARCHAR(100),founder_gender VARCHAR(10)); CREATE TABLE investment_rounds(id INT PRIMARY KEY,company_id INT,funding_amount INT); INSERT INTO company_founding VALUES (1,'Acme Inc','Female'); INSERT INTO company_founding VALUES (2,'Beta Corp','Male'); INSERT INTO company_founding VALUES (3,'Charlie LLC','Female'); INSERT INTO investment_rounds VALUES (1,1,1000000); INSERT INTO investment_rounds VALUES (2,1,2000000); INSERT INTO investment_rounds VALUES (3,3,500000);
SELECT cf.company_name, AVG(ir.funding_amount) FROM company_founding cf INNER JOIN investment_rounds ir ON cf.id = ir.company_id WHERE cf.founder_gender = 'Female' GROUP BY cf.company_name;
What is the percentage of cases won by attorney 'Lisa Kim'?
CREATE TABLE case_outcomes (case_id INT,attorney_name VARCHAR(50),case_won BOOLEAN); INSERT INTO case_outcomes (case_id,attorney_name,case_won) VALUES (1,'Lisa Kim',true),(2,'Mike Johnson',false),(3,'Lisa Kim',true);
SELECT (COUNT(*) * 100.0 / (SELECT COUNT(*) FROM case_outcomes WHERE attorney_name = 'Lisa Kim')) AS percentage_won FROM case_outcomes WHERE case_won = true AND attorney_name = 'Lisa Kim';
Which artists are the most and least productive in terms of art pieces created?
CREATE TABLE artist_productivity (id INT,artist_name VARCHAR(50),year INT,num_pieces INT);
SELECT artist_name, year, num_pieces FROM (SELECT artist_name, year, num_pieces, DENSE_RANK() OVER (ORDER BY num_pieces DESC) as rank FROM artist_productivity) a WHERE rank <= 1 OR rank >= 11;
What is the minimum and maximum production volume for each mine in Canada?
CREATE TABLE productivity (id INT,mine_id INT,year INT,tons_per_employee INT); INSERT INTO productivity (id,mine_id,year,tons_per_employee) VALUES (9,9,2022,180); INSERT INTO productivity (id,mine_id,year,tons_per_employee) VALUES (10,10,2022,200);
SELECT m.name, MIN(p.tons_per_employee) AS min_production, MAX(p.tons_per_employee) AS max_production FROM mines m JOIN productivity p ON m.id = p.mine_id WHERE m.location = 'Canada' GROUP BY m.name;
Find the names and ages of all ships in the fleet_management table that do not appear in the government_registry table.
CREATE TABLE fleet_management(ship_id INT,ship_name VARCHAR(50),age INT); CREATE TABLE government_registry(ship_id INT,ship_name VARCHAR(50),age INT);
SELECT FM.ship_name, FM.age FROM fleet_management FM WHERE FM.ship_id NOT IN (SELECT GR.ship_id FROM government_registry GR);
Find the total number of emergency calls and crimes committed in areas with high poverty levels.
CREATE TABLE areas (area_id INT,area_name VARCHAR(255),poverty_level DECIMAL(5,2));CREATE TABLE emergency_calls (id INT,area_id INT,call_type VARCHAR(255),call_date DATE);CREATE TABLE crimes (id INT,area_id INT,crime_type VARCHAR(255),crime_date DATE);
SELECT 'Total emergency calls' AS metric, COUNT(ec.id) AS count FROM emergency_calls ec JOIN areas a ON ec.area_id = a.area_id WHERE a.poverty_level >= 0.2 UNION ALL SELECT 'Total crimes' AS metric, COUNT(c.id) AS count FROM crimes c JOIN areas a ON c.area_id = a.area_id WHERE a.poverty_level >= 0.2;
What are the unique types of infrastructure and their respective standard design codes in 'Nevada' and 'Arizona'?
CREATE TABLE Infrastructure (type TEXT,state TEXT,design_code TEXT); INSERT INTO Infrastructure (type,state,design_code) VALUES ('Bridges','Nevada','AASHTO LRFD'); INSERT INTO Infrastructure (type,state,design_code) VALUES ('Dams','Arizona','USBR Design Standards');
SELECT DISTINCT type, design_code FROM Infrastructure WHERE state IN ('Nevada', 'Arizona');
What is the maximum donation amount received from a single donor in the United Kingdom in the year 2018?
CREATE TABLE donations (id INT,donor_id INT,donation_amount DECIMAL(10,2),donation_date DATE); CREATE TABLE donors (id INT,country VARCHAR(50)); INSERT INTO donations (id,donor_id,donation_amount,donation_date) VALUES (1,1,500.00,'2018-10-20'); INSERT INTO donors (id,country) VALUES (1,'United Kingdom');
SELECT MAX(donation_amount) FROM donations JOIN donors ON donations.donor_id = donors.id WHERE donors.country = 'United Kingdom' AND YEAR(donation_date) = 2018;
Which sustainable material has the highest sales in the last quarter?
CREATE TABLE sales (id INT,product_id INT,material VARCHAR(50),sale_date DATE,quantity INT);
SELECT material, SUM(quantity) AS total_sales FROM sales WHERE material IN ('organic_cotton', 'recycled_polyester', 'tencel') AND sale_date >= DATE_SUB(CURDATE(), INTERVAL 3 MONTH) GROUP BY material ORDER BY total_sales DESC LIMIT 1;
Who are the top 3 attorneys with the highest number of successful pro-bono cases in Colorado in the last 2 years?
CREATE TABLE Attorneys (AttorneyID INT,AttorneyName TEXT,ProBonoCases INT,CaseResolutionDate DATE,State TEXT); INSERT INTO Attorneys (AttorneyID,AttorneyName,ProBonoCases,CaseResolutionDate,State) VALUES (1,'John Smith',25,'2022-01-15','Colorado');
SELECT AttorneyName, SUM(ProBonoCases) as TotalProBonoCases FROM Attorneys WHERE State = 'Colorado' AND CaseResolutionDate BETWEEN DATE_SUB(CURRENT_DATE, INTERVAL 2 YEAR) AND CURRENT_DATE GROUP BY AttorneyName ORDER BY TotalProBonoCases DESC LIMIT 3;
What is the maximum carbon sequestration value for each wildlife habitat?
CREATE TABLE habitat (id INT,name VARCHAR(255),carbon_sequestration FLOAT); INSERT INTO habitat (id,name,carbon_sequestration) VALUES (1,'Habitat1',123.45); INSERT INTO habitat (id,name,carbon_sequestration) VALUES (2,'Habitat2',234.56); CREATE TABLE wildlife (id INT,name VARCHAR(255),habitat_id INT); INSERT INTO wildlife (id,name,habitat_id) VALUES (1,'Wildlife1',1); INSERT INTO wildlife (id,name,habitat_id) VALUES (2,'Wildlife2',2);
SELECT w.name, MAX(h.carbon_sequestration) FROM habitat h JOIN wildlife w ON h.id = w.habitat_id GROUP BY w.name;
How many units of each brand's lipstick were sold in Canada in 2021?
CREATE TABLE LipstickSales (sale_id INT,product_id INT,sale_price DECIMAL(5,2),sale_date DATE,brand TEXT,country TEXT); INSERT INTO LipstickSales (sale_id,product_id,sale_price,sale_date,brand,country) VALUES (1,301,12.99,'2021-04-21','Maybelline','Canada');
SELECT brand, product_id, SUM(1) AS units_sold FROM LipstickSales WHERE country = 'Canada' AND sale_date BETWEEN '2021-01-01' AND '2021-12-31' GROUP BY brand, product_id;
List all wastewater treatment plants in California with their capacity.
CREATE TABLE wastewater_plants (plant_id INT,plant_name VARCHAR(255),state VARCHAR(255),capacity FLOAT); INSERT INTO wastewater_plants (plant_id,plant_name,state,capacity) VALUES (1,'LA WWTP','California',5000000),(2,'NY WWTP','New York',3000000);
SELECT plant_name, capacity FROM wastewater_plants WHERE state = 'California';
What is the average budget allocated for military innovation by each country in Africa?
CREATE TABLE military_innovation (country VARCHAR(50),budget INT); INSERT INTO military_innovation (country,budget) VALUES ('Algeria',1200000),('Angola',800000),('Egypt',3000000);
SELECT AVG(budget) avg_budget, country FROM military_innovation WHERE country IN ('Algeria', 'Angola', 'Egypt') GROUP BY country;
How many patients with diabetes live in each state?
CREATE TABLE Patients (PatientID INT,Age INT,Gender TEXT,Diagnosis TEXT,State TEXT); INSERT INTO Patients (PatientID,Age,Gender,Diagnosis,State) VALUES (1,45,'Male','Diabetes','Texas');
SELECT State, COUNT(*) FROM Patients WHERE Diagnosis = 'Diabetes' GROUP BY State;
What is the total transaction amount for each day in January 2022, for transactions that occurred in the United States or Canada?
CREATE TABLE transactions (id INT,transaction_date DATE,country VARCHAR(255),amount DECIMAL(10,2)); INSERT INTO transactions (id,transaction_date,country,amount) VALUES (1,'2022-01-01','USA',100.00),(2,'2022-01-02','Canada',200.00),(3,'2022-01-03','USA',300.00),(4,'2022-01-04','Mexico',400.00);
SELECT transaction_date, SUM(amount) FROM transactions WHERE (country = 'USA' OR country = 'Canada') AND transaction_date BETWEEN '2022-01-01' AND '2022-01-31' GROUP BY transaction_date;
Which mines have both water contamination incidents and geology survey data?
CREATE TABLE mining_incidents (mine_name VARCHAR(255),incident_date DATE,incident_type VARCHAR(255)); INSERT INTO mining_incidents (mine_name,incident_date,incident_type) VALUES ('Green Valley','2017-06-05','Water Contamination'); CREATE TABLE geology_survey (mine_name VARCHAR(255),survey_date DATE,mineral_deposits INT); INSERT INTO geology_survey (mine_name,survey_date,mineral_deposits) VALUES ('Green Valley','2018-02-15',8000); INSERT INTO geology_survey (mine_name,survey_date,mineral_deposits) VALUES ('Blue Hills','2019-01-01',9000);
SELECT mine_name FROM mining_incidents WHERE incident_type = 'Water Contamination' INTERSECT SELECT mine_name FROM geology_survey;
What is the number of articles published by each author in the "Ethics" topic, with an inner join to the authors table?
CREATE TABLE news_articles (article_id INT PRIMARY KEY,title TEXT,topic TEXT,author_id INT,publication_date DATE); CREATE TABLE authors (author_id INT PRIMARY KEY,author_name TEXT);
SELECT a.author_name, COUNT(*) FROM news_articles n INNER JOIN authors a ON n.author_id = a.author_id WHERE n.topic = 'Ethics' GROUP BY a.author_name;
What is the maximum and minimum property size for each city?
CREATE TABLE property (id INT,size FLOAT,city VARCHAR(20)); INSERT INTO property (id,size,city) VALUES (1,1500,'Denver'),(2,2000,'Portland'),(3,1000,'NYC'),(4,2500,'Austin');
SELECT city, MAX(size) as max_size, MIN(size) as min_size FROM property GROUP BY city;
Who are the top 5 consumers by total spent on circular supply chain products?
CREATE TABLE consumers (consumer_id INT,total_spent DECIMAL(10,2)); CREATE TABLE purchases (purchase_id INT,consumer_id INT,product_id INT,is_circular_supply BOOLEAN); INSERT INTO consumers (consumer_id,total_spent) VALUES (1,500),(2,700),(3,600),(4,800),(5,900); INSERT INTO purchases (purchase_id,consumer_id,product_id,is_circular_supply) VALUES (1,1,1,TRUE),(2,1,2,FALSE),(3,2,3,TRUE),(4,3,4,TRUE),(5,4,5,TRUE);
SELECT consumers.consumer_id, SUM(purchases.total_spent) AS total_spent FROM consumers INNER JOIN purchases ON consumers.consumer_id = purchases.consumer_id WHERE purchases.is_circular_supply = TRUE GROUP BY consumers.consumer_id ORDER BY total_spent DESC LIMIT 5;
List all marine species with a known depth in the 'MarineSpecies' table.
CREATE TABLE MarineSpecies (SpeciesID INT PRIMARY KEY,SpeciesName TEXT,KnownDepth FLOAT);
SELECT SpeciesName FROM MarineSpecies WHERE KnownDepth IS NOT NULL;
Show the names and locations of mines where the total amount of coal mined is equal to the total amount of iron mined.
CREATE TABLE mine (id INT,name VARCHAR(50),location VARCHAR(50));CREATE TABLE coal_mine (mine_id INT,amount INT);CREATE TABLE iron_mine (mine_id INT,amount INT);
SELECT m.name, m.location FROM mine m INNER JOIN coal_mine c ON m.id = c.mine_id INNER JOIN iron_mine i ON m.id = i.mine_id GROUP BY m.id, m.name, m.location HAVING SUM(c.amount) = SUM(i.amount);
Update the disability type for student with ID 123 to 'Mental Health'
CREATE TABLE Students (StudentID INT PRIMARY KEY,Name VARCHAR(50),Disability VARCHAR(20));
UPDATE Students SET Disability = 'Mental Health' WHERE StudentID = 123;
What is the average number of research grants per female Principal Investigator (PI)?
CREATE TABLE grants (id INT,pi_gender VARCHAR(6),amount DECIMAL(10,2)); INSERT INTO grants (id,pi_gender,amount) VALUES (1,'Female',50000),(2,'Male',75000),(3,'Female',100000),(4,'Non-binary',80000);
SELECT AVG(total_grants) FROM (SELECT pi_gender, COUNT(*) as total_grants FROM grants WHERE pi_gender = 'Female' GROUP BY pi_gender) as subquery;
How many citizen feedback records were received in total for each service?
CREATE TABLE feedback (service varchar(20),location varchar(20),date date); INSERT INTO feedback (service,location,date) VALUES ('Education','Urban','2021-01-01'),('Healthcare','Urban','2021-02-01'),('Education','Rural','2020-12-01'),('Healthcare','Rural','2020-11-01');
SELECT service, COUNT(*) FROM feedback GROUP BY service;
What is the total water usage by all agricultural customers in the month of July?
CREATE TABLE water_usage(customer_id INT,usage FLOAT,month DATE); INSERT INTO water_usage(customer_id,usage,month) VALUES (1,500,'2022-07-01'),(2,350,'2022-07-01'),(3,700,'2022-07-01');
SELECT SUM(usage) FROM water_usage WHERE month = '2022-07-01' AND customer_type = 'agricultural';
What is the total revenue for each type of network infrastructure investment, for the year 2022?
CREATE TABLE network_investments (investment_id INT,investment_type VARCHAR(50),cost DECIMAL(5,2),investment_date DATE);
SELECT investment_type, SUM(cost) AS total_cost FROM network_investments WHERE YEAR(investment_date) = 2022 GROUP BY investment_type;
Add a new teacher with a unique teacher_id, teacher_name, and assignment to a school, updating the corresponding school record accordingly.
CREATE TABLE schools (school_id INT,school_name TEXT); CREATE TABLE teachers (teacher_id INT,teacher_name TEXT,school_id INT);
INSERT INTO teachers (teacher_id, teacher_name, school_id) VALUES (98765, 'Mx. Lopez', 4321); UPDATE schools s SET s.teacher_id = 98765 WHERE EXISTS (SELECT * FROM teachers t WHERE t.school_id = s.school_id AND s.teacher_id != 98765);
How many customers from the US prefer size 16 and above in women's clothing?
CREATE TABLE CustomerInfo (CustomerID INT,Country VARCHAR(255),PreferredSize INT); INSERT INTO CustomerInfo (CustomerID,Country,PreferredSize) VALUES (1,'US',18),(2,'CA',14),(3,'US',16),(4,'MX',12);
SELECT COUNT(*) FROM CustomerInfo WHERE Country = 'US' AND PreferredSize >= 16;
What is the total value of artworks from female artists in the USA?
CREATE TABLE artists (artist_id INT,name VARCHAR(50),gender VARCHAR(50),country VARCHAR(50)); INSERT INTO artists (artist_id,name,gender,country) VALUES (1,'Georgia O''Keeffe','Female','USA'); CREATE TABLE art_pieces (art_piece_id INT,title VARCHAR(50),value INT,artist_id INT); INSERT INTO art_pieces (art_piece_id,title,value,artist_id) VALUES (1,'Black Iris III',14000000,1);
SELECT SUM(ap.value) FROM art_pieces ap INNER JOIN artists a ON ap.artist_id = a.artist_id WHERE a.gender = 'Female' AND a.country = 'USA';
What is the total number of ethical AI projects in the Middle East and their budgets in 2021?
CREATE TABLE ethical_ai_projects (id INT,region VARCHAR(255),year INT,projects INT,budget DECIMAL(10,2)); INSERT INTO ethical_ai_projects (id,region,year,projects,budget) VALUES (1,'Middle East',2021,50,450000.00); INSERT INTO ethical_ai_projects (id,region,year,projects,budget) VALUES (2,'Europe',2021,60,600000.00);
SELECT region, SUM(budget) FROM ethical_ai_projects WHERE year = 2021 AND region = 'Middle East' GROUP BY region;
Who is the top-rated eco-friendly hotel in Barcelona?
CREATE TABLE hotels (id INT,name TEXT,city TEXT,rating FLOAT); INSERT INTO hotels (id,name,city,rating) VALUES (1,'Eco Hotel','Barcelona',4.6),(2,'Green Lodge','Barcelona',4.7),(3,'Sustainable Suites','Barcelona',4.5);
SELECT name FROM hotels WHERE city = 'Barcelona' AND rating = (SELECT MAX(rating) FROM hotels WHERE city = 'Barcelona' AND name IN ('Eco Hotel', 'Green Lodge', 'Sustainable Suites'));
How many waste generation records are missing a year value?
CREATE TABLE waste_generation (year INT,sector TEXT,amount INT); INSERT INTO waste_generation (year,sector,amount) VALUES (NULL,'commercial',1200),(2018,'residential',800),(2019,'commercial',1500),(2019,'residential',900),(2020,'commercial',NULL),(2020,'residential',1100);
SELECT COUNT(*) FROM waste_generation WHERE year IS NULL;
What is the total revenue from bookings in hotels under the 'Eco-friendly' category, for users from Australia, in 2022, considering both completed and cancelled bookings?
CREATE TABLE hotels(hotel_id INT,hotel_name TEXT,category TEXT); INSERT INTO hotels(hotel_id,hotel_name,category) VALUES (1,'Green Haven Hotel','Eco-friendly'); CREATE TABLE bookings(booking_id INT,hotel_id INT,booking_status TEXT,booking_revenue DECIMAL,booking_date DATE); CREATE TABLE users(user_id INT,user_country TEXT);
SELECT SUM(booking_revenue) FROM hotels INNER JOIN bookings ON hotels.hotel_id = bookings.hotel_id INNER JOIN users ON bookings.user_id = users.user_id WHERE hotels.category = 'Eco-friendly' AND users.user_country = 'Australia' AND YEAR(booking_date) = 2022 AND (booking_status = 'completed' OR booking_status = 'cancelled');
Display the number of tunnels and bridges in each state
CREATE TABLE TB_By_State (id INT,state VARCHAR(50),type VARCHAR(50)); INSERT INTO TB_By_State (id,state,type) VALUES (1,'California','Tunnel'),(2,'California','Bridge'),(3,'Texas','Bridge');
SELECT state, type, COUNT(*) FROM TB_By_State GROUP BY state, type;
Who are the top 2 researchers with the most funding in the 'genetic research' sector?
CREATE TABLE researchers (id INT,name VARCHAR(50),sector VARCHAR(50),funding FLOAT); INSERT INTO researchers (id,name,sector,funding) VALUES (1,'Alice','genetic research',2000000),(2,'Bob','bioprocess engineering',1500000),(3,'Charlie','genetic research',2500000);
SELECT name FROM researchers WHERE sector = 'genetic research' ORDER BY funding DESC LIMIT 2;
Calculate the percentage of projects completed on time, in the Southern region, for the first half of 2021.
CREATE TABLE ProjectTimelineByHalf (ProjectID int,Region varchar(20),Half int,OnTime bit); INSERT INTO ProjectTimelineByHalf (ProjectID,Region,Half,OnTime) VALUES (1,'Southern',1,1),(2,'Northern',1,0),(3,'Southern',1,1);
SELECT Region, PERCENTAGE(SUM(OnTime) OVER (PARTITION BY Region) / COUNT(*) OVER (PARTITION BY Region)) as PercentageOnTime FROM ProjectTimelineByHalf WHERE Region = 'Southern' AND Half = 1;
Which menu items have a high waste percentage and are not locally sourced?
CREATE TABLE Dishes (DishID INT,Name VARCHAR(50),WastePercentage DECIMAL(3,2),LocallySourced BOOLEAN); INSERT INTO Dishes (DishID,Name,WastePercentage,LocallySourced) VALUES (1,'Chicken Curry',0.35,FALSE),(2,'Vegetable Lasagna',0.25,TRUE),(3,'Fish Tacos',0.40,FALSE);
SELECT Name FROM Dishes WHERE WastePercentage > 0.3 AND LocallySourced = FALSE;
List all Shariah-compliant financial products and their respective categories, ordered by product name.
CREATE TABLE shariah_compliant_finance (product_id INT,product_name VARCHAR(50),category VARCHAR(50)); INSERT INTO shariah_compliant_finance (product_id,product_name,category) VALUES (1,'Musharakah','Profit and Loss Sharing'),(2,'Ijarah','Leasing'),(3,'Murabahah','Cost Plus'),(4,'Takaful','Insurance');
SELECT product_name, category FROM shariah_compliant_finance ORDER BY product_name;
Which community health workers have the highest cultural competency score?
CREATE TABLE community_health_workers (id INT,name VARCHAR(50),cultural_competency_score INT); INSERT INTO community_health_workers (id,name,cultural_competency_score) VALUES (1,'John Doe',90),(2,'Jane Smith',85);
SELECT name, cultural_competency_score, RANK() OVER (ORDER BY cultural_competency_score DESC) as rank FROM community_health_workers;
What is the total water consumption in regions with severe droughts in 2019?
CREATE TABLE water_usage (region VARCHAR(255),year INT,total_consumption INT); INSERT INTO water_usage (region,year,total_consumption) VALUES ('North',2018,5000),('North',2019,5500),('South',2018,6000),('South',2019,6500); CREATE TABLE drought_info (region VARCHAR(255),year INT,severity INT); INSERT INTO drought_info (region,year,severity) VALUES ('North',2018,3),('North',2019,5),('South',2018,2),('South',2019,4);
SELECT SUM(w.total_consumption) FROM water_usage w JOIN drought_info d ON w.region = d.region WHERE w.year = 2019 AND d.severity = 5;
What is the minimum installed capacity (in MW) of solar energy generators in Italy?
CREATE TABLE solar_generators (country VARCHAR(20),capacity FLOAT); INSERT INTO solar_generators (country,capacity) VALUES ('Italy',1000.0),('Italy',1500.0),('Italy',2000.0);
SELECT MIN(capacity) FROM solar_generators WHERE country = 'Italy';
What is the total biomass of fish in Chilean farms that grow fish in offshore cages?
CREATE TABLE chilean_farms (farmer_id INT,farm_location TEXT,farming_method TEXT,biomass FLOAT); INSERT INTO chilean_farms (farmer_id,farm_location,farming_method,biomass) VALUES (1,'Santiago','Offshore cages',300.4),(2,'Valparaiso','Flow-through',250.0),(3,'Concepcion','Offshore cages',400.5);
SELECT SUM(biomass) FROM chilean_farms WHERE farming_method = 'Offshore cages';
List all smart city initiatives in the USA with their respective start dates and end dates.
CREATE TABLE smart_cities (initiative_id INT,initiative_name VARCHAR(255),country VARCHAR(255),start_date DATE,end_date DATE);
SELECT initiative_name, start_date, end_date FROM smart_cities WHERE country = 'USA';
What is the minimum number of visitors for the "Photography" exhibition in the first quarter of 2022?
CREATE TABLE daily_visitor_count (date DATE,exhibition_id INT,visitor_count INT); INSERT INTO daily_visitor_count (date,exhibition_id,visitor_count) VALUES ('2022-01-01',5,200);
SELECT MIN(visitor_count) FROM daily_visitor_count WHERE exhibition_id = 5 AND date BETWEEN '2022-01-01' AND '2022-03-31';
What is the total duration (in days) of each space mission?
CREATE TABLE space_missions (id INT,mission_name VARCHAR(255),start_date DATE,end_date DATE); INSERT INTO space_missions (id,mission_name,start_date,end_date) VALUES (1,'Apollo 11','1969-07-16','1969-07-24'),(2,'Mars Rover','2004-01-04','2019-02-13'),(3,'Apollo 13','1970-04-11','1970-04-17');
SELECT mission_name, DATEDIFF(end_date, start_date) OVER (PARTITION BY mission_name) as TotalDuration FROM space_missions;
List the regions that have invested in Fiber network infrastructure, and the respective investment amounts.
CREATE TABLE network_investments (investment_id INT,technology VARCHAR(20),region VARCHAR(50),investment_amount INT); INSERT INTO network_investments (investment_id,technology,region,investment_amount) VALUES (1,'4G','North',10000),(2,'5G','North',20000),(3,'3G','South',15000),(4,'5G','East',25000),(5,'Fiber','West',40000),(6,'Cable','West',20000),(7,'DSL','East',18000),(8,'Fiber','North',50000);
SELECT technology, region, investment_amount FROM network_investments WHERE technology = 'Fiber';
Which agricultural innovation projects have a budget greater than the average budget in the 'agricultural_innovation_projects' table?
CREATE TABLE agricultural_innovation_projects (id INT,project_name VARCHAR(50),budget FLOAT); INSERT INTO agricultural_innovation_projects (id,project_name,budget) VALUES (1,'Drip Irrigation',250000.00),(2,'Livestock Genetics',320000.00),(3,'Crop Sensors',400000.00);
SELECT project_name FROM agricultural_innovation_projects WHERE budget > (SELECT AVG(budget) FROM agricultural_innovation_projects);
How many safety incidents occurred in chemical manufacturing plants in Nigeria in the year 2018?
CREATE TABLE safety_incidents (id INT,plant_id INT,incident_date DATE); CREATE TABLE manufacturing_plants (id INT,plant_name VARCHAR(100),country VARCHAR(50)); INSERT INTO manufacturing_plants (id,plant_name,country) VALUES (1,'Nigeria Plant 1','Nigeria'),(2,'Nigeria Plant 2','Nigeria'); INSERT INTO safety_incidents (id,plant_id,incident_date) VALUES (1,1,'2018-01-01'),(2,1,'2018-05-15'),(3,2,'2018-12-28');
SELECT COUNT(*) FROM safety_incidents JOIN manufacturing_plants ON safety_incidents.plant_id = manufacturing_plants.id WHERE manufacturing_plants.country = 'Nigeria' AND EXTRACT(YEAR FROM incident_date) = 2018;
Show me the average budget of intelligence agencies in the 'Intelligence_Agencies' table.
CREATE SCHEMA IF NOT EXISTS defense_security;CREATE TABLE IF NOT EXISTS defense_security.Intelligence_Agencies (id INT PRIMARY KEY,agency_name VARCHAR(255),location VARCHAR(255),budget INT);INSERT INTO defense_security.Intelligence_Agencies (id,agency_name,location,budget) VALUES (1,'Central Intelligence Agency (CIA)','Virginia',15000000000);
SELECT AVG(budget) FROM defense_security.Intelligence_Agencies;
What is the highest salary for an employee in the Finance department?
CREATE TABLE Employees (Employee_ID INT PRIMARY KEY,First_Name VARCHAR(30),Last_Name VARCHAR(30),Department VARCHAR(30),Salary DECIMAL(10,2)); INSERT INTO Employees (Employee_ID,First_Name,Last_Name,Department,Salary) VALUES (1,'Kevin','Garcia','Finance',70000.00); INSERT INTO Employees (Employee_ID,First_Name,Last_Name,Department,Salary) VALUES (2,'Lucy','Gonzalez','Finance',75000.00);
SELECT MAX(Salary) FROM Employees WHERE Department = 'Finance';
What is the most common mental health condition treated in the last 12 months in Pacific Islander community and the average age of patients with this condition?
CREATE TABLE mental_health_conditions (condition_id INT,name VARCHAR(255),description VARCHAR(255)); CREATE TABLE patients (patient_id INT,age INT,gender VARCHAR(10),condition VARCHAR(255),ethnicity VARCHAR(255)); CREATE TABLE therapy_sessions (session_id INT,patient_id INT,therapist_id INT,session_date DATE); CREATE TABLE communities (community_id INT,name VARCHAR(255),type VARCHAR(255));
SELECT mental_health_conditions.name, AVG(patients.age) FROM patients JOIN therapy_sessions ON patients.patient_id = therapy_sessions.patient_id JOIN mental_health_conditions ON patients.condition = mental_health_conditions.condition JOIN communities ON patients.community_id = communities.community_id WHERE communities.type = 'Pacific Islander' AND therapy_sessions.session_date >= DATE_SUB(CURRENT_DATE, INTERVAL 12 MONTH) GROUP BY patients.condition ORDER BY COUNT(*) DESC LIMIT 1;
Identify mine sites where mercury pollution exceeds the allowed limit.
CREATE TABLE EnvironmentalImpact (SiteID INT,Pollutant VARCHAR(50),AmountDecimal FLOAT,Measurement VARCHAR(50),Date DATE,AllowedLimitDecimal FLOAT); ALTER TABLE MineSites ADD CONSTRAINT FK_SiteID FOREIGN KEY (SiteID) REFERENCES EnvironmentalImpact(SiteID);
SELECT MineSites.Name, EnvironmentalImpact.Pollutant, EnvironmentalImpact.AmountDecimal FROM MineSites JOIN EnvironmentalImpact ON MineSites.SiteID = EnvironmentalImpact.SiteID WHERE EnvironmentalImpact.Pollutant = 'Mercury' AND EnvironmentalImpact.AmountDecimal > EnvironmentalImpact.AllowedLimitDecimal;
What is the total revenue for each dish category?
CREATE TABLE dishes (dish_id INT,dish VARCHAR(50),category VARCHAR(50));CREATE TABLE orders (order_id INT,dish_id INT,price DECIMAL(5,2));
SELECT c.category, SUM(o.price) as total_revenue FROM dishes d JOIN orders o ON d.dish_id = o.dish_id GROUP BY c.category;
What is the total amount of socially responsible loans issued by financial institutions in the Asia Pacific region?
CREATE TABLE financial_institutions (institution_id INT,institution_name TEXT,region TEXT);CREATE TABLE loans (loan_id INT,institution_id INT,loan_amount DECIMAL,is_socially_responsible BOOLEAN);
SELECT SUM(loan_amount) FROM loans JOIN financial_institutions ON loans.institution_id = financial_institutions.institution_id WHERE is_socially_responsible = TRUE AND region = 'Asia Pacific';
Delete all cultural competency trainings for the Midwest?
CREATE TABLE cultural_competency_trainings (region VARCHAR(50),trainings INT); INSERT INTO cultural_competency_trainings (region,trainings) VALUES ('Northeast',300),('Southeast',250),('Midwest',200),('Southwest',180),('West',350);
DELETE FROM cultural_competency_trainings WHERE region = 'Midwest';
Calculate the percentage of healthcare providers with low cultural competency scores.
CREATE TABLE healthcare_providers (provider_id INT,name TEXT,state TEXT,cultural_competency_score INT); INSERT INTO healthcare_providers (provider_id,name,state,cultural_competency_score) VALUES (1,'Ms. Emily Davis','TX'),(2,'Mr. Jose Garcia','TX');
SELECT COUNT(*) * 100.0 / (SELECT COUNT(*) FROM healthcare_providers) AS percentage FROM healthcare_providers WHERE cultural_competency_score < 50;
List all vegan makeup products and their respective suppliers.
CREATE TABLE MakeupProducts (product_id INT,product_name VARCHAR(100),category VARCHAR(50),vegan BOOLEAN); CREATE TABLE Suppliers (supplier_id INT,supplier_name VARCHAR(100),product_id INT);
SELECT MakeupProducts.product_name, Suppliers.supplier_name FROM MakeupProducts INNER JOIN Suppliers ON MakeupProducts.product_id = Suppliers.product_id WHERE MakeupProducts.vegan = TRUE;
Delete the record of the athlete with 'athlete_id' 152 from the 'baseball_players' table
CREATE TABLE baseball_players (player_id INT,player_name VARCHAR(50),position VARCHAR(50),team VARCHAR(50));
DELETE FROM baseball_players WHERE player_id = 152;
Find the daily average transaction amount for the top 10 customers with the highest transaction values in Q1 2022?
CREATE TABLE customers (customer_id INT,country_code CHAR(2)); CREATE TABLE transactions (transaction_id INT,customer_id INT,transaction_amount DECIMAL(10,2),transaction_date DATE);
SELECT AVG(transaction_amount) FROM (SELECT transaction_amount FROM transactions INNER JOIN customers ON transactions.customer_id = customers.customer_id WHERE transactions.transaction_date BETWEEN '2022-01-01' AND '2022-03-31' GROUP BY customer_id ORDER BY SUM(transaction_amount) DESC LIMIT 10) AS top_customers;
What is the total number of shipwrecks in the Caribbean Sea?
CREATE TABLE shipwrecks (name VARCHAR(255),location VARCHAR(255));
SELECT COUNT(*) FROM shipwrecks WHERE location = 'Caribbean Sea';
Update the age of patient 3 in 'RuralClinicA' to 40
CREATE TABLE RuralClinicA (patient_id INT,age INT,gender VARCHAR(10)); INSERT INTO RuralClinicA (patient_id,age,gender) VALUES (1,45,'Female'),(2,60,'Female'),(3,35,'Male');
UPDATE RuralClinicA SET age = 40 WHERE patient_id = 3;
What is the average number of attendees per event in Spain?
CREATE TABLE Events (EventID INT,Country TEXT,Attendees INT); INSERT INTO Events (EventID,Country,Attendees) VALUES (1,'Spain',200),(2,'France',300),(3,'Spain',250);
SELECT AVG(Attendees) FROM Events WHERE Country = 'Spain';
How many clinical trials were conducted for each drug in the 'ClinicalTrials' table, unpivoted and with a total row?
CREATE TABLE ClinicalTrials (trial_id INT,drug_name VARCHAR(255),trial_status VARCHAR(255)); INSERT INTO ClinicalTrials (trial_id,drug_name,trial_status) VALUES (1,'DrugA','Completed'),(2,'DrugA','Failed'),(3,'DrugB','Completed'),(4,'DrugC','In Progress');
SELECT drug_name, 'trial_count' as metric, COUNT(*) as value FROM ClinicalTrials GROUP BY drug_name UNION ALL SELECT 'Total', COUNT(*) as value FROM ClinicalTrials;
What is the average horsepower of sports cars released between 2015 and 2018?
CREATE TABLE sports_cars (year INT,make VARCHAR(50),model VARCHAR(50),horsepower INT); INSERT INTO sports_cars (year,make,model,horsepower) VALUES (2015,'Ferrari','488 GTB',661),(2016,'Lamborghini','Huracan',602),(2017,'McLaren','720S',710),(2018,'Porsche','911 GT2 RS',690);
SELECT AVG(horsepower) FROM sports_cars WHERE year BETWEEN 2015 AND 2018;
Update the rating of all lip balms to 3
CREATE TABLE cosmetics (id INT,name VARCHAR(255),rating INT,category VARCHAR(255)); INSERT INTO cosmetics (id,name,rating,category) VALUES (1,'Lip Balm 1',1,'Lip Balm'),(2,'Lip Balm 2',5,'Lip Balm'),(3,'Lip Balm 3',3,'Lip Balm'),(4,'Lip Balm 4',4,'Lip Balm');
UPDATE cosmetics SET rating = 3 WHERE category = 'Lip Balm';
What is the total tons of minerals extracted and the average number of employees for each company in each state?
CREATE TABLE mine_productivity (company VARCHAR(255),state VARCHAR(255),year INT,total_tons FLOAT,employees INT); INSERT INTO mine_productivity (company,state,year,total_tons,employees) VALUES ('ABC Mining','Colorado',2015,250000,500),('ABC Mining','Colorado',2016,275000,550),('DEF Mining','Wyoming',2015,300000,600),('DEF Mining','Wyoming',2016,325000,650);
SELECT company, state, SUM(total_tons) as total_tons, AVG(employees) as avg_employees FROM mine_productivity GROUP BY company, state;
What was the total revenue for each dispensary in Oregon, broken down by quarter in 2021?
CREATE TABLE Dispensaries (id INT,name TEXT,state TEXT,revenue FLOAT,date DATE); INSERT INTO Dispensaries (id,name,state,revenue,date) VALUES (1,'Dispensary A','OR',250000.00,'2021-01-01'),(2,'Dispensary B','OR',300000.00,'2021-02-01'),(3,'Dispensary C','OR',150000.00,'2021-03-01'),(4,'Dispensary D','OR',400000.00,'2021-04-01'),(5,'Dispensary E','OR',200000.00,'2021-01-01');
SELECT name, DATE_TRUNC('quarter', date) AS quarter, SUM(revenue) FROM Dispensaries WHERE state = 'OR' GROUP BY name, quarter ORDER BY quarter;
Retrieve the number of green buildings in the state of New York.
CREATE TABLE green_buildings (id INT,state VARCHAR(20)); INSERT INTO green_buildings (id,state) VALUES (1,'New York'),(2,'California');
SELECT COUNT(*) FROM green_buildings WHERE state = 'New York';
Find the total capacity of warehouses in California and Texas.
CREATE TABLE Warehouses (WarehouseID INT,WarehouseName VARCHAR(50),City VARCHAR(50),State VARCHAR(50),Capacity INT); INSERT INTO Warehouses (WarehouseID,WarehouseName,City,State,Capacity) VALUES (1,'Warehouse A','Los Angeles','CA',60000),(2,'Warehouse B','Dallas','TX',80000),(3,'Warehouse C','Miami','FL',40000);
SELECT SUM(Capacity) FROM Warehouses WHERE State IN ('CA', 'TX');
Number of hotel adoptions of AI in 'Asia' since 2020?
CREATE TABLE hotel_ai (hotel_id INT,hotel_name TEXT,ai_adoption_date DATE); INSERT INTO hotel_ai (hotel_id,hotel_name,ai_adoption_date) VALUES (1,'Hotel Asia','2021-12-15'),(2,'Hotel Asia','2022-02-01');
SELECT COUNT(*) FROM hotel_ai WHERE ai_adoption_date >= '2020-01-01' AND hotel_name IN (SELECT hotel_name FROM hotels WHERE hotel_location = 'Asia');
List all volunteers who have contributed more than 20 hours in total, along with their corresponding organization names and the causes they supported, for mission areas Art and Culture and Environment.
CREATE TABLE volunteers (id INT,name VARCHAR(100),organization_id INT,cause VARCHAR(50),hours DECIMAL(5,2)); CREATE TABLE organizations (id INT,name VARCHAR(100),mission_area VARCHAR(50),state VARCHAR(50)); INSERT INTO volunteers VALUES (1,'James Smith',3,'Art and Culture',25); INSERT INTO volunteers VALUES (2,'Emily Johnson',4,'Environment',22);
SELECT v.name, o.name as organization_name, v.cause, SUM(v.hours) as total_hours FROM volunteers v INNER JOIN organizations o ON v.organization_id = o.id WHERE o.mission_area IN ('Art and Culture', 'Environment') GROUP BY v.name, v.organization_id, v.cause HAVING SUM(v.hours) > 20;
What is the minimum number of personnel contributed to peacekeeping operations by countries in the Asia-Pacific region?
CREATE TABLE Peacekeeping_Operations (Nation VARCHAR(50),Continent VARCHAR(50),Personnel INT); INSERT INTO Peacekeeping_Operations (Nation,Continent,Personnel) VALUES ('Australia','Asia-Pacific',1500),('Indonesia','Asia-Pacific',2000),('Japan','Asia-Pacific',1750);
SELECT MIN(Personnel) FROM Peacekeeping_Operations WHERE Continent = 'Asia-Pacific';
What is the total yield of apples in Washington in the past year?
CREATE TABLE Farming (location VARCHAR(50),crop VARCHAR(50),yield INT,timestamp TIMESTAMP);
SELECT SUM(yield) FROM Farming WHERE location = 'Washington' AND crop = 'apples' AND timestamp > NOW() - INTERVAL '1 year';
Which minerals were extracted in quantities greater than 500 tons by companies that have mining operations in Russia?
CREATE TABLE company (id INT,name VARCHAR(255),country VARCHAR(255));CREATE TABLE extraction (company_id INT,mineral VARCHAR(255),amount INT);
SELECT DISTINCT e.mineral FROM extraction e JOIN company c ON e.company_id = c.id WHERE c.country = 'Russia' AND e.amount > 500;
Remove the 'community_engagement' record for 'City M' from the 'community_engagement' table
CREATE TABLE community_engagement (id INT,city VARCHAR(50),organization VARCHAR(50),type VARCHAR(50),year INT); INSERT INTO community_engagement (id,city,organization,type,year) VALUES (1,'City M','Organization A','Cultural Festival',2018),(2,'City N','Organization B','Language Workshop',2019),(3,'City O','Organization C','Art Exhibition',2020);
DELETE FROM community_engagement WHERE city = 'City M';
What percentage of marine protected areas are in the Indian ocean?
CREATE TABLE marine_protected_areas (area_name TEXT,ocean TEXT); CREATE VIEW marine_protected_areas_count AS SELECT ocean,COUNT(*) FROM marine_protected_areas GROUP BY ocean;
SELECT 100.0 * SUM(CASE WHEN ocean = 'Indian' THEN 1 ELSE 0 END) / (SELECT COUNT(*) FROM marine_protected_areas_count) FROM marine_protected_areas;
What is the recycling rate in percentage for each material type in 2019?
CREATE TABLE recycling_rates (material VARCHAR(255),year INT,rate FLOAT); INSERT INTO recycling_rates (material,year,rate) VALUES ('Plastic',2019,12.0),('Glass',2019,22.0),('Paper',2019,35.0),('Metal',2019,45.0);
SELECT r.material, AVG(r.rate) as avg_rate FROM recycling_rates r WHERE r.year = 2019 GROUP BY r.material;
List all states and their respective percentage of total government spending on healthcare.
CREATE TABLE government_spending (state VARCHAR(20),category VARCHAR(20),amount INT); INSERT INTO government_spending (state,category,amount) VALUES ('New York','Healthcare',180000000),('California','Healthcare',250000000),('Texas','Healthcare',220000000),('Florida','Healthcare',160000000),('Pennsylvania','Healthcare',140000000);
SELECT state, ROUND(100.0*SUM(CASE WHEN category = 'Healthcare' THEN amount ELSE 0 END)/SUM(amount), 1) AS healthcare_percentage FROM government_spending GROUP BY state;
Find the number of unique founders from each country.
CREATE TABLE founders (id INT,name TEXT,country TEXT); INSERT INTO founders (id,name,country) VALUES (1,'John Doe','USA'); INSERT INTO founders (id,name,country) VALUES (2,'Jane Smith','Canada'); INSERT INTO founders (id,name,country) VALUES (3,'Alice','India'); INSERT INTO founders (id,name,country) VALUES (4,'Bob','USA');
SELECT country, COUNT(DISTINCT name) FROM founders GROUP BY country;
How many organizations received grants in France and Germany between 2018 and 2020?
CREATE TABLE Grants (GrantID INT,OrganizationID INT,Country TEXT,GrantYear INT); CREATE TABLE Organizations (OrganizationID INT,OrganizationName TEXT); INSERT INTO Grants (GrantID,OrganizationID,Country,GrantYear) VALUES (1,1,'France',2018),(2,2,'Germany',2019),(3,1,'France',2020); INSERT INTO Organizations (OrganizationID,OrganizationName) VALUES (1,'Greenpeace'),(2,'Doctors Without Borders');
SELECT COUNT(DISTINCT o.OrganizationID) FROM Grants g JOIN Organizations o ON g.OrganizationID = o.OrganizationID WHERE g.Country IN ('France', 'Germany') AND g.GrantYear BETWEEN 2018 AND 2020;
Which broadband subscribers in the Southeast region have had the most usage in the past year?
CREATE TABLE subscribers(id INT,region VARCHAR(10)); CREATE TABLE usage(subscriber_id INT,usage_date DATE,data_usage INT);
SELECT subscribers.id, SUM(usage.data_usage) as total_usage FROM subscribers JOIN usage ON subscribers.id = usage.subscriber_id WHERE subscribers.region = 'Southeast' AND usage.usage_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR) GROUP BY subscribers.id ORDER BY total_usage DESC LIMIT 1;
What is the average citizen satisfaction rating for public transportation and waste management services combined, in the 'CityData' schema's 'CitySatisfaction' table, for the year 2022?
CREATE SCHEMA CityData; CREATE TABLE CitySatisfaction (Service varchar(255),Year int,Satisfaction int); INSERT INTO CitySatisfaction (Service,Year,Satisfaction) VALUES ('Public Transportation',2022,7),('Public Transportation',2022,8),('Waste Management',2022,9),('Waste Management',2022,6);
SELECT AVG(Satisfaction) FROM CityData.CitySatisfaction WHERE Year = 2022 AND Service IN ('Public Transportation', 'Waste Management');
What is the total revenue generated from expedited shipments?
CREATE TABLE shipments (id INT,shipment_type VARCHAR(10),revenue DECIMAL(10,2)); INSERT INTO shipments (id,shipment_type,revenue) VALUES (1,'domestic',500.00),(2,'international',800.00),(3,'expedited',1000.00);
SELECT SUM(revenue) FROM shipments WHERE shipment_type = 'expedited';
What is the maximum price of a skincare product in Canada?
CREATE TABLE product_pricing(id INT,product_name VARCHAR(50),price FLOAT,product_category VARCHAR(50),supplier_country VARCHAR(30)); INSERT INTO product_pricing(id,product_name,price,product_category,supplier_country) VALUES (2,'Moisturizer',35.00,'Skincare','Canada');
SELECT MAX(price) FROM product_pricing WHERE product_category = 'Skincare' AND supplier_country = 'Canada';
What is the total billing amount for cases handled by attorneys who identify as female and have at least 5 years of experience?
CREATE TABLE attorneys (attorney_id INT,gender TEXT,years_of_experience INT); CREATE TABLE cases (case_id INT,attorney_id INT,billing_amount INT);
SELECT SUM(cases.billing_amount) FROM cases INNER JOIN attorneys ON cases.attorney_id = attorneys.attorney_id WHERE attorneys.gender = 'female' AND attorneys.years_of_experience >= 5;