instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
What is the total revenue generated by sustainable tourism accommodations in each country?
CREATE TABLE accommodations (accommodation_id INT,name VARCHAR(255),location VARCHAR(255),type VARCHAR(255),num_reviews INT,avg_review_score DECIMAL(5,2),country VARCHAR(255),revenue DECIMAL(10,2)); INSERT INTO accommodations (accommodation_id,name,location,type,num_reviews,avg_review_score,country,revenue) VALUES (1,'...
SELECT country, SUM(revenue) AS total_revenue FROM accommodations GROUP BY country;
What is the average number of therapy sessions per month for patients in London?
CREATE TABLE therapy_sessions_london (id INT,patient_id INT,session_date DATE); INSERT INTO therapy_sessions_london (id,patient_id,session_date) VALUES (1,1,'2021-01-01'),(2,1,'2021-02-01'),(3,2,'2021-03-01'),(4,3,'2021-04-01'),(5,3,'2021-04-15'),(6,4,'2021-05-01');
SELECT EXTRACT(MONTH FROM session_date) AS month, AVG(therapy_sessions_london.id) AS avg_sessions FROM therapy_sessions_london WHERE city = 'London' GROUP BY month;
What is the average yield of rice crops in Indonesia, considering only organic farming methods?
CREATE TABLE rice_yields (farmer_id INT,country VARCHAR(50),crop VARCHAR(50),yield INT,is_organic BOOLEAN); INSERT INTO rice_yields (farmer_id,country,crop,yield,is_organic) VALUES (1,'Indonesia','Rice',1000,true),(2,'Indonesia','Rice',1200,false),(3,'Indonesia','Rice',1500,true);
SELECT AVG(yield) FROM rice_yields WHERE country = 'Indonesia' AND is_organic = true;
Insert a new record for a worker in the 'Electronics' industry who is 30 years old, male, earns a salary of $65,000, and has received ethical manufacturing training.
CREATE TABLE Workers (ID INT,Age INT,Gender VARCHAR(10),Salary DECIMAL(5,2),Industry VARCHAR(20),Ethical_Training BOOLEAN); INSERT INTO Workers (ID,Age,Gender,Salary,Industry,Ethical_Training) VALUES (1,42,'Female',50000.00,'Textile',FALSE); INSERT INTO Workers (ID,Age,Gender,Salary,Industry,Ethical_Training) VALUES (2...
INSERT INTO Workers (ID, Age, Gender, Salary, Industry, Ethical_Training) VALUES (4, 30, 'Male', 65000.00, 'Electronics', TRUE);
How many fires were reported in the 'Harlem' district during each month in 2022?
CREATE TABLE fire_data (fire_id INT,fire_type TEXT,district TEXT,date DATE);
SELECT district, EXTRACT(MONTH FROM date) AS month, COUNT(*) AS num_fires FROM fire_data WHERE district = 'Harlem' AND date BETWEEN '2022-01-01' AND '2022-12-31' GROUP BY district, month;
Update the claims table and insert a new claim record for policy number 3 with a claim amount of 5000 and claim date of '2021-03-15'
CREATE TABLE claims (claim_number INT,policy_number INT,claim_amount INT,claim_date DATE);
INSERT INTO claims (claim_number, policy_number, claim_amount, claim_date) VALUES (1, 3, 5000, '2021-03-15'); UPDATE claims SET claim_amount = 6000 WHERE policy_number = 3 AND claim_date = '2020-01-01';
Delete all records from the 'Habitats' table.
CREATE TABLE habitats (id INT,habitat_type VARCHAR(255)); INSERT INTO habitats (id,habitat_type) VALUES (1,'Forest'),(2,'Savannah'),(3,'Wetlands');
DELETE FROM habitats;
What is the total water consumption by each sector in the most recent year?
CREATE TABLE sector_year_consumption (year INT,sector INT,consumption FLOAT,PRIMARY KEY(year,sector)); INSERT INTO sector_year_consumption (year,sector,consumption) VALUES (2015,1,15000),(2015,2,20000),(2015,3,30000),(2016,1,16000),(2016,2,22000),(2016,3,32000),(2017,1,17000),(2017,2,24000),(2017,3,34000);
SELECT syc.sector, SUM(syc.consumption) as total_consumption FROM sector_year_consumption syc JOIN (SELECT MAX(year) as most_recent_year FROM sector_year_consumption) max_year ON 1=1 WHERE syc.year = max_year.most_recent_year GROUP BY syc.sector;
How many total volunteers have there been in projects funded by the European Union?
CREATE TABLE volunteers (id INT,project_id INT,name TEXT); INSERT INTO volunteers (id,project_id,name) VALUES (1,1,'Alice'),(2,1,'Bob'),(3,2,'Charlie'); CREATE TABLE projects (id INT,funder TEXT,total_funding DECIMAL); INSERT INTO projects (id,funder,total_funding) VALUES (1,'European Union',20000.00),(2,'United Nation...
SELECT COUNT(*) FROM volunteers INNER JOIN projects ON volunteers.project_id = projects.id WHERE projects.funder = 'European Union';
Find the top 5 organizations with the largest number of volunteers in Asia.
CREATE TABLE organizations (id INT,name VARCHAR(50),country VARCHAR(50),num_volunteers INT); INSERT INTO organizations (id,name,country,num_volunteers) VALUES (1,'UNICEF','India',500),(2,'Red Cross','China',700),(3,'Greenpeace','Japan',300);
SELECT name, num_volunteers FROM organizations WHERE country IN ('India', 'China', 'Japan', 'Pakistan', 'Indonesia') ORDER BY num_volunteers DESC LIMIT 5;
What is the minimum monthly bill for broadband subscribers in the city of San Francisco?
CREATE TABLE broadband_subscribers (subscriber_id INT,monthly_bill FLOAT,city VARCHAR(20)); INSERT INTO broadband_subscribers (subscriber_id,monthly_bill,city) VALUES (1,60.5,'San Francisco'),(2,70.3,'Houston'),(3,55.7,'San Francisco');
SELECT MIN(monthly_bill) FROM broadband_subscribers WHERE city = 'San Francisco';
List all unique garment types in the 'Inventory' table, excluding 'Unisex' entries.
CREATE TABLE Inventory (garment_type VARCHAR(20)); INSERT INTO Inventory (garment_type) VALUES ('Dress'),('Shirt'),('Pants'),('Unisex');
SELECT DISTINCT garment_type FROM Inventory WHERE garment_type != 'Unisex';
What is the maximum flight time for Boeing 737 aircraft?
CREATE TABLE Flight_Data (flight_date DATE,aircraft_model VARCHAR(255),flight_time TIME); INSERT INTO Flight_Data (flight_date,aircraft_model,flight_time) VALUES ('2020-01-01','Boeing 737','03:00:00'),('2020-02-01','Boeing 737','04:00:00'),('2020-03-01','Boeing 737','05:00:00'),('2020-04-01','Boeing 737','03:30:00'),('...
SELECT MAX(EXTRACT(EPOCH FROM flight_time)) / 60.0 AS max_flight_time FROM Flight_Data WHERE aircraft_model = 'Boeing 737';
What is the earliest release date of any album?
CREATE TABLE albums (id INT,title TEXT,release_date DATE); INSERT INTO albums (id,title,release_date) VALUES (1,'Millennium','1999-12-31'),(2,'Hybrid Theory','2000-01-02');
SELECT MIN(release_date) FROM albums;
Identify the top 3 mine sites with the highest labor productivity.
CREATE TABLE MineSites (SiteID INT PRIMARY KEY,Name VARCHAR(50),Country VARCHAR(50),LaborProductivityDecimal FLOAT); CREATE VIEW LaborProductivityView AS SELECT Employees.SiteID,AVG(LaborProductivity.ProductivityDecimal) AS AverageProductivity FROM Employees JOIN LaborProductivity ON Employees.EmployeeID = LaborProduct...
SELECT MineSites.Name, AVG(LaborProductivityView.AverageProductivity) AS AverageProductivity FROM MineSites JOIN LaborProductivityView ON MineSites.SiteID = LaborProductivityView.SiteID GROUP BY MineSites.Name ORDER BY AverageProductivity DESC LIMIT 3;
What is the total revenue of vegan makeup products in the UK in 2021?
CREATE TABLE MakeupSales (sale_id INT,product_name VARCHAR(100),category VARCHAR(50),price DECIMAL(10,2),quantity INT,sale_date DATE,country VARCHAR(50),vegan BOOLEAN);
SELECT SUM(price * quantity) FROM MakeupSales WHERE category = 'Makeup' AND country = 'UK' AND vegan = TRUE AND sale_date >= '2021-01-01' AND sale_date < '2022-01-01';
List the number of fans from different countries who have attended home games of each team, excluding games with attendance less than 15000.
CREATE TABLE teams (team_id INT,team_name VARCHAR(50));CREATE TABLE games (game_id INT,team_id INT,home_team BOOLEAN,price DECIMAL(5,2),attendance INT,fan_country VARCHAR(50));INSERT INTO teams (team_id,team_name) VALUES (1,'Knicks'),(2,'Lakers');INSERT INTO games (game_id,team_id,home_team,price,attendance,fan_country...
SELECT t.team_name, COUNT(DISTINCT g.fan_country) AS unique_fan_countries FROM teams t INNER JOIN games g ON t.team_id = g.team_id AND g.home_team = t.team_id WHERE g.attendance >= 15000 GROUP BY t.team_name;
Show the total inventory cost for 'vegan' and 'gluten-free' items across all restaurants.
CREATE TABLE Inventory (restaurant VARCHAR(20),item_type VARCHAR(15),cost DECIMAL(5,2)); INSERT INTO Inventory (restaurant,item_type,cost) VALUES ('GreenLeaf','vegan',5.50),('GreenLeaf','gluten-free',4.75),('Sprout','vegan',6.25),('Sprout','gluten-free',5.00);
SELECT SUM(cost) FROM Inventory WHERE item_type IN ('vegan', 'gluten-free');
What is the count of players from Latin America who have played at least 5 different games?
CREATE TABLE PlayersLA (PlayerID INT,PlayerName VARCHAR(100),Country VARCHAR(50)); INSERT INTO PlayersLA (PlayerID,PlayerName,Country) VALUES (1,'Pedro Alvarez','Brazil'),(2,'Jose Garcia','Argentina'),(3,'Maria Rodriguez','Colombia'); CREATE TABLE GameSessionsLA (SessionID INT,PlayerID INT,GameID INT); INSERT INTO Game...
SELECT COUNT(DISTINCT PlayerID) FROM (SELECT PlayerID FROM GameSessionsLA JOIN PlayersLA ON GameSessionsLA.PlayerID = PlayersLA.PlayerID GROUP BY PlayerID HAVING COUNT(DISTINCT GameID) >= 5) AS Subquery;
How many viewers watched the 'Music Concert' from the 'Streaming' platform?
CREATE TABLE viewership (id INT,event VARCHAR(50),platform VARCHAR(20),viewers INT); INSERT INTO viewership (id,event,platform,viewers) VALUES (1,'Music Concert','Streaming',500000),(2,'Sports Event','Streaming',750000),(3,'Movie Night','Theater',300000);
SELECT viewers FROM viewership WHERE event = 'Music Concert' AND platform = 'Streaming';
What is the average donation amount for each category?
CREATE TABLE Donations (DonationID INT,DonorID INT,DonationDate DATE,DonationAmount DECIMAL(10,2),DonationPurpose VARCHAR(50)); CREATE TABLE Donors (DonorID INT,DonorName VARCHAR(50),DonationType VARCHAR(50));
SELECT DonationPurpose, AVG(DonationAmount) FROM Donations d JOIN Donors don ON d.DonorID = don.DonorID GROUP BY DonationPurpose;
Assign a quartile rank based on carbon footprint, ordered by carbon footprint in ascending order.
CREATE TABLE SustainabilityMetrics (ProductID INT,SustainabilityRating INT,CarbonFootprint INT); INSERT INTO SustainabilityMetrics (ProductID,SustainabilityRating,CarbonFootprint) VALUES (1,90,50); INSERT INTO SustainabilityMetrics (ProductID,SustainabilityRating,CarbonFootprint) VALUES (2,85,75);
SELECT ProductID, SustainabilityRating, CarbonFootprint, NTILE(4) OVER (ORDER BY CarbonFootprint ASC) as 'Quartile' FROM SustainabilityMetrics;
Identify the number of cases heard by each judge, along with the judge's name, in the state of Texas.
CREATE TABLE court_cases (case_id INT,judge_name TEXT,case_state TEXT); INSERT INTO court_cases (case_id,judge_name,case_state) VALUES (11111,'Judge Smith','Texas'); INSERT INTO court_cases (case_id,judge_name,case_state) VALUES (22222,'Judge Johnson','Texas');
SELECT judge_name, COUNT(*) as cases_heard FROM court_cases WHERE case_state = 'Texas' GROUP BY judge_name;
What was the average age of visitors who attended the 'Art of the Renaissance' exhibition?
CREATE TABLE exhibitions (exhibition_id INT,exhibition_name VARCHAR(255),start_date DATE,end_date DATE); INSERT INTO exhibitions (exhibition_id,exhibition_name,start_date,end_date) VALUES (1,'Art of the Renaissance','2020-01-01','2020-12-31'); CREATE TABLE visitors (visitor_id INT,exhibition_id INT,age INT,gender VARCH...
SELECT AVG(age) FROM visitors WHERE exhibition_id = 1;
What are the campaigns running after January 1, 2023?
CREATE TABLE campaigns (id INT PRIMARY KEY,name VARCHAR(255),start_date DATE,end_date DATE); INSERT INTO campaigns (id,name,start_date,end_date) VALUES (7,'Mindfulness in Daily Life','2023-01-02','2023-12-31');
SELECT * FROM campaigns WHERE start_date >= '2023-01-01';
How many tickets were sold for the home_team in the ticket_sales table?
CREATE TABLE ticket_sales (sale_id INT,team VARCHAR(50),quantity INT); INSERT INTO ticket_sales (sale_id,team,quantity) VALUES (1,'home_team',100); INSERT INTO ticket_sales (sale_id,team,quantity) VALUES (2,'away_team',75);
SELECT SUM(quantity) FROM ticket_sales WHERE team = 'home_team';
Add a new exhibition with ID 3, title 'Surrealism in the 20th Century', genre 'Surrealism', and century '20th Century'.
CREATE TABLE Exhibitions (id INT,title VARCHAR(255),genre VARCHAR(255),century VARCHAR(255));
INSERT INTO Exhibitions (id, title, genre, century) VALUES (3, 'Surrealism in the 20th Century', 'Surrealism', '20th Century');
What is the total funding received by biotech startups located in India?
CREATE TABLE startups (id INT,name VARCHAR(50),location VARCHAR(50),funding FLOAT); INSERT INTO startups (id,name,location,funding) VALUES (1,'Genomic Solutions','USA',5000000),(2,'BioTech Innovations','Europe',7000000),(3,'Medical Innovations','UK',6000000),(4,'Innovative Biotech','India',8000000);
SELECT SUM(funding) FROM startups WHERE location = 'India';
Identify the carbon price for a specific country on a particular date.
CREATE TABLE carbon_prices (country VARCHAR(255),date DATE,price FLOAT); INSERT INTO carbon_prices VALUES ('USA','2023-01-01',10),('Canada','2023-01-01',15),('USA','2023-02-01',11),('Canada','2023-02-01',16);
SELECT price FROM carbon_prices WHERE country = 'Canada' AND date = '2023-02-01';
What is the average number of citizen feedback records per month for 2023?
CREATE TABLE feedback (id INT,created_at DATETIME); INSERT INTO feedback (id,created_at) VALUES (1,'2023-01-01 12:34:56'),(2,'2023-01-15 10:20:34'),(3,'2023-02-20 16:45:01');
SELECT AVG(num_records) FROM (SELECT DATE_FORMAT(created_at, '%Y-%m') as month, COUNT(*) as num_records FROM feedback WHERE created_at BETWEEN '2023-01-01' AND '2023-12-31' GROUP BY month) as subquery;
Write a SQL query to retrieve the policyholder information and corresponding claim data from the view you created
SELECT * FROM policyholder_claim_info;
SELECT * FROM policyholder_claim_info;
How many agricultural innovation projects were started in Nigeria between 2010 and 2014?'
CREATE TABLE agricultural_innovation_projects (id INT,country VARCHAR(255),start_year INT,end_year INT,started INT); INSERT INTO agricultural_innovation_projects (id,country,start_year,end_year,started) VALUES (1,'Nigeria',2010,2014,1),(2,'Nigeria',2012,2016,1),(3,'Nigeria',2011,2015,1);
SELECT COUNT(*) FROM agricultural_innovation_projects WHERE country = 'Nigeria' AND start_year >= 2010 AND end_year <= 2014 AND started = 1;
What is the number of startups founded by individuals from underrepresented racial or ethnic backgrounds in the tech sector?
CREATE TABLE startup (id INT,name TEXT,industry TEXT,founding_date DATE,founder_race TEXT); INSERT INTO startup (id,name,industry,founding_date,founder_race) VALUES (1,'AptDeco','E-commerce','2014-02-14','Black'),(2,'Blavity','Media','2014-07-17','Black');
SELECT COUNT(*) FROM startup WHERE industry = 'Tech' AND founder_race IN ('Black', 'Hispanic', 'Indigenous', 'Asian', 'Pacific Islander', 'Multiracial');
What is the average age of volunteers in the 'volunteer_program' table?
CREATE TABLE volunteer_program (id INT,name VARCHAR(50),age INT,location VARCHAR(30)); INSERT INTO volunteer_program (id,name,age,location) VALUES (1,'John Doe',25,'New York'),(2,'Jane Smith',32,'California'),(3,'Alice Johnson',22,'Texas');
SELECT AVG(age) FROM volunteer_program;
What is the percentage of the population that is fully vaccinated, broken down by age group?
CREATE TABLE Vaccination (ID INT,Age INT,Population INT,Vaccinated INT); INSERT INTO Vaccination (ID,Age,Population,Vaccinated) VALUES (1,18,1000,800),(2,19,1000,850),(3,20,1000,750);
SELECT Age, (SUM(Vaccinated) OVER (PARTITION BY Age)::FLOAT / SUM(Population) OVER (PARTITION BY Age)) * 100 as VaccinationPercentage FROM Vaccination;
Update the 'project_status' for 'Project 123' in the 'research_projects' table to 'completed'
CREATE TABLE research_projects (project_id INT PRIMARY KEY,project_name VARCHAR(50),project_status VARCHAR(50));
UPDATE research_projects SET project_status = 'completed' WHERE project_name = 'Project 123';
Delete all smart contracts for a specific user '0xabc...'.
CREATE TABLE smart_contracts (contract_address VARCHAR(64),user_address VARCHAR(64));
DELETE FROM smart_contracts WHERE user_address = '0xabc...';
How many donations were made by first-time donors in the year 2020?
CREATE TABLE donations (donor_id INT,donation_date DATE,donation_amount FLOAT); INSERT INTO donations (donor_id,donation_date,donation_amount) VALUES (1,'2020-01-01',50.00),(2,'2019-12-31',100.00),(3,'2020-05-15',25.00);
SELECT COUNT(*) FROM donations WHERE YEAR(donation_date) = 2020 AND donor_id NOT IN (SELECT donor_id FROM donations WHERE YEAR(donation_date) < 2020);
Which marine species have been observed in more than one region?
CREATE TABLE marine_species (id INT,species_name VARCHAR(50),common_name VARCHAR(50),region VARCHAR(20));INSERT INTO marine_species (id,species_name,common_name,region) VALUES (1,'Orcinus_orca','Killer Whale','Arctic');INSERT INTO marine_species (id,species_name,common_name,region) VALUES (2,'Balaenoptera_bonaerensis',...
SELECT species_name FROM marine_species GROUP BY species_name HAVING COUNT(DISTINCT region) > 1;
Delete all records in the 'Crops' table where the 'CropYield' is less than 20
CREATE TABLE Crops(CropID INT,CropName VARCHAR(50),CropYield INT); INSERT INTO Crops(CropID,CropName,CropYield) VALUES (1,'Corn',25),(2,'Soybean',30),(3,'Wheat',18);
DELETE FROM Crops WHERE CropYield < 20;
How many refugees were supported in each region?
CREATE TABLE Refugees (RefugeeID INT,Region VARCHAR(20)); INSERT INTO Refugees (RefugeeID,Region) VALUES (1,'Africa'),(2,'Asia'),(3,'Europe');
SELECT Region, COUNT(RefugeeID) as NumRefugees FROM Refugees GROUP BY Region;
Insert a new record in the sustainable_metrics table for brand 'EcoFriendlyBrand', metric 'WaterConsumption' and value 10
CREATE TABLE sustainable_metrics (brand VARCHAR(255) PRIMARY KEY,metric VARCHAR(255),value INT); INSERT INTO sustainable_metrics (brand,metric,value) VALUES ('AnotherBrand','CarbonFootprint',12),('BrandX','WaterConsumption',15);
INSERT INTO sustainable_metrics (brand, metric, value) VALUES ('EcoFriendlyBrand', 'WaterConsumption', 10);
What is the total capacity of containers for all vessels in the fleet_management table?
CREATE TABLE fleet_management (vessel_id INT,vessel_name VARCHAR(50),total_capacity INT); INSERT INTO fleet_management (vessel_id,vessel_name,total_capacity) VALUES (1,'Vessel_A',5000),(2,'Vessel_B',6000),(3,'Vessel_C',4000);
SELECT SUM(total_capacity) FROM fleet_management;
What is the total number of mobile and broadband subscribers for each sales region?
CREATE TABLE mobile_subscribers (region VARCHAR(50),subscriber_id INT); INSERT INTO mobile_subscribers VALUES ('Region A',100); INSERT INTO mobile_subscribers VALUES ('Region A',200); INSERT INTO mobile_subscribers VALUES ('Region B',300); INSERT INTO mobile_subscribers VALUES ('Region C',400); INSERT INTO broadband_su...
SELECT region, COUNT(mobile_subscribers.subscriber_id) + COUNT(broadband_subscribers.subscriber_id) as total_subscribers FROM mobile_subscribers FULL OUTER JOIN broadband_subscribers ON mobile_subscribers.region = broadband_subscribers.region GROUP BY region;
List the countries that had more than 5000 visitors in 2021.
CREATE TABLE CountryData (Country VARCHAR(20),Year INT,Visitors INT); INSERT INTO CountryData (Country,Year,Visitors) VALUES ('France',2021,6000),('Spain',2021,4000),('Germany',2021,7000),('France',2020,5000);
SELECT Country FROM CountryData WHERE Year = 2021 AND Visitors > 5000;
What is the average mental health score for students in grade 12?
CREATE TABLE students (id INT,name VARCHAR(255),grade INT,mental_health_score INT); INSERT INTO students (id,name,grade,mental_health_score) VALUES (1,'Jane Doe',12,80);
SELECT AVG(mental_health_score) FROM students WHERE grade = 12;
What are the average warehouse management costs for each warehouse in Q2 2022?
CREATE TABLE warehouse_costs (warehouse_id INT,warehouse_location VARCHAR(255),cost DECIMAL(10,2),quarter INT,year INT); INSERT INTO warehouse_costs (warehouse_id,warehouse_location,cost,quarter,year) VALUES (1,'NYC Warehouse',2500.00,2,2022),(2,'LA Warehouse',3000.00,2,2022),(3,'CHI Warehouse',2000.00,2,2022);
SELECT warehouse_location, AVG(cost) as avg_cost FROM warehouse_costs WHERE quarter = 2 AND year = 2022 GROUP BY warehouse_location;
Which marine protected areas in the Indian Ocean have an average depth greater than 500 meters?
CREATE TABLE marine_protected_areas (name VARCHAR(255),location VARCHAR(255),avg_depth FLOAT); INSERT INTO marine_protected_areas (name,location,avg_depth) VALUES ('MPA 1','Indian Ocean',700.0),('MPA 2','Atlantic Ocean',300.0);
SELECT name FROM marine_protected_areas WHERE location = 'Indian Ocean' AND avg_depth > 500;
What is the total number of labor rights violations reported each month, including months with no violations?
CREATE TABLE violations (id INT,location TEXT,type TEXT,date DATE); INSERT INTO violations (id,location,type,date) VALUES (1,'California','wage theft','2021-01-01'); CREATE TABLE months (id INT,month TEXT,year INT); INSERT INTO months (id,month,year) VALUES (1,'January',2021),(2,'February',2021);
SELECT m.month, m.year, COALESCE(SUM(v.id), 0) FROM months m LEFT JOIN violations v ON EXTRACT(MONTH FROM v.date) = m.id AND EXTRACT(YEAR FROM v.date) = m.year GROUP BY m.month, m.year;
What is the number of hospitals and clinics in each state?
CREATE TABLE states (state_abbr CHAR(2),state_name VARCHAR(50)); INSERT INTO states VALUES ('CA','California'),('NY','New York'),('TX','Texas'); CREATE TABLE hospitals (hospital_id INT,hospital_name VARCHAR(100),state_abbr CHAR(2)); INSERT INTO hospitals VALUES (1,'UCSF Medical Center','CA'),(2,'NY Presbyterian','NY'),...
SELECT s.state_name, COUNT(h.hospital_id) AS hospitals, COUNT(c.clinic_id) AS clinics FROM states s LEFT JOIN hospitals h ON s.state_abbr = h.state_abbr LEFT JOIN clinics c ON s.state_abbr = c.state_abbr GROUP BY s.state_name;
Find the average depth of the Arctic Ocean floor mapping project zones with pollution levels above the median.
CREATE TABLE arctic_zones (id INT,zone VARCHAR(255),depth INT,pollution_level INT); INSERT INTO arctic_zones VALUES (1,'Zone A',4000,30); INSERT INTO arctic_zones VALUES (2,'Zone B',5000,20); INSERT INTO arctic_zones VALUES (3,'Zone C',3500,45);
SELECT AVG(depth) FROM arctic_zones WHERE pollution_level > (SELECT AVG(pollution_level) FROM arctic_zones);
What is the average maintenance cost for each driver in the 'Tram' service in the last month?
CREATE TABLE DriverMaintenance (MaintenanceID INT,DriverID INT,MaintenanceCost DECIMAL(5,2),Service VARCHAR(50),MaintenanceDate DATE); INSERT INTO DriverMaintenance (MaintenanceID,DriverID,MaintenanceCost,Service,MaintenanceDate) VALUES (1,1,200.00,'Tram','2022-02-01'),(2,1,250.00,'Tram','2022-02-03'),(3,2,300.00,'Tram...
SELECT d.DriverName, AVG(dm.MaintenanceCost) as AvgMaintenanceCost FROM Drivers d JOIN DriverMaintenance dm ON d.DriverID = dm.DriverID WHERE d.Service = 'Tram' AND dm.MaintenanceDate >= DATEADD(month, -1, GETDATE()) GROUP BY d.DriverName;
Show the number of security incidents and their severity by month
CREATE TABLE incident_monthly (id INT,incident_date DATE,severity VARCHAR(10)); INSERT INTO incident_monthly (id,incident_date,severity) VALUES (1,'2022-01-01','Low'),(2,'2022-01-15','Medium'),(3,'2022-02-01','High'),(4,'2022-03-01','Critical'),(5,'2022-03-15','Low'),(6,'2022-04-01','Medium');
SELECT EXTRACT(MONTH FROM incident_date) as month, severity, COUNT(*) as incidents FROM incident_monthly GROUP BY month, severity;
List all co-owned properties and their corresponding city in the RealEstateCoOwnership schema.
CREATE TABLE RealEstateCoOwnership.Properties (id INT,city VARCHAR(50)); INSERT INTO RealEstateCoOwnership.Properties (id,city) VALUES (1,'San Francisco'),(2,'New York'); CREATE TABLE RealEstateCoOwnership.CoOwnership (property_id INT,coowner VARCHAR(50)); INSERT INTO RealEstateCoOwnership.CoOwnership (property_id,coow...
SELECT Properties.id, Properties.city, CoOwnership.coowner FROM RealEstateCoOwnership.Properties INNER JOIN RealEstateCoOwnership.CoOwnership ON Properties.id = CoOwnership.property_id;
How many community service hours were completed by offenders in each state?
CREATE TABLE offenders (id INT,name TEXT,state TEXT,community_service_hours INT); INSERT INTO offenders (id,name,state,community_service_hours) VALUES (1,'John Doe','Washington',50); INSERT INTO offenders (id,name,state,community_service_hours) VALUES (2,'Jane Smith','Oregon',75); INSERT INTO offenders (id,name,state,c...
SELECT state, SUM(community_service_hours) FROM offenders GROUP BY state
What is the average weekly wage for male workers in the 'Manufacturing' industry?
CREATE TABLE Employees (id INT,Gender TEXT,Department TEXT,WeeklyWage DECIMAL);
SELECT AVG(WeeklyWage) FROM Employees WHERE Gender = 'Male' AND Department = 'Manufacturing';
Delete records of products that have been discontinued in the past 3 years from the products table.
CREATE TABLE products (product_id INT PRIMARY KEY,product_name TEXT,discontinued_date DATE);
DELETE FROM products WHERE discontinued_date >= DATE(NOW()) - INTERVAL 3 YEAR;
SELECT MemberID, COUNT(*) as WorkoutCountLastMonth FROM Workouts WHERE DATE_TRUNC('month', Date) = DATE_TRUNC('month', CURRENT_DATE - INTERVAL '1 month') GROUP BY MemberID ORDER BY WorkoutCountLastMonth DESC;
CREATE TABLE Members (MemberID INT,Name VARCHAR(50),Age INT,Gender VARCHAR(10),City VARCHAR(50),State VARCHAR(20)); INSERT INTO Members (MemberID,Name,Age,Gender,City,State) VALUES (1011,'Ella Nguyen',33,'Female','Hanoi','Vietnam'); INSERT INTO Members (MemberID,Name,Age,Gender,City,State) VALUES (1012,'Alioune Diop',4...
SELECT MemberID, WorkoutType, DATE_TRUNC('hour', Date) as Hour, COUNT(*) as WorkoutCountPerHour FROM Workouts GROUP BY MemberID, WorkoutType, Hour ORDER BY Hour;
What is the healthcare access score for urban areas in Africa in 2018?
CREATE TABLE HealthcareAccess (Location VARCHAR(50),Continent VARCHAR(50),Year INT,Score FLOAT); INSERT INTO HealthcareAccess (Location,Continent,Year,Score) VALUES ('Rural','Africa',2018,65.2),('Urban','Africa',2018,80.5);
SELECT Score FROM HealthcareAccess WHERE Location = 'Urban' AND Continent = 'Africa' AND Year = 2018;
Who are the founders of AI companies in 'Asia' and when were they founded?
CREATE TABLE ai_companies (id INT PRIMARY KEY,name VARCHAR(50),year_founded INT,region VARCHAR(50)); INSERT INTO ai_companies (id,name,year_founded,region) VALUES (1,'AlphaAI',2010,'North America'); INSERT INTO ai_companies (id,name,year_founded,region) VALUES (2,'BetaTech',2015,'Europe'); INSERT INTO ai_companies (id,...
SELECT name, year_founded FROM ai_companies WHERE region = 'Asia';
List all cases that were opened more than 30 days ago, but have not yet been closed.
CREATE TABLE Cases (CaseID INT,CaseOpenDate DATETIME,CaseCloseDate DATETIME);
SELECT CaseID, CaseOpenDate, CaseCloseDate FROM Cases WHERE CaseOpenDate < DATE_SUB(CURDATE(), INTERVAL 30 DAY) AND CaseCloseDate IS NULL;
What is the total number of contracts negotiated by each contractor and their total cost?
CREATE TABLE ContractNegotiations (contract_id INT,contractor VARCHAR(50),contract_cost DECIMAL(10,2)); INSERT INTO ContractNegotiations (contract_id,contractor,contract_cost) VALUES (1,'ABC',1000000.00); INSERT INTO ContractNegotiations (contract_id,contractor,contract_cost) VALUES (2,'DEF',2000000.00);
SELECT contractor, COUNT(*) as total_contracts, SUM(contract_cost) as total_cost FROM ContractNegotiations GROUP BY contractor;
How many safety tests were conducted on autonomous vehicles in Q1 2021?
CREATE TABLE Safety_Tests_2 (Test_Quarter INT,Vehicle_Type VARCHAR(20)); INSERT INTO Safety_Tests_2 (Test_Quarter,Vehicle_Type) VALUES (1,'Autonomous'),(1,'Gasoline'),(2,'Autonomous'),(2,'Gasoline'),(3,'Autonomous'),(3,'Gasoline'),(4,'Autonomous'),(4,'Gasoline');
SELECT COUNT(*) FROM Safety_Tests_2 WHERE Vehicle_Type = 'Autonomous' AND Test_Quarter = 1;
Delete records in the 'equipment_rentals' table that have rental_dates older than 2 years
CREATE TABLE equipment_rentals (id INT,equipment_id INT,rental_dates DATE);
DELETE FROM equipment_rentals WHERE rental_dates < DATE_SUB(CURDATE(), INTERVAL 2 YEAR);
What is the total number of cases in each category, ordered by the total count?
CREATE TABLE cases (id INT,category VARCHAR(255),description TEXT,created_at TIMESTAMP); INSERT INTO cases (id,category,description,created_at) VALUES (1,'Civil','Case description 1','2021-01-01 10:00:00'),(2,'Criminal','Case description 2','2021-01-02 10:00:00'),(3,'Civil','Case description 3','2021-01-03 10:00:00');
SELECT category, COUNT(*) as total_cases FROM cases GROUP BY category ORDER BY total_cases DESC;
What was the total humanitarian assistance provided in 2009?
CREATE TABLE HumanitarianAssistance (Country VARCHAR(50),Year INT,Amount FLOAT); INSERT INTO HumanitarianAssistance (Country,Year,Amount) VALUES ('Country 1',2009,1000000),('Country 2',2009,1100000);
SELECT SUM(Amount) FROM HumanitarianAssistance WHERE Year = 2009;
Who are the top 3 donors in terms of total donation amount in 2020, and how much did they donate in total?
CREATE TABLE donors (id INT,name TEXT,donation_amount DECIMAL(10,2),donation_date DATE); INSERT INTO donors (id,name,donation_amount,donation_date) VALUES (1,'John Doe',1000.00,'2020-01-05'); INSERT INTO donors (id,name,donation_amount,donation_date) VALUES (2,'Jane Smith',1500.00,'2020-03-12');
SELECT name, SUM(donation_amount) AS total_donation FROM donors WHERE donation_date BETWEEN '2020-01-01' AND '2020-12-31' GROUP BY name ORDER BY total_donation DESC LIMIT 3;
How many hybrid vehicles were sold in Washington in Q4 of 2021?
CREATE TABLE HybridSales (Id INT,Vehicle VARCHAR(255),ModelYear INT,State VARCHAR(255),QuantitySold INT,Quarter INT); INSERT INTO HybridSales (Id,Vehicle,ModelYear,State,QuantitySold,Quarter) VALUES (1,'Toyota Prius',2021,'Washington',3000,4),(2,'Honda Insight',2021,'Washington',1500,4),(3,'Hyundai Ioniq',2021,'Washing...
SELECT SUM(QuantitySold) FROM HybridSales WHERE ModelYear = 2021 AND State = 'Washington' AND Quarter = 4 AND Vehicle LIKE '%Hybrid%'
What is the maximum size of a marine protected area (in square kilometers) in the Indian Ocean?
CREATE TABLE marine_protected_areas (id INT,name VARCHAR(255),area_size FLOAT,region VARCHAR(255)); INSERT INTO marine_protected_areas (id,name,area_size,region) VALUES (1,'Chagos Marine Reserve',640000,'Indian');
SELECT MAX(area_size) FROM marine_protected_areas WHERE region = 'Indian';
What is the minimum budget for any education program?
CREATE TABLE Education_Programs AS SELECT 'Young_Protectors' AS program,11000 AS budget UNION SELECT 'Green_Champions',13000;
SELECT MIN(budget) FROM Education_Programs;
What is the total number of streams for all songs in the R&B genre on the music streaming platform in Germany?
CREATE TABLE music_platform (id INT,genre VARCHAR(50),streams INT,country VARCHAR(50));
SELECT SUM(streams) as total_streams FROM music_platform WHERE genre = 'R&B' AND country = 'Germany';
Who is the head of the Canadian Security Intelligence Service and what is their background?
CREATE TABLE intelligence_agency_leaders (id INT,agency_name VARCHAR(255),leader_name VARCHAR(255),leader_background TEXT); INSERT INTO intelligence_agency_leaders (id,agency_name,leader_name,leader_background) VALUES (1,'CSIS','David Vigneault','David Vigneault has been the Director of the Canadian Security Intelligen...
SELECT leader_name, leader_background FROM intelligence_agency_leaders WHERE agency_name = 'CSIS';
How many wells were drilled each year in the last 5 years?
CREATE TABLE wells (well_id INT,drill_date DATE); INSERT INTO wells (well_id,drill_date) VALUES (1,'2018-01-01'),(2,'2019-01-01'),(3,'2020-01-01'),(4,'2021-01-01'),(5,'2022-01-01');
SELECT YEAR(drill_date) AS Year, COUNT(*) AS Number_of_Wells FROM wells WHERE drill_date >= DATEADD(year, -5, GETDATE()) GROUP BY YEAR(drill_date) ORDER BY Year
What is the difference in transaction amount between consecutive transactions for each customer?
CREATE TABLE transactions (transaction_date DATE,customer_id INT,transaction_amt DECIMAL(10,2)); INSERT INTO transactions (transaction_date,customer_id,transaction_amt) VALUES ('2022-01-01',1,200.00),('2022-01-02',1,250.00),('2022-01-03',1,300.00);
SELECT transaction_date, customer_id, transaction_amt, LAG(transaction_amt, 1) OVER (PARTITION BY customer_id ORDER BY transaction_date) AS previous_transaction_amt, transaction_amt - LAG(transaction_amt, 1) OVER (PARTITION BY customer_id ORDER BY transaction_date) AS transaction_diff FROM transactions;
Update the 'reefs' table to set the conservation_status to 'critical' for the reef with reef_id '10'.
CREATE TABLE reefs (reef_id INT,reef_name TEXT,temperature FLOAT,depth FLOAT,conservation_status TEXT);
UPDATE reefs SET conservation_status = 'critical' WHERE reef_id = 10;
What are the total sales of eco-friendly clothing items in each region?
CREATE TABLE Sales (SaleID INT,Item TEXT,Region TEXT,IsEcoFriendly BOOLEAN); INSERT INTO Sales (SaleID,Item,Region,IsEcoFriendly) VALUES (1,'T-Shirt','North',TRUE),(2,'Pants','South',FALSE),(3,'Jacket','East',TRUE),(4,'Hat','West',FALSE);
SELECT Region, SUM(TotalSales) FROM (SELECT Region, Item, IsEcoFriendly, COUNT(*) AS TotalSales FROM Sales GROUP BY Region, Item, IsEcoFriendly) AS Subquery WHERE IsEcoFriendly = TRUE GROUP BY Region;
Show the number of posts made by users from the Middle East, grouped by day of the week.
CREATE TABLE posts (id INT,user_id INT,post_date DATE); INSERT INTO posts (id,user_id,post_date) VALUES (1,1,'2021-01-01'),(2,2,'2021-01-02'),(3,3,'2021-01-03'); CREATE TABLE users (id INT,country VARCHAR(50)); INSERT INTO users (id,country) VALUES (1,'Iran'),(2,'Saudi Arabia'),(3,'Turkey');
SELECT DATE_FORMAT(post_date, '%W') as day_of_week, COUNT(*) as post_count FROM posts JOIN users ON posts.user_id = users.id WHERE users.country IN ('Iran', 'Saudi Arabia', 'Turkey') GROUP BY day_of_week;
On which dates did Texas have a drought impact greater than 0.7?
CREATE TABLE DroughtImpact (Id INT,Location VARCHAR(50),Impact DECIMAL(5,2),Date DATE); INSERT INTO DroughtImpact (Id,Location,Impact,Date) VALUES (1,'Texas',0.8,'2021-06-15'); INSERT INTO DroughtImpact (Id,Location,Impact,Date) VALUES (2,'Texas',0.6,'2021-07-01');
SELECT Date, AVG(Impact) FROM DroughtImpact WHERE Location = 'Texas' GROUP BY Date HAVING AVG(Impact) > 0.7;
Update the nitrogen level for crop type 'wheat' to 120 in the last 60 days.
CREATE TABLE crop_nutrient_levels (crop_type VARCHAR(255),nutrient_name VARCHAR(255),level INT,record_date DATE); INSERT INTO crop_nutrient_levels (crop_type,nutrient_name,level,record_date) VALUES ('corn','nitrogen',100,'2022-02-01'),('soybeans','nitrogen',110,'2022-02-02'),('corn','nitrogen',95,'2022-02-03'),('soybea...
UPDATE crop_nutrient_levels SET level = 120 WHERE crop_type = 'wheat' AND record_date >= DATE_SUB(CURDATE(), INTERVAL 60 DAY);
What is the minimum number of electric cars in the state of California?
CREATE TABLE if not exists car_share (id INT,state VARCHAR(20),car_type VARCHAR(20),quantity INT);INSERT INTO car_share (id,state,car_type,quantity) VALUES (1,'California','electric_car',1000),(2,'California','hybrid_car',800),(3,'Oregon','electric_car',600),(4,'Oregon','hybrid_car',500);
SELECT MIN(quantity) FROM car_share WHERE state = 'California' AND car_type = 'electric_car';
Update the name of the product with id 3 to 'Vegan Cheese'
CREATE TABLE products (id INT PRIMARY KEY,name VARCHAR(100),category VARCHAR(50),price DECIMAL(5,2));
UPDATE products SET name = 'Vegan Cheese' WHERE id = 3;
What is the maximum duration of space missions conducted by 'StarCorp'?
CREATE TABLE SpaceMissions (id INT,name VARCHAR(50),company VARCHAR(50),duration INT); INSERT INTO SpaceMissions (id,name,company,duration) VALUES (1,'Apollo 11','StarCorp',195),(2,'Apollo 13','StarCorp',142),(3,'Apollo 17','StarCorp',301);
SELECT MAX(duration) FROM SpaceMissions WHERE company = 'StarCorp';
Find the names of TV shows that have never been in the Top 10 most-watched list for any given year.
CREATE TABLE TV_Shows (show_id INT PRIMARY KEY,name VARCHAR(100),genre VARCHAR(50)); CREATE TABLE Ratings (year INT,show_id INT,rank INT,PRIMARY KEY (year,show_id)); INSERT INTO TV_Shows (show_id,name,genre) VALUES (1,'The Crown','Drama'),(2,'Stranger Things','Sci-fi'); INSERT INTO Ratings (year,show_id,rank) VALUES (2...
SELECT name FROM TV_Shows WHERE show_id NOT IN (SELECT show_id FROM Ratings WHERE rank <= 10);
Count the number of employees in each department, excluding any managers
CREATE TABLE employee_roles(emp_id INT,dept_id INT,role_id INT); INSERT INTO employee_roles VALUES (1,1,1),(2,1,2),(3,2,1),(4,2,2),(5,3,1);
SELECT d.dept_name, COUNT(e.emp_id) as num_employees FROM departments d JOIN employee_roles e ON d.dept_id = e.dept_id WHERE e.role_id != 1 GROUP BY d.dept_name;
Which consumers prefer 'cruelty-free' products in 'France'?
CREATE TABLE consumer_preferences (consumer_id INT,country VARCHAR(50),favorite_product VARCHAR(100),is_cruelty_free BOOLEAN); INSERT INTO consumer_preferences (consumer_id,country,favorite_product,is_cruelty_free) VALUES (1,'United States','Nourishing Face Cream',true),(2,'France','Hydrating Body Lotion',false);
SELECT consumer_id FROM consumer_preferences WHERE country = 'France' AND is_cruelty_free = true;
What is the average salinity of the ocean in each hemisphere?
CREATE TABLE ocean_salinity (id INT,year INT,hemisphere VARCHAR(50),avg_salinity FLOAT); INSERT INTO ocean_salinity (id,year,hemisphere,avg_salinity) VALUES (1,2020,'Northern Hemisphere',35); INSERT INTO ocean_salinity (id,year,hemisphere,avg_salinity) VALUES (2,2020,'Southern Hemisphere',34.7);
SELECT hemisphere, AVG(avg_salinity) FROM ocean_salinity GROUP BY hemisphere;
Remove all vehicle maintenance records for electric buses.
CREATE TABLE vehicles (vehicle_id INT,vehicle_type TEXT); INSERT INTO vehicles (vehicle_id,vehicle_type) VALUES (1,'Tram'),(2,'Bus'),(3,'Train'),(4,'Electric Bus'); CREATE TABLE maintenance (maintenance_id INT,vehicle_id INT,maintenance_date DATE); INSERT INTO maintenance (maintenance_id,vehicle_id,maintenance_date) VA...
DELETE FROM maintenance WHERE vehicle_id IN (SELECT vehicle_id FROM vehicles WHERE vehicle_type = 'Electric Bus');
How many hours did the vessel 'Vessel1' spend near the coast of Canada?
CREATE TABLE vessel_positions (id INT,vessel_id INT,timestamp TIMESTAMP,longitude FLOAT,latitude FLOAT); INSERT INTO vessel_positions (id,vessel_id,timestamp,longitude,latitude) VALUES (1,1,'2021-03-01 12:34:56',-66.13374,43.64831); INSERT INTO vessel_positions (id,vessel_id,timestamp,longitude,latitude) VALUES (2,1,'2...
SELECT TIMESTAMPDIFF(HOUR, MIN(timestamp), MAX(timestamp)) FROM vessel_positions WHERE vessel_id = 1 AND longitude BETWEEN -141.00024 AND -52.63551;
What is the maximum salary in the 'management' department?
CREATE TABLE employees (id INT,department VARCHAR(20),salary DECIMAL(10,2)); INSERT INTO employees (id,department,salary) VALUES (1,'management',75000.00),(2,'mining',60000.00),(3,'geology',65000.00);
SELECT MAX(salary) FROM employees WHERE department = 'management';
What is the average salary of employees in the 'sales' department?
CREATE TABLE employees (id INT,name VARCHAR(50),department VARCHAR(20),salary DECIMAL(10,2)); INSERT INTO employees (id,name,department,salary) VALUES (1,'John Doe','manufacturing',50000.00),(2,'Jane Smith','engineering',60000.00),(3,'Alice Johnson','HR',55000.00),(4,'Bob Brown','quality control',52000.00),(5,'Charlie ...
SELECT AVG(salary) FROM employees WHERE department = 'sales';
What is the total CO2 emission from gold and copper mining operations in Peru and Mexico?
CREATE TABLE mining_operations (id INT,location VARCHAR(50),operation_type VARCHAR(50),monthly_co2_emission INT); INSERT INTO mining_operations (id,location,operation_type,monthly_co2_emission) VALUES (1,'Peru','Gold',10000),(2,'Mexico','Gold',15000),(3,'Chile','Copper',20000);
SELECT SUM(CASE WHEN operation_type IN ('Gold', 'Copper') AND location IN ('Peru', 'Mexico') THEN monthly_co2_emission ELSE 0 END) as total_emission FROM mining_operations;
What is the total number of public health policy analyses conducted for indigenous communities, grouped by location?
CREATE TABLE policy_analyses_2 (id INT,community TEXT,location TEXT,analyses_count INT); INSERT INTO policy_analyses_2 (id,community,location,analyses_count) VALUES (1,'Indigenous A','urban',3),(2,'Indigenous B','rural',5),(3,'Indigenous A','urban',2);
SELECT location, SUM(analyses_count) FROM policy_analyses_2 WHERE community LIKE '%Indigenous%' GROUP BY location;
What was the average monthly sales revenue for each store location in Canada in 2020?
CREATE TABLE sales (store_location VARCHAR(50),sale_date DATE,revenue DECIMAL(10,2));
SELECT store_location, AVG(revenue) as avg_monthly_revenue FROM sales WHERE country = 'Canada' AND sale_date BETWEEN '2020-01-01' AND '2020-12-31' GROUP BY store_location;
What is the total number of patients served by community health workers?
CREATE TABLE worker_patient_data_total (worker_id INT,patients_served INT); INSERT INTO worker_patient_data_total (worker_id,patients_served) VALUES (1,50); INSERT INTO worker_patient_data_total (worker_id,patients_served) VALUES (2,75);
SELECT SUM(patients_served) FROM worker_patient_data_total;
How many hospitals in New York have more than 500 beds?
CREATE TABLE hospital (hospital_id INT,hospital_name TEXT,state TEXT,num_of_beds INT,has_maternity_ward BOOLEAN); INSERT INTO hospital (hospital_id,hospital_name,state,num_of_beds,has_maternity_ward) VALUES (1,'UCLA Medical Center','California',500,true); INSERT INTO hospital (hospital_id,hospital_name,state,num_of_bed...
SELECT COUNT(*) FROM hospital WHERE state = 'New York' AND num_of_beds > 500;
What is the total CO2 emission of the mining sector in the state of Texas in the last 5 years?
CREATE TABLE co2_emissions (id INT,company TEXT,location TEXT,timestamp TIMESTAMP,co2_emission FLOAT); INSERT INTO co2_emissions (id,company,location,timestamp,co2_emission) VALUES (1,'Texas Mining Inc','Texas','2018-01-01 12:00:00',1200);
SELECT SUM(co2_emission) FROM co2_emissions WHERE location = 'Texas' AND EXTRACT(YEAR FROM timestamp) >= EXTRACT(YEAR FROM CURRENT_DATE) - 5;
Update animal count in 'conservation_program' for Panda
CREATE TABLE conservation_program (id INT PRIMARY KEY,animal_name VARCHAR,num_animals INT); INSERT INTO conservation_program (id,animal_name,num_animals) VALUES (1,'Tiger',300),(2,'Panda',150),(3,'Rhino',70),(4,'Elephant',450);
UPDATE conservation_program SET num_animals = 200 WHERE animal_name = 'Panda';
What is the total capacity of vessels in the vessels table that were built before 2010?
CREATE TABLE vessels (id INT,name VARCHAR(255),country VARCHAR(255),capacity INT,year_built INT); INSERT INTO vessels (id,name,country,capacity,year_built) VALUES (1,'Vessel1','China',10000,2005),(2,'Vessel2','Japan',12000,2008),(3,'Vessel3','South Korea',8000,2012);
SELECT SUM(capacity) as total_capacity_before_2010 FROM vessels WHERE year_built < 2010;
Delete all environmental violations that occurred before 2010 and provide a summary.
CREATE TABLE EnvironmentalViolations (ViolationID INT,ViolationDate DATE,Description VARCHAR(255),FineAmount DECIMAL(10,2),MineID INT);
WITH pre_2010 AS (DELETE FROM EnvironmentalViolations WHERE ViolationDate < '2010-01-01' RETURNING *) SELECT COUNT(*) as ViolationsDeleted FROM pre_2010;
What is the average temperature in the Atlantic Ocean?
CREATE TABLE ocean_temperatures (ocean TEXT,temperature FLOAT);
SELECT AVG(temperature) FROM ocean_temperatures WHERE ocean = 'Atlantic Ocean';