instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
How many sustainable projects are there in each region?
CREATE TABLE Building_Permits (id INT,region VARCHAR(20),permit_number VARCHAR(20),project VARCHAR(30),is_sustainable BOOLEAN); INSERT INTO Building_Permits (id,region,permit_number,project,is_sustainable) VALUES (1,'North','GP001','Green Tower',true),(2,'West','GP002','Solar Park',false),(3,'East','GP003','Wind Farm',true);
SELECT region, COUNT(*) FROM Building_Permits WHERE is_sustainable = true GROUP BY region;
Find the total carbon sequestered in the year 2019 in California forests, excluding national parks.
CREATE TABLE forests (id INT,name VARCHAR(50),state VARCHAR(50),is_national_park BOOLEAN); INSERT INTO forests (id,name,state,is_national_park) VALUES (1,'Yosemite National Park','California',true); CREATE TABLE carbon_sequestration (id INT,forest_id INT,year INT,sequestration FLOAT); INSERT INTO carbon_sequestration (id,forest_id,year,sequestration) VALUES (1,1,2019,35000);
SELECT SUM(cs.sequestration) FROM carbon_sequestration cs JOIN forests f ON cs.forest_id = f.id WHERE f.state = 'California' AND NOT f.is_national_park AND cs.year = 2019;
Show average sustainability rating for each fabric type
CREATE TABLE fabrics_sourced (id INT PRIMARY KEY,fabric_type VARCHAR(255),country VARCHAR(255),sustainability_rating INT);
SELECT fabric_type, AVG(sustainability_rating) FROM fabrics_sourced GROUP BY fabric_type;
Which refugee support organizations provided assistance in Europe in 2020?
CREATE TABLE RefugeeSupport (support_id INT,support_location VARCHAR(50),support_year INT,support_organization VARCHAR(50)); INSERT INTO RefugeeSupport (support_id,support_location,support_year,support_organization) VALUES (1,'Germany',2020,'Non-Profit A'),(2,'Canada',2019,'Non-Profit B'),(3,'France',2020,'Government Agency C');
SELECT DISTINCT support_organization FROM RefugeeSupport WHERE support_location LIKE 'Europe%' AND support_year = 2020;
What is the second highest cost of a spacecraft manufactured in Europe?
CREATE TABLE SpacecraftManufacturing(id INT,country VARCHAR(50),cost FLOAT); INSERT INTO SpacecraftManufacturing(id,country,cost) VALUES (1,'France',30000000),(2,'Germany',35000000),(3,'France',28000000),(4,'UK',40000000);
SELECT cost FROM (SELECT cost FROM SpacecraftManufacturing WHERE country = 'France' ORDER BY cost DESC LIMIT 2) AS subquery ORDER BY cost LIMIT 1;
What is the total number of construction labor hours spent on permits issued in California since 2010?
CREATE TABLE Permits (PermitID INT,IssueDate DATE,State CHAR(2)); INSERT INTO Permits (PermitID,IssueDate,State) VALUES (1,'2010-03-05','CA'),(2,'2011-06-18','NY'),(3,'2012-09-21','CA'); CREATE TABLE LaborHours (LaborHourID INT,PermitID INT,Hours DECIMAL(10,2)); INSERT INTO LaborHours (LaborHourID,PermitID,Hours) VALUES (1,1,250.00),(2,1,300.00),(3,2,150.00),(4,3,400.00);
SELECT SUM(LaborHours.Hours) FROM LaborHours INNER JOIN Permits ON LaborHours.PermitID = Permits.PermitID WHERE Permits.State = 'CA' AND Permits.IssueDate >= '2010-01-01';
What is the total quantity of crops and animals raised by each farmer in 'region2'?
CREATE TABLE farm (farm_id INT,farm_name TEXT,region TEXT); INSERT INTO farm (farm_id,farm_name,region) VALUES (1,'FarmA','region1'),(2,'FarmB','region2'),(3,'FarmC','region2'); CREATE TABLE crop_production (production_id INT,farm_id INT,crop_name TEXT,quantity INT); INSERT INTO crop_production (production_id,farm_id,crop_name,quantity) VALUES (1,1,'Corn',500),(2,1,'Potatoes',200),(3,2,'Corn',700),(4,2,'Beans',300),(5,3,'Carrots',400); CREATE TABLE animal_rearing (rearing_id INT,farm_id INT,animal_type TEXT,quantity INT); INSERT INTO animal_rearing (rearing_id,farm_id,animal_type,quantity) VALUES (1,1,'Cattle',10),(2,1,'Chickens',50),(3,2,'Pigs',20),(4,3,'Goats',30);
SELECT f.farm_name, SUM(cp.quantity) as total_crops, SUM(ar.quantity) as total_animals FROM farm f LEFT JOIN crop_production cp ON f.farm_id = cp.farm_id LEFT JOIN animal_rearing ar ON f.farm_id = ar.farm_id WHERE f.region = 'region2' GROUP BY f.farm_name;
What is the total sales volume for manufacturers in India who use sustainable materials?
CREATE TABLE manufacturers (id INT,name VARCHAR(50),country VARCHAR(50)); INSERT INTO manufacturers (id,name,country) VALUES (1,'Manufacturer A','India'),(2,'Manufacturer B','India'),(3,'Manufacturer C','USA'); CREATE TABLE material_sourcing (id INT,manufacturer_id INT,sustainable_sourcing BOOLEAN); INSERT INTO material_sourcing (id,manufacturer_id,sustainable_sourcing) VALUES (1,1,true),(2,2,true),(3,3,false); CREATE TABLE sales_volume (id INT,manufacturer_id INT,volume INT); INSERT INTO sales_volume (id,manufacturer_id,volume) VALUES (1,1,500),(2,2,250),(3,3,750);
SELECT m.name, SUM(SV.volume) as total_sales_volume FROM sales_volume SV JOIN manufacturers m ON SV.manufacturer_id = m.id JOIN material_sourcing MS ON m.id = MS.manufacturer_id WHERE m.country = 'India' AND MS.sustainable_sourcing = true GROUP BY m.name;
Create a view to display the number of users by gender in the 'user_demographics' table
CREATE TABLE user_demographics (user_id INT,age INT,gender VARCHAR(10),occupation VARCHAR(255)); INSERT INTO user_demographics (user_id,age,gender,occupation) VALUES (1,35,'male','software engineer');
CREATE VIEW user_gender_counts AS SELECT gender, COUNT(*) as user_count FROM user_demographics GROUP BY gender;
Insert a new record into the 'crypto_exchanges' table with 'exchange_name' 'Kraken', 'exchange_location' 'USA', and 'year_founded' 2011
CREATE TABLE crypto_exchanges (exchange_name VARCHAR(50),exchange_location VARCHAR(50),year_founded INT,regulatory_status VARCHAR(20));
INSERT INTO crypto_exchanges (exchange_name, exchange_location, year_founded, regulatory_status) VALUES ('Kraken', 'USA', 2011, 'Registered');
Insert a new mining site named 'Site D' located in 'Country W' with no environmental impact score yet.
CREATE TABLE mining_sites (site_id INT,site_name TEXT,location TEXT); INSERT INTO mining_sites (site_id,site_name,location) VALUES (1,'Site A','Country X'),(2,'Site B','Country Y'),(3,'Site C','Country Z');
INSERT INTO mining_sites (site_id, site_name, location) VALUES (4, 'Site D', 'Country W');
What is the average safety rating for electric vehicles in the vehicle_safety_data table?
CREATE TABLE vehicle_safety_data (id INT,make VARCHAR(20),model VARCHAR(20),safety_rating DECIMAL(3,1)); INSERT INTO vehicle_safety_data (id,make,model,safety_rating) VALUES (1,'Tesla','Model 3',5.3),(2,'Ford','Mustang Mach-E',4.8),(3,'Chevrolet','Bolt',5.1);
SELECT AVG(safety_rating) FROM vehicle_safety_data WHERE make IN ('Tesla', 'Ford', 'Chevrolet') AND model IN (SELECT DISTINCT model FROM vehicle_safety_data WHERE make IN ('Tesla', 'Ford', 'Chevrolet') AND is_electric = TRUE);
How many artifacts are made of gold in Peru?
CREATE TABLE Site (SiteID INT PRIMARY KEY,SiteName VARCHAR(50),Country VARCHAR(50),City VARCHAR(50)); INSERT INTO Site (SiteID,SiteName,Country,City) VALUES (7,'Machu Picchu','Peru','Cuzco'); CREATE TABLE Artifact (ArtifactID INT PRIMARY KEY,SiteID INT,ArtifactName VARCHAR(50),Material VARCHAR(50),Era VARCHAR(50)); INSERT INTO Artifact (ArtifactID,SiteID,ArtifactName,Material,Era) VALUES (6,2,'Golden Mask','Gold','Inca'),(7,7,'Golden Idol','Gold','Inca');
SELECT COUNT(*) FROM Artifact WHERE Material = 'Gold' AND SiteID = (SELECT SiteID FROM Site WHERE SiteName = 'Machu Picchu');
Who are the top 3 threat actors by the number of incidents in the last month?
CREATE TABLE threat_actors (id INT,actor_name VARCHAR(255),incident_time TIMESTAMP);
SELECT actor_name, COUNT(*) as incident_count FROM threat_actors WHERE incident_time >= DATE_SUB(CURRENT_TIMESTAMP, INTERVAL 1 MONTH) GROUP BY actor_name ORDER BY incident_count DESC LIMIT 3;
List drugs with R&D expenditures over $5 million in H1 2019?
CREATE TABLE rd_expenditures (drug_name TEXT,half INT,year INT,expenditure FLOAT); INSERT INTO rd_expenditures (drug_name,half,year,expenditure) VALUES ('DrugC',1,2019,6000000.0),('DrugD',2,2019,4000000.0);
SELECT drug_name FROM rd_expenditures WHERE expenditure > 5000000 AND half = 1 AND year = 2019;
What is the total production quantity (in metric tons) of cerium, lanthanum, and samarium in 2017 and 2018?
CREATE TABLE production_data (element VARCHAR(20),year INT,quantity FLOAT); INSERT INTO production_data (element,year,quantity) VALUES ('cerium',2015,3000),('cerium',2016,3500),('cerium',2017,4000),('cerium',2018,4500),('cerium',2019,5000),('cerium',2020,5500),('lanthanum',2015,2000),('lanthanum',2016,2200),('lanthanum',2017,2500),('lanthanum',2018,2800),('lanthanum',2019,3100),('lanthanum',2020,3400),('samarium',2015,1000),('samarium',2016,1100),('samarium',2017,1200),('samarium',2018,1300),('samarium',2019,1400),('samarium',2020,1500);
SELECT SUM(quantity) FROM production_data WHERE element IN ('cerium', 'lanthanum', 'samarium') AND year BETWEEN 2017 AND 2018;
What is the minimum number of defense projects in the African region that were completed on time?
CREATE TABLE projects (id INT,region VARCHAR(255),completed_on_time BOOLEAN); INSERT INTO projects (id,region,completed_on_time) VALUES (1,'Africa',true),(2,'Europe',false),(3,'Africa',true);
SELECT MIN(id) as min_project_id FROM projects WHERE region = 'Africa' AND completed_on_time = true;
How many artworks were created each year in France?
CREATE TABLE ArtWorks (ArtworkID int,Title varchar(100),YearCreated int,Country varchar(100));
SELECT YearCreated, COUNT(ArtworkID) FROM ArtWorks
count the total number of unique fabric types used in garment manufacturing for sustainable fabrics
CREATE TABLE Fabrics (fabric_id INT,fabric_type VARCHAR(25),is_sustainable BOOLEAN); INSERT INTO Fabrics (fabric_id,fabric_type,is_sustainable) VALUES (1,'Cotton',true),(2,'Polyester',false),(3,'Hemp',true),(4,'Silk',false),(5,'Recycled Polyester',true);
SELECT COUNT(DISTINCT fabric_type) FROM Fabrics WHERE is_sustainable = true;
Determine the total weight of shipments sent via air freight to each country in the Europe region in the past quarter.
CREATE TABLE Shipments (ShipmentID int,CarrierID int,ShippedWeight int,ShippedDate datetime,ShippingMethod varchar(255));CREATE TABLE Carriers (CarrierID int,CarrierName varchar(255),Region varchar(255)); INSERT INTO Carriers (CarrierID,CarrierName,Region) VALUES (1,'Carrier A','Europe'); INSERT INTO Shipments (ShipmentID,CarrierID,ShippedWeight,ShippedDate,ShippingMethod) VALUES (1,1,100,'2022-01-01','Air Freight');
SELECT s.ShippingMethod, w.Country, SUM(s.ShippedWeight) as TotalWeight FROM Shipments s INNER JOIN Carriers c ON s.CarrierID = c.CarrierID INNER JOIN Warehouses w ON s.WarehouseID = w.WarehouseID WHERE s.ShippingMethod = 'Air Freight' AND c.Region = 'Europe' AND s.ShippedDate >= DATEADD(quarter, -1, GETDATE()) GROUP BY s.ShippingMethod, w.Country;
How many different animals were observed in the 'arctic_animal_sightings' table for each observer?
CREATE TABLE arctic_animal_sightings (id INT,observer VARCHAR(255),animal VARCHAR(255)); INSERT INTO arctic_animal_sightings (id,observer,animal) VALUES (1,'John','Polar Bear'),(2,'Sarah','Walrus'),(3,'John','Fox');
SELECT observer, COUNT(DISTINCT animal) AS animal_count FROM arctic_animal_sightings GROUP BY observer;
What is the average response time for citizen feedback in 'City F'?
CREATE TABLE city_feedback (city VARCHAR(255),feedback_id INT,feedback TEXT,response_time INT); INSERT INTO city_feedback
SELECT AVG(response_time) FROM city_feedback WHERE city = 'City F'
What is the minimum and maximum number of sustainable tourism certifications held by hotels in South America?
CREATE TABLE Hotels (HotelID INT,HotelName VARCHAR(50),SustainableCertifications INT,Continent VARCHAR(20)); INSERT INTO Hotels (HotelID,HotelName,SustainableCertifications,Continent) VALUES (1,'GreenPalace',3,'South America'),(2,'EcoLodge',7,'South America');
SELECT MIN(SustainableCertifications) as MinCertifications, MAX(SustainableCertifications) as MaxCertifications FROM Hotels WHERE Continent = 'South America';
What is the maximum CO2 emission increase in Africa in any year since 2000, and what is the year in which it occurred?
CREATE TABLE co2_emissions (id INT,region VARCHAR(255),year INT,co2_emission INT); INSERT INTO co2_emissions (id,region,year,co2_emission) VALUES (1,'Africa',2000,400);
SELECT region, MAX(co2_emission) AS max_co2, year FROM co2_emissions WHERE region = 'Africa' GROUP BY region, year HAVING max_co2 = (SELECT MAX(co2_emission) FROM co2_emissions WHERE region = 'Africa');
What is the average number of visitors per day for the 'Contemporary Art' exhibition in 2021?
CREATE TABLE Exhibition_Daily_Attendance (exhibition_id INT,visit_date DATE,visitor_count INT); CREATE TABLE Exhibitions (id INT,name VARCHAR(50)); INSERT INTO Exhibitions (id,name) VALUES (1,'Contemporary Art'); ALTER TABLE Exhibition_Daily_Attendance ADD FOREIGN KEY (exhibition_id) REFERENCES Exhibitions(id);
SELECT AVG(visitor_count) FROM Exhibition_Daily_Attendance WHERE exhibition_id = 1 AND visit_date BETWEEN '2021-01-01' AND '2021-12-31';
What is the average calorie count for vegetarian dishes in the restaurants table?
CREATE TABLE restaurants (id INT,dish VARCHAR(255),category VARCHAR(255),calories INT);
SELECT AVG(calories) FROM restaurants WHERE category = 'vegetarian';
Which location had the highest drought impact in 2018?
CREATE TABLE DroughtImpact (Id INT,Location VARCHAR(100),Impact INT,Year INT); INSERT INTO DroughtImpact (Id,Location,Impact,Year) VALUES (1,'Region1',3,2018); INSERT INTO DroughtImpact (Id,Location,Impact,Year) VALUES (2,'Region1',5,2019); INSERT INTO DroughtImpact (Id,Location,Impact,Year) VALUES (3,'Region2',2,2018); INSERT INTO DroughtImpact (Id,Location,Impact,Year) VALUES (4,'Region2',4,2019);
SELECT Location, MAX(Impact) FROM DroughtImpact WHERE Year = 2018 GROUP BY Location;
What is the total revenue generated from users in London and Paris, for users who have spent more than $500?
CREATE TABLE sales_data (id INT,user_id INT,city VARCHAR(50),amount DECIMAL(10,2)); INSERT INTO sales_data (id,user_id,city,amount) VALUES (1,1,'London',600),(2,2,'Paris',700),(3,3,'London',300),(4,4,'Paris',400);
SELECT city, SUM(amount) as total_revenue FROM sales_data WHERE city IN ('London', 'Paris') AND amount > 500 GROUP BY city;
Find the top 3 most expensive sustainable material types and their average prices.
CREATE TABLE Sustainable_Materials (Type VARCHAR(255),Price FLOAT); INSERT INTO Sustainable_Materials (Type,Price) VALUES ('Organic Cotton',3.5),('Recycled Polyester',4.2),('Hemp',2.8);
SELECT Type, AVG(Price) as Average_Price FROM (SELECT Type, Price, ROW_NUMBER() OVER (ORDER BY Price DESC) as Rank FROM Sustainable_Materials) WHERE Rank <= 3 GROUP BY Type;
How many streams did song 'Heat Waves' by Glass Animals get in Canada?
CREATE TABLE SongStreams (id INT,song VARCHAR(50),country VARCHAR(20),streams INT); INSERT INTO SongStreams (id,song,country,streams) VALUES (1,'Bohemian Rhapsody','USA',1000000),(2,'Heat Waves','Canada',800000);
SELECT streams FROM SongStreams WHERE song = 'Heat Waves' AND country = 'Canada';
What is the total installed solar capacity for each city?
CREATE TABLE cities (id INT,name VARCHAR(50)); INSERT INTO cities (id,name) VALUES (1,'CityA'),(2,'CityB'); CREATE TABLE projects (id INT,city_id INT,type VARCHAR(50),capacity INT); INSERT INTO projects (id,city_id,type,capacity) VALUES (1,1,'Solar',1000),(2,2,'Solar',2000),(3,1,'Wind',1500);
SELECT c.name, SUM(p.capacity) as total_solar_capacity FROM cities c INNER JOIN projects p ON c.id = p.city_id WHERE p.type = 'Solar' GROUP BY c.name;
List the top 5 cities with the highest number of recycling centers.
CREATE TABLE cities (id INT,name TEXT,country TEXT); CREATE TABLE recycling_centers (id INT,city_id INT,type TEXT); INSERT INTO cities VALUES (1,'City A','Country A'),(2,'City B','Country A'),(3,'City C','Country B'); INSERT INTO recycling_centers VALUES (1,1,'Glass'),(2,1,'Paper'),(3,2,'Plastic'),(4,3,'Glass'),(5,3,'Plastic');
SELECT cities.name, COUNT(recycling_centers.id) AS center_count FROM cities INNER JOIN recycling_centers ON cities.id = recycling_centers.city_id GROUP BY cities.name ORDER BY center_count DESC LIMIT 5;
What is the total amount of resources extracted from each mine, in the past quarter?
CREATE TABLE mine (id INT,name TEXT,location TEXT); CREATE TABLE resource_extraction (id INT,mine_id INT,date DATE,quantity INT);
SELECT mine.name, SUM(resource_extraction.quantity) as total_quantity FROM mine INNER JOIN resource_extraction ON mine.id = resource_extraction.mine_id WHERE resource_extraction.date BETWEEN DATE_SUB(CURRENT_DATE, INTERVAL 3 MONTH) AND CURRENT_DATE GROUP BY mine.name;
List all the mining sites located in 'California' with their respective environmental impact scores.
CREATE TABLE mining_sites (site_id INT,site_name VARCHAR(50),state VARCHAR(20));CREATE VIEW environmental_impact AS SELECT site_id,SUM(pollution_level) AS total_impact FROM pollution_data GROUP BY site_id;
SELECT s.site_name, e.total_impact FROM mining_sites s INNER JOIN environmental_impact e ON s.site_id = e.site_id WHERE state = 'California';
What is the maximum number of attempts for unsuccessful exploitation of a specific vulnerability?
CREATE TABLE exploitation_attempts (id INT,vulnerability_id INT,attempts INT,success BOOLEAN); INSERT INTO exploitation_attempts (id,vulnerability_id,attempts,success) VALUES (1,1,5,true),(2,1,3,false),(3,2,10,true);
SELECT MAX(attempts) FROM exploitation_attempts WHERE success = false;
Get the total number of volunteers for each program
CREATE TABLE volunteers (id INT,program_id INT,is_active BOOLEAN);
SELECT p.name, COUNT(v.program_id) as total_volunteers FROM programs p JOIN volunteers v ON p.id = v.program_id GROUP BY p.id;
What is the total number of policies and total claim amount for policies issued in the last month, grouped by underwriter?
CREATE TABLE policy (policy_id INT,underwriter_id INT,issue_date DATE,zip_code INT,risk_score INT); CREATE TABLE claim (claim_id INT,policy_id INT,claim_amount INT);
SELECT underwriter_id, COUNT(policy_id) as policy_count, SUM(claim_amount) as total_claim_amount FROM claim JOIN policy ON claim.policy_id = policy.policy_id WHERE policy.issue_date >= DATEADD(MONTH, -1, GETDATE()) GROUP BY underwriter_id;
Update the capacity of the landfill in Mumbai to 150000 units and update its start date to 2015-01-01.
CREATE TABLE landfill (id INT,name VARCHAR(20),location VARCHAR(20),capacity INT,start_date DATE); INSERT INTO landfill (id,name,location,capacity,start_date) VALUES (1,'Mumbai Landfill','Mumbai',120000,'2018-01-01');
UPDATE landfill SET capacity = 150000, start_date = '2015-01-01' WHERE name = 'Mumbai Landfill';
What is the maximum production rate of wells in the 'Caspian Sea'?
CREATE TABLE wells (well_id INT,well_name VARCHAR(50),region VARCHAR(50),production_rate FLOAT); INSERT INTO wells (well_id,well_name,region,production_rate) VALUES (16,'Well P','Caspian Sea',7000),(17,'Well Q','Caspian Sea',8000),(18,'Well R','Caspian Sea',9000);
SELECT MAX(production_rate) FROM wells WHERE region = 'Caspian Sea';
What are the details of the military technologies that were developed by a specific country, say 'USA', from the 'military_tech' table?
CREATE TABLE military_tech (id INT,tech_name VARCHAR(255),country VARCHAR(255),tech_date DATE);
SELECT * FROM military_tech WHERE country = 'USA';
How many community health workers serve patients in rural areas?
CREATE TABLE community_health_workers (id INT,name VARCHAR,location VARCHAR,patients_served INT); INSERT INTO community_health_workers (id,name,location,patients_served) VALUES (1,'John Doe','Rural',50); INSERT INTO community_health_workers (id,name,location,patients_served) VALUES (2,'Jane Smith','Urban',75);
SELECT location, SUM(patients_served) as total_patients FROM community_health_workers WHERE location = 'Rural' GROUP BY location;
Which ocean has the minimum temperature?
CREATE TABLE temperature_readings (location TEXT,temperature FLOAT); INSERT INTO temperature_readings (location,temperature) VALUES ('Arctic Ocean',-2.34),('North Atlantic',12.56),('North Pacific',15.43);
SELECT location FROM temperature_readings WHERE temperature = (SELECT MIN(temperature) FROM temperature_readings);
What is the average cost of accommodations per student for each accommodation type?
CREATE TABLE Accommodations (id INT,type VARCHAR(255),cost FLOAT,student VARCHAR(255)); CREATE TABLE Students (id INT,name VARCHAR(255),age INT,disability VARCHAR(255));
SELECT type, AVG(cost) FROM Accommodations GROUP BY type;
What was the approval date of a specific drug in a certain country?
CREATE TABLE drug_approval (drug_name VARCHAR(255),country VARCHAR(255),approval_date DATE);
SELECT approval_date FROM drug_approval WHERE drug_name = 'DrugB' AND country = 'CountryX';
What is the average number of UNESCO World Heritage Sites per country in Europe?
CREATE TABLE countries (country_name VARCHAR(50),continent VARCHAR(50)); INSERT INTO countries VALUES ('France','Europe'); INSERT INTO countries VALUES ('Brazil','South America'); CREATE TABLE world_heritage_sites (site_name VARCHAR(50),country VARCHAR(50)); INSERT INTO world_heritage_sites VALUES ('Eiffel Tower','France'); INSERT INTO world_heritage_sites VALUES ('Iguazu Falls','Brazil');
SELECT C.continent, AVG(CASE WHEN C.continent = 'Europe' THEN COUNT(WHS.country) END) as avg_world_heritage_sites FROM countries C JOIN world_heritage_sites WHS ON C.country_name = WHS.country GROUP BY C.continent;
What is the average time taken for each athlete to complete the swimming events, in the swimming table?
CREATE TABLE swimming (athlete VARCHAR(50),event VARCHAR(50),time TIME);
SELECT athlete, AVG(EXTRACT(EPOCH FROM time)/60) AS avg_time FROM swimming GROUP BY athlete;
Increase the capacity of the 'Screening Facility' in the 'Southeast' region in the wastewater_facilities table by 50000 BOD
CREATE TABLE wastewater_facilities (id INT PRIMARY KEY,name VARCHAR(50),facility_type VARCHAR(50),region VARCHAR(20),capacity_bod INT,operational_status VARCHAR(20)); INSERT INTO wastewater_facilities (id,name,facility_type,region,capacity_bod,operational_status) VALUES (1,'Facility A','Sewage Treatment Plant','Northeast',500000,'Operational'),(2,'Facility B','Screening Facility','Southeast',250000,'Operational'),(3,'Facility C','Sewage Treatment Plant','Midwest',750000,'Operational');
UPDATE wastewater_facilities SET capacity_bod = capacity_bod + 50000 WHERE name = 'Facility B' AND region = 'Southeast';
What was the total waste reduction in the USA in Q1 2022 from using biodegradable materials?
CREATE TABLE WasteReduction (reduction_date DATE,waste_reduction INT,biodegradable_materials BOOLEAN);
SELECT SUM(waste_reduction) FROM WasteReduction WHERE reduction_date BETWEEN '2022-01-01' AND '2022-03-31' AND biodegradable_materials = TRUE AND country = 'USA';
How many investments have been made in women-founded startups in the healthcare sector in the last 2 years?
CREATE TABLE investment (id INT,company_id INT,investor TEXT,year INT,amount FLOAT); INSERT INTO investment (id,company_id,investor,year,amount) VALUES (1,1,'Kleiner Perkins',2022,12000000.0); CREATE TABLE company (id INT,name TEXT,industry TEXT,founder TEXT,PRIMARY KEY (id)); INSERT INTO company (id,name,industry,founder) VALUES (1,'HealFast','Healthcare','Female');
SELECT COUNT(*) FROM investment i JOIN company c ON i.company_id = c.id WHERE c.founder = 'Female' AND c.industry = 'Healthcare' AND i.year >= (SELECT YEAR(CURRENT_DATE()) - 2);
Display total ticket sales by month
CREATE TABLE ticket_sales (sale_date DATE,team VARCHAR(50),tickets_sold INT); INSERT INTO ticket_sales (sale_date,team,tickets_sold) VALUES ('2022-01-01','Team A',1000),('2022-01-02','Team B',1200),('2022-02-01','Team A',1500);
SELECT DATE_FORMAT(sale_date, '%Y-%m') AS month, SUM(tickets_sold) AS total_sales FROM ticket_sales GROUP BY month;
List the top 5 military threats in the last month
CREATE TABLE military_threats (threat_id INT,country VARCHAR(255),level VARCHAR(255),threat_date DATE);
SELECT country, level, threat_date FROM military_threats WHERE threat_date >= DATE(NOW()) - INTERVAL 1 MONTH ORDER BY threat_date DESC LIMIT 5;
How many tickets were sold for each event type (theater, dance, music) at cultural centers in Chicago?
CREATE TABLE events (id INT,title VARCHAR(50),event_type VARCHAR(50),city VARCHAR(50),tickets_sold INT); INSERT INTO events (id,title,event_type,city,tickets_sold) VALUES (1,'The Nutcracker','theater','Chicago',1800); INSERT INTO events (id,title,event_type,city,tickets_sold) VALUES (2,'Swan Lake','dance','Chicago',1400); INSERT INTO events (id,title,event_type,city,tickets_sold) VALUES (3,'Mozart Requiem','music','Chicago',1200);
SELECT event_type, SUM(tickets_sold) FROM events WHERE city = 'Chicago' GROUP BY event_type;
What is the average transaction value per digital asset?
CREATE TABLE AssetTransactions (AssetID int,TransactionDate date,Value float); INSERT INTO AssetTransactions (AssetID,TransactionDate,Value) VALUES (1,'2021-01-02',100.5),(2,'2021-02-15',250.7),(3,'2021-05-03',75.3),(1,'2021-12-30',1500.0);
SELECT AssetID, AVG(Value) as AvgTransactionValue FROM AssetTransactions GROUP BY AssetID;
Show all records in the space_exploration table where the mission_status is 'Active' and agency is 'NASA'
CREATE TABLE space_exploration (id INT,mission_name VARCHAR(255),mission_status VARCHAR(255),agency VARCHAR(255),launch_date DATE);
SELECT * FROM space_exploration WHERE mission_status = 'Active' AND agency = 'NASA';
What is the average financial wellbeing score for each gender?
CREATE TABLE financial_wellbeing_gender (person_id INT,gender VARCHAR(6),score INT); INSERT INTO financial_wellbeing_gender (person_id,gender,score) VALUES (1,'Male',7),(2,'Female',8),(3,'Male',9),(4,'Female',6),(5,'Male',8);
SELECT gender, AVG(score) FROM financial_wellbeing_gender GROUP BY gender;
How many items are made of materials that are not sustainably sourced?
CREATE TABLE products (id INT,name TEXT,material TEXT,sustainable BOOLEAN); INSERT INTO products (id,name,material,sustainable) VALUES (1,'Shirt','Organic Cotton',1),(2,'Pants','Conventional Cotton',0);
SELECT COUNT(*) FROM products WHERE sustainable = 0;
Update the funding for military innovations in the 'innovations' table
CREATE TABLE innovations (id INT PRIMARY KEY,innovation_name VARCHAR(100),description TEXT,category VARCHAR(50),funding FLOAT);
UPDATE innovations SET funding = 12000000.00 WHERE innovation_name = 'Hypersonic Missile';
What is the total number of building permits issued in each city, for the past year?
CREATE TABLE BuildingPermits (PermitID INT,PermitType TEXT,DateIssued DATE,City TEXT);
SELECT City, Count(PermitID) AS Count FROM BuildingPermits WHERE DateIssued >= DATEADD(year, -1, GETDATE()) GROUP BY City;
What are the top 5 textile suppliers for sustainable brands in Germany?
CREATE TABLE Textile_Suppliers (supplier_id INT,supplier_name TEXT,country TEXT,is_sustainable BOOLEAN); CREATE TABLE Brands_Textile_Suppliers (brand_id INT,supplier_id INT); CREATE TABLE Brands (brand_id INT,brand_name TEXT,country TEXT,is_sustainable BOOLEAN);
SELECT s.supplier_name, COUNT(DISTINCT bts.brand_id) as sustainable_brand_count FROM Textile_Suppliers s JOIN Brands_Textile_Suppliers bts ON s.supplier_id = bts.supplier_id JOIN Brands b ON bts.brand_id = b.brand_id WHERE s.is_sustainable = TRUE AND b.country = 'Germany' GROUP BY s.supplier_name ORDER BY sustainable_brand_count DESC LIMIT 5;
Delete all users who signed up using a social media account
CREATE TABLE users (id INT PRIMARY KEY,name VARCHAR(50),email VARCHAR(50),signup_date DATE,signup_source VARCHAR(20));
DELETE FROM users WHERE signup_source IN ('facebook', 'twitter', 'google');
Which satellites are in a specific orbit type, based on the SatelliteOrbits table?
CREATE TABLE SatelliteOrbits (SatelliteID INT,OrbitType VARCHAR(50),OrbitHeight INT); INSERT INTO SatelliteOrbits (SatelliteID,OrbitType,OrbitHeight) VALUES (101,'LEO',500),(201,'MEO',8000),(301,'GEO',36000),(401,'LEO',600),(501,'MEO',10000);
SELECT SatelliteID, OrbitType FROM SatelliteOrbits WHERE OrbitType = 'LEO';
What is the total number of autonomous driving research projects in Japan and South Korea?
CREATE TABLE ResearchProjects (Id INT,Name TEXT,Location TEXT); INSERT INTO ResearchProjects (Id,Name,Location) VALUES (1,'Project A','Japan'); INSERT INTO ResearchProjects (Id,Name,Location) VALUES (2,'Project B','South Korea');
SELECT COUNT(*) FROM ResearchProjects WHERE Location IN ('Japan', 'South Korea');
What is the average salary of employees in mining companies in the top 3 countries with the highest total salary costs?
CREATE TABLE company (id INT,name VARCHAR(255),country VARCHAR(255),num_employees INT,avg_salary DECIMAL(10,2));CREATE VIEW mining_companies AS SELECT * FROM company WHERE industry = 'Mining';
SELECT AVG(c.avg_salary) as avg_salary FROM company c JOIN (SELECT country, SUM(num_employees * avg_salary) as total_salary_costs FROM mining_companies GROUP BY country ORDER BY total_salary_costs DESC LIMIT 3) mc ON c.country = mc.country WHERE c.industry = 'Mining';
Which art pieces in the 'ArtHeritage' table have been preserved for more than 50 years?
CREATE TABLE ArtHeritage (id INT,name VARCHAR(50),type VARCHAR(50),year INT,country VARCHAR(50)); INSERT INTO ArtHeritage (id,name,type,year,country) VALUES (1,'Pottery','Art',2005,'Mexico'); INSERT INTO ArtHeritage (id,name,type,year,country) VALUES (2,'Woven Baskets','Art',1950,'USA');
SELECT name, type, year, country FROM ArtHeritage WHERE year <= (EXTRACT(YEAR FROM CURRENT_DATE) - 50);
What is the number of individuals in Europe who have received financial capability training in the last 12 months?
CREATE TABLE financial_capability (individual_id TEXT,training_date DATE,country TEXT); INSERT INTO financial_capability (individual_id,training_date,country) VALUES ('11111','2022-01-01','Germany'); INSERT INTO financial_capability (individual_id,training_date,country) VALUES ('22222','2022-02-01','France');
SELECT COUNT(individual_id) FROM financial_capability WHERE training_date >= DATEADD(year, -1, CURRENT_DATE) AND country = 'Europe';
Find the number of co-owned properties in Austin, TX that were built after 2010.
CREATE TABLE properties (id INT,city VARCHAR(50),state VARCHAR(2),build_date DATE,co_owners INT); INSERT INTO properties (id,city,state,build_date,co_owners) VALUES (1,'Austin','TX','2015-01-01',2),(2,'Dallas','TX','2005-01-01',1);
SELECT COUNT(*) FROM properties WHERE city = 'Austin' AND state = 'TX' AND build_date > '2010-01-01' AND co_owners > 1;
What is the difference in average customer size between the US and Canada?
CREATE TABLE CustomerSizesUS (CustomerID INT,Country TEXT,AvgSize DECIMAL(5,2)); INSERT INTO CustomerSizesUS (CustomerID,Country,AvgSize) VALUES (1,'US',8.5),(2,'US',7.5),(3,'US',9.5),(4,'US',6.5); CREATE TABLE CustomerSizesCA (CustomerID INT,Country TEXT,AvgSize DECIMAL(5,2)); INSERT INTO CustomerSizesCA (CustomerID,Country,AvgSize) VALUES (1,'Canada',7.0),(2,'Canada',6.0),(3,'Canada',8.0),(4,'Canada',9.0);
SELECT AVG(CSUS.AvgSize) - AVG(CSCA.AvgSize) FROM CustomerSizesUS CSUS, CustomerSizesCA CSCA WHERE CSUS.Country = 'US' AND CSCA.Country = 'Canada';
Count of monitored habitats with gorillas
CREATE TABLE if not exists habitat_monitoring (id INT,habitat VARCHAR(255),animal VARCHAR(255),PRIMARY KEY(id,habitat,animal)); INSERT INTO habitat_monitoring (id,habitat,animal) VALUES (1,'Forest','Gorilla'),(2,'Grassland','Lion'),(3,'Wetlands','Crocodile'),(4,'Forest','Elephant'),(5,'Forest','Gorilla');
SELECT habitat, COUNT(*) FROM habitat_monitoring WHERE animal = 'Gorilla' GROUP BY habitat;
Delete graduate student records with GPA below 3.0.
CREATE TABLE graduates (id INT,name VARCHAR(50),department VARCHAR(50),gpa DECIMAL(3,2)); INSERT INTO graduates (id,name,department,gpa) VALUES (1,'James Smith','Mathematics',3.3),(2,'Emily Johnson','Physics',2.9);
DELETE FROM graduates WHERE gpa < 3.0;
Identify the players who scored more than 30 points in a game, for each game in the 'nba_games' table.
CREATE TABLE nba_games (game_id INT,home_team_id INT,away_team_id INT); CREATE TABLE nba_game_scores (game_id INT,team_id INT,player_name VARCHAR(255),points INT);
SELECT game_id, home_team_id AS team_id, player_name, points FROM nba_game_scores WHERE points > 30 UNION ALL SELECT game_id, away_team_id, player_name, points FROM nba_game_scores WHERE points > 30;
What is the CO2 emission of each production facility in the Asia-Pacific region for the year 2021?
CREATE TABLE facility_data (facility_id INT,facility_location VARCHAR(255),CO2_emission INT,year INT);
SELECT facility_location, SUM(CO2_emission) AS total_CO2_emission FROM facility_data WHERE facility_location LIKE 'Asia-Pacific%' AND year = 2021 GROUP BY facility_location;
What is the total funding received by dance programs targeting underrepresented communities?
CREATE TABLE DancePrograms (programID INT,communityType VARCHAR(20),fundingAmount DECIMAL(10,2)); INSERT INTO DancePrograms (programID,communityType,fundingAmount) VALUES (1,'Underrepresented',25000.00),(2,'General',15000.00),(3,'Underrepresented',30000.00);
SELECT SUM(fundingAmount) FROM DancePrograms WHERE communityType = 'Underrepresented';
Find the average daily revenue of eco-friendly hotels in France and Italy, and the average daily visitor count to museums in these two countries.
CREATE TABLE hotel_revenue (hotel_id INT,country VARCHAR(20),daily_revenue FLOAT); INSERT INTO hotel_revenue (hotel_id,country,daily_revenue) VALUES (1,'France',100),(2,'France',120),(3,'Italy',150),(4,'Italy',140); CREATE TABLE museum_visitors (visit_id INT,country VARCHAR(20),daily_visitors INT); INSERT INTO museum_visitors (visit_id,country,daily_visitors) VALUES (1,'France',50),(2,'France',60),(3,'Italy',70),(4,'Italy',80);
SELECT AVG(daily_revenue) FROM hotel_revenue WHERE country = 'France' UNION ALL SELECT AVG(daily_visitors) FROM museum_visitors WHERE country = 'France' UNION ALL SELECT AVG(daily_revenue) FROM hotel_revenue WHERE country = 'Italy' UNION ALL SELECT AVG(daily_visitors) FROM museum_visitors WHERE country = 'Italy';
What is the average number of electric vehicles per city in the 'transportation' schema, grouped by country?
CREATE TABLE city_electric_vehicles (city_name VARCHAR(255),country VARCHAR(255),num_electric_vehicles INT); INSERT INTO city_electric_vehicles (city_name,country,num_electric_vehicles) VALUES ('San Francisco','USA',15000),('Los Angeles','USA',20000),('Toronto','Canada',10000),('Montreal','Canada',8000),('Mexico City','Mexico',5000);
SELECT country, AVG(num_electric_vehicles) FROM city_electric_vehicles GROUP BY country;
Identify the countries that have higher production of Terbium than Lanthanum.
CREATE TABLE production (id INT,country VARCHAR(255),element VARCHAR(255),quantity INT); INSERT INTO production (id,country,element,quantity) VALUES (1,'China','Terbium',900),(2,'China','Lanthanum',8000),(3,'USA','Terbium',700),(4,'USA','Lanthanum',5000),(5,'Australia','Terbium',800),(6,'Australia','Lanthanum',6000);
SELECT country FROM production WHERE element = 'Terbium' AND quantity > (SELECT quantity FROM production WHERE element = 'Lanthanum' AND country = production.country) GROUP BY country;
Which malware has been detected in the 'Asia-Pacific' region in the last week?
CREATE TABLE malware_data (id INT,name VARCHAR(255),region VARCHAR(255),last_seen DATETIME); INSERT INTO malware_data (id,name,region,last_seen) VALUES (1,'WannaCry','Asia-Pacific','2022-01-01 12:00:00'),(2,'Emotet','North America','2022-01-02 13:00:00');
SELECT name FROM malware_data WHERE region = 'Asia-Pacific' AND last_seen >= DATE_SUB(NOW(), INTERVAL 1 WEEK);
Insert a new water conservation initiative
CREATE TABLE water_conservation_initiatives (id INT,name VARCHAR(50),description TEXT,start_date DATE,end_date DATE);
INSERT INTO water_conservation_initiatives (id, name, description, start_date, end_date) VALUES (1, 'Watering Restrictions', 'Restrictions on watering lawns and gardens', '2023-01-01', '2023-12-31');
What is the average number of medical personnel per hospital in Indonesia?
CREATE TABLE hospitals_indonesia (id INT,name TEXT,personnel INT); INSERT INTO hospitals_indonesia (id,name,personnel) VALUES (1,'Hospital Z',250);
SELECT AVG(personnel) FROM hospitals_indonesia;
What is the total rainfall in the last week for region 'MX-SON'?
CREATE TABLE region (id INT,name VARCHAR(255),rainfall FLOAT,rainfall_timestamp DATETIME); INSERT INTO region (id,name,rainfall,rainfall_timestamp) VALUES (1,'MX-SON',15.5,'2022-02-25 14:30:00'),(2,'MX-SIN',13.8,'2022-02-27 09:15:00'),(3,'MX-CHI',17.9,'2022-03-01 12:00:00');
SELECT SUM(rainfall) FROM region WHERE name = 'MX-SON' AND rainfall_timestamp >= DATEADD(week, -1, CURRENT_TIMESTAMP);
Which timber production sites have an area larger than 800?
CREATE TABLE timber_production_2 (id INT,name VARCHAR(50),area FLOAT); INSERT INTO timber_production_2 (id,name,area) VALUES (1,'Timber Inc.',1000.0),(2,'WoodCo',600.0),(3,'Forest Ltd.',1200.0);
SELECT name FROM timber_production_2 WHERE area > 800;
Which 'Film Appreciation' events in Seattle had less than 30 attendees?
CREATE TABLE event_attendance_2 (event_name VARCHAR(50),city VARCHAR(50),attendees INT); INSERT INTO event_attendance_2 (event_name,city,attendees) VALUES ('Film Appreciation','Seattle',25);
SELECT event_name, city FROM event_attendance_2 WHERE event_name = 'Film Appreciation' AND city = 'Seattle' AND attendees < 30;
What is the average military spending by countries in the North American region?
CREATE TABLE military_spending (country VARCHAR(50),region VARCHAR(50),spending NUMERIC(10,2)); INSERT INTO military_spending (country,region,spending) VALUES ('USA','North America',7319340000),('Canada','North America',22597000000),('Mexico','North America',640000000);
SELECT AVG(spending) FROM military_spending WHERE region = 'North America';
How many students have a mental health score greater than 80?
CREATE TABLE student_mental_health (student_id INT,mental_health_score INT); INSERT INTO student_mental_health (student_id,mental_health_score) VALUES (1,80),(2,85),(3,70),(4,82),(5,78),(6,75);
SELECT COUNT(*) FROM student_mental_health WHERE mental_health_score > 80;
How many unique first-time attendees were there at comedy events, in the past six months, for each state and gender?
CREATE TABLE Events (id INT,state VARCHAR(50),date DATE,event_type VARCHAR(50)); INSERT INTO Events (id,state,date,event_type) VALUES (1,'California','2021-01-01','Comedy'),(2,'New York','2021-02-01','Comedy'); CREATE TABLE Attendance (id INT,event_id INT,is_new_attendee BOOLEAN,gender VARCHAR(10)); INSERT INTO Attendance (id,event_id,is_new_attendee,gender) VALUES (1,1,TRUE,'Female'),(2,1,TRUE,'Male'),(3,2,FALSE,'Non-binary');
SELECT e.state, a.gender, COUNT(DISTINCT a.id) AS count FROM Events e INNER JOIN Attendance a ON e.id = a.event_id AND a.is_new_attendee = TRUE WHERE e.date >= DATE_SUB(CURRENT_DATE, INTERVAL 6 MONTH) AND e.event_type = 'Comedy' GROUP BY e.state, a.gender;
Which adaptation measures were implemented in South America in 2018?
CREATE TABLE adaptation_measures (region TEXT,year INT,measure TEXT); INSERT INTO adaptation_measures (region,year,measure) VALUES ('Asia',2015,'Building sea walls'),('Asia',2015,'Planting mangroves'),('Asia',2018,'Improving irrigation systems'),('Asia',2018,'Constructing early warning systems'),('South America',2015,'Building flood defenses'),('South America',2018,'Implementing afforestation programs'),('Africa',2015,'Constructing dikes'),('Africa',2018,'Promoting climate-smart agriculture');
SELECT measure FROM adaptation_measures WHERE region = 'South America' AND year = 2018;
Update the CO2 emissions of Building A in Texas to 110.5.
CREATE TABLE buildings (id INT,name TEXT,state TEXT,co2_emissions FLOAT); INSERT INTO buildings (id,name,state,co2_emissions) VALUES (1,'Building A','Texas',120.5),(2,'Building B','California',150.3),(3,'Building C','California',100.2);
UPDATE buildings SET co2_emissions = 110.5 WHERE name = 'Building A' AND state = 'Texas';
What was the minimum CO2 emission for any garment production in Brazil in 2020?
CREATE TABLE co2_emission (garment_type VARCHAR(20),country VARCHAR(20),year INT,co2_emission FLOAT); INSERT INTO co2_emission (garment_type,country,year,co2_emission) VALUES ('tops','Brazil',2020,5.5),('bottoms','Brazil',2020,6.2),('dresses','Brazil',2020,4.8);
SELECT MIN(co2_emission) FROM co2_emission WHERE country = 'Brazil' AND year = 2020;
List all social impact bonds along with their issuer countries and the corresponding ESG scores.
CREATE TABLE social_impact_bonds (bond_id INT,bond_name TEXT,issuer_country TEXT); CREATE TABLE esg_scores (bond_id INT,esg_score INT); INSERT INTO social_impact_bonds (bond_id,bond_name,issuer_country) VALUES (1,'SIB A','USA'),(2,'SIB B','Germany'); INSERT INTO esg_scores (bond_id,esg_score) VALUES (1,80),(2,85);
SELECT s.bond_name, s.issuer_country, e.esg_score FROM social_impact_bonds s JOIN esg_scores e ON s.bond_id = e.bond_id;
What is the average horsepower of electric vehicles released in 2020?
CREATE TABLE ElectricVehicles (id INT,name VARCHAR(50),horsepower INT,release_year INT); INSERT INTO ElectricVehicles (id,name,horsepower,release_year) VALUES (1,'Tesla Model 3',258,2020); INSERT INTO ElectricVehicles (id,name,horsepower,release_year) VALUES (2,'Nissan Leaf',147,2020);
SELECT AVG(horsepower) FROM ElectricVehicles WHERE release_year = 2020 AND horsepower IS NOT NULL;
List all ports with their corresponding cargo handling records, sorted by the date of cargo handling in descending order.
CREATE TABLE ports (id INT,name VARCHAR(50)); CREATE TABLE cargo_handling (id INT,port_id INT,date DATE,cargo_weight INT); INSERT INTO ports (id,name) VALUES (1,'PortA'),(2,'PortB'); INSERT INTO cargo_handling (id,port_id,date,cargo_weight) VALUES (1,1,'2021-01-01',5000),(2,2,'2021-02-01',6000);
SELECT ports.name, cargo_handling.date, cargo_handling.cargo_weight FROM ports INNER JOIN cargo_handling ON ports.id = cargo_handling.port_id ORDER BY cargo_handling.date DESC;
What is the total number of policy making events in each city, partitioned by event category?
CREATE TABLE PolicyEvents (city VARCHAR(50),event_category VARCHAR(50),participation INT); INSERT INTO PolicyEvents (city,event_category,participation) VALUES ('CityA','Workshop',50),('CityA','Meeting',30),('CityB','Workshop',40),('CityB','Conference',60);
SELECT city, event_category, SUM(participation) AS total_participation FROM PolicyEvents GROUP BY city, event_category;
How many unique chemical substances are there in the chemical_substances table?
CREATE TABLE chemical_substances (substance_id INT,substance_name VARCHAR(255)); INSERT INTO chemical_substances (substance_id,substance_name) VALUES (1,'SubstanceA'),(2,'SubstanceB'),(3,'SubstanceC'),(4,'SubstanceA');
SELECT COUNT(DISTINCT substance_name) AS unique_substances FROM chemical_substances;
What was the earliest excavation date for each site?
CREATE TABLE excavation_sites (site_id INT,site_name VARCHAR(50),country VARCHAR(50)); INSERT INTO excavation_sites (site_id,site_name,country) VALUES (1,'Site A','USA'); CREATE TABLE artifacts (artifact_id INT,site_id INT,excavation_date DATE);
SELECT e.site_name, MIN(a.excavation_date) as earliest_date FROM excavation_sites e JOIN artifacts a ON e.site_id = a.site_id GROUP BY e.site_id, e.site_name ORDER BY earliest_date ASC;
What is the total mass of space debris in the space_debris table, in kilograms, for debris with a known origin?
CREATE TABLE space_debris (debris_id INT,name VARCHAR(100),origin VARCHAR(100),mass FLOAT,launch_date DATE);
SELECT SUM(mass) FROM space_debris WHERE origin IS NOT NULL;
What is the average height of trees in the protected_zone table, and how does it compare to the average height of trees in the unprotected_zone table?
CREATE TABLE protected_zone (tree_id INT,species VARCHAR(50),age INT,height INT,location VARCHAR(50));CREATE TABLE unprotected_zone (tree_id INT,species VARCHAR(50),age INT,height INT,location VARCHAR(50));
SELECT AVG(height) FROM protected_zone;SELECT AVG(height) FROM unprotected_zone;
What was the average drug approval time for drugs approved in 2018?
CREATE TABLE drug_approval (drug_name VARCHAR(255),approval_date DATE); INSERT INTO drug_approval (drug_name,approval_date) VALUES ('Drug A','2018-01-01'),('Drug B','2018-06-15'),('Drug C','2018-12-25');
SELECT AVG(DATEDIFF('2018-12-31', approval_date)) FROM drug_approval;
Find the total number of evidence-based policy making data sets in 'municipality', 'city', and 'county' schemas.
CREATE SCHEMA municipality; CREATE SCHEMA city; CREATE SCHEMA county; CREATE TABLE municipality.policy_data (id INT,name VARCHAR(255),is_evidence_based BOOLEAN); CREATE TABLE city.policy_data (id INT,name VARCHAR(255),is_evidence_based BOOLEAN); CREATE TABLE county.policy_data (id INT,name VARCHAR(255),is_evidence_based BOOLEAN); INSERT INTO municipality.policy_data (id,name,is_evidence_based) VALUES (1,'transportation',true),(2,'housing',false),(3,'education',true); INSERT INTO city.policy_data (id,name,is_evidence_based) VALUES (1,'transportation',true),(2,'housing',false); INSERT INTO county.policy_data (id,name,is_evidence_based) VALUES (1,'transportation',true),(2,'health',true);
SELECT COUNT(*) FROM ( (SELECT * FROM municipality.policy_data WHERE is_evidence_based = true) UNION (SELECT * FROM city.policy_data WHERE is_evidence_based = true) UNION (SELECT * FROM county.policy_data WHERE is_evidence_based = true) ) AS combined_policy_data;
Find the average depth of all marine life research sites
CREATE TABLE marine_sites (site_id INT,site_name VARCHAR(255),longitude DECIMAL(9,6),latitude DECIMAL(9,6),depth DECIMAL(5,2));
SELECT AVG(depth) FROM marine_sites;
What is the percentage of games won by team 'Green' in the eSports tournament?
CREATE TABLE eSports_games_3 (id INT,team1 TEXT,team2 TEXT,winner TEXT); INSERT INTO eSports_games_3 (id,team1,team2,winner) VALUES (1,'Green','Blue','Green'),(2,'Yellow','Green','Yellow'),(3,'Green','Purple','Green');
SELECT (COUNT(*) FILTER (WHERE winner = 'Green')) * 100.0 / COUNT(*) FROM eSports_games_3 WHERE team1 = 'Green' OR team2 = 'Green';
Find the wells with production rates in the top 10 percentile.
CREATE TABLE wells (well_id INT,well_type VARCHAR(10),location VARCHAR(20),production_rate FLOAT); INSERT INTO wells (well_id,well_type,location,production_rate) VALUES (1,'offshore','Gulf of Mexico',1000),(2,'onshore','Texas',800),(3,'offshore','North Sea',1200),(4,'onshore','Alberta',900);
SELECT * FROM (SELECT well_id, well_type, location, production_rate, PERCENT_RANK() OVER (ORDER BY production_rate DESC) pr FROM wells) t WHERE pr >= 0.9;