instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
Calculate the average budget for ethical AI research per month in the year 2022.
CREATE TABLE Ethical_AI_Budget (Month INT,Budget FLOAT); INSERT INTO Ethical_AI_Budget (Month,Budget) VALUES (1,150000),(2,160000),(3,170000),(4,180000),(5,190000),(6,200000),(7,210000),(8,220000),(9,230000),(10,240000),(11,250000),(12,260000);
SELECT AVG(Budget) FROM Ethical_AI_Budget WHERE Year = 2022;
Show the total revenue for each music genre available on the 'desktop' platform.
CREATE TABLE artists (id INT,name TEXT,genre TEXT); CREATE TABLE albums (id INT,title TEXT,artist_id INT,platform TEXT); CREATE TABLE sales (id INT,album_id INT,quantity INT,revenue DECIMAL); CREATE VIEW genre_sales AS SELECT ar.genre,SUM(s.revenue) as total_revenue FROM albums a JOIN sales s ON a.id = s.album_id JOIN artists ar ON a.artist_id = ar.id GROUP BY ar.genre; CREATE VIEW genre_sales_web AS SELECT * FROM genre_sales WHERE platform = 'desktop';
SELECT genre, total_revenue FROM genre_sales_web;
What is the carbon footprint of flights between New Zealand and Australia?
CREATE TABLE Flights (id INT,origin TEXT,destination TEXT,distance FLOAT,emissions FLOAT); INSERT INTO Flights (id,origin,destination,distance,emissions) VALUES (1,'New Zealand','Australia',3000,750),(2,'Australia','New Zealand',3000,750);
SELECT SUM(emissions) FROM Flights WHERE origin = 'New Zealand' AND destination = 'Australia';
Delete the "accessibility_features" table
CREATE TABLE accessibility_features (name TEXT,description TEXT,platform TEXT); INSERT INTO accessibility_features (name,description,platform) VALUES ('VoiceOver','Screen reader for visually impaired users','iOS'); INSERT INTO accessibility_features (name,description,platform) VALUES ('Dictation','Speech-to-text functionality','Android');
DROP TABLE accessibility_features;
Which organizations have provided support in both the education and health sectors?
CREATE TABLE organizations (id INT,name TEXT,sector TEXT); INSERT INTO organizations (id,name,sector) VALUES (1,'UNICEF','Education'),(2,'World Food Programme','Disaster Response'),(3,'Save the Children','Health'),(4,'International Red Cross','Health,Education');
SELECT name FROM organizations WHERE sector = 'Education' INTERSECT SELECT name FROM organizations WHERE sector = 'Health';
How many wells were drilled in the SCOOP and STACK plays in Oklahoma?
CREATE TABLE plays (id INT,state VARCHAR(255),play VARCHAR(255),num_drilled INT); INSERT INTO plays (id,state,play,num_drilled) VALUES (1,'Oklahoma','SCOOP',1500),(2,'Oklahoma','STACK',2000);
SELECT SUM(num_drilled) as total_wells FROM plays WHERE state = 'Oklahoma' AND play IN ('SCOOP', 'STACK');
What is the total number of artists and the total number of artworks in the database?
CREATE TABLE artists (id INT,name VARCHAR(255),year_of_birth INT); CREATE TABLE artworks (id INT,artist_id INT,title VARCHAR(255),year_of_creation INT);
SELECT (SELECT COUNT(*) FROM artists) AS total_artists, (SELECT COUNT(*) FROM artworks) AS total_artworks;
What are the user names and purchase dates for electric vehicle purchases made by users between the ages of 30 and 50?
CREATE TABLE ElectricVehicleAdoption (UserID INT PRIMARY KEY,VehicleID INT,PurchaseDate DATE); CREATE TABLE Users (UserID INT PRIMARY KEY,UserName VARCHAR(50),Age INT);
SELECT Users.UserName, ElectricVehicleAdoption.PurchaseDate FROM Users CROSS JOIN ElectricVehicleAdoption WHERE Users.Age BETWEEN 30 AND 50;
What is the total installed capacity of renewable energy projects in 'country1'?
CREATE TABLE renewable_energy_projects (id INT,project_name TEXT,country TEXT,installed_capacity FLOAT); INSERT INTO renewable_energy_projects (id,project_name,country,installed_capacity) VALUES (1,'Project C','country1',500.0),(2,'Project D','country2',300.0);
SELECT SUM(installed_capacity) FROM renewable_energy_projects WHERE country = 'country1';
What is the total installed solar capacity in Canada and Mexico combined?
CREATE TABLE SolarCapacities (id INT,country VARCHAR(20),capacity FLOAT); INSERT INTO SolarCapacities (id,country,capacity) VALUES (1,'Canada',8000.0),(2,'Mexico',9000.0),(3,'United States',12000.0);
SELECT SUM(capacity) FROM SolarCapacities WHERE country IN ('Canada', 'Mexico');
What is the lowest value military equipment sale?
CREATE TABLE military_sales (id INT,country VARCHAR,value FLOAT); INSERT INTO military_sales (id,country,value) VALUES (1,'Canada',5000000),(2,'Mexico',3000000),(3,'Canada',7000000);
SELECT MIN(value) FROM military_sales;
What is the number of complaints received for each mobile plan in the last quarter?
CREATE TABLE mobile_plans (id INT,name VARCHAR(50),price DECIMAL(5,2)); INSERT INTO mobile_plans (id,name,price) VALUES (1,'PlanA',30.00),(2,'PlanB',45.00); CREATE TABLE complaints (date DATE,plan_id INT,description VARCHAR(255)); INSERT INTO complaints (date,plan_id,description) VALUES ('2022-01-01',1,'Poor signal');
SELECT m.name, COUNT(c.date) as num_complaints FROM mobile_plans m INNER JOIN complaints c ON m.id = c.plan_id WHERE c.date BETWEEN DATE_SUB(CURDATE(), INTERVAL 3 MONTH) AND CURDATE() GROUP BY m.name;
What is the total revenue generated from sales in the 'sales' table for products in the 'sustainable_products' table?
CREATE TABLE sales (sale_id INT,product_id INT,price DECIMAL(10,2),quantity INT);
SELECT SUM(price * quantity) FROM sales s JOIN sustainable_products sp ON s.product_id = sp.product_id;
What is the maximum billing amount for cases in the "criminal" department?
CREATE TABLE CaseTypes (id INT,case_type VARCHAR(50),billing_amount DECIMAL(10,2));
SELECT case_type, MAX(billing_amount) FROM CaseTypes WHERE case_type = 'criminal' GROUP BY case_type;
Add a new department named 'Engineering' with a budget of 150000 and a manager_id of 3.
CREATE TABLE departments (id INT,name VARCHAR(50),budget INT,manager_id INT);
INSERT INTO departments (id, name, budget, manager_id) VALUES (5, 'Engineering', 150000, 3);
Which space missions encountered the most unique asteroids?
CREATE TABLE SpaceMissions (id INT,mission VARCHAR(255),year INT); CREATE TABLE AsteroidEncounters (id INT,mission_id INT,asteroid VARCHAR(255));
SELECT SpaceMissions.mission, COUNT(DISTINCT AsteroidEncounters.asteroid) as unique_asteroids FROM SpaceMissions INNER JOIN AsteroidEncounters ON SpaceMissions.id = AsteroidEncounters.mission_id GROUP BY SpaceMissions.mission ORDER BY unique_asteroids DESC;
What is the minimum billing amount for cases in the civil law specialization?
CREATE TABLE Attorneys (AttorneyID INT,Specialization VARCHAR(255)); INSERT INTO Attorneys (AttorneyID,Specialization) VALUES (1,'Civil Law'); INSERT INTO Attorneys (AttorneyID,Specialization) VALUES (2,'Criminal Law'); INSERT INTO Attorneys (AttorneyID,Specialization) VALUES (3,'Family Law'); CREATE TABLE Cases (CaseID INT,AttorneyID INT,BillingAmount DECIMAL(10,2)); INSERT INTO Cases (CaseID,AttorneyID,BillingAmount) VALUES (1,1,2000.00); INSERT INTO Cases (CaseID,AttorneyID,BillingAmount) VALUES (2,2,3000.00); INSERT INTO Cases (CaseID,AttorneyID,BillingAmount) VALUES (3,3,1500.00);
SELECT MIN(BillingAmount) FROM Cases INNER JOIN Attorneys ON Cases.AttorneyID = Attorneys.AttorneyID WHERE Specialization = 'Civil Law';
What is the total number of workplaces with safety issues by state?
CREATE TABLE Workplace_Safety (state VARCHAR(20),workplace_id INT,safety_issue BOOLEAN); INSERT INTO Workplace_Safety (state,workplace_id,safety_issue) VALUES ('California',101,true),('California',102,false),('New York',201,true);
SELECT state, SUM(safety_issue) as total_safety_issues FROM (SELECT state, workplace_id, CASE WHEN safety_issue = true THEN 1 ELSE 0 END as safety_issue FROM Workplace_Safety) subquery GROUP BY state;
What are the total CO2 emissions for all mining sites in the 'environmental_impact' table?
CREATE TABLE environmental_impact (site_name VARCHAR(50),co2_emissions INT,waste_generation INT); INSERT INTO environmental_impact (site_name,co2_emissions,waste_generation) VALUES ('Site Alpha',1200,500),('Site Bravo',1800,800),('Site Charlie',2500,1000);
SELECT SUM(co2_emissions) FROM environmental_impact;
Which factories have a higher percentage of workers earning a living wage compared to the industry average?
CREATE TABLE Factory (id INT,name VARCHAR(255),location VARCHAR(255),workers INT,living_wage_workers INT); INSERT INTO Factory (id,name,location,workers,living_wage_workers) VALUES (1001,'Green Manufacturing','USA',500,350),(1002,'Eco-Friendly Fashion','China',800,600);
SELECT name, ((living_wage_workers / workers) * 100) as wage_percentage FROM Factory;
Display the total mass of space debris added to orbit each year
CREATE TABLE space_debris_by_year (debris_id INT,debris_type VARCHAR(50),mass FLOAT,debris_year INT); INSERT INTO space_debris_by_year (debris_id,debris_type,mass,debris_year) VALUES (1,'Fuel Tanks',350.0,2019); INSERT INTO space_debris_by_year (debris_id,debris_type,mass,debris_year) VALUES (2,'Instruments',75.2,2020); INSERT INTO space_debris_by_year (debris_id,debris_type,mass,debris_year) VALUES (3,'Payload Adapters',120.5,2021);
SELECT debris_year, SUM(mass) as total_mass_kg FROM space_debris_by_year GROUP BY debris_year;
What is the number of smart contracts deployed each day in the month of March 2023?
CREATE TABLE smart_contracts (contract_address VARCHAR(42),deployment_date DATE); INSERT INTO smart_contracts (contract_address,deployment_date) VALUES ('0x123','2023-03-01'),('0x456','2023-03-01'),('0x789','2023-03-02'),('0xabc','2023-03-02'),('0xdef','2023-03-03');
SELECT deployment_date, COUNT(*) FROM smart_contracts WHERE deployment_date BETWEEN '2023-03-01' AND '2023-03-31' GROUP BY deployment_date ORDER BY deployment_date;
Show the names and number of beds of hospitals in "Texas" with more than 300 beds
CREATE TABLE hospitals_tx(id INT,name TEXT,beds INT); INSERT INTO hospitals_tx(id,name,beds) VALUES (1,'Texas Medical Center',1000),(2,'Methodist Hospital',550),(3,'Rural Health Care',30),(4,'Parkland Hospital',860);
SELECT name, beds FROM hospitals_tx WHERE beds > 300 AND state = 'Texas';
How many hockey fans are there who have attended a game in the last 3 years and are from Canada?
CREATE TABLE fans (id INT,name VARCHAR(50),country VARCHAR(50),last_game_date DATE); INSERT INTO fans (id,name,country,last_game_date) VALUES (1,'Jacob Smith','Canada','2021-01-01'); INSERT INTO fans (id,name,country,last_game_date) VALUES (2,'Sophia Johnson','USA','2020-01-01');
SELECT COUNT(*) FROM fans WHERE country = 'Canada' AND last_game_date >= DATEADD(year, -3, GETDATE());
What is the earliest date a medical emergency was recorded in the North district?
CREATE TABLE emergency_incidents (id INT,district VARCHAR(20),type VARCHAR(20),date DATE); INSERT INTO emergency_incidents (id,district,type,date) VALUES (1,'Downtown','Fire','2022-01-01'); INSERT INTO emergency_incidents (id,district,type,date) VALUES (2,'Uptown','Medical','2022-01-02'); INSERT INTO emergency_incidents (id,district,type,date) VALUES (3,'North','Fire','2022-01-03'); INSERT INTO emergency_incidents (id,district,type,date) VALUES (4,'North','Medical','2022-01-04');
SELECT MIN(date) FROM emergency_incidents WHERE district = 'North' AND type = 'Medical';
What is the total quantity of 'Eco-friendly Tops' sold in each store in 'Brazil' for the 'Winter 2024' season?
CREATE TABLE StoreSales (StoreID INT,ProductID INT,QuantitySold INT,StoreCountry VARCHAR(50),SaleDate DATE); INSERT INTO StoreSales (StoreID,ProductID,QuantitySold,StoreCountry,SaleDate) VALUES (1,8,50,'Brazil','2024-01-21'),(2,9,30,'Brazil','2024-01-03'),(3,8,70,'Brazil','2024-01-15'); CREATE TABLE Products (ProductID INT,ProductType VARCHAR(20),Sustainable BOOLEAN); INSERT INTO Products (ProductID,ProductType,Sustainable) VALUES (8,'Eco-friendly Tops',TRUE),(9,'Regular Tops',FALSE);
SELECT StoreCountry, ProductType, SUM(QuantitySold) as TotalQuantitySold FROM StoreSales S JOIN Products P ON S.ProductID = P.ProductID WHERE P.ProductType = 'Eco-friendly Tops' AND StoreCountry = 'Brazil' AND SaleDate BETWEEN '2024-01-01' AND '2024-03-31' GROUP BY StoreCountry, ProductType;
Find the total waste generated by the top 3 contributors in the 'waste_data' table, excluding the 'Government' sector.
CREATE TABLE waste_data (contributor VARCHAR(20),waste_generated FLOAT); INSERT INTO waste_data (contributor,waste_generated) VALUES ('Manufacturing',1200.5),('Commercial',850.7),('Government',400),('Residential',600.3);
SELECT SUM(waste_generated) FROM waste_data WHERE contributor NOT IN ('Government') LIMIT 3;
What is the total installed capacity in MW for wind energy in Brazil?
CREATE TABLE installed_capacity (country VARCHAR(50),technology VARCHAR(50),capacity_mw INT); INSERT INTO installed_capacity (country,technology,capacity_mw) VALUES ('Brazil','Wind',15000),('Brazil','Solar',8000),('Brazil','Hydro',95000);
SELECT capacity_mw FROM installed_capacity WHERE country = 'Brazil' AND technology = 'Wind';
How many posts were made by users with the word "AI" in their username, in the social_media database?
CREATE TABLE users (user_id INT,username VARCHAR(20),email VARCHAR(50)); CREATE TABLE posts (post_id INT,user_id INT,content TEXT,post_time TIMESTAMP);
SELECT COUNT(*) FROM posts p JOIN users u ON p.user_id = u.user_id WHERE u.username LIKE '%AI%';
What is the minimum salary for employees who identify as Hispanic or Latino?
CREATE TABLE employees (id INT,ethnicity VARCHAR(20),salary FLOAT); INSERT INTO employees (id,ethnicity,salary) VALUES (1,'Hispanic or Latino',50000); INSERT INTO employees (id,ethnicity,salary) VALUES (2,'Asian',60000); INSERT INTO employees (id,ethnicity,salary) VALUES (3,'African American',65000); INSERT INTO employees (id,ethnicity,salary) VALUES (4,'White',70000); INSERT INTO employees (id,ethnicity,salary) VALUES (5,'Hispanic or Latino',45000);
SELECT MIN(salary) as min_salary FROM employees WHERE ethnicity = 'Hispanic or Latino';
What is the name of each museum in the state of New York and the number of exhibits it has?
CREATE TABLE states (id INT,name VARCHAR(255)); CREATE TABLE museums (id INT,state_id INT,name VARCHAR(255),exhibits INT);
SELECT m.name, m.exhibits FROM museums m JOIN states s ON m.state_id = s.id WHERE s.name = 'New York';
What is the total number of unique users who have streamed songs from a specific genre?
CREATE TABLE StreamingData (StreamID INT,UserID INT,SongID INT,StreamDate DATE); INSERT INTO StreamingData VALUES (1,1,1001,'2022-01-01'),(2,2,1002,'2022-01-02'); CREATE TABLE Songs (SongID INT,SongName VARCHAR(100),Genre VARCHAR(50)); INSERT INTO Songs VALUES (1001,'Shake It Off','Pop'),(1002,'Dynamite','Pop'); CREATE TABLE Users (UserID INT,UserName VARCHAR(50)); INSERT INTO Users VALUES (1,'Aarav'),(2,'Bella');
SELECT COUNT(DISTINCT Users.UserID) FROM StreamingData JOIN Songs ON StreamingData.SongID = Songs.SongID JOIN Users ON StreamingData.UserID = Users.UserID WHERE Songs.Genre = 'Pop';
Present founders who identify as LGBTQ+.
CREATE TABLE lgbtq_founders (company_id INT,founder_id INT,founder_lgbtq BOOLEAN); INSERT INTO lgbtq_founders (company_id,founder_id,founder_lgbtq) VALUES (1,1,FALSE),(1,2,TRUE),(2,1,FALSE),(3,1,FALSE);
SELECT company_id, founder_id FROM lgbtq_founders WHERE founder_lgbtq = TRUE;
Which cities have the highest total donation amounts in the 'donors' table, joined with their corresponding city information from the 'cities' table?
CREATE TABLE donors (donor_id INT,donor_name TEXT,donation_amount DECIMAL,city_id INT); CREATE TABLE cities (city_id INT,city_name TEXT);
SELECT cities.city_name, SUM(donation_amount) as total_donations FROM donors INNER JOIN cities ON donors.city_id = cities.city_id GROUP BY cities.city_name ORDER BY total_donations DESC LIMIT 1;
What is the average assets of clients living in New York?
CREATE TABLE clients (client_id INT,name VARCHAR(50),age INT,assets DECIMAL(10,2),city VARCHAR(50)); INSERT INTO clients VALUES (1,'John Doe',55,500000.00,'New York'),(2,'Jane Smith',45,700000.00,'Los Angeles'),(3,'Mike Johnson',58,300000.00,'New York'),(4,'Alice Davis',35,800000.00,'Chicago'),(5,'Bob Brown',40,600000.00,'New York');
SELECT AVG(assets) FROM clients WHERE city = 'New York';
What is the sum of transaction amounts for retail customers in the Europe region?
CREATE TABLE transactions (id INT,customer_type VARCHAR(20),region VARCHAR(20),transaction_amount DECIMAL(10,2)); INSERT INTO transactions (id,customer_type,region,transaction_amount) VALUES (1,'retail','Latin America',100.00),(2,'wholesale','North America',500.00),(3,'retail','Europe',200.00),(4,'wholesale','Asia-Pacific',300.00);
SELECT SUM(transaction_amount) FROM transactions WHERE customer_type = 'retail' AND region = 'Europe';
Show total installed capacity of solar projects in 'africa'
CREATE TABLE solar_projects (id INT PRIMARY KEY,project_name VARCHAR(255),location VARCHAR(255),capacity_mw FLOAT,completion_date DATE);
SELECT SUM(capacity_mw) FROM solar_projects WHERE location = 'africa';
What are the names of all hospitals and their total number of beds in the health division?
CREATE TABLE hospitals (id INT,name VARCHAR(50),division VARCHAR(50),num_beds INT); INSERT INTO hospitals (id,name,division,num_beds) VALUES (1,'Hospital A','Health',200),(2,'Hospital B','Health',250),(3,'Hospital C','Health',300);
SELECT name, SUM(num_beds) FROM hospitals WHERE division = 'Health' GROUP BY name;
What is the profit margin for each menu category?
CREATE TABLE MenuCategoryCosts (MenuCategoryID INT,Category VARCHAR(50),Cost DECIMAL(10,2)); INSERT INTO MenuCategoryCosts (MenuCategoryID,Category,Cost) VALUES (1,'Entree',2500.00),(2,'Appetizer',1000.00),(3,'Dessert',1500.00);
SELECT mc.Category, (mc.Revenue - mcc.Cost) as Profit, ((mc.Revenue - mcc.Cost) / mc.Revenue) * 100 as ProfitMargin FROM MenuCategories mc JOIN MenuCategoryCosts mcc ON mc.Category = mcc.Category;
List all broadband customers in New York who have a plan with speeds between 50 Mbps and 150 Mbps.
CREATE TABLE broadband_customers (customer_id INT,name VARCHAR(50),plan_speed FLOAT,state VARCHAR(20)); INSERT INTO broadband_customers (customer_id,name,plan_speed,state) VALUES (1,'Jamila Smith',100,'New York');
SELECT * FROM broadband_customers WHERE state = 'New York' AND plan_speed BETWEEN 50 AND 150;
List all investors who have not invested in any company in the technology sector.
CREATE TABLE investments (investor_id INT,company_id INT); INSERT INTO investments (investor_id,company_id) VALUES (1,1),(1,2),(2,3),(3,4),(3,5); CREATE TABLE companies (id INT,sector VARCHAR(20)); INSERT INTO companies (id,sector) VALUES (1,'Technology'),(2,'Real Estate'),(3,'Finance'),(4,'Healthcare'),(5,'Healthcare');
SELECT i.name FROM investors AS i LEFT JOIN investments AS inv ON i.id = inv.investor_id LEFT JOIN companies AS c ON inv.company_id = c.id WHERE c.sector != 'Technology' GROUP BY i.name HAVING COUNT(inv.id) = 0;
List the peacekeeping operations with the most troops from the 'peacekeeping_operations' and 'troop_deployments' tables?
CREATE TABLE peacekeeping_operations (operation_id INT,operation_name VARCHAR(50)); CREATE TABLE troop_deployments (deployment_id INT,operation_id INT,troop_count INT); INSERT INTO peacekeeping_operations VALUES (1,'MINUSTAH'),(2,'UNMIL'),(3,'MONUSCO'); INSERT INTO troop_deployments VALUES (1,1,5000),(2,1,3000),(3,2,4000),(4,2,6000),(5,3,7000);
SELECT p.operation_name, SUM(t.troop_count) as total_troops FROM peacekeeping_operations p JOIN troop_deployments t ON p.operation_id = t.operation_id GROUP BY p.operation_name ORDER BY total_troops DESC;
Which factories have workers in both 'engineering' and 'quality control' departments?
CREATE TABLE factories (factory_id INT,factory_name VARCHAR(20)); INSERT INTO factories VALUES (1,'Factory X'),(2,'Factory Y'),(3,'Factory Z'); CREATE TABLE departments (department_id INT,department VARCHAR(20)); INSERT INTO departments VALUES (1,'engineering'),(2,'quality control'),(3,'maintenance'); CREATE TABLE workers (worker_id INT,factory_id INT,department_id INT); INSERT INTO workers VALUES (1,1,1),(2,1,2),(3,2,1),(4,2,3),(5,3,2),(6,3,3);
SELECT f.factory_name FROM workers w INNER JOIN factories f ON w.factory_id = f.factory_id INNER JOIN departments d ON w.department_id = d.department_id WHERE d.department IN ('engineering', 'quality control') GROUP BY f.factory_name HAVING COUNT(DISTINCT d.department_id) = 2;
List all the regions with mobile subscribers.
CREATE TABLE mobile_subscribers (id INT,name VARCHAR(50),region VARCHAR(20)); INSERT INTO mobile_subscribers (id,name,region) VALUES (1,'Jane Doe','Urban');
SELECT DISTINCT region FROM mobile_subscribers;
Calculate the total number of hospital beds in rural healthcare facilities in Russia and Ukraine.
CREATE TABLE healthcare_facilities (facility_id INT,country VARCHAR(20),num_beds INT); INSERT INTO healthcare_facilities (facility_id,country,num_beds) VALUES (1,'Russia',150),(2,'Ukraine',200);
SELECT SUM(num_beds) FROM healthcare_facilities WHERE country IN ('Russia', 'Ukraine');
What is the number of workers in each department, grouped by their age range?
CREATE TABLE department (dept_id INT,dept_name VARCHAR(50),worker_id INT); INSERT INTO department (dept_id,dept_name,worker_id) VALUES (1,'Mining',1),(1,'Mining',5),(2,'Engineering',2); CREATE TABLE worker_demographics (worker_id INT,worker_age INT); INSERT INTO worker_demographics (worker_id,worker_age) VALUES (1,25),(2,35),(3,45),(4,55),(5,65); CREATE TABLE age_ranges (age_range_id INT,lower_limit INT,upper_limit INT); INSERT INTO age_ranges (age_range_id,lower_limit,upper_limit) VALUES (1,18,30),(2,31,40),(3,41,50),(4,51,60),(5,61,80);
SELECT dept_name, CASE WHEN worker_age BETWEEN lower_limit AND upper_limit THEN age_range_id END as age_range_id, COUNT(*) as count FROM department d JOIN worker_demographics w ON d.worker_id = w.worker_id JOIN age_ranges a ON w.worker_age BETWEEN a.lower_limit AND a.upper_limit GROUP BY dept_name, age_range_id;
Show the number of R&B songs released before 1990.
CREATE TABLE Songs (song_id INT,artist_id INT,title VARCHAR(100),release_year INT,genre VARCHAR(20));
SELECT COUNT(song_id) FROM Songs WHERE genre = 'R&B' AND release_year < 1990;
List all the suppliers providing organic ingredients.
CREATE TABLE suppliers (id INT,name TEXT,organic_supplier BOOLEAN); INSERT INTO suppliers (id,name,organic_supplier) VALUES (1,'Green Earth',true),(2,'Global Foods',false);
SELECT name FROM suppliers WHERE organic_supplier = true;
What is the average length of all bridges in the city of Mexico City, Mexico?
CREATE TABLE Bridges (id INT,name VARCHAR(100),length FLOAT,city VARCHAR(50));
SELECT AVG(length) FROM Bridges WHERE city = 'Mexico City';
Which marine mammal species have a population size in the top 20%?
CREATE TABLE marine_species (name TEXT,category TEXT,population INT); INSERT INTO marine_species (name,category,population) VALUES ('Blue Whale','Mammal',10000),('Dolphin','Mammal',25000),('Clownfish','Fish',150000);
SELECT name, population FROM (SELECT name, population, PERCENT_RANK() OVER (ORDER BY population DESC) as rank FROM marine_species WHERE category = 'Mammal') as ranked_species WHERE rank <= 0.2;
what is the percentage of sustainable seafood in Japan's market?
CREATE TABLE SeafoodMarket (Country TEXT,Sustainability TEXT,Percentage FLOAT); INSERT INTO SeafoodMarket (Country,Sustainability,Percentage) VALUES ('Japan','Sustainable',45.0),('Japan','Non-Sustainable',55.0),('United States','Sustainable',70.0),('United States','Non-Sustainable',30.0),('China','Sustainable',15.0),('China','Non-Sustainable',85.0);
SELECT Percentage FROM SeafoodMarket WHERE Country = 'Japan' AND Sustainability = 'Sustainable';
What is the average number of members per union advocating for labor rights?
CREATE TABLE unions (union_id INT,union_name TEXT,advocacy TEXT,members INT); INSERT INTO unions (union_id,union_name,advocacy,members) VALUES (1001,'United Steelworkers','labor rights',5000); INSERT INTO unions (union_id,union_name,advocacy,members) VALUES (1002,'Transport Workers Union','collective bargaining',6000);
SELECT AVG(u.members) FROM unions u WHERE u.advocacy = 'labor rights';
What is the average amount of humanitarian assistance provided by each organization in the last 5 years?
CREATE TABLE HumanitarianAssistance (Organization VARCHAR(50),Year INT,Amount DECIMAL(10,2)); INSERT INTO HumanitarianAssistance (Organization,Year,Amount) VALUES ('UNHCR',2017,500000),('WFP',2018,700000),('Red Cross',2019,600000),('CARE',2020,800000),('Oxfam',2021,900000);
SELECT AVG(Amount) AS AverageAssistance FROM (SELECT Amount FROM HumanitarianAssistance WHERE Year >= 2017 GROUP BY Year, Organization ORDER BY Year DESC) AS LastFiveYears;
What is the distribution of articles by author and topic?
CREATE TABLE news_articles (article_id INT PRIMARY KEY,title TEXT,topic TEXT,author TEXT,publication_date DATE);
SELECT author, topic, COUNT(*) FROM news_articles GROUP BY author, topic;
What is the average age of athletes in the 'Athletes' table who have won a gold medal in the Olympics, grouped by their nationality?
CREATE TABLE athletes (athlete_id INT,name VARCHAR(50),nationality VARCHAR(50),age INT,medal VARCHAR(10),event VARCHAR(50)); INSERT INTO athletes (athlete_id,name,nationality,age,medal,event) VALUES (1,'Usain Bolt','Jamaica',30,'Gold','100m sprint');
SELECT nationality, AVG(age) FROM athletes WHERE medal = 'Gold' AND event LIKE '%Olympics%' GROUP BY nationality;
What is the total number of policy violations by employees in the sales department?
CREATE TABLE policy_violations (id INT,employee_id INT,department VARCHAR(255),violation_count INT); INSERT INTO policy_violations (id,employee_id,department,violation_count) VALUES (1,111,'sales',3),(2,222,'marketing',2),(3,111,'sales',1),(4,333,'HR',5),(5,222,'marketing',1);
SELECT employee_id, SUM(violation_count) as total_violations FROM policy_violations WHERE department = 'sales' GROUP BY employee_id;
Find all habitats with a population of less than 500
CREATE TABLE animal_populations (id INT,species VARCHAR(50),population INT,habitat_id INT); INSERT INTO animal_populations (id,species,population,habitat_id) VALUES (1,'Giraffe',400,1),(2,'Elephant',800,2),(3,'Lion',300,1),(4,'Rhinoceros',100,2),(5,'Hippopotamus',1200,3),(6,'Polar Bear',200,4),(7,'Penguin',250,5),(8,'Seal',700,4),(9,'Walrus',600,4); CREATE TABLE habitats (id INT,type VARCHAR(50)); INSERT INTO habitats (id,type) VALUES (1,'Savannah'),(2,'Forest'),(3,'River'),(4,'Arctic'),(5,'Antarctic');
SELECT h.type FROM habitats h INNER JOIN animal_populations ap ON h.id = ap.habitat_id WHERE ap.population < 500 GROUP BY h.type;
What is the total waste generated by the production of eco-friendly products in South America?
CREATE TABLE eco_friendly_products (id INT,country VARCHAR(255),waste_kg INT); INSERT INTO eco_friendly_products VALUES (1,'Argentina',50),(2,'Colombia',75),(3,'Brazil',100),(4,'Chile',80);
SELECT SUM(waste_kg) FROM eco_friendly_products WHERE country IN ('Argentina', 'Colombia', 'Brazil', 'Chile');
Who is the most prolific female artist in terms of exhibitions?
CREATE TABLE female_artists (artist_id INT,artist_name VARCHAR(255),artist_country VARCHAR(255),artist_birth_date DATE,artist_exhibition_count INT); INSERT INTO female_artists (artist_id,artist_name,artist_country,artist_birth_date,artist_exhibition_count) VALUES (1,'Yayoi Kusama','Japan','1929-03-22',50); INSERT INTO female_artists (artist_id,artist_name,artist_country,artist_birth_date,artist_exhibition_count) VALUES (2,'Brigit Riley','United Kingdom','1931-04-22',45);
SELECT artist_id, artist_name, artist_country, artist_birth_date, artist_exhibition_count, RANK() OVER (ORDER BY artist_exhibition_count DESC) as rank FROM female_artists;
List the membership status and join date for members who have completed at least one workout and live in Canada or Mexico.
CREATE TABLE members (id INT,name VARCHAR(50),membership_status VARCHAR(20),join_date DATE,state VARCHAR(20)); CREATE TABLE user_workouts (user_id INT,workout_type VARCHAR(20)); INSERT INTO user_workouts (user_id,workout_type) VALUES (1,'Running'),(1,'Cycling'),(2,'Running'),(3,'Cycling'),(3,'Swimming'),(4,'Running'),(4,'Swimming'),(5,'Yoga');
SELECT membership_status, join_date FROM members WHERE state IN ('Canada', 'Mexico') AND id IN (SELECT user_id FROM user_workouts) ORDER BY join_date;
What is the change in obesity rates for each city in the United States between 2015 and 2020?
CREATE TABLE obesity_usa (city TEXT,year INT,obesity_rate INT); INSERT INTO obesity_usa (city,year,obesity_rate) VALUES ('New York',2015,22),('New York',2016,23),('New York',2017,24),('Los Angeles',2015,25),('Los Angeles',2016,26),('Los Angeles',2017,27);
SELECT city, (obesity_rate_2020 - obesity_rate_2015) AS obesity_change FROM (SELECT city, obesity_rate AS obesity_rate_2015, LEAD(obesity_rate, 5) OVER (PARTITION BY city ORDER BY year) AS obesity_rate_2020 FROM obesity_usa) WHERE obesity_rate_2020 IS NOT NULL;
What is the average ice thickness in the Arctic per month since 2010?
CREATE TABLE ice_thickness (month INT,year INT,ice_thickness FLOAT); INSERT INTO ice_thickness (month,year,ice_thickness) VALUES (1,2010,3.5),(2,2010,3.7);
SELECT t.month, AVG(t.ice_thickness) as avg_thickness FROM ice_thickness t GROUP BY t.month;
Determine the average kills per match by champion in LoL
CREATE TABLE lolgames (game_id INT,champion VARCHAR(50),kills INT); INSERT INTO lolgames (game_id,champion,kills) VALUES (1,'Ashe',10);
SELECT champion, AVG(kills) as avg_kills_per_match, RANK() OVER (ORDER BY AVG(kills) DESC) as rank FROM lolgames GROUP BY champion
Find the difference between the total inventory of ethical products and non-ethical products.
CREATE TABLE inventory (product_id INT,ethical BOOLEAN,in_stock INT); INSERT INTO inventory (product_id,ethical,in_stock) VALUES (1,true,50),(2,false,75),(3,true,30),(4,false,80),(5,true,100),(6,false,90);
SELECT SUM(CASE WHEN ethical = true THEN in_stock ELSE 0 END) - SUM(CASE WHEN ethical = false THEN in_stock ELSE 0 END) as inventory_difference;
What is the total humanitarian assistance provided by country in the last 3 years?
CREATE TABLE HumanitarianAssistance(Year INT,Country NVARCHAR(50),Amount DECIMAL(18,2));INSERT INTO HumanitarianAssistance(Year,Country,Amount) VALUES (2018,'United States',6500000000),(2018,'Germany',2000000000),(2019,'United States',7000000000),(2019,'Germany',2500000000),(2020,'United States',8000000000),(2020,'Germany',3000000000);
SELECT Country, SUM(Amount) AS Total_Assistance FROM HumanitarianAssistance WHERE Year >= 2018 GROUP BY Country;
What is the minimum budget allocated for disability accommodations in '2021'?
CREATE TABLE DisabilityAccommodations (year INT,budget DECIMAL(5,2)); INSERT INTO DisabilityAccommodations (year,budget) VALUES (2018,450000.00),(2019,500000.00),(2020,600000.00),(2021,700000.00);
SELECT MIN(budget) FROM DisabilityAccommodations WHERE year = 2021;
Delete all records of workers who have been terminated and replace them with new hires who have received ethical manufacturing training.
CREATE TABLE Workers (ID INT,Terminated BOOLEAN,Ethical_Training BOOLEAN); INSERT INTO Workers (ID,Terminated,Ethical_Training) VALUES (1,TRUE,FALSE); INSERT INTO Workers (ID,Terminated,Ethical_Training) VALUES (2,FALSE,TRUE); INSERT INTO Workers (ID,Terminated,Ethical_Training) VALUES (3,TRUE,FALSE); INSERT INTO Workers (ID,Terminated,Ethical_Training) VALUES (4,FALSE,TRUE); DELETE FROM Workers WHERE Terminated = TRUE; INSERT INTO Workers (ID,Terminated,Ethical_Training) VALUES (5,FALSE,TRUE); INSERT INTO Workers (ID,Terminated,Ethical_Training) VALUES (6,FALSE,TRUE);
DELETE FROM Workers WHERE Terminated = TRUE; INSERT INTO Workers (ID, Terminated, Ethical_Training) VALUES (5, FALSE, TRUE), (6, FALSE, TRUE);
List the top 3 producing countries of Dysprosium in 2019 from the 'supply_chain' table.
CREATE TABLE supply_chain (country VARCHAR(50),element VARCHAR(10),year INT,production INT); INSERT INTO supply_chain (country,element,year,production) VALUES ('China','Dysprosium',2019,1200),('Malaysia','Dysprosium',2019,800),('Australia','Dysprosium',2019,600),('China','Dysprosium',2019,1500),('Malaysia','Dysprosium',2019,900),('Australia','Dysprosium',2019,700),('China','Dysprosium',2019,1800),('Malaysia','Dysprosium',2019,1000),('Australia','Dysprosium',2019,800);
SELECT country, SUM(production) as total_production FROM supply_chain WHERE element = 'Dysprosium' AND year = 2019 GROUP BY country ORDER BY total_production DESC LIMIT 3;
What is the average media literacy score for creators by gender, for creators in Canada?
CREATE TABLE creators (id INT,gender VARCHAR(10),media_literacy_score FLOAT,country VARCHAR(20)); INSERT INTO creators (id,gender,media_literacy_score,country) VALUES (1,'Female',75.3,'Canada'),(2,'Male',82.1,'Canada'),(3,'Non-binary',68.9,'Canada');
SELECT gender, AVG(media_literacy_score) AS avg_score FROM creators WHERE country = 'Canada' GROUP BY gender;
What is the transaction volume by hour for the last week?
CREATE TABLE TransactionDates (TransactionID INT,TransactionDate DATE,TransactionTime TIME); INSERT INTO TransactionDates (TransactionID,TransactionDate,TransactionTime) VALUES (1,'2022-01-01','12:00:00'),(2,'2022-01-01','15:30:00'),(3,'2022-01-08','09:45:00');
SELECT EXTRACT(HOUR FROM TransactionTime) AS Hour, COUNT(*) AS TransactionCount FROM TransactionDates WHERE TransactionDate > NOW() - INTERVAL '7 days' GROUP BY Hour;
What are the names and carbon prices for each Canadian province?
CREATE TABLE canada_provinces (province VARCHAR(255),carbon_price FLOAT); INSERT INTO canada_provinces (province,carbon_price) VALUES ('Ontario',20.5),('Quebec',35.7),('British Columbia',40.2),('Alberta',15.9);
SELECT province, carbon_price FROM canada_provinces;
Update the region of users who live in 'New York' to 'Northeast'.
CREATE TABLE users (id INT,region VARCHAR(255),last_login_date DATE);
UPDATE users SET region = 'Northeast' WHERE region = 'New York';
What is the percentage of mobile customers who have used international roaming, segmented by country?
CREATE TABLE international_roaming_segmented (customer_id INT,used BOOLEAN,country VARCHAR(50)); INSERT INTO international_roaming_segmented (customer_id,used,country) VALUES (1,TRUE,'USA'),(2,FALSE,'Mexico'),(3,TRUE,'Canada');
SELECT country, (COUNT(CASE WHEN used = TRUE THEN 1 END) * 100.0 / COUNT(customer_id)) AS percentage FROM international_roaming_segmented GROUP BY country;
Show the mental health scores of students who have not participated in professional development programs and those who have.
CREATE TABLE student_scores (student_id INT,mental_health_score INT,participated_in_pd BOOLEAN); INSERT INTO student_scores (student_id,mental_health_score,participated_in_pd) VALUES (1,75,true),(2,80,false),(3,60,true);
SELECT mental_health_score FROM student_scores WHERE participated_in_pd = true UNION SELECT mental_health_score FROM student_scores WHERE participated_in_pd = false;
What is the total revenue for each fashion trend in the past week?
CREATE TABLE sales (id INT,item_id INT,trend TEXT,revenue FLOAT,date DATE);
SELECT trend, SUM(revenue) FROM sales WHERE date >= DATE_SUB(CURDATE(), INTERVAL 1 WEEK) GROUP BY trend;
What is the average pollution level in the Arctic region in the 'Pollution' schema?
CREATE SCHEMA Pollution;CREATE TABLE PollutionData (id INT,country TEXT,region TEXT,pollution_level REAL); INSERT INTO PollutionData (id,country,region,pollution_level) VALUES (1,'Canada','Arctic',5.5),(2,'Greenland','Arctic',5.0),(3,'Norway','Arctic',4.8),(4,'Russia','Arctic',6.0),(5,'United States','Arctic',5.2);
SELECT AVG(pollution_level) FROM Pollution.PollutionData WHERE region = 'Arctic';
What is the number of carbon offset programs implemented in 'Asia'?
CREATE TABLE carbon_offset_programs (program_id INT,program_name VARCHAR(255),location VARCHAR(255)); INSERT INTO carbon_offset_programs (program_id,program_name,location) VALUES (1,'Tree Planting Program 1','Asia'),(2,'Energy Efficiency Program 1','North America'),(3,'Tree Planting Program 2','Asia');
SELECT COUNT(*) FROM carbon_offset_programs WHERE location = 'Asia';
How many volunteers joined after participating in a community outreach event in '2021'?
CREATE TABLE volunteer_events (id INT,event_name TEXT,year INT,num_volunteers INT); INSERT INTO volunteer_events (id,event_name,year,num_volunteers) VALUES (1,'Youth Mentoring Program',2021,150),(2,'Feeding the Homeless',2021,200),(3,'Climate Action Rally',2021,100);
SELECT SUM(num_volunteers) FROM volunteer_events WHERE year = 2021 AND event_name IN (SELECT event_name FROM volunteer_events WHERE year = 2021 AND num_volunteers > 0);
List the unique types of healthcare providers in the rural healthcare system.
CREATE TABLE Providers (ID INT,Name TEXT,Type TEXT); INSERT INTO Providers VALUES (1,'Dr. Smith','Doctor'); INSERT INTO Providers VALUES (2,'Jane Doe,RN','Nurse'); INSERT INTO Providers VALUES (3,'Mobile Medical Unit','Clinic');
SELECT DISTINCT Type FROM Providers;
Delete all records from the sharks table where the weight is greater than 1000.0
CREATE TABLE sharks (id INT,species VARCHAR(255),weight FLOAT); INSERT INTO sharks (id,species,weight) VALUES (1,'Great White',2000.0),(2,'Hammerhead',150.0);
DELETE FROM sharks WHERE weight > 1000.0;
What is the total number of hospitals and clinics in each state?
CREATE TABLE facilities (id INT,name TEXT,type TEXT,state TEXT); INSERT INTO facilities (id,name,type,state) VALUES (1,'UCLA Medical Center','hospital','California');
SELECT facilities.state, COUNT(*) FROM facilities GROUP BY facilities.state;
Which bus routes in Istanbul have the lowest fare?
CREATE TABLE BusRoutes (RouteID int,Fare decimal(5,2)); INSERT INTO BusRoutes (RouteID,Fare) VALUES (1,1.50),(2,1.00),(3,1.50);
SELECT RouteID, MIN(Fare) FROM BusRoutes;
What is the average years of experience for each gender in the workforce?
CREATE TABLE workforce (id INT,name VARCHAR(50),gender VARCHAR(10),department VARCHAR(50),years_of_experience INT); INSERT INTO workforce (id,name,gender,department,years_of_experience) VALUES (1,'Employee A','Female','Engineering',6); INSERT INTO workforce (id,name,gender,department,years_of_experience) VALUES (2,'Employee B','Male','Manufacturing',4); INSERT INTO workforce (id,name,gender,department,years_of_experience) VALUES (3,'Employee C','Female','Manufacturing',8);
SELECT gender, AVG(years_of_experience) FROM workforce GROUP BY gender;
What are the total costs of all rural infrastructure projects for indigenous communities?
CREATE TABLE rural_infrastructure (id INT,project_name VARCHAR(50),project_type VARCHAR(50),community_type VARCHAR(50),cost DECIMAL(10,2)); INSERT INTO rural_infrastructure VALUES (1,'Solar Irrigation System','Agricultural Innovation','Indigenous',25000.00),(2,'Modern Greenhouse','Agricultural Innovation','Farmers Association',30000.00),(3,'Precision Agriculture Tools','Agricultural Innovation','Indigenous',28000.00);
SELECT SUM(cost) FROM rural_infrastructure WHERE community_type = 'Indigenous';
Delete energy efficiency stats for a specific building
CREATE TABLE buildings (id INT,name TEXT); CREATE TABLE energy_efficiency_stats (building_id INT,year INT,energy_savings FLOAT); INSERT INTO buildings (id,name) VALUES (1,'Headquarters'),(2,'Branch Office'); INSERT INTO energy_efficiency_stats (building_id,year,energy_savings) VALUES (1,2020,20000.00),(1,2021,25000.00),(2,2020,15000.00);
WITH cte_delete AS (DELETE FROM energy_efficiency_stats WHERE building_id = 1) SELECT * FROM buildings WHERE id = 1;
Show the names of rural infrastructure projects and their respective start dates.
CREATE TABLE rural_infrastructure (id INT,project_name VARCHAR(255),start_date DATE); INSERT INTO rural_infrastructure (id,project_name,start_date) VALUES (1,'Road Construction','2021-01-01'),(2,'Bridge Building','2020-06-15');
SELECT project_name, start_date FROM rural_infrastructure;
List the virtual tours in Indonesia that were launched after 2021-06-01.
CREATE TABLE virtual_tour_launches (tour_id INT,tour_name TEXT,launch_date DATE); INSERT INTO virtual_tour_launches (tour_id,tour_name,launch_date) VALUES (1,'Indonesian Rainforest Tour','2022-02-01'),(2,'European Art Tour','2021-06-15');
SELECT tour_name FROM virtual_tour_launches WHERE launch_date > '2021-06-01' AND tour_name LIKE '%Indonesia%';
List the countries with travel advisories and their respective regions, along with the total expenditure by international visitors for the last available year.
CREATE TABLE travel_advisories_ext (id INT,country VARCHAR(50),region VARCHAR(50),travel_warning BOOLEAN,advisory_text TEXT,year INT); INSERT INTO travel_advisories_ext (id,country,region,travel_warning,advisory_text,year) VALUES (1,'Thailand','Southeast Asia',true,'Avoid non-essential travel due to civil unrest.',2022);
SELECT ta.country, ta.region, t.total_expenditure FROM travel_advisories_ext ta JOIN tourism_spending t ON ta.country = t.country AND t.year = (SELECT MAX(year) FROM tourism_spending WHERE country = ta.country) WHERE ta.travel_warning = true;
How many digital divide projects are led by women in the technology for social good domain?
CREATE TABLE Projects (ProjectID INT,ProjectName VARCHAR(50),LeaderGender VARCHAR(10),Domain VARCHAR(50)); INSERT INTO Projects (ProjectID,ProjectName,LeaderGender,Domain) VALUES (1,'Bridging the Gap','Female','Social Good'); INSERT INTO Projects (ProjectID,ProjectName,LeaderGender,Domain) VALUES (2,'Tech4All','Male','Social Good');
SELECT COUNT(*) FROM Projects WHERE LeaderGender = 'Female' AND Domain = 'Social Good';
What are the top 5 most common types of security incidents in the 'IT' department?
CREATE TABLE security_incidents (id INT,incident_type VARCHAR(50),department VARCHAR(50));
SELECT incident_type, COUNT(*) as num_incidents FROM security_incidents WHERE department = 'IT' GROUP BY incident_type ORDER BY num_incidents DESC LIMIT 5;
What is the average production time for garments in the "Autumn 2022" collection?
CREATE TABLE Autumn2022 (garment_id INT,garment_name VARCHAR(50),production_time INT); INSERT INTO Autumn2022 (garment_id,garment_name,production_time) VALUES (1,'Wool Coat',3),(2,'Cotton Shirt',1),(3,'Denim Jeans',2),(4,'Fleece Hoodie',2);
SELECT AVG(production_time) FROM Autumn2022;
What percentage of orders contain at least one vegetarian menu item?
CREATE TABLE orders (order_id INT,dish_id INT); CREATE TABLE dishes (dish_id INT,dish_name VARCHAR(255),category VARCHAR(255)); INSERT INTO dishes (dish_id,dish_name,category) VALUES (1,'Quinoa Salad','Vegetarian'),(2,'Pizza Margherita','Vegetarian'),(3,'Chicken Alfredo','Non-vegetarian'); INSERT INTO orders (order_id,dish_id) VALUES (1,1),(2,3),(3,1),(4,2),(5,1),(6,3);
SELECT 100.0 * COUNT(DISTINCT o.order_id) / (SELECT COUNT(DISTINCT order_id) FROM orders) AS vegetarian_order_percentage FROM orders o JOIN dishes d ON o.dish_id = d.dish_id WHERE d.category = 'Vegetarian';
Delete all records from the 'energy_storage' table that have a capacity less than 50.
CREATE TABLE energy_storage (id INT,name VARCHAR(255),capacity FLOAT); INSERT INTO energy_storage (id,name,capacity) VALUES (1,'Storage A',75.2),(2,'Storage B',30.1),(3,'Storage C',60.0);
DELETE FROM energy_storage WHERE capacity < 50;
Delete all travel advisories for South America in the last 12 months.
CREATE TABLE TravelAdvisories (id INT,country VARCHAR(50),advisory VARCHAR(50),start_date DATE); INSERT INTO TravelAdvisories (id,country,advisory,start_date) VALUES (1,'Brazil','Avoid crowded areas','2022-01-01');
DELETE FROM TravelAdvisories WHERE country LIKE 'South%' AND start_date >= DATE_SUB(CURDATE(), INTERVAL 12 MONTH);
Add a new record for the "Nets" team to the "teams" table
CREATE TABLE teams (team_id INT PRIMARY KEY,team_name VARCHAR(50),city VARCHAR(50),sport VARCHAR(50));
INSERT INTO teams (team_id, team_name, city, sport) VALUES (5, 'Nets', 'Brooklyn', 'Basketball');
How many employees were hired in each quarter of 2022, for companies with more than 500 employees?
CREATE TABLE Companies (company_id INT,num_employees INT,registration_date DATE); INSERT INTO Companies (company_id,num_employees,registration_date) VALUES (1,1000,'2022-01-01'); INSERT INTO Companies (company_id,num_employees,registration_date) VALUES (2,750,'2022-01-01'); INSERT INTO Companies (company_id,num_employees,registration_date) VALUES (3,550,'2022-01-01');
SELECT DATE_FORMAT(c.registration_date, '%Y-%m') as quarter, COUNT(*) as num_hired FROM Companies c WHERE c.num_employees > 500 AND c.registration_date BETWEEN '2022-01-01' AND '2022-12-31' GROUP BY quarter;
Identify the maximum safety incident rate in the chemical industry in Japan, in the last 3 years.
CREATE TABLE incidents (id INT,industry VARCHAR(255),incident_rate FLOAT,incident_date DATE,country VARCHAR(255));
SELECT country, MAX(incident_rate) as max_rate FROM incidents WHERE industry = 'chemical' AND country = 'Japan' AND incident_date > DATE_SUB(CURDATE(), INTERVAL 3 YEAR) GROUP BY country;
Update 'impact' to 9.0 for records in 'drought_impact' view where 'region' is 'Texas'
CREATE TABLE drought_impact (id INT PRIMARY KEY,region VARCHAR(20),impact FLOAT);
UPDATE drought_impact SET impact = 9.0 WHERE region = 'Texas';
What is the name and age of government employees who have been working for more than 20 years?
CREATE TABLE GovernmentEmployees (EmployeeID INT,Name VARCHAR(50),Age INT,YearsOfService INT); CREATE TABLE EmployeePromotion (EmployeeID INT,PromotionDate DATE); INSERT INTO GovernmentEmployees VALUES (1,'John',45,22),(2,'Jane',50,25),(3,'Mike',30,15); INSERT INTO EmployeePromotion VALUES (1,'2002-01-01'),(2,'2010-01-01'),(3,'2005-01-01');
SELECT Name, Age FROM GovernmentEmployees INNER JOIN EmployeePromotion ON GovernmentEmployees.EmployeeID = EmployeePromotion.EmployeeID WHERE YearsOfService > 20;
What is the cultural competency score for each community health worker by their language proficiency?
CREATE TABLE CulturalCompetency (WorkerID INT,LanguageProficiency VARCHAR(255),Score INT); INSERT INTO CulturalCompetency (WorkerID,LanguageProficiency,Score) VALUES (1,'English',90),(2,'Spanish',85),(3,'Mandarin',95),(4,'French',80),(5,'Arabic',90);
SELECT LanguageProficiency, AVG(Score) as AvgScore FROM CulturalCompetency GROUP BY LanguageProficiency;