instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
What is the minimum and maximum age of metal artifacts at Site C?
CREATE TABLE artifact_ages (artifact_id INT,site_id INT,artifact_type TEXT,age INT); INSERT INTO artifact_ages (artifact_id,site_id,artifact_type,age) VALUES (1,1,'ceramic',120),(2,1,'metal',150),(3,1,'bone',100),(4,2,'ceramic',180),(5,2,'metal',200),(6,2,'bone',170),(7,3,'ceramic',300),(8,3,'metal',350),(9,3,'bone',32...
SELECT MIN(age), MAX(age) FROM artifact_ages WHERE site_id = 3 AND artifact_type = 'metal';
What is the total revenue generated from mobile and broadband services in the third quarter of 2021?
CREATE TABLE mobile_revenue(quarter INT,revenue FLOAT); INSERT INTO mobile_revenue(quarter,revenue) VALUES (3,2000000),(1,1500000),(3,1750000); CREATE TABLE broadband_revenue(quarter INT,revenue FLOAT); INSERT INTO broadband_revenue(quarter,revenue) VALUES (3,2500000),(2,2250000),(3,3000000);
SELECT (SELECT SUM(revenue) FROM mobile_revenue WHERE quarter = 3) + (SELECT SUM(revenue) FROM broadband_revenue WHERE quarter = 3);
Get the number of employees in each department and the total number of employees from the 'employee' and 'department' tables
CREATE TABLE employee (id INT,name VARCHAR(50),gender VARCHAR(50),department_id INT); CREATE TABLE department (id INT,name VARCHAR(50));
SELECT department.name, COUNT(employee.id), (SELECT COUNT(*) FROM employee) AS total_employees FROM employee RIGHT JOIN department ON employee.department_id = department.id GROUP BY department.name;
Delete the membership record of user 'Mike Johnson'
CREATE TABLE membership (user_id INT,name VARCHAR(50),status VARCHAR(20)); INSERT INTO membership (user_id,name,status) VALUES (3,'Mike Johnson','Active');
WITH deleted_membership AS (DELETE FROM membership WHERE name = 'Mike Johnson' RETURNING *) SELECT * FROM deleted_membership;
What is the total revenue from mobile and broadband services for each region?
CREATE TABLE regions (region_id INT,region_name VARCHAR(50)); CREATE TABLE mobile_services (service_id INT,service_name VARCHAR(50),region_id INT,revenue INT); CREATE TABLE broadband_services (service_id INT,service_name VARCHAR(50),region_id INT,revenue INT);
SELECT r.region_name, m.revenue AS mobile_revenue, b.revenue AS broadband_revenue, m.revenue + b.revenue AS total_revenue FROM regions r LEFT JOIN mobile_services m ON r.region_id = m.region_id LEFT JOIN broadband_services b ON r.region_id = b.region_id;
Determine the total number of Shariah-compliant financial institutions in North America with a ROE greater than 10%.
CREATE TABLE shariah_compliant_finance (id INT,institution_name VARCHAR(255),country VARCHAR(255),num_branches INT,ROE FLOAT); INSERT INTO shariah_compliant_finance (id,institution_name,country,num_branches,ROE) VALUES (1,'Islamic Bank of America','USA',5,0.12),(2,'Shariah Finance Canada','Canada',7,0.11),(3,'Al-Baraka...
SELECT COUNT(*) FROM shariah_compliant_finance WHERE country LIKE 'North America' AND ROE > 0.10;
Insert new records for traditional art forms: Madhubani painting, Kathakali dance, and Maqam music.
CREATE TABLE art_forms (id INT PRIMARY KEY,name VARCHAR(50),type VARCHAR(30)); INSERT INTO art_forms (id,name,type) VALUES (1,'Throat Singing','Music'),(2,'Batik','Textile'),(3,'Ikebana','Visual Arts');
INSERT INTO art_forms (name, type) VALUES ('Madhubani Painting', 'Visual Arts'), ('Kathakali Dance', 'Performance Arts'), ('Maqam Music', 'Music');
How many biosensors have been developed in Canada for glucose detection?
CREATE TABLE biosensors (id INT,name VARCHAR(50),country VARCHAR(50),target VARCHAR(50),quantity INT); INSERT INTO biosensors (id,name,country,target,quantity) VALUES (1,'BioSensor1','Canada','glucose',500); INSERT INTO biosensors (id,name,country,target,quantity) VALUES (2,'BioSensor2','Canada','lactate',300);
SELECT COUNT(*) FROM biosensors WHERE country = 'Canada' AND target = 'glucose';
Calculate the percentage of community engagement events in each city, ordered by the percentage in descending order.
CREATE TABLE community_events (event_id INT,event_name TEXT,city TEXT,year INT); INSERT INTO community_events (event_id,event_name,city,year) VALUES (1,'Cultural Festival','New York',2020),(2,'Traditional Music Concert','Los Angeles',2019);
SELECT city, ROUND(100.0 * COUNT(*) / (SELECT COUNT(*) FROM community_events) , 2) as percentage FROM community_events GROUP BY city ORDER BY percentage DESC;
How many models were developed by each organization?
CREATE TABLE model (model_id INT,name VARCHAR(50),organization_id INT); INSERT INTO model VALUES (1,'ModelA',1),(2,'ModelB',2),(3,'ModelC',3),(4,'ModelD',1),(5,'ModelE',3),(6,'ModelF',2),(7,'ModelG',1); CREATE TABLE organization (organization_id INT,name VARCHAR(50),type VARCHAR(20)); INSERT INTO organization VALUES (1...
SELECT organization.name, COUNT(model.model_id) FROM model JOIN organization ON model.organization_id = organization.organization_id GROUP BY organization.name;
What is the average quantity of garments sold by the top 3 designers, per transaction, for each city?
CREATE TABLE Designers (DesignerID INT,DesignerName VARCHAR(50),City VARCHAR(50)); INSERT INTO Designers VALUES (1,'DesignerA','New York'),(2,'DesignerB','Los Angeles'),(3,'DesignerC','Chicago'),(4,'DesignerD','New York'); CREATE TABLE Transactions (TransactionID INT,DesignerID INT,Quantity INT); INSERT INTO Transactio...
SELECT AVG(Quantity) AS Avg_Quantity, City FROM (SELECT DesignerName, City, Quantity, ROW_NUMBER() OVER (PARTITION BY City ORDER BY SUM(Quantity) DESC) AS DesignerRank FROM Designers JOIN Transactions ON Designers.DesignerID = Transactions.DesignerID GROUP BY DesignerName, City) AS Subquery WHERE DesignerRank <= 3 GROU...
What is the average salinity of seawater in the Indian Ocean?
CREATE TABLE seawater_salinity (location VARCHAR(255),salinity FLOAT,date DATE);
SELECT AVG(salinity) FROM seawater_salinity WHERE location = 'Indian Ocean';
What was the minimum number of likes received by a post in each month of 2021?
CREATE TABLE posts (id INT,likes INT,created_at TIMESTAMP);
SELECT MONTH(created_at) AS month, MIN(likes) AS min_likes FROM posts WHERE YEAR(created_at) = 2021 GROUP BY month;
What is the total amount donated to healthcare by donors from California who donated more than $1000?
CREATE TABLE donations (id INT,donor_state VARCHAR(255),recipient_sector VARCHAR(255),donation_amount DECIMAL(10,2)); INSERT INTO donations (id,donor_state,recipient_sector,donation_amount) VALUES (1,'California','healthcare',1500.00),(2,'California','education',500.00),(3,'Texas','healthcare',2000.00);
SELECT SUM(donation_amount) FROM donations WHERE donor_state = 'California' AND recipient_sector = 'healthcare' AND donation_amount > 1000;
Calculate the number of sustainable products produced by each manufacturer, ranked by the total quantity sold.
CREATE TABLE products (id INT PRIMARY KEY,name VARCHAR(255),price DECIMAL(5,2),manufacturer_id INT,is_sustainable BOOLEAN,FOREIGN KEY (manufacturer_id) REFERENCES manufacturers(id)); CREATE TABLE sales (id INT PRIMARY KEY,product_id INT,quantity INT,sale_date DATE,FOREIGN KEY (product_id) REFERENCES products(id));
SELECT m.id, m.name, SUM(p.is_sustainable) as sustainable_products, SUM(s.quantity) as total_sold, ROW_NUMBER() OVER (ORDER BY total_sold DESC) as rank FROM manufacturers m JOIN products p ON m.id = p.manufacturer_id JOIN sales s ON p.id = s.product_id GROUP BY m.id, m.name ORDER BY rank;
What is the maximum and minimum pollution concentration for each location, and the average number of cleanup efforts at each location?
CREATE TABLE Pollution (id INT PRIMARY KEY,location VARCHAR(255),pollutant VARCHAR(255),concentration FLOAT); CREATE TABLE CleanUp (id INT PRIMARY KEY,location VARCHAR(255),cleanup_date DATE,volunteers INT,hours_worked INT);
SELECT l.location, MAX(p.concentration) as max_pollution, MIN(p.concentration) as min_pollution, AVG(c.volunteers + c.hours_worked) as avg_cleanup_efforts FROM (SELECT DISTINCT location FROM Pollution) as l LEFT JOIN Pollution p ON l.location = p.location LEFT JOIN CleanUp c ON l.location = c.location GROUP BY l.locati...
What is the total volume of plastic waste in the Pacific Ocean?
CREATE TABLE plastic_waste (id INT,location VARCHAR(50),volume FLOAT); INSERT INTO plastic_waste (id,location,volume) VALUES (1,'Pacific Ocean',8000000.0); INSERT INTO plastic_waste (id,location,volume) VALUES (2,'Pacific Ocean',10000000.0);
SELECT SUM(volume) FROM plastic_waste WHERE location = 'Pacific Ocean';
What is the number of criminal cases heard by each judge in the city of Chicago in 2020?
CREATE TABLE judges (id INT,name TEXT,city TEXT); INSERT INTO judges (id,name,city) VALUES (1,'Judge A','Chicago'),(2,'Judge B','Chicago'),(3,'Judge C','New York'); CREATE TABLE cases (id INT,judge_id INT,year INT,case_type TEXT); INSERT INTO cases (id,judge_id,year,case_type) VALUES (1,1,2020,'Criminal'),(2,1,2019,'Ci...
SELECT j.name, COUNT(*) as cases_heard FROM cases JOIN judges j ON cases.judge_id = j.id WHERE cases.year = 2020 AND cases.case_type = 'Criminal' GROUP BY j.name;
Calculate the total budget for habitat preservation efforts
CREATE TABLE budgets (id INT,category VARCHAR(255),amount INT); INSERT INTO budgets (id,category,amount) VALUES (1,'Habitat Restoration',30000),(2,'Habitat Maintenance',20000),(3,'Wildlife Awareness',15000);
SELECT SUM(amount) as total_budget FROM budgets WHERE category LIKE '%habitat%';
Which organizations have no volunteers?
CREATE TABLE org_volunteer (org_id INT,vol_id INT); INSERT INTO org_volunteer (org_id,vol_id) VALUES (1,1),(1,2),(2,3),(3,4),(3,5);
SELECT org_id FROM organization WHERE org_id NOT IN (SELECT org_id FROM org_volunteer);
Delete the membership of user with ID 001
CREATE TABLE memberships (id INT,user_id INT); INSERT INTO memberships (id,user_id) VALUES (1,1),(2,2),(3,3);
DELETE FROM memberships WHERE user_id = 1;
What is the average amount of experience for employees in the 'mining_operations' table, grouped by their job titles?
CREATE TABLE mining_operations (id INT,name VARCHAR(50),job_title VARCHAR(50),department VARCHAR(50),experience INT); INSERT INTO mining_operations (id,name,job_title,department,experience) VALUES (1,'John Doe','Mining Engineer','Operations',7); INSERT INTO mining_operations (id,name,job_title,department,experience) VA...
SELECT job_title, AVG(experience) as avg_experience FROM mining_operations GROUP BY job_title;
What is the maximum speed of any aircraft manufactured by Airbus?
CREATE TABLE AircraftSpeeds (AircraftID INT,Name VARCHAR(100),Manufacturer VARCHAR(50),MaxSpeed FLOAT);
SELECT MAX(MaxSpeed) FROM AircraftSpeeds WHERE Manufacturer = 'Airbus';
Delete vessels that are inactive for more than 6 months
CREATE SCHEMA if not exists ocean_shipping;CREATE TABLE if not exists ocean_shipping.vessels (id INT,name VARCHAR(255),status VARCHAR(255),last_maintenance DATE);
DELETE FROM ocean_shipping.vessels WHERE last_maintenance < DATE_SUB(CURRENT_DATE, INTERVAL 6 MONTH);
What is the maximum speed of a spacecraft launched before 2010?
CREATE TABLE spacecraft (id INT,name VARCHAR(255),launch_country VARCHAR(255),launch_date DATE,max_speed FLOAT);
SELECT max(max_speed) as max_speed FROM spacecraft WHERE launch_date < '2010-01-01';
What is the total amount of waste generated by each chemical plant in the waste_generation table?
CREATE TABLE waste_generation (plant_name VARCHAR(255),waste_amount FLOAT);
SELECT plant_name, SUM(waste_amount) FROM waste_generation GROUP BY plant_name;
What was the total construction cost for each type of infrastructure development project in California in 2020?
CREATE TABLE InfrastructureCosts (State TEXT,Year INTEGER,ProjectType TEXT,ConstructionCost REAL); INSERT INTO InfrastructureCosts (State,Year,ProjectType,ConstructionCost) VALUES ('California',2020,'Bridge',1500000.0),('California',2020,'Highway',2200000.0),('California',2020,'Tunnel',3000000.0);
SELECT ProjectType, SUM(ConstructionCost) as TotalCost FROM InfrastructureCosts WHERE State = 'California' AND Year = 2020 GROUP BY ProjectType;
What is the percentage of wind projects in the renewable_projects table compared to the total number of projects?
CREATE TABLE renewable_projects (project_id INT,project_name TEXT,project_type TEXT);
SELECT (COUNT(CASE WHEN project_type = 'Wind' THEN 1 END) * 100.0 / COUNT(*)) AS wind_percentage FROM renewable_projects;
List all suppliers that provide products for a specific restaurant, excluding any suppliers that have had food safety violations in the past year.
CREATE TABLE suppliers (id INT,name TEXT,restaurant TEXT,violation_date DATE);
SELECT name FROM suppliers WHERE restaurant = 'Restaurant A' AND id NOT IN (SELECT supplier_id FROM violations WHERE violation_date >= DATEADD(year, -1, GETDATE()));
Insert data into 'equipment_maintenance' table for a helicopter
CREATE TABLE equipment_maintenance (equipment_id INTEGER PRIMARY KEY,last_maintenance_date DATE,next_maintenance_date DATE,completed_maintenance BOOLEAN);
INSERT INTO equipment_maintenance (equipment_id, last_maintenance_date, next_maintenance_date, completed_maintenance) VALUES (2, DATE('2022-01-01'), DATE('2022-07-01'), FALSE);
Which faculty members have received grants with an amount greater than $100,000 in the past 5 years?
CREATE TABLE Grants (GrantID INT,Title VARCHAR(100),Amount DECIMAL(10,2),Organization VARCHAR(50),StartDate DATE,EndDate DATE,FacultyID INT); CREATE TABLE Faculty (FacultyID INT,FirstName VARCHAR(50),LastName VARCHAR(50),Department VARCHAR(50),Rank VARCHAR(10));
SELECT f.FirstName, f.LastName, g.Amount FROM Grants g JOIN Faculty f ON g.FacultyID = f.FacultyID WHERE g.Amount > 100000 AND g.StartDate >= DATEADD(year, -5, GETDATE());
Delete households in the household_water_consumption table that consume more water than the average water consumption for the state of California.
CREATE TABLE household_water_consumption (id INT,state VARCHAR(20),water_consumption FLOAT); INSERT INTO household_water_consumption (id,state,water_consumption) VALUES (1,'California',1200),(2,'Texas',1500),(3,'California',1100),(4,'Texas',1400); INSERT INTO household_water_consumption (id,state,water_consumption) VAL...
DELETE FROM household_water_consumption WHERE id IN (SELECT id FROM (SELECT id, water_consumption, AVG(water_consumption) OVER (PARTITION BY state) AS avg_consumption FROM household_water_consumption) AS subquery WHERE state = 'California' AND water_consumption > avg_consumption);
What are the names of recipients who have received more funding than any donor's contribution?
CREATE TABLE Donors (Id INT,Name VARCHAR(50),Age INT,Amount DECIMAL(10,2)); INSERT INTO Donors (Id,Name,Age,Amount) VALUES (1,'Jamie Brown',32,1200.00),(2,'Olivia Johnson',37,1500.00),(3,'Sophia Adams',42,1800.00); CREATE TABLE Recipients (Id INT,Name VARCHAR(50),Age INT,Amount DECIMAL(10,2)); INSERT INTO Recipients (I...
SELECT Name FROM Recipients WHERE Amount > ALL (SELECT Amount FROM Donors);
How many donors are from each country, in the 'Donors' table?
CREATE TABLE Donors (id INT,name VARCHAR(50),city VARCHAR(50),state VARCHAR(50),country VARCHAR(50),type VARCHAR(10),donation_amount DECIMAL(10,2));
SELECT country, COUNT(DISTINCT id) as num_donors FROM Donors GROUP BY country;
What is the average age of astronauts from Nigeria?
CREATE TABLE Astronaut (id INT PRIMARY KEY,name VARCHAR(50),age INT,gender VARCHAR(10),nationality VARCHAR(50));
SELECT AVG(Astronaut.age) as avg_age FROM Astronaut WHERE Astronaut.nationality = 'Nigeria';
What are the top 3 defense contractors by contract value for each year from 2018 to 2020?
CREATE TABLE defense_contracts (contractor VARCHAR(255),year INT,value FLOAT); INSERT INTO defense_contracts (contractor,year,value) VALUES ('Lockheed Martin',2018,50.0),('Raytheon',2018,30.0),('Boeing',2018,40.0),('Northrop Grumman',2018,45.0),('General Dynamics',2018,35.0),('Lockheed Martin',2019,60.0),('Raytheon',20...
SELECT contractor, year, SUM(value) as total_value FROM defense_contracts GROUP BY contractor, year ORDER BY year, total_value DESC LIMIT 3;
How many movies were released per year by 'Marvel Studios'?
CREATE TABLE studios (id INT,name VARCHAR(50)); INSERT INTO studios (id,name) VALUES (1,'Marvel Studios'); CREATE TABLE movies (id INT,title VARCHAR(50),studio_id INT,release_year INT); INSERT INTO movies (id,title,studio_id,release_year) VALUES (1,'Iron Man',1,2008),(2,'Captain America',1,2011),(3,'Black Widow',1,2021...
SELECT release_year, COUNT(*) as count FROM movies WHERE studio_id = (SELECT id FROM studios WHERE name = 'Marvel Studios') GROUP BY release_year ORDER BY release_year;
Which vessels have a higher speed than any vessel that departed from the port of Mumbai, India in the month of December 2021?
CREATE TABLE vessels (id INT,name TEXT,speed FLOAT,departed_port TEXT,departed_date DATE); INSERT INTO vessels (id,name,speed,departed_port,departed_date) VALUES (1,'VesselA',15.2,'Mumbai','2021-12-01'); INSERT INTO vessels (id,name,speed,departed_port,departed_date) VALUES (2,'VesselB',17.8,'Mumbai','2021-12-15'); INS...
SELECT * FROM vessels WHERE speed > (SELECT MAX(speed) FROM vessels WHERE departed_port = 'Mumbai' AND departed_date >= '2021-12-01' AND departed_date < '2022-01-01');
What is the total CO2 emission of buildings in the 'urban' schema, grouped by certification level?
CREATE TABLE urban.buildings (certification_level VARCHAR(255),co2_emission INT); INSERT INTO urban.buildings (certification_level,co2_emission) VALUES ('Gold',1200),('Gold',1500),('Silver',1700),('Silver',1300),('Bronze',1000),('Bronze',1100);
SELECT certification_level, SUM(co2_emission) FROM urban.buildings GROUP BY certification_level;
What is the total revenue generated from organic products in the last month?
CREATE TABLE sales (id INT,product_id INT,price DECIMAL(5,2),sale_date DATE); INSERT INTO sales (id,product_id,price,sale_date) VALUES (1,101,25.99,'2022-01-01'),(2,102,12.50,'2022-01-02'); CREATE TABLE products (id INT,name VARCHAR(50),organic BOOLEAN); INSERT INTO products (id,name,organic) VALUES (101,'Apples',true)...
SELECT SUM(sales.price) FROM sales INNER JOIN products ON sales.product_id = products.id WHERE products.organic = true AND sales.sale_date >= '2022-01-01' AND sales.sale_date < '2022-02-01';
What is the average rating of hotels in the 'Americas' region?
CREATE TABLE hotels (id INT,name TEXT,region TEXT,rating FLOAT); INSERT INTO hotels (id,name,region,rating) VALUES (1,'Hotel X','Americas',4.2),(2,'Hotel Y','Americas',3.9),(3,'Hotel Z','Europe',4.5);
SELECT AVG(rating) FROM hotels WHERE region = 'Americas';
What is the percentage of revenue from sustainable sources out of the total revenue?
CREATE TABLE revenue (id INT,source VARCHAR(50),amount INT); INSERT INTO revenue (id,source,amount) VALUES (1,'Conventional',5000),(2,'Sustainable',3000),(3,'Conventional',6000),(4,'Sustainable',4000),(5,'Conventional',7000),(6,'Sustainable',5000);
SELECT (SUM(CASE WHEN source = 'Sustainable' THEN amount ELSE 0 END) / SUM(amount)) * 100 as pct FROM revenue;
Add a new donor, 'Maria Garcia', to the 'donor_demographics' table.
CREATE TABLE donor_demographics (donor_id INTEGER,donor_name TEXT,age INTEGER,location TEXT); INSERT INTO donor_demographics (donor_id,donor_name,age,location) VALUES (1,'John Smith',35,'New York'),(2,'Jane Doe',28,'San Francisco');
INSERT INTO donor_demographics (donor_id, donor_name, age, location) VALUES (3, 'Maria Garcia', 32, 'Mexico City');
List all climate communication projects in South America that started after 2012.
CREATE TABLE climate_projects (project_id INT,project_name TEXT,location TEXT,project_type TEXT,start_year INT); INSERT INTO climate_projects (project_id,project_name,location,project_type,start_year) VALUES (1,'Communication 1','Brazil','climate communication',2013),(2,'Mitigation 1','Colombia','climate mitigation',20...
SELECT * FROM climate_projects WHERE project_type = 'climate communication' AND location LIKE 'South America%' AND start_year > 2012;
What is the distribution of digital assets by their respective regulatory frameworks, including only assets with a market capitalization greater than $500 million?
CREATE TABLE digital_assets (asset_id INT,asset_name VARCHAR(255),network VARCHAR(255),market_cap DECIMAL(10,2),framework VARCHAR(255)); INSERT INTO digital_assets (asset_id,asset_name,network,market_cap,framework) VALUES (1,'ETH','ethereum',2000000000,'EU'),(2,'USDC','ethereum',500000000,'US'),(3,'UNI','ethereum',3000...
SELECT framework, COUNT(asset_id) as count FROM digital_assets WHERE market_cap > 500000000 GROUP BY framework;
What is the average temperature in the Pacific Ocean by month in 2020?
CREATE TABLE ocean_temperature (ocean_name VARCHAR(255),measurement_date DATE,temperature DECIMAL(5,2)); INSERT INTO ocean_temperature (ocean_name,measurement_date,temperature) VALUES ('Pacific Ocean','2020-01-01',20.5),('Pacific Ocean','2020-02-01',21.3),('Pacific Ocean','2020-03-01',22.1);
SELECT EXTRACT(MONTH FROM measurement_date) AS month, AVG(temperature) AS avg_temperature FROM ocean_temperature WHERE ocean_name = 'Pacific Ocean' AND YEAR(measurement_date) = 2020 GROUP BY month;
What is the average investment amount per investor?
CREATE TABLE investors (id INT PRIMARY KEY,name VARCHAR(255),location VARCHAR(255),investment_amount DECIMAL(10,2)); INSERT INTO investors (id,name,location,investment_amount) VALUES (1,'Alice','USA',5000.00),(2,'Bob','Canada',3000.00),(3,'Charlie','UK',4000.00),(4,'Diana','Germany',6000.00);
SELECT id, AVG(investment_amount) FROM investors GROUP BY id;
What is the average amount donated by all donors in the last month?
CREATE TABLE Donor (DonorID int,DonorName varchar(50),Country varchar(50)); CREATE TABLE Donation (DonationID int,DonorID int,DonationAmount int,DonationDate date);
SELECT AVG(DonationAmount) as AvgDonation FROM Donation JOIN Donor ON Donation.DonorID = Donor.DonorID WHERE DonationDate >= DATEADD(month, -1, GETDATE());
How many cultural competency training sessions were conducted in a specific year?
CREATE TABLE CulturalCompetencyTraining (ID INT PRIMARY KEY,EmployeeID INT,TrainingType VARCHAR(20),Hours INT,Date DATE);
SELECT COUNT(*) as TotalSessions FROM CulturalCompetencyTraining WHERE Date >= '2021-01-01' AND Date <= '2021-12-31';
Find the average word count of articles published in the 'opinion' section.
CREATE TABLE articles (id INT,section VARCHAR(255),word_count INT,date DATE);
SELECT AVG(word_count) FROM articles WHERE section='opinion';
What is the average maintenance cost per aircraft type, ordered by the highest average cost?
CREATE TABLE Aircraft (Type VARCHAR(50),Cost FLOAT); INSERT INTO Aircraft (Type,Cost) VALUES ('F-16',5000000),('F-35',8000000),('A-10',4000000);
SELECT Type, AVG(Cost) as Avg_Cost FROM Aircraft GROUP BY Type ORDER BY Avg_Cost DESC;
What is the minimum number of humanitarian assistance operations participated in by each country?
CREATE TABLE CountryHumanitarianAssistance (id INT,country VARCHAR(50),num_operations INT);
SELECT country, MIN(num_operations) FROM CountryHumanitarianAssistance GROUP BY country;
What is the total number of articles published in a specific language?
CREATE TABLE language_counts (id INT PRIMARY KEY,article_id INT,language VARCHAR(50),FOREIGN KEY (article_id) REFERENCES articles(id));
SELECT language, COUNT(*) as total_articles FROM language_counts GROUP BY language;
What are the top 3 most visited countries in Africa with the most biodiversity?
CREATE TABLE regions (id INT PRIMARY KEY,name VARCHAR(255));CREATE TABLE countries (id INT PRIMARY KEY,name VARCHAR(255),region_id INT,FOREIGN KEY (region_id) REFERENCES regions(id));CREATE TABLE tourism (id INT PRIMARY KEY,country_id INT,FOREIGN KEY (country_id) REFERENCES countries(id),visitors INT);CREATE TABLE biod...
SELECT country, visitors, score FROM top_countries_in_africa WHERE score > 80 LIMIT 3;
Which customers have made transactions in all 3 continents: Europe, Asia, and Americas?
CREATE TABLE Transactions (id INT,customer_id INT,region VARCHAR(10)); INSERT INTO Transactions (id,customer_id,region) VALUES (1,10,'Europe'),(2,10,'Asia'),(3,11,'Asia'),(4,12,'Europe'),(5,13,'Americas'),(6,10,'Americas');
SELECT customer_id FROM Transactions GROUP BY customer_id HAVING COUNT(DISTINCT region) = 3;
Insert records for new co-ownership properties in Mumbai and Rio de Janeiro.
CREATE TABLE CoOwnershipProperties (PropertyID INT,City VARCHAR(50),MaintenanceCost DECIMAL(5,2));
INSERT INTO CoOwnershipProperties (PropertyID, City, MaintenanceCost) VALUES (6, 'Mumbai', 110.00), (7, 'Rio de Janeiro', 150.00);
Which community health workers are serving patients with mental health disorders in Texas?
CREATE TABLE community_health_workers (worker_id INT,worker_name TEXT,state TEXT); INSERT INTO community_health_workers (worker_id,worker_name,state) VALUES (1,'Ana','Texas'),(2,'Ben','California'); CREATE TABLE mental_health_patients (patient_id INT,worker_id INT,diagnosis TEXT); INSERT INTO mental_health_patients (pa...
SELECT DISTINCT c.worker_name FROM community_health_workers c JOIN mental_health_patients m ON c.worker_id = m.worker_id WHERE c.state = 'Texas' AND m.diagnosis IS NOT NULL;
What is the average cost of development per drug that received approval in Canada after 2015?
CREATE TABLE drug_approval (drug_name TEXT,approval_date DATE,country TEXT); INSERT INTO drug_approval (drug_name,approval_date,country) VALUES ('DrugA','2016-01-01','Canada'),('DrugB','2017-05-15','Canada'),('DrugC','2014-10-30','USA'); CREATE TABLE drug_cost (drug_name TEXT,development_cost NUMERIC); INSERT INTO drug...
SELECT AVG(development_cost) FROM drug_cost INNER JOIN drug_approval ON drug_cost.drug_name = drug_approval.drug_name WHERE drug_approval.country = 'Canada' AND drug_approval.approval_date > '2015-01-01';
Calculate the average CO2 emissions for buildings in Texas that have a Platinum LEED certification.
CREATE TABLE buildings (id INT,name TEXT,state TEXT,co2_emissions FLOAT,leed_certification TEXT); INSERT INTO buildings (id,name,state,co2_emissions,leed_certification) VALUES (1,'Building A','Texas',120.5,'Platinum'),(2,'Building B','Texas',150.3,'Gold'),(3,'Building C','California',100.2,'Platinum');
SELECT AVG(co2_emissions) FROM buildings WHERE state = 'Texas' AND leed_certification = 'Platinum';
Delete infrastructure projects with a budget less than $100,000 in the 'rural_infrastructure' table.
CREATE TABLE rural_infrastructure (id INT,project_name VARCHAR(50),budget FLOAT); INSERT INTO rural_infrastructure (id,project_name,budget) VALUES (1,'Road Repair',120000.00),(2,'Bridge Construction',400000.00);
DELETE FROM rural_infrastructure WHERE budget < 100000.00;
What is the maximum delivery time for shipments to Brazil?
CREATE TABLE Brazil_Shipments (id INT,destination_country VARCHAR(50),delivery_time INT); INSERT INTO Brazil_Shipments (id,destination_country,delivery_time) VALUES (1,'Brazil',10),(2,'Brazil',12),(3,'Argentina',11);
SELECT MAX(delivery_time) FROM Brazil_Shipments WHERE destination_country = 'Brazil';
Who is the MVP candidate with the most assists in the last 20 games?
CREATE TABLE players (player_name TEXT,team TEXT,position TEXT,assists INT); INSERT INTO players (player_name,team,position,assists) VALUES ('Sue Bird','Seattle Storm','Guard',15),('Breanna Stewart','Seattle Storm','Forward',5);
SELECT player_name, assists FROM (SELECT player_name, assists, RANK() OVER (PARTITION BY team ORDER BY assists DESC ROWS BETWEEN UNBOUNDED PRECEDING AND 19 PRECEDING) as rank FROM players WHERE position = 'Guard') subquery WHERE rank = 1;
Which electric vehicles were sold in China in 2020 with more than 100,000 units?
CREATE TABLE EVSales (Year INT,Make VARCHAR(255),Model VARCHAR(255),Country VARCHAR(255),UnitsSold INT); INSERT INTO EVSales (Year,Make,Model,Country,UnitsSold) VALUES (2020,'Tesla','Model 3','China',120000);
SELECT Make, Model, SUM(UnitsSold) FROM EVSales WHERE Country = 'China' AND Year = 2020 GROUP BY Make, Model HAVING SUM(UnitsSold) > 100000;
What is the average size, in hectares, of community development initiatives in Brazil?
CREATE TABLE community_development_initiatives (id INT,name TEXT,size_ha FLOAT,country TEXT); INSERT INTO community_development_initiatives (id,name,size_ha,country) VALUES (1,'Initiative A',50.3,'Brazil'); INSERT INTO community_development_initiatives (id,name,size_ha,country) VALUES (2,'Initiative B',32.1,'Brazil');
SELECT AVG(size_ha) FROM community_development_initiatives WHERE country = 'Brazil';
How many students have been enrolled in each open pedagogy course, in chronological order?
CREATE TABLE open_pedagogy_enrollment (student_id INT,course_id INT,enrollment_date DATE); INSERT INTO open_pedagogy_enrollment VALUES (1,101,'2019-01-01'),(2,102,'2019-01-02');
SELECT course_id, COUNT(DISTINCT student_id) OVER (PARTITION BY course_id ORDER BY enrollment_date) as student_count FROM open_pedagogy_enrollment;
What is the average budget for defense diplomacy in 'Europe'?
CREATE TABLE Budget (id INT,region VARCHAR(30),amount INT); INSERT INTO Budget (id,region,amount) VALUES (1,'Europe',5000000);
SELECT AVG(amount) FROM Budget WHERE region = 'Europe';
Identify the top 3 carbon offset programs in terms of total CO2 emissions reduced in the African region.
CREATE TABLE offset_programs (program_name VARCHAR(255),region VARCHAR(255),co2_reduction FLOAT); INSERT INTO offset_programs (program_name,region,co2_reduction) VALUES ('Tree Planting Initiative A','Africa',50000),('Cookstove Distribution Project B','Africa',40000),('Solar Lighting Program C','Africa',30000),('Wind Fa...
SELECT program_name, SUM(co2_reduction) as total_reduction FROM offset_programs WHERE region = 'Africa' GROUP BY program_name ORDER BY total_reduction DESC LIMIT 3;
Insert a new record for a dance event with 100 attendees in Chicago.
CREATE TABLE Events (ID INT,City VARCHAR(50),EventType VARCHAR(50),AttendeeCount INT);
INSERT INTO Events (ID, City, EventType, AttendeeCount) VALUES (4, 'Chicago', 'Dance', 100);
Display the top 3 cuisines with the highest average revenue across all cities.
CREATE TABLE Restaurants (restaurant_id INT,name TEXT,city TEXT,cuisine TEXT,revenue FLOAT); INSERT INTO Restaurants (restaurant_id,name,city,cuisine,revenue) VALUES (1,'Asian Fusion','New York','Asian',50000.00),(2,'Bella Italia','Los Angeles','Italian',60000.00),(3,'Sushi House','New York','Asian',70000.00),(4,'Pizze...
SELECT cuisine, AVG(revenue) as avg_revenue FROM Restaurants GROUP BY cuisine ORDER BY avg_revenue DESC LIMIT 3;
Show the names of all agricultural innovation projects and their start dates from the "rural_projects" table
CREATE TABLE rural_projects (id INT,province VARCHAR(255),project_type VARCHAR(255),start_date DATE);
SELECT project_type, start_date FROM rural_projects WHERE project_type = 'Agricultural Innovation';
Create a table for patient outcomes
CREATE TABLE patient_outcomes (id INT PRIMARY KEY,patient_id INT,mental_health_condition_id INT,treatment_approach_id INT,outcome_date DATE,outcome_description TEXT);
CREATE TABLE patient_outcomes (id INT PRIMARY KEY, patient_id INT, mental_health_condition_id INT, treatment_approach_id INT, outcome_date DATE, outcome_description TEXT);
What is the average age of visitors who attended exhibitions in 'New Delhi' or 'Mumbai'?
CREATE TABLE Exhibitions (exhibition_id INT,city VARCHAR(20),country VARCHAR(20)); INSERT INTO Exhibitions (exhibition_id,city,country) VALUES (1,'New Delhi','India'),(2,'Mumbai','India'),(3,'Bengaluru','India'); CREATE TABLE Visitors (visitor_id INT,exhibition_id INT,age INT); INSERT INTO Visitors (visitor_id,exhibiti...
SELECT AVG(age) FROM Visitors v JOIN Exhibitions e ON v.exhibition_id = e.exhibition_id WHERE e.city IN ('New Delhi', 'Mumbai');
What is the total number of vegan meals served in the last 30 days, grouped by meal type?
CREATE TABLE meals (id INT,meal_name TEXT,is_vegan BOOLEAN,date DATE);
SELECT meal_type, COUNT(*) FROM meals WHERE is_vegan = TRUE AND date >= DATE(NOW()) - INTERVAL 30 DAY GROUP BY meal_type;
Which biosensor technology developers in Singapore received funding in 2021?
CREATE TABLE biosensor_developers (id INT,name TEXT,country TEXT,funding_source TEXT,funding_date DATE,funding_amount FLOAT); INSERT INTO biosensor_developers (id,name,country,funding_source,funding_date,funding_amount) VALUES (1,'BioTechNexus','Singapore','VC','2021-05-12',7000000);
SELECT name FROM biosensor_developers WHERE country = 'Singapore' AND funding_date >= '2021-01-01' AND funding_date <= '2021-12-31';
What is the maximum number of food safety violations recorded for a single inspection?
CREATE TABLE RestaurantInspections (inspection_id INT,restaurant_id INT,violation_count INT); INSERT INTO RestaurantInspections (inspection_id,restaurant_id,violation_count) VALUES (1,1,2),(2,1,0),(3,2,1),(4,3,10);
SELECT MAX(violation_count) FROM RestaurantInspections;
List the ports, their cargo handling operations, and the corresponding vessel types in the 'port_operations' and 'shipping' schemas.
CREATE TABLE port_operations.ports (id INT,name VARCHAR(50),location VARCHAR(50)); CREATE TABLE port_operations.cargo_handling (id INT,port_id INT,volume INT,vessel_type VARCHAR(50)); CREATE TABLE shipping.vessels (id INT,name VARCHAR(50),type VARCHAR(50),capacity INT);
SELECT p.name, ch.volume, s.type FROM port_operations.ports p INNER JOIN port_operations.cargo_handling ch ON p.id = ch.port_id INNER JOIN shipping.vessels s ON ch.vessel_type = s.type;
List the number of mental health parity incidents in each province for the last 6 months.
CREATE TABLE MentalHealthParity (IncidentID INT,IncidentDate DATE,Province VARCHAR(255)); INSERT INTO MentalHealthParity (IncidentID,IncidentDate,Province) VALUES (1,'2022-01-01','Ontario'); INSERT INTO MentalHealthParity (IncidentID,IncidentDate,Province) VALUES (2,'2022-02-15','Quebec'); INSERT INTO MentalHealthParit...
SELECT Province, COUNT(*) FROM MentalHealthParity WHERE IncidentDate >= DATEADD(month, -6, GETDATE()) GROUP BY Province;
How many emergency medical incidents were there in each borough?
CREATE TABLE emergency_incidents (id INT,incident_type VARCHAR(50),borough VARCHAR(50)); INSERT INTO emergency_incidents (id,incident_type,borough) VALUES (1,'Medical Emergency','Brooklyn'),(2,'Medical Emergency','Manhattan');
SELECT borough, COUNT(*) FROM emergency_incidents WHERE incident_type = 'Medical Emergency' GROUP BY borough;
Delete records with gender 'M' from the 'diversity_metrics' table
diversity_metrics
DELETE FROM diversity_metrics WHERE gender = 'M';
Find the sum of investments for projects with a climate action focus in the Asia-Pacific region.
CREATE TABLE projects_investments (id INT,name TEXT,focus TEXT,region TEXT,investment FLOAT); INSERT INTO projects_investments (id,name,focus,region,investment) VALUES (1,'Clean Energy Project','Climate Action','Asia-Pacific',100000.0),(2,'Sustainable Agriculture Program','Biodiversity','Asia-Pacific',150000.0);
SELECT SUM(investment) FROM projects_investments WHERE focus = 'Climate Action' AND region = 'Asia-Pacific';
What is the total cost of wind energy transactions for each destination?
CREATE TABLE energy_transactions (id INT PRIMARY KEY,source VARCHAR(50),destination VARCHAR(50),energy_type VARCHAR(50),quantity INT,transaction_date DATE);
SELECT energy_transactions.destination, SUM(energy_transactions.quantity * carbon_pricing.price) FROM energy_transactions INNER JOIN carbon_pricing ON energy_transactions.energy_type = carbon_pricing.location WHERE energy_type = 'Wind' GROUP BY energy_transactions.destination;
What is the total budget for agricultural innovation projects in Southeast Asia that have a budget greater than $50,000?
CREATE TABLE agricultural_innovation (id INT,project_budget INT,project_status TEXT,country TEXT); INSERT INTO agricultural_innovation (id,project_budget,project_status,country) VALUES (1,60000,'completed','Thailand'),(2,45000,'in_progress','Vietnam'),(3,70000,'completed','Malaysia');
SELECT SUM(project_budget) FROM agricultural_innovation WHERE project_budget > 50000 AND country IN ('Southeast Asia');
What is the average points per game scored by players from the United States in the NBA?
CREATE TABLE players (id INT,name TEXT,country TEXT,points_per_game FLOAT);
SELECT AVG(points_per_game) FROM players WHERE country = 'United States';
What is the average number of AI safety incidents per country in the last year?
CREATE TABLE ai_safety_incidents (incident_id INT,incident_date DATE,incident_country TEXT); INSERT INTO ai_safety_incidents (incident_id,incident_date,incident_country) VALUES (1,'2021-03-15','USA'),(2,'2020-12-21','Canada'),(3,'2021-08-01','UK'); CREATE TABLE countries (country_id INT,country_name TEXT); INSERT INTO ...
SELECT c.country_name, AVG(EXTRACT(YEAR FROM ai.incident_date)) as avg_year FROM ai_safety_incidents ai JOIN countries c ON ai.incident_country = c.country_name GROUP BY c.country_name;
What is the total climate finance spent by each country in the 'americas' region?
CREATE TABLE climate_finance (country VARCHAR(20),amount FLOAT); INSERT INTO climate_finance (country,amount) VALUES ('usa',100000),('canada',75000),('brazil',55000),('argentina',40000),('mexico',35000);
SELECT country, SUM(amount) FROM climate_finance WHERE country IN ('usa', 'canada', 'brazil', 'argentina', 'mexico') GROUP BY country;
What is the total waste generated from disposable cutlery in the last quarter?
CREATE TABLE inventory (item_id INT,name TEXT,category TEXT,unit_price FLOAT,unit_quantity INT,unit_weight FLOAT,waste_factor FLOAT); INSERT INTO inventory (item_id,name,category,unit_price,unit_quantity,unit_weight,waste_factor) VALUES (1,'Plastic Spoon','Disposable',0.05,100,0.01,0.02),(2,'Paper Plate','Disposable',0...
SELECT SUM(i.unit_quantity * i.unit_weight * s.sale_quantity * i.waste_factor) as total_waste FROM inventory i JOIN sales s ON i.item_id = s.item_id WHERE i.category = 'Disposable' AND s.sale_date BETWEEN '2022-01-01' AND '2022-03-31';
Insert a new record for 'Bamboo Viscose' with a water consumption reduction of '50%' into the 'sustainability_metrics' table
CREATE TABLE sustainability_metrics (id INT PRIMARY KEY,fabric VARCHAR(50),water_reduction DECIMAL(3,2));
INSERT INTO sustainability_metrics (id, fabric, water_reduction) VALUES (2, 'Bamboo Viscose', 0.50);
What's the average production budget for action movies released between 2010 and 2015, and their respective IMDb ratings?
CREATE TABLE Movies (MovieID INT,Title VARCHAR(255),Genre VARCHAR(50),ReleaseYear INT,ProductionBudget DECIMAL(10,2),IMDBRating DECIMAL(3,2));
SELECT AVG(ProductionBudget) AS Avg_Budget, AVG(IMDBRating) AS Avg_Rating FROM Movies WHERE Genre = 'Action' AND ReleaseYear BETWEEN 2010 AND 2015;
Find the top 2 cities with the highest average donation amount in 2023?
CREATE TABLE Donations (id INT,user_id INT,city VARCHAR(50),amount DECIMAL(10,2),donation_date DATE); INSERT INTO Donations (id,user_id,city,amount,donation_date) VALUES (1,1001,'New York',50.00,'2023-01-05'); INSERT INTO Donations (id,user_id,city,amount,donation_date) VALUES (2,1002,'Toronto',75.00,'2023-01-10'); INS...
SELECT city, AVG(amount) as avg_donation FROM Donations WHERE donation_date >= '2023-01-01' AND donation_date < '2024-01-01' GROUP BY city ORDER BY avg_donation DESC LIMIT 2;
Delete all records of Classical music streams in Brazil before January 1, 2021.
CREATE TABLE streams (song_id INT,stream_date DATE,genre VARCHAR(20),country VARCHAR(20),revenue DECIMAL(10,2)); INSERT INTO streams (song_id,stream_date,genre,country,revenue) VALUES (17,'2020-12-31','Classical','Brazil',2.50);
DELETE FROM streams WHERE genre = 'Classical' AND country = 'Brazil' AND stream_date < '2021-01-01';
Show the names and locations of all restorative justice programs starting in 2023 from the 'programs' table
CREATE TABLE programs (id INT,name VARCHAR(50),location VARCHAR(50),type VARCHAR(50),start_date DATE,end_date DATE);
SELECT name, location FROM programs WHERE type = 'Restorative Justice' AND start_date >= '2023-01-01';
What are the total production rates for each compound in Factory A?
CREATE TABLE factories (id INT,name VARCHAR(255)); CREATE TABLE production_rates (factory_id INT,compound_name VARCHAR(255),production_rate INT); INSERT INTO factories (id,name) VALUES (1,'Factory A'),(2,'Factory B'); INSERT INTO production_rates (factory_id,compound_name,production_rate) VALUES (1,'Compound X',200),(1...
SELECT compound_name, SUM(production_rate) FROM production_rates INNER JOIN factories ON production_rates.factory_id = factories.id WHERE factories.name = 'Factory A' GROUP BY compound_name;
How many space missions have been conducted by NASA?
CREATE TABLE space_missions (id INT,name VARCHAR(50),agency VARCHAR(50),year INT); INSERT INTO space_missions (id,name,agency,year) VALUES (1,'Apollo 11','NASA',1969); INSERT INTO space_missions (id,name,agency,year) VALUES (2,'Voyager 1','NASA',1977); INSERT INTO space_missions (id,name,agency,year) VALUES (3,'Mars Cu...
SELECT COUNT(*) FROM space_missions WHERE agency = 'NASA';
What is the total wind energy production in Canada and Mexico?
CREATE TABLE wind_energy (country VARCHAR(20),production FLOAT); INSERT INTO wind_energy (country,production) VALUES ('Canada',15.2),('Canada',15.5),('Mexico',12.6),('Mexico',12.9);
SELECT SUM(production) as total_production, country FROM wind_energy GROUP BY country;
What's the sensor data for humidity above 70%?
CREATE TABLE sensor_data (id INT,sensor_id VARCHAR(255),temperature DECIMAL(4,2),humidity DECIMAL(4,2),PRIMARY KEY (id)); INSERT INTO sensor_data (id,sensor_id,temperature,humidity) VALUES (1,'s1',24.3,55.1),(2,'s2',26.8,48.6),(3,'s3',22.9,72.5);
SELECT * FROM sensor_data WHERE humidity > 70.0;
What is the average distance of the International Space Station from Earth?
CREATE TABLE Space_Stations (ID INT,Name VARCHAR(50),Type VARCHAR(50),Average_Distance FLOAT); INSERT INTO Space_Stations (ID,Name,Type,Average_Distance) VALUES (1,'International Space Station','Space Station',410.4);
SELECT AVG(Average_Distance) FROM Space_Stations WHERE Name = 'International Space Station';
What is the average age of patients who received cognitive behavioral therapy (CBT)?
CREATE TABLE patients (patient_id INT,age INT,treatment VARCHAR(20)); INSERT INTO patients (patient_id,age,treatment) VALUES (1,35,'CBT'),(2,28,'CBT'),(3,42,'CBT');
SELECT AVG(age) FROM patients WHERE treatment = 'CBT';
List the total number of species observed and the number of unique species observed for each year in the Arctic region.
CREATE TABLE species_data (measurement_id INT,measurement_date DATE,observed_species VARCHAR(50),location VARCHAR(50));
SELECT YEAR(measurement_date) AS year, COUNT(observed_species) AS total_species_observed, COUNT(DISTINCT observed_species) AS unique_species_observed FROM species_data WHERE location LIKE '%Arctic%' GROUP BY year;
What was the total R&D expenditure for the year 2020 by company?
CREATE SCHEMA pharma;CREATE TABLE pharma.company (id INT,name VARCHAR(50));CREATE TABLE pharma.expenditure (company_id INT,year INT,amount DECIMAL(10,2)); INSERT INTO pharma.company (id,name) VALUES (1,'AstraZeneca'),(2,'Pfizer'); INSERT INTO pharma.expenditure (company_id,year,amount) VALUES (1,2020,12000000),(1,2019,...
SELECT c.name, SUM(e.amount) FROM pharma.expenditure e JOIN pharma.company c ON e.company_id = c.id WHERE e.year = 2020 GROUP BY c.name;
What is the total number of cruelty-free and non-cruelty-free products?
CREATE TABLE products_cruelty (id INT,product_name TEXT,cruelty_free BOOLEAN); INSERT INTO products_cruelty (id,product_name,cruelty_free) VALUES (1,'Lotion',true),(2,'Shampoo',false),(3,'Soap',true);
SELECT cruelty_free, COUNT(*) FROM products_cruelty GROUP BY cruelty_free;