instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
List all suppliers that provide recycled materials for manufacturing.
CREATE TABLE suppliers (id INT,name VARCHAR(255),material VARCHAR(255)); INSERT INTO suppliers (id,name,material) VALUES (1,'Supplier A','Plastic'),(2,'Supplier B','Glass'),(3,'Supplier C','Recycled Plastic'),(4,'Supplier D','Metal');
SELECT s.name FROM suppliers s WHERE s.material = 'Recycled Plastic' OR s.material = 'Recycled Glass';
What is the success rate of programs that have 'Youth' in their name?
CREATE TABLE ProgramOutcomes (ProgramID INT,ProgramName TEXT,SuccessRate DECIMAL(5,2)); CREATE TABLE Programs (ProgramID INT,ProgramName TEXT,HasYouth INTEGER);
SELECT AVG(ProgramOutcomes.SuccessRate) AS AverageSuccessRate FROM ProgramOutcomes INNER JOIN Programs ON ProgramOutcomes.ProgramID = Programs.ProgramID WHERE Programs.HasYouth = 1;
What is the total investment for bioprocess engineering companies in Texas?
CREATE TABLE companies (id INT,name VARCHAR(50),type VARCHAR(50),location VARCHAR(50),investment FLOAT); INSERT INTO companies (id,name,type,location,investment) VALUES (1,'BioTex','Bioprocess','Texas',5000000); INSERT INTO companies (id,name,type,location,investment) VALUES (2,'ProBioLabs','Genetic Research','Texas',3000000);
SELECT SUM(investment) FROM companies WHERE type = 'Bioprocess' AND location = 'Texas';
How many times has the energy sector been targeted by cyber attacks?
CREATE TABLE attacks (id INT,sector VARCHAR(20),type VARCHAR(50)); INSERT INTO attacks (id,sector,type) VALUES (1,'Energy','Cyber Attack'),(2,'Healthcare','Phishing'),(3,'Financial','Ransomware');
SELECT COUNT(*) FROM attacks WHERE sector = 'Energy' AND type = 'Cyber Attack';
What is the average time to fill open positions, segmented by job category?
CREATE TABLE JobOpenings (OpeningID INT,JobCategory VARCHAR(20),OpeningDate DATE,CloseDate DATE); INSERT INTO JobOpenings (OpeningID,JobCategory,OpeningDate,CloseDate) VALUES (1,'Marketing','2022-01-01','2022-02-15'),(2,'IT','2022-03-01','2022-04-10');
SELECT JobCategory, AVG(DATEDIFF(CloseDate, OpeningDate)) FROM JobOpenings GROUP BY JobCategory;
What is the total number of employees hired from underrepresented communities, by year?
CREATE TABLE Employees (EmployeeID INT,HireDate DATE); CREATE TABLE UnderrepresentedCommunities (CommunityID INT,CommunityName VARCHAR(50)); CREATE TABLE EmployeeCommunities (EmployeeID INT,CommunityID INT);
SELECT YEAR(e.HireDate) AS Year, COUNT(DISTINCT e.EmployeeID) FROM Employees e INNER JOIN EmployeeCommunities ec ON e.EmployeeID = ec.EmployeeID INNER JOIN UnderrepresentedCommunities uc ON ec.CommunityID = uc.CommunityID GROUP BY YEAR(e.HireDate);
Calculate the average distance of freight for each city of origin.
CREATE TABLE Freight (id INT PRIMARY KEY,shipment_id INT,origin VARCHAR(50),destination VARCHAR(50),distance INT,cost FLOAT); INSERT INTO Freight (id,shipment_id,origin,destination,distance,cost) VALUES (1,1,'Mumbai','Delhi',1400,7200.5),(2,2,'Tokyo','Seoul',2100,1050.3),(3,3,'São Paulo','Buenos Aires',1084,542.7);
SELECT origin, AVG(distance) FROM Freight GROUP BY origin;
List the Impressionist artists and their artworks.
CREATE TABLE Impressionist_Art(artist VARCHAR(20),artwork VARCHAR(20),movement VARCHAR(20)); INSERT INTO Impressionist_Art VALUES ('Monet','Water Lilies','Impressionism'),('Renoir','Dance at Le Moulin de la Galette','Impressionism'),('Degas','Ballet Rehearsal','Impressionism'),('Morisot','The Cradle','Impressionism'),('Cassatt','The Bath','Impressionism');
SELECT artist, artwork FROM Impressionist_Art WHERE movement = 'Impressionism';
Identify the top 3 most vulnerable software vendors, ranked by the total number of high risk vulnerabilities, in the past year.
CREATE TABLE vulnerabilities (id INT,detection_date DATE,software_vendor VARCHAR(255),risk_score INT); INSERT INTO vulnerabilities (id,detection_date,software_vendor,risk_score) VALUES (1,'2022-01-01','VendorA',9),(2,'2022-01-05','VendorB',7),(3,'2022-01-10','VendorC',8);
SELECT software_vendor, SUM(CASE WHEN risk_score >= 8 THEN 1 ELSE 0 END) as high_risk_vulnerabilities, RANK() OVER (ORDER BY SUM(CASE WHEN risk_score >= 8 THEN 1 ELSE 0 END) DESC) as rank FROM vulnerabilities WHERE detection_date >= DATE(NOW()) - INTERVAL '1 year' GROUP BY software_vendor HAVING rank <= 3;
List the drivers who have collected the highest total fare in the past month.
CREATE TABLE driver (driver_id INT,driver_name TEXT);CREATE TABLE fare (fare_id INT,driver_id INT,fare_amount DECIMAL,collection_date DATE); INSERT INTO driver (driver_id,driver_name) VALUES (1,'Driver1'),(2,'Driver2'),(3,'Driver3'),(4,'Driver4'),(5,'Driver5'); INSERT INTO fare (fare_id,driver_id,fare_amount,collection_date) VALUES (1,1,5.00,'2022-03-01'),(2,1,5.00,'2022-03-02'),(3,2,3.00,'2022-03-01'),(4,2,3.00,'2022-03-03'),(5,3,2.00,'2022-03-01');
SELECT d.driver_name, SUM(f.fare_amount) as total_fare FROM driver d JOIN fare f ON d.driver_id = f.driver_id WHERE f.collection_date BETWEEN DATEADD(month, -1, GETDATE()) AND GETDATE() GROUP BY d.driver_id ORDER BY total_fare DESC;
Display the names and nutrient information of all food items that are low in sodium (<=140mg) in the food_nutrition_info table.
CREATE TABLE food_nutrition_info (food_id INT,food_name VARCHAR(255),sodium_content DECIMAL(5,2));
SELECT food_name, sodium_content FROM food_nutrition_info WHERE sodium_content <= 140.0;
What is the total number of 'skilled' workers in 'Germany'?
CREATE TABLE workers (id INT,name TEXT,skill TEXT,location TEXT); INSERT INTO workers (id,name,skill,location) VALUES (1,'John','skilled','Germany'),(2,'Jane','unskilled','Germany'),(3,'Mark','skilled','France');
SELECT COUNT(*) FROM workers WHERE skill = 'skilled' AND location = 'Germany';
What is the distribution of clean energy policy trends in developed and developing countries?
CREATE TABLE policy_trends_developed (country VARCHAR(255),trend VARCHAR(255)); INSERT INTO policy_trends_developed (country,trend) VALUES ('US','Renewable Energy'),('UK','Carbon Pricing'),('Germany','Energy Efficiency'); CREATE TABLE policy_trends_developing (country VARCHAR(255),trend VARCHAR(255)); INSERT INTO policy_trends_developing (country,trend) VALUES ('India','Renewable Energy'),('Brazil','Energy Efficiency'),('South Africa','Carbon Pricing');
SELECT country, COUNT(trend) AS num_trends, 100.0 * COUNT(trend) / (SELECT COUNT(*) FROM policy_trends_developed) AS percent FROM policy_trends_developed GROUP BY country UNION ALL SELECT country, COUNT(trend) AS num_trends, 100.0 * COUNT(trend) / (SELECT COUNT(*) FROM policy_trends_developing) AS percent FROM policy_trends_developing GROUP BY country;
List all lunar rovers deployed by China and India on the Moon.
CREATE TABLE lunar_rovers (id INT,name VARCHAR(255),deployment_date DATE,deploying_country VARCHAR(255)); INSERT INTO lunar_rovers (id,name,deployment_date,deploying_country) VALUES (1,'Yutu','2013-12-14','China'); INSERT INTO lunar_rovers (id,name,deployment_date,deploying_country) VALUES (2,'Pragyan','2019-09-21','India'); CREATE VIEW lunar_rovers_china AS SELECT * FROM lunar_rovers WHERE deploying_country = 'China'; CREATE VIEW lunar_rovers_india AS SELECT * FROM lunar_rovers WHERE deploying_country = 'India';
SELECT * FROM lunar_rovers l INNER JOIN lunar_rovers_china c ON l.id = c.id INNER JOIN lunar_rovers_india i ON l.id = i.id;
Calculate the number of animals in the 'habitat_preservation' program that were added in the last month
CREATE TABLE animal_population (animal_id INT,animal_name VARCHAR(50),program VARCHAR(50),added_date DATE); INSERT INTO animal_population (animal_id,animal_name,program,added_date) VALUES (1,'Grizzly Bear','habitat_preservation','2022-01-01'),(2,'Gray Wolf','community_education','2022-02-01'),(3,'Bald Eagle','habitat_preservation','2022-03-01'),(4,'Red Fox','community_education','2022-04-01');
SELECT COUNT(*) FROM animal_population WHERE program = 'habitat_preservation' AND added_date >= DATEADD(MONTH, -1, GETDATE());
What is the average runtime of movies by release year?
CREATE TABLE movie_runtime (title VARCHAR(255),runtime INT,release_year INT); INSERT INTO movie_runtime (title,runtime,release_year) VALUES ('Pulp Fiction',154,1994),('The Matrix',136,1999);
SELECT release_year, AVG(runtime) FROM movie_runtime GROUP BY release_year;
Rank countries by the percentage of international visitors who travel sustainably in 2019.
CREATE TABLE CountrySustainableTravel (country_id INT,year INT,pct_sustainable_travel FLOAT); INSERT INTO CountrySustainableTravel (country_id,year,pct_sustainable_travel) VALUES (1,2019,0.5); INSERT INTO CountrySustainableTravel (country_id,year,pct_sustainable_travel) VALUES (2,2019,0.7); INSERT INTO CountrySustainableTravel (country_id,year,pct_sustainable_travel) VALUES (3,2019,0.6); INSERT INTO CountrySustainableTravel (country_id,year,pct_sustainable_travel) VALUES (4,2019,0.8);
SELECT country_id, RANK() OVER (ORDER BY pct_sustainable_travel DESC) as rank FROM CountrySustainableTravel WHERE year = 2019;
Update the 'area' value for the record with id 3 in the 'wildlife_habitat' table to 95.8 square kilometers.
CREATE TABLE wildlife_habitat (id INT,name VARCHAR(255),area FLOAT); INSERT INTO wildlife_habitat (id,name,area) VALUES (1,'Habitat1',50.3),(2,'Habitat2',32.7),(3,'Habitat3',86.9),(4,'Habitat4',45.6);
UPDATE wildlife_habitat SET area = 95.8 WHERE id = 3;
What is the total expenditure on inclusion efforts for each department, ordered from highest to lowest?
CREATE TABLE departments (id INT,name TEXT); CREATE TABLE inclusion_expenses (id INT,department_id INT,amount INT); INSERT INTO departments (id,name) VALUES (1,'Dept A'),(2,'Dept B'); INSERT INTO inclusion_expenses (id,department_id,amount) VALUES (1,1,1000),(2,1,2000),(3,2,1500);
SELECT departments.name, SUM(inclusion_expenses.amount) FROM departments INNER JOIN inclusion_expenses ON departments.id = inclusion_expenses.department_id GROUP BY departments.name ORDER BY SUM(inclusion_expenses.amount) DESC;
Add a new platform to the 'platforms' table with the platform name 'New Platform'
CREATE TABLE platforms (id INT,platform TEXT);
INSERT INTO platforms (id, platform) VALUES (null, 'New Platform');
How many AI safety incidents were reported for each AI subfield in the second half of 2020 and the first half of 2021, and which subfield had the most incidents in this period?
CREATE TABLE ai_safety_incidents (incident_id INT,incident_date DATE,ai_subfield TEXT,incident_description TEXT); INSERT INTO ai_safety_incidents (incident_id,incident_date,ai_subfield,incident_description) VALUES (1,'2020-07-01','Explainable AI','Model failed to provide clear explanations'); INSERT INTO ai_safety_incidents (incident_id,incident_date,ai_subfield,incident_description) VALUES (2,'2021-02-01','Algorithmic Fairness','AI system showed bias against certain groups'); INSERT INTO ai_safety_incidents (incident_id,incident_date,ai_subfield,incident_description) VALUES (3,'2020-08-01','Explainable AI','Model provided inconsistent explanations');
SELECT ai_subfield, SUM(CASE WHEN incident_date BETWEEN '2020-07-01' AND '2021-06-30' THEN 1 ELSE 0 END) as incidents FROM ai_safety_incidents GROUP BY ai_subfield ORDER BY incidents DESC LIMIT 1;
Get the average manufacturing time for sustainable materials in Germany.
CREATE TABLE Manufacturing(id INT,material_name VARCHAR(50),manufacturing_time INT,production_country VARCHAR(50),is_sustainable BOOLEAN); INSERT INTO Manufacturing(id,material_name,manufacturing_time,production_country,is_sustainable) VALUES (1,'Organic Cotton',10,'Germany',true); INSERT INTO Manufacturing(id,material_name,manufacturing_time,production_country,is_sustainable) VALUES (2,'Conventional Cotton',8,'Germany',false);
SELECT AVG(manufacturing_time) FROM Manufacturing WHERE is_sustainable = true AND production_country = 'Germany';
How many bioprocess engineering jobs are available in Canada?
CREATE SCHEMA if not exists engineering; CREATE TABLE if not exists engineering.jobs(job_id INT PRIMARY KEY,title VARCHAR(100),location VARCHAR(50),salary DECIMAL(10,2)); INSERT INTO engineering.jobs (job_id,title,location,salary) VALUES (1,'Bioprocess Engineer','Canada',80000); INSERT INTO engineering.jobs (job_id,title,location,salary) VALUES (2,'Mechanical Engineer','Canada',70000);
SELECT COUNT(*) FROM engineering.jobs WHERE title = 'Bioprocess Engineer' AND location = 'Canada';
List the number of unique IP addresses and domains found in threat intelligence data
CREATE TABLE threat_intelligence (id INT,source VARCHAR(10),ip_address VARCHAR(15),domain VARCHAR(25)); INSERT INTO threat_intelligence (id,source,ip_address,domain) VALUES (1,'TI1','192.168.1.1','example1.com'),(2,'TI2','192.168.1.2','example2.com'),(3,'TI3','192.168.1.3','example3.com'),(4,'TI4','192.168.1.4','example4.com');
SELECT source, COUNT(DISTINCT ip_address) as unique_ips, COUNT(DISTINCT domain) as unique_domains FROM threat_intelligence GROUP BY source;
What is the number of rural ambulance services in each county, ordered by county name.
CREATE TABLE ambulances (ambulance_id INT,name TEXT,rural BOOLEAN); CREATE TABLE counties (county_code TEXT,county_name TEXT); INSERT INTO ambulances (ambulance_id,name,rural) VALUES (1,'Rural Ambulance Service',TRUE),(2,'Urban Ambulance Service',FALSE); INSERT INTO counties (county_code,county_name) VALUES ('NY-1','New York County 1'),('NY-2','New York County 2');
SELECT 'Ambulance' as type, counties.county_name, COUNT(ambulances.ambulance_id) as count FROM ambulances INNER JOIN counties ON TRUE WHERE ambulances.rural = TRUE GROUP BY counties.county_name ORDER BY counties.county_name;
Update the species name for species_id 123
species (species_id,common_name,scientific_name,family)
UPDATE species SET common_name = 'New Name' WHERE species_id = 123
What is the most expensive property in Denver with an inclusive housing policy?
CREATE TABLE properties (id INT,city VARCHAR(50),listing_price DECIMAL(10,2),has_inclusive_policy BOOLEAN); INSERT INTO properties (id,city,listing_price,has_inclusive_policy) VALUES (1,'Denver',1000000.00,TRUE),(2,'Denver',800000.00,FALSE),(3,'Denver',900000.00,TRUE);
SELECT * FROM properties WHERE city = 'Denver' AND has_inclusive_policy = TRUE ORDER BY listing_price DESC LIMIT 1;
What is the average response time for emergency calls in Miami, considering only incidents that occurred after midnight?
CREATE TABLE emergency_calls (call_id INT,call_time TIMESTAMP,city TEXT,response_time INT); INSERT INTO emergency_calls (call_id,call_time,city,response_time) VALUES (1,'2022-01-01 01:23:45','Miami',15); INSERT INTO emergency_calls (call_id,call_time,city,response_time) VALUES (2,'2022-01-01 00:12:34','Miami',20); INSERT INTO emergency_calls (call_id,call_time,city,response_time) VALUES (3,'2022-01-02 03:45:01','Miami',12);
SELECT AVG(response_time) FROM emergency_calls WHERE city = 'Miami' AND EXTRACT(HOUR FROM call_time) > 0;
What is the number of citizen complaints received in each district, ordered from the most to least complaints?
CREATE TABLE Citizen_Complaints(District VARCHAR(255),Complaint VARCHAR(255)); INSERT INTO Citizen_Complaints VALUES ('District 1','Potholes'),('District 1','Garbage'),('District 2','Potholes'),('District 3','Graffiti'),('District 3','Potholes');
SELECT District, COUNT(Complaint) as Num_Complaints FROM Citizen_Complaints GROUP BY District ORDER BY Num_Complaints DESC;
List all projects with a start date on or after "2022-01-01" from the "Projects" table.
CREATE TABLE Projects (project_id INT,contractor_id INT,start_date DATE,end_date DATE);
SELECT * FROM Projects WHERE start_date >= '2022-01-01';
Determine the percentage of total energy production for each energy source (wind, solar, hydro) in a given year.
CREATE TABLE energy_production (energy_source VARCHAR(255),year INT,monthly_production FLOAT); INSERT INTO energy_production VALUES ('Wind',2022,2000),('Solar',2022,3000),('Hydro',2022,4000),('Wind',2022,2500),('Solar',2022,3500),('Hydro',2022,4500);
SELECT energy_source, SUM(monthly_production) / SUM(SUM(monthly_production)) OVER () AS percentage_of_total FROM energy_production WHERE year = 2022 GROUP BY energy_source;
List all unique cities and the total number of arts education programs in 'Southern' region for 2021 and 2022, sorted by the total number of programs in descending order.
CREATE TABLE Education (city VARCHAR(20),region VARCHAR(20),year INT,program_count INT); INSERT INTO Education (city,region,year,program_count) VALUES ('Los Angeles','Southern',2021,50),('San Diego','Southern',2021,40),('Santa Monica','Southern',2021,30),('Los Angeles','Southern',2022,60),('San Diego','Southern',2022,55),('Santa Monica','Southern',2022,45);
SELECT city, SUM(program_count) FROM Education WHERE region = 'Southern' AND year IN (2021, 2022) GROUP BY city ORDER BY SUM(program_count) DESC;
How many patients have been diagnosed with Dengue Fever in the last 6 months in each region?
CREATE TABLE Patients (ID INT,Disease VARCHAR(20),DiagnosisDate DATE,Region VARCHAR(20)); INSERT INTO Patients (ID,Disease,DiagnosisDate,Region) VALUES (1,'Dengue Fever','2022-01-01','Central'),(2,'Dengue Fever','2022-06-15','Central');
SELECT Region, COUNT(*) AS CountPerRegion FROM Patients WHERE Disease = 'Dengue Fever' AND DiagnosisDate >= DATEADD(MONTH, -6, GETDATE()) GROUP BY Region;
What is the total number of eco-friendly accommodations in Canada and the United States?
CREATE TABLE accommodations (accommodation_id INT,name VARCHAR(50),country VARCHAR(50),is_eco_friendly BOOLEAN);
SELECT COUNT(*) FROM accommodations WHERE (country = 'Canada' OR country = 'United States') AND is_eco_friendly = TRUE;
What is the total installed capacity of renewable energy sources in each country?
CREATE TABLE renewable_energy_sources (id INT,country VARCHAR(255),source VARCHAR(255),installed_capacity INT); INSERT INTO renewable_energy_sources (id,country,source,installed_capacity) VALUES (1,'Germany','Solar',500),(2,'France','Wind',600),(3,'Spain','Hydro',700),(4,'Italy','Geothermal',800),(5,'Germany','Wind',900);
SELECT country, SUM(installed_capacity) FROM renewable_energy_sources GROUP BY country;
What are the top 2 countries with the least number of ethical AI principles?
CREATE TABLE EthicalAI (country VARCHAR(20),num_principles INT); INSERT INTO EthicalAI (country,num_principles) VALUES ('USA',5),('China',3),('India',4),('Brazil',6),('Russia',2);
SELECT country, num_principles FROM (SELECT country, num_principles FROM EthicalAI ORDER BY num_principles LIMIT 2) AS subquery ORDER BY num_principles DESC;
What is the maximum amount invested in the 'Education' sector?
CREATE TABLE ImpactInvestments (InvestmentID INT,InvestmentAmount DECIMAL(10,2),Sector VARCHAR(30)); INSERT INTO ImpactInvestments (InvestmentID,InvestmentAmount,Sector) VALUES (1,5000,'Education'),(2,10000,'Healthcare'),(3,7500,'Education');
SELECT MAX(InvestmentAmount) FROM ImpactInvestments WHERE Sector = 'Education';
What is the total quantity of ethically sourced products sold in Canada in Q1 2022?
CREATE TABLE Products (productID int,productName varchar(255),ethicallySourced varchar(5),price decimal(10,2)); INSERT INTO Products VALUES (1,'ProductA','Y',19.99); CREATE TABLE Suppliers (supplierID int,supplierName varchar(255),country varchar(255)); INSERT INTO Suppliers VALUES (1,'SupplierA','Canada'); CREATE TABLE Sales (saleID int,productID int,quantity int,date datetime); INSERT INTO Sales VALUES (1,1,50,'2022-04-01');
SELECT SUM(S.quantity) as total_quantity FROM Sales S INNER JOIN Products P ON S.productID = P.productID INNER JOIN Suppliers Supp ON P.supplierID = Supp.supplierID WHERE P.ethicallySourced = 'Y' AND Supp.country = 'Canada' AND YEAR(S.date) = 2022 AND QUARTER(S.date) = 1;
Which districts have a recycling rate higher than the average recycling rate?
CREATE TABLE RecyclingRates (id INT,district VARCHAR(20),recycling_rate DECIMAL(5,2)); INSERT INTO RecyclingRates (id,district,recycling_rate) VALUES (1,'DistrictA',0.65),(2,'DistrictB',0.70),(3,'DistrictC',0.55);
SELECT district FROM RecyclingRates WHERE recycling_rate > (SELECT AVG(recycling_rate) FROM RecyclingRates);
What is the minimum number of streams for any artist from the UK?
CREATE TABLE Streaming (id INT,artist VARCHAR(50),streams INT,country VARCHAR(50)); INSERT INTO Streaming (id,artist,streams,country) VALUES (1,'Sia',1000000,'Australia'),(2,'Taylor Swift',2000000,'USA'),(3,'Ed Sheeran',1200000,'UK');
SELECT MIN(streams) FROM Streaming WHERE country = 'UK';
Show the names and regions of all protected species with an ID greater than 100.
CREATE TABLE ProtectedSpecies(species_id INT,species_name TEXT,region TEXT); INSERT INTO ProtectedSpecies (species_id,species_name,region) VALUES (101,'Lynx','Region C'),(102,'Seal','Region D'),(103,'Otter','Region C');
SELECT species_name, region FROM ProtectedSpecies WHERE species_id > 100;
What is the total number of AI creativity incidents reported in the arts sector, and what is the minimum number of incidents reported for a single incident type?
CREATE TABLE AICreativity (id INT,incident_sector VARCHAR(50),incident_type VARCHAR(50)); INSERT INTO AICreativity (id,incident_sector,incident_type) VALUES (1,'Arts','Artistic Freedom'),(2,'Arts','Artistic Expression'),(3,'Finance','Financial Loss'),(4,'Arts','Censorship'),(5,'Arts','Artistic Integrity');
SELECT incident_sector, COUNT(incident_type) as incident_count FROM AICreativity WHERE incident_sector = 'Arts' GROUP BY incident_sector; SELECT MIN(incident_count) as min_incidents FROM (SELECT incident_sector, COUNT(incident_type) as incident_count FROM AICreativity WHERE incident_sector = 'Arts' GROUP BY incident_sector) as subquery;
What is the maximum temperature per year for each species?
CREATE TABLE species (species_id INT,species_name VARCHAR(255)); INSERT INTO species (species_id,species_name) VALUES (1,'SpeciesA'),(2,'SpeciesB'); CREATE TABLE temperature (year INT,species_id INT,temp FLOAT); INSERT INTO temperature (year,species_id,temp) VALUES (2000,1,15),(2000,2,22),(2001,1,18),(2001,2,23),(2002,1,12),(2002,2,26);
SELECT species_id, MAX(temp) as max_temp FROM temperature GROUP BY species_id, YEAR(year)
What is the maximum budget for rural infrastructure projects in Colombia's Antioquia department?
CREATE TABLE rural_infrastructure (id INT,project_name VARCHAR(255),budget FLOAT,department VARCHAR(50)); INSERT INTO rural_infrastructure (id,project_name,budget,department) VALUES (1,'Road Maintenance',95000.00,'Antioquia'),(2,'Water Supply System',120000.00,'Antioquia'),(3,'Sanitation Services',110000.00,'Antioquia');
SELECT MAX(budget) FROM rural_infrastructure WHERE department = 'Antioquia'
What are the details of marine conservation laws in Fiji?
CREATE TABLE MarineConservationLaws (id INT,law VARCHAR(50),description TEXT,country VARCHAR(50)); INSERT INTO MarineConservationLaws (id,law,description,country) VALUES (1,'Coral Reef Protection Act','Protects coral reefs from destructive fishing practices','Fiji');
SELECT * FROM MarineConservationLaws WHERE country = 'Fiji';
How many products have received a safety violation in the past year and are not cruelty-free certified?
CREATE TABLE products (product_id INT,product_name TEXT,is_cruelty_free BOOLEAN); CREATE TABLE safety_records (record_id INT,product_id INT,violation_date DATE);
SELECT COUNT(DISTINCT products.product_id) FROM products INNER JOIN safety_records ON products.product_id = safety_records.product_id WHERE safety_records.violation_date >= NOW() - INTERVAL '1 year' AND products.is_cruelty_free = FALSE;
What was the total revenue of vegan dishes in January?
CREATE TABLE revenue_by_month (month VARCHAR(10),dish VARCHAR(50),sales DECIMAL(10,2)); INSERT INTO revenue_by_month (month,dish,sales) VALUES ('January','Vegan Pizza',100.00),('January','Vegan Pasta',125.00); CREATE VIEW monthly_revenue AS SELECT month,SUM(sales) as total_sales FROM revenue_by_month GROUP BY month;
SELECT total_sales FROM monthly_revenue WHERE month = 'January' AND dish IN ('Vegan Pizza', 'Vegan Pasta', 'Vegan Curry');
What is the average carbon offset of renewable energy projects in the Western region?
CREATE TABLE offsets (id INT,region VARCHAR(20),project VARCHAR(20),offset INT); INSERT INTO offsets (id,region,project,offset) VALUES (1,'Western','Wind Farm',5000); INSERT INTO offsets (id,region,project,offset) VALUES (2,'Eastern','Solar Farm',6000);
SELECT AVG(offset) FROM offsets WHERE region = 'Western';
What is the total number of genetic research projects per researcher and their corresponding rank, ordered by total projects?
CREATE SCHEMA if not exists genetics;CREATE TABLE if not exists genetics.research_projects (id INT PRIMARY KEY,researcher_id INT,name VARCHAR(255)); INSERT INTO genetics.research_projects (id,researcher_id,name) VALUES (1,1,'ProjectA'),(2,2,'ProjectB'),(3,1,'ProjectC'),(4,3,'ProjectD'),(5,1,'ProjectE'),(6,4,'ProjectF');
SELECT researcher_id, COUNT(*) AS total_projects, ROW_NUMBER() OVER (ORDER BY COUNT(*) DESC) AS rank FROM genetics.research_projects WINDOW W AS (PARTITION BY researcher_id ORDER BY researcher_id ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) GROUP BY researcher_id, W.researcher_id ORDER BY rank;
Identify cities with more than 1000 trips on shared scooters
CREATE TABLE shared_vehicles (id INT,vehicle_type VARCHAR(20),trip_count INT); INSERT INTO shared_vehicles (id,vehicle_type,trip_count) VALUES (1,'ebike',1200),(2,'escooter',800),(3,'car',1500); CREATE TABLE city_data (city VARCHAR(20),shared_ebikes BOOLEAN,shared_escooters BOOLEAN); INSERT INTO city_data (city,shared_ebikes,shared_escooters) VALUES ('New York',true,true),('Los Angeles',false,false),('Chicago',true,true);
SELECT city FROM city_data WHERE shared_escooters = true AND city IN (SELECT city FROM (SELECT city, SUM(trip_count) AS total_trips FROM shared_vehicles WHERE vehicle_type = 'escooter' GROUP BY city) AS shared_scooters WHERE total_trips > 1000);
What is the total size of sustainable urbanism projects in Toronto?
CREATE TABLE sustainable_urbanism (size INT,city VARCHAR(20));
SELECT SUM(size) FROM sustainable_urbanism WHERE city = 'Toronto';
Change the category of 'Impossible Burger' to 'Plant-based' in the menu_items table
CREATE TABLE menu_items (item_id INT,item_name TEXT,category TEXT,price DECIMAL(5,2),inventory_count INT); CREATE TABLE menu_categories (category_id INT,category_name TEXT);
UPDATE menu_items mi JOIN menu_categories mc ON mi.category = mc.category_name SET mi.category = 'Plant-based' WHERE mi.item_name = 'Impossible Burger' AND mc.category_name = 'New';
What is the number of students who received accommodations in each building?
CREATE TABLE Buildings (BuildingID INT,BuildingName VARCHAR(50)); INSERT INTO Buildings (BuildingID,BuildingName) VALUES (1,'Adams Hall'); INSERT INTO Buildings (BuildingID,BuildingName) VALUES (2,'Brown Hall'); CREATE TABLE Accommodations (StudentID INT,BuildingID INT); INSERT INTO Accommodations (StudentID,BuildingID) VALUES (1,1); INSERT INTO Accommodations (StudentID,BuildingID) VALUES (2,1); INSERT INTO Accommodations (StudentID,BuildingID) VALUES (3,2);
SELECT b.BuildingName, COUNT(a.StudentID) AS NumStudents FROM Accommodations a INNER JOIN Buildings b ON a.BuildingID = b.BuildingID GROUP BY b.BuildingName;
How many Series A investments have been made in companies with at least one female founder?
CREATE TABLE company (id INT,name TEXT,founder_gender TEXT); CREATE TABLE investment_rounds (id INT,company_id INT,round TEXT,funding_amount INT);
SELECT COUNT(*) FROM investment_rounds JOIN company ON investment_rounds.company_id = company.id WHERE round = 'Series A' AND founder_gender = 'Female';
What is the distribution of gender in the profiles table, grouped by region?
CREATE TABLE profiles (id INT,user_id INT,gender VARCHAR(10),country VARCHAR(50),region VARCHAR(50));
SELECT region, gender, COUNT(*) FROM profiles GROUP BY region, gender;
What is the average carbon offset of projects in the 'CarbonOffsetProjects' table?
CREATE TABLE CarbonOffsetProjects (project TEXT,carbon_offset FLOAT); INSERT INTO CarbonOffsetProjects (project,carbon_offset) VALUES ('ProjectA',1200),('ProjectB',1500),('ProjectC',1800);
SELECT AVG(carbon_offset) FROM CarbonOffsetProjects;
What is the average mental health score of students by gender and ethnicity?
CREATE TABLE students (id INT,gender TEXT,ethnicity TEXT,mental_health_score INT);
SELECT students.gender, students.ethnicity, AVG(students.mental_health_score) as avg_score FROM students GROUP BY students.gender, students.ethnicity;
What is the maximum rating of a sustainable winery in France?
CREATE TABLE wineries (id INT,name TEXT,country TEXT,rating FLOAT,sustainable BOOLEAN); INSERT INTO wineries (id,name,country,rating,sustainable) VALUES (1,'Château Margaux','France',9.8,TRUE);
SELECT MAX(rating) FROM wineries WHERE country = 'France' AND sustainable = TRUE;
What is the percentage of workplaces with safety issues in each state?
CREATE TABLE Workplace_Safety (state VARCHAR(20),workplace_id INT,safety_issue BOOLEAN); INSERT INTO Workplace_Safety (state,workplace_id,safety_issue) VALUES ('California',101,true),('California',102,false),('New York',201,true);
SELECT state, (SUM(safety_issue) / COUNT(*)) * 100 as safety_issue_percentage FROM Workplace_Safety GROUP BY state;
What is the total amount of water saved in liters through water conservation initiatives in the state of California?
CREATE TABLE WaterConservationInitiatives (initiative_id INT,state VARCHAR(20),water_saved_liters INT); INSERT INTO WaterConservationInitiatives (initiative_id,state,water_saved_liters) VALUES (1,'California',1800000),(2,'California',2000000);
SELECT SUM(water_saved_liters) FROM WaterConservationInitiatives WHERE state = 'California';
What is the total carbon offset of each carbon offset program?
CREATE TABLE Carbon_Offset_Programs (program_id INT,program_name VARCHAR(20),total_carbon_offset INT); INSERT INTO Carbon_Offset_Programs (program_id,program_name,total_carbon_offset) VALUES (1,'Trees for the Future',50000),(2,'Clean Energy Corps',75000),(3,'Solar for All',100000);
SELECT program_name, total_carbon_offset FROM Carbon_Offset_Programs;
Find the maximum number of labor disputes in the 'labor_disputes_union' table for each state.
CREATE TABLE labor_disputes_union (state VARCHAR(50),year INT,disputes INT); INSERT INTO labor_disputes_union (state,year,disputes) VALUES ('California',2018,150),('Texas',2019,120),('New York',2020,180);
SELECT state, MAX(disputes) AS max_disputes FROM labor_disputes_union GROUP BY state;
What is the percentage of international visitors to Italy who prefer eco-friendly accommodation?
CREATE TABLE ItalyAccommodation (visitor INT,eco_friendly_accommodation BOOLEAN); INSERT INTO ItalyAccommodation (visitor,eco_friendly_accommodation) VALUES (12000000,true),(13000000,false);
SELECT (SUM(eco_friendly_accommodation) * 100.0 / COUNT(*)) AS pct_eco_friendly FROM ItalyAccommodation;
Find the number of public schools in each city and the total budget allocated to those schools from the 'education_budget' database.
CREATE TABLE cities (id INT PRIMARY KEY,name VARCHAR(255));CREATE TABLE schools (id INT PRIMARY KEY,name VARCHAR(255),type VARCHAR(255),city_id INT,FOREIGN KEY (city_id) REFERENCES cities(id));CREATE TABLE budgets (id INT PRIMARY KEY,school_id INT,amount INT,FOREIGN KEY (school_id) REFERENCES schools(id)); INSERT INTO cities (id,name) VALUES (1,'New York'); INSERT INTO cities (id,name) VALUES (2,'Los Angeles'); INSERT INTO schools (id,name,type,city_id) VALUES (1,'Public School 1','public',1); INSERT INTO schools (id,name,type,city_id) VALUES (2,'Private School 1','private',1);
SELECT cities.name, COUNT(schools.id) as school_count, SUM(budgets.amount) as total_budget FROM cities INNER JOIN schools ON cities.id = schools.city_id INNER JOIN budgets ON schools.id = budgets.school_id WHERE schools.type = 'public' GROUP BY cities.name;
What are the names of all public buildings that have been built before 1980 and their current occupancy levels?
CREATE TABLE public_buildings (id INT,name VARCHAR(50),year_built INT,occupancy FLOAT); INSERT INTO public_buildings (id,name,year_built,occupancy) VALUES (1,'City Hall',1975,0.75),(2,'Library',1982,0.9),(3,'Police Station',1968,0.6);
SELECT name, year_built, occupancy FROM public_buildings WHERE year_built < 1980;
What is the percentage of sustainable sourced ingredients for each menu category?
CREATE TABLE menu_categories (menu_category VARCHAR(255),ingredients VARCHAR(255)); INSERT INTO menu_categories (menu_category,ingredients) VALUES ('Appetizers','Chicken Wings,Lettuce,Tomatoes'),('Entrees','Beef,Chicken,Rice'),('Desserts','Fruit,Flour,Sugar');
SELECT menu_category, AVG(sustainable_ingredients_percentage) FROM (SELECT menu_category, IF(FIND_IN_SET('Chicken', ingredients), 1, 0) + IF(FIND_IN_SET('Beef', ingredients), 1, 0) + IF(FIND_IN_SET('Rice', ingredients), 1, 0) + IF(FIND_IN_SET('Lettuce', ingredients), 1, 0) + IF(FIND_IN_SET('Tomatoes', ingredients), 1, 0) + IF(FIND_IN_SET('Fruit', ingredients), 1, 0) + IF(FIND_IN_SET('Flour', ingredients), 1, 0) + IF(FIND_IN_SET('Sugar', ingredients), 1, 0) / COUNT(*) * 100 AS sustainable_ingredients_percentage FROM menu_categories GROUP BY menu_category) AS subquery GROUP BY menu_category;
What is the average budget for Explainable AI projects?
CREATE TABLE explainable_ai_projects (id INT PRIMARY KEY,project_name VARCHAR(50),budget FLOAT); INSERT INTO explainable_ai_projects (id,project_name,budget) VALUES (1,'Interpretability',60000.0),(2,'Feature Importance',55000.0),(3,'Model Transparency',58000.0),(4,'Explainable Boosting',62000.0),(5,'Local Interpretable Model',65000.0);
SELECT AVG(budget) FROM explainable_ai_projects;
What is the average age of players who have played the game "Galactic Gold" and are from the United States?
CREATE TABLE Players (PlayerID INT,PlayerAge INT,GameName VARCHAR(20),Country VARCHAR(20)); INSERT INTO Players (PlayerID,PlayerAge,GameName,Country) VALUES (1,25,'Galactic Gold','United States'); INSERT INTO Players (PlayerID,PlayerAge,GameName,Country) VALUES (2,32,'Starship Showdown','Canada');
SELECT AVG(PlayerAge) FROM Players WHERE GameName = 'Galactic Gold' AND Country = 'United States';
Which vessels have not complied with emission standards in the last 6 months?
CREATE TABLE VesselEmissions (VesselID INT,ComplianceDate DATE,Compliance BOOLEAN); INSERT INTO VesselEmissions (VesselID,ComplianceDate,Compliance) VALUES (1,'2021-01-15',FALSE),(2,'2021-02-20',TRUE),(3,'2021-03-05',FALSE);
SELECT VesselID FROM VesselEmissions WHERE Compliance = FALSE AND ComplianceDate >= DATEADD(month, -6, GETDATE());
What is the average number of workplace safety incidents for each union in the healthcare industry, excluding unions with less than 5000 members?
CREATE TABLE union_healthcare (union_id INT,union_name TEXT,industry TEXT,members INT,incidents INT); INSERT INTO union_healthcare (union_id,union_name,industry,members,incidents) VALUES (1,'Union L','Healthcare',7000,20),(2,'Union M','Healthcare',3000,15),(3,'Union N','Healthcare',8000,10);
SELECT industry, AVG(incidents) FROM union_healthcare WHERE industry = 'Healthcare' AND members >= 5000 GROUP BY industry;
How many users have participated in outdoor activities in each country?
CREATE TABLE user_activity (id INT,user_id INT,activity VARCHAR(20),country VARCHAR(20)); INSERT INTO user_activity (id,user_id,activity,country) VALUES (1,1,'running','USA'),(2,2,'swimming','CAN'),(3,3,'hiking','USA'),(4,4,'cycling','MEX');
SELECT country, COUNT(*) as num_users FROM user_activity WHERE activity LIKE '%outdoor%' GROUP BY country;
What is the total number of fire incidents in the city of Houston reported in the month of June 2022?
CREATE TABLE fire_incidents (id INT,city VARCHAR(20),month INT,year INT,incidents INT); INSERT INTO fire_incidents (id,city,month,year,incidents) VALUES (1,'Houston',6,2022,40); INSERT INTO fire_incidents (id,city,month,year,incidents) VALUES (2,'Houston',6,2022,45);
SELECT SUM(incidents) FROM fire_incidents WHERE city = 'Houston' AND month = 6 AND year = 2022;
What is the total number of mitigation projects in 'americas' and 'europe' regions?
CREATE TABLE mitigation_projects (id INT,region VARCHAR(20)); INSERT INTO mitigation_projects (id,region) VALUES (1,'americas'),(2,'europe'),(3,'africa');
SELECT region, COUNT(*) FROM mitigation_projects WHERE region IN ('americas', 'europe') GROUP BY region;
Create a table named 'satellite_deployment'
CREATE TABLE satellite_deployment (id INT PRIMARY KEY,name VARCHAR(255),country VARCHAR(255),launch_date DATE);
CREATE TABLE satellite_deployment (id INT PRIMARY KEY, name VARCHAR(255), country VARCHAR(255), launch_date DATE);
Examine the number of collective bargaining agreements per union, grouped by union and year for the 'Service Industry' unions
CREATE TABLE UnionInfo (UnionID INT,UnionName VARCHAR(50),Sector VARCHAR(20)); INSERT INTO UnionInfo (UnionID,UnionName,Sector) VALUES (1001,'Retail Workers United','Service Industry'); INSERT INTO UnionInfo (UnionID,UnionName,Sector) VALUES (1002,'Transport Workers Union','Transportation'); CREATE TABLE CollectiveBargaining (CBAID INT,UnionID INT,AgreementDate DATE,ExpirationDate DATE); INSERT INTO CollectiveBargaining (CBAID,UnionID,AgreementDate,ExpirationDate) VALUES (1,1001,'2018-01-01','2021-12-31'); INSERT INTO CollectiveBargaining (CBAID,UnionID,AgreementDate,ExpirationDate) VALUES (2,1002,'2019-06-15','2022-06-14');
SELECT UnionID, YEAR(AgreementDate) as AgreementYear, COUNT(*) as CBACount FROM CollectiveBargaining INNER JOIN UnionInfo ON CollectiveBargaining.UnionID = UnionInfo.UnionID WHERE Sector = 'Service Industry' GROUP BY UnionID, AgreementYear;
List the number of refugee families assisted by each organization, categorized by their emergency needs in 2020, and the total budget spent on each category?
CREATE TABLE refugee_assistance (family_id INT,organization_id INT,emergency_need VARCHAR(20),budget DECIMAL(10,2),assistance_date DATE); INSERT INTO refugee_assistance (family_id,organization_id,emergency_need,budget,assistance_date) VALUES (1201,2001,'Food',5000.00,'2020-01-12'),(1202,2001,'Shelter',7000.00,'2020-02-03'),(1203,2002,'Healthcare',6000.00,'2020-03-25'),(1204,2003,'Education',8000.00,'2020-04-12');
SELECT organization_id, emergency_need, COUNT(*) as families_assisted, SUM(budget) as total_budget_spent FROM refugee_assistance WHERE EXTRACT(YEAR FROM assistance_date) = 2020 GROUP BY organization_id, emergency_need;
Add a new artist 'Bad Bunny' from the Reggaeton genre to the MusicArtists table.
CREATE TABLE MusicArtists (artist_id INT,artist_name VARCHAR(50),genre VARCHAR(20));
INSERT INTO MusicArtists (artist_id, artist_name, genre) VALUES (102, 'Bad Bunny', 'Reggaeton');
Compare the number of hybrid and electric vehicles in the vehicle_sales table with the number of hybrid and electric vehicles in the autonomous_vehicles table.
CREATE TABLE vehicle_sales (id INT,vehicle_type VARCHAR(50)); INSERT INTO vehicle_sales (id,vehicle_type) VALUES (1,'Tesla Model 3'),(2,'Nissan Leaf'),(3,'Honda Civic'),(4,'Toyota Prius'); CREATE TABLE autonomous_vehicles (id INT,vehicle_type VARCHAR(50)); INSERT INTO autonomous_vehicles (id,vehicle_type) VALUES (1,'Wayve Pod'),(2,'Nuro R2'),(3,'Tesla Model S'),(4,'Baidu Apollo');
SELECT (SELECT COUNT(*) FROM vehicle_sales WHERE vehicle_type IN ('hybrid', 'electric')) - (SELECT COUNT(*) FROM autonomous_vehicles WHERE vehicle_type IN ('hybrid', 'electric'));
What is the total biomass of fish for each species in a specific country?
CREATE TABLE Country (id INT,name VARCHAR(50),continent VARCHAR(50)); CREATE TABLE Species (id INT,name VARCHAR(50),scientific_name VARCHAR(50)); CREATE TABLE FarmSpecies (farm_id INT,species_id INT,biomass INT); CREATE TABLE Farm (id INT,name VARCHAR(50),country_id INT);
SELECT s.name, SUM(fs.biomass) FROM Species s JOIN FarmSpecies fs ON s.id = fs.species_id JOIN Farm f ON fs.farm_id = f.id JOIN Country c ON f.country_id = c.id WHERE c.name = [some_country_name] GROUP BY s.name;
What are the top 3 most vulnerable systems by IP address and the number of vulnerabilities in the last month?
CREATE TABLE system_vulnerabilities (ip_address VARCHAR(15),vulnerability_date DATE,vulnerability_id INT); INSERT INTO system_vulnerabilities (ip_address,vulnerability_date,vulnerability_id) VALUES ('192.168.1.1','2021-11-01',1),('192.168.1.1','2021-11-05',2),('192.168.1.2','2021-11-02',3),('192.168.1.3','2021-11-03',4),('192.168.1.3','2021-11-04',5),('192.168.1.4','2021-11-05',6);
SELECT ip_address, COUNT(vulnerability_id) as num_vulnerabilities FROM system_vulnerabilities WHERE vulnerability_date >= DATEADD(month, -1, CURRENT_DATE) GROUP BY ip_address ORDER BY num_vulnerabilities DESC FETCH FIRST 3 ROWS ONLY;
What is the distribution of funding for AI research by institution?
CREATE TABLE institution_data (project_id INT,project_name VARCHAR(50),institution VARCHAR(50),amount FLOAT);
SELECT institution, SUM(amount) as total_funding FROM institution_data GROUP BY institution;
How many volunteers from Mexico have participated in health-related programs in the past year?
CREATE TABLE volunteers (id INT,country VARCHAR(50),program_id INT,participation_date DATE); CREATE TABLE programs (id INT,focus_area VARCHAR(50)); INSERT INTO volunteers (id,country,program_id,participation_date) VALUES (1,'Mexico',1,'2021-04-01'); INSERT INTO programs (id,focus_area) VALUES (1,'Healthy Living');
SELECT COUNT(DISTINCT volunteers.id) FROM volunteers JOIN programs ON volunteers.program_id = programs.id WHERE volunteers.country = 'Mexico' AND programs.focus_area = 'health-related programs' AND participation_date >= DATE_SUB(CURDATE(), INTERVAL 1 YEAR);
How many donors have updated their contact information in the last month?
CREATE TABLE donors (id INT,donor_name VARCHAR,email VARCHAR,phone VARCHAR,last_update DATE); INSERT INTO donors (id,donor_name,email,phone,last_update) VALUES (1,'Jane Doe','jane@example.com','555-1234','2022-01-01'),(2,'John Smith','john@example.com','555-5678','2022-02-10');
SELECT COUNT(*) FROM donors WHERE last_update >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH) AND (email IS NOT NULL AND email != '' OR phone IS NOT NULL AND phone != '');
What is the demographic breakdown of audience members who attended events in 2021?
CREATE TABLE AgeGroups (AgeGroupID INT,AgeGroup VARCHAR(50)); CREATE TABLE AudienceDemographics (AudienceID INT,AgeGroupID INT); INSERT INTO AgeGroups (AgeGroupID,AgeGroup) VALUES (1,'Under 18'),(2,'18-24'),(3,'25-34'),(4,'35-44'),(5,'45-54'),(6,'55-64'),(7,'65+'); INSERT INTO AudienceDemographics (AudienceID,AgeGroupID) VALUES (1,2),(2,3),(3,4),(4,5);
SELECT ag.AgeGroup, COUNT(a.AudienceID) as NumAudienceMembers FROM Audience a INNER JOIN AudienceDemographics ad ON a.AudienceID = ad.AudienceID INNER JOIN AgeGroups ag ON ad.AgeGroupID = ag.AgeGroupID INNER JOIN AudienceAttendance aa ON a.AudienceID = aa.AudienceID INNER JOIN Events e ON aa.EventID = e.EventID WHERE e.EventDate >= '2021-01-01' AND e.EventDate < '2022-01-01' GROUP BY ag.AgeGroup;
What is the maximum donation amount given by a single donor?
CREATE TABLE donations (id INT,donor_id INT,amount DECIMAL(10,2)); INSERT INTO donations (id,donor_id,amount) VALUES (1,1,50.00),(2,1,100.00),(3,2,75.00);
SELECT MAX(amount) FROM donations;
How many urban farms are there in the US?
CREATE TABLE farms (id INT,type VARCHAR(255),location VARCHAR(255)); INSERT INTO farms (id,type,location) VALUES (1,'Urban','US');
SELECT COUNT(*) FROM farms WHERE type = 'Urban' AND location = 'US';
What is the maximum pH value for aquatic locations with a temperature between 10 and 20 degrees Celsius?
CREATE TABLE OceanHealth (Location VARCHAR(50),pH FLOAT,Temperature FLOAT); INSERT INTO OceanHealth (Location,pH,Temperature) VALUES ('Caribbean',8.2,25); INSERT INTO OceanHealth (Location,pH,Temperature) VALUES ('Baltic',8.5,15);
SELECT MAX(pH) FROM OceanHealth WHERE Temperature BETWEEN 10 AND 20;
List the regions and the number of communities in each region from the 'indigenous_communities' table.
CREATE TABLE indigenous_communities (community_id INT,community_name VARCHAR(255),population INT,region VARCHAR(255));
SELECT region, COUNT(DISTINCT community_id) AS community_count FROM indigenous_communities GROUP BY region;
Find the total revenue generated by 'Organic Cotton Hoodies' sold in the United States for the year 2022.
CREATE TABLE garments (id INT,name VARCHAR(255),category VARCHAR(255),country VARCHAR(255),price DECIMAL(10,2)); INSERT INTO garments (id,name,category,country,price) VALUES (1,'Organic Cotton Hoodie','Tops','United States',50.00); CREATE TABLE orders (id INT,garment_id INT,quantity INT,order_date DATE);
SELECT SUM(quantity * price) FROM orders INNER JOIN garments ON orders.garment_id = garments.id WHERE garments.name = 'Organic Cotton Hoodie' AND garments.country = 'United States' AND YEAR(order_date) = 2022;
What is the average account balance for socially responsible lending customers in the South region?
CREATE TABLE customers (customer_id INT,name VARCHAR(50),region VARCHAR(20),account_balance DECIMAL(10,2)); INSERT INTO customers (customer_id,name,region,account_balance) VALUES (1,'John Doe','South',5000.00),(2,'Jane Smith','North',7000.00);
SELECT AVG(account_balance) FROM customers WHERE region = 'South' AND product_type = 'Socially Responsible Lending';
What is the total assets value for all customers from the Western region?
CREATE TABLE customers (customer_id INT,name TEXT,region TEXT); INSERT INTO customers (customer_id,name,region) VALUES (1,'John Smith','Western'),(2,'Jane Doe','Eastern'); CREATE TABLE assets (asset_id INT,customer_id INT,value INT); INSERT INTO assets (asset_id,customer_id,value) VALUES (1,1,5000),(2,1,7000),(3,2,3000);
SELECT SUM(a.value) FROM assets a INNER JOIN customers c ON a.customer_id = c.customer_id WHERE c.region = 'Western';
What is the total quantity of each appetizer sold?
CREATE TABLE appetizer_orders (order_id INT,appetizer VARCHAR(255),appetizer_quantity INT); INSERT INTO appetizer_orders VALUES (1,'Bruschetta',15),(2,'Calamari',8),(3,'Bruschetta',12);
SELECT appetizer, SUM(appetizer_quantity) FROM appetizer_orders GROUP BY appetizer;
Find the top 5 artists with the highest number of streams in the 'music_streaming' table, who are from Africa or of African descent.
CREATE TABLE music_streaming (stream_id INT,user_id INT,song_id INT,streams INT,date DATE,artist_id INT,artist_race VARCHAR(50),artist_nationality VARCHAR(50)); CREATE TABLE songs (song_id INT,song_name VARCHAR(100),artist_id INT,artist_race VARCHAR(50),artist_nationality VARCHAR(100));
SELECT s.artist_name, SUM(ms.streams) AS total_streams FROM music_streaming ms JOIN songs s ON ms.song_id = s.song_id WHERE (s.artist_race LIKE '%African%' OR s.artist_nationality LIKE '%Africa%') GROUP BY s.artist_name ORDER BY total_streams DESC LIMIT 5;
What is the average ticket price for each team's games?
CREATE TABLE teams (team_id INT,team_name VARCHAR(255)); INSERT INTO teams (team_id,team_name) VALUES (1,'Golden State Warriors'),(2,'Los Angeles Lakers'); CREATE TABLE ticket_sales (game_id INT,team_id INT,ticket_price DECIMAL(5,2)); INSERT INTO ticket_sales (game_id,team_id,ticket_price) VALUES (1,1,150.00),(2,1,200.00),(3,2,100.00);
SELECT t.team_name, AVG(ts.ticket_price) as avg_ticket_price FROM teams t INNER JOIN ticket_sales ts ON t.team_id = ts.team_id GROUP BY t.team_name;
How many artworks were sold by Indigenous artists from Canada in each year?
CREATE TABLE ArtWorkSales (artworkID INT,saleDate DATE,artistID INT,revenue DECIMAL(10,2)); CREATE TABLE Artists (artistID INT,artistName VARCHAR(50),country VARCHAR(50));
SELECT YEAR(saleDate) as sale_year, COUNT(*) as artwork_count FROM ArtWorkSales aws JOIN Artists a ON aws.artistID = a.artistID WHERE a.country = 'Canada' AND a.artistName IN (SELECT artistName FROM Artists WHERE ethnicity = 'Indigenous') GROUP BY sale_year;
What is the total number of military bases in the Pacific region?
CREATE TABLE military_bases (id INT,name TEXT,location TEXT,type TEXT);INSERT INTO military_bases (id,name,location,type) VALUES (1,'Andersen AFB','Guam','Air Force');INSERT INTO military_bases (id,name,location,type) VALUES (2,'Camp H.M. Smith','Hawaii','Joint Base');
SELECT SUM(number_of_bases) FROM (SELECT COUNT(*) AS number_of_bases FROM military_bases WHERE location = 'Pacific') AS subquery;
What is the total mass of space debris collected by the Japanese Kounotori-8 mission?
CREATE TABLE space_debris (id INT,name VARCHAR(50),mission VARCHAR(50),mass FLOAT); INSERT INTO space_debris VALUES (1,'Debris-1','Kounotori-8',2.6);
SELECT SUM(mass) as total_mass FROM space_debris WHERE mission = 'Kounotori-8';
List the first name, last name, and city for all providers who have 'therapist' in their specialty and are located in New York, NY, along with the number of patients assigned to each provider, and the average mental health score for each provider's patients
CREATE TABLE providers (provider_id INT,first_name VARCHAR(50),last_name VARCHAR(50),specialty VARCHAR(50),city VARCHAR(50),state VARCHAR(2)); CREATE TABLE patients (patient_id INT,provider_id INT,first_name VARCHAR(50),last_name VARCHAR(50),city VARCHAR(50),state VARCHAR(2),mental_health_score INT); CREATE TABLE mental_health_scores (score_id INT,patient_id INT,mental_health_score INT);
SELECT p.first_name, p.last_name, p.city, AVG(m.mental_health_score) AS avg_score, COUNT(pa.patient_id) AS patient_count FROM providers p JOIN patients pa ON p.provider_id = pa.provider_id JOIN mental_health_scores m ON pa.patient_id = m.patient_id WHERE p.specialty LIKE '%therapist%' AND p.city = 'New York' AND p.state = 'NY' GROUP BY p.provider_id, p.first_name, p.last_name, p.city ORDER BY avg_score DESC;
What is the count of community development initiatives in Country A?
CREATE TABLE rural_communities (id INT,community_name VARCHAR(255),location VARCHAR(255),country VARCHAR(255),initiative_type VARCHAR(255),start_date DATE,end_date DATE); INSERT INTO rural_communities (id,community_name,location,country,initiative_type,start_date,end_date) VALUES (1,'Community A','Village B,Country A','Country A','Community Development','2019-01-01','2023-12-31');
SELECT COUNT(*) FROM rural_communities WHERE country = 'Country A' AND initiative_type = 'Community Development';
How many tournaments have taken place per month in the last year?
CREATE TABLE monthly_tournaments (id INT,year INT,month INT,tournaments INT); INSERT INTO monthly_tournaments (id,year,month,tournaments) VALUES (1,2022,1,3),(2,2022,2,2),(3,2022,3,4);
SELECT TO_CHAR(DATE '2022-01-01' + INTERVAL month MONTH, 'Month YYYY') AS month_year, SUM(tournaments) OVER (ORDER BY DATE '2022-01-01' + INTERVAL month MONTH RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS total_tournaments FROM monthly_tournaments;