instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
Insert a new row in the dapps table with name 'Axie Infinity' if it doesn't exist.
CREATE TABLE if not exists dapps (id INT PRIMARY KEY,name TEXT,category TEXT,platform TEXT); INSERT INTO dapps (id,name,category,platform) VALUES (1,'CryptoKitties','NFT','Ethereum'),(2,'Decentraland','Virtual World','Ethereum'),(3,'Aavegotchi','NFT','Ethereum');
INSERT INTO dapps (name, category, platform) SELECT 'Axie Infinity', 'GameFi', 'Ethereum' WHERE NOT EXISTS (SELECT * FROM dapps WHERE name = 'Axie Infinity');
Which crop was harvested the earliest?
CREATE TABLE Crops (id INT,crop TEXT,harvest_date DATE);INSERT INTO Crops (id,crop,harvest_date) VALUES (1,'Corn','2021-07-01'),(2,'Potatoes','2021-06-15'),(3,'Carrots','2021-09-15'),(4,'Beans','2021-08-01');
SELECT MIN(harvest_date) Min_Harvest_Date FROM Crops;
What is the average playtime per session for players from Australia?
CREATE TABLE PlayerSessionTimes (PlayerID int,SessionID int,Playtime int); INSERT INTO PlayerSessionTimes (PlayerID,SessionID,Playtime) VALUES (1,1,100),(1,2,120),(2,1,150),(2,2,180),(3,1,200),(3,2,220),(4,1,250),(4,2,280),(5,1,300),(5,2,320),(1,3,350),(2,3,380),(3,3,400),(4,3,450),(5,3,500),(1,4,550),(2,4,600),(3,4,65...
SELECT AVG(Playtime) FROM PlayerSessionTimes JOIN (SELECT PlayerID, AVG(Playtime) AS AvgPlaytime FROM PlayerSessionTimes GROUP BY PlayerID) AS AvgPlaytimes ON PlayerSessionTimes.PlayerID = AvgPlaytimes.PlayerID WHERE Country = 'Australia';
How many times has each activity been booked in the 'activities' table for the month of July 2022?
CREATE TABLE activities (activity_id INT,activity_name TEXT,booking_date DATE); INSERT INTO activities (activity_id,activity_name,booking_date) VALUES (1,'Bike Tour','2022-07-01'),(2,'Walking Tour','2022-07-03'),(3,'Cooking Class','2022-07-02'),(4,'Museum Visit','2022-07-05');
SELECT activity_name, COUNT(*) AS bookings_per_activity FROM activities WHERE EXTRACT(MONTH FROM booking_date) = 7 GROUP BY activity_name;
Find national security incidents involving foreign entities
CREATE TABLE Incident (id INT PRIMARY KEY,name VARCHAR(255),description TEXT,incident_date DATE,incident_type VARCHAR(255)); CREATE TABLE ForeignEntity (id INT PRIMARY KEY,name VARCHAR(255),country VARCHAR(255)); INSERT INTO ForeignEntity (id,name,country) VALUES (1,'Moscow','Russia'),(2,'Beijing','China'); INSERT INTO...
SELECT i.name, i.incident_date, i.incident_type, f.name AS foreign_entity_name FROM Incident i INNER JOIN ForeignEntity f ON i.foreign_entity_id = f.id;
What is the minimum salary for workers in the 'transportation' industry?
CREATE TABLE transportation_workers (id INT,name VARCHAR(255),industry VARCHAR(255),salary DECIMAL(10,2)); INSERT INTO transportation_workers (id,name,industry,salary) VALUES (1,'Mark Brown','transportation',45000.00),(2,'Laura Johnson','transportation',50000.00);
SELECT MIN(salary) FROM transportation_workers WHERE industry = 'transportation';
What is the maximum area, in square kilometers, of farmland dedicated to any single crop type?
CREATE TABLE crops (id INT,crop_name VARCHAR(50),area_ha INT); INSERT INTO crops (id,crop_name,area_ha) VALUES (1,'Corn',500),(2,'Soybeans',350),(3,'Wheat',420);
SELECT MAX(area_sq_km) as max_area_sq_km FROM (SELECT crop_name, SUM(area_ha * 0.01) as area_sq_km FROM crops GROUP BY crop_name) as subquery;
What is the maximum number of calories burned by a member during a single workout?
CREATE TABLE Members (MemberID INT,Name VARCHAR(50)); INSERT INTO Members (MemberID,Name) VALUES (1,'John Doe'); INSERT INTO Members (MemberID,Name) VALUES (2,'Jane Doe'); CREATE TABLE Workouts (WorkoutID INT,WorkoutDate DATE,Calories INT,MemberID INT); INSERT INTO Workouts (WorkoutID,WorkoutDate,Calories,MemberID) VAL...
SELECT MAX(Workouts.Calories) FROM Workouts;
What is the total revenue for each restaurant in the 'rural' region, grouped by restaurant category?
CREATE TABLE restaurants (id INT,name TEXT,region TEXT,category TEXT); INSERT INTO restaurants (id,name,region,category) VALUES (1,'Restaurant A','urban','fine_dining'),(2,'Restaurant B','rural','casual_dining'),(3,'Restaurant C','rural','fine_dining'); CREATE TABLE revenue (restaurant_id INT,revenue INT); INSERT INTO ...
SELECT r.category, SUM(re.revenue) as total_revenue FROM restaurants r JOIN revenue re ON r.id = re.restaurant_id WHERE r.region = 'rural' GROUP BY r.category;
Show the continents with the top 3 highest average international visitor count in 2021.
CREATE TABLE VisitorStatistics (id INT,continent VARCHAR(50),year INT,visitors INT,PRIMARY KEY(id)); INSERT INTO VisitorStatistics (id,continent,year,visitors) VALUES (1,'Asia',2021,10000),(2,'Europe',2021,15000),(3,'Africa',2021,12000),(4,'Asia',2021,11000),(5,'Europe',2021,14000),(6,'Africa',2021,13000),(7,'Asia',202...
SELECT continent, AVG(visitors) AS avg_visitors FROM VisitorStatistics WHERE year = 2021 GROUP BY continent ORDER BY avg_visitors DESC LIMIT 3;
List all creative AI applications that have been evaluated as high risk.
CREATE TABLE applications (id INT,name VARCHAR(100),risk FLOAT); INSERT INTO applications (id,name,risk) VALUES (1,'AI Artist',0.8),(2,'AI Writer',0.6),(3,'AI Musician',0.9); CREATE TABLE risk_levels (id INT,level VARCHAR(10)); INSERT INTO risk_levels (id,level) VALUES (1,'Low'),(2,'Medium'),(3,'High');
SELECT applications.name FROM applications INNER JOIN risk_levels ON applications.risk = risk_levels.id WHERE risk_levels.level = 'High';
Insert a new drug 'DrugF' into the 'drug_approval' table.
CREATE TABLE drug_approval (drug_id INT,drug_name VARCHAR(255),approval_date DATE,manufacturer VARCHAR(255));
INSERT INTO drug_approval (drug_id, drug_name, approval_date, manufacturer) VALUES (3, 'DrugF', CURDATE(), 'ManufacturerC');
Find the maximum sustainable material usage in garments produced in Europe.
CREATE TABLE garment_production (id INT,material_percentage DECIMAL,region VARCHAR(20)); INSERT INTO garment_production (id,material_percentage,region) VALUES (1,85.00,'Europe'),(2,92.00,'Asia'),(3,88.00,'Europe');
SELECT MAX(material_percentage) FROM garment_production WHERE region = 'Europe';
Show the total CO2 emissions reduction (in metric tons) for Electric Vehicle charging stations in the top 3 states
CREATE TABLE ev_charging_stations (id INT,state VARCHAR(50),name VARCHAR(100),co2_emissions_reduction_tons FLOAT);
SELECT state, SUM(co2_emissions_reduction_tons) as total_reduction FROM ev_charging_stations GROUP BY state ORDER BY total_reduction DESC LIMIT 3;
List all smart contracts associated with developers from African countries.
CREATE TABLE Developers (DeveloperId INT,DeveloperName VARCHAR(50),Country VARCHAR(50)); CREATE TABLE SmartContracts (ContractId INT,ContractName VARCHAR(50),DeveloperId INT); INSERT INTO Developers (DeveloperId,DeveloperName,Country) VALUES (1,'Efosa','Nigeria'); INSERT INTO Developers (DeveloperId,DeveloperName,Count...
SELECT sc.ContractName FROM SmartContracts sc INNER JOIN Developers d ON sc.DeveloperId = d.DeveloperId WHERE d.Country IN ('Nigeria', 'Egypt');
Determine the number of Shariah-compliant loans issued per month, in 2022.
CREATE TABLE shariah_loans (id INT,client_name VARCHAR(50),issue_date DATE,amount FLOAT);
SELECT DATE_TRUNC('month', issue_date) as month, COUNT(*) as num_loans FROM shariah_loans WHERE issue_date >= '2022-01-01' AND issue_date < '2023-01-01' GROUP BY month;
Which materials had a higher recycling rate in 2020 compared to 2019?
CREATE TABLE recycling_rates(year INT,material VARCHAR(255),recycling_rate DECIMAL(5,2)); INSERT INTO recycling_rates VALUES (2018,'Paper',0.45),(2018,'Plastic',0.20),(2018,'Glass',0.35),(2019,'Paper',0.47),(2019,'Plastic',0.21),(2019,'Glass',0.36),(2020,'Paper',0.50),(2020,'Plastic',0.23),(2020,'Glass',0.38);
SELECT material, (r20.recycling_rate - r19.recycling_rate) AS difference FROM recycling_rates r20 JOIN recycling_rates r19 ON r20.material = r19.material WHERE r20.year = 2020 AND r19.year = 2019 AND r20.recycling_rate > r19.recycling_rate;
Insert a new record into the crime_incidents table for the 'Vandalism' incident type and an incident date of '2022-05-12'
CREATE TABLE crime_incidents (id INT PRIMARY KEY,incident_date DATE,incident_type VARCHAR(255));
INSERT INTO crime_incidents (incident_date, incident_type) VALUES ('2022-05-12', 'Vandalism');
List all renewable energy projects in the city of Chicago that involve solar power.
CREATE TABLE renewable_energy (project_id INT,project_name VARCHAR(255),city VARCHAR(255),state VARCHAR(255),technology VARCHAR(255));
SELECT project_name FROM renewable_energy WHERE city = 'Chicago' AND technology = 'Solar';
How many animals were admitted to the rescue center in the last 6 months from the 'Mountain' region?
CREATE TABLE rescue_center (id INT,animal_name VARCHAR(50),date_admitted DATE,region VARCHAR(20)); INSERT INTO rescue_center (id,animal_name,date_admitted,region) VALUES (1,'Fox','2021-01-05','Mountain'); INSERT INTO rescue_center (id,animal_name,date_admitted,region) VALUES (2,'Eagle','2021-06-10','Forest');
SELECT COUNT(animal_name) FROM rescue_center WHERE date_admitted BETWEEN DATE_SUB(CURRENT_DATE, INTERVAL 6 MONTH) AND CURRENT_DATE AND region = 'Mountain';
Find the average budget allocation for education services in each state
CREATE TABLE states (state_id INT,state_name TEXT,budget_allocation FLOAT);CREATE TABLE education_services (service_id INT,state_id INT,budget FLOAT);
SELECT s.state_name, AVG(es.budget) FROM states s INNER JOIN education_services es ON s.state_id = es.state_id GROUP BY s.state_name;
Which non-profit organization received the highest donation in '2021'?
CREATE TABLE Donations (DonationID int,DonationAmount decimal(10,2),DonationYear int,NonProfitName varchar(50)); INSERT INTO Donations (DonationID,DonationAmount,DonationYear,NonProfitName) VALUES (1,5000,2021,'Children Education Fund'),(2,7000,2021,'Disaster Relief Foundation'),(3,3000,2021,'Animal Welfare Society');
SELECT NonProfitName, MAX(DonationAmount) as HighestDonation FROM Donations WHERE DonationYear = 2021 GROUP BY NonProfitName;
Delete fairness AI datasets after '2021-12-31'
CREATE TABLE fairness_datasets (id INT,name VARCHAR(255),description VARCHAR(255),last_modified DATETIME); INSERT INTO fairness_datasets (id,name,description,last_modified) VALUES (1,'Adult Census Income','Income dataset for adults with sensitive features','2021-12-30 15:00:00');
DELETE FROM fairness_datasets WHERE last_modified > '2021-12-31 00:00:00';
What is the total sales revenue for each drug approved by the FDA in 2019?
CREATE TABLE drug_approval (drug_name VARCHAR(255),approval_body VARCHAR(255),approval_year INT); CREATE TABLE sales_revenue (drug_name VARCHAR(255),sales_revenue FLOAT,approval_year INT); INSERT INTO drug_approval (drug_name,approval_body,approval_year) VALUES ('DrugA','FDA',2019),('DrugB','EMA',2018),('DrugC','FDA',2...
SELECT drug_approval.drug_name, SUM(sales_revenue) FROM drug_approval INNER JOIN sales_revenue ON drug_approval.drug_name = sales_revenue.drug_name WHERE drug_approval.approval_body = 'FDA' AND drug_approval.approval_year = 2019 GROUP BY drug_name;
What is the total number of farmers in the 'agriculture_innovation' table, partitioned by their country and sorted by the number of farmers in descending order?;
CREATE TABLE agriculture_innovation (id INT,name VARCHAR(50),country VARCHAR(50),number_of_farmers INT); INSERT INTO agriculture_innovation VALUES (1,'John Doe','USA',200),(2,'Jane Smith','Canada',250),(3,'Pedro Sanchez','Mexico',300),(4,'Maria Garcia','Brazil',400),(5,'Jacques Dupont','France',150);
SELECT country, SUM(number_of_farmers) as total_farmers FROM agriculture_innovation GROUP BY country ORDER BY total_farmers DESC;
What is the maximum depth recorded for marine species in the Mammalia phylum?
CREATE TABLE marine_species (species_id INT,species_name VARCHAR(100),max_depth FLOAT,phylum VARCHAR(50),order_name VARCHAR(50),family VARCHAR(50));
SELECT MAX(max_depth) FROM marine_species WHERE phylum = 'Mammalia';
What is the average age of inmates in each prison in the 'prisons' table?
CREATE TABLE prisons (id INT,name VARCHAR(50),location VARCHAR(50),capacity INT,population INT,avg_age FLOAT); INSERT INTO prisons (id,name,location,capacity,population,avg_age) VALUES (1,'Folsom State Prison','California',2600,2100,35.5),(2,'Sing Sing Correctional Facility','New York',1932,1585,42.3);
SELECT name, AVG(avg_age) FROM prisons GROUP BY name;
Find the intersection of emergency calls and crimes reported in the Central and Westside districts.
CREATE TABLE Districts (district_name TEXT,calls INTEGER,crimes INTEGER); INSERT INTO Districts (district_name,calls,crimes) VALUES ('Central',300,200),('Westside',250,150);
SELECT calls, crimes FROM Districts WHERE district_name = 'Central' INTERSECT SELECT calls, crimes FROM Districts WHERE district_name = 'Westside';
What is the total number of high severity incidents in the 'IncidentReports' table?
CREATE TABLE IncidentReports (id INT,incident_name VARCHAR(50),severity VARCHAR(10),incident_type VARCHAR(50)); INSERT INTO IncidentReports (id,incident_name,severity,incident_type) VALUES (1,'Incident1','High','Malware'),(2,'Incident2','Medium','Phishing'),(3,'Incident3','Low','Unpatched Software'),(4,'Incident4','Hig...
SELECT COUNT(*) as total_high_severity_incidents FROM IncidentReports WHERE severity = 'High';
List all esports events that are not in the USA.
CREATE TABLE esports_events (event_id INT,event_name VARCHAR(50),location VARCHAR(50)); INSERT INTO esports_events (event_id,event_name,location) VALUES (1,'DreamHack','Sweden'),(2,'ESL One','Germany'),(3,'PGN','Poland'),(4,'CDL','USA'),(5,'BlizzCon','USA');
SELECT event_name FROM esports_events WHERE location NOT IN ('USA');
What is the total quantity of 'Casual Shirts' sold in the 'North' region for each quarter in 2021?
CREATE TABLE Sales (product VARCHAR(20),region VARCHAR(10),quarter INT,year INT,quantity INT); INSERT INTO Sales (product,region,quarter,year,quantity) VALUES ('Casual Shirts','North',1,2021,350),('Casual Shirts','North',2,2021,400),('Casual Shirts','North',3,2021,325),('Casual Shirts','North',4,2021,450);
SELECT region, quarter, SUM(quantity) as total_quantity FROM Sales WHERE product = 'Casual Shirts' AND year = 2021 GROUP BY region, quarter;
What is the minimum speed in knots for the vessel 'IslandHopper'?
CREATE TABLE Vessels(Id INT,Name VARCHAR(255),AverageSpeed DECIMAL(5,2)); INSERT INTO Vessels VALUES (1,'VesselA',15.5),(2,'IslandHopper',18.3),(3,'VesselC',20.2);
SELECT MIN(v.AverageSpeed) FROM Vessels v WHERE v.Name = 'IslandHopper';
Which countries have the highest iron ore production in 2020?
CREATE TABLE production (country VARCHAR(50),material VARCHAR(50),year INT,tons INT); INSERT INTO production (country,material,year,tons) VALUES ('Australia','Iron Ore',2020,900),('Brazil','Iron Ore',2020,400),('South Africa','Iron Ore',2020,300),('China','Iron Ore',2020,250),('India','Iron Ore',2020,200);
SELECT country, SUM(tons) as total_tons FROM production WHERE material = 'Iron Ore' AND year = 2020 GROUP BY country ORDER BY total_tons DESC LIMIT 3;
What is the average number of workplace safety violations recorded for each union in New York?
CREATE TABLE unions (id INT,name VARCHAR(255),state VARCHAR(255)); CREATE TABLE safety_violations (id INT,union_id INT,violation_count INT); INSERT INTO unions (id,name,state) VALUES (1,'CWA','New York'); INSERT INTO safety_violations (id,union_id,violation_count) VALUES (1,1,55);
SELECT u.name, AVG(sv.violation_count) as avg_violations FROM unions u JOIN safety_violations sv ON u.id = sv.union_id WHERE u.state = 'New York' GROUP BY u.name;
What is the minimum age of athletes in the baseball_teams table?
CREATE TABLE baseball_teams (team_name TEXT,athlete_name TEXT,athlete_age INTEGER);
SELECT MIN(athlete_age) FROM baseball_teams;
Which products have safety incidents in the Asia-Pacific region?
CREATE TABLE product_safety_records (id INT,product_id INT,incident_date DATE,incident_description VARCHAR(255)); INSERT INTO product_safety_records (id,product_id,incident_date,incident_description) VALUES (1,101,'2020-01-01','Minor irritation'),(2,103,'2019-12-15','Allergy reported'),(3,102,'2019-11-30','No incidents...
SELECT product_id FROM product_safety_records WHERE incident_description <> 'No incidents' AND country = 'Asia-Pacific';
How many cargo weight records were created per day for the last month?
CREATE TABLE vessels (id INT,name VARCHAR(255)); CREATE TABLE cargo (id INT,vessel_id INT,weight INT,timestamp TIMESTAMP); INSERT INTO vessels VALUES (1,'Vessel A'),(2,'Vessel B'); INSERT INTO cargo VALUES (1,1,10000,'2021-01-01 10:00:00'),(2,1,12000,'2021-01-15 12:00:00'),(3,2,15000,'2021-01-03 08:00:00'),(4,1,11000,'...
SELECT DATE(c.timestamp) as date, COUNT(*) as records FROM cargo c WHERE c.timestamp >= DATE_SUB(CURRENT_TIMESTAMP, INTERVAL 1 MONTH) GROUP BY date;
What is the average property tax for each city?
CREATE TABLE tax (id INT,amount FLOAT,city VARCHAR(20)); INSERT INTO tax (id,amount,city) VALUES (1,5000,'Denver'),(2,6000,'Portland'),(3,4000,'NYC'),(4,7000,'Austin'); CREATE TABLE property (id INT,city VARCHAR(20),tax_id INT); INSERT INTO property (id,city,tax_id) VALUES (1,'Denver',1),(2,'Portland',2),(3,'NYC',3),(4...
SELECT p.city, AVG(t.amount) FROM property p JOIN tax t ON p.tax_id = t.id GROUP BY p.city;
Find the number of museums in each state in the USA.
CREATE TABLE museums (id INT,museum_name VARCHAR(255),state VARCHAR(255)); INSERT INTO museums (id,museum_name,state) VALUES (1,'The Met','New York'),(2,'The Guggenheim','New York'),(3,'The MoMA','New York'),(4,'The Getty','California'),(5,'The Broad','California');
SELECT state, COUNT(*) FROM museums GROUP BY state;
What is the total number of hours spent on lifelong learning activities by teachers who have completed professional development courses in the last year?
CREATE TABLE lifelong_learning_activities (activity_id INT,teacher_id INT,hours_spent INT); INSERT INTO lifelong_learning_activities (activity_id,teacher_id,hours_spent) VALUES (1,1,5),(2,1,6),(3,2,7),(4,2,8),(5,3,9),(6,3,10);
SELECT SUM(lifelong_learning_activities.hours_spent) as total_hours FROM lifelong_learning_activities JOIN teachers ON teachers.teacher_id = lifelong_learning_activities.teacher_id JOIN professional_development_courses ON teachers.teacher_id = professional_development_courses.teacher_id WHERE professional_development_c...
Add a new bill to the 'bills' table
CREATE TABLE bills (id INT PRIMARY KEY,title VARCHAR(255),sponsor_id INT,status VARCHAR(255));
INSERT INTO bills (id, title, sponsor_id, status) VALUES (1, 'Public Space Enhancement Act', 1, 'Introduced'), (2, 'Affordable Housing Development Act', 2, 'Passed');
What is the daily sales trend for the top 3 eco-friendly retailers in the past week?
CREATE TABLE Retailer (id INT,name VARCHAR(255),eco_friendly BOOLEAN); CREATE TABLE Sales (id INT,retailer_id INT,sale_date DATE,revenue FLOAT);
SELECT r.name, sale_date, SUM(revenue) as daily_sales FROM Sales s JOIN Retailer r ON s.retailer_id = r.id WHERE retailer_id IN (SELECT id FROM Retailer WHERE eco_friendly = true ORDER BY SUM(revenue) DESC LIMIT 3) AND sale_date >= (CURRENT_DATE - INTERVAL '1 week') GROUP BY ROLLUP(r.name, sale_date) ORDER BY r.name, s...
What is the maximum caloric content for dishes in each cuisine type?
CREATE TABLE CuisineTypes (CuisineTypeID INT,CuisineType VARCHAR(50));CREATE TABLE Dishes (DishID INT,DishName VARCHAR(50),CuisineTypeID INT,CaloricContent INT); INSERT INTO CuisineTypes VALUES (1,'Italian'),(2,'Chinese'),(3,'Indian'); INSERT INTO Dishes VALUES (1,'Pizza Margherita',1,500),(2,'Spaghetti Bolognese',1,70...
SELECT ct.CuisineType, MAX(d.CaloricContent) as MaxCaloricContent FROM CuisineTypes ct JOIN Dishes d ON ct.CuisineTypeID = d.CuisineTypeID GROUP BY ct.CuisineType;
What is the maximum number of students in a classroom for teachers in the 'ClassroomSize' table who teach more than 30 students?
CREATE TABLE ClassroomSize (id INT,name TEXT,students_in_classroom INT); INSERT INTO ClassroomSize (id,name,students_in_classroom) VALUES (1,'Pam',28),(2,'Sam',35),(3,'Terry',25);
SELECT MAX(students_in_classroom) FROM ClassroomSize WHERE students_in_classroom > 30;
Calculate the average weekly production cost for the 'Nano Polymer' chemical
CREATE TABLE weekly_cost (chemical VARCHAR(20),week INT,year INT,cost FLOAT); INSERT INTO weekly_cost (chemical,week,year,cost) VALUES ('Nano Polymer',1,2019,100.25),('Nano Polymer',2,2019,105.33),('Nano Polymer',3,2019,110.10),('Nano Polymer',1,2020,115.00),('Nano Polymer',2,2020,120.00),('Nano Polymer',3,2020,125.00)...
SELECT AVG(cost) FROM weekly_cost WHERE chemical = 'Nano Polymer';
Create view 'vw_emergency_contacts' with columns 'id', 'name', 'phone_number' based on 'emergency_contacts' table
CREATE TABLE emergency_contacts (id INT,name TEXT,phone_number TEXT); INSERT INTO emergency_contacts (id,name,phone_number) VALUES (1,'John Doe','1234567890'),(2,'Jane Smith','0987654321'); CREATE VIEW vw_emergency_contacts AS SELECT id,name,phone_number FROM emergency_contacts;
CREATE VIEW vw_emergency_contacts AS SELECT id, name, phone_number FROM emergency_contacts;
How many games are in the 'Racing' genre?
Game_Design
SELECT COUNT(*) FROM Game_Design WHERE Genre = 'Racing';
How many spacecraft were launched by Chinese companies before 2000?
CREATE TABLE Spacecraft (id INT,name VARCHAR(50),manufacturer VARCHAR(50),launch_date DATE); INSERT INTO Spacecraft (id,name,manufacturer,launch_date) VALUES (1,'Shenzhou 1','CNSA','1999-11-20'); INSERT INTO Spacecraft (id,name,manufacturer,launch_date) VALUES (2,'Tanwen 1','CNSA','1990-04-26');
SELECT COUNT(s.id) as spacecraft_count FROM Spacecraft s INNER JOIN Manufacturer m ON s.manufacturer = m.name WHERE m.country = 'China' AND s.launch_date < '2000-01-01';
What is the average coal production per machine by region, sorted by the highest average?
CREATE TABLE CoalMines (Region VARCHAR(255),MineID INT,Production INT,MachineType VARCHAR(255)); INSERT INTO CoalMines (Region,MineID,Production,MachineType) VALUES ('North',1,500,'Excavator'),('North',2,700,'Shovel'),('South',1,300,'Excavator'),('South',2,600,'Shovel'),('East',1,800,'Excavator'),('East',2,900,'Shovel'...
SELECT Region, AVG(Production) as Avg_Production FROM CoalMines GROUP BY Region ORDER BY Avg_Production DESC;
How many employees were hired in the last six months in the Sales department?
CREATE TABLE Employees (Employee_ID INT PRIMARY KEY,First_Name VARCHAR(30),Last_Name VARCHAR(30),Department VARCHAR(30),Hire_Date DATE); INSERT INTO Employees (Employee_ID,First_Name,Last_Name,Department,Hire_Date) VALUES (1,'Charlie','Brown','Sales','2022-01-15'); INSERT INTO Employees (Employee_ID,First_Name,Last_Nam...
SELECT COUNT(*) FROM Employees WHERE Department = 'Sales' AND Hire_Date >= DATE_SUB(CURDATE(), INTERVAL 6 MONTH);
What is the total number of mining operations in the state of California?
CREATE TABLE mining_operations (id INT,name TEXT,location TEXT); INSERT INTO mining_operations (id,name,location) VALUES (1,'Gold Ridge Mine','California');
SELECT COUNT(*) FROM mining_operations WHERE location = 'California';
What is the average ticket price for concerts in the United States in 2022?
CREATE TABLE ConcertTicketPrices (country VARCHAR(255),year INT,price FLOAT);
SELECT AVG(price) FROM ConcertTicketPrices WHERE country = 'United States' AND year = 2022;
How many health equity metrics were added in each month of 2021?
CREATE TABLE health_equity_metrics (id INT,metric_name VARCHAR(50),add_date DATE); INSERT INTO health_equity_metrics (id,metric_name,add_date) VALUES (1,'Income Inequality','2021-02-03'),(2,'Race-based Disparities','2021-04-05'),(3,'Healthcare Access','2021-06-07'),(4,'Education Levels','2021-08-09');
SELECT DATE_FORMAT(add_date, '%Y-%m') as month, COUNT(*) as num_metrics FROM health_equity_metrics GROUP BY month;
What is the minimum number of reviews for hotels in Canada?
CREATE TABLE hotels (id INT,name TEXT,country TEXT,reviews INT); INSERT INTO hotels (id,name,country,reviews) VALUES (1,'Hotel A','Canada',120),(2,'Hotel B','Canada',80),(3,'Hotel C','Canada',50);
SELECT MIN(reviews) FROM hotels WHERE country = 'Canada';
Find the number of transactions per month for the past year for a specific client
CREATE TABLE transactions (transaction_id INT PRIMARY KEY,client_id INT,transaction_date DATE);
SELECT MONTH(transaction_date) AS month, COUNT(*) FROM transactions WHERE client_id = 1 AND transaction_date >= DATE_SUB(NOW(), INTERVAL 1 YEAR) GROUP BY month;
Calculate the total quantity of items in Warehouse D for February 2023
CREATE TABLE Warehouse (id INT,name VARCHAR(50),total_quantity INT,date DATE); INSERT INTO Warehouse (id,name,total_quantity,date) VALUES (1,'Warehouse D',500,'2023-02-01');
SELECT SUM(total_quantity) FROM Warehouse WHERE name = 'Warehouse D' AND date = '2023-02-01';
Delete data from the table for cultural competency
CREATE TABLE cultural_competency (id INT PRIMARY KEY,state VARCHAR(2),year INT,training_hours FLOAT);
DELETE FROM cultural_competency WHERE state = 'NY';
How many peacekeeping missions were conducted by Bangladesh in 2016?
CREATE TABLE bangladesh_missions (year INT,mission_type VARCHAR(50),num_missions INT); INSERT INTO bangladesh_missions (year,mission_type,num_missions) VALUES (2016,'peacekeeping',10),(2017,'peacekeeping',11),(2018,'peacekeeping',12),(2019,'peacekeeping',13),(2020,'peacekeeping',14),(2021,'peacekeeping',15);
SELECT num_missions FROM bangladesh_missions WHERE year = 2016 AND mission_type = 'peacekeeping';
What is the earliest launch date of a spacecraft manufactured by AstroCorp?
CREATE TABLE Launches (id INT,spacecraft_id INT,launch_date DATE); INSERT INTO Launches (id,spacecraft_id,launch_date) VALUES (1,1,'2005-01-01'),(2,2,'2010-01-01');
SELECT MIN(launch_date) FROM Launches INNER JOIN Spacecrafts ON Launches.spacecraft_id = Spacecrafts.id WHERE manufacturer = 'AstroCorp';
Find the average investment round size for companies founded in 2017
CREATE TABLE investment (id INT,company_id INT,investment_round_size REAL,investment_round_date DATE); CREATE TABLE startup (id INT,name TEXT,founding_year INT,founder_gender TEXT);
SELECT AVG(investment_round_size) FROM investment JOIN startup ON investment.company_id = startup.id WHERE startup.founding_year = 2017;
What is the total number of defense diplomacy events in the Asia-Pacific region?
CREATE TABLE DefenseDiplomacy (id INT,event VARCHAR(50),location VARCHAR(50)); INSERT INTO DefenseDiplomacy (id,event,location) VALUES (1,'Military Exercise','Japan'),(2,'Military Exercise','South Korea'),(3,'Diplomatic Meeting','China');
SELECT COUNT(*) FROM DefenseDiplomacy WHERE location LIKE '%Asia-Pacific%';
What was the average financial wellbeing score for customers of WISE Bank in Q1 2021?
CREATE TABLE WISE_Bank (id INT,customer_id INT,score INT,score_date DATE); INSERT INTO WISE_Bank (id,customer_id,score,score_date) VALUES (1,1001,85,'2021-03-01');
SELECT AVG(score) FROM WISE_Bank WHERE QUARTER(score_date) = 1 AND YEAR(score_date) = 2021;
Find the number of carbon offset programs in the province of British Columbia that have a target of reducing at least 50,000 metric tons of CO2?
CREATE TABLE carbon_offset_programs (id INT,program_name VARCHAR(255),province VARCHAR(255),target_reduction INT);
SELECT COUNT(program_name) FROM carbon_offset_programs WHERE province = 'British Columbia' AND target_reduction >= 50000;
Number of sculptures made by Korean artists sold after 2000?
CREATE TABLE ArtSales (id INT,artwork_name VARCHAR(50),price FLOAT,sale_date DATE,artwork_type VARCHAR(20),artist_nationality VARCHAR(30)); INSERT INTO ArtSales (id,artwork_name,price,sale_date,artwork_type,artist_nationality) VALUES (1,'Sculpture1',15000,'2001-01-01','Sculpture','Korean');
SELECT COUNT(*) FROM ArtSales WHERE artwork_type = 'Sculpture' AND artist_nationality = 'Korean' AND sale_date >= '2000-01-01';
Insert a new sale for the state of Washington in Q3 2022 with a revenue of 20000 and a strain of "Purple Haze"
CREATE TABLE sales (id INT,state VARCHAR(50),quarter VARCHAR(10),strain VARCHAR(50),revenue INT);
INSERT INTO sales (state, quarter, strain, revenue) VALUES ('Washington', 'Q3', 'Purple Haze', 20000);
Find the top 5 most frequently purchased products, including their production location, and rank them by sales quantity.
CREATE TABLE sales (sale_id int,product_id int,production_location varchar);
SELECT product_id, production_location, ROW_NUMBER() OVER (ORDER BY COUNT(*) DESC) as rank FROM sales GROUP BY product_id, production_location FETCH FIRST 5 ROWS ONLY;
What is the total quantity of each fabric type in stock?
CREATE TABLE fabric_stock (id INT PRIMARY KEY,fabric VARCHAR(20),quantity INT);
SELECT fabric, SUM(quantity) FROM fabric_stock GROUP BY fabric;
How many artworks were exhibited in 'Museum X'?
CREATE TABLE Exhibitions (exhibition_id INT,museum_name VARCHAR(255),artist_id INT,artwork_id INT); INSERT INTO Exhibitions (exhibition_id,museum_name,artist_id,artwork_id) VALUES (1,'Museum X',101,201),(2,'Museum X',102,202),(3,'Museum X',103,203),(4,'Museum X',104,204);
SELECT COUNT(artwork_id) FROM Exhibitions WHERE museum_name = 'Museum X';
Who are the top 3 union leaders with the longest membership tenure?
CREATE TABLE union_members (id INT,name VARCHAR,state VARCHAR,union_since DATE); INSERT INTO union_members (id,name,state,union_since) VALUES (11,'Alex Brown','CA','2010-05-15'); INSERT INTO union_members (id,name,state,union_since) VALUES (12,'Jessica Green','NY','2017-02-02');
SELECT name, state, union_since, ROW_NUMBER() OVER (ORDER BY DATEDIFF(day, union_since, CURRENT_DATE) DESC) as tenure_rank FROM union_members WHERE state IN ('CA', 'NY') ORDER BY tenure_rank FETCH NEXT 3 ROWS ONLY;
What is the number of hotels in Canada that have adopted AI technology for guest services?
CREATE TABLE hotel_tech (hotel_id INT,hotel_name VARCHAR(255),ai_adoption BOOLEAN,country VARCHAR(255)); INSERT INTO hotel_tech (hotel_id,hotel_name,ai_adoption,country) VALUES (1,'Hotel A',TRUE,'Canada'),(2,'Hotel B',FALSE,'Canada'),(3,'Hotel C',TRUE,'USA');
SELECT COUNT(*) FROM hotel_tech WHERE ai_adoption = TRUE AND country = 'Canada';
Update the salinity level for all Trout in Tank11 to 25 ppt.
CREATE TABLE Tank11 (species VARCHAR(20),individual_id INT,salinity FLOAT); INSERT INTO Tank11 (species,individual_id,salinity) VALUES ('Trout',1,30),('Trout',2,25),('Tilapia',1,15),('Salmon',1,20);
UPDATE Tank11 SET salinity = 25 WHERE species = 'Trout';
What is the average word count for articles in the 'Culture' category?
CREATE TABLE categories (id INT,name TEXT); INSERT INTO categories (id,name) VALUES (1,'Culture'),(2,'Science'),(3,'Politics'); CREATE TABLE articles (id INT,category_id INT,word_count INT); INSERT INTO articles (id,category_id,word_count) VALUES (1,1,800),(2,2,1200),(3,1,900);
SELECT AVG(word_count) FROM articles WHERE category_id = 1;
How many unique donors contributed to each cause?
CREATE TABLE Donors (DonorID INT,DonorName TEXT,DonationAmount DECIMAL(10,2),Cause TEXT);
SELECT Cause, COUNT(DISTINCT DonorName) as UniqueDonors FROM Donors GROUP BY Cause;
How many rural hospitals are there in the state of Texas?
CREATE TABLE rural_hospitals (id INT,name TEXT,location TEXT,state TEXT); INSERT INTO rural_hospitals (id,name,location,state) VALUES (1,'Hospital A','Rural Area 1','Texas'),(2,'Hospital B','Rural Area 2','California');
SELECT COUNT(*) FROM rural_hospitals WHERE state = 'Texas';
Delete records of volunteers who have not volunteered in the last 6 months?
CREATE TABLE volunteer_hours (volunteer_id INT,hours INT,volunteer_date DATE); INSERT INTO volunteer_hours (volunteer_id,hours,volunteer_date) VALUES (3,2,'2022-03-10'),(4,6,'2022-02-15');
DELETE FROM volunteers WHERE volunteer_id NOT IN (SELECT volunteer_id FROM volunteer_hours WHERE volunteer_date >= (CURRENT_DATE - INTERVAL '6 months'));
Identify the top 5 donors who have increased their donation amounts the most in the last year, and show the percentage increase in their donations.
CREATE TABLE donors (id INT,name TEXT,country TEXT,donation FLOAT);
SELECT donors.name, ((donations2.total_donation - donations1.total_donation) / donations1.total_donation) * 100 as percentage_increase FROM donors JOIN (SELECT donor_id, SUM(amount) as total_donation FROM donations WHERE donation_date BETWEEN DATE_SUB(CURDATE(), INTERVAL 1 YEAR) AND DATE_SUB(CURDATE(), INTERVAL 6 MONTH...
What is the maximum cargo weight transported by a vessel in a single trip?
CREATE TABLE Vessels (VesselID INT,Name TEXT,Type TEXT,MaxCapacity INT); CREATE TABLE Trips (TripID INT,VesselID INT,Date DATE,CargoWeight INT); INSERT INTO Vessels VALUES (1,'Tanker 1','Oil Tanker',150000); INSERT INTO Trips VALUES (1,1,'2020-01-01',100000);
SELECT MAX(Trips.CargoWeight) FROM Trips;
Delete satellites launched before a certain date
CREATE TABLE Satellites (ID INT,Name VARCHAR(50),LaunchDate DATE); INSERT INTO Satellites (ID,Name,LaunchDate) VALUES (1,'Sat1','2018-01-01'),(2,'Sat2','2020-05-15'),(3,'Sat3','2019-09-01'),(4,'Sat4','2016-03-01'),(5,'Sat5','2017-12-25');
DELETE FROM Satellites WHERE LaunchDate < '2018-01-01';
Identify customers who made a transaction on two consecutive days in the past month.
CREATE TABLE customers (customer_id INT,name VARCHAR(50)); CREATE TABLE transactions (transaction_id INT,customer_id INT,transaction_date DATE); INSERT INTO customers (customer_id,name) VALUES (1,'Daniel Kim'); INSERT INTO transactions (transaction_id,customer_id,transaction_date) VALUES (1,1,'2022-01-01'); INSERT INTO...
SELECT t1.customer_id, t1.transaction_date as transaction_date_1, t2.transaction_date as transaction_date_2 FROM transactions t1 INNER JOIN transactions t2 ON t1.customer_id = t2.customer_id AND t1.transaction_date + 1 = t2.transaction_date WHERE t1.transaction_date BETWEEN DATEADD(month, -1, GETDATE()) AND GETDATE();
Which destinations have the most sustainable tourism practices?
CREATE TABLE destinations (id INT,name VARCHAR(50),sustainable_practices INT); INSERT INTO destinations (id,name,sustainable_practices) VALUES (1,'National Park A',3),(2,'Beach Resort B',5),(3,'Historic Site C',4),(4,'Ski Resort D',2);
SELECT name, sustainable_practices, RANK() OVER (ORDER BY sustainable_practices DESC) as rank FROM destinations;
What is the average temperature recorded by soil moisture sensor 'SM001' in the past week?
CREATE TABLE sensor_data (id INT,sensor_id VARCHAR(10),temperature FLOAT,timestamp TIMESTAMP); INSERT INTO sensor_data (id,sensor_id,temperature,timestamp) VALUES (1,'SM001',22.5,'2022-01-01 10:00:00'),(2,'SM001',23.3,'2022-01-02 10:00:00');
SELECT AVG(temperature) FROM sensor_data WHERE sensor_id = 'SM001' AND timestamp BETWEEN DATE_SUB(CURRENT_TIMESTAMP, INTERVAL 7 DAY) AND CURRENT_TIMESTAMP;
Which volunteers have completed more than 100 hours of work in the last 3 months?
CREATE TABLE volunteers (id INT,name VARCHAR(255),department_id INT,hours_worked INT);
SELECT volunteers.name FROM volunteers WHERE volunteers.hours_worked > 100 AND volunteers.worked_date BETWEEN DATE_SUB(CURRENT_DATE, INTERVAL 3 MONTH) AND CURRENT_DATE;
Update team names to uppercase in the 'esports_teams' table
CREATE TABLE esports_teams (team_id INT,team_name VARCHAR(50));
UPDATE esports_teams SET team_name = UPPER(team_name);
What was the total quantity of each product sold by every dispensary in California in July 2022?
CREATE TABLE Dispensaries (id INT,name TEXT,state TEXT); CREATE TABLE Sales (dispid INT,date DATE,product TEXT,quantity INT); INSERT INTO Dispensaries (id,name,state) VALUES (1,'Dispensary One','California'); INSERT INTO Dispensaries (id,name,state) VALUES (2,'Dispensary Two','California'); INSERT INTO Sales (dispid,da...
SELECT d.name, s.product, SUM(s.quantity) as total_quantity FROM Dispensaries d JOIN Sales s ON d.id = s.dispid WHERE d.state = 'California' AND MONTH(s.date) = 7 GROUP BY d.name, s.product;
What is the number of farms by country and water type?
CREATE TABLE Country (id INT PRIMARY KEY,name VARCHAR(50)); CREATE TABLE Farm (id INT PRIMARY KEY,country_id INT,water_type VARCHAR(50),FOREIGN KEY (country_id) REFERENCES Country(id));
SELECT Country.name, Farm.water_type, COUNT(Farm.id) FROM Country INNER JOIN Farm ON Country.id = Farm.country_id GROUP BY Country.name, Farm.water_type;
What is the average fare amount for each route type?
CREATE TABLE route_types (route_type_id SERIAL PRIMARY KEY,route_type_name VARCHAR(255)); CREATE TABLE fares (fare_id SERIAL PRIMARY KEY,route_id VARCHAR(255),fare_amount DECIMAL(10,2),route_type_id INTEGER,effective_date DATE);
SELECT rt.route_type_name, AVG(f.fare_amount) avg_fare_amount FROM fares f JOIN route_types rt ON f.route_type_id = rt.route_type_id GROUP BY rt.route_type_name;
What is the total distance traveled by electric vehicles in Rome, Italy?
CREATE TABLE electric_vehicles (vehicle_id INT,trip_duration INT,start_time TIMESTAMP,end_time TIMESTAMP,start_location TEXT,end_location TEXT,city TEXT,electric BOOLEAN);
SELECT SUM(trip_duration * (60 / (end_time - start_time))) FROM electric_vehicles WHERE city = 'Rome' AND electric = TRUE;
Which organizations have limited technology accessibility in South America?
CREATE TABLE org_access (org_id INT,accessibility INT,region TEXT); INSERT INTO org_access (org_id,accessibility,region) VALUES (1,3,'South America'),(2,5,'Europe'),(3,2,'South America');
SELECT org_id FROM org_access WHERE region = 'South America' AND accessibility < 5;
What is the total price of all co-owned properties in Staten Island?
CREATE TABLE CoOwnedProperties (PropertyID int,Price int,Borough varchar(255)); INSERT INTO CoOwnedProperties (PropertyID,Price,Borough) VALUES (1,500000,'Staten Island');
SELECT SUM(Price) as TotalPrice FROM CoOwnedProperties WHERE Borough = 'Staten Island';
What is the average arrival delay for flights from Tokyo to New York?
CREATE TABLE flights (flight_id INT,departure_city VARCHAR(50),arrival_city VARCHAR(50),arrival_delay INT); INSERT INTO flights (flight_id,departure_city,arrival_city,arrival_delay) VALUES (1,'Tokyo','New York',30),(2,'Tokyo','New York',15),(3,'Tokyo','New York',45);
SELECT AVG(arrival_delay) FROM flights WHERE departure_city = 'Tokyo' AND arrival_city = 'New York';
What is the recycling rate for each material type in the city of New York in 2019?'
CREATE TABLE recycling_rates (city VARCHAR(20),year INT,material VARCHAR(20),recycling_rate FLOAT); INSERT INTO recycling_rates (city,year,material,recycling_rate) VALUES ('New York',2019,'Plastic',0.3),('New York',2019,'Paper',0.6),('New York',2019,'Glass',0.4);
SELECT material, AVG(recycling_rate) as avg_recycling_rate FROM recycling_rates WHERE city = 'New York' AND year = 2019 GROUP BY material;
Add a new game 'Mystic Quest' to the 'game_design' table
CREATE TABLE game_design (game_id INT,game_name VARCHAR(50),genre VARCHAR(50),rating FLOAT);
INSERT INTO game_design (game_id, game_name, genre, rating) VALUES (4, 'Mystic Quest', 'RPG', 8.5);
List all locations affected by 'flood' in 'disaster_data' table.
CREATE TABLE disaster_data (id INT,year INT,type VARCHAR(50),location VARCHAR(50));
SELECT DISTINCT location FROM disaster_data WHERE type = 'flood';
What is the average number of fans per match for each team?
CREATE TABLE teams (team_id INT,team_name VARCHAR(255)); CREATE TABLE matches (match_id INT,home_team_id INT,away_team_id INT,home_team_attendance INT,away_team_attendance INT,match_date DATE);
SELECT t.team_name, AVG(home_team_attendance + away_team_attendance) as avg_attendance FROM matches m JOIN teams t ON m.home_team_id = t.team_id GROUP BY t.team_name;
What is the total budget of climate communication projects in North America that started after 2018?
CREATE TABLE climate_communication (id INT,project_name TEXT,budget INT,start_year INT,location TEXT); INSERT INTO climate_communication (id,project_name,budget,start_year,location) VALUES (1,'Climate Education',30000,2019,'North America'); INSERT INTO climate_communication (id,project_name,budget,start_year,location) ...
SELECT SUM(budget) FROM climate_communication WHERE location = 'North America' AND start_year > 2018;
What is the maximum power consumption (in kWh) by a machine in any category in the 'plant1'?
CREATE TABLE machines (machine_id INT,plant VARCHAR(10),category VARCHAR(10),power_consumption FLOAT); INSERT INTO machines (machine_id,plant,category,power_consumption) VALUES (1,'plant1','molding',5.6),(2,'plant2','tooling',7.3),(3,'plant1','tooling',6.2),(4,'plant1','molding',9.1);
SELECT MAX(power_consumption) FROM machines WHERE plant = 'plant1';
How many criminal incidents were reported in 'New York' in the month of 'January' 2021?
CREATE TABLE criminal_incidents (id INT,city VARCHAR(20),incident_date DATE); INSERT INTO criminal_incidents (id,city,incident_date) VALUES (1,'New York','2021-01-15');
SELECT COUNT(*) FROM criminal_incidents WHERE city = 'New York' AND incident_date BETWEEN '2021-01-01' AND '2021-01-31';
What is the minimum temperature recorded in Florida in the past month?
CREATE TABLE Weather (location VARCHAR(50),temperature INT,timestamp TIMESTAMP);
SELECT MIN(temperature) FROM Weather WHERE location = 'Florida' AND timestamp > NOW() - INTERVAL '1 month';
Insert a new exhibition with the name 'Dinosaurs' and 1000 visitors
CREATE TABLE Exhibitions (id INT,name TEXT,visitor_count INT);
INSERT INTO Exhibitions (id, name, visitor_count) VALUES (1, 'Dinosaurs', 1000);
Calculate the moving average of water usage for each mining operation over the past 7 days.
CREATE TABLE Mining_Operation (Operation_ID INT,Mine_Name VARCHAR(50),Location VARCHAR(50),Operation_Type VARCHAR(50),Start_Date DATE,End_Date DATE); CREATE TABLE Environmental_Impact (Impact_ID INT,Operation_ID INT,Date DATE,Carbon_Emissions INT,Water_Usage INT,Waste_Generation INT);
SELECT Operation_ID, Date, Water_Usage, AVG(Water_Usage) OVER (PARTITION BY Operation_ID ORDER BY Date ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS Water_Usage_Moving_Avg FROM Environmental_Impact WHERE Operation_ID IN (1, 2, 3);