instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
Find the number of eco-certified accommodations in France
CREATE TABLE accommodations (id INT,country VARCHAR(50),is_eco_certified BOOLEAN); INSERT INTO accommodations (id,country,is_eco_certified) VALUES (1,'France',TRUE),(2,'Italy',FALSE);
SELECT COUNT(*) FROM accommodations WHERE country = 'France' AND is_eco_certified = TRUE;
Find the total number of citizen complaints submitted by users from 'Toronto' and 'Montreal' in the 'complaints' table, excluding duplicate entries.
CREATE TABLE users (id INT PRIMARY KEY,city VARCHAR(255));CREATE TABLE complaints (id INT PRIMARY KEY,user_id INT,title VARCHAR(255));
SELECT COUNT(DISTINCT c.id) FROM complaints c JOIN users u ON c.user_id = u.id WHERE u.city IN ('Toronto', 'Montreal');
Identify the garment with the highest retail price for each fabric type.
CREATE TABLE Garments (garment_id INT,garment_name VARCHAR(50),retail_price DECIMAL(5,2),fabric VARCHAR(50)); INSERT INTO Garments (garment_id,garment_name,retail_price,fabric) VALUES (1,'Sequin Evening Gown',850.99,'Sequin'),(2,'Cashmere Sweater',250.00,'Cashmere'),(3,'Silk Blouse',150.00,'Silk');
SELECT garment_name, retail_price, fabric FROM (SELECT garment_name, retail_price, fabric, ROW_NUMBER() OVER (PARTITION BY fabric ORDER BY retail_price DESC) as rn FROM Garments) sub WHERE rn = 1;
Update the country of an employee in the Employees table.
CREATE TABLE Employees (id INT,name VARCHAR(100),department VARCHAR(50),country VARCHAR(50)); INSERT INTO Employees (id,name,department,country) VALUES (1,'John Doe','IT','United States'),(2,'Jane Smith','Marketing','Canada'),(3,'Mike Johnson','IT','France'),(4,'Sara Connor','HR','United States'),(5,'David Brown','Fina...
UPDATE Employees SET country = 'Germany' WHERE id = 3;
What is the latest contract value and date for each vendor?
CREATE TABLE vendors (vendor_id INT,vendor_name TEXT,contract_value DECIMAL(10,2),contract_date DATE); INSERT INTO vendors VALUES (1,'VendorA',500000,'2021-01-01'),(2,'VendorB',700000,'2021-02-01');
SELECT vendor_name, MAX(contract_date) AS latest_date, MAX(contract_value) OVER (PARTITION BY vendor_name) AS latest_value FROM vendors;
Find the number of rural infrastructure projects in the 'rural_infrastructure' table, ordered by the start date.
CREATE TABLE rural_infrastructure (id INT,project_name VARCHAR(255),start_date DATE); INSERT INTO rural_infrastructure (id,project_name,start_date) VALUES (1,'Road Construction','2021-01-01'),(2,'Bridge Building','2020-06-15');
SELECT COUNT(*) FROM rural_infrastructure ORDER BY start_date
How many autonomous taxis were in service in New York City each month in 2021?
CREATE TABLE autonomous_taxis (taxi_id INT,registration_date DATE,deregistration_date DATE); INSERT INTO autonomous_taxis (taxi_id,registration_date,deregistration_date) VALUES (1,'2021-01-01','2022-01-01'),(2,'2021-02-01','2022-02-01'),(3,'2021-03-01','2022-03-01');
SELECT EXTRACT(MONTH FROM registration_date) AS month, COUNT(DISTINCT taxi_id) AS taxis_in_service FROM autonomous_taxis WHERE deregistration_date > '2021-12-31' GROUP BY month
Update the Instagram engagement metrics to reflect an increase in likes
CREATE TABLE social_media_engagement (id INT PRIMARY KEY,platform VARCHAR(15),likes INT,shares INT,comments INT);
UPDATE social_media_engagement SET likes = 600 WHERE platform = 'Instagram';
What's the total number of workers in the mining industry, categorized by their job roles?
CREATE TABLE workforce (id INT PRIMARY KEY,name VARCHAR(50),ethnicity VARCHAR(50),role VARCHAR(50)); INSERT INTO workforce (id,name,ethnicity,role) VALUES (1,'John Doe','Caucasian','Miner'),(2,'Jane Smith','African American','Engineer'),(3,'Alberto Garcia','Hispanic','Manager');
SELECT role, COUNT(*) as total_workers FROM workforce GROUP BY role;
Determine the number of times menu items are prepared with plastic utensils and potential cost savings by switching to compostable alternatives.
CREATE TABLE menus (menu_item_name VARCHAR(255),daily_sales INT); CREATE TABLE utensils (utensil_type VARCHAR(255),daily_usage INT,cost_per_unit DECIMAL(10,2),is_compostable BOOLEAN);
SELECT m.menu_item_name, SUM(u.daily_usage) as plastic_utensils_used, (SUM(u.daily_usage) * u.cost_per_unit) as current_cost, ((SUM(u.daily_usage) * uc.cost_per_unit) - (SUM(u.daily_usage) * u.cost_per_unit)) as potential_savings FROM menus m CROSS JOIN utensils u INNER JOIN utensils uc ON u.utensil_type = uc.utensil_t...
List all the deep-sea expeditions in the Atlantic Ocean in 2019.
CREATE TABLE expeditions (id INT,location VARCHAR(50),year INT,type VARCHAR(20)); INSERT INTO expeditions (id,location,year,type) VALUES (1,'Atlantic Ocean',2018,'Research'),(2,'Atlantic Ocean',2019,NULL),(3,'Atlantic Ocean',2020,'Exploration');
SELECT * FROM expeditions WHERE location = 'Atlantic Ocean' AND year = 2019;
Which countries source the most organic ingredients for our cosmetics products?
CREATE TABLE ingredient_source (ingredient_id INT,country VARCHAR(50),is_organic BOOLEAN); INSERT INTO ingredient_source (ingredient_id,country,is_organic) VALUES (1,'USA',true),(2,'Canada',false),(3,'Mexico',true);
SELECT country, COUNT(ingredient_id) as organic_ingredient_count FROM ingredient_source WHERE is_organic = true GROUP BY country ORDER BY organic_ingredient_count DESC;
Show the total revenue for each platform for the 'Classical' genre in the first quarter of 2021.
CREATE TABLE Revenue (RevenueId INT,Platform VARCHAR(255),Genre VARCHAR(255),Revenue DECIMAL(10,2),Date DATE); INSERT INTO Revenue (RevenueId,Platform,Genre,Revenue,Date) VALUES (1,'Spotify','Classical',1000,'2021-01-01'),(2,'Apple Music','Classical',1500,'2021-01-01'),(3,'Deezer','Classical',800,'2021-01-01'),(4,'Tida...
SELECT Platform, Genre, SUM(Revenue) AS TotalRevenue FROM Revenue WHERE Genre = 'Classical' AND Date BETWEEN '2021-01-01' AND '2021-03-31' GROUP BY Platform;
What is the minimum horsepower of electric vehicles in the 'GreenAutos' database?
CREATE TABLE ElectricVehicles (Id INT,Make VARCHAR(50),Model VARCHAR(50),Year INT,Horsepower INT);
SELECT MIN(Horsepower) FROM ElectricVehicles WHERE FuelType = 'Electric';
What is the average price of fair trade coffee in Germany compared to the global average?
CREATE TABLE Coffee (country VARCHAR(50),price INT,fair_trade BOOLEAN); INSERT INTO Coffee (country,price,fair_trade) VALUES ('Germany',12,1),('USA',10,1),('Brazil',8,0),('Vietnam',6,0);
SELECT AVG(price) AS average_price FROM Coffee WHERE fair_trade = 1 AND country = 'Germany';
What is the total funding allocated to rural infrastructure projects in the 'rural_infrastructure' table, that are located in the Northeast region?
CREATE TABLE rural_infrastructure (id INT,project_name TEXT,location TEXT,start_date DATE,funding_amount FLOAT); INSERT INTO rural_infrastructure (id,project_name,location,start_date,funding_amount) VALUES (1,'Road Expansion','Northeast','2020-06-01',200000.00),(2,'Water Treatment','Southeast','2019-12-31',300000.00);
SELECT SUM(funding_amount) FROM rural_infrastructure WHERE location = 'Northeast';
What are the total donation amounts by city?
CREATE TABLE donations (id INT,city VARCHAR(50),amount DECIMAL(10,2)); INSERT INTO donations (id,city,amount) VALUES (1,'New York',150.00),(2,'Los Angeles',200.00),(3,'Chicago',100.00);
SELECT city, SUM(amount) as total_donations FROM donations GROUP BY city;
What is the total expenditure on tourism in Australia in 2020?
CREATE TABLE aus_expenditure (country VARCHAR(50),year INT,expenditure INT); INSERT INTO aus_expenditure (country,year,expenditure) VALUES ('Australia',2020,8000000000);
SELECT expenditure FROM aus_expenditure WHERE country = 'Australia' AND year = 2020;
List all energy storage systems in the 'energy_storage' schema.
CREATE SCHEMA energy_storage; CREATE TABLE energy_storage_systems (name TEXT,capacity INTEGER); INSERT INTO energy_storage_systems (name,capacity) VALUES ('System A',400),('System B',800);
SELECT * FROM energy_storage.energy_storage_systems;
What is the average habitat size in square kilometers for each habitat type in the North American conservation programs?
CREATE TABLE north_american_habitats (habitat_type VARCHAR(50),size INT); INSERT INTO north_american_habitats (habitat_type,size) VALUES ('Forests',5000),('Wetlands',3000),('Grasslands',7000);
SELECT habitat_type, AVG(size) FROM north_american_habitats GROUP BY habitat_type;
List the wastewater treatment facilities in Argentina and their capacities?
CREATE TABLE treatment_facilities_AR (name VARCHAR(50),country VARCHAR(20),capacity INT); INSERT INTO treatment_facilities_AR (name,country,capacity) VALUES ('Facility1','Argentina',5000),('Facility2','Argentina',7000);
SELECT name, capacity FROM treatment_facilities_AR WHERE country = 'Argentina';
What is the average population served per hospital?
CREATE TABLE rural_hospitals(hospital_id INT PRIMARY KEY,name VARCHAR(255),bed_count INT,rural_population_served INT);
SELECT AVG(rural_population_served) FROM rural_hospitals;
How many mobile subscribers have a subscription fee greater than the average subscription fee in the 'mobile_subscriber' table?
CREATE TABLE mobile_subscriber (subscriber_id INT,subscription_start_date DATE,subscription_fee DECIMAL(10,2)); INSERT INTO mobile_subscriber (subscriber_id,subscription_start_date,subscription_fee) VALUES (1,'2020-01-01',30.00),(2,'2019-06-15',40.00),(3,'2021-02-20',35.00);
SELECT COUNT(*) FROM mobile_subscriber WHERE subscription_fee > (SELECT AVG(subscription_fee) FROM mobile_subscriber);
What is the earliest start date for completed projects for community development initiatives in South America?
CREATE TABLE CommunityProjects (ProjectID INT,ProjectName VARCHAR(50),Location VARCHAR(50),StartDate DATE,CompletionDate DATE); INSERT INTO CommunityProjects (ProjectID,ProjectName,Location,StartDate,CompletionDate) VALUES (1,'Clean Water Project','Brazil','2016-01-01','2017-12-31'),(2,'Renewable Energy Initiative','Ar...
SELECT MIN(StartDate) FROM CommunityProjects WHERE Location IN ('Brazil', 'Argentina') AND CompletionDate IS NOT NULL;
What is the average water temperature in freshwater mollusk farms in the Northern Hemisphere over the past year?
CREATE TABLE mollusk_farms (id INT,name TEXT,type TEXT,location TEXT,water_temp FLOAT,record_date DATE); INSERT INTO mollusk_farms (id,name,type,location,water_temp,record_date) VALUES (1,'Farm S','Mollusk','Canada',15.0,'2022-03-10'),(2,'Farm T','Mollusk','Alaska',12.5,'2022-02-15');
SELECT AVG(water_temp) FROM mollusk_farms WHERE type = 'Mollusk' AND location IN (SELECT location FROM mollusk_farms WHERE biomass IS NOT NULL GROUP BY location HAVING EXTRACT(HOUR FROM AVG(location)) < 12) AND record_date BETWEEN DATE('now', '-1 year') AND DATE('now');
What is the maximum budget for humanitarian assistance operations in Asia in 2018?
CREATE TABLE HumanitarianAssistance (id INT PRIMARY KEY,operation VARCHAR(100),location VARCHAR(50),year INT,budget INT); INSERT INTO HumanitarianAssistance (id,operation,location,year,budget) VALUES (1,'Asia Quake Relief','Nepal',2018,567890123);
SELECT MAX(budget) FROM HumanitarianAssistance WHERE location LIKE '%Asia%' AND year = 2018;
What is the average number of peacekeeping personnel per operation?
CREATE TABLE peacekeeping_ops (operation_id INT,num_personnel INT);
SELECT AVG(num_personnel) FROM peacekeeping_ops;
What is the total sum of interest-free loans issued to clients in rural areas?
CREATE TABLE loans (id INT,client_name VARCHAR(50),issue_date DATE,amount FLOAT,interest_free BOOLEAN);
SELECT SUM(amount) FROM loans WHERE interest_free = TRUE AND location LIKE '%rural%';
How many tickets were sold for each event in 'events' table?
CREATE TABLE events (id INT PRIMARY KEY,name VARCHAR(100),date DATE,location VARCHAR(100),tickets_sold INT);
SELECT name, tickets_sold FROM events GROUP BY name;
Which artist had the highest revenue generated from sales at the "National Gallery" in 2021?
CREATE TABLE ArtistSales3 (GalleryName TEXT,ArtistName TEXT,NumPieces INTEGER,PricePerPiece FLOAT); INSERT INTO ArtistSales3 (GalleryName,ArtistName,NumPieces,PricePerPiece) VALUES ('National Gallery','Picasso',14,95.5),('National Gallery','Dali',16,85.0),('National Gallery','Mondrian',19,90.0);
SELECT ArtistName, SUM(NumPieces * PricePerPiece) AS Revenue FROM ArtistSales3 WHERE GalleryName = 'National Gallery' AND YEAR(SaleDate) = 2021 GROUP BY ArtistName ORDER BY Revenue DESC LIMIT 1;
Get the daily active user count for India in November 2021.
CREATE TABLE if not exists activity (user_id INT,country VARCHAR(50),activity_date DATE,year INT,month INT,day INT); INSERT INTO activity (user_id,country,activity_date) VALUES (1,'India','2021-11-01'),(2,'India','2021-11-02');
SELECT COUNT(DISTINCT user_id) FROM activity WHERE country = 'India' AND month = 11 AND year = 2021;
Delete all records from the "activities" table where the activity type is "hiking"
CREATE TABLE activities (id INT PRIMARY KEY,name TEXT,type TEXT); INSERT INTO activities (id,name,type) VALUES (1,'Hiking in the Alps','hiking'); INSERT INTO activities (id,name,type) VALUES (2,'Scuba Diving in the Red Sea','diving');
DELETE FROM activities WHERE type = 'hiking';
How many criminal cases were handled by attorney 'John Doe'?
CREATE TABLE cases (case_id INT,attorney_name VARCHAR(50),case_type VARCHAR(50)); INSERT INTO cases (case_id,attorney_name,case_type) VALUES (1,'John Doe','criminal'),(2,'Jane Smith','civil'),(3,'John Doe','family');
SELECT COUNT(*) FROM cases WHERE attorney_name = 'John Doe' AND case_type = 'criminal';
What contemporary artists have explored the theme of climate change in their installations, and what countries are they from?
CREATE TABLE Artists (ArtistID INT,Name VARCHAR(50),Nationality VARCHAR(50)); CREATE TABLE Installations (InstallationID INT,ArtistID INT,Title VARCHAR(50),Theme VARCHAR(50)); INSERT INTO Artists VALUES (1,'Olafur Eliasson','Iceland'); INSERT INTO Installations VALUES (1,1,'Ice Watch','Climate Change');
SELECT a.Name, a.Nationality FROM Artists a INNER JOIN Installations i ON a.ArtistID = i.ArtistID WHERE i.Theme = 'Climate Change';
Delete the 'Foundation' product with the lowest rating.
CREATE TABLE Products (ProductID int,ProductName varchar(50),Category varchar(50),Rating float); INSERT INTO Products (ProductID,ProductName,Category,Rating) VALUES (1,'Foundation A','Foundation',3.5),(2,'Foundation B','Foundation',4.2),(3,'Lipstick C','Lipstick',4.7);
DELETE FROM Products WHERE Category = 'Foundation' AND Rating = (SELECT MIN(Rating) FROM Products WHERE Category = 'Foundation');
Which cybersecurity strategies were implemented in the last year and what were their budgets from the 'cyber_strategies' table?
CREATE TABLE cyber_strategies (id INT,strategy_name VARCHAR(255),strategy_date DATE,budget DECIMAL(10,2));
SELECT strategy_name, strategy_date, budget FROM cyber_strategies WHERE strategy_date >= DATE(NOW()) - INTERVAL 1 YEAR;
What is the average number of employees in circular economy companies in France?
CREATE TABLE companies (id INT,name VARCHAR(50),country VARCHAR(50),circular INT,employees INT);
SELECT AVG(employees) FROM companies WHERE country = 'France' AND circular = 1;
Delete records of healthcare workers older than 50 in the "rural_hospitals" table.
CREATE TABLE rural_hospitals (id INT,name TEXT,location TEXT,age INT,position TEXT); INSERT INTO rural_hospitals (id,name,location,age,position) VALUES (1,'Hospital A','Rural Area 1',55,'Doctor'),(2,'Hospital B','Rural Area 2',48,'Nurse');
DELETE FROM rural_hospitals WHERE age > 50;
Show the number of days in 2023 where there were at least two emergency calls
CREATE TABLE emergency_calls_2023 (id INT,call_date DATE); INSERT INTO emergency_calls_2023 (id,call_date) VALUES (1,'2023-01-01'),(2,'2023-01-02'),(3,'2023-01-03'),(4,'2023-02-01'),(5,'2023-02-02'),(6,'2023-03-01'),(7,'2023-03-01'),(8,'2023-03-01');
SELECT call_date FROM emergency_calls_2023 GROUP BY call_date HAVING COUNT(*) >= 2;
Update the 'end_date' column in the 'climate_adaptation_measures' table where the 'id' is 2
CREATE TABLE climate_adaptation_measures (id INT,measure VARCHAR(255),start_date DATE,end_date DATE);
UPDATE climate_adaptation_measures SET end_date = '2026-12-31' WHERE id = 2;
What are the job titles and salaries of all veterans employed in the IT industry in the state of New York?
CREATE TABLE VeteranEmployment (employee_id INT,name VARCHAR(255),job_title VARCHAR(255),industry VARCHAR(255),state VARCHAR(255),salary FLOAT); INSERT INTO VeteranEmployment (employee_id,name,job_title,industry,state,salary) VALUES (1,'John Doe','Software Engineer','IT','New York',80000),(2,'Jane Smith','Data Analyst'...
SELECT job_title, salary FROM VeteranEmployment WHERE industry = 'IT' AND state = 'New York';
What is the average price of vegan dishes in each category?
CREATE TABLE menu_categories (category_id INT,category VARCHAR(255));
SELECT category, AVG(price) as avg_price FROM menus JOIN menu_categories ON menus.category = menu_categories.category WHERE menus.category IN ('vegan appetizers', 'vegan entrees', 'vegan desserts') GROUP BY category;
What are the combined costs of the top 2 most expensive community development projects in the 'rural_infrastructure' table?
CREATE TABLE rural_infrastructure (id INT,project_name VARCHAR(50),project_type VARCHAR(50),community_type VARCHAR(50),cost DECIMAL(10,2)); INSERT INTO rural_infrastructure VALUES (1,'Solar Irrigation System','Agricultural Innovation','Indigenous',25000.00),(2,'Modern Greenhouse','Agricultural Innovation','Farmers Asso...
SELECT SUM(cost) FROM (SELECT * FROM (SELECT * FROM rural_infrastructure WHERE project_type = 'Agricultural Innovation' ORDER BY cost DESC LIMIT 2) ORDER BY cost DESC);
Identify the top 5 animal species with the highest conservation spending.
CREATE TABLE conservation_funding (id INT,animal_species VARCHAR(255),spending FLOAT,year INT);
SELECT animal_species, SUM(spending) as total_spending FROM conservation_funding GROUP BY animal_species ORDER BY total_spending DESC LIMIT 5;
What is the number of projects in each category?
CREATE TABLE Infrastructure (id INT,category VARCHAR(20)); INSERT INTO Infrastructure (id,category) VALUES (1,'Transportation'),(2,'WaterSupply'),(3,'Transportation'),(4,'WaterSupply'),(5,'SewerSystems');
SELECT category, COUNT(*) FROM Infrastructure GROUP BY category;
Insert a new artwork into the artworks table with the title 'The Starry Night', created by 'Vincent van Gogh' in 1889, and associated with the style 'Post-Impressionism'.
CREATE TABLE art_styles (id INT,style VARCHAR(255),movement VARCHAR(255)); INSERT INTO art_styles (id,style,movement) VALUES (1,'Post-Impressionism','Post-Impressionist Movement'); CREATE TABLE artworks (id INT,title VARCHAR(255),year INT,style_id INT);
INSERT INTO artworks (id, title, year, style_id) SELECT 1, 'The Starry Night', 1889, s.id FROM art_styles s WHERE s.style = 'Post-Impressionism';
What is the success rate (exit or IPO) of startups founded by immigrants?
CREATE TABLE company (id INT,name TEXT,founding_year INT,founder_immigrant TEXT); INSERT INTO company (id,name,founding_year,founder_immigrant) VALUES (1,'Acme Corp',2010,'No'),(2,'Beta Inc',2012,'Yes'); CREATE TABLE exit (id INT,company_id INT,exit_type TEXT); INSERT INTO exit (id,company_id,exit_type) VALUES (1,1,'Ac...
SELECT COUNT(*) * 100.0 / (SELECT COUNT(*) FROM company WHERE founder_immigrant = 'Yes') AS success_rate FROM exit WHERE company_id IN (SELECT id FROM company WHERE founder_immigrant = 'Yes');
What is the percentage of fair trade products by category?
CREATE TABLE FairTradeProducts (product_id INT,product_name VARCHAR(255),category VARCHAR(255),is_fair_trade BOOLEAN); INSERT INTO FairTradeProducts (product_id,product_name,category,is_fair_trade) VALUES (1,'Organic Cotton T-Shirt','Tops',true),(2,'Conventional Cotton Pants','Bottoms',false),(3,'Fair Trade Coffee','Fo...
SELECT category, ROUND(COUNT(*) FILTER (WHERE is_fair_trade = true) * 100.0 / COUNT(*), 2) as fair_trade_percentage FROM FairTradeProducts GROUP BY category;
What are the names of the top 2 ingredients used in cosmetic products certified as vegan and launched in 2019?
CREATE TABLE ingredients (ingredient_id INT,product_id INT,ingredient_name VARCHAR(100),source_country VARCHAR(50),launch_year INT,is_vegan BOOLEAN); INSERT INTO ingredients (ingredient_id,product_id,ingredient_name,source_country,launch_year,is_vegan) VALUES (1,1,'Beeswax','France',2020,false),(2,2,'Water','Canada',20...
SELECT ingredient_name FROM ingredients WHERE is_vegan = true AND launch_year = 2019 GROUP BY ingredient_name ORDER BY COUNT(*) DESC LIMIT 2;
What is the total capacity of shelters with a capacity less than 50 in 'south_america' region?
CREATE TABLE region (region_id INT,name VARCHAR(255)); INSERT INTO region (region_id,name) VALUES (1,'south_america'); CREATE TABLE shelter (shelter_id INT,name VARCHAR(255),region_id INT,capacity INT); INSERT INTO shelter (shelter_id,name,region_id,capacity) VALUES (1,'Shelter1',1,50),(2,'Shelter2',1,75);
SELECT SUM(capacity) FROM shelter WHERE region_id = (SELECT region_id FROM region WHERE name = 'south_america') AND capacity < 50;
Which space missions have had incidents?
CREATE TABLE space_missions (mission_id INT,name VARCHAR(100),launch_date DATE); CREATE TABLE mission_incidents (mission_id INT,incident_count INT); INSERT INTO space_missions (mission_id,name,launch_date) VALUES (1,'Mission1','2010-05-05'); INSERT INTO mission_incidents (mission_id,incident_count) VALUES (1,3);
SELECT space_missions.name FROM space_missions INNER JOIN mission_incidents ON space_missions.mission_id = mission_incidents.mission_id WHERE mission_incidents.incident_count > 0;
What was the most popular eco-tourist destination in Oceania in 2021?
CREATE TABLE eco_tourists (id INT,continent VARCHAR(50),country VARCHAR(50),eco_visitors INT,year INT); INSERT INTO eco_tourists (id,continent,country,eco_visitors,year) VALUES (1,'Oceania','Australia',2000,2021),(2,'Oceania','New Zealand',1500,2021);
SELECT country, MAX(eco_visitors) FROM eco_tourists WHERE continent = 'Oceania' AND year = 2021 GROUP BY country;
What are the average construction costs for all water treatment facilities in the Great Plains region?
CREATE TABLE water_treatment (project_id INT,project_name VARCHAR(100),state CHAR(2),construction_cost FLOAT); INSERT INTO water_treatment VALUES (1,'Denver Water Treatment Plant Expansion','CO',100000000),(2,'Kansas City Water Treatment Plant Upgrade','MO',80000000),(3,'Oklahoma City Water Treatment Plant Modernizatio...
SELECT AVG(construction_cost) FROM water_treatment WHERE state IN ('CO', 'KS', 'MT', 'NE', 'ND', 'SD', 'OK', 'TX', 'WY');
What is the average total cost of projects in the water division?
CREATE TABLE Projects (id INT,division VARCHAR(20),total_cost FLOAT); INSERT INTO Projects (id,division,total_cost) VALUES (1,'water',500000),(2,'transportation',300000),(3,'water',750000);
SELECT AVG(total_cost) FROM Projects WHERE division = 'water';
What is the average carbon sequestration rate for each tree species in the year 2005?
CREATE TABLE TreeSpecies (id INT,name VARCHAR(255)); INSERT INTO TreeSpecies (id,name) VALUES (1,'Pine'),(2,'Oak'),(3,'Maple'),(4,'Birch'); CREATE TABLE CarbonSeq (id INT,tree_species_id INT,year INT,rate FLOAT); INSERT INTO CarbonSeq (id,tree_species_id,year,rate) VALUES (1,1,2000,2.5),(2,1,2005,3.0),(3,2,2000,4.0),(4...
SELECT ts.id, ts.name, AVG(cs.rate) AS avg_rate FROM TreeSpecies ts JOIN CarbonSeq cs ON ts.id = cs.tree_species_id WHERE cs.year = 2005 GROUP BY ts.id;
What is the number of renewable energy projects per region?
CREATE TABLE projects_by_region (region VARCHAR(50),project_count INT); INSERT INTO projects_by_region (region,project_count) VALUES ('East',150),('Central',250),('West',350);
SELECT region, project_count FROM projects_by_region;
What is the average movie duration for French films directed by women?
CREATE TABLE movies (id INT,title VARCHAR(255),duration INT,production_country VARCHAR(64),director_id INT,PRIMARY KEY (id),FOREIGN KEY (director_id) REFERENCES directors(id)); CREATE TABLE directors (id INT,name VARCHAR(255),gender VARCHAR(8),PRIMARY KEY (id)); INSERT INTO directors (id,name,gender) VALUES (1,'Directo...
SELECT AVG(movies.duration) FROM movies INNER JOIN directors ON movies.director_id = directors.id WHERE directors.gender = 'Female' AND movies.production_country = 'France';
How many donors are there in each age group?
CREATE TABLE donors (id INT,first_name VARCHAR(20),last_name VARCHAR(20),dob DATE); CREATE VIEW age_groups AS SELECT 1 AS id,'Under 18' AS name UNION ALL SELECT 2 AS id,'18-24' AS name UNION ALL SELECT 3 AS id,'25-34' AS name UNION ALL SELECT 4 AS id,'35-44' AS name UNION ALL SELECT 5 AS id,'45-54' AS name UNION ALL SE...
SELECT ag.name, COUNT(d.id) as donor_count FROM donors d JOIN age_groups ag ON FLOOR(DATEDIFF('year', d.dob, CURDATE()) / 10) + 1 = ag.id GROUP BY ag.id;
Calculate the average number of charging stations per city for cities with more than 1 million people in the cities and ev_charging_stations tables
CREATE TABLE city_demographics (id INT PRIMARY KEY,city VARCHAR(255),population INT);
SELECT AVG(num_chargers) FROM (SELECT cities.city_name as city, COUNT(*) as num_chargers FROM cities JOIN ev_charging_stations ON cities.city_name LIKE CONCAT('%', ev_charging_stations.location, '%') GROUP BY cities.city_name HAVING population > 1000000) AS charging_cities;
How many marine species are present in the 'Coral Reef' habitat type, and what is the total biomass of those species?
CREATE TABLE marine_species (id INT,species_name TEXT,habitat_type TEXT,biomass FLOAT); INSERT INTO marine_species (id,species_name,habitat_type,biomass) VALUES (1,'Species 1','Coral Reef',10),(2,'Species 2','Coral Reef',15),(3,'Species 3','Open Ocean',20);
SELECT COUNT(*), SUM(biomass) FROM marine_species WHERE habitat_type = 'Coral Reef';
What is the total number of articles published by each author in the 'investigative_reports' table?
CREATE TABLE investigative_reports (id INT,author VARCHAR(255),title VARCHAR(255),publication_date DATE);
SELECT author, COUNT(*) as total_articles FROM investigative_reports GROUP BY author;
Update ticket prices for a specific event, identified by its event ID.
CREATE TABLE salesperson (salesperson_id INT,name VARCHAR(50),position VARCHAR(50)); CREATE TABLE tickets (ticket_id INT,salesperson_id INT,event_id INT,price DECIMAL(5,2),quantity INT); CREATE TABLE events (event_id INT,name VARCHAR(50),date DATE); INSERT INTO tickets VALUES (1,1,1,50,100); INSERT INTO events VALUES (...
UPDATE tickets t SET t.price = 60 WHERE t.event_id = 1;
What is the total amount of gold extracted in the 'production_data' table for the month of January 2022?
CREATE TABLE production_data (id INT,date DATE,coal_production INT,gold_production INT); INSERT INTO production_data (id,date,coal_production,gold_production) VALUES (1,'2022-01-01',200,10); INSERT INTO production_data (id,date,coal_production,gold_production) VALUES (2,'2022-01-02',250,15);
SELECT SUM(gold_production) as total_gold_production FROM production_data WHERE date BETWEEN '2022-01-01' AND '2022-01-31';
List all companies in the "Sustainability_2022" table with a higher rating than the average rating
CREATE TABLE Sustainability_2022 (id INT,company VARCHAR(50),rating DECIMAL(2,1),year INT); INSERT INTO Sustainability_2022 (id,company,rating,year) VALUES (1,'CompanyA',3.7,2022),(2,'CompanyB',4.1,2022),(3,'CompanyC',2.9,2022);
SELECT company FROM Sustainability_2022 WHERE rating > (SELECT AVG(rating) FROM Sustainability_2022);
What is the average hourly wage for construction workers in the sustainable building sector, compared to the traditional construction sector, over the past 6 months?
CREATE TABLE LaborStatistics (StatID INT,Gender TEXT,Age INT,JobCategory TEXT,HourlyWage NUMERIC,DateRecorded DATE);
SELECT AVG(HourlyWage) AS AvgHourlyWage FROM LaborStatistics WHERE JobCategory = 'Sustainable Building' AND DateRecorded >= DATEADD(month, -6, GETDATE()) UNION ALL SELECT AVG(HourlyWage) FROM LaborStatistics WHERE JobCategory = 'Traditional Construction' AND DateRecorded >= DATEADD(month, -6, GETDATE());
List all technology for social good initiatives in Africa, ordered by their budget.
CREATE TABLE african_initiatives (initiative VARCHAR(50),budget INT); INSERT INTO african_initiatives (initiative,budget) VALUES ('Solar power project',100000),('Clean water access program',150000),('Healthcare software',200000);
SELECT initiative FROM african_initiatives ORDER BY budget;
What is the total transaction amount for each customer in the "investment" category?
CREATE TABLE customers (id INT,name VARCHAR(50),category VARCHAR(50)); INSERT INTO customers (id,name,category) VALUES (1,'John Doe','investment'); INSERT INTO customers (id,name,category) VALUES (2,'Jane Smith','savings'); INSERT INTO customers (id,name,category) VALUES (3,'Jim Brown','investment'); CREATE TABLE trans...
SELECT c.name, SUM(t.amount) as total_amount FROM customers c INNER JOIN transactions t ON c.id = t.customer_id WHERE c.category = 'investment' GROUP BY c.name;
List the number of marine species in each order in the 'species_orders' table, sorted by the number of species in descending order.
CREATE TABLE species_orders (order_id INT,order_name VARCHAR(50),species_count INT);
SELECT order_name, COUNT(*) FROM species_orders GROUP BY order_id ORDER BY species_count DESC;
What is the average claim amount for policyholders from Texas?
CREATE TABLE policyholders (id INT,name TEXT,age INT,gender TEXT,policy_type TEXT,state TEXT); INSERT INTO policyholders (id,name,age,gender,policy_type,state) VALUES (1,'John Doe',35,'Male','Auto','Texas'); INSERT INTO policyholders (id,name,age,gender,policy_type,state) VALUES (2,'Jane Smith',42,'Female','Home','Texa...
SELECT AVG(claim_amount) FROM claims JOIN policyholders ON claims.policyholder_id = policyholders.id WHERE policyholders.state = 'Texas';
Who is the oldest member with a 'Gold' membership?
CREATE TABLE Members (MemberID INT,Age INT,MembershipType VARCHAR(20)); INSERT INTO Members (MemberID,Age,MembershipType) VALUES (1,42,'Gold'),(2,35,'Platinum'),(3,50,'Gold');
SELECT MemberID, Age FROM Members WHERE MembershipType = 'Gold' ORDER BY Age DESC LIMIT 1;
What is the total waste generation in grams for the top 2 countries in 2020, ordered by the greatest total amount?
CREATE TABLE waste_generation (country VARCHAR(50),year INT,waste_generation_grams INT); INSERT INTO waste_generation (country,year,waste_generation_grams) VALUES ('Canada',2020,5000000),('Mexico',2020,6000000),('Brazil',2020,7000000);
SELECT country, SUM(waste_generation_grams) as total_waste_generation_2020 FROM waste_generation WHERE year = 2020 GROUP BY country ORDER BY total_waste_generation_2020 DESC LIMIT 2;
List the dams in Texas that were constructed in the 1980s.
CREATE TABLE Dams(id INT,name TEXT,location TEXT,built DATE); INSERT INTO Dams(id,name,location,built) VALUES (1,'Amistad Dam','Texas','1969-09-28');
SELECT name FROM Dams WHERE location = 'Texas' AND built BETWEEN '1980-01-01' AND '1989-12-31';
What is the total waste generation by city and region in the year 2021?
CREATE TABLE WasteGeneration (city VARCHAR(255),region VARCHAR(255),year INT,waste_quantity INT); INSERT INTO WasteGeneration (city,region,year,waste_quantity) VALUES ('CityA','RegionA',2021,1500),('CityB','RegionA',2021,1200),('CityC','RegionB',2021,1800);
SELECT city, region, SUM(waste_quantity) FROM WasteGeneration WHERE year = 2021 GROUP BY city, region;
List the names and ages of healthcare workers in California.
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 name, age FROM healthcare_workers WHERE location = 'California';
Show total billing amounts for attorney 'Sophia Garcia'
CREATE TABLE attorneys (id INT,name VARCHAR(50),department VARCHAR(20)); CREATE TABLE cases (id INT,attorney_id INT,case_number VARCHAR(20),billing_amount DECIMAL(10,2)); INSERT INTO attorneys (id,name,department) VALUES (1,'Sophia Garcia','civil'); INSERT INTO cases (id,attorney_id,case_number,billing_amount) VALUES (...
SELECT SUM(billing_amount) FROM cases WHERE attorney_id = (SELECT id FROM attorneys WHERE name = 'Sophia Garcia');
Delete the record with the highest waste generation in grams for Brazil in 2019.
CREATE TABLE waste_generation (country VARCHAR(50),year INT,waste_generation_grams INT); INSERT INTO waste_generation (country,year,waste_generation_grams) VALUES ('Brazil',2019,1000000),('Brazil',2019,1200000);
DELETE FROM waste_generation WHERE country = 'Brazil' AND year = 2019 AND waste_generation_grams = (SELECT MAX(waste_generation_grams) FROM waste_generation WHERE country = 'Brazil' AND year = 2019);
What is the percentage of players in each game category with a score above the average score for that category?
CREATE TABLE CategoryScores (PlayerID int,PlayerName varchar(50),Game varchar(50),Category varchar(50),Score int); INSERT INTO CategoryScores (PlayerID,PlayerName,Game,Category,Score) VALUES (1,'Player1','Game1','Action',1000),(2,'Player2','Game2','RPG',1200),(3,'Player3','Game3','Strategy',1400),(4,'Player4','Game1','...
SELECT Category, COUNT(*) as NumPlayers, AVG(Score) OVER (PARTITION BY Category) as AvgScore, COUNT(*) FILTER (WHERE Score > AVG(Score) OVER (PARTITION BY Category)) * 100.0 / COUNT(*) as Percentage FROM CategoryScores GROUP BY Category;
Delete all firewall rules that have not been modified in the past year.
CREATE TABLE firewall_rules (rule_id INT PRIMARY KEY,last_modified DATE);
DELETE FROM firewall_rules WHERE last_modified < DATEADD(year, -1, GETDATE());
What are the names of all the workforce development programs?
CREATE TABLE workforce_development (id INT,name VARCHAR(255),location VARCHAR(255)); INSERT INTO workforce_development (id,name,location) VALUES (1,'Sustainable Manufacturing Bootcamp','USA'); INSERT INTO workforce_development (id,name,location) VALUES (2,'Green Jobs Apprenticeship','Canada');
SELECT name FROM workforce_development;
Which hotel in the 'hotel_tech_adoption' table has the highest number of AI-powered features?
CREATE TABLE hotel_tech_adoption (hotel_id INT,hotel_name TEXT,ai_powered_features INT); INSERT INTO hotel_tech_adoption (hotel_id,hotel_name,ai_powered_features) VALUES (1,'The Oberoi',7),(2,'Hotel Ritz',5),(3,'Four Seasons',8);
SELECT hotel_name, MAX(ai_powered_features) FROM hotel_tech_adoption;
List the number of community health workers and their total health equity metric scores by state in 2021, and the percentage of workers who met all health equity metrics.
CREATE TABLE community_health_workers_scores (id INT,state VARCHAR(50),year INT,worker_id INT,metric1 BOOLEAN,metric2 BOOLEAN,metric3 BOOLEAN); INSERT INTO community_health_workers_scores (id,state,year,worker_id,metric1,metric2,metric3) VALUES (1,'California',2021,1,true,true,true),(2,'California',2021,2,true,false,tr...
SELECT state, COUNT(worker_id) as num_workers, SUM((CASE WHEN metric1 THEN 1 ELSE 0 END) + (CASE WHEN metric2 THEN 1 ELSE 0 END) + (CASE WHEN metric3 THEN 1 ELSE 0 END)) as total_score, 100.0 * AVG(CASE WHEN (metric1 AND metric2 AND metric3) THEN 1.0 ELSE 0.0 END) as percentage_met_all FROM community_health_workers_sco...
What is the failure rate of aircraft by country?
CREATE SCHEMA Aircraft;CREATE TABLE Aircraft.FlightSafetyRecords (manufacturer VARCHAR(50),country VARCHAR(50),failure INT);INSERT INTO Aircraft.FlightSafetyRecords (manufacturer,country,failure) VALUES ('Boeing','USA',15),('Airbus','Europe',10),('Comac','China',5),('Mitsubishi','Japan',3),('HAL','India',2);
SELECT country, 100.0 * AVG(failure) AS failure_rate FROM Aircraft.FlightSafetyRecords GROUP BY country;
What is the average financial wellbeing score for clients in the United States?
CREATE TABLE financial_wellbeing (client_id INT,country VARCHAR(50),score DECIMAL(3,2)); INSERT INTO financial_wellbeing (client_id,country,score) VALUES (1,'United States',75.5),(2,'Canada',72.3),(3,'Mexico',68.1);
SELECT AVG(score) FROM financial_wellbeing WHERE country = 'United States';
What is the median age of artists in African countries?
CREATE TABLE artist_demographics (id INT,name VARCHAR(50),country VARCHAR(50),age INT); INSERT INTO artist_demographics (id,name,country,age) VALUES (1,'John Doe','Nigeria',45),(2,'Jane Smith','South Africa',35),(3,'Mike Johnson','Egypt',55);
SELECT AVG(age) FROM (SELECT age FROM artist_demographics WHERE country IN ('Nigeria', 'South Africa', 'Egypt') ORDER BY age) AS subquery GROUP BY age LIMIT 1;
Delete waste generation records for region 'North' in the year 2021.
CREATE TABLE waste_generation(region VARCHAR(20),year INT,waste_gram INT); INSERT INTO waste_generation(region,year,waste_gram) VALUES('North',2021,50000),('North',2022,60000),('South',2021,40000),('South',2022,70000);
DELETE FROM waste_generation WHERE region = 'North' AND year = 2021;
Delete all mining permits expired before 2015
mining_permits(permit_id,mine_id,issue_date,expiry_date)
DELETE FROM mining_permits WHERE expiry_date < '2015-01-01';
Show the product names and their origins that are not from countries with high ethical labor violations.
CREATE TABLE ClothingInventory (product_id INT,product_name TEXT,origin TEXT); INSERT INTO ClothingInventory (product_id,product_name,origin) VALUES (1,'Organic Cotton T-Shirt','India'),(2,'Hemp Pants','China'); CREATE TABLE SupplyChainViolations (country TEXT,num_violations INT); INSERT INTO SupplyChainViolations (cou...
SELECT product_name, origin FROM ClothingInventory C1 WHERE origin NOT IN (SELECT country FROM SupplyChainViolations WHERE num_violations > 10);
How many countries are represented in the 'carbon_pricing' table?
CREATE TABLE carbon_pricing (country VARCHAR(50),carbon_price NUMERIC(5,2)); INSERT INTO carbon_pricing (country,carbon_price) VALUES ('Germany',25.0),('France',30.0),('Canada',40.0),('Brazil',15.0),('India',5.0);
SELECT COUNT(DISTINCT country) FROM carbon_pricing;
Show the total assets of customers from India
CREATE TABLE customers (id INT,name VARCHAR(50),asset_value FLOAT,country VARCHAR(50)); INSERT INTO customers (id,name,asset_value,country) VALUES (1,'Ravi Kumar',50000.00,'India'),(2,'Sophia Lee',75000.00,'South Korea'),(3,'Kenji Nakamura',60000.00,'Japan'),(4,'Priya Gupta',80000.00,'India'),(5,'Frederick Johnson',450...
SELECT SUM(asset_value) FROM customers WHERE country = 'India';
What is the average number of plays per day for the rock genre on Spotify?
CREATE TABLE Plays (Platform VARCHAR(20),Genre VARCHAR(10),Plays INT,EventDate DATE); INSERT INTO Plays (Platform,Genre,Plays,EventDate) VALUES ('Spotify','Rock',20000,'2021-01-01'),('Spotify','Pop',30000,'2021-01-01'),('Spotify','Rock',22000,'2021-01-02'),('Spotify','Pop',28000,'2021-01-02'),('Spotify','Rock',19000,'2...
SELECT Platform, AVG(Plays/DATEDIFF(EventDate, LAG(EventDate) OVER (PARTITION BY Platform, Genre ORDER BY EventDate))) as AvgDailyPlays FROM Plays WHERE Genre = 'Rock' AND Platform = 'Spotify' GROUP BY Platform;
Determine the number of food safety inspections for each establishment type
CREATE TABLE establishments (establishment_id INT,name VARCHAR(50),type VARCHAR(50)); INSERT INTO establishments (establishment_id,name,type) VALUES (1,'Pizza Palace','restaurant'),(2,'Fresh Foods','supermarket'),(3,'Green Garden','grocery'),(4,'Healthy Bites','cafe'); CREATE TABLE inspections (inspection_id INT,establ...
SELECT type, COUNT(*) as inspection_count FROM inspections JOIN establishments ON inspections.establishment_id = establishments.establishment_id GROUP BY type;
What is the total amount of fertilizer used for each crop type in the past month?
CREATE TABLE crop_fertilizer (crop_type TEXT,date DATE,amount INTEGER);
SELECT crop_type, SUM(amount) as total_amount FROM crop_fertilizer WHERE date >= DATEADD(month, -1, GETDATE()) GROUP BY crop_type;
What is the total number of open data initiatives in the justice and transportation sectors?
CREATE TABLE open_data_initiatives (id INT,sector VARCHAR(20),status VARCHAR(10)); INSERT INTO open_data_initiatives (id,sector,status) VALUES (1,'justice','open'),(2,'transportation','open'),(3,'education','closed');
SELECT SUM(id) FROM open_data_initiatives WHERE sector IN ('justice', 'transportation') AND status = 'open';
Count the number of tigers in each habitat preservation project
CREATE TABLE habitat_preservation_projects (id INT,project_name VARCHAR(255),location VARCHAR(255)); CREATE TABLE tiger_populations (id INT,project_id INT,tiger_count INT); INSERT INTO habitat_preservation_projects (id,project_name,location) VALUES (1,'Save The Tiger Fund','India'),(2,'Sumatran Tiger Project','Indonesi...
SELECT habitat_preservation_projects.project_name, tiger_populations.tiger_count FROM habitat_preservation_projects INNER JOIN tiger_populations ON habitat_preservation_projects.id = tiger_populations.project_id;
What is the total volume of water saved through water conservation initiatives in the state of Texas for each year since 2016?
CREATE TABLE conservation_initiatives_texas (initiative_id INT,state VARCHAR(20),savings_volume FLOAT,initiative_year INT); INSERT INTO conservation_initiatives_texas (initiative_id,state,savings_volume,initiative_year) VALUES (1,'Texas',2000000,2016); INSERT INTO conservation_initiatives_texas (initiative_id,state,sav...
SELECT initiative_year, SUM(savings_volume) FROM conservation_initiatives_texas WHERE state = 'Texas' GROUP BY initiative_year;
Find the total number of employees from the 'hr' and 'operations' departments and exclude employees from the 'management' role.
CREATE TABLE employees (id INT,name VARCHAR(50),department VARCHAR(50),role VARCHAR(50));INSERT INTO employees (id,name,department,role) VALUES (1,'John Doe','hr','employee'); INSERT INTO employees (id,name,department,role) VALUES (2,'Jane Smith','hr','manager'); INSERT INTO employees (id,name,department,role) VALUES (...
SELECT COUNT(*) FROM employees WHERE department IN ('hr', 'operations') AND role != 'manager';
What is the number of debris types in the space_debris table?
CREATE TABLE space_debris (id INT PRIMARY KEY,debris_name VARCHAR(100),launch_date DATE,type VARCHAR(50));
SELECT COUNT(DISTINCT type) FROM space_debris;
Count the number of renewable energy projects in 'renewable_projects' table grouped by project type
CREATE TABLE renewable_projects (id INT,type VARCHAR(50),location VARCHAR(50),capacity INT,status VARCHAR(10));
SELECT type, COUNT(*) FROM renewable_projects GROUP BY type;
List all unique 'ethnicities' from 'victims' table
CREATE TABLE victims (id INT PRIMARY KEY,name VARCHAR(255),age INT,ethnicity VARCHAR(50),gender VARCHAR(10));
SELECT DISTINCT ethnicity FROM victims;
List the top 3 most expensive makeup products in the 'makeup' table, partitioned by product type.
CREATE TABLE makeup (product_id INT,product_name VARCHAR(50),price DECIMAL(5,2),product_type VARCHAR(20));
SELECT product_name, price, ROW_NUMBER() OVER (PARTITION BY product_type ORDER BY price DESC) as rank FROM makeup WHERE rank <= 3;