instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
Delete records of users who have not interacted with the creative AI application in the past year
CREATE TABLE users (id INT,last_interaction TIMESTAMP); INSERT INTO users (id,last_interaction) VALUES (1,'2021-01-01 10:00:00'),(2,'2021-06-15 14:30:00'),(3,'2020-12-25 09:15:00'),(4,'2019-08-05 16:20:00');
DELETE FROM users WHERE last_interaction < NOW() - INTERVAL 1 YEAR;
What is the difference between the total transaction amount in the last 30 days and the total transaction amount in the 30 days prior to that?
CREATE TABLE Transactions (TransactionID INT,TransactionDate DATE,Amount DECIMAL(18,2));INSERT INTO Transactions VALUES (1,'2022-01-01',1000.00),(2,'2022-01-15',2000.00),(3,'2022-02-01',3000.00),(4,'2022-03-01',1500.00),(5,'2022-03-15',2500.00);
SELECT (SUM(CASE WHEN TransactionDate >= DATEADD(day,-30,GETDATE()) THEN Amount ELSE 0 END) - SUM(CASE WHEN TransactionDate >= DATEADD(day,-60,GETDATE()) AND TransactionDate < DATEADD(day,-30,GETDATE()) THEN Amount ELSE 0 END)) AS TransactionAmountDifference FROM Transactions;
What is the average budget allocated for utilities in rural areas?
CREATE TABLE areas (id INT,name VARCHAR(20)); INSERT INTO areas (id,name) VALUES (1,'Urban'),(2,'Rural'); CREATE TABLE budget (item VARCHAR(20),area_id INT,amount INT); INSERT INTO budget (item,area_id,amount) VALUES ('Utilities',1,6000000),('Utilities',2,3500000);
SELECT AVG(amount) FROM budget WHERE item = 'Utilities' AND area_id = (SELECT id FROM areas WHERE name = 'Rural');
Identify the number of renewable energy projects in Texas with a completion year greater than 2018.
CREATE TABLE renewable_energy_projects (id INT,state VARCHAR(20),completion_year INT); INSERT INTO renewable_energy_projects (id,state,completion_year) VALUES (1,'Texas',2017),(2,'Texas',2020);
SELECT COUNT(*) FROM renewable_energy_projects WHERE state = 'Texas' AND completion_year > 2018;
What is the total quantity of mineral extracted for each mine in a specific year?
CREATE TABLE ExtractionData (ExtractionDataID INT,MineID INT,Date DATE,Mineral TEXT,Quantity INT);
SELECT MineID, SUM(Quantity) FROM ExtractionData WHERE YEAR(Date) = 2022 GROUP BY MineID;
Which program has the least number of volunteers?
CREATE TABLE Volunteers (VolunteerID INT,Name TEXT,Program TEXT);
SELECT Program, COUNT(*) AS Count FROM Volunteers GROUP BY Program ORDER BY Count ASC LIMIT 1;
List biotech startups in descending order based on their funding amounts.
CREATE SCHEMA if not exists biotech;CREATE TABLE if not exists biotech.startups (id INT,name VARCHAR(255),country VARCHAR(255),funding_amount DECIMAL(10,2)); INSERT INTO biotech.startups (id,name,country,funding_amount) VALUES (1,'Genetix','USA',2000000.00),(2,'BioSense','Canada',1500000.00);
SELECT * FROM biotech.startups ORDER BY funding_amount DESC;
What is the total billing amount for cases handled by attorneys who identify as male?
CREATE TABLE Attorneys (AttorneyID INT PRIMARY KEY,Sexuality VARCHAR(255),HourlyRate DECIMAL(5,2)); INSERT INTO Attorneys (AttorneyID,Sexuality,HourlyRate) VALUES (1,'Heterosexual',300.00),(2,'Gay',250.00),(3,'Straight',350.00); CREATE TABLE Cases (CaseID INT PRIMARY KEY,AttorneyID INT,HoursBilled DECIMAL(5,2)); INSERT INTO Cases (CaseID,AttorneyID,HoursBilled) VALUES (1,1,50.00),(2,2,75.00),(3,3,100.00);
SELECT SUM(HoursBilled * Attorneys.HourlyRate) FROM Cases JOIN Attorneys ON Cases.AttorneyID = Attorneys.AttorneyID WHERE Attorneys.Sexuality IN ('Heterosexual', 'Straight');
What are the total labor hours for the Sustainable Housing project?
CREATE TABLE labor (id INT,project_id INT,worker_name VARCHAR(50),hours FLOAT); INSERT INTO labor (id,project_id,worker_name,hours) VALUES (6,6,'Jamila',200);
SELECT SUM(hours) FROM labor WHERE project_id = 6;
What is the average budget for sustainable energy projects in Africa?
CREATE TABLE projects (id INT,region VARCHAR(50),name VARCHAR(50),budget INT); INSERT INTO projects (id,region,name,budget) VALUES (1,'Africa','Solar Power',80000),(2,'Asia','Wind Energy',100000);
SELECT AVG(budget) FROM projects WHERE region = 'Africa' AND name LIKE '%sustainable energy%';
Find the total biomass of fish in the sustainable_seafood_trends_2 table for each fishing_method.
CREATE TABLE sustainable_seafood_trends_2 (fishing_method VARCHAR(255),biomass FLOAT); INSERT INTO sustainable_seafood_trends_2 (fishing_method,biomass) VALUES ('Line Fishing',550),('Trawling',750),('Potting',650);
SELECT fishing_method, SUM(biomass) FROM sustainable_seafood_trends_2 GROUP BY fishing_method;
How many crimes were reported in District2 of CityJ in 2018?
CREATE TABLE crimes_2 (id INT,city VARCHAR(50),district VARCHAR(50),year INT,crime_count INT); INSERT INTO crimes_2 (id,city,district,year,crime_count) VALUES (1,'CityJ','District2',2018,33),(2,'CityJ','District2',2017,40),(3,'CityK','District3',2018,47);
SELECT SUM(crime_count) FROM crimes_2 WHERE city = 'CityJ' AND district = 'District2' AND year = 2018;
Find the names of athletes who have participated in baseball and soccer, but not basketball.
CREATE TABLE athletes_2 (name TEXT,sport TEXT); INSERT INTO athletes_2 (name,sport) VALUES ('John Doe','Baseball'),('Jane Doe','Soccer'),('Jim Smith','Baseball'),('Jill Smith','Soccer'),('James Johnson','Basketball');
SELECT name FROM athletes_2 WHERE sport IN ('Baseball', 'Soccer') AND name NOT IN (SELECT name FROM athletes_2 WHERE sport = 'Basketball');
What was the total revenue from users in France and Germany for the 'electronics' product category in Q2 2022?
CREATE TABLE products (product_id INT,product_name VARCHAR(255),category VARCHAR(255)); INSERT INTO products (product_id,product_name,category) VALUES (1,'Laptop 1','electronics'),(2,'Phone 1','electronics'); CREATE TABLE users (user_id INT,user_country VARCHAR(255)); INSERT INTO users (user_id,user_country) VALUES (1,'France'),(2,'Germany'); CREATE TABLE orders (order_id INT,user_id INT,product_id INT,order_date DATE,revenue DECIMAL(10,2)); INSERT INTO orders (order_id,user_id,product_id,order_date,revenue) VALUES (1,1,1,'2022-04-01',800),(2,2,1,'2022-04-05',900);
SELECT SUM(revenue) FROM orders o JOIN products p ON o.product_id = p.product_id JOIN users u ON o.user_id = u.user_id WHERE u.user_country IN ('France', 'Germany') AND p.category = 'electronics' AND o.order_date BETWEEN '2022-04-01' AND '2022-06-30';
Calculate the percentage of students who are international in the 'English' program.
CREATE TABLE students (student_id INT,program_name VARCHAR(255),is_international BOOLEAN); INSERT INTO students (student_id,program_name,is_international) VALUES (1,'Computer Science',TRUE),(2,'Physics',FALSE),(3,'English',TRUE);
SELECT program_name, AVG(is_international) * 100.0 AS pct_international FROM students GROUP BY program_name;
What is the total communication budget for each organization in 2019?
CREATE TABLE communication_budget (org_name VARCHAR(50),year INT,budget FLOAT); INSERT INTO communication_budget (org_name,year,budget) VALUES ('UNFCCC',2019,1000000),('Greenpeace',2019,1200000),('WWF',2019,1500000);
SELECT org_name, SUM(budget) as total_budget FROM communication_budget WHERE year = 2019 GROUP BY org_name;
Find the number of military equipment sales by quarter in 2021 and display the result in a YYYY-Q format.
CREATE TABLE QuarterlySales (sale_id INT,equipment_type VARCHAR(50),sale_value FLOAT,sale_date DATE); INSERT INTO QuarterlySales (sale_id,equipment_type,sale_value,sale_date) VALUES (5,'Tanks',18000000,'2021-02-15'),(6,'Fighter Jets',55000000,'2021-03-20'),(7,'Armored Vehicles',8000000,'2021-06-05'),(8,'Helicopters',15000000,'2021-09-01');
SELECT DATE_FORMAT(sale_date, '%Y-Q') AS Quarter, COUNT(*) AS SalesCount FROM QuarterlySales WHERE YEAR(sale_date) = 2021 GROUP BY Quarter;
How many times did each user attempt to log in, successfully and unsuccessfully, over the past week?
CREATE TABLE login_attempts (id INT,user_name VARCHAR(255),success BOOLEAN,login_time TIMESTAMP); INSERT INTO login_attempts (id,user_name,success,login_time) VALUES (1,'user1',false,'2022-06-01 10:00:00'),(2,'user2',true,'2022-06-02 11:00:00');
SELECT user_name, SUM(CASE WHEN success THEN 1 ELSE 0 END) as successful_logins, SUM(CASE WHEN NOT success THEN 1 ELSE 0 END) as unsuccessful_logins FROM login_attempts WHERE login_time >= DATE(NOW()) - INTERVAL '7 days' GROUP BY user_name;
What is the number of clinics in urban and rural areas of Florida and Georgia?
CREATE TABLE clinics (id INT,name TEXT,location TEXT); INSERT INTO clinics (id,name,location) VALUES (1,'Clinic A','Urban Florida'); INSERT INTO clinics (id,name,location) VALUES (2,'Clinic B','Rural Florida'); INSERT INTO clinics (id,name,location) VALUES (3,'Clinic C','Urban Georgia'); INSERT INTO clinics (id,name,location) VALUES (4,'Clinic D','Rural Georgia');
SELECT COUNT(*) FROM clinics WHERE location IN ('Urban Florida', 'Rural Florida', 'Urban Georgia', 'Rural Georgia');
Identify the military technology patents filed by ASEAN countries in 2021.
CREATE TABLE Patents (id INT PRIMARY KEY,country VARCHAR(50),tech_name VARCHAR(50),filing_year INT); INSERT INTO Patents (id,country,tech_name,filing_year) VALUES (1,'Singapore','AI-based surveillance',2021),(2,'Indonesia','Drone technology',2021),(3,'Thailand','Cybersecurity software',2021);
SELECT country, tech_name FROM Patents WHERE country IN ('Singapore', 'Indonesia', 'Thailand') AND filing_year = 2021;
What is the total oil production in the 'Middle East' for the year 2020?
CREATE TABLE production (production_id INT,location VARCHAR(255),year INT,oil_production FLOAT); INSERT INTO production (production_id,location,year,oil_production) VALUES (1,'Saudi Arabia',2020,5000000),(2,'Iran',2020,3000000),(3,'Iraq',2019,4000000);
SELECT SUM(oil_production) FROM production WHERE location LIKE '%Middle East%' AND year = 2020;
How many people attended the 'Jazz Night' event by age group?
CREATE TABLE Events (event_id INT,event_name VARCHAR(50)); CREATE TABLE Attendees (attendee_id INT,event_id INT,age INT); INSERT INTO Events (event_id,event_name) VALUES (1,'Jazz Night'); INSERT INTO Attendees (attendee_id,event_id,age) VALUES (1,1,25),(2,1,35),(3,1,45);
SELECT e.event_name, a.age, COUNT(a.attendee_id) FROM Events e JOIN Attendees a ON e.event_id = a.event_id WHERE e.event_name = 'Jazz Night' GROUP BY e.event_name, a.age;
Show the number of users who played a specific game in the last month, grouped by country.
CREATE TABLE users(id INT,name VARCHAR(50),country VARCHAR(50),last_login DATETIME); CREATE TABLE game_sessions(id INT,user_id INT,game_name VARCHAR(50),start_time DATETIME);
SELECT game_name, country, COUNT(DISTINCT users.id) as num_users FROM game_sessions JOIN users ON game_sessions.user_id = users.id WHERE start_time >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH) GROUP BY game_name, country;
Find the number of articles published per day for the last week in 'weeklyreview' database.
CREATE TABLE articles (article_id INT,publish_date DATE); INSERT INTO articles VALUES (1,'2022-01-01'); INSERT INTO articles VALUES (2,'2022-01-02');
SELECT DATE(publish_date), COUNT(*) FROM articles WHERE publish_date >= CURDATE() - INTERVAL 7 DAY GROUP BY DATE(publish_date)
How many operational and inoperable satellites are in orbit?
CREATE TABLE satellites (id INT,name VARCHAR(255),status VARCHAR(255)); INSERT INTO satellites (id,name,status) VALUES (1,'Satellite 1','Operational'),(2,'Satellite 2','Operational'),(3,'Satellite 3','Inoperable');
SELECT SUM(CASE WHEN status = 'Operational' THEN 1 ELSE 0 END) AS operational, SUM(CASE WHEN status = 'Inoperable' THEN 1 ELSE 0 END) AS inoperable FROM satellites;
What is the average income for clients who won their cases?
CREATE TABLE CaseResults (CaseID INT,Won BOOLEAN); INSERT INTO CaseResults (CaseID,Won) VALUES (1,TRUE),(2,FALSE);
SELECT AVG(Clients.Income) FROM Clients INNER JOIN CaseResults ON Clients.CaseID = CaseResults.CaseID WHERE CaseResults.Won = TRUE;
What is the change in population of dolphins in the Indian Ocean over the past 15 years?
CREATE TABLE dolphin_population (year INT,ocean VARCHAR(255),population INT); INSERT INTO dolphin_population (year,ocean,population) VALUES (2006,'Indian Ocean',950000),(2007,'Indian Ocean',930000),(2008,'Indian Ocean',920000),(2009,'Indian Ocean',910000),(2010,'Indian Ocean',900000),(2011,'Indian Ocean',890000),(2012,'Indian Ocean',880000),(2013,'Indian Ocean',870000),(2014,'Indian Ocean',860000),(2015,'Indian Ocean',850000),(2016,'Indian Ocean',840000),(2017,'Indian Ocean',830000),(2018,'Indian Ocean',820000),(2019,'Indian Ocean',810000),(2020,'Indian Ocean',800000);
SELECT year, population, LAG(population) OVER (ORDER BY year) as prev_population, population - LAG(population) OVER (ORDER BY year) as population_change FROM dolphin_population WHERE ocean = 'Indian Ocean';
What is the total number of defense projects and their total cost for each category?
CREATE TABLE DefenseProjects (project_id INT,project_category VARCHAR(50),project_cost DECIMAL(10,2)); INSERT INTO DefenseProjects (project_id,project_category,project_cost) VALUES (1,'Research',1000000.00); INSERT INTO DefenseProjects (project_id,project_category,project_cost) VALUES (2,'Development',2000000.00);
SELECT project_category, COUNT(*) as total_projects, SUM(project_cost) as total_cost FROM DefenseProjects GROUP BY project_category;
What is the average trip duration for electric buses in the city of 'Los Angeles'?
CREATE TABLE if not exists Cities (id int,name text); INSERT INTO Cities (id,name) VALUES (1,'Los Angeles'),(2,'New York'); CREATE TABLE if not exists Vehicles (id int,type text,capacity int,city_id int); INSERT INTO Vehicles (id,type,capacity,city_id) VALUES (1,'Electric Bus',50,1),(2,'Diesel Bus',60,1),(3,'Electric Bus',40,2); CREATE TABLE if not exists Trips (id int,vehicle_id int,duration int); INSERT INTO Trips (id,vehicle_id,duration) VALUES (1,1,120),(2,1,180),(3,2,210),(4,3,150);
SELECT AVG(duration) FROM Trips JOIN Vehicles ON Trips.vehicle_id = Vehicles.id WHERE Vehicles.type = 'Electric Bus' AND Vehicles.city_id = (SELECT id FROM Cities WHERE name = 'Los Angeles');
What is the total number of animals in 'Refuge A' and 'Refuge B'?
CREATE TABLE RefugeA(animal_id INT,species VARCHAR(20),refuge VARCHAR(10)); INSERT INTO RefugeA VALUES (1,'Bear','RefugeA'),(2,'Deer','RefugeA'),(3,'Raccoon','RefugeA'); CREATE TABLE RefugeB(animal_id INT,species VARCHAR(20),refuge VARCHAR(10)); INSERT INTO RefugeB VALUES (4,'Fox','RefugeB'),(5,'Rabbit','RefugeB'),(6,'Bear','RefugeB');
SELECT SUM(qty) FROM (SELECT COUNT(*) as qty FROM RefugeA UNION ALL SELECT COUNT(*) as qty FROM RefugeB) as total;
What is the total quantity of gold mined by mining operations located in Canada?
CREATE TABLE mining_operation (id INT,name VARCHAR(50),location VARCHAR(50),resource VARCHAR(50),quantity INT); INSERT INTO mining_operation (id,name,location,resource,quantity) VALUES (1,'Operation A','Canada','Gold',1000); INSERT INTO mining_operation (id,name,location,resource,quantity) VALUES (2,'Operation B','USA','Silver',2000); INSERT INTO mining_operation (id,name,location,resource,quantity) VALUES (3,'Operation C','Canada','Gold',1500);
SELECT SUM(quantity) FROM mining_operation WHERE location = 'Canada' AND resource = 'Gold';
What is the total revenue for online travel agencies in 'Sydney'?
CREATE TABLE otas (ota_id INT,name TEXT,city TEXT,revenue FLOAT);
SELECT city, SUM(revenue) as total_revenue FROM otas WHERE city = 'Sydney' GROUP BY city;
Determine the annual change in average property price in the Bay Area, partitioned by property type and ordered by price in descending order.
CREATE TABLE bay_area_properties_yearly (property_id INT,year INT,price DECIMAL(10,2),size INT,co_ownership BOOLEAN,property_type VARCHAR(20)); INSERT INTO bay_area_properties_yearly (property_id,year,price,size,co_ownership,property_type) VALUES (1,2020,1000000,2000,TRUE,'Condo'),(2,2021,1200000,3000,TRUE,'House'),(3,2020,800000,1500,FALSE,'Condo'),(4,2021,1300000,2500,FALSE,'House'),(5,2020,1100000,2000,TRUE,'House');
SELECT property_type, EXTRACT(YEAR FROM date_trunc('year', time)) AS year, AVG(price) AS avg_price, LAG(AVG(price)) OVER (PARTITION BY property_type ORDER BY EXTRACT(YEAR FROM date_trunc('year', time))) - AVG(price) AS annual_change, ROW_NUMBER() OVER (PARTITION BY property_type ORDER BY EXTRACT(YEAR FROM date_trunc('year', time)) DESC) AS rank FROM bay_area_properties_yearly GROUP BY property_type, year ORDER BY property_type, rank;
How many energy storage projects have been implemented each year in the storage table?
CREATE TABLE storage (id INT,name VARCHAR(50),type VARCHAR(50),capacity INT,created_at TIMESTAMP);
SELECT EXTRACT(YEAR FROM created_at) as year, COUNT(*) as num_projects FROM storage GROUP BY year ORDER BY year ASC;
What is the total rainfall in the last month for region 'CA-BC'?
CREATE TABLE region (id INT,name VARCHAR(255),rainfall FLOAT); INSERT INTO region (id,name,rainfall) VALUES (1,'US-MN',12.5),(2,'US-ND',11.8),(3,'CA-BC',18.3);
SELECT SUM(rainfall) FROM region WHERE name = 'CA-BC' AND rainfall_timestamp >= DATEADD(month, -1, CURRENT_TIMESTAMP);
What is the maximum number of military vehicles sold by GroundForce to the Mexican government?
CREATE TABLE GroundForce.VehicleSales (id INT,manufacturer VARCHAR(255),model VARCHAR(255),quantity INT,price DECIMAL(10,2),buyer_country VARCHAR(255),sale_date DATE);
SELECT MAX(quantity) FROM GroundForce.VehicleSales WHERE buyer_country = 'Mexico';
Retrieve all records from the 'suppliers' table where the country is not 'Italy'
CREATE TABLE suppliers (id INT,name TEXT,country TEXT); INSERT INTO suppliers (id,name,country) VALUES (1,'Green Earth Farms','France'),(2,'La Placita Market','Spain'),(3,'Bella Verde Organics','Italy');
SELECT * FROM suppliers WHERE country != 'Italy';
What is the maximum monthly bill for broadband subscribers in the state of Texas?
CREATE TABLE broadband_subscribers (subscriber_id INT,monthly_bill FLOAT,state VARCHAR(20)); INSERT INTO broadband_subscribers (subscriber_id,monthly_bill,state) VALUES (1,60.5,'Texas'),(2,70.3,'Texas'),(3,55.7,'California');
SELECT MAX(monthly_bill) FROM broadband_subscribers WHERE state = 'Texas';
Which were the top 3 most vulnerable software applications by severity in the EMEA region in H1 2021?
CREATE TABLE vulnerabilities (id INT,app_name VARCHAR(255),severity INT,region VARCHAR(255),occurrence_date DATE); INSERT INTO vulnerabilities (id,app_name,severity,region,occurrence_date) VALUES (1,'App1',8,'EMEA','2021-02-03');
SELECT app_name, severity FROM vulnerabilities WHERE region = 'EMEA' AND occurrence_date >= '2021-01-01' AND occurrence_date < '2021-07-01' GROUP BY app_name HAVING COUNT(*) <= 3 ORDER BY severity DESC;
Which disability accommodations have been implemented in California?
CREATE TABLE Accommodations (id INT,name TEXT,location TEXT); INSERT INTO Accommodations (id,name,location) VALUES (1,'Ramp','California'),(2,'Elevator','New York');
SELECT name FROM Accommodations WHERE location = 'California';
What is the total cost and number of initiatives for water conservation in Georgia in the year 2022?
CREATE TABLE WaterConservationInitiatives (InitiativeID INT PRIMARY KEY,Location VARCHAR(255),InitiativeType VARCHAR(255),Cost INT,StartDate DATETIME,EndDate DATETIME); INSERT INTO WaterConservationInitiatives (InitiativeID,Location,InitiativeType,Cost,StartDate,EndDate) VALUES (1,'Georgia','Water-efficient Appliances',10000,'2022-01-01','2022-12-31');
SELECT InitiativeType, SUM(Cost) as TotalCost, COUNT(*) as TotalInitiatives FROM WaterConservationInitiatives WHERE Location = 'Georgia' AND YEAR(StartDate) = 2022 GROUP BY InitiativeType;
Who are the first and last female astronauts to go to the International Space Station?
CREATE TABLE astronauts (id INT,name VARCHAR(50),gender VARCHAR(10),nationality VARCHAR(50)); CREATE TABLE space_missions (id INT,mission_name VARCHAR(50),launch_date DATE,return_date DATE,astronaut_id INT);
SELECT astronauts.name FROM astronauts INNER JOIN space_missions ON astronauts.id = space_missions.astronaut_id WHERE gender = 'Female' AND space_missions.mission_name = 'International Space Station' GROUP BY astronauts.name ORDER BY launch_date LIMIT 1; SELECT astronauts.name FROM astronauts INNER JOIN space_missions ON astronauts.id = space_missions.astronaut_id WHERE gender = 'Female' AND space_missions.mission_name = 'International Space Station' GROUP BY astronauts.name ORDER BY return_date DESC LIMIT 1;
What is the total donation amount per program?
CREATE TABLE Donations (DonationID INT,DonationDate DATE,DonationAmount DECIMAL(10,2),ProgramID INT); INSERT INTO Donations (DonationID,DonationDate,DonationAmount,ProgramID) VALUES (1,'2022-01-01',100.00,1),(2,'2022-01-15',200.00,1),(3,'2022-02-01',300.00,2),(4,'2022-02-15',400.00,2);
SELECT ProgramID, SUM(DonationAmount) OVER (PARTITION BY ProgramID ORDER BY ProgramID) AS TotalDonation FROM Donations;
What is the total transaction amount for 'South America' customers?
CREATE TABLE transactions (id INT,customer_region VARCHAR(20),transaction_amount DECIMAL(10,2)); INSERT INTO transactions (id,customer_region,transaction_amount) VALUES (1,'North America',500.00),(2,'North America',750.00),(3,'South America',800.00),(4,'Europe',900.00);
SELECT SUM(transaction_amount) FROM transactions WHERE customer_region = 'South America';
What is the total duration of all media contents produced in 2022?
CREATE TABLE media_contents (content_id INTEGER,title VARCHAR(255),duration INTEGER,release_year INTEGER); INSERT INTO media_contents (content_id,title,duration,release_year) VALUES (1,'Content1',120,2021),(2,'Content2',90,2020),(3,'Content3',150,2022),(4,'Content4',100,2019),(5,'Content5',110,2022),(6,'Content6',130,2018),(7,'Content7',80,2022);
SELECT SUM(duration) FROM media_contents WHERE release_year = 2022;
Which forests in Australia have eucalyptus trees?
CREATE TABLE forests (id INT PRIMARY KEY,name VARCHAR(50),country VARCHAR(50),hectares DECIMAL(10,2)); CREATE TABLE trees (id INT PRIMARY KEY,species VARCHAR(50),age INT,forest_id INT,FOREIGN KEY (forest_id) REFERENCES forests(id)); INSERT INTO forests (id,name,country,hectares) VALUES (1,'Eucalyptus Forest','Australia',250000.00); INSERT INTO trees (id,species,age,forest_id) VALUES (1,'Eucalyptus',150,1);
SELECT forests.name FROM forests INNER JOIN trees ON forests.id = trees.forest_id WHERE forests.country = 'Australia' AND trees.species = 'Eucalyptus';
How many electric vehicle charging stations are there in Germany, France, and Spain?
CREATE TABLE charging_stations (country VARCHAR(50),num_stations INT); INSERT INTO charging_stations (country,num_stations) VALUES ('Germany',25000),('France',22000),('Spain',12000);
SELECT country, num_stations FROM charging_stations WHERE country IN ('Germany', 'France', 'Spain');
Find the number of female founders in the "tech" industry
CREATE TABLE company (id INT,name VARCHAR(255),industry VARCHAR(255)); INSERT INTO company (id,name,industry) VALUES (1,'Acme Inc','tech'),(2,'Beta Corp','finance');
SELECT COUNT(*) FROM company WHERE industry = 'tech' AND gender = 'female';
What are the average kills, deaths, and assists per game for each player?
CREATE TABLE games (id INT,player_id INT,kills INT,deaths INT,assists INT); INSERT INTO games VALUES (1,1,10,5,3); INSERT INTO games VALUES (2,1,15,7,5); INSERT INTO games VALUES (3,2,5,2,1); INSERT INTO games VALUES (4,2,8,4,2);
SELECT player_id, AVG(kills) as avg_kills, AVG(deaths) as avg_deaths, AVG(assists) as avg_assists FROM games GROUP BY player_id;
What is the total number of tourists visiting national parks in Canada and the US?
CREATE TABLE national_parks (country VARCHAR(20),name VARCHAR(50),visitors INT); INSERT INTO national_parks (country,name,visitors) VALUES ('Canada','Banff',4000000),('Canada','Jasper',2500000),('US','Yosemite',3000000),('US','Yellowstone',4500000);
SELECT SUM(visitors) FROM national_parks WHERE country IN ('Canada', 'US');
Insert a new space mission record for 'Mars Sample Return Mission 1' with a launch date of '2030-10-01' into the SpaceMissions table.
CREATE TABLE SpaceMissions (MissionID INT,MissionName VARCHAR(255),LaunchDate DATE); INSERT INTO SpaceMissions (MissionID,MissionName,LaunchDate) VALUES (100,'Apollo 10','1969-05-18'),(101,'Apollo 11','1969-07-16');
INSERT INTO SpaceMissions (MissionID, MissionName, LaunchDate) VALUES (102, 'Mars Sample Return Mission 1', '2030-10-01');
Find the total number of broadband subscribers who have upgraded their plans in the last month in the 'South' and 'East' regions.
CREATE TABLE broadband_subscribers (subscriber_id INT,region VARCHAR(20),plan_start_date DATE,plan_end_date DATE); INSERT INTO broadband_subscribers (subscriber_id,region,plan_start_date,plan_end_date) VALUES (1,'South','2021-01-01','2021-01-31'),(2,'East','2021-02-01','2021-02-28');
SELECT COUNT(*) FROM broadband_subscribers WHERE region IN ('South', 'East') AND plan_end_date >= CURDATE() - INTERVAL 1 MONTH AND plan_start_date < CURDATE() - INTERVAL 1 MONTH;
List the precision farming crops that are grown in either California or Texas, but not in both.
CREATE TABLE Crops(state VARCHAR(255),name VARCHAR(255)); INSERT INTO Crops(state,name) VALUES('California','Corn'),('California','Soybean'),('California','Wheat'),('Texas','Cotton'),('Texas','Rice');
SELECT name FROM Crops WHERE state = 'California' UNION SELECT name FROM Crops WHERE state = 'Texas' EXCEPT SELECT name FROM Crops WHERE state = 'California' INTERSECT SELECT name FROM Crops WHERE state = 'Texas';
What is the name, position, and hospital_id of the staff member with name 'Dr. John Doe' in the 'healthcare_staff' table?
CREATE TABLE healthcare_staff (name VARCHAR(255),gender VARCHAR(255),position VARCHAR(255),hospital_id INT); INSERT INTO healthcare_staff (name,gender,position,hospital_id) VALUES ('Dr. John Doe','Male','Doctor',1),('Dr. Jane Smith','Female','Doctor',2),('Dr. Maria Garcia','Female','Doctor',3);
SELECT name, position, hospital_id FROM healthcare_staff WHERE name = 'Dr. John Doe';
Find the total revenue and CO2 emissions for each garment category in 2022.
CREATE TABLE sales (sale_id INT,product_category VARCHAR(255),sale_date DATE,revenue DECIMAL(10,2)); CREATE TABLE garment_manufacturing (garment_category VARCHAR(255),manufacturing_date DATE,co2_emissions INT);
SELECT sales.product_category, SUM(sales.revenue) as total_revenue, SUM(garment_manufacturing.co2_emissions) as total_co2_emissions FROM sales JOIN garment_manufacturing ON sales.product_category = garment_manufacturing.garment_category WHERE sales.sale_date BETWEEN '2022-01-01' AND '2022-12-31' GROUP BY sales.product_category;
How many startups founded by individuals from underrepresented racial or ethnic backgrounds have received Series A funding or higher in the Tech sector?
CREATE TABLE startups(id INT,name TEXT,industry TEXT,funding_round TEXT,founder TEXT); INSERT INTO startups VALUES(1,'StartupA','Tech','Seed','Asian'); INSERT INTO startups VALUES(2,'StartupB','Tech','Series A','Man'); INSERT INTO startups VALUES(3,'StartupC','Healthcare','Seed','Hispanic'); INSERT INTO startups VALUES(4,'StartupD','Finance','Series B','Woman'); INSERT INTO startups VALUES(5,'StartupE','Tech','Series A','Underrepresented Minority');
SELECT COUNT(*) FROM startups WHERE industry = 'Tech' AND founder IN ('Underrepresented Minority', 'African American', 'Hispanic', 'Native American') AND funding_round >= 'Series A';
What is the total waste generation in kg for the city of San Francisco in 2020?
CREATE TABLE waste_generation (city VARCHAR(255),year INT,waste_kg FLOAT); INSERT INTO waste_generation (city,year,waste_kg) VALUES ('San Francisco',2020,300000);
SELECT waste_kg FROM waste_generation WHERE city = 'San Francisco' AND year = 2020;
Show the average labor hours per worker for sustainable building projects, excluding workers who have not worked on any sustainable projects.
CREATE TABLE construction_workers (worker_id INT,name TEXT); CREATE TABLE project_types (project_id INT,project_type TEXT); CREATE TABLE worker_projects (worker_id INT,project_id INT,total_labor_hours INT); INSERT INTO construction_workers (worker_id,name) VALUES (1,'John Doe'),(2,'Jane Smith'),(3,'Maria Garcia'),(4,'Ahmed Patel'); INSERT INTO project_types (project_id,project_type) VALUES (1,'Residential'),(2,'Commercial'),(3,'Sustainable'); INSERT INTO worker_projects (worker_id,project_id,total_labor_hours) VALUES (1,1,500),(1,2,300),(2,2,600),(2,3,400),(3,1,700),(3,3,500),(4,NULL,NULL);
SELECT AVG(worker_projects.total_labor_hours / NULLIF(COUNT(DISTINCT worker_projects.project_id), 0)) FROM worker_projects INNER JOIN (SELECT DISTINCT worker_id FROM worker_projects INNER JOIN project_types ON worker_projects.project_id = project_types.project_id WHERE project_types.project_type = 'Sustainable') AS sustainable_workers ON worker_projects.worker_id = sustainable_workers.worker_id;
Find all countries that have launched satellites, but have not launched any missions to the International Space Station, and display them in reverse alphabetical order.
CREATE TABLE SatelliteLaunches (SatelliteName TEXT,LaunchCountry TEXT);CREATE TABLE ISSMissions (AstronautName TEXT,MissionCountry TEXT);
(SELECT LaunchCountry FROM SatelliteLaunches EXCEPT SELECT MissionCountry FROM ISSMissions) EXCEPT (SELECT NULL) ORDER BY LaunchCountry DESC;
What is the average rating for menu items in each price range?
CREATE TABLE menu(id INT,item VARCHAR(255),price DECIMAL(10,2),rating INT); INSERT INTO menu(id,item,price,rating) VALUES (1,'Salad',10.00,4),(2,'Sandwich',12.00,5),(3,'Pasta',15.00,3);
SELECT price_range, AVG(rating) as avg_rating FROM (SELECT CASE WHEN price <= 10 THEN 'Low' WHEN price <= 20 THEN 'Medium' ELSE 'High' END as price_range, rating FROM menu) subquery GROUP BY price_range;
Which sites have the most artifacts?
CREATE TABLE SiteArtifactCount (SiteID varchar(5),ArtifactCount int); INSERT INTO SiteArtifactCount (SiteID,ArtifactCount) VALUES ('S001',250),('S002',300),('S003',400);
SELECT SiteID, ArtifactCount FROM SiteArtifactCount ORDER BY ArtifactCount DESC LIMIT 1;
What is the total number of mining sites and their average elevation, partitioned by the type of mineral extracted?
CREATE TABLE Mining_Sites (Id INT,Name VARCHAR(50),Mineral VARCHAR(50),Elevation FLOAT,Type VARCHAR(50)); INSERT INTO Mining_Sites (Id,Name,Mineral,Elevation,Type) VALUES (1,'Site A','Gold',5000.00,'underground'); INSERT INTO Mining_Sites (Id,Name,Mineral,Elevation,Type) VALUES (2,'Site B','Silver',6000.00,'open-pit');
SELECT Type, COUNT(*) as Total_Sites, AVG(Elevation) as Avg_Elevation FROM Mining_Sites GROUP BY Type;
What is the average data usage by mobile customers in California, grouped by the city?
CREATE TABLE mobile_customers (customer_id INT,data_usage FLOAT,city VARCHAR(20),state VARCHAR(20)); INSERT INTO mobile_customers (customer_id,data_usage,city,state) VALUES (1,3.5,'San Francisco','California'),(2,6.2,'Los Angeles','California');
SELECT city, AVG(data_usage) FROM mobile_customers WHERE state = 'California' GROUP BY city;
How many complaints were filed with the city of Sydney, broken down by department, for the month of March 2022?
CREATE TABLE complaints (department VARCHAR(20),complaint_count INT,complaint_date DATE); INSERT INTO complaints (department,complaint_count,complaint_date) VALUES ('Public Works',300,'2022-03-01');
SELECT department, SUM(complaint_count) FROM complaints WHERE complaint_date BETWEEN '2022-03-01' AND '2022-03-31' GROUP BY department;
Find the maximum depth at which the Orca is found.
CREATE TABLE marine_species (id INT,species_name VARCHAR(50),habitat_depth FLOAT); INSERT INTO marine_species (id,species_name,habitat_depth) VALUES (1,'Orca',200.0),(2,'Blue Whale',500.0);
SELECT MAX(habitat_depth) FROM marine_species WHERE species_name = 'Orca';
List all drugs approved in 2020 with their sales in Q4 2020
CREATE TABLE drug_approval (drug_name TEXT,approval_year INTEGER);
SELECT a.drug_name, s.revenue FROM drug_approval a INNER JOIN sales s ON a.drug_name = s.drug_name WHERE a.approval_year = 2020 AND s.quarter = 'Q4';
What are the average minimum storage temperatures for chemicals produced in the APAC region?
CREATE TABLE storage_temperature (id INT PRIMARY KEY,chemical_name VARCHAR(50),region VARCHAR(50),minimum_temperature INT); INSERT INTO storage_temperature (id,chemical_name,region,minimum_temperature) VALUES (1,'Nitric Acid','APAC',-20);
SELECT region, AVG(minimum_temperature) as avg_min_temperature FROM storage_temperature WHERE region = 'APAC' GROUP BY region;
What is the average policy premium for policyholders living in 'California'?
CREATE TABLE Policyholders (PolicyholderID INT,Premium DECIMAL(10,2),PolicyholderState VARCHAR(10)); INSERT INTO Policyholders (PolicyholderID,Premium,PolicyholderState) VALUES (1,2500,'California'),(2,1500,'New York'),(3,1000,'California');
SELECT AVG(Premium) FROM Policyholders WHERE PolicyholderState = 'California';
What is the total amount of research grants awarded to graduate students in the Engineering department?
CREATE TABLE graduate_students (id INT,name VARCHAR(50),department VARCHAR(50)); CREATE TABLE grants (id INT,title VARCHAR(100),amount INT,student_id INT);
SELECT SUM(grants.amount) FROM grants INNER JOIN graduate_students ON grants.student_id = graduate_students.id WHERE graduate_students.department = 'Engineering';
Find the number of museum visitors in the last 6 months from Tokyo, Japan.
CREATE TABLE museum_visitors (id INT,visitor_name VARCHAR(255),visit_date DATE); INSERT INTO museum_visitors (id,visitor_name,visit_date) VALUES ('John Smith','2022-01-01'),('Jane Doe','2022-01-02'),('Mike Johnson','2022-07-01');
SELECT COUNT(*) FROM museum_visitors WHERE visit_date >= DATE_SUB(CURRENT_DATE, INTERVAL 6 MONTH) AND city = 'Tokyo';
What is the total number of unique IP addresses involved in incidents per month?
CREATE TABLE incident_ip_addresses (incident_id INT,ip_address VARCHAR(15)); INSERT INTO incident_ip_addresses (incident_id,ip_address) VALUES (1,'192.168.1.1'); INSERT INTO incident_ip_addresses (incident_id,ip_address) VALUES (2,'192.168.1.2'); INSERT INTO incident_ip_addresses (incident_id,ip_address) VALUES (3,'192.168.1.1'); INSERT INTO incident_ip_addresses (incident_id,ip_address) VALUES (4,'192.168.1.3');
SELECT DATEADD(month, DATEDIFF(month, 0, incident_date), 0) as month, COUNT(DISTINCT ip_address) as num_unique_ips FROM incident_ip_addresses GROUP BY month ORDER BY month;
What is the average number of lanes for highways in 'Highways' table?
CREATE TABLE Highways(state VARCHAR(255),length FLOAT,type VARCHAR(255),lanes INT); INSERT INTO Highways VALUES('California',500.0,'Rural',4),('California',700.0,'Urban',6),('Texas',400.0,'Rural',2),('Texas',800.0,'Urban',8),('NewYork',300.0,'Rural',3),('NewYork',600.0,'Urban',5);
SELECT AVG(lanes) FROM Highways;
What is the maximum CO2 emission for a fair trade certified factory in Bangladesh?
CREATE TABLE CO2Emissions (factory VARCHAR(50),certification VARCHAR(50),CO2_emission INT); INSERT INTO CO2Emissions VALUES ('Factory1','Fair Trade',500),('Factory2','Not Certified',600),('Factory3','Fair Trade',450),('Factory4','Not Certified',700);
SELECT MAX(CO2_emission) FROM CO2Emissions WHERE certification = 'Fair Trade' AND country = 'Bangladesh';
What are the distinct cargo types that have been transported to the Port of Sydney and the Port of Melbourne?
CREATE TABLE port (port_id INT,port_name VARCHAR(50)); INSERT INTO port (port_id,port_name) VALUES (1,'Port of Sydney'),(2,'Port of Melbourne'); CREATE TABLE cargo (cargo_id INT,cargo_type VARCHAR(50)); CREATE TABLE transport (transport_id INT,cargo_id INT,port_id INT); INSERT INTO transport (transport_id,cargo_id,port_id) VALUES (1,1,1),(2,2,1),(3,1,2),(4,3,2);
SELECT cargo_type FROM cargo, transport WHERE cargo.cargo_id = transport.cargo_id AND port_id IN (1, 2) GROUP BY cargo_type;
What is the total quantity of chemicals produced in January 2021?
CREATE TABLE production_rates (rate_id INT,chemical VARCHAR(20),production_rate INT,measurement_date DATE); INSERT INTO production_rates (rate_id,chemical,production_rate,measurement_date) VALUES (1,'P',500,'2021-01-01'),(2,'P',700,'2021-01-02'),(3,'Q',600,'2021-01-01'),(4,'P',800,'2021-02-01');
SELECT SUM(production_rate) FROM production_rates WHERE measurement_date BETWEEN '2021-01-01' AND '2021-01-31';
What is the percentage of employees who have completed unconscious bias training?
CREATE TABLE Training (EmployeeID INT,TrainingName VARCHAR(30),CompletionDate DATE); INSERT INTO Training (EmployeeID,TrainingName,CompletionDate) VALUES (2,'Unconscious Bias','2021-11-05');
SELECT (COUNT(*) / (SELECT COUNT(*) FROM Employees)) * 100 AS Percentage FROM Training WHERE TrainingName = 'Unconscious Bias';
What is the total number of registered voters in 'voter_registration' table, grouped by county?
CREATE TABLE voter_registration (voter_id INT,voter_name VARCHAR(255),registration_date DATE,county VARCHAR(255));
SELECT county, COUNT(voter_id) AS total_registered_voters FROM voter_registration GROUP BY county;
List the number of times each agricultural machine was used in the past week.
CREATE TABLE machine_usage (machine TEXT,usage INTEGER,start_time TIMESTAMP,end_time TIMESTAMP);
SELECT machine, COUNT(*) as usage_count FROM machine_usage WHERE start_time BETWEEN DATEADD(day, -7, CURRENT_TIMESTAMP) AND CURRENT_TIMESTAMP GROUP BY machine;
Number of safety tests per vehicle model
CREATE TABLE ModelTests (Id INT PRIMARY KEY,Model VARCHAR(50),TestId INT,FOREIGN KEY (TestId) REFERENCES SafetyTests(Id));
SELECT Model, COUNT(*) FROM ModelTests JOIN SafetyTests ON ModelTests.TestId = SafetyTests.Id GROUP BY Model;
List all the articles published by 'National Public Radio' in the 'Politics' category.
CREATE TABLE npr (article_id INT,title TEXT,category TEXT,publisher TEXT); INSERT INTO npr (article_id,title,category,publisher) VALUES (1,'Article 1','Politics','National Public Radio'),(2,'Article 2','Business','National Public Radio');
SELECT * FROM npr WHERE category = 'Politics';
Which hour of the day has the highest usage of autonomous taxis in New York?
CREATE TABLE taxi_usage (id INT,hour INT,usage INT,date DATE); INSERT INTO taxi_usage (id,hour,usage,date) VALUES (1,10,1500,'2022-01-01'),(2,12,2000,'2022-01-01');
SELECT hour, MAX(usage) AS max_usage FROM taxi_usage WHERE city = 'New York' AND trip_type = 'autonomous' GROUP BY hour;
How many food safety violations were there in each restaurant in February 2022?
CREATE TABLE restaurants (id INT,name TEXT,location TEXT); INSERT INTO restaurants (id,name,location) VALUES (1,'Restaurant A','City A'),(2,'Restaurant B','City B'); CREATE TABLE inspections (restaurant_id INT,date DATE,violations INT); INSERT INTO inspections (restaurant_id,date,violations) VALUES (1,'2022-02-01',2),(1,'2022-02-15',1),(2,'2022-02-03',3),(2,'2022-02-20',0);
SELECT r.id, SUM(i.violations) as total_violations FROM inspections i JOIN restaurants r ON i.restaurant_id = r.id WHERE i.date BETWEEN '2022-02-01' AND '2022-02-28' GROUP BY r.id;
List all safety inspection records for 'VesselK' in Q1 2022.
CREATE TABLE Vessels (vessel_name VARCHAR(255)); INSERT INTO Vessels (vessel_name) VALUES ('VesselK'),('VesselL'); CREATE TABLE Inspections (vessel_name VARCHAR(255),inspection_date DATE); INSERT INTO Inspections (vessel_name,inspection_date) VALUES ('VesselK','2022-01-03'),('VesselK','2022-03-19'),('VesselL','2022-02-05');
SELECT * FROM Inspections WHERE vessel_name = 'VesselK' AND inspection_date BETWEEN '2022-01-01' AND '2022-03-31';
What is the total number of workplaces with successful collective bargaining agreements in Canada, grouped by province?
CREATE TABLE workplaces (id INT,name TEXT,country TEXT,type TEXT,total_employees INT); INSERT INTO workplaces (id,name,country,type,total_employees) VALUES (1,'ABC Company','Canada','Manufacturing',500); INSERT INTO workplaces (id,name,country,type,total_employees) VALUES (2,'XYZ Corporation','Canada','Service',300);
SELECT country, type, COUNT(*) as total_workplaces FROM workplaces WHERE country = 'Canada' AND type = 'Manufacturing' AND total_employees > 0 GROUP BY country, type;
Find the names of all the indigenous communities in the 'Arctic_Communities' table that have a population size greater than any community in the 'Antarctic_Communities' table.
CREATE TABLE Arctic_Communities (name TEXT,population INTEGER); CREATE TABLE Antarctic_Communities (name TEXT,population INTEGER);
SELECT name FROM Arctic_Communities WHERE Arctic_Communities.population > (SELECT MAX(population) FROM Antarctic_Communities)
What are the transactions done on credit cards?
CREATE TABLE transactions (id INT,transaction_number VARCHAR(20),account_number VARCHAR(20),transaction_type VARCHAR(20),transaction_date DATE,amount DECIMAL(10,2)); CREATE TABLE accounts (id INT,account_number VARCHAR(20),customer_id INT,account_type VARCHAR(20),balance DECIMAL(10,2)); INSERT INTO transactions (id,transaction_number,account_number,transaction_type,transaction_date,amount) VALUES (1,'ABC123','1234567890','Deposit','2022-01-01',2000.00); INSERT INTO transactions (id,transaction_number,account_number,transaction_type,transaction_date,amount) VALUES (2,'DEF456','0987654321','Withdrawal','2022-01-02',500.00); INSERT INTO accounts (id,account_number,customer_id,account_type,balance) VALUES (1,'1234567890',1,'Checking',5000.00); INSERT INTO accounts (id,account_number,customer_id,account_type,balance) VALUES (2,'0987654321',2,'Credit Card',10000.00);
SELECT * FROM transactions WHERE account_number IN (SELECT account_number FROM accounts WHERE account_type = 'Credit Card');
What is the total number of historical events with attendance over 500?
CREATE TABLE events (id INT,name VARCHAR(255),date DATE,category VARCHAR(255),price DECIMAL(5,2),attendance INT); INSERT INTO events (id,name,date,category,price,attendance) VALUES (1,'Exhibition','2022-06-01','museums',75.00,1000),(2,'Tour','2022-06-02','historical',40.00,600),(3,'Workshop','2022-06-03','museums',30.00,750),(4,'Reenactment','2022-06-04','historical',50.00,800);
SELECT COUNT(*) FROM events WHERE category = 'historical' AND attendance > 500;
Which community development initiatives have the lowest budget allocations in the 'community_development_2' table?
CREATE TABLE community_development_2 (id INT,initiative_name VARCHAR(50),budget DECIMAL(10,2)); INSERT INTO community_development_2 (id,initiative_name,budget) VALUES (1,'Clean Water Initiative',50000.00),(2,'Renewable Energy',75000.00),(3,'Waste Management',45000.00);
SELECT initiative_name FROM community_development_2 ORDER BY budget ASC LIMIT 1;
Insert records for the environmental impact of 'Ethyl Acetate' and 'Methyl Ethyl Ketone' in the environmental_impact_table
CREATE TABLE environmental_impact_table (record_id INT,chemical_id INT,environmental_impact_float);
INSERT INTO environmental_impact_table (chemical_id, environmental_impact_float) VALUES (1, 2.5), (2, 3.2);
What is the maximum production value (in USD) of organic farms in the 'agroecology' schema?
CREATE SCHEMA agroecology;CREATE TABLE organic_farms (id INT,name VARCHAR(50),production_value INT);
SELECT MAX(production_value) FROM agroecology.organic_farms;
What is the total number of registered users from each country, ordered by the number of users in descending order?
CREATE TABLE users (id INT,name VARCHAR(50),country VARCHAR(50)); INSERT INTO users (id,name,country) VALUES (1,'John Doe','USA'),(2,'Jane Smith','Canada'),(3,'Pedro Martinez','Mexico'),(4,'Sophia Garcia','Spain'),(5,'Michael Lee','USA'),(6,'Emily White','Canada'),(7,'Daniel Kim','South Korea'),(8,'Fatima Alvarez','Mexico'),(9,'Lucas Silva','Brazil');
SELECT country, COUNT(*) OVER (PARTITION BY country) as total_users FROM users ORDER BY total_users DESC;
Which regions received the most support in the form of medical supplies and how much support did they receive?
CREATE TABLE MedicalSupport (Id INT,Region VARCHAR(50),Item VARCHAR(50),Quantity INT); INSERT INTO MedicalSupport (Id,Region,Item,Quantity) VALUES (1,'Middle East','Medical Supplies',500),(2,'Asia','Medical Supplies',800),(3,'Africa','Medical Supplies',1000),(4,'South America','Medical Supplies',600);
SELECT Region, SUM(Quantity) FROM MedicalSupport WHERE Item = 'Medical Supplies' GROUP BY Region ORDER BY SUM(Quantity) DESC;
What is the total weight of artifacts from the 'Stone Age' context?
CREATE TABLE excavation_sites (site_id INT,site_name VARCHAR(255),site_period VARCHAR(255)); INSERT INTO excavation_sites (site_id,site_name,site_period) VALUES (1,'Site A','Stone Age'),(2,'Site B','Iron Age'),(3,'Site C','Bronze Age'); CREATE TABLE artifacts (artifact_id INT,site_id INT,artifact_weight DECIMAL(5,2),artifact_type VARCHAR(255)); INSERT INTO artifacts (artifact_id,site_id,artifact_weight,artifact_type) VALUES (1,1,23.5,'Pottery'),(2,1,15.3,'Bone'),(3,2,8.9,'Metal'),(4,2,34.7,'Stone'),(5,3,100.2,'Jewelry'),(6,3,12.8,'Ceramic');
SELECT SUM(a.artifact_weight) AS total_weight FROM excavation_sites s JOIN artifacts a ON s.site_id = a.site_id WHERE s.site_period = 'Stone Age';
What is the name of the creator with the most transactions on the Binance network?
CREATE TABLE creators (id INT,name TEXT,country TEXT); INSERT INTO creators (id,name,country) VALUES (1,'Alice','USA'),(2,'Bob','Canada'),(3,'Charlie','China'); CREATE TABLE transactions (id INT,creator_id INT,network TEXT); INSERT INTO transactions (id,creator_id,network) VALUES (1,1,'Ethereum'),(2,1,'Binance'),(3,2,'Ethereum'),(4,3,'Binance'),(5,3,'Binance');
SELECT c.name FROM creators c INNER JOIN transactions t ON c.id = t.creator_id WHERE t.network = 'Binance' GROUP BY c.name ORDER BY COUNT(*) DESC LIMIT 1;
What is the number of autonomous driving research projects completed before '2020' in the 'research' table?
CREATE TABLE research (year INT,type VARCHAR(15)); INSERT INTO research VALUES (2018,'autonomous driving'),(2019,'autonomous driving'),(2020,'autonomous driving'),(2020,'electric vehicle'),(2021,'autonomous driving');
SELECT COUNT(*) FROM research WHERE type = 'autonomous driving' AND year < 2020;
What is the total number of visitors for 'Impressionist Art' and 'Contemporary Art' exhibitions?
CREATE TABLE Exhibitions (exhibition_id INT,name VARCHAR(100),visitor_count INT); INSERT INTO Exhibitions (exhibition_id,name,visitor_count) VALUES (1,'Impressionist Art',800),(2,'Contemporary Art',600);
SELECT SUM(visitor_count) FROM Exhibitions WHERE name IN ('Impressionist Art', 'Contemporary Art');
Identify the top contributing countries in terms of visitor count.
CREATE TABLE Countries (Country_ID INT,Country_Name VARCHAR(255)); INSERT INTO Countries (Country_ID,Country_Name) VALUES (1,'United States'),(2,'Mexico'),(3,'Canada'),(4,'Brazil'),(5,'Argentina'); CREATE TABLE Visitor_Origins (Visitor_ID INT,Country_ID INT);
SELECT c.Country_Name, COUNT(v.Visitor_ID) AS Visitor_Count FROM Countries c JOIN Visitor_Origins v ON c.Country_ID = v.Country_ID GROUP BY c.Country_Name ORDER BY Visitor_Count DESC LIMIT 5;
What is the founding year and location of the most recently founded company?
CREATE TABLE Founding_Data (company_name VARCHAR(50),founding_year INT,founding_location VARCHAR(50)); INSERT INTO Founding_Data (company_name,founding_year,founding_location) VALUES ('Waystar Royco',1980,'New York'); INSERT INTO Founding_Data (company_name,founding_year,founding_location) VALUES ('Pied Piper',2012,'California'); INSERT INTO Founding_Data (company_name,founding_year,founding_location) VALUES ('Austin Biotech',2005,'Texas'); INSERT INTO Founding_Data (company_name,founding_year,founding_location) VALUES ('Everest Technologies',2022,'Nepal');
SELECT company_name, founding_year, founding_location FROM Founding_Data WHERE founding_year = (SELECT MAX(founding_year) FROM Founding_Data);
What is the total number of patients who have completed therapy sessions in the African region?
CREATE TABLE patients (id INT,region VARCHAR(50),therapy_sessions INT); INSERT INTO patients (id,region,therapy_sessions) VALUES (1,'Africa',5),(2,'Africa',3),(3,'Asia',NULL);
SELECT SUM(therapy_sessions) FROM patients WHERE region = 'Africa' AND therapy_sessions IS NOT NULL;
What is the monthly trend of news article word counts for the "politics" section in 2022?
CREATE TABLE news_articles (id INT,title TEXT,publish_date DATE,word_count INT); CREATE VIEW news_summary AS SELECT id,title,publish_date,EXTRACT(MONTH FROM publish_date) as month,EXTRACT(YEAR FROM publish_date) as year,word_count FROM news_articles WHERE section = 'politics';
SELECT month, AVG(word_count) as avg_word_count FROM news_summary WHERE year = 2022 GROUP BY month;