instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
What is the minimum range of electric vehicles in the 'EVSpecs' database produced by Nissan?
CREATE TABLE EVSpecs (Id INT,Make VARCHAR(50),Model VARCHAR(50),Range FLOAT);
SELECT MIN(Range) FROM EVSpecs WHERE Make = 'Nissan';
How many vegan items are there in the inventory?
CREATE TABLE inventory (item_id INT,item_name TEXT,is_vegan BOOLEAN); INSERT INTO inventory (item_id,item_name,is_vegan) VALUES (1,'Hamburger',false),(2,'Veggie Pizza',true),(3,'Chicken Sandwich',false);
SELECT COUNT(*) FROM inventory WHERE is_vegan = true;
List all airports with a runway length greater than 3000 meters
CREATE TABLE Airports (airport_id int,airport_name varchar(255),runway_length decimal(10,2),location varchar(255));
SELECT airport_id, airport_name, runway_length, location FROM Airports WHERE runway_length > 3000;
What is the earliest therapy session date?
CREATE TABLE therapy_sessions (id INT,patient_id INT,session_date DATE);
SELECT MIN(session_date) FROM therapy_sessions;
How many clients have opened a new account in the last month?
CREATE TABLE clients (id INT,last_account_opening DATE); INSERT INTO clients (id,last_account_opening) VALUES (1,'2022-04-15'),(2,'2022-03-01'),(3,'2022-05-05');
SELECT COUNT(*) FROM clients WHERE last_account_opening BETWEEN DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH) AND CURRENT_DATE;
Which brands have discontinued the most products in the last year?
CREATE TABLE Discontinued (Brand VARCHAR(50),Product VARCHAR(50),Discontinued_Date DATE); INSERT INTO Discontinued (Brand,Product,Discontinued_Date) VALUES ('BrandA','Product1','2022-01-01'),('BrandA','Product2','2022-02-01'),('BrandB','Product3','2022-03-01');
SELECT Brand, COUNT(Product) FROM Discontinued WHERE Discontinued_Date >= DATEADD(year, -1, GETDATE()) GROUP BY Brand ORDER BY COUNT(Product) DESC;
What is the average CO2 emissions reduction (in metric tons) for each carbon offset project?
CREATE TABLE carbon_offset_projects (id INT,project_name VARCHAR(255),co2_emissions_reduction FLOAT);
SELECT AVG(co2_emissions_reduction) FROM carbon_offset_projects;
Count the number of vessels that arrived in a Canadian port with cargo in the last month.
CREATE TABLE Vessels (VesselID INT,VesselName TEXT); CREATE TABLE Ports (PortID INT,PortName TEXT,Country TEXT); CREATE TABLE Cargo (VesselID INT,PortID INT,ArrivalDate DATE); INSERT INTO Ports (PortID,PortName,Country) VALUES (1,'Vancouver','Canada'),(2,'Montreal','Canada'); INSERT INTO Vessels (VesselID,VesselName) VALUES (1,'Sea Tiger'),(2,'Ocean Wave'),(3,'River Queen'),(4,'Blue Whale'); INSERT INTO Cargo (VesselID,PortID,ArrivalDate) VALUES (1,1,'2022-07-01'),(1,2,'2022-07-15'),(2,1,'2022-07-20'),(3,2,'2022-07-25'),(4,1,'2022-07-30');
SELECT COUNT(*) FROM Cargo INNER JOIN Vessels ON Cargo.VesselID = Vessels.VesselID INNER JOIN Ports ON Cargo.PortID = Ports.PortID WHERE ArrivalDate >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH) AND Country = 'Canada';
What is the average temperature in each Arctic region for the last 5 years?
CREATE TABLE temperature_data (id INT,arctic_region VARCHAR(255),date DATE,temperature FLOAT); INSERT INTO temperature_data (id,arctic_region,date,temperature) VALUES (1,'North Pole','2018-01-01',-25.0),(2,'Canada','2018-01-01',-20.0);
SELECT arctic_region, AVG(temperature) FROM temperature_data WHERE date >= DATEADD(year, -5, CURRENT_DATE) GROUP BY arctic_region;
Which ocean has the greatest number of marine mammal species?
CREATE TABLE marine_mammals (name VARCHAR(255),species_count INT,ocean VARCHAR(255)); INSERT INTO marine_mammals (name,species_count,ocean) VALUES ('Dolphins',42,'Pacific');
SELECT ocean, COUNT(*) as total FROM marine_mammals GROUP BY ocean ORDER BY total DESC LIMIT 1;
Find the names of refugees who received support from organizations based in France or Germany?
CREATE TABLE refugees (id INT,name TEXT,country TEXT); CREATE TABLE support (id INT,refugee_id INT,organization_country TEXT); INSERT INTO refugees (id,name,country) VALUES (1,'RefugeeA','Syria'),(2,'RefugeeB','Iraq'); INSERT INTO support (id,refugee_id,organization_country) VALUES (1,1,'France'),(2,1,'Germany'),(3,2,'France');
SELECT DISTINCT r.name FROM refugees r JOIN support s ON r.id = s.refugee_id WHERE s.organization_country IN ('France', 'Germany');
Which Green building certifications were issued in the European Union?
CREATE TABLE green_buildings (building_id INT,building_name TEXT,country TEXT,certification TEXT); INSERT INTO green_buildings (building_id,building_name,country,certification) VALUES (1,'Green Building 1','Germany','LEED'),(2,'Green Building 2','France','BREEAM');
SELECT country, certification FROM green_buildings WHERE country LIKE 'Europe%';
How many network infrastructure investments were made in a specific country in the last year?
CREATE TABLE network_investments (investment_id INT,investment_date DATE,country VARCHAR(50),investment_amount INT);
SELECT country, COUNT(investment_id) FROM network_investments WHERE investment_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR) GROUP BY country;
What is the number of COVID-19 cases per 100,000 people?
CREATE TABLE cases_population (county VARCHAR(100),cases INT,population INT);
SELECT county, 100000.0*cases/population FROM cases_population;
Identify countries with a marine research station in the Arctic Ocean.
CREATE TABLE countries (country_name VARCHAR(50),has_arctic_station BOOLEAN); INSERT INTO countries (country_name,has_arctic_station) VALUES ('Canada',true),('Brazil',false);
SELECT country_name FROM countries WHERE has_arctic_station = true;
Increase the budget of all marine research projects led by the Ocean Exploration Trust by 15%
CREATE TABLE marine_research_projects (id INT,name VARCHAR(255),location VARCHAR(255),budget DECIMAL(10,2),organization VARCHAR(255)); INSERT INTO marine_research_projects (id,name,location,budget,organization) VALUES (1,'Coral Reef Study','Indian Ocean',250000.00,'Ocean Exploration Trust'),(2,'Ocean Current Analysis','Atlantic Ocean',350000.00,'National Oceanic and Atmospheric Administration');
UPDATE marine_research_projects SET budget = budget * 1.15 WHERE organization = 'Ocean Exploration Trust';
What is the average cargo weight of vessels that had accidents and were registered in Panama in 2018?
CREATE TABLE Vessels (ID INT,Name TEXT,Cargo_Weight INT,Accidents INT,Registered_Country TEXT,Year INT);CREATE VIEW Panama_Registered_Vessels AS SELECT * FROM Vessels WHERE Registered_Country = 'Panama';
SELECT AVG(Cargo_Weight) FROM Panama_Registered_Vessels WHERE Accidents > 0 AND Year = 2018;
Who is the farmer in 'Toronto' with the lowest yield of carrots?
CREATE TABLE urban_farmers (id INT,name VARCHAR(50),location VARCHAR(50),crops VARCHAR(50)); CREATE TABLE crops (id INT,name VARCHAR(50),yield INT); INSERT INTO urban_farmers VALUES (1,'Ella Evans','Toronto','Carrots'); INSERT INTO crops VALUES (1,'Carrots',100);
SELECT name FROM urban_farmers INNER JOIN crops ON urban_farmers.crops = crops.name WHERE crops.name = 'Carrots' AND crops.yield = (SELECT MIN(yield) FROM crops WHERE name = 'Carrots') AND urban_farmers.location = 'Toronto';
Which cities had the most diverse visitor demographics in 2018?
CREATE TABLE CityDemographics (id INT,city VARCHAR(20),year INT,diversity_score FLOAT); INSERT INTO CityDemographics (id,city,year,diversity_score) VALUES (1,'Paris',2019,0.75),(2,'London',2018,0.82),(3,'New York',2018,0.88),(4,'Tokyo',2018,0.70);
SELECT city, diversity_score FROM CityDemographics WHERE year = 2018 ORDER BY diversity_score DESC LIMIT 1;
What is the average calorie intake for meals served in 'sustainable_restaurants' table, grouped by cuisine type?
CREATE TABLE sustainable_restaurants (restaurant_id INT,cuisine VARCHAR(255),avg_calories DECIMAL(5,2));
SELECT cuisine, AVG(avg_calories) FROM sustainable_restaurants GROUP BY cuisine;
Calculate the total budget for all programs in the 'wildlife_protection' department
CREATE TABLE program_info (program_id INT,program_name VARCHAR(20),department VARCHAR(20)); INSERT INTO program_info (program_id,program_name,department) VALUES (1,'habitat_restoration','wildlife_protection'),(2,'community_education','public_awareness'),(3,'species_conservation','wildlife_protection'); CREATE TABLE program_budget (program_id INT,budget INT); INSERT INTO program_budget (program_id,budget) VALUES (1,5000),(2,7000),(3,8000);
SELECT SUM(program_budget.budget) FROM program_budget INNER JOIN program_info ON program_budget.program_id = program_info.program_id WHERE program_info.department = 'wildlife_protection';
Insert a new record for a completed project in the Projects table.
CREATE TABLE Projects (ProjectID INT,ProjectName VARCHAR(50),StartDate DATE,EndDate DATE,EmployeeID INT,FOREIGN KEY (EmployeeID) REFERENCES Employees(EmployeeID));
INSERT INTO Projects (ProjectID, ProjectName, StartDate, EndDate, EmployeeID) VALUES (2, 'Eco-Friendly Renovation', '2021-10-01', '2022-03-31', 3);
What's the total amount of funds raised by NGOs located in Africa and Asia?
CREATE TABLE ngo_funds (id INT,ngo_name VARCHAR(50),location VARCHAR(20),funds_raised DECIMAL(10,2)); INSERT INTO ngo_funds (id,ngo_name,location,funds_raised) VALUES (1,'Save the Children','Africa',50000),(2,'CARE International','Asia',75000),(3,'World Vision','Africa',60000),(4,'Plan International','Asia',80000);
SELECT SUM(funds_raised) FROM ngo_funds WHERE location IN ('Africa', 'Asia');
Find the average 'Safety_Rating' in the 'Workplace_Safety' table for the 'Construction' industry.
CREATE TABLE Workplace_Safety (id INT,industry VARCHAR(20),safety_rating FLOAT); INSERT INTO Workplace_Safety (id,industry,safety_rating) VALUES (1,'Construction',4.2),(2,'Manufacturing',3.9),(3,'Construction',4.5);
SELECT AVG(safety_rating) FROM Workplace_Safety WHERE industry = 'Construction';
What percentage of articles published in 2021 by "The Guardian" are about "Politics"?
CREATE TABLE articles (id INT,title TEXT,content TEXT,publication_date DATE,newspaper TEXT); CREATE TABLE categories (id INT,article_id INT,category TEXT);
SELECT (COUNT(CASE WHEN c.category = 'Politics' THEN 1 END) * 100.0 / COUNT(*)) AS politics_percentage FROM articles a INNER JOIN categories c ON a.id = c.article_id WHERE a.publication_date BETWEEN '2021-01-01' AND '2021-12-31' AND a.newspaper = 'The Guardian';
Insert new records into the 'ChargingStations' table for 2 new electric charging stations
CREATE TABLE ChargingStations (station_id INT,location VARCHAR(30),PRIMARY KEY (station_id));
INSERT INTO ChargingStations (station_id, location) VALUES (1001, 'Oakland Ave, Oakland'), (1002, 'Market St, San Francisco');
What are the top 5 most common vulnerabilities by type across all software?
CREATE TABLE vulnerabilities (id INT,software_id INT,type VARCHAR(255)); INSERT INTO vulnerabilities (id,software_id,type) VALUES (1,1,'Buffer Overflow'),(2,1,'SQL Injection'),(3,2,'Cross-Site Scripting'),(4,2,'Buffer Overflow'),(5,3,'SQL Injection');
SELECT type, COUNT(*) as count FROM vulnerabilities GROUP BY type ORDER BY count DESC LIMIT 5;
Identify the number of unique research grants received by female faculty members.
CREATE TABLE faculty (id INT,name VARCHAR(50),gender VARCHAR(10),department VARCHAR(20)); CREATE TABLE research_grants (faculty_id INT,grant_amount DECIMAL(10,2)); INSERT INTO faculty (id,name,gender,department) VALUES (1,'Alex Brown','Male','Computer Science'),(2,'Rachel Green','Female','Biology'),(3,'Jessica White','Female','Chemistry'); INSERT INTO research_grants (faculty_id,grant_amount) VALUES (1,25000.00),(1,30000.00),(3,40000.00);
SELECT COUNT(DISTINCT grant_amount) as num_unique_grants FROM research_grants rg JOIN faculty f ON rg.faculty_id = f.id WHERE f.gender = 'Female';
List menu items and their categories that are not available in any order.
CREATE TABLE inventory (menu_id INT,inventory_quantity INT); CREATE VIEW menu_categories AS SELECT menu_id,'Non-veg' AS category FROM menus WHERE menu_type = 'Non-veg' UNION SELECT menu_id,'Veg' FROM menus WHERE menu_type = 'Veg'; CREATE TABLE orders (order_id INT,menu_id INT);
SELECT m.menu_name, c.category FROM inventory i RIGHT JOIN menus m ON i.menu_id = m.menu_id JOIN menu_categories c ON m.menu_id = c.menu_id LEFT JOIN orders o ON m.menu_id = o.menu_id WHERE i.inventory_quantity > 0 AND o.order_id IS NULL;
What is the average population of Arctic communities?
CREATE TABLE community (id INT PRIMARY KEY,name VARCHAR(255),location VARCHAR(255),population INT); INSERT INTO community (id,name,location,population) VALUES (1,'Inuit','Arctic',5000); INSERT INTO community (id,name,location,population) VALUES (2,'Samí','Arctic',80000); INSERT INTO community (id,name,location,population) VALUES (3,'Aleut','Alaska',2500);
SELECT AVG(population) FROM community WHERE location = 'Arctic';
Which water conservation initiatives were implemented before 2018?
CREATE TABLE water_conservation_initiatives (id INT,name VARCHAR(50),year INT); INSERT INTO water_conservation_initiatives (id,name,year) VALUES (1,'Initiative A',2015); INSERT INTO water_conservation_initiatives (id,name,year) VALUES (2,'Initiative B',2017);
SELECT w.name FROM water_conservation_initiatives w WHERE w.year < 2018;
What is the maximum and minimum installed capacity of wind farms in the country of Spain, and what are their names?
CREATE TABLE wind_farms (id INT,name VARCHAR(255),country VARCHAR(255),capacity FLOAT,completion_date DATE);
SELECT name, MAX(capacity) AS max_capacity, MIN(capacity) AS min_capacity FROM wind_farms WHERE country = 'Spain';
What is the maximum temperature (in Fahrenheit) recorded by the IoT sensors in "Field2" in the morning (before 12:00 PM) on any day in 2021?
CREATE TABLE Field2_Temp (sensor_id INT,sensor_reading TIME,temp FLOAT); INSERT INTO Field2_Temp (sensor_id,sensor_reading,temp) VALUES (1,'06:00:00',75.2),(2,'11:00:00',80.5),(1,'09:00:00',78.9);
SELECT MAX(temp) FROM Field2_Temp WHERE sensor_reading < '12:00:00' AND YEAR(sensor_reading) = 2021;
Insert a new artist 'Maria Fernandes' in the 'Artists' table
CREATE TABLE Artists (ArtistID INT PRIMARY KEY,ArtistName VARCHAR(100));
INSERT INTO Artists (ArtistID, ArtistName) VALUES (101, 'Maria Fernandes');
Calculate the percentage of garments in each size range, for each clothing category, sold in the United States.
CREATE TABLE GarmentSales (SaleID INT,GarmentID INT,Size VARCHAR(255),Category VARCHAR(255),Country VARCHAR(255)); INSERT INTO GarmentSales (SaleID,GarmentID,Size,Category,Country) VALUES (1,1,'Small','Tops','USA');
SELECT Category, Size, COUNT(*) * 100.0 / SUM(COUNT(*)) OVER (PARTITION BY Category) as Percentage FROM GarmentSales WHERE Country = 'USA' GROUP BY Category, Size;
What was the total cost of sustainable building projects in the city of Atlanta in 2020?
CREATE TABLE Sustainable_Projects (id INT,project_cost FLOAT,year INT,city VARCHAR(20)); INSERT INTO Sustainable_Projects (id,project_cost,year,city) VALUES (1,6000000,2020,'Atlanta');
SELECT SUM(project_cost) FROM Sustainable_Projects WHERE year = 2020 AND city = 'Atlanta';
Insert a new record in the trending_fashions table for style 'Jumpsuit', region 'Europe' and popularity 80
CREATE TABLE trending_fashions (style VARCHAR(255) PRIMARY KEY,region VARCHAR(255),popularity INT); INSERT INTO trending_fashions (style,region,popularity) VALUES ('Tunic','MiddleEast',60),('Pants','Asia',90);
INSERT INTO trending_fashions (style, region, popularity) VALUES ('Jumpsuit', 'Europe', 80);
What is the minimum budget for each program in 2027, excluding any updates made to the budgets?
CREATE TABLE Programs (ProgramID INT,Name TEXT,InitialBudget DECIMAL(10,2));CREATE TABLE BudgetUpdates (UpdateID INT,ProgramID INT,NewBudget DECIMAL(10,2),UpdateDate DATE);
SELECT P.Name, MIN(P.InitialBudget) as MinBudget FROM Programs P LEFT JOIN BudgetUpdates BU ON P.ProgramID = BU.ProgramID GROUP BY P.ProgramID, P.Name;
What is the total quantity of organic waste produced in the city of London, United Kingdom, for the year 2021?
CREATE TABLE waste_types (type VARCHAR(20),quantity INT); INSERT INTO waste_types (type,quantity) VALUES ('organic',16000),('plastic',9000),('glass',5000);
SELECT SUM(quantity) FROM waste_types WHERE type = 'organic' AND YEAR(date) = 2021;
What is the percentage of soybean fields in Brazil that have a pH level above 7.5, based on IoT sensor data?
CREATE TABLE pH_data (location VARCHAR(255),date DATE,pH FLOAT); INSERT INTO pH_data (location,date,pH) VALUES ('Brazil Soybean Field 1','2021-06-01',8.2),('Brazil Soybean Field 1','2021-06-02',8.3),('Brazil Soybean Field 2','2021-06-01',7.4);
SELECT 100.0 * COUNT(*) / (SELECT COUNT(*) FROM pH_data WHERE location LIKE '%Brazil Soybean Field%') FROM pH_data WHERE pH > 7.5 AND location LIKE '%Brazil Soybean Field%';
Find the total number of players who played more than 50% of the game time in the last 6 months.
CREATE TABLE GameEvents (PlayerID INT,EventTimestamp DATETIME,EventType VARCHAR(255)); INSERT INTO GameEvents (PlayerID,EventTimestamp,EventType) VALUES (1,'2021-06-01 12:00:00','GameStart'),(2,'2021-06-01 13:00:00','GameEnd'),(3,'2021-06-01 14:00:00','GameStart');
SELECT COUNT(DISTINCT PlayerID) as TotalPlayers FROM GameEvents WHERE EventType = 'GameStart' AND EventTimestamp BETWEEN DATEADD(month, -6, CURRENT_DATE) AND CURRENT_DATE AND (SELECT COUNT(*) FROM GameEvents as GE2 WHERE GE2.PlayerID = GameEvents.PlayerID AND GE2.EventType IN ('GameStart', 'GameEnd') AND GE2.EventTimestamp BETWEEN GameEvents.EventTimestamp AND DATEADD(month, 6, GameEvents.EventTimestamp)) > (SELECT COUNT(*) FROM GameEvents as GE3 WHERE GE3.PlayerID = GameEvents.PlayerID AND GE3.EventType = 'GameStart' AND GE3.EventTimestamp BETWEEN DATEADD(month, -6, CURRENT_DATE) AND GameEvents.EventTimestamp);
How many citizens provided feedback for service request SR001?
CREATE TABLE feedback (id INT,service_request_id INT,feedback TEXT);
SELECT COUNT(*) FROM feedback WHERE service_request_id = 1;
Which suppliers have provided more than 500kg of organic ingredients in total?
CREATE TABLE suppliers (supplier_id INT,supplier_name VARCHAR(255)); CREATE TABLE ingredients (ingredient_id INT,ingredient_name VARCHAR(255),is_organic BOOLEAN); CREATE TABLE inventory (inventory_id INT,ingredient_id INT,supplier_id INT,quantity FLOAT); INSERT INTO suppliers (supplier_id,supplier_name) VALUES (1,'Eco Farms'),(2,'Green Earth'),(3,'Local Harvest'); INSERT INTO ingredients (ingredient_id,ingredient_name,is_organic) VALUES (1,'Tomatoes',true),(2,'Chicken',false),(3,'Spinach',true); INSERT INTO inventory (inventory_id,ingredient_id,supplier_id,quantity) VALUES (1,1,1,300),(2,2,1,500),(3,3,2,1000),(4,1,2,700),(5,3,3,400);
SELECT supplier_name, SUM(quantity) as total_kg_organic FROM inventory i JOIN ingredients ing ON i.ingredient_id = ing.ingredient_id JOIN suppliers s ON i.supplier_id = s.supplier_id WHERE is_organic = true GROUP BY supplier_name HAVING SUM(quantity) > 500;
What was the total waste generated by the 'Eco-friendly Production' plant in the first half of 2021?
CREATE TABLE Plants (id INT,name VARCHAR(255)); INSERT INTO Plants (id,name) VALUES (6,'Eco-friendly Production'); CREATE TABLE Waste (plant_id INT,quantity INT,waste_date DATE); INSERT INTO Waste (plant_id,quantity,waste_date) VALUES (6,250,'2021-01-01'),(6,300,'2021-04-01');
SELECT SUM(quantity) FROM Waste WHERE plant_id = 6 AND waste_date BETWEEN '2021-01-01' AND '2021-06-30';
What is the average number of stories for buildings in Texas?
CREATE TABLE buildings (id INT,name VARCHAR(50),state VARCHAR(50),num_stories INT); INSERT INTO buildings (id,name,state,num_stories) VALUES (1,'Building A','Texas',5),(2,'Building B','Texas',10),(3,'Building C','California',3);
SELECT AVG(num_stories) FROM buildings WHERE state = 'Texas';
What is the total R&D expenditure for the drug 'Drexo' in Asia?
CREATE TABLE rd_expenditure_2 (drug_name TEXT,expenditure NUMERIC,region TEXT); INSERT INTO rd_expenditure_2 (drug_name,expenditure,region) VALUES ('Curely',6000000,'Japan'),('Drexo',8000000,'China');
SELECT SUM(expenditure) FROM rd_expenditure_2 WHERE drug_name = 'Drexo' AND region = 'Asia';
How many hectares of mangrove forests are there in Indonesia?
CREATE TABLE mangrove_forests (country VARCHAR(20),area FLOAT); INSERT INTO mangrove_forests (country,area) VALUES ('Indonesia',12345.6),('Brazil',7890.1);
SELECT SUM(area) FROM mangrove_forests WHERE country = 'Indonesia';
What are the player counts and average scores for each game released before 2018?
CREATE TABLE GameSessions (SessionID int,GameName varchar(50),PlayerCount int,ReleaseYear int,AvgScore int); INSERT INTO GameSessions (SessionID,GameName,PlayerCount,ReleaseYear,AvgScore) VALUES (1,'GameC',100,2017,80); INSERT INTO GameSessions (SessionID,GameName,PlayerCount,ReleaseYear,AvgScore) VALUES (2,'GameD',150,2018,85);
SELECT GameName, SUM(PlayerCount) as TotalPlayers, AVG(AvgScore) as AvgScore FROM GameSessions WHERE ReleaseYear < 2018 GROUP BY GameName;
What is the average funding received by biotech startups in the US and Canada?
CREATE SCHEMA if not exists biotech;USE biotech;CREATE TABLE if not exists startups (name VARCHAR(255),location VARCHAR(255),funding FLOAT);INSERT INTO startups (name,location,funding) VALUES ('Startup1','USA',5000000),('Startup2','Canada',7000000),('Startup3','USA',3000000);
SELECT AVG(funding) FROM startups WHERE location IN ('USA', 'Canada');
Identify the number of employees in each department and the percentage of the total workforce.
CREATE TABLE departments (id INT,department TEXT,employee_count INT); INSERT INTO departments (id,department,employee_count) VALUES (1,'mining_operations',150); INSERT INTO departments (id,department,employee_count) VALUES (2,'geology',120);
SELECT department, employee_count, ROUND(100.0 * employee_count / (SELECT SUM(employee_count) FROM departments), 2) AS percentage FROM departments;
What was the maximum precipitation recorded in 'Spring' per device?
CREATE TABLE sensors (id INT,device_id VARCHAR(255),precipitation INT,reading_date DATE); INSERT INTO sensors (id,device_id,precipitation,reading_date) VALUES (1,'Dev1',15,'2021-03-01'); INSERT INTO sensors (id,device_id,precipitation,reading_date) VALUES (2,'Dev2',20,'2021-04-15');
SELECT device_id, MAX(precipitation) FROM sensors WHERE reading_date BETWEEN (SELECT MIN(reading_date) FROM sensors WHERE EXTRACT(MONTH FROM reading_date) IN (3,4,5)) AND (SELECT MAX(reading_date) FROM sensors WHERE EXTRACT(MONTH FROM reading_date) IN (3,4,5)) GROUP BY device_id
What percentage of cosmetic products are not safety certified?
CREATE TABLE products (product_id INT,product_name TEXT,is_safety_certified BOOLEAN); INSERT INTO products (product_id,product_name,is_safety_certified) VALUES (1,'Eyeshadow',true),(2,'Blush',false),(3,'Highlighter',true);
SELECT (COUNT(*) - SUM(is_safety_certified)) * 100.0 / COUNT(*) as percentage FROM products;
Which athlete has the lowest wellbeing score on each team?
CREATE TABLE athlete_wellbeing (athlete_id INT,team_id INT,athlete_name VARCHAR(255),nationality VARCHAR(255),score INT); INSERT INTO athlete_wellbeing (athlete_id,team_id,athlete_name,nationality,score) VALUES (1,1,'AthleteA','USA',8),(2,1,'AthleteB','Canada',9),(3,2,'AthleteC','Brazil',7),(4,2,'AthleteD','India',6),(5,2,'AthleteE','India',8);
SELECT team_id, MIN(score) as lowest_score FROM athlete_wellbeing GROUP BY team_id;
Find the average price of products sourced from each country, excluding products sourced from China.
CREATE TABLE products (product_id INT,product_name VARCHAR(50),source_country VARCHAR(50),price DECIMAL(5,2)); INSERT INTO products (product_id,product_name,source_country,price) VALUES (1,'T-Shirt','USA',20.99),(2,'Pants','China',15.99),(3,'Jacket','India',35.99),(4,'Socks','Bangladesh',7.99);
SELECT source_country, AVG(price) FROM products WHERE source_country <> 'China' GROUP BY source_country;
What is the average speed of vessels for each country?
CREATE TABLE country_vessels (id INT,country VARCHAR(50),vessel_id INT,name VARCHAR(50),speed DECIMAL(5,2)); INSERT INTO country_vessels VALUES (1,'Japan',1,'Vessel1',25.6),(2,'Japan',2,'Vessel2',27.3),(3,'China',3,'Vessel3',24.5);
SELECT country, AVG(speed) FROM country_vessels GROUP BY country;
Display the number of players who achieved a win rate of over 70% in 'CS:GO'.
CREATE TABLE CSGOPlayers (PlayerID INT,Player VARCHAR(50),Wins INT,Losses INT); INSERT INTO CSGOPlayers (PlayerID,Player,Wins,Losses) VALUES (1,'Han',70,30); INSERT INTO CSGOPlayers (PlayerID,Player,Wins,Losses) VALUES (2,'Sophia',85,20); INSERT INTO CSGOPlayers (PlayerID,Player,Wins,Losses) VALUES (3,'Minho',65,35); INSERT INTO CSGOPlayers (PlayerID,Player,Wins,Losses) VALUES (4,'Lena',90,10);
SELECT COUNT(*) FROM CSGOPlayers WHERE (Wins / (Wins + Losses)) > 0.7 AND Game = 'CS:GO';
Delete a training program record from the 'training_programs' table
CREATE TABLE training_programs (id INT PRIMARY KEY,program_name VARCHAR(50),start_date DATE,end_date DATE,location VARCHAR(50));
DELETE FROM training_programs WHERE id = 1001;
Which communities are engaged in preserving the heritage sites in Europe and what are those sites?
CREATE TABLE Communities (id INT,name TEXT); INSERT INTO Communities (id,name) VALUES (1,'Romans'); CREATE TABLE HeritageCommunities (id INT,community_id INT,heritage_site TEXT); INSERT INTO HeritageCommunities (id,community_id,heritage_site) VALUES (1,1,'Colosseum');
SELECT C.name, HC.heritage_site FROM Communities C INNER JOIN HeritageCommunities HC ON C.id = HC.community_id WHERE HC.heritage_site = 'Colosseum';
Find the top 2 dispensaries with the highest total revenue in Oregon in Q2 2022.
CREATE TABLE dispensaries (id INT,name VARCHAR(50),state VARCHAR(20)); CREATE TABLE sales (id INT,dispensary_id INT,revenue DECIMAL(10,2),date DATE); INSERT INTO dispensaries (id,name,state) VALUES (1,'Green Valley','Oregon'),(2,'Emerald City','Oregon'); INSERT INTO sales (id,dispensary_id,revenue,date) VALUES (1,1,8000.00,'2022-04-01'),(2,2,9000.00,'2022-04-02');
SELECT dispensary_id, SUM(revenue) as total_revenue FROM sales WHERE date BETWEEN '2022-04-01' AND '2022-06-30' GROUP BY dispensary_id ORDER BY total_revenue DESC FETCH NEXT 2 ROWS ONLY;
Who are the top 5 students with the most accommodations provided?
CREATE TABLE Students (Id INT,Name VARCHAR(100),DisabilityType VARCHAR(50)); CREATE TABLE Accommodations (Id INT,StudentId INT,AccommodationType VARCHAR(50),DateProvided DATETIME); INSERT INTO Students (Id,Name,DisabilityType) VALUES (1,'Jane Doe','Mobility Impairment'),(2,'John Doe','Visual Impairment'),(3,'Sarah Smith','Learning Disability'),(4,'Michael Lee','Hearing Impairment'),(5,'David Kim','Psychiatric Disability'); INSERT INTO Accommodations (Id,StudentId,AccommodationType,DateProvided) VALUES (1,1,'Wheelchair Ramp','2021-01-01'),(2,1,'Note Taker','2021-01-02'),(3,2,'Screen Reader','2021-01-03'),(4,2,'Braille Materials','2021-01-04'),(5,3,'Extra Time','2021-01-05'),(6,3,'Quiet Space','2021-01-06'),(7,4,'Sign Language Interpreter','2021-01-07'),(8,4,'Captioned Videos','2021-01-08'),(9,5,'Therapy Sessions','2021-01-09'),(10,5,'Medication Reminders','2021-01-10');
SELECT Students.Name, COUNT(*) AS NumberOfAccommodations FROM Students JOIN Accommodations ON Students.Id = Accommodations.StudentId GROUP BY Students.Id ORDER BY NumberOfAccommodations DESC LIMIT 5;
What is the total number of Green buildings in each country?
CREATE TABLE green_buildings_2 (building_id INT,building_name TEXT,country TEXT); INSERT INTO green_buildings_2 (building_id,building_name,country) VALUES (1,'Green Building 1','USA'),(2,'Green Building 2','USA'),(3,'Green Building 3','Canada');
SELECT country, COUNT(*) FROM green_buildings_2 GROUP BY country;
Find the average number of biosensor technology patents per year between 2018 and 2021.
CREATE SCHEMA if not exists biotech;CREATE TABLE if not exists biotech.patents (id INT,title VARCHAR(100),country VARCHAR(50),research_area VARCHAR(50),patent_year INT); INSERT INTO biotech.patents (id,title,country,research_area,patent_year) VALUES (1,'Patent6','USA','Biosensor Technology',2018),(2,'Patent7','Canada','Biosensor Technology',2020),(3,'Patent8','USA','Biosensor Technology',2021),(4,'Patent9','UK','Biosensor Technology',2019);
SELECT AVG(patent_year) FROM biotech.patents WHERE research_area = 'Biosensor Technology' AND patent_year BETWEEN 2018 AND 2021 GROUP BY research_area, patent_year;
Insert a new record into the 'patients' table with the following details: first name 'John', last name 'Doe', age 30, gender 'Male', and ethnicity 'Caucasian'.
CREATE TABLE patients (patient_id INT PRIMARY KEY AUTO_INCREMENT,first_name VARCHAR(50),last_name VARCHAR(50),age INT,gender VARCHAR(10),ethnicity VARCHAR(50));
INSERT INTO patients (first_name, last_name, age, gender, ethnicity) VALUES ('John', 'Doe', 30, 'Male', 'Caucasian');
How many heritage sites are in Africa, with their names and the year they were added to the list, sorted by the year added?
CREATE TABLE HeritageSites (SiteName VARCHAR(255),Country VARCHAR(255),YearAdded INT); INSERT INTO HeritageSites (SiteName,Country,YearAdded) VALUES ('Medina of Tunis','Tunisia',1979),('City of Valletta','Malta',1980),('Historic Centre of Rome','Italy',1980),('Sundarbans National Park','India',1987),('Aapravasi Ghat','Mauritius',2006),('Robben Island','South Africa',1999);
SELECT SiteName, Country, YearAdded FROM HeritageSites WHERE Country = 'Africa' ORDER BY YearAdded ASC;
What is the percentage of community health workers who identify as Hispanic or Latino by state?
CREATE TABLE States (state_id INT,state_name TEXT); CREATE TABLE CommunityHealthWorkers (worker_id INT,worker_ethnicity TEXT,state_id INT);
SELECT COUNT(*) FILTER (WHERE worker_ethnicity = 'Hispanic or Latino') * 100.0 / COUNT(*) as pct_hispanic_workers, s.state_name FROM CommunityHealthWorkers chw JOIN States s ON chw.state_id = s.state_id GROUP BY s.state_id;
What is the total number of streams for each artist in descending order?
CREATE TABLE artist_streams (stream_id INT,artist_id INT,streams_amount INT); CREATE TABLE artist (artist_id INT,artist_name VARCHAR(255));
SELECT artist_name, SUM(streams_amount) FROM artist_streams JOIN artist ON artist_streams.artist_id = artist.artist_id GROUP BY artist_name ORDER BY SUM(streams_amount) DESC;
Delete co-living properties in cities without inclusive housing policies.
CREATE TABLE CoLivingProperties(id INT,size FLOAT,city VARCHAR(20));INSERT INTO CoLivingProperties(id,size,city) VALUES (1,800,'Portland'),(2,900,'Seattle'),(3,1000,'SanFrancisco'),(4,1100,'Austin'); CREATE TABLE Cities(id INT,city VARCHAR(20),inclusive VARCHAR(20));INSERT INTO Cities(id,city,inclusive) VALUES (1,'Portland','Yes'),(2,'Seattle','Yes'),(3,'SanFrancisco','No'),(4,'Austin','Yes');
DELETE FROM CoLivingProperties WHERE city NOT IN (SELECT city FROM Cities WHERE inclusive = 'Yes');
What is the total number of marine protected areas in the Pacific region and their total area?
CREATE TABLE marine_protected_areas (id INT,name VARCHAR(255),region VARCHAR(255)); INSERT INTO marine_protected_areas (id,name,region) VALUES (1,'Galapagos Marine Reserve','Pacific'),(2,'Great Barrier Reef','Pacific');
SELECT SUM(area) as total_area, region FROM marine_protected_areas JOIN areas_of_marine_protected_areas ON marine_protected_areas.id = areas_of_marine_protected_areas.marine_protected_area_id WHERE region = 'Pacific' GROUP BY region;
How many circular supply chain initiatives have been implemented in the United States, according to CircularSupplyChain table?
CREATE TABLE CircularSupplyChain (initiative_id INT,initiative_name VARCHAR(100),country VARCHAR(50),start_date DATE); INSERT INTO CircularSupplyChain (initiative_id,initiative_name,country,start_date) VALUES (1,'Project Reclaim','USA','2019-04-01'),(2,'Closed Loop Partnership','Canada','2020-06-15'),(3,'GreenBlue Initiative','USA','2018-09-20');
SELECT COUNT(*) FROM CircularSupplyChain WHERE country = 'USA';
What was the total quantity sold for hybrid strains in Michigan in 2021?
CREATE TABLE sales (id INT,state VARCHAR(50),year INT,strain_type VARCHAR(50),quantity SINT); INSERT INTO sales (id,state,year,strain_type,quantity) VALUES (1,'Michigan',2021,'Hybrid',500),(2,'Michigan',2021,'Sativa',600),(3,'California',2021,'Indica',400);
SELECT SUM(quantity) FROM sales WHERE state = 'Michigan' AND year = 2021 AND strain_type = 'Hybrid';
List the top 5 most read news articles in descending order by views.
CREATE TABLE articles (id INT,title VARCHAR(100),content TEXT,views INT);
SELECT title FROM (SELECT title, ROW_NUMBER() OVER (ORDER BY views DESC) as rn FROM articles) tmp WHERE rn <= 5;
What is the average water temperature for fish stock management in each region?
CREATE TABLE regional_temps (id INT,region TEXT,farm_id INT,water_temperature DECIMAL(5,2)); INSERT INTO regional_temps (id,region,farm_id,water_temperature) VALUES (1,'Atlantic',1,11.5),(2,'Atlantic',2,12.0),(3,'Pacific',3,16.0),(4,'Pacific',4,17.5),(5,'Atlantic',5,10.0);
SELECT region, AVG(water_temperature) as avg_temp FROM regional_temps GROUP BY region;
What is the total revenue for concerts held in 'Los Angeles'?
CREATE TABLE concerts (id INT,artist_id INT,city VARCHAR(50),revenue FLOAT); INSERT INTO concerts (id,artist_id,city,revenue) VALUES (1,1,'Los Angeles',500000),(2,1,'New York',700000),(3,2,'Seoul',800000),(4,2,'Tokyo',900000),(5,1,'Los Angeles',600000);
SELECT SUM(revenue) as total_revenue FROM concerts WHERE city = 'Los Angeles';
How many water conservation initiatives were implemented in the Midwest region in Q3 of 2019?
CREATE TABLE conservation_initiatives (id INT,name TEXT,region TEXT,timestamp DATETIME); INSERT INTO conservation_initiatives (id,name,region,timestamp) VALUES (1,'Initiative A','Midwest','2019-07-01 10:00:00'),(2,'Initiative B','Midwest','2019-04-01 15:00:00'),(3,'Initiative C','Midwest','2019-07-15 09:30:00');
SELECT COUNT(*) FROM conservation_initiatives WHERE region = 'Midwest' AND QUARTER(timestamp) = 3 AND YEAR(timestamp) = 2019;
What is the maximum biomass of fish in aquaculture farms in India in 2019?
CREATE TABLE Fish_Farms (id INT,country VARCHAR(255),year INT,biomass INT); INSERT INTO Fish_Farms (id,country,year,biomass) VALUES (1,'India',2018,300),(2,'India',2019,450),(3,'China',2018,500),(4,'India',2020,550);
SELECT MAX(Fish_Farms.biomass) FROM Fish_Farms WHERE Fish_Farms.country = 'India' AND Fish_Farms.year = 2019;
Show the number of wells in the South Pacific that were drilled each year from 2010 to 2020.
CREATE TABLE wells_south_pacific (id INT,location VARCHAR(20),drill_date DATE);
SELECT drill_date, COUNT(*) FROM wells_south_pacific WHERE location LIKE 'South Pacific%' AND drill_date BETWEEN '2010-01-01' AND '2020-12-31' GROUP BY drill_date;
Add a traditional art from Africa to the 'traditional_arts' table
CREATE TABLE traditional_arts (id INT PRIMARY KEY,name VARCHAR(255),type VARCHAR(255),region VARCHAR(255));
INSERT INTO traditional_arts (id, name, type, region) VALUES (1, 'Adire Textiles', 'Textile', 'West Africa');
Delete all warehouse records with a stock level below 10 for items in the 'Electronics' category.
CREATE TABLE Warehouses (WarehouseID INT,Item VARCHAR(255),Category VARCHAR(255),StockLevel INT); INSERT INTO Warehouses (WarehouseID,Item,Category,StockLevel) VALUES (1,'Laptop','Electronics',25),(2,'Monitor','Electronics',12),(3,'Keyboard','Electronics',18),(4,'Table','Furniture',30),(5,'Chair','Furniture',40);
DELETE FROM Warehouses WHERE StockLevel < 10 AND Category = 'Electronics';
What is the average well-being score for athletes in each team, excluding the lowest and highest scores?
CREATE TABLE teams (team_id INT,team_name VARCHAR(50));CREATE TABLE athletes (athlete_id INT,athlete_name VARCHAR(50),team_id INT,well_being_score INT); INSERT INTO teams (team_id,team_name) VALUES (1,'Atlanta Hawks'),(2,'Boston Celtics'); INSERT INTO athletes (athlete_id,athlete_name,team_id,well_being_score) VALUES (1,'Player1',1,5),(2,'Player2',1,8),(3,'Player3',2,7),(4,'Player4',2,10),(5,'Player5',2,9);
SELECT t.team_name, AVG(a.well_being_score) FROM teams t JOIN athletes a ON t.team_id = a.team_id WHERE a.well_being_score NOT IN (SELECT MIN(well_being_score) FROM athletes) AND a.well_being_score NOT IN (SELECT MAX(well_being_score) FROM athletes) GROUP BY t.team_id;
List the unique climate adaptation strategies used in each region.
CREATE TABLE region (name VARCHAR(255),PRIMARY KEY (name)); INSERT INTO region (name) VALUES ('Asia'),('Europe'),('North America'),('South America'),('Africa'),('Oceania'); CREATE TABLE climate_adaptation_strategies (strategy_name VARCHAR(255),location VARCHAR(255)); INSERT INTO climate_adaptation_strategies (strategy_name,location) VALUES ('Strategy 1','Asia'),('Strategy 2','Europe'),('Strategy 3','North America'),('Strategy 1','South America'),('Strategy 2','Africa'),('Strategy 3','Oceania');
SELECT r.name, strategy_name FROM region r JOIN climate_adaptation_strategies s ON r.name = s.location;
What is the total quantity of organic ingredients used in menu items?
CREATE TABLE Dishes (DishID INT,Name VARCHAR(50),Quantity INT); CREATE TABLE Ingredients (IngredientID INT,DishID INT,Quantity INT,Organic BOOLEAN); INSERT INTO Dishes (DishID,Name,Quantity) VALUES (1,'Quinoa Salad',200),(2,'Pizza Margherita',300); INSERT INTO Ingredients (IngredientID,DishID,Quantity,Organic) VALUES (1,1,200,TRUE),(2,1,0,FALSE),(3,2,300,TRUE);
SELECT SUM(i.Quantity) FROM Dishes d JOIN Ingredients i ON d.DishID = i.DishID WHERE i.Organic = TRUE;
What are the total home runs hit by baseball players in the current year?
CREATE TABLE home_runs (player VARCHAR(50),year INT,home_runs INT); INSERT INTO home_runs (player,year,home_runs) VALUES ('Johnson',2021,40),('Johnson',2022,35),('Brown',2021,50),('Brown',2022,55);
SELECT player, SUM(home_runs) AS total_home_runs FROM home_runs WHERE year = YEAR(GETDATE()) GROUP BY player
How many sustainable fabric types does each supplier offer?
CREATE TABLE suppliers (id INT,name TEXT); CREATE TABLE supplier_fabrics (id INT,supplier INT,fabric TEXT); INSERT INTO suppliers (id,name) VALUES (1,'GreenFabrics'),(2,'EcoWeave'),(3,'SustainaTex'); INSERT INTO supplier_fabrics (id,supplier,fabric) VALUES (1,1,'Organic Cotton'),(2,1,'Recycled Polyester'),(3,2,'Hemp'),(4,2,'Tencel'),(5,3,'Lyocell'),(6,3,'Bamboo');
SELECT supplier, COUNT(DISTINCT fabric) as unique_fabrics FROM supplier_fabrics GROUP BY supplier;
Which artist has the most works in the modern art category?
CREATE TABLE artists (artist_id INT PRIMARY KEY,artist_name TEXT,style TEXT);CREATE TABLE works (work_id INT PRIMARY KEY,work_title TEXT,artist_id INT,category TEXT,FOREIGN KEY (artist_id) REFERENCES artists(artist_id));INSERT INTO artists (artist_id,artist_name,style) VALUES (1,'Pablo Picasso','Cubism'); INSERT INTO works (work_id,work_title,artist_id,category) VALUES (1,'Guernica',1,'Modern Art');
SELECT a.artist_name FROM artists a JOIN works w ON a.artist_id = w.artist_id WHERE w.category = 'Modern Art' GROUP BY a.artist_name ORDER BY COUNT(w.work_id) DESC LIMIT 1;
Which community education programs were held in the 'community_education' table, and what was the total number of attendees for each program?
CREATE TABLE community_education (program_name VARCHAR(255),location VARCHAR(255),date DATE,num_attendees INT); INSERT INTO community_education (program_name,location,date,num_attendees) VALUES ('Wildlife Awareness','New York','2020-01-01',50),('Nature Walk','California','2019-05-15',25),('Wildlife Awareness','Florida','2020-03-10',75);
SELECT program_name, SUM(num_attendees) as total_attendees FROM community_education GROUP BY program_name;
What is the average speed of spacecraft in the space_exploration table?
CREATE TABLE space_exploration (id INT,name VARCHAR(20),launch_date DATE,max_speed FLOAT); INSERT INTO space_exploration (id,name,launch_date,max_speed) VALUES (1,'Voyager 1','1977-09-05',61000),(2,'New Horizons','2006-01-19',58000),(3,'Parker Solar Probe','2018-08-12',724200);
SELECT AVG(max_speed) FROM space_exploration;
What is the average rating for each menu category by location?
CREATE TABLE menu_location_ratings (menu_category VARCHAR(50),location_name VARCHAR(50),rating NUMERIC(3,2)); INSERT INTO menu_location_ratings (menu_category,location_name,rating) VALUES ('Appetizers','San Francisco',4.5),('Entrees','San Francisco',4.0),('Desserts','San Francisco',3.5),('Appetizers','New York',3.0),('Entrees','New York',4.0),('Desserts','New York',4.5);
SELECT menu_category, location_name, AVG(rating) AS avg_rating FROM menu_location_ratings GROUP BY menu_category, location_name;
What is the average mass of spacecraft manufactured by each company?
CREATE TABLE Spacecraft (SpacecraftID INT,Manufacturer VARCHAR(50),Model VARCHAR(50),Mass FLOAT);
SELECT Manufacturer, AVG(Mass) FROM Spacecraft GROUP BY Manufacturer;
What is the total revenue for each supplier, by day?
CREATE TABLE purchases (purchase_date DATE,supplier VARCHAR(255),revenue DECIMAL(10,2));
SELECT supplier, DATE_TRUNC('day', purchase_date) AS purchase_day, SUM(revenue) AS total_revenue FROM purchases GROUP BY supplier, purchase_day;
What is the average veteran unemployment rate by state from 2015 to 2019?
CREATE TABLE veteran_unemployment (state TEXT,year INT,rate DECIMAL); INSERT INTO veteran_unemployment (state,year,rate) VALUES ('California',2015,4.1),('California',2016,3.9),('California',2017,3.7),('California',2018,3.5),('California',2019,3.4),('Texas',2015,3.5),('Texas',2016,3.3),('Texas',2017,3.2),('Texas',2018,3.1),('Texas',2019,3.0);
SELECT state, AVG(rate) FROM veteran_unemployment WHERE year BETWEEN 2015 AND 2019 GROUP BY state;
What is the total fare collected for a specific train line in Berlin?
CREATE TABLE train_lines (line_id INT,city VARCHAR(50)); INSERT INTO train_lines (line_id,city) VALUES (1,'Berlin'),(2,'Berlin'); CREATE TABLE fares_collected (line_id INT,fare DECIMAL(5,2)); INSERT INTO fares_collected (line_id,fare) VALUES (1,500.00),(1,750.00),(2,300.00),(2,400.00);
SELECT SUM(fare) FROM fares_collected INNER JOIN train_lines ON fares_collected.line_id = train_lines.line_id WHERE city = 'Berlin' AND train_lines.line_id = 1;
List all marine species and their status under maritime law.
CREATE TABLE MarineSpecies (id INT,species TEXT,status TEXT);INSERT INTO MarineSpecies (id,species,status) VALUES (1,'Blue Whale','Endangered'); INSERT INTO MarineSpecies (id,species,status) VALUES (2,'Dolphin','Protected');
SELECT species, status FROM MarineSpecies;
What is the total weight of freight shipped from each country?
CREATE TABLE Carrier (id INT,name VARCHAR(30),country VARCHAR(20)); INSERT INTO Carrier (id,name,country) VALUES (1,'FedEx','USA'),(2,'DHL','Germany'),(3,'UPS','Canada'); CREATE TABLE Freight (id INT,route_id INT,shipped_weight INT); INSERT INTO Freight (id,route_id,shipped_weight) VALUES (1,1,250),(2,2,350),(3,3,450); CREATE TABLE Route (id INT,origin VARCHAR(20),destination VARCHAR(20)); INSERT INTO Route (id,origin,destination) VALUES (1,'New York','Los Angeles'),(2,'Berlin','Paris'),(3,'Toronto','Vancouver');
SELECT c.country, SUM(f.shipped_weight) FROM Carrier c JOIN Route r ON c.id = r.id JOIN Freight f ON r.id = f.route_id GROUP BY c.country;
Find the number of cases won by attorneys in the city of Seattle.
CREATE TABLE attorneys (id INT,name TEXT,city TEXT); INSERT INTO attorneys (id,name,city) VALUES (1,'Harry Stone','Seattle'); CREATE TABLE cases (id INT,attorney_id INT,result TEXT); INSERT INTO cases (id,attorney_id,result) VALUES (1,1,'won');
SELECT COUNT(*) FROM cases INNER JOIN attorneys ON cases.attorney_id = attorneys.id WHERE attorneys.city = 'Seattle' AND cases.result = 'won';
What was the average number of hours spent by volunteers from a particular city in 2021?
CREATE TABLE volunteer_hours (volunteer_id INT,volunteer_city TEXT,hours_spent INT,hours_date DATE); CREATE TABLE cities (city_id INT,city_name TEXT); INSERT INTO cities VALUES (1,'New York'); INSERT INTO cities VALUES (2,'Los Angeles');
SELECT volunteer_city, AVG(hours_spent) as avg_hours_spent FROM volunteer_hours JOIN cities ON volunteer_hours.volunteer_city = cities.city_name WHERE YEAR(hours_date) = 2021 GROUP BY volunteer_city;
Delete all records from 'FarmersMarket' view
CREATE VIEW FarmersMarket AS SELECT * FROM Products WHERE is_organic = TRUE; INSERT INTO Products (id,name,is_organic) VALUES (1,'Product1',TRUE),(2,'Product2',FALSE),(3,'Product3',TRUE);
DELETE FROM FarmersMarket;
How many sustainable garments were sold in Q2 2021?
CREATE TABLE sales (id INT,garment_id INT,date DATE); INSERT INTO sales (id,garment_id,date) VALUES
SELECT COUNT(*) FROM sales INNER JOIN garments ON sales.garment_id = garments.id WHERE garments.sustainable = 'true' AND date BETWEEN '2021-04-01' AND '2021-06-30';
How many species are there in the 'Marine Biology' journal?
CREATE TABLE marine_biology_journal (id INT,species TEXT); INSERT INTO marine_biology_journal (id,species) VALUES (1,'Corals'),(2,'Fish'),(3,'Mammals'),(4,'Plankton'),(5,'Turtles');
SELECT COUNT(*) FROM marine_biology_journal;
What is the average age of engineers in the Mining department?
CREATE TABLE Employees (EmployeeID INT,Department VARCHAR(20),Position VARCHAR(20),Age INT); INSERT INTO Employees (EmployeeID,Department,Position,Age) VALUES (1,'Mining','Engineer',35),(2,'Mining','Engineer',40),(3,'HR','Engineer',32); CREATE TABLE Department (Department VARCHAR(20),DepartmentHead VARCHAR(20)); INSERT INTO Department (Department,DepartmentHead) VALUES ('Mining','John'),('HR','Jane');
SELECT AVG(Age) FROM Employees WHERE Department = 'Mining' AND Position = 'Engineer';
What are the top 3 threat actors by the number of attacks in the last 6 months?
CREATE TABLE threat_actors (threat_actor_id INT,threat_actor_name VARCHAR(255),attack_count INT); INSERT INTO threat_actors (threat_actor_id,threat_actor_name,attack_count) VALUES (1,'APT28',12),(2,'Lazarus Group',15),(3,'Cozy Bear',9),(4,'Fancy Bear',18),(5,'WannaCry',7);
SELECT threat_actor_name, attack_count FROM threat_actors ORDER BY attack_count DESC LIMIT 3;