instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
What is the minimum energy efficiency rating for buildings in California, and the maximum energy efficiency rating for buildings in California?
CREATE TABLE buildings (id INT,state VARCHAR(255),energy_efficiency_rating FLOAT); INSERT INTO buildings (id,state,energy_efficiency_rating) VALUES (1,'CA',90.5),(2,'NY',85.0),(3,'FL',95.0),(4,'TX',88.0),(5,'CA',92.0),(6,'NY',87.5),(7,'FL',94.5),(8,'TX',89.5),(9,'CA',85.0),(10,'CA',96.0);
SELECT MIN(energy_efficiency_rating) as min_rating, MAX(energy_efficiency_rating) as max_rating FROM buildings WHERE state = 'California';
Insert new farm 'Farm C' into aquaculture_farms table.
CREATE TABLE aquaculture_farms (id INT,name VARCHAR(255)); INSERT INTO aquaculture_farms (id,name) VALUES (1,'Farm A'),(2,'Farm B');
INSERT INTO aquaculture_farms (name) VALUES ('Farm C');
What is the average research funding per faculty member in the Physics department?
CREATE TABLE funding (id INT,department VARCHAR(10),faculty_id INT,amount INT); INSERT INTO funding (id,department,faculty_id,amount) VALUES (1,'Physics',1,20000),(2,'Physics',2,25000),(3,'Physics',3,30000); CREATE TABLE faculty (id INT,department VARCHAR(10)); INSERT INTO faculty (id,department) VALUES (1,'Physics'),(...
SELECT AVG(amount) FROM funding JOIN faculty ON funding.faculty_id = faculty.id WHERE department = 'Physics';
Update the "CitizenFeedback" table to reflect new feedback for the specified public service
CREATE TABLE CitizenFeedback (ID INT,Service TEXT,Feedback TEXT,Timestamp DATETIME);
WITH feedback_update AS (UPDATE CitizenFeedback SET Feedback = 'Great service!', Timestamp = '2022-04-12 14:30:00' WHERE ID = 1001 AND Service = 'Senior Transportation' RETURNING ID, Service, Feedback, Timestamp) SELECT * FROM feedback_update;
Which cybersecurity strategies were implemented in 2021 and have not been updated since then?
CREATE TABLE cyber_strategy_implementation (strategy_id INT PRIMARY KEY,strategy_name VARCHAR(255),implementation_year INT); INSERT INTO cyber_strategy_implementation (strategy_id,strategy_name,implementation_year) VALUES (1,'Firewall Implementation',2021),(2,'Intrusion Detection System',2020),(3,'Penetration Testing',...
SELECT s.strategy_name FROM cyber_strategies s INNER JOIN cyber_strategy_implementation i ON s.strategy_name = i.strategy_name WHERE i.implementation_year = 2021 AND NOT EXISTS (SELECT 1 FROM cyber_strategy_updates u WHERE u.strategy_name = i.strategy_name AND u.update_date > i.implementation_date);
What is the average delivery time for each route?
CREATE TABLE route_stats (route_id VARCHAR(5),avg_delivery_time INT); INSERT INTO route_stats (route_id,avg_delivery_time) VALUES ('R1',45),('R2',30),('R3',50),('R4',60),('R5',70);
SELECT route_id, avg_delivery_time FROM route_stats;
Calculate the total annual energy savings for green buildings constructed in each month of the year
CREATE TABLE month (id INT,month TEXT);
SELECT month.month, SUM(green_buildings.annual_energy_savings_kWh) FROM green_buildings JOIN green_buildings_timeline ON green_buildings.id = green_buildings_timeline.building_id JOIN month ON MONTH(green_buildings_timeline.start_date) = month.id GROUP BY month.month;
Who are the top 3 artists with the highest number of art pieces in the sculpture medium?
CREATE TABLE artists (id INT,name TEXT,city TEXT,country TEXT);CREATE TABLE art_pieces (id INT,title TEXT,medium TEXT,artist_id INT);
SELECT a.name, COUNT(ap.id) as num_pieces FROM artists a JOIN art_pieces ap ON a.id = ap.artist_id WHERE ap.medium = 'sculpture' GROUP BY a.name ORDER BY num_pieces DESC LIMIT 3;
Insert a new museum
CREATE TABLE Museums (MuseumID INT,Name VARCHAR(100),City VARCHAR(50),Country VARCHAR(50));
INSERT INTO Museums (MuseumID, Name, City, Country) VALUES (2, 'Museo de Arte Moderno', 'Mexico City', 'Mexico');
How many donors from Asia contributed more than $200 in H1 2022?
CREATE TABLE donations (id INT,donor VARCHAR(50),region VARCHAR(50),amount DECIMAL(10,2),donation_date DATE); INSERT INTO donations (id,donor,region,amount,donation_date) VALUES (1,'John Doe','Asia',500,'2022-01-05'); INSERT INTO donations (id,donor,region,amount,donation_date) VALUES (2,'Jane Smith','Europe',300,'2022...
SELECT region, COUNT(DISTINCT donor) as donor_count FROM donations WHERE region = 'Asia' AND amount > 200 AND donation_date BETWEEN '2022-01-01' AND '2022-06-30' GROUP BY region;
What is the renewable energy project budget for projects that started between 2017 and 2019, ordered by the project budget in descending order?
CREATE TABLE renewable_energy_projects (id INT,project_name VARCHAR(100),start_date DATE,project_budget FLOAT);
SELECT * FROM renewable_energy_projects WHERE start_date BETWEEN '2017-01-01' AND '2019-12-31' ORDER BY project_budget DESC;
How many hospitals are there in California?
CREATE TABLE Zipcodes (Zip VARCHAR(10),City VARCHAR(50),State VARCHAR(20),HospitalCount INT); INSERT INTO Zipcodes (Zip,City,State,HospitalCount) VALUES ('90001','Los Angeles','California',15);
SELECT SUM(HospitalCount) FROM Zipcodes WHERE State = 'California';
What is the minimum price for each garment category?
CREATE TABLE garment_prices (id INT PRIMARY KEY,category VARCHAR(20),price DECIMAL(5,2));
SELECT category, MIN(price) FROM garment_prices GROUP BY category;
What are the names and countries of cities with a population greater than 1,000,000?
CREATE TABLE cities (id INT PRIMARY KEY,name VARCHAR(50),country VARCHAR(50),population INT); INSERT INTO cities (id,name,country,population) VALUES (1,'Tokyo','Japan',9400000); INSERT INTO cities (id,name,country,population) VALUES (2,'Delhi','India',16800000);
SELECT cities.name, cities.country FROM cities WHERE cities.population > 1000000;
What was the total revenue for each team in the 2021 season?
CREATE TABLE teams (id INT,name VARCHAR(255)); INSERT INTO teams (id,name) VALUES (1,'TeamA'),(2,'TeamB'); CREATE TABLE games (id INT,home_team_id INT,away_team_id INT,home_team_score INT,away_team_score INT,price DECIMAL(5,2)); CREATE TABLE revenue (team_id INT,year INT,revenue DECIMAL(10,2));
SELECT t.name, r.year, SUM(r.revenue) as total_revenue FROM revenue r JOIN teams t ON r.team_id = t.id WHERE r.year = 2021 GROUP BY t.name, r.year;
What is the average rating of eco-friendly accommodations in Australia?
CREATE TABLE accommodations (accommodation_id INT,name TEXT,country TEXT,is_eco_friendly BOOLEAN,rating FLOAT); INSERT INTO accommodations (accommodation_id,name,country,is_eco_friendly,rating) VALUES (1,'Green Lodge','Australia',TRUE,4.5),(2,'Eco Retreat','Australia',TRUE,4.7),(3,'Hotel City','Australia',FALSE,3.9);
SELECT AVG(rating) FROM accommodations WHERE country = 'Australia' AND is_eco_friendly = TRUE;
What is the total length of all tunnels in the state of New York?
CREATE TABLE Tunnels (id INT,name TEXT,state TEXT,length FLOAT); INSERT INTO Tunnels (id,name,state,length) VALUES (1,'Holland Tunnel','New York',8500.0); INSERT INTO Tunnels (id,name,state,length) VALUES (2,'Queens Midtown Tunnel','New York',1900.0);
SELECT SUM(length) FROM Tunnels WHERE state = 'New York'
Insert a new record into the "public_works_projects" table for a project called "Road Resurfacing Initiative"
CREATE TABLE public_works_projects (project_id INT,project_name VARCHAR(50),start_date DATE,end_date DATE,budget DECIMAL(10,2));
INSERT INTO public_works_projects (project_name) VALUES ('Road Resurfacing Initiative');
Find the number of rural healthcare providers in each region, ranked by total in Oregon.
CREATE TABLE providers (provider_id INT,name TEXT,location TEXT,rural BOOLEAN);CREATE TABLE regions (region_id INT,name TEXT,state TEXT,rural_population INT);
SELECT region, COUNT(*) AS providers FROM providers WHERE rural GROUP BY region ORDER BY providers DESC;
Who are the top 3 streamed artists from the United States?
CREATE TABLE Users (UserID INT,UserName VARCHAR(100),Country VARCHAR(50)); INSERT INTO Users VALUES (1,'User A','United States'),(2,'User B','Canada'),(3,'User C','United States');
SELECT ArtistID, COUNT(*) AS StreamCount FROM Streams JOIN Users ON Streams.UserID = Users.UserID WHERE Users.Country = 'United States' GROUP BY ArtistID ORDER BY StreamCount DESC LIMIT 3;
Which vessels have not been inspected for over a month, and what is their average capacity?
CREATE TABLE vessels (vessel_id INT,vessel_name VARCHAR(100),last_inspection_date DATE,capacity INT); INSERT INTO vessels VALUES (1,'MV Ever Given','2022-02-28',20000); INSERT INTO vessels VALUES (2,'MV Maersk Mc-Kinney Moller','2022-03-15',15000); INSERT INTO vessels VALUES (3,'MV CMA CGM Jacques Saade',NULL,22000);
SELECT vessels.vessel_name, AVG(vessels.capacity) as avg_capacity FROM vessels WHERE vessels.last_inspection_date < DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH) GROUP BY vessels.vessel_name;
List all building projects that started before 2020-06-01 and ended after 2020-12-31?
CREATE TABLE project_timeline (id INT,project VARCHAR(50),start_date DATE,end_date DATE); INSERT INTO project_timeline (id,project,start_date,end_date) VALUES (1,'Office Building','2019-12-20','2021-04-30'),(2,'Residential Apartments','2021-03-01','2022-08-01'),(3,'School','2020-06-15','2021-10-15');
SELECT * FROM project_timeline WHERE start_date < '2020-06-01' AND end_date > '2020-12-31';
How many users have interacted with accessible technology in each country?
CREATE TABLE users (user_id INT,country VARCHAR(50)); INSERT INTO users VALUES (1,'USA'),(2,'Canada'),(3,'Mexico'); CREATE TABLE interactions (interaction_id INT,user_id INT,technology_type VARCHAR(20)); INSERT INTO interactions VALUES (1,1,'accessible'),(2,2,'non-accessible'),(3,3,'accessible');
SELECT country, COUNT(DISTINCT user_id) FROM interactions INNER JOIN users ON interactions.user_id = users.user_id WHERE technology_type = 'accessible' GROUP BY country;
What is the maximum budget allocated to a department in 2023?
CREATE TABLE department (id INT,name TEXT,budget INT,created_at DATETIME); INSERT INTO department (id,name,budget,created_at) VALUES (1,'education',500000,'2021-01-01'),(2,'healthcare',1000000,'2022-01-01');
SELECT name, MAX(budget) as max_budget FROM department WHERE created_at BETWEEN '2023-01-01' AND '2023-12-31' GROUP BY name;
What is the total budget for technology for social good projects in the Middle East?
CREATE TABLE Tech_For_Good (project_id INT,project_name VARCHAR(100),region VARCHAR(50),budget FLOAT); INSERT INTO Tech_For_Good (project_id,project_name,region,budget) VALUES (1,'Project A','Middle East',45000.00),(2,'Project B','Africa',55000.00),(3,'Project C','Asia',65000.00);
SELECT SUM(budget) FROM Tech_For_Good WHERE region = 'Middle East';
What is the minimum fare for trams in the 'Riverside' region?
CREATE TABLE Trams (tram_id INT,region VARCHAR(20),fare DECIMAL(5,2)); INSERT INTO Trams (tram_id,region,fare) VALUES (501,'Riverside',2.00),(502,'Riverside',2.50),(503,'Riverside',3.00);
SELECT MIN(fare) FROM Trams WHERE region = 'Riverside';
What are the names of astronauts who have flown on both SpaceX and NASA crafts and their respective missions?
CREATE TABLE astronauts (astronaut_id INT,name VARCHAR(100),age INT,craft VARCHAR(50),mission VARCHAR(100)); INSERT INTO astronauts (astronaut_id,name,age,craft,mission) VALUES (1,'John',45,'Dragon','Mars'),(2,'Sarah',36,'Starship','ISS'),(3,'Mike',50,'Falcon','Mars'),(4,'Jane',42,'Apollo','Moon'),(5,'Emma',34,'Shuttle...
SELECT DISTINCT a.name, a.mission FROM astronauts a INNER JOIN spacex_crafts c ON a.craft = c.craft INNER JOIN nasa_crafts n ON a.craft = n.craft;
How many tickets were sold by age group?
CREATE TABLE age_groups (age_group_id INT,age_group_name VARCHAR(50),lower_bound INT,upper_bound INT);
SELECT ag.age_group_name, SUM(t.quantity) as tickets_sold FROM age_groups ag JOIN tickets t ON t.age BETWEEN ag.lower_bound AND ag.upper_bound GROUP BY ag.age_group_name;
What is the maximum speed of vessels in the container ship category?
CREATE TABLE Vessels (VesselID INT,VesselType VARCHAR(50),AvgSpeed DECIMAL(5,2)); INSERT INTO Vessels VALUES (1,'Container Ship',21.5),(2,'Tanker',18.2),(3,'Container Ship',22.6);
SELECT MAX(AvgSpeed) FROM Vessels WHERE VesselType = 'Container Ship';
What is the percentage of children vaccinated for Hepatitis B in South America?
CREATE TABLE Vaccinations (Disease VARCHAR(50),Continent VARCHAR(50),Percentage_Vaccinated FLOAT); INSERT INTO Vaccinations (Disease,Continent,Percentage_Vaccinated) VALUES ('Hepatitis B','South America',90.0);
SELECT Percentage_Vaccinated FROM Vaccinations WHERE Disease = 'Hepatitis B' AND Continent = 'South America';
What is the average response time for emergency calls in the city of Chicago during the winter months (December, January, February)?
CREATE TABLE emergency_calls (id INT,city VARCHAR(20),call_date DATE,response_time INT); INSERT INTO emergency_calls (id,city,call_date,response_time) VALUES (1,'Chicago','2021-12-01',120),(2,'Chicago','2022-01-15',150),(3,'Chicago','2022-02-28',90);
SELECT AVG(response_time) FROM emergency_calls WHERE city = 'Chicago' AND EXTRACT(MONTH FROM call_date) IN (12, 1, 2);
Display the number of employees who have completed technical training, by country, and sort the results by the number of employees in descending order
CREATE TABLE Employees (EmployeeID INT,FirstName VARCHAR(50),LastName VARCHAR(50),Country VARCHAR(50),TechnicalTraining BOOLEAN); INSERT INTO Employees (EmployeeID,FirstName,LastName,Country,TechnicalTraining) VALUES (1,'John','Doe','USA',true); INSERT INTO Employees (EmployeeID,FirstName,LastName,Country,TechnicalTrai...
SELECT Country, COUNT(*) as NumberOfEmployees FROM Employees WHERE TechnicalTraining = true GROUP BY Country ORDER BY NumberOfEmployees DESC;
Calculate the total duration spent on exhibitions by visitors from each US state.
CREATE TABLE exhibition_visits (id INT,visitor_id INT,exhibition_id INT,duration_mins INT,state TEXT); INSERT INTO exhibition_visits (id,visitor_id,exhibition_id,duration_mins,state) VALUES (1,1,1,60,'CA'),(2,2,1,75,'NY');
SELECT state, SUM(duration_mins) FROM exhibition_visits WHERE state IS NOT NULL GROUP BY state;
Calculate the minimum heart rate recorded for users living in Florida on weekends.
CREATE TABLE users (id INT,state VARCHAR(20)); CREATE TABLE workout_data (id INT,user_id INT,hr INT,date DATE);
SELECT MIN(hr) FROM workout_data w JOIN users u ON w.user_id = u.id WHERE u.state = 'Florida' AND (DAYOFWEEK(w.date) = 1 OR DAYOFWEEK(w.date) = 7);
What is the minimum number of likes for posts related to vegan food?
CREATE TABLE posts (id INT,category VARCHAR(255),likes INT); INSERT INTO posts (id,category,likes) VALUES (1,'Vegan Food',100),(2,'Vegan Food',200),(3,'Fitness',300),(4,'Travel',400),(5,'Vegan Food',500);
SELECT MIN(posts.likes) AS min_likes FROM posts WHERE posts.category = 'Vegan Food';
Delete any marine protected areas with an average depth below 100 meters.
CREATE TABLE marine_protected_areas (name VARCHAR(255),location VARCHAR(255),avg_depth FLOAT);
DELETE FROM marine_protected_areas WHERE avg_depth < 100;
What are the total expenses for SpaceX satellite deployment projects, NASA space exploration research programs, and ROSCOSMOS space station missions?
CREATE TABLE ROSCOSMOS_Missions (mission_id INT,name VARCHAR(50),type VARCHAR(50),expenses DECIMAL(10,2)); INSERT INTO ROSCOSMOS_Missions (mission_id,name,type,expenses) VALUES (1,'MIR','Space Station',3500000.00),(2,'ISS Upgrades','Space Station',2000000.00);
SELECT SUM(expenses) FROM SpaceX_Projects WHERE type IN ('Satellite Deployment', 'Space Exploration') UNION ALL SELECT SUM(expenses) FROM NASA_Research WHERE type IN ('Space Exploration', 'Space Station') UNION ALL SELECT SUM(expenses) FROM ROSCOSMOS_Missions WHERE type = 'Space Station';
Which customers have made investments in both the US and Canada?
CREATE TABLE customers (customer_id INT,name TEXT,country TEXT); INSERT INTO customers (customer_id,name,country) VALUES (1,'John Doe','USA'); INSERT INTO customers (customer_id,name,country) VALUES (2,'Jane Smith','Canada');
SELECT customer_id, name FROM customers WHERE country = 'USA' INTERSECT SELECT customer_id, name FROM customers WHERE country = 'Canada';
What is the average number of visitors per month for cultural events in Tokyo?
CREATE TABLE Cultural_Events (name VARCHAR(255),city VARCHAR(255),visitors_per_month DECIMAL(5,2));
SELECT AVG(visitors_per_month) FROM Cultural_Events WHERE city = 'Tokyo';
list all hospitals and their capacities in 'Region3'
CREATE TABLE Regions (RegionName VARCHAR(20),HospitalName VARCHAR(20),HospitalCapacity INT); INSERT INTO Regions (RegionName,HospitalName,HospitalCapacity) VALUES ('Region3','HospitalX',200),('Region3','HospitalY',250);
SELECT HospitalName, HospitalCapacity FROM Regions WHERE RegionName = 'Region3';
What is the average property price for buildings with a green certification in each city?
CREATE TABLE cities (id INT,name VARCHAR(30)); CREATE TABLE properties (id INT,city VARCHAR(20),price INT,green_certified BOOLEAN); INSERT INTO cities (id,name) VALUES (1,'Vancouver'),(2,'Seattle'),(3,'Portland'); INSERT INTO properties (id,city,price,green_certified) VALUES (101,'Vancouver',600000,true),(102,'Vancouve...
SELECT cities.name, AVG(properties.price) FROM cities INNER JOIN properties ON cities.name = properties.city WHERE properties.green_certified = true GROUP BY cities.name;
What is the total revenue for events in the 'Art' category?
CREATE TABLE Events (id INT,name VARCHAR(255),date DATE,category VARCHAR(255),revenue INT); CREATE VIEW EventRevenue AS SELECT id,SUM(revenue) AS total_revenue FROM Events GROUP BY id;
SELECT total_revenue FROM EventRevenue WHERE id IN (SELECT id FROM Events WHERE category = 'Art');
What is the average CO2 emission for each mode of transport in 2021 and 2022?
CREATE TABLE Transport_Emissions (id INT,mode VARCHAR(20),co2_emission FLOAT,year INT); INSERT INTO Transport_Emissions (id,mode,co2_emission,year) VALUES (1,'Plane',120.0,2021),(2,'Train',15.0,2021),(3,'Bus',40.0,2021),(4,'Car',60.0,2021),(5,'Plane',130.0,2022),(6,'Train',16.0,2022),(7,'Bus',42.0,2022),(8,'Car',65.0,2...
SELECT mode, AVG(co2_emission) as avg_emission FROM Transport_Emissions WHERE year IN (2021, 2022) GROUP BY mode;
List the top 3 cities with the most packages shipped in March 2022
CREATE TABLE packages (id INT,warehouse_id INT,weight FLOAT); INSERT INTO packages (id,warehouse_id,weight) VALUES (1,1,50.5),(2,1,45.3),(3,2,60.1),(4,2,70.0),(5,3,30.2);
SELECT warehouses.city, COUNT(*) as num_shipments FROM shipments JOIN packages ON shipments.id = packages.id JOIN warehouses ON shipments.warehouse_id = warehouses.id WHERE sent_date >= '2022-03-01' AND sent_date < '2022-04-01' GROUP BY warehouses.city ORDER BY num_shipments DESC LIMIT 3;
What was the average funding per attendee for the 'Theater for All' programs in New York?
CREATE TABLE funding_distribution (program_name VARCHAR(50),city VARCHAR(50),attendees INT,amount DECIMAL(10,2)); INSERT INTO funding_distribution (program_name,city,attendees,amount) VALUES ('Theater for All','New York',100,15000.00);
SELECT AVG(amount / attendees) FROM funding_distribution WHERE program_name = 'Theater for All' AND city = 'New York';
How many community policing programs were implemented in Denver in 2018?
CREATE TABLE community_programs (id INT,program VARCHAR(30),city VARCHAR(20),start_year INT); INSERT INTO community_programs (id,program,city,start_year) VALUES (1,'Coffee with a Cop','Denver',2015),(2,'Block Watch','Denver',2016),(3,'Community Police Academy','Denver',2017),(4,'Junior Police Academy','Denver',2018),(5...
SELECT COUNT(*) as total FROM community_programs WHERE city = 'Denver' AND start_year = 2018;
Find the number of sensors for each crop type in the 'sensor_data_2021' table.
CREATE TABLE sensor_data_2021 (id INT,crop VARCHAR(20),sensor_id INT); INSERT INTO sensor_data_2021 (id,crop,sensor_id) VALUES (1,'Corn',101),(2,'Soybean',102),(3,'Corn',103);
SELECT crop, COUNT(DISTINCT sensor_id) FROM sensor_data_2021 GROUP BY crop;
What is the total number of players in the Players table?
CREATE TABLE Players (Player_ID INT,Age INT,Gender VARCHAR(10),Country VARCHAR(20)); INSERT INTO Players (Player_ID,Age,Gender,Country) VALUES (1,25,'Male','Country_X'),(2,30,'Female','Country_Y');
SELECT COUNT(*) FROM Players;
Show the total number of security incidents that occurred in the last month, broken down by the day they occurred and the source IP address.
CREATE TABLE security_incidents (incident_time TIMESTAMP,source_ip VARCHAR(255));
SELECT DATE(incident_time) AS incident_date, source_ip, COUNT(*) AS total FROM security_incidents WHERE incident_time >= NOW() - INTERVAL '1 month' GROUP BY incident_date, source_ip;
What was the highest revenue drug in 2022?
CREATE TABLE drug_revenues (drug_name VARCHAR(100),revenue FLOAT,year INT); INSERT INTO drug_revenues (drug_name,revenue,year) VALUES ('DrugA',1500000,2022),('DrugB',2000000,2022),('DrugC',1200000,2022),('DrugD',2200000,2022);
SELECT drug_name, revenue FROM drug_revenues WHERE year = 2022 AND revenue = (SELECT MAX(revenue) FROM drug_revenues WHERE year = 2022);
Identify players who achieved a high score of over 1000 in game 'Call of Duty'
CREATE TABLE players (id INT,name VARCHAR(100),game_id INT,high_score INT); CREATE TABLE games (id INT,name VARCHAR(100)); INSERT INTO players (id,name,game_id,high_score) VALUES (1,'Jane Doe',1,1500); INSERT INTO games (id,name) VALUES (1,'Call of Duty');
SELECT players.name FROM players JOIN games ON players.game_id = games.id WHERE games.name = 'Call of Duty' AND players.high_score > 1000;
Find the total retail price of garments 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 fabric, SUM(retail_price) FROM Garments GROUP BY fabric;
What is the total cost of sustainable practices for the 'Mechanical Engineering' department?
CREATE TABLE SustainablePractices (PracticeID INT,PracticeName VARCHAR(50),Description VARCHAR(255),Department VARCHAR(50),Cost DECIMAL(10,2)); INSERT INTO SustainablePractices (PracticeID,PracticeName,Description,Department,Cost) VALUES (3,'Geothermal Energy','Utilizing geothermal energy to power construction equipmen...
SELECT SUM(SustainablePractices.Cost) FROM SustainablePractices WHERE SustainablePractices.Department = 'Mechanical Engineering';
Update the "region" field in the "destinations" table for all records with a "destination_name" of 'Rio de Janeiro' to be 'South America'
CREATE TABLE destinations (destination_id INT,destination_name VARCHAR(50),region VARCHAR(20),sustainable_practices_score DECIMAL(3,1),PRIMARY KEY (destination_id));
UPDATE destinations SET region = 'South America' WHERE destination_name = 'Rio de Janeiro';
What is the average data usage in gigabytes per month for customers in the city of Seattle?
CREATE TABLE customers (customer_id INT,name VARCHAR(255),city VARCHAR(255)); INSERT INTO customers (customer_id,name,city) VALUES (1,'John Doe','Seattle'),(2,'Jane Smith','New York'); CREATE TABLE data_usage (customer_id INT,monthly_data_usage DECIMAL(10,2)); INSERT INTO data_usage (customer_id,monthly_data_usage) VAL...
SELECT AVG(monthly_data_usage) FROM data_usage INNER JOIN customers ON data_usage.customer_id = customers.customer_id WHERE city = 'Seattle';
How many public transportation trips were taken in 2020, by mode and city?
CREATE TABLE TransportationTrips (Year INT,Mode VARCHAR(255),City VARCHAR(255),Count INT); INSERT INTO TransportationTrips (Year,Mode,City,Count) VALUES (2020,'Bus','New York',500000),(2020,'Subway','New York',700000),(2020,'Bus','Los Angeles',400000),(2020,'Subway','Los Angeles',600000),(2020,'LightRail','Los Angeles'...
SELECT Mode, City, SUM(Count) AS TotalTrips FROM TransportationTrips WHERE Year = 2020 GROUP BY Mode, City;
List the names of attorneys who have never lost a case.
CREATE TABLE cases (case_id INT,case_outcome VARCHAR(10),attorney_id INT); INSERT INTO cases (case_id,case_outcome,attorney_id) VALUES (1,'Won',101),(2,'Lost',102),(3,'Won',101); CREATE TABLE attorneys (attorney_id INT,attorney_name VARCHAR(20)); INSERT INTO attorneys (attorney_id,attorney_name) VALUES (101,'Smith'),(1...
SELECT a.attorney_name FROM attorneys a LEFT JOIN cases c ON a.attorney_id = c.attorney_id WHERE c.case_outcome IS NULL;
What is the total number of VR headsets sold in California, USA between 2018 and 2020?
CREATE TABLE VRHeadsetsSales (SaleID INT,State VARCHAR(50),Country VARCHAR(50),Year INT,QuantitySold INT); INSERT INTO VRHeadsetsSales (SaleID,State,Country,Year,QuantitySold) VALUES (1,'California','USA',2017,2000),(2,'Texas','USA',2018,3000),(3,'California','USA',2018,4000),(4,'California','USA',2019,5000),(5,'New Yo...
SELECT SUM(QuantitySold) FROM VRHeadsetsSales WHERE State = 'California' AND Year BETWEEN 2018 AND 2020;
What is the average project timeline in months for sustainable building projects in the city of Los Angeles?
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','Sustaina...
SELECT city, AVG(timeline_in_months) FROM project_timeline WHERE city = 'Los Angeles' AND project_type = 'Sustainable' GROUP BY city;
Which cruelty-free makeup brands have the highest customer satisfaction ratings?
CREATE TABLE brands (brand_id INT,brand_name VARCHAR(255),is_cruelty_free BOOLEAN,customer_satisfaction_rating DECIMAL(3,2));
SELECT brand_name, MAX(customer_satisfaction_rating) FROM brands WHERE is_cruelty_free = TRUE GROUP BY brand_name;
What is the total number of reported crimes in the state of Florida?
CREATE TABLE crimes (id INT,state VARCHAR(20),date DATE,crime VARCHAR(20)); INSERT INTO crimes (id,state,date,crime) VALUES (1,'Florida','2021-01-01','Theft'),(2,'Florida','2021-02-01','Burglary'),(3,'Florida','2021-03-01','Assault');
SELECT COUNT(*) FROM crimes WHERE state = 'Florida';
What is the maximum loan amount issued by a bank in a specific region?
CREATE TABLE banks (id INT,name VARCHAR(255),region VARCHAR(255)); CREATE TABLE loans (id INT,bank_id INT,amount DECIMAL(10,2),issue_date DATE); INSERT INTO banks (id,name,region) VALUES (1,'Islamic Bank 1','Middle East'),(2,'Islamic Bank 2','Asia'),(3,'Ethical Bank 1','Europe'),(4,'Socially Responsible Bank 1','North ...
SELECT MAX(l.amount) as max_loan_amount FROM banks b JOIN loans l ON b.id = l.bank_id WHERE b.region = 'Middle East';
List the top 5 countries with the highest number of unique users who have streamed music.
CREATE TABLE UserStreamCountries (Country VARCHAR(20),UserCount INT); INSERT INTO UserStreamCountries (Country,UserCount) VALUES ('USA','10000000'),('UK','6000000'),('Canada','4000000'),('Australia','3000000'),('Germany','5000000');
SELECT Country, UserCount FROM UserStreamCountries ORDER BY UserCount DESC LIMIT 5;
What is the average severity of vulnerabilities for each operating system?
CREATE TABLE Vulnerabilities (id INT,operating_system VARCHAR(255),severity INT); INSERT INTO Vulnerabilities (id,operating_system,severity) VALUES (1,'Windows',7),(2,'Linux',5),(3,'Windows',9); CREATE TABLE OperatingSystems (id INT,name VARCHAR(255)); INSERT INTO OperatingSystems (id,name) VALUES (1,'Windows'),(2,'Lin...
SELECT OperatingSystems.name AS Operating_System, AVG(Vulnerabilities.severity) AS Average_Severity FROM Vulnerabilities INNER JOIN OperatingSystems ON Vulnerabilities.operating_system = OperatingSystems.name GROUP BY OperatingSystems.name;
What is the total biomass (kg) of fish in fish farms located in the Arctic Ocean?
CREATE TABLE fish_farms (id INT,name TEXT,location TEXT,biomass FLOAT); INSERT INTO fish_farms (id,name,location,biomass) VALUES (1,'Farm A','Arctic Ocean',100.5),(2,'Farm B','Arctic Ocean',120.0),(3,'Farm C','Antarctic Ocean',150.0);
SELECT SUM(biomass) FROM fish_farms WHERE location = 'Arctic Ocean';
List the names and providers of virtual tours offered in Portugal and their respective providers.
CREATE TABLE virtual_tours (tour_id INT,name TEXT,provider TEXT,country TEXT); INSERT INTO virtual_tours (tour_id,name,provider,country) VALUES (1,'Lisbon City Tour','Virtual Voyages','Portugal'),(2,'Sintra Palace Tour','Virtually There','Portugal');
SELECT name, provider FROM virtual_tours WHERE country = 'Portugal';
What is the minimum time between subway train arrivals in New York City?
CREATE TABLE subway_stations (station_id INT,station_name VARCHAR(50),city VARCHAR(50),time_between_arrivals TIME); INSERT INTO subway_stations (station_id,station_name,city,time_between_arrivals) VALUES (1,'Times Square','New York City','5:00'),(2,'Grand Central','New York City','3:00'),(3,'Penn Station','New York Cit...
SELECT MIN(TIME_TO_SEC(time_between_arrivals))/60.0 FROM subway_stations WHERE city = 'New York City';
What is the total number of spacecraft built by each manufacturer and the number of those spacecraft that were part of missions to Mars?
CREATE TABLE Spacecrafts (id INT,name VARCHAR(100),manufacturer VARCHAR(100),mission_to_mars BOOLEAN); CREATE TABLE Manufacturers (id INT,name VARCHAR(100)); INSERT INTO Spacecrafts VALUES (1,'Mars Rover 1','SpaceCorp',TRUE); INSERT INTO Spacecrafts VALUES (2,'Mars Rover 2','SpaceCorp',FALSE); INSERT INTO Manufacturers...
SELECT Manufacturers.name, SUM(CASE WHEN Spacecrafts.mission_to_mars = TRUE THEN 1 ELSE 0 END) AS missions_to_mars, SUM(CASE WHEN Spacecrafts.mission_to_mars = TRUE THEN 1 ELSE 0 END) / COUNT(*) * 100 AS mars_mission_percentage FROM Spacecrafts INNER JOIN Manufacturers ON Spacecrafts.manufacturer = Manufacturers.name G...
Which organizations are associated with ethical AI frameworks and have given more than one talk?
CREATE TABLE ethical_ai_frameworks (id INT PRIMARY KEY,name VARCHAR(255),description TEXT,organization VARCHAR(255)); INSERT INTO ethical_ai_frameworks (id,name,description,organization) VALUES (1,'Ethical AI 1.0','A framework for building ethical AI','AI for Good Foundation'); INSERT INTO ethical_ai_frameworks (id,nam...
SELECT DISTINCT organization FROM talks WHERE organization IN (SELECT organization FROM ethical_ai_frameworks) GROUP BY organization HAVING COUNT(*) > 1;
What is the total installed capacity (in MW) of solar power plants in 'Africa' that have an efficiency rating above 22%?
CREATE TABLE solar_plants (id INT,name VARCHAR(50),location VARCHAR(50),efficiency FLOAT,capacity INT); INSERT INTO solar_plants (id,name,location,efficiency,capacity) VALUES (1,'SolarPlant1','Africa',0.25,100),(2,'SolarPlant2','Africa',0.28,150);
SELECT SUM(capacity) FROM solar_plants WHERE location = 'Africa' AND efficiency > 0.22;
Insert new records of ticket sales for a new event, identified by its event ID, including salesperson information.
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 salesperson VALUES (1,'John Doe','Senior Salesperson'); IN...
INSERT INTO tickets (ticket_id, salesperson_id, event_id, price, quantity) VALUES (2, 1, 2, 75, 50);
Drop the 'TopTeachers' view
CREATE TABLE Teachers (TeacherID INT,Name VARCHAR(100),Subject VARCHAR(50)); CREATE VIEW TopTeachers AS SELECT Name,Subject FROM Teachers WHERE Subject = 'Science';
DROP VIEW TopTeachers;
What is the minimum impact investment amount for the 'microfinance' sector?
CREATE TABLE impact_investments (id INT,sector VARCHAR(20),investment_amount FLOAT); INSERT INTO impact_investments (id,sector,investment_amount) VALUES (1,'microfinance',10000),(2,'renewable_energy',50000),(3,'microfinance',15000);
SELECT MIN(investment_amount) FROM impact_investments WHERE sector = 'microfinance';
Delete all records for the 'Australia' team from the players table.
CREATE TABLE players (player_name VARCHAR(50),jersey_number INT,country_name VARCHAR(50)); INSERT INTO players (player_name,jersey_number,country_name) VALUES ('John',10,'USA'),('Alex',12,'USA'),('James',7,'Australia'),('Ben',8,'Australia');
DELETE FROM players WHERE country_name = 'Australia';
Identify crops that are present in both organic and conventional farming methods.
CREATE TABLE Crops (name VARCHAR(50),farming_method VARCHAR(50)); INSERT INTO Crops (name,farming_method) VALUES ('Corn','Organic'),('Soybean','Conventional'),('Wheat','Organic');
SELECT name FROM Crops WHERE farming_method IN ('Organic', 'Conventional') GROUP BY name HAVING COUNT(DISTINCT farming_method) = 2
What is the total number of space missions launched before 1999?
CREATE TABLE Missions (id INT,name VARCHAR(50),launch_year INT); INSERT INTO Missions (id,name,launch_year) VALUES (1,'Mission1',2000),(2,'Mission2',1999),(3,'Mission3',2001);
SELECT COUNT(*) FROM Missions WHERE launch_year < 1999;
Add a new record of a humanitarian mission.
CREATE TABLE humanitarian_missions (id INT,mission VARCHAR(255),country VARCHAR(255),year INT);
INSERT INTO humanitarian_missions (id, mission, country, year) VALUES (1, 'Rebuilding Schools in Haiti', 'Haiti', 2022);
What's the total amount of donations received by each country?
CREATE TABLE donations (id INT,donor_name VARCHAR(50),donation_amount DECIMAL(10,2),donation_date DATE,country_code CHAR(2));
SELECT country_code, SUM(donation_amount) FROM donations GROUP BY country_code;
Calculate the average funding amount for startups in the "technology" sector
CREATE TABLE funding (startup_id INT,amount INT,sector VARCHAR(20));
SELECT AVG(funding.amount) FROM funding INNER JOIN startups ON funding.startup_id = startups.id WHERE startups.sector = 'technology';
What is the average number of streams per user for users in Texas who have streamed songs by artists from the Country genre?
CREATE TABLE Users (id INT,state VARCHAR(255),genre VARCHAR(255),streams INT);
SELECT AVG(streams) FROM Users WHERE state = 'Texas' AND genre = 'Country';
List of green investments by a specific Canadian fund
CREATE TABLE fund_green_investments(fund_id INT,investment_id INT);
SELECT investment_id FROM fund_green_investments WHERE fund_id = 2;
Update the country of the artist with ID 6 to Ghana.
CREATE TABLE Artists (ArtistID INT,ArtistName VARCHAR(100),Country VARCHAR(50)); INSERT INTO Artists (ArtistID,ArtistName,Country) VALUES (6,'Burna Boy','Nigeria');
UPDATE Artists SET Country = 'Ghana' WHERE ArtistID = 6;
List companies that have implemented Industry 4.0 practices
CREATE TABLE Companies (Company_ID INT,Company_Name VARCHAR(100),Industry_4_0 BOOLEAN);
SELECT DISTINCT Company_Name FROM Companies WHERE Industry_4_0 = TRUE;
What is the maximum temperature recorded by IoT sensors in Kenya in the last 14 days?
CREATE TABLE if NOT EXISTS iot_sensors_3 (id int,location varchar(50),temperature float,timestamp datetime); INSERT INTO iot_sensors_3 (id,location,temperature,timestamp) VALUES (1,'Kenya',31.6,'2022-03-22 10:00:00');
SELECT MAX(temperature) FROM iot_sensors_3 WHERE location = 'Kenya' AND timestamp >= DATE_SUB(NOW(), INTERVAL 14 DAY);
Identify the average age of patients who have been treated by therapists named "Sophia" or "Liam", and group the result by their gender.
CREATE TABLE patients (patient_id INT,therapist_id INT,age INT,gender TEXT); INSERT INTO patients (patient_id,therapist_id,age,gender) VALUES (1,1,30,'Female'),(2,1,40,'Male'),(3,2,50,'Female'),(4,2,60,'Non-binary'),(5,3,25,'Male'),(6,3,35,'Female'); CREATE TABLE therapists (therapist_id INT,first_name TEXT); INSERT IN...
SELECT therapists.first_name, patients.gender, AVG(patients.age) AS avg_age FROM patients JOIN therapists ON patients.therapist_id = therapists.therapist_id WHERE therapists.first_name IN ('Sophia', 'Liam') GROUP BY therapists.first_name, patients.gender;
List mining sites in Peru with EIA due dates in the next 3 months.
CREATE TABLE mining_sites (site_id INT,site_name VARCHAR(50),country VARCHAR(20)); INSERT INTO mining_sites (site_id,site_name,country) VALUES (1,'Mining Site A','Peru'),(2,'Mining Site B','Peru'),(3,'Mining Site C','Peru'); CREATE TABLE eia_schedule (site_id INT,eia_date DATE); INSERT INTO eia_schedule (site_id,eia_da...
SELECT site_name FROM mining_sites INNER JOIN eia_schedule ON mining_sites.site_id = eia_schedule.site_id WHERE eia_schedule.eia_date BETWEEN DATE_ADD(CURDATE(), INTERVAL 3 MONTH) AND DATE_ADD(CURDATE(), INTERVAL 4 MONTH);
What is the number of bookings per day for the 'bookings' table in the month of August 2022?
CREATE TABLE bookings (booking_id INT,booking_date DATE); INSERT INTO bookings (booking_id,booking_date) VALUES (1,'2022-08-01'),(2,'2022-08-02'),(3,'2022-08-03');
SELECT DATE(booking_date) AS booking_day, COUNT(*) AS bookings_per_day FROM bookings WHERE EXTRACT(MONTH FROM booking_date) = 8 GROUP BY booking_day;
List the top 3 contributing countries to climate change based on emissions data
CREATE TABLE emissions (id INT PRIMARY KEY,country VARCHAR(50),emissions INT); INSERT INTO emissions (id,country,emissions) VALUES (1,'China',10000),(2,'US',8000),(3,'India',6000);
SELECT country, emissions FROM emissions ORDER BY emissions DESC LIMIT 3
What is the average weight of all penguins in the 'penguins' table?
CREATE TABLE penguins (id INT,species VARCHAR(20),avg_weight FLOAT);
SELECT avg(avg_weight) FROM penguins;
Remove products sourced from a supplier with a low ethical rating
CREATE TABLE products (product_id INT,supplier_id INT,ethical_rating INT); CREATE TABLE suppliers (supplier_id INT,supplier_name VARCHAR(50),ethical_rating INT); INSERT INTO products (product_id,supplier_id,ethical_rating) VALUES (1,101,9),(2,102,5),(3,103,8); INSERT INTO suppliers (supplier_id,supplier_name,ethical_ra...
DELETE FROM products WHERE supplier_id IN (SELECT supplier_id FROM suppliers WHERE ethical_rating < 7);
List the top 2 genres with the highest average concert ticket prices.
CREATE TABLE artists (name VARCHAR(50),genre VARCHAR(50)); INSERT INTO artists (name,genre) VALUES ('Beyoncé','Pop'),('Drake','Hip Hop'),('Taylor Swift','Country Pop'),('Kendrick Lamar','Hip Hop'); CREATE TABLE concerts (artist_name VARCHAR(50),venue VARCHAR(50),ticket_price DECIMAL(5,2)); INSERT INTO concerts (artist_...
SELECT genre, AVG(ticket_price) AS avg_ticket_price, ROW_NUMBER() OVER(ORDER BY AVG(ticket_price) DESC) AS rank FROM artists JOIN concerts ON artists.name = concerts.artist_name GROUP BY genre ORDER BY rank ASC LIMIT 2;
What are the total sales and average play time for 'Action' games on Console by region?
CREATE TABLE Games (Id INT,Name VARCHAR(100),Genre VARCHAR(50),Platform VARCHAR(50),Sales INT,PlayTime FLOAT,Region VARCHAR(50)); INSERT INTO Games VALUES (1,'GameG','Action','Console',5000,20.5,'North America'),(2,'GameH','Role-playing','Console',7000,35.2,'Europe'),(3,'GameI','Action','Console',8000,18.4,'North Ameri...
SELECT Region, SUM(Sales) AS Total_Sales, AVG(PlayTime) AS Avg_PlayTime FROM Games WHERE Genre = 'Action' AND Platform = 'Console' GROUP BY Region;
List the names and number of public meetings for each district in the city of Mumbai for the year 2020
CREATE TABLE mumbai_districts (district_id INT,district_name VARCHAR(50),city VARCHAR(20),year INT,meetings_held INT); INSERT INTO mumbai_districts (district_id,district_name,city,year,meetings_held) VALUES (1,'Colaba','Mumbai',2020,10);
SELECT district_name, SUM(meetings_held) FROM mumbai_districts WHERE city = 'Mumbai' AND year = 2020 GROUP BY district_name;
What is the maximum carbon sequestration observed in a year in Greenland?
CREATE TABLE CarbonSequestration (ID INT,Location TEXT,Year INT,Sequestration INT); INSERT INTO CarbonSequestration (ID,Location,Year,Sequestration) VALUES (1,'Greenland',2010,1000); INSERT INTO CarbonSequestration (ID,Location,Year,Sequestration) VALUES (2,'Greenland',2011,1500);
SELECT MAX(Year) as Max_Year, MAX(Sequestration) as Max_Sequestration FROM CarbonSequestration WHERE Location = 'Greenland';
What is the minimum rainfall in the 'climate_data' table for each season?
CREATE TABLE climate_data (id INT,season VARCHAR(10),rainfall DECIMAL(3,1));
SELECT season, MIN(rainfall) FROM climate_data GROUP BY season;
Count the number of green building certifications for each year
CREATE TABLE green_building_certifications (id INT,certification_date DATE);
SELECT EXTRACT(YEAR FROM certification_date) AS year, COUNT(*) FROM green_building_certifications GROUP BY year;
What is the maximum amount of grant funding received by a single faculty member in the Physics department in a single year?
CREATE TABLE grants (id INT,faculty_id INT,year INT,amount DECIMAL(10,2)); INSERT INTO grants (id,faculty_id,year,amount) VALUES (1,1,2020,25000); INSERT INTO grants (id,faculty_id,year,amount) VALUES (2,2,2019,30000); CREATE TABLE faculty (id INT,name VARCHAR(50),department VARCHAR(50)); INSERT INTO faculty (id,name,d...
SELECT MAX(g.amount) FROM grants g JOIN faculty f ON g.faculty_id = f.id WHERE f.department = 'Physics';
What is the average rainfall for farms located in India?
CREATE TABLE rainfall_data (id INT,farm_id INT,rainfall FLOAT,record_date DATE); INSERT INTO rainfall_data (id,farm_id,rainfall,record_date) VALUES (1,1,25.5,'2022-01-01'),(2,2,30.0,'2022-01-01'),(3,3,18.2,'2022-01-01'),(4,4,22.8,'2022-01-01'),(5,5,35.1,'2022-01-01'),(6,6,20.5,'2022-01-01'),(7,7,40.0,'2022-01-01'),(8,8...
SELECT AVG(rainfall) FROM rainfall_data WHERE farm_id IN (SELECT id FROM farmers WHERE location = 'India');
What is the total number of satellites launched by country in descending order?
CREATE SCHEMA aerospace; CREATE TABLE aerospace.satellites (satellite_id INT,country VARCHAR(50),launch_date DATE); INSERT INTO aerospace.satellites VALUES (1,'USA','2000-01-01'); INSERT INTO aerospace.satellites VALUES (2,'Russia','2001-02-01'); INSERT INTO aerospace.satellites VALUES (3,'China','2002-03-01');
SELECT country, COUNT(satellite_id) OVER (ORDER BY COUNT(satellite_id) DESC) as total_launched FROM aerospace.satellites GROUP BY country;
Which element had the highest production increase from 2017 to 2018 in Asia?
CREATE TABLE production (year INT,region VARCHAR(10),element VARCHAR(10),quantity INT); INSERT INTO production (year,region,element,quantity) VALUES (2015,'Asia','Lanthanum',1200),(2016,'Asia','Lanthanum',1400),(2017,'Asia','Lanthanum',1500),(2018,'Asia','Lanthanum',1800),(2019,'Asia','Lanthanum',2000);
SELECT element, (MAX(quantity) - MIN(quantity)) AS production_increase FROM production WHERE region = 'Asia' AND year IN (2017, 2018) GROUP BY element ORDER BY production_increase DESC LIMIT 1;