instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
How many FPS games were sold in the EU region in 2021?
CREATE TABLE GameSales (GameID INT PRIMARY KEY,GameType VARCHAR(20),Region VARCHAR(10),SalesYear INT); INSERT INTO GameSales (GameID,GameType,Region,SalesYear) VALUES (1,'FPS','EU',2021); INSERT INTO GameSales (GameID,GameType,Region,SalesYear) VALUES (2,'RPG','NA',2020);
SELECT COUNT(*) FROM GameSales WHERE GameType = 'FPS' AND Region = 'EU' AND SalesYear = 2021;
Show the total revenue for each genre of games
CREATE TABLE Games (game_id INT,game_name VARCHAR(100),genre VARCHAR(50),revenue INT); INSERT INTO Games (game_id,game_name,genre,revenue) VALUES (1,'GameA','Action',50000),(2,'GameB','Adventure',40000),(3,'GameC','Strategy',45000),(4,'GameD','Action',60000),(5,'GameE','Adventure',55000);
SELECT genre, SUM(revenue) AS total_revenue FROM Games GROUP BY genre;
How many climate mitigation projects were initiated in African countries between 2015 and 2018?
CREATE TABLE climate_projects (year INT,region VARCHAR(255),type VARCHAR(255),count INT); INSERT INTO climate_projects (year,region,type,count) VALUES (2015,'Africa','climate mitigation',120); INSERT INTO climate_projects (year,region,type,count) VALUES (2016,'Africa','climate mitigation',150); INSERT INTO climate_projects (year,region,type,count) VALUES (2017,'Africa','climate mitigation',180); INSERT INTO climate_projects (year,region,type,count) VALUES (2018,'Africa','climate mitigation',200);
SELECT SUM(count) FROM climate_projects WHERE year BETWEEN 2015 AND 2018 AND region = 'Africa' AND type = 'climate mitigation';
What are the names and total cargo weights for all shipments that share a warehouse with shipment ID 12345?
CREATE TABLE Warehouses (WarehouseID int,WarehouseName varchar(50)); CREATE TABLE Shipments (ShipmentID int,WarehouseID int,CargoWeight int); INSERT INTO Warehouses VALUES (1,'WarehouseA'),(2,'WarehouseB'),(3,'WarehouseC'); INSERT INTO Shipments VALUES (12345,1,5000),(67890,1,7000),(11121,2,6000),(22232,3,8000)
SELECT Warehouses.WarehouseName, SUM(Shipments.CargoWeight) as TotalCargoWeight FROM Warehouses INNER JOIN Shipments ON Warehouses.WarehouseID = Shipments.WarehouseID WHERE Shipments.ShipmentID <> 12345 AND Warehouses.WarehouseID = (SELECT WarehouseID FROM Shipments WHERE ShipmentID = 12345) GROUP BY Warehouses.WarehouseName;
What is the minimum gas price for transactions in the last 7 days?
CREATE TABLE transactions (id INT,transaction_hash VARCHAR(255),gas_price INT,timestamp TIMESTAMP); INSERT INTO transactions (id,transaction_hash,gas_price,timestamp) VALUES (1,'0x123...',10,'2022-02-01 00:00:00'),(2,'0x456...',12,'2022-02-02 12:34:56'),(3,'0x789...',8,'2022-02-09 14:23:01');
SELECT MIN(gas_price) as min_gas_price FROM transactions WHERE timestamp >= DATE_SUB(NOW(), INTERVAL 7 DAY);
What is the percentage of patients who identified as LGBTQ+ and experienced improvement after therapy?
CREATE TABLE patients (id INT,age INT,gender VARCHAR(50),sexual_orientation VARCHAR(50),therapy_date DATE,improvement BOOLEAN);
SELECT (COUNT(*) * 100.0 / (SELECT COUNT(*) FROM patients WHERE sexual_orientation LIKE '%LGBTQ%' AND therapy_date IS NOT NULL)) as percentage FROM patients WHERE sexual_orientation LIKE '%LGBTQ%' AND improvement = TRUE;
What is the average number of visitors to heritage sites in European countries?
CREATE TABLE HeritageSitesEurope (site_name VARCHAR(50),country VARCHAR(50),visitors INT); INSERT INTO HeritageSitesEurope (site_name,country,visitors) VALUES ('Acropolis','Greece',2000000),('Colosseum','Italy',4000000),('Tower of London','England',3000000);
SELECT AVG(visitors) FROM HeritageSitesEurope WHERE country IN ('Greece', 'Italy', 'England') AND region = 'Europe';
What was the total oil production in Q1 2020 for wells in the North Sea?
CREATE TABLE wells (well_id INT,well_name VARCHAR(50),oil_production FLOAT,gas_production FLOAT,location VARCHAR(50)); INSERT INTO wells (well_id,well_name,oil_production,gas_production,location) VALUES (1,'Well A',1500,2000,'North Sea'),(2,'Well B',1200,1800,'North Sea');
SELECT SUM(oil_production) FROM wells WHERE location = 'North Sea' AND EXTRACT(MONTH FROM timestamp) BETWEEN 1 AND 3 AND EXTRACT(YEAR FROM timestamp) = 2020;
What is the average funding amount per round for startups in the healthcare industry?
CREATE TABLE companies (id INT,name VARCHAR(50),founding_date DATE,industry VARCHAR(20)); CREATE TABLE investment_rounds (id INT,company_id INT,round_type VARCHAR(20),funding_amount INT);
SELECT AVG(funding_amount) FROM investment_rounds ir JOIN companies c ON ir.company_id = c.id WHERE c.industry = 'Healthcare';
What is the number of movies and TV shows produced in each country, and the total runtime for each, in 2018?
CREATE TABLE media_content (id INT,title VARCHAR(255),release_year INT,runtime INT,genre VARCHAR(255),format VARCHAR(50),country VARCHAR(255));
SELECT country, format, COUNT(*), SUM(runtime) FROM media_content WHERE release_year = 2018 GROUP BY country, format;
What is the annual CO2 emission for each mining operation?
CREATE TABLE mining_operation (operation_id INT,operation_name TEXT,year INT,co2_emission INT);
SELECT operation_name, co2_emission, year FROM mining_operation;
What is the average number of climate change adaptation projects per year in the Middle East from 2010 to 2020?
CREATE TABLE adaptation_projects (id INT,region VARCHAR(255),year INT,type VARCHAR(255),cost FLOAT); INSERT INTO adaptation_projects (id,region,year,type,cost) VALUES (1,'Middle East',2010,'climate change adaptation',300000);
SELECT AVG(cost) FROM adaptation_projects WHERE region = 'Middle East' AND type = 'climate change adaptation' AND year BETWEEN 2010 AND 2020;
Display the number of 5-star hotels and their sustainable certifications in Oceania.
CREATE TABLE hotels (hotel_id INT,name TEXT,country TEXT,stars INT,is_sustainable BOOLEAN); CREATE TABLE countries (country_id INT,name TEXT,region TEXT);
SELECT h.country, SUM(h.stars = 5) AS five_star_hotels, SUM(h.is_sustainable) AS sustainable_certifications FROM hotels h WHERE h.country IN (SELECT name FROM countries WHERE region = 'Oceania') GROUP BY h.country;
What is the average property price in eco-friendly neighborhoods in Seattle?
CREATE TABLE Seattle_Neighborhoods (Neighborhood VARCHAR(255),IsEcoFriendly BOOLEAN); INSERT INTO Seattle_Neighborhoods (Neighborhood,IsEcoFriendly) VALUES ('Ballard',true),('Fremont',false),('Capitol Hill',true),('West Seattle',false); CREATE TABLE Properties (Neighborhood VARCHAR(255),Price INT); INSERT INTO Properties (Neighborhood,Price) VALUES ('Ballard',750000),('Fremont',825000),('Capitol Hill',650000),('West Seattle',900000);
SELECT AVG(Properties.Price) FROM Properties INNER JOIN Seattle_Neighborhoods ON Properties.Neighborhood = Seattle_Neighborhoods.Neighborhood WHERE Seattle_Neighborhoods.IsEcoFriendly = true;
What are the total greenhouse gas emissions of chemical manufacturers in the US and Canada?
CREATE TABLE chemical_manufacturers (manufacturer_id INT,name VARCHAR(255),country VARCHAR(255)); INSERT INTO chemical_manufacturers (manufacturer_id,name,country) VALUES (1,'ManufacturerA','USA'),(2,'ManufacturerB','Canada'),(3,'ManufacturerC','USA'); CREATE TABLE emissions (emission_id INT,manufacturer_id INT,gas_type VARCHAR(255),amount INT); INSERT INTO emissions (emission_id,manufacturer_id,gas_type,amount) VALUES (1,1,'CO2',1000),(2,1,'CH4',200),(3,2,'CO2',1500),(4,3,'CO2',1200),(5,3,'CH4',300)
SELECT cm.name, SUM(e.amount) FROM chemical_manufacturers cm JOIN emissions e ON cm.manufacturer_id = e.manufacturer_id WHERE cm.country IN ('USA', 'Canada') AND e.gas_type = 'CO2' GROUP BY cm.name
What is the total number of police officers in each station?
CREATE TABLE Station (sid INT,name VARCHAR(255),type VARCHAR(255)); CREATE TABLE Employee (eid INT,sid INT,role VARCHAR(255));
SELECT Station.name, SUM(CASE WHEN Employee.role = 'police officer' THEN 1 ELSE 0 END) as total_police FROM Station INNER JOIN Employee ON Station.sid = Employee.sid GROUP BY Station.name;
What is the total sales revenue for products sourced from fair trade suppliers in the last year?
CREATE TABLE products (product_id INT,product_name VARCHAR(255),supplier_type VARCHAR(255),sales FLOAT,sale_date DATE); INSERT INTO products (product_id,product_name,supplier_type,sales,sale_date) VALUES (1,'Organic Cotton Shirt','Fair Trade',50,'2022-01-01'),(2,'Recycled Tote Bag','Fair Trade',30,'2022-01-02'),(3,'Eco-Friendly Notebook','Direct',75,'2022-01-03');
SELECT SUM(sales) FROM products WHERE supplier_type = 'Fair Trade' AND sale_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR);
Update the number of mental health parity violations in Texas to 18.
CREATE TABLE mental_health_parity (state VARCHAR(2),violations INT); INSERT INTO mental_health_parity (state,violations) VALUES ('CA',25),('NY',30),('TX',15);
UPDATE mental_health_parity SET violations = 18 WHERE state = 'TX';
Insert a new record with date '2022-03-01' and temperature 24.0 in the AquaticFarm table.
CREATE TABLE AquaticFarm (date DATE,temperature FLOAT);
INSERT INTO AquaticFarm (date, temperature) VALUES ('2022-03-01', 24.0);
What is the maximum sentiment score of an article in the algorithmic fairness domain?
CREATE TABLE articles (id INT,title VARCHAR(100),sentiment FLOAT,domain VARCHAR(50)); INSERT INTO articles (id,title,sentiment,domain) VALUES (1,'Algorithmic Fairness: Achieving Equity in AI',0.8,'Algorithmic Fairness'),(2,'The Challenges of AI Safety',0.6,'AI Safety'),(3,'The Future of Creative AI',0.9,'Creative AI');
SELECT MAX(articles.sentiment) FROM articles WHERE articles.domain = 'Algorithmic Fairness';
What are the top 5 most visited museums by international tourists?
CREATE TABLE museums (id INT,name TEXT,city TEXT);CREATE TABLE museum_visitors (id INT,visitor_id INT,museum_id INT,country TEXT);CREATE TABLE visitors (id INT,name TEXT);
SELECT m.name, COUNT(mv.visitor_id) as num_visitors FROM museums m JOIN museum_visitors mv ON m.id = mv.museum_id JOIN visitors v ON mv.visitor_id = v.id WHERE v.country != 'USA' GROUP BY m.name ORDER BY num_visitors DESC LIMIT 5;
List the number of new members acquired per week for the first half of 2021, excluding members from the "West" region.
CREATE TABLE membership (member_id INT,join_date DATE,region VARCHAR(20),PRIMARY KEY (member_id)); INSERT INTO membership (member_id,join_date,region) VALUES (1,'2021-01-01','East'),(2,'2021-01-02','West'),(3,'2021-02-01','North');
SELECT DATE_FORMAT(join_date, '%Y-%u') as week, COUNT(*) as new_members FROM membership WHERE region != 'West' AND join_date >= '2021-01-01' AND join_date < '2021-07-01' GROUP BY week;
What is the total inventory value of non-vegetarian dishes sold on a given date?
CREATE TABLE dishes (id INT,name TEXT,type TEXT,price DECIMAL,inventory INT); INSERT INTO dishes (id,name,type,price,inventory) VALUES (1,'Pizza Margherita','Veg',7.50,50),(2,'Chicken Alfredo','Non-Veg',12.00,30),(3,'Veggie Delight Sandwich','Veg',6.50,75); CREATE TABLE sales (id INT,dish_id INT,quantity INT,date DATE); INSERT INTO sales (id,dish_id,quantity,date) VALUES (1,2,3,'2022-01-01'),(2,1,2,'2022-01-02'),(3,3,1,'2022-01-03');
SELECT SUM(d.price * d.inventory * s.quantity) as total_inventory_value FROM dishes d INNER JOIN sales s ON d.id = s.dish_id WHERE d.type = 'Non-Veg' AND s.date = '2022-01-01';
Update the feeding habits of the 'Basking Shark' to 'Filter Feeder' in the North Atlantic.
CREATE TABLE marine_species (id INT,species VARCHAR(50),ocean VARCHAR(50),feeding_habits VARCHAR(50));
UPDATE marine_species SET feeding_habits = 'Filter Feeder' WHERE species = 'Basking Shark' AND ocean = 'North Atlantic';
Find the top 3 states with the highest veteran employment rate in 2021
CREATE TABLE veteran_employment_rates (state VARCHAR(255),year INT,employment_rate FLOAT); INSERT INTO veteran_employment_rates (state,year,employment_rate) VALUES ('CA',2021,0.8); INSERT INTO veteran_employment_rates (state,year,employment_rate) VALUES ('NY',2021,0.7); INSERT INTO veteran_employment_rates (state,year,employment_rate) VALUES ('TX',2021,0.9);
SELECT state, employment_rate FROM veteran_employment_rates WHERE year = 2021 ORDER BY employment_rate DESC LIMIT 3;
What is the average number of likes per post for the 'social_media' table, assuming the 'likes' column is of type INTEGER?
CREATE TABLE social_media (user_id INT,post_id INT,post_date DATE,likes INT);
SELECT AVG(likes) FROM social_media;
What is the total recyclability rating of materials from Mexico and Canada?
CREATE TABLE materials (id INT PRIMARY KEY,name VARCHAR(255),origin VARCHAR(255),recyclability_rating FLOAT); INSERT INTO materials (id,name,origin,recyclability_rating) VALUES (1,'Recycled Plastic','Mexico',4.6),(2,'Reused Metal','Canada',4.5),(3,'Eco-Friendly Paper','Mexico',4.7);
SELECT SUM(recyclability_rating) FROM materials WHERE origin IN ('Mexico', 'Canada');
Find the total biomass of fish in the sustainable_seafood_trends_3 table for each fishing_method.
CREATE TABLE sustainable_seafood_trends_3 (fishing_method VARCHAR(255),biomass FLOAT); INSERT INTO sustainable_seafood_trends_3 (fishing_method,biomass) VALUES ('Line Fishing',600),('Trawling',800),('Potting',700);
SELECT fishing_method, SUM(biomass) FROM sustainable_seafood_trends_3 GROUP BY fishing_method;
What are the top 5 most common vulnerabilities in the ThreatIntel database?
CREATE TABLE ThreatIntel (id INT,vulnerability VARCHAR(255),frequency INT); INSERT INTO ThreatIntel (id,vulnerability,frequency) VALUES (1,'CVE-2019-12345',25),(2,'CVE-2020-67890',18),(3,'CVE-2021-09876',15),(4,'CVE-2018-32100',14),(5,'CVE-2022-23456',13);
SELECT vulnerability, frequency FROM (SELECT vulnerability, frequency, ROW_NUMBER() OVER (ORDER BY frequency DESC) AS rank FROM ThreatIntel) AS ranked_vulnerabilities WHERE rank <= 5;
List all donors who have donated more than $1000 in total
CREATE TABLE donors (id INT,name VARCHAR(50)); CREATE TABLE donations (id INT,donor_id INT,amount DECIMAL(10,2));
SELECT d.name FROM donors d JOIN donations don ON d.id = donations.donor_id GROUP BY d.name HAVING SUM(donations.amount) > 1000;
What is the average product price per brand, ordered by the average price?
CREATE TABLE products (product_id INT,product_name VARCHAR(255),brand VARCHAR(255),price DECIMAL(10,2)); INSERT INTO products VALUES (1,'ProductA','BrandX',50),(2,'ProductB','BrandX',75),(3,'ProductC','BrandY',60);
SELECT brand, AVG(price) as avg_price FROM products GROUP BY brand ORDER BY avg_price DESC;
What is the total funding received by biotech startups in California, Texas, and New York?
CREATE SCHEMA if not exists biotech; CREATE TABLE if not exists biotech.startups (id INT,name VARCHAR(50),location VARCHAR(50),funding DECIMAL(10,2)); INSERT INTO biotech.startups (id,name,location,funding) VALUES (1,'Genentech','California',5000000.00),(2,'Celgene','New Jersey',7000000.00),(3,'Ambry Genetics','California',3000000.00),(4,'Myriad Genetics','Texas',4000000.00);
SELECT SUM(funding) FROM biotech.startups WHERE location IN ('California', 'Texas', 'New York');
Compare the number of wells drilled in the USA and Canada.
CREATE TABLE wells (well_id INT,country VARCHAR(50)); INSERT INTO wells (well_id,country) VALUES (1,'Canada'),(2,'USA'),(3,'Norway');
SELECT 'Canada' as country, COUNT(*) as num_wells FROM wells WHERE country = 'Canada' UNION ALL SELECT 'USA' as country, COUNT(*) as num_wells FROM wells WHERE country = 'USA';
What are the names of clinics that do not offer diabetes treatment?
CREATE TABLE clinics (id INT,name TEXT,diabetes_treatment BOOLEAN); INSERT INTO clinics VALUES (1,'Rural Clinic A',FALSE); INSERT INTO clinics VALUES (2,'Rural Clinic B',TRUE); INSERT INTO clinics VALUES (3,'Rural Clinic C',FALSE);
SELECT name FROM clinics WHERE diabetes_treatment = FALSE;
What are the names of virtual tours in Paris with a rating above 4.5?
CREATE TABLE tours (id INT,name TEXT,city TEXT,rating FLOAT); INSERT INTO tours (id,name,city,rating) VALUES (1,'Paris Tour 1','Paris',4.7),(2,'Paris Tour 2','Paris',4.3);
SELECT name FROM tours WHERE city = 'Paris' AND rating > 4.5;
Insert a new wind energy project 'Windfarm 2' in Germany with an installed capacity of 200 MW.
CREATE TABLE wind_energy (project_id INT,project_name VARCHAR(255),country VARCHAR(255),installed_capacity FLOAT);
INSERT INTO wind_energy (project_name, country, installed_capacity) VALUES ('Windfarm 2', 'Germany', 200);
Delete all records from the "ocean_temperature" table where the temperature is above 30 degrees Celsius
CREATE TABLE ocean_temperature (id INT PRIMARY KEY,location VARCHAR(255),temperature FLOAT); INSERT INTO ocean_temperature (id,location,temperature) VALUES (1,'Pacific Ocean',28.5); INSERT INTO ocean_temperature (id,location,temperature) VALUES (2,'Atlantic Ocean',29.8);
DELETE FROM ocean_temperature WHERE temperature > 30;
What is the total installed capacity of wind energy projects in each country, sorted by the total capacity in descending order?
CREATE TABLE wind_projects (id INT,country VARCHAR(50),capacity FLOAT);
SELECT country, SUM(capacity) as total_capacity FROM wind_projects GROUP BY country ORDER BY total_capacity DESC;
Find the number of unique attendees who attended both 'Music Festival' and 'Music Concert'.
CREATE TABLE attendee_demographics (attendee_id INT,attendee_name VARCHAR(50),attendee_age INT); INSERT INTO attendee_demographics (attendee_id,attendee_name,attendee_age) VALUES (1,'Jane Smith',25),(2,'Michael Johnson',17),(3,'Sophia Rodriguez',16),(4,'David Kim',22); CREATE TABLE event_attendance (attendee_id INT,event_name VARCHAR(50)); INSERT INTO event_attendance (attendee_id,event_name) VALUES (1,'Music Festival'),(2,'Music Concert'),(3,'Music Festival'),(4,'Music Concert'),(5,'Music Festival'),(1,'Music Concert');
SELECT COUNT(DISTINCT attendee_id) FROM event_attendance WHERE event_name IN ('Music Festival', 'Music Concert') GROUP BY attendee_id HAVING COUNT(DISTINCT event_name) = 2;
How many grants were awarded to faculty members in the Mathematics department in 2020 and 2021?
CREATE TABLE Grants (GrantID INT,AwardYear INT,Department VARCHAR(50),Amount DECIMAL(10,2)); INSERT INTO Grants (GrantID,AwardYear,Department,Amount) VALUES (1,2020,'Mathematics',50000),(2,2021,'Physics',60000),(3,2020,'Mathematics',55000),(4,2021,'Computer Science',70000);
SELECT COUNT(*) FROM Grants WHERE Department = 'Mathematics' AND AwardYear IN (2020, 2021);
List all the vessels that have had an incident in the last 5 years.
CREATE TABLE vessel_incident (id INT,vessel_id INT,incident_date DATE);
SELECT v.name FROM vessel_incident vi JOIN vessel v ON vi.vessel_id = v.id WHERE vi.incident_date >= DATE_SUB(CURRENT_DATE, INTERVAL 5 YEAR);
How many safety incidents were reported in the chemical plant last year?
CREATE TABLE safety_incidents (incident_id INT,incident_date DATE); INSERT INTO safety_incidents (incident_id,incident_date) VALUES (1,'2021-02-01'),(2,'2021-05-15'),(3,'2021-08-20'),(4,'2020-12-10');
SELECT COUNT(*) FROM safety_incidents WHERE incident_date BETWEEN '2021-01-01' AND '2021-12-31';
What is the difference in ocean health metrics between freshwater and marine aquaculture sites?
CREATE TABLE ocean_health_metrics (site_id INT,site_type VARCHAR(50),metric_name VARCHAR(50),value FLOAT); INSERT INTO ocean_health_metrics VALUES (1,'Freshwater','pH',7.8),(2,'Marine','pH',8.1),(3,'Freshwater','Salinity',1.2),(4,'Marine','Salinity',3.5),(5,'Freshwater','Temperature',15.5),(6,'Marine','Temperature',18.0);
SELECT site_type, metric_name, AVG(value) AS avg_value FROM ocean_health_metrics GROUP BY site_type, metric_name;
What is the total waste generation by businesses in the city of San Francisco?
CREATE TABLE waste_generation (id INT,business_name TEXT,city TEXT,waste_quantity INT); INSERT INTO waste_generation (id,business_name,city,waste_quantity) VALUES (1,'Business A','San Francisco',500),(2,'Business B','San Francisco',750);
SELECT SUM(waste_quantity) FROM waste_generation WHERE city = 'San Francisco' AND business_name IS NOT NULL;
How many volunteers participated in the "Human Rights" program in each month of 2020, broken down by gender?
CREATE TABLE Volunteers (id INT,volunteer VARCHAR(50),program VARCHAR(50),gender VARCHAR(10),volunteer_date DATE); INSERT INTO Volunteers (id,volunteer,program,gender,volunteer_date) VALUES (1,'Jane Doe','Human Rights','Female','2020-01-01');
SELECT EXTRACT(MONTH FROM volunteer_date) AS Month, gender, COUNT(volunteer) AS Volunteer_Count FROM Volunteers WHERE program = 'Human Rights' AND YEAR(volunteer_date) = 2020 GROUP BY Month, gender;
What is the average distance traveled for healthcare access for Indigenous communities in Canada?
CREATE TABLE healthcare_access (patient_id INT,community VARCHAR(20),distance FLOAT); INSERT INTO healthcare_access (patient_id,community,distance) VALUES (1,'Indigenous',50.5); INSERT INTO healthcare_access (patient_id,community,distance) VALUES (2,'Non-Indigenous',20.3);
SELECT AVG(distance) FROM healthcare_access WHERE community = 'Indigenous';
Insert a new record in the restaurant_menu table for 'Vegetarian Biryani' dish under 'Indian Cuisine' category.
CREATE TABLE restaurant_menu (dish VARCHAR(255),category VARCHAR(255),price DECIMAL(10,2)); INSERT INTO restaurant_menu (dish,category,price) VALUES ('Veg Samosas','Indian Cuisine',5.50); INSERT INTO restaurant_menu (dish,category,price) VALUES ('Chicken Tikka Masala','Indian Cuisine',12.99);
INSERT INTO restaurant_menu (dish, category, price) VALUES ('Vegetarian Biryani', 'Indian Cuisine', 10.99);
List all disaster preparedness events and their corresponding locations in the 'Northside' district.
CREATE TABLE events (event_id INT,event_name TEXT,location_id INT); CREATE TABLE locations (location_id INT,district_id INT,location_text TEXT);
SELECT e.event_name, l.location_text FROM events e INNER JOIN locations l ON e.location_id = l.location_id WHERE l.district_id = (SELECT district_id FROM districts WHERE district_name = 'Northside');
What is the total capacity of green hotels in India?
CREATE TABLE IF NOT EXISTS hotels (id INT PRIMARY KEY,name TEXT,country TEXT,is_green BOOLEAN,capacity INT); INSERT INTO hotels (id,name,country,is_green,capacity) VALUES (1,'EcoHotel','India',true,200),(2,'LuxuryHotel','UAE',false,500),(3,'GreenResort','India',true,300);
SELECT SUM(capacity) FROM hotels WHERE is_green = true AND country = 'India';
Insert a new employee record into the 'employees' table
CREATE TABLE employees (id INT PRIMARY KEY,first_name VARCHAR(50),last_name VARCHAR(50),department VARCHAR(50),hire_date DATE);
INSERT INTO employees (id, first_name, last_name, department, hire_date) VALUES (101, 'Jamila', 'Garcia', 'Marketing', '2022-04-11');
What is the percentage of organic fruits imported from Egypt?
CREATE TABLE imports (id INT,product TEXT,is_organic BOOLEAN,country TEXT); INSERT INTO imports (id,product,is_organic,country) VALUES (1,'Apples',true,'Egypt'); INSERT INTO imports (id,product,is_organic,country) VALUES (2,'Oranges',false,'Egypt'); INSERT INTO imports (id,product,is_organic,country) VALUES (3,'Bananas',true,'Egypt');
SELECT (COUNT(*) FILTER (WHERE is_organic = true) * 100.0 / (SELECT COUNT(*) FROM imports WHERE country = 'Egypt')) FROM imports WHERE product = 'Apples' OR product = 'Bananas' AND country = 'Egypt';
Find the top 3 states with the highest number of COVID-19 cases?
CREATE TABLE covid_data (state VARCHAR(255),cases INT); INSERT INTO covid_data (state,cases) VALUES ('State A',1000),('State B',2000),('State C',1500),('State D',2500),('State E',3000);
SELECT state, cases, RANK() OVER (ORDER BY cases DESC) as rank FROM covid_data WHERE rank <= 3;
Insert a new record for a community health worker with ethnicity 'Asian'.
CREATE TABLE community_health_workers (id INT,name VARCHAR,age INT,ethnicity VARCHAR);
INSERT INTO community_health_workers (name, age, ethnicity) VALUES ('Mike Lee', 30, 'Asian');
Count the total number of members in each union having a safety_rating greater than 8.5.
CREATE TABLE Union_Members (union_id INT,member_id INT,safety_rating FLOAT); INSERT INTO Union_Members (union_id,member_id,safety_rating) VALUES (1,101,8.75),(1,102,9.25),(2,201,7.50),(2,202,8.75);
SELECT union_id, COUNT(member_id) FROM Union_Members WHERE safety_rating > 8.5 GROUP BY union_id;
Update the donation amount to $9000 for donor_id 4.
CREATE TABLE donors (donor_id INT,donation_amount DECIMAL(10,2),donation_year INT,gender VARCHAR(10)); INSERT INTO donors (donor_id,donation_amount,donation_year,gender) VALUES (1,5000.00,2020,'female'),(2,3000.00,2019,'male'),(3,7000.00,2020,'non-binary'),(4,8000.00,2021,'non-binary');
UPDATE donors SET donation_amount = 9000 WHERE donor_id = 4;
List all campaigns in New York that started after 2018
CREATE TABLE campaigns (id INT,name TEXT,budget INT,start_date DATE,state TEXT); INSERT INTO campaigns (id,name,budget,start_date,state) VALUES (1,'EndStigma',50000,'2019-03-01','New York'); INSERT INTO campaigns (id,name,budget,start_date,state) VALUES (2,'HealthyMinds',75000,'2018-06-15','California'); INSERT INTO campaigns (id,name,budget,start_date,state) VALUES (3,'MentalHealthMatters',60000,'2017-12-09','New York');
SELECT name FROM campaigns WHERE state = 'New York' AND start_date > '2018-12-31';
Find the top 3 rural infrastructure projects with the highest budgets and their completion years.
CREATE TABLE infrastructure (id INT,project VARCHAR(50),year INT,budget INT); INSERT INTO infrastructure (id,project,year,budget) VALUES (1,'Road Construction',2018,300000),(2,'Bridge Building',2020,400000);
SELECT project, year, budget FROM infrastructure ORDER BY budget DESC LIMIT 3;
How many satellites were launched in each year by agency?
CREATE TABLE Space_Satellites (Satellite_ID INT,Satellite_Name VARCHAR(100),Launch_Date DATE,Country_Name VARCHAR(50),Agency_Name VARCHAR(50)); INSERT INTO Space_Satellites (Satellite_ID,Satellite_Name,Launch_Date,Country_Name,Agency_Name) VALUES (1,'Sat1','2000-01-01','USA','NASA'),(2,'Sat2','2001-01-01','Russia','Roscosmos'),(3,'Sat3','2002-01-01','China','CNSA'),(4,'Sat4','2003-01-01','USA','NASA'),(5,'Sat5','2004-01-01','India','ISRO');
SELECT EXTRACT(YEAR FROM Launch_Date) as Launch_Year, Agency_Name, COUNT(*) as Total_Satellites FROM Space_Satellites GROUP BY Launch_Year, Agency_Name;
What is the total amount of waste produced by coal mines?
CREATE TABLE WasteProduction (SiteID INT,MineType VARCHAR(10),Waste INT); INSERT INTO WasteProduction (SiteID,MineType,Waste) VALUES (1,'Coal',1000),(2,'Coal',1500),(3,'Gold',500);
SELECT SUM(Waste) FROM WasteProduction WHERE MineType = 'Coal';
Delete records from sustainability table where brand='XYZ'
CREATE TABLE sustainability (id INT,brand VARCHAR(50),score INT,category VARCHAR(50));
DELETE FROM sustainability WHERE brand = 'XYZ';
What is the total amount of research grants awarded to faculty members in the Arts department for each year?
CREATE TABLE faculty (id INT,name VARCHAR(50),department VARCHAR(50)); INSERT INTO faculty (id,name,department) VALUES (1,'Irene','Arts'); INSERT INTO faculty (id,name,department) VALUES (2,'Jack','Engineering'); CREATE TABLE grants (id INT,faculty_id INT,amount DECIMAL(10,2),year INT); INSERT INTO grants (id,faculty_id,amount,year) VALUES (1,1,5000,2020); INSERT INTO grants (id,faculty_id,amount,year) VALUES (2,2,7500,2019);
SELECT g.year, SUM(g.amount) AS total_grant_amount FROM grants g JOIN faculty f ON g.faculty_id = f.id WHERE f.department = 'Arts' GROUP BY g.year;
Calculate the percentage change in weight of each chemical produced by the same manufacturer, between the second and third quarters of the year
CREATE TABLE quarterly_chemicals (manufacturer_id INT,chemical_id INT,chemical_type VARCHAR(50),quarter INT,weight FLOAT); INSERT INTO quarterly_chemicals (manufacturer_id,chemical_id,chemical_type,quarter,weight) VALUES (1,1,'Acid',1,150.5),(1,1,'Acid',2,155.6),(1,1,'Acid',3,160.3),(1,1,'Acid',4,165.4),(2,2,'Alkali',1,200.3),(2,2,'Alkali',2,205.4),(2,2,'Alkali',3,210.5),(2,2,'Alkali',4,215.6);
SELECT a.manufacturer_id, a.chemical_id, a.chemical_type, a.quarter, a.weight, b.weight, ((a.weight - b.weight) / b.weight) * 100 as percentage_change FROM quarterly_chemicals a JOIN quarterly_chemicals b ON a.manufacturer_id = b.manufacturer_id AND a.chemical_id = b.chemical_id WHERE a.quarter = 3 AND b.quarter = 2;
What is the average mental health score by gender and age group?
CREATE TABLE mental_health_scores (score_id INT,student_id INT,score_date DATE,mental_health_score INT,gender VARCHAR(10),age_group VARCHAR(20)); INSERT INTO mental_health_scores (score_id,student_id,score_date,mental_health_score,gender,age_group) VALUES (1,1,'2022-01-01',75,'Male','10-14'),(2,2,'2022-01-01',85,'Female','15-19'),(3,3,'2022-02-01',80,'Male','10-14'),(4,4,'2022-02-01',90,'Female','15-19');
SELECT gender, age_group, AVG(mental_health_score) FROM mental_health_scores GROUP BY gender, age_group;
How many IoT sensors were installed in rural and urban areas in each country in the past quarter?
CREATE TABLE country (id INTEGER,name TEXT);CREATE TABLE region (id INTEGER,country_id INTEGER,name TEXT,type TEXT);CREATE TABLE iot_sensor (id INTEGER,region_id INTEGER,installed_date DATE);
SELECT co.name as country, r.type as area_type, COUNT(s.id) as num_sensors FROM country co INNER JOIN region r ON co.id = r.country_id INNER JOIN iot_sensor s ON r.id = s.region_id WHERE s.installed_date >= DATEADD(quarter, -1, CURRENT_DATE) GROUP BY co.name, r.type;
What is the percentage change in production rate for each well between January and February?
CREATE TABLE well_production (well_id INT,measurement_date DATE,production_rate FLOAT); INSERT INTO well_production (well_id,measurement_date,production_rate) VALUES (1,'2022-01-01',500),(1,'2022-02-01',550),(2,'2022-01-01',700),(2,'2022-02-01',650);
SELECT a.well_id, (b.production_rate - a.production_rate) * 100.0 / a.production_rate AS Percentage_Change FROM well_production a JOIN well_production b ON a.well_id = b.well_id WHERE a.measurement_date = '2022-01-01' AND b.measurement_date = '2022-02-01'
List all products with a rating higher than the average rating for their respective category, ordered by category in ascending order.
CREATE TABLE products (product_id INT,name VARCHAR(255),category VARCHAR(255),rating FLOAT);
SELECT * FROM products WHERE rating > (SELECT AVG(rating) FROM products p2 WHERE p2.category = products.category) ORDER BY category ASC;
Identify the top 3 users who have streamed the most classical and blues songs, in descending order.
CREATE TABLE users (id INT,name VARCHAR(255)); CREATE TABLE songs (id INT,title VARCHAR(255),genre VARCHAR(255)); CREATE TABLE user_song_interactions (id INT,user_id INT,song_id INT,interaction_type VARCHAR(255),timestamp TIMESTAMP); INSERT INTO users (id,name) VALUES (1,'Jane Smith'),(2,'John Doe'); INSERT INTO songs (id,title,genre) VALUES (1,'Symphony','Classical'),(2,'Rhythm','Blues'); INSERT INTO user_song_interactions (id,user_id,song_id,interaction_type,timestamp) VALUES (1,1,1,'Stream',NOW()),(2,2,1,'Stream',NOW()); CREATE VIEW classical_blues_songs AS SELECT song_id FROM songs WHERE genre IN ('Classical','Blues');
SELECT user_id, COUNT(*) AS streams FROM user_song_interactions WHERE song_id IN (SELECT song_id FROM classical_blues_songs) GROUP BY user_id ORDER BY streams DESC LIMIT 3;
Calculate the average research grant amount for faculty members in the Chemistry department
CREATE TABLE faculty(faculty_id INT,name VARCHAR(50),gender VARCHAR(10),department VARCHAR(20)); INSERT INTO faculty VALUES (1,'Sophia','Female','Chemistry'); INSERT INTO faculty VALUES (2,'Tyler','Male','Chemistry'); CREATE TABLE research_grants(grant_id INT,faculty_id INT,amount DECIMAL(10,2)); INSERT INTO research_grants VALUES (1,1,50000); INSERT INTO research_grants VALUES (2,2,75000);
SELECT AVG(amount) FROM faculty f INNER JOIN research_grants g ON f.faculty_id = g.faculty_id WHERE f.department = 'Chemistry';
What is the total production of corn by region?
CREATE TABLE Region (id INT,name VARCHAR(255)); INSERT INTO Region (id,name) VALUES (1,'North'),(2,'South'),(3,'East'),(4,'West'); CREATE TABLE Crop (id INT,name VARCHAR(255),region_id INT,production INT); INSERT INTO Crop (id,name,region_id,production) VALUES (1,'Corn',1,500),(2,'Soybean',2,300),(3,'Corn',4,700);
SELECT SUM(Crop.production) FROM Crop INNER JOIN Region ON Crop.region_id = Region.id WHERE Crop.name = 'Corn';
Count the number of vessels that have had safety inspections in the last year
CREATE TABLE Vessels (Id INT,Name VARCHAR(50),LastInspection DATE); INSERT INTO Vessels (Id,Name,LastInspection) VALUES (1,'Vessel1','2021-03-15'),(2,'Vessel2','2020-06-20'),(3,'Vessel3','2022-01-05'),(4,'Vessel4','2021-12-10');
SELECT COUNT(*) FROM Vessels WHERE LastInspection >= DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR);
List the number of OTA bookings made for each hotel in the 'City' category.
CREATE TABLE otas (ota_id INT,hotel_id INT,bookings INT); CREATE TABLE hotels (hotel_id INT,name TEXT,category TEXT); INSERT INTO otas (ota_id,hotel_id,bookings) VALUES (1,1,100),(2,2,150),(3,1,75); INSERT INTO hotels (hotel_id,name,category) VALUES (1,'Hotel A','City'),(2,'Hotel B','Luxury');
SELECT hotels.name, SUM(otas.bookings) FROM otas INNER JOIN hotels ON otas.hotel_id = hotels.hotel_id WHERE hotels.category = 'City' GROUP BY hotels.name;
Show the names of students who received accommodations in both the psychology and social work departments during the fall 2022 semester.
CREATE TABLE psychology_accommodations (student_id INT,semester VARCHAR(10));CREATE TABLE social_work_accommodations (student_id INT,semester VARCHAR(10)); INSERT INTO psychology_accommodations VALUES (8,'fall 2022'),(9,'fall 2022'),(10,'fall 2022'); INSERT INTO social_work_accommodations VALUES (9,'fall 2022'),(10,'fall 2022'),(11,'fall 2022');
SELECT student_id FROM psychology_accommodations WHERE semester = 'fall 2022' INTERSECT SELECT student_id FROM social_work_accommodations WHERE semester = 'fall 2022';
Show the total number of subscribers for each account type, excluding subscribers with a 'test' technology type
CREATE TABLE subscriber_data (subscriber_id INT,subscriber_type VARCHAR(20),tech_type VARCHAR(20)); INSERT INTO subscriber_data (subscriber_id,subscriber_type,tech_type) VALUES (1,'Regular','4G'),(2,'Test','3G'),(3,'Regular','5G');
SELECT subscriber_type, COUNT(*) as total_subscribers FROM subscriber_data WHERE tech_type != 'Test' GROUP BY subscriber_type;
List the names and professional development hours of teachers who have participated in workshops on open pedagogy and lifelong learning, sorted alphabetically by name.
CREATE TABLE Teachers (teacher_id INT,name VARCHAR(255),professional_development_hours INT); CREATE TABLE Workshops (workshop_id INT,name VARCHAR(255),topic VARCHAR(255)); INSERT INTO Workshops (workshop_id,name,topic) VALUES (1,'Open Pedagogy Workshop','open pedagogy'),(2,'Lifelong Learning Seminar','lifelong learning'); CREATE TABLE TeacherWorkshops (teacher_id INT,workshop_id INT);
SELECT Teachers.name, Teachers.professional_development_hours FROM Teachers INNER JOIN TeacherWorkshops ON Teachers.teacher_id = TeacherWorkshops.teacher_id INNER JOIN Workshops ON TeacherWorkshops.workshop_id = Workshops.workshop_id WHERE Workshops.topic IN ('open pedagogy', 'lifelong learning') ORDER BY Teachers.name ASC;
Display the veteran employment statistics for each state in the US, sorted by the employment rate.
CREATE TABLE veteran_employment(id INT,state VARCHAR(20),employed_veterans INT,total_veterans INT);
SELECT state, employed_veterans, total_veterans, (employed_veterans::FLOAT/total_veterans)*100 AS employment_rate FROM veteran_employment ORDER BY employment_rate DESC;
How many patients were treated with cognitive behavioral therapy (CBT)?
CREATE TABLE treatments (treatment_id INT,patient_id INT,therapy_type VARCHAR(50),duration INT); INSERT INTO treatments (treatment_id,patient_id,therapy_type,duration) VALUES (1,1,'CBT',12);
SELECT COUNT(*) FROM treatments WHERE therapy_type = 'CBT';
Identify departments with no employees.
CREATE TABLE Employees (EmployeeID INT,FirstName VARCHAR(50),LastName VARCHAR(50),Department VARCHAR(50),ManagerID INT); INSERT INTO Employees (EmployeeID,FirstName,LastName,Department,ManagerID) VALUES (1,'Jane','Smith','Marketing',2),(2,'Bruce','Johnson','IT',NULL),(3,'Alice','Williams','Marketing',1),(4,'Charlie','Brown','HR',NULL); CREATE TABLE Departments (DepartmentID INT,Department VARCHAR(50)); INSERT INTO Departments (DepartmentID,Department) VALUES (1,'Marketing'),(2,'IT'),(3,'Sales'),(4,'HR');
SELECT D.Department FROM Departments D LEFT JOIN Employees E ON D.Department = E.Department WHERE E.EmployeeID IS NULL;
Update the donation amount for DonorID 001 to $100000.
CREATE TABLE Donors (DonorID INT,DonorName VARCHAR(50),TotalDonation DECIMAL(10,2));
UPDATE Donors SET TotalDonation = 100000 WHERE DonorID = 1;
Which systems in the 'vulnerabilities' table have a cve_count less than 5?
CREATE TABLE vulnerabilities (system_id INT,system_name VARCHAR(100),cve_count INT); INSERT INTO vulnerabilities (system_id,system_name,cve_count) VALUES (1,'Server01',20),(2,'Workstation01',15),(3,'Firewall01',5),(4,'Router01',12),(5,'Switch01',8),(6,'Printer01',3);
SELECT system_name FROM vulnerabilities WHERE cve_count < 5;
How many train maintenance incidents were reported in Tokyo in the past year, broken down by month?
CREATE TABLE tokyo_train_maintenance (incident_id INT,incident_date DATE);
SELECT DATE_FORMAT(incident_date, '%Y-%m') AS month, COUNT(*) FROM tokyo_train_maintenance WHERE incident_date >= DATE_SUB(NOW(), INTERVAL 1 YEAR) GROUP BY month;
Show the top 3 genres by total streams, including the total number of streams and the average number of streams per user.
CREATE TABLE artist_genre_streams (genre_id INT,artist_id INT,song_id INT); INSERT INTO artist_genre_streams (genre_id,artist_id,song_id) VALUES (1,1,1),(1,1,2),(2,2,3); CREATE TABLE genres (genre_id INT,genre_name VARCHAR(50)); INSERT INTO genres (genre_id,genre_name) VALUES (1,'Hip-Hop'),(2,'R&B'),(3,'Jazz');
SELECT g.genre_name, SUM(s.song_id) AS total_streams, AVG(s.song_id / u.user_count) AS avg_streams_per_user FROM genres g INNER JOIN artist_genre_streams s ON g.genre_id = s.genre_id INNER JOIN artists a ON s.artist_id = a.artist_id INNER JOIN streams stream ON s.song_id = stream.song_id INNER JOIN users u ON stream.user_id = u.user_id GROUP BY g.genre_name ORDER BY total_streams DESC LIMIT 3;
What are the names and titles of all employees who joined after 2015 in the 'city_employees' table?
CREATE TABLE city_employees (id INT,first_name VARCHAR(50),last_name VARCHAR(50),position VARCHAR(50),hire_date DATE); INSERT INTO city_employees (id,first_name,last_name,position,hire_date) VALUES (1,'John','Doe','Engineer','2016-01-01'); INSERT INTO city_employees (id,first_name,last_name,position,hire_date) VALUES (2,'Jane','Smith','Manager','2014-01-01');
SELECT first_name, last_name, position FROM city_employees WHERE hire_date > '2015-12-31';
How many security incidents were reported in the healthcare industry in the last quarter?
CREATE TABLE security_incidents (id INT,industry VARCHAR(20),date DATE);
SELECT COUNT(*) FROM security_incidents WHERE industry = 'healthcare' AND date >= ADD_MONTHS(TRUNC(SYSDATE, 'Q'), -3) AND date < TRUNC(SYSDATE, 'Q');
What is the total number of publications by assistant professors in the Engineering college?
CREATE TABLE faculty(id INT,rank TEXT,college TEXT); CREATE TABLE publications(id INT,faculty_id INT,year INT); INSERT INTO faculty(id,rank,college) VALUES (1,'assistant professor','Engineering'),(2,'associate professor','Liberal Arts'); INSERT INTO publications(id,faculty_id,year) VALUES (1,1,2020),(2,1,2021),(3,2,2019);
SELECT COUNT(*) FROM publications JOIN faculty ON publications.id = faculty.id WHERE rank = 'assistant professor' AND college = 'Engineering';
What is the total number of medical supplies donated by each organization for the Yemen crisis?
CREATE TABLE Donors (DonorID int,DonorName varchar(50),DonatedAmount decimal(10,2)); INSERT INTO Donors (DonorID,DonorName,DonatedAmount) VALUES (1,'UNICEF',1200.00),(2,'International Medical Corps',1800.00); CREATE TABLE DisasterRelief (CampaignID int,DonorID int,DisasterType varchar(50),DonatedAmount decimal(10,2)); INSERT INTO DisasterRelief (CampaignID,DonorID,DisasterType,DonatedAmount) VALUES (1,1,'Yemen Crisis',600.00),(1,2,'Yemen Crisis',1000.00);
SELECT DonorName, SUM(DonatedAmount) as TotalDonated FROM Donors INNER JOIN DisasterRelief ON Donors.DonorID = DisasterRelief.DonorID WHERE DisasterType = 'Yemen Crisis' GROUP BY DonorName;
Who scored the most points for the Celtics in the 2020-2021 season?
CREATE TABLE teams (team_name VARCHAR(255),season_start_year INT,season_end_year INT); INSERT INTO teams (team_name,season_start_year,season_end_year) VALUES ('Celtics',2020,2021); CREATE TABLE players (player_name VARCHAR(255),team_name VARCHAR(255),points_scored INT);
SELECT player_name, MAX(points_scored) FROM players WHERE team_name = 'Celtics' AND season_start_year = 2020 AND season_end_year = 2021 GROUP BY player_name;
What was the total value of military contracts awarded in the last fiscal year?
CREATE TABLE contracts (contract_name VARCHAR(255),contract_value DECIMAL(10,2),contract_date DATE,contract_type VARCHAR(255));
SELECT SUM(contract_value) FROM contracts WHERE contract_date BETWEEN DATE_SUB(CURDATE(), INTERVAL 1 YEAR) AND LAST_DAY(DATE_SUB(CURDATE(), INTERVAL 1 YEAR)) AND contract_type = 'Military';
List all food recalls in the food_recalls table that were due to contamination.
CREATE TABLE food_recalls (recall_id INT,recall_date DATE,food_item VARCHAR(255),recall_reason VARCHAR(255));
SELECT recall_id, recall_date, food_item FROM food_recalls WHERE recall_reason LIKE '%contamination%';
What is the minimum amount of investment in network infrastructure in the Central Africa region in the last 3 years?
CREATE TABLE investments (id INT,region VARCHAR(20),year INT,amount FLOAT); INSERT INTO investments (id,region,year,amount) VALUES (1,'Central Africa',2020,1500000),(2,'Central Africa',2019,1300000),(3,'Central Africa',2018,1100000),(4,'East Africa',2020,2000000),(5,'East Africa',2019,1800000),(6,'East Africa',2018,1600000);
SELECT MIN(amount) FROM investments WHERE region = 'Central Africa' AND year BETWEEN 2018 AND 2020;
What is the average duration of songs per genre, based on the 'genre' and 'duration' tables, joined with the 'song' table?
CREATE TABLE genre (genre_id INT,genre_name VARCHAR(255)); CREATE TABLE song (song_id INT,song_name VARCHAR(255),genre_id INT,duration_id INT); CREATE TABLE duration (duration_id INT,duration_seconds INT);
SELECT g.genre_name, AVG(d.duration_seconds) AS avg_duration FROM genre g INNER JOIN song s ON g.genre_id = s.genre_id INNER JOIN duration d ON s.duration_id = d.duration_id GROUP BY g.genre_name;
What are the explainable AI techniques used in AI applications from Africa, grouped by technique?
CREATE TABLE ai_techniques (application VARCHAR(255),technique VARCHAR(255),region VARCHAR(255)); INSERT INTO ai_techniques (application,technique,region) VALUES ('AIApp1','ExplainableTech3','Africa'); INSERT INTO ai_techniques (application,technique,region) VALUES ('AIApp2','ExplainableTech4','Africa'); INSERT INTO ai_techniques (application,technique,region) VALUES ('AIApp3','ExplainableTech5','Europe');
SELECT technique, COUNT(*) as num_applications FROM ai_techniques WHERE region = 'Africa' GROUP BY technique ORDER BY num_applications DESC;
List the top 3 authors with the highest number of publications in Mathematics
CREATE TABLE authors(author_id INT,name VARCHAR(50),gender VARCHAR(10)); INSERT INTO authors VALUES (1,'Clara','Female'); INSERT INTO authors VALUES (2,'Daniel','Male'); CREATE TABLE publications(publication_id INT,author_id INT,title VARCHAR(100),discipline VARCHAR(20)); INSERT INTO publications VALUES (1,1,'Book on Algebra','Mathematics'); INSERT INTO publications VALUES (2,1,'Paper on Number Theory','Mathematics'); INSERT INTO publications VALUES (3,2,'Paper on Calculus','Mathematics');
SELECT a.name, COUNT(*) as pub_count FROM authors a JOIN publications p ON a.author_id = p.author_id WHERE p.discipline = 'Mathematics' GROUP BY a.name ORDER BY pub_count DESC LIMIT 3;
What is the average number of hybrid trains in the railways table for each railway company?
CREATE TABLE railways (id INT,company TEXT,train_type TEXT,fuel_type TEXT,total_trains INT); INSERT INTO railways (id,company,train_type,fuel_type,total_trains) VALUES (1,'RailCo','Train','Electric',100),(2,'RailX','Train','Hybrid',80),(3,'RailEasy','Train','Hybrid',70);
SELECT company, AVG(total_trains) as avg_hybrid_trains FROM railways WHERE train_type = 'Train' AND fuel_type = 'Hybrid' GROUP BY company;
What is the average age of volunteers in each country?
CREATE TABLE Volunteers (VolunteerID int,Name varchar(50),Age int,Country varchar(50)); INSERT INTO Volunteers (VolunteerID,Name,Age,Country) VALUES (1,'Alice Johnson',30,'USA'),(2,'Bob Brown',45,'Canada'),(3,'Carlos Garcia',25,'Mexico'),(4,'Daniela Green',35,'USA');
SELECT v.Country, AVG(v.Age) AS AverageAge FROM Volunteers v GROUP BY v.Country;
Add a new column 'rank' to the 'players' table
CREATE TABLE players (id INT,name TEXT,last_login DATETIME);
ALTER TABLE players ADD COLUMN rank INT;
What is the average sourcing cost for organic ingredients across all products?
CREATE TABLE Ingredients (Product_ID INT,Ingredient_Name TEXT,Organic BOOLEAN,Sourcing_Cost FLOAT); INSERT INTO Ingredients (Product_ID,Ingredient_Name,Organic,Sourcing_Cost) VALUES (1,'Aloe Vera',TRUE,5.2),(1,'Chamomile',FALSE,2.8),(2,'Rosehip',TRUE,4.5),(2,'Lavender',TRUE,6.1),(3,'Jojoba',TRUE,3.9),(3,'Argan',TRUE,7.5);
SELECT AVG(Sourcing_Cost) FROM Ingredients WHERE Organic = TRUE;
What is the total value of defense projects delayed in 'Asia' between '2018' and '2020'?
CREATE TABLE Defense_Project_Timelines (project VARCHAR(255),region VARCHAR(255),start_year INT,end_year INT,delayed BOOLEAN,value INT); INSERT INTO Defense_Project_Timelines (project,region,start_year,end_year,delayed,value) VALUES ('Project C','Asia',2018,2019,true,7000000),('Project D','Asia',2020,2021,false,6000000);
SELECT SUM(value) FROM Defense_Project_Timelines WHERE region = 'Asia' AND start_year <= 2018 AND end_year >= 2020 AND delayed = true;
Find the number of AI safety incidents and their severity, partitioned by incident type, ordered by severity in descending order?
CREATE TABLE ai_safety_incidents (incident_id INT,incident_type VARCHAR(50),severity DECIMAL(3,2)); INSERT INTO ai_safety_incidents (incident_id,incident_type,severity) VALUES (1,'Cybersecurity',0.75),(2,'Data Privacy',0.85),(3,'Algorithmic Bias',0.95),(4,'Ethical Concerns',1.00);
SELECT incident_type, COUNT(*) as num_incidents, AVG(severity) as avg_severity FROM ai_safety_incidents GROUP BY incident_type ORDER BY avg_severity DESC;
Which agencies have spent exactly the overall average budget, displayed in alphabetical order?
CREATE TABLE agencies (agency_name TEXT,budget INT); INSERT INTO agencies (agency_name,budget) VALUES ('Agency1',1000000),('Agency2',1000000),('Agency3',1200000),('Agency4',800000),('Agency5',1000000);
SELECT agency_name FROM agencies WHERE budget = (SELECT AVG(budget) FROM agencies) ORDER BY agency_name ASC;
List the top 5 busiest train stations in London by total entries for the month of April 2021, excluding weekends.
CREATE TABLE london_stations (station_id INT,station_name TEXT,entries INT,entry_date DATE); INSERT INTO london_stations (station_id,station_name,entries,entry_date) VALUES (1,'Victoria',15000,'2021-04-01'),(2,'Liverpool Street',12000,'2021-04-01');
SELECT station_name, SUM(entries) FROM london_stations WHERE entry_date BETWEEN '2021-04-01' AND '2021-04-30' AND EXTRACT(DAY FROM entry_date) IN (1, 2, 3, 4, 5, 6, 7) GROUP BY station_name ORDER BY SUM(entries) DESC LIMIT 5;