instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
What is the average environmental impact score of mining operations in Australia that were established after 2010?
CREATE TABLE mining_operations (id INT,location VARCHAR(255),established_year INT,environmental_impact_score INT); INSERT INTO mining_operations (id,location,established_year,environmental_impact_score) VALUES (1,'Australia',2005,60),(2,'Australia',2012,70),(3,'Australia',2008,50);
SELECT AVG(environmental_impact_score) FROM mining_operations WHERE location = 'Australia' AND established_year > 2010;
What is the total number of user interactions from the 'Northeast' region?
CREATE TABLE regions (region_id INT,region_name VARCHAR(50)); INSERT INTO regions (region_id,region_name) VALUES (1,'Northeast'); INSERT INTO regions (region_id,region_name) VALUES (2,'Southeast'); CREATE TABLE user_interactions (user_id INT,article_id INT,interaction_date DATE,region_id INT); INSERT INTO user_interactions (user_id,article_id,interaction_date,region_id) VALUES (1,101,'2021-01-01',1); INSERT INTO user_interactions (user_id,article_id,interaction_date,region_id) VALUES (2,102,'2021-01-02',2);
SELECT COUNT(user_interactions.interaction_id) FROM user_interactions WHERE user_interactions.region_id = (SELECT region_id FROM regions WHERE regions.region_name = 'Northeast');
What is the average word count of articles written by female authors?
CREATE TABLE news_articles (id INT,title VARCHAR(100),content TEXT,word_count INT,author_gender VARCHAR(10));
SELECT AVG(word_count) FROM news_articles WHERE author_gender = 'Female';
What is the total savings of customers in the East region?
CREATE TABLE customers (id INT,name TEXT,region TEXT,savings REAL);
SELECT SUM(savings) FROM customers WHERE region = 'East';
What are the names and success statuses of intelligence operations conducted in 'Russia' according to the 'Intel_Ops' table?
CREATE TABLE Intel_Ops (ops_id INT,ops_name VARCHAR(50),ops_location VARCHAR(50),ops_year INT,ops_success BOOLEAN); INSERT INTO Intel_Ops (ops_id,ops_name,ops_location,ops_year,ops_success) VALUES (1,'Operation Red Sparrow','Russia',2020,true); INSERT INTO Intel_Ops (ops_id,ops_name,ops_location,ops_year,ops_success) VALUES (2,'Operation Black Swan','Iran',2019,false);
SELECT ops_name, ops_success FROM Intel_Ops WHERE ops_location = 'Russia';
Calculate the total water usage for all mining operations, per month
CREATE TABLE WaterUsage (SiteID INT,UsageDate DATE,AmountUsed INT); INSERT INTO WaterUsage (SiteID,UsageDate,AmountUsed) VALUES (1,'2021-01-01',500),(1,'2021-01-15',700);
SELECT DATE_FORMAT(UsageDate, '%Y-%m') as Month, SUM(AmountUsed) as TotalWaterUsage FROM WaterUsage GROUP BY Month;
What is the maximum depth and average temperature of the Atlantic Ocean where marine species reside, grouped by species?
CREATE TABLE marine_species_atlantic_ocean (id INT,species_name VARCHAR(255),population INT,habitat VARCHAR(255)); INSERT INTO marine_species_atlantic_ocean (id,species_name,population,habitat) VALUES (1,'Blue Whale',10000,'Atlantic Ocean'),(2,'Great White Shark',3000,'Atlantic Ocean'); CREATE TABLE oceanography_atlantic_ocean (region VARCHAR(255),depth FLOAT,temperature FLOAT,salinity FLOAT); INSERT INTO oceanography_atlantic_ocean (region,depth,temperature,salinity) VALUES ('Atlantic Ocean',7000,20,36.5);
SELECT m.species_name, MAX(o.depth) AS max_depth, AVG(o.temperature) AS avg_temperature FROM marine_species_atlantic_ocean m INNER JOIN oceanography_atlantic_ocean o ON m.habitat = o.region GROUP BY m.species_name;
Show the number of sustainable tourism initiatives in Spain and Portugal.
CREATE TABLE sustainable_tourism (initiative_id INT,name TEXT,country TEXT); INSERT INTO sustainable_tourism VALUES (1,'Eco-friendly Beaches','Spain'),(2,'Sustainable Wine Tourism','Spain'),(3,'Green Energy Sites','Portugal');
SELECT country, COUNT(*) FROM sustainable_tourism GROUP BY country;
Count the number of athletes who have competed in the Olympics from Australia
CREATE TABLE athletes (id INT,name VARCHAR(50),country VARCHAR(50),sport VARCHAR(20));
SELECT COUNT(*) FROM athletes WHERE country = 'Australia' AND sport IN (SELECT sport FROM events WHERE name LIKE '%Olympics%');
How many donors made donations in each quarter of 2021?
CREATE TABLE donations (donor_id INT,donation_date DATE); INSERT INTO donations (donor_id,donation_date) VALUES (1,'2021-01-01'),(1,'2021-04-01'),(2,'2021-02-01'),(2,'2021-03-01'),(3,'2021-04-01');
SELECT CONCAT('Q', QUARTER(donation_date)) as quarter, COUNT(DISTINCT donor_id) as num_donors FROM donations WHERE YEAR(donation_date) = 2021 GROUP BY quarter;
What is the average rating of hotels in the 'Luxury' category?
CREATE TABLE Hotels (hotel_id INT,hotel_name VARCHAR(100),category VARCHAR(50),rating FLOAT); INSERT INTO Hotels (hotel_id,hotel_name,category,rating) VALUES (1,'Hotel A','Boutique',4.6),(2,'Hotel B','Boutique',4.3),(3,'Hotel C','Economy',3.5),(4,'Hotel D','Economy',3.8),(5,'Hotel E','Luxury',4.9),(6,'Hotel F','Luxury',4.7);
SELECT AVG(rating) FROM Hotels WHERE category = 'Luxury';
Which countries have the most ethical AI initiatives, and how many of them are focused on social good?
CREATE SCHEMA if not exists ai_stats; CREATE TABLE if not exists ai_stats.ethical_initiatives (country VARCHAR(255),initiatives INT,focused_on_social_good BOOLEAN); INSERT INTO ai_stats.ethical_initiatives (country,initiatives,focused_on_social_good) VALUES ('USA',100,true),('Canada',50,false),('Germany',75,true),('South Africa',25,true);
SELECT country, SUM(focused_on_social_good) as focused_on_social_good, MAX(initiatives) as initiatives FROM ai_stats.ethical_initiatives GROUP BY country ORDER BY initiatives DESC;
What is the minimum number of community development projects completed in Africa in the last 5 years?
CREATE TABLE community_development (id INT,location VARCHAR(255),year INT,completed BOOLEAN);
SELECT MIN(year) - 5, MIN(completed) FROM community_development WHERE location LIKE '%Africa%' AND completed = TRUE AND year > (SELECT MAX(year) FROM community_development WHERE location LIKE '%Africa%' AND completed = TRUE AND year < (SELECT MAX(year) FROM community_development WHERE location LIKE '%Africa%') - 5);
What is the sum of volunteer hours per country in Q1 2022?
CREATE TABLE q1_volunteer_hours (id INT,volunteer_name VARCHAR(50),country VARCHAR(50),volunteer_hours INT); INSERT INTO q1_volunteer_hours (id,volunteer_name,country,volunteer_hours) VALUES (1,'Kwame','Ghana',10),(2,'Priya','India',15),(3,'Kwame','Ghana',12);
SELECT country, SUM(volunteer_hours) as total_volunteer_hours FROM q1_volunteer_hours WHERE volunteer_date BETWEEN '2022-01-01' AND '2022-03-31' GROUP BY country;
Update the salary of all employees in the IT department by 5%.
CREATE TABLE employees (id INT,name VARCHAR(50),department VARCHAR(50),salary DECIMAL(5,2)); INSERT INTO employees (id,name,department,salary) VALUES (1,'John Doe','IT',50000.00); INSERT INTO employees (id,name,department,salary) VALUES (2,'Jane Smith','HR',55000.00);
UPDATE employees SET salary = salary * 1.05 WHERE department = 'IT';
Find the risk assessment details for the company with ID 4.
CREATE TABLE risk_assessment (company_id INT,risk_level VARCHAR(10),mitigation_strategy TEXT); INSERT INTO risk_assessment (company_id,risk_level,mitigation_strategy) VALUES (4,'medium','Regular audits and employee trainings.'),(5,'low','Minor improvements in supply chain management.'),(6,'high','Immediate actions to reduce environmental impact.');
SELECT * FROM risk_assessment WHERE company_id = 4;
Identify the artist with the most works displayed in galleries located in New York, and show the number of works and gallery names.
CREATE TABLE Artists (id INT,name VARCHAR(30)); CREATE TABLE Works (id INT,artist_id INT,title VARCHAR(50)); CREATE TABLE Gallery_Works (id INT,gallery_id INT,work_id INT); CREATE TABLE Galleries (id INT,name VARCHAR(30),city VARCHAR(20));
SELECT a.name, COUNT(w.id) as num_works, g.name as gallery_name FROM Artists a JOIN Works w ON a.id = w.artist_id JOIN Gallery_Works gw ON w.id = gw.work_id JOIN Galleries g ON gw.gallery_id = g.id WHERE g.city = 'New York' GROUP BY a.name, g.name ORDER BY num_works DESC LIMIT 1;
List the programs that have had the most volunteers over the past 12 months, excluding the 'Food Bank' program?
CREATE TABLE Programs (id INT,program_name VARCHAR(255)); CREATE TABLE Volunteers (id INT,volunteer_name VARCHAR(255),program VARCHAR(255),volunteer_date DATE); INSERT INTO Programs (id,program_name) VALUES (1,'Food Bank'),(2,'Education'),(3,'Healthcare'); INSERT INTO Volunteers (id,volunteer_name,program,volunteer_date) VALUES (1,'John Doe','Education','2021-01-01'),(2,'Jane Smith','Healthcare','2021-02-01'),(3,'Alice Johnson','Food Bank','2021-03-01');
SELECT program_name, COUNT(*) as total_volunteers FROM Programs p INNER JOIN Volunteers v ON p.program_name = v.program WHERE program_name != 'Food Bank' AND volunteer_date >= DATE_SUB(CURDATE(), INTERVAL 12 MONTH) GROUP BY program_name ORDER BY total_volunteers DESC LIMIT 1;
What is the percentage of female workers in each department, and which department has the highest percentage of female workers?
CREATE TABLE Departments (DepartmentID INT,DepartmentName VARCHAR(50),ManagerID INT);CREATE TABLE Employees (EmployeeID INT,DepartmentID INT,FirstName VARCHAR(50),LastName VARCHAR(50),Gender VARCHAR(10));CREATE VIEW DepartmentGender AS SELECT DepartmentID,FirstName,LastName,Gender,COUNT(*) OVER (PARTITION BY DepartmentID) AS DepartmentSize,COUNT(*) FILTER (WHERE Gender = 'Female') OVER (PARTITION BY DepartmentID) AS FemaleCount FROM Employees;CREATE VIEW DepartmentFemalePercentage AS SELECT DepartmentID,ROUND((FemaleCount::DECIMAL / DepartmentSize::DECIMAL) * 100,2) AS FemalePercentage FROM DepartmentGender;
SELECT DepartmentName, FemalePercentage FROM DepartmentFemalePercentage WHERE FemalePercentage = (SELECT MAX(FemalePercentage) FROM DepartmentFemalePercentage);
Show the number of veterans hired in each state for the last 6 months, excluding California
CREATE TABLE veteran_employment (employment_id INT,veteran_state VARCHAR(2),hire_date DATE); INSERT INTO veteran_employment (employment_id,veteran_state,hire_date) VALUES (1,'CA','2021-02-15'),(2,'TX','2021-08-24'),(3,'NY','2021-07-02'),(4,'CA','2021-11-10'),(5,'NJ','2021-05-15');
SELECT veteran_state, COUNT(*) AS hires FROM veteran_employment WHERE hire_date >= DATE_SUB(CURRENT_DATE, INTERVAL 6 MONTH) AND veteran_state != 'CA' GROUP BY veteran_state;
What is the total renewable energy subsidy (in USD) for each country, ranked from highest to lowest?
CREATE TABLE renewable_subsidy (country VARCHAR(50),subsidy FLOAT); INSERT INTO renewable_subsidy (country,subsidy) VALUES ('Country E',8000000),('Country F',7000000),('Country G',9000000),('Country H',6000000);
SELECT country, subsidy, ROW_NUMBER() OVER (ORDER BY subsidy DESC) as rank FROM renewable_subsidy;
What is the total number of carbon offset projects in the 'carbon_offset_projects' table, and what is the total quantity of offsets sold by these projects?
CREATE TABLE carbon_offset_projects (id INT,country VARCHAR(255),name VARCHAR(255),offset_type VARCHAR(255),total_offset_quantity INT,offset_price FLOAT,start_date DATE,end_date DATE); INSERT INTO carbon_offset_projects (id,country,name,offset_type,total_offset_quantity,offset_price,start_date,end_date) VALUES (1,'Brazil','Amazon Rainforest Protection','Forestation',1000000,15.00,'2022-01-01','2030-12-31'),(2,'Indonesia','Peatland Restoration','Reforestation',500000,20.00,'2021-01-01','2025-12-31');
SELECT COUNT(*) as project_count, SUM(total_offset_quantity) as total_offset_quantity FROM carbon_offset_projects;
Who are the top 3 customers with the highest total cost of orders in the year 2022?
CREATE TABLE Customers (customer_id INT,first_name VARCHAR(15),last_name VARCHAR(15)); CREATE TABLE Orders (order_id INT,customer_id INT,order_date DATE); CREATE TABLE Order_Items (order_item_id INT,order_id INT,menu_id INT,quantity INT); CREATE TABLE Menu (menu_id INT,menu_name VARCHAR(20),is_vegetarian BOOLEAN); CREATE TABLE Inventory (inventory_id INT,menu_id INT,inventory_cost FLOAT); INSERT INTO Customers (customer_id,first_name,last_name) VALUES (1,'John','Doe'),(2,'Jane','Doe'),(3,'Bob','Smith'),(4,'Amy','Johnson'); INSERT INTO Orders (order_id,customer_id,order_date) VALUES (1,1,'2022-01-01'),(2,1,'2022-01-02'),(3,2,'2022-01-03'),(4,1,'2022-01-04'),(5,3,'2022-01-05'); INSERT INTO Order_Items (order_item_id,order_id,menu_id,quantity) VALUES (1,1,1,2),(2,2,2,1),(3,3,3,3),(4,4,1,1),(5,5,4,2); INSERT INTO Menu (menu_id,menu_name,is_vegetarian) VALUES (1,'Breakfast',TRUE),(2,'Lunch',FALSE),(3,'Dinner',FALSE),(4,'Dessert',FALSE); INSERT INTO Inventory (inventory_id,menu_id,inventory_cost) VALUES (1,1,5.0),(2,2,3.5),(3,1,8.0),(4,3,7.0),(5,4,4.0);
SELECT Customers.first_name, Customers.last_name, SUM(Inventory.inventory_cost * Order_Items.quantity) AS total_cost FROM Customers INNER JOIN Orders ON Customers.customer_id = Orders.customer_id INNER JOIN Order_Items ON Orders.order_id = Order_Items.order_id INNER JOIN Menu ON Order_Items.menu_id = Menu.menu_id INNER JOIN Inventory ON Menu.menu_id = Inventory.menu_id WHERE YEAR(Orders.order_date) = 2022 GROUP BY Customers.customer_id ORDER BY total_cost DESC LIMIT 3;
What is the average sustainability rating for each product category?
CREATE TABLE product_categories (id INT,product_id INT,category VARCHAR(255)); INSERT INTO product_categories (id,product_id,category) VALUES (1,1,'Electronics'),(2,2,'Clothing'),(3,3,'Home Appliances'); CREATE TABLE products (id INT,name VARCHAR(255),supplier_id INT,category VARCHAR(255),sustainability_rating FLOAT); INSERT INTO products (id,name,supplier_id,category,sustainability_rating) VALUES (1,'Product X',1,'Electronics',4.3),(2,'Product Y',2,'Clothing',4.7),(3,'Product Z',3,'Home Appliances',3.5);
SELECT pc.category, AVG(p.sustainability_rating) as avg_sustainability_rating FROM product_categories pc JOIN products p ON pc.product_id = p.id GROUP BY pc.category;
What is the average number of eco-friendly tours booked per month in Asia and Europe?
CREATE TABLE Tours (region TEXT,tour_type TEXT,bookings NUMERIC); INSERT INTO Tours (region,tour_type,bookings) VALUES ('Asia','Eco-Friendly',300),('Asia','Regular',500),('Europe','Eco-Friendly',400),('Europe','Regular',600);
SELECT region, AVG(bookings) FROM Tours WHERE tour_type = 'Eco-Friendly' GROUP BY region;
What is the average risk assessment for policies in Texas by Underwriting team?
CREATE TABLE UnderwritingData (PolicyID INT,Team VARCHAR(20),RiskAssessment DECIMAL(5,2),State VARCHAR(20)); INSERT INTO UnderwritingData VALUES (1,'Team A',0.35,'California'),(2,'Team B',0.20,'California'),(3,'Team A',0.15,'Texas');
SELECT Team, AVG(RiskAssessment) FROM UnderwritingData WHERE State = 'Texas' GROUP BY Team;
List of unique mental health conditions treated in India.
CREATE TABLE conditions (condition_id INT,condition VARCHAR(50)); INSERT INTO conditions (condition_id,condition) VALUES (1,'Depression'),(2,'Anxiety'),(3,'Bipolar Disorder'); CREATE TABLE patients (patient_id INT,condition_id INT,country VARCHAR(50)); INSERT INTO patients (patient_id,condition_id,country) VALUES (1,1,'India'),(2,2,'Canada'),(3,3,'India');
SELECT DISTINCT conditions.condition FROM conditions INNER JOIN patients ON conditions.condition_id = patients.condition_id WHERE patients.country = 'India';
What is the minimum age of employees who identify as transgender or non-binary and have completed diversity training?
CREATE TABLE EmployeeDetails (EmployeeID INT,Age INT,GenderIdentity VARCHAR(20),DiversityTraining BOOLEAN); INSERT INTO EmployeeDetails (EmployeeID,Age,GenderIdentity,DiversityTraining) VALUES (1,30,'Transgender',TRUE),(2,40,'Female',FALSE),(3,25,'Non-binary',TRUE);
SELECT MIN(Age) FROM EmployeeDetails WHERE GenderIdentity IN ('Transgender', 'Non-binary') AND DiversityTraining = TRUE;
What is the total revenue for each art exhibition?
CREATE TABLE Exhibitions (id INT,name VARCHAR(255),location VARCHAR(255),start_date DATE,end_date DATE,revenue FLOAT);
SELECT name, SUM(revenue) FROM Exhibitions GROUP BY name;
Identify the animal species and their average weight in each habitat
CREATE TABLE animals (id INT,name VARCHAR(20),species VARCHAR(20),habitat_id INT,weight DECIMAL(5,2)); INSERT INTO animals (id,name,species,habitat_id,weight) VALUES (1,'Elephant','African',1,6000),(2,'Lion','African',2,400),(3,'Hippo','African',2,3000),(4,'Tiger','Asian',3,300),(5,'Crane','African',3,100),(6,'Rhinoceros','African',1,2000),(7,'Zebra','African',2,450); CREATE TABLE habitats (id INT,type VARCHAR(20)); INSERT INTO habitats (id,type) VALUES (1,'Forest'),(2,'Savannah'),(3,'Wetlands');
SELECT h.type, a.species, AVG(a.weight) as avg_weight FROM animals a JOIN habitats h ON a.habitat_id = h.id GROUP BY h.type, a.species;
Insert a new record for a 100-hectare wildlife habitat in India.
CREATE TABLE wildlife_habitats (id INT,name VARCHAR(50),area_ha FLOAT,country VARCHAR(50));
INSERT INTO wildlife_habitats (name, area_ha, country) VALUES ('Indian Wildlife', 100.0, 'India');
List the astronauts who have spent the least time in space, and their total days in space
CREATE TABLE astronauts (name VARCHAR(255),days_in_space FLOAT); INSERT INTO astronauts (name,days_in_space) VALUES ('John Doe',450); INSERT INTO astronauts (name,days_in_space) VALUES ('Jane Smith',600); INSERT INTO astronauts (name,days_in_space) VALUES ('Mike Johnson',550);
SELECT name, MIN(days_in_space) FROM astronauts;
Find the top 3 dates in the 'satellite_data' table with the lowest temperature for 'Field_6'.
CREATE TABLE satellite_data (field VARCHAR(255),temperature FLOAT,date DATE);
SELECT date, temperature FROM (SELECT date, temperature, ROW_NUMBER() OVER (PARTITION BY field ORDER BY temperature ASC) as rn FROM satellite_data WHERE field = 'Field_6') t WHERE rn <= 3;
What is the maximum fare for train trips in Oslo?
CREATE TABLE if not exists oslo_train_trips (id INT,trip_id INT,fare DECIMAL(5,2),route_id INT,vehicle_id INT,timestamp TIMESTAMP);
SELECT MAX(fare) FROM oslo_train_trips WHERE fare IS NOT NULL;
What is the total funding amount for biotech startups in the Asia-Pacific region?
CREATE TABLE Startups (startup_id INT,startup_name TEXT,industry TEXT,total_funding FLOAT); CREATE VIEW BiotechStartups AS SELECT * FROM Startups WHERE industry = 'Biotech'; CREATE VIEW AsiaPacificStartups AS SELECT * FROM Startups WHERE region = 'Asia-Pacific';
SELECT SUM(total_funding) FROM BiotechStartups INNER JOIN AsiaPacificStartups ON BiotechStartups.startup_id = AsiaPacificStartups.startup_id;
Which state has the highest gold production per employee?
CREATE TABLE companies (id INT,state VARCHAR(20),employees INT,gold_production FLOAT); INSERT INTO companies (id,state,employees,gold_production) VALUES (1,'Queensland',50,12000.5),(2,'NewSouthWales',75,18000.3),(3,'Victoria',100,25000.0);
SELECT state, MAX(gold_production/employees) as productivity FROM companies;
Update the 'military_equipment' table to change the 'equipment_type' of 'Item 123' to 'Aircraft'
CREATE TABLE military_equipment (equipment_id INT PRIMARY KEY,equipment_type VARCHAR(50),manufactured_year INT,quantity INT,country VARCHAR(50));
UPDATE military_equipment SET equipment_type = 'Aircraft' WHERE equipment_id = 123;
Which Islamic banks have the highest average loan amount in Malaysia?
CREATE TABLE islamic_banks (id INT,bank_name VARCHAR(50),country VARCHAR(50),avg_loan_amount FLOAT); INSERT INTO islamic_banks (id,bank_name,country,avg_loan_amount) VALUES (1,'Bank Islam Malaysia','Malaysia',25000.00),(2,'Maybank Islamic','Malaysia',30000.00);
SELECT country, bank_name, avg_loan_amount, RANK() OVER (ORDER BY avg_loan_amount DESC) as rank FROM islamic_banks WHERE country = 'Malaysia';
What is the total population of all birds in the savannah habitat?
CREATE TABLE animals (id INT,name VARCHAR(50),species VARCHAR(50),population INT,habitat VARCHAR(50)); INSERT INTO animals (id,name,species,population,habitat) VALUES (7,'Eagle','Bird',30,'Savannah'); INSERT INTO animals (id,name,species,population,habitat) VALUES (8,'Ostrich','Bird',50,'Savannah');
SELECT SUM(population) FROM animals WHERE species LIKE '%Bird' AND habitat = 'Savannah';
List all campaigns in California that started after 2018 and their corresponding budgets.
CREATE TABLE campaigns (campaign_id INT,state TEXT,start_date DATE); INSERT INTO campaigns (campaign_id,state,start_date) VALUES (1,'California','2018-01-01'),(2,'California','2019-01-01'),(3,'Texas','2017-01-01'); CREATE TABLE campaign_budgets (campaign_id INT,budget INT); INSERT INTO campaign_budgets (campaign_id,budget) VALUES (1,50000),(2,75000),(3,60000);
SELECT campaigns.state, campaign_budgets.budget FROM campaigns JOIN campaign_budgets ON campaigns.campaign_id = campaign_budgets.campaign_id WHERE campaigns.state = 'California' AND campaigns.start_date > '2018-01-01';
Show the number of startups founded each year
CREATE TABLE founding_year (company_name VARCHAR(50),founding_year INT); INSERT INTO founding_year (company_name,founding_year) VALUES ('Acme Inc',2010),('Beta Corp',2005),('Echo Startups',2012);
SELECT founding_year, COUNT(*) FROM founding_year GROUP BY founding_year;
What is the total number of marine protected areas in the Pacific Ocean region?
CREATE TABLE pacific_ocean (id INT,name VARCHAR(100),region VARCHAR(50)); INSERT INTO pacific_ocean (id,name,region) VALUES (1,'Pacific Ocean','Pacific'); CREATE TABLE marine_protected_areas (id INT,name VARCHAR(100),size FLOAT,ocean_id INT); INSERT INTO marine_protected_areas (id,name,size,ocean_id) VALUES (1,'Great Barrier Reef',344400,1);
SELECT COUNT(*) FROM marine_protected_areas mpa INNER JOIN pacific_ocean p ON mpa.ocean_id = p.id;
Calculate the percentage of employees who are male and female in each department in the "employee", "department", and "gender" tables
CREATE TABLE employee (id INT,department_id INT,gender_id INT); CREATE TABLE department (id INT,name TEXT); CREATE TABLE gender (id INT,name TEXT);
SELECT d.name, (COUNT(CASE WHEN g.name = 'male' THEN 1 END) / COUNT(*)) * 100 AS pct_male, (COUNT(CASE WHEN g.name = 'female' THEN 1 END) / COUNT(*)) * 100 AS pct_female FROM department d JOIN employee e ON d.id = e.department_id JOIN gender g ON e.gender_id = g.id GROUP BY d.name;
What is the average age of male patients diagnosed with heart disease in rural Alaska?
CREATE TABLE patients (id INT,name VARCHAR(50),age INT,gender VARCHAR(10),state VARCHAR(50)); CREATE TABLE diagnoses (id INT,patient_id INT,diagnosis VARCHAR(50),diagnosis_date DATE); INSERT INTO patients (id,name,age,gender,state) VALUES (1,'John Doe',45,'Male','Alaska'); INSERT INTO diagnoses (id,patient_id,diagnosis) VALUES (1,1,'Heart Disease');
SELECT AVG(age) FROM patients JOIN diagnoses ON patients.id = diagnoses.patient_id WHERE diagnoses.diagnosis = 'Heart Disease' AND patients.gender = 'Male' AND patients.state = 'Alaska';
Insert new records into the museum_operations table for a new exhibit.
CREATE TABLE museum_operations (exhibit_id INT,exhibit_name TEXT,start_date DATE,end_date DATE,daily_visitors INT);
INSERT INTO museum_operations (exhibit_id, exhibit_name, start_date, end_date, daily_visitors) VALUES (1001, 'Contemporary Art from Japan', '2023-03-01', '2023-05-31', 500);
What is the average rating of VR games released in 2021?
CREATE TABLE Games (GameID INT,GameName VARCHAR(100),Genre VARCHAR(50),ReleaseYear INT,Rating DECIMAL(3,1)); INSERT INTO Games (GameID,GameName,Genre,ReleaseYear,Rating) VALUES (1,'Beat Saber','VR',2018,9.0),(2,'Job Simulator','VR',2016,8.3),(3,'Echo VR','VR',2021,8.7);
SELECT AVG(Rating) FROM Games WHERE Genre = 'VR' AND ReleaseYear = 2021;
Update the 'mascot' for the 'team' with ID '101' in the 'teams' table
CREATE TABLE teams (id INT PRIMARY KEY,name VARCHAR(50),city VARCHAR(50),mascot VARCHAR(50));
UPDATE teams SET mascot = 'Green Griffins' WHERE id = 101;
Which fields had precipitation over 7mm in the last week?
CREATE TABLE field_precipitation (field_id INT,date DATE,precipitation FLOAT); INSERT INTO field_precipitation (field_id,date,precipitation) VALUES (7,'2021-07-01',12.5),(7,'2021-07-02',8.3),(8,'2021-07-03',15.2);
SELECT field_id, COUNT(*) as precipitation_days FROM field_precipitation WHERE field_id IN (7, 8) AND precipitation > 7 GROUP BY field_id HAVING precipitation_days > 0;
What is the minimum donation amount per state?
CREATE TABLE Donations (id INT,donor_name TEXT,donation_amount DECIMAL(10,2),state TEXT); INSERT INTO Donations (id,donor_name,donation_amount,state) VALUES (1,'John Doe',50.00,'NY'),(2,'Jane Smith',100.00,'CA');
SELECT state, MIN(donation_amount) FROM Donations GROUP BY state;
Find the indigenous food systems with the highest and lowest water efficiency scores.
CREATE TABLE indigenous_food_systems_we (system_name VARCHAR(255),we_score FLOAT);
SELECT system_name, MAX(we_score) as highest_we_score, MIN(we_score) as lowest_we_score FROM indigenous_food_systems_we GROUP BY system_name;
Insert a new record into the 'public_services' table for 'Waste Collection'
CREATE TABLE public_services (service_id INT,service_name VARCHAR(50),service_frequency VARCHAR(20));
INSERT INTO public_services (service_name) VALUES ('Waste Collection');
Select all records from 'veteran_employment' table
CREATE TABLE veteran_employment (id INT PRIMARY KEY,company VARCHAR(255),location VARCHAR(255),job_title VARCHAR(255),num_veterans INT); INSERT INTO veteran_employment (id,company,location,job_title,num_veterans) VALUES (1,'Lockheed Martin','Arlington,VA','Software Engineer',50),(2,'Raytheon Technologies','Cambridge,MA','Hardware Engineer',35);
SELECT * FROM veteran_employment;
List regions with the lowest energy efficiency and their carbon pricing
CREATE TABLE energy_efficiency (region VARCHAR(20),efficiency INT);CREATE TABLE carbon_pricing (region VARCHAR(20),price DECIMAL(5,2));
SELECT e.region, e.efficiency, c.price FROM energy_efficiency e JOIN carbon_pricing c ON e.region = c.region WHERE e.efficiency = (SELECT MIN(efficiency) FROM energy_efficiency) LIMIT 1;
What is the average weight of adult gorillas in the 'Mountain Gorilla' sanctuary that weigh over 150 kg?
CREATE TABLE gorillas (gorilla_id INT,gorilla_name VARCHAR(50),age INT,weight FLOAT,sanctuary VARCHAR(50)); INSERT INTO gorillas (gorilla_id,gorilla_name,age,weight,sanctuary) VALUES (1,'Gorilla_1',12,130,'Mountain Gorilla'); INSERT INTO gorillas (gorilla_id,gorilla_name,age,weight,sanctuary) VALUES (2,'Gorilla_2',8,180,'Mountain Gorilla');
SELECT AVG(weight) FROM gorillas WHERE sanctuary = 'Mountain Gorilla' AND age >= 18 AND weight > 150;
How many units of ethically produced clothing items were sold in the last month?
CREATE TABLE sales (sale_id INT,product_category VARCHAR(50),units_sold INT,sale_date DATE); INSERT INTO sales (sale_id,product_category,units_sold,sale_date) VALUES (1,'Ethical Clothing',25,'2022-01-01'),(2,'Regular Clothing',30,'2022-01-02'),(3,'Ethical Clothing',20,'2022-01-03');
SELECT SUM(units_sold) FROM sales WHERE product_category = 'Ethical Clothing' AND sale_date >= DATEADD(month, -1, CURRENT_DATE);
Count the number of unique dish categories.
CREATE TABLE dishes (id INT,name TEXT,category TEXT); INSERT INTO dishes (id,name,category) VALUES (1,'Spicy Veggie Burger','Vegan'),(2,'Quinoa Salad','Vegan'),(3,'Beef Tacos','Mexican'),(4,'Chicken Burrito','Mexican'),(5,'Fish and Chips','Seafood');
SELECT COUNT(DISTINCT category) FROM dishes;
What is the average age of community health workers who identify as Indigenous?
CREATE TABLE CommunityHealthWorkers (WorkerID INT,Age INT,Identity VARCHAR(255)); INSERT INTO CommunityHealthWorkers VALUES (1,35,'Indigenous'); INSERT INTO CommunityHealthWorkers VALUES (2,40,'Non-Indigenous');
SELECT Identity, AVG(Age) FROM CommunityHealthWorkers WHERE Identity = 'Indigenous' GROUP BY Identity;
How many users from the 'users' table, who have their location set to 'Canada', have not posted in the 'food' category from the 'posts' table, in the past 30 days?
CREATE TABLE users (user_id INT,user_category VARCHAR(20),user_location VARCHAR(20)); CREATE TABLE posts (post_id INT,user_id INT,post_category VARCHAR(20),post_date DATE);
SELECT COUNT(DISTINCT user_id) FROM users WHERE user_location = 'Canada' AND user_id NOT IN (SELECT user_id FROM posts WHERE post_category = 'food' AND post_date >= CURDATE() - INTERVAL 30 DAY);
Delete all AI safety research papers published before 2015.
CREATE TABLE ai_safety_papers (year INT,paper_title VARCHAR(255),author_name VARCHAR(255)); INSERT INTO ai_safety_papers (year,paper_title,author_name) VALUES ('2014','SafeAI: A Framework for Safe Artificial Intelligence','John Doe');
DELETE FROM ai_safety_papers WHERE year < 2015;
List all restaurants in California that source ingredients from sustainable suppliers.
CREATE TABLE Restaurant (id INT,name VARCHAR(50),type VARCHAR(50),location VARCHAR(50)); INSERT INTO Restaurant (id,name,type,location) VALUES (1,'Plant-Based Bistro','Vegan','California'); INSERT INTO Restaurant (id,name,type,location) VALUES (2,'Seafood Shack','Seafood','Florida'); CREATE TABLE Supplier (id INT,name VARCHAR(50),location VARCHAR(50),sustainable BOOLEAN); INSERT INTO Supplier (id,name,location,sustainable) VALUES (1,'Green Growers','California',true); INSERT INTO Supplier (id,name,location,sustainable) VALUES (2,'Fresh Catch','Florida',false); CREATE TABLE RestaurantSupplier (restaurant_id INT,supplier_id INT); INSERT INTO RestaurantSupplier (restaurant_id,supplier_id) VALUES (1,1);
SELECT Restaurant.name FROM Restaurant INNER JOIN RestaurantSupplier ON Restaurant.id = RestaurantSupplier.restaurant_id INNER JOIN Supplier ON RestaurantSupplier.supplier_id = Supplier.id WHERE Restaurant.location = 'California' AND Supplier.sustainable = true;
What is the maximum weekly wage for union workers in the 'healthcare' sector?
CREATE TABLE union_wages (id INT,sector VARCHAR(20),wage FLOAT); INSERT INTO union_wages (id,sector,wage) VALUES (1,'healthcare',1000),(2,'technology',1500),(3,'healthcare',1200);
SELECT sector, MAX(wage) as max_wage FROM union_wages WHERE sector = 'healthcare' GROUP BY sector;
What is the minimum capacity of any carbon pricing policy in the 'carbon_pricing' schema?
CREATE SCHEMA carbon_pricing; CREATE TABLE carbon_pricing_policies (name TEXT,capacity INTEGER); INSERT INTO carbon_pricing_policies (name,capacity) VALUES ('Policy A',400),('Policy B',800);
SELECT MIN(capacity) FROM carbon_pricing.carbon_pricing_policies;
What is the total revenue generated from garment manufacturing in 'Oceania' in Q1 2022?
CREATE TABLE oceania_manufacturing(region VARCHAR(20),revenue INT,manufacturing_date DATE); INSERT INTO oceania_manufacturing (region,revenue,manufacturing_date) VALUES ('Oceania',4000,'2022-01-01'); INSERT INTO oceania_manufacturing (region,revenue,manufacturing_date) VALUES ('Oceania',5000,'2022-01-02');
SELECT SUM(revenue) FROM oceania_manufacturing WHERE region = 'Oceania' AND manufacturing_date BETWEEN '2022-01-01' AND '2022-03-31';
List all marine protected areas in the Caribbean and the number of species they protect.
CREATE TABLE marine_protected_areas (id INT,name VARCHAR(255),region VARCHAR(255)); CREATE TABLE protected_species (id INT,area_id INT,species_name VARCHAR(255)); INSERT INTO marine_protected_areas (id,name,region) VALUES (1,'Bahamas National Trust','Caribbean'),(2,'Marine Protected Areas in Belize','Caribbean'); INSERT INTO protected_species (id,area_id,species_name) VALUES (1,1,'Queen Conch'),(2,1,'Nassau Grouper'),(3,2,'Queen Conch'),(4,2,'Hawksbill Turtle');
SELECT marine_protected_areas.name, COUNT(DISTINCT protected_species.species_name) FROM marine_protected_areas INNER JOIN protected_species ON marine_protected_areas.id = protected_species.area_id WHERE marine_protected_areas.region = 'Caribbean' GROUP BY marine_protected_areas.name;
What is the total budget for programs in the Middle East and Europe?
CREATE TABLE Programs (id INT,name TEXT,region TEXT,budget FLOAT); INSERT INTO Programs (id,name,region,budget) VALUES (1,'Refugee Support','Middle East',1500.0),(2,'Cultural Exchange','Europe',2500.0);
SELECT SUM(budget) FROM Programs WHERE region IN ('Middle East', 'Europe');
Calculate the average safety rating of cosmetic products in the European market.
CREATE TABLE products (product_id INT,market TEXT,safety_rating FLOAT);
SELECT market, AVG(safety_rating) as avg_safety_rating FROM products WHERE market = 'Europe' GROUP BY market;
How many garments of each type were sold in the last 30 days, ordered by the number of garments sold?
CREATE TABLE garment (garment_id INT,type VARCHAR(50)); CREATE TABLE sales (sales_id INT,sale_date DATE,garment_id INT);
SELECT type, COUNT(*) AS quantity_sold FROM garment INNER JOIN sales ON garment.garment_id = sales.garment_id WHERE sale_date >= CURRENT_DATE - INTERVAL '30 days' GROUP BY type ORDER BY quantity_sold DESC;
How many timber harvests occurred in each year in the 'harvest_year' table?
CREATE TABLE harvest_year (id INT,year INT,quantity INT); INSERT INTO harvest_year (id,year,quantity) VALUES (1,2010,1200),(2,2011,1500),(3,2012,1300),(4,2013,1800);
SELECT year, COUNT(*) FROM harvest_year GROUP BY year;
What is the difference in speed between the fastest and slowest electric vehicles in the 'fleet' table?
CREATE TABLE fleet (id INT,vehicle_type VARCHAR(20),speed FLOAT,date DATE); INSERT INTO fleet (id,vehicle_type,speed,date) VALUES (1,'ElectricCar',80.5,'2022-03-01'); INSERT INTO fleet (id,vehicle_type,speed,date) VALUES (2,'ElectricBike',30.2,'2022-03-01'); INSERT INTO fleet (id,vehicle_type,speed,date) VALUES (3,'ElectricScooter',45.9,'2022-03-01');
SELECT FLOAT(MAX(speed) - MIN(speed)) as speed_difference FROM fleet WHERE vehicle_type LIKE 'Electric%';
How many vessels arrived at a US port with cargo in the last month?
CREATE TABLE Vessels (VesselID INT,VesselName TEXT); CREATE TABLE Ports (PortID INT,PortName TEXT,Country TEXT); CREATE TABLE Cargo (VesselID INT,PortID INT,ArrivalDate DATE); INSERT INTO Ports (PortID,PortName,Country) VALUES (1,'New York','USA'),(2,'Los Angeles','USA'); INSERT INTO Vessels (VesselID,VesselName) VALUES (1,'Sea Tiger'),(2,'Ocean Wave'),(3,'River Queen'); INSERT INTO Cargo (VesselID,PortID,ArrivalDate) VALUES (1,1,'2021-07-01'),(1,2,'2021-07-15'),(2,1,'2021-07-20'),(3,2,'2021-07-25');
SELECT COUNT(*) FROM Cargo INNER JOIN Vessels ON Cargo.VesselID = Vessels.VesselID INNER JOIN Ports ON Cargo.PortID = Ports.PortID WHERE ArrivalDate >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH) AND Country = 'USA';
Identify the number of startups founded by immigrants in the artificial intelligence industry that have received funding.
CREATE TABLE company (id INT,name TEXT,industry TEXT,founding_date DATE,founder_immigrant TEXT); INSERT INTO company (id,name,industry,founding_date,founder_immigrant) VALUES (1,'AIco','Artificial Intelligence','2020-01-01','Yes');
SELECT COUNT(DISTINCT company.id) FROM company JOIN funding_records ON company.id = funding_records.company_id WHERE company.industry = 'Artificial Intelligence' AND company.founder_immigrant = 'Yes';
Display the total number of trips taken by each mode of transportation (car, bus, train, bike) in 'multimodal_mobility' table.
CREATE TABLE multimodal_mobility (id INT,user_id INT,trip_date DATE,mode VARCHAR(10),num_trips INT);
SELECT mode, SUM(num_trips) AS total_trips FROM multimodal_mobility GROUP BY mode;
Insert a new record into the 'oil_refineries' table with the following data: 'Puerto La Cruz', 'Venezuela', 1950, 180000
CREATE TABLE oil_refineries (refinery_name VARCHAR(50),country VARCHAR(50),establishment_year INT,refinery_capacity INT);
INSERT INTO oil_refineries (refinery_name, country, establishment_year, refinery_capacity) VALUES ('Puerto La Cruz', 'Venezuela', 1950, 180000);
What is the average weight of shipments from Canada?
CREATE TABLE Shipments (id INT,weight FLOAT,origin VARCHAR(20)); INSERT INTO Shipments (id,weight,origin) VALUES (1,50.3,'Canada'),(2,70.5,'USA'),(3,30.1,'Canada');
SELECT AVG(weight) FROM Shipments WHERE origin = 'Canada'
What is the total cost for each satellite model?
CREATE TABLE satellites (satellite_id INT,model VARCHAR(100),manufacturer VARCHAR(100),cost DECIMAL(10,2)); INSERT INTO satellites (satellite_id,model,manufacturer,cost) VALUES (1,'SatModel A','Galactic Inc.',200000.00); INSERT INTO satellites (satellite_id,model,manufacturer,cost) VALUES (2,'SatModel B','Cosmic Corp.',350000.00);
SELECT model, SUM(cost) FROM satellites GROUP BY model;
Delete all records from the 'circular_economy' table where the 'reuse_percentage' is less than 50
CREATE TABLE circular_economy (id INT PRIMARY KEY,product_name VARCHAR(100),reuse_percentage INT);
DELETE FROM circular_economy WHERE reuse_percentage < 50;
List the top 5 busiest subway stations in New York by entrances and exits, for the month of January 2022.
CREATE TABLE subway_stations (station_id INT,station_name TEXT,lines TEXT); CREATE TABLE entrances_exits (station_id INT,time TIMESTAMP,entries INT,exits INT);
SELECT station_name, SUM(entries + exits) as total FROM subway_stations JOIN entrances_exits ON subway_stations.station_id = entrances_exits.station_id WHERE time BETWEEN '2022-01-01 00:00:00' AND '2022-01-31 23:59:59' GROUP BY station_name ORDER BY total DESC LIMIT 5;
What is the total number of workplace safety incidents in the "safety_database" for each quarter in 2022?
CREATE TABLE incidents (id INT,quarter INT,num_incidents INT); INSERT INTO incidents (id,quarter,num_incidents) VALUES (1,1,100),(2,1,120),(3,2,150),(4,2,170),(5,3,200),(6,3,220),(7,4,250),(8,4,270);
SELECT quarter, SUM(num_incidents) FROM incidents WHERE quarter BETWEEN 1 AND 4 GROUP BY quarter;
How many clinical trials were conducted by 'CompanyZ' in 2018?
CREATE TABLE sponsor_trials(sponsor_name TEXT,trial_id INT,trial_year INT); INSERT INTO sponsor_trials(sponsor_name,trial_id,trial_year) VALUES('CompanyZ',2,2018);
SELECT COUNT(*) FROM sponsor_trials WHERE sponsor_name = 'CompanyZ' AND trial_year = 2018;
Show the number of startups founded by women in the last 10 years
CREATE TABLE startup (id INT,name TEXT,founding_year INT,founder_gender TEXT); INSERT INTO startup (id,name,founding_year,founder_gender) VALUES (1,'Acme Inc',2012,'Female'); INSERT INTO startup (id,name,founding_year,founder_gender) VALUES (2,'Beta Corp',2018,'Male');
SELECT COUNT(*) FROM startup WHERE founder_gender = 'Female' AND founding_year >= YEAR(CURRENT_DATE) - 10;
What is the total revenue generated from each game genre, and how many games belong to each genre?
CREATE TABLE GameDesign (GameID INT,GameTitle VARCHAR(20),Genre VARCHAR(10),Price DECIMAL(5,2)); INSERT INTO GameDesign (GameID,GameTitle,Genre,Price) VALUES (1,'RacingGame','Racing',29.99),(2,'RPG','RPG',49.99),(3,'Shooter','FPS',39.99),(4,'Puzzle','Puzzle',19.99),(5,'Strategy','Strategy',34.99);
SELECT Genre, SUM(Price) AS TotalRevenue, COUNT(GameID) AS GameCount FROM GameDesign GROUP BY Genre;
What is the average military spending for countries in a specific region?
CREATE TABLE Country (Name VARCHAR(50),Region VARCHAR(50),MilitarySpending NUMERIC(18,2)); INSERT INTO Country (Name,Region,MilitarySpending) VALUES ('United States','North America',770000),('Canada','North America',25000),('Mexico','North America',5000),('Brazil','South America',30000),('Argentina','South America',7000);
SELECT Region, AVG(MilitarySpending) AS AverageMilitarySpending FROM Country GROUP BY Region;
Find the top 3 cities with the most diverse art program attendance (visual arts, performing arts, literature)
CREATE TABLE cities (id INT,name VARCHAR(255)); CREATE TABLE programs (id INT,name VARCHAR(255)); CREATE TABLE attendances (city_id INT,program_id INT); INSERT INTO cities (id,name) VALUES (1,'CityA'),(2,'CityB'),(3,'CityC'); INSERT INTO programs (id,name) VALUES (1,'Visual Arts'),(2,'Performing Arts'),(3,'Literature'); INSERT INTO attendances (city_id,program_id) VALUES (1,1),(1,2),(1,3),(2,1),(2,3),(3,1);
SELECT c.name, COUNT(a.program_id) AS attendance FROM cities c JOIN attendances a ON c.id = a.city_id JOIN programs p ON a.program_id = p.id WHERE p.name IN ('Visual Arts', 'Performing Arts', 'Literature') GROUP BY c.name ORDER BY attendance DESC LIMIT 3
Show the number of safety incidents, the total cost of those incidents, and the incident type for each chemical plant located in a specific region, grouped by incident type.
CREATE TABLE chemical_plants (plant_id INT,plant_name TEXT,location TEXT); CREATE TABLE safety_incidents (incident_id INT,plant_id INT,incident_date DATE,cost INT,incident_type TEXT); INSERT INTO chemical_plants (plant_id,plant_name,location) VALUES (1,'ABC Plant','East'),(2,'XYZ Plant','West'); INSERT INTO safety_incidents (incident_id,plant_id,incident_date,cost,incident_type) VALUES (1,1,'2022-01-01',1000,'Fire'),(2,2,'2021-12-15',2000,'Chemical Spill');
SELECT chemical_plants.location, incident_type, COUNT(safety_incidents.incident_id) AS number_of_incidents, SUM(safety_incidents.cost) AS total_cost FROM chemical_plants INNER JOIN safety_incidents ON chemical_plants.plant_id = safety_incidents.plant_id WHERE chemical_plants.location = 'East' GROUP BY chemical_plants.location, incident_type;
Delete all records of clients who have not invested in Shariah-compliant funds.
CREATE TABLE clients (id INT,name VARCHAR(255)); INSERT INTO clients (id,name) VALUES (1,'John Doe'),(2,'Jane Smith'),(3,'Alice Johnson'),(4,'Bob Brown'); CREATE TABLE investments (id INT,client_id INT,fund_type VARCHAR(255),amount DECIMAL(10,2)); INSERT INTO investments (id,client_id,fund_type,amount) VALUES (1,1,'Shariah-compliant',5000),(2,2,'Standard',3000),(3,4,'Standard',7000);
DELETE FROM clients WHERE id NOT IN (SELECT client_id FROM investments WHERE fund_type = 'Shariah-compliant');
Calculate the average revenue generated per eco-friendly hotel in Portugal.
CREATE TABLE eco_hotels (hotel_id INT,name TEXT,country TEXT,revenue FLOAT); INSERT INTO eco_hotels VALUES (1,'Green Hotel','Portugal',50000),(2,'Eco Resort','Portugal',75000),(3,'Sustainable Hotel','Portugal',60000);
SELECT AVG(revenue) FROM eco_hotels WHERE country = 'Portugal';
Calculate the average temperature and humidity for the greenhouses with the highest energy consumption in the last month.
CREATE TABLE greenhouse (id INT,name VARCHAR(255)); CREATE TABLE sensor (id INT,greenhouse_id INT,temperature INT,humidity INT,energy_consumption INT,timestamp TIMESTAMP); INSERT INTO greenhouse VALUES (1,'Greenhouse A'),(2,'Greenhouse B'); INSERT INTO sensor VALUES (1,1,25,60,1000,'2022-04-01 10:00:00'),(2,2,22,70,1200,'2022-04-01 10:00:00');
SELECT g.name, AVG(s.temperature) as avg_temperature, AVG(s.humidity) as avg_humidity FROM greenhouse g INNER JOIN sensor s ON g.id = s.greenhouse_id WHERE s.energy_consumption = (SELECT MAX(energy_consumption) FROM sensor WHERE timestamp BETWEEN DATE_SUB(NOW(), INTERVAL 1 MONTH) AND NOW()) AND s.timestamp BETWEEN DATE_SUB(NOW(), INTERVAL 1 MONTH) AND NOW() GROUP BY g.name;
What is the maximum number of patients served by a rural clinic in Canada?
CREATE TABLE clinics (id INT,name VARCHAR(50),location VARCHAR(50),patients_served INT);
SELECT MAX(patients_served) FROM clinics WHERE location LIKE '%Canada%' AND location LIKE '%rural%';
Who are the top 10 community health workers with the most clients served?
CREATE TABLE clients_served (worker_id INT,clients_served INT);
SELECT worker_id, clients_served FROM (SELECT worker_id, clients_served, ROW_NUMBER() OVER (ORDER BY clients_served DESC) as rn FROM clients_served) x WHERE rn <= 10;
Find the total installed capacity (in MW) of all Renewable Energy Projects in Germany
CREATE TABLE renewable_projects_germany (id INT,name VARCHAR(100),country VARCHAR(50),type VARCHAR(50),capacity_mw FLOAT); INSERT INTO renewable_projects_germany (id,name,country,type,capacity_mw) VALUES (1,'Project 1','Germany','Wind Farm',50.0),(2,'Project 2','Germany','Solar Plant',75.0),(3,'Project 3','Germany','Hydro Plant',100.0);
SELECT SUM(capacity_mw) FROM renewable_projects_germany WHERE country = 'Germany';
Find the total installed capacity of renewable energy projects in each country, with a minimum threshold of 100 MW.
CREATE TABLE renewable_projects (project_id INT,project_name VARCHAR(100),country VARCHAR(50),installed_capacity FLOAT); CREATE TABLE countries (country VARCHAR(50),continent VARCHAR(50));
SELECT r.country, SUM(r.installed_capacity) FROM renewable_projects r INNER JOIN countries c ON r.country = c.country GROUP BY r.country HAVING SUM(r.installed_capacity) >= 100;
What is the maximum number of articles published by a single author in a day?
CREATE TABLE authors (id INT,name VARCHAR(20)); CREATE TABLE articles (id INT,author_id INT,publication_date DATE); INSERT INTO authors (id,name) VALUES (1,'John Doe'),(2,'Jane Smith'); INSERT INTO articles (id,author_id,publication_date) VALUES (1,1,'2022-01-01'),(2,1,'2022-01-01'),(3,2,'2022-01-02');
SELECT MAX(cnt) FROM (SELECT author_id, COUNT(*) as cnt FROM articles GROUP BY author_id, publication_date) as temp WHERE temp.cnt > 1;
Which retailers in Africa do not carry any fair trade products?
CREATE TABLE retailers (id INT,name TEXT,country TEXT); INSERT INTO retailers (id,name,country) VALUES (1,'Retailer A','South Africa'),(2,'Retailer B','Egypt'),(3,'Retailer C','Nigeria'); CREATE TABLE products (id INT,name TEXT,is_fair_trade BOOLEAN); INSERT INTO products (id,name,is_fair_trade) VALUES (1,'Product X',true),(2,'Product Y',false),(3,'Product Z',true),(4,'Product W',false); CREATE TABLE retailer_products (retailer_id INT,product TEXT,quantity INT); INSERT INTO retailer_products (retailer_id,product,quantity) VALUES (1,'Product X',100),(1,'Product Z',50),(2,'Product Y',150),(3,'Product W',80);
SELECT retailers.name FROM retailers LEFT JOIN retailer_products ON retailers.id = retailer_products.retailer_id LEFT JOIN products ON retailer_products.product = products.name WHERE products.is_fair_trade IS NULL AND retailers.country = 'Africa';
What is the total amount of grants received by 'organization Z' in the year 2023?
CREATE TABLE organization (organization_id INT,name VARCHAR(50)); INSERT INTO organization (organization_id,name) VALUES (1,'Organization X'),(2,'Organization Y'),(3,'Organization Z'); CREATE TABLE year (year_id INT,year INT); INSERT INTO year (year_id,year) VALUES (1,2023),(2,2022); CREATE TABLE grants (grant_id INT,amount INT,organization_id INT,year_id INT); INSERT INTO grants (grant_id,amount,organization_id,year_id) VALUES (1,500,3,1),(2,700,3,1),(3,300,1,1);
SELECT SUM(amount) FROM grants WHERE organization_id = 3 AND year_id = 1;
List the publications with at least two authors from underrepresented communities.
CREATE TABLE publication (id INT,title VARCHAR(100),num_authors INT); CREATE TABLE author (id INT,publication_id INT,community VARCHAR(50));
SELECT p.title FROM publication p JOIN (SELECT publication_id FROM author WHERE community IN ('Community A', 'Community B') GROUP BY publication_id HAVING COUNT(*) >= 2) a ON p.id = a.publication_id;
What is the difference in donation amounts between the top 3 and bottom 3 donor countries?
CREATE TABLE donor_countries (country VARCHAR(50),donation DECIMAL(10,2)); INSERT INTO donor_countries (country,donation) VALUES ('United States',50000.00),('Germany',40000.00),('United Kingdom',30000.00),('France',20000.00),('Canada',10000.00);
SELECT SUM(a.donation) - SUM(b.donation) FROM (SELECT donation FROM donor_countries ORDER BY donation DESC LIMIT 3) a, (SELECT donation FROM donor_countries ORDER BY donation ASC LIMIT 3) b;
What is the total production of Europium, Gadolinium, and Terbium in 2020?
CREATE TABLE production (year INT,element VARCHAR(10),quantity INT); INSERT INTO production (year,element,quantity) VALUES (2018,'Europium',1000),(2019,'Europium',1100),(2020,'Europium',1200),(2021,'Europium',1300),(2018,'Gadolinium',1500),(2019,'Gadolinium',1600),(2020,'Gadolinium',1700),(2021,'Gadolinium',1800),(2018,'Terbium',2000),(2019,'Terbium',2200),(2020,'Terbium',2400),(2021,'Terbium',2600);
SELECT SUM(quantity) FROM production WHERE element IN ('Europium', 'Gadolinium', 'Terbium') AND year = 2020;
What are the names of all bioprocess engineering projects in Europe that have used machine learning techniques?
CREATE TABLE bioprocess_engineering (project_name VARCHAR(255),location VARCHAR(255),method VARCHAR(255)); INSERT INTO bioprocess_engineering (project_name,location,method) VALUES ('ProjEurope','Europe','Machine Learning');
SELECT project_name FROM bioprocess_engineering WHERE location = 'Europe' AND method = 'Machine Learning';
Add a new station to 'stations' table
CREATE TABLE stations (id INT PRIMARY KEY,name VARCHAR(50),location VARCHAR(100));
INSERT INTO stations (id, name, location) VALUES (1, 'Central', 'Downtown');
Delete all records of food safety inspection for 'Italian' cuisine
CREATE TABLE food_safety_inspections (record_id INT,inspection_date DATE,cuisine VARCHAR(255),violation_count INT); INSERT INTO food_safety_inspections (record_id,inspection_date,cuisine,violation_count) VALUES (1,'2022-01-01','Italian',3),(2,'2022-01-15','Mexican',0),(3,'2022-03-01','French',1),(4,'2022-04-01','Thai',2),(5,'2022-04-15','Italian',1);
DELETE FROM food_safety_inspections WHERE cuisine = 'Italian';