instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
What is the total amount donated by each donor and the total number of donations for each donor?
CREATE TABLE donations (donor_id INT,donation_date DATE,amount DECIMAL(10,2)); INSERT INTO donations (donor_id,donation_date,amount) VALUES (1,'2021-01-01',50.00),(2,'2021-01-15',100.00),(1,'2021-03-05',200.00);
SELECT donor_id, SUM(amount) AS total_donated, COUNT(*) AS num_donations FROM donations GROUP BY donor_id;
What is the distribution of startups founded by people from different countries in the fintech sector by founding year?
CREATE TABLE companies (id INT,name TEXT,founding_year INT,industry TEXT,founder_country TEXT);
SELECT founding_year, founder_country, COUNT(*) FROM companies WHERE industry = 'fintech' GROUP BY founding_year, founder_country;
Insert a new program outcome record for literacy program in Kenya with 15 participants.
CREATE TABLE ProgramOutcomes (id INT,program VARCHAR(255),country VARCHAR(255),participants INT);
INSERT INTO ProgramOutcomes (program, country, participants) VALUES ('Literacy Program', 'Kenya', 15);
What is the average price of sustainable products in the 'Health & Beauty' category sold by retailers located in New York?
CREATE TABLE retailers (retailer_id INT,retailer_name VARCHAR(255),state VARCHAR(255)); INSERT INTO retailers (retailer_id,retailer_name,state) VALUES (1,'Eco-Friendly Goods','New York'); CREATE TABLE products (product_id INT,product_name VARCHAR(255),price DECIMAL(5,2),sustainable BOOLEAN,retailer_id INT); INSERT INTO products (product_id,product_name,price,sustainable,retailer_id) VALUES (1,'Organic Shampoo',14.99,true,1); INSERT INTO products (product_id,product_name,price,sustainable,retailer_id) VALUES (2,'Natural Conditioner',12.49,true,1);
SELECT AVG(price) FROM products JOIN retailers ON products.retailer_id = retailers.retailer_id WHERE sustainable = true AND category = 'Health & Beauty' AND state = 'New York';
Calculate the total number of founders who are immigrants and have founded a company in the biotech industry.
CREATE TABLE companies (id INT,name TEXT,industry TEXT,founding_date DATE,founder_country TEXT,founder_immigrant BOOLEAN);CREATE VIEW founders AS SELECT DISTINCT company_id,founder_id FROM company_founders;
SELECT COUNT(DISTINCT founders.founder_id) FROM founders INNER JOIN companies ON founders.company_id = companies.id WHERE companies.industry = 'biotech' AND companies.founder_immigrant = true;
Count the number of cultivators in the Pacific Northwest region without a valid compliance certificate.
CREATE TABLE Cultivators (cultivator_id INT,region TEXT,compliance_certificate BOOLEAN);
SELECT COUNT(cultivator_id) FROM Cultivators WHERE region = 'Pacific Northwest' AND compliance_certificate = FALSE;
How many users have posted more than 5 times in the 'users' and 'posts' tables?
CREATE TABLE users (id INT,name VARCHAR(50),age INT,gender VARCHAR(10)); INSERT INTO users (id,name,age,gender) VALUES (1,'Alice',25,'Female'),(2,'Bob',30,'Male'); CREATE TABLE posts (id INT,user_id INT,content TEXT,timestamp DATETIME); INSERT INTO posts (id,user_id,content,timestamp) VALUES (1,1,'Hello World!','2022-01-01 10:00:00'),(2,1,'First post','2022-01-02 11:00:00'),(3,2,'SQL practice','2022-01-03 12:00:00'),(4,1,'Third post','2022-01-04 13:00:00'),(5,1,'Fourth post','2022-01-05 14:00:00'),(6,1,'Fifth post','2022-01-06 15:00:00'),(7,1,'Sixth post','2022-01-07 16:00:00');
SELECT COUNT(DISTINCT u.id) FROM users u JOIN posts p ON u.id = p.user_id GROUP BY u.id HAVING COUNT(p.id) > 5;
list all unique news topics
CREATE TABLE News (id INT,topic VARCHAR(50)); INSERT INTO News (id,topic) VALUES (1,'Politics'); INSERT INTO News (id,topic) VALUES (2,'Sports'); INSERT INTO News (id,topic) VALUES (3,'Entertainment');
SELECT DISTINCT topic FROM News;
What is the average CO2 emissions of materials used in production per country?
CREATE TABLE ProductionMaterials (id INT,name TEXT,co2_emissions INT,country TEXT); INSERT INTO ProductionMaterials (id,name,co2_emissions,country) VALUES (1,'Organic Cotton',4,'USA'),(2,'Recycled Polyester',7,'Mexico'),(3,'Hemp',2,'India'),(4,'Tencel',3,'Bangladesh');
SELECT country, AVG(co2_emissions) FROM ProductionMaterials GROUP BY country;
Find the names of graduate students who have never received a research grant.
CREATE TABLE grad_students (id INT,name VARCHAR(50));CREATE TABLE research_grants (id INT,grant_id INT,student_id INT);
SELECT DISTINCT gs.name FROM grad_students gs LEFT JOIN research_grants rg ON gs.id = rg.student_id WHERE rg.id IS NULL;
What is the cultural competency score of each healthcare provider?
CREATE TABLE Providers (ProviderID int,ProviderName varchar(50));CREATE TABLE CulturalCompetency (CCID int,ProviderID int,Score int);
SELECT ProviderName, AVG(Score) as AvgScore FROM CulturalCompetency JOIN Providers ON CulturalCompetency.ProviderID = Providers.ProviderID GROUP BY ProviderID, ProviderName;
Show the number of animals in each habitat
CREATE TABLE if not exists habitat_info (id INT,habitat VARCHAR(255),animal VARCHAR(255)); INSERT INTO habitat_info (id,habitat,animal) VALUES (1,'Forest','Tiger'),(2,'Forest','Elephant'),(3,'Grassland','Lion'),(4,'Grassland','Giraffe'),(5,'Wetlands','Crocodile'),(6,'Forest','Rhinoceros');
SELECT habitat, COUNT(animal) FROM habitat_info GROUP BY habitat;
What is the average cargo weight transported by vessels flying the flag of Singapore to Africa in Q1 2022?
CREATE TABLE Cargo (CargoID INT,VesselFlag VARCHAR(50),Destination VARCHAR(50),CargoWeight INT,TransportDate DATE); INSERT INTO Cargo VALUES (1,'Singapore','Africa',13000,'2022-01-05'),(2,'Marshall Islands','Asia',20000,'2022-02-15'),(3,'Singapore','Africa',14000,'2022-03-20');
SELECT AVG(CargoWeight) FROM Cargo WHERE VesselFlag = 'Singapore' AND Destination = 'Africa' AND TransportDate >= '2022-01-01' AND TransportDate <= '2022-03-31';
Display the structure of the 'farmers' table
CREATE TABLE farmers (id INT PRIMARY KEY,name VARCHAR(50),age INT,gender VARCHAR(10),location VARCHAR(50),profession VARCHAR(50)); INSERT INTO farmers (id,name,age,gender,location,profession) VALUES (1,'John Doe',35,'Male','USA','Farmer'),(2,'Jane Smith',40,'Female','Canada','Farmer');
DESCRIBE farmers;
What is the total data usage for each mobile plan in the last quarter?
CREATE TABLE mobile_plans (id INT,name VARCHAR(50),price DECIMAL(5,2)); INSERT INTO mobile_plans (id,name,price) VALUES (1,'PlanA',30.00),(2,'PlanB',45.00); CREATE TABLE data_usage (date DATE,plan_id INT,data_used INT); INSERT INTO data_usage (date,plan_id,data_used) VALUES ('2022-01-01',1,2000),('2022-01-01',2,3000);
SELECT m.name, SUM(du.data_used) as total_data_usage FROM mobile_plans m INNER JOIN data_usage du ON m.id = du.plan_id WHERE du.date BETWEEN DATE_SUB(CURDATE(), INTERVAL 3 MONTH) AND CURDATE() GROUP BY m.name;
What is the name of the intelligence operation and the number of personnel involved in the 'intelligence_ops' view for the year 2020?
CREATE VIEW intelligence_ops AS SELECT op_id,type,location,num_personnel,report_date FROM intelligence_operations WHERE status = 'completed'; CREATE TABLE intelligence_operations (op_id INT PRIMARY KEY,type VARCHAR(50),location VARCHAR(100),num_personnel INT,report_date DATE,status VARCHAR(50)); INSERT INTO intelligence_operations (op_id,type,location,num_personnel,report_date,status) VALUES (1,'Operation Red Sparrow',100,'2020-06-12'),(2,'Operation Iron Eagle',150,'2019-09-28');
SELECT type, num_personnel FROM intelligence_ops WHERE YEAR(report_date) = 2020;
Show the average food safety inspection score by restaurant location for the last year.
CREATE TABLE inspections (inspection_id INT,restaurant_id INT,date DATE,score INT); INSERT INTO inspections (inspection_id,restaurant_id,date,score) VALUES (1,1,'2022-02-01',95),(2,1,'2022-03-01',90),(3,2,'2022-02-15',85),(4,2,'2022-03-15',92); CREATE TABLE restaurants (restaurant_id INT,name VARCHAR(255),location VARCHAR(255)); INSERT INTO restaurants (restaurant_id,name,location) VALUES (1,'Restaurant A','City A'),(2,'Restaurant B','City B');
SELECT r.location, AVG(i.score) as avg_score FROM inspections i JOIN restaurants r ON i.restaurant_id = r.restaurant_id WHERE i.date >= DATE(NOW()) - INTERVAL 365 DAY GROUP BY r.location;
List the unique first names of all instructors who have taught at least one Zumba class in the entire year of 2021.
CREATE TABLE Instructors (InstructorID int,FirstName varchar(20)); INSERT INTO Instructors (InstructorID,FirstName) VALUES (1,'Jane'),(2,'Jim'),(3,'Janet'); CREATE TABLE Classes (ClassID int,InstructorID int,ClassType varchar(10)); INSERT INTO Classes (ClassID,InstructorID,ClassType) VALUES (1,1,'Zumba'),(2,2,'Yoga'),(3,3,'Pilates');
SELECT DISTINCT FirstName FROM Instructors i WHERE EXISTS (SELECT 1 FROM Classes c WHERE i.InstructorID = c.InstructorID AND c.ClassType = 'Zumba');
Display the name and region for pollution sources in the pollution_sources table, partitioned by pollution amount in 10 equal groups and ordered by pollution amount in ascending order.
CREATE TABLE pollution_sources (id INT,name VARCHAR(255),region VARCHAR(255),pollution_amount INT); INSERT INTO pollution_sources (id,name,region,pollution_amount) VALUES (1,'Oceanic Chemical Pollution','Atlantic Ocean',60000); INSERT INTO pollution_sources (id,name,region,pollution_amount) VALUES (2,'Marine Debris','Indian Ocean',30000);
SELECT name, region, NTILE(10) OVER (ORDER BY pollution_amount) AS pollution_group FROM pollution_sources ORDER BY pollution_amount ASC;
Which companies have manufactured spacecraft with a mass of over 5000 kg?
CREATE TABLE SpacecraftManufacturing (ID INT,Manufacturer VARCHAR(255),Mass INT); INSERT INTO SpacecraftManufacturing (ID,Manufacturer,Mass) VALUES (1,'SpaceCorp',3000),(2,'Galactic',6000),(3,'Cosmos',4000);
SELECT Manufacturer FROM SpacecraftManufacturing WHERE Mass > 5000;
How many veterans are currently employed in each veteran status category?
CREATE TABLE Veterans (VeteranID INT,VeteranName VARCHAR(50),VeteranAge INT,VeteranGender VARCHAR(10),VeteranStatus VARCHAR(20),VeteranEmploymentStatus VARCHAR(20),PRIMARY KEY (VeteranID)); CREATE VIEW VeteranSummary AS SELECT VeteranStatus,COUNT(*) as TotalVeterans FROM Veterans GROUP BY VeteranStatus;
SELECT VeteranStatus, TotalVeterans FROM VeteranSummary WHERE VeteranEmploymentStatus = 'Employed';
Show the total number of defense contracts awarded to companies in Texas and Florida.
CREATE TABLE defense_contracts (contract_id INT,company_name VARCHAR(100),state VARCHAR(50),contract_value FLOAT);
SELECT SUM(contract_value) FROM defense_contracts WHERE state IN ('Texas', 'Florida');
What are the total number of marine protected areas in Southeast Asia?
CREATE TABLE Southeast_Asia_MPAs (mpa_name TEXT,country TEXT); INSERT INTO Southeast_Asia_MPAs (mpa_name,country) VALUES ('Tubbataha Reefs Natural Park','Philippines'),('Sundarbans National Park','India'),('Belum-Temengor','Malaysia');
SELECT COUNT(*) FROM Southeast_Asia_MPAs;
How many employees were hired in Q1 of 2021?
CREATE TABLE HiringData (HireDate DATE,EmployeeID INT); INSERT INTO HiringData (HireDate,EmployeeID) VALUES ('2021-01-01',1),('2021-03-15',2),('2020-12-31',3),('2021-01-10',4);
SELECT COUNT(*) FROM HiringData WHERE HireDate BETWEEN '2021-01-01' AND '2021-03-31';
List all train stations with their corresponding line names and number of platforms.
CREATE TABLE train_lines (line_id INT,line_name TEXT); CREATE TABLE train_stations (station_id INT,station_name TEXT,line_id INT,num_platforms INT); INSERT INTO train_lines VALUES (1,'Line 1'),(2,'Line 2'),(3,'Line 3'); INSERT INTO train_stations VALUES (1,'Station A',1,4),(2,'Station B',1,6),(3,'Station C',2,2),(4,'Station D',3,8);
SELECT train_stations.station_name, train_lines.line_name, train_stations.num_platforms FROM train_stations INNER JOIN train_lines ON train_stations.line_id = train_lines.line_id;
What is the average age of players who have played VR games, and how many VR games have been released?
CREATE TABLE Players (PlayerID INT,Age INT,Gender VARCHAR(10)); INSERT INTO Players VALUES (1,25,'Male'),(2,30,'Female'),(3,35,'Non-binary'); CREATE TABLE Games (GameID INT,GameName VARCHAR(20),Genre VARCHAR(10),VR BIT); INSERT INTO Games VALUES (1,'GameA','Action',1),(2,'GameB','Puzzle',0),(3,'GameC','Adventure',1);
SELECT AVG(Players.Age) AS AvgAge, COUNT(Games.GameID) AS VRGameCount FROM Players INNER JOIN Games ON Players.PlayerID = Games.GameID WHERE Games.VR = 1;
How many defense contracts were awarded to companies from Canada in 2021?
CREATE TABLE defense_contracts (id INT,company VARCHAR(50),country VARCHAR(50),year INT,contract_value FLOAT); INSERT INTO defense_contracts (id,company,country,year,contract_value) VALUES (1,'Lockheed Martin Canada','Canada',2021,10000000); INSERT INTO defense_contracts (id,company,country,year,contract_value) VALUES (2,'Bombardier Inc.','Canada',2021,5000000);
SELECT COUNT(*) FROM defense_contracts WHERE country = 'Canada' AND year = 2021;
Delete records of a specific drug from drug_approval table
CREATE TABLE drug_approval (drug_code CHAR(5),approval_date DATE); INSERT INTO drug_approval (drug_code,approval_date) VALUES ('DR001','2020-01-01'),('DR002','2019-01-01');
DELETE FROM drug_approval WHERE drug_code = 'DR001';
What is the percentage of vegan dishes in the menu?
CREATE TABLE menu_items (item VARCHAR(50),type VARCHAR(15),cost DECIMAL(10,2)); INSERT INTO menu_items (item,type,cost) VALUES ('Vegan Pizza','Vegan',12.00),('Vegan Pasta','Vegan',15.00); CREATE VIEW vegan_menu_items AS SELECT item FROM menu_items WHERE type = 'Vegan'; CREATE VIEW total_menu_items AS SELECT COUNT(*) as num_items FROM menu_items;
SELECT 100.0 * COUNT(*) / (SELECT num_items FROM total_menu_items) as percentage FROM vegan_menu_items;
Insert new team records into the 'esports_teams' table
CREATE TABLE esports_teams (team_id INT,team_name VARCHAR(50));
INSERT INTO esports_teams (team_id, team_name) VALUES (1, 'Phoenix Rising'), (2, 'Titan Squad'), (3, 'Cosmic Force');
Which mining operations have a labor productivity higher than 200?
CREATE TABLE work (id INT,mining_operation TEXT,productivity FLOAT); INSERT INTO work (id,mining_operation,productivity) VALUES (1,'Operation A',150.5); INSERT INTO work (id,mining_operation,productivity) VALUES (2,'Operation B',250.3);
SELECT mining_operation FROM work WHERE productivity > 200;
Which menu items had sales over 100 in January 2022?
CREATE TABLE menu_sales_2 (item VARCHAR(255),sales INTEGER,sale_date DATE); INSERT INTO menu_sales_2 (item,sales,sale_date) VALUES ('Burger',150,'2022-01-01'),('Pizza',200,'2022-01-01'),('Burger',120,'2022-01-02');
SELECT item, sales FROM menu_sales_2 WHERE sale_date BETWEEN '2022-01-01' AND '2022-01-31' AND sales > 100;
What is the gender distribution among visual art workshop participants?
CREATE TABLE VisualArtWorkshops (id INT,title VARCHAR(50),participants INT); INSERT INTO VisualArtWorkshops (id,title,participants) VALUES (1,'Watercolor Workshop',30); INSERT INTO VisualArtWorkshops (id,title,participants) VALUES (2,'Drawing Workshop',25); CREATE TABLE VisualArtWorkshopParticipants (id INT,workshop_id INT,gender VARCHAR(10),age INT); INSERT INTO VisualArtWorkshopParticipants (id,workshop_id,gender,age) VALUES (1,1,'Female',25); INSERT INTO VisualArtWorkshopParticipants (id,workshop_id,gender,age) VALUES (2,1,'Male',30); INSERT INTO VisualArtWorkshopParticipants (id,workshop_id,gender,age) VALUES (3,2,'Non-binary',22);
SELECT w.title, p.gender, COUNT(*) as participants FROM VisualArtWorkshops w JOIN VisualArtWorkshopParticipants p ON w.id = p.workshop_id GROUP BY p.gender;
What was the average weight of stone artifacts, per country?
CREATE TABLE artifact_details (id INT,artifact_id INT,artifact_type VARCHAR(50),weight INT);
SELECT country, AVG(CASE WHEN artifact_type = 'stone' THEN weight ELSE NULL END) as avg_weight FROM excavation_sites GROUP BY country
How many local vendors have partnered with our platform in Spain?
CREATE TABLE vendors (id INT,name TEXT,country TEXT); INSERT INTO vendors (id,name,country) VALUES (1,'Vendor A','Spain'),(2,'Vendor B','France');
SELECT COUNT(*) FROM vendors WHERE country = 'Spain';
Calculate the number of donations to social justice organizations in the UK.
CREATE TABLE organization (org_id INT PRIMARY KEY,name VARCHAR(255),industry VARCHAR(255),country VARCHAR(255)); INSERT INTO organization (org_id,name,industry,country) VALUES (3,'Justice for All','Nonprofit','UK');
SELECT COUNT(*) FROM (SELECT donation.donation_id FROM donation JOIN organization ON donation.org_id = organization.org_id WHERE organization.country = 'UK' AND organization.industry = 'Nonprofit' AND organization.name = 'Justice for All') AS donation_subquery;
What is the maximum monthly data usage for broadband subscribers?
CREATE TABLE broadband_usage (id INT,name VARCHAR(50),data_usage FLOAT); INSERT INTO broadband_usage (id,name,data_usage) VALUES (1,'Jim Brown',200.0);
SELECT MAX(data_usage) FROM broadband_usage WHERE data_usage > 0;
Find the total revenue generated by organic farming in the Northeast region.
CREATE TABLE organic_farming (farmer_id INT,name VARCHAR(30),region VARCHAR(20),revenue REAL); INSERT INTO organic_farming (farmer_id,name,region,revenue) VALUES (1,'Smith','Northeast',12000),(2,'Johnson','Northeast',15000),(3,'Williams','Midwest',9000),(4,'Brown','Southwest',18000),(5,'Jones','Northeast',11000);
SELECT SUM(revenue) FROM organic_farming WHERE region = 'Northeast';
What is the total amount of water treated in wastewater treatment plants in the New York region in the last month?
CREATE TABLE wastewater_treatment (region VARCHAR(20),plant_id INT,treated_water FLOAT,timestamp TIMESTAMP); INSERT INTO wastewater_treatment (region,plant_id,treated_water,timestamp) VALUES ('New York',1,500000,'2022-01-01 10:00:00'),('New York',2,600000,'2022-02-01 10:00:00');
SELECT SUM(treated_water) FROM wastewater_treatment WHERE region = 'New York' AND timestamp BETWEEN DATE_SUB(CURRENT_TIMESTAMP, INTERVAL 1 MONTH) AND CURRENT_TIMESTAMP;
What is the average age and total number of beneficiaries in each country, grouped by their registration date?
CREATE TABLE Beneficiaries (id INT,name VARCHAR(50),gender VARCHAR(50),age INT,country VARCHAR(50),registration_date DATE); INSERT INTO Beneficiaries (id,name,gender,age,country,registration_date) VALUES (1,'Ahmed','Male',25,'Egypt','2020-12-12'),(2,'Bella','Female',35,'Nigeria','2021-01-01'),(3,'Charlie','Male',45,'Mexico','2022-03-03');
SELECT country, registration_date, AVG(age) as avg_age, COUNT(*) as total_beneficiaries FROM Beneficiaries GROUP BY country, registration_date;
Update the address of the contractor 'BMC' in the 'contractors' table
CREATE TABLE contractors (contractor_id INT,name VARCHAR(50),address VARCHAR(100));
UPDATE contractors SET address = '123 Green Street' WHERE name = 'BMC';
Delete records of tourists visiting Greece in 2022 from the UK.
CREATE TABLE tourism_data (id INT,country VARCHAR(50),destination VARCHAR(50),arrival_date DATE,age INT); INSERT INTO tourism_data (id,country,destination,arrival_date,age) VALUES (17,'UK','Greece','2022-03-01',36),(18,'UK','Greece','2022-07-22',41);
DELETE FROM tourism_data WHERE country = 'UK' AND destination = 'Greece' AND YEAR(arrival_date) = 2022;
What are the names of all bridges in the 'infrastructure' schema that are taller than 100 meters?
CREATE TABLE bridges (name VARCHAR(255),height INT); INSERT INTO bridges (name,height) VALUES ('Bridge1',120),('Bridge2',90),('Bridge3',110);
SELECT name FROM bridges WHERE height > 100;
What is the total revenue for each platform in the 'digital_sales' table, joined with the 'platform' table?
CREATE TABLE platform (platform_id INT,platform_name VARCHAR(255)); CREATE TABLE digital_sales (sale_id INT,song_id INT,platform_id INT,sales_revenue DECIMAL(10,2));
SELECT p.platform_name, SUM(ds.sales_revenue) AS total_revenue FROM platform p INNER JOIN digital_sales ds ON p.platform_id = ds.platform_id GROUP BY p.platform_name;
What is the total waste generation in grams for each South American country in 2021?
CREATE TABLE waste_generation (country VARCHAR(50),year INT,continent VARCHAR(50),waste_generation FLOAT); INSERT INTO waste_generation (country,year,continent,waste_generation) VALUES ('Brazil',2021,'South America',6000),('Argentina',2021,'South America',5000),('Colombia',2021,'South America',4000);
SELECT country, SUM(waste_generation) FROM waste_generation WHERE year = 2021 AND continent = 'South America' GROUP BY country;
Which defense contractors have performed maintenance on military aircraft more than 100 times in the last 6 months?
CREATE TABLE defense_contractors (contractor_id INT,contractor_name VARCHAR(255));CREATE TABLE military_aircraft (aircraft_id INT,contractor_id INT,last_maintenance_date DATE); INSERT INTO defense_contractors (contractor_id,contractor_name) VALUES (1,'Contractor1'),(2,'Contractor2'),(3,'Contractor3'); INSERT INTO military_aircraft (aircraft_id,contractor_id,last_maintenance_date) VALUES (1,1,'2022-01-01'),(2,1,'2022-02-15'),(3,2,'2022-03-01'),(4,3,'2022-04-10'),(5,1,'2022-05-12'),(6,2,'2022-06-01');
SELECT contractor_name FROM defense_contractors d JOIN military_aircraft ma ON d.contractor_id = ma.contractor_id WHERE ma.last_maintenance_date >= DATE_SUB(CURRENT_DATE, INTERVAL 6 MONTH) GROUP BY contractor_name HAVING COUNT(ma.aircraft_id) > 100;
Which satellites were deployed by SpaceTech Inc. between 2000 and 2010?
CREATE TABLE satellites (satellite_id INT,name VARCHAR(100),manufacturer VARCHAR(100),launch_date DATE); INSERT INTO satellites (satellite_id,name,manufacturer,launch_date) VALUES (1,'Sat1','SpaceTech Inc.','2005-03-14'); INSERT INTO satellites (satellite_id,name,manufacturer,launch_date) VALUES (2,'Sat2','Aerospace Corp.','2008-09-27'); INSERT INTO satellites (satellite_id,name,manufacturer,launch_date) VALUES (3,'Sat3','SpaceTech Inc.','2002-11-17');
SELECT name FROM satellites WHERE manufacturer = 'SpaceTech Inc.' AND launch_date BETWEEN '2000-01-01' AND '2010-12-31';
What is the average ESG score for all companies?
CREATE TABLE companies (id INT,name VARCHAR(255),sector VARCHAR(255),ESG_score FLOAT); INSERT INTO companies (id,name,sector,ESG_score) VALUES (1,'Google','Technology',80.0),(2,'Apple','Technology',85.0),(3,'Johnson & Johnson','Healthcare',82.0);
SELECT AVG(ESG_score) FROM companies;
Add a new wind turbine with id 5 and capacity 2000 in the 'renewable_energy' table
CREATE TABLE renewable_energy (id INT,type VARCHAR(50),capacity INT);
INSERT INTO renewable_energy (id, type, capacity) VALUES (5, 'wind turbine', 2000);
Identify the average ESG scores of companies in the agriculture sector in Europe and Asia.
CREATE TABLE regions (id INT,company_id INT,region TEXT); INSERT INTO regions (id,company_id,region) VALUES (1,3,'Germany'),(2,4,'France'),(3,5,'China'),(4,6,'Japan');
SELECT companies.sector, AVG(companies.ESG_score) AS avg_ESG_score FROM companies INNER JOIN regions ON companies.id = regions.company_id WHERE companies.sector = 'Agriculture' AND (regions.region = 'Europe' OR regions.region = 'Asia') GROUP BY companies.sector;
What is the average donation amount per month for each program in Brazil?
CREATE TABLE Donations (id INT,donation_amount DECIMAL(10,2),donation_date DATE,program VARCHAR(50),country VARCHAR(50)); CREATE TABLE Programs (id INT,program VARCHAR(50),country VARCHAR(50)); INSERT INTO Donations (id,donation_amount,donation_date,program,country) VALUES (1,100.00,'2021-01-01','Health','Brazil'); INSERT INTO Donations (id,donation_amount,donation_date,program,country) VALUES (2,200.00,'2021-01-02','Education','Brazil'); INSERT INTO Programs (id,program,country) VALUES (1,'Health','Brazil'); INSERT INTO Programs (id,program,country) VALUES (2,'Education','Brazil');
SELECT p.program, EXTRACT(MONTH FROM d.donation_date) as month, AVG(d.donation_amount) as avg_donation_per_month FROM Donations d INNER JOIN Programs p ON d.program = p.program WHERE d.country = 'Brazil' GROUP BY p.program, month;
What is the average salary of female workers in the 'technology' department?
CREATE TABLE employees (id INT,name VARCHAR(255),department VARCHAR(255),salary FLOAT); INSERT INTO employees (id,name,department,salary) VALUES (1,'John Doe','technology',80000.00),(2,'Jane Smith','technology',75000.00),(3,'Alice Johnson','marketing',70000.00);
SELECT AVG(salary) FROM employees WHERE department = 'technology' AND gender = 'female';
How many marine species are endangered in the Indian Ocean?
CREATE TABLE marine_species (name TEXT,region TEXT,endangered BOOLEAN); INSERT INTO marine_species (name,region,endangered) VALUES ('Whale Shark','Indian Ocean',TRUE),('Dugong','Indian Ocean',TRUE);
SELECT COUNT(*) FROM marine_species WHERE region = 'Indian Ocean' AND endangered = TRUE;
Delete records of 'yellow' line maintenance.
CREATE TABLE maintenance (line VARCHAR(10),date DATE,type VARCHAR(20)); INSERT INTO maintenance (line,date,type) VALUES ('red','2022-01-01','routine'),('red','2022-02-01','emergency'),('blue','2022-03-01','routine'),('yellow','2022-04-01','routine'),('yellow','2022-05-01','emergency');
DELETE FROM maintenance WHERE line = 'yellow';
Identify the minimum budget required for AI projects in all continents.
CREATE TABLE ai_projects_2 (project_id INT,region VARCHAR(20),budget DECIMAL(10,2)); INSERT INTO ai_projects_2 (project_id,region,budget) VALUES (1,'North America',50000.00),(2,'Latin America',25000.00),(3,'Europe',70000.00),(4,'Asia',30000.00),(5,'Africa',40000.00);
SELECT MIN(budget) FROM ai_projects_2;
What is the maximum daily passenger capacity for international flights from India?
CREATE TABLE flights (id INT,origin VARCHAR(20),destination VARCHAR(20),daily_capacity INT,passenger_count INT); INSERT INTO flights (id,origin,destination,daily_capacity,passenger_count) VALUES (1,'India','US',300,250),(2,'India','UK',250,220),(3,'India','Canada',200,180);
SELECT MAX(daily_capacity) FROM flights WHERE origin = 'India';
Delete records from construction_projects table where city is 'GreenValley' and completion_date is before '2020-01-01'
CREATE TABLE construction_projects (id INT,city VARCHAR(20),completion_date DATE);
DELETE FROM construction_projects WHERE city = 'GreenValley' AND completion_date < '2020-01-01';
Identify the top 3 states with the highest number of military equipment types
CREATE TABLE equipment (equipment_id INT,equipment_type TEXT,state TEXT); INSERT INTO equipment (equipment_id,equipment_type,state) VALUES (1,'Tank','California'),(2,'Helicopter','Texas'),(3,'Fighter Jet','California'),(4,'Artillery','New York'),(5,'Tank','Texas'),(6,'Helicopter','California'),(7,'Artillery','New York');
SELECT state, COUNT(DISTINCT equipment_type) as equipment_types FROM equipment GROUP BY state ORDER BY equipment_types DESC LIMIT 3;
Identify the circular economy initiatives in 'Germany'
CREATE TABLE circular_economy (id INT,initiative VARCHAR(50),country VARCHAR(20)); INSERT INTO circular_economy (id,initiative,country) VALUES (1,'Recycling Program','Germany'),(2,'Waste Reduction Campaign','Germany');
SELECT initiative FROM circular_economy WHERE country = 'Germany';
What is the total billing amount for each attorney, grouped by their respective practice areas?
CREATE TABLE Attorneys (AttorneyID INT,Name VARCHAR(50),PracticeArea VARCHAR(50)); INSERT INTO Attorneys (AttorneyID,Name,PracticeArea) VALUES (1,'Smith','Civil Law'),(2,'Jones','Criminal Law'); CREATE TABLE Billing (BillID INT,AttorneyID INT,Amount DECIMAL(10,2)); INSERT INTO Billing (BillID,AttorneyID,Amount) VALUES (1,1,500),(2,1,750),(3,2,800);
SELECT p.PracticeArea, SUM(b.Amount) AS TotalBilling FROM Attorneys p JOIN Billing b ON p.AttorneyID = b.AttorneyID GROUP BY p.PracticeArea;
What is the maximum daily production of Terbium in 2018 from the Daily_Production table?
CREATE TABLE Daily_Production (date DATE,terbium_production FLOAT);
SELECT MAX(terbium_production) FROM Daily_Production WHERE EXTRACT(YEAR FROM date) = 2018;
How many unique materials are used in the production of products that are both ethically sourced and have a circular supply chain?
CREATE TABLE products (product_id INT,is_ethically_sourced BOOLEAN,has_circular_supply_chain BOOLEAN,raw_material VARCHAR(50));
SELECT COUNT(DISTINCT raw_material) FROM products WHERE is_ethically_sourced = TRUE AND has_circular_supply_chain = TRUE;
What is the maximum revenue generated in a single day for the "Modern Art" exhibition?
CREATE TABLE daily_revenue (date DATE,exhibition_id INT,revenue DECIMAL(5,2)); INSERT INTO daily_revenue (date,exhibition_id,revenue) VALUES ('2022-01-01',9,700.00),('2022-01-02',9,800.00),('2022-01-03',10,900.00);
SELECT MAX(revenue) FROM daily_revenue WHERE exhibition_id = 9;
How many aquaculture sites are present in each country, ranked by the number of species per site?
CREATE TABLE aquaculture_sites (site_id INT,country VARCHAR(50),species INT); INSERT INTO aquaculture_sites VALUES (1,'Norway',5),(2,'Norway',3),(3,'Canada',4),(4,'Canada',6),(5,'USA',2),(6,'USA',1);
SELECT country, COUNT(*) AS site_count, RANK() OVER (ORDER BY COUNT(*) DESC) AS site_count_rank FROM aquaculture_sites GROUP BY country;
List all trades executed in the past week with a value greater than 10000 USD in the EURUSD currency pair.
CREATE TABLE trades (trade_id INT,customer_id INT,currency_pair TEXT,trade_value DECIMAL(10,2),trade_date DATE); INSERT INTO trades VALUES (1,1,'EURUSD',12000.00,'2022-02-05'); INSERT INTO trades VALUES (2,2,'GBPUSD',8000.00,'2022-02-07'); INSERT INTO trades VALUES (3,3,'EURUSD',15000.00,'2022-02-10');
SELECT * FROM trades WHERE currency_pair = 'EURUSD' AND trade_value > 10000 AND trade_date >= DATEADD(day, -7, GETDATE());
Which menu items are served at both restaurant 1 and restaurant 3? Display the menu item name.
CREATE TABLE menu_items_r1 (menu_item_id INT,menu_item_name TEXT); INSERT INTO menu_items_r1 (menu_item_id,menu_item_name) VALUES (1,'Cheeseburger'),(2,'Fries'),(3,'Salad'); CREATE TABLE menu_items_r3 (menu_item_id INT,menu_item_name TEXT); INSERT INTO menu_items_r3 (menu_item_id,menu_item_name) VALUES (1,'Cheeseburger'),(3,'Salad'),(4,'Onion Rings');
SELECT menu_item_name FROM menu_items_r1 WHERE menu_item_name IN (SELECT menu_item_name FROM menu_items_r3);
List the digital assets and their corresponding regulatory frameworks from the 'crypto_assets' and 'regulations' tables.
CREATE TABLE crypto_assets (asset_id INT,asset_name VARCHAR(50),regulation_id INT); CREATE TABLE regulations (regulation_id INT,regulation_name VARCHAR(50)); INSERT INTO crypto_assets (asset_id,asset_name,regulation_id) VALUES (1,'Bitcoin',1); INSERT INTO regulations (regulation_id,regulation_name) VALUES (1,'EU AML');
SELECT crypto_assets.asset_name, regulations.regulation_name FROM crypto_assets INNER JOIN regulations ON crypto_assets.regulation_id = regulations.regulation_id;
List all suppliers providing both organic and non-organic products.
CREATE TABLE Suppliers (supplier_id INT,supplier_name VARCHAR(50),product_type VARCHAR(50)); INSERT INTO Suppliers (supplier_id,supplier_name,product_type) VALUES (1,'Organic Valley','Organic'),(2,'Tyson Foods','Non-organic'),(3,'Earthbound Farms','Organic'),(4,'Smithfield Foods','Non-organic');
SELECT supplier_name FROM Suppliers WHERE product_type = 'Organic' INTERSECT SELECT supplier_name FROM Suppliers WHERE product_type = 'Non-organic';
List all dishes that contain ingredients from a supplier in the Midwest.
CREATE TABLE Suppliers (sid INT,name TEXT,location TEXT);CREATE TABLE Dishes (did INT,name TEXT);CREATE TABLE Ingredients (iid INT,dish_id INT,supplier_id INT);INSERT INTO Suppliers VALUES (1,'SupplierA','Midwest');INSERT INTO Dishes VALUES (1,'DishA');INSERT INTO Ingredients VALUES (1,1,1);
SELECT Dishes.name FROM Dishes INNER JOIN Ingredients ON Dishes.did = Ingredients.dish_id INNER JOIN Suppliers ON Ingredients.supplier_id = Suppliers.sid WHERE Suppliers.location = 'Midwest';
Which researchers have researched a specific marine species?
CREATE TABLE ResearchSpecies (id INT,researcher VARCHAR(30),species VARCHAR(50)); INSERT INTO ResearchSpecies (id,researcher,species) VALUES (1,'Alice','Coral'),(2,'Bob','Whale Shark'),(3,'Alice','Starfish'),(4,'Bob','Dolphin');
SELECT researcher FROM ResearchSpecies WHERE species = 'Coral';
Calculate the average number of streams per user for each artist.
CREATE TABLE artists (artist_id INT,artist_name VARCHAR(255)); CREATE TABLE songs (song_id INT,title VARCHAR(255),genre_id INT,release_date DATE,artist_id INT); CREATE TABLE users (user_id INT,user_country VARCHAR(255)); CREATE TABLE streams (stream_id INT,song_id INT,user_id INT,stream_date DATE,revenue DECIMAL(10,2));
SELECT a.artist_name, AVG(st.stream_count) as avg_streams_per_user FROM artists a JOIN (SELECT song_id, user_id, COUNT(*) as stream_count FROM streams GROUP BY song_id, user_id) st ON a.artist_id = st.song_id GROUP BY a.artist_name;
Which regions in Japan have the most volunteers?
CREATE TABLE regions (id INT,region_name TEXT); CREATE TABLE volunteers (id INT,region_id INT,volunteer_count INT); INSERT INTO regions (id,region_name) VALUES (1,'Kanto'),(2,'Kansai'),(3,'Chubu'); INSERT INTO volunteers (id,region_id,volunteer_count) VALUES (1,1,300),(2,2,250),(3,1,200);
SELECT regions.region_name, SUM(volunteers.volunteer_count) as total_volunteers FROM regions JOIN volunteers ON regions.id = volunteers.region_id GROUP BY regions.region_name ORDER BY total_volunteers DESC;
What are the locations of rural infrastructure projects with a completion percentage greater than 70?
CREATE TABLE RuralInfrastructure (id INT,project_id INT,project_type VARCHAR(255),completion_percentage INT);
SELECT DISTINCT location FROM RuralInfrastructure WHERE completion_percentage > 70;
How many unique suppliers provided Gd in 2021, sorted in descending order?
CREATE TABLE supply (supplier VARCHAR(25),element VARCHAR(2),quantity INT,year INT); INSERT INTO supply VALUES ('SupplierA','Gd',150,2021),('SupplierB','Gd',200,2021),('SupplierC','Gd',100,2021),('SupplierA','Gd',120,2021);
SELECT COUNT(DISTINCT supplier) as unique_suppliers FROM supply WHERE element = 'Gd' AND year = 2021 ORDER BY unique_suppliers DESC;
Delete all space mission records from the year 2025.
CREATE TABLE space_missions (id INT,mission_name TEXT,year INT,country TEXT); INSERT INTO space_missions (id,mission_name,year,country) VALUES (1,'Artemis III',2025,'USA');
DELETE FROM space_missions WHERE year = 2025;
What was the total water consumption by industrial sector in the year 2021 and what was the average water consumption per sector?
CREATE TABLE industrial_water_consumption (id INT,sector VARCHAR(50),event_date DATE,water_consumption FLOAT); INSERT INTO industrial_water_consumption (id,sector,event_date,water_consumption) VALUES (1,'SectorA','2021-01-01',1200),(2,'SectorB','2021-01-01',1500),(3,'SectorC','2021-01-01',1800);
SELECT sector, SUM(water_consumption) as total_water_consumption, AVG(water_consumption) as avg_water_consumption_per_sector FROM industrial_water_consumption WHERE YEAR(event_date) = 2021 GROUP BY sector;
Delete a teacher record from the 'Teachers' table
CREATE TABLE Teachers (TeacherID int,FirstName varchar(20),LastName varchar(20),Age int,Gender varchar(10),Subject varchar(20));
DELETE FROM Teachers WHERE TeacherID = 5678;
Create a view that joins 'employees' and 'departments' tables on 'department_id'
CREATE TABLE employees (id INT,first_name VARCHAR(50),last_name VARCHAR(50),department_id INT); CREATE TABLE departments (id INT,department_name VARCHAR(50)); INSERT INTO employees (id,first_name,last_name,department_id) VALUES (1,'John','Doe',10),(2,'Jane','Doe',20); INSERT INTO departments (id,department_name) VALUES (10,'IT'),(20,'Marketing');
CREATE VIEW employee_departments AS SELECT employees.first_name, employees.last_name, departments.department_name FROM employees INNER JOIN departments ON employees.department_id = departments.id;
Find the average donation amount for each program and the total number of donations for each program.
CREATE TABLE Donations (DonationID INT,DonorID INT,ProgramID INT,DonationAmount DECIMAL); INSERT INTO Donations (DonationID,DonorID,ProgramID,DonationAmount) VALUES (1,1,1,150.00),(2,2,1,120.00),(3,3,2,90.00),(4,1,3,100.00),(5,4,1,160.00),(6,1,2,180.00),(7,2,2,130.00),(8,3,3,110.00);
SELECT Programs.Name, AVG(Donations.DonationAmount) as AvgDonation, COUNT(Donations.DonationID) as TotalDonations FROM Programs JOIN Donations ON Programs.ProgramID = Donations.ProgramID GROUP BY Programs.Name;
What is the average price of dishes in each menu category?
CREATE TABLE menu (category VARCHAR(255),price FLOAT); INSERT INTO menu (category,price) VALUES ('Appetizers',7.99),('Entrees',14.99),('Desserts',5.99);
SELECT category, AVG(price) FROM menu GROUP BY category;
How many recycling facilities are there in each city?
CREATE TABLE recycling_facilities (city VARCHAR(255),facility_type VARCHAR(255)); INSERT INTO recycling_facilities (city,facility_type) VALUES ('CityA','Plastic'),('CityA','Paper'),('CityA','Glass'),('CityB','Plastic'),('CityB','Paper'),('CityB','Glass');
SELECT city, COUNT(DISTINCT facility_type) FROM recycling_facilities GROUP BY city;
What is the distribution of case types (civil, criminal, etc.) for attorneys in the 'attorneys_cases' table, grouped by attorney gender identity?
CREATE TABLE attorney_gender_identity (attorney_id INT,gender_identity VARCHAR(30)); CREATE TABLE attorneys_cases (case_id INT,attorney_id INT,case_type VARCHAR(10));
SELECT a.gender_identity, c.case_type, COUNT(*) AS count FROM attorney_gender_identity a JOIN attorneys_cases c ON a.attorney_id = c.attorney_id GROUP BY a.gender_identity, c.case_type;
What is the total water consumption for the month of July for all water treatment plants in the 'Rural' region?
CREATE TABLE WaterConsumption (id INT,plant_id INT,consumption_date DATE,consumption INT); INSERT INTO WaterConsumption (id,plant_id,consumption_date,consumption) VALUES (1,1,'2021-07-01',15000),(2,1,'2021-07-02',16000),(3,2,'2021-07-01',18000),(4,2,'2021-07-02',19000),(5,3,'2021-07-01',20000),(6,3,'2021-07-02',21000);
SELECT SUM(consumption) FROM WaterConsumption WHERE region = 'Rural' AND MONTH(consumption_date) = 7;
List all news articles related to 'indigenous rights' or 'colonialism', returning their title, content, and author's name, for articles published in English or French.
CREATE TABLE articles_multilang (id INT,title VARCHAR(255),content TEXT,author_id INT,language VARCHAR(255)); INSERT INTO articles_multilang (id,title,content,author_id,language) VALUES (1,'Article 1','Indigenous rights...',1,'en'),(2,'Article 2','Les droits...',2,'fr'); CREATE TABLE authors_multilang (id INT,name VARCHAR(255)); INSERT INTO authors_multilang (id,name) VALUES (1,'Author 1'),(2,'Author 2');
SELECT a.title, a.content, au.name FROM articles_multilang a JOIN authors_multilang au ON a.author_id = au.id WHERE a.title LIKE '%indigenous rights%' OR a.title LIKE '%colonialism%' OR a.content LIKE '%indigenous rights%' OR a.content LIKE '%colonialism%' AND (a.language = 'en' OR a.language = 'fr');
What is the average donation amount per donor for the Environment department in 2023?
CREATE TABLE Donors (DonorID INT,DonorName VARCHAR(50)); INSERT INTO Donors (DonorID,DonorName) VALUES (1,'Sophia Kim'),(2,'William Davis'),(3,'Isabella Hernandez'); CREATE TABLE Donations (DonationID INT,DonorID INT,DonationDate DATE,Amount DECIMAL(10,2),Department VARCHAR(50)); INSERT INTO Donations (DonationID,DonorID,DonationDate,Amount,Department) VALUES (1,1,'2023-01-01',50.00,'Environment'),(2,1,'2023-01-05',75.00,'Environment'),(3,2,'2023-01-10',100.00,'Environment'),(4,3,'2023-01-15',125.00,'Environment');
SELECT Department, AVG(Amount) as AvgDonation FROM (SELECT DonorID, AVG(Amount) as Amount FROM Donations WHERE Year(DonationDate) = 2023 AND Department = 'Environment' GROUP BY DonorID) AS AvgDonations INNER JOIN Donors ON AvgDonations.DonorID = Donors.DonorID WHERE Department = 'Environment';
What is the total budget for peacekeeping operations by each department, only for departments that have spent more than $2 million?
CREATE TABLE DepartmentPeacekeepingOperations (id INT,department VARCHAR(50),budget INT);
SELECT department, SUM(budget) FROM DepartmentPeacekeepingOperations GROUP BY department HAVING SUM(budget) > 2000000;
What is the total financial assets of Shariah-compliant institutions in Africa?
CREATE TABLE if not exists africa_financial_assets (id INT,institution_name VARCHAR(100),country VARCHAR(50),is_shariah_compliant BOOLEAN,assets DECIMAL(15,2));
SELECT SUM(assets) FROM africa_financial_assets WHERE country IN (SELECT DISTINCT country FROM africa_financial_assets WHERE is_shariah_compliant = TRUE) AND is_shariah_compliant = TRUE;
What is the difference in average word count between articles about arts and culture, and technology?
CREATE TABLE articles (id INT,title VARCHAR(50),category VARCHAR(20),author_id INT,word_count INT); INSERT INTO articles (id,title,category,author_id,word_count) VALUES (1,'Technology Advancements','technology',1,1200),(2,'Art Exhibit','arts_and_culture',2,1500),(3,'Sports News','sports',3,800),(4,'Political Update','politics',1,1000),(5,'Theater Performance','arts_and_culture',2,1300),(6,'Software Development','technology',3,1100);
SELECT AVG(CASE WHEN articles.category = 'technology' THEN articles.word_count ELSE NULL END) - AVG(CASE WHEN articles.category = 'arts_and_culture' THEN articles.word_count ELSE NULL END) AS avg_word_count_diff FROM articles;
What is the average time to disposition for cases that were dismissed, by month and year?
CREATE TABLE CaseTiming (CaseID INT,TimeToDisposition INT,DismissalDate DATE); INSERT INTO CaseTiming (CaseID,TimeToDisposition,DismissalDate) VALUES (1,60,'2022-02-15'),(2,30,'2022-03-01'),(3,90,'2022-04-10'),(4,45,'2022-05-15');
SELECT DATEPART(year, DismissalDate) AS Year, DATEPART(month, DismissalDate) AS Month, AVG(TimeToDisposition) AS AverageTimeToDisposition FROM CaseTiming WHERE DismissalDate IS NOT NULL GROUP BY DATEPART(year, DismissalDate), DATEPART(month, DismissalDate);
List all mining operations that exceeded their annual emission limit in 2021.
CREATE TABLE operations (id INT,name TEXT); CREATE TABLE emissions (operation_id INT,year INT,amount FLOAT,limit FLOAT); INSERT INTO operations (id,name) VALUES (1,'Operation A'),(2,'Operation B'); INSERT INTO emissions (operation_id,year,amount,limit) VALUES (1,2021,12000.0,10000.0),(2,2021,9000.0,11000.0);
SELECT operations.name FROM operations INNER JOIN emissions ON operations.id = emissions.operation_id WHERE emissions.year = 2021 AND emissions.amount > emissions.limit;
Update the size of farm 'Joyful Fields' in Kenya to 220
CREATE TABLE farms (id INT,name TEXT,location TEXT,size FLOAT); INSERT INTO farms (id,name,location,size) VALUES (1,'Joyful Fields','Kenya',200.0);
UPDATE farms SET size = 220 WHERE name = 'Joyful Fields';
What is the difference in the number of successful and unsuccessful space missions for each organization?
CREATE TABLE space_missions (id INT,organization VARCHAR(255),result VARCHAR(10)); INSERT INTO space_missions (id,organization,result) VALUES (1,'NASA','successful'),(2,'SpaceX','successful'),(3,'ESA','unsuccessful'),(4,'NASA','successful'),(5,'SpaceX','unsuccessful');
SELECT organization, COUNT(*) FILTER (WHERE result = 'successful') - COUNT(*) FILTER (WHERE result = 'unsuccessful') as mission_difference FROM space_missions GROUP BY organization;
What is the policy number, coverage start date, and name of the agent for all policies in the 'California' region?
CREATE TABLE policies (policy_number INT,coverage_start_date DATE,agent_id INT,region VARCHAR(20)); INSERT INTO policies (policy_number,coverage_start_date,agent_id,region) VALUES (12345,'2020-01-01',1001,'California'); INSERT INTO policies (policy_number,coverage_start_date,agent_id,region) VALUES (67890,'2020-02-01',1002,'California'); CREATE TABLE agents (agent_id INT,name VARCHAR(50)); INSERT INTO agents (agent_id,name) VALUES (1001,'John Smith'); INSERT INTO agents (agent_id,name) VALUES (1002,'Jane Doe');
SELECT policies.policy_number, policies.coverage_start_date, agents.name FROM policies INNER JOIN agents ON policies.agent_id = agents.agent_id WHERE policies.region = 'California';
What is the average number of employees per workplace, categorized by industry and union status?
CREATE TABLE workplaces (id INT,name VARCHAR(255),industry VARCHAR(255),union_status VARCHAR(255),num_employees INT); INSERT INTO workplaces (id,name,industry,union_status,num_employees) VALUES (1,'ABC Company','Manufacturing','Union',500),(2,'XYZ Corporation','Manufacturing','Union',250),(3,'DEF Industries','Retail','Non-Union',300),(4,'GHI Company','Retail','Union',150),(5,'JKL Industries','Construction','Non-Union',200);
SELECT industry, union_status, AVG(num_employees) as 'Average Employees' FROM workplaces GROUP BY industry, union_status;
Show the average number of points scored by each team in the 'nba_games' table.
CREATE TABLE nba_games (game_id INT,home_team_id INT,away_team_id INT,home_team_points INT,away_team_points INT);
SELECT home_team_id AS team_id, AVG(home_team_points) AS avg_points FROM nba_games GROUP BY home_team_id UNION ALL SELECT away_team_id, AVG(away_team_points) FROM nba_games GROUP BY away_team_id;
Create a view to display average response time by response type
CREATE TABLE emergency_response (response_type VARCHAR(255),response_time TIME,location VARCHAR(255));
CREATE VIEW avg_response_time AS SELECT response_type, AVG(TIME_TO_SEC(response_time))/60 as avg_response_time FROM emergency_response GROUP BY response_type;
How many dispensaries are there in the city of Denver, CO?
CREATE TABLE dispensaries (id INT,city VARCHAR(50),state VARCHAR(50),count INT); INSERT INTO dispensaries (id,city,state,count) VALUES (1,'Denver','Colorado',100),(2,'Los Angeles','California',200),(3,'Portland','Oregon',150);
SELECT COUNT(*) FROM dispensaries WHERE city = 'Denver';
What is the maximum number of sustainable tourism certifications obtained by hotels in the United States?
CREATE TABLE Hotels (name VARCHAR(50),location VARCHAR(20),certifications INT);
SELECT MAX(certifications) FROM Hotels WHERE location = 'United States';
List all cities and the number of open civic tech issues
CREATE TABLE cities (id INT,name VARCHAR(255)); INSERT INTO cities (id,name) VALUES (1,'New York'),(2,'Los Angeles'),(3,'Chicago'); CREATE TABLE civic_tech_issues (id INT,city_id INT,status VARCHAR(255)); INSERT INTO civic_tech_issues (id,city_id,status) VALUES (1,1,'open'),(2,1,'closed'),(3,2,'open'),(4,3,'closed');
SELECT c.name, COUNT(cti.id) as open_issues FROM cities c LEFT JOIN civic_tech_issues cti ON c.id = cti.city_id AND cti.status = 'open' GROUP BY c.id;
What was the average donation amount by cause in 2022?
CREATE TABLE DonationCauses (DonorID INT,DonationYear INT,DonationAmount DECIMAL(10,2),DonationCause VARCHAR(50)); INSERT INTO DonationCauses (DonorID,DonationYear,DonationAmount,DonationCause) VALUES (1,2022,100.00,'Education'),(2,2022,200.00,'Health'),(3,2022,150.00,'Environment'),(4,2022,75.00,'Education'),(5,2022,300.00,'Health');
SELECT DonationCause, AVG(DonationAmount) as AvgDonationAmount FROM DonationCauses WHERE DonationYear = 2022 GROUP BY DonationCause;