instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
Update the device type for ID 103 to 'Apple Watch'
CREATE TABLE wearables (member_id INT,device_type VARCHAR(50),heart_rate INT);
UPDATE wearables SET device_type = 'Apple Watch' WHERE member_id = 103;
What is the total number of schools rebuilt in Haiti and the number of classrooms in those schools?
CREATE TABLE schools (id INT,country VARCHAR(255),name VARCHAR(255),classrooms INT); INSERT INTO schools (id,country,name,classrooms) VALUES (1,'Haiti','School 1',5),(2,'Haiti','School 2',6);
SELECT country, SUM(classrooms) FROM schools GROUP BY country;
Insert a new record of military equipment sale
CREATE TABLE sales (id INT,year INT,country VARCHAR(255),equipment_type VARCHAR(255),revenue FLOAT);
INSERT INTO sales (id, year, country, equipment_type, revenue) VALUES (2, 2021, 'Canada', 'Naval Vessels', 12000000);
What is the total CO2 emission for each mine in the last 6 months?
CREATE TABLE mine (id INT,name TEXT,location TEXT); INSERT INTO mine (id,name,location) VALUES (1,'Mine G','Country T'),(2,'Mine H','Country S'); CREATE TABLE environmental_impact (mine_id INT,co2_emission INT,timestamp TIMESTAMP); INSERT INTO environmental_impact (mine_id,co2_emission,timestamp) VALUES (1,1000,'2023-01-01 00:00:00'),(2,1500,'2023-01-01 00:00:00');
SELECT mine_id, SUM(co2_emission) as total_emission FROM environmental_impact WHERE timestamp >= DATEADD(month, -6, CURRENT_TIMESTAMP) GROUP BY mine_id;
Insert a new vessel 'Mystic Turtle' with type 'Cruise' into the Vessels table.
CREATE TABLE Vessels (ID INT,Name VARCHAR(50),Type VARCHAR(50));
INSERT INTO Vessels (ID, Name, Type) VALUES (4, 'Mystic Turtle', 'Cruise');
What is the average calorie count per meal for vegetarian dishes?
CREATE TABLE Cuisines (CuisineID INT,CuisineType VARCHAR(50)); CREATE TABLE Meals (MealID INT,CuisineID INT,MealName VARCHAR(50),CalorieCount INT,IsVegetarian BIT); INSERT INTO Cuisines (CuisineID,CuisineType) VALUES (1,'American'),(2,'Italian'); INSERT INTO Meals (MealID,CuisineID,MealName,CalorieCount,IsVegetarian) VALUES (1,1,'Classic Burger',550,0),(2,1,'Turkey Sandwich',700,0),(3,2,'Margherita Pizza',800,1),(4,2,'Spaghetti Bolognese',1000,0);
SELECT CuisineType, AVG(CalorieCount) as avg_calories FROM Cuisines C JOIN Meals M ON C.CuisineID = M.CuisineID WHERE IsVegetarian = 1 GROUP BY CuisineType;
How many public awareness campaigns were launched in each year in the 'campaigns' schema?
CREATE TABLE campaigns (campaign_id INT,launch_date DATE); INSERT INTO campaigns (campaign_id,launch_date) VALUES (1,'2019-01-01'),(2,'2020-05-15'),(3,'2018-12-31'),(4,'2021-03-20');
SELECT EXTRACT(YEAR FROM launch_date) AS year, COUNT(*) AS campaigns_launched FROM campaigns GROUP BY year;
List all mines with their environmental impact score
CREATE TABLE mine (id INT,name TEXT,location TEXT,environmental_impact_score INT); INSERT INTO mine VALUES (1,'Mine A','Country A',60); INSERT INTO mine VALUES (2,'Mine B','Country B',75); INSERT INTO mine VALUES (3,'Mine C','Country C',45);
SELECT name, environmental_impact_score FROM mine;
How many news stories were published about climate change in the last month?
CREATE TABLE news_story (news_story_id INT,publication_date DATE,topic VARCHAR(50)); INSERT INTO news_story (news_story_id,publication_date,topic) VALUES (1,'2023-01-01','Climate Change'),(2,'2023-02-01','Politics'),(3,'2023-03-01','Climate Change');
SELECT COUNT(*) as num_stories FROM news_story WHERE topic = 'Climate Change' AND publication_date >= CURDATE() - INTERVAL 1 MONTH;
Show the total number of space missions and total number of satellites?
CREATE TABLE space_missions (mission_id INT,name VARCHAR(100),launch_date DATE); INSERT INTO space_missions (mission_id,name,launch_date) VALUES (1,'Luna 1','1959-01-02'),(2,'Apollo 11','1969-07-16'); CREATE TABLE satellites (satellite_id INT,name VARCHAR(100),owner_country VARCHAR(50)); INSERT INTO satellites (satellite_id,name,owner_country) VALUES (1,'GPS Satellite','USA'),(2,'Beidou Satellite','China');
SELECT (SELECT COUNT(*) FROM space_missions) AS total_missions, (SELECT COUNT(*) FROM satellites) AS total_satellites;
What is the total number of defense contracts awarded to companies in California between 2018 and 2020?
CREATE TABLE DefenseContracts (id INT,contractor VARCHAR(255),state VARCHAR(255),year INT,contract_value INT); INSERT INTO DefenseContracts (id,contractor,state,year,contract_value) VALUES (1,'ABC Corp','California',2018,100000),(2,'XYZ Inc','Texas',2018,200000),(3,'DEF LLC','California',2019,300000),(4,'ABC Corp','California',2019,400000),(5,'XYZ Inc','Texas',2019,500000),(6,'DEF LLC','California',2020,600000);
SELECT contractor, SUM(contract_value) FROM DefenseContracts WHERE state = 'California' AND year BETWEEN 2018 AND 2020 GROUP BY contractor;
What is the average energy efficiency rating of Green buildings in 'Region J' for each building type?
CREATE TABLE GreenBuildings (BuildingID INT,BuildingType VARCHAR(255),Region VARCHAR(255),EnergyEfficiencyRating FLOAT); INSERT INTO GreenBuildings (BuildingID,BuildingType,Region,EnergyEfficiencyRating) VALUES (1,'Residential','Region J',85.0);
SELECT BuildingType, AVG(EnergyEfficiencyRating) FROM GreenBuildings WHERE Region = 'Region J' GROUP BY BuildingType;
What is the policy number, coverage type, and effective date for policies with a sum insured greater than $500,000?
CREATE TABLE Policy (PolicyNumber INT,CoverageType VARCHAR(50),SumInsured INT,EffectiveDate DATE); INSERT INTO Policy (PolicyNumber,CoverageType,SumInsured,EffectiveDate) VALUES (1,'Home',700000,'2020-01-01'); INSERT INTO Policy (PolicyNumber,CoverageType,SumInsured,EffectiveDate) VALUES (2,'Auto',300000,'2019-05-15');
SELECT PolicyNumber, CoverageType, EffectiveDate FROM Policy WHERE SumInsured > 500000;
What is the order ID and delivery time for the 90th percentile delivery time for each courier in the 'courier_performances' view, ordered by the 90th percentile delivery time?
CREATE VIEW courier_performances AS SELECT courier_id,order_id,delivery_time,PERCENTILE_CONT(0.9) WITHIN GROUP (ORDER BY delivery_time) OVER (PARTITION BY courier_id) as pct_90 FROM orders;
SELECT courier_id, order_id, delivery_time FROM courier_performances WHERE pct_90 = delivery_time ORDER BY delivery_time;
List all cybersecurity incidents in Europe and the corresponding incident response time in 2021 and 2022.
CREATE TABLE CybersecurityIncidents (id INT,incident_name VARCHAR(255),incident_date DATE,country VARCHAR(255)); INSERT INTO CybersecurityIncidents (id,incident_name,incident_date,country) VALUES (1,'Incident A','2021-01-01','France'),(2,'Incident B','2021-02-15','Germany'),(3,'Incident C','2022-03-03','UK'); CREATE TABLE ResponseTimes (incident_id INT,response_time INT); INSERT INTO ResponseTimes (incident_id,response_time) VALUES (1,4),(2,6),(3,5);
SELECT i.incident_name, i.country, r.response_time FROM CybersecurityIncidents i INNER JOIN ResponseTimes r ON i.id = r.incident_id WHERE i.country IN ('France', 'Germany', 'UK') AND i.incident_date BETWEEN '2021-01-01' AND '2022-12-31' ORDER BY i.incident_date;
What is the total number of military equipment sales in the second half of the year 2022?
CREATE TABLE military_equipment_sales (id INT,sale_date DATE,quantity INT); INSERT INTO military_equipment_sales (id,sale_date,quantity) VALUES (1,'2022-01-01',500),(2,'2022-02-01',600),(3,'2022-07-01',700),(4,'2022-08-01',800);
SELECT SUM(quantity) FROM military_equipment_sales WHERE sale_date BETWEEN '2022-07-01' AND '2022-12-31';
What is the average safety rating for Mexican restaurants?
CREATE TABLE Restaurants (id INT,name VARCHAR(50),type VARCHAR(20),safety_rating INT); INSERT INTO Restaurants (id,name,type,safety_rating) VALUES (1,'Green Garden','Vegan',5); INSERT INTO Restaurants (id,name,type,safety_rating) VALUES (2,'Bistro Bella','Italian',4); INSERT INTO Restaurants (id,name,type,safety_rating) VALUES (3,'Taqueria Tina','Mexican',5); INSERT INTO Restaurants (id,name,type,safety_rating) VALUES (4,'Sushi Bar','Asian',4);
SELECT AVG(safety_rating) FROM Restaurants WHERE type LIKE '%Mexican%';
How many male patients with chronic conditions live in New York?
CREATE TABLE Patients (PatientID INT,Gender TEXT,ChronicConditions TEXT,State TEXT); INSERT INTO Patients (PatientID,Gender,ChronicConditions,State) VALUES (1,'Male','Diabetes','New York');
SELECT COUNT(*) FROM Patients WHERE Gender = 'Male' AND ChronicConditions IS NOT NULL AND State = 'New York';
Update the aircraft_manufacturing table to set the status of all records with manufacturer 'Airbus' to 'In Production'
CREATE TABLE aircraft_manufacturing (id INT,aircraft_name VARCHAR(255),manufacturer VARCHAR(255),manufacturing_date DATE,status VARCHAR(255));
UPDATE aircraft_manufacturing SET status = 'In Production' WHERE manufacturer = 'Airbus';
What is the maximum checking account balance in the Miami branch?
CREATE TABLE accounts (customer_id INT,account_type VARCHAR(20),branch VARCHAR(20),balance DECIMAL(10,2)); INSERT INTO accounts (customer_id,account_type,branch,balance) VALUES (1,'Savings','New York',5000.00),(2,'Checking','New York',7000.00),(3,'Checking','Miami',9000.00),(4,'Savings','Miami',4000.00);
SELECT MAX(balance) FROM accounts WHERE account_type = 'Checking' AND branch = 'Miami';
What was the total sales revenue for the top 3 drugs in 2020?
CREATE SCHEMA sales;CREATE TABLE sales.drugs (id INT,name VARCHAR(50));CREATE TABLE sales.sales_data (drug_id INT,year INT,revenue DECIMAL(10,2)); INSERT INTO sales.drugs (id,name) VALUES (1,'DrugA'),(2,'DrugB'),(3,'DrugC'),(4,'DrugD'); INSERT INTO sales.sales_data (drug_id,year,revenue) VALUES (1,2020,12000000),(1,2019,11000000),(2,2020,15000000),(2,2019,13000000),(3,2020,10000000),(3,2019,9000000),(4,2020,8000000),(4,2019,7000000);
SELECT d.name, SUM(sd.revenue) FROM sales.sales_data sd JOIN sales.drugs d ON sd.drug_id = d.id WHERE sd.year = 2020 GROUP BY d.name ORDER BY SUM(sd.revenue) DESC LIMIT 3;
Find the difference in the number of public universities between New York and Texas.
CREATE TABLE universities (name VARCHAR(255),state VARCHAR(255)); INSERT INTO universities (name,state) VALUES ('University1','New York'),('University2','New York'),('University3','Texas');
SELECT (SELECT COUNT(*) FROM universities WHERE state = 'New York') - (SELECT COUNT(*) FROM universities WHERE state = 'Texas');
Who are the attorneys with cases in New York?
CREATE TABLE cases (id INT,attorney_id INT,state VARCHAR(2)); INSERT INTO cases (id,attorney_id,state) VALUES (1,1001,'NY'),(2,1001,'CA'),(3,1002,'TX'); CREATE TABLE attorneys (id INT,name VARCHAR(50)); INSERT INTO attorneys (id,name) VALUES (1001,'John Doe'),(1002,'Jane Smith');
SELECT a.name FROM attorneys a INNER JOIN cases c ON a.id = c.attorney_id WHERE c.state = 'NY';
Display the total network investments made in 'rural' areas for mobile and broadband networks separately, and the difference between the two.
CREATE TABLE MobileInvestments (Area varchar(10),Investment int,Service varchar(10)); CREATE TABLE BroadbandInvestments (Area varchar(10),Investment int,Service varchar(10)); INSERT INTO MobileInvestments (Area,Investment,Service) VALUES ('North',100000,'mobile'),('South',120000,'mobile'),('rural',85000,'mobile'),('East',75000,'mobile'); INSERT INTO BroadbandInvestments (Area,Investment,Service) VALUES ('North',90000,'broadband'),('South',110000,'broadband'),('rural',90000,'broadband'),('East',80000,'broadband');
SELECT SUM(CASE WHEN Area = 'rural' AND Service = 'mobile' THEN Investment ELSE 0 END) AS RuralMobile, SUM(CASE WHEN Area = 'rural' AND Service = 'broadband' THEN Investment ELSE 0 END) AS RuralBroadband, RuralMobile - RuralBroadband AS InvestmentDifference FROM MobileInvestments MI JOIN BroadbandInvestments BI ON 1=1 WHERE MI.Service = BI.Service;
Update the budget allocation for public transportation services in urban areas by 10%.
CREATE TABLE transportation (area VARCHAR(20),service_type VARCHAR(50),budget_allocation FLOAT); INSERT INTO transportation (area,service_type,budget_allocation) VALUES ('urban','public_transportation',2000000),('rural','public_transportation',1500000);
UPDATE transportation SET budget_allocation = budget_allocation * 1.1 WHERE area = 'urban' AND service_type = 'public_transportation';
What is the percentage of female faculty members in the School of Business?
CREATE TABLE faculty_members (id INT,faculty_name VARCHAR(50),faculty_department VARCHAR(50),faculty_gender VARCHAR(10)); INSERT INTO faculty_members (id,faculty_name,faculty_department,faculty_gender) VALUES (1,'Jane Smith','Management','Female'),(2,'John Doe','Marketing','Male'),(3,'Bob Johnson','Finance','Male'),(4,'Sara Davis','Accounting','Female'),(5,'Mike Brown','Economics','Male');
SELECT (COUNT(*) FILTER (WHERE faculty_gender = 'Female')) * 100.0 / COUNT(*) FROM faculty_members WHERE faculty_department LIKE '%Business%';
List eSports teams with the highest number of players
CREATE TABLE teams (id INT,region VARCHAR(10),players INT); INSERT INTO teams (id,region,players) VALUES (1,'Europe',50); INSERT INTO teams (id,region,players) VALUES (2,'Asia',75); INSERT INTO teams (id,region,players) VALUES (3,'America',100);
SELECT id, region, players FROM teams ORDER BY players DESC LIMIT 1;
What is the total number of emergency calls in each neighborhood?
CREATE TABLE neighborhoods (name VARCHAR(255),zip_code VARCHAR(10)); INSERT INTO neighborhoods (name,zip_code) VALUES ('Central Park','10022'),('Harlem','10026'),('Brooklyn Heights','11201'); CREATE TABLE emergency_calls (id INT,neighborhood VARCHAR(255),call_time TIMESTAMP); INSERT INTO emergency_calls (id,neighborhood,call_time) VALUES (1,'Central Park','2022-01-01 12:00:00'),(2,'Harlem','2022-01-02 13:00:00'),(3,'Brooklyn Heights','2022-01-03 14:00:00');
SELECT neighborhood, COUNT(*) as total_calls FROM emergency_calls GROUP BY neighborhood;
Update the name of the satellite with ID 456 to "Hubble".
CREATE TABLE satellites (id INT,name VARCHAR(255),country_of_origin VARCHAR(255),avg_distance FLOAT);
UPDATE satellites SET name = 'Hubble' WHERE id = 456;
List the names of all non-profits and the number of capacity building activities they have conducted in the last year.
CREATE TABLE non_profit (id INT,name TEXT); INSERT INTO non_profit (id,name) VALUES (1,'Habitat for Humanity'),(2,'American Red Cross'),(3,'Doctors Without Borders'); CREATE TABLE capacity_building (id INT,non_profit_id INT,activity_date DATE); INSERT INTO capacity_building (id,non_profit_id,activity_date) VALUES (1,3,'2021-05-12'),(2,1,'2022-03-15'),(3,2,'2021-12-28'),(4,1,'2020-08-07'),(5,3,'2021-01-02');
SELECT n.name, COUNT(cb.id) as num_activities FROM non_profit n INNER JOIN capacity_building cb ON n.id = cb.non_profit_id WHERE cb.activity_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR) GROUP BY n.id;
How many animal species inhabit the forests in the 'wildlife' table?
CREATE TABLE wildlife (id INT,forest_id INT,species VARCHAR(50));
SELECT COUNT(DISTINCT species) FROM wildlife;
What is the total number of military innovation projects in the Americas that have a budget over $10 million?
CREATE TABLE Military_Innovation (Nation VARCHAR(50),Continent VARCHAR(50),Project VARCHAR(50),Budget DECIMAL(10,2)); INSERT INTO Military_Innovation (Nation,Continent,Project,Budget) VALUES ('USA','Americas','Stealth Drone Project',15000000.00),('Brazil','Americas','Cyber Defense System',12000000.00);
SELECT SUM(Budget) FROM Military_Innovation WHERE Continent = 'Americas' AND Budget > 10000000;
What is the maximum number of refugees supported by a single refugee support project in South America?
CREATE TABLE projects (id INT,name TEXT,category TEXT,location TEXT,num_refugees INT,start_date DATE,end_date DATE); INSERT INTO projects (id,name,category,location,num_refugees,start_date,end_date) VALUES (1,'Refugee Support Project','Refugee','South America',150,'2019-01-01','2019-12-31'),(2,'Disaster Relief Project','Disaster','Asia',50,'2019-01-01','2020-12-31'),(3,'Community Development Project','Community','Africa',200,'2018-01-01','2018-12-31');
SELECT MAX(num_refugees) FROM projects WHERE category = 'Refugee' AND location = 'South America';
What is the release date of the earliest song by artists who have released songs on both the 'indie_platform' and 'mainstream_platform' platforms?
CREATE TABLE artist (artist_id INT,artist_name VARCHAR(50)); INSERT INTO artist (artist_id,artist_name) VALUES (1,'Artist A'),(2,'Artist B'); CREATE TABLE song (song_id INT,song_name VARCHAR(50),artist_id INT,platform VARCHAR(20),release_date DATE); INSERT INTO song (song_id,song_name,artist_id,platform,release_date) VALUES (1,'Song 1',1,'indie_platform','2020-01-01'),(2,'Song 2',2,'mainstream_platform','2019-01-01'),(3,'Song 3',1,'mainstream_platform','2021-01-01');
SELECT MIN(s.release_date) FROM song s JOIN (SELECT artist_id FROM song WHERE platform = 'indie_platform' INTERSECT SELECT artist_id FROM song WHERE platform = 'mainstream_platform') sub ON s.artist_id = sub.artist_id;
Which donors have donated the most in the last 6 months?
CREATE TABLE Donations (DonorID INT,DonationDate DATE,DonationAmount DECIMAL(10,2)); CREATE TABLE Donors (DonorID INT,DonorName VARCHAR(50));
SELECT d.DonorName, SUM(d.DonationAmount) FROM Donations d JOIN Donors don ON d.DonorID = don.DonorID WHERE d.DonationDate >= DATEADD(month, -6, GETDATE()) GROUP BY d.DonorID, don.DonorName ORDER BY SUM(d.DonationAmount) DESC;
What is the minimum sale price for properties in each borough?
CREATE TABLE Boroughs (BoroughID INT,BoroughName VARCHAR(255)); CREATE TABLE Properties (PropertyID INT,BoroughID INT,SalePrice DECIMAL(10,2));
SELECT B.BoroughName, MIN(P.SalePrice) as MinSalePrice FROM Boroughs B JOIN Properties P ON B.BoroughID = P.BoroughID GROUP BY B.BoroughName;
How many vessels were involved in maritime safety incidents in the Atlantic Ocean in 2018?
CREATE TABLE maritime_safety_incidents (id INT,vessels INT,year INT,region VARCHAR(255)); INSERT INTO maritime_safety_incidents (id,vessels,year,region) VALUES (1,3,2018,'Atlantic'); INSERT INTO maritime_safety_incidents (id,vessels,year,region) VALUES (2,5,2018,'Atlantic');
SELECT SUM(vessels) FROM maritime_safety_incidents WHERE region = 'Atlantic' AND year = 2018;
What is the maximum fare collected on a single day?
CREATE TABLE daily_fare_collection (collection_id INT,collection_date DATE,fare_amount DECIMAL); INSERT INTO daily_fare_collection (collection_id,collection_date,fare_amount) VALUES (1,'2023-03-01',12000.00),(2,'2023-03-02',15000.00),(3,'2023-03-03',11000.00);
SELECT collection_date, MAX(fare_amount) AS max_daily_fare FROM daily_fare_collection GROUP BY collection_date;
What is the life expectancy in Southeast Asian countries in 2022?
CREATE TABLE LifeExpectancy (Country VARCHAR(50),Continent VARCHAR(50),Year INT,LifeExp DECIMAL(3,1)); INSERT INTO LifeExpectancy (Country,Continent,Year,LifeExp) VALUES ('Thailand','Southeast Asia',2022,76.7),('Vietnam','Southeast Asia',2022,75.9),('Cambodia','Southeast Asia',2022,70.6);
SELECT LifeExp FROM LifeExpectancy WHERE Continent = 'Southeast Asia' AND Year = 2022;
List all teachers who have led a professional development workshop in the 'teacher_development' schema
CREATE SCHEMA teacher_development; CREATE TABLE teacher_development.workshops (workshop_id INT,teacher_id INT); CREATE TABLE teacher_development.teachers (teacher_id INT,name VARCHAR(50)); INSERT INTO teacher_development.teachers (teacher_id,name) VALUES (1001,'Alice Johnson'),(1002,'Bob Williams'); INSERT INTO teacher_development.workshops (workshop_id,teacher_id) VALUES (201,1001),(202,1002),(203,1001);
SELECT name FROM teacher_development.teachers WHERE teacher_id IN (SELECT teacher_id FROM teacher_development.workshops);
What is the minimum cargo weight and the number of voyages for vessels with 'OOCL' prefix in the Atlantic Ocean in 2018?
CREATE TABLE Vessels (ID INT,Name TEXT,Cargo_Weight INT,Voyages INT,Prefix TEXT,Year INT);CREATE VIEW Atlantic_Ocean_Vessels AS SELECT * FROM Vessels WHERE Region = 'Atlantic Ocean';
SELECT MIN(Cargo_Weight), SUM(Voyages) FROM Atlantic_Ocean_Vessels WHERE Prefix = 'OOCL' AND Year = 2018;
What is the total volume of timber harvested in each country in 2020, sorted in descending order by total volume?
CREATE TABLE forests (id INT,country VARCHAR(50),year INT,volume FLOAT); INSERT INTO forests (id,country,year,volume) VALUES (1,'Canada',2020,50.5),(2,'USA',2020,40.3),(3,'China',2020,35.7),(4,'Russia',2020,30.1);
SELECT country, SUM(volume) AS total_volume FROM forests WHERE year = 2020 GROUP BY country ORDER BY total_volume DESC;
What is the number of containers loaded and unloaded at port 'LA' in the 'port_operations' table?
CREATE TABLE port_operations (id INT,port VARCHAR(50),operation_type VARCHAR(50),container_count INT); INSERT INTO port_operations (id,port,operation_type,container_count) VALUES (1,'LA','Load',200),(2,'LA','Unload',150),(3,'NY','Load',300),(4,'NY','Unload',250);
SELECT SUM(container_count) FROM port_operations WHERE port = 'LA';
What is the average age of female soccer players in the WPSL?
CREATE TABLE players (id INT,name VARCHAR(50),age INT,gender VARCHAR(10),sport VARCHAR(20));INSERT INTO players (id,name,age,gender,sport) VALUES (1,'Alice',25,'Female','Soccer'); INSERT INTO players (id,name,age,gender,sport) VALUES (2,'Bella',30,'Female','Soccer');
SELECT AVG(age) FROM players WHERE gender = 'Female' AND sport = 'Soccer';
List all companies that have a female founder and have raised a Series A round
CREATE TABLE company_founding(id INT PRIMARY KEY,company_name VARCHAR(100),founder_gender VARCHAR(10)); CREATE TABLE investment_rounds(id INT PRIMARY KEY,company_id INT,round_type VARCHAR(50),funding_amount INT); INSERT INTO company_founding VALUES (1,'Acme Inc','Female'); INSERT INTO company_founding VALUES (2,'Beta Corp','Male'); INSERT INTO company_founding VALUES (3,'Charlie LLC','Female'); INSERT INTO investment_rounds VALUES (1,1,'Seed',100000); INSERT INTO investment_rounds VALUES (2,1,'Series A',2000000); INSERT INTO investment_rounds VALUES (3,3,'Series B',5000000); INSERT INTO investment_rounds VALUES (4,3,'Series A',3000000);
SELECT cf.company_name FROM company_founding cf INNER JOIN investment_rounds ir ON cf.id = ir.company_id WHERE ir.round_type = 'Series A' AND cf.founder_gender = 'Female';
What is the total number of open civic data sets in 'city' and 'state' schemas?
CREATE SCHEMA city; CREATE SCHEMA state; CREATE TABLE city.civic_data (id INT,name VARCHAR(255),is_open BOOLEAN); CREATE TABLE state.civic_data (id INT,name VARCHAR(255),is_open BOOLEAN); INSERT INTO city.civic_data (id,name,is_open) VALUES (1,'traffic',true),(2,'crime',false); INSERT INTO state.civic_data (id,name,is_open) VALUES (1,'education',true),(2,'healthcare',true);
SELECT COUNT(*) FROM ( (SELECT * FROM city.civic_data WHERE is_open = true) UNION (SELECT * FROM state.civic_data WHERE is_open = true) ) AS combined_civic_data;
How many primary school children visited the museum last year from France?
CREATE TABLE museum_visitors (id INT,age INT,country VARCHAR(255)); INSERT INTO museum_visitors (id,age,country) VALUES (1,8,'France'),(2,10,'Germany'),(3,6,'France');
SELECT COUNT(*) FROM museum_visitors WHERE age BETWEEN 6 AND 11 AND country = 'France';
What is the average gross tonnage of vessels per port, ordered by the highest average?
CREATE TABLE Port (PortID INT,PortName VARCHAR(100),City VARCHAR(100),Country VARCHAR(100)); INSERT INTO Port (PortID,PortName,City,Country) VALUES (1,'Port of Los Angeles','Los Angeles','USA'); INSERT INTO Port (PortID,PortName,City,Country) VALUES (2,'Port of Rotterdam','Rotterdam','Netherlands'); CREATE TABLE Vessel (VesselID INT,VesselName VARCHAR(100),PortID INT,LOA DECIMAL(5,2),GrossTonnage DECIMAL(5,2)); INSERT INTO Vessel (VesselID,VesselName,PortID,LOA,GrossTonnage) VALUES (1,'Ever Given',1,400.00,220000.00); INSERT INTO Vessel (VesselID,VesselName,PortID,LOA,GrossTonnage) VALUES (2,'MSC Zoe',2,399.99,199672.00);
SELECT PortID, AVG(GrossTonnage) OVER(PARTITION BY PortID ORDER BY PortID) AS AvgGT FROM Vessel ORDER BY AvgGT DESC
List all spacecraft with manufacturing country and launch date.
CREATE TABLE spacecraft (spacecraft_id INT,name VARCHAR(50),manufacturing_country VARCHAR(50),launch_date DATE);
SELECT name, manufacturing_country, launch_date FROM spacecraft;
Identify the defense contracts awarded to companies located in New York and New Jersey with an amount between $250,000 and $750,000, and their respective award dates.
CREATE TABLE defense_contracts(id INT,company VARCHAR(50),amount INT,award_date DATE);
SELECT company, amount, award_date FROM defense_contracts WHERE state IN ('New York', 'New Jersey') AND amount BETWEEN 250000 AND 750000;
What is the average number of points scored per game by each basketball player in the last season?
CREATE TABLE games (id INT,game_date DATE,team VARCHAR(20)); CREATE TABLE points (id INT,game_id INT,player VARCHAR(20),points INT);
SELECT team, player, AVG(points) FROM points JOIN games ON points.game_id = games.id WHERE games.game_date >= DATE_SUB(CURDATE(), INTERVAL 1 YEAR) AND games.team = 'Boston Celtics' GROUP BY team, player;
Which military vehicles have the highest and lowest average price by manufacturer?
CREATE TABLE VehiclePrices (id INT PRIMARY KEY,manufacturer VARCHAR(50),vehicle_type VARCHAR(50),price DECIMAL(10,2)); INSERT INTO VehiclePrices (id,manufacturer,vehicle_type,price) VALUES (1,'Lockheed Martin','F-35 Fighter Jet',100000000.00),(2,'General Dynamics','M1 Abrams Tank',8000000.00),(3,'Boeing','V-22 Osprey',70000000.00);
SELECT manufacturer, vehicle_type, MAX(price) as max_price, MIN(price) as min_price FROM VehiclePrices GROUP BY manufacturer;
Find the average price of non-GMO items in the inventory.
CREATE TABLE Inventory(item_id INT,item_name VARCHAR(50),is_non_gmo BOOLEAN,price DECIMAL(5,2)); INSERT INTO Inventory VALUES(1,'Apples',TRUE,0.99),(2,'Bananas',TRUE,1.49),(3,'Corn',FALSE,1.25);
SELECT AVG(price) FROM Inventory WHERE is_non_gmo = TRUE;
Which authors have published the most articles in a specific language?
CREATE TABLE articles (author VARCHAR(50),article_language VARCHAR(50),article_title VARCHAR(100),publication_date DATE); INSERT INTO articles (author,article_language,article_title,publication_date) VALUES ('Sofia Garcia','Spanish','Article 1','2021-01-01'); INSERT INTO articles (author,article_language,article_title,publication_date) VALUES ('Carlos Lopez','Spanish','Article 2','2021-01-02'); INSERT INTO articles (author,article_language,article_title,publication_date) VALUES ('John Doe','English','Article 3','2021-01-03');
SELECT author, COUNT(*) as article_count FROM articles WHERE article_language = 'Spanish' GROUP BY author ORDER BY article_count DESC;
What is the total value of artwork for each artist?
CREATE TABLE Artists (ArtistID INT,Name VARCHAR(100),Nationality VARCHAR(50)); INSERT INTO Artists VALUES (1,'Pablo Picasso','Spanish'); INSERT INTO Artists VALUES (2,'Henri Matisse','French'); CREATE TABLE Artwork (ArtworkID INT,Title VARCHAR(100),Type VARCHAR(50),Price FLOAT,ArtistID INT); INSERT INTO Artwork VALUES (1,'Guernica','Painting',2000000,1); INSERT INTO Artwork VALUES (2,'The Dance','Painting',1500000,2); INSERT INTO Artwork VALUES (3,'Three Musicians','Painting',1000000,1);
SELECT AR.Name, SUM(A.Price) FROM Artwork A JOIN Artists AR ON A.ArtistID = AR.ArtistID GROUP BY AR.Name;
How many socially responsible loans were issued by region in the country in 2021?
CREATE TABLE socially_responsible_loans_2021 (region TEXT,num_loans INTEGER,loan_date DATE); INSERT INTO socially_responsible_loans_2021 (region,num_loans,loan_date) VALUES ('North',200,'2021-04-01'),('South',300,'2021-02-15'),('East',150,'2021-06-20');
SELECT region, SUM(num_loans) FROM socially_responsible_loans_2021 GROUP BY region;
What is the total number of goals scored by Messi and Ronaldo in their club careers?
CREATE TABLE careers (player VARCHAR(100),team VARCHAR(100),goals INT); INSERT INTO careers (player,team,goals) VALUES ('Lionel Messi','Barcelona',672),('Cristiano Ronaldo','Real Madrid',450);
SELECT SUM(goals) FROM careers WHERE player IN ('Lionel Messi', 'Cristiano Ronaldo');
What is the average age of healthcare workers by location in the "healthcare_workers" table?
CREATE TABLE healthcare_workers (id INT,name VARCHAR(50),age INT,gender VARCHAR(10),location VARCHAR(50)); INSERT INTO healthcare_workers (id,name,age,gender,location) VALUES (1,'John Doe',35,'Male','New York'); INSERT INTO healthcare_workers (id,name,age,gender,location) VALUES (2,'Jane Smith',32,'Female','California');
SELECT location, AVG(age) FROM healthcare_workers GROUP BY location;
How many sustainable materials have been used in production since 2020?
CREATE TABLE materials (material_id INT,material_sustainable BOOLEAN,material_purchase_date DATE);
SELECT COUNT(*) AS sustainable_material_count FROM materials WHERE material_sustainable = TRUE AND material_purchase_date >= '2020-01-01'
What is the average water consumption per capita in the cities of Lima and Santiago for the year 2020?
CREATE TABLE south_america_population (id INT,city VARCHAR(50),population INT,year INT); INSERT INTO south_america_population (id,city,population,year) VALUES (1,'Lima',10000000,2020); INSERT INTO south_america_population (id,city,population,year) VALUES (2,'Santiago',8000000,2020); CREATE TABLE south_america_water_consumption (id INT,city VARCHAR(50),water_consumption FLOAT,year INT); INSERT INTO south_america_water_consumption (id,city,water_consumption,year) VALUES (1,'Lima',500000000,2020); INSERT INTO south_america_water_consumption (id,city,water_consumption,year) VALUES (2,'Santiago',400000000,2020);
SELECT AVG(sawc.water_consumption / sap.population) FROM south_america_water_consumption sawc INNER JOIN south_america_population sap ON sawc.city = sap.city WHERE sawc.year = 2020;
Show the average gas content for all reservoirs in field 'F-01'
CREATE TABLE reservoirs (reservoir_id INT,reservoir_name VARCHAR(255),field_name VARCHAR(255),oil_grade VARCHAR(255),gas_content FLOAT);
SELECT AVG(gas_content) FROM reservoirs WHERE field_name = 'F-01';
Display the number of employees and total salary expenses for companies with more than 50 employees in the manufacturing industry.
CREATE TABLE companies (company_id INT,name TEXT,industry TEXT,num_employees INT); INSERT INTO companies (company_id,name,industry,num_employees) VALUES (1,'GreenTech','Manufacturing',75),(2,'EcoPlants','Manufacturing',35),(3,'BlueFactory','Retail',200),(4,'GreenBuild','Manufacturing',60); CREATE TABLE salaries (employee_id INT,company_id INT,salary INT); INSERT INTO salaries (employee_id,company_id,salary) VALUES (1,1,5000),(2,1,5500),(3,1,6000),(4,2,4000),(5,2,4500),(6,3,7000),(7,3,7500),(8,4,5000),(9,4,5500),(10,4,6000);
SELECT c.name, SUM(s.salary) AS total_salary_expense FROM companies c INNER JOIN salaries s ON c.company_id = s.company_id WHERE c.industry = 'Manufacturing' GROUP BY c.company_id HAVING COUNT(s.employee_id) > 50;
Count of active platforms in the South China Sea.
CREATE TABLE platforms (id INT,location VARCHAR(50),status VARCHAR(50)); INSERT INTO platforms (id,location,status) VALUES (1,'South China Sea','Active');
SELECT COUNT(*) FROM platforms WHERE location = 'South China Sea' AND status = 'Active';
Find the percentage of people who identify as LGBTQ+ in each county, ordered from the highest to lowest?
CREATE TABLE lgbtq_data (id INT,county TEXT,lgbtq INT,population INT); INSERT INTO lgbtq_data (id,county,lgbtq,population) VALUES (1,'County A',200,10000),(2,'County B',300,20000);
SELECT county, (SUM(lgbtq) OVER (PARTITION BY county)) * 100.0 / SUM(population) OVER (PARTITION BY county) as pct_lgbtq FROM lgbtq_data ORDER BY pct_lgbtq DESC;
Which states have the highest and lowest average mental health scores for teachers?
CREATE TABLE teacher_mental_health (teacher_id INT,state VARCHAR(50),score INT); INSERT INTO teacher_mental_health (teacher_id,state,score) VALUES (1,'California',75),(2,'Texas',80),(3,'California',70);
SELECT state, AVG(score) as avg_score FROM teacher_mental_health GROUP BY state ORDER BY avg_score DESC LIMIT 1;
Find the top 3 states with the highest number of rural hospitals.
CREATE TABLE hospitals (id INT,state CHAR(2),num_beds INT,rural_hospital BOOLEAN); INSERT INTO hospitals (id,state,num_beds,rural_hospital) VALUES (1,'TX',50,true),(2,'CA',100,false);
SELECT state, ROW_NUMBER() OVER (ORDER BY COUNT(*) DESC) as rank FROM hospitals WHERE rural_hospital = true GROUP BY state LIMIT 3;
Which sports have the highest average ticket sales and the lowest average ticket sales?
CREATE TABLE ticket_sales_data (sport VARCHAR(20),ticket_sales INT);
SELECT sport, AVG(ticket_sales) AS avg_sales FROM ticket_sales_data GROUP BY sport ORDER BY avg_sales DESC, sport LIMIT 2; SELECT sport, AVG(ticket_sales) AS avg_sales FROM ticket_sales_data GROUP BY sport ORDER BY avg_sales ASC, sport LIMIT 1;
What is the total preference score for each product in the Europe region?
CREATE TABLE consumer_preferences (id INT,consumer_id INT,product_id INT,preference_score INT,country VARCHAR(50)); INSERT INTO consumer_preferences (id,consumer_id,product_id,preference_score,country) VALUES (1,1,101,8,'Asia-Pacific'),(2,2,102,9,'Asia-Pacific'),(3,3,101,7,'Asia-Pacific'),(4,4,103,10,'Asia-Pacific'),(5,5,102,8,'Asia-Pacific'),(6,6,101,9,'Europe'),(7,7,102,8,'Europe'),(8,8,103,7,'Europe');
SELECT product_id, SUM(preference_score) as total_score FROM consumer_preferences WHERE country = 'Europe' GROUP BY product_id;
Update the number of beds to 75 in the record with the name 'Eureka Community Hospital' in the 'rural_hospitals' table
CREATE TABLE rural_hospitals (id INT,name VARCHAR(50),beds INT,location VARCHAR(50));
UPDATE rural_hospitals SET beds = 75 WHERE name = 'Eureka Community Hospital';
What is the distribution of financial literacy scores for customers in Texas?
CREATE TABLE customers (customer_id INT,name VARCHAR(255),state VARCHAR(255),financial_literacy_score INT);
SELECT state, COUNT(*) as count, MIN(financial_literacy_score) as min_score, AVG(financial_literacy_score) as avg_score, MAX(financial_literacy_score) as max_score FROM customers WHERE state = 'Texas' GROUP BY state;
How many esports events have been held in each country, and what is the maximum number of events held in a country?
CREATE TABLE EsportsEvents (id INT,name VARCHAR(50),country VARCHAR(50),num_events INT); INSERT INTO EsportsEvents (id,name,country,num_events) VALUES (1,'Event1','USA',2),(2,'Event2','Canada',3),(3,'Event3','USA',5);
SELECT country, COUNT(*) AS num_events, MAX(num_events) AS max_events_per_country FROM EsportsEvents GROUP BY country;
What is the average heart rate for users with a 'standard' membership type during their strength training workouts?
CREATE TABLE memberships (user_id INT,membership_type VARCHAR(10)); CREATE TABLE workouts (workout_id INT,user_id INT,workout_type VARCHAR(20),heart_rate INT);
SELECT AVG(heart_rate) FROM workouts JOIN memberships ON workouts.user_id = memberships.user_id WHERE memberships.membership_type = 'standard' AND workout_type = 'strength training';
Delete all posts from users who have a privacy setting of 'low'
CREATE TABLE posts (id INT,user_id INT,post_text TEXT); CREATE TABLE users (id INT,privacy_setting VARCHAR(20)); INSERT INTO users (id,privacy_setting) VALUES (1,'medium'),(2,'high'),(3,'low'); INSERT INTO posts (id,user_id,post_text) VALUES (1,1,'Hello World!'),(2,2,'Goodbye World!'),(3,3,'This is a private post.');
DELETE t1 FROM posts t1 JOIN users t2 ON t1.user_id = t2.id WHERE t2.privacy_setting = 'low';
Add a new social enterprise in the 'Housing' category with an ESG rating of 9.0 and a risk score of 1.8
CREATE TABLE social_enterprises (id INT,category TEXT,ESG_rating FLOAT,risk_score FLOAT);
INSERT INTO social_enterprises (id, category, ESG_rating, risk_score) VALUES (7, 'Housing', 9.0, 1.8);
Update the gender of a player with a given ID
CREATE TABLE Players (PlayerID INT PRIMARY KEY,Name VARCHAR(50),Age INT,Gender VARCHAR(10)); INSERT INTO Players (PlayerID,Name,Age,Gender) VALUES (1,'John Doe',25,'Male'); INSERT INTO Players (PlayerID,Name,Age,Gender) VALUES (2,'Jane Doe',30,'Female');
UPDATE Players SET Gender = 'Non-binary' WHERE PlayerID = 1;
What is the total billing amount for cases handled by attorneys named 'John Smith'?
CREATE TABLE attorneys (attorney_id INT,name TEXT); INSERT INTO attorneys (attorney_id,name) VALUES (1,'John Smith'),(2,'Jane Smith'),(3,'Bob Johnson'); CREATE TABLE cases (case_id INT,attorney_id INT,billing_amount INT); INSERT INTO cases (case_id,attorney_id,billing_amount) VALUES (1,1,5000),(2,1,7000),(3,2,6000);
SELECT SUM(billing_amount) FROM cases WHERE attorney_id IN (SELECT attorney_id FROM attorneys WHERE name = 'John Smith')
Find the intersection of open data sets related to diversity in 'state', 'county', and 'city' schemas.
CREATE SCHEMA state; CREATE SCHEMA county; CREATE SCHEMA city; CREATE TABLE state.diversity_data (id INT,name VARCHAR(255),is_open BOOLEAN); CREATE TABLE county.diversity_data (id INT,name VARCHAR(255),is_open BOOLEAN); CREATE TABLE city.diversity_data (id INT,name VARCHAR(255),is_open BOOLEAN); INSERT INTO state.diversity_data (id,name,is_open) VALUES (1,'population',true),(2,'workforce',true); INSERT INTO county.diversity_data (id,name,is_open) VALUES (1,'population',true),(2,'workforce',true); INSERT INTO city.diversity_data (id,name,is_open) VALUES (1,'population',true),(2,'workforce',true),(3,'elected_officials',true);
SELECT * FROM ( (SELECT * FROM state.diversity_data WHERE is_open = true) INTERSECT (SELECT * FROM county.diversity_data WHERE is_open = true) INTERSECT (SELECT * FROM city.diversity_data WHERE is_open = true) ) AS intersected_data;
How many marine species are present in each ocean basin?
CREATE TABLE marine_species (id INT,species_name TEXT,ocean_basin TEXT);
SELECT species_name, ocean_basin, COUNT(*) FROM marine_species GROUP BY ocean_basin;
What was the total military spending by NATO countries in 2020?
CREATE SCHEMA if not exists military_spending;CREATE TABLE if not exists military_spending_data(country text,military_spending integer,year integer);INSERT INTO military_spending_data(country,military_spending,year) VALUES('United States',732,2020),('United Kingdom',60,2020),('France',50,2020),('Germany',45,2020),('Italy',25,2020),('Canada',22,2020);
SELECT SUM(military_spending) FROM military_spending_data WHERE country IN ('United States', 'United Kingdom', 'France', 'Germany', 'Italy', 'Canada') AND year = 2020;
Insert a new row in the smart_contracts table with name 'Sushiswap' if it doesn't exist.
CREATE TABLE if not exists smart_contracts (id INT PRIMARY KEY,name TEXT,language TEXT,version TEXT); INSERT INTO smart_contracts (id,name,language,version) VALUES (1,'CryptoKitties','Solidity','0.4.24');
INSERT INTO smart_contracts (name, language, version) SELECT 'Sushiswap', 'Vyper', '0.3.0' WHERE NOT EXISTS (SELECT * FROM smart_contracts WHERE name = 'Sushiswap');
How many socially responsible loans were issued by financial institutions in Europe?
CREATE TABLE financial_institutions (institution_id INT,institution_name TEXT); INSERT INTO financial_institutions (institution_id,institution_name) VALUES (1,'GreenBank Europe'),(2,'FairFinance Europe'),(3,'EthicalBank Europe'); CREATE TABLE loans (loan_id INT,institution_id INT,loan_type TEXT); INSERT INTO loans (loan_id,institution_id,loan_type) VALUES (1,1,'socially responsible'),(2,1,'conventional'),(3,2,'socially responsible'),(4,2,'socially responsible'),(5,3,'conventional');
SELECT COUNT(*) FROM loans WHERE loan_type = 'socially responsible' AND institution_id IN (SELECT institution_id FROM financial_institutions WHERE institution_name LIKE '%Europe%');
Determine the percentage of female and male faculty members in the College of Business and Management, for each rank, and order the results by rank.
CREATE TABLE FacultyDemographics (id INT,name VARCHAR(255),rank VARCHAR(255),department VARCHAR(255),gender VARCHAR(10));
SELECT rank, gender, COUNT(*) as count, ROUND(COUNT(*) * 100.0 / SUM(COUNT(*)) OVER (PARTITION BY rank), 2) as percentage FROM FacultyDemographics WHERE department LIKE 'Business%' GROUP BY rank, gender ORDER BY rank;
List producers with a production volume greater than 1500
CREATE TABLE producers (id INT PRIMARY KEY,name VARCHAR(255),location VARCHAR(255),production_volume INT);
SELECT name FROM producers WHERE production_volume > (SELECT 1500);
Calculate the number of transactions and total revenue from Dysprosium sales by each supplier in Asia, for 2019.
CREATE TABLE transactions (id INT,supplier VARCHAR(50),Dysprosium_sold FLOAT,revenue FLOAT,datetime DATETIME); INSERT INTO transactions (id,supplier,Dysprosium_sold,revenue,datetime) VALUES (1,'China National Nuke',150.0,2500.0,'2019-01-01 10:00:00'),(2,'Korea Resource',200.0,3000.0,'2019-01-15 14:30:00');
SELECT supplier, COUNT(DISTINCT id) AS transactions, SUM(revenue) AS total_revenue FROM transactions WHERE YEAR(datetime) = 2019 AND supplier LIKE 'Asia%' GROUP BY supplier;
What are the production figures for the 'Girassol' field for the year 2019?
CREATE TABLE field_production (field VARCHAR(50),year INT,oil_production FLOAT,gas_production FLOAT); INSERT INTO field_production (field,year,oil_production,gas_production) VALUES ('Girassol',2019,1234.5,678.9);
SELECT year, oil_production, gas_production FROM field_production WHERE field = 'Girassol';
What is the average age of attendees who attended 'Theater for All' and 'Music for Everyone' events?
CREATE TABLE EventAttendance (event_name VARCHAR(255),attendee_age INT,attendee_gender VARCHAR(50)); INSERT INTO EventAttendance (event_name,attendee_age,attendee_gender) VALUES ('Theater for All',30,'Male'),('Theater for All',40,'Female'),('Theater for All',45,'Non-binary'),('Music for Everyone',22,'Male'),('Music for Everyone',27,'Female'),('Music for Everyone',32,'Non-binary');
SELECT AVG(attendee_age) FROM EventAttendance WHERE event_name IN ('Theater for All', 'Music for Everyone');
Which community development initiatives have the lowest and highest economic diversification impact?
CREATE TABLE initiative (id INT,name TEXT,location TEXT,economic_diversification_impact INT); INSERT INTO initiative (id,name,location,economic_diversification_impact) VALUES (1,'Handicraft Training','Bangladesh',50),(2,'Agricultural Training','Pakistan',70),(3,'IT Training','Nepal',90),(4,'Fishery Training','Sri Lanka',60);
SELECT name, economic_diversification_impact FROM (SELECT name, economic_diversification_impact, RANK() OVER (ORDER BY economic_diversification_impact ASC) as low_rank, RANK() OVER (ORDER BY economic_diversification_impact DESC) as high_rank FROM initiative) sub WHERE low_rank = 1 OR high_rank = 1;
What are the details of projects that have received funding for climate change mitigation in Brazil?
CREATE TABLE climate_mitigation_projects (id INT,name VARCHAR(255),location VARCHAR(255),funding FLOAT); INSERT INTO climate_mitigation_projects (id,name,location,funding) VALUES (1,'Project A','Brazil',5000000);
SELECT * FROM climate_mitigation_projects WHERE location = 'Brazil';
Delete the energy storage system with id 4 if it exists.
CREATE TABLE energy_storage (id INT,name TEXT,capacity FLOAT,region TEXT); INSERT INTO energy_storage (id,name,capacity,region) VALUES (4,'GHI Battery',4000,'East');
DELETE FROM energy_storage WHERE id = 4;
List the top 5 socially responsible lenders in the US by total loans issued?
CREATE TABLE socially_responsible_lending (lender_name TEXT,total_loans_issued NUMERIC,country TEXT); INSERT INTO socially_responsible_lending (lender_name,total_loans_issued,country) VALUES ('Amalgamated Bank',3456,'USA'); INSERT INTO socially_responsible_lending (lender_name,total_loans_issued,country) VALUES ('Beneficial State Bank',2678,'USA');
SELECT lender_name, total_loans_issued FROM socially_responsible_lending WHERE country = 'USA' ORDER BY total_loans_issued DESC LIMIT 5;
What is the minimum flight hours for aircrafts manufactured by Airbus?
CREATE TABLE FlightSafety(id INT,aircraft_id INT,manufacturer VARCHAR(255),flight_hours INT); INSERT INTO FlightSafety(id,aircraft_id,manufacturer,flight_hours) VALUES (1,1001,'Boeing',12000),(2,1002,'Airbus',10500),(3,1003,'Boeing',18000),(4,1004,'Airbus',12000),(5,1005,'Airbus',11000);
SELECT MIN(flight_hours) FROM FlightSafety WHERE manufacturer = 'Airbus';
List the stations with a passenger count greater than 1000, based on the 'passenger_counts' table.
CREATE TABLE passenger_counts (station VARCHAR(255),passenger_count INT);
SELECT station FROM passenger_counts WHERE passenger_count > 1000;
What is the average CO2 emission of tours in Germany?
CREATE TABLE tours (id INT,name TEXT,country TEXT,co2_emission FLOAT); INSERT INTO tours (id,name,country,co2_emission) VALUES (1,'Tour A','Germany',2.5),(2,'Tour B','Germany',3.2);
SELECT AVG(co2_emission) FROM tours WHERE country = 'Germany';
How many 4-star food safety inspections were there in Los Angeles?
CREATE TABLE Inspections (id INT,restaurant_id INT,location VARCHAR(50),rating INT); INSERT INTO Inspections (id,restaurant_id,location,rating) VALUES (1,1,'New York',5); INSERT INTO Inspections (id,restaurant_id,location,rating) VALUES (2,2,'Los Angeles',3); INSERT INTO Inspections (id,restaurant_id,location,rating) VALUES (3,3,'Los Angeles',4);
SELECT COUNT(*) FROM Inspections WHERE location = 'Los Angeles' AND rating = 4;
how many wildlife habitats are there in each region?
CREATE TABLE wildlife_habitats (id INT,region VARCHAR(255),habitat_type VARCHAR(255));
SELECT region, COUNT(DISTINCT id) as num_habitats FROM wildlife_habitats GROUP BY region;
Find the total hectares of forests in Africa with koala populations.
CREATE TABLE forests (id INT PRIMARY KEY,name VARCHAR(50),country VARCHAR(50),hectares DECIMAL(10,2)); CREATE TABLE animals (id INT PRIMARY KEY,species VARCHAR(50),population INT,forest_id INT,FOREIGN KEY (forest_id) REFERENCES forests(id)); INSERT INTO forests (id,name,country,hectares) VALUES (1,'Savannah Forest','Africa',300000.00); INSERT INTO animals (id,species,population,forest_id) VALUES (1,'Koala',20,1);
SELECT SUM(hectares) FROM forests INNER JOIN animals ON forests.id = animals.forest_id WHERE forests.country = 'Africa' AND animals.species = 'Koala';
What is the average number of new species discovered per deep-sea expedition in the last 5 years?
CREATE TABLE deep_sea_expeditions (expedition_name TEXT,year INT,new_species_discovered INT); INSERT INTO deep_sea_expeditions (expedition_name,year,new_species_discovered) VALUES ('Mariana Trench Exploration',2017,32),('Atlantic Canyons Expedition',2018,28),('Arctic Ocean Exploration',2019,15);
SELECT AVG(new_species_discovered) FROM deep_sea_expeditions WHERE year >= 2017;
What is the average risk score for policyholders living in rural areas?
CREATE TABLE UnderwritingData (PolicyholderID INT,Smoker BOOLEAN,VehicleYear INT,HouseLocation VARCHAR(25)); INSERT INTO UnderwritingData (PolicyholderID,Smoker,VehicleYear,HouseLocation) VALUES (1,True,2015,'Urban'); INSERT INTO UnderwritingData (PolicyholderID,Smoker,VehicleYear,HouseLocation) VALUES (2,False,2018,'Rural');CREATE TABLE RiskAssessment (PolicyholderID INT PRIMARY KEY,RiskScore INT); INSERT INTO RiskAssessment (PolicyholderID,RiskScore) VALUES (1,50); INSERT INTO RiskAssessment (PolicyholderID,RiskScore) VALUES (2,30);
SELECT AVG(RiskScore) FROM RiskAssessment WHERE PolicyholderID IN (SELECT PolicyholderID FROM UnderwritingData WHERE HouseLocation = 'Rural');
What is the number of climate adaptation projects in South America for each year?
CREATE TABLE ClimateAdaptationProjects (project_id INT,project_name VARCHAR(50),continent VARCHAR(50),year INT); INSERT INTO ClimateAdaptationProjects (project_id,project_name,continent,year) VALUES (1,'Coastal Protection','South America',2020),(2,'Drought Resistance','South America',2021);
SELECT continent, year, COUNT(*) as num_projects FROM ClimateAdaptationProjects WHERE continent = 'South America' GROUP BY continent, year;
Delete a record of a marine species from the 'marine_species' table
CREATE TABLE marine_species (id INT PRIMARY KEY,species_name VARCHAR(255),conservation_status VARCHAR(255));
DELETE FROM marine_species WHERE species_name = 'Green Sea Turtle';