instruction stringlengths 0 1.06k | input stringlengths 11 5.3k | response stringlengths 2 4.44k |
|---|---|---|
What are the top 3 broadband services with the highest revenue in the state of California, considering both subscription fees and one-time fees? | CREATE TABLE broadband_services (service_id INT,subscription_fee FLOAT,one_time_fee FLOAT,state VARCHAR(20)); | SELECT service_id, subscription_fee + one_time_fee as total_revenue FROM broadband_services WHERE state = 'California' GROUP BY service_id ORDER BY total_revenue DESC LIMIT 3; |
What are the unique AI trends mentioned in the tech_trends table for the hospitality industry? | CREATE TABLE tech_trends (tech_id INT,tech_name TEXT,industry TEXT,description TEXT); INSERT INTO tech_trends (tech_id,tech_name,industry,description) VALUES (1,'AI-powered chatbots','Hospitality','Automated customer service using AI technology'),(2,'AI-powered housekeeping robots','Hospitality','Automated housekeeping using AI technology'),(3,'Virtual Reality Tours','Real Estate','Virtual tours of properties using VR technology'); | SELECT DISTINCT tech_name FROM tech_trends WHERE industry = 'Hospitality'; |
What is the total amount of funding received by each organization for disaster response in Latin America, for the last 5 years, and the average response time? | CREATE TABLE disaster_response (response_id INT,ngo_id INT,disaster_id INT,funding DECIMAL(10,2),response_time INT); INSERT INTO disaster_response VALUES (1,1,1,50000,10); INSERT INTO disaster_response VALUES (2,1,2,75000,15); INSERT INTO disaster_response VALUES (3,2,3,100000,20); INSERT INTO disaster_response VALUES (4,2,4,80000,12); | SELECT ngo.name as organization, SUM(funding) as total_funding, AVG(response_time) as avg_response_time FROM disaster_response JOIN ngo ON disaster_response.ngo_id = ngo.ngo_id WHERE ngo.region = 'Latin America' AND disaster_response.response_time >= DATE_SUB(CURRENT_DATE, INTERVAL 5 YEAR) GROUP BY ngo.name; |
What is the monthly sales trend of cosmetic products in India, and which product categories have the highest and lowest sales? | CREATE TABLE sales (id INT,product_name VARCHAR(255),product_category VARCHAR(255),sale_date DATE,sales_amount DECIMAL(10,2),country VARCHAR(255)); | SELECT DATE_TRUNC('month', sale_date) as month, product_category, AVG(sales_amount) as avg_sales FROM sales WHERE country = 'India' GROUP BY month, product_category ORDER BY month, avg_sales DESC; |
What is the average quantity of rice produced annually per farmer in the 'agriculture' schema? | CREATE SCHEMA agriculture; CREATE TABLE rice_farmers (farmer_id INT,rice_quantity INT); INSERT INTO rice_farmers (farmer_id,rice_quantity) VALUES (1,800),(2,900),(3,700); | SELECT AVG(rice_quantity) FROM agriculture.rice_farmers; |
What is the total number of songs released per year? | CREATE TABLE Albums (album_id INT,release_year INT); INSERT INTO Albums (album_id,release_year) VALUES (1,2010),(2,2011),(3,2012); CREATE TABLE Songs (song_id INT,album_id INT); INSERT INTO Songs (song_id,album_id) VALUES (1,1),(2,1),(3,2),(4,3); | SELECT release_year, COUNT(s.song_id) AS total_songs FROM Albums a JOIN Songs s ON a.album_id = s.album_id GROUP BY release_year; |
What is the average consumer awareness score for the ethical fashion brand 'GreenFashions' in the 'Asia' region, and how does it compare to the global average? | CREATE TABLE consumer_awareness (id INT PRIMARY KEY,brand VARCHAR(255),region VARCHAR(255),score INT); INSERT INTO consumer_awareness (id,brand,region,score) VALUES (1,'GreenFashions','Asia',80),(2,'GreenFashions','Europe',85),(3,'EcoFriendlyFashions','Asia',75),(4,'EcoFriendlyFashions','USA',90); CREATE TABLE regions (id INT PRIMARY KEY,region VARCHAR(255)); INSERT INTO regions (id,region) VALUES (1,'Asia'),(2,'Europe'),(3,'USA'); | SELECT AVG(ca.score) as avg_score FROM consumer_awareness ca JOIN regions r ON ca.region = r.region WHERE ca.brand = 'GreenFashions' AND r.region = 'Asia'; SELECT AVG(score) as global_avg_score FROM consumer_awareness WHERE brand = 'GreenFashions'; |
What is the number of autonomous vehicle accidents per month? | CREATE TABLE autonomous_accidents (accident_date DATE,is_autonomous BOOLEAN); | SELECT DATE_TRUNC('month', accident_date) as month, COUNT(*) as num_accidents FROM autonomous_accidents WHERE is_autonomous = true GROUP BY month; |
List the agricultural innovation metrics in the Himalayan region by year. | CREATE TABLE Metrics (metric TEXT,year INTEGER,region TEXT); INSERT INTO Metrics (metric,year,region) VALUES ('Crop Yield',2018,'Himalayan'),('Soil Fertility',2019,'Himalayan'),('Irrigation Efficiency',2020,'Himalayan'); | SELECT year, metric FROM Metrics WHERE region = 'Himalayan'; |
What is the ratio of electric to conventional vehicles for each transportation mode? | CREATE TABLE transportation_modes (id INT,name VARCHAR(20)); CREATE TABLE electric_vehicles (id INT,mode_id INT,vehicle_count INT); CREATE TABLE conventional_vehicles (id INT,mode_id INT,vehicle_count INT); INSERT INTO transportation_modes (id,name) VALUES (1,'Car'),(2,'Truck'),(3,'Bus'); INSERT INTO electric_vehicles (id,mode_id,vehicle_count) VALUES (1,1,1000),(2,2,500),(3,3,200); INSERT INTO conventional_vehicles (id,mode_id,vehicle_count) VALUES (4,1,3000),(5,2,2000),(6,3,1000); | SELECT tm.name, (SUM(ev.vehicle_count) / SUM(cv.vehicle_count)) AS ratio FROM transportation_modes tm JOIN electric_vehicles ev ON tm.id = ev.mode_id JOIN conventional_vehicles cv ON tm.id = cv.mode_id GROUP BY tm.name; |
Create a view named 'top_athlete_sports' that displays the top 2 sports with the highest average age of athletes in the 'athlete_wellbeing' table | CREATE TABLE athlete_wellbeing (athlete_id INT,name VARCHAR(50),age INT,sport VARCHAR(50)); INSERT INTO athlete_wellbeing (athlete_id,name,age,sport) VALUES (1,'John Doe',25,'Basketball'); INSERT INTO athlete_wellbeing (athlete_id,name,age,sport) VALUES (2,'Jane Smith',28,'Basketball'); INSERT INTO athlete_wellbeing (athlete_id,name,age,sport) VALUES (3,'Jim Brown',30,'Football'); INSERT INTO athlete_wellbeing (athlete_id,name,age,sport) VALUES (4,'Lucy Davis',22,'Football'); INSERT INTO athlete_wellbeing (athlete_id,name,age,sport) VALUES (5,'Mark Johnson',20,'Hockey'); INSERT INTO athlete_wellbeing (athlete_id,name,age,sport) VALUES (6,'Sara Lee',35,'Tennis'); INSERT INTO athlete_wellbeing (athlete_id,name,age,sport) VALUES (7,'Mike Johnson',28,'Tennis'); | CREATE VIEW top_athlete_sports AS SELECT sport, AVG(age) as avg_age FROM athlete_wellbeing GROUP BY sport ORDER BY avg_age DESC LIMIT 2; |
What is the total number of green buildings and their total floor area for each city? | CREATE TABLE Cities (CityID int,CityName varchar(50)); CREATE TABLE GreenBuildings (BuildingID int,CityID int,FloorArea int,GreenBuilding int); | SELECT Cities.CityName, GreenBuildings.GreenBuilding, COUNT(GreenBuildings.BuildingID) as TotalBuildings, SUM(GreenBuildings.FloorArea) as TotalFloorArea FROM Cities INNER JOIN GreenBuildings ON Cities.CityID = GreenBuildings.CityID GROUP BY Cities.CityName, GreenBuildings.GreenBuilding; |
What are the top 5 cruelty-free cosmetic products by sales in the Canadian region for 2021? | CREATE TABLE products (product_id INT,product_name VARCHAR(100),is_cruelty_free BOOLEAN,region VARCHAR(50),sales INT); INSERT INTO products (product_id,product_name,is_cruelty_free,region,sales) VALUES (1,'Lipstick',true,'Canada',500),(2,'Mascara',false,'Canada',700),(3,'Foundation',true,'Canada',800),(4,'Eyeshadow',true,'USA',600),(5,'Blush',false,'Canada',400); | SELECT product_name, sales FROM products WHERE is_cruelty_free = true AND region = 'Canada' ORDER BY sales DESC LIMIT 5; |
What is the average property price for green-certified buildings in the CityOfSustainability schema? | CREATE TABLE CityOfSustainability.GreenBuildings (id INT,price FLOAT); INSERT INTO CityOfSustainability.GreenBuildings (id,price) VALUES (1,500000.0),(2,700000.0); | SELECT AVG(price) FROM CityOfSustainability.GreenBuildings; |
List the co-owners and their respective properties in co_ownership table. | CREATE TABLE co_ownership (owner_id INT,property_id INT,name VARCHAR(255)); INSERT INTO co_ownership (owner_id,property_id,name) VALUES (1,3,'Alice Johnson'),(2,3,'Bob Smith'),(3,4,'Eva Brown'); | SELECT owner_id, name, property_id FROM co_ownership; |
How many space missions were led by astronauts from India? | CREATE TABLE space_missions(id INT,mission_name VARCHAR(50),leader_name VARCHAR(50),leader_country VARCHAR(50)); INSERT INTO space_missions VALUES(1,'Mangalyaan','Kalpana Chawla','India'),(2,'Aryabhata','Rakesh Sharma','India'); | SELECT COUNT(*) FROM space_missions WHERE leader_country = 'India'; |
What is the total revenue for online travel agencies in Asia? | CREATE TABLE bookings (id INT,ota_id INT,date DATE,price FLOAT); CREATE TABLE otas (id INT,name TEXT,location TEXT); INSERT INTO bookings (id,ota_id,date,price) VALUES (1,1,'2022-01-01',200),(2,2,'2022-01-02',300),(3,1,'2022-02-01',400),(4,3,'2022-02-02',100),(5,2,'2022-03-01',500); INSERT INTO otas (id,name,location) VALUES (1,'Expedia','USA'),(2,'Booking.com','Netherlands'),(3,'Agoda','Singapore'); | SELECT SUM(price) FROM bookings INNER JOIN otas ON bookings.ota_id = otas.id WHERE otas.location = 'Asia'; |
What is the maximum depth and corresponding marine protected area name in the Atlantic region? | CREATE TABLE marine_protected_areas (id INT,name VARCHAR(255),depth FLOAT,region VARCHAR(255)); INSERT INTO marine_protected_areas (id,name,depth,region) VALUES (1,'Bermuda Park',3000,'Atlantic'); INSERT INTO marine_protected_areas (id,name,depth,region) VALUES (2,'Azores Marine Park',4000,'Atlantic'); | SELECT name, depth FROM marine_protected_areas WHERE region = 'Atlantic' ORDER BY depth DESC LIMIT 1; |
List the total number of properties and total area in square meters for each city in the 'inclusive_cities' table. | CREATE TABLE inclusive_cities (id INT,name VARCHAR(255),num_properties INT,total_area INT); INSERT INTO inclusive_cities (id,name,num_properties,total_area) VALUES (1,'New York',5000,600000),(2,'Los Angeles',3000,450000),(3,'Chicago',2500,325000); | SELECT name, SUM(num_properties), SUM(total_area) FROM inclusive_cities GROUP BY name; |
INSERT INTO EndangeredLanguages (Language, NativeSpeakers, Name) VALUES ('Livonian', 2, 'Livonian Language'); | INSERT INTO EndangeredLanguages (Language,NativeSpeakers,Name) VALUES ('Livonian',2,'Livonian Language'),('Ona',1,'Ona Language'),('Lemerig',0,'Lemerig Language'),('Tsakhur',5000,'Tsakhur Language'),('Ubykh',1,'Ubykh Language'); | FROM EndangeredLanguages ORDER BY NativeSpeakers ASC; |
Find the number of bike trips per hour for the month of January 2022 | CREATE TABLE bike_trips (id INT PRIMARY KEY,trip_time TIMESTAMP,trip_duration INT); | SELECT HOUR(trip_time) AS hour, COUNT(*) AS num_trips FROM bike_trips WHERE trip_time >= '2022-01-01 00:00:00' AND trip_time < '2022-02-01 00:00:00' GROUP BY hour; |
What is the percentage of electric vehicles sold in '2020' and '2021' in the 'sales' table? | CREATE TABLE sales (year INT,vehicle_type VARCHAR(10),vehicle_count INT); INSERT INTO sales VALUES (2018,'electric',1000),(2019,'electric',2000),(2020,'electric',3000),(2020,'gasoline',4000),(2021,'electric',4000); | SELECT (COUNT(*) * 100.0 / (SELECT SUM(vehicle_count) FROM sales WHERE year IN (2020, 2021))) AS percentage FROM sales WHERE vehicle_type = 'electric' AND year IN (2020, 2021); |
What is the maximum number of volunteer hours spent in a single day in the Chicago region? | CREATE TABLE VolunteerHours (HourID INT,VolunteerName TEXT,Region TEXT,HoursSpent DECIMAL,HourDate DATE); INSERT INTO VolunteerHours (HourID,VolunteerName,Region,HoursSpent,HourDate) VALUES (1,'Isabella Nguyen','Chicago',8.00,'2022-01-01'),(2,'Ava Johnson','Chicago',10.00,'2022-02-01'); | SELECT MAX(HoursSpent) FROM VolunteerHours WHERE Region = 'Chicago' GROUP BY HourDate; |
What is the average health equity score for mental health facilities in urban areas? | CREATE TABLE mental_health_facilities (facility_id INT,location VARCHAR(255),health_equity_score INT); INSERT INTO mental_health_facilities (facility_id,location,health_equity_score) VALUES (1,'Urban',85),(2,'Rural',75),(3,'Urban',90),(4,'Urban',80),(5,'Rural',70),(6,'Urban',95); | SELECT AVG(health_equity_score) as avg_score FROM mental_health_facilities WHERE location = 'Urban'; |
Rank fishing vessels that caught the most fish in the Indian Ocean in descending order. | CREATE TABLE fishing_vessels (id INT,vessel_name VARCHAR(50),caught_fish INT,ocean VARCHAR(50)); INSERT INTO fishing_vessels (id,vessel_name,caught_fish,ocean) VALUES (1,'Vessel A',5000,'Indian Ocean'),(2,'Vessel B',7000,'Indian Ocean'),(3,'Vessel C',3000,'Atlantic Ocean'); | SELECT vessel_name, caught_fish, ROW_NUMBER() OVER (ORDER BY caught_fish DESC) as rank FROM fishing_vessels WHERE ocean = 'Indian Ocean'; |
What is the total number of employees working on ethical AI initiatives in the company? | CREATE TABLE ethical_ai_employees (id INT,employee_name VARCHAR(50),ethical_ai BOOLEAN);INSERT INTO ethical_ai_employees (id,employee_name,ethical_ai) VALUES (1,'Jane Doe',true),(2,'John Smith',false),(3,'Alice Johnson',true); | SELECT COUNT(*) as total_employees FROM ethical_ai_employees WHERE ethical_ai = true; |
What is the maximum budget allocated for transportation in the year 2019 in the state of "California"? | CREATE TABLE budget_allocation (year INT,state TEXT,category TEXT,amount FLOAT); INSERT INTO budget_allocation (year,state,category,amount) VALUES (2020,'California','Transportation',12000000),(2019,'California','Transportation',10000000),(2018,'California','Transportation',8000000); | SELECT MAX(amount) FROM budget_allocation WHERE year = 2019 AND state = 'California' AND category = 'Transportation'; |
What is the least preferred eyeshadow shade among consumers? | CREATE TABLE consumer_preferences (preference_id INT,consumer_id INT,product_id INT,shade VARCHAR(255)); INSERT INTO consumer_preferences (preference_id,consumer_id,product_id,shade) VALUES (1,1,1,'Light Beige'),(2,2,1,'Medium Beige'),(3,3,2,'Dark Beige'),(4,4,3,'Light Brown'),(5,5,3,'Medium Brown'); | SELECT shade, COUNT(*) AS preference_count FROM consumer_preferences WHERE product_id = 1 GROUP BY shade ORDER BY preference_count ASC LIMIT 1; |
What is the total production of well 'W001' in the Oil_Production table? | CREATE TABLE Oil_Production (well text,production_date date,quantity real); INSERT INTO Oil_Production (well,production_date,quantity) VALUES ('W001','2021-01-01',150.5),('W001','2021-01-02',160.3); | SELECT SUM(quantity) FROM Oil_Production WHERE well = 'W001'; |
What is the total spending on rural infrastructure projects in each continent? | CREATE TABLE project (project_id INT,name VARCHAR(50),location VARCHAR(50),spending FLOAT); CREATE TABLE continent (continent_id INT,name VARCHAR(50),description TEXT); CREATE TABLE location (location_id INT,name VARCHAR(50),continent_id INT); | SELECT c.name, SUM(p.spending) FROM project p JOIN location l ON p.location = l.name JOIN continent c ON l.continent_id = c.continent_id GROUP BY c.name; |
How many users have posted more than 10 times in the last week from Germany? | CREATE TABLE users (id INT,name VARCHAR(50),country VARCHAR(50)); INSERT INTO users (id,name,country) VALUES (1,'John Doe','USA'),(2,'Jane Smith','Germany'); CREATE TABLE posts (id INT,user_id INT,timestamp DATETIME); INSERT INTO posts (id,user_id,timestamp) VALUES (1,1,'2022-01-01 12:00:00'),(2,1,'2022-01-02 14:00:00'),(3,2,'2022-01-03 10:00:00'),(4,2,'2022-01-04 16:00:00'),(5,2,'2022-01-05 18:00:00'); | SELECT COUNT(DISTINCT users.id) FROM users INNER JOIN posts ON users.id = posts.user_id WHERE users.country = 'Germany' AND posts.timestamp >= DATE_SUB(NOW(), INTERVAL 1 WEEK) GROUP BY users.id HAVING COUNT(posts.id) > 10; |
What is the total number of subscribers? | CREATE TABLE subscriber_count (id INT,subscriber_type VARCHAR(20),name VARCHAR(50)); INSERT INTO subscriber_count (id,subscriber_type,name) VALUES (1,'Broadband','Jim Brown'); | SELECT COUNT(*) FROM subscriber_count; |
Update the number of units in the Downtown area of the InclusiveHousing table. | CREATE TABLE InclusiveHousing (area TEXT,num_units INT,wheelchair_accessible BOOLEAN,pets_allowed BOOLEAN); INSERT INTO InclusiveHousing (area,num_units,wheelchair_accessible,pets_allowed) VALUES ('Eastside',10,TRUE,FALSE),('Westside',15,TRUE,TRUE),('Downtown',20,TRUE,TRUE); | UPDATE InclusiveHousing SET num_units = 25 WHERE area = 'Downtown'; |
List all companies and their circular economy initiatives in the 'Africa' region. | CREATE TABLE Companies (id INT,name VARCHAR(255),region VARCHAR(255)); INSERT INTO Companies (id,name,region) VALUES (1,'CompanyA','Africa'),(2,'CompanyB','Europe'),(3,'CompanyC','Asia-Pacific'); CREATE TABLE CircularEconomy (id INT,company_id INT,initiative VARCHAR(255)); INSERT INTO CircularEconomy (id,company_id,initiative) VALUES (1,1,'Recycling program'),(2,1,'Product repair services'),(3,2,'Recyclable packaging'),(4,3,'Product remanufacturing'); | SELECT Companies.name, GROUP_CONCAT(CircularEconomy.initiative) FROM Companies JOIN CircularEconomy ON Companies.id = CircularEconomy.company_id WHERE Companies.region = 'Africa' GROUP BY Companies.name; |
Identify research projects and their respective leaders, if any, working on climate change mitigation strategies. | CREATE TABLE research_projects (id INT PRIMARY KEY,name VARCHAR(50),topic VARCHAR(50)); CREATE TABLE researchers (id INT PRIMARY KEY,name VARCHAR(50),project_id INT,FOREIGN KEY (project_id) REFERENCES research_projects(id)); CREATE TABLE leader_roles (id INT PRIMARY KEY,researcher_id INT,project_id INT,FOREIGN KEY (researcher_id) REFERENCES researchers(id),FOREIGN KEY (project_id) REFERENCES research_projects(id)); | SELECT research_projects.name, researchers.name FROM research_projects LEFT JOIN leaders_roles ON research_projects.id = leaders_roles.project_id LEFT JOIN researchers ON leaders_roles.researcher_id = researchers.id WHERE research_projects.topic LIKE '%climate change mitigation%'; |
What is the total number of military equipment donated by the USA and China to African countries since 2010, ordered by the most recent donors? | CREATE TABLE MilitaryDonations (donor VARCHAR(255),recipient VARCHAR(255),equipment VARCHAR(255),donation_date DATE); INSERT INTO MilitaryDonations (donor,recipient,equipment,donation_date) VALUES ('USA','Kenya','tanks','2011-04-02'); INSERT INTO MilitaryDonations (donor,recipient,equipment,donation_date) VALUES ('China','Nigeria','radars','2015-08-17'); | SELECT SUM(equipment_count) as total_donations FROM (SELECT CASE WHEN donor IN ('USA', 'China') THEN donor END AS donor, COUNT(equipment) as equipment_count FROM MilitaryDonations WHERE recipient LIKE 'Africa%' AND donation_date >= '2010-01-01' GROUP BY donor, YEAR(donation_date), MONTH(donation_date), DAY(donation_date) ORDER BY MAX(donation_date)) as subquery; |
Update the price of the virtual tour of the Louvre Museum to 15 euros. | CREATE TABLE virtual_tours (tour_id INT,tour_name TEXT,price FLOAT); INSERT INTO virtual_tours (tour_id,tour_name,price) VALUES (1,'Louvre Museum Tour',12.50),(2,'Eiffel Tower Tour',10.00); | UPDATE virtual_tours SET price = 15.00 WHERE tour_name = 'Louvre Museum Tour'; |
What was the total amount donated by users from the USA in Q1 2021? | CREATE TABLE Donations (id INT,user_id INT,country VARCHAR(50),amount DECIMAL(10,2),donation_date DATE); INSERT INTO Donations (id,user_id,country,amount,donation_date) VALUES (1,1001,'USA',50.00,'2021-01-05'); INSERT INTO Donations (id,user_id,country,amount,donation_date) VALUES (2,1002,'Canada',75.00,'2021-01-10'); | SELECT SUM(amount) FROM Donations WHERE country = 'USA' AND donation_date >= '2021-01-01' AND donation_date < '2021-04-01'; |
What is the average age of farmers in the view 'young_farmers'? | CREATE TABLE farmers (farmer_id INT PRIMARY KEY,name VARCHAR(255),age INT,location VARCHAR(255)); INSERT INTO farmers (farmer_id,name,age,location) VALUES (1,'John Doe',35,'Springfield'); CREATE VIEW young_farmers AS SELECT * FROM farmers WHERE age < 30; | SELECT AVG(age) FROM young_farmers; |
Insert a new record in the food_safety_inspections table with a restaurant_id of 100, an inspection_date of '2023-01-19', and a violation_count of 2 | CREATE TABLE food_safety_inspections (restaurant_id INT,inspection_date DATE,violation_count INT); | INSERT INTO food_safety_inspections (restaurant_id, inspection_date, violation_count) VALUES (100, '2023-01-19', 2); |
What is the minimum number of visitors for an exhibition in India? | CREATE TABLE ExhibitionAttendance (exhibition_id INT,country VARCHAR(20),visitor_count INT); INSERT INTO ExhibitionAttendance (exhibition_id,country,visitor_count) VALUES (1,'India',50),(2,'India',75),(3,'India',100),(4,'Brazil',120); | SELECT MIN(visitor_count) FROM ExhibitionAttendance WHERE country = 'India'; |
What is the earliest route departure date for warehouse 'ASIA-SIN'? | CREATE TABLE routes (id INT,warehouse_id VARCHAR(5),departure_date DATE); INSERT INTO routes VALUES (1,'ASIA','2021-10-01'),(2,'ASIA-SIN','2021-10-05'),(3,'ASIA','2021-10-10'); | SELECT MIN(departure_date) FROM routes WHERE warehouse_id = (SELECT id FROM warehouses WHERE name = 'ASIA-SIN'); |
What is the average age of members who have a gold membership and have used the cycling class more than 5 times in the last month? | CREATE TABLE Members (MemberID int,Age int,MembershipType varchar(10)); INSERT INTO Members (MemberID,Age,MembershipType) VALUES (1,35,'Gold'); CREATE TABLE Classes (ClassID int,ClassType varchar(10),MemberID int); INSERT INTO Classes (ClassID,ClassType,MemberID) VALUES (1,'Cycling',1); | SELECT AVG(Age) FROM Members m JOIN Classes c ON m.MemberID = c.MemberID WHERE m.MembershipType = 'Gold' AND c.ClassType = 'Cycling' GROUP BY m.MemberID HAVING COUNT(c.ClassID) > 5; |
List the names of all students who have attended a lifelong learning event and the name of the event they attended. | CREATE TABLE student_attendance (student_id INT,event_id INT,attended BOOLEAN); INSERT INTO student_attendance (student_id,event_id,attended) VALUES (1,1,true); CREATE TABLE students (id INT,name VARCHAR(255)); INSERT INTO students (id,name) VALUES (1,'Jane Doe'); CREATE TABLE lifelong_learning_events (id INT,name VARCHAR(255)); INSERT INTO lifelong_learning_events (id,name) VALUES (1,'Python Programming Workshop'); | SELECT students.name, lifelong_learning_events.name FROM student_attendance INNER JOIN students ON student_attendance.student_id = students.id INNER JOIN lifelong_learning_events ON student_attendance.event_id = lifelong_learning_events.id WHERE attended = true; |
What is the total quantity of items with type 'K' or type 'L' in warehouse W and warehouse X? | CREATE TABLE warehouse_w(item_id INT,item_type VARCHAR(10),quantity INT);CREATE TABLE warehouse_x(item_id INT,item_type VARCHAR(10),quantity INT);INSERT INTO warehouse_w(item_id,item_type,quantity) VALUES (1,'K',200),(2,'L',300),(3,'K',50),(4,'L',400);INSERT INTO warehouse_x(item_id,item_type,quantity) VALUES (1,'K',150),(2,'L',250),(3,'K',40),(4,'L',350); | SELECT quantity FROM warehouse_w WHERE item_type IN ('K', 'L') UNION ALL SELECT quantity FROM warehouse_x WHERE item_type IN ('K', 'L'); |
What is the difference in waste generation between the residential and commercial sectors in Sydney since 2020? | CREATE TABLE waste_generation (id INT,sector VARCHAR(20),location VARCHAR(20),amount DECIMAL(10,2),date DATE); | SELECT residential.location, residential.amount - commercial.amount FROM waste_generation AS residential INNER JOIN waste_generation AS commercial ON residential.location = commercial.location AND residential.date = commercial.date WHERE residential.sector = 'residential' AND commercial.sector = 'commercial' AND residential.date >= '2020-01-01'; |
Find the number of streams and revenue for songs by artist 'Taylor Swift' in the United States, grouped by month. | CREATE TABLE Streams (song_id INT,artist VARCHAR(50),country VARCHAR(50),date DATE,streams INT,revenue FLOAT); | SELECT DATE_FORMAT(date, '%Y-%m') AS month, SUM(streams), SUM(revenue) FROM Streams WHERE artist = 'Taylor Swift' AND country = 'United States' GROUP BY month; |
What is the minimum age of policyholders who have a life insurance policy? | CREATE TABLE LifePolicies (PolicyholderID int); CREATE TABLE Policyholders (PolicyholderID int,Age int); INSERT INTO LifePolicies (PolicyholderID) VALUES (1); INSERT INTO LifePolicies (PolicyholderID) VALUES (2); INSERT INTO Policyholders (PolicyholderID,Age) VALUES (1,40); INSERT INTO Policyholders (PolicyholderID,Age) VALUES (2,50); | SELECT MIN(Age) FROM Policyholders INNER JOIN LifePolicies ON Policyholders.PolicyholderID = LifePolicies.PolicyholderID; |
Update the rating of all lipsticks with the name 'Ruby Red' to 4.8. | CREATE TABLE products (product_id INT,name VARCHAR(255),category VARCHAR(255),rating FLOAT); | UPDATE products SET rating = 4.8 WHERE name = 'Ruby Red' AND category = 'lipstick'; |
Insert a new spacecraft 'Comet Cruiser' with a mass of 3000 kg manufactured by 'AstroTech'. | CREATE TABLE Spacecrafts (Spacecraft_ID INT,Name VARCHAR(255),Manufacturer VARCHAR(255),Mass FLOAT); | INSERT INTO Spacecrafts (Name, Manufacturer, Mass) VALUES ('Comet Cruiser', 'AstroTech', 3000); |
Show the number of art pieces from each country and total museum attendance from the 'ArtCollection' and 'MuseumAttendance' tables, grouped by year. | CREATE TABLE ArtCollection (id INT,name VARCHAR(50),country VARCHAR(50),year INT); CREATE TABLE MuseumAttendance (id INT,year INT,attendance INT); | SELECT year, country, COUNT(name) as art_pieces, SUM(attendance) as total_attendance FROM ArtCollection JOIN MuseumAttendance ON ArtCollection.year = MuseumAttendance.year GROUP BY year, country; |
What are the names of the artists who have performed in both New York and Los Angeles and the total number of concerts they have held in these two cities? | CREATE TABLE Artists (artist_name TEXT,location TEXT,num_concerts INTEGER); INSERT INTO Artists (artist_name,location,num_concerts) VALUES ('Artist A','New York',300),('Artist B','New York',400),('Artist A','Los Angeles',500); | SELECT artist_name, SUM(num_concerts) as total_concerts FROM Artists WHERE location IN ('New York', 'Los Angeles') GROUP BY artist_name HAVING COUNT(DISTINCT location) = 2; |
What is the total revenue generated from ads promoting plant-based diets, shown to users in Canada on mobile devices, in the last week? | CREATE TABLE ads (ad_id INT,user_id INT,device_type TEXT,content TEXT,revenue DECIMAL(10,2),show_date DATE); | SELECT SUM(revenue) FROM ads WHERE content LIKE '%plant-based diet%' AND country = 'Canada' AND device_type = 'mobile' AND show_date >= DATEADD(day, -7, GETDATE()); |
Insert a new record into the humanitarian_operations table for an operation named 'Medical Assistance in Africa' that started on '2022-06-01' | CREATE TABLE humanitarian_operations (operation_id INT,name VARCHAR(50),location VARCHAR(50),start_date DATE,end_date DATE); | INSERT INTO humanitarian_operations (name, location, start_date, end_date) VALUES ('Medical Assistance in Africa', 'Africa', '2022-06-01', NULL); |
Find the number of farms in each country and the average yield for each country. | CREATE TABLE Farm (FarmID int,FarmType varchar(20),Country varchar(50),Yield int); INSERT INTO Farm (FarmID,FarmType,Country,Yield) VALUES (1,'Organic','USA',150),(2,'Conventional','Canada',200),(3,'Urban','Mexico',100),(4,'Organic','USA',180),(5,'Organic','Mexico',120); | SELECT Country, COUNT(*) as NumFarms, AVG(Yield) as AvgYield FROM Farm GROUP BY Country; |
How many unique species are registered in the 'biodiversity' table, and what are their names? | CREATE TABLE biodiversity (species_id INT,species_name TEXT,other_data TEXT); | SELECT COUNT(DISTINCT species_name) as unique_species_count, species_name FROM biodiversity GROUP BY species_name; |
What was the total weight of artifacts excavated per analyst each year? | CREATE TABLE analysts (analyst_id INT,name VARCHAR(50),start_date DATE); INSERT INTO analysts (analyst_id,name,start_date) VALUES (1,'John Doe','2020-01-01'); CREATE TABLE artifact_analysis (analysis_id INT,artifact_id INT,analyst_id INT,analysis_date DATE,weight DECIMAL(5,2)); | SELECT a.name, EXTRACT(YEAR FROM aa.analysis_date) as analysis_year, SUM(aa.weight) as total_weight FROM analysts a JOIN artifact_analysis aa ON a.analyst_id = aa.analyst_id GROUP BY a.analyst_id, a.name, analysis_year ORDER BY analysis_year, total_weight DESC; |
Identify the common crops grown in Mexico and Canada. | CREATE TABLE crops (country VARCHAR(20),crop VARCHAR(20)); INSERT INTO crops VALUES ('Mexico','Corn'),('Mexico','Beans'),('Canada','Wheat'),('Canada','Canola'); | SELECT crop FROM crops WHERE country = 'Mexico' INTERSECT SELECT crop FROM crops WHERE country = 'Canada' |
What is the total investment amount in social impact projects for each quarter since Q1 2020? | CREATE TABLE projects (id INT,name VARCHAR(255),investment_amount DECIMAL(10,2),sector VARCHAR(255),country VARCHAR(255),project_start_date DATE); CREATE VIEW social_impact_projects AS SELECT * FROM projects WHERE sector IN ('Renewable Energy','Affordable Housing','Education','Healthcare'); | SELECT QUARTER(project_start_date) AS quarter, SUM(investment_amount) FROM social_impact_projects GROUP BY quarter; |
What is the total number of intelligence operations and their types for each country? | CREATE TABLE IntelligenceOperations (OperationID INT,OperationType VARCHAR(20),OperationCountry VARCHAR(30)); INSERT INTO IntelligenceOperations (OperationID,OperationType,OperationCountry) VALUES (1,'Surveillance','USA'),(2,'Infiltration','Russia'),(3,'Surveillance','China'); | SELECT OperationCountry, OperationType, COUNT(*) as Total FROM IntelligenceOperations GROUP BY OperationCountry, OperationType; |
What is the average energy efficiency score for residential buildings in the state of California, considering only buildings with a score above 80? | CREATE TABLE ResidentialBuildings (id INT,state VARCHAR(20),energy_efficiency_score INT); INSERT INTO ResidentialBuildings (id,state,energy_efficiency_score) VALUES (1,'California',75),(2,'California',85),(3,'California',90); | SELECT AVG(energy_efficiency_score) FROM ResidentialBuildings WHERE state = 'California' AND energy_efficiency_score > 80; |
What is the total number of plays for a specific song in the 'music_streaming' table? | CREATE TABLE music_streaming (song_id INT,song_name TEXT,artist_name TEXT,plays INT); | SELECT SUM(plays) FROM music_streaming WHERE song_name = 'Work'; |
What is the total number of charging stations for electric vehicles in California and New York? | CREATE TABLE charging_stations (station_id INT,station_name VARCHAR(50),location VARCHAR(50),quantity INT); CREATE TABLE electric_vehicles (vehicle_id INT,model VARCHAR(20),manufacture VARCHAR(20),vehicle_type VARCHAR(20),state VARCHAR(20)); | SELECT SUM(quantity) FROM charging_stations cs JOIN electric_vehicles ev ON cs.location = ev.state WHERE ev.state IN ('California', 'New York'); |
Identify the number of sculptures created by female artists from Japan and their average size. | CREATE TABLE Artists (ArtistID INT,ArtistName VARCHAR(50),Gender VARCHAR(10),Nationality VARCHAR(20),BirthYear INT); INSERT INTO Artists (ArtistID,ArtistName,Gender,Nationality,BirthYear) VALUES (1,'Kusama Yayoi','Female','Japanese',1929); CREATE TABLE Artworks (ArtworkID INT,ArtistID INT,ArtworkName VARCHAR(50),ArtworkType VARCHAR(20),Size FLOAT); INSERT INTO Artworks (ArtworkID,ArtistID,ArtworkName,ArtworkType,Size) VALUES (1,1,'Pumpkin','Sculpture',250.0); | SELECT COUNT(Artworks.ArtworkID), AVG(Artworks.Size) FROM Artists INNER JOIN Artworks ON Artists.ArtistID = Artworks.ArtistID WHERE Artists.Gender = 'Female' AND Artists.Nationality = 'Japanese' AND Artworks.ArtworkType = 'Sculpture'; |
What is the average number of veterans employed by each employer, and what is the total number of veterans employed by all employers? | CREATE TABLE veteran_employment (employer_id INT,employer_name VARCHAR(255),num_veterans INT,city VARCHAR(255),state VARCHAR(255)); | SELECT AVG(num_veterans) AS avg_veterans_per_employer, SUM(num_veterans) AS total_veterans FROM veteran_employment; |
What is the total budget allocated to healthcare programs in New York state in 2022? | CREATE TABLE HealthcareBudget (state VARCHAR(20),year INT,program VARCHAR(30),budget INT); INSERT INTO HealthcareBudget (state,year,program,budget) VALUES ('New York',2022,'Primary Care',1000000),('New York',2022,'Mental Health',2000000),('New York',2022,'Preventive Care',1500000); | SELECT SUM(budget) FROM HealthcareBudget WHERE state = 'New York' AND year = 2022 AND program LIKE 'Healthcare%'; |
Which aircraft has the most accidents in a specific region? | CREATE TABLE aircrafts (aircraft_id INT,model VARCHAR(50),region VARCHAR(50)); INSERT INTO aircrafts (aircraft_id,model,region) VALUES (1,'Boeing 747','North America'),(2,'Airbus A320','Europe'),(3,'Boeing 737','Asia'); CREATE TABLE accidents (accident_id INT,aircraft_id INT,date DATE); INSERT INTO accidents (accident_id,aircraft_id) VALUES (1,1),(2,1),(3,3),(4,2),(5,2); | SELECT a.model, COUNT(*) as num_accidents FROM aircrafts a JOIN accidents b ON a.aircraft_id = b.aircraft_id WHERE a.region = 'North America' GROUP BY a.model ORDER BY num_accidents DESC LIMIT 1; |
Delete records of emergency calls with a response time greater than 60 minutes | CREATE TABLE emergency_calls (call_id INT,did INT,response_time INT); INSERT INTO emergency_calls (call_id,did,response_time) VALUES (1,1,45),(2,2,62),(3,3,55); | DELETE FROM emergency_calls WHERE response_time > 60; |
Create a view that displays fish production by species and location | CREATE TABLE fish_species (species_id INT PRIMARY KEY,species_name VARCHAR(255),scientific_name VARCHAR(255),conservation_status VARCHAR(50)); CREATE TABLE farm_locations (location_id INT PRIMARY KEY,location_name VARCHAR(255),country VARCHAR(255),ocean VARCHAR(255)); CREATE TABLE fish_production (production_id INT PRIMARY KEY,species_id INT,location_id INT,year INT,quantity INT,FOREIGN KEY (species_id) REFERENCES fish_species(species_id),FOREIGN KEY (location_id) REFERENCES farm_locations(location_id)); | CREATE VIEW fish_production_by_species_location AS SELECT fp.species_id, fs.species_name, fl.location_id, fl.location_name, fp.year, fp.quantity FROM fish_production fp JOIN fish_species fs ON fp.species_id = fs.species_id JOIN farm_locations fl ON fp.location_id = fl.location_id; |
How many podcasts in Oceania have a focus on media literacy and are hosted by women? | CREATE TABLE podcasts (id INT,name TEXT,focus TEXT,location TEXT,host TEXT); INSERT INTO podcasts (id,name,focus,location,host) VALUES (1,'Podcast1','Media Literacy','Oceania','Host1'); INSERT INTO podcasts (id,title,focus,location,host) VALUES (2,'Podcast2','Politics','Europe','Host2'); | SELECT COUNT(*) FROM podcasts WHERE focus = 'Media Literacy' AND location = 'Oceania' AND host IN (SELECT host FROM hosts WHERE gender = 'Female'); |
What is the average depth of the 'Indian Ocean' in the ocean_floor_mapping table? | CREATE TABLE ocean_floor_mapping (location TEXT,depth INTEGER); INSERT INTO ocean_floor_mapping (location,depth) VALUES ('Challenger Deep',10994),('Mariana Trench',10972),('Tonga Trench',10823),('Indian Ocean',4665); | SELECT AVG(depth) FROM ocean_floor_mapping WHERE location = 'Indian Ocean'; |
What is the R&D expenditure for company 'BioPharm' in 2020? | CREATE TABLE rd_expenditure_data (company_name VARCHAR(50),expenditure_year INT,amount DECIMAL(10,2)); INSERT INTO rd_expenditure_data (company_name,expenditure_year,amount) VALUES ('BioPharm',2020,8000000),('BioPharm',2018,7000000); | SELECT amount FROM rd_expenditure_data WHERE company_name = 'BioPharm' AND expenditure_year = 2020; |
Get the number of cyber threats mitigated per day in the last week | CREATE TABLE CyberThreatMitigation (id INT,mitigation_date DATE,mitigation_status VARCHAR(50)); INSERT INTO CyberThreatMitigation (id,mitigation_date,mitigation_status) VALUES (1,'2022-01-01','Mitigated'); | SELECT DATE(mitigation_date), COUNT(*) FROM CyberThreatMitigation WHERE mitigation_date >= CURDATE() - INTERVAL 7 DAY AND mitigation_status = 'Mitigated' GROUP BY DATE(mitigation_date); |
Delete all records for attendees with age below 18 in the 'Children's Program'. | CREATE TABLE Attendance (attendance_id INT PRIMARY KEY,attendee_id INT,attendee_age INT,event_id INT); | DELETE FROM Attendance WHERE attendee_age < 18 AND event_id IN (SELECT event_id FROM Events WHERE program = 'Children''s Program'); |
What is the average donation amount by donor type, excluding the top and bottom 25% and updating the result in the 'donation_stats' table. | CREATE SCHEMA if not exists arts_culture;CREATE TABLE if not exists arts_culture.donors (donor_id INT PRIMARY KEY,name VARCHAR(255),type VARCHAR(255),donation DECIMAL(10,2));CREATE TABLE if not exists arts_culture.donation_stats (type VARCHAR(255),avg_donation DECIMAL(10,2));INSERT INTO arts_culture.donors (donor_id,name,type,donation) VALUES (1,'John Doe','Individual',50.00),(2,'Jane Smith','Individual',100.00),(3,'Google Inc.','Corporation',5000.00);INSERT INTO arts_culture.donation_stats (type,avg_donation) VALUES ('Individual',75.00),('Corporation',5000.00); | UPDATE arts_culture.donation_stats ds SET avg_donation = (SELECT AVG(donation) FROM (SELECT donation, type, NTILE(100) OVER (ORDER BY donation) as percentile FROM arts_culture.donors) d WHERE percentile NOT IN (1, 2, 99, 100) GROUP BY type) WHERE ds.type = 'Individual'; |
How many diamond mines are there in Russia? | CREATE TABLE diamond_mines (id INT,name TEXT,location TEXT); INSERT INTO diamond_mines (id,name,location) VALUES (1,'Mirny GOK','Yakutia,Russia'),(2,'Udachny','Yakutia,Russia'),(3,'Aikhal','Yakutia,Russia'); | SELECT COUNT(*) FROM diamond_mines WHERE location LIKE '%Russia%'; |
What is the cultural competency score for a healthcare provider in Florida? | CREATE TABLE healthcare_providers (id INT,name TEXT,cultural_competency_score INT,state TEXT); INSERT INTO healthcare_providers (id,name,cultural_competency_score,state) VALUES (1,'Dr. John Doe',85,'Florida'); INSERT INTO healthcare_providers (id,name,cultural_competency_score,state) VALUES (2,'Dr. Jane Smith',90,'California'); | SELECT cultural_competency_score FROM healthcare_providers WHERE name = 'Dr. John Doe' AND state = 'Florida'; |
How many chemical spills occurred in the past 12 months, grouped by country? | CREATE TABLE spills (id INT,location TEXT,spill_date DATE); INSERT INTO spills (id,location,spill_date) VALUES (1,'US','2021-03-15'),(2,'MX','2021-07-22'),(3,'CA','2020-11-01'),(4,'MX','2021-02-03'),(5,'US','2021-06-09'),(6,'CA','2020-05-12'); | SELECT location, COUNT(*) FROM spills WHERE spill_date >= DATE_SUB(CURRENT_DATE, INTERVAL 12 MONTH) GROUP BY location; |
What is the total weight of spacecrafts manufactured in 2023 by 'Cosmos Constructors'? | CREATE TABLE Spacecrafts (id INT,name VARCHAR(50),manufacturer VARCHAR(50),weight FLOAT,manufacture_year INT); INSERT INTO Spacecrafts (id,name,manufacturer,weight,manufacture_year) VALUES (1,'New Horizons','Cosmos Constructors',450.0,2023),(2,'Voyager 3','Cosmos Constructors',800.0,2022),(3,'Voyager 4','Cosmos Constructors',820.0,2023); | SELECT SUM(weight) FROM Spacecrafts WHERE manufacturer = 'Cosmos Constructors' AND manufacture_year = 2023; |
What is the total funding for genomic data analysis projects? | CREATE TABLE genomic_data (id INT,project TEXT,funding FLOAT); INSERT INTO genomic_data (id,project,funding) VALUES (1,'Whole Genome Sequencing',9000000.0); INSERT INTO genomic_data (id,project,funding) VALUES (2,'Genomic Data Analysis',11000000.0); | SELECT SUM(funding) FROM genomic_data WHERE project = 'Genomic Data Analysis'; |
What is the maximum age of players who have played multiplayer games, categorized by the genre of the game? | CREATE TABLE Players (PlayerID INT,Age INT,GameGenre VARCHAR(10));CREATE TABLE MultiplayerGames (GameID INT,PlayerID INT); | SELECT g.GameGenre, MAX(p.Age) as MaxAge FROM Players p INNER JOIN MultiplayerGames mg ON p.PlayerID = mg.PlayerID GROUP BY g.GameGenre; |
What is the average employment rate for veterans in each state? | CREATE TABLE Veterans (State VARCHAR(255),Employment_Rate FLOAT); INSERT INTO Veterans (State,Employment_Rate) VALUES ('California',65.2),('Texas',70.5),('New York',68.7),('Florida',72.1),('Illinois',66.9); | SELECT State, AVG(Employment_Rate) FROM Veterans GROUP BY State; |
What is the combined capacity of renewable energy projects in Brazil? | CREATE TABLE RenewableEnergyProjects (id INT,project_name VARCHAR(50),country VARCHAR(50),capacity_mw INT); INSERT INTO RenewableEnergyProjects (id,project_name,country,capacity_mw) VALUES (3,'Hydroelectric Dam','Brazil',10000); | SELECT SUM(r.capacity_mw) FROM RenewableEnergyProjects r WHERE r.country = 'Brazil'; |
What is the total amount donated by top 2 donors in 2020? | CREATE TABLE Donors (DonorID INT,DonorName TEXT,Country TEXT,Amount DECIMAL(10,2),DonationYear INT); INSERT INTO Donors (DonorID,DonorName,Country,Amount,DonationYear) VALUES (1,'John Doe','USA',500.00,2020),(2,'Jane Smith','Canada',300.00,2020),(3,'Marie Curie','France',700.00,2020); | SELECT DonorName, SUM(Amount) AS TotalDonations FROM Donors WHERE DonationYear = 2020 AND DonorID IN (1, 3) GROUP BY DonorName; |
Landfill capacity of the 'Amazonas' landfill in 2019 and 2020. | CREATE TABLE landfill_capacity (landfill VARCHAR(50),year INT,capacity INT); INSERT INTO landfill_capacity (landfill,year,capacity) VALUES ('Amazonas',2019,7000000),('Amazonas',2020,7500000),('Sao_Paulo',2019,8000000),('Sao_Paulo',2020,8500000); | SELECT landfill, (SUM(capacity) FILTER (WHERE year = 2019)) AS capacity_2019, (SUM(capacity) FILTER (WHERE year = 2020)) AS capacity_2020 FROM landfill_capacity WHERE landfill = 'Amazonas' GROUP BY landfill; |
What is the total contract value and associated equipment for each vendor? | CREATE TABLE if not exists vendor_equipment (vendor_id INT,vendor VARCHAR(255),equipment VARCHAR(255),contract_value FLOAT); INSERT INTO vendor_equipment (vendor_id,vendor,equipment,contract_value) VALUES (1,'XYZ Corp','M2 Bradley',2000000); | SELECT vendor, equipment, SUM(contract_value) as total_contract_value FROM vendor_equipment GROUP BY vendor, equipment; |
What is the average data usage for postpaid customers in each region, sorted by usage in descending order? | CREATE TABLE mobile_customers (customer_id INT,plan_type VARCHAR(10),data_usage FLOAT,region VARCHAR(20)); INSERT INTO mobile_customers (customer_id,plan_type,data_usage,region) VALUES (1,'postpaid',3.5,'Chicago'),(2,'prepaid',2.0,'Chicago'),(3,'postpaid',5.0,'New York'); CREATE TABLE regions (region VARCHAR(20)); INSERT INTO regions (region) VALUES ('Chicago'),('New York'); CREATE TABLE plan_types (plan_type VARCHAR(10)); INSERT INTO plan_types (plan_type) VALUES ('postpaid'),('prepaid'); | SELECT r.region, AVG(mc.data_usage) AS avg_data_usage FROM mobile_customers mc JOIN regions r ON mc.region = r.region JOIN plan_types pt ON mc.plan_type = pt.plan_type WHERE pt.plan_type = 'postpaid' GROUP BY r.region ORDER BY avg_data_usage DESC; |
How many rural infrastructure projects were completed in the 'Mississippi Delta' region before 2015? | CREATE TABLE rural_infrastructure (id INT,project_name VARCHAR(255),region VARCHAR(255),completion_date DATE); INSERT INTO rural_infrastructure (id,project_name,region,completion_date) VALUES (1,'Rural Electrification','Mississippi Delta','2013-05-01'),(2,'Water Supply System','Mississippi Delta','2015-12-31'); | SELECT COUNT(*) FROM rural_infrastructure WHERE region = 'Mississippi Delta' AND completion_date < '2015-01-01'; |
What is the percentage change in the average monthly production of Europium from Q1 2019 to Q2 2019? | CREATE TABLE production (id INT,element TEXT,month INT,year INT,quantity INT); | SELECT ((Q2_avg - Q1_avg) / Q1_avg) * 100 as percentage_change FROM (SELECT AVG(quantity) as Q1_avg FROM production WHERE element = 'Europium' AND month BETWEEN 1 AND 3 AND year = 2019) q1, (SELECT AVG(quantity) as Q2_avg FROM production WHERE element = 'Europium' AND month BETWEEN 4 AND 6 AND year = 2019) q2; |
List the total sales for farmers in California and Texas. | CREATE TABLE Farmers (farmer_id INT,state VARCHAR(50),sales FLOAT); INSERT INTO Farmers (farmer_id,state,sales) VALUES (1,'California',10000),(2,'Texas',15000),(3,'California',12000); | SELECT SUM(sales) FROM Farmers WHERE state IN ('California', 'Texas') |
What is the total donation amount by donors from the United States? | CREATE TABLE donors (id INT,name TEXT,country TEXT,donation_amount DECIMAL(10,2)); INSERT INTO donors VALUES (1,'John Doe','USA',500.00),(2,'Jane Smith','Canada',300.00); | SELECT SUM(donation_amount) FROM donors WHERE country = 'USA'; |
Show the total number of marine species found in each ocean basin | CREATE TABLE ocean_basins (id INT,species_count INT); | SELECT name, species_count FROM ocean_basins; |
Find the number of unique users who have streamed songs in Spanish, in the last month. | CREATE TABLE users (id INT,last_stream_date DATE); CREATE TABLE streams (user_id INT,song_id INT,language VARCHAR(255)); | SELECT COUNT(DISTINCT users.id) FROM users INNER JOIN streams ON users.id = streams.user_id WHERE streams.language = 'Spanish' AND users.last_stream_date >= NOW() - INTERVAL 1 MONTH; |
What is the total number of lifetime learning hours for 'Student Y' up to '2022'? | CREATE TABLE lifelong_learning (student_name VARCHAR(20),learning_hours INT,learning_date DATE); INSERT INTO lifelong_learning (student_name,learning_hours,learning_date) VALUES ('Student Y',10,'2017-09-01'),('Student Y',8,'2018-02-14'),('Student Y',12,'2019-06-22'),('Student Y',15,'2020-12-31'),('Student Y',11,'2021-07-04'),('Student Y',7,'2022-02-15'); | SELECT student_name, SUM(learning_hours) as total_hours FROM lifelong_learning WHERE student_name = 'Student Y' AND learning_date <= '2022-12-31' GROUP BY student_name; |
Delete all food safety inspection records for 'XYZ Diner' in 2021. | CREATE TABLE food_safety_inspections (restaurant_id INT,inspection_date DATE,result VARCHAR(10)); | DELETE FROM food_safety_inspections WHERE restaurant_id = 2 AND inspection_date BETWEEN '2021-01-01' AND '2021-12-31'; |
How many renewable energy installations are there in each region in Australia? | CREATE TABLE renewable_energy (id INT,region VARCHAR(255),installation INT); INSERT INTO renewable_energy (id,region,installation) VALUES (1,'New South Wales',1000),(2,'Victoria',1500),(3,'New South Wales',1200),(4,'Victoria',1800); | SELECT region, COUNT(DISTINCT installation) as num_installations FROM renewable_energy GROUP BY region; |
Find the names of artists who have not received any funding. | CREATE TABLE artists (id INT,name VARCHAR(255)); INSERT INTO artists (id,name) VALUES (1,'Picasso'),(2,'Van Gogh'),(3,'Monet'),(4,'Dali'); CREATE TABLE funding (artist_id INT,source VARCHAR(255),amount FLOAT); INSERT INTO funding (artist_id,source,amount) VALUES (1,'Private Donor',10000),(1,'Corporation',20000),(2,'Government',15000),(2,'Private Donor',5000); | SELECT name FROM artists WHERE id NOT IN (SELECT artist_id FROM funding); |
What is the total number of streams for R&B tracks on YouTube, grouped by month? | CREATE TABLE MonthlyStreams (StreamID INT,TrackID INT,PlatformID INT,Date DATE,Streams INT); INSERT INTO MonthlyStreams (StreamID,TrackID,PlatformID,Date,Streams) VALUES (1,1,3,'2022-01-01',100); | SELECT EXTRACT(MONTH FROM Date) as Month, EXTRACT(YEAR FROM Date) as Year, SUM(Streams) as TotalStreams FROM MonthlyStreams JOIN Tracks ON MonthlyStreams.TrackID = Tracks.TrackID JOIN StreamingPlatforms ON MonthlyStreams.PlatformID = StreamingPlatforms.PlatformID WHERE Genre = 'R&B' AND PlatformName = 'YouTube' GROUP BY Month, Year; |
Delete all records from the 'visitors' table where age is less than 18 | CREATE TABLE visitors (id INT PRIMARY KEY,age INT,gender VARCHAR(10),city VARCHAR(20)); | DELETE FROM visitors WHERE age < 18; |
List all volunteers who have not volunteered since 2021 | CREATE TABLE Volunteers (VolunteerID INT PRIMARY KEY,VolunteerName VARCHAR(50),LastVolunteerDate DATE); INSERT INTO Volunteers (VolunteerID,VolunteerName,LastVolunteerDate) VALUES (1,'John Doe','2021-12-30'); INSERT INTO Volunteers (VolunteerID,VolunteerName,LastVolunteerDate) VALUES (2,'Jane Smith','2022-03-20'); | SELECT VolunteerName FROM Volunteers WHERE LastVolunteerDate < '2022-01-01'; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.