instruction
stringlengths 0
1.06k
| input
stringlengths 11
5.3k
| response
stringlengths 2
4.44k
|
---|---|---|
Insert a new record in the 'wastewater_treatment' table with the following data: plant_id = 3, location = 'North Bay', capacity = 1000000
|
CREATE TABLE wastewater_treatment (plant_id INT PRIMARY KEY,location VARCHAR(50),capacity INT);
|
INSERT INTO wastewater_treatment (plant_id, location, capacity) VALUES (3, 'North Bay', 1000000);
|
What is the average mass of a satellite in low Earth orbit?
|
CREATE TABLE satellite_mass (satellite_name TEXT,orbit_type TEXT,satellite_weight REAL); INSERT INTO satellite_mass (satellite_name,orbit_type,satellite_weight) VALUES ('ISS','Low Earth Orbit',419500),('Hubble','Low Earth Orbit',11000);
|
SELECT AVG(satellite_weight) FROM satellite_mass WHERE orbit_type = 'Low Earth Orbit';
|
What is the average age of patients who received CBT?
|
CREATE TABLE patients (id INT,name TEXT,age INT,treatment TEXT); INSERT INTO patients (id,name,age,treatment) VALUES (1,'John Doe',35,'CBT'),(2,'Jane Smith',40,'DBT');
|
SELECT AVG(age) FROM patients WHERE treatment = 'CBT';
|
What is the average project timeline in months for sustainable building projects in the city of Chicago?
|
CREATE TABLE project_timeline (project_id INT,city VARCHAR(20),project_type VARCHAR(20),timeline_in_months INT); INSERT INTO project_timeline (project_id,city,project_type,timeline_in_months) VALUES (1,'Chicago','Sustainable',18),(2,'Chicago','Conventional',20),(3,'New York','Sustainable',22),(4,'Los Angeles','Sustainable',24),(5,'Chicago','Sustainable',26),(6,'Chicago','Conventional',19);
|
SELECT city, AVG(timeline_in_months) FROM project_timeline WHERE city = 'Chicago' AND project_type = 'Sustainable' GROUP BY city;
|
What was the total revenue for Quebec in June 2022?
|
CREATE TABLE restaurant_revenue (location VARCHAR(255),revenue FLOAT,month VARCHAR(9)); INSERT INTO restaurant_revenue (location,revenue,month) VALUES ('Quebec',12000,'June-2022'),('Montreal',15000,'June-2022');
|
SELECT SUM(revenue) FROM restaurant_revenue WHERE location = 'Quebec' AND month = 'June-2022';
|
What is the name of the forest where the highest temperature was recorded and it was established after the average year of establishment?
|
CREATE TABLE Forests (id INT,name VARCHAR(50),country VARCHAR(50),hectares INT,year_established INT); CREATE TABLE Climate (id INT,temperature FLOAT,year INT,forest_id INT); INSERT INTO Forests (id,name,country,hectares,year_established) VALUES (1,'Bialowieza','Poland',141000,1921),(2,'Amazon','Brazil',340000,1968),(3,'Daintree','Australia',12000,1770); INSERT INTO Climate (id,temperature,year,forest_id) VALUES (1,15.5,1921,1),(2,28.7,2005,2),(3,34.1,1998,3),(4,26.3,1982,2);
|
SELECT Forests.name FROM Forests, Climate WHERE Forests.id = Climate.forest_id AND temperature = (SELECT MAX(temperature) FROM Climate) AND year_established > (SELECT AVG(year_established) FROM Forests);
|
Update the address for properties with the green_certification 'LEED' to 'Green Certified'.
|
CREATE TABLE GreenBuildings (id INT,building_id INT,address VARCHAR(100),green_certification VARCHAR(50));
|
UPDATE GreenBuildings SET address = 'Green Certified' WHERE green_certification = 'LEED';
|
Insert a new record for the album 'Thriller' with 30,000,000 sales in 1982-12-15
|
CREATE TABLE if not exists sales (sale_id serial PRIMARY KEY,sale_date date,title varchar(255),revenue decimal(10,2));
|
insert into sales (sale_date, title, revenue) values ('1982-12-15', 'Thriller', 30000000 * 0.01);
|
Which countries have the most carbon offset initiatives, and how many initiatives are there in each country?
|
CREATE TABLE carbon_offsets (initiative VARCHAR(255),country VARCHAR(255)); CREATE TABLE country_populations (country VARCHAR(255),population INT);
|
SELECT country, COUNT(initiative) as num_initiatives FROM carbon_offsets GROUP BY country ORDER BY num_initiatives DESC;
|
Find the total number of disability support programs in California and Texas.
|
CREATE TABLE disability_support_programs (id INT,state VARCHAR(255),program_name VARCHAR(255)); INSERT INTO disability_support_programs (id,state,program_name) VALUES (1,'California','Accessible Technology Initiative'); INSERT INTO disability_support_programs (id,state,program_name) VALUES (2,'Texas','Promoting the Readiness of Minors in Supplemental Security Income');
|
SELECT SUM(total) FROM (SELECT COUNT(*) AS total FROM disability_support_programs WHERE state = 'California' UNION ALL SELECT COUNT(*) AS total FROM disability_support_programs WHERE state = 'Texas') AS subquery;
|
What is the number of agricultural projects in Nigeria and Kenya led by women that were completed in 2019?
|
CREATE TABLE Agricultural_Projects (Project_ID INT,Project_Name TEXT,Location TEXT,Status TEXT,Led_By TEXT,Year INT); INSERT INTO Agricultural_Projects (Project_ID,Project_Name,Location,Status,Led_By,Year) VALUES (1,'Crop Diversification','Nigeria','Completed','Women',2019),(2,'Livestock Improvement','Kenya','Completed','Women',2019);
|
SELECT COUNT(*) FROM Agricultural_Projects WHERE Status = 'Completed' AND Led_By = 'Women' AND Year = 2019 AND Location IN ('Nigeria', 'Kenya');
|
How many donations were made by each donor in the year 2020?
|
CREATE TABLE Donations (donor_id INT,donation_amount FLOAT,donation_date DATE); INSERT INTO Donations (donor_id,donation_amount,donation_date) VALUES (1,500,'2020-01-01'),(2,300,'2020-02-03'),(1,700,'2020-12-31');
|
SELECT donor_id, SUM(donation_amount) as total_donations FROM Donations WHERE YEAR(donation_date) = 2020 GROUP BY donor_id;
|
What is the total CO2 emission reduction per country?
|
CREATE TABLE co2_emission_reduction (reduction_id INT,country_id INT,co2_reduction FLOAT); INSERT INTO co2_emission_reduction VALUES (1,1,5000),(2,1,7000),(3,2,6000),(4,3,8000);
|
SELECT country_id, SUM(co2_reduction) as total_reduction FROM co2_emission_reduction GROUP BY country_id;
|
How many circular economy initiatives were implemented in Tokyo by 2022?
|
CREATE TABLE circular_economy_initiatives (city VARCHAR(50),initiative_date DATE,initiative_type VARCHAR(50)); INSERT INTO circular_economy_initiatives (city,initiative_date,initiative_type) VALUES ('Tokyo','2021-03-15','Recycling Program'),('Tokyo','2020-08-01','Composting Program'),('Tokyo','2019-12-01','Waste Reduction Campaign');
|
SELECT COUNT(*) FROM circular_economy_initiatives WHERE city = 'Tokyo' AND initiative_date <= '2022-12-31';
|
What is the total number of accommodations provided in the Art department, and the total number of accommodations provided in the Physical Education department?
|
CREATE TABLE ArtAccommodations (AccommodationID INT,Department VARCHAR(20)); INSERT INTO ArtAccommodations (AccommodationID,Department) VALUES (1,'Art'),(2,'Art'),(3,'Art'); CREATE TABLE PhysicalEducationAccommodations (AccommodationID INT,Department VARCHAR(20)); INSERT INTO PhysicalEducationAccommodations (AccommodationID,Department) VALUES (4,'Physical Education'),(5,'Physical Education'),(6,'Physical Education');
|
SELECT COUNT(*) FROM ArtAccommodations WHERE Department = 'Art' UNION SELECT COUNT(*) FROM PhysicalEducationAccommodations WHERE Department = 'Physical Education';
|
Show all records from the public transportation usage table
|
CREATE TABLE public_transit (id INT PRIMARY KEY,agency VARCHAR(255),line VARCHAR(255),route_id VARCHAR(255),stop_id VARCHAR(255),city VARCHAR(255),state VARCHAR(255),country VARCHAR(255),passengers INT); INSERT INTO public_transit (id,agency,line,route_id,stop_id,city,state,country,passengers) VALUES (1,'SF Muni','N Judah','123','456','San Francisco','California','USA',50);
|
SELECT * FROM public_transit;
|
What is the total length of subway systems in South Korea and China?
|
CREATE TABLE subway_systems (id INT,country VARCHAR(255),total_length INT); INSERT INTO subway_systems (id,country,total_length) VALUES (1,'South Korea',960),(2,'China',5600),(3,'Japan',1270),(4,'India',290);
|
SELECT SUM(total_length) FROM subway_systems WHERE country IN ('South Korea', 'China');
|
Calculate the average fare and number of trips per route in the Parisian public transportation
|
CREATE TABLE parisian_transportation (route_id INT,trips_taken INT,fare_collected DECIMAL(5,2)); INSERT INTO parisian_transportation (route_id,trips_taken,fare_collected) VALUES (4,700,1625.00),(5,800,2350.00),(6,650,1425.00);
|
SELECT route_id, AVG(trips_taken) as average_trips, AVG(fare_collected) as average_fare FROM parisian_transportation GROUP BY route_id;
|
Delete all records of the 'Atlanta Hawks' in the 'teams' table.
|
CREATE TABLE teams (id INT,name TEXT,city TEXT); INSERT INTO teams (id,name,city) VALUES (1,'Boston Celtics','Boston'),(2,'NY Knicks','NY'),(3,'LA Lakers','LA'),(4,'Atlanta Hawks','Atlanta'),(5,'Chicago Bulls','Chicago');
|
DELETE FROM teams WHERE name = 'Atlanta Hawks';
|
Show companies in the education sector with ESG scores below 60 in North America.
|
CREATE TABLE regions (id INT,company_id INT,region TEXT); INSERT INTO regions (id,company_id,region) VALUES (1,2,'USA'),(2,9,'Canada');
|
SELECT * FROM companies WHERE sector = 'Education' AND ESG_score < 60 AND companies.country IN ('USA', 'Canada');
|
Find the percentage of students with mental health disabilities who received tutoring or extended testing time.
|
CREATE TABLE accommodation (student_id INT,accommodation_type TEXT,accommodation_date DATE); INSERT INTO accommodation (student_id,accommodation_type,accommodation_date) VALUES (1,'Tutoring','2022-01-01'),(2,'Quiet Space','2022-02-01'),(3,'Extended Testing Time','2022-03-01'),(4,'Tutoring','2022-04-01');
|
SELECT COUNT(DISTINCT student_id) * 100.0 / (SELECT COUNT(DISTINCT student_id) FROM accommodation WHERE student_id IN (SELECT student_id FROM student WHERE disability = 'Mental Health')) as percentage FROM accommodation WHERE student_id IN (SELECT student_id FROM student WHERE disability = 'Mental Health') AND accommodation_type IN ('Tutoring', 'Extended Testing Time');
|
How many climate mitigation projects were completed in Latin America and the Caribbean between 2010 and 2015?
|
CREATE TABLE project (project_id INT,project_name VARCHAR(50),region VARCHAR(30),mitigation BOOLEAN,completion_year INT); INSERT INTO project VALUES (1,'Solar Farm','Latin America',true,2012),(2,'Wind Turbines','Caribbean',true,2013),(3,'Energy Efficiency','Latin America',false,2011),(4,'Carbon Capture','Caribbean',true,2014);
|
SELECT COUNT(*) FROM project WHERE region IN ('Latin America', 'Caribbean') AND mitigation = true AND completion_year BETWEEN 2010 AND 2015;
|
What is the total number of police officers and firefighters in each borough?
|
CREATE TABLE boroughs (bid INT,name VARCHAR(255)); CREATE TABLE police_officers (oid INT,bid INT,rank VARCHAR(255)); CREATE TABLE firefighters (fid INT,bid INT,rank VARCHAR(255)); INSERT INTO boroughs VALUES (1,'Manhattan'),(2,'Brooklyn'); INSERT INTO police_officers VALUES (1,1,'Captain'),(2,2,'Lieutenant'); INSERT INTO firefighters VALUES (1,1,'Captain'),(2,2,'Lieutenant');
|
SELECT b.name, COUNT(po.oid) + COUNT(f.fid) as total_employees FROM boroughs b LEFT JOIN police_officers po ON b.bid = po.bid LEFT JOIN firefighters f ON b.bid = f.bid GROUP BY b.bid;
|
Update the horsepower of the 'Chevrolet Bolt' to 266 in the 'GreenAutos' database.
|
CREATE TABLE ElectricVehicles (Id INT,Make VARCHAR(50),Model VARCHAR(50),Year INT,Horsepower INT);
|
UPDATE ElectricVehicles SET Horsepower = 266 WHERE Make = 'Chevrolet' AND Model = 'Bolt';
|
What is the minimum population size of all marine mammals in the Antarctic region?
|
CREATE TABLE marine_mammals (mammal_id INT,name VARCHAR(50),population INT,habitat VARCHAR(50)); INSERT INTO marine_mammals (mammal_id,name,population,habitat) VALUES (1,'Krill',5000000000,'Antarctic Region'),(2,'Crabeater Seal',2500000,'Antarctic Region'),(3,'Antarctic Fur Seal',500000,'Antarctic Region');
|
SELECT MIN(population) FROM marine_mammals WHERE habitat = 'Antarctic Region';
|
What is the average billing amount for cases handled by attorneys from Indigenous communities?
|
CREATE TABLE Attorneys (AttorneyID int,Community varchar(20),HourlyRate decimal(5,2)); INSERT INTO Attorneys (AttorneyID,Community,HourlyRate) VALUES (1,'Indigenous',300.00),(2,'Middle Eastern',250.00),(3,'Pacific Islander',350.00),(4,'Caucasian',200.00),(5,'African',400.00); CREATE TABLE Cases (CaseID int,AttorneyID int); INSERT INTO Cases (CaseID,AttorneyID) VALUES (1,1),(2,2),(3,3),(4,5),(5,1),(6,4);
|
SELECT AVG(HourlyRate * 8 * 22) AS AverageBillingAmount FROM Attorneys WHERE Community = 'Indigenous';
|
What is the average life expectancy in each country in the world?
|
CREATE TABLE life_expectancy (id INT,country TEXT,years_of_life_expectancy INT); INSERT INTO life_expectancy (id,country,years_of_life_expectancy) VALUES (1,'United States',78),(2,'Mexico',75),(3,'Canada',82),(4,'Brazil',74),(5,'Australia',83),(6,'Russia',70),(7,'China',76),(8,'India',70),(9,'Germany',81),(10,'France',82);
|
SELECT country, AVG(years_of_life_expectancy) FROM life_expectancy GROUP BY country;
|
How many users from Brazil and Colombia interacted with posts about social justice in the last month?
|
CREATE TABLE posts (post_id INT,post_country VARCHAR(255),post_topic VARCHAR(255),post_date DATE); CREATE TABLE user_interactions (interaction_id INT,user_id INT,post_id INT,interaction_type VARCHAR(10)); INSERT INTO posts (post_id,post_country,post_topic,post_date) VALUES (1,'Brazil','social justice','2023-01-01'),(2,'Colombia','social justice','2023-01-05'); INSERT INTO user_interactions (interaction_id,user_id,post_id,interaction_type) VALUES (1,1,1,'like'),(2,2,1,'share'),(3,3,2,'comment');
|
SELECT SUM(interaction_type = 'like') + SUM(interaction_type = 'share') + SUM(interaction_type = 'comment') AS total_interactions FROM user_interactions WHERE post_id IN (SELECT post_id FROM posts WHERE post_date BETWEEN DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH) AND CURRENT_DATE AND post_country IN ('Brazil', 'Colombia') AND post_topic = 'social justice');
|
What is the total cost of SpacecraftManufacturing for US based spacecraft?
|
CREATE TABLE SpacecraftManufacturing (spacecraft_model VARCHAR(255),spacecraft_country VARCHAR(255),cost INT); INSERT INTO SpacecraftManufacturing (spacecraft_model,spacecraft_country,cost) VALUES ('Apollo','USA',25400000),('Space Shuttle','USA',192000000),('Orion','USA',15100000);
|
SELECT SUM(cost) FROM SpacecraftManufacturing WHERE spacecraft_country = 'USA';
|
Find the number of satellites in orbit for each country and order them by the total number of satellites.
|
CREATE TABLE CountrySatellites (Country VARCHAR(50),Satellites INT); INSERT INTO CountrySatellites (Country,Satellites) VALUES ('USA',1417),('Russia',1250),('China',413),('India',127),('Japan',125),('Germany',77),('France',66),('Italy',60),('UK',59),('Canada',54);
|
SELECT Country, Satellites, RANK() OVER (ORDER BY Satellites DESC) as Rank FROM CountrySatellites;
|
What are the top 5 characters with the most wins, and their total playtime in hours?
|
CREATE TABLE WinsStats (CharacterID int,CharacterName varchar(50),Wins int,Playtime decimal(10,2)); INSERT INTO WinsStats (CharacterID,CharacterName,Wins,Playtime) VALUES (1,'Knight',250,100.25),(2,'Mage',225,115.00),(3,'Archer',200,120.50),(4,'Healer',175,95.00),(5,'Warrior',150,85.75),(6,'Assassin',125,70.00);
|
SELECT ws.CharacterName, SUM(ws.Wins) as TotalWins, SUM(ws.Playtime / 60) as TotalPlaytimeInHours FROM WinsStats ws GROUP BY ws.CharacterName ORDER BY TotalWins DESC LIMIT 5;
|
What is the total number of IoT sensors in each farm?
|
CREATE TABLE farm_iot_sensors (farm_id INTEGER,sensor_id INTEGER); INSERT INTO farm_iot_sensors VALUES (1,101),(1,102),(2,201); CREATE TABLE farms (farm_id INTEGER,farm_name TEXT); INSERT INTO farms VALUES (1,'Farm A'),(2,'Farm B');
|
SELECT farm_name, COUNT(sensor_id) as total_sensors FROM farm_iot_sensors JOIN farms ON farm_iot_sensors.farm_id = farms.farm_id GROUP BY farm_name;
|
How many exhibitions featured more than 10 abstract expressionist artists?
|
CREATE TABLE Exhibitions (id INT,name TEXT,year INT,art_style TEXT,num_artists INT); INSERT INTO Exhibitions (id,name,year,art_style,num_artists) VALUES (1,'Exhibition1',2000,'Abstract Expressionism',12),(2,'Exhibition2',2005,'Cubism',8),(3,'Exhibition3',2010,'Abstract Expressionism',20);
|
SELECT COUNT(*) FROM Exhibitions WHERE art_style = 'Abstract Expressionism' GROUP BY art_style HAVING COUNT(*) > 10;
|
What is the average number of posts per day for users in the 'influencer' group, who have more than 10,000 followers and have posted more than 50 times in the last 30 days?
|
CREATE TABLE users (id INT,name VARCHAR(50),group VARCHAR(50),followers INT,posts INT,last_post_date DATE); INSERT INTO users (id,name,group,followers,posts,last_post_date) VALUES (1,'Alice','influencer',15000,75,'2022-01-01'); INSERT INTO users (id,name,group,followers,posts,last_post_date) VALUES (2,'Bob','influencer',22000,120,'2022-01-02'); INSERT INTO users (id,name,group,followers,posts,last_post_date) VALUES (3,'Charlie','fan',500,20,'2022-01-03');
|
SELECT AVG(posts) FROM users WHERE group = 'influencer' AND followers > 10000 AND posts > 50 AND last_post_date >= DATEADD(day, -30, GETDATE());
|
What is the total quantity of eco-friendly dyes used by each textile mill, ordered from most to least?
|
CREATE TABLE TextileMills (id INT,mill VARCHAR(50),dye_type VARCHAR(50),quantity INT); INSERT INTO TextileMills (id,mill,dye_type,quantity) VALUES (1,'Mill A','Natural Dye',2000),(2,'Mill B','Low-Impact Dye',3000),(3,'Mill C','Natural Dye',1500);
|
SELECT mill, SUM(quantity) AS total_quantity FROM TextileMills WHERE dye_type IN ('Natural Dye', 'Low-Impact Dye') GROUP BY mill ORDER BY total_quantity DESC;
|
How many matches were played by the Chicago Bulls in the 1995-1996 NBA season and what was their average points difference?
|
CREATE TABLE matches (team VARCHAR(50),opponent VARCHAR(50),points_team INTEGER,points_opponent INTEGER,season VARCHAR(10)); INSERT INTO matches (team,opponent,points_team,points_opponent,season) VALUES ('Chicago Bulls','Charlotte Hornets',103,84,'1995-1996'),('Chicago Bulls','Miami Heat',112,89,'1995-1996');
|
SELECT COUNT(*), AVG(points_team - points_opponent) FROM matches WHERE team = 'Chicago Bulls' AND season = '1995-1996';
|
Which countries have the highest and lowest food safety violation rates?
|
CREATE TABLE food_safety_records (country VARCHAR(50),violations INT); INSERT INTO food_safety_records (country,violations) VALUES ('United States',500),('Canada',300),('Mexico',700),('Brazil',400);
|
SELECT country, violations FROM food_safety_records ORDER BY violations DESC LIMIT 1; SELECT country, violations FROM food_safety_records ORDER BY violations ASC LIMIT 1;
|
What is the total number of emergency calls in the city of Phoenix for each day of the week?
|
CREATE TABLE emergency_calls (id INT,city VARCHAR(20),call_date DATE); INSERT INTO emergency_calls (id,city,call_date) VALUES (1,'Phoenix','2021-01-01'),(2,'Phoenix','2021-01-03'),(3,'Phoenix','2021-01-05');
|
SELECT EXTRACT(DOW FROM call_date) as day_of_week, COUNT(*) FROM emergency_calls WHERE city = 'Phoenix' GROUP BY day_of_week;
|
What is the average age of readers who prefer news about politics in the "NewsReporting" database?
|
CREATE TABLE ReaderDemographics (ReaderID INT,Age INT,PreferredNewsTopic VARCHAR(255)); INSERT INTO ReaderDemographics (ReaderID,Age,PreferredNewsTopic) VALUES (1,45,'politics');
|
SELECT AVG(Age) FROM ReaderDemographics WHERE PreferredNewsTopic = 'politics'
|
What is the average ocean temperature in the Arctic Ocean?
|
CREATE TABLE ocean_temperature (id INT,location VARCHAR(255),temperature FLOAT,date DATE); INSERT INTO ocean_temperature (id,location,temperature,date) VALUES (2,'Arctic Ocean',5.0,'2022-05-01');
|
SELECT location, AVG(temperature) FROM ocean_temperature WHERE location = 'Arctic Ocean'
|
Which marine species are found in the Arctic Ocean?
|
CREATE TABLE marine_species (name TEXT,habitat TEXT); INSERT INTO marine_species (name,habitat) VALUES ('Polar Bear','Arctic'),('Narwhal','Arctic'),('Walrus','Arctic'),('Beluga Whale','Arctic');
|
SELECT name FROM marine_species WHERE habitat = 'Arctic';
|
Insert records into 'smart_grid' for three cities
|
CREATE TABLE smart_grid (id INT PRIMARY KEY,city VARCHAR(50),power_sources VARCHAR(50));
|
INSERT INTO smart_grid (id, city, power_sources) VALUES (1, 'San Francisco', 'Solar, Wind'); INSERT INTO smart_grid (id, city, power_sources) VALUES (2, 'New York', 'Solar, Hydro'); INSERT INTO smart_grid (id, city, power_sources) VALUES (3, 'Tokyo', 'Wind, Geothermal');
|
How many users have updated their account information more than once?
|
CREATE TABLE Users (user_id INT,update_count INT); INSERT INTO Users (user_id,update_count) VALUES (1,3),(2,1),(3,2);
|
SELECT COUNT(*) as num_users FROM Users WHERE update_count > 1;
|
Calculate the average salary for employees in each department, excluding employees who were hired after '2022-02-01'
|
CREATE TABLE Employees (EmployeeID INT,FirstName VARCHAR(50),LastName VARCHAR(50),Department VARCHAR(50),Location VARCHAR(50),Salary DECIMAL(10,2),HireDate DATE); INSERT INTO Employees (EmployeeID,FirstName,LastName,Department,Location,Salary,HireDate) VALUES (1,'John','Doe','IT','New York',80000.00,'2022-01-01'),(2,'Jane','Doe','HR','Los Angeles',65000.00,'2022-02-15'),(3,'Jim','Smith','IT','Chicago',85000.00,'2022-03-20');
|
SELECT Department, AVG(Salary) FROM Employees WHERE HireDate <= '2022-02-01' GROUP BY Department;
|
What is the total quantity of sustainable fabrics sourced from Spain?
|
CREATE TABLE fabrics (id INT,fabric_type VARCHAR(50),country VARCHAR(50),quantity INT); INSERT INTO fabrics (id,fabric_type,country,quantity) VALUES (1,'Tencel','Spain',2500);
|
SELECT SUM(quantity) FROM fabrics WHERE fabric_type = 'Tencel' AND country = 'Spain';
|
Find the top 3 news articles read by females in Canada.
|
CREATE TABLE articles (id INT,title VARCHAR(100),category VARCHAR(20)); CREATE TABLE readership (reader_id INT,article_id INT,gender VARCHAR(10),country VARCHAR(50)); INSERT INTO articles (id,title,category) VALUES (1,'Arctic wildlife on the decline','Environment'); INSERT INTO readership (reader_id,article_id,gender,country) VALUES (1,1,'Female','Canada');
|
SELECT a.title, r.gender, r.country FROM articles a JOIN ( SELECT article_id, gender, country FROM readership WHERE gender = 'Female' AND country = 'Canada' LIMIT 3) r ON a.id = r.article_id
|
What is the most common age range of visitors who attended exhibitions in New York?
|
CREATE TABLE exhibitions (id INT,city VARCHAR(50),visitor_age INT); INSERT INTO exhibitions (id,city,visitor_age) VALUES (1,'New York',35),(2,'New York',42),(3,'New York',30);
|
SELECT city, COUNT(*) AS visitor_count, NTILE(4) OVER (ORDER BY visitor_age) AS age_range FROM exhibitions GROUP BY city, NTILE(4) OVER (ORDER BY visitor_age) HAVING city = 'New York';
|
What is the total waste generation by material type in 2022 for the city of San Francisco?
|
CREATE TABLE waste_generation (city VARCHAR(20),material VARCHAR(20),year INT,quantity INT); INSERT INTO waste_generation (city,material,year,quantity) VALUES ('San Francisco','Plastic',2022,1500),('San Francisco','Glass',2022,2000),('San Francisco','Paper',2022,2500),('San Francisco','Metal',2022,1000);
|
SELECT SUM(quantity) AS total_waste_generation, material FROM waste_generation WHERE city = 'San Francisco' AND year = 2022 GROUP BY material;
|
What is the total production volume for each chemical category?
|
CREATE TABLE production_volume (chemical_category VARCHAR(255),production_volume INT); INSERT INTO production_volume (chemical_category,production_volume) VALUES ('Polymers',1200),('Dyes',800),('Acids',1500);
|
SELECT chemical_category, SUM(production_volume) OVER (PARTITION BY chemical_category) AS total_volume FROM production_volume;
|
List all security incidents where the source IP address is from a country with a high risk of cyber attacks according to the Cybersecurity and Infrastructure Security Agency (CISA)?
|
CREATE TABLE incident (incident_id INT,incident_date DATE,incident_description TEXT,source_ip VARCHAR(255));CREATE VIEW country_risk AS SELECT ip_address,risk_level FROM ip_address_risk WHERE agency = 'CISA';
|
SELECT incident_description, source_ip FROM incident i JOIN country_risk cr ON i.source_ip = cr.ip_address WHERE cr.risk_level = 'high';
|
What is the maximum number of streams for a classical music track in a single day?
|
CREATE TABLE streams (id INT,track_id INT,date DATE,views INT); INSERT INTO streams (id,track_id,date,views) VALUES (1,1,'2022-01-01',10000);
|
SELECT MAX(views) FROM streams WHERE genre = 'Classical' GROUP BY track_id;
|
What is the average budget allocation per service category in France?
|
CREATE TABLE budget_france (region VARCHAR(20),category VARCHAR(20),allocation DECIMAL(10,2)); INSERT INTO budget_france VALUES ('France','Education',12000.00);
|
SELECT AVG(allocation) FROM budget_france WHERE region = 'France' GROUP BY category;
|
What is the total square footage of building projects per labor category?
|
CREATE TABLE labor_statistics (labor_category VARCHAR(50),average_wage NUMERIC(10,2)); INSERT INTO labor_statistics (labor_category,average_wage) VALUES ('Carpenters','35.56'),('Electricians','38.42'),('Plumbers','42.15'); CREATE TABLE project_data (project_id SERIAL PRIMARY KEY,labor_category VARCHAR(50),square_footage INTEGER); INSERT INTO project_data (project_id,labor_category,square_footage) VALUES (1,'Carpenters',15000),(2,'Electricians',20000),(3,'Plumbers',25000);
|
SELECT labor_category, SUM(square_footage) FROM project_data GROUP BY labor_category;
|
What is the average ethical rating of facilities in the 'Americas' region?
|
CREATE TABLE facility_ratings (id INT,facility_name VARCHAR(255),region VARCHAR(255),ethical_rating INT); INSERT INTO facility_ratings (id,facility_name,region,ethical_rating) VALUES (1,'Green Textiles','Americas',9),(2,'EcoMetal','Europe',10),(3,'SolarSteel','Asia',8);
|
SELECT AVG(ethical_rating) FROM facility_ratings WHERE region = 'Americas';
|
Find the number of unique genres in each country with at least one concert.
|
CREATE TABLE CountryConcerts (Country VARCHAR(50),ConcertID INT); INSERT INTO CountryConcerts (Country,ConcertID) VALUES ('USA',1); INSERT INTO CountryConcerts (Country,ConcertID) VALUES ('Canada',2); INSERT INTO CountryConcerts (Country,ConcertID) VALUES ('Mexico',3);
|
SELECT Country, COUNT(DISTINCT Genre) AS UniqueGenres FROM CountryConcerts JOIN Concerts ON CountryConcerts.ConcertID = Concerts.ConcertID JOIN Songs ON Concerts.ConcertID = Songs.ConcertID GROUP BY Country HAVING COUNT(DISTINCT Concerts.ConcertID) > 0;
|
Identify the top three community health workers with the most unique patients served, along with the number of patients they have served.
|
CREATE TABLE CommunityHealthWorker (ID INT,Name TEXT); INSERT INTO CommunityHealthWorker (ID,Name) VALUES (1,'Mabel Lee'); INSERT INTO CommunityHealthWorker (ID,Name) VALUES (2,'Ali Hassan'); INSERT INTO CommunityHealthWorker (ID,Name) VALUES (3,'Lauren Johnson'); CREATE TABLE PatientCommunityHealthWorker (PatientID INT,CommunityHealthWorkerID INT);
|
SELECT CommunityHealthWorkerID, COUNT(DISTINCT PatientID) as PatientsServed FROM PatientCommunityHealthWorker GROUP BY CommunityHealthWorkerID ORDER BY PatientsServed DESC LIMIT 3;
|
How many autonomous vehicles were sold in 'sales_data' view?
|
CREATE VIEW sales_data AS SELECT id,vehicle_type,avg_speed,sales FROM vehicle_sales WHERE sales > 20000;
|
SELECT COUNT(*) FROM sales_data WHERE vehicle_type LIKE '%autonomous%';
|
Which products from brands with an average preference rating above 4 have been reviewed more than 30 times and have a carbon footprint below 3.5?
|
CREATE TABLE Brand_Preferences (brand_id INT,brand TEXT,total_products INT,avg_preference_rating DECIMAL); INSERT INTO Brand_Preferences (brand_id,brand,total_products,avg_preference_rating) VALUES (1,'EcoPure',15,4.7),(2,'Natural Beauty',12,4.3),(3,'Green Visions',10,4.9),(4,'Pure & Simple',14,4.1); CREATE TABLE Product_Sustainability (product_id INT,brand_id INT,carbon_footprint DECIMAL); INSERT INTO Product_Sustainability (product_id,brand_id,carbon_footprint) VALUES (1001,1,3.2),(1002,2,4.1),(1003,3,2.8),(1004,4,3.7),(1005,1,2.9); CREATE TABLE Product_Reviews (product_id INT,review_count INT); INSERT INTO Product_Reviews (product_id,review_count) VALUES (1001,45),(1002,32),(1003,38),(1004,29),(1005,42);
|
SELECT product_id FROM Product_Sustainability INNER JOIN Brand_Preferences ON Product_Sustainability.brand_id = Brand_Preferences.brand_id INNER JOIN Product_Reviews ON Product_Sustainability.product_id = Product_Reviews.product_id WHERE avg_preference_rating > 4 AND review_count > 30 AND carbon_footprint < 3.5;
|
What is the number of public museums in each district in the city of Chicago, including their names and number of exhibits?
|
CREATE TABLE districts(id INT,name TEXT); INSERT INTO districts VALUES (1,'District A'); INSERT INTO districts VALUES (2,'District B'); INSERT INTO districts VALUES (3,'District C'); CREATE TABLE museums(id INT,district_id INT,name TEXT,exhibits INT); INSERT INTO museums VALUES (1,1,'Museum A',100); INSERT INTO museums VALUES (2,1,'Museum B',120); INSERT INTO museums VALUES (3,2,'Museum C',140); INSERT INTO museums VALUES (4,3,'Museum D',160);
|
SELECT d.name as district_name, m.name as museum_name, COUNT(*) as museum_count, SUM(m.exhibits) as total_exhibits FROM districts d JOIN museums m ON d.id = m.district_id WHERE d.name = 'Chicago' GROUP BY d.name, m.name;
|
What is the total value of green building projects in Washington state?
|
CREATE TABLE green_buildings (id INT,project_name VARCHAR(50),state VARCHAR(50),value FLOAT); INSERT INTO green_buildings (id,project_name,state,value) VALUES (1,'Seattle Green Tower','Washington',15000000.00); INSERT INTO green_buildings (id,project_name,state,value) VALUES (2,'Tacoma Green Project','Washington',20000000.00);
|
SELECT SUM(value) FROM green_buildings WHERE state = 'Washington' AND project_name LIKE '%green%'
|
List the first and last name of the youngest donor for each country?
|
CREATE TABLE Donors (DonorID INT,FirstName VARCHAR(50),LastName VARCHAR(50),Country VARCHAR(100),DateOfBirth DATE); INSERT INTO Donors (DonorID,FirstName,LastName,Country,DateOfBirth) VALUES (1,'John','Doe','USA','1980-01-01'),(2,'Jane','Doe','Canada','1990-01-01');
|
SELECT FirstName, LastName, Country, MIN(DateOfBirth) as YoungestDonor FROM Donors GROUP BY Country;
|
What is the total quantity of garments produced by each manufacturer in the 'GarmentProduction' table, excluding any duplicates based on the 'manufacturer_id'?
|
CREATE TABLE GarmentProduction (manufacturer_id INT,garment_type VARCHAR(50),quantity INT); INSERT INTO GarmentProduction (manufacturer_id,garment_type,quantity) VALUES (1,'T-Shirt',500),(2,'Jeans',300),(1,'T-Shirt',500);
|
SELECT DISTINCT manufacturer_id, SUM(quantity) FROM GarmentProduction GROUP BY manufacturer_id;
|
What is the minimum severity of vulnerabilities for applications in the 'Finance' department?
|
CREATE TABLE dept_vulnerabilities (id INT,department VARCHAR(255),app_name VARCHAR(255),severity INT); INSERT INTO dept_vulnerabilities (id,department,app_name,severity) VALUES (1,'Finance','App1',5),(2,'Finance','App2',3),(3,'IT','App3',7);
|
SELECT department, MIN(severity) FROM dept_vulnerabilities WHERE department = 'Finance';
|
Delete all records of oil spills in the Atlantic Ocean with a severity level less than or equal to 3.
|
CREATE TABLE oil_spills_atlantic (id INT,location VARCHAR(20),severity INT);
|
DELETE FROM oil_spills_atlantic WHERE location LIKE 'Atlantic Ocean%' AND severity <= 3;
|
What is the total revenue of customers in the Southeast region?
|
CREATE TABLE customers (id INT,name VARCHAR(50),region VARCHAR(50),revenue FLOAT); INSERT INTO customers (id,name,region,revenue) VALUES (1,'John Smith','Southeast',5000),(2,'Jane Doe','Northeast',7000),(3,'Bob Johnson','Southeast',6000);
|
SELECT SUM(revenue) FROM customers WHERE region = 'Southeast';
|
How many food safety inspections were conducted for each restaurant, and what is the average score of the inspections?
|
CREATE TABLE inspections (inspection_id INT,restaurant_id INT,inspection_date DATE,score INT); INSERT INTO inspections (inspection_id,restaurant_id,inspection_date,score) VALUES (1,1,'2022-01-01',95);
|
SELECT restaurant_id, COUNT(*), AVG(score) FROM inspections GROUP BY restaurant_id;
|
Determine the total installed capacity of wind turbines in Germany.
|
CREATE TABLE renewable_energy (id INT,type TEXT,country TEXT,capacity FLOAT); INSERT INTO renewable_energy (id,type,country,capacity) VALUES (1,'Wind Turbine','Germany',2.2),(2,'Solar Panel','Spain',3.2),(3,'Wind Turbine','France',2.5);
|
SELECT SUM(capacity) FROM renewable_energy WHERE type = 'Wind Turbine' AND country = 'Germany';
|
What is the maximum property price in neighborhoods with inclusive housing policies?
|
CREATE TABLE neighborhoods (neighborhood_id INT,name VARCHAR(255),inclusive_housing BOOLEAN,max_property_price DECIMAL(10,2)); INSERT INTO neighborhoods (neighborhood_id,name,inclusive_housing,max_property_price) VALUES (1,'Central Park',true,1200000),(2,'Soho',false,1500000),(3,'Greenwich Village',true,1300000),(4,'Harlem',true,800000);
|
SELECT MAX(max_property_price) FROM neighborhoods WHERE inclusive_housing = true
|
Update the rate of 'Paper' to 0.35 in recycling_rates table
|
CREATE TABLE recycling_rates (id INT PRIMARY KEY,location VARCHAR(255),recycling_type VARCHAR(255),rate DECIMAL(5,4),date DATE);
|
UPDATE recycling_rates SET rate = 0.35 WHERE recycling_type = 'Paper';
|
What is the average number of artworks checked out by visitors who are members of the museum?
|
CREATE TABLE members(member_id INT,name VARCHAR(50),member_type VARCHAR(50)); INSERT INTO members (member_id,name,member_type) VALUES (1,'John Doe','Individual'),(2,'Jane Smith','Family'); CREATE TABLE artworks(artwork_id INT,title VARCHAR(50),is_checked_out INT); INSERT INTO artworks (artwork_id,title,is_checked_out) VALUES (1,'Mona Lisa',1),(2,'Starry Night',0);
|
SELECT AVG(a.is_checked_out) FROM artworks a JOIN members m ON a.member_id = m.member_id WHERE m.member_type = 'Individual' OR m.member_type = 'Family';
|
Identify customers who have shipped the most in the last month.
|
CREATE TABLE Shipment (id INT PRIMARY KEY,customer_id INT,weight FLOAT,shipped_date DATE); INSERT INTO Shipment (id,customer_id,weight,shipped_date) VALUES (7,1,120.5,'2022-05-01'),(8,2,150.3,'2022-05-05'),(9,3,180.7,'2022-05-07'),(10,1,90.2,'2022-06-10'),(11,2,135.6,'2022-07-14'),(12,4,175.8,'2022-07-20'); CREATE TABLE Customer (id INT PRIMARY KEY,name VARCHAR(100),address VARCHAR(200),phone VARCHAR(15)); INSERT INTO Customer (id,name,address,phone) VALUES (1,'John Doe','123 Main St,Miami,FL','305-555-1212'),(2,'Jane Smith','456 Oak St,San Francisco,CA','415-555-3434'),(3,'Mike Johnson','789 Elm St,Dallas,TX','214-555-5656'),(4,'Emilia Clarke','700 Spruce St,New York,NY','646-555-7878');
|
SELECT customer_id, SUM(weight) AS total_weight FROM Shipment WHERE shipped_date >= DATEADD(month, -1, GETDATE()) GROUP BY customer_id ORDER BY total_weight DESC;
|
What is the average age of male reporters in the 'news' table?
|
CREATE TABLE news (id INT,name VARCHAR(50),gender VARCHAR(10),age INT); INSERT INTO news (id,name,gender,age) VALUES (1,'John','Male',35),(2,'Alex','Male',45);
|
SELECT AVG(age) FROM news WHERE gender = 'Male';
|
What is the total cost of goods sold for each product line in the 'finance' schema?
|
CREATE TABLE finance.cost_of_goods_sold (product_line VARCHAR(50),month INT,year INT,cost DECIMAL(10,2)); INSERT INTO finance.cost_of_goods_sold (product_line,month,year,cost) VALUES ('Product Line A',1,2022,10000.00),('Product Line A',2,2022,20000.00),('Product Line B',1,2022,15000.00),('Product Line B',2,2022,25000.00);
|
SELECT product_line, SUM(cost) as total_cost_of_goods_sold FROM finance.cost_of_goods_sold GROUP BY product_line;
|
What is the total number of climate monitoring stations in the 'canada' and 'greenland' regions?
|
CREATE TABLE climate_monitoring_stations (id INT,station_name VARCHAR(255),region VARCHAR(255)); INSERT INTO climate_monitoring_stations (id,station_name,region) VALUES (1,'Station A','canada'),(2,'Station B','greenland'),(3,'Station C','canada'),(4,'Station D','norway');
|
SELECT region FROM climate_monitoring_stations WHERE region IN ('canada', 'greenland') GROUP BY region;
|
List all virtual reality (VR) games with a rating higher than 8.5, ordered alphabetically.
|
CREATE TABLE Games (GameID INT,GameName VARCHAR(100),Genre VARCHAR(50),Rating DECIMAL(3,1)); INSERT INTO Games (GameID,GameName,Genre,Rating) VALUES (1,'Beat Saber','VR',9.0),(2,'Job Simulator','VR',8.3),(3,'Echo VR','VR',8.7);
|
SELECT GameName FROM Games WHERE Genre = 'VR' AND Rating > 8.5 ORDER BY GameName;
|
What is the average horsepower of electric vehicles manufactured in Germany?
|
CREATE TABLE Manufacturers (ID INT,Name VARCHAR(100),Country VARCHAR(50)); INSERT INTO Manufacturers (ID,Name,Country) VALUES (1,'Audi','Germany'),(2,'BMW','Germany'),(3,'Porsche','Germany'); CREATE TABLE Vehicles (ID INT,Name VARCHAR(100),ManufacturerID INT,Horsepower INT,VehicleType VARCHAR(50)); INSERT INTO Vehicles (ID,Name,ManufacturerID,Horsepower,VehicleType) VALUES (1,'e-Tron',1,402,'Electric'),(2,'i3',2,170,'Electric'),(3,'i8',2,369,'Electric'),(4,'Taycan',3,751,'Electric');
|
SELECT AVG(Horsepower) FROM Vehicles WHERE ManufacturerID IN (SELECT ID FROM Manufacturers WHERE Country = 'Germany') AND VehicleType = 'Electric';
|
What is the total number of factories in the 'Renewable Energy' sector that are compliant with ethical manufacturing practices?
|
CREATE TABLE factories (id INT,sector VARCHAR(255),ethical_practices BOOLEAN);
|
SELECT COUNT(*) FROM factories WHERE sector = 'Renewable Energy' AND ethical_practices = TRUE;
|
What is the failure rate for SpaceX missions?
|
CREATE TABLE space_missions (mission_id INT,mission_year INT,mission_status VARCHAR(10),mission_company VARCHAR(100));
|
SELECT mission_company, COUNT(*) * 100.0 / (SELECT COUNT(*) FROM space_missions WHERE mission_company = 'SpaceX') AS failure_rate FROM space_missions WHERE mission_status = 'failed' AND mission_company = 'SpaceX' GROUP BY mission_company;
|
List all attorneys who have not handled any cases?
|
CREATE TABLE attorneys (attorney_id INT,name VARCHAR(50)); CREATE TABLE cases (case_id INT,attorney_id INT); INSERT INTO attorneys (attorney_id,name) VALUES (1,'Smith'),(2,'Johnson'),(3,'Williams'),(4,'Brown'); INSERT INTO cases (case_id,attorney_id) VALUES (1,2),(2,1),(3,3),(4,2);
|
SELECT attorneys.name FROM attorneys LEFT JOIN cases ON attorneys.attorney_id = cases.attorney_id WHERE cases.attorney_id IS NULL;
|
What are the top 3 genres with the most songs in the song_releases table?
|
CREATE TABLE song_releases (song_id INT,genre VARCHAR(20));
|
SELECT genre, COUNT(*) FROM song_releases GROUP BY genre ORDER BY COUNT(*) DESC LIMIT 3;
|
What is the total amount of resources depleted by each mining operation last quarter?
|
CREATE TABLE ResourceDepletion (Operation VARCHAR(50),Resource VARCHAR(50),DepletionQuantity FLOAT); INSERT INTO ResourceDepletion(Operation,Resource,DepletionQuantity) VALUES ('Operation A','Coal',12000),('Operation A','Iron',15000),('Operation B','Coal',10000),('Operation B','Iron',18000),('Operation C','Coal',16000),('Operation C','Iron',13000);
|
SELECT Operation, SUM(DepletionQuantity) FROM ResourceDepletion WHERE Resource IN ('Coal', 'Iron') AND DepletionQuantity >= 0 GROUP BY Operation;
|
What are the R&D projects in the 'Cybersecurity' category and their start dates?
|
CREATE TABLE if not exists rnd_projects (id INT,project_name VARCHAR(100),category VARCHAR(50),cost INT,start_date DATE,end_date DATE); INSERT INTO rnd_projects (id,project_name,category,cost,start_date,end_date) VALUES (1,'Stealth Fighter','Aircraft',5000000,'2010-01-01','2015-12-31'); INSERT INTO rnd_projects (id,project_name,category,cost,start_date,end_date) VALUES (2,'AI-Powered Drone','UAV',1000000,'2018-01-01','2020-12-31');
|
SELECT project_name, category, start_date FROM rnd_projects WHERE category = 'Cybersecurity';
|
What is the earliest year of a vehicle in the 'maintenance' schema?
|
CREATE SCHEMA maintenance; CREATE TABLE maintenance.vehicle_maintenance (id INT PRIMARY KEY,vehicle_id INT,year INT); INSERT INTO maintenance.vehicle_maintenance (id,vehicle_id,year) VALUES (1,1,2015),(2,2,2018),(3,3,2020),(4,4,2017),(5,5,2019);
|
SELECT MIN(year) FROM maintenance.vehicle_maintenance;
|
Find the percentage of female and male employees in the 'mining_operations' table, grouped by their job title.
|
CREATE TABLE mining_operations (employee_id INT,job_title VARCHAR(50),gender VARCHAR(10)); INSERT INTO mining_operations (employee_id,job_title,gender) VALUES (1,'Engineer','Male'),(2,'Operator','Female'),(3,'Manager','Male');
|
SELECT job_title, CONCAT(ROUND(100.0 * SUM(CASE WHEN gender = 'Female' THEN 1 ELSE 0 END) / COUNT(*) * 100.0, 2), '%') as female_percentage, CONCAT(ROUND(100.0 * SUM(CASE WHEN gender = 'Male' THEN 1 ELSE 0 END) / COUNT(*) * 100.0, 2), '%') as male_percentage FROM mining_operations GROUP BY job_title;
|
How many sustainable tourism initiatives are there in total in 'sustainable_tourism_initiatives' table?
|
CREATE TABLE sustainable_tourism_initiatives (initiative_id INT,initiative VARCHAR(50)); INSERT INTO sustainable_tourism_initiatives (initiative_id,initiative) VALUES (1,'Eco-tours'),(2,'Green hotels'),(3,'Carbon offset programs');
|
SELECT COUNT(*) FROM sustainable_tourism_initiatives;
|
What is the average speed of all cyclists in the tour_de_france table, grouped by stage?
|
CREATE TABLE tour_de_france (id INT,cyclist VARCHAR(50),stage INT,speed DECIMAL(5,2));
|
SELECT stage, AVG(speed) AS avg_speed FROM tour_de_france GROUP BY stage;
|
What is the average temperature in the Antarctic region in 2020?
|
CREATE TABLE temperature_data (id INT,region VARCHAR(50),year INT,temperature DECIMAL); INSERT INTO temperature_data (id,region,year,temperature) VALUES (1,'Arctic',2020,-25.6); INSERT INTO temperature_data (id,region,year,temperature) VALUES (2,'Antarctic',2019,-35.7); INSERT INTO temperature_data (id,region,year,temperature) VALUES (3,'Antarctic',2020,-45.6);
|
SELECT AVG(temperature) FROM temperature_data WHERE region = 'Antarctic' AND year = 2020;
|
What is the sum of budgets for construction projects in Arizona that started after 2017?
|
CREATE TABLE Budget_Sum (id INT,project_name TEXT,state TEXT,start_date DATE,budget INT); INSERT INTO Budget_Sum (id,project_name,state,start_date,budget) VALUES (1,'Highway Expansion','Arizona','2018-02-14',12000000),(2,'School Addition','Arizona','2017-12-31',8000000);
|
SELECT SUM(budget) FROM Budget_Sum WHERE state = 'Arizona' AND start_date > '2017-01-01';
|
What is the total number of safety incidents, by type, in the 'safety_incidents' table?
|
CREATE TABLE safety_incidents (id INT,incident_type VARCHAR(50),incident_date DATE); INSERT INTO safety_incidents (id,incident_type,incident_date) VALUES (1,'Fall','2021-03-15'),(2,'Electrical Shock','2021-03-17'),(3,'Fall','2021-03-20');
|
SELECT incident_type, COUNT(*) as num_incidents FROM safety_incidents GROUP BY incident_type;
|
Show the number of athletes enrolled in wellbeing programs, by sport, for the past year.
|
CREATE TABLE athlete (athlete_id INT,name VARCHAR(50),sport VARCHAR(50)); CREATE TABLE wellbeing_programs (program_id INT,athlete_id INT,enrollment_date DATE); INSERT INTO athlete VALUES (1,'Jane Smith','Basketball'); INSERT INTO wellbeing_programs VALUES (1,1,'2022-06-15');
|
SELECT a.sport, COUNT(DISTINCT a.athlete_id) AS athletes_enrolled FROM athlete a JOIN wellbeing_programs wp ON a.athlete_id = wp.athlete_id WHERE wp.enrollment_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR) GROUP BY a.sport;
|
List all permits that were issued in the second quarter of the year
|
CREATE TABLE building_permits (permit_number VARCHAR(10),issue_date DATE); INSERT INTO building_permits (permit_number,issue_date) VALUES ('N-12345','2021-03-01'),('A-54321','2021-06-15'),('P-98765','2021-09-30');
|
SELECT permit_number FROM building_permits WHERE EXTRACT(QUARTER FROM issue_date) = 2;
|
How many marine species are recorded in the Indian Ocean, excluding fish?
|
CREATE TABLE indian_ocean (id INT,name VARCHAR(100),region VARCHAR(50)); CREATE TABLE marine_species (id INT,name VARCHAR(100),species_type VARCHAR(50),ocean_id INT); INSERT INTO indian_ocean (id,name,region) VALUES (1,'Indian Ocean','Indian'); INSERT INTO marine_species (id,name,species_type,ocean_id) VALUES (1,'Blue Whale','Mammal',1),(2,'Clownfish','Fish',1);
|
SELECT COUNT(*) FROM marine_species ms WHERE ms.ocean_id = (SELECT id FROM indian_ocean WHERE name = 'Indian Ocean') AND species_type != 'Fish';
|
What is the maximum length of any wastewater treatment facility in California, and the name of the facility, along with its construction year?
|
CREATE TABLE wastewater_treatment_facilities (id INT,facility_name VARCHAR(255),location VARCHAR(255),length FLOAT,construction_year INT); INSERT INTO wastewater_treatment_facilities (id,facility_name,location,length,construction_year) VALUES (1,'Central Valley Water Treatment','California',12.5,1995),(2,'Southern California Water Reclamation','California',15.2,2000),(3,'San Francisco Water Treatment','California',10.8,2005);
|
SELECT facility_name, length, construction_year FROM wastewater_treatment_facilities WHERE location = 'California' AND length = (SELECT MAX(length) FROM wastewater_treatment_facilities WHERE location = 'California');
|
What is the average broadband speed for subscribers in each country?
|
CREATE TABLE broadband_subscribers (id INT,subscriber_name VARCHAR(50),country VARCHAR(50),speed DECIMAL(10,2));
|
SELECT country, AVG(speed) FROM broadband_subscribers GROUP BY country;
|
Find the difference in the number of IoT sensors installed in January and February.
|
CREATE TABLE iot_sensors (id INT,installation_date DATE,sensor_type VARCHAR(255)); INSERT INTO iot_sensors (id,installation_date,sensor_type) VALUES (1,'2022-01-01','temperature'),(2,'2022-01-05','humidity'),(3,'2022-02-10','moisture'),(4,'2022-02-15','light');
|
SELECT COUNT(*) - (SELECT COUNT(*) FROM iot_sensors WHERE MONTH(installation_date) = 2) AS jan_feb_sensor_count_diff FROM iot_sensors WHERE MONTH(installation_date) = 1;
|
How many streams were there for the R&B genre in 2021?
|
CREATE TABLE music_streams (stream_id INT,genre VARCHAR(10),year INT,streams INT); INSERT INTO music_streams (stream_id,genre,year,streams) VALUES (1,'Classical',2019,1000000),(2,'Jazz',2020,1500000),(3,'Classical',2020,1200000),(4,'Pop',2019,1800000),(5,'Rock',2021,4500000),(6,'R&B',2021,5000000); CREATE VIEW genre_streams AS SELECT genre,SUM(streams) as total_streams FROM music_streams GROUP BY genre;
|
SELECT total_streams FROM genre_streams WHERE genre = 'R&B' AND year = 2021;
|
What is the total claim amount for policyholders who are male and over the age of 50?
|
CREATE TABLE Policyholders (ID INT,Name VARCHAR(50),Age INT,Gender VARCHAR(10),City VARCHAR(50),State VARCHAR(20),ZipCode VARCHAR(10)); CREATE TABLE Claims (ID INT,PolicyholderID INT,ClaimAmount DECIMAL(10,2),ClaimDate DATE);
|
SELECT SUM(Claims.ClaimAmount) FROM Claims JOIN Policyholders ON Claims.PolicyholderID = Policyholders.ID WHERE Policyholders.Gender = 'Male' AND Policyholders.Age > 50;
|
What is the number of public meetings held in the Midwest in the past year?
|
CREATE TABLE public_meetings (meeting_id INT,meeting_name VARCHAR(255),state VARCHAR(255),region VARCHAR(255),meeting_date DATE); INSERT INTO public_meetings (meeting_id,meeting_name,state,region,meeting_date) VALUES (1,'Meeting A','Illinois','Midwest','2022-01-01'),(2,'Meeting B','Indiana','Midwest','2022-02-01');
|
SELECT COUNT(*) FROM public_meetings WHERE region = 'Midwest' AND meeting_date >= DATEADD(year, -1, GETDATE());
|
How many patients were treated in each region in Canada?
|
CREATE TABLE patients (id INT,region VARCHAR(255),treatment_received BOOLEAN); INSERT INTO patients (id,region,treatment_received) VALUES (1,'Ontario',true),(2,'Quebec',false),(3,'Ontario',true);
|
SELECT region, COUNT(*) FROM patients WHERE treatment_received = true GROUP BY region;
|
How many fair trade certified products does each brand offer?
|
CREATE TABLE brands (brand_id INT,brand_name TEXT); INSERT INTO brands (brand_id,brand_name) VALUES (1,'H&M'),(2,'Patagonia'),(3,'Everlane'); CREATE TABLE products (product_id INT,product_name TEXT,brand_id INT,fair_trade_certified BOOLEAN); INSERT INTO products (product_id,product_name,brand_id,fair_trade_certified) VALUES (1,'Organic Cotton T-Shirt',1,TRUE),(2,'Organic Cotton T-Shirt',2,FALSE),(3,'Organic Cotton Hoodie',2,TRUE),(4,'Hemp T-Shirt',3,TRUE);
|
SELECT brands.brand_name, COUNT(*) as num_fair_trade FROM brands JOIN products ON brands.brand_id = products.brand_id WHERE products.fair_trade_certified = TRUE GROUP BY brands.brand_id;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.