instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
What is the average property price per square foot in the city of Denver?
CREATE TABLE Properties (PropertyID INT,Price DECIMAL(10,2),City VARCHAR(255),SquareFootage INT); INSERT INTO Properties (PropertyID,Price,City,SquareFootage) VALUES (1,500000,'Denver',2000),(2,600000,'Denver',2500),(3,400000,'Denver',1800);
SELECT AVG(Price/SquareFootage) FROM Properties WHERE City = 'Denver';
Find the total oil production for each platform in Q1 2020
CREATE TABLE platform (id INT,name VARCHAR(50),location VARCHAR(50)); CREATE TABLE production (platform_id INT,date DATE,oil_production FLOAT);
SELECT p.name, SUM(p.oil_production) FROM production p JOIN platform pl ON p.platform_id = pl.id WHERE p.date BETWEEN '2020-01-01' AND '2020-03-31' GROUP BY p.platform_id;
Find the number of LEED certified buildings in each state.
CREATE TABLE buildings (id INT,name TEXT,state TEXT,leed_certification TEXT); INSERT INTO buildings (id,name,state,leed_certification) VALUES (1,'Building A','Texas','Platinum'),(2,'Building B','California','Gold'),(3,'Building C','California','Platinum'),(4,'Building D','Texas','Gold'),(5,'Building E','New York','Plat...
SELECT state, COUNT(*) FROM buildings WHERE leed_certification IS NOT NULL GROUP BY state;
List the top 5 spacecraft manufacturers with the most spacecraft launched, and the number of spacecraft launched?
CREATE TABLE spacecraft_manufacturers (id INT,name VARCHAR(50));CREATE TABLE spacecraft (id INT,manufacturer_id INT,name VARCHAR(50),launch_date DATE);
SELECT manufacturers.name, COUNT(spacecraft.id) as number_of_launches FROM spacecraft_manufacturers manufacturers JOIN spacecraft spacecraft ON manufacturers.id = spacecraft.manufacturer_id GROUP BY manufacturers.id ORDER BY number_of_launches DESC LIMIT 5;
What is the average age of customers who have made a credit transaction?
CREATE TABLE customer (id INT,name VARCHAR(255),age INT,gender VARCHAR(10)); INSERT INTO customer (id,name,age,gender) VALUES (1,'John Doe',35,'Male'); INSERT INTO customer (id,name,age,gender) VALUES (2,'Jane Smith',28,'Female'); CREATE TABLE transactions (id INT,customer_id INT,transaction_date DATE,amount DECIMAL(10...
SELECT AVG(customer.age) AS avg_age FROM customer INNER JOIN transactions ON customer.id = transactions.customer_id WHERE transactions.type = 'credit';
What are the names of the departments that have published more than 50 papers in the past year, and how many papers did each of these departments publish?
CREATE TABLE departments (id INT,name VARCHAR(255)); INSERT INTO departments (id,name) VALUES (1,'Mechanical Engineering'),(2,'Electrical Engineering'); CREATE TABLE papers (id INT,department_id INT,publication_date DATE,PRIMARY KEY (id),FOREIGN KEY (department_id) REFERENCES departments(id)); INSERT INTO papers (id,de...
SELECT d.name, COUNT(p.id) AS count FROM departments d JOIN papers p ON d.id = p.department_id WHERE p.publication_date >= DATE_TRUNC('year', NOW()) - INTERVAL '1 year' GROUP BY d.id HAVING count > 50;
What is the maximum cultural competency rating for mental health facilities in the Northeast region?
CREATE TABLE MentalHealthFacilities (Id INT,Region VARCHAR(255),CulturalCompetencyRating INT); INSERT INTO MentalHealthFacilities (Id,Region,CulturalCompetencyRating) VALUES (1,'Northeast',9); INSERT INTO MentalHealthFacilities (Id,Region,CulturalCompetencyRating) VALUES (2,'Southwest',7); INSERT INTO MentalHealthFacil...
SELECT MAX(CulturalCompetencyRating) FROM MentalHealthFacilities WHERE Region = 'Northeast';
What is the average streaming time per user in 'music_streaming' table?
CREATE TABLE music_streaming (user_id INT,song_id INT,duration FLOAT,date DATE);
SELECT AVG(duration) AS avg_duration FROM music_streaming;
What is the number of inclusion efforts by disability services provider and disability type?
CREATE TABLE inclusion_efforts (effort_id INT,effort_name VARCHAR(50),provider_name VARCHAR(50),disability_type VARCHAR(50)); INSERT INTO inclusion_efforts (effort_id,effort_name,provider_name,disability_type) VALUES (1,'Wheelchair Ramp Construction','University A','Physical');
SELECT provider_name, disability_type, COUNT(*) as total_efforts FROM inclusion_efforts GROUP BY provider_name, disability_type;
What is the average age of patients who have received group therapy in the treatment_history table?
CREATE TABLE treatment_history (patient_id INT,treatment_date DATE,treatment_type VARCHAR(255),facility_id INT,facility_name VARCHAR(255),facility_location VARCHAR(255)); CREATE TABLE patients (patient_id INT,first_name VARCHAR(255),last_name VARCHAR(255),age INT,gender VARCHAR(255),address VARCHAR(255),phone_number VA...
SELECT AVG(p.age) FROM treatment_history th JOIN patients p ON th.patient_id = p.patient_id WHERE th.treatment_type = 'group therapy';
Update the role of employee with ID 2 to 'Senior Engineer'.
CREATE TABLE Employees (id INT,name VARCHAR(50),role VARCHAR(50),experience INT); INSERT INTO Employees (id,name,role,experience) VALUES (1,'Jane Doe','Engineer',7); INSERT INTO Employees (id,name,role,experience) VALUES (2,'Michael Brown','Engineer',11);
UPDATE Employees SET role = 'Senior Engineer' WHERE id = 2;
What is the total number of tourists visiting Africa from North America?
CREATE TABLE africa_countries (country VARCHAR(50)); INSERT INTO africa_countries (country) VALUES ('Egypt'),('Morocco'),('Tunisia'),('South Africa'),('Kenya'); CREATE TABLE tourist_visits (country VARCHAR(50),region VARCHAR(50),visitors INT); INSERT INTO tourist_visits (country,region,visitors) VALUES ('Egypt','North ...
SELECT SUM(visitors) FROM tourist_visits WHERE country IN (SELECT country FROM africa_countries) AND region = 'North America';
Find the number of patients by gender who visited Rural Health Clinic A in 2021
CREATE TABLE rhc_visits (clinic_id INT,visit_date DATE,patient_gender VARCHAR(10)); INSERT INTO rhc_visits VALUES (1,'2021-01-01'),(1,'2021-01-15','Female');
SELECT patient_gender, COUNT(*) as num_visits FROM rhc_visits WHERE clinic_id = 1 AND YEAR(visit_date) = 2021 GROUP BY patient_gender;
Which users have the most followers, and what is the total number of posts, comments, and likes for those users in the past month?
CREATE TABLE user_info (user_id INT,username VARCHAR(50),country VARCHAR(50),followers INT); CREATE TABLE user_activity (user_id INT,post_date DATE,post_type VARCHAR(10),activity INT); INSERT INTO user_info (user_id,username,country,followers) VALUES (1,'johndoe','USA',1000),(2,'janedoe','Canada',2000),(3,'samantha','M...
SELECT ui.username, SUM(ua.activity) as total_activity FROM user_info ui JOIN user_activity ua ON ui.user_id = ua.user_id WHERE ui.followers IN (SELECT MAX(followers) FROM user_info) AND ua.post_date BETWEEN DATE_SUB(NOW(), INTERVAL 1 MONTH) AND NOW() GROUP BY ui.username;
Number of unique visitors who engaged with digital installations grouped by their home continent?
CREATE TABLE DigitalInstallations (InstallationID INT,Continent VARCHAR(50)); INSERT INTO DigitalInstallations (InstallationID,Continent) VALUES (1,'North America'),(2,'Europe'); CREATE TABLE VisitorEngagements (EngagementID INT,VisitorID INT,InstallationID INT); INSERT INTO VisitorEngagements (EngagementID,VisitorID,I...
SELECT COUNT(DISTINCT VisitorID), Continent FROM VisitorEngagements VE JOIN DigitalInstallations DI ON VE.InstallationID = DI.InstallationID GROUP BY Continent;
Identify the top 3 busiest stations in the transportation system.
CREATE TABLE ENTRIES (station_name TEXT,entries INT); INSERT INTO ENTRIES (station_name,entries) VALUES ('Station1',200),('Station2',150),('Station3',250),('Station4',300),('Station5',100);
SELECT station_name FROM (SELECT station_name, DENSE_RANK() OVER (ORDER BY entries DESC) AS rank FROM ENTRIES) subquery WHERE rank <= 3;
What is the maximum waste generation rate in the 'Educational' sector?
CREATE TABLE EducationalWaste (id INT,sector VARCHAR(20),waste_generation_rate FLOAT); INSERT INTO EducationalWaste (id,sector,waste_generation_rate) VALUES (1,'Educational',2.5),(2,'Educational',3.5);
SELECT MAX(waste_generation_rate) FROM EducationalWaste WHERE sector = 'Educational';
List all the unique accommodations provided by the disability services.
CREATE TABLE Accommodations (accommodation_id INT,accommodation VARCHAR(255)); INSERT INTO Accommodations VALUES (1,'Extra Time');
SELECT DISTINCT accommodation FROM Accommodations;
What is the maximum number of tickets sold for a single 'music' event?
CREATE TABLE event_tickets (id INT,event_name TEXT,tickets_sold INT); INSERT INTO event_tickets (id,event_name,tickets_sold) VALUES (1,'Rock Concert',200),(2,'Classical Concert',150);
SELECT MAX(tickets_sold) FROM event_tickets WHERE event_name IN (SELECT event_name FROM events WHERE event_category = 'music');
What is the total budget allocation for healthcare services in rural areas?
CREATE TABLE cities (id INT,name VARCHAR(20),type VARCHAR(10)); INSERT INTO cities VALUES (1,'CityA','Urban'),(2,'CityB','Rural'),(3,'CityC','Rural'); CREATE TABLE budget_allocation (service VARCHAR(20),city_id INT,amount INT); INSERT INTO budget_allocation VALUES ('Healthcare',1,500000),('Healthcare',2,300000),('Healt...
SELECT SUM(amount) FROM budget_allocation WHERE service = 'Healthcare' AND city_id IN (SELECT id FROM cities WHERE type = 'Rural');
List all the investments made by venture capital firms in the year 2018
CREATE TABLE investments(id INT,startup_id INT,investor TEXT,investment_amount FLOAT,investment_year INT); INSERT INTO investments (id,startup_id,investor,investment_amount,investment_year) VALUES (1,1,'Sequoia',1000000,2018); INSERT INTO investments (id,startup_id,investor,investment_amount,investment_year) VALUES (2,...
SELECT startup_id, investor, investment_amount FROM investments WHERE investment_year = 2018;
Delete paraben-free skincare products priced below $15.
CREATE TABLE products (id INT,name VARCHAR(255),category VARCHAR(255),price DECIMAL(5,2),paraben_free BOOLEAN); INSERT INTO products (id,name,category,price,paraben_free) VALUES (1,'Cleanser','skincare',19.99,true),(2,'Toner','skincare',12.99,true),(3,'Moisturizer','skincare',24.99,false);
DELETE FROM products WHERE category = 'skincare' AND paraben_free = true AND price < 15;
What is the percentage of Shariah-compliant financial products sold in each region?
CREATE TABLE sales (sale_id INT,product_type VARCHAR(30),region VARCHAR(20),sale_date DATE); INSERT INTO sales (sale_id,product_type,region,sale_date) VALUES (1,'Shariah-compliant Mortgage','East','2021-03-21'),(2,'Conventional Car Loan','West','2022-05-14');
SELECT region, (COUNT(*) FILTER (WHERE product_type LIKE '%Shariah-compliant%')) * 100.0 / COUNT(*) AS shariah_percentage FROM sales GROUP BY region;
How many climate mitigation initiatives were implemented in South America in 2022?
CREATE TABLE Initiatives (Year INT,Region VARCHAR(20),Status VARCHAR(20),Type VARCHAR(20)); INSERT INTO Initiatives (Year,Region,Status,Type) VALUES (2022,'South America','Implemented','Climate Mitigation');
SELECT COUNT(*) FROM Initiatives WHERE Year = 2022 AND Region = 'South America' AND Type = 'Climate Mitigation' AND Status = 'Implemented';
How many virtual tours have been engaged with for hotels that have implemented AI-powered solutions in the Americas?
CREATE TABLE hotels (hotel_id INT,hotel_name TEXT,region TEXT); CREATE TABLE ai_solutions (solution_id INT,hotel_id INT,implemented_date DATE); CREATE TABLE virtual_tours (tour_id INT,hotel_id INT,engagement_score INT); INSERT INTO hotels (hotel_id,hotel_name,region) VALUES (1,'Desert Oasis','Americas'),(2,'Mountain Vi...
SELECT COUNT(DISTINCT vt.hotel_id) AS total_tours_engaged FROM virtual_tours vt INNER JOIN hotels h ON vt.hotel_id = h.hotel_id INNER JOIN ai_solutions ai ON h.hotel_id = ai.hotel_id WHERE h.region = 'Americas';
What is the average price of seeds for farmers who use more than two types of seeds?
CREATE TABLE seeds (id INT PRIMARY KEY,name VARCHAR(255),price DECIMAL(10,2),crop VARCHAR(255),farm_id INT,FOREIGN KEY (farm_id) REFERENCES farmers(id));
SELECT f.name, AVG(s.price) FROM seeds s JOIN farmers f ON s.farm_id = f.id GROUP BY f.id HAVING COUNT(DISTINCT s.crop) > 2;
Update the email addresses for teachers living in 'Ontario'
CREATE TABLE teachers (id INT,name VARCHAR(20),state VARCHAR(20),email VARCHAR(30)); INSERT INTO teachers (id,name,state,email) VALUES (1,'Mme. Lefebvre','Ontario','mme.lefebvre@example.com'); INSERT INTO teachers (id,name,state,email) VALUES (2,'Mr. Kim','British Columbia','mr.kim@example.com'); INSERT INTO teachers (...
UPDATE teachers SET email = CASE WHEN state = 'Ontario' THEN CONCAT(name, '@ontarioeducators.ca') ELSE email END WHERE state = 'Ontario';
What are the top 5 longest bioprocess engineering projects in the 'medical devices' industry?
CREATE TABLE bioprocess_engineering (id INT,project_name VARCHAR(100),industry VARCHAR(100),duration INT);
SELECT project_name, duration FROM bioprocess_engineering WHERE industry = 'medical devices' GROUP BY project_name ORDER BY duration DESC LIMIT 5;
What is the total installed capacity of renewable energy projects in 'Country A'?
CREATE TABLE Projects (ProjectID INT,ProjectName VARCHAR(255),Country VARCHAR(255),InstalledCapacity FLOAT); INSERT INTO Projects (ProjectID,ProjectName,Country,InstalledCapacity) VALUES (1,'Solar Farm 1','Country A',5000.0);
SELECT SUM(InstalledCapacity) FROM Projects WHERE Country = 'Country A';
What is the maximum price of sustainable silk products?
CREATE TABLE products (product_id int,material varchar(20),price decimal(5,2)); INSERT INTO products (product_id,material,price) VALUES (1,'organic cotton',25.99),(2,'recycled polyester',19.99),(3,'organic cotton',34.99),(4,'sustainable silk',59.99),(5,'sustainable silk',79.99);
SELECT MAX(price) FROM products WHERE material = 'sustainable silk';
How many food safety violations were there in 'Cafe R' in 2021?
CREATE TABLE Inspections (Restaurant VARCHAR(255),Date DATE,Violation INT); INSERT INTO Inspections (Restaurant,Date,Violation) VALUES ('Cafe R','2021-01-01',1),('Cafe R','2021-02-01',0),('Cafe R','2021-03-01',1),('Cafe R','2021-04-01',0),('Cafe R','2021-05-01',1);
SELECT COUNT(*) FROM Inspections WHERE Restaurant = 'Cafe R' AND YEAR(Date) = 2021 AND Violation > 0;
How many unique services are provided by the government in 'Texas' and 'New York'?
CREATE TABLE services (state VARCHAR(20),service VARCHAR(20)); INSERT INTO services (state,service) VALUES ('Texas','Education'),('Texas','Transportation'),('New York','Healthcare'),('New York','Education'),('New York','Transportation');
SELECT COUNT(DISTINCT service) FROM services WHERE state IN ('Texas', 'New York');
List the products in the Inventory table that are not associated with any department, excluding products with 'Solar' in their name.
CREATE TABLE Inventory (InventoryID INT,ProductID INT,ProductName VARCHAR(50),QuantityOnHand INT,ReorderLevel INT,Department VARCHAR(50)); INSERT INTO Inventory (InventoryID,ProductID,ProductName,QuantityOnHand,ReorderLevel,Department) VALUES (1,1001,'Eco-Friendly Parts',500,300,'Manufacturing'); INSERT INTO Inventory ...
SELECT ProductName FROM Inventory WHERE Department IS NULL AND ProductName NOT LIKE '%Solar%';
What is the maximum water consumption in the Water_Usage table for the year 2021?
CREATE TABLE Water_Usage (id INT,year INT,water_consumption FLOAT); INSERT INTO Water_Usage (id,year,water_consumption) VALUES (1,2018,12000.0),(2,2019,13000.0),(3,2020,14000.0),(4,2021,15000.0),(5,2021,16000.0);
SELECT MAX(water_consumption) FROM Water_Usage WHERE year = 2021;
What is the total quantity of 'Wool Sweaters' sold and returned between '2022-01-16' and '2022-01-31'?
CREATE TABLE sales (id INT,product VARCHAR(50),quantity INT,price DECIMAL(5,2),date DATE); INSERT INTO sales (id,product,quantity,price,date) VALUES (1,'Wool Sweaters',75,60.00,'2022-01-18'),(2,'Wool Sweaters',30,60.00,'2022-01-25'); CREATE TABLE returns (id INT,product VARCHAR(50),quantity INT,reason VARCHAR(50),date ...
SELECT SUM(s.quantity) FROM sales s WHERE s.product = 'Wool Sweaters' AND s.date BETWEEN '2022-01-16' AND '2022-01-31' UNION SELECT SUM(r.quantity) FROM returns r WHERE r.product = 'Wool Sweaters' AND r.date BETWEEN '2022-01-16' AND '2022-01-31';
Show the total sales of products that are made of recycled materials in Japan.
CREATE TABLE products (product_id INT,name VARCHAR(50),recycled_materials BOOLEAN,price DECIMAL(5,2)); CREATE TABLE sales (sale_id INT,product_id INT,sale_date DATE,quantity INT); CREATE VIEW product_sales_view AS SELECT products.product_id,products.name,products.recycled_materials,products.price,SUM(sales.quantity) as...
SELECT total_sold FROM product_sales_view WHERE recycled_materials = true AND country = 'Japan';
What is the maximum temperature recorded in the 'arctic_weather' table for each month in 2021?
CREATE TABLE arctic_weather (date DATE,temperature FLOAT);
SELECT EXTRACT(MONTH FROM date) AS month, MAX(temperature) FROM arctic_weather WHERE EXTRACT(YEAR FROM date) = 2021 GROUP BY EXTRACT(MONTH FROM date);
List the unique categories of public services in the city.
CREATE TABLE public_services (category VARCHAR(255),name VARCHAR(255),location VARCHAR(255));
SELECT DISTINCT category FROM public_services;
Determine the number of artworks by indigenous artists in each country.
CREATE TABLE artworks (id INT,artist_name VARCHAR(255),country VARCHAR(255)); INSERT INTO artworks (id,artist_name,country) VALUES (1,'Rigoberto Torres','USA'),(2,'Dana Claxton','Canada'),(3,'Tracey Moffatt','Australia'),(4,'Marlene Dumas','South Africa');
SELECT country, COUNT(*) FROM artworks WHERE artist_name IN (SELECT artist_name FROM artists WHERE ethnicity = 'Indigenous') GROUP BY country;
Calculate the total number of cultural heritage sites preserved in 'Africa' and 'Asia' as of 2022.
CREATE TABLE cultural_heritage (id INT,site_name VARCHAR(100),location VARCHAR(50),year_preserved INT); INSERT INTO cultural_heritage (id,site_name,location,year_preserved) VALUES (1,'Giza Pyramids','Africa',2000),(2,'Taj Mahal','Asia',1995);
SELECT SUM(CASE WHEN location IN ('Africa', 'Asia') THEN 1 ELSE 0 END) as total_sites FROM cultural_heritage WHERE year_preserved <= 2022;
What is the percentage of broadband subscribers who have experienced a network issue in the last month?
CREATE TABLE broadband_subscribers_network_issues (subscriber_id INT,name VARCHAR(255),last_network_issue_date DATE); INSERT INTO broadband_subscribers_network_issues (subscriber_id,name,last_network_issue_date) VALUES (1,'John Doe','2022-01-15'),(2,'Jane Doe',NULL);
SELECT 100.0 * COUNT(CASE WHEN last_network_issue_date IS NOT NULL AND last_network_issue_date >= DATE_SUB(CURDATE(), INTERVAL 1 MONTH) THEN 1 END) / COUNT(*) AS percentage FROM broadband_subscribers;
What was the average sales quantity for DrugY in 2021?
CREATE TABLE sales_data (drug_name VARCHAR(100),sales_quantity INT,year INT); INSERT INTO sales_data (drug_name,sales_quantity,year) VALUES ('DrugX',1200,2021),('DrugY',800,2021),('DrugX',1500,2022),('DrugY',900,2022);
SELECT AVG(sales_quantity) FROM sales_data WHERE drug_name = 'DrugY' AND year = 2021;
What are the top 5 most vulnerable systems by operating system?
CREATE TABLE systems (system_id INT,system_name VARCHAR(255),operating_system VARCHAR(255),vulnerability_score INT); INSERT INTO systems (system_id,system_name,operating_system,vulnerability_score) VALUES (1,'Web Server 1','Windows Server 2016',7),(2,'Database Server 1','Red Hat Enterprise Linux 7',5),(3,'Email Server ...
SELECT operating_system, system_name, vulnerability_score FROM systems ORDER BY vulnerability_score DESC LIMIT 5;
Find the minimum temperature recorded at each location
temperature_readings
SELECT location, MIN(temperature) as min_temperature FROM temperature_readings GROUP BY location;
What is the average age of players who have played the game "Galactic Conquest" and spent more than $50 on in-game purchases?
CREATE TABLE Players (PlayerID INT,PlayerAge INT,GameName VARCHAR(20)); INSERT INTO Players (PlayerID,PlayerAge,GameName) VALUES (1,25,'Galactic Conquest'),(2,30,'Cosmic Fury'),(3,22,'Galactic Conquest'); CREATE TABLE InGamePurchases (PlayerID INT,Amount DECIMAL(5,2)); INSERT INTO InGamePurchases (PlayerID,Amount) VALU...
SELECT AVG(Players.PlayerAge) FROM Players JOIN InGamePurchases ON Players.PlayerID = InGamePurchases.PlayerID WHERE Players.GameName = 'Galactic Conquest' AND InGamePurchases.Amount > 50;
How many days did it take to resolve each broadband outage in the state of Texas?
CREATE TABLE broadband_outages (id INT,outage_id INT,state VARCHAR(20),outage_date DATE,resolve_date DATE);
SELECT state, DATEDIFF(resolve_date, outage_date) FROM broadband_outages WHERE state = 'Texas';
Identify the number of unique players who played each game, including those with zero players.
CREATE TABLE GamePlayers (GameTitle VARCHAR(255),PlayerID INT); INSERT INTO GamePlayers VALUES ('GameA',1),('GameA',2),('GameB',1),('GameC',1),('GameC',2),('GameC',3);
SELECT g.GameTitle, COALESCE(COUNT(DISTINCT g.PlayerID), 0) as UniquePlayers FROM GamePlayers g GROUP BY g.GameTitle;
What is the most popular clothing item size in Canada?
CREATE TABLE clothing_inventory (id INT,item_name VARCHAR(255),size VARCHAR(10),quantity INT,country VARCHAR(50));
SELECT item_name, size, SUM(quantity) as total_quantity FROM clothing_inventory WHERE country = 'Canada' GROUP BY item_name, size ORDER BY total_quantity DESC LIMIT 1;
What is the percentage of mobile subscribers with 4G or 5G coverage in the 'subscriber_data' table?
CREATE TABLE subscriber_data (subscriber_id INT,plan_type VARCHAR(20),coverage VARCHAR(10)); INSERT INTO subscriber_data VALUES (1,'Basic','4G'),(2,'Premium','5G'),(3,'Basic','4G');
SELECT COUNT(*) * 100.0 / (SELECT COUNT(*) FROM subscriber_data) AS percentage FROM subscriber_data WHERE coverage IN ('4G', '5G');
Get products that are present in both 'products' and 'products_sustainability' tables
CREATE TABLE products (id INT,name TEXT,category TEXT);CREATE TABLE products_sustainability (id INT,name TEXT,sustainable_label TEXT);
SELECT * FROM products INNER JOIN products_sustainability ON products.id = products_sustainability.id;
What is the average age of all individuals from the 'ancient_burials' table?
CREATE TABLE ancient_burials (id INT,name VARCHAR(50),age INT,gender VARCHAR(10),grave_contents VARCHAR(255)); INSERT INTO ancient_burials (id,name,age,gender,grave_contents) VALUES (1,'John Doe',45,'Male','Pottery,coins');
SELECT AVG(age) FROM ancient_burials;
What is the average ticket price for each section in the stadium?
CREATE TABLE tickets (section VARCHAR(50),price DECIMAL(5,2)); INSERT INTO tickets (section,price) VALUES ('Section 101',50.00),('Section 201',40.00),('Section 301',35.00);
SELECT section, AVG(price) FROM tickets GROUP BY section;
Find the number of marine species in each ocean and the total number of marine species in the oceanography table.
CREATE TABLE marine_species_status (id INT,species_name VARCHAR(255),conservation_status VARCHAR(255),ocean VARCHAR(255)); INSERT INTO marine_species_status (id,species_name,conservation_status,ocean) VALUES (1,'Blue Whale','Endangered','Atlantic Ocean'),(2,'Blue Whale','Endangered','Pacific Ocean'); CREATE TABLE ocean...
SELECT ocean, COUNT(*) FROM marine_species_status GROUP BY ocean UNION ALL SELECT 'Total', COUNT(*) FROM marine_species_status;
What is the average budget for education projects in the 'education_projects' table?
CREATE TABLE education_projects (project VARCHAR(50),budget INT); INSERT INTO education_projects (project,budget) VALUES ('School Construction',20000000); INSERT INTO education_projects (project,budget) VALUES ('Teacher Training',5000000); INSERT INTO education_projects (project,budget) VALUES ('Curriculum Development'...
SELECT AVG(budget) FROM education_projects;
Display the 'vehicle_type' and 'safety_rating' where 'safety_rating' is greater than 4.0
CREATE TABLE vehicle_safety_test_results (id INT PRIMARY KEY,vehicle_type VARCHAR(255),safety_rating DECIMAL(3,2));
SELECT vehicle_type, safety_rating FROM vehicle_safety_test_results WHERE safety_rating > 4.0;
What is the total quantity of locally sourced ingredients used in each dish category?
CREATE TABLE Dishes (DishID INT,DishName VARCHAR(50),Category VARCHAR(50),LocallySourced INT,IngredientQTY INT,Price DECIMAL(5,2)); INSERT INTO Dishes (DishID,DishName,Category,LocallySourced,IngredientQTY,Price) VALUES (1,'Veggie Pizza','Pizza',1,500,12.99),(2,'Margherita Pizza','Pizza',0,300,10.99),(3,'Chicken Caesar...
SELECT Category, SUM(CASE WHEN LocallySourced = 1 THEN IngredientQTY ELSE 0 END) as TotalLocalIngredientQTY FROM Dishes GROUP BY Category;
What is the total number of international visitors to Japan in the last 12 months?
CREATE TABLE visitor_stats (visitor_id INT,country TEXT,visit_date DATE); INSERT INTO visitor_stats (visitor_id,country,visit_date) VALUES (1,'Japan','2022-01-01'),(2,'Japan','2022-02-14'),(3,'UK','2022-03-03');
SELECT COUNT(DISTINCT visitor_id) FROM visitor_stats WHERE country = 'Japan' AND visit_date >= DATEADD(month, -12, CURRENT_DATE);
Insert a new supplier from 'Mexico' with id 5
CREATE TABLE suppliers (id INT PRIMARY KEY,name VARCHAR(100),address VARCHAR(255),city VARCHAR(100),country VARCHAR(100));
INSERT INTO suppliers (id, name, address, city, country) VALUES (5, 'La Huerta', '456 Elm St', 'Mexico City', 'Mexico');
What is the total budget allocated for digital divide reduction programs in H1 and H2 of 2022?
CREATE TABLE Digital_Divide_Half_Year (half_year VARCHAR(10),budget FLOAT); INSERT INTO Digital_Divide_Half_Year (half_year,budget) VALUES ('H1 2022',12000000),('H1 2022',13000000),('H2 2022',14000000),('H2 2022',15000000);
SELECT Digital_Divide_Half_Year.half_year, SUM(Digital_Divide_Half_Year.budget) FROM Digital_Divide_Half_Year WHERE Digital_Divide_Half_Year.half_year IN ('H1 2022', 'H2 2022') GROUP BY Digital_Divide_Half_Year.half_year;
List all public transportation usage data for New York City
CREATE TABLE public_transportation (id INT PRIMARY KEY,location VARCHAR(100),type VARCHAR(100),passengers INT,year INT);
SELECT * FROM public_transportation WHERE location = 'New York City';
List military equipment types in the 'equipment_maintenance' table
CREATE TABLE equipment_maintenance (maintenance_id INT,equipment_type VARCHAR(50),maintenance_activity VARCHAR(100),maintenance_date DATE);
SELECT DISTINCT equipment_type FROM equipment_maintenance;
What is the percentage of community health workers that are male, female, and non-binary by state?
CREATE TABLE CommunityHealthWorkers (WorkerID INT,State VARCHAR(255),Gender VARCHAR(255)); INSERT INTO CommunityHealthWorkers (WorkerID,State,Gender) VALUES (1,'California','Male'),(2,'Texas','Female'),(3,'New York','Non-binary'),(4,'Florida','Male'),(5,'Illinois','Female');
SELECT State, Gender, COUNT(*) as WorkerCount, CONCAT(ROUND(COUNT(*) * 100.0 / (SELECT COUNT(*) FROM CommunityHealthWorkers GROUP BY State), 2), '%') as WorkerPercentage FROM CommunityHealthWorkers GROUP BY State, Gender;
How many military operations have been conducted by NATO and non-NATO countries?
CREATE TABLE MilitaryOperations (Country VARCHAR(255),Operation VARCHAR(255)); INSERT INTO MilitaryOperations (Country,Operation) VALUES ('NATO','Operation Allied Force'),('NATO','Operation Unified Protector'),('Non-NATO','Vietnam War'),('Non-NATO','Falklands War');
SELECT Operation FROM MilitaryOperations WHERE Country IN ('NATO', 'Non-NATO')
What is the count of clients with credit card accounts in the Atlanta branch?
CREATE TABLE clients (client_id INT,name TEXT,dob DATE,branch TEXT);CREATE TABLE accounts (account_id INT,client_id INT,account_type TEXT);INSERT INTO clients VALUES (2,'Jessica Smith','1995-06-28','Atlanta');INSERT INTO accounts VALUES (102,2,'Credit Card');
SELECT COUNT(*) FROM clients INNER JOIN accounts ON clients.client_id = accounts.client_id WHERE accounts.account_type = 'Credit Card' AND clients.branch = 'Atlanta';
Insert a new record into the 'authors' table with the name 'Alex Brown' and newspaper 'The Washington Post'
CREATE TABLE authors (id INT,name VARCHAR(50),newspaper VARCHAR(50));
INSERT INTO authors (name, newspaper) VALUES ('Alex Brown', 'The Washington Post');
Which countries have deployed the most satellites and the total number of satellites deployed?
CREATE SCHEMA Satellite;CREATE TABLE Satellite.SatelliteDeployment (country VARCHAR(50),num_satellites INT);INSERT INTO Satellite.SatelliteDeployment (country,num_satellites) VALUES ('USA',1200),('China',400),('Russia',350),('India',200);
SELECT country, SUM(num_satellites) AS total_satellites FROM Satellite.SatelliteDeployment GROUP BY country ORDER BY total_satellites DESC;
What is the total number of menu items sold in the Western region?
CREATE TABLE menu (menu_id INT,menu_name TEXT,menu_type TEXT,price DECIMAL,daily_sales INT,region TEXT);
SELECT SUM(daily_sales) FROM menu WHERE region = 'Western';
What is the average value of investments made in the technology sector?
CREATE TABLE investments (id INT,sector VARCHAR(20),date DATE,value FLOAT); INSERT INTO investments (id,sector,date,value) VALUES (1,'Technology','2018-01-01',100000.0),(2,'Finance','2016-01-01',75000.0),(3,'Technology','2017-01-01',125000.0);
SELECT AVG(value) FROM investments WHERE sector = 'Technology';
What is the total number of green buildings and their total floor area for each energy efficiency rating?
CREATE TABLE EnergyEfficiencyRatings (RatingID int,RatingName varchar(50)); CREATE TABLE GreenBuildings (BuildingID int,RatingID int,FloorArea int);
SELECT EnergyEfficiencyRatings.RatingName, COUNT(GreenBuildings.BuildingID) as TotalGreenBuildings, SUM(GreenBuildings.FloorArea) as TotalFloorArea FROM EnergyEfficiencyRatings INNER JOIN GreenBuildings ON EnergyEfficiencyRatings.RatingID = GreenBuildings.RatingID GROUP BY EnergyEfficiencyRatings.RatingName;
What is the total watch time for all movies by the director 'Christopher Nolan'?
CREATE TABLE directors (id INT,name VARCHAR(50)); INSERT INTO directors (id,name) VALUES (1,'Christopher Nolan'); CREATE TABLE movies (id INT,title VARCHAR(50),director_id INT,watch_time INT); INSERT INTO movies (id,title,director_id,watch_time) VALUES (1,'Inception',1,5000),(2,'Interstellar',1,6000);
SELECT SUM(watch_time) FROM movies WHERE director_id = (SELECT id FROM directors WHERE name = 'Christopher Nolan');
What is the average severity of vulnerabilities in the finance department?
CREATE TABLE vulnerabilities (id INT,department VARCHAR(255),severity FLOAT); INSERT INTO vulnerabilities (id,department,severity) VALUES (1,'finance',7.5),(2,'marketing',5.0),(3,'finance',8.0);
SELECT AVG(severity) FROM vulnerabilities WHERE department = 'finance';
Find the number of climate adaptation projects in Asia and Oceania that have been successful and their respective funding sources.
CREATE TABLE climate_adaptation (project_name VARCHAR(50),location VARCHAR(50),status VARCHAR(50),funding_source VARCHAR(50)); INSERT INTO climate_adaptation (project_name,location,status,funding_source) VALUES ('Resilient Cities','China','Successful','GCF'),('Green Infrastructure','Japan','Successful','ADB'),('Coastal...
SELECT status, funding_source FROM climate_adaptation WHERE location IN ('Asia', 'Oceania') AND status = 'Successful';
What is the average budget allocated for public libraries in the state of New York?
CREATE TABLE state_facilities (state VARCHAR(20),facility VARCHAR(20),budget INT); INSERT INTO state_facilities (state,facility,budget) VALUES ('New York','Public Library',800000);
SELECT AVG(budget) FROM state_facilities WHERE state = 'New York' AND facility = 'Public Library';
What is the average budget allocated to schools in each district?
CREATE TABLE districts (district_id INT,district_name VARCHAR(50),budget_allocation INT); INSERT INTO districts VALUES (1,'DistrictA',5000000),(2,'DistrictB',6000000),(3,'DistrictC',4500000); CREATE TABLE schools (school_id INT,school_name VARCHAR(50),district_id INT,budget_allocation INT); INSERT INTO schools VALUES (...
SELECT district_id, AVG(budget_allocation) as avg_budget FROM schools GROUP BY district_id;
Update the region of donors who have donated more than $5000 in the 'asia' region to 'emerging_market'.
CREATE TABLE donors (id INT,name TEXT,region TEXT,donation_amount FLOAT); INSERT INTO donors (id,name,region,donation_amount) VALUES (1,'John Doe','Asia',5000.00),(2,'Jane Smith','Europe',3000.00);
UPDATE donors SET region = 'Emerging_Market' WHERE region = 'Asia' AND donation_amount > 5000;
Show the number of new users who have joined each social media platform in the past month, broken down by age group (children, teenagers, adults, seniors).
CREATE TABLE users (user_id INT,platform VARCHAR(20),join_date DATE,age_group VARCHAR(20)); INSERT INTO users VALUES (1,'Instagram','2022-01-01','teenagers'),(2,'Facebook','2022-01-02','adults');
SELECT u.platform, u.age_group, COUNT(*) as num_users FROM users u WHERE u.join_date >= DATEADD(month, -1, GETDATE()) GROUP BY u.platform, u.age_group;
Update the 'completed' status to 'true' for the training program with program name 'Data Analysis' for the 'Finance' department
CREATE TABLE training_programs (id INT,department VARCHAR(20),program VARCHAR(50),date DATE,completed BOOLEAN); INSERT INTO training_programs (id,department,program,date,completed) VALUES (1,'Finance','Data Analysis','2022-01-01',false);
WITH t AS (UPDATE training_programs SET completed = true WHERE department = 'Finance' AND program = 'Data Analysis' RETURNING id) SELECT * FROM training_programs WHERE id IN (SELECT id FROM t);
How many successful satellite deployments were made by SpaceX in 2020?
CREATE TABLE satellite_deployments (id INT,company VARCHAR(50),launch_year INT,success BOOLEAN);
SELECT COUNT(*) FROM satellite_deployments WHERE company = 'SpaceX' AND launch_year = 2020 AND success = TRUE;
What is the percentage of co-owned properties in each neighborhood?
CREATE TABLE Neighborhoods (NeighborhoodID INT,NeighborhoodName VARCHAR(255)); CREATE TABLE Properties (PropertyID INT,NeighborhoodID INT,CoOwned BOOLEAN);
SELECT NeighborhoodName, AVG(CASE WHEN CoOwned = 1 THEN 100.0 ELSE 0.0 END) AS CoOwnedPercentage FROM Properties JOIN Neighborhoods ON Properties.NeighborhoodID = Neighborhoods.NeighborhoodID GROUP BY NeighborhoodName;
What is the combined capacity of all rural healthcare facilities in each state?
CREATE TABLE facilities (id INT,name TEXT,location TEXT,capacity INT); INSERT INTO facilities (id,name,location,capacity) VALUES (1,'Rural Upstate Health Center','New York',40),(2,'Rural Finger Lakes Clinic','New York',25),(3,'Rural Desert Health Center','Arizona',35),(4,'Rural Gulf Coast Clinic','Florida',20);
SELECT location, SUM(capacity) FROM facilities GROUP BY location;
What is the total number of streams and albums sold by artists who are from Africa?
CREATE TABLE Artists (ArtistID INT,ArtistName VARCHAR(100),Country VARCHAR(50)); INSERT INTO Artists (ArtistID,ArtistName,Country) VALUES (1,'Burna Boy','Nigeria'),(2,'Green Day','USA'); CREATE TABLE MusicStreams (StreamID INT,SongID INT,ArtistID INT); INSERT INTO MusicStreams (StreamID,SongID,ArtistID) VALUES (1,1,1),...
SELECT COUNT(DISTINCT ms.StreamID) + COUNT(DISTINCT a.AlbumID) AS TotalReleases FROM Artists a JOIN MusicStreams ms ON a.ArtistID = ms.ArtistID JOIN Albums al ON a.ArtistID = al.ArtistID WHERE Country IN ('Nigeria', 'Egypt', 'South Africa', 'Kenya', 'Algeria');
What is the average speed of high-speed trains in Tokyo?
CREATE TABLE high_speed_trains (train_id INT,speed FLOAT,city VARCHAR(50));
SELECT AVG(speed) FROM high_speed_trains WHERE city = 'Tokyo';
Show the total carbon sequestration for each country in 2020, with the countries sorted by the least amount.
CREATE TABLE carbon_sequestration (id INT PRIMARY KEY,country VARCHAR(50),year INT,sequestration INT);
SELECT country, SUM(sequestration) as total_sequestration FROM carbon_sequestration WHERE year = 2020 GROUP BY country ORDER BY total_sequestration ASC;
Which drugs were approved in 'RegionY' in 2018?
CREATE TABLE drug_approval(region varchar(20),year int,drug varchar(20));INSERT INTO drug_approval VALUES ('RegionY',2018,'DrugA');INSERT INTO drug_approval VALUES ('RegionY',2018,'DrugB');
SELECT DISTINCT drug FROM drug_approval WHERE region = 'RegionY' AND year = 2018;
Update contract status for negotiation ID 123
CREATE TABLE contracts(id INT,negotiation_id INT,status TEXT);INSERT INTO contracts(id,negotiation_id,status) VALUES (1,123,'pending');
WITH updated_status AS (UPDATE contracts SET status = 'completed' WHERE negotiation_id = 123) SELECT * FROM updated_status;
What is the average price of properties in a sustainable urbanism project in Atlanta with more than 1 co-owner?
CREATE TABLE property_prices (property_id INT,city VARCHAR(50),price INT); CREATE TABLE sustainable_urbanism (property_id INT,sustainable_project BOOLEAN); CREATE TABLE co_ownership (property_id INT,co_owner_count INT); INSERT INTO property_prices (property_id,city,price) VALUES (1,'Atlanta',500000),(2,'Portland',40000...
SELECT AVG(price) FROM property_prices p JOIN sustainable_urbanism s ON p.property_id = s.property_id JOIN co_ownership c ON p.property_id = c.property_id WHERE p.city = 'Atlanta' AND c.co_owner_count > 1;
How many different curators participated in art exhibitions in 2019?
CREATE TABLE Curators (id INT,name VARCHAR(50),exhibition_id INT);INSERT INTO Curators (id,name,exhibition_id) VALUES (1,'Alice',1),(2,'Bob',1),(3,'Carol',2),(4,'Dave',3),(5,'Alice',4);
SELECT COUNT(DISTINCT name) FROM Curators C INNER JOIN Exhibitions E ON C.exhibition_id = E.id WHERE E.year = 2019;
Identify dispensaries in California with the highest sales revenue for the "OG Kush" strain.
CREATE TABLE Dispensaries (id INT,name TEXT,state TEXT); INSERT INTO Dispensaries (id,name,state) VALUES (1,'Green Leaf','California'),(2,'Buds R Us','California'),(3,'Happy High','Colorado'),(4,'Cannabis Corner','Colorado'); CREATE TABLE Sales (dispensary_id INT,strain TEXT,quantity INT,revenue DECIMAL); INSERT INTO S...
SELECT Dispensaries.name, SUM(Sales.revenue) as total_revenue FROM Dispensaries INNER JOIN Sales ON Dispensaries.id = Sales.dispensary_id WHERE strain = 'OG Kush' AND state = 'California' GROUP BY Dispensaries.name ORDER BY total_revenue DESC LIMIT 1;
What was the total revenue generated from users in the United States for Q1 2022?
CREATE TABLE if not exists revenue (user_id INT,country VARCHAR(50),revenue FLOAT,quarter INT,year INT); INSERT INTO revenue (user_id,country,revenue,quarter,year) VALUES (1,'United States',50.00,1,2022),(2,'Canada',30.00,1,2022);
SELECT SUM(revenue) FROM revenue WHERE country = 'United States' AND quarter = 1 AND year = 2022;
Update the carbon pricing data to include a 5% increase in price for March 2022.
CREATE TABLE carbon_prices (date DATE,price FLOAT); INSERT INTO carbon_prices (date,price) VALUES ('2021-01-01',25),('2021-01-02',26),('2021-01-03',27),('2021-02-01',28),('2021-02-02',29),('2021-02-03',30),('2021-03-01',31),('2021-03-02',32),('2021-03-03',33);
UPDATE carbon_prices SET price = price * 1.05 WHERE date >= '2022-03-01';
Determine the maximum number of days between two security incidents in the IT department in 2022
CREATE TABLE incidents (id INT,department VARCHAR(255),date DATE); INSERT INTO incidents (id,department,date) VALUES (1,'IT','2022-01-01'); INSERT INTO incidents (id,department,date) VALUES (2,'IT','2022-01-05');
SELECT DATEDIFF(MAX(date), MIN(date)) as max_days_between_incidents FROM incidents WHERE department = 'IT' AND YEAR(date) = 2022;
What is the previous offset amount for each carbon offset initiative, starting with the initiative that began on 2021-01-01?
CREATE TABLE carbon_offset_initiatives (id INT,project_name VARCHAR(255),location VARCHAR(255),offset_amount INT,start_date DATE,end_date DATE); INSERT INTO carbon_offset_initiatives (id,project_name,location,offset_amount,start_date,end_date) VALUES (1,'Tree Planting','New York',5000,'2020-01-01','2022-12-31'); INSERT...
SELECT project_name, location, offset_amount, start_date, LAG(offset_amount) OVER (ORDER BY start_date) as previous_offset_amount FROM carbon_offset_initiatives WHERE start_date >= '2021-01-01';
Insert a new Green building project 'ProjectE' in France with renewable energy source 'Wind'.
CREATE TABLE green_buildings (project_name VARCHAR(50),country VARCHAR(50),renewable_energy_source VARCHAR(50));
INSERT INTO green_buildings (project_name, country, renewable_energy_source) VALUES ('ProjectE', 'France', 'Wind');
What is the total amount donated by each donor in the year 2020, ordered by the total donation amount in descending order?
CREATE TABLE Donors (DonorID INT,DonorName TEXT,TotalDonation DECIMAL); CREATE TABLE Donations (DonationID INT,DonorID INT,DonationDate DATE,DonationAmount DECIMAL);
SELECT D.DonorName, SUM(D.DonationAmount) as TotalDonation FROM Donations D JOIN Donors DON ON D.DonorID = DON.DonorID WHERE YEAR(D.DonationDate) = 2020 GROUP BY D.DonorName ORDER BY TotalDonation DESC;
Which spacecraft have a mass greater than 1200 tons?
CREATE TABLE SpacecraftData (id INT,name VARCHAR(50),manufacturer VARCHAR(50),mass FLOAT); INSERT INTO SpacecraftData (id,name,manufacturer,mass) VALUES (1,'Saturn V','NASA',3000),(2,'Space Shuttle','NASA',2000),(3,'Proton-M','Russia',1100),(4,'Long March 5','China',1700);
SELECT name, manufacturer, mass FROM SpacecraftData WHERE mass > 1200;
What is the maximum salary paid to a worker in each factory?
CREATE TABLE factories(factory_id INT,name TEXT,location TEXT); CREATE TABLE workers(worker_id INT,name TEXT,salary DECIMAL,factory_id INT);
SELECT f.name, MAX(w.salary) as max_salary FROM factories f JOIN workers w ON f.factory_id = w.factory_id GROUP BY f.name;
What is the average word count of articles published in the "opinion" category?
CREATE TABLE articles (id INT,title VARCHAR(100),word_count INT,publication_date DATE,category VARCHAR(50));
SELECT AVG(word_count) FROM articles WHERE category = 'opinion';
What is the number of online course enrollments by institution, course type, and student gender?
CREATE TABLE institutions (id INT,name VARCHAR(50),type VARCHAR(20)); INSERT INTO institutions (id,name,type) VALUES (1,'University X','Public'),(2,'College Y','Private'),(3,'Institute Z','Private'); CREATE TABLE enrollments (id INT,institution_id INT,course_type VARCHAR(20),student_count INT,student_gender VARCHAR(10)...
SELECT i.name, e.course_type, e.student_gender, SUM(e.student_count) as total_enrolled FROM institutions i JOIN enrollments e ON i.id = e.institution_id GROUP BY i.name, e.course_type, e.student_gender;
What is the total area of all protected forests in the United States?
CREATE TABLE forests (id INT,name TEXT,area REAL,country TEXT); INSERT INTO forests (id,name,area,country) VALUES (1,'Green Mountain National Forest',398222.0,'United States'),(2,'White Mountain National Forest',750690.0,'United States');
SELECT SUM(area) FROM forests WHERE country = 'United States' AND category = 'protected';
What is the number of IoT devices with anomalous readings in the past week?
CREATE TABLE iot_anomaly (id INT,device_id INT,anomaly VARCHAR(255),anomaly_timestamp DATETIME); INSERT INTO iot_anomaly (id,device_id,anomaly,anomaly_timestamp) VALUES (1,1001,'High','2022-02-20 15:30:00'),(2,1002,'Low','2022-02-23 09:45:00'),(3,1003,'High','2022-02-27 12:00:00');
SELECT COUNT(*) FROM iot_anomaly WHERE anomaly IN ('High', 'Low') AND anomaly_timestamp >= DATEADD(week, -1, CURRENT_TIMESTAMP);