instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
List all unique attorney last names who have billed for cases in the 'Bankruptcy' case type, sorted alphabetically.
CREATE TABLE BankruptcyCases (CaseID INT,CaseType VARCHAR(20),AttorneyLastName VARCHAR(20),BillingAmount DECIMAL(10,2)); INSERT INTO BankruptcyCases (CaseID,CaseType,AttorneyLastName,BillingAmount) VALUES (1,'Bankruptcy','Davis',8000.00),(2,'Bankruptcy','Miller',4000.00);
SELECT DISTINCT AttorneyLastName FROM BankruptcyCases WHERE CaseType = 'Bankruptcy' ORDER BY AttorneyLastName;
What is the total number of wheelchair accessible and non-accessible vehicles in the fleet?
CREATE TABLE vehicles (vehicle_id INT,wheelchair_accessible BOOLEAN); INSERT INTO vehicles VALUES (1,TRUE); INSERT INTO vehicles VALUES (2,FALSE); INSERT INTO vehicles VALUES (3,TRUE); INSERT INTO vehicles VALUES (4,FALSE); INSERT INTO vehicles VALUES (5,TRUE);
SELECT SUM(IF(vehicles.wheelchair_accessible = TRUE, 1, 0)) as wheelchair_accessible_vehicles, SUM(IF(vehicles.wheelchair_accessible = FALSE, 1, 0)) as non_wheelchair_accessible_vehicles FROM vehicles;
Who are the top 3 clients with the highest total investments in Malaysia?
CREATE TABLE investments (id INT,client_name VARCHAR(50),country VARCHAR(50),type VARCHAR(50),value DECIMAL(10,2),date DATE); INSERT INTO investments (id,client_name,country,type,value,date) VALUES (1,'Ahmad','Malaysia','stocks',12000,'2022-01-01'); INSERT INTO investments (id,client_name,country,type,value,date) VALUES (2,'Nadia','Malaysia','bonds',15000,'2022-01-02'); INSERT INTO investments (id,client_name,country,type,value,date) VALUES (3,'Haris','Malaysia','real_estate',18000,'2022-01-03');
SELECT client_name, SUM(value) as total_investments, ROW_NUMBER() OVER (ORDER BY SUM(value) DESC) as rank FROM investments WHERE country = 'Malaysia' GROUP BY client_name HAVING rank <= 3;
What is the minimum and maximum budget for traditional arts initiatives in the 'Americas'?
CREATE TABLE traditional_arts_initiatives (id INT,initiative VARCHAR(50),budget INT,location VARCHAR(50)); INSERT INTO traditional_arts_initiatives (id,initiative,budget,location) VALUES (1,'Mexican Folk Art Revival',5000,'Americas'),(2,'Brazilian Capoeira Restoration',7000,'Americas');
SELECT MIN(budget), MAX(budget) FROM traditional_arts_initiatives WHERE location = 'Americas';
Find the number of unique customers who benefited from socially responsible lending?
CREATE TABLE customers (id INT,loan_id INT,name TEXT,city TEXT); INSERT INTO customers (id,loan_id,name,city) VALUES (1,1,'Fatima','New York'),(2,1,'Ali','New York'),(3,2,'Aisha','Los Angeles'),(4,3,'Zayd','Chicago');
SELECT COUNT(DISTINCT customers.id) FROM customers JOIN loans ON customers.loan_id = loans.id WHERE loans.is_shariah_compliant = FALSE AND loans.type = 'Socially responsible';
Delete policy records with a policy type of 'Commercial Auto' and effective date before '2019-01-01'
CREATE TABLE policy (policy_id INT,policy_type VARCHAR(20),effective_date DATE); INSERT INTO policy VALUES (1,'Commercial Auto','2018-01-01'); INSERT INTO policy VALUES (2,'Personal Auto','2020-01-01');
DELETE FROM policy WHERE policy_type = 'Commercial Auto' AND effective_date < '2019-01-01';
Find the temperature difference between the highest and lowest temperature records for each farm.
CREATE TABLE Satellite_Imagery (id INT,farm_id INT,date DATE,moisture INT,temperature INT); INSERT INTO Satellite_Imagery (id,farm_id,date,moisture,temperature) VALUES (1,1,'2022-05-01',60,75); INSERT INTO Satellite_Imagery (id,farm_id,date,moisture,temperature) VALUES (2,1,'2022-05-05',70,80); INSERT INTO Satellite_Imagery (id,farm_id,date,moisture,temperature) VALUES (3,2,'2022-05-03',75,70);
SELECT farm_id, MAX(temperature) - MIN(temperature) FROM Satellite_Imagery GROUP BY farm_id;
What is the total climate finance for women-led projects in Africa in the energy sector?
CREATE TABLE climate_finance_for_women (fund_id INT,project_name VARCHAR(100),country VARCHAR(50),sector VARCHAR(50),amount FLOAT,gender_flag BOOLEAN); INSERT INTO climate_finance_for_women (fund_id,project_name,country,sector,amount,gender_flag) VALUES (1,'Solar Power for Women','Kenya','Energy',3000000,TRUE);
SELECT SUM(amount) FROM climate_finance_for_women WHERE country = 'Africa' AND sector = 'Energy' AND gender_flag = TRUE;
Calculate the percentage of security incidents caused by insider threats in the government sector in the second half of 2021.
CREATE TABLE incidents (id INT,cause VARCHAR(255),sector VARCHAR(255),date DATE); INSERT INTO incidents (id,cause,sector,date) VALUES (1,'insider threat','financial','2021-01-01'); INSERT INTO incidents (id,cause,sector,date) VALUES (2,'phishing','government','2021-02-01');
SELECT 100.0 * SUM(CASE WHEN cause = 'insider threat' AND sector = 'government' THEN 1 ELSE 0 END) / COUNT(*) as percentage FROM incidents WHERE date >= '2021-07-01' AND date < '2022-01-01';
What was the average number of attendees for events in the 'Exhibitions' category?
CREATE TABLE event_attendance (id INT,event_id INT,attendee_count INT); INSERT INTO event_attendance (id,event_id,attendee_count) VALUES (1,1,250),(2,2,320),(3,3,175); CREATE TABLE events (id INT,category VARCHAR(10)); INSERT INTO events (id,category) VALUES (1,'Dance'),(2,'Music'),(3,'Theater'),(4,'Exhibitions');
SELECT AVG(attendee_count) FROM event_attendance JOIN events ON event_attendance.event_id = events.id WHERE events.category = 'Exhibitions';
What is the minimum energy storage capacity (in MWh) of battery storage systems in California, grouped by system type?
CREATE TABLE battery_storage (id INT,system_type TEXT,state TEXT,capacity_mwh FLOAT); INSERT INTO battery_storage (id,system_type,state,capacity_mwh) VALUES (1,'Lithium-ion','California',50.0),(2,'Flow','California',75.0),(3,'Sodium-ion','California',40.0);
SELECT system_type, MIN(capacity_mwh) FROM battery_storage WHERE state = 'California' GROUP BY system_type;
Find the average funding received by startups in each country in the 'StartupFunding' table?
CREATE SCHEMA BiotechStartups; CREATE TABLE StartupFunding (startup_name VARCHAR(50),country VARCHAR(50),funding DECIMAL(10,2)); INSERT INTO StartupFunding VALUES ('StartupA','USA',500000),('StartupB','Canada',750000);
SELECT country, AVG(funding) as avg_funding FROM BiotechStartups.StartupFunding GROUP BY country;
Calculate the percentage of organic farms out of all farms for each country.
CREATE TABLE Farm (FarmID int,FarmType varchar(20),Country varchar(50)); INSERT INTO Farm (FarmID,FarmType,Country) VALUES (1,'Organic','USA'),(2,'Conventional','Canada'),(3,'Urban','Mexico'),(4,'Organic','USA'),(5,'Organic','Mexico');
SELECT Country, 100.0 * COUNT(*) FILTER (WHERE FarmType = 'Organic') / COUNT(*) as PctOrganic FROM Farm GROUP BY Country;
What is the total quantity of 'Veggie Delight' sandwiches sold in January 2022?
CREATE TABLE menu (item_name TEXT,quantity_sold INTEGER,sale_date DATE); INSERT INTO menu (item_name,quantity_sold,sale_date) VALUES ('Veggie Delight',15,'2022-01-01'); INSERT INTO menu (item_name,quantity_sold,sale_date) VALUES ('Veggie Delight',12,'2022-01-02');
SELECT SUM(quantity_sold) FROM menu WHERE item_name = 'Veggie Delight' AND sale_date BETWEEN '2022-01-01' AND '2022-01-31';
What is the average salary of female employees?
CREATE TABLE employees (id INT,name VARCHAR(50),dept_id INT,salary DECIMAL(10,2),gender VARCHAR(50));
SELECT AVG(salary) FROM employees WHERE gender = 'Female';
Which country has the highest soybean yield in 2021?
CREATE TABLE Yield (id INT PRIMARY KEY,crop VARCHAR(50),country VARCHAR(50),year INT,yield INT); INSERT INTO Yield (id,crop,country,year,yield) VALUES (1,'Soybeans','Brazil',2021,3500); INSERT INTO Yield (id,crop,country,year,yield) VALUES (2,'Soybeans','USA',2021,3300); INSERT INTO Yield (id,crop,country,year,yield) VALUES (3,'Corn','China',2021,6000);
SELECT country, MAX(yield) FROM Yield WHERE crop = 'Soybeans' AND year = 2021 GROUP BY country;
Which analysts have excavated artifacts in the 'Ancient Civilizations' category?
CREATE TABLE analysts (analyst_id INT,name VARCHAR(50),start_date DATE); INSERT INTO analysts (analyst_id,name,start_date) VALUES (1,'John Doe','2020-01-01'); CREATE TABLE artifacts (artifact_id INT,analyst_id INT,category VARCHAR(50));
SELECT a.name FROM analysts a JOIN artifacts art ON a.analyst_id = art.analyst_id WHERE art.category = 'Ancient Civilizations' GROUP BY a.analyst_id, a.name HAVING COUNT(art.artifact_id) > 0;
What is the average price of Fair Trade certified products in the 'organic_products' table?
CREATE TABLE organic_products (product_id INT,product_name VARCHAR(50),price DECIMAL(5,2),certification VARCHAR(20)); INSERT INTO organic_products (product_id,product_name,price,certification) VALUES (1,'Bananas',1.50,'Fair Trade'),(2,'Quinoa',7.99,'USDA Organic'),(3,'Coffee',9.99,'Fair Trade');
SELECT AVG(price) FROM organic_products WHERE certification = 'Fair Trade';
How many violations did each facility have on average during their inspections?
CREATE TABLE FoodInspections (id INT PRIMARY KEY,facility_name VARCHAR(255),inspection_date DATE,violation_count INT); INSERT INTO FoodInspections (id,facility_name,inspection_date,violation_count) VALUES (1,'Tasty Burgers','2021-03-15',3),(2,'Fresh Greens','2021-03-17',0),(3,'Pizza Palace','2021-03-18',2);
SELECT facility_name, AVG(violation_count) FROM FoodInspections GROUP BY facility_name;
What is the percentage of successful appeals for juvenile cases?
CREATE TABLE appeals (appeal_id INT,case_id INT,case_type VARCHAR(50),appeal_outcome VARCHAR(50)); INSERT INTO appeals (appeal_id,case_id,case_type,appeal_outcome) VALUES (1,1,'juvenile','successful'),(2,2,'criminal','unsuccessful'),(3,3,'juvenile','successful');
SELECT (COUNT(*) * 100.0 / (SELECT COUNT(*) FROM appeals WHERE case_type = 'juvenile')) AS percentage_successful FROM appeals WHERE appeal_outcome = 'successful' AND case_type = 'juvenile';
How many returns were made from California to the Los Angeles warehouse in Q2 2021?
CREATE TABLE Warehouse (id INT,name VARCHAR(255)); INSERT INTO Warehouse (id,name) VALUES (1,'New York'),(2,'Los Angeles'); CREATE TABLE Shipments (id INT,type VARCHAR(10),warehouse_id INT,shipment_date DATE); INSERT INTO Shipments (id,type,warehouse_id,shipment_date) VALUES (1,'Delivery',1,'2021-01-01'),(2,'Return',2,'2021-03-15'),(3,'Delivery',2,'2021-05-01');
SELECT COUNT(*) FROM Shipments WHERE type = 'Return' AND warehouse_id = (SELECT id FROM Warehouse WHERE name = 'Los Angeles') AND shipment_date BETWEEN '2021-04-01' AND '2021-06-30';
Find the total number of volunteers for each organization.
CREATE TABLE organization (id INT,name VARCHAR(255)); INSERT INTO organization (id,name) VALUES (1,'Habitat for Humanity'),(2,'American Red Cross'); CREATE TABLE volunteer (id INT,name VARCHAR(255),organization_id INT); INSERT INTO volunteer (id,name,organization_id) VALUES (1,'John Doe',1),(2,'Jane Smith',1),(3,'Bob Johnson',2);
SELECT organization_id, COUNT(*) as total_volunteers FROM volunteer GROUP BY organization_id;
What is the average CO2 emission for products sold in Canada?
CREATE TABLE vendors (vendor_id INT,vendor_name TEXT,country TEXT);CREATE TABLE products (product_id INT,product_name TEXT,price DECIMAL,CO2_emission INT,vendor_id INT); INSERT INTO vendors (vendor_id,vendor_name,country) VALUES (1,'VendorA','Canada'),(2,'VendorB','USA'); INSERT INTO products (product_id,product_name,price,CO2_emission,vendor_id) VALUES (1,'ProductX',15.99,500,1),(2,'ProductY',12.49,300,1),(3,'ProductZ',9.99,800,2);
SELECT AVG(CO2_emission) FROM products JOIN vendors ON products.vendor_id = vendors.vendor_id WHERE country = 'Canada';
Update the address of policyholder with policy_holder_id 222 in the 'policy_holder' table to '456 Elm St, Los Angeles, CA 90001'.
CREATE TABLE policy_holder (policy_holder_id INT,first_name VARCHAR(20),last_name VARCHAR(20),address VARCHAR(50));
UPDATE policy_holder SET address = '456 Elm St, Los Angeles, CA 90001' WHERE policy_holder_id = 222;
What is the maximum CO2 emission for buildings in each city in the 'smart_cities' schema?
CREATE TABLE smart_cities.buildings (id INT,city VARCHAR(255),co2_emissions INT); CREATE VIEW smart_cities.buildings_view AS SELECT id,city,co2_emissions FROM smart_cities.buildings;
SELECT city, MAX(co2_emissions) FROM smart_cities.buildings_view GROUP BY city;
Which strains were sold in Oregon in Q3 2021 and Q4 2021?
CREATE TABLE Inventory (id INT,strain TEXT,state TEXT); INSERT INTO Inventory (id,strain,state) VALUES (1,'Strain A','Oregon'),(2,'Strain B','Oregon'),(3,'Strain C','Oregon'); CREATE TABLE Sales (id INT,inventory_id INT,sold_date DATE); INSERT INTO Sales (id,inventory_id,sold_date) VALUES (1,1,'2021-07-01'),(2,1,'2021-08-01'),(3,2,'2021-10-01'),(4,3,'2021-11-01');
SELECT i.strain FROM Inventory i INNER JOIN Sales s ON i.id = s.inventory_id WHERE s.sold_date BETWEEN '2021-07-01' AND '2021-12-31' AND i.state = 'Oregon' GROUP BY i.strain;
What is the minimum number of employees in organizations that have implemented technology for social good initiatives in South America?
CREATE TABLE social_good_orgs (org_id INT,employees INT,region VARCHAR(20)); INSERT INTO social_good_orgs (org_id,employees,region) VALUES (1,100,'South America'),(2,200,'Africa'),(3,150,'South America'),(4,250,'Europe');
SELECT MIN(employees) FROM social_good_orgs WHERE region = 'South America';
What is the average price of organic skincare products in the 'organic_skincare' table?
CREATE TABLE organic_skincare (product_id INT,product_name VARCHAR(50),price DECIMAL(5,2),is_organic BOOLEAN);
SELECT AVG(price) FROM organic_skincare WHERE is_organic = TRUE;
Calculate the total amount of aluminum mined globally in 2021
CREATE TABLE mining_operations (id INT,mine_name TEXT,location TEXT,material TEXT,quantity INT,date DATE); INSERT INTO mining_operations (id,mine_name,location,material,quantity,date) VALUES (9,'Aluminum Atlas','Canada','aluminum',4000,'2021-01-01');
SELECT SUM(quantity) FROM mining_operations WHERE material = 'aluminum' AND date = '2021-01-01';
What is the minimum Europium production in 2022 from mines in Asia?
CREATE TABLE mines (id INT,name TEXT,location TEXT,europium_production FLOAT,timestamp DATE); INSERT INTO mines (id,name,location,europium_production,timestamp) VALUES (1,'Mine A','China',120.5,'2022-01-01'),(2,'Mine B','Japan',150.7,'2022-02-01'),(3,'Mine C','USA',200.3,'2022-03-01');
SELECT MIN(europium_production) FROM mines WHERE location = 'Asia' AND YEAR(mines.timestamp) = 2022;
What is the maximum investment per project in the 'rural_infrastructure_projects' table?
CREATE TABLE rural_infrastructure_projects (id INT,project VARCHAR(50),investment FLOAT); INSERT INTO rural_infrastructure_projects (id,project,investment) VALUES (1,'Rural Road Construction',50000.0); INSERT INTO rural_infrastructure_projects (id,project,investment) VALUES (2,'Rural Water Supply',60000.0); INSERT INTO rural_infrastructure_projects (id,project,investment) VALUES (3,'Rural Electricity Grid',75000.0);
SELECT MAX(investment) FROM rural_infrastructure_projects;
How many users have a membership longer than 1 year, grouped by their preferred workout time?
CREATE TABLE memberships (id INT,user_id INT,start_date DATE,end_date DATE); INSERT INTO memberships (id,user_id,start_date,end_date) VALUES (1,1,'2021-01-01','2022-01-01'),(2,2,'2020-01-01','2021-01-01'),(3,3,'2019-01-01','2020-01-01'); CREATE TABLE user_preferences (id INT,user_id INT,preferred_workout_time TIME); INSERT INTO user_preferences (id,user_id,preferred_workout_time) VALUES (1,1,'07:00:00'),(2,2,'17:00:00'),(3,3,'12:00:00');
SELECT COUNT(*), preferred_workout_time FROM memberships m JOIN user_preferences p ON m.user_id = p.user_id WHERE DATEDIFF(m.end_date, m.start_date) > 365 GROUP BY preferred_workout_time;
Identify the number of unique esports events and their types in the last 6 months.
CREATE TABLE EsportsEvents (EventID INT,EventName TEXT,EventType TEXT,EventDate DATE); INSERT INTO EsportsEvents (EventID,EventName,EventType,EventDate) VALUES (1,'ELC','League','2022-01-01'),(2,'DAC','Championship','2022-02-15'),(3,'GCS','Cup','2021-12-10'),(4,'WCS','Series','2022-04-20'),(5,'EPL','League','2022-05-05'),(6,'IEM','Cup','2022-06-12');
SELECT COUNT(DISTINCT EventID), EventType FROM EsportsEvents WHERE EventDate >= DATEADD(month, -6, GETDATE()) GROUP BY EventType;
List all programs with their respective outcomes and total expenses in the Asia-Pacific region.
CREATE TABLE Programs (ProgramID INT,ProgramName TEXT,Location TEXT); INSERT INTO Programs (ProgramID,ProgramName,Location) VALUES (1,'Health Education','Asia-Pacific'),(2,'Clean Water Initiative','Africa'); CREATE TABLE ProgramOutcomes (OutcomeID INT,ProgramID INT,Outcome TEXT,Expenses DECIMAL(10,2)); INSERT INTO ProgramOutcomes (OutcomeID,ProgramID,Outcome,Expenses) VALUES (1,1,'Trained 500 teachers',25000.00),(2,1,'Improved 10 schools',30000.00),(3,2,'Provided clean water to 3 villages',45000.00);
SELECT programs.ProgramName, outcomes.Outcome, SUM(outcomes.Expenses) AS TotalExpenses FROM Programs programs INNER JOIN ProgramOutcomes outcomes ON programs.ProgramID = outcomes.ProgramID WHERE programs.Location = 'Asia-Pacific' GROUP BY programs.ProgramName, outcomes.Outcome;
What is the total amount of defense spending by country and year?
CREATE TABLE defense_spending (id INT PRIMARY KEY,amount FLOAT,year INT,country VARCHAR(255));
SELECT country, year, SUM(amount) as total_spending FROM defense_spending GROUP BY country, year;
What was the average donation amount by organizations in Nigeria in Q2 2021?
CREATE TABLE Donations (id INT,donor_name VARCHAR(255),donation_amount DECIMAL(10,2),donation_date DATE); INSERT INTO Donations (id,donor_name,donation_amount,donation_date) VALUES (1,'ABC Corporation Nigeria',500.00,'2021-04-12'),(2,'XYZ Foundation Nigeria',700.00,'2021-06-02');
SELECT AVG(donation_amount) FROM Donations WHERE donor_name LIKE '%Nigeria%' AND donation_date BETWEEN '2021-04-01' AND '2021-06-30' AND donor_name NOT LIKE '%individual%';
Show the number of security incidents and their category by year
CREATE TABLE incident_yearly (id INT,incident_date DATE,category VARCHAR(10)); INSERT INTO incident_yearly (id,incident_date,category) VALUES (1,'2021-01-01','Malware'),(2,'2021-01-15','Phishing'),(3,'2022-01-01','Insider Threat'),(4,'2022-01-01','DDoS'),(5,'2022-02-01','Phishing'),(6,'2023-03-01','Insider Threat');
SELECT EXTRACT(YEAR FROM incident_date) as year, category, COUNT(*) as incidents FROM incident_yearly GROUP BY year, category;
What is the total number of properties in the city of Portland?
CREATE TABLE properties (id INT,property_id INT,city TEXT,size INT); INSERT INTO properties (id,property_id,city,size) VALUES (1,101,'Austin',1200),(2,102,'Seattle',900),(3,103,'Austin',1500),(4,106,'Portland',1400),(5,107,'Portland',1600);
SELECT COUNT(*) FROM properties WHERE city = 'Portland';
Which companies had workplace safety incidents in the past year?
CREATE TABLE workplace_safety (id INT,company VARCHAR,incident_date DATE,description VARCHAR,severity VARCHAR); INSERT INTO workplace_safety (id,company,incident_date,description,severity) VALUES (9,'LMN Inc','2022-02-03','Fire','Major'); INSERT INTO workplace_safety (id,company,incident_date,description,severity) VALUES (10,'PQR Corp','2021-11-29','Chemical spill','Minor');
SELECT company, COUNT(*) OVER (PARTITION BY company) as incidents_past_year FROM workplace_safety WHERE incident_date BETWEEN DATEADD(year, -1, CURRENT_DATE) AND CURRENT_DATE;
Identify the unique services provided by schools in the last academic year, along with their respective budgets.
CREATE TABLE services (id INT,school_id INT,service VARCHAR(255),budget INT); INSERT INTO services (id,school_id,service,budget) VALUES (1,1,'Service1',10000),(2,1,'Service2',12000),(3,2,'Service1',11000); CREATE TABLE schools (id INT,name VARCHAR(255),academic_year INT); INSERT INTO schools (id,name,academic_year) VALUES (1,'School1',2021),(2,'School2',2021);
SELECT DISTINCT s.service, sc.budget FROM services s JOIN schools sc ON s.school_id = sc.id WHERE sc.academic_year = 2021
What are the top 3 countries with the highest carbon pricing levels?
CREATE TABLE carbon_pricing (country TEXT,level REAL); INSERT INTO carbon_pricing (country,level) VALUES ('Switzerland',105.86),('Sweden',123.36),('Norway',62.26),('United Kingdom',30.15),('Germany',29.81),('France',32.37),('Italy',27.04),('Spain',25.76),('Finland',24.56),('Ireland',20.00);
SELECT country, level FROM carbon_pricing ORDER BY level DESC LIMIT 3
What is the minimum water temperature required for each species in the Pacific region?
CREATE TABLE species_info (id INT,species TEXT,region TEXT,min_temp DECIMAL(5,2),max_temp DECIMAL(5,2)); INSERT INTO species_info (id,species,region,min_temp,max_temp) VALUES (1,'Salmon','Pacific',8.0,16.0),(2,'Tilapia','Atlantic',20.0,30.0),(3,'Shrimp','Pacific',18.0,28.0),(4,'Trout','Atlantic',12.0,20.0),(5,'Cod','Pacific',10.0,18.0);
SELECT species, min_temp as min_required_temp FROM species_info WHERE region = 'Pacific';
What is the total quantity of recycled materials used in production by each company?
CREATE TABLE recycled_materials(company VARCHAR(50),material VARCHAR(50),quantity INT);
SELECT company, SUM(quantity) FROM recycled_materials GROUP BY company;
What is the number of vaccinations administered in each country?
CREATE TABLE vaccinations(id INT,patient_id INT,country TEXT,date DATE);
SELECT country, COUNT(*) FROM vaccinations GROUP BY country;
How many customers have ordered more than 10 drinks from the coffee menu in the last month?
CREATE TABLE CoffeeMenu(menu_item VARCHAR(50),price DECIMAL(5,2)); CREATE TABLE Orders(order_id INT,customer_id INT,menu_item VARCHAR(50),order_date DATE); INSERT INTO CoffeeMenu VALUES('Espresso',2.99),('Latte',3.99),('Cappuccino',3.49); INSERT INTO Orders VALUES(1,1,'Espresso','2022-01-01'),(2,2,'Latte','2022-01-02'),(3,1,'Cappuccino','2022-01-03'),(4,3,'Espresso','2022-01-04'),(5,1,'Latte','2022-01-05'),(6,2,'Espresso','2022-01-06'),(7,1,'Cappuccino','2022-01-07'),(8,4,'Espresso','2022-01-08'),(9,1,'Latte','2022-01-09'),(10,2,'Cappuccino','2022-01-10');
SELECT COUNT(DISTINCT customer_id) FROM Orders JOIN CoffeeMenu ON Orders.menu_item = CoffeeMenu.menu_item WHERE order_date >= '2022-01-01' AND order_date < '2022-02-01' GROUP BY customer_id HAVING COUNT(*) > 10;
What is the minimum number of wins for players who play "Shooter Game 2022"?
CREATE TABLE Players (PlayerID INT,PlayerName VARCHAR(50),Game VARCHAR(50),Wins INT); INSERT INTO Players (PlayerID,PlayerName,Game,Wins) VALUES (1,'John Doe','Shooter Game 2022',25),(2,'Jane Smith','Shooter Game 2022',30),(3,'Alice Johnson','Shooter Game 2022',22);
SELECT MIN(Wins) FROM Players WHERE Game = 'Shooter Game 2022';
What is the minimum fare collected for accessible taxis in Tokyo in the month of April 2022?
CREATE TABLE taxi_routes (route_id INT,vehicle_type VARCHAR(10),fare DECIMAL(5,2)); CREATE TABLE taxi_fares (fare_id INT,route_id INT,fare_amount DECIMAL(5,2),fare_collection_date DATE,is_accessible BOOLEAN); INSERT INTO taxi_routes VALUES (1,'Taxi',700),(2,'Accessible Taxi',900); INSERT INTO taxi_fares VALUES (1,1,700,'2022-04-01',true),(2,1,700,'2022-04-02',false),(3,2,900,'2022-04-03',true);
SELECT MIN(f.fare_amount) FROM taxi_fares f JOIN taxi_routes br ON f.route_id = br.route_id WHERE f.is_accessible = true AND f.fare_collection_date BETWEEN '2022-04-01' AND '2022-04-30';
Create a table for teacher professional development data
CREATE TABLE teacher_professional_development (teacher_id INT,professional_development_score INT);
CREATE TABLE teacher_professional_development (teacher_id INT, professional_development_score INT);
Identify the smallest Renewable Energy Project in India by capacity
CREATE TABLE renewable_energy_projects (id INT,name VARCHAR(100),country VARCHAR(50),capacity_mw FLOAT); INSERT INTO renewable_energy_projects (id,name,country,capacity_mw) VALUES (1,'Project 1','India',30.5),(2,'Project 2','India',15.2);
SELECT name, MIN(capacity_mw) FROM renewable_energy_projects WHERE country = 'India';
How many users have booked tours in each country?
CREATE TABLE countries (id INT PRIMARY KEY,name VARCHAR(255)); CREATE TABLE bookings (id INT PRIMARY KEY,user_id INT,country_id INT,FOREIGN KEY (country_id) REFERENCES countries(id)); CREATE TABLE tours (id INT PRIMARY KEY,tour_type VARCHAR(255)); ALTER TABLE bookings ADD FOREIGN KEY (tour_type) REFERENCES tours(id);
SELECT countries.name, COUNT(bookings.id) FROM countries INNER JOIN bookings ON countries.id = bookings.country_id GROUP BY countries.name;
Who has booked the 'Rickshaw Bangkok' accommodation and what are their names?
CREATE TABLE Tourist (Tourist_ID INT PRIMARY KEY,Tourist_Name VARCHAR(100)); INSERT INTO Tourist (Tourist_ID,Tourist_Name) VALUES (1,'John Doe'); CREATE TABLE Accommodation (Accommodation_ID INT PRIMARY KEY,Accommodation_Name VARCHAR(100),Country_ID INT,FOREIGN KEY (Country_ID) REFERENCES Country(Country_ID)); INSERT INTO Accommodation (Accommodation_ID,Accommodation_Name,Country_ID) VALUES (1,'Rickshaw Bangkok',1); CREATE TABLE Booking (Booking_ID INT PRIMARY KEY,Tourist_ID INT,Accommodation_ID INT,Check_in_Date DATE,Check_out_Date DATE,FOREIGN KEY (Tourist_ID) REFERENCES Tourist(Tourist_ID),FOREIGN KEY (Accommodation_ID) REFERENCES Accommodation(Accommodation_ID)); INSERT INTO Booking (Booking_ID,Tourist_ID,Accommodation_ID,Check_in_Date,Check_out_Date) VALUES (1,1,1,'2023-01-01','2023-01-05');
SELECT Tourist_Name FROM Tourist INNER JOIN Booking ON Tourist.Tourist_ID = Booking.Tourist_ID WHERE Accommodation_ID = (SELECT Accommodation_ID FROM Accommodation WHERE Accommodation_Name = 'Rickshaw Bangkok');
What is the adoption rate of virtual tours in Asian hotels?
CREATE TABLE hotels (hotel_id INT,hotel_name TEXT,country TEXT); INSERT INTO hotels (hotel_id,hotel_name,country) VALUES (1,'Hotel A','Japan'),(2,'Hotel B','China'),(3,'Hotel C','India'); CREATE TABLE virtual_tours (hotel_id INT,tour_name TEXT); INSERT INTO virtual_tours (hotel_id,tour_name) VALUES (1,'Tour A'),(2,'Tour B'),(3,'Tour C'),(4,'Tour D');
SELECT country, (COUNT(DISTINCT hotels.hotel_id) / (SELECT COUNT(DISTINCT hotel_id) FROM hotels WHERE country = hotels.country) * 100) as adoption_rate FROM hotels INNER JOIN virtual_tours ON hotels.hotel_id = virtual_tours.hotel_id GROUP BY country;
Which restaurants have had more than 3 inspections with a rating below 80?
CREATE TABLE Restaurant (id INT,name VARCHAR(50)); INSERT INTO Restaurant (id,name) VALUES (1,'Fresh Harvest'); INSERT INTO Restaurant (id,name) VALUES (2,'Green Living'); INSERT INTO Restaurant (id,name) VALUES (3,'Taste of Nature'); CREATE TABLE FoodInspections (id INT,restaurant_id INT,inspection_date DATE,rating INT); INSERT INTO FoodInspections (id,restaurant_id,inspection_date,rating) VALUES (1,1,'2022-01-01',75); INSERT INTO FoodInspections (id,restaurant_id,inspection_date,rating) VALUES (2,1,'2022-02-01',85); INSERT INTO FoodInspections (id,restaurant_id,inspection_date,rating) VALUES (3,2,'2022-03-01',90); INSERT INTO FoodInspections (id,restaurant_id,inspection_date,rating) VALUES (4,2,'2022-04-01',80); INSERT INTO FoodInspections (id,restaurant_id,inspection_date,rating) VALUES (5,3,'2022-05-01',60); INSERT INTO FoodInspections (id,restaurant_id,inspection_date,rating) VALUES (6,3,'2022-06-01',65); INSERT INTO FoodInspections (id,restaurant_id,inspection_date,rating) VALUES (7,3,'2022-07-01',70);
SELECT Restaurant.name FROM Restaurant LEFT JOIN FoodInspections ON Restaurant.id = FoodInspections.restaurant_id WHERE FoodInspections.rating < 80 GROUP BY Restaurant.name HAVING COUNT(FoodInspections.id) > 3;
Delete all records in the "EconomicDiversification" table where the budget is less than $100,000
CREATE TABLE EconomicDiversification (id INT PRIMARY KEY,project_name VARCHAR(255),budget DECIMAL(10,2));
DELETE FROM EconomicDiversification WHERE budget < 100000;
What is the average risk score of vulnerabilities detected in the last 30 days, grouped by software vendor?
CREATE TABLE vulnerabilities (id INT,detection_date DATE,software_vendor VARCHAR(255),risk_score INT); INSERT INTO vulnerabilities (id,detection_date,software_vendor,risk_score) VALUES (1,'2022-01-01','VendorA',7),(2,'2022-01-05','VendorB',5),(3,'2022-01-10','VendorA',9);
SELECT software_vendor, AVG(risk_score) as avg_risk_score FROM vulnerabilities WHERE detection_date >= DATE(NOW()) - INTERVAL 30 DAY GROUP BY software_vendor;
What is the average number of publications per graduate student in each department?
CREATE TABLE departments (department VARCHAR(50),avg_publications FLOAT); INSERT INTO departments VALUES ('Computer Science',3.5),('Mathematics',2.8),('Physics',4.2);
SELECT d.department, AVG(gs.publications) FROM (SELECT department, COUNT(publication) AS publications FROM graduate_students GROUP BY department) gs JOIN departments d ON gs.department = d.department GROUP BY d.department;
List the environmental impact scores of production sites in Germany, partitioned by state in ascending order.
CREATE TABLE german_sites (site_id INT,site_name TEXT,state TEXT,environmental_score FLOAT); INSERT INTO german_sites (site_id,site_name,state,environmental_score) VALUES (1,'Site E','Bavaria',85.2),(2,'Site F','Baden-Württemberg',88.7),(3,'Site G','Bavaria',90.1),(4,'Site H','Hesse',82.6);
SELECT state, environmental_score, RANK() OVER (PARTITION BY state ORDER BY environmental_score) as rank FROM german_sites WHERE country = 'Germany' GROUP BY state, environmental_score;
What is the average cost of the top 5 most frequently sourced ingredients?
CREATE TABLE ingredients (ingredient_id INT,ingredient_name TEXT,sourcing_frequency INT); INSERT INTO ingredients (ingredient_id,ingredient_name,sourcing_frequency) VALUES (1,'Water',100),(2,'Glycerin',80),(3,'Shea Butter',60);
SELECT AVG(cost) FROM (SELECT * FROM (SELECT ingredient_name, sourcing_frequency, ROW_NUMBER() OVER (ORDER BY sourcing_frequency DESC) AS rn FROM ingredients) sub WHERE rn <= 5) sub2 JOIN ingredients ON sub2.ingredient_name = ingredients.ingredient_name;
What was the total CO2 emissions (Mt) from the power sector in India in 2019?
CREATE TABLE co2_emissions (id INT,sector TEXT,year INT,emissions_mt FLOAT); INSERT INTO co2_emissions (id,sector,year,emissions_mt) VALUES (1,'Power',2018,1200.1),(2,'Power',2019,1300.2);
SELECT SUM(emissions_mt) FROM co2_emissions WHERE sector = 'Power' AND year = 2019;
What is the minimum claim amount for policyholders in Arizona?
INSERT INTO claims (id,policyholder_id,claim_amount,claim_date) VALUES (9,7,100,'2021-03-05');
SELECT MIN(claim_amount) FROM claims JOIN policyholders ON claims.policyholder_id = policyholders.id WHERE policyholders.state = 'Arizona';
What is the average data usage for mobile subscribers?
CREATE TABLE avg_mobile_usage (id INT,name VARCHAR(50),data_usage FLOAT); INSERT INTO avg_mobile_usage (id,name,data_usage) VALUES (1,'Janet Smith',12.5);
SELECT AVG(data_usage) FROM avg_mobile_usage WHERE data_usage > 0;
What is the total number of tourists who visited Japan in 2020 from European countries?
CREATE TABLE tourism_data (visitor_country VARCHAR(50),destination_country VARCHAR(50),visit_year INT); INSERT INTO tourism_data (visitor_country,destination_country,visit_year) VALUES ('France','Japan',2020),('Germany','Japan',2020),('Italy','Japan',2020);
SELECT SUM(*) FROM tourism_data WHERE visitor_country LIKE 'Europe%' AND visit_year = 2020 AND destination_country = 'Japan';
What is the total capacity of all cargo ships owned by the ACME corporation?
CREATE TABLE cargo_ships (id INT,name VARCHAR(50),capacity INT,owner_id INT); INSERT INTO cargo_ships (id,name,capacity,owner_id) VALUES (1,'Sea Titan',150000,1),(2,'Ocean Marvel',200000,1),(3,'Cargo Master',120000,2); CREATE TABLE owners (id INT,name VARCHAR(50)); INSERT INTO owners (id,name) VALUES (1,'ACME Corporation'),(2,'Global Shipping');
SELECT SUM(capacity) FROM cargo_ships JOIN owners ON cargo_ships.owner_id = owners.id WHERE owners.name = 'ACME Corporation';
Who are the top 5 authors with the highest number of published articles on media ethics in the last year?
CREATE TABLE authors (id INT,name VARCHAR(255),articles_written INT); CREATE TABLE articles_authors (article_id INT,author_id INT); INSERT INTO authors (id,name,articles_written) VALUES (1,'Author 1',50),(2,'Author 2',30); INSERT INTO articles_authors (article_id,author_id) VALUES (1,1),(2,1); CREATE VIEW articles_view AS SELECT a.id,a.title,a.publish_date,aa.author_id FROM articles a JOIN articles_authors aa ON a.id = aa.article_id WHERE a.publish_date >= DATE_SUB(NOW(),INTERVAL 1 YEAR);
SELECT a.name, COUNT(av.article_id) AS articles_count FROM authors a JOIN articles_view av ON a.id = av.author_id GROUP BY a.id ORDER BY articles_count DESC LIMIT 5;
What is the production volume trend for each chemical category over time?
CREATE TABLE production_volume (chemical_category VARCHAR(255),production_date DATE,production_volume INT); INSERT INTO production_volume (chemical_category,production_date,production_volume) VALUES ('Polymers','2023-03-01',200),('Polymers','2023-03-02',250),('Dyes','2023-03-01',150);
SELECT chemical_category, production_date, SUM(production_volume) OVER (PARTITION BY chemical_category ORDER BY production_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_total FROM production_volume;
What are the names of all aircraft manufactured by companies based in the USA?
CREATE TABLE Manufacturers (Id INT,Name VARCHAR(50),Country VARCHAR(50)); INSERT INTO Manufacturers (Id,Name,Country) VALUES (1,'Boeing','USA'),(2,'Airbus','France'),(3,'Embraer','Brazil'),(4,'Bombardier','Canada'); CREATE TABLE Aircraft (Id INT,Name VARCHAR(50),ManufacturerId INT); INSERT INTO Aircraft (Id,Name,ManufacturerId) VALUES (1,'747',1),(2,'777',1),(3,'A320',2),(4,'A350',2),(5,'ERJ145',3),(6,'CRJ700',4);
SELECT Aircraft.Name FROM Aircraft JOIN Manufacturers ON Aircraft.ManufacturerId = Manufacturers.Id WHERE Manufacturers.Country = 'USA';
What is the average ticket price for football matches in the 'Central' region?
CREATE TABLE stadiums (stadium_id INT,stadium_name TEXT,region TEXT); INSERT INTO stadiums (stadium_id,stadium_name,region) VALUES (1,'Freedom Field','Central'),(2,'Eagle Stadium','Northeast'),(3,'Thunder Dome','Southwest'); CREATE TABLE matches (match_id INT,stadium_id INT,sport TEXT,ticket_price DECIMAL); INSERT INTO matches (match_id,stadium_id,sport,ticket_price) VALUES (1,1,'Football',50.00),(2,1,'Football',55.00),(3,2,'Soccer',30.00),(4,3,'Basketball',70.00);
SELECT AVG(ticket_price) FROM matches WHERE sport = 'Football' AND stadium_id IN (SELECT stadium_id FROM stadiums WHERE region = 'Central');
How many bridges are there in each district?
CREATE TABLE bridges (id INT,name VARCHAR(50),district VARCHAR(50),length FLOAT); INSERT INTO bridges VALUES (1,'Golden Gate','San Francisco',2737),(2,'Brooklyn','New York',1825),(3,'Tower','London',244);
SELECT district, COUNT(*) FROM bridges GROUP BY district;
List all socially responsible lending activities by GreenBank in 2021.
CREATE TABLE socially_responsible_lending (bank_name TEXT,activity_name TEXT,activity_date DATE); INSERT INTO socially_responsible_lending (bank_name,activity_name,activity_date) VALUES ('GreenBank','Solar Panel Loans','2021-02-15'),('GreenBank','Education Loans','2021-05-10'),('GreenBank','Affordable Housing Loans','2021-12-28');
SELECT * FROM socially_responsible_lending WHERE bank_name = 'GreenBank' AND activity_date BETWEEN '2021-01-01' AND '2021-12-31';
What is the maximum construction cost of any project in the city of Sydney, Australia?
CREATE TABLE ConstructionProjects (id INT,city VARCHAR(50),country VARCHAR(50),cost FLOAT);
SELECT MAX(cost) FROM ConstructionProjects WHERE city = 'Sydney' AND country = 'Australia';
How many cases were handled by attorneys with less than 5 years of experience?
CREATE TABLE Cases (CaseID int,AttorneyID int); INSERT INTO Cases (CaseID,AttorneyID) VALUES (1,1),(2,3),(3,2),(4,1),(5,3),(6,2),(7,1); INSERT INTO Attorneys (AttorneyID,ExperienceYears) VALUES (1,12),(2,8),(3,4);
SELECT COUNT(*) FROM Cases c JOIN Attorneys a ON c.AttorneyID = a.AttorneyID WHERE a.ExperienceYears < 5;
Update the department of a principal investigator in the genetic research team
CREATE TABLE employees (id INT PRIMARY KEY,name VARCHAR(255),department VARCHAR(255)); INSERT INTO employees (id,name,department) VALUES (1,'Alice','Genetics'),(2,'Bob','Bioengineering');
UPDATE employees SET department = 'Synthetic Biology' WHERE id = 1;
What is the total revenue generated from sustainable fashion sales in the 'sales_data' table?
CREATE TABLE sales_data (id INT,product_id INT,price DECIMAL(5,2),is_sustainable BOOLEAN); INSERT INTO sales_data (id,product_id,price,is_sustainable) VALUES (1,1,10.00,true),(2,2,20.00,true); ALTER TABLE fashion_trend_data ADD COLUMN id INT PRIMARY KEY; ALTER TABLE sales_data ADD COLUMN product_id INT REFERENCES fashion_trend_data(id);
SELECT SUM(price) FROM sales_data WHERE is_sustainable = true;
How many professional development workshops were held in urban areas?
CREATE TABLE area (area_id INT,area_type TEXT); CREATE TABLE workshop (workshop_id INT,area_id INT,num_participants INT); INSERT INTO area (area_id,area_type) VALUES (1,'urban'),(2,'suburban'),(3,'rural'); INSERT INTO workshop (workshop_id,area_id,num_participants) VALUES (101,1,30),(102,1,45),(103,2,25),(104,3,50);
SELECT COUNT(*) FROM workshop INNER JOIN area ON workshop.area_id = area.area_id WHERE area.area_type = 'urban';
What is the average billing amount per case for each attorney?
CREATE TABLE Attorneys (AttorneyID INT,Name VARCHAR(50)); INSERT INTO Attorneys (AttorneyID,Name) VALUES (1,'Jose Garcia'),(2,'Lee Kim'); CREATE TABLE Cases (CaseID INT,AttorneyID INT,BillingAmount DECIMAL(10,2)); INSERT INTO Cases (CaseID,AttorneyID,BillingAmount) VALUES (1,1,5000.00),(2,1,3000.00),(3,2,4000.00),(4,2,2000.00);
SELECT Attorneys.Name, AVG(Cases.BillingAmount) FROM Attorneys INNER JOIN Cases ON Attorneys.AttorneyID = Cases.AttorneyID GROUP BY Attorneys.Name;
What is the average financial capability score for clients in urban areas?
CREATE TABLE financial_capability (id INT,location VARCHAR(50),score FLOAT); INSERT INTO financial_capability (id,location,score) VALUES (1,'Rural',6.5),(2,'Urban',7.2),(3,'Suburban',8.0);
SELECT AVG(score) as avg_score FROM financial_capability WHERE location = 'Urban';
Insert a new record of budget allocation for the 'Transportation' department for the year 2023
CREATE TABLE budget_allocation (department TEXT,year INT,allocation DECIMAL(10,2));
INSERT INTO budget_allocation (department, year, allocation) VALUES ('Transportation', 2023, 500000.00);
List the states with no drought conditions in the last 3 months.
CREATE TABLE drought_conditions (state TEXT,date DATE,status TEXT); INSERT INTO drought_conditions (state,date,status) VALUES ('California','2022-01-01','Drought'),('California','2022-04-01','Drought'),('Texas','2022-01-01','No Drought'),('Texas','2022-04-01','No Drought'),('Florida','2022-01-01','No Drought'),('Florida','2022-04-01','No Drought');
SELECT state FROM drought_conditions WHERE status = 'No Drought' AND date BETWEEN '2022-01-01' AND '2022-04-01' GROUP BY state HAVING COUNT(*) = 2;
What is the minimum year of construction for vessels that have reported incidents of illegal fishing activities in the Arctic Ocean?
CREATE TABLE vessels (id INT,name VARCHAR(255),year_built INT,incidents INT,region VARCHAR(255)); INSERT INTO vessels (id,name,year_built,incidents,region) VALUES (1,'Arctic Hunter',2005,2,'Arctic');
SELECT MIN(year_built) FROM vessels WHERE region = 'Arctic' AND incidents > 0;
What is the total sales of dermatology drugs in Australia?
CREATE TABLE sales_data (drug_name VARCHAR(50),country VARCHAR(50),sales_amount NUMERIC(10,2)); INSERT INTO sales_data (drug_name,country,sales_amount) VALUES ('DrugX','Australia',3000000),('DrugY','Australia',4000000),('DrugZ','Australia',5000000);
SELECT SUM(sales_amount) FROM sales_data WHERE drug_category = 'Dermatology' AND country = 'Australia';
What is the distribution of space debris by country?
CREATE TABLE space_debris (debris_id INT,name VARCHAR(255),country VARCHAR(255),debris_type VARCHAR(255));
SELECT country, COUNT(*) as total_debris FROM space_debris GROUP BY country;
How many renewable energy projects have been completed in the state of New York in the last 5 years?
CREATE TABLE Projects (project_id INT,project_name VARCHAR(100),state VARCHAR(100),completion_date DATE);
SELECT COUNT(*) FROM Projects WHERE state = 'New York' AND completion_date >= DATE_SUB(CURRENT_DATE, INTERVAL 5 YEAR);
Delete records with a warehouse_id of 15 from the warehouse table
CREATE TABLE warehouse (warehouse_id INT,warehouse_name VARCHAR(50),city VARCHAR(50),country VARCHAR(50));
DELETE FROM warehouse WHERE warehouse_id = 15;
What is the average salary of employees in the Safety department?
CREATE TABLE Employees (EmployeeID INT PRIMARY KEY,FirstName VARCHAR(50),LastName VARCHAR(50),Department VARCHAR(50),Salary DECIMAL(10,2)); INSERT INTO Employees (EmployeeID,FirstName,LastName,Department,Salary) VALUES (3,'Alice','Smith','Safety',60000.00); INSERT INTO Employees (EmployeeID,FirstName,LastName,Department,Salary) VALUES (4,'Bob','Johnson','Manufacturing',52000.00);
SELECT AVG(Employees.Salary) FROM Employees WHERE Employees.Department = 'Safety';
Which indigenous communities in South America have a language that is at risk of disappearing and what are their associated cultural practices?
CREATE TABLE Communities (id INT,name TEXT); INSERT INTO Communities (id,name) VALUES (1,'Quechua'); CREATE TABLE Languages (id INT,community_id INT,language TEXT,status TEXT); INSERT INTO Languages (id,community_id,language,status) VALUES (1,1,'Quechua Language','At Risk'); CREATE TABLE CulturalPractices (id INT,community_id INT,practice TEXT); INSERT INTO CulturalPractices (id,community_id,practice) VALUES (1,1,'Pottery');
SELECT C.name, L.language, CP.practice FROM Communities C INNER JOIN Languages L ON C.id = L.community_id INNER JOIN CulturalPractices CP ON C.id = CP.community_id WHERE L.status = 'At Risk';
List the smart contracts that were executed by the company with the id 3 in the month of October 2021.
CREATE TABLE Companies (id INT,name VARCHAR(255)); CREATE TABLE SmartContracts (id INT,company_id INT,execution_date DATE); INSERT INTO Companies (id,name) VALUES (1,'CompanyA'),(2,'CompanyB'),(3,'CompanyC'); INSERT INTO SmartContracts (id,company_id,execution_date) VALUES (1,1,'2021-10-15'),(2,2,'2021-11-01'),(3,3,'2021-10-01'),(4,3,'2021-10-15');
SELECT SmartContracts.id FROM SmartContracts JOIN Companies ON SmartContracts.company_id = Companies.id WHERE Companies.id = 3 AND SmartContracts.execution_date >= '2021-10-01' AND SmartContracts.execution_date < '2021-11-01';
List all farmers who cultivate 'Amaranth' and their corresponding communities.
CREATE TABLE farmer (id INT PRIMARY KEY,name VARCHAR(50),crop_id INT,community_id INT); CREATE TABLE crop (id INT PRIMARY KEY,name VARCHAR(50)); CREATE TABLE community (id INT PRIMARY KEY,name VARCHAR(50)); INSERT INTO crop (id,name) VALUES (1,'Amaranth'),(2,'Cassava'); INSERT INTO community (id,name) VALUES (1,'San Juan'),(2,'Nima'); INSERT INTO farmer (id,name,crop_id,community_id) VALUES (1,'John Doe',1,1),(2,'Jane Doe',2,2);
SELECT f.name, co.name AS community_name FROM farmer f INNER JOIN crop c ON f.crop_id = c.id INNER JOIN community co ON f.community_id = co.id WHERE c.name = 'Amaranth';
What is the percentage of restorative justice programs that were successful?
CREATE TABLE restorative_justice_outcomes (offender_id INT,program_id INT,outcome VARCHAR(20));
SELECT (COUNT(*) * 100.0 / (SELECT COUNT(*) FROM restorative_justice_outcomes)) AS percentage FROM restorative_justice_outcomes WHERE outcome = 'successful';
Update the count of artifacts in 'Tikal' to 85.
CREATE TABLE ExcavationSite (SiteID INT,SiteName TEXT,Country TEXT,NumArtifacts INT); INSERT INTO ExcavationSite (SiteID,SiteName,Country,NumArtifacts) VALUES (1,'Pompeii','Italy',52),(2,'Tutankhamun','Egypt',35),(3,'Machu Picchu','Peru',42),(4,'Tikal','Guatemala',80);
UPDATE ExcavationSite SET NumArtifacts = 85 WHERE SiteName = 'Tikal';
Which athletes have the most wins in the last 5 years, and how many wins did they have?
CREATE TABLE athletes (id INT,name TEXT,sport TEXT,wins INT,losses INT); INSERT INTO athletes (id,name,sport,wins,losses) VALUES (1,'John Doe','Basketball',300,150); INSERT INTO athletes (id,name,sport,wins,losses) VALUES (2,'Jane Smith','Soccer',200,50);
SELECT a.name, a.wins FROM athletes a INNER JOIN (SELECT athlete_id, SUM(wins) AS total_wins FROM games WHERE game_date >= DATE_SUB(CURRENT_DATE, INTERVAL 5 YEAR) GROUP BY athlete_id) b ON a.id = b.athlete_id ORDER BY total_wins DESC;
Which union has the highest number of members in 'California'?
CREATE TABLE union_members (id INT,union_name VARCHAR(255),state VARCHAR(255),member_count INT); INSERT INTO union_members (id,union_name,state,member_count) VALUES (1,'United Steelworkers','California',15000),(2,'Teamsters','California',20000);
SELECT union_name, member_count FROM union_members WHERE state = 'California' ORDER BY member_count DESC LIMIT 1;
What is the total revenue of organic skincare products in Q3 2019?
CREATE TABLE cosmetics_sales(product_name TEXT,revenue DECIMAL,is_organic BOOLEAN,sale_date DATE); INSERT INTO cosmetics_sales(product_name,revenue,is_organic,sale_date) VALUES('Organic Skincare Product 1',56.99,true,'2019-09-01');
SELECT SUM(revenue) FROM cosmetics_sales WHERE is_organic = true AND sale_date >= '2019-07-01' AND sale_date < '2019-10-01';
What is the average horsepower of electric vehicles in the 'GreenAutos' database?
CREATE TABLE ElectricVehicles (Id INT,Make VARCHAR(50),Model VARCHAR(50),Year INT,Horsepower INT);
SELECT AVG(Horsepower) FROM ElectricVehicles WHERE FuelType = 'Electric';
What are the top 3 countries with the highest energy efficiency ratings for residential buildings, along with their average ratings?
CREATE TABLE Country (CountryID INT,CountryName VARCHAR(100)); INSERT INTO Country VALUES (1,'Canada'),(2,'USA'),(3,'Mexico'),(4,'Brazil'),(5,'Germany'); CREATE TABLE Building (BuildingID INT,BuildingName VARCHAR(100),CountryID INT,EnergyEfficiencyRating FLOAT); INSERT INTO Building VALUES (1,'House A',1,90),(2,'Apartment B',2,80),(3,'Condo C',3,95),(4,'Townhouse D',4,98),(5,'Villa E',5,85);
SELECT CountryName, AVG(EnergyEfficiencyRating) AS AvgRating FROM Building JOIN Country ON Building.CountryID = Country.CountryID GROUP BY CountryID ORDER BY AvgRating DESC LIMIT 3;
Find the number of times each irrigation system was activated in the past month.
CREATE TABLE irrigation (id INT,system_id INT,activation_time DATETIME);
SELECT system_id, COUNT(*) as activation_count FROM irrigation WHERE activation_time >= DATE_SUB(CURRENT_TIMESTAMP, INTERVAL 1 MONTH) GROUP BY system_id;
What is the total population of all marine species in the Pacific region?
CREATE TABLE marine_species_pacific (name VARCHAR(255),region VARCHAR(255),population INT); INSERT INTO marine_species_pacific (name,region,population) VALUES ('Clownfish','Pacific',500),('Sea Turtle','Pacific',1000);
SELECT SUM(population) FROM marine_species_pacific WHERE region = 'Pacific';
Which players are from the same country as coach Mateo Garcia?
CREATE TABLE Players (PlayerID INT,Name VARCHAR(50),Sport VARCHAR(20),Age INT,Country VARCHAR(50)); INSERT INTO Players (PlayerID,Name,Sport,Age,Country) VALUES (1,'John Doe','Basketball',25,'United States'),(2,'Maria Rodriguez','Basketball',35,'Spain'),(3,'Lucas Hernandez','Soccer',27,'Argentina');
SELECT * FROM Players WHERE Country = (SELECT Country FROM Coaches WHERE Name = 'Mateo Garcia');
What is the average treatment cost per patient for each treatment type, sorted by cost?
CREATE TABLE treatments (id INT,patient_id INT,treatment_type VARCHAR(50),duration INT,cost FLOAT); INSERT INTO treatments (id,patient_id,treatment_type,duration,cost) VALUES (21,13,'Psychotherapy',12,120); INSERT INTO treatments (id,patient_id,treatment_type,duration,cost) VALUES (22,14,'Medication',20,250); INSERT INTO treatments (id,patient_id,treatment_type,duration,cost) VALUES (23,15,'Mindfulness',10,60); INSERT INTO treatments (id,patient_id,treatment_type,duration,cost) VALUES (24,16,'Exercise',15,80);
SELECT treatment_type, AVG(cost) as avg_cost, RANK() OVER (ORDER BY AVG(cost) DESC) as cost_rank FROM treatments GROUP BY treatment_type ORDER BY avg_cost;
List all smart city technology adoptions and their corresponding energy savings percentages from the 'smart_city_technology' table.
CREATE TABLE smart_city_technology (technology_name TEXT,energy_savings_percentage REAL);
SELECT technology_name, energy_savings_percentage FROM smart_city_technology;
What is the average cultural competency score of health equity metrics?
CREATE TABLE health_equity_metrics (id INT,name TEXT,score INT,category TEXT);
SELECT AVG(score) FROM health_equity_metrics WHERE category = 'cultural competency';