instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
What is the total revenue from concert ticket sales for a given artist in a given year?
CREATE TABLE Concerts (id INT,artist_id INT,city VARCHAR(50),revenue DECIMAL(10,2),year INT);
SELECT artist_id, SUM(revenue) AS total_revenue FROM Concerts WHERE year = 2021 GROUP BY artist_id;
What is the total number of security incidents for each department in the last month?
CREATE TABLE security_incidents (id INT,department VARCHAR(50),timestamp DATETIME);
SELECT department, COUNT(*) as num_incidents FROM security_incidents WHERE timestamp > DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH) GROUP BY department;
What is the highest ticket price for a play in London?
CREATE TABLE plays (title VARCHAR(255),location VARCHAR(255),price DECIMAL(5,2)); INSERT INTO plays (title,location,price) VALUES ('Hamilton','London',250.00),('Macbeth','London',150.00),('Romeo and Juliet','London',120.00);
SELECT MAX(price) FROM plays WHERE location = 'London';
What is the total amount of waste produced by each process in the last 3 months?
CREATE TABLE processes (id INT,name TEXT); INSERT INTO processes (id,name) VALUES (1,'Process A'),(2,'Process B'),(3,'Process C'); CREATE TABLE waste (process_id INT,waste_date DATE,amount FLOAT); INSERT INTO waste (process_id,waste_date,amount) VALUES (1,'2022-03-01',150.0),(1,'2022-04-01',160.0),(1,'2022-05-01',170.0),(2,'2022-03-01',120.0),(2,'2022-04-01',125.0),(2,'2022-05-01',130.0),(3,'2022-03-01',180.0),(3,'2022-04-01',190.0),(3,'2022-05-01',200.0);
SELECT process_id, SUM(amount) as total_waste FROM waste WHERE waste_date BETWEEN DATE_SUB(NOW(), INTERVAL 3 MONTH) AND NOW() GROUP BY process_id;
What is the total cost of space exploration missions led by NASA?
CREATE TABLE SpaceExploration (id INT,agency VARCHAR(255),country VARCHAR(255),cost FLOAT); INSERT INTO SpaceExploration VALUES (1,'NASA','USA',22000000000),(2,'ESA','Europe',18000000000),(3,'Roscosmos','Russia',15000000000),(4,'ISRO','India',7000000000);
SELECT SUM(cost) FROM SpaceExploration WHERE agency = 'NASA';
Show the total number of members from each country who have a gym membership, excluding those who also use wearable technology.
CREATE TABLE members_geo_ext(id INT,name VARCHAR(50),gender VARCHAR(10),age INT,membership_type VARCHAR(20),country VARCHAR(20),city VARCHAR(20),wearable_device VARCHAR(20)); INSERT INTO members_geo_ext(id,name,gender,age,membership_type,country,city,wearable_device) VALUES (1,'John Doe','Male',30,'Gym','USA','New York','Smartwatch'),(2,'Jane Doe','Female',45,'Swimming','Mexico','Mexico City',NULL);
SELECT country, COUNT(*) as count FROM members_geo_ext WHERE membership_type = 'Gym' AND wearable_device IS NULL GROUP BY country;
Which marine species have the same number of individuals in the 'PollutionMonitoring' and 'ConservationEfforts' tables?
CREATE TABLE PollutionMonitoring (SpeciesID INT,Individuals INT); INSERT INTO PollutionMonitoring (SpeciesID,Individuals) VALUES (1,100),(2,200),(3,300); CREATE TABLE ConservationEfforts (SpeciesID INT,Individuals INT); INSERT INTO ConservationEfforts (SpeciesID,Individuals) VALUES (2,200),(3,300),(4,400);
SELECT P.SpeciesID FROM PollutionMonitoring P INNER JOIN ConservationEfforts C ON P.SpeciesID = C.SpeciesID WHERE P.Individuals = C.Individuals;
What is the count of unique players for each game in Central America?
CREATE TABLE UniquePlayerGames (player_id INT,game_id INT,region VARCHAR(255)); INSERT INTO UniquePlayerGames (player_id,game_id,region) VALUES (17,9,'Central America'),(18,9,'Central America'),(19,10,'Central America'),(20,10,'Central America'),(21,11,'Central America'),(22,11,'Central America');
SELECT G.game_name, COUNT(DISTINCT UPG.player_id) as unique_player_count FROM UniquePlayerGames UPG JOIN Games G ON UPG.game_id = G.game_id GROUP BY G.game_name;
Delete all records of agricultural innovation projects in India that have a grant amount greater than 20000.
CREATE TABLE agricultural_innovations (id INT,project_name TEXT,sector TEXT,country TEXT,grant_amount DECIMAL(10,2)); INSERT INTO agricultural_innovations (id,project_name,sector,country,grant_amount) VALUES (1,'Precision Agriculture','Agricultural Innovation','India',25000.00),(2,'Sustainable Farming','Agricultural Innovation','India',18000.00),(3,'Agri-Tech Startup','Agricultural Innovation','India',22000.00);
DELETE FROM agricultural_innovations WHERE country = 'India' AND grant_amount > 20000;
What is the average gas production rate in the Marcellus Shale and Haynesville Shale?
CREATE TABLE wells (id INT,region VARCHAR(255),well_type VARCHAR(255),gas_production DECIMAL(5,2)); INSERT INTO wells (id,region,well_type,gas_production) VALUES (1,'Marcellus Shale','Gas',10.0),(2,'Marcellus Shale','Oil',15.0),(3,'Haynesville Shale','Gas',12.0),(4,'Haynesville Shale','Oil',18.0);
SELECT AVG(gas_production) as avg_gas_production FROM wells WHERE region IN ('Marcellus Shale', 'Haynesville Shale') AND well_type = 'Gas';
How many hospitals are there in Texas that have less than 50 beds?
CREATE TABLE hospitals (id INT,name VARCHAR(50),state VARCHAR(25),num_beds INT); INSERT INTO hospitals (id,name,state,num_beds) VALUES (1,'Hospital A','Texas',60),(2,'Hospital B','Texas',30),(3,'Hospital C','California',75);
SELECT COUNT(*) FROM hospitals WHERE state = 'Texas' AND num_beds < 50;
What is the total number of students served by each program?
CREATE TABLE program (id INT,name VARCHAR(255)); INSERT INTO program (id,name) VALUES (1,'Accommodations'),(2,'Support Programs'),(3,'Policy Advocacy'),(4,'Inclusion'); CREATE TABLE student_program (program_id INT,student_id INT);
SELECT p.name, COUNT(sp.student_id) as total_students FROM program p JOIN student_program sp ON p.id = sp.program_id GROUP BY p.name;
What is the total number of construction workers in 'Solar Suburb'?
CREATE TABLE Construction_Workers (worker_id INT,name VARCHAR(30),hours_worked FLOAT,location VARCHAR(20)); INSERT INTO Construction_Workers VALUES (1,'John Doe',150.25,'Solar Suburb'),(2,'Jane Smith',200.50,'Rural County'),(3,'Mike Johnson',300.75,'Solar Suburb'),(4,'Sara Doe',250.50,'Solar Suburb');
SELECT COUNT(DISTINCT worker_id) FROM Construction_Workers WHERE location = 'Solar Suburb';
Add a new column 'manufacturer' to 'vehicle_safety_test_results' table
CREATE TABLE vehicle_safety_test_results (id INT PRIMARY KEY,vehicle_type VARCHAR(255),safety_rating DECIMAL(3,2));
ALTER TABLE vehicle_safety_test_results ADD manufacturer VARCHAR(255);
What is the average cost of military equipment maintenance for Australia and New Zealand?
CREATE TABLE military_equipment_maintenance (id INT,country VARCHAR(50),cost FLOAT); INSERT INTO military_equipment_maintenance (id,country,cost) VALUES (1,'Australia',800000),(2,'Australia',750000),(3,'New Zealand',700000);
SELECT AVG(cost) FROM military_equipment_maintenance WHERE country IN ('Australia', 'New Zealand') GROUP BY country;
What is the minimum transaction amount for each digital asset in the 'crypto_transactions' table, ordered by the minimum transaction amount in ascending order?
CREATE TABLE crypto_transactions (transaction_id INT,digital_asset VARCHAR(20),transaction_amount DECIMAL(10,2),transaction_time DATETIME);
SELECT digital_asset, MIN(transaction_amount) as min_transaction_amount FROM crypto_transactions GROUP BY digital_asset ORDER BY min_transaction_amount;
What is the total installed capacity of hydroelectric power plants in the country of Canada, and what are their names?
CREATE TABLE hydro_power_plants (id INT,name VARCHAR(255),country VARCHAR(255),capacity FLOAT,completion_date DATE);
SELECT name, SUM(capacity) AS total_capacity FROM hydro_power_plants WHERE country = 'Canada' GROUP BY name;
Find the maximum and minimum investment amounts for economic diversification projects.
CREATE TABLE econ_diversification (id INT,project_name VARCHAR(255),investment_amount FLOAT); INSERT INTO econ_diversification (id,project_name,investment_amount) VALUES (1,'Renewable Energy',800000),(2,'Tourism Development',600000);
SELECT MAX(investment_amount) AS max_investment, MIN(investment_amount) AS min_investment FROM econ_diversification;
What is the latest crop health analysis from satellite imagery?
CREATE TABLE satellite_image (image_id INT,analysis_date DATE,crop_health INT); INSERT INTO satellite_image (image_id,analysis_date,crop_health) VALUES (1,'2021-04-01',80),(2,'2021-04-10',85),(3,'2021-04-20',90),(4,'2021-05-01',75),(5,'2021-05-15',88);
SELECT * FROM satellite_image ORDER BY analysis_date DESC LIMIT 1;
Insert a new author 'Charlie' with ID 4, affiliation 'IBM Watson'.
CREATE TABLE authors (author_id INT,name VARCHAR(50),affiliation VARCHAR(100)); INSERT INTO authors (author_id,name,affiliation) VALUES (1,'Alice','University of Oxford'); INSERT INTO authors (author_id,name,affiliation) VALUES (2,'Bob','Google Research');
INSERT INTO authors (author_id, name, affiliation) VALUES (4, 'Charlie', 'IBM Watson');
Delete the record of the most expensive garment sold in the North American market.
CREATE TABLE garment_prices (id INT,garment_type VARCHAR(255),region VARCHAR(255),price INT); INSERT INTO garment_prices (id,garment_type,region,price) VALUES (1,'Dress','North America',200),(2,'Jacket','North America',300),(3,'Skirt','North America',400);
DELETE FROM garment_prices WHERE id = (SELECT id FROM (SELECT ROW_NUMBER() OVER (ORDER BY price DESC) as row_num, id FROM garment_prices WHERE region = 'North America') t WHERE t.row_num = 1);
List the names of all regulatory frameworks in the database.
CREATE TABLE regulatory_frameworks (framework_id serial,framework_name varchar(20)); INSERT INTO regulatory_frameworks (framework_id,framework_name) VALUES (1,'GDPR'),(2,'HIPAA'),(3,'PCI-DSS');
SELECT framework_name FROM regulatory_frameworks;
What is the total cost of accommodations for students with hearing impairments in April?
CREATE TABLE Accommodations (student_id INT,accommodation_type VARCHAR(255),cost FLOAT,month INT);
SELECT SUM(cost) FROM Accommodations WHERE accommodation_type = 'Hearing Impairment' AND month = 4;
Find the total weight of chemicals produced by each manufacturer, partitioned by year and ordered from most to least weight in 2024
CREATE TABLE multi_annual_chemicals (manufacturer_id INT,manufacturer_name VARCHAR(50),year INT,weight FLOAT); INSERT INTO multi_annual_chemicals (manufacturer_id,manufacturer_name,year,weight) VALUES (1,'AusChem',2023,800.5),(2,'British Biotech',2023,900.3),(3,'ChemCorp',2023,700.7),(4,'Global Green Chemicals',2023,600.5),(5,'EuroChem',2023,500.9),(1,'AusChem',2024,900.7),(2,'British Biotech',2024,850.4),(3,'ChemCorp',2024,750.6),(4,'Global Green Chemicals',2024,650.8),(5,'EuroChem',2024,550.2);
SELECT manufacturer_id, manufacturer_name, SUM(weight) OVER (PARTITION BY manufacturer_id ORDER BY year DESC) as total_weight FROM multi_annual_chemicals WHERE year IN (2023, 2024) ORDER BY total_weight DESC;
Identify the top 2 countries with the highest number of climate mitigation projects in South Asia.
CREATE TABLE climate_mitigation_south_asia (country VARCHAR(50),project VARCHAR(50)); INSERT INTO climate_mitigation_south_asia (country,project) VALUES ('India','Solar Energy Project'),('Bangladesh','Energy Efficiency Project'),('Pakistan','Wind Energy Project'),('Sri Lanka','Hydropower Project');
SELECT country, COUNT(project) AS project_count FROM climate_mitigation_south_asia WHERE country IN ('India', 'Bangladesh', 'Pakistan', 'Sri Lanka', 'Nepal') GROUP BY country ORDER BY project_count DESC LIMIT 2;
What is the minimum rating of French news articles published in 2016?
CREATE TABLE news_articles (id INT,title TEXT,country TEXT,year INT,rating FLOAT); INSERT INTO news_articles (id,title,country,year,rating) VALUES (1,'ArticleA','France',2016,7.2),(2,'ArticleB','France',2017,8.5),(3,'ArticleC','USA',2018,9.1);
SELECT MIN(rating) FROM news_articles WHERE country = 'France' AND year = 2016;
What are the demographics of patients who received mental health treatment in Canada?
CREATE TABLE patients (id INT PRIMARY KEY,age INT,gender VARCHAR(50),country VARCHAR(50));
SELECT age, gender FROM patients WHERE country = 'Canada' AND id IN (SELECT patient_id FROM prescriptions);
Insert new basketball player records into the basketball_players table
CREATE TABLE basketball_players (player_id INT,name VARCHAR(50),position VARCHAR(50),height FLOAT,weight INT,team_id INT);
INSERT INTO basketball_players (player_id, name, position, height, weight, team_id) VALUES (1, 'Alex Thompson', 'Guard', 1.85, 82, 101), (2, 'Jasmine Davis', 'Forward', 1.93, 78, 202), (3, 'Michael Chen', 'Center', 2.08, 105, 303);
List aircraft models along with the number of flight hours they have accumulated, ranked in descending order per manufacturer.
CREATE TABLE AircraftModels (ModelID INT,Model VARCHAR(50),Manufacturer VARCHAR(50),FlightHours INT); INSERT INTO AircraftModels (ModelID,Model,Manufacturer,FlightHours) VALUES (1,'787','Boeing',2500000); INSERT INTO AircraftModels (ModelID,Model,Manufacturer,FlightHours) VALUES (2,'A350','Airbus',3000000); INSERT INTO AircraftModels (ModelID,Model,Manufacturer,FlightHours) VALUES (3,'CRJ','Bombardier',1000000); INSERT INTO AircraftModels (ModelID,Model,Manufacturer,FlightHours) VALUES (4,'737','Boeing',4000000);
SELECT Model, Manufacturer, SUM(FlightHours) AS Total_Flight_Hours, RANK() OVER (PARTITION BY Manufacturer ORDER BY SUM(FlightHours) DESC) AS Flight_Hour_Rank FROM AircraftModels GROUP BY Model, Manufacturer;
List the unique 'cultural_background' values from the 'community_health_workers' table.
CREATE TABLE community_health_workers (id INT,name VARCHAR(50),cultural_background VARCHAR(50)); INSERT INTO community_health_workers (id,name,cultural_background) VALUES (1,'Ana Garcia','Hispanic'); INSERT INTO community_health_workers (id,name,cultural_background) VALUES (2,'Hiroshi Tanaka','Japanese');
SELECT DISTINCT cultural_background FROM community_health_workers;
What is the total number of students enrolled in each course, and what is the average age of students in each course?
CREATE TABLE courses (course_id INT,course_name VARCHAR(50),instructor_id INT); INSERT INTO courses (course_id,course_name,instructor_id) VALUES (1,'Introduction to Computer Science',1),(2,'Data Structures and Algorithms',1),(3,'Calculus I',2),(4,'Calculus II',2); CREATE TABLE students_courses (student_id INT,course_id INT,student_age INT); INSERT INTO students_courses (student_id,course_id,student_age) VALUES (1,1,20),(2,1,19),(3,2,22),(4,2,21),(5,3,23),(6,3,22),(7,4,21),(8,4,20);
SELECT c.course_name, COUNT(sc.student_id) as total_enrolled, AVG(sc.student_age) as avg_student_age FROM courses c JOIN students_courses sc ON c.course_id = sc.course_id GROUP BY c.course_name;
How many wells were drilled in 'Brazil' before 2016
CREATE TABLE drilled_wells (well_id INT,well_name VARCHAR(50),country VARCHAR(50),drill_year INT); INSERT INTO drilled_wells (well_id,well_name,country,drill_year) VALUES (1,'Well1','Brazil',2016),(2,'Well2','Brazil',2015),(3,'Well3','USA',2017);
SELECT COUNT(*) FROM drilled_wells WHERE country = 'Brazil' AND drill_year < 2016;
Update the donation amount for donor 1 on 2021-01-01 to 600.
CREATE TABLE Donations (donor_id INT,donation_amount DECIMAL(10,2),donation_date DATE); INSERT INTO Donations (donor_id,donation_amount,donation_date) VALUES (1,500,'2021-01-01'),(2,300,'2021-03-15'),(1,700,'2021-04-01');
UPDATE Donations SET donation_amount = 600 WHERE donor_id = 1 AND donation_date = '2021-01-01';
How many mobile customers signed up in Oceania each year?
CREATE TABLE subscribers (id INT,name VARCHAR(50),type VARCHAR(20),data_usage FLOAT,subscription_date DATE); INSERT INTO subscribers (id,name,type,data_usage,subscription_date) VALUES (5,'Jackie Liu','Mobile',3.2,'2021-02-20'); CREATE TABLE regions (id INT,name VARCHAR(50),continent VARCHAR(50)); INSERT INTO regions (id,name,continent) VALUES (5,'Oceania','Oceania'); CREATE TABLE subscriber_regions (subscriber_id INT,region_id INT); INSERT INTO subscriber_regions (subscriber_id,region_id) VALUES (5,5);
SELECT YEAR(subscription_date) AS year, COUNT(*) AS count FROM subscribers s INNER JOIN subscriber_regions sr ON s.id = sr.subscriber_id INNER JOIN regions r ON sr.region_id = r.id WHERE s.type = 'Mobile' AND r.continent = 'Oceania' GROUP BY year;
List all the bridges along with their construction dates from the 'bridge_info' and 'construction_dates' tables.
CREATE TABLE bridge_info (bridge_id INT,bridge_name VARCHAR(50)); CREATE TABLE construction_dates (bridge_id INT,construction_year INT); INSERT INTO bridge_info (bridge_id,bridge_name) VALUES (1,'Brooklyn Bridge'),(2,'Golden Gate Bridge'),(3,'Tacoma Narrows Bridge'); INSERT INTO construction_dates (bridge_id,construction_year) VALUES (1,1883),(2,1937),(3,1940);
SELECT bridge_info.bridge_name, construction_dates.construction_year FROM bridge_info INNER JOIN construction_dates ON bridge_info.bridge_id = construction_dates.bridge_id;
What is the total number of military equipment serviced by defense contractors based in Texas?
CREATE TABLE military_equipment (id INT,name VARCHAR(50),company VARCHAR(50),service_frequency INT,company_location VARCHAR(50)); INSERT INTO military_equipment (id,name,company,service_frequency,company_location) VALUES (1,'M1 Abrams','XYZ',12,'Texas'); INSERT INTO military_equipment (id,name,company,service_frequency,company_location) VALUES (2,'F-35','ABC',24,'New York');
SELECT SUM(service_frequency) FROM military_equipment WHERE company_location = 'Texas';
List all brands that have at least one product with a certain certification
CREATE TABLE brands (id INT,name VARCHAR(255)); CREATE TABLE products (id INT,brand_id INT,certification VARCHAR(255));
SELECT b.name FROM brands b INNER JOIN products p ON b.id = p.brand_id WHERE p.certification = 'certification' GROUP BY b.name HAVING COUNT(*) > 0;
What is the average age of athletes in the FINA World Championships?
CREATE TABLE fina_athletes (athlete_id INT,athlete_name VARCHAR(50),birthdate DATE,gender VARCHAR(50));
SELECT AVG(DATEDIFF('2022-07-15', birthdate)/365.25) AS avg_age FROM fina_athletes;
List the wells with the highest production volume in each country
CREATE TABLE wells (well_id INT,well_name VARCHAR(50),production_volume FLOAT,country VARCHAR(50)); INSERT INTO wells VALUES (1,'Well A',1000,'Brazil'); INSERT INTO wells VALUES (2,'Well B',1500,'Norway'); INSERT INTO wells VALUES (3,'Well C',1200,'Brazil'); INSERT INTO wells VALUES (4,'Well D',800,'Nigeria'); INSERT INTO wells VALUES (5,'Well E',1800,'Norway');
SELECT country, MAX(production_volume) FROM wells GROUP BY country;
What is the total transaction volume for each regulatory status per day?
CREATE TABLE daily_transaction_volume (regulatory_status VARCHAR(255),transaction_volume INT,date DATE); INSERT INTO daily_transaction_volume (regulatory_status,transaction_volume,date) VALUES ('Regulated',50000,'2022-01-01'),('Partially Regulated',40000,'2022-01-01'),('Unregulated',30000,'2022-01-01'),('Regulated',60000,'2022-01-02'),('Partially Regulated',50000,'2022-01-02'),('Unregulated',40000,'2022-01-02');
SELECT regulatory_status, date, SUM(transaction_volume) OVER (PARTITION BY regulatory_status, date) FROM daily_transaction_volume;
What is the CO2 emission of each production country?
CREATE TABLE factories (id INT,name VARCHAR(100),country VARCHAR(50),co2_emission INT);
SELECT factories.country, SUM(factories.co2_emission) AS co2_emission FROM factories GROUP BY factories.country;
What are the total sales figures for 'DrugA' and 'DrugB'?
CREATE TABLE sales(drug varchar(10),revenue int); INSERT INTO sales(drug,revenue) VALUES('DrugA',5000),('DrugB',6000);
SELECT SUM(revenue) FROM sales WHERE drug IN ('DrugA', 'DrugB')
What is the average income in Texas for households with more than two members?
CREATE TABLE states (id INT,name VARCHAR(255)); INSERT INTO states (id,name) VALUES (1,'Texas'); CREATE TABLE households (id INT,state_id INT,income FLOAT,members INT); INSERT INTO households (id,state_id,income,members) VALUES (1,1,75000,3),(2,1,100000,2),(3,1,60000,4),(4,1,90000,3);
SELECT AVG(households.income) AS avg_income FROM households INNER JOIN states ON households.state_id = states.id WHERE states.name = 'Texas' AND households.members > 2;
List the unique journalist names and their respective total article counts from the "news_articles" table, excluding any articles published before 2015.
CREATE TABLE news_articles (article_id INT,journalist VARCHAR(255),publish_date DATE);
SELECT journalist, COUNT(*) AS article_count FROM news_articles WHERE publish_date >= '2015-01-01' GROUP BY journalist;
What is the average salary of employees who identify as veterans?
CREATE TABLE Employees (EmployeeID INT,Veteran VARCHAR(10),Salary DECIMAL(10,2)); INSERT INTO Employees (EmployeeID,Veteran,Salary) VALUES (5,'Yes',85000.00);
SELECT AVG(Salary) FROM Employees WHERE Veteran = 'Yes';
Find all products that are not present in the ethical products report but are in the inventory.
CREATE TABLE ethical_products_report (product_id INT,product_name VARCHAR(50),price DECIMAL,ethical BOOLEAN); CREATE TABLE inventory (product_id INT,in_stock INT); INSERT INTO ethical_products_report (product_id,product_name,price,ethical) VALUES (1,'Product A',15.99,true),(2,'Product B',25.49,false),(3,'Product C',12.99,true); INSERT INTO inventory (product_id,in_stock) VALUES (1,50),(3,100),(6,75);
SELECT i.product_id, e.product_name, i.in_stock FROM inventory i LEFT JOIN ethical_products_report e ON i.product_id = e.product_id WHERE e.product_id IS NULL;
Count the number of mitigation projects between 2018 and 2020 inclusive that have received funding from both the public and private sectors, and show the total budget for these projects.
CREATE TABLE climate_mitigation_funding (year INT,project VARCHAR(20),sector VARCHAR(10),budget FLOAT); INSERT INTO climate_mitigation_funding (year,project,sector,budget) VALUES (2018,'Project1','Public',7000000),(2018,'Project1','Private',3000000),(2019,'Project2','Public',8000000),(2019,'Project2','Private',2000000),(2020,'Project3','Public',9000000),(2020,'Project3','Private',1000000);
SELECT COUNT(DISTINCT project) AS num_projects, SUM(budget) AS total_budget FROM climate_mitigation_funding WHERE year BETWEEN 2018 AND 2020 AND sector IN ('Public', 'Private') GROUP BY project HAVING COUNT(DISTINCT sector) = 2;
How many unique donors made donations in each state?
CREATE TABLE Donors (id INT,donor_name TEXT,state TEXT); INSERT INTO Donors (id,donor_name,state) VALUES (1,'Sophia','CA'),(2,'Ethan','TX');
SELECT state, COUNT(DISTINCT donor_name) FROM Donors GROUP BY state;
What is the total number of volunteers for an organization, including those who have not provided their email address?
CREATE TABLE organization (org_id INT,org_name TEXT); INSERT INTO organization (org_id,org_name) VALUES (1,'Volunteers Inc'); INSERT INTO organization (org_id,org_name) VALUES (2,'Helping Hands'); CREATE TABLE volunteer (vol_id INT,vol_name TEXT,org_id INT,vol_email TEXT); INSERT INTO volunteer (vol_id,vol_name,org_id,vol_email) VALUES (1,'Alice',1,'alice@example.com'); INSERT INTO volunteer (vol_id,vol_name,org_id,vol_email) VALUES (2,'Bob',1,NULL); INSERT INTO volunteer (vol_id,vol_name,org_id,vol_email) VALUES (3,'Charlie',2,'charlie@example.com');
SELECT org_id, COUNT(*) as total_volunteers FROM volunteer GROUP BY org_id;
Show the number of mobile subscribers and broadband subscribers in each region.
CREATE TABLE regions (region_id INT PRIMARY KEY,region_name VARCHAR(255)); INSERT INTO regions (region_id,region_name) VALUES (1,'East'),(2,'West'),(3,'Central'),(4,'North'),(5,'South'); CREATE TABLE mobile_subscribers (subscriber_id INT PRIMARY KEY,region_id INT); INSERT INTO mobile_subscribers (subscriber_id,region_id) VALUES (1,1),(2,2),(3,3),(4,4),(5,5); CREATE TABLE broadband_subscribers (subscriber_id INT PRIMARY KEY,region_id INT); INSERT INTO broadband_subscribers (subscriber_id,region_id) VALUES (1,1),(2,2),(3,3),(4,4),(6,5);
SELECT r.region_name, COUNT(m.subscriber_id) as mobile_subscribers, COUNT(b.subscriber_id) as broadband_subscribers 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 GROUP BY r.region_name;
What is the total number of affordable housing units in Miami and Austin?
CREATE TABLE city_housing (city VARCHAR(20),type VARCHAR(20),units INT); INSERT INTO city_housing (city,type,units) VALUES ('Miami','Affordable',1000); INSERT INTO city_housing (city,type,units) VALUES ('Austin','Affordable',1200);
SELECT SUM(units) FROM city_housing WHERE city IN ('Miami', 'Austin') AND type = 'Affordable';
List the investment strategies that prioritize gender equality for organizations with a risk assessment below 50.
CREATE TABLE investment_strategies (strategy_id INT,organization_id INT,strategy_name VARCHAR(100),focus_area VARCHAR(50)); CREATE TABLE risk_assessment (organization_id INT,risk_score INT); INSERT INTO investment_strategies (strategy_id,organization_id,strategy_name,focus_area) VALUES (1,1,'Impact Bonds','Gender Equality'),(2,2,'Green Energy','Renewable Energy'),(3,3,'Social Housing','Affordable Housing'); INSERT INTO risk_assessment (organization_id,risk_score) VALUES (1,45),(2,60),(3,35),(4,45);
SELECT i.strategy_name FROM investment_strategies i INNER JOIN risk_assessment r ON i.organization_id = r.organization_id WHERE r.risk_score < 50 AND i.focus_area = 'Gender Equality';
How many fans attended baseball games in the Midwest division last season?
CREATE TABLE games (game_id INT,team TEXT,fans INT,division TEXT); INSERT INTO games (game_id,team,fans,division) VALUES (1,'Chicago Cubs',35000,'Central'),(2,'St. Louis Cardinals',40000,'Central');
SELECT SUM(fans) FROM games WHERE division = 'Central';
List all movies and their genres that have been released on streaming services, ordered by the production budget in descending order.
CREATE TABLE movies (movie_id INT,title TEXT,genre TEXT,budget INT,platform TEXT); INSERT INTO movies (movie_id,title,genre,budget,platform) VALUES (1,'Movie 4','Comedy',2000000,'Netflix'),(2,'Movie 5','Drama',1500000,'Hulu'),(3,'Movie 6','Action',2500000,'Amazon Prime');
SELECT movies.title, movies.genre, movies.budget FROM movies ORDER BY movies.budget DESC;
What is the total number of vulnerabilities detected in the energy sector this year, grouped by month?
CREATE TABLE vulnerabilities_by_month (id INT,sector VARCHAR(255),detection_date DATE,severity FLOAT); INSERT INTO vulnerabilities_by_month (id,sector,detection_date,severity) VALUES (1,'energy','2021-01-01',5.5);
SELECT MONTH(detection_date), COUNT(*) FROM vulnerabilities_by_month WHERE sector = 'energy' AND YEAR(detection_date) = YEAR(CURDATE()) GROUP BY MONTH(detection_date);
What is the market share of electric vehicles in the 'vehicle_sales' table by quarter?
CREATE TABLE schema.vehicle_sales (vehicle_id INT,vehicle_type VARCHAR(50),sale_date DATE,quantity INT); INSERT INTO schema.vehicle_sales (vehicle_id,vehicle_type,sale_date,quantity) VALUES (1,'hybrid','2021-01-01',200),(2,'electric','2021-01-01',300),(3,'fossil_fuel','2021-01-01',400),(4,'hybrid','2021-04-01',250),(5,'electric','2021-04-01',350),(6,'fossil_fuel','2021-04-01',450),(7,'hybrid','2021-07-01',300),(8,'electric','2021-07-01',400),(9,'fossil_fuel','2021-07-01',500),(10,'hybrid','2021-10-01',350),(11,'electric','2021-10-01',450),(12,'fossil_fuel','2021-10-01',550);
SELECT EXTRACT(QUARTER FROM sale_date) AS quarter, (SUM(CASE WHEN vehicle_type = 'electric' THEN quantity ELSE 0 END)::DECIMAL / SUM(quantity)) * 100 AS market_share FROM schema.vehicle_sales GROUP BY quarter;
What is the average length of fishing vessels in the South Atlantic and Caribbean Seas?
CREATE TABLE fishing_vessels (id INT,name VARCHAR(255),sea VARCHAR(255),length FLOAT); INSERT INTO fishing_vessels (id,name,sea,length) VALUES (1,'Vessel A','South Atlantic',50.5); INSERT INTO fishing_vessels (id,name,sea,length) VALUES (2,'Vessel B','Caribbean Sea',60.3); INSERT INTO fishing_vessels (id,name,sea,length) VALUES (3,'Vessel C','South Atlantic',70.2);
SELECT AVG(length) FROM fishing_vessels WHERE sea IN ('South Atlantic', 'Caribbean Sea');
What is the average salary of male and female employees in the Marketing department?
CREATE TABLE Employees (EmployeeID INT,Name VARCHAR(50),Department VARCHAR(50),Position VARCHAR(50),Salary FLOAT,Gender VARCHAR(10)); INSERT INTO Employees (EmployeeID,Name,Department,Position,Salary,Gender) VALUES (1,'John Doe','IT','Developer',75000.00,'Male'),(2,'Jane Smith','IT','Developer',80000.00,'Female'),(3,'Alice Johnson','Marketing','Marketing Specialist',60000.00,'Female'),(4,'Bob Brown','HR','HR Specialist',65000.00,'Male');
SELECT Department, Gender, AVG(Salary) FROM Employees WHERE Department = 'Marketing' GROUP BY Department, Gender;
What is the average CO2 emissions of products manufactured in the USA?
CREATE TABLE products (product_id INT,product_name VARCHAR(50),co2_emissions FLOAT,country VARCHAR(50)); INSERT INTO products (product_id,product_name,co2_emissions,country) VALUES (1,'Laptop',250,'USA'),(2,'Smartphone',80,'China'),(3,'Table',150,'USA');
SELECT AVG(co2_emissions) FROM products WHERE country = 'USA';
What is the average rating of games designed by female developers from the USA?
CREATE TABLE games (id INT,game_name VARCHAR(255),genre VARCHAR(255),rating INT,developer_id INT,developer_gender VARCHAR(255),developer_location VARCHAR(255)); INSERT INTO games (id,game_name,genre,rating,developer_id,developer_gender,developer_location) VALUES;
SELECT AVG(rating) FROM games WHERE developer_gender = 'Female' AND developer_location = 'USA'
What was the average monthly production of Neodymium in 2020?
CREATE TABLE production (year INT,element VARCHAR(10),month INT,quantity INT); INSERT INTO production (year,element,month,quantity) VALUES (2020,'Neodymium',1,1200); INSERT INTO production (year,element,month,quantity) VALUES (2020,'Neodymium',2,1400);
SELECT AVG(quantity) FROM production WHERE year = 2020 AND element = 'Neodymium';
What is the total CO2 emissions and average pollution index for the Indigo Igloo mine for each year?
CREATE TABLE environmental_impact (year INT,mine_name TEXT,pollution_index INT,co2_emissions INT); INSERT INTO environmental_impact (year,mine_name,pollution_index,co2_emissions) VALUES (2015,'Aggromine A',28,1200),(2016,'Borax Bravo',34,2100),(2017,'Carbon Cat',30,1500),(2018,'Diamond Delta',22,800),(2018,'Diamond Delta',25,900),(2019,'Indigo Igloo',18,1100),(2019,'Indigo Igloo',19,1200),(2019,'Indigo Igloo',20,1300);
SELECT year, mine_name, AVG(pollution_index) as avg_pollution, SUM(co2_emissions) as total_co2_emissions FROM environmental_impact WHERE mine_name = 'Indigo Igloo' GROUP BY year;
Identify users who have posted content related to 'climate change' in the last week, and the number of likes and shares for each post.
CREATE TABLE users (user_id INT,username VARCHAR(255)); CREATE TABLE posts (post_id INT,user_id INT,content TEXT,post_date DATE); CREATE TABLE post_likes (post_id INT,likes INT); CREATE TABLE post_shares (post_id INT,shares INT);
SELECT u.username, p.post_id, p.content, p.post_date, SUM(pl.likes) as total_likes, SUM(ps.shares) as total_shares FROM users u INNER JOIN posts p ON u.user_id = p.user_id INNER JOIN post_likes pl ON p.post_id = pl.post_id INNER JOIN post_shares ps ON p.post_id = ps.post_id WHERE p.content LIKE '%climate change%' AND p.post_date >= DATE_SUB(CURDATE(), INTERVAL 1 WEEK) GROUP BY p.post_id;
What is the average horsepower of vehicles manufactured in Japan with a manual transmission?
CREATE TABLE Vehicle (id INT,make VARCHAR(255),model VARCHAR(255),horsepower INT,transmission VARCHAR(255),country VARCHAR(255)); INSERT INTO Vehicle (id,make,model,horsepower,transmission,country) VALUES (1,'Toyota','Corolla',130,'Manual','Japan');
SELECT AVG(horsepower) FROM Vehicle WHERE country = 'Japan' AND transmission = 'Manual';
What is the total number of components produced by each manufacturer, ranked by the highest total?
CREATE TABLE Manufacturers (ManufacturerID int,Name varchar(50),ComponentsProduced int); INSERT INTO Manufacturers (ManufacturerID,Name,ComponentsProduced) VALUES (1,'ABC Manufacturing',1500),(2,'XYZ Manufacturing',2000),(3,'LMN Manufacturing',1200),(4,'OPQ Manufacturing',1800);
SELECT Name, SUM(ComponentsProduced) as TotalComponents FROM Manufacturers GROUP BY Name ORDER BY TotalComponents DESC;
Who is the driver with the most total fares collected?
CREATE TABLE drivers (driver_id varchar(255),driver_name varchar(255),total_fares decimal(10,2)); INSERT INTO drivers (driver_id,driver_name,total_fares) VALUES ('D1','Siti Binti',5000.00),('D2','Ram Mohan',6000.00),('D3','Park Soo-Jin',7000.00),('D4','Juan Rodriguez',8000.00);
SELECT driver_name, total_fares FROM drivers ORDER BY total_fares DESC LIMIT 1;
Find the combined biomass of all farmed species in Chile.
CREATE TABLE FarmI (country VARCHAR(20),species VARCHAR(20),biomass FLOAT); INSERT INTO FarmI (country,species,biomass) VALUES ('Chile','Salmon',300000); INSERT INTO FarmI (country,species,biomass) VALUES ('Chile','Cod',150000); INSERT INTO FarmI (country,species,biomass) VALUES ('Chile','Tilapia',100000);
SELECT SUM(biomass) FROM FarmI WHERE country='Chile';
Find the maximum transaction amount for each investment strategy in the "InvestmentStrategies" table.
CREATE TABLE InvestmentStrategies (InvestmentStrategyID INT,CustomerID INT,TransactionDate DATE,TransactionAmount DECIMAL(10,2));
SELECT InvestmentStrategyID, MAX(TransactionAmount) as MaxTransactionAmount FROM InvestmentStrategies GROUP BY InvestmentStrategyID;
What is the average safety violation cost per chemical plant in India?
CREATE TABLE chemical_plants (plant_id INT,plant_name VARCHAR(50),country VARCHAR(50),safety_violation_cost DECIMAL(10,2)); INSERT INTO chemical_plants (plant_id,plant_name,country,safety_violation_cost) VALUES (1,'Plant A','India',5000),(2,'Plant B','India',7000),(3,'Plant C','USA',3000);
SELECT AVG(safety_violation_cost) FROM chemical_plants WHERE country = 'India';
List all destinations visited by Australian tourists with a high safety score?
CREATE TABLE Destinations (id INT,destination_name VARCHAR(50),safety_score INT); CREATE TABLE Tourists_Destinations (tourist_id INT,destination_id INT); INSERT INTO Destinations VALUES (1,'Sydney',90); INSERT INTO Destinations VALUES (2,'Melbourne',85); INSERT INTO Tourists_Destinations VALUES (1,1); INSERT INTO Tourists_Destinations VALUES (1,2);
SELECT Destinations.destination_name FROM Destinations INNER JOIN Tourists_Destinations ON Destinations.id = Tourists_Destinations.destination_id WHERE Tourists_Destinations.tourist_id IN (SELECT id FROM Tourists WHERE nationality = 'Australia') AND Destinations.safety_score >= 80;
How many policies were issued in 'Q3 2022' to policyholders residing in urban areas?
CREATE TABLE policies (id INT,policyholder_id INT,issue_date DATE); INSERT INTO policies (id,policyholder_id,issue_date) VALUES (1,1,'2022-07-15'); CREATE TABLE policyholders (id INT,address TEXT,dob DATE); INSERT INTO policyholders (id,address,dob) VALUES (1,'123 Main St,New York,NY 10001','1985-08-22'); CREATE TABLE zipcodes (zipcode INT,city TEXT,area_type TEXT); INSERT INTO zipcodes (zipcode,city,area_type) VALUES (10001,'New York','Urban');
SELECT COUNT(policies.id) FROM policies JOIN policyholders ON policies.policyholder_id = policyholders.id JOIN zipcodes ON SUBSTRING(policyholders.address FROM 14 FOR 5) = zipcodes.zipcode WHERE policies.issue_date BETWEEN '2022-07-01' AND '2022-09-30' AND zipcodes.area_type = 'Urban';
What is the maximum 'emissions reduction' achieved by 'Canada' in a single 'year' from the 'reduction' table?
CREATE TABLE reduction (country VARCHAR(255),reduction INT,year INT);
SELECT MAX(reduction) FROM reduction WHERE country = 'Canada';
What is the total spending of international visitors in New Zealand in 2020?
CREATE TABLE Country (CountryID INT,CountryName VARCHAR(100),Continent VARCHAR(50)); INSERT INTO Country (CountryID,CountryName,Continent) VALUES (1,'New Zealand','Australia'); CREATE TABLE InternationalVisitors (VisitorID INT,CountryID INT,Year INT,Spending DECIMAL(10,2)); INSERT INTO InternationalVisitors (VisitorID,CountryID,Year,Spending) VALUES (1,1,2020,3500.00),(2,1,2020,4000.00);
SELECT SUM(Spending) FROM InternationalVisitors WHERE CountryID = 1 AND Year = 2020;
What is the total donation amount by each donor's country?
CREATE TABLE Donors (DonorID INT,DonorName TEXT,DonationAmount DECIMAL,Country TEXT); INSERT INTO Donors (DonorID,DonorName,DonationAmount,Country) VALUES (1,'John Doe',500.00,'USA'),(2,'Jane Smith',350.00,'Canada'),(3,'Alice Johnson',700.00,'USA');
SELECT Country, SUM(DonationAmount) as TotalDonation FROM Donors GROUP BY Country;
What is the average temperature for each station in the 'ClimateData' table with at least two years of data?
CREATE TABLE ClimateData (station_id INT,year INT,temperature FLOAT); INSERT INTO ClimateData (station_id,year,temperature) VALUES (1,2000,-10.5); INSERT INTO ClimateData (station_id,year,temperature) VALUES (1,2001,-11.0); INSERT INTO ClimateData (station_id,year,temperature) VALUES (2,2005,-15.0);
SELECT station_id, AVG(temperature) FROM ClimateData GROUP BY station_id HAVING COUNT(year) > 1;
Count the number of companies founded by underrepresented minorities in the healthcare sector
CREATE TABLE companies (company_id INT,company_name VARCHAR(50),industry VARCHAR(50),founder_minority VARCHAR(20)); INSERT INTO companies VALUES (1,'Epsilon Inc','Healthcare','African American'); INSERT INTO companies VALUES (2,'Zeta Corp','Education','Latinx');
SELECT COUNT(*) FROM companies WHERE industry = 'Healthcare' AND founder_minority IS NOT NULL;
Show transactions that were made on a weekend.
CREATE TABLE transactions (id INT,transaction_date DATE); INSERT INTO transactions (id,transaction_date) VALUES (1,'2022-01-01'),(2,'2022-01-08'),(3,'2022-01-15'),(4,'2022-01-22'),(5,'2022-01-29');
SELECT * FROM transactions WHERE DAYOFWEEK(transaction_date) IN (1, 7);
Determine the number of unique customers by location.
CREATE TABLE orders (id INT,customer_id INT,location TEXT); INSERT INTO orders (id,customer_id,location) VALUES (1,1001,'San Francisco'),(2,1002,'New York'),(3,1003,'Chicago'),(4,1001,'Los Angeles'),(5,1004,'Austin'),(6,1005,'Seattle'),(7,1002,'Miami'),(8,1001,'Boston');
SELECT location, COUNT(DISTINCT customer_id) FROM orders GROUP BY location;
Find the total number of visitors that attended exhibitions in Berlin and have a membership.
CREATE TABLE Members (id INT,membership BOOLEAN,city VARCHAR(50)); INSERT INTO Members (id,membership,city) VALUES (1,TRUE,'Berlin'); CREATE TABLE Exhibitions (id INT,city VARCHAR(50),visitors INT); INSERT INTO Exhibitions (id,city,visitors) VALUES (1,'Berlin',3500);
SELECT SUM(Exhibitions.visitors) FROM Exhibitions INNER JOIN Members ON Exhibitions.city = Members.city WHERE Members.city = 'Berlin' AND Members.membership = TRUE;
Update user email
CREATE TABLE user_details (id INT PRIMARY KEY,user_id INT,phone VARCHAR(20),address VARCHAR(100));
UPDATE users u SET email = 'bob@example.com' FROM user_details ud WHERE u.id = ud.user_id AND ud.phone = '123-456-7890';
What is the average carbon sequestered by trees in the forest?
CREATE TABLE trees (id INT,carbon_sequestered DECIMAL(10,2));
SELECT AVG(carbon_sequestered) as avg_carbon_sequestered FROM trees;
Show the total number of military personnel by country in Europe and the number of cybersecurity incidents affecting those countries since 2019.
CREATE TABLE military_personnel (id INT PRIMARY KEY,country VARCHAR(255),num_personnel INT); CREATE TABLE cybersecurity_incidents (id INT PRIMARY KEY,incident_name VARCHAR(255),location VARCHAR(255),date DATE); INSERT INTO military_personnel (id,country,num_personnel) VALUES (1,'France',200000); INSERT INTO cybersecurity_incidents (id,incident_name,location,date) VALUES (1,'Ransomware Attack','Germany','2019-06-15');
SELECT m.country, m.num_personnel, COUNT(c.id) as incidents_since_2019 FROM military_personnel m LEFT JOIN cybersecurity_incidents c ON m.country = c.location AND c.date >= '2019-01-01' WHERE m.country LIKE '%Europe%' GROUP BY m.country;
What is the demographic distribution of users who engaged with opinion pieces?
CREATE TABLE user_demographics (user_id text,age integer,gender text,engagement text); INSERT INTO user_demographics (user_id,age,gender,engagement) VALUES ('User 1',35,'Male','opinion piece'); INSERT INTO user_demographics (user_id,age,gender,engagement) VALUES ('User 2',27,'Female','opinion piece');
SELECT gender, age, COUNT(*) as count FROM user_demographics WHERE engagement = 'opinion piece' GROUP BY gender, age;
What is the percentage of transactions that were made using a credit card in Q1 2022?
CREATE TABLE transactions (transaction_id INT,customer_id INT,transaction_amount DECIMAL(10,2),transaction_date DATE,payment_method VARCHAR(50));
SELECT 100.0 * SUM(CASE WHEN payment_method = 'credit card' THEN 1 ELSE 0 END) / COUNT(*) FROM transactions WHERE transactions.transaction_date BETWEEN '2022-01-01' AND '2022-03-31';
How many astronauts were born in the state of Texas?
CREATE TABLE astronauts (id INT,name VARCHAR(255),birth_date DATE,state VARCHAR(255)); INSERT INTO astronauts (id,name,birth_date,state) VALUES (1,'Nicole Aunapu Mann','1977-06-24','Texas');
SELECT COUNT(*) FROM astronauts WHERE state = 'Texas';
What are the top 5 most recent vulnerabilities?
CREATE TABLE schema1.vulnerabilities (id INT,name VARCHAR(255),severity VARCHAR(50),description TEXT,date_discovered DATE,last_observed DATE); INSERT INTO schema1.vulnerabilities (id,name,severity,description,date_discovered,last_observed) VALUES (1,'SQL Injection','Critical','Allows unauthorized access','2021-01-01','2021-02-01'),(2,'XSS','High','Allows unauthorized access','2021-01-10','2021-02-10');
SELECT * FROM schema1.vulnerabilities ORDER BY date_discovered DESC LIMIT 5;
Calculate the average budget allocated to each department in the current fiscal year
CREATE TABLE Budget (BudgetID INT,Department TEXT,Amount DECIMAL(10,2),FiscalYear INT); INSERT INTO Budget (BudgetID,Department,Amount,FiscalYear) VALUES (1,'Police',5000000,2023),(2,'Education',7000000,2023),(3,'Health',8000000,2023);
SELECT Department, AVG(Amount) FROM Budget WHERE FiscalYear = YEAR(GETDATE()) GROUP BY Department;
What is the average price of sustainable products?
CREATE TABLE Food (FoodID varchar(10),FoodName varchar(20),Sustainable bit,Price decimal(5,2)); INSERT INTO Food VALUES ('A','Product A',1,2.50),('B','Product B',0,3.00),('C','Product C',1,2.00);
SELECT AVG(Price) FROM Food WHERE Sustainable = 1;
List the number of unique achievements earned by players on '2022-01-02' in 'player_achievements' table
CREATE TABLE player_achievements (player_id INT,achievement_name VARCHAR(255),date_earned DATE);
SELECT COUNT(DISTINCT achievement_name) FROM player_achievements WHERE date_earned = '2022-01-02';
What is the percentage of haircare products that are sulfate-free in the Western region?
CREATE TABLE haircare_products(product VARCHAR(255),region VARCHAR(255),sulfate_free BOOLEAN); INSERT INTO haircare_products(product,region,sulfate_free) VALUES('Product I','Western',true),('Product J','Western',false),('Product K','Western',true),('Product L','Western',false);
SELECT (COUNT(*) * 100.0 / (SELECT COUNT(*) FROM haircare_products WHERE region = 'Western')) AS percentage FROM haircare_products WHERE sulfate_free = true;
What is the total number of volunteers in Africa and Latin America?
CREATE TABLE volunteers (id INT,name TEXT,region TEXT); INSERT INTO volunteers VALUES (1,'James Lee','Asia'),(2,'Anna Chen','Asia'),(3,'Mohammed Ahmed','Africa'),(4,'Maria Rodriguez','Latin America');
SELECT COUNT(*) FROM volunteers WHERE region IN ('Africa', 'Latin America');
How many animals of each species are there in the 'Forest' habitat?
CREATE TABLE animal_population (species TEXT,habitat TEXT,animal_count INTEGER); INSERT INTO animal_population (species,habitat,animal_count) VALUES ('Deer','Forest',15),('Rabbit','Forest',20),('Squirrel','Forest',30);
SELECT species, animal_count FROM animal_population WHERE habitat = 'Forest';
Calculate the percentage of cases that are dismissed, for each state, ordered from highest to lowest percentage?
CREATE TABLE law_firms (firm_id INT,name VARCHAR(50),state VARCHAR(20)); INSERT INTO law_firms (firm_id,name,state) VALUES (1,'Law Firm A','NY'),(2,'Law Firm B','CA'),(3,'Law Firm C','NY'),(4,'Law Firm D','IL'),(5,'Law Firm E','CA'); CREATE TABLE cases (case_id INT,firm_id INT,case_status VARCHAR(10)); INSERT INTO cases (case_id,firm_id,case_status) VALUES (101,1,'open'),(102,1,'dismissed'),(103,2,'open'),(104,3,'open'),(105,3,'dismissed'),(106,3,'open'),(107,3,'dismissed'),(108,4,'open'),(109,4,'open'),(110,5,'open');
SELECT state, 100.0 * SUM(CASE WHEN case_status = 'dismissed' THEN 1 ELSE 0 END) / COUNT(*) as dismissed_percentage FROM cases JOIN law_firms ON cases.firm_id = law_firms.firm_id GROUP BY state ORDER BY dismissed_percentage DESC;
What is the total budget and the number of programs in each department for the current year?
CREATE TABLE department_budget (id INT,department VARCHAR(255),program_budget DECIMAL(10,2)); INSERT INTO department_budget (id,department,program_budget) VALUES (1,'Education',5000),(2,'Health',7000),(3,'Education',3000),(4,'Environment',8000),(5,'Health',9000),(6,'Education',4000);
SELECT department, SUM(program_budget) AS total_budget, COUNT(*) AS num_programs FROM department_budget GROUP BY department;
What is the average temperature in fields located in 'US-CA'?
CREATE TABLE Fields (id INT PRIMARY KEY,name VARCHAR(255),acres FLOAT,location VARCHAR(255)); INSERT INTO Fields (id,name,acres,location) VALUES (1,'FieldA',5.6,'US-MN'),(2,'FieldB',3.2,'US-CA'); CREATE TABLE IoT_Sensors (id INT PRIMARY KEY,Field_id INT,temperature FLOAT,humidity FLOAT); INSERT INTO IoT_Sensors (id,Field_id,temperature,humidity) VALUES (1,1,20.5,60.3),(2,2,25.3,70.2);
SELECT AVG(IoT_Sensors.temperature) FROM IoT_Sensors INNER JOIN Fields ON IoT_Sensors.Field_id = Fields.id WHERE Fields.location = 'US-CA';
What is the total quantity of 'recycled_materials' table for each material type?
CREATE TABLE recycled_materials (id INT,producer VARCHAR(20),material VARCHAR(20),quantity INT); INSERT INTO recycled_materials (id,producer,material,quantity) VALUES (1,'EcoFabrics','cotton',5000),(2,'GreenYarn','wool',3000),(3,'EcoFabrics','polyester',7000),(4,'GreenYarn','cotton',4000),(5,'SustainaFiber','silk',6000);
SELECT material, SUM(quantity) AS total_quantity FROM recycled_materials GROUP BY material;
Insert a new artwork 'Artwork 4' by artist 'Artist 3'.
CREATE TABLE artists (id INT,name TEXT); INSERT INTO artists (id,name) VALUES (1,'Artist 1'),(2,'Artist 2'),(3,'Artist 3'); CREATE TABLE artworks (id INT,title TEXT,year_created INT,artist_id INT);
INSERT INTO artworks (id, title, year_created, artist_id) VALUES (4, 'Artwork 4', 2022, 3);
Decrease R&D expenditure of 'DrugK' by 15% in H1 2021.
CREATE TABLE rd_expenditures_3 (drug_name TEXT,expenditure DECIMAL(10,2),expenditure_date DATE); INSERT INTO rd_expenditures_3 (drug_name,expenditure,expenditure_date) VALUES ('DrugK',300000.00,'2021-01-01'),('DrugK',325000.00,'2021-02-01'),('DrugK',350000.00,'2021-03-01'),('DrugK',375000.00,'2021-04-01'),('DrugK',400000.00,'2021-05-01'),('DrugK',425000.00,'2021-06-01');
UPDATE rd_expenditures_3 SET expenditure = FLOOR(expenditure * 0.85) WHERE drug_name = 'DrugK' AND expenditure_date BETWEEN '2021-01-01' AND '2021-06-30';
Drop the 'claims' table
CREATE TABLE claims (claim_id INT PRIMARY KEY,policyholder_id INT,claim_amount DECIMAL(10,2),claim_date DATE);
DROP TABLE claims;
What is the total duration of all videos published by the 'Education' channel in the last month?
CREATE TABLE videos (id INT,title VARCHAR(255),channel VARCHAR(50),duration INT,publication_date DATE); INSERT INTO videos (id,title,channel,duration,publication_date) VALUES (1,'Video1','Education',1200,'2022-03-02'),(2,'Video2','Sports',900,'2022-03-10'),(3,'Video3','Education',1500,'2022-03-25');
SELECT SUM(duration) FROM videos WHERE channel = 'Education' AND publication_date >= DATE_SUB(CURDATE(), INTERVAL 1 MONTH);