instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
How many employees were hired in Q1 2022 from underrepresented communities?
CREATE TABLE Hiring (HireID INT,EmployeeID INT,HireDate DATE,Community VARCHAR(50)); INSERT INTO Hiring (HireID,EmployeeID,HireDate,Community) VALUES (1,5,'2022-01-15','LatinX'),(2,6,'2022-02-20','African American'),(3,7,'2022-03-05','LGBTQ+'),(4,8,'2022-04-12','Women in STEM');
SELECT COUNT(*) FROM Hiring WHERE QUARTER(HireDate) = 1 AND YEAR(HireDate) = 2022 AND Community IN ('LatinX', 'African American', 'LGBTQ+', 'Women in STEM');
Display the daily production rate for Well005
CREATE TABLE wells (id INT,well_name VARCHAR(255),location VARCHAR(255),drill_year INT,company VARCHAR(255),daily_production_rate DECIMAL(5,2)); INSERT INTO wells (id,well_name,location,drill_year,company,daily_production_rate) VALUES (1,'Well001','Gulf of Mexico',2020,'CompanyA',100.50); INSERT INTO wells (id,well_name,location,drill_year,company,daily_production_rate) VALUES (2,'Well002','North Sea',2019,'CompanyB',150.25); INSERT INTO wells (id,well_name,location,drill_year,company,daily_production_rate) VALUES (3,'Well003','Brazil',2019,'CompanyC',200.00); INSERT INTO wells (id,well_name,location,drill_year,company,daily_production_rate) VALUES (4,'Well004','Gulf of Mexico',2018,'CompanyX',175.25); INSERT INTO wells (id,well_name,location,drill_year,company,daily_production_rate) VALUES (5,'Well005','South China Sea',2020,'CompanyY',120.00);
SELECT daily_production_rate FROM wells WHERE well_name = 'Well005';
Which countries donated the most in 2019?
CREATE TABLE donors (id INT,name TEXT,country TEXT,amount_donated DECIMAL(10,2)); INSERT INTO donors
SELECT country, SUM(amount_donated) FROM donors WHERE year = 2019 GROUP BY country ORDER BY SUM(amount_donated) DESC LIMIT 3;
What is the difference between the number of AI projects in the US and the number of AI projects in the EU?
CREATE SCHEMA if not exists ai_projects; CREATE TABLE if not exists ai_projects.projects (id INT PRIMARY KEY,project_name VARCHAR(255),location VARCHAR(255)); INSERT INTO ai_projects.projects (id,project_name,location) VALUES (1,'AI Project 1','USA'),(2,'AI Project 2','USA'),(3,'AI Project 3','EU'),(4,'AI Project 4','EU');
SELECT COUNT(*) - (SELECT COUNT(*) FROM ai_projects.projects WHERE location = 'EU') as diff FROM ai_projects.projects WHERE location = 'USA';
Which subway line in Seoul has the highest ridership?
CREATE TABLE subway (line_id INT,city VARCHAR(50),daily_ridership INT); INSERT INTO subway (line_id,city,daily_ridership) VALUES (1,'Seoul',300000),(2,'Seoul',450000),(3,'Tokyo',500000),(4,'Tokyo',600000);
SELECT line_id, city, daily_ridership FROM (SELECT line_id, city, daily_ridership, RANK() OVER (PARTITION BY city ORDER BY daily_ridership DESC) as rnk FROM subway) tmp WHERE rnk = 1 AND city = 'Seoul';
How many fair-trade certified garment factories are in Asia?
CREATE TABLE garment_factories (id INT,certification VARCHAR(20),region VARCHAR(20)); INSERT INTO garment_factories (id,certification,region) VALUES (1,'Fair Trade','China'),(2,'GOTS','India'),(3,'Fair Trade','Vietnam');
SELECT COUNT(*) FROM garment_factories WHERE certification = 'Fair Trade' AND region = 'Asia';
Identify the total revenue generated from circular economy practices in the year 2021 in the 'EthicalFashion' database
CREATE TABLE sales_2021 (sale_id INT,item_id INT,sale_price DECIMAL(10,2),is_circular_economy BOOLEAN,sale_date DATE);
SELECT SUM(sale_price) FROM sales_2021 WHERE is_circular_economy = TRUE AND YEAR(sale_date) = 2021;
What is the total number of labor violations reported for each production facility?
CREATE TABLE Facility_Violations (violation_id INT,facility_id INT,violation_date DATE);
SELECT Facility_Violations.facility_id, COUNT(*) as total_violations FROM Facility_Violations GROUP BY Facility_Violations.facility_id;
Which countries have the highest average donation amount?
CREATE TABLE donations (id INT,donor_name VARCHAR,country VARCHAR,amount DECIMAL); INSERT INTO donations (id,donor_name,country,amount) VALUES (1,'John Doe','USA',100.00),(2,'Jane Smith','Canada',150.00);
SELECT country, AVG(amount) as avg_donation FROM donations GROUP BY country ORDER BY avg_donation DESC;
Find the supplier with the lowest average delivery time for orders in the last month.
CREATE TABLE Suppliers (SupplierID int,SupplierName varchar(50)); CREATE TABLE Products (ProductID int,ProductName varchar(50),SupplierID int); CREATE TABLE Orders (OrderID int,ProductID int,OrderDate date,DeliveryTime int); INSERT INTO Suppliers VALUES (1,'SupplierA'),(2,'SupplierB'); INSERT INTO Products VALUES (1,'Organic Apples',1),(2,'Bananas',2); INSERT INTO Orders VALUES (1,1,'2022-01-01',2),(2,2,'2022-01-03',3);
SELECT SupplierName, AVG(DeliveryTime) as AvgDeliveryTime FROM Orders o JOIN Products p ON o.ProductID = p.ProductID JOIN Suppliers sp ON p.SupplierID = sp.SupplierID WHERE OrderDate >= DATEADD(month, -1, GETDATE()) GROUP BY SupplierName ORDER BY AvgDeliveryTime ASC;
What is the average package weight shipped from each warehouse, excluding shipments over 80 kg?
CREATE TABLE warehouse (id INT,location VARCHAR(255)); INSERT INTO warehouse (id,location) VALUES (1,'Mumbai'),(2,'Delhi'); CREATE TABLE packages (id INT,warehouse_id INT,weight FLOAT); INSERT INTO packages (id,warehouse_id,weight) VALUES (1,1,50.3),(2,1,30.1),(3,2,70.0),(4,2,85.0);
SELECT warehouse_id, AVG(weight) as avg_weight FROM packages WHERE weight < 80 GROUP BY warehouse_id;
Calculate the average funding received by biotech startups in each country.
CREATE SCHEMA if not exists biotech;CREATE TABLE if not exists biotech.startups(id INT,name TEXT,location TEXT,funding FLOAT);INSERT INTO biotech.startups (id,name,location,funding) VALUES (1,'StartupA','US',5000000),(2,'StartupB','UK',3000000),(3,'StartupC','UK',4000000),(4,'StartupD','Germany',6000000);
SELECT location, AVG(funding) FROM biotech.startups GROUP BY location;
How many public schools are there in each state?
CREATE TABLE schools (id INT,school_name VARCHAR(50),state VARCHAR(50)); INSERT INTO schools (id,school_name,state) VALUES (1,'School A','California'),(2,'School B','California'),(3,'School C','Texas');
SELECT state, COUNT(*) as school_count FROM schools GROUP BY state;
Find cities with no renewable energy projects
CREATE TABLE city_renewable_projects (city VARCHAR(50),project_type VARCHAR(50),PRIMARY KEY (city,project_type));
SELECT city FROM city_renewable_projects WHERE city NOT IN (SELECT city FROM renewable_projects GROUP BY city);
Which health equity metrics have been collected for patients in the 'rural' region?
CREATE TABLE HealthEquityMetrics (Patient_ID INT,Metric_Name VARCHAR(50),Metric_Value FLOAT,Region VARCHAR(50)); INSERT INTO HealthEquityMetrics (Patient_ID,Metric_Name,Metric_Value,Region) VALUES (1,'Income',30000,'rural'); INSERT INTO HealthEquityMetrics (Patient_ID,Metric_Name,Metric_Value,Region) VALUES (2,'Education',8,'rural');
SELECT Metric_Name, Metric_Value FROM HealthEquityMetrics WHERE Region = 'rural';
How many local businesses in Madrid offer virtual experiences?
CREATE TABLE local_businesses (business_id INT,city TEXT,virtual_experience BOOLEAN); INSERT INTO local_businesses (business_id,city,virtual_experience) VALUES (1,'Madrid',true),(2,'Madrid',false);
SELECT COUNT(*) FROM local_businesses WHERE city = 'Madrid' AND virtual_experience = true;
List all sustainable tourism initiatives in Canada and their respective number of participants.
CREATE TABLE initiatives (initiative_id INT,name TEXT,country TEXT); CREATE TABLE participants (initiative_id INT,participant_id INT); INSERT INTO initiatives VALUES (1,'Green Trails','Canada'),(2,'Eco-friendly Cruises','Canada'); INSERT INTO participants VALUES (1,1),(1,2),(2,3),(2,4),(2,5);
SELECT initiatives.name, COUNT(participants.participant_id) FROM initiatives INNER JOIN participants ON initiatives.initiative_id = participants.initiative_id WHERE country = 'Canada' GROUP BY initiatives.name;
What is the percentage of hotels adopting 'AI chatbots' in 'Berlin'?
CREATE TABLE Adoption (hotel_id INT,city TEXT,ai_chatbot BOOLEAN); INSERT INTO Adoption (hotel_id,city,ai_chatbot) VALUES (1,'Berlin',TRUE),(2,'Berlin',TRUE),(3,'Berlin',FALSE);
SELECT 100.0 * SUM(ai_chatbot) / COUNT(*) FROM Adoption WHERE city = 'Berlin';
How many Indigenous communities in the Arctic are experiencing negative socio-economic impacts due to climate change?
CREATE TABLE IndigenousCommunities(community TEXT,socio_economic_impact TEXT,climate_change_impact TEXT); INSERT INTO IndigenousCommunities(community,socio_economic_impact,climate_change_impact) VALUES ('Inuit','High','Very High'),('Sami','Medium','High');
SELECT COUNT(*) FROM IndigenousCommunities WHERE socio_economic_impact = 'High' AND climate_change_impact = 'High' OR socio_economic_impact = 'Very High' AND climate_change_impact = 'Very High';
What is the age distribution of traditional artists in India?
CREATE TABLE traditional_artists (id INT PRIMARY KEY,name TEXT,age INT,art_form TEXT,country TEXT);
WITH age_groups AS (VALUES (0, 20), (21, 40), (41, 60), (61, 120)) SELECT art_form, SUM(CASE WHEN age >= age_groups.col1 AND age < age_groups.col2 THEN 1 ELSE 0 END) AS artist_count FROM traditional_artists, age_groups WHERE country = 'India' GROUP BY art_form;
What is the success rate of therapy sessions per region?
CREATE TABLE therapy_sessions_outcomes (session_id INT,outcome CHAR(1),region VARCHAR(20)); INSERT INTO therapy_sessions_outcomes (session_id,outcome,region) VALUES (1,'Y','Asia'),(2,'N','Europe'),(3,'Y','America');
SELECT region, AVG(CASE WHEN outcome = 'Y' THEN 1.0 ELSE 0.0 END) as success_rate FROM therapy_sessions_outcomes GROUP BY region;
What is the total number of lanes for all highways in the database?
CREATE TABLE Highways (id INT,name VARCHAR(100),lanes INT); INSERT INTO Highways (id,name,lanes) VALUES (1,'I-10',6),(2,'I-20',4),(3,'I-35',8);
SELECT SUM(lanes) FROM Highways;
Which infrastructure projects in 'London' have a budget greater than $2,000,000?
CREATE TABLE InfrastructureD(id INT,city VARCHAR(20),project VARCHAR(30),budget DECIMAL(10,2)); INSERT INTO InfrastructureD(id,city,project,budget) VALUES (1,'London','Tunnel Construction',2500000.00),(2,'Rome','Railway Upgrade',1000000.00);
SELECT city, project, budget FROM InfrastructureD WHERE budget > 2000000.00 AND city = 'London';
Which destinations have travel advisories in South America?
CREATE TABLE countries (name VARCHAR(50)); CREATE TABLE travel_advisories (country VARCHAR(50),advisory VARCHAR(100)); INSERT INTO countries (name) VALUES ('Argentina'),('Brazil'),('Colombia'),('Peru'),('Ecuador'); INSERT INTO travel_advisories (country,advisory) VALUES ('Brazil','Avoid non-essential travel'),('Venezuela','Do not travel');
SELECT countries.name FROM countries LEFT JOIN travel_advisories ON countries.name = travel_advisories.country WHERE travel_advisories.advisory IS NOT NULL AND countries.name NOT IN ('Venezuela');
What is the total number of cases in the 'Criminal_Justice_Reform' category in the last 6 months?
CREATE TABLE cases (id INT,category VARCHAR(20),date DATE); INSERT INTO cases (id,category,date) VALUES (1,'Restorative_Justice','2022-01-01'),(2,'Access_to_Justice','2021-12-15'),(3,'Criminal_Justice_Reform','2022-02-10'),(4,'Legal_Technology','2021-11-05'),(5,'Criminal_Justice_Reform','2022-03-01'),(6,'Criminal_Justice_Reform','2022-04-15');
SELECT COUNT(*) FROM cases WHERE category = 'Criminal_Justice_Reform' AND date >= DATEADD(month, -6, GETDATE());
List all the unique ports and countries where oil spills have occurred in the last 5 years.
CREATE TABLE oil_spills (id INT,port VARCHAR(30),country VARCHAR(30),date DATE); INSERT INTO oil_spills (id,port,country,date) VALUES (1,'Port of Los Angeles','USA','2020-01-01'); INSERT INTO oil_spills (id,port,country,date) VALUES (2,'Port of Rotterdam','Netherlands','2019-08-15');
SELECT DISTINCT port, country FROM oil_spills WHERE date >= DATE_SUB(CURRENT_DATE, INTERVAL 5 YEAR);
Update the 'MarineLife' table to include the endangered status for all species
CREATE TABLE MarineLife (id INT,species VARCHAR(50),population INT,last_sighting DATE,endangered BOOLEAN); INSERT INTO MarineLife (id,species,population,last_sighting,endangered) VALUES (1,'Shark',500,'2019-01-01',FALSE),(2,'Starfish',3000,'2020-05-15',FALSE),(3,'Jellyfish',1500,'2018-12-27',FALSE);
UPDATE MarineLife SET endangered = TRUE WHERE id IN (SELECT id FROM (SELECT MAX(id) FROM MarineLife) AS max_id);
What is the average word count for articles published on the "politics" section in 2019?
CREATE TABLE article_text (id INT,article_id INT,text TEXT); CREATE VIEW article_summary AS SELECT a.id,a.title,a.section,a.publish_date,COUNT(at.word) as word_count FROM website_articles a JOIN article_text at ON a.id = at.article_id GROUP BY a.id;
SELECT AVG(word_count) FROM article_summary WHERE section = 'politics' AND publish_date BETWEEN '2019-01-01' AND '2019-12-31';
Find the earliest start date for defense projects in the 'Asia-Pacific' region.
CREATE TABLE DefenseProjects (project_id INT,project_name VARCHAR(255),region VARCHAR(255),start_date DATE,end_date DATE); INSERT INTO DefenseProjects (project_id,project_name,region,start_date,end_date) VALUES (1,'Project X','Asia-Pacific','2022-02-01','2023-01-31'),(2,'Project Y','Europe','2021-06-15','2022-05-31'),(3,'Project Z','Asia-Pacific','2024-04-01','2025-03-31');
SELECT MIN(start_date) AS min_start_date FROM DefenseProjects WHERE region = 'Asia-Pacific';
Insert a new defense project timeline with Thailand, 'Type 16 MCV', '2022-04-01', '2024-04-01'.
CREATE TABLE DefenseProjectTimelines (id INT PRIMARY KEY,project_name VARCHAR(50),negotiation_start_date DATE,negotiation_end_date DATE,country VARCHAR(50));
INSERT INTO DefenseProjectTimelines (project_name, negotiation_start_date, negotiation_end_date, country) VALUES ('Type 16 MCV', '2022-04-01', '2024-04-01', 'Thailand');
Identify the mine with the greatest total CO2 emissions in 2020.
CREATE TABLE Emission_Statistics (Mine_Name VARCHAR(50),CO2_Emissions FLOAT,Year INT); INSERT INTO Emission_Statistics (Mine_Name,CO2_Emissions,Year) VALUES ('Topaz Tops',1200.0,2020),('Moonstone Mines',1400.5,2020),('Jade Jamboree',1100.2,2020);
SELECT Mine_Name FROM Emission_Statistics WHERE Year = 2020 GROUP BY Mine_Name ORDER BY SUM(CO2_Emissions) DESC LIMIT 1;
Update labor_stats table to set 'total_employees' to 250 for 'site_id' 004
CREATE TABLE labor_stats (site_id VARCHAR(10) PRIMARY KEY,total_employees INT,turnover_rate DECIMAL(5,2));
UPDATE labor_stats SET total_employees = 250 WHERE site_id = '004';
What is the total quantity of copper extracted by each company?
CREATE TABLE company (id INT,name VARCHAR(50));CREATE TABLE extraction (company_id INT,mineral VARCHAR(10),quantity INT); INSERT INTO company (id,name) VALUES (1,'XYZ Ltd'),(2,'ABC Pvt Ltd'); INSERT INTO extraction (company_id,mineral,quantity) VALUES (1,'gold',400),(1,'copper',600),(2,'copper',750),(2,'zinc',850);
SELECT e.company_id, c.name, SUM(e.quantity) AS total_copper_quantity FROM extraction e JOIN company c ON e.company_id = c.id WHERE e.mineral = 'copper' GROUP BY e.company_id, c.name;
What is the average monthly cost of mobile plans for the 'Rural' area in the 'North' region?
CREATE TABLE network_investments (investment_id INT,region VARCHAR(255),area VARCHAR(255),investment_amount DECIMAL(10,2),investment_date DATE); CREATE TABLE mobile_plans (plan_id INT,plan_name VARCHAR(255),company_name VARCHAR(255),data_limit INT,monthly_cost DECIMAL(10,2)); INSERT INTO network_investments (investment_id,region,area,investment_amount,investment_date) VALUES (1,'North','Rural',50000,'2022-01-01'); INSERT INTO mobile_plans (plan_id,plan_name,company_name,data_limit,monthly_cost) VALUES (1,'Basic','Telco Inc.',1000,50.00),(2,'Premium','Telco Inc.',5000,100.00);
SELECT AVG(monthly_cost) FROM mobile_plans JOIN network_investments ON 1=1 WHERE region = 'North' AND area = 'Rural';
Calculate the average revenue per concert for artists who have held at least three concerts.
CREATE TABLE concerts (concert_id INT,artist_id INT,city VARCHAR(50),revenue DECIMAL(10,2)); INSERT INTO concerts (concert_id,artist_id,city,revenue) VALUES (1,101,'Los Angeles',50000.00),(2,102,'New York',75000.00),(3,101,'Chicago',60000.00),(4,101,'San Francisco',80000.00),(5,103,'Toronto',40000.00);
SELECT artist_id, AVG(revenue) AS avg_revenue_per_concert FROM (SELECT artist_id, revenue, ROW_NUMBER() OVER (PARTITION BY artist_id ORDER BY concert_id) AS rn FROM concerts) t WHERE rn >= 3 GROUP BY artist_id;
Get the average age of subscribers who prefer 'Politics' from each country.
CREATE TABLE subscribers (id INT,age INT,country TEXT,interest TEXT);
SELECT country, AVG(age) AS avg_age FROM subscribers WHERE interest = 'Politics' GROUP BY country;
What is the maximum donation amount given in the year 2022?
CREATE TABLE donations (donation_id INT,donation_date DATE,donation_amount FLOAT); INSERT INTO donations (donation_id,donation_date,donation_amount) VALUES (1,'2022-01-01',25000.00),(2,'2022-02-01',30000.00);
SELECT MAX(donation_amount) FROM donations WHERE YEAR(donation_date) = 2022;
What is the minimum donation amount in the 'Donations' table for each month in 2021?
CREATE TABLE Donations (DonationID INT,DonorID INT,DonationAmount DECIMAL(10,2),DonationDate DATE);
SELECT DATE_FORMAT(DonationDate, '%Y-%m') AS Month, MIN(DonationAmount) FROM Donations WHERE YEAR(DonationDate) = 2021 GROUP BY Month;
Identify the number of marine protected areas in the Arctic region?
CREATE TABLE marine_protected_areas (area_name TEXT,region TEXT); INSERT INTO marine_protected_areas (area_name,region) VALUES ('North Pole','Arctic'),('Franz Josef Land','Arctic');
SELECT COUNT(*) FROM marine_protected_areas WHERE region = 'Arctic';
Insert records for new affordable housing units in Dallas and Houston.
CREATE TABLE AffordableHousing (UnitID INT,City VARCHAR(50),OccupancyRate DECIMAL(4,2));
INSERT INTO AffordableHousing (UnitID, City, OccupancyRate) VALUES (4, 'Dallas', 0.85), (5, 'Houston', 0.92);
What is the maximum property price in neighborhoods with inclusive housing policies, and the minimum size of properties in those neighborhoods?
CREATE TABLE property (id INT,price INT,size_sqft INT,area VARCHAR(255),has_inclusive_policy BOOLEAN); INSERT INTO property (id,price,size_sqft,area,has_inclusive_policy) VALUES (1,500000,1500,'urban',true),(2,400000,1200,'urban',false);
SELECT MAX(price), MIN(size_sqft) FROM property WHERE area = 'urban' AND has_inclusive_policy = true;
Calculate the total mass of all satellites in low Earth orbit (LEO) and geostationary orbit (GEO), and show the percentage of mass in each orbit type.
CREATE TABLE Satellite_Orbits (id INT,satellite_name VARCHAR(255),orbit_type VARCHAR(255),mass FLOAT);
SELECT orbit_type, SUM(mass) as total_mass, (SUM(mass) / (SELECT SUM(mass) FROM Satellite_Orbits) * 100) as percentage FROM Satellite_Orbits WHERE orbit_type IN ('LEO', 'GEO') GROUP BY orbit_type;
What is the average cost of Mars missions?
CREATE TABLE mars_missions (id INT,name VARCHAR(50),cost INT); INSERT INTO mars_missions (id,name,cost) VALUES (1,'Mars Rover 2001',2500000),(2,'Mars Rover 2010',3000000),(3,'Mars Orbiter 2020',2000000000);
SELECT AVG(cost) FROM mars_missions WHERE name LIKE '%Mars%';
What is the average mass of spacecrafts manufactured by Galactic Innovations?
CREATE TABLE Spacecrafts (id INT,name VARCHAR(100),manufacturer VARCHAR(100),mass FLOAT,launched BOOLEAN); INSERT INTO Spacecrafts (id,name,manufacturer,mass,launched) VALUES (1,'GalacticShip 1','Galactic Innovations',500,true),(2,'GalacticShip 2','Galactic Innovations',800,false);
SELECT AVG(mass) FROM Spacecrafts WHERE manufacturer = 'Galactic Innovations';
What is the average number of wins per season for each coach?
CREATE TABLE Coaches (CoachID INT,CoachName VARCHAR(50),TeamID INT,SeasonYear INT,Wins INT); INSERT INTO Coaches VALUES (1,'Coach1',1,2020,85),(2,'Coach1',1,2019,80),(3,'Coach2',2,2020,90),(4,'Coach2',2,2019,95);
SELECT CoachID, AVG(Wins) AS AvgWinsPerSeason FROM Coaches GROUP BY CoachID;
What is the minimum number of passengers for shared autonomous vehicles in District 3?
CREATE TABLE shared_autonomous_vehicles (vehicle_id INT,passengers INT,district INT); INSERT INTO shared_autonomous_vehicles (vehicle_id,passengers,district) VALUES (301,6,3),(302,4,3),(303,7,4);
SELECT MIN(passengers) FROM shared_autonomous_vehicles WHERE district = 3;
What is the total number of hybrid vehicles in the 'vehicle_data' table, grouped by their 'vehicle_type'?
CREATE TABLE vehicle_data (id INT PRIMARY KEY,make VARCHAR(50),model VARCHAR(50),vehicle_type VARCHAR(50),is_ev BOOLEAN,is_hybrid BOOLEAN,registration_date DATE); INSERT INTO vehicle_data (id,make,model,vehicle_type,is_ev,is_hybrid,registration_date) VALUES (1,'Toyota','Corolla Hybrid','Sedan',false,true,'2021-06-10'); INSERT INTO vehicle_data (id,make,model,vehicle_type,is_ev,is_hybrid,registration_date) VALUES (2,'Honda','Civic Hybrid','Sedan',false,true,'2021-07-12');
SELECT vehicle_type, COUNT(*) FROM vehicle_data WHERE is_hybrid = true GROUP BY vehicle_type;
How many members are there in the 'construction_union' table?
CREATE TABLE construction_union (member_id INT,union_name VARCHAR(20)); INSERT INTO construction_union (member_id,union_name) VALUES (1,'United Union of Construction Workers'),(2,'Construction Brotherhood'),(3,'Laborers International Union');
SELECT COUNT(*) FROM construction_union;
What is the number of employees in each industry, categorized by union status?
CREATE TABLE employees (id INT,name VARCHAR(255),industry VARCHAR(255),union_status VARCHAR(255),num_employees INT); INSERT INTO employees (id,name,industry,union_status,num_employees) VALUES (1,'John Doe','Manufacturing','Union',50),(2,'Jane Smith','Manufacturing','Non-Union',75),(3,'Bob Johnson','Retail','Union',30),(4,'Alice Williams','Retail','Union',40),(5,'Charlie Brown','Construction','Non-Union',100);
SELECT industry, union_status, SUM(num_employees) as 'Total Employees' FROM employees GROUP BY industry, union_status;
What is the total number of workers represented by labor unions in the healthcare industry?
CREATE TABLE unions (id INT,name TEXT,industry TEXT); INSERT INTO unions (id,name,industry) VALUES (1,'National Nurses United','Healthcare'),(2,'SEIU','Healthcare'),(3,'AFSCME','Public Service');
SELECT SUM(workers_represented) FROM unions WHERE industry = 'Healthcare';
What is the maximum speed of the Tesla Model S?
CREATE TABLE vehicle_specs (make VARCHAR(255),model VARCHAR(255),max_speed INT); INSERT INTO vehicle_specs (make,model,max_speed) VALUES ('Tesla','Model S',200),('Tesla','Model 3',140);
SELECT max_speed FROM vehicle_specs WHERE make = 'Tesla' AND model = 'Model S';
What is the number of hybrid vehicles produced each year since 2010 in the 'production_stats' table?
CREATE TABLE production_stats (make VARCHAR(50),model VARCHAR(50),year INT,vehicle_type VARCHAR(50),quantity INT);
SELECT year, SUM(quantity) FROM production_stats WHERE vehicle_type = 'hybrid' AND year >= 2010 GROUP BY year;
Insert records for waste generation metrics
CREATE TABLE waste_generation_metrics (id INT PRIMARY KEY,region VARCHAR(255),total_waste_generated FLOAT,recycled_waste FLOAT,landfilled_waste FLOAT); INSERT INTO waste_generation_metrics (id,region,total_waste_generated,recycled_waste,landfilled_waste) VALUES (1,'North America',50000000,25000000,20000000),(2,'Europe',40000000,30000000,5000000),(3,'Asia',70000000,40000000,25000000);
INSERT INTO waste_generation_metrics (id, region, total_waste_generated, recycled_waste, landfilled_waste) VALUES (1, 'North America', 50000000, 25000000, 20000000), (2, 'Europe', 40000000, 30000000, 5000000), (3, 'Asia', 70000000, 40000000, 25000000);
Calculate the total water usage in cubic meters for each month in the year 2020
CREATE TABLE water_usage_by_month (year INT,month INT,usage FLOAT); INSERT INTO water_usage_by_month (year,month,usage) VALUES (2020,1,289.56),(2020,2,301.23),(2020,3,345.78),(2020,4,299.67),(2020,5,456.34),(2020,6,500.89),(2020,7,567.89),(2020,8,434.56),(2020,9,356.78),(2020,10,444.45),(2020,11,600.11),(2020,12,700.22);
SELECT EXTRACT(MONTH FROM date) AS month, SUM(usage) FROM water_usage_by_month WHERE year = 2020 GROUP BY month;
Show the total water usage for each location and year
CREATE TABLE water_usage (location VARCHAR(255),year INT,usage INT);
SELECT location, year, SUM(usage) as total_usage FROM water_usage GROUP BY location, year;
Update the operational status of the wastewater_facilities table to 'Under Maintenance' for the 'Screening Facility' in the 'Southeast' region
CREATE TABLE wastewater_facilities (id INT PRIMARY KEY,name VARCHAR(50),facility_type VARCHAR(50),region VARCHAR(20),capacity_bod INT,operational_status VARCHAR(20)); INSERT INTO wastewater_facilities (id,name,facility_type,region,capacity_bod,operational_status) VALUES (1,'Facility A','Sewage Treatment Plant','Northeast',500000,'Operational'),(2,'Facility B','Screening Facility','Southeast',250000,'Operational'),(3,'Facility C','Sewage Treatment Plant','Midwest',750000,'Operational');
UPDATE wastewater_facilities SET operational_status = 'Under Maintenance' WHERE name = 'Facility B' AND region = 'Southeast';
What is the total distance covered by users wearing shoe brand X?
CREATE TABLE shoe_usage (id INT,user_id INT,distance FLOAT,shoe_brand VARCHAR(20)); INSERT INTO shoe_usage (id,user_id,distance,shoe_brand) VALUES (1,1,5.0,'Nike'),(2,2,7.0,'Adidas'),(3,3,6.0,'Nike');
SELECT SUM(distance) FROM shoe_usage WHERE shoe_brand = 'Nike';
What is the most recent launch date for satellites manufactured by Indian Space Research Organisation (ISRO)?
CREATE TABLE Satellite (id INT,name VARCHAR(255),manufacturer_id INT,launch_date DATE); INSERT INTO Satellite (id,name,manufacturer_id,launch_date) VALUES (1,'GOES-R',1,'2016-11-19'); INSERT INTO Satellite (id,name,manufacturer_id,launch_date) VALUES (2,'Sentinel-2B',2,'2017-03-07'); INSERT INTO Satellite (id,name,manufacturer_id,launch_date) VALUES (3,'GSAT-19',3,'2017-06-28');
SELECT MAX(launch_date) FROM Satellite WHERE manufacturer_id = (SELECT id FROM Manufacturer WHERE name = 'Indian Space Research Organisation');
What is the average ph level in saltwater aquaculture facilities in the North Atlantic region?
CREATE TABLE saltwater_aquaculture (id INT,name TEXT,location TEXT,ph FLOAT); INSERT INTO saltwater_aquaculture (id,name,location,ph) VALUES (1,'Facility A','North Atlantic',8.1),(2,'Facility B','North Atlantic',7.9),(3,'Facility C','Indian Ocean',8.3);
SELECT AVG(ph) FROM saltwater_aquaculture WHERE location = 'North Atlantic';
What is the maximum dissolved oxygen level by region and month?
CREATE TABLE Region (id INT PRIMARY KEY,name VARCHAR(50)); CREATE TABLE DissolvedOxygen (region_id INT,date DATE,level DECIMAL(5,2),FOREIGN KEY (region_id) REFERENCES Region(id));
SELECT Region.name, DATE_FORMAT(DissolvedOxygen.date, '%Y-%m') AS month, MAX(DissolvedOxygen.level) FROM Region INNER JOIN DissolvedOxygen ON Region.id = DissolvedOxygen.region_id GROUP BY Region.name, month;
Add a new sustainable practice to the SustainablePractices table for a specific project.
CREATE TABLE SustainablePractices (PracticeID INT,PracticeName VARCHAR(50),Description VARCHAR(255),ProjectID INT,FOREIGN KEY (ProjectID) REFERENCES Projects(ProjectID));
INSERT INTO SustainablePractices (PracticeID, PracticeName, Description, ProjectID) VALUES (3, 'Rainwater Harvesting', 'Collection and usage of rainwater', 3);
List all building permits issued for residential buildings in the state of Texas and Washington.
CREATE TABLE permit (id INT,state VARCHAR(20),type VARCHAR(20),permit_number INT); INSERT INTO permit (id,state,type,permit_number) VALUES (1,'Washington','Commercial',100),(2,'Washington','Residential',150),(3,'California','Commercial',80),(4,'Texas','Residential',200);
SELECT permit_number FROM permit WHERE (state = 'Texas' OR state = 'Washington') AND type = 'Residential';
What is the average price per gram of concentrate sold by Dispensary X?
CREATE TABLE dispensary (id INT,name VARCHAR(255),product VARCHAR(255),price FLOAT,quantity INT); INSERT INTO dispensary (id,name,product,price,quantity) VALUES (1,'Dispensary X','Concentrate',12.5,100);
SELECT AVG(price / 1000) FROM dispensary WHERE name = 'Dispensary X' AND product = 'Concentrate';
Show the maximum billing amount for any case
CREATE TABLE cases (case_id INT,billing_amount INT); INSERT INTO cases (case_id,billing_amount) VALUES (1,5000),(2,7000);
SELECT MAX(billing_amount) FROM cases;
What is the average pro-bono hours per week for each attorney in the 'probono_billing' table?
CREATE TABLE attorney (attorney_id INT,name TEXT,join_date DATE); INSERT INTO attorney (attorney_id,name,join_date) VALUES (4,'Alex Garcia','2019-01-02'),(5,'Dana Stewart','2020-02-15'),(6,'Elias Kim','2018-03-20'); CREATE TABLE probono_billing (attorney_id INT,client_id INT,hours FLOAT,billing_date DATE); INSERT INTO probono_billing (attorney_id,client_id,hours,billing_date) VALUES (4,104,15,'2022-01-01'),(5,105,20,'2022-01-08'),(6,106,18,'2022-01-15');
SELECT attorney_id, AVG(hours / 7) FROM probono_billing JOIN attorney ON probono_billing.attorney_id = attorney.attorney_id GROUP BY attorney_id;
What is the number of reported infectious disease cases in African countries in the past year?
CREATE TABLE infectious_diseases (id INT,country TEXT,date TEXT,cases INT); INSERT INTO infectious_diseases (id,country,date,cases) VALUES (1,'Nigeria','2021-01-01',100),(2,'Egypt','2021-02-02',50),(3,'South Africa','2021-03-03',75),(4,'Nigeria','2021-04-04',120),(5,'Egypt','2021-05-05',60),(6,'South Africa','2021-06-06',80),(7,'Nigeria','2022-01-01',110),(8,'Egypt','2022-02-02',65),(9,'South Africa','2022-03-03',90);
SELECT country, COUNT(*) FROM infectious_diseases WHERE country IN ('Nigeria', 'Egypt', 'South Africa') AND date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR) GROUP BY country;
List the names of the top 5 most funded startups founded by underrepresented minority founders?
CREATE TABLE companies (id INT,name TEXT,founder_race TEXT);CREATE TABLE funding_rounds (company_id INT,funding_amount INT);
SELECT c.name FROM companies c JOIN (SELECT company_id, SUM(funding_amount) as total_funding FROM funding_rounds fr GROUP BY company_id ORDER BY total_funding DESC LIMIT 5) f ON c.id = f.company_id WHERE c.founder_race IN ('African American', 'Hispanic', 'Native American', 'Pacific Islander');
Display the names of companies founded by individuals who identify as Black and have raised Seed or Series A funding.
CREATE TABLE startup (id INT,name TEXT,founder_identity TEXT,funding TEXT); INSERT INTO startup (id,name,founder_identity,funding) VALUES (1,'TechCo','Black Female','Seed'),(2,'InnovateIT','Black Male','Series A'),(3,'GreenSolutions','White Male','Seed'),(4,'DataDriven','Asian Female','Series B');
SELECT name FROM startup WHERE founder_identity LIKE 'Black%' AND funding IN ('Seed', 'Series A');
List the agroecology farmers' details and their offered produce in African regions.
CREATE TABLE Agroecology_Farmers (id INT PRIMARY KEY,name VARCHAR(50),age INT,location VARCHAR(50),sustainable_practices BOOLEAN); INSERT INTO Agroecology_Farmers (id,name,age,location,sustainable_practices) VALUES (1,'Mariam Diop',45,'Senegalese Savannah',true); INSERT INTO Agroecology_Farmers (id,name,age,location,sustainable_practices) VALUES (2,'Moses Owino',50,'Kenyan Highlands',true); CREATE TABLE Agroecology_Produce (id INT PRIMARY KEY,product_name VARCHAR(50),price DECIMAL(5,2),farmer_id INT,location VARCHAR(50)); INSERT INTO Agroecology_Produce (id,product_name,price,farmer_id,location) VALUES (1,'Millet',0.50,1,'Senegalese Savannah'); INSERT INTO Agroecology_Produce (id,product_name,price,farmer_id,location) VALUES (2,'Tea',1.00,2,'Kenyan Highlands');
SELECT af.name, af.location, ap.product_name, ap.price FROM Agroecology_Farmers af INNER JOIN Agroecology_Produce ap ON af.id = ap.farmer_id WHERE af.location IN ('Senegalese Savannah', 'Kenyan Highlands');
What is the total yield of organic crops in California and Texas in 2020?
CREATE TABLE organic_farms (id INT,state VARCHAR(2),year INT,yield INT); INSERT INTO organic_farms (id,state,year,yield) VALUES (1,'CA',2020,1500),(2,'TX',2020,1200);
SELECT SUM(yield) FROM organic_farms WHERE state IN ('CA', 'TX') AND year = 2020;
How many wheelchair accessible spaces are in parking lots with over 50 spaces?
CREATE TABLE ParkingLots (lot_id INT,num_spaces INT,wheelchair_accessible BOOLEAN);
SELECT COUNT(*) FROM ParkingLots WHERE num_spaces > 50 AND wheelchair_accessible = TRUE;
What is the average budget allocation for disability accommodations by region?
CREATE TABLE disability_accommodations (accom_id INT,accom_name TEXT,budget DECIMAL(10,2),region_id INT);CREATE TABLE regions (region_id INT,region_name TEXT);
SELECT r.region_name, AVG(d.budget) AS avg_budget FROM disability_accommodations d INNER JOIN regions r ON d.region_id = r.region_id GROUP BY r.region_name;
Show the latest 3 records of ocean salinity measurements from the 'salinity_measurements' table.
CREATE TABLE salinity_measurements (measurement_time TIMESTAMP,salinity FLOAT,location TEXT); INSERT INTO salinity_measurements (measurement_time,salinity,location) VALUES ('2022-01-01 12:00:00',34.5,'Atlantic Ocean'),('2022-01-01 13:00:00',35.1,'Atlantic Ocean');
SELECT * FROM (SELECT ROW_NUMBER() OVER (ORDER BY measurement_time DESC) as rn, * FROM salinity_measurements) tmp WHERE rn <= 3;
Calculate the average carbon sequestered per hectare in mangrove forests
CREATE TABLE forests_carbon (id INT,type VARCHAR(20),area FLOAT,carbon FLOAT); INSERT INTO forests_carbon (id,type,area,carbon) VALUES (1,'Mangrove',100,100000);
SELECT AVG(carbon / area) FROM forests_carbon WHERE type = 'Mangrove';
List timber sales by year and forest, ordered by revenue
CREATE TABLE forests (id INT,name VARCHAR(50),hectares DECIMAL(5,2),year_planted INT,country VARCHAR(50),PRIMARY KEY (id)); INSERT INTO forests (id,name,hectares,year_planted,country) VALUES (1,'Forest A',123.45,1990,'USA'),(2,'Forest B',654.32,1985,'Canada'),(3,'Forest C',456.78,2010,'USA'),(4,'Forest D',903.45,1980,'Mexico'); CREATE TABLE timber_sales (id INT,forest_id INT,year INT,volume DECIMAL(10,2),price DECIMAL(10,2),PRIMARY KEY (id)); INSERT INTO timber_sales (id,forest_id,year,volume,price) VALUES (1,1,2021,120.50,100.00),(2,1,2022,150.75,125.50),(3,2,2021,450.23,50.00),(4,2,2022,520.89,75.25),(5,3,2021,300.56,150.00),(6,3,2022,345.98,175.50);
SELECT f.name, t.year, SUM(t.volume * t.price) as revenue FROM forests f INNER JOIN timber_sales t ON f.id = t.forest_id GROUP BY f.name, t.year ORDER BY revenue DESC;
What is the average area of timber production areas in hectares?
CREATE TABLE timber_production (id INT,name VARCHAR(50),area_ha FLOAT,country VARCHAR(50));
SELECT AVG(area_ha) FROM timber_production;
Show the number of safety incidents for each country's ingredient sourcing.
CREATE TABLE Ingredient_Sourcing (id INT,country VARCHAR(50),incidents INT); INSERT INTO Ingredient_Sourcing (id,country,incidents) VALUES (1,'USA',5),(2,'Canada',2),(3,'Mexico',7);
SELECT country, incidents FROM Ingredient_Sourcing;
Identify the regions with sales of organic makeup products
CREATE TABLE sales (product_type VARCHAR(20),region VARCHAR(10),sales NUMERIC(10,2)); INSERT INTO sales (product_type,region,sales) VALUES ('foundation','North',500),('lipstick','East',600),('eyeshadow','West',400),('blush','South',700),('mascara','North',800),('foundation','West',900); CREATE TABLE products (product_type VARCHAR(20),organic BOOLEAN); INSERT INTO products (product_type,organic) VALUES ('foundation',TRUE),('lipstick',FALSE),('eyeshadow',TRUE),('blush',FALSE),('mascara',TRUE);
SELECT DISTINCT region FROM sales INNER JOIN products ON sales.product_type = products.product_type WHERE products.organic = TRUE AND sales.product_type = 'makeup';
Which brands of makeup have a rating of at least 4?
CREATE TABLE makeup_ratings (brand VARCHAR(255),rating DECIMAL(2,1)); INSERT INTO makeup_ratings (brand,rating) VALUES ('CeraVe',4.5),('Dermalogica',4.7),('Maybelline',3.8),('Lancome',4.6);
SELECT brand FROM makeup_ratings WHERE rating >= 4.0;
How many artworks in the 'ArtCollection' table were created during the 20th century?
CREATE TABLE ArtCollection (ArtworkID INT,ArtworkYear INT); INSERT INTO ArtCollection (ArtworkID,ArtworkYear) VALUES (1,1905),(2,1910),(3,1915),(4,1920),(5,1925),(6,1930),(7,1935),(8,1940),(9,1945),(10,1950);
SELECT COUNT(*) AS Artworks20thCentury FROM ArtCollection WHERE ArtworkYear BETWEEN 1901 AND 2000;
Delete a record from 'military_equipment' table
CREATE TABLE military_equipment (id INT PRIMARY KEY,name VARCHAR(255),type VARCHAR(255),country VARCHAR(255)); INSERT INTO military_equipment (id,name,type,country) VALUES (1,'M1 Abrams','Tank','USA');
DELETE FROM military_equipment WHERE id = 1;
Find the top 3 customers with the highest risk score, and their corresponding portfolio values?
CREATE TABLE customers (customer_id INT,name VARCHAR(50),age INT,gender VARCHAR(10),risk_score INT,portfolio_value DECIMAL(10,2));
SELECT customer_id, name, risk_score, portfolio_value FROM (SELECT customer_id, name, risk_score, portfolio_value, ROW_NUMBER() OVER (ORDER BY risk_score DESC) as rn FROM customers) t WHERE rn <= 3;
What is the minimum balance for customers in the Africa region who have a balance greater than $10,000 in their savings account?
CREATE TABLE account_types (account_id INT,customer_id INT,account_type VARCHAR(20),balance DECIMAL(10,2)); INSERT INTO account_types (account_id,customer_id,account_type,balance) VALUES (1,1,'Savings',12000.00),(2,1,'Checking',5000.00),(3,2,'Savings',8000.00),(4,2,'Checking',3000.00),(5,3,'Savings',15000.00),(6,3,'Checking',5500.00);
SELECT MIN(balance) FROM account_types WHERE account_type = 'Savings' AND customer_id IN (SELECT customer_id FROM account_types WHERE account_type = 'Checking' AND balance > 10000);
List all the vessels that entered the port of New York and their corresponding cargo types, sorted by the vessel ID.
CREATE TABLE port (port_id INT,port_name VARCHAR(50)); INSERT INTO port (port_id,port_name) VALUES (1,'Oakland'),(2,'Seattle'),(3,'Long Beach'),(4,'New York'); CREATE TABLE vessels (vessel_id INT,port_id INT); INSERT INTO vessels (vessel_id,port_id) VALUES (101,3),(102,3),(103,4),(104,3); CREATE TABLE cargo (cargo_id INT,cargo_type VARCHAR(50),vessel_id INT); INSERT INTO cargo (cargo_id,cargo_type,vessel_id) VALUES (201,'Containers',101),(202,'Vehicles',102),(203,'Bulk',103);
SELECT vessels.vessel_id, cargo.cargo_type FROM vessels JOIN port ON vessels.port_id = port.port_id JOIN cargo ON vessels.vessel_id = cargo.vessel_id WHERE port.port_name = 'New York' ORDER BY vessels.vessel_id;
What is the minimum weight of containers shipped from the Port of Tokyo to Japan in 2018?
CREATE TABLE ports (port_id INT,port_name TEXT,country TEXT);CREATE TABLE shipments (shipment_id INT,shipment_weight INT,ship_date DATE,port_id INT); INSERT INTO ports VALUES (1,'Port of Tokyo','Japan'),(2,'Port of Yokohama','Japan'); INSERT INTO shipments VALUES (1,2000,'2018-01-01',1),(2,1500,'2018-02-15',2);
SELECT MIN(shipment_weight) FROM shipments JOIN ports ON shipments.port_id = ports.port_id WHERE ports.country = 'Japan' AND ports.port_name = 'Port of Tokyo' AND ship_date BETWEEN '2018-01-01' AND '2018-12-31';
Calculate the moving average of energy savings for each program in the 'energy_efficiency' table over the last 3 records.
CREATE TABLE energy_efficiency (program VARCHAR(50),energy_savings FLOAT); INSERT INTO energy_efficiency (program,energy_savings) VALUES ('sustainable_manufacturing',12.5),('energy_audits',7.8),('smart_meters',10.2),('sustainable_manufacturing',11.7),('energy_audits',8.1),('smart_meters',10.6);
SELECT program, AVG(energy_savings) OVER (PARTITION BY program ORDER BY program ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS moving_avg FROM energy_efficiency;
Delete the 'top_ethical_companies' view
CREATE VIEW top_ethical_companies AS SELECT company_name,ethical_certification FROM ethical_manufacturing ORDER BY ethical_certification DESC LIMIT 5;
DROP VIEW top_ethical_companies;
How many workers are employed in 'renewable energy' sector?
CREATE TABLE workers (id INT,worker_name VARCHAR(255),department VARCHAR(255)); INSERT INTO workers (id,worker_name,department) VALUES (1,'John Doe','renewable energy'),(2,'Jane Smith','textiles'),(3,'Michael Brown','renewable energy');
SELECT COUNT(*) FROM workers WHERE department = 'renewable energy';
Minimum excavation date in 'asian_archaeology'?
CREATE TABLE asian_archaeology (site_id INT,excavation_date DATE);
SELECT MIN(excavation_date) FROM asian_archaeology;
What is the total number of military bases in the 'NorthAmerica' schema?
CREATE SCHEMA NorthAmerica; CREATE TABLE MilitaryBases (id INT,name VARCHAR(255),type VARCHAR(255),location VARCHAR(255)); INSERT INTO MilitaryBases (id,name,type,location) VALUES (1,'Fort Bragg','Army Base','North Carolina'); INSERT INTO MilitaryBases (id,name,type,location) VALUES (2,'Camp Pendleton','Marine Corps Base','California');
SELECT COUNT(*) FROM NorthAmerica.MilitaryBases;
What is the average amount donated by each donor who has donated more than $100 in total?
CREATE TABLE Donors (DonorID INT,Name TEXT,State TEXT,DonationAmount DECIMAL); INSERT INTO Donors (DonorID,Name,State,DonationAmount) VALUES (1,'John Doe','California',50.00),(2,'Jane Smith','Texas',100.00),(3,'Brian Kim','California',150.00);
SELECT DonorID, AVG(DonationAmount) FROM Donors GROUP BY DonorID HAVING SUM(DonationAmount) > 100;
What is the average mental health score for students in each gender, grouped by age and ethnicity?
CREATE TABLE students (id INT,name VARCHAR(50),gender VARCHAR(10),mental_health_score INT,age INT,ethnicity VARCHAR(50)); INSERT INTO students (id,name,gender,mental_health_score,age,ethnicity) VALUES (1,'Jane Doe','Female',80,19,'Hispanic');
SELECT gender, age, ethnicity, AVG(mental_health_score) as avg_score FROM students GROUP BY gender, age, ethnicity;
What is the average mental health score of students who have participated in open pedagogy initiatives?
CREATE TABLE students (student_id INT,mental_health_score INT,participated_in_open_pedagogy BOOLEAN); INSERT INTO students (student_id,mental_health_score,participated_in_open_pedagogy) VALUES (1,80,TRUE),(2,70,FALSE),(3,90,TRUE);
SELECT AVG(mental_health_score) FROM students WHERE participated_in_open_pedagogy = TRUE;
What is the number of open pedagogy resources accessed by students in each country?
CREATE TABLE student_access (student_id INT,country VARCHAR(10),resource_id VARCHAR(5)); INSERT INTO student_access (student_id,country,resource_id) VALUES (1,'USA','R101'),(2,'CAN','R201'),(3,'USA','R102'),(4,'MEX','R301'),(5,'CAN','R202'); CREATE TABLE open_resources (resource_id VARCHAR(5),resource_name VARCHAR(20)); INSERT INTO open_resources (resource_id,resource_name) VALUES ('R101','OER Textbook'),('R102','Open Source Software'),('R201','MOOC Course'),('R202','Online Tutorial'),('R301','Podcast');
SELECT country, COUNT(*) FROM student_access JOIN open_resources ON student_access.resource_id = open_resources.resource_id GROUP BY country;
What is the percentage of teachers who have completed professional development courses in each district, ordered by the percentage?
CREATE TABLE districts (district_id INT,district_name VARCHAR(50)); INSERT INTO districts VALUES (1,'District A'),(2,'District B'),(3,'District C'); CREATE TABLE teachers (teacher_id INT,district_id INT,completed_pd_course BOOLEAN); INSERT INTO teachers VALUES (1,1,TRUE),(2,1,TRUE),(3,2,TRUE),(4,2,FALSE),(5,3,FALSE),(6,3,FALSE);
SELECT district_id, district_name, AVG(completed_pd_course) * 100.0 as pct_completed FROM districts JOIN teachers ON districts.district_id = teachers.district_id GROUP BY district_id, district_name ORDER BY pct_completed DESC;
Delete all energy storage projects in France before 2010.
CREATE TABLE energy_storage (name TEXT,country TEXT,technology TEXT,capacity_mwh INTEGER,year INTEGER); INSERT INTO energy_storage (name,country,technology,capacity_mwh,year) VALUES ('Project A','France','Battery',50,2005),('Project B','France','Pumped Hydro',200,2012);
DELETE FROM energy_storage WHERE country = 'France' AND technology IN ('Battery', 'Pumped Hydro') AND year < 2010;
What is the total number of oil rigs in the North Sea that were installed after 2010?
CREATE TABLE oil_rigs (id INT,location VARCHAR(20),installation_date DATE);
SELECT COUNT(*) FROM oil_rigs WHERE location LIKE 'North Sea%' AND installation_date > '2010-01-01';
What is the total number of points scored by each basketball player in the NBA?
CREATE TABLE nba_scores (player_id INT,player_name VARCHAR(50),team_id INT,team_name VARCHAR(50),points INT); INSERT INTO nba_scores (player_id,player_name,team_id,team_name,points) VALUES (1,'Stephen Curry',30,'Golden State Warriors',3245),(2,'LeBron James',23,'Los Angeles Lakers',3037),(3,'Kevin Durant',7,'Brooklyn Nets',2774);
SELECT player_name, SUM(points) as total_points FROM nba_scores GROUP BY player_name;
What is the total amount of food aid sent to 'countries' table and which countries received it?
CREATE TABLE food_aid (food_aid_id INT,country_id INT,aid_amount DECIMAL(10,2)); CREATE TABLE countries (country_id INT,country_name VARCHAR(50)); INSERT INTO food_aid (food_aid_id,country_id,aid_amount) VALUES (1,1,25000),(2,2,32000),(3,3,18000),(4,4,40000),(5,5,22000),(6,1,10000); INSERT INTO countries (country_id,country_name) VALUES (1,'Syria'),(2,'Yemen'),(3,'South Sudan'),(4,'Afghanistan'),(5,'Nigeria'),(6,'Iraq');
SELECT country_name, SUM(aid_amount) as total_food_aid FROM countries INNER JOIN food_aid ON countries.country_id = food_aid.country_id GROUP BY country_name;
Which countries have the most unvaccinated children under 5 in the 'vaccinations' table?
CREATE TABLE vaccinations (country VARCHAR(50),num_children_unvaccinated INT); INSERT INTO vaccinations (country,num_children_unvaccinated) VALUES ('Afghanistan',600000),('Burkina Faso',450000),('Nigeria',2500000),('South Sudan',700000),('Yemen',900000);
SELECT country, SUM(num_children_unvaccinated) as total_unvaccinated FROM vaccinations GROUP BY country ORDER BY total_unvaccinated DESC;