instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
What is the average precipitation in the top 5 driest regions in the past year?
CREATE TABLE precipitation_data (region VARCHAR(255),precipitation INT,date DATE); INSERT INTO precipitation_data (region,precipitation,date) VALUES ('Africa',50,'2022-01-01'),('Asia',75,'2022-01-01'),('Australia',100,'2022-01-01'),('South America',125,'2022-01-01'),('Antarctica',150,'2022-01-01');
SELECT region, AVG(precipitation) as avg_precipitation FROM (SELECT region, precipitation, RANK() OVER (PARTITION BY NULL ORDER BY precipitation ASC) as rain_rank FROM precipitation_data WHERE date BETWEEN '2022-01-01' AND '2022-12-31' GROUP BY region) subquery WHERE rain_rank <= 5 GROUP BY region;
What is the minimum age of trees in the mature_forest table?
CREATE TABLE mature_forest (id INT,species VARCHAR(255),age INT); INSERT INTO mature_forest (id,species,age) VALUES (1,'Pine',25),(2,'Oak',30),(3,'Maple',28);
SELECT MIN(age) FROM mature_forest;
Create a view to show all completed projects
CREATE TABLE climate_mitigation_projects (id INT PRIMARY KEY,name VARCHAR(50),location VARCHAR(50),start_date DATE,end_date DATE,budget FLOAT);
CREATE VIEW completed_projects AS SELECT * FROM climate_mitigation_projects WHERE end_date < CURDATE();
Identify the top 3 states with the highest number of hospitals and the corresponding number of beds in those hospitals.
CREATE TABLE hospitals (hospital_id INT,name VARCHAR(50),state VARCHAR(20),num_beds INT); INSERT INTO hospitals (hospital_id,name,state,num_beds) VALUES (1,'Hospital A','New York',500),(2,'Hospital B','Texas',600),(3,'Hospital C','California',700); CREATE TABLE states (state VARCHAR(20),region VARCHAR(20)); INSERT INTO states (state,region) VALUES ('New York','Northeast'),('Texas','South'),('California','West');
SELECT s.state, h.num_beds FROM hospitals h INNER JOIN states s ON h.state = s.state WHERE h.state IN (SELECT s.state FROM hospitals h INNER JOIN states s ON h.state = s.state GROUP BY s.state ORDER BY COUNT(h.hospital_id) DESC LIMIT 3) ORDER BY num_beds DESC;
What is the total training cost for underrepresented employees in the last year?
CREATE TABLE Training (TrainingID INT,EmployeeID INT,TrainingType VARCHAR(20),Cost DECIMAL(10,2),TrainingDate DATE); INSERT INTO Training (TrainingID,EmployeeID,TrainingType,Cost,TrainingDate) VALUES (1,1,'Diversity',1500.00,'2021-01-01'),(2,2,'Leadership',2000.00,'2021-02-01'),(3,3,'Diversity',1000.00,'2021-03-01');
SELECT SUM(Cost) FROM Training JOIN Employees ON Training.EmployeeID = Employees.EmployeeID WHERE Employees.Gender IN ('Female', 'Non-binary') OR Employees.Department = 'Diversity';
What is the total number of volunteers and total hours donated by them in '2022'?
CREATE TABLE Volunteers (VolunteerID int,VolunteerName varchar(50),HoursDonated int,VolunteerYear int); INSERT INTO Volunteers (VolunteerID,VolunteerName,HoursDonated,VolunteerYear) VALUES (1,'Grace Blue',30,2022),(2,'Harry Yellow',20,2022),(3,'Ivy Purple',15,2022),(4,'Jack Orange',25,2022);
SELECT COUNT(VolunteerName) as TotalVolunteers, SUM(HoursDonated) as TotalHours FROM Volunteers WHERE VolunteerYear = 2022;
What is the average salary of construction workers in California, grouped by occupation?
CREATE TABLE Construction_Labor (worker_id INT,occupation VARCHAR(50),state VARCHAR(50),salary FLOAT); INSERT INTO Construction_Labor VALUES (7890,'Electrician','California',60000);
SELECT occupation, AVG(salary) FROM Construction_Labor WHERE state = 'California' GROUP BY occupation;
How many media outlets in Africa have a media literacy score above 7?
CREATE TABLE media_outlets (id INT,name TEXT,country TEXT,media_literacy_score INT); INSERT INTO media_outlets (id,name,country,media_literacy_score) VALUES (1,'Outlet 1','Nigeria',6); INSERT INTO media_outlets (id,name,country,media_literacy_score) VALUES (2,'Outlet 2','Kenya',7);
SELECT COUNT(*) FROM media_outlets WHERE country = 'Africa' AND media_literacy_score > 7;
What is the maximum number of flu shots administered in a single day in the European region?
CREATE TABLE flu_shots (flu_shot_id INT,patient_id INT,date DATE,region VARCHAR(20)); INSERT INTO flu_shots (flu_shot_id,patient_id,date,region) VALUES (1,3,'2021-01-01','European'); INSERT INTO flu_shots (flu_shot_id,patient_id,date,region) VALUES (2,4,'2021-02-01','American');
SELECT MAX(count) FROM (SELECT date, COUNT(*) as count FROM flu_shots GROUP BY date) as subquery
How many climate communication projects are in 'Europe' and 'North America'?
CREATE TABLE climate_communication (project_id INT,project_name VARCHAR(255),location VARCHAR(255),start_date DATE,end_date DATE);
SELECT COUNT(*) FROM climate_communication WHERE location IN ('Europe', 'North America');
How many volunteers have contributed to each program in 2022?
CREATE TABLE programs (id INT,name VARCHAR(255)); INSERT INTO programs (id,name) VALUES (1,'Women Empowerment'),(2,'Refugee Support'),(3,'Disaster Relief'); CREATE TABLE volunteer_hours (id INT,program_id INT,volunteer_id INT,hours INT); INSERT INTO volunteer_hours (id,program_id,volunteer_id,hours) VALUES (1,1,1,25),(2,2,2,30),(3,1,3,20),(4,3,4,40),(5,2,5,35),(6,1,6,22),(7,3,7,45),(8,2,8,33),(9,1,9,27),(10,3,10,50),(11,1,11,20),(12,2,12,25),(13,1,13,30),(14,3,14,35),(15,2,15,30),(16,1,16,25),(17,3,17,40),(18,2,18,35),(19,1,19,30),(20,3,20,45),(21,1,21,20),(22,2,22,25),(23,1,23,30),(24,3,24,35),(25,2,25,30),(26,1,26,25),(27,3,27,40),(28,2,28,35),(29,1,29,30),(30,3,30,45);
SELECT program_id, COUNT(DISTINCT volunteer_id) as num_volunteers FROM volunteer_hours GROUP BY program_id;
Which organizations have received grants for capacity building in the last year?
CREATE TABLE organizations (id INT,name VARCHAR(50),type VARCHAR(30)); CREATE TABLE grants (id INT,org_id INT,amount INT,date DATE,purpose VARCHAR(30)); INSERT INTO organizations (id,name,type) VALUES (1,'ABC Nonprofit','capacity building'),(2,'DEF Nonprofit','social impact'),(3,'GHI Nonprofit','fundraising'); INSERT INTO grants (id,org_id,amount,date,purpose) VALUES (1,1,10000,'2023-01-01','capacity building'),(2,2,5000,'2022-12-15','program delivery'),(3,3,7500,'2023-02-05','capacity building');
SELECT organizations.name FROM organizations INNER JOIN grants ON organizations.id = grants.org_id WHERE grants.date >= DATEADD(year, -1, GETDATE()) AND organizations.type = 'capacity building';
What is the count of new employees by gender in the last 3 months?
CREATE TABLE employees (id INT,name VARCHAR(255),gender VARCHAR(10),hire_date DATE); INSERT INTO employees (id,name,gender,hire_date) VALUES (1,'Jane Doe','Female','2022-03-15'),(2,'Alice Smith','Female','2022-02-03'),(3,'Bob Johnson','Male','2022-01-01'),(4,'Grace Lee','Female','2022-04-01');
SELECT gender, COUNT(id) as new_employees FROM employees WHERE hire_date >= DATE_SUB(CURDATE(), INTERVAL 3 MONTH) GROUP BY gender;
List all the satellite images taken in the past month, along with the average temperature and humidity at the time of capture.
CREATE TABLE satellite_data (id INT,image_id VARCHAR(255),temperature INT,humidity INT,timestamp DATETIME); INSERT INTO satellite_data (id,image_id,temperature,humidity,timestamp) VALUES (1,'IMG001',20,70,'2022-01-01 10:00:00');
SELECT image_id, AVG(temperature) as avg_temp, AVG(humidity) as avg_humidity FROM satellite_data WHERE timestamp >= DATE_SUB(CURRENT_TIMESTAMP(), INTERVAL 1 MONTH) GROUP BY image_id;
What was the total amount donated by each gender in H1 2021?
CREATE TABLE Donors (DonorID int,DonorName varchar(50),Gender varchar(50),AmountDonated numeric(10,2)); INSERT INTO Donors (DonorID,DonorName,Gender,AmountDonated) VALUES (1,'John Doe','Male',500.00),(2,'Jane Smith','Female',750.00);
SELECT Gender, SUM(AmountDonated) as TotalDonated FROM Donors WHERE AmountDonated >= 0 AND AmountDonated < 9999.99 GROUP BY Gender;
List the total quantity of fruits ordered from local suppliers in California?
CREATE TABLE Suppliers (SupplierID INT,SupplierName VARCHAR(50),Location VARCHAR(50)); INSERT INTO Suppliers (SupplierID,SupplierName,Location) VALUES (1,'Fresh CA Produce','California'); CREATE TABLE Products (ProductID INT,ProductName VARCHAR(50),SupplierID INT,Category VARCHAR(50),Price DECIMAL(5,2)); INSERT INTO Products (ProductID,ProductName,SupplierID,Category,Price) VALUES (1,'Fresh Strawberries',1,'Fruits',3.99); CREATE TABLE Orders (OrderID INT,ProductID INT,Quantity INT,OrderDate DATE,SupplierID INT); INSERT INTO Orders (OrderID,ProductID,Quantity,OrderDate,SupplierID) VALUES (1,1,20,'2021-07-01',1);
SELECT SUM(Quantity) FROM Orders JOIN Products ON Orders.ProductID = Products.ProductID JOIN Suppliers ON Products.SupplierID = Suppliers.SupplierID WHERE Suppliers.Location = 'California' AND Products.Category = 'Fruits';
What is the average number of graduate students enrolled per program?
CREATE TABLE program (id INT,name TEXT);CREATE TABLE student (id INT,program_id INT,enrollment_status TEXT);
SELECT AVG(s.count) FROM (SELECT program_id, COUNT(*) AS count FROM student s GROUP BY program_id) s;
What is the total balance for all customers in the Southeast region?
CREATE TABLE customers (id INT,name VARCHAR(50),region VARCHAR(50),balance DECIMAL(10,2)); INSERT INTO customers (id,name,region,balance) VALUES (1,'John Doe','Southeast',5000.00),(2,'Jane Smith','Northeast',7000.00);
SELECT SUM(balance) FROM customers WHERE region = 'Southeast';
What are the average dimensions of sculptures in the surrealism category?
CREATE TABLE dimensions (dimension_id INT PRIMARY KEY,work_id INT,height FLOAT,width FLOAT,depth FLOAT,FOREIGN KEY (work_id) REFERENCES works(work_id));
SELECT AVG(height) AS avg_height, AVG(width) AS avg_width, AVG(depth) AS avg_depth FROM dimensions d JOIN works w ON d.work_id = w.work_id WHERE w.style = 'Surrealism' AND w.category = 'Sculpture';
Update the total_incidents column in the workplace_safety_metrics table to 15 for all records with an incident_type of 'Electrical Hazards' and union_id of 006
CREATE TABLE workplace_safety_metrics (ws_id SERIAL PRIMARY KEY,union_id VARCHAR(5),incident_type TEXT,total_incidents INT,date DATE);
UPDATE workplace_safety_metrics SET total_incidents = 15 WHERE incident_type = 'Electrical Hazards' AND union_id = '006';
List all cruelty-free products and their brands with more than 1000 sales
CREATE TABLE sales (product_id INT,brand_id INT,quantity INT); CREATE TABLE products (id INT,name VARCHAR(255),brand_id INT,is_cruelty_free BOOLEAN);
SELECT p.name, b.brand_name FROM products p INNER JOIN (SELECT brand_id, SUM(quantity) as total_sales FROM sales GROUP BY brand_id HAVING total_sales > 1000) s ON p.brand_id = s.brand_id INNER JOIN brands b ON p.brand_id = b.id WHERE p.is_cruelty_free = TRUE;
What is the average CO2 emission per flight for each airline company?
CREATE TABLE Airline_Companies (Company_Name VARCHAR(50)); INSERT INTO Airline_Companies (Company_Name) VALUES ('AirAsia'),('Lufthansa'),('Delta'); CREATE TABLE Emissions (Company_Name VARCHAR(50),Flight_Number INT,Year INT,CO2_Emissions INT); INSERT INTO Emissions (Company_Name,Flight_Number,Year,CO2_Emissions) VALUES ('AirAsia',101,2020,120),('AirAsia',102,2020,140),('Lufthansa',201,2020,200),('Lufthansa',202,2020,220),('Delta',301,2020,250),('Delta',302,2020,270);
SELECT AC.Company_Name, AVG(E.CO2_Emissions) AS Avg_CO2_Emissions FROM Emissions E JOIN Airline_Companies AC ON E.Company_Name = AC.Company_Name GROUP BY AC.Company_Name;
Show the total number of satellites launched by each country in the last 10 years from the satellite_deployment table
CREATE TABLE satellite_deployment (id INT PRIMARY KEY,country VARCHAR(100),launch_date DATE,satellite_name VARCHAR(100));
SELECT country, COUNT(*) FROM satellite_deployment WHERE launch_date >= DATE_SUB(CURRENT_DATE, INTERVAL 10 YEAR) GROUP BY country;
Find the average 'Cultural Competency' training duration for providers in 'New York' and 'Los Angeles'.
CREATE TABLE ProviderTrainings (ID INT PRIMARY KEY,ProviderID INT,Training VARCHAR(50),Duration INT,Location VARCHAR(50),Date DATE); INSERT INTO ProviderTrainings (ID,ProviderID,Training,Duration,Location,Date) VALUES (1,201,'Cultural Competency',120,'New York','2022-01-01'); INSERT INTO ProviderTrainings (ID,ProviderID,Training,Duration,Location,Date) VALUES (2,202,'Language Access',90,'Los Angeles','2021-02-01'); INSERT INTO ProviderTrainings (ID,ProviderID,Training,Duration,Location,Date) VALUES (3,203,'Cultural Sensitivity',150,'New York','2019-03-01');
SELECT AVG(Duration) FROM ProviderTrainings WHERE Training = 'Cultural Competency' AND Location IN ('New York', 'Los Angeles');
Find the total quantity of each strain sold in Colorado and Oregon.
CREATE TABLE sales (sale_id INT,dispensary_id INT,strain VARCHAR(255),quantity INT);CREATE TABLE dispensaries (dispensary_id INT,name VARCHAR(255),state VARCHAR(255));
SELECT strain, SUM(quantity) as total_quantity FROM sales JOIN dispensaries ON sales.dispensary_id = dispensaries.dispensary_id WHERE state IN ('Colorado', 'Oregon') GROUP BY strain;
How many patients have been treated with meditation in the past year?
CREATE TABLE patients (patient_id INT,age INT,gender VARCHAR(20),condition VARCHAR(50),registration_date DATE); INSERT INTO patients (patient_id,age,gender,condition,registration_date) VALUES (1,35,'Female','Depression','2021-05-18'); CREATE TABLE treatments (treatment_id INT,patient_id INT,therapy_type VARCHAR(50),duration INT,treatment_date DATE); INSERT INTO treatments (treatment_id,patient_id,therapy_type,duration,treatment_date) VALUES (1,1,'Meditation',12,'2021-08-23');
SELECT COUNT(DISTINCT patients.patient_id) FROM patients JOIN treatments ON patients.patient_id = treatments.patient_id WHERE treatments.therapy_type = 'Meditation' AND treatments.treatment_date >= '2020-08-01';
What is the maximum number of trips taken by shared scooters in Berlin on a single day?
CREATE TABLE public.trips_by_day (id SERIAL PRIMARY KEY,vehicle_type TEXT,city TEXT,trips_on_day INTEGER); INSERT INTO public.trips_by_day (vehicle_type,city,trips_on_day) VALUES ('shared_scooter','Berlin',1500),('shared_scooter','Berlin',1700),('shared_scooter','London',1200);
SELECT MAX(trips_on_day) FROM public.trips_by_day WHERE vehicle_type = 'shared_scooter' AND city = 'Berlin';
How many schools were built in each country?
CREATE TABLE SchoolConstruction (Country VARCHAR(20),NumSchools INT); INSERT INTO SchoolConstruction (Country,NumSchools) VALUES ('Afghanistan',15),('Syria',20),('Iraq',10),('Jordan',12),('Lebanon',18);
SELECT Country, SUM(NumSchools) as TotalSchools FROM SchoolConstruction GROUP BY Country;
Delete records from the 'infrastructure_development' table where the 'location' is 'South Atlantic'
CREATE TABLE infrastructure_development (project_id INT,location VARCHAR(30),start_date DATE,end_date DATE,cost INT); INSERT INTO infrastructure_development (project_id,location,start_date,end_date,cost) VALUES (3,'South Atlantic','2019-01-01','2022-12-31',600000000);
DELETE FROM infrastructure_development WHERE location = 'South Atlantic';
What is the average size of sustainable urbanism projects in the city of Tokyo?
CREATE TABLE SustainableUrbanism (id INT,city VARCHAR(20),size FLOAT);
SELECT AVG(size) FROM SustainableUrbanism WHERE city = 'Tokyo';
Delete all records from the "Census" table where the state is 'California'.
CREATE TABLE Census (id INT,state VARCHAR(50),population INT); INSERT INTO Census (id,state,population) VALUES (1,'California',39512223),(2,'Texas',29528404),(3,'Florida',21538187),(4,'New York',19453561),(5,'Pennsylvania',12801989);
DELETE FROM Census WHERE state = 'California';
What is the maximum recycling rate for any material in the East region?
CREATE TABLE Recycling_Rates (material VARCHAR(20),region VARCHAR(20),recycling_rate DECIMAL(4,2)); INSERT INTO Recycling_Rates (material,region,recycling_rate) VALUES ('Glass','East',0.60),('Paper','East',0.75),('Plastic','West',0.55),('Metal','North',0.80);
SELECT region, MAX(recycling_rate) FROM Recycling_Rates WHERE region = 'East' GROUP BY region;
What is the maximum depth ever reached by a submersible in the Atlantic Ocean?
CREATE TABLE submersible_dives (id INT,submersible_name VARCHAR(50),region VARCHAR(20),dive_date DATE,max_depth INT);INSERT INTO submersible_dives (id,submersible_name,region,dive_date,max_depth) VALUES (1,'Trieste','Atlantic','1960-01-23',10972);INSERT INTO submersible_dives (id,submersible_name,region,dive_date,max_depth) VALUES (2,'Mir','Atlantic','2000-08-23',6170);
SELECT MAX(max_depth) FROM submersible_dives WHERE region = 'Atlantic';
Find the total number of workplace injuries for each union, and return only the unions with more than 1000 injuries.
CREATE TABLE injuries (id INT PRIMARY KEY,union_id INT,injury_count INT); INSERT INTO injuries (id,union_id,injury_count) VALUES (1,1,1500),(2,2,800),(3,3,1200);
SELECT union_id, SUM(injury_count) AS total_injuries FROM injuries GROUP BY union_id HAVING total_injuries > 1000;
What is the maximum number of people in space at any given time, according to the Astronaut_Missions table?
CREATE TABLE Astronaut_Missions (ID INT,Astronaut_Name VARCHAR(255),Mission_Name VARCHAR(255),In_Space BOOLEAN); INSERT INTO Astronaut_Missions (ID,Astronaut_Name,Mission_Name,In_Space) VALUES (1,'Neil Armstrong','Apollo 11',TRUE),(2,'Buzz Aldrin','Apollo 11',TRUE);
SELECT MAX(Num_In_Space) FROM (SELECT COUNT(*) as Num_In_Space FROM Astronaut_Missions WHERE In_Space = TRUE GROUP BY Mission_Name) AS Subquery;
What is the average energy consumption of buildings in each location that have energy consumption above the average energy consumption of all buildings in the 'GreenBuildings' table?
CREATE TABLE GreenBuildings (id INT,name VARCHAR(50),location VARCHAR(50),energyConsumption DECIMAL(5,2)); CREATE TABLE Averages (location VARCHAR(50),avg_consumption DECIMAL(5,2)); INSERT INTO Averages (location,avg_consumption) SELECT location,AVG(energyConsumption) FROM GreenBuildings GROUP BY location; CREATE TABLE AboveAverage (location VARCHAR(50),energyConsumption DECIMAL(5,2)); INSERT INTO AboveAverage (location,energyConsumption) SELECT location,AVG(energyConsumption) as energyConsumption FROM GreenBuildings GROUP BY location HAVING AVG(energyConsumption) > (SELECT AVG(avg_consumption) FROM Averages);
SELECT location, AVG(energyConsumption) as avg_above_average FROM AboveAverage GROUP BY location;
Find the total sales quantity of hybrid strains in Oregon and Washington, and the percentage of total sales for each state.
CREATE TABLE total_sales (state VARCHAR(20),sales_quantity INT,strain_type VARCHAR(10)); INSERT INTO total_sales (state,sales_quantity,strain_type) VALUES ('Oregon',200,'hybrid'); INSERT INTO total_sales (state,sales_quantity,strain_type) VALUES ('Washington',150,'hybrid'); INSERT INTO total_sales (state,sales_quantity,strain_type) VALUES ('California',300,'indica'); INSERT INTO total_sales (state,sales_quantity,strain_type) VALUES ('California',150,'sativa'); INSERT INTO total_sales (state,sales_quantity,strain_type) VALUES ('California',200,'hybrid');
SELECT state, sales_quantity, (sales_quantity::FLOAT / SUM(sales_quantity) OVER (PARTITION BY strain_type)) * 100 AS percentage FROM total_sales WHERE strain_type = 'hybrid';
What is the maximum salary of workers who are not union members, grouped by their industry?
CREATE TABLE workers (id INT,name TEXT,industry TEXT,union_member BOOLEAN,salary REAL); INSERT INTO workers (id,name,industry,union_member,salary) VALUES (1,'John Doe','construction',true,60000.00),(2,'Jane Smith','retail',false,35000.00);
SELECT industry, MAX(salary) FROM workers WHERE NOT union_member GROUP BY industry;
What is the average temperature recorded in each Arctic research station in 2020?
CREATE TABLE WeatherData (Station VARCHAR(255),Date DATE,Temperature FLOAT); INSERT INTO WeatherData (Station,Date,Temperature) VALUES ('StationA','2020-01-01',-10.5),('StationB','2020-01-01',-12.3);
SELECT Station, AVG(Temperature) FROM WeatherData WHERE YEAR(Date) = 2020 GROUP BY Station;
What was the total cost of spacecraft manufactured by 'AeroCorp'?
CREATE TABLE SpacecraftManufacturing(company VARCHAR(20),cost INT); INSERT INTO SpacecraftManufacturing(company,cost) VALUES('AeroCorp',5000000),('GalacticTech',7000000),('SpaceEagle',6000000);
SELECT SUM(cost) FROM SpacecraftManufacturing WHERE company = 'AeroCorp';
What is the total number of hours spent playing VR games by players, grouped by their preferred gaming platform and region?
CREATE TABLE players (id INT,platform VARCHAR(20),region VARCHAR(20),total_hours_played INT);CREATE TABLE game_sessions (id INT,player_id INT,session_duration INT,game_type VARCHAR(10));
SELECT p.platform, p.region, SUM(gs.session_duration) AS total_hours_played FROM players p INNER JOIN game_sessions gs ON p.id = gs.player_id WHERE gs.game_type = 'VR' GROUP BY p.platform, p.region;
Identify habitats that require preservation efforts
CREATE TABLE critical_habitats (id INT,habitat_id INT,reason VARCHAR(50)); INSERT INTO critical_habitats (id,habitat_id,reason) VALUES (1,1,'Endangered Species'),(2,3,'Biodiversity Hotspot'),(3,4,'Climate Change Impact'); CREATE TABLE habitats (id INT,type VARCHAR(50)); INSERT INTO habitats (id,type) VALUES (1,'Forest'),(2,'Savannah'),(3,'Wetlands'),(4,'Mountain');
SELECT h.type FROM habitats h INNER JOIN critical_habitats ch ON h.id = ch.habitat_id;
Update the name of an existing organization
CREATE TABLE organization (org_id INT,org_name TEXT); INSERT INTO organization (org_id,org_name) VALUES (1,'Volunteers Inc'); INSERT INTO organization (org_id,org_name) VALUES (2,'Helping Hands');
UPDATE organization SET org_name = 'Compassionate Communities' WHERE org_id = 2;
What is the average gas production in Canada in 2018?
CREATE TABLE gas_production (well_id INT,year INT,oil_production INT,gas_production INT); INSERT INTO gas_production (well_id,year,oil_production,gas_production) VALUES (1,2018,120000,50000); INSERT INTO gas_production (well_id,year,oil_production,gas_production) VALUES (2,2017,130000,60000); INSERT INTO gas_production (well_id,year,oil_production,gas_production) VALUES (3,2018,110000,45000);
SELECT AVG(gas_production) FROM gas_production WHERE year = 2018 AND state = 'Canada';
What is the name of the most expensive product?
CREATE TABLE products (id INT,company VARCHAR(255),price DECIMAL(5,2),name VARCHAR(255)); INSERT INTO products (id,company,price,name) VALUES (1,'ABC',50.99,'Cleanser'),(2,'DEF',35.49,'Toner'),(3,'GHI',65.99,'Moisturizer'),(4,'JKL',25.99,'Serum');
SELECT name FROM products WHERE price = (SELECT MAX(price) FROM products);
What is the total number of articles published in the Spanish language in 2021?
CREATE TABLE articles (id INT,title VARCHAR(255),language VARCHAR(50),publication_date DATE); INSERT INTO articles (id,title,language,publication_date) VALUES (1,'ArticleE','Spanish','2021-01-01'),(2,'ArticleF','English','2022-12-31'),(3,'ArticleG','French','2022-01-01'),(4,'ArticleH','Spanish','2020-12-31');
SELECT COUNT(*) FROM articles WHERE language = 'Spanish' AND YEAR(publication_date) = 2021;
What is the number of mental health parity violation incidents reported by community health workers in New York?
CREATE TABLE mental_health_parity (id INT,worker_id INT,incident_date DATE,violation_count INT); INSERT INTO mental_health_parity (id,worker_id,incident_date,violation_count) VALUES (1,123,'2021-01-01',5),(2,123,'2021-01-15',3); CREATE TABLE community_health_workers (id INT,name VARCHAR(50),region VARCHAR(50)); INSERT INTO community_health_workers (id,name,region) VALUES (123,'John Doe','New York');
SELECT SUM(violation_count) FROM mental_health_parity INNER JOIN community_health_workers ON mental_health_parity.worker_id = community_health_workers.id WHERE community_health_workers.region = 'New York';
What is the number of unique customers who have purchased skincare products in the 'customer_skincare_sales' table?
CREATE TABLE customer_skincare_sales (customer_id INT,product_id INT,sale_price DECIMAL(5,2));
SELECT COUNT(DISTINCT customer_id) FROM customer_skincare_sales;
List the regions and their water usage in cubic meters from the 'drought_impact' and 'water_usage' tables
CREATE TABLE drought_impact (region_id INT,drought_status VARCHAR(50),water_usage FLOAT);
SELECT drought_impact.region_id, drought_impact.drought_status, water_usage FROM drought_impact INNER JOIN water_usage ON drought_impact.region_id = water_usage.region_id;
How many exoplanets have been discovered in the constellation Cygnus?
CREATE TABLE exoplanets (id INT,exoplanet_name VARCHAR(50),constellation VARCHAR(30),discovery_year INT);
SELECT COUNT(*) FROM exoplanets WHERE constellation = 'Cygnus';
What is the average mass of space objects in low Earth orbit?
CREATE TABLE space_objects_leo (id INT,name VARCHAR(255),mass FLOAT); INSERT INTO space_objects_leo (id,name,mass) VALUES (1,'Space Object 1',1000.0),(2,'Space Object 2',1500.0),(3,'Space Object 3',500.0);
SELECT AVG(mass) FROM space_objects_leo;
Delete all records from the "products" table where the "manufacturing_country" is "China"
CREATE TABLE products (id INT PRIMARY KEY,name VARCHAR(100),manufacturing_country VARCHAR(50)); INSERT INTO products (id,name,manufacturing_country) VALUES (1,'productA','China'),(2,'productB','Mexico');
DELETE FROM products WHERE manufacturing_country = 'China';
List the number of wells drilled in the North Sea by each country in 2019
CREATE TABLE well_drilling (year INT,region VARCHAR(255),country VARCHAR(255),num_wells INT); INSERT INTO well_drilling (year,region,country,num_wells) VALUES (2017,'North Sea','Norway',25),(2017,'North Sea','UK',30),(2017,'North Sea','Denmark',12),(2018,'North Sea','Norway',28),(2018,'North Sea','UK',32),(2018,'North Sea','Denmark',15),(2019,'North Sea','Norway',31),(2019,'North Sea','UK',35),(2019,'North Sea','Denmark',18);
SELECT country, SUM(num_wells) FROM well_drilling WHERE year = 2019 AND region = 'North Sea' GROUP BY country;
What's the total number of players who play action games on VR platforms?
CREATE TABLE Players (PlayerID INT,Name VARCHAR(100),Age INT,FavoriteGenre VARCHAR(50),VRPossible BOOLEAN); INSERT INTO Players (PlayerID,Name,Age,FavoriteGenre,VRPossible) VALUES (1,'John Doe',25,'Action',true),(2,'Jane Smith',28,'Adventure',true),(3,'James Johnson',30,'Simulation',true),(4,'Emily Davis',24,'Strategy',false);
SELECT COUNT(*) FROM Players WHERE FavoriteGenre = 'Action' AND VRPossible = true;
Find the yttrium production difference between 2018 and 2019 for each company.
CREATE TABLE YttriumProduction (Company VARCHAR(50),Year INT,Production FLOAT); INSERT INTO YttriumProduction(Company,Year,Production) VALUES ('CompanyA',2018,115.6),('CompanyA',2019,134.8),('CompanyA',2020,146.2),('CompanyB',2018,98.1),('CompanyB',2019,109.5),('CompanyB',2020,120.9);
SELECT Company, Production - LEAD(Production) OVER (PARTITION BY Company ORDER BY Year) as Difference FROM YttriumProduction WHERE Company IN ('CompanyA', 'CompanyB');
How many bikes are available at each station on the Green Line?
CREATE TABLE stations (line_name VARCHAR(50),station_name VARCHAR(50),bikes_available INT); INSERT INTO stations (line_name,station_name,bikes_available) VALUES ('Green Line','Station A',10),('Green Line','Station B',8),('Green Line','Station C',12);
SELECT station_name, bikes_available FROM stations WHERE line_name = 'Green Line';
Delete all products that have 'Made in China' in 'origin' column
CREATE TABLE product (product_id VARCHAR(10),name VARCHAR(50),price DECIMAL(5,2),supplier_id VARCHAR(10),origin VARCHAR(50),primary key (product_id));
DELETE FROM product WHERE origin LIKE '%Made in China%';
Update the price of samarium oxide to $30.50 in the table 'market_trends'
CREATE TABLE market_trends (id INT,element VARCHAR(10),price DECIMAL(5,2),date DATE); INSERT INTO market_trends (id,element,price,date) VALUES (1,'samarium',28.25,'2022-01-01'),(2,'samarium',29.00,'2022-02-01'),(3,'samarium',30.00,'2022-03-01');
UPDATE market_trends SET price = 30.50 WHERE element = 'samarium';
Which universities have marine research stations in the Pacific Ocean?
CREATE TABLE Research_Station (station_name VARCHAR(50),latitude NUMERIC(8,2),longitude NUMERIC(8,2),ocean_name VARCHAR(50)); INSERT INTO Research_Station (station_name,latitude,longitude,ocean_name) VALUES ('Station A',40.7128,-74.0060,'Pacific'),('Station B',34.0522,-118.2437,'Indian'); CREATE TABLE University (university_name VARCHAR(50),station_name VARCHAR(50)); INSERT INTO University (university_name,station_name) VALUES ('University X','Station A'),('University Y','Station B');
SELECT University.university_name FROM University INNER JOIN Research_Station ON University.station_name = Research_Station.station_name WHERE Research_Station.ocean_name = 'Pacific';
Delete all records from 'Rosetta Stone' excavation.
CREATE TABLE ExcavationSites (SiteID INT PRIMARY KEY,Name VARCHAR(255),Country VARCHAR(255),StartDate DATE,EndDate DATE); INSERT INTO ExcavationSites (SiteID,Name,Country,StartDate,EndDate) VALUES (4,'Rosetta Stone','Egypt','1799-07-15','1799-07-19'); CREATE TABLE Artifacts (ArtifactID INT PRIMARY KEY,Name VARCHAR(255),SiteID INT,DateFound DATE,Description TEXT); INSERT INTO Artifacts (ArtifactID,Name,SiteID,DateFound,Description) VALUES (5,'Rosetta Stone',4,'1799-07-16','Stone slab inscribed with three versions of a decree issued at Memphis');
DELETE FROM Artifacts WHERE SiteID = 4; DELETE FROM ExcavationSites WHERE SiteID = 4;
Delete all records of customers from 'Africa' region.
CREATE TABLE customers (id INT,name VARCHAR(100),region VARCHAR(50),assets_value FLOAT); INSERT INTO customers (id,name,region,assets_value) VALUES (1,'Oluwatobi Adebayo','Africa',300000.00);
DELETE FROM customers WHERE region = 'Africa';
What is the average temperature trend in France over the past 5 years, based on historical IoT sensor data?
CREATE TABLE weather_data (location VARCHAR(255),date DATE,temperature FLOAT); INSERT INTO weather_data (location,date,temperature) VALUES ('France','2017-01-01',4.2),('France','2017-01-02',4.5),('France','2018-01-01',3.9),('France','2018-01-02',4.1),('France','2019-01-01',3.7),('France','2019-01-02',3.8),('France','2020-01-01',4.0),('France','2020-01-02',4.3);
SELECT AVG(temperature) FROM (SELECT temperature FROM weather_data WHERE location = 'France' AND date BETWEEN '2017-01-01' AND '2021-12-31' GROUP BY YEAR(date)) AS subquery;
What was the maximum number of attendees at events in the Midwest region in 2021?
CREATE TABLE EventAttendance (event_id INT,region VARCHAR(50),attendees INT,event_date DATE); INSERT INTO EventAttendance (event_id,region,attendees,event_date) VALUES (200,'Midwest',500,'2021-01-01'),(201,'Midwest',600,'2021-02-01'),(202,'West',400,'2021-01-01');
SELECT MAX(attendees) FROM EventAttendance WHERE region = 'Midwest' AND YEAR(event_date) = 2021;
Which spacecraft have been used in the most space missions?
CREATE TABLE spacecraft_missions (id INT PRIMARY KEY,spacecraft_name VARCHAR(50),mission_name VARCHAR(50));
SELECT spacecraft_name, COUNT(*) as num_missions FROM spacecraft_missions GROUP BY spacecraft_name ORDER BY num_missions DESC;
What is the number of female founders in each industry?
CREATE TABLE founders (founder_id INT,company_id INT,gender VARCHAR(10)); CREATE TABLE companies (company_id INT,industry VARCHAR(255)); INSERT INTO founders (founder_id,company_id,gender) VALUES (1,1,'Female'),(2,2,'Male'),(3,3,'Female'),(4,4,'Female'); INSERT INTO companies (company_id,industry) VALUES (1,'Tech'),(2,'Healthcare'),(3,'Tech'),(4,'Healthcare');
SELECT industry, COUNT(f.founder_id) as num_female_founders FROM founders f JOIN companies c ON f.company_id = c.company_id WHERE f.gender = 'Female' GROUP BY industry;
What is the total investment in bioprocess engineering by month in 2021?
CREATE TABLE bioprocess(id INT,investment VARCHAR(50),date DATE,amount DECIMAL(10,2)); INSERT INTO bioprocess VALUES (1,'InvestmentA','2021-04-15',2000000.00),(2,'InvestmentB','2021-06-30',1500000.00),(3,'InvestmentC','2021-02-28',2500000.00);
SELECT EXTRACT(MONTH FROM date), SUM(amount) FROM bioprocess GROUP BY EXTRACT(MONTH FROM date);
Show the client_name and case_outcome for all cases in the 'civil' table
CREATE TABLE civil (case_id INT,client_name VARCHAR(50),case_type VARCHAR(20),case_outcome VARCHAR(20),case_date DATE); INSERT INTO civil (case_id,client_name,case_type,case_outcome,case_date) VALUES (7,'Alice Davis','traffic','settled','2021-02-22');
SELECT client_name, case_outcome FROM civil;
Which vessels have been inspected in the last month?
CREATE TABLE Vessel (vessel_id INT,name VARCHAR(255),type VARCHAR(255),max_speed DECIMAL(5,2)); CREATE TABLE Inspection (inspection_id INT,vessel_id INT,inspection_time TIMESTAMP); INSERT INTO Vessel (vessel_id,name,type,max_speed) VALUES (1,'Test Vessel 1','Cargo',20.5),(2,'Test Vessel 2','Tanker',15.2); INSERT INTO Inspection (inspection_id,vessel_id,inspection_time) VALUES (1,1,'2022-01-01 12:00:00'),(2,2,'2022-01-15 10:00:00'),(3,1,'2022-02-01 09:00:00');
SELECT v.vessel_id, v.name FROM Vessel v INNER JOIN Inspection i ON v.vessel_id = i.vessel_id WHERE i.inspection_time >= NOW() - INTERVAL '1 month';
Update the 'climate_pledges' table by setting 'status' to 'active' for all records where 'country' is 'India'
CREATE TABLE climate_pledges (id INT,country VARCHAR(255),status VARCHAR(255));
UPDATE climate_pledges SET status = 'active' WHERE country = 'India';
Add a new record for a patient from Texas who received group therapy.
CREATE TABLE patients (id INT,name TEXT,state TEXT);CREATE TABLE treatments (id INT,patient_id INT,therapy TEXT);
INSERT INTO patients (id, name, state) VALUES (1, 'Maria Rodriguez', 'Texas');INSERT INTO treatments (id, patient_id, therapy) VALUES (1, 1, 'Group Therapy');
How many total donations were made by 'local_communities' in the 'community_support' table?
CREATE TABLE community_support (donation_id INT,community VARCHAR(50),amount DECIMAL(10,2),donation_date DATE); INSERT INTO community_support (donation_id,community,amount,donation_date) VALUES (1,'Hopeful Hearts Local Community',150.00,'2021-01-01'),(2,'United Neighbors (humanitarian aid)',200.00,'2021-02-01');
SELECT SUM(amount) FROM community_support WHERE community LIKE '%local community%';
What is the total number of employees in factories that use renewable energy?
CREATE TABLE RenewableEnergyFactories (id INT,num_employees INT);
select sum(num_employees) from RenewableEnergyFactories;
Calculate the average temperature for the last 7 days for 'field6'.
CREATE TABLE field6 (date DATE,temperature FLOAT); INSERT INTO field6 (date,temperature) VALUES ('2021-10-20',15.2),('2021-10-21',16.1),('2021-10-22',17.3);
SELECT AVG(temperature) FROM field6 WHERE date >= (CURRENT_DATE - INTERVAL '7 days');
What is the average viewership for each artist's music videos?
CREATE TABLE Music_Videos (artist VARCHAR(255),viewership INT); INSERT INTO Music_Videos (artist,viewership) VALUES ('Artist1',10000000),('Artist2',15000000),('Artist3',20000000),('Artist4',12000000),('Artist5',18000000);
SELECT artist, AVG(viewership) FROM Music_Videos GROUP BY artist;
Compare the number of high and medium severity vulnerabilities found in the last quarter for web and desktop applications.
CREATE TABLE vulnerabilities (id INT,app_type VARCHAR(10),severity VARCHAR(10),timestamp TIMESTAMP);
SELECT app_type, severity, COUNT(*) as total FROM vulnerabilities WHERE severity IN ('high', 'medium') AND timestamp >= NOW() - INTERVAL 3 MONTH GROUP BY app_type, severity;
What is the total value of defense contracts awarded to companies in the aerospace industry in the last fiscal year?
CREATE TABLE defense_contracts (contract_id INT,contract_date DATE,contract_value DECIMAL(10,2),contractor TEXT,industry TEXT);
SELECT SUM(contract_value) FROM defense_contracts WHERE industry = 'aerospace' AND contract_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR) AND contract_date < DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR - INTERVAL 1 DAY);
What is the total number of healthcare providers in rural areas of Alaska, serving more than 500 patients?
CREATE TABLE provider (provider_id INT,name VARCHAR(50),location VARCHAR(20),patients_served INT); INSERT INTO provider (provider_id,name,location,patients_served) VALUES (1,'Rural Provider A','Alaska',700); INSERT INTO provider (provider_id,name,location,patients_served) VALUES (2,'Rural Provider B','Alaska',300); INSERT INTO provider (provider_id,name,location,patients_served) VALUES (3,'Urban Provider A','California',800);
SELECT location, COUNT(*) FROM provider WHERE patients_served > 500 AND location = 'Alaska' GROUP BY location;
What is the total number of primary care physicians and pediatricians in the database?
CREATE TABLE Providers (ID INT,Name TEXT,Specialty TEXT); INSERT INTO Providers (ID,Name,Specialty) VALUES (1,'Dr. A','Primary Care'); INSERT INTO Providers (ID,Name,Specialty) VALUES (2,'Dr. B','Pediatrics');
SELECT COUNT(*) FROM Providers WHERE Specialty = 'Primary Care' UNION SELECT COUNT(*) FROM Providers WHERE Specialty = 'Pediatrics';
What is the name of the manufacturer for the latest unmanned aerial vehicle (UAV) in the 'military_tech' table?
CREATE TABLE military_tech (code INT,name VARCHAR(50),type VARCHAR(50),manufacturer VARCHAR(50),last_updated TIMESTAMP);
SELECT manufacturer FROM military_tech WHERE type = 'UAV' AND last_updated = (SELECT MAX(last_updated) FROM military_tech WHERE type = 'UAV');
List the number of sustainable hotels in each country that have more than 150 reviews.
CREATE TABLE sustainable_hotels (id INT,name TEXT,country TEXT,reviews INT); INSERT INTO sustainable_hotels (id,name,country,reviews) VALUES (1,'Eco-Hotel','Germany',180),(2,'Green-Lodge','Germany',120),(3,'Nature-Resort','Italy',200);
SELECT country, COUNT(*) as hotel_count FROM sustainable_hotels WHERE reviews > 150 GROUP BY country;
What is the average mobile data usage in GB per customer in the Southeast Asia region for the past year?
CREATE TABLE subscribers (id INT,service VARCHAR(10),region VARCHAR(20)); INSERT INTO subscribers (id,service,region) VALUES (1,'mobile','Southeast Asia'),(2,'broadband','Southeast Asia'); CREATE TABLE usage (subscriber_id INT,data_usage FLOAT,year INT); INSERT INTO usage (subscriber_id,data_usage,year) VALUES (1,12.5,2022),(1,13.0,2021),(1,11.5,2020),(2,550,2022),(2,555,2021),(2,550,2020);
SELECT AVG(usage.data_usage/1024/1024/1024) FROM usage JOIN subscribers ON usage.subscriber_id = subscribers.id WHERE subscribers.service = 'mobile' AND subscribers.region = 'Southeast Asia' AND usage.year BETWEEN 2021 AND 2022;
Which indigenous communities are affected by the decline in caribou populations?
CREATE TABLE caribou_data (id INT,community VARCHAR(255),population INT); INSERT INTO caribou_data (id,community,population) VALUES (1,'Gwich’in',1000),(2,'Inuit',800); CREATE TABLE community_data (id INT,community VARCHAR(255),population INT); INSERT INTO community_data (id,community,population) VALUES (1,'Gwich’in',3000),(2,'Inuit',5000);
SELECT a.community FROM caribou_data a JOIN community_data b ON a.community = b.community WHERE a.population < b.population;
What is the minimum size (in square kilometers) of a habitat for animals in the 'habitats' table that are not mammals?
CREATE TABLE habitats (id INT,animal_type VARCHAR(50),size_km FLOAT); INSERT INTO habitats (id,animal_type,size_km) VALUES (1,'Mammal',45.1),(2,'Reptile',25.1);
SELECT MIN(size_km) FROM habitats WHERE animal_type != 'Mammal';
What was the average donation amount per donor for donations made in 2022?
CREATE TABLE donors (id INT,donor_name VARCHAR(50),donation_amount DECIMAL(10,2),donation_date DATE); INSERT INTO donors (id,donor_name,donation_amount,donation_date) VALUES (4,'Jamie Smith',120.00,'2022-01-05'),(5,'Ali Hassan',180.00,'2022-02-20'),(6,'Park Soo-jin',220.00,'2022-03-12');
SELECT AVG(donation_amount) as average_donation_amount FROM donors WHERE donation_date BETWEEN '2022-01-01' AND '2022-12-31';
What was the total cost of bridge construction projects in 'Texas' in 2018?
CREATE TABLE bridge_construction (id INT,project_name TEXT,location TEXT,cost INT,completion_date DATE); INSERT INTO bridge_construction (id,project_name,location,cost,completion_date) VALUES (1,'Houston Tunnel','Texas',12000000,'2018-08-25'); INSERT INTO bridge_construction (id,project_name,location,cost,completion_date) VALUES (2,'Dallas Overpass','Texas',9000000,'2018-12-11');
SELECT SUM(cost) FROM bridge_construction WHERE location = 'Texas' AND YEAR(completion_date) = 2018;
What are the names and ages of volunteers who made donations greater than $200?
CREATE TABLE Volunteers (id INT,name TEXT,age INT); CREATE TABLE Donations (id INT,volunteer_id INT,amount FLOAT); INSERT INTO Volunteers (id,name,age) VALUES (1,'Fatima',35),(2,'Jakub',40); INSERT INTO Donations (id,volunteer_id,amount) VALUES (1,1,300.0),(2,2,150.0);
SELECT Volunteers.name, Volunteers.age FROM Volunteers INNER JOIN Donations ON Volunteers.id = Donations.volunteer_id WHERE Donations.amount > 200.0;
Calculate the total habitat depth for all marine species.
CREATE TABLE species (id INT,name VARCHAR(50),habitat_type VARCHAR(50),habitat_depth FLOAT);
SELECT SUM(habitat_depth) FROM species;
Calculate the total quantity of products in all categories
CREATE TABLE products (product_id INT,category VARCHAR(20),quantity INT); INSERT INTO products (product_id,category,quantity) VALUES (1,'apparel',50),(2,'accessories',70),(3,'home_decor',40),(4,'electronics',600),(5,'grocery',60),(6,'toys',30),(7,'furniture',150);
SELECT SUM(quantity) FROM products;
Count the number of investment strategies for each risk level.
CREATE TABLE investment_strategies (strategy_id INT,ESG_score FLOAT,risk_level INT); INSERT INTO investment_strategies (strategy_id,ESG_score,risk_level) VALUES (101,86.2,3),(102,78.9,5),(103,88.7,2),(104,65.1,1);
SELECT risk_level, COUNT(*) FROM investment_strategies GROUP BY risk_level;
Who is the oldest artist in the database?
CREATE TABLE Artists (id INT,name TEXT,gender TEXT,birth_date DATE); INSERT INTO Artists VALUES (1,'Leonardo da Vinci','Male','1452-04-15'); INSERT INTO Artists VALUES (2,'Michelangelo','Male','1475-03-06'); INSERT INTO Artists VALUES (3,'Artemisia Gentileschi','Female','1593-07-08');
SELECT name, MAX(birth_date) as birth_date FROM Artists;
How many marine species are impacted by ocean acidification?
CREATE TABLE ocean_acidification_impact (species_id INTEGER,species_name VARCHAR(255),impact VARCHAR(50));
SELECT COUNT(species_id) FROM ocean_acidification_impact WHERE impact IS NOT NULL;
What is the financial capability score distribution across different age groups?
CREATE TABLE financial_capability (id INT,age_group VARCHAR(50),score FLOAT); INSERT INTO financial_capability (id,age_group,score) VALUES (1,'18-24',6.5),(2,'25-34',7.2),(3,'35-44',8.0),(4,'45-54',8.5),(5,'55-64',7.8),(6,'65+',7.0);
SELECT age_group, AVG(score) as avg_score, STDDEV(score) as std_dev FROM financial_capability GROUP BY age_group;
Insert new records into the community table
CREATE TABLE community(id INT,name VARCHAR(255),population INT,language VARCHAR(255));
INSERT INTO community (id, name, population, language) VALUES (1, 'Inuit', 80000, 'Inuktitut'); INSERT INTO community (id, name, population, language) VALUES (2, 'Sami', 80000, 'Northern Sami');
What is the total revenue generated by Latin music genres in 2021?
CREATE TABLE Sales (SaleID int,Genre varchar(50),SalesDate date,Revenue decimal(10,2)); INSERT INTO Sales VALUES (1,'Latin Pop','2021-01-01',5000); INSERT INTO Sales VALUES (2,'Reggaeton','2021-02-01',7000); INSERT INTO Sales VALUES (3,'Salsa','2021-03-01',6000);
SELECT SUM(Revenue) as TotalRevenue FROM Sales WHERE Genre like 'Latin%' AND YEAR(SalesDate) = 2021;
Identify the number of workers per sustainable material used in projects
CREATE TABLE labor_statistics (id INT PRIMARY KEY,project_id INT,workers_count INT,FOREIGN KEY (project_id) REFERENCES project(id)); INSERT INTO labor_statistics (id,project_id,workers_count) VALUES (1,1,50);
SELECT sm.material_name, AVG(l.workers_count) AS avg_workers_count FROM labor_statistics l INNER JOIN project p ON l.project_id = p.id INNER JOIN building_permit bp ON p.id = bp.project_id INNER JOIN sustainable_material sm ON bp.id = sm.permit_id WHERE sm.material_name IN ('Recycled Steel', 'Bamboo Flooring') GROUP BY sm.material_name;
What is the maximum landfill capacity in the state of California?
CREATE TABLE landfill_capacity (state VARCHAR(2),capacity INT); INSERT INTO landfill_capacity (state,capacity) VALUES ('CA',1500000),('NY',1200000),('NJ',1000000);
SELECT MAX(capacity) FROM landfill_capacity WHERE state = 'CA';
Which projects have contracts starting in the first quarter of 2024?
CREATE TABLE contracts (id INT PRIMARY KEY,project_id INT,contract_start_date DATE,contract_end_date DATE); INSERT INTO contracts (id,project_id,contract_start_date,contract_end_date) VALUES (1,1,'2024-01-01','2026-12-31');
SELECT project_id FROM contracts WHERE contract_start_date BETWEEN '2024-01-01' AND '2024-03-31';
List all states that do not have any community health workers.
CREATE TABLE state_health_equity (state VARCHAR(2),num_community_health_workers INT); INSERT INTO state_health_equity (state,num_community_health_workers) VALUES ('NY',10),('CA',5),('TX',0); CREATE VIEW community_health_workers_by_state AS SELECT state,COUNT(*) FROM community_health_workers GROUP BY state;
SELECT state FROM state_health_equity WHERE num_community_health_workers = 0 INTERSECT SELECT state FROM community_health_workers_by_state;
Delete all records from the 'equipment_inventory' table where the quantity is 0.
CREATE TABLE equipment_inventory (id INT,type VARCHAR(50),quantity INT); INSERT INTO equipment_inventory (id,type,quantity) VALUES (1,'Drilling Machine',15); INSERT INTO equipment_inventory (id,type,quantity) VALUES (2,'Excavator',8); INSERT INTO equipment_inventory (id,type,quantity) VALUES (3,'Bulldozer',5); INSERT INTO equipment_inventory (id,type,quantity) VALUES (4,'Dump Truck',0);
DELETE FROM equipment_inventory WHERE quantity = 0;
What is the average energy consumption per smart city?
CREATE TABLE smart_cities (city_name TEXT,energy_consumption FLOAT); INSERT INTO smart_cities VALUES ('CityA',500.0),('CityB',700.0),('CityC',300.0);
SELECT AVG(energy_consumption) FROM smart_cities;