instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
Which suppliers provide vegan certified products?
CREATE TABLE suppliers (supplier_id INT,supplier_name VARCHAR(30),certified_vegan BOOLEAN); INSERT INTO suppliers (supplier_id,supplier_name,certified_vegan) VALUES (1,'Green Earth',true),(2,'Sunrise Fresh',false);
SELECT supplier_name FROM suppliers WHERE certified_vegan = true;
Drop the autonomous vehicle testing table
CREATE TABLE autonomous_testing (id INT PRIMARY KEY,location VARCHAR(100),company VARCHAR(100),date DATE,miles_driven INT);
DROP TABLE autonomous_testing;
What is the average transaction amount for each decentralized application (DApp) in the 'dapps' table, partitioned by week?
CREATE TABLE dapps (dapp_id INT,dapp_name VARCHAR(30),transaction_amount DECIMAL(10,2),transaction_time DATETIME);
SELECT dapp_name, AVG(transaction_amount) as avg_transaction_amount, DATE_TRUNC('week', transaction_time) as week FROM dapps GROUP BY dapp_name, week ORDER BY week;
What is the average budget allocated for military innovation by countries in Europe?
CREATE TABLE MilitaryInnovation (id INT,country VARCHAR(50),budget DECIMAL(10,2),year INT); INSERT INTO MilitaryInnovation (id,country,budget,year) VALUES (1,'France',5000000,2020),(2,'Germany',6000000,2020),(3,'Italy',4000000,2020);
SELECT AVG(budget) FROM MilitaryInnovation WHERE country IN ('France', 'Germany', 'Italy') AND year = 2020 AND category = 'military innovation';
What are the total number of hotels in the APAC region with a virtual tour and their average rating?
CREATE TABLE hotels (id INT,name TEXT,region TEXT,has_virtual_tour BOOLEAN,rating FLOAT); INSERT INTO hotels (id,name,region,has_virtual_tour,rating) VALUES (1,'Hotel1','APAC',true,4.5),(2,'Hotel2','APAC',false,4.2),(3,'Hotel3','NA',true,4.8);
SELECT AVG(rating), COUNT(*) FROM hotels WHERE region = 'APAC' AND has_virtual_tour = true;
Create a view to show the number of candidates interviewed by department and ethnicity
CREATE TABLE interview_data (interview_id INTEGER,candidate_id INTEGER,department VARCHAR(50),ethnicity VARCHAR(30),interview_date DATE); INSERT INTO interview_data (interview_id,candidate_id,department,ethnicity,interview_date) VALUES (1,201,'Engineering','Asian','2022-01-03'),(2,202,'Engineering','White','2022-01-10'),(3,203,'Marketing','Hispanic','2022-02-15'),(4,204,'Human Resources','Black','2022-03-21'),(5,205,'Human Resources','Asian','2022-04-12'),(6,206,'Engineering','White','2022-05-02');
CREATE VIEW candidates_interviewed_by_dept_ethnicity AS SELECT department, ethnicity, COUNT(*) as total FROM interview_data GROUP BY department, ethnicity;
Identify the number of satellites launched by each country in the Asia-Pacific region.
CREATE TABLE satellites_by_country (id INT,country VARCHAR(255),name VARCHAR(255)); INSERT INTO satellites_by_country (id,country,name) VALUES (1,'USA','Starlink 1'),(2,'New Zealand','Photon 1'),(3,'Australia','Fedsat 1'),(4,'China','Beidou-3 M23'),(5,'India','GSAT 10');
SELECT country, COUNT(*) as num_satellites FROM satellites_by_country WHERE country IN ('Australia', 'China', 'India', 'Japan', 'South Korea', 'North Korea', 'New Zealand', 'Papua New Guinea', 'Philippines', 'Singapore', 'Sri Lanka', 'Thailand', 'Vietnam') GROUP BY country ORDER BY num_satellites DESC;
How many factories in 'region2' have no workers in the 'textiles' department?
CREATE TABLE factories (factory_id INT,region VARCHAR(20)); CREATE TABLE departments (department_id INT,name VARCHAR(20)); CREATE TABLE workers (worker_id INT,factory_id INT,department_id INT); INSERT INTO factories (factory_id,region) VALUES (1,'region1'),(2,'region1'),(3,'region2'),(4,'region3'); INSERT INTO departments (department_id,name) VALUES (1,'textiles'),(2,'metalwork'),(3,'electronics'); INSERT INTO workers (worker_id,factory_id,department_id) VALUES (1,1,1),(2,1,2),(3,2,3),(4,3,1);
SELECT COUNT(f.factory_id) FROM factories f LEFT JOIN workers w ON f.factory_id = w.factory_id AND w.department_id = (SELECT department_id FROM departments WHERE name = 'textiles') WHERE f.region = 'region2' AND w.worker_id IS NULL;
List the programs that have had donations but no recent activity (no donations in the last 3 months) and their last donation date.
CREATE TABLE Donations (DonationID INT,DonorID INT,ProgramID INT,DonationDate DATE); INSERT INTO Donations (DonationID,DonorID,ProgramID,DonationDate) VALUES (1,1,1,'2021-01-01'),(2,2,1,'2021-02-01'),(3,3,2,'2021-03-01'),(4,1,3,'2021-04-01'),(5,4,1,'2022-01-01'),(6,1,2,'2022-02-01'),(7,2,2,'2022-03-01'),(8,3,3,'2022-04-01');
SELECT Programs.Name, MAX(Donations.DonationDate) as LastDonationDate FROM Programs JOIN Donations ON Programs.ProgramID = Donations.ProgramID WHERE Donations.DonationDate < DATE_SUB(CURRENT_DATE, INTERVAL 3 MONTH) GROUP BY Programs.Name HAVING COUNT(Donations.DonationID) > 0;
What are the names and production quantities of all gas wells in the 'gulf' region?
CREATE TABLE gas_wells (well_name TEXT,region TEXT,production_quantity INT); INSERT INTO gas_wells (well_name,region,production_quantity) VALUES ('Well A','gulf',5000),('Well B','gulf',7000),('Well C','ocean',6000);
SELECT well_name, production_quantity FROM gas_wells WHERE region = 'gulf';
List the total number of acres and average yield for each crop type in the 'precision_farming' table.
CREATE TABLE precision_farming (id INT,crop VARCHAR(255),acres DECIMAL(10,2),yield DECIMAL(10,2));
SELECT crop, SUM(acres) as total_acres, AVG(yield) as avg_yield FROM precision_farming GROUP BY crop;
Show the difference in average age between fans of 'Basketball' and 'Soccer' in 'fan_data' table
CREATE TABLE fan_data (fan_id INT,age INT,gender VARCHAR(10),city VARCHAR(50),state VARCHAR(20),country VARCHAR(50)); INSERT INTO fan_data (fan_id,age,gender,city,state,country) VALUES (1,22,'Male','New York','NY','USA'); INSERT INTO fan_data (fan_id,age,gender,city,state,country) VALUES (2,28,'Female','Los Angeles','CA','USA');
SELECT AVG(age) - (SELECT AVG(age) FROM fan_data WHERE sport = 'Basketball') AS age_difference FROM fan_data WHERE sport = 'Soccer';
How many hotels were added in 'California' each month in 2021?
CREATE TABLE hotels_history (hotel_id INT,action TEXT,city TEXT,date DATE);
SELECT DATE_FORMAT(date, '%Y-%m') as month, COUNT(*) FROM hotels_history WHERE action = 'add' AND city = 'California' AND date BETWEEN '2021-01-01' AND '2021-12-31' GROUP BY month;
How many hours were volunteered by each gender in 2020?
CREATE TABLE volunteer_hours (id INT,volunteer_name TEXT,gender TEXT,hours INT,volunteer_date DATE); INSERT INTO volunteer_hours (id,volunteer_name,gender,hours,volunteer_date) VALUES (1,'Alice','Female',5,'2020-06-15'); INSERT INTO volunteer_hours (id,volunteer_name,gender,hours,volunteer_date) VALUES (2,'Bob','Male',8,'2020-12-31');
SELECT gender, SUM(hours) as total_hours FROM volunteer_hours WHERE volunteer_date >= '2020-01-01' AND volunteer_date < '2021-01-01' GROUP BY gender;
How many citizen complaints were received in each district for the last 30 days?
CREATE TABLE Complaints (Complaint_ID INT,District_Name VARCHAR(255),Complaint_Date DATE); INSERT INTO Complaints VALUES (1,'District A','2022-01-01'),(2,'District B','2022-01-05'),(3,'District A','2022-01-10');
SELECT District_Name, COUNT(*) OVER (PARTITION BY District_Name) AS Complaints_Count FROM Complaints WHERE Complaint_Date >= DATEADD(day, -30, GETDATE());
Which cruelty-free certified products have the highest consumer preference ratings?
CREATE TABLE products (product_id INT,name VARCHAR(50),cruelty_free BOOLEAN,preference_rating INT); INSERT INTO products (product_id,name,cruelty_free,preference_rating) VALUES (1,'Lipstick A',true,8),(2,'Lipstick B',false,9),(3,'Eyeshadow C',true,7); CREATE TABLE certifications (product_id INT,certification_name VARCHAR(50)); INSERT INTO certifications (product_id,certification_name) VALUES (1,'Cruelty-Free'),(3,'Cruelty-Free');
SELECT products.name, products.preference_rating FROM products INNER JOIN certifications ON products.product_id = certifications.product_id WHERE certifications.certification_name = 'Cruelty-Free' ORDER BY products.preference_rating DESC;
What is the total tonnage of cargo shipped from the Port of Oakland to Japan in 2020?
CREATE TABLE ports (port_id INT,port_name TEXT,country TEXT); INSERT INTO ports VALUES (1,'Port of Oakland','USA'); CREATE TABLE shipments (shipment_id INT,port_id INT,cargo_tonnage INT,ship_date DATE); INSERT INTO shipments VALUES (1,1,5000,'2020-01-01');
SELECT SUM(cargo_tonnage) FROM shipments JOIN ports ON shipments.port_id = ports.port_id WHERE ports.port_name = 'Port of Oakland' AND YEAR(ship_date) = 2020 AND ports.country = 'Japan';
How many cases were won or lost by attorneys in the Midwest region?
CREATE TABLE Attorneys (AttorneyID int,Name varchar(50),Region varchar(10)); INSERT INTO Attorneys VALUES (1,'Mohammed Al-Hussein','Midwest'),(2,'Kimberly Johnson','Southeast'); CREATE TABLE Cases (CaseID int,AttorneyID int,Outcome varchar(10)); INSERT INTO Cases VALUES (1,1,'Won'),(2,1,'Lost'),(3,2,'Won'),(4,2,'Won');
SELECT A.Region, A.Name, COUNT(C.CaseID) as NumCases FROM Attorneys A JOIN Cases C ON A.AttorneyID = C.AttorneyID GROUP BY A.Region, A.Name;
Find the number of exoplanet discoveries made by the TESS and Cheops missions.
CREATE TABLE exoplanets (id INT,name VARCHAR(255),discovery_mission VARCHAR(255),discovery_date DATE); INSERT INTO exoplanets (id,name,discovery_mission,discovery_date) VALUES (1,'TESS-1b','TESS','2019-07-25'); INSERT INTO exoplanets (id,name,discovery_mission,discovery_date) VALUES (2,'CHEOPS-1a','CHEOPS','2022-11-11'); CREATE VIEW tess_exoplanets AS SELECT * FROM exoplanets WHERE discovery_mission = 'TESS'; CREATE VIEW cheops_exoplanets AS SELECT * FROM exoplanets WHERE discovery_mission = 'CHEOPS';
SELECT COUNT(*) as num_discoveries FROM exoplanets e INNER JOIN tess_exoplanets t ON e.id = t.id INNER JOIN cheops_exoplanets c ON e.id = c.id;
List the total number of threat intelligence reports issued for each category, ordered by the total count in descending order.
CREATE TABLE threat_intelligence(report_date DATE,report_category VARCHAR(20)); INSERT INTO threat_intelligence(report_date,report_category) VALUES ('2021-01-01','cyber'),('2021-01-05','terrorism'),('2021-02-01','cyber'),('2021-03-01','foreign_intelligence');
SELECT report_category, COUNT(*) as total_reports FROM threat_intelligence GROUP BY report_category ORDER BY total_reports DESC;
Get the number of factories in each country
CREATE TABLE factories (factory_id INT,country_id INT); INSERT INTO factories (factory_id,country_id) VALUES (1,1),(2,2),(3,1); CREATE TABLE countries (country_id INT,country_name VARCHAR(255)); INSERT INTO countries (country_id,country_name) VALUES (1,'USA'),(2,'Canada');
SELECT countries.country_name, COUNT(DISTINCT factories.factory_id) FROM factories INNER JOIN countries ON factories.country_id = countries.country_id GROUP BY countries.country_name;
How many unique donors are there for each program in 'Volunteer Program'?
CREATE TABLE program_donors (program_id INT,donor_id INT);
SELECT program_id, COUNT(DISTINCT donor_id) AS unique_donors FROM program_donors WHERE program_id IN (SELECT id FROM programs WHERE name = 'Volunteer Program') GROUP BY program_id;
What is the maximum and minimum environmental impact score of mining operations in each country?
CREATE TABLE mining_operations (id INT,location VARCHAR(255),environmental_impact_score INT); INSERT INTO mining_operations (id,location,environmental_impact_score) VALUES (1,'Canada',85),(2,'Canada',60),(3,'USA',70),(4,'USA',90),(5,'Mexico',88),(6,'Mexico',55),(7,'Australia',60),(8,'Australia',75);
SELECT location, MAX(environmental_impact_score) AS max_score, MIN(environmental_impact_score) AS min_score FROM mining_operations GROUP BY location;
What is the total installed capacity (in MW) of renewable energy projects in India that were completed after 2018, grouped by type?
CREATE TABLE india_renewable_projects (name TEXT,type TEXT,completion_date DATE,capacity_mw REAL); INSERT INTO india_renewable_projects (name,type,completion_date,capacity_mw) VALUES ('Solar Project 1','Solar','2019-01-01',50),('Wind Project 2','Wind','2020-01-01',75);
SELECT type, SUM(capacity_mw) FROM india_renewable_projects WHERE completion_date > '2018-12-31' GROUP BY type;
Which countries have the most fitness centers?
CREATE TABLE FitnessCenters (CenterID INT,Name VARCHAR(50),Country VARCHAR(50)); INSERT INTO FitnessCenters (CenterID,Name,Country) VALUES (1,'FitLife','USA'),(2,'EnerGym','Canada'),(3,'Vitalite','France'),(4,'FitEarth','USA'),(5,'ActiveZone','Germany');
SELECT Country, COUNT(*) FROM FitnessCenters GROUP BY Country ORDER BY COUNT(*) DESC;
What is the total quantity of garments, in the 'inventory' table, that are made of sustainable materials and have not been sold yet?
CREATE TABLE inventory (id INT,garment_id INT,garment_name VARCHAR(50),garment_material VARCHAR(50),quantity INT); CREATE VIEW sustainable_materials AS SELECT 'organic cotton' AS material UNION ALL SELECT 'hemp' UNION ALL SELECT 'recycled polyester' UNION ALL SELECT 'tencel' UNION ALL SELECT 'modal';
SELECT SUM(quantity) AS total_quantity FROM inventory WHERE garment_material IN (SELECT material FROM sustainable_materials) AND quantity > 0;
What is the average launch cost, in USD, for each space agency's missions?
CREATE TABLE space_missions (mission_id INT,agency VARCHAR(50),launch_cost DECIMAL(10,2)); INSERT INTO space_missions (mission_id,agency,launch_cost) VALUES (1,'NASA',1000000.00),(2,'NASA',2000000.00),(3,'ESA',500000.00),(4,'ESA',700000.00),(5,'ISRO',150000.00),(6,'ISRO',200000.00);
SELECT agency, AVG(launch_cost) as average_cost FROM space_missions GROUP BY agency;
What is the total number of donors for each program and their average donation amount?
CREATE TABLE programs (id INT,name VARCHAR(255)); INSERT INTO programs (id,name) VALUES (1,'Education'),(2,'Health'),(3,'Environment'); CREATE TABLE donors (id INT,name VARCHAR(255),program_id INT,total_donations DECIMAL(10,2));
SELECT p.name, COUNT(*) as total_donors, AVG(d.total_donations) as avg_donation_amount FROM programs p JOIN donors d ON p.id = d.program_id GROUP BY p.id;
Which risk categories have the highest average risk score for each business unit?
CREATE TABLE risk_scores (score_id INT,business_unit VARCHAR(50),risk_category VARCHAR(50),value DECIMAL(10,2)); INSERT INTO risk_scores (score_id,business_unit,risk_category,value) VALUES (1,'Internal Audit','Operational Risk',7.25),(2,'Internal Audit','Compliance Risk',7.50),(3,'Marketing','Operational Risk',6.75),(4,'Marketing','Compliance Risk',7.00);
SELECT business_unit, risk_category, AVG(value) AS average_risk_score FROM risk_scores GROUP BY business_unit, risk_category ORDER BY average_risk_score DESC;
What is the average donation amount per donor in the Asia region?
CREATE TABLE Donors (donor_id INT,donor_name TEXT,donation_amount DECIMAL,donation_date DATE,region TEXT);
SELECT AVG(Donations.donation_amount) FROM Donors AS Donations INNER JOIN (SELECT * FROM Regions WHERE Regions.region = 'Asia') AS Reg ON Donors.region = Reg.region_name;
What is the total number of posts with hashtags?
CREATE TABLE posts (id INT,user_id INT,post_text VARCHAR(255),hashtags INT); INSERT INTO posts (id,user_id,post_text,hashtags) VALUES (1,1,'#Hello #World!',2),(2,2,'Nice to meet you!',0),(3,3,'Hello #Friends!',1),(4,4,'Hi there!',0);
SELECT SUM(hashtags) FROM posts;
List all suppliers from France that supply products to stores in New York.
CREATE TABLE suppliers (id INT,name VARCHAR(255),country VARCHAR(255)); CREATE TABLE stores (id INT,name VARCHAR(255),city VARCHAR(255)); CREATE TABLE store_supplies (store_id INT,supplier_id INT);
SELECT s.name FROM suppliers s JOIN store_supplies ss ON s.id = ss.supplier_id JOIN stores st ON ss.store_id = st.id WHERE s.country = 'France' AND st.city = 'New York';
Insert a new record in the 'Faculty_Members' table with the following details: Faculty_ID = 20, First_Name = 'Sofia', Last_Name = 'Ahmed', Title = 'Professor', Department = 'Computer Science', Hire_Date = '2018-01-01', Salary = 85000
CREATE TABLE Faculty_Members (Faculty_ID INT,First_Name VARCHAR(50),Last_Name VARCHAR(50),Title VARCHAR(20),Department VARCHAR(50),Hire_Date DATE,Salary DECIMAL(10,2));
INSERT INTO Faculty_Members (Faculty_ID, First_Name, Last_Name, Title, Department, Hire_Date, Salary) VALUES (20, 'Sofia', 'Ahmed', 'Professor', 'Computer Science', '2018-01-01', 85000);
What are the top 5 threat actors with the highest number of reported cybersecurity incidents?
CREATE TABLE threat_actors (id INT,actor_name VARCHAR(255),category VARCHAR(255),description TEXT,reported_incidents INT); INSERT INTO threat_actors (id,actor_name,category,description,reported_incidents) VALUES (1,'Actor1','Nation-state','Description of Actor1',100);
SELECT actor_name, reported_incidents FROM threat_actors ORDER BY reported_incidents DESC LIMIT 5;
What is the change in recycling rate for each initiative compared to the previous year?
CREATE TABLE Initiatives (InitiativeID INT,InitiativeName VARCHAR(50),RecyclingRate FLOAT,Year INT); INSERT INTO Initiatives VALUES (1,'Initiative1',0.7,2021),(1,'Initiative1',0.75,2022),(2,'Initiative2',0.6,2021),(2,'Initiative2',0.65,2022),(3,'Initiative3',0.8,2021),(3,'Initiative3',0.82,2022);
SELECT InitiativeName, (RecyclingRate - LAG(RecyclingRate) OVER (PARTITION BY InitiativeName ORDER BY Year)) as ChangeInRecyclingRate FROM Initiatives;
What is the daily average number of new followers for users in the fashion industry?
CREATE TABLE user_stats (user_id INT,stat_type VARCHAR(50),stat_date DATE,value INT); INSERT INTO user_stats (user_id,stat_type,stat_date,value) VALUES (1,'new_followers','2022-01-01',50),(2,'new_followers','2022-01-01',75),(1,'new_followers','2022-01-02',75),(5,'new_followers','2022-01-03',100);
SELECT AVG(value) FROM user_stats WHERE stat_type = 'new_followers' AND stat_date >= DATEADD(day, -30, GETDATE()) AND stat_date < DATEADD(day, -29, GETDATE()) AND user_stats.user_id IN (SELECT user_id FROM users WHERE industry = 'fashion');
Find the top 3 tours with the highest revenue in Africa?
CREATE TABLE Tours (id INT,name TEXT,country TEXT,type TEXT,revenue INT); INSERT INTO Tours (id,name,country,type,revenue) VALUES (1,'Cultural Heritage Tour','Egypt','Cultural',40000);
SELECT name, SUM(revenue) AS total_revenue FROM Tours WHERE EXTRACT(CONTINENT FROM (SELECT country FROM Tours WHERE Tours.id = Bookings.tour_id)) = 'Africa' GROUP BY name ORDER BY total_revenue DESC LIMIT 3;
Count the number of vessels in each category in the North Atlantic ocean
CREATE TABLE north_atlantic_vessels (vessel_id INT,vessel_name VARCHAR(255),category VARCHAR(255),longitude DECIMAL(9,6),latitude DECIMAL(9,6)); CREATE VIEW north_atlantic_vessels_north_atlantic AS SELECT * FROM north_atlantic_vessels WHERE longitude BETWEEN -90 AND -20 AND latitude BETWEEN 20 AND 60;
SELECT category, COUNT(*) FROM north_atlantic_vessels_north_atlantic GROUP BY category;
How many research grants were awarded to each department in the past year?
CREATE TABLE grants (grant_id INT,student_id INT,department TEXT,year INT,amount INT); INSERT INTO grants (grant_id,student_id,department,year,amount) VALUES (1,1,'Health',2021,5000),(2,2,'Education',2022,15000);
SELECT g.department, COUNT(*) as grant_count FROM grants g WHERE g.year = 2022 GROUP BY g.department;
Who are the top 3 users with the most failed login attempts in the past month?
CREATE TABLE login_attempts (id INT,user VARCHAR(255),success BOOLEAN,attempt_date DATE);
SELECT user, COUNT(*) as total_failed_attempts FROM login_attempts WHERE success = 0 AND attempt_date >= DATEADD(month, -1, GETDATE()) GROUP BY user ORDER BY total_failed_attempts DESC LIMIT 3;
How many affordable housing units are available in the InclusiveHousing schema for each city, broken down by property type?
CREATE TABLE InclusiveHousing.AffordableHousing (city VARCHAR(50),property_type VARCHAR(50),units INT); INSERT INTO InclusiveHousing.AffordableHousing (city,property_type,units) VALUES ('Chicago','Apartment',300),('Chicago','House',200),('Houston','Apartment',500),('Houston','House',300);
SELECT city, property_type, SUM(units) AS total_units FROM InclusiveHousing.AffordableHousing GROUP BY city, property_type;
What is the total revenue for each restaurant category in Q1 2022?
CREATE TABLE revenue (restaurant_name TEXT,category TEXT,revenue NUMERIC,date DATE); INSERT INTO revenue (restaurant_name,category,revenue,date) VALUES ('ABC Bistro','Italian',5000,'2022-01-01'),('ABC Bistro','Italian',6000,'2022-02-01'),('XYZ Café','Coffee Shop',3000,'2022-01-01'),('XYZ Café','Coffee Shop',3500,'2022-02-01');
SELECT category, SUM(revenue) as total_revenue FROM revenue WHERE date BETWEEN '2022-01-01' AND '2022-03-31' GROUP BY category;
How many players from Brazil won more than 5 games in a row?
CREATE TABLE Games (GameID INT,PlayerID INT,Result BOOLEAN); INSERT INTO Games (GameID,PlayerID,Result) VALUES (1,4,TRUE),(2,4,TRUE),(3,4,TRUE),(4,5,FALSE),(5,5,TRUE),(6,1,TRUE),(7,1,TRUE),(8,1,TRUE),(9,1,FALSE);
SELECT COUNT(*) FROM (SELECT * FROM Games WHERE PlayerID IN (SELECT PlayerID FROM Games WHERE Result = TRUE GROUP BY PlayerID HAVING COUNT(*) > 4)) AS Subquery;
What is the visitor growth rate for each country between 2018 and 2020?
CREATE TABLE CountryVisitorData (country_id INT,year INT,visitors INT); INSERT INTO CountryVisitorData (country_id,year,visitors) VALUES (1,2018,5000000); INSERT INTO CountryVisitorData (country_id,year,visitors) VALUES (1,2019,5500000); INSERT INTO CountryVisitorData (country_id,year,visitors) VALUES (1,2020,5750000); INSERT INTO CountryVisitorData (country_id,year,visitors) VALUES (2,2018,8000000); INSERT INTO CountryVisitorData (country_id,year,visitors) VALUES (2,2019,8500000); INSERT INTO CountryVisitorData (country_id,year,visitors) VALUES (2,2020,9000000); INSERT INTO CountryVisitorData (country_id,year,visitors) VALUES (3,2018,6000000); INSERT INTO CountryVisitorData (country_id,year,visitors) VALUES (3,2019,6250000); INSERT INTO CountryVisitorData (country_id,year,visitors) VALUES (3,2020,6500000);
SELECT country_id, (visitors - LAG(visitors, 1) OVER (PARTITION BY country_id ORDER BY year)) * 100.0 / LAG(visitors, 1) OVER (PARTITION BY country_id ORDER BY year) as growth_rate FROM CountryVisitorData;
Delete record where id=2 from 'rural_hospitals'
CREATE TABLE if not exists 'rural_hospitals' (id INT,name TEXT,address TEXT,worker_age INT,PRIMARY KEY(id));
DELETE FROM 'rural_hospitals' WHERE id = 2;
What is the total CO2 emission of the mining sector in the state of New York in the last 3 years?
CREATE TABLE co2_emissions (id INT,company TEXT,location TEXT,timestamp TIMESTAMP,co2_emission FLOAT); INSERT INTO co2_emissions (id,company,location,timestamp,co2_emission) VALUES (1,'New York Mining Inc','New York','2019-01-01 12:00:00',800);
SELECT SUM(co2_emission) FROM co2_emissions WHERE location = 'New York' AND EXTRACT(YEAR FROM timestamp) >= EXTRACT(YEAR FROM CURRENT_DATE) - 3;
Which Shariah-compliant investments have the highest and lowest returns in each quarter?
CREATE TABLE shariah_compliant_investments (investment_id INT,investment_name VARCHAR(255),investment_type VARCHAR(255),issue_date DATE,return_rate DECIMAL(5,2));CREATE VIEW quarters AS SELECT DATE_TRUNC('quarter',issue_date) AS quarter FROM shariah_compliant_investments;
SELECT q.quarter, i.investment_name, MAX(i.return_rate) AS max_return, MIN(i.return_rate) AS min_return FROM shariah_compliant_investments i INNER JOIN quarters q ON i.issue_date BETWEEN q.quarter AND q.quarter + INTERVAL '3 months' GROUP BY q.quarter, i.investment_name;
How many spacecraft were manufactured in each year?
CREATE TABLE spacecraft_manufacturing (id INT,spacecraft_name VARCHAR(255),manufacture_year INT,country VARCHAR(255)); INSERT INTO spacecraft_manufacturing (id,spacecraft_name,manufacture_year,country) VALUES (1,'Voyager 1',1977,'USA'),(2,'Voyager 2',1977,'USA'),(3,'Cassini',1997,'Europe');
SELECT manufacture_year, COUNT(*) OVER (PARTITION BY manufacture_year) as TotalSpacecraft FROM spacecraft_manufacturing;
Show me the cybersecurity policies that were created in the last month.
CREATE TABLE cybersecurity_policies (id INT,name VARCHAR(50),description TEXT,date DATE); INSERT INTO cybersecurity_policies (id,name,description,date) VALUES (1,'Incident response policy','Outlines the process for responding to security incidents','2022-04-15'),(2,'Access control policy','Defines who has access to what resources','2022-05-05');
SELECT * FROM cybersecurity_policies WHERE date >= DATEADD(month, -1, GETDATE());
Determine if there are any duplicate policy types for policyholders in 'UnderwritingTable2'.
CREATE TABLE UnderwritingTable2 (PolicyID INT,PolicyType VARCHAR(20)); INSERT INTO UnderwritingTable2 (PolicyID,PolicyType) VALUES (1,'Life'),(2,'Health'),(3,'Life');
SELECT PolicyType, COUNT(*) FROM UnderwritingTable2 GROUP BY PolicyType HAVING COUNT(*) > 1;
Which programs had the highest and lowest total financial impact in the last quarter?
CREATE TABLE Programs (ProgramID int,ProgramName varchar(50),StartDate date,EndDate date); CREATE TABLE ProgramFinancials (ProgramID int,Quarter int,Amount float);
SELECT ProgramName, CASE WHEN Amount = (SELECT MAX(Amount) FROM ProgramFinancials WHERE Quarter = (SELECT EXTRACT(QUARTER FROM MIN(StartDate)) FROM Programs)) THEN 'Highest' ELSE 'Lowest' END AS FinancialImpact FROM Programs JOIN ProgramFinancials ON Programs.ProgramID = ProgramFinancials.ProgramID WHERE Quarter = (SELECT EXTRACT(QUARTER FROM CURRENT_DATE) FROM Programs) GROUP BY ProgramName, Amount HAVING COUNT(*) = 1;
What is the trend of geopolitical risk assessments for defense projects in the Middle East?
CREATE TABLE geopolitical_risk_assessments (id INT,assessment_date DATE,project VARCHAR(50),region VARCHAR(20),risk_level DECIMAL(3,2));
SELECT region, AVG(risk_level) as avg_risk_level FROM geopolitical_risk_assessments WHERE region = 'Middle East' GROUP BY region, YEAR(assessment_date), QUARTER(assessment_date) ORDER BY YEAR(assessment_date), QUARTER(assessment_date);
What was the total production of Cerium in 2015 for the top 2 producers?
CREATE TABLE cerium_production (country VARCHAR(50),year INT,quantity INT); INSERT INTO cerium_production (country,year,quantity) VALUES ('China',2015,230000),('United States',2015,55000),('Australia',2015,15000),('Malaysia',2015,12000),('India',2015,10000);
SELECT country, SUM(quantity) FROM cerium_production WHERE year = 2015 GROUP BY country ORDER BY SUM(quantity) DESC LIMIT 2;
How many satellites have been deployed by year?
CREATE TABLE Satellite_Deployment (ID INT,Year INT,Satellite_Count INT); INSERT INTO Satellite_Deployment (ID,Year,Satellite_Count) VALUES (1,2010,50),(2,2015,75),(3,2020,100);
SELECT Year, SUM(Satellite_Count) FROM Satellite_Deployment GROUP BY Year;
Update records in the GeopoliticalRiskAssessments table
CREATE TABLE GeopoliticalRiskAssessments (id INT,country VARCHAR(50),risk_level INT,assessment_date DATE); INSERT INTO GeopoliticalRiskAssessments (id,country,risk_level,assessment_date) VALUES (1,'Country A',3,'2021-01-01'),(2,'Country B',5,'2021-02-01');
UPDATE GeopoliticalRiskAssessments SET risk_level = 4 WHERE id = 1;
Create a table named 'CulturalCompetency'
CREATE TABLE CulturalCompetency (ID INT PRIMARY KEY,HealthWorkerName VARCHAR(100),CulturalCompetencyScore INT);
CREATE TABLE CulturalCompetency (ID INT PRIMARY KEY, HealthWorkerName VARCHAR(100), CulturalCompetencyScore INT);
What is the maximum number of people that have been in space at the same time?
CREATE TABLE space_personnel (id INT,personnel_name VARCHAR(50),mission_name VARCHAR(50),in_space DATE);
SELECT MAX(COUNT(*)) FROM space_personnel GROUP BY in_space;
Find the total number of goals scored by soccer players in team 202?
CREATE TABLE goals (goal_id INT,player_id INT,match_id INT,team_id INT,goals INT); INSERT INTO goals (goal_id,player_id,match_id,team_id,goals) VALUES (1,3,5,202,1);
SELECT SUM(goals) FROM goals WHERE team_id = 202;
Which countries have no 'Diamond' mineral extractions in the 'Antarctica' region?
CREATE TABLE Countries_Antarctica_2 (country TEXT,region TEXT); CREATE TABLE Mineral_Extractions_Antarctica_2 (country TEXT,mineral TEXT,quantity INTEGER); INSERT INTO Countries_Antarctica_2 (country,region) VALUES ('Antarctica Base 3','Antarctica'); INSERT INTO Countries_Antarctica_2 (country,region) VALUES ('Antarctica Base 4','Antarctica'); INSERT INTO Mineral_Extractions_Antarctica_2 (country,mineral,quantity) VALUES ('Antarctica Base 3','Ice',1800); INSERT INTO Mineral_Extractions_Antarctica_2 (country,mineral,quantity) VALUES ('Antarctica Base 4','Ice',2000); INSERT INTO Mineral_Extractions_Antarctica_2 (country,mineral,quantity) VALUES ('Antarctica Base 3','Snow',2500);
SELECT c.country FROM Countries_Antarctica_2 c LEFT JOIN Mineral_Extractions_Antarctica_2 mea ON c.country = mea.country AND mea.mineral = 'Diamond' WHERE mea.country IS NULL;
Compare the landfill capacity of cities in the 'East Coast' region with those in the 'West Coast' region.
CREATE TABLE cities (city_name VARCHAR(50),region VARCHAR(50)); INSERT INTO cities (city_name,region) VALUES ('New York','East Coast'),('Boston','East Coast'),('San Francisco','West Coast'),('Los Angeles','West Coast'); CREATE TABLE landfill_capacity (city_name VARCHAR(50),capacity INT); INSERT INTO landfill_capacity (city_name,capacity) VALUES ('New York',5000),('Boston',4000),('San Francisco',3000),('Los Angeles',6000);
SELECT c.region, AVG(lc.capacity) as avg_capacity FROM landfill_capacity lc JOIN cities c ON lc.city_name = c.city_name GROUP BY c.region;
Which fish species have a stock size that is decreasing for three consecutive years?
CREATE TABLE fish_stock (year INT,species VARCHAR(255),stock_size INT); INSERT INTO fish_stock (year,species,stock_size) VALUES (2019,'Salmon',6000),(2020,'Salmon',5500),(2021,'Salmon',5000),(2019,'Tuna',4000),(2020,'Tuna',4000),(2021,'Tuna',4000);
SELECT species FROM (SELECT species, stock_size, LAG(stock_size, 2) OVER (PARTITION BY species ORDER BY year) AS lag_2, LAG(stock_size, 1) OVER (PARTITION BY species ORDER BY year) AS lag_1 FROM fish_stock) AS subquery WHERE subquery.stock_size < subquery.lag_1 AND subquery.lag_1 < subquery.lag_2;
Insert a new program with ID 6 named "Environmental Education"?
CREATE TABLE programs (program_id INT,program_name TEXT); INSERT INTO programs (program_id,program_name) VALUES (1,'Youth Mentoring'),(2,'Food Security'),(3,'Elder Care'),(4,'Arts Education'),(5,'After School Program');
INSERT INTO programs (program_id, program_name) VALUES (6, 'Environmental Education');
Delete products from the inventory table that have not been sold in the last 6 months.
CREATE TABLE inventory (product_id INT,last_sale_date DATE); INSERT INTO inventory VALUES (1,'2022-01-01'),(2,'2022-05-01'),(3,'2021-12-31'),(4,'2022-03-15');
DELETE FROM inventory WHERE last_sale_date < DATE_SUB(CURRENT_DATE, INTERVAL 6 MONTH);
What is the total population of all species?
CREATE TABLE species (id INT,name VARCHAR(50),population INT,conservation_status VARCHAR(20)); INSERT INTO species (id,name,population,conservation_status) VALUES (1,'Polar Bear',26500,'Vulnerable'),(2,'Arctic Fox',15000,'Least Concern'),(3,'Walrus',35000,'Vulnerable');
SELECT SUM(population) FROM species;
What is the earliest date a satellite was deployed by each manufacturer?
CREATE TABLE Satellites_Manufacturers (Id INT,Satellite_Id INT,Manufacturer VARCHAR(50),Deployment_Date DATE); INSERT INTO Satellites_Manufacturers (Id,Satellite_Id,Manufacturer,Deployment_Date) VALUES (1,1,'SpaceX','2018-01-01'),(2,2,'SpaceX','2019-01-01'),(3,3,'ULA','2018-01-01');
SELECT Manufacturer, MIN(Deployment_Date) AS Earliest_Deployment_Date FROM Satellites_Manufacturers GROUP BY Manufacturer;
Display all the students who have not completed any professional development courses
CREATE TABLE Student (StudentID INT,Name VARCHAR(50)); CREATE TABLE Course (CourseID INT,Name VARCHAR(50)); CREATE TABLE StudentCourse (StudentID INT,CourseID INT); INSERT INTO Student (StudentID,Name) VALUES (1,'John Doe'),(2,'Jane Smith'); INSERT INTO Course (CourseID,Name) VALUES (101,'Professional Development 101'),(102,'Intro to Programming'); INSERT INTO StudentCourse (StudentID,CourseID) VALUES (1,101);
SELECT s.Name FROM Student s WHERE NOT EXISTS (SELECT 1 FROM StudentCourse sc WHERE s.StudentID = sc.StudentID);
What is the total quantity of military equipment sold by Lockheed Martin to India in 2020?
CREATE SCHEMA if not exists defense_contractors;CREATE TABLE if not exists military_equipment_sales(supplier text,purchaser text,quantity integer,sale_year integer,product text);INSERT INTO military_equipment_sales(supplier,purchaser,quantity,sale_year,product) VALUES('Lockheed Martin','India',120,2020,'F-16'),('Lockheed Martin','India',150,2020,'C-130J'),('Lockheed Martin','Pakistan',50,2020,'C-130J');
SELECT SUM(quantity) FROM military_equipment_sales WHERE supplier = 'Lockheed Martin' AND purchaser = 'India' AND sale_year = 2020;
Delete the records of waste production for the 'Africa' region in January 2022.
CREATE TABLE waste_production (region varchar(20),waste_amount int,date date);
DELETE FROM waste_production WHERE region = 'Africa' AND date = '2022-01-01';
What is the minimum cost of projects in the water division?
CREATE TABLE Projects (id INT,division VARCHAR(10)); INSERT INTO Projects (id,division) VALUES (1,'water'),(2,'transport'),(3,'energy'); CREATE TABLE WaterProjects (id INT,project_id INT,cost DECIMAL(10,2)); INSERT INTO WaterProjects (id,project_id,cost) VALUES (1,1,500000),(2,1,550000),(3,2,600000);
SELECT MIN(w.cost) FROM WaterProjects w JOIN Projects p ON w.project_id = p.id WHERE p.division = 'water';
How many sustainable tourism initiatives are there per country in 'sustainable_tourism_initiatives' table?
CREATE TABLE sustainable_tourism_initiatives (initiative_id INT,country VARCHAR(50),initiative VARCHAR(50)); INSERT INTO sustainable_tourism_initiatives (initiative_id,country,initiative) VALUES (1,'Mexico','Eco-tours'),(2,'Indonesia','Green hotels'),(3,'Mexico','Carbon offset programs');
SELECT country, COUNT(*) FROM sustainable_tourism_initiatives GROUP BY country;
Identify the warehouse with the highest number of packages shipped in the 'AMER' region
CREATE TABLE warehouses (id INT,name TEXT,region TEXT); INSERT INTO warehouses (id,name,region) VALUES (1,'Warehouse A','EMEA'),(2,'Warehouse B','APAC'),(3,'Warehouse C','AMER'),(4,'Warehouse D','AMER'); CREATE TABLE shipments (id INT,warehouse_id INT,packages INT); INSERT INTO shipments (id,warehouse_id,packages) VALUES (1,3,600),(2,3,800),(3,4,550),(4,4,750);
SELECT warehouses.name, SUM(shipments.packages) AS total_packages FROM warehouses JOIN shipments ON warehouses.id = shipments.warehouse_id WHERE warehouses.region = 'AMER' GROUP BY warehouses.name ORDER BY total_packages DESC LIMIT 1;
Which countries have received the most funding from the Global Environment Facility in the last 5 years?
CREATE TABLE climate_finance (id INT PRIMARY KEY,donor VARCHAR(100),recipient VARCHAR(100),amount FLOAT,year INT); INSERT INTO climate_finance (id,donor,recipient,amount,year) VALUES (1,'Global Environment Facility','Bangladesh',5000000,2018); INSERT INTO climate_finance (id,donor,recipient,amount,year) VALUES (2,'Global Environment Facility','India',8000000,2019); INSERT INTO climate_finance (id,donor,recipient,amount,year) VALUES (3,'Global Environment Facility','Nepal',3000000,2020); INSERT INTO climate_finance (id,donor,recipient,amount,year) VALUES (4,'Global Environment Facility','Pakistan',6000000,2021);
SELECT recipient, SUM(amount) as total_funding, YEAR(FROM_UNIXTIME(year)) as year FROM climate_finance WHERE donor = 'Global Environment Facility' AND YEAR(FROM_UNIXTIME(year)) >= YEAR(CURDATE()) - 5 GROUP BY recipient, year ORDER BY total_funding DESC;
Delete all workouts performed by 'John Doe' in 'Park City' gym using DELETE command
CREATE TABLE workouts (workout_id INT,member_id INT,gym_id INT,workout_date DATE,calories INT); INSERT INTO workouts (workout_id,member_id,gym_id,workout_date,calories) VALUES (1,1,1,'2022-01-01',300),(2,2,1,'2022-01-02',400),(3,1,2,'2022-01-03',500); CREATE TABLE members (member_id INT,name TEXT,age INT,gender TEXT); INSERT INTO members (member_id,name,age,gender) VALUES (1,'John Doe',30,'Male'),(2,'Jane Doe',28,'Female'); CREATE TABLE gyms (gym_id INT,name TEXT,city TEXT); INSERT INTO gyms (gym_id,name,city) VALUES (1,'Park City','New York'),(2,'Central Park','New York');
DELETE FROM workouts WHERE member_id IN (SELECT member_id FROM members WHERE name = 'John Doe') AND gym_id IN (SELECT gym_id FROM gyms WHERE city = 'New York' AND name = 'Park City');
What is the average speed of vessels that arrived in the port of Oakland in January 2022?
CREATE TABLE VesselArrivals (vessel_id INT,arrival_date DATE,speed DECIMAL(5,2)); INSERT INTO VesselArrivals (vessel_id,arrival_date,speed) VALUES (1,'2022-01-01',15.5),(2,'2022-01-15',18.3);
SELECT AVG(speed) FROM VesselArrivals WHERE arrival_date BETWEEN '2022-01-01' AND '2022-01-31';
Identify the top 2 candidates who belong to underrepresented racial or ethnic groups, ordered by application date in descending order, for each job title.
CREATE TABLE Applications (ApplicationID INT,CandidateName VARCHAR(50),RaceEthnicity VARCHAR(30),JobTitle VARCHAR(30),ApplicationDate DATE); INSERT INTO Applications (ApplicationID,CandidateName,RaceEthnicity,JobTitle,ApplicationDate) VALUES (1,'Jamal Johnson','African American','Manager','2022-01-01'),(2,'Sophia Rodriguez','Hispanic','Manager','2022-01-02'),(3,'Taro Nakamura','Asian','Developer','2022-01-03'),(4,'Aisha Williams','African American','Developer','2022-01-04');
SELECT JobTitle, CandidateName, ApplicationDate, ROW_NUMBER() OVER (PARTITION BY JobTitle ORDER BY CASE WHEN RaceEthnicity IN ('African American', 'Hispanic', 'Asian', 'Native American', 'Pacific Islander') THEN 1 ELSE 2 END, ApplicationDate DESC) AS Rank FROM Applications WHERE Rank <= 2;
List all green building certifications and the number of buildings certified under each in a specific region.
CREATE TABLE GreenBuildingCertifications (CertificationID INT,CertificationName VARCHAR(50));CREATE TABLE GreenBuildings (BuildingID INT,CertificationID INT);
SELECT GreenBuildingCertifications.CertificationName, COUNT(GreenBuildings.BuildingID) FROM GreenBuildingCertifications INNER JOIN GreenBuildings ON GreenBuildingCertifications.CertificationID = GreenBuildings.CertificationID WHERE GreenBuildings.Region = 'Northeast' GROUP BY GreenBuildingCertifications.CertificationName;
What is the total quantity of resources depleted in each region for the past 5 years?
CREATE TABLE resources (id INT,region TEXT,quantity FLOAT); CREATE TABLE depletions (resource_id INT,year INT,quantity FLOAT); INSERT INTO resources (id,region,quantity) VALUES (1,'Region A',50000.0),(2,'Region B',60000.0); INSERT INTO depletions (resource_id,year,quantity) VALUES (1,2017,5000.0),(1,2018,5500.0),(1,2019,6000.0),(1,2020,6500.0),(1,2021,7000.0),(2,2017,6000.0),(2,2018,6500.0),(2,2019,7000.0),(2,2020,7500.0),(2,2021,8000.0);
SELECT resources.region, SUM(depletions.quantity) FROM resources INNER JOIN depletions ON resources.id = depletions.resource_id WHERE depletions.year BETWEEN 2017 AND 2021 GROUP BY resources.region;
Update exhibition visitor counts based on actual data
CREATE TABLE DigitalExhibitions (exhibition_id INT,exhibition_name VARCHAR(50),estimated_visitors INT);
UPDATE DigitalExhibitions SET visitors = (SELECT COUNT(*) FROM DigitalVisitors WHERE exhibition_id = DigitalExhibitions.exhibition_id) WHERE EXISTS (SELECT * FROM DigitalVisitors WHERE DigitalExhibitions.exhibition_id = DigitalVisitors.exhibition_id);
Provide the number of employees and production rate of each mine in Canada.
CREATE TABLE canada_mines (id INT,mine_name TEXT,location TEXT,num_employees INT,production_rate FLOAT); INSERT INTO canada_mines (id,mine_name,location,num_employees,production_rate) VALUES (1,'Maple Mine','Ontario,Canada',500,15000.0),(2,'Pine Pit','Alberta,Canada',300,20000.0);
SELECT id, mine_name, location, num_employees, production_rate FROM canada_mines;
What is the number of unique users who have posted about 'recycling' in the 'waste_reduction' table and what is the maximum number of likes for their posts?
CREATE TABLE waste_reduction(user_id INT,post_date DATE,post_text TEXT,likes INT);
SELECT COUNT(DISTINCT user_id) AS users, MAX(likes) AS max_likes FROM waste_reduction WHERE post_text LIKE '%recycling%';
How many autonomous driving research papers were published by 'Wayve' in the 'research_papers' table?
CREATE TABLE research_papers (paper_id INT,title VARCHAR(100),author VARCHAR(50),publication_date DATE); CREATE VIEW wayve_papers AS SELECT * FROM research_papers WHERE author = 'Wayve';
SELECT COUNT(*) FROM wayve_papers;
What is the average price of vegan hair care products?
CREATE TABLE Products (id INT,name VARCHAR(50),category VARCHAR(50),price DECIMAL(5,2),vegan BOOLEAN); INSERT INTO Products (id,name,category,price,vegan) VALUES (1,'Nourishing Shampoo','Hair Care',10.99,true),(2,'Strengthening Conditioner','Hair Care',14.50,false),(3,'Volumizing Serum','Hair Care',18.99,true);
SELECT AVG(p.price) as avg_price FROM Products p WHERE p.category = 'Hair Care' AND p.vegan = true;
What is the total number of articles published by 'CNN' and 'Fox News' in the technology category?
CREATE TABLE cnn (article_id INT,title TEXT,category TEXT,publisher TEXT); INSERT INTO cnn (article_id,title,category,publisher) VALUES (1,'Article 1','Technology','CNN'),(2,'Article 2','Politics','CNN'); CREATE TABLE fox_news (article_id INT,title TEXT,category TEXT,publisher TEXT); INSERT INTO fox_news (article_id,title,category,publisher) VALUES (3,'Article 3','Business','Fox News'),(4,'Article 4','Technology','Fox News');
SELECT COUNT(*) FROM ( (SELECT * FROM cnn WHERE category = 'Technology') UNION (SELECT * FROM fox_news WHERE category = 'Technology') );
What is the minimum revenue of hotels in the Caribbean that offer virtual tours?
CREATE TABLE caribbean_hotels (hotel_id INT,hotel_name TEXT,country TEXT,revenue FLOAT,has_virtual_tour BOOLEAN); INSERT INTO caribbean_hotels (hotel_id,hotel_name,country,revenue,has_virtual_tour) VALUES (1,'The Beach Retreat','Bahamas',50000,true),(2,'The Island Inn','Jamaica',45000,false),(3,'Caribbean Resort','Puerto Rico',60000,true);
SELECT MIN(revenue) FROM caribbean_hotels WHERE has_virtual_tour = true AND country = 'Caribbean';
List the names and total funding of programs with an impact score above 80 and funded by private sources.
CREATE TABLE programs (name VARCHAR(25),impact_score INT,funding_source VARCHAR(15)); INSERT INTO programs (name,impact_score,funding_source) VALUES ('ProgramA',85,'private'),('ProgramB',70,'public'),('ProgramC',90,'private');
SELECT name, SUM(CASE WHEN funding_source = 'private' THEN 1 ELSE 0 END) AS total_private_funding FROM programs WHERE impact_score > 80 GROUP BY name;
How many space missions were led by astronauts from Canada?
CREATE TABLE SpaceMissions (id INT,name VARCHAR(50),leader_nationality VARCHAR(50)); INSERT INTO SpaceMissions (id,name,leader_nationality) VALUES (1,'Mars Science Laboratory','Canada'); INSERT INTO SpaceMissions (id,name,leader_nationality) VALUES (2,'CANDARM','Canada'); INSERT INTO SpaceMissions (id,name,leader_nationality) VALUES (3,'STS-41D','Canada');
SELECT COUNT(*) FROM SpaceMissions WHERE leader_nationality = 'Canada';
Count the number of users who have achieved a step count greater than 15000 for at least 20 days in the last 30 days.
CREATE TABLE user_steps (user_id INT,date DATE,steps INT);
SELECT COUNT(DISTINCT user_id) FROM user_steps WHERE steps > 15000 GROUP BY user_id HAVING COUNT(DISTINCT date) >= 20 AND date >= CURDATE() - INTERVAL 30 DAY;
Find the average construction cost of airports in the Northeast region
CREATE TABLE Airport (id INT,name VARCHAR(255),region VARCHAR(255),construction_cost DECIMAL(10,2)); INSERT INTO Airport (id,name,region,construction_cost) VALUES (1,'Airport A','Northeast',1000000.00),(2,'Airport B','Southeast',800000.00),(3,'Airport C','Northeast',1200000.00);
SELECT region, AVG(construction_cost) FROM Airport WHERE region = 'Northeast' GROUP BY region;
What is the minimum funding round size for companies founded in the last 5 years?
CREATE TABLE company (id INT,name TEXT,founding_year INT,founder_gender TEXT); INSERT INTO company (id,name,founding_year,founder_gender) VALUES (1,'Acme Inc',2015,'female'); INSERT INTO company (id,name,founding_year,founder_gender) VALUES (2,'Beta Corp',2018,'male');
SELECT MIN(funding_round_size) FROM investment_rounds INNER JOIN company ON investment_rounds.company_id = company.id WHERE company.founding_year >= (SELECT YEAR(CURRENT_DATE()) - 5);
Which genetic research projects ended between 2019 and 2020?
CREATE TABLE research_projects (proj_id INT,org_id INT,proj_status VARCHAR(50),proj_end_date DATE); INSERT INTO research_projects (proj_id,org_id,proj_status,proj_end_date) VALUES (1,1,'completed','2018-12-01'),(2,1,'in progress','2019-05-15'),(3,2,'completed','2020-08-30'),(4,2,'completed','2021-01-20'),(5,3,'in progress','2022-04-05'),(6,4,'completed','2019-06-25'),(7,4,'completed','2020-11-10');
SELECT * FROM research_projects WHERE proj_end_date BETWEEN '2019-01-01' AND '2020-12-31';
What is the total number of marine species observed in each Arctic country?
CREATE TABLE marine_species (id INT,country VARCHAR(255),species VARCHAR(255)); INSERT INTO marine_species (id,country,species) VALUES (1,'Canada','Beluga'),(2,'USA','Ringed Seal'),(3,'Norway','Polar Cod');
SELECT country, COUNT(species) FROM marine_species GROUP BY country;
Calculate the percentage of factories in each region that have implemented circular economy practices in the past 6 months.
CREATE TABLE Factories (FactoryID INT,FactoryName VARCHAR(50),CountryID INT,Region VARCHAR(50),CircularEconomy BOOLEAN); CREATE TABLE Countries (CountryID INT,CountryName VARCHAR(50),Continent VARCHAR(50)); INSERT INTO Factories VALUES (1,'Factory A',1,'Region A',TRUE),(2,'Factory B',2,'Region A',FALSE),(3,'Factory C',3,'Region B',TRUE),(4,'Factory D',1,'Region B',FALSE),(5,'Factory E',2,'Region C',TRUE); INSERT INTO Countries VALUES (1,'Kenya','Africa'),(2,'Nigeria','Africa'),(3,'India','Asia');
SELECT f.Region, COUNT(DISTINCT f.FactoryID) * 100.0 / (SELECT COUNT(DISTINCT FactoryID) FROM Factories WHERE CircularEconomy = TRUE) AS Percentage FROM Factories f JOIN Countries c ON f.CountryID = c.CountryID WHERE c.Continent = 'Africa' OR c.Continent = 'Asia' AND f.CircularEconomy = TRUE AND f.ImplementationDate >= DATEADD(month, -6, GETDATE()) GROUP BY f.Region;
Update the profile picture URL for user 'user4' in the 'professional' network.
CREATE TABLE users (id INT,username VARCHAR(255),network VARCHAR(255),profile_picture VARCHAR(255)); INSERT INTO users (id,username,network,profile_picture) VALUES (4,'user4','professional','old_url'),(5,'user5','social','new_url');
UPDATE users SET profile_picture = 'new_url' WHERE username = 'user4' AND network = 'professional';
Identify the top 3 countries with the highest number of agroecological practices.
CREATE TABLE agroecology (id INT,country TEXT,practice_count INT); INSERT INTO agroecology (id,country,practice_count) VALUES (1,'Country 1',50),(2,'Country 2',75),(3,'Country 3',100);
SELECT country, practice_count FROM agroecology ORDER BY practice_count DESC LIMIT 3;
List the number of beauty products that are both eco-friendly and cruelty-free, grouped by region
CREATE TABLE products (product_type VARCHAR(20),eco_friendly BOOLEAN,cruelty_free BOOLEAN,region VARCHAR(10)); INSERT INTO products (product_type,eco_friendly,cruelty_free,region) VALUES ('lipstick',TRUE,TRUE,'North'),('mascara',FALSE,FALSE,'North'),('eyeshadow',TRUE,TRUE,'West'),('blush',TRUE,FALSE,'South'),('foundation',TRUE,TRUE,'East');
SELECT region, COUNT(*) FROM products WHERE eco_friendly = TRUE AND cruelty_free = TRUE GROUP BY region;
How many biosensor technology patents were filed in 2020?
CREATE TABLE patents (id INT,patent_number VARCHAR(50),technology VARCHAR(50),filing_date DATE); INSERT INTO patents (id,patent_number,technology,filing_date) VALUES (1,'US2020012345','Biosensor','2020-03-15'); INSERT INTO patents (id,patent_number,technology,filing_date) VALUES (2,'US2020067890','Bioprocess','2020-11-28');
SELECT COUNT(*) FROM patents WHERE technology = 'Biosensor' AND YEAR(filing_date) = 2020;
Who is the community health worker with the least mental health parity consultations in New York?
CREATE TABLE community_health_workers (id INT,name TEXT,zip TEXT,consultations INT); INSERT INTO community_health_workers (id,name,zip,consultations) VALUES (1,'Fatima Ahmed','10001',10),(2,'Michael Chen','11201',15); CREATE VIEW ny_workers AS SELECT * FROM community_health_workers WHERE zip BETWEEN '10001' AND '11999';
SELECT name FROM ny_workers WHERE consultations = (SELECT MIN(consultations) FROM ny_workers);
Rank research labs by total funding in India.
CREATE TABLE research_labs (id INT,name TEXT,country TEXT,funding FLOAT); INSERT INTO research_labs (id,name,country,funding) VALUES (1,'LabA','India',1500000.0),(2,'LabB','India',1200000.0),(3,'LabC','UK',900000.0);
SELECT name, ROW_NUMBER() OVER (ORDER BY funding DESC) as rank FROM research_labs WHERE country = 'India';
What is the average rating of "sustainable" products in the "haircare" category?
CREATE TABLE products_categories (id INT,product VARCHAR(100),category VARCHAR(100),rating FLOAT,sustainable BOOLEAN);
SELECT AVG(rating) FROM products_categories WHERE sustainable = TRUE AND category = 'haircare';
Identify the top 3 public health policy violations in the Eastern region by case count.
CREATE TABLE eastern_violations (region VARCHAR(255),violation VARCHAR(255),cases INT); INSERT INTO eastern_violations (region,violation,cases) VALUES ('Eastern','Noise Complaint',500); INSERT INTO eastern_violations (region,violation,cases) VALUES ('Eastern','Littering',400); INSERT INTO eastern_violations (region,violation,cases) VALUES ('Eastern','Speeding',300);
SELECT violation, SUM(cases) AS total_cases FROM eastern_violations GROUP BY violation ORDER BY total_cases DESC LIMIT 3;