instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
Find the number of offshore drilling platforms for each country in the OilRig table
CREATE TABLE OilRig (RigID int,RigName varchar(50),DrillingType varchar(50),WaterDepth int,Country varchar(50));
SELECT Country, COUNT(*) as Num_Offshore_Rigs FROM OilRig WHERE DrillingType = 'Offshore' GROUP BY Country;
Show the daily maintenance records for buses with registration numbers starting with 'A' in the first quarter of 2021
CREATE TABLE buses (id INT PRIMARY KEY,registration_number VARCHAR(10),next_maintenance_date DATE);
SELECT DATE(next_maintenance_date) AS maintenance_date, registration_number FROM buses WHERE registration_number LIKE 'A%' AND next_maintenance_date >= '2021-01-01' AND next_maintenance_date < '2021-04-01';
What is the total amount of relief aid provided by 'Red Cross' for disasters not related to 'Floods'?
CREATE TABLE Relief_Aid (id INT,disaster_id INT,organization VARCHAR(50),amount FLOAT,date DATE); INSERT INTO Relief_Aid (id,disaster_id,organization,amount,date) VALUES (7,8,'Red Cross',12000,'2021-07-01'); CREATE TABLE Disaster (id INT,name VARCHAR(50),location VARCHAR(50),type VARCHAR(50),start_date DATE,end_date ...
SELECT SUM(Relief_Aid.amount) FROM Relief_Aid WHERE Relief_Aid.organization = 'Red Cross' AND Relief_Aid.disaster_id NOT IN (SELECT Disaster.id FROM Disaster WHERE Disaster.type = 'Flood')
List the unique industries of startups that have at least one female founder and have received funding.
CREATE TABLE startups (id INT,name VARCHAR(255),founding_year INT,founder_gender VARCHAR(10),industry VARCHAR(255)); INSERT INTO startups (id,name,founding_year,founder_gender,industry) VALUES (1,'Kilo Lima',2015,'Female','Tech'),(2,'Mike November',2017,'Male','Retail'),(3,'November Oscar',2018,'Female','Tech'); CREATE...
SELECT DISTINCT startups.industry FROM startups INNER JOIN funding ON startups.id = funding.startup_id WHERE startups.founder_gender = 'Female';
What is the percentage of uninsured individuals by race and ethnicity, and how does it compare to the overall percentage?
CREATE TABLE RaceEthnicityData (RaceEthnicity VARCHAR(255),Uninsured DECIMAL(3,1)); INSERT INTO RaceEthnicityData (RaceEthnicity,Uninsured) VALUES ('Asian',5.0),('Black',12.0),('Hispanic',18.0),('White',8.0); CREATE TABLE OverallData (OverallUninsured DECIMAL(3,1)); INSERT INTO OverallData (OverallUninsured) VALUES (10...
SELECT RaceEthnicity, Uninsured, Uninsured * 100.0 / (SELECT OverallUninsured FROM OverallData) AS Percentage FROM RaceEthnicityData;
What are the names and number of employees of organizations in the ethical AI sector that have been granted funding from the European Commission in Europe?
CREATE TABLE orgs (org_id INT,name VARCHAR(50),employees INT,sector VARCHAR(50)); CREATE TABLE funding_source (funding_source_id INT,name VARCHAR(50)); CREATE TABLE funding (funding_id INT,org_id INT,funding_source_id INT,funded_country VARCHAR(50)); INSERT INTO orgs (org_id,name,employees,sector) VALUES (1,'OrgX',100,...
SELECT o.name, COUNT(f.org_id) FROM orgs o JOIN funding f ON o.org_id = f.org_id JOIN funding_source fs ON f.funding_source_id = fs.funding_source_id WHERE o.sector = 'ethical AI' AND fs.name = 'European Commission' AND f.funded_country = 'Europe' GROUP BY o.name;
Identify the number of mobile subscribers in each region and their average monthly usage
CREATE TABLE mobile_subscribers (subscriber_id INT,subscriber_type VARCHAR(10),region VARCHAR(10),usage FLOAT);
SELECT region, COUNT(*), AVG(usage) FROM mobile_subscribers GROUP BY region;
What is the total number of repeat attendees for visual arts programs, and how does this number vary by age group?
CREATE TABLE VisualArtsPrograms (ProgramID INT,ProgramName VARCHAR(50),Date DATE); CREATE TABLE Attendees (AttendeeID INT,AttendeeName VARCHAR(50),Age INT,ProgramID INT,FirstAttendance DATE,LastAttendance DATE,FOREIGN KEY (ProgramID) REFERENCES VisualArtsPrograms(ProgramID));
SELECT AVG(Attendees.Age), COUNT(DISTINCT Attendees.AttendeeID) FROM Attendees WHERE DATEDIFF(Attendees.LastAttendance, Attendees.FirstAttendance) > 365 GROUP BY (Attendees.Age / 10) * 10;
What is the maximum, minimum, and average military spending per capita for countries involved in peacekeeping operations?
CREATE TABLE peacekeeping_operations (id INT,country VARCHAR,military_spending FLOAT,population INT);
SELECT country, MAX(military_spending / population) AS max_military_spending_per_capita, MIN(military_spending / population) AS min_military_spending_per_capita, AVG(military_spending / population) AS avg_military_spending_per_capita FROM peacekeeping_operations GROUP BY country;
Find the maximum production volume for wells in the Caspian Sea in 2021.
CREATE TABLE wells (id INT,location VARCHAR(20),volume INT,date DATE); INSERT INTO wells (id,location,volume,date) VALUES (1,'Caspian Sea',1200,'2021-01-01'); INSERT INTO wells (id,location,volume,date) VALUES (2,'Caspian Sea',2300,'2021-02-01'); INSERT INTO wells (id,location,volume,date) VALUES (3,'Caspian Sea',3400,...
SELECT MAX(volume) FROM wells WHERE location = 'Caspian Sea' AND YEAR(date) = 2021;
What is the total area of properties in the city of Boston with a sustainable urbanism rating above 7?
CREATE TABLE properties (id INT,area FLOAT,city VARCHAR(20),sustainable_urbanism_rating INT); INSERT INTO properties (id,area,city,sustainable_urbanism_rating) VALUES (1,1500,'Boston',8),(2,1200,'Boston',7),(3,1800,'Boston',9),(4,1100,'Chicago',6),(5,1400,'Boston',7.5);
SELECT SUM(area) FROM properties WHERE city = 'Boston' AND sustainable_urbanism_rating > 7;
List all projects in the "public" schema that have a name that contains the substring "ex" and have a start date within the last 30 days?
CREATE TABLE IF NOT EXISTS public.projects2 (id SERIAL PRIMARY KEY,name TEXT,start_date DATE); INSERT INTO public.projects2 (name,start_date) SELECT 'ExampleProject3',CURRENT_DATE - INTERVAL '10 days' FROM generate_series(1,10); INSERT INTO public.projects2 (name,start_date) SELECT 'ExampleProject4',CURRENT_DATE - INTE...
SELECT name, start_date FROM public.projects2 WHERE name ILIKE '%ex%' AND start_date >= CURRENT_DATE - INTERVAL '30 days';
What was the average donation amount for recurring donors in 2022?
CREATE TABLE Recurring_Donors (donor_id INT,donation_amount DECIMAL(10,2),donation_frequency INT,first_donation_date DATE);
SELECT AVG(donation_amount) FROM Recurring_Donors WHERE donor_id IN (SELECT donor_id FROM Recurring_Donors GROUP BY donor_id HAVING COUNT(*) > 1) AND first_donation_date < '2022-01-01';
Show the total economic impact of tourism in New York City, including direct and indirect effects.
CREATE TABLE EconomicImpact (region VARCHAR(50),impact FLOAT,direct BOOLEAN); INSERT INTO EconomicImpact (region,impact,direct) VALUES ('New York City',250000.00,true),('New York City',125000.00,false);
SELECT SUM(impact) FROM EconomicImpact WHERE region = 'New York City';
What is the number of unique countries represented in the 'readers' table?
CREATE TABLE readers (id INT,name VARCHAR(50),age INT,gender VARCHAR(10),country VARCHAR(50));
SELECT COUNT(DISTINCT country) FROM readers;
Which menu item had the highest revenue in February 2022?
CREATE TABLE menu_engineering (item VARCHAR(255),revenue FLOAT,month VARCHAR(9)); INSERT INTO menu_engineering (item,revenue,month) VALUES ('Burger',3000,'February-2022'),('Pizza',2500,'February-2022'),('Salad',2000,'February-2022');
SELECT item, MAX(revenue) FROM menu_engineering WHERE month = 'February-2022';
What is the total capacity of hospitals and clinics in the Midwest region?
CREATE TABLE hospitals (id INT,name TEXT,region TEXT,capacity INT); INSERT INTO hospitals (id,name,region,capacity) VALUES (1,'Hospital A','Midwest',200),(2,'Hospital B','Midwest',300),(3,'Clinic C','Northeast',50),(4,'Hospital D','West',250),(5,'Clinic E','South',40);
SELECT SUM(capacity) FROM hospitals WHERE region = 'Midwest';
Update the is_vegan column to true for all items in the menu_items table with 'vegetable stir-fry' as the name
CREATE TABLE menu_items (menu_item_id INT,name VARCHAR(50),description TEXT,price DECIMAL(5,2),category VARCHAR(20),is_vegan BOOLEAN);
UPDATE menu_items SET is_vegan = TRUE WHERE name = 'vegetable stir-fry';
How many paintings were created per year by artists from different countries?
CREATE TABLE artists (id INT,name VARCHAR(50),country VARCHAR(50)); INSERT INTO artists (id,name,country) VALUES (1,'Frida Kahlo','Mexico'); INSERT INTO artists (id,name,country) VALUES (2,'Pablo Picasso','Spain'); CREATE TABLE paintings (id INT,artist_id INT,year INT); INSERT INTO paintings (id,artist_id,year) VALUES ...
SELECT p.year, country, COUNT(p.id) as paintings_per_year FROM paintings p JOIN artists a ON p.artist_id = a.id GROUP BY p.year, country;
Update the room rates for hotels in Barcelona with an ID greater than 3.
CREATE TABLE hotel_rooms (hotel_id INT,city VARCHAR(50),room_rate DECIMAL(5,2)); INSERT INTO hotel_rooms (hotel_id,city,room_rate) VALUES (1,'Barcelona',100),(2,'Barcelona',120),(3,'Barcelona',150),(4,'Madrid',80);
UPDATE hotel_rooms SET room_rate = room_rate * 1.1 WHERE city = 'Barcelona' AND hotel_id > 3;
What is the average property price in the eco-friendly communities?
CREATE TABLE eco_communities (community_id INT,property_id INT,price DECIMAL(10,2)); INSERT INTO eco_communities (community_id,property_id,price) VALUES (1,101,500000.00),(1,102,550000.00),(2,201,400000.00),(2,202,420000.00);
SELECT AVG(price) FROM eco_communities;
How many tourists visited Japan in 2020 and 2021 combined?
CREATE TABLE tourism_stats (visitor_country VARCHAR(20),year INT,tourists INT); INSERT INTO tourism_stats (visitor_country,year,tourists) VALUES ('Japan',2020,800),('Japan',2021,900),('Japan',2019,1000);
SELECT SUM(tourists) FROM (SELECT tourists FROM tourism_stats WHERE visitor_country = 'Japan' AND year IN (2020, 2021)) subquery;
Which creative AI applications have been cited the least, by year of release?
CREATE TABLE citation_data (application VARCHAR(255),year INT,citations INT); INSERT INTO citation_data (application,year,citations) VALUES ('App7',2018,30); INSERT INTO citation_data (application,year,citations) VALUES ('App8',2019,45); INSERT INTO citation_data (application,year,citations) VALUES ('App9',2020,55); IN...
SELECT application, year, citations, RANK() OVER (PARTITION BY year ORDER BY citations ASC) as rank FROM citation_data ORDER BY year, citations;
How many basic memberships were sold in each country in the first quarter of 2021?
CREATE TABLE Countries (CountryID INT,CountryName VARCHAR(50)); CREATE TABLE Members (MemberID INT,MemberName VARCHAR(50),CountryID INT,JoinDate DATE,MembershipType VARCHAR(50),MembershipFee DECIMAL(5,2));
SELECT c.CountryName, COUNT(m.MemberID) AS BasicMemberships FROM Countries c INNER JOIN Members m ON c.CountryID = m.CountryID WHERE m.MembershipType = 'Basic' AND YEAR(m.JoinDate) = 2021 AND QUARTER(m.JoinDate) = 1 GROUP BY c.CountryName;
List all volunteers who have contributed more than 15 hours in total, along with their corresponding organization names and the causes they supported.
CREATE TABLE volunteers (id INT,name VARCHAR(100),organization_id INT,cause VARCHAR(50),hours DECIMAL(5,2)); INSERT INTO volunteers VALUES (1,'Jose Garcia',3,'Human Rights',20); INSERT INTO volunteers VALUES (2,'Sophia Kim',4,'Children',18);
SELECT v.name, o.name as organization_name, v.cause, SUM(v.hours) as total_hours FROM volunteers v INNER JOIN organizations o ON v.organization_id = o.id GROUP BY v.name, v.organization_id, v.cause HAVING SUM(v.hours) > 15;
Compare production trends between offshore and onshore wells
CREATE TABLE if not exists fact_production (production_id INT PRIMARY KEY,well_id INT,date DATE,oil_volume DECIMAL(10,2),gas_volume DECIMAL(10,2)); CREATE TABLE if not exists dim_well (well_id INT PRIMARY KEY,well_name VARCHAR(255),location VARCHAR(255)); CREATE TABLE if not exists dim_date (date DATE PRIMARY KEY,year ...
SELECT dim_well.location, AVG(fact_production.oil_volume) AS avg_oil_volume, AVG(fact_production.gas_volume) AS avg_gas_volume FROM fact_production INNER JOIN dim_well ON fact_production.well_id = dim_well.well_id INNER JOIN dim_date ON fact_production.date = dim_date.date GROUP BY dim_well.location WITH ROLLUP;
Find the banks with the highest and lowest average financial capability scores among their customers.
CREATE TABLE banks_customers (bank_id INT,customer_id INT,financial_capability_score INT); INSERT INTO banks_customers (bank_id,customer_id,financial_capability_score) VALUES (1,1,85),(1,2,70),(2,3,90),(2,4,60),(3,5,80);
SELECT b.name, AVG(bc.financial_capability_score) as avg_score FROM banks_customers bc JOIN banks b ON bc.bank_id = b.id GROUP BY b.id ORDER BY avg_score DESC, b.name LIMIT 1; SELECT b.name, AVG(bc.financial_capability_score) as avg_score FROM banks_customers bc JOIN banks b ON bc.bank_id = b.id GROUP BY b.id ORDER BY...
What is the minimum number of attendees at a cultural event in Tokyo?
CREATE TABLE events (id INT,name TEXT,location TEXT,attendance INT); INSERT INTO events (id,name,location,attendance) VALUES (1,'Festival A','Tokyo',500),(2,'Conference B','London',300),(3,'Exhibition C','Tokyo',700);
SELECT MIN(attendance) FROM events WHERE location = 'Tokyo';
What is the average co-ownership cost per square foot, partitioned by property type, in the 'green_co_ownership' table, ordered by cost?
CREATE TABLE green_co_ownership (id INT,city VARCHAR(255),co_ownership_cost DECIMAL(10,2),size INT,property_type VARCHAR(255)); INSERT INTO green_co_ownership (id,city,co_ownership_cost,size,property_type) VALUES (1,'Amsterdam',650000,1300,'Apartment'),(2,'Berlin',500000,1700,'House');
SELECT property_type, AVG(co_ownership_cost / size) OVER (PARTITION BY property_type ORDER BY co_ownership_cost) AS avg_cost_per_sqft FROM green_co_ownership;
Who is the contact person for the AI for Social Equality project?
CREATE TABLE ai_for_social_equality (id INT,project_name VARCHAR(255),contact_person VARCHAR(255)); INSERT INTO ai_for_social_equality (id,project_name,contact_person) VALUES (1,'AI for Social Equality','Jamal Williams'),(2,'AI for Minority Rights','Sofia Garcia');
SELECT contact_person FROM ai_for_social_equality WHERE project_name = 'AI for Social Equality';
What is the maximum and minimum technology accessibility score for each country?
CREATE TABLE accessibility_scores (id INT,country VARCHAR(50),score INT);INSERT INTO accessibility_scores (id,country,score) VALUES (1,'USA',80),(2,'Canada',85),(3,'Mexico',70);
SELECT country, MAX(score) as max_score, MIN(score) as min_score FROM accessibility_scores GROUP BY country;
How many Arctic fox dens in Norway are experiencing negative socio-economic impacts due to climate change?
CREATE TABLE ArcticFoxDens(den TEXT,socio_economic_impact TEXT,climate_change_impact TEXT); INSERT INTO ArcticFoxDens(den,socio_economic_impact,climate_change_impact) VALUES ('Troms','High','Very High'),('Finnmark','Medium','High');
SELECT COUNT(*) FROM ArcticFoxDens WHERE socio_economic_impact = 'High' AND climate_change_impact = 'High' OR socio_economic_impact = 'Very High' AND climate_change_impact = 'Very High';
What is the average agricultural innovation metric for female farmers in Southeast Asia, ranked by country?
CREATE TABLE Farmers_SEA (FarmerID INT,Country VARCHAR(20),Gender VARCHAR(10),Metric FLOAT); INSERT INTO Farmers_SEA (FarmerID,Country,Gender,Metric) VALUES (1,'Indonesia','Female',4.1),(2,'Thailand','Female',3.5),(3,'Vietnam','Female',4.6),(4,'Philippines','Female',3.9),(5,'Malaysia','Female',4.7),(6,'Myanmar','Female...
SELECT Country, AVG(Metric) as Avg_Metric FROM Farmers_SEA WHERE Country IN ('Indonesia', 'Thailand', 'Vietnam', 'Philippines', 'Malaysia', 'Myanmar') AND Gender = 'Female' GROUP BY Country ORDER BY Avg_Metric DESC;
How many Smart City initiatives were implemented in each country?
CREATE TABLE Countries (id INT,name VARCHAR(50)); INSERT INTO Countries (id,name) VALUES (1,'CountryA'),(2,'CountryB'); CREATE TABLE SmartCities (id INT,country_id INT,initiative_count INT); INSERT INTO SmartCities (id,country_id,initiative_count) VALUES (1,1,5),(2,1,3),(3,2,7);
SELECT Countries.name, SUM(SmartCities.initiative_count) FROM Countries INNER JOIN SmartCities ON Countries.id = SmartCities.country_id GROUP BY Countries.name;
List all cases and the number of associated bills.
CREATE TABLE cases (case_id INT,case_type VARCHAR(255)); INSERT INTO cases (case_id,case_type) VALUES (1,'Civil'),(2,'Criminal'); CREATE TABLE billing (bill_id INT,case_id INT,amount DECIMAL(10,2)); INSERT INTO billing (bill_id,case_id,amount) VALUES (1,1,500.00),(2,1,250.00),(3,2,750.00);
SELECT c.case_id, c.case_type, COUNT(b.bill_id) as num_bills FROM cases c LEFT OUTER JOIN billing b ON c.case_id = b.case_id GROUP BY c.case_id, c.case_type;
Add a new record to the broadband_usage table
CREATE TABLE broadband_usage (usage_id INT,subscriber_id INT,usage_start_time TIMESTAMP,usage_end_time TIMESTAMP,data_used DECIMAL(10,2));
INSERT INTO broadband_usage (usage_id, subscriber_id, usage_start_time, usage_end_time, data_used) VALUES (11111, 12345, '2022-01-01 08:00:00', '2022-01-01 09:00:00', 123.45);
Which cruelty-free makeup products have the most sales?
CREATE TABLE sales_data (product_id INT,product_name TEXT,is_cruelty_free BOOLEAN,units_sold INT); INSERT INTO sales_data (product_id,product_name,is_cruelty_free,units_sold) VALUES (1,'Mascara',TRUE,200),(2,'Lipstick',FALSE,150),(3,'Eyeshadow',TRUE,250),(4,'Foundation',FALSE,300),(5,'Blush',TRUE,350);
SELECT product_name, units_sold, RANK() OVER (PARTITION BY is_cruelty_free ORDER BY units_sold DESC) as sales_rank FROM sales_data WHERE is_cruelty_free = TRUE;
How many local artisans are there in Barcelona's Gothic Quarter?
CREATE TABLE local_artisans (artisan_id INT,name TEXT,district TEXT); INSERT INTO local_artisans (artisan_id,name,district) VALUES (1,'Marta','Gothic Quarter'),(2,'Pedro','El Raval');
SELECT COUNT(*) FROM local_artisans WHERE district = 'Gothic Quarter';
Show the total budget for each department in the city of Chicago for the year 2020
CREATE TABLE city_departments (dept_id INT,dept_name VARCHAR(50),city VARCHAR(20),year INT,budget INT); INSERT INTO city_departments (dept_id,dept_name,city,year,budget) VALUES (1,'Chicago Public Schools','Chicago',2020,80000);
SELECT dept_name, SUM(budget) FROM city_departments WHERE city = 'Chicago' AND year = 2020 GROUP BY dept_name;
find the maximum mass of spacecraft manufactured by each country
CREATE TABLE Spacecraft_Manufacturing(name VARCHAR(50),mass FLOAT,country VARCHAR(50));
CREATE VIEW Spacecraft_Max_Mass AS SELECT country, MAX(mass) AS max_mass FROM Spacecraft_Manufacturing GROUP BY country;
What is the maximum prize pool for esports events in Europe?
CREATE TABLE PrizePools (EventID INT,Region VARCHAR(50),PrizePool INT); INSERT INTO PrizePools (EventID,Region,PrizePool) VALUES (1,'North America',100000),(2,'Europe',150000),(3,'Asia',200000);
SELECT MAX(PrizePool) FROM PrizePools WHERE Region = 'Europe';
What is the total quantity of fish farmed in Africa by farmers who are below 30 years old?
CREATE TABLE Farmers (FarmerID INT,Name VARCHAR(50),Age INT,Country VARCHAR(50)); INSERT INTO Farmers (FarmerID,Name,Age,Country) VALUES (1,'Aliou Diagne',28,'Senegal'); INSERT INTO Farmers (FarmerID,Name,Age,Country) VALUES (2,'Oluremi Adebayo',35,'Nigeria');
SELECT SUM(Quantity) FROM FishStock fs JOIN Farmers f ON fs.FarmerID = f.FarmerID WHERE f.Country = 'Africa' AND f.Age < 30;
Show the number of active volunteers per month for the last 12 months.
CREATE TABLE VolunteerActivity (ActivityID int,VolunteerID int,ActivityDate date);
SELECT DATEPART(YEAR, ActivityDate) as Year, DATEPART(MONTH, ActivityDate) as Month, COUNT(DISTINCT VolunteerID) as ActiveVolunteers FROM VolunteerActivity WHERE ActivityDate >= DATEADD(YEAR, -1, GETDATE()) GROUP BY DATEPART(YEAR, ActivityDate), DATEPART(MONTH, ActivityDate) ORDER BY Year, Month;
Which European country had the highest average international visitor spending in 2019?
CREATE TABLE Country (CountryID INT,CountryName VARCHAR(100),Continent VARCHAR(50)); INSERT INTO Country (CountryID,CountryName,Continent) VALUES (1,'France','Europe'),(2,'Germany','Europe'),(3,'Italy','Europe'); CREATE TABLE InternationalVisitors (VisitorID INT,CountryID INT,Year INT,Spending DECIMAL(10,2)); INSERT IN...
SELECT Context.CountryName, AVG(InternationalVisitors.Spending) FROM Country AS Context INNER JOIN InternationalVisitors ON Context.CountryID = InternationalVisitors.CountryID WHERE Context.Continent = 'Europe' AND InternationalVisitors.Year = 2019 GROUP BY Context.CountryID ORDER BY AVG(InternationalVisitors.Spending)...
Which rare earth elements have the highest market value?
CREATE TABLE element_market_value (element VARCHAR(50),market_value DECIMAL(10,2)); INSERT INTO element_market_value (element,market_value) VALUES ('Neodymium',110.54),('Praseodymium',72.34),('Dysprosium',143.87),('Samarium',51.76),('Gadolinium',42.58);
SELECT element FROM element_market_value ORDER BY market_value DESC LIMIT 3;
What is the total waste generated by non-recyclable packaging materials?
CREATE TABLE inventory (ingredient_id INT,ingredient_name VARCHAR(50),packaging_type VARCHAR(50),quantity INT); INSERT INTO inventory VALUES (1,'Tomatoes','Plastic',100),(2,'Chicken','Cardboard',50),(3,'Lettuce','Biodegradable',80); CREATE TABLE packaging (packaging_id INT,packaging_type VARCHAR(50),is_recyclable BOOLE...
SELECT SUM(quantity) FROM inventory INNER JOIN packaging ON inventory.packaging_type = packaging.packaging_type WHERE packaging.is_recyclable = false;
Identify the language preservation initiatives with the highest and lowest engagement scores in Africa, ordered by score.
CREATE TABLE Languages (Language VARCHAR(255),Country VARCHAR(255),EngagementScore INT);
SELECT Language, EngagementScore FROM (SELECT Language, Country, EngagementScore, ROW_NUMBER() OVER (ORDER BY EngagementScore DESC) AS Rank, COUNT(*) OVER () AS TotalRows FROM Languages WHERE Country = 'Africa') AS LanguageRanks WHERE Rank = 1 OR Rank = TotalRows;
What is the average time between login attempts for all users?
CREATE TABLE login_attempts (user_id INT,timestamp TIMESTAMP); INSERT INTO login_attempts (user_id,timestamp) VALUES (1,'2022-01-01 10:00:00'),(2,'2022-01-02 15:30:00'),(1,'2022-01-03 08:45:00'),(3,'2022-01-04 14:20:00'),(4,'2022-01-05 21:00:00'),(1,'2022-01-06 06:15:00'),(5,'2022-01-07 12:30:00'),(1,'2022-01-07 19:45:...
SELECT AVG(time_between_login_attempts) as avg_time_between_login_attempts FROM (SELECT user_id, TIMESTAMPDIFF(SECOND, LAG(timestamp) OVER (PARTITION BY user_id ORDER BY timestamp), timestamp) as time_between_login_attempts FROM login_attempts) as login_attempts_time_diff;
How many crimes were reported in the last month in the 'Downtown' district?
CREATE TABLE districts (district_id INT,district_name TEXT);CREATE TABLE crimes (crime_id INT,district_id INT,crime_date DATE);
SELECT COUNT(*) FROM crimes WHERE district_id = (SELECT district_id FROM districts WHERE district_name = 'Downtown') AND crime_date >= DATEADD(month, -1, GETDATE());
Delete records from the 'autonomous_vehicles' table where the 'manufacturing_country' is 'Germany'
CREATE TABLE autonomous_vehicles (id INT,model VARCHAR(50),manufacturing_country VARCHAR(50));
DELETE FROM autonomous_vehicles WHERE manufacturing_country = 'Germany';
What is the total budget allocated for inclusion efforts in disability services in the North and South regions?
CREATE TABLE Inclusion_Efforts (region VARCHAR(255),budget INT); INSERT INTO Inclusion_Efforts (region,budget) VALUES ('North',1000000),('North',1200000),('South',1500000),('South',1800000),('East',800000);
SELECT SUM(budget) FROM Inclusion_Efforts WHERE region IN ('North', 'South');
Create a table named 'recycling_initiatives'
CREATE TABLE recycling_initiatives (country VARCHAR(50),year INT,initiative_metric INT);
CREATE TABLE recycling_initiatives ( country VARCHAR(50), year INT, initiative_metric INT);
What is the number of clean energy policy trends in the 'clean_energy_policy' schema for each region in the 'regions' table?
CREATE TABLE clean_energy_policy (id INT,name VARCHAR(50),region_id INT); CREATE TABLE regions (id INT,name VARCHAR(50)); INSERT INTO clean_energy_policy (id,name,region_id) VALUES (1,'Policy 1',1),(2,'Policy 2',2),(3,'Policy 3',3); INSERT INTO regions (id,name) VALUES (1,'Region A'),(2,'Region B'),(3,'Region C');
SELECT regions.name, COUNT(*) FROM clean_energy_policy INNER JOIN regions ON clean_energy_policy.region_id = regions.id GROUP BY regions.name;
What is the total donation amount per category in 2022?
CREATE TABLE Donations (donation_id INT,donor_id INT,donation_category VARCHAR(50),donation_amount DECIMAL(10,2),donation_date DATE); INSERT INTO Donations (donation_id,donor_id,donation_category,donation_amount,donation_date) VALUES (1,1,'Education',500.00,'2022-07-15'),(2,2,'Healthcare',300.00,'2022-09-01'),(3,1,'Edu...
SELECT donation_category, SUM(donation_amount) as total_donation_amount_per_category_in_2022 FROM Donations WHERE donation_date BETWEEN '2022-01-01' AND '2022-12-31' GROUP BY donation_category;
Which drug has the highest R&D cost among all drugs approved in Europe?
CREATE TABLE drug (drug_id INT,drug_name TEXT,rd_cost FLOAT,approval_region TEXT); INSERT INTO drug (drug_id,drug_name,rd_cost,approval_region) VALUES (1,'DrugA',20000000,'Europe'),(2,'DrugB',30000000,'US'),(3,'DrugC',15000000,'Europe');
SELECT drug_name FROM drug WHERE rd_cost = (SELECT MAX(rd_cost) FROM drug WHERE approval_region = 'Europe');
What is the total production of the 'Platinum Mine 1' in the 'platinum_mines' table?
CREATE TABLE platinum_mines (id INT,name TEXT,location TEXT,production INT); INSERT INTO platinum_mines (id,name,location,production) VALUES (1,'Platinum Mine 1','Country X',1200); INSERT INTO platinum_mines (id,name,location,production) VALUES (2,'Platinum Mine 2','Country Y',1500);
SELECT SUM(production) FROM platinum_mines WHERE name = 'Platinum Mine 1';
What is the percentage of women who received the HPV vaccine in Texas compared to the national average?
CREATE TABLE vaccine_administration (patient_id INT,vaccine TEXT,gender TEXT,state TEXT); INSERT INTO vaccine_administration (patient_id,vaccine,gender,state) VALUES (1,'HPV','Female','Texas'); INSERT INTO vaccine_administration (patient_id,vaccine,gender,state) VALUES (2,'HPV','Male','California');
SELECT (COUNT(*) FILTER (WHERE state = 'Texas')) * 100.0 / (SELECT COUNT(*) FROM vaccine_administration WHERE vaccine = 'HPV' AND gender = 'Female') AS percentage FROM vaccine_administration WHERE vaccine = 'HPV' AND gender = 'Female';
What is the average attendance for games featuring the LA Lakers?
CREATE TABLE teams (id INT,name TEXT,city TEXT); INSERT INTO teams (id,name,city) VALUES (4,'LA Lakers','Los Angeles'); CREATE TABLE games (id INT,home_team_id INT,away_team_id INT,attendance INT);
SELECT AVG(attendance) FROM games WHERE home_team_id = (SELECT id FROM teams WHERE name = 'LA Lakers' AND city = 'Los Angeles') OR away_team_id = (SELECT id FROM teams WHERE name = 'LA Lakers' AND city = 'Los Angeles');
What is the average quantity of cannabis produced per day for each cultivation license in the state of Michigan, ordered from highest to lowest average quantity?
CREATE TABLE Licenses2 (LicenseID int,LicenseName varchar(255),LicenseNumber varchar(255),State varchar(255)); INSERT INTO Licenses2 (LicenseID,LicenseName,LicenseNumber,State) VALUES (1,'Michigan Greens','MI001','Michigan'); INSERT INTO Licenses2 (LicenseID,LicenseName,LicenseNumber,State) VALUES (2,'Northern Lights',...
SELECT Licenses2.LicenseName, AVG(Production4.Quantity/DATEDIFF(day, MIN(ProductionDate), MAX(ProductionDate))) AS AvgDailyQuantity FROM Licenses2 INNER JOIN Production4 ON Licenses2.LicenseID = Production4.LicenseID WHERE Licenses2.State = 'Michigan' GROUP BY Licenses2.LicenseName ORDER BY AvgDailyQuantity DESC;
Count the number of meat and pantry items
CREATE TABLE ingredients (id INT,name TEXT,category TEXT); INSERT INTO ingredients (id,name,category) VALUES (1,'Tomato','Produce'),(2,'Olive Oil','Pantry'),(3,'Chicken Breast','Meat'),(4,'Salt','Pantry');
SELECT SUM(CASE WHEN category IN ('Meat', 'Pantry') THEN 1 ELSE 0 END) FROM ingredients;
What is the total volume of trees in the 'TemperateRainforest' table that are taller than 100 feet?
CREATE TABLE TemperateRainforest (id INT,species VARCHAR(255),diameter FLOAT,height FLOAT,volume FLOAT); INSERT INTO TemperateRainforest (id,species,diameter,height,volume) VALUES (1,'Redwood',5.6,350,23.4); INSERT INTO TemperateRainforest (id,species,diameter,height,volume) VALUES (2,'DouglasFir',3.9,120,17.2);
SELECT SUM(volume) FROM TemperateRainforest WHERE height > 100;
List the departments and number of employees in each, ordered by the number of employees.
CREATE TABLE Employees (EmployeeID INT,Department VARCHAR(50)); INSERT INTO Employees (EmployeeID,Department) VALUES (1,'HR'),(2,'IT'),(3,'IT'),(4,'HR'),(5,'Marketing'),(6,'Finance'),(7,'Finance');
SELECT Department, COUNT(*) AS EmployeeCount FROM Employees GROUP BY Department ORDER BY EmployeeCount DESC;
Get the 'algorithm' and 'recall' values for records with 'precision' > 0.9 in the 'evaluation_data' table
CREATE TABLE evaluation_data (id INT,algorithm VARCHAR(20),precision DECIMAL(3,2),recall DECIMAL(3,2)); INSERT INTO evaluation_data (id,algorithm,precision,recall) VALUES (1,'Random Forest',0.92,0.85),(2,'XGBoost',0.95,0.87),(3,'Naive Bayes',0.88,0.83);
SELECT algorithm, recall FROM evaluation_data WHERE precision > 0.9;
What is the total number of satellites launched by each company in the satellite_launches table?
CREATE TABLE satellite_launches (launch_id INT,company_id INT,satellite_id INT,launch_date DATE);
SELECT company_id, COUNT(*) as total_launches FROM satellite_launches GROUP BY company_id;
What is the distribution of security incidents by country in the past year from the 'security_incidents' table?
CREATE TABLE security_incidents (id INT,country VARCHAR(50),incidents INT,year INT);
SELECT country, SUM(incidents) FROM security_incidents WHERE year = YEAR(CURRENT_DATE) - 1 GROUP BY country;
Find the total usage hours of autonomous vehicles in the autonomous_vehicles table
CREATE TABLE autonomous_vehicle_usage (id INT PRIMARY KEY,user_id INT,vehicle_id INT,usage_hours TIMESTAMP);
SELECT SUM(usage_hours) FROM autonomous_vehicle_usage JOIN autonomous_vehicles ON autonomous_vehicle_usage.vehicle_id = autonomous_vehicles.id;
What is the number of animals that were rescued in each year in the 'rescued_animals' table?
CREATE TABLE rescued_animals (id INT,animal_name VARCHAR(50),year INT,num_rescued INT); INSERT INTO rescued_animals (id,animal_name,year,num_rescued) VALUES (1,'tiger',2018,20),(2,'elephant',2019,30),(3,'giraffe',2018,40),(4,'tiger',2019,30),(5,'elephant',2018,45);
SELECT year, SUM(num_rescued) FROM rescued_animals GROUP BY year;
What is the average number of likes on posts mentioning brand Z in Germany?
CREATE TABLE post_likes (like_id INT,post_id INT,like_count INT,post_date DATE,country VARCHAR(50)); INSERT INTO post_likes (like_id,post_id,like_count,post_date,country) VALUES (1,1,20,'2022-01-01','Germany'),(2,2,30,'2022-01-02','Germany'),(3,3,10,'2022-01-03','Germany'); CREATE TABLE posts (post_id INT,post_text TEX...
SELECT AVG(like_count) FROM post_likes INNER JOIN posts ON post_likes.post_id = posts.post_id WHERE brand_mentioned = 'brandZ' AND country = 'Germany';
List all military innovation projects and their start dates.
CREATE TABLE Military_Innovation (Project_ID INT,Project_Name VARCHAR(50),Start_Date DATE); INSERT INTO Military_Innovation (Project_ID,Project_Name,Start_Date) VALUES (1,'Stealth Fighter Project','1980-01-01');
SELECT * FROM Military_Innovation;
What is the maximum and minimum biomass of fish for each species in the aquaculture facility?
CREATE TABLE fish_species (id INT,species TEXT,biomass_tolerance FLOAT);CREATE TABLE fish_population (id INT,species TEXT,population INT,biomass FLOAT,date DATE);
SELECT species, MAX(biomass) AS max_biomass, MIN(biomass) AS min_biomass FROM fish_population fp JOIN fish_species fs ON fp.species = fs.species GROUP BY species;
List all customers in the 'Europe' region?
CREATE TABLE customers (id INT,name VARCHAR(50),region VARCHAR(20)); INSERT INTO customers (id,name,region) VALUES (1,'John Doe','Southwest'),(2,'Jane Smith','Northeast'),(3,'Michael Johnson','North America'),(4,'Sarah Lee','North America'),(5,'Emma Watson','Europe'),(6,'Oliver Twist','Europe');
SELECT * FROM customers WHERE region = 'Europe';
What is the total number of songs and albums sold by artists who identify as part of the LGBTQ+ community?
CREATE TABLE Artists (ArtistID INT,ArtistName VARCHAR(100),LGBTQ BOOLEAN); INSERT INTO Artists (ArtistID,ArtistName,LGBTQ) VALUES (1,'Sam Smith',TRUE),(2,'Taylor Swift',FALSE); CREATE TABLE MusicStreams (StreamID INT,SongID INT,ArtistID INT); INSERT INTO MusicStreams (StreamID,SongID,ArtistID) VALUES (1,1,1),(2,2,2); C...
SELECT COUNT(DISTINCT ms.StreamID) + COUNT(DISTINCT a.AlbumID) AS TotalReleases FROM Artists a JOIN MusicStreams ms ON a.ArtistID = ms.ArtistID JOIN Albums al ON a.ArtistID = al.ArtistID WHERE LGBTQ = TRUE;
What is the percentage of events where each team sold out?
CREATE TABLE teams (team_id INT,team_name VARCHAR(255)); INSERT INTO teams (team_id,team_name) VALUES (1,'Knights'),(2,'Lions'),(3,'Titans'); CREATE TABLE events (event_id INT,team_id INT,num_tickets_sold INT,total_seats INT); INSERT INTO events (event_id,team_id,num_tickets_sold,total_seats) VALUES (1,1,500,1000),(2,1...
SELECT e.team_id, (COUNT(*) * 100.0 / (SELECT COUNT(*) FROM events e WHERE e.total_seats >= e.num_tickets_sold)) as sold_out_percentage FROM events e GROUP BY e.team_id HAVING COUNT(*) = (SELECT COUNT(*) FROM events e WHERE e.team_id = e.team_id);
What is the average environmental impact score per product category?
CREATE TABLE environmental_impact (product_category VARCHAR(255),environmental_impact_score FLOAT); INSERT INTO environmental_impact (product_category,environmental_impact_score) VALUES ('Polymers',5.2),('Dyes',6.1),('Solvents',4.9);
SELECT product_category, AVG(environmental_impact_score) OVER (PARTITION BY product_category) AS avg_impact_score FROM environmental_impact;
Get the details of the oldest national security strategy in Europe.
CREATE TABLE national_security_strategies (strategy_id INT,country VARCHAR(255),details TEXT,timestamp TIMESTAMP); INSERT INTO national_security_strategies (strategy_id,country,details,timestamp) VALUES (1,'UK','Defend the realm...','2021-06-01 12:00:00'),(2,'France','Promote peace...','2021-07-04 10:30:00'),(3,'German...
SELECT * FROM national_security_strategies WHERE country LIKE 'Europe%' ORDER BY timestamp ASC LIMIT 1;
What is the total quantity of products that are made from recycled polyester or recycled cotton?
CREATE TABLE PRODUCT (id INT PRIMARY KEY,name TEXT,material TEXT,quantity INT,country TEXT,certifications TEXT,is_recycled BOOLEAN,recycled_material TEXT); INSERT INTO PRODUCT (id,name,material,quantity,country,certifications,is_recycled,recycled_material) VALUES (1,'Organic Cotton Shirt','Organic Cotton',30,'USA','GOT...
SELECT SUM(quantity) FROM PRODUCT WHERE recycled_material IN ('Recycled Polyester', 'Recycled Cotton');
Identify the top 3 attorneys with the highest billing amounts for cases in the 'Civil Litigation' practice area.
CREATE TABLE attorneys (attorney_id INT,name VARCHAR(30)); CREATE TABLE cases (case_id INT,attorney_id INT,practice_area VARCHAR(20),billing_amount DECIMAL(10,2)); INSERT INTO attorneys (attorney_id,name) VALUES (1,'John Smith'),(2,'Jane Doe'),(3,'Alex Johnson'),(4,'Emily Davis'); INSERT INTO cases (case_id,attorney_id...
SELECT attorney_id, name, SUM(billing_amount) as total_billing FROM attorneys JOIN cases ON attorneys.attorney_id = cases.attorney_id WHERE practice_area = 'Civil Litigation' GROUP BY attorney_id, name ORDER BY total_billing DESC LIMIT 3;
Update the budget of the movie with ID 1 to 22000000.
CREATE TABLE movies (id INT,title VARCHAR(255),release_year INT,director_gender VARCHAR(10),budget INT); INSERT INTO movies (id,title,release_year,director_gender,budget) VALUES (1,'Movie1',2020,'Female',20000000),(2,'Movie2',2019,'Male',30000000);
UPDATE movies SET budget = 22000000 WHERE id = 1;
How many volunteers participated in marine conservation programs in 2021?
CREATE TABLE Conservation_Volunteer (Id INT,Volunteer_Date DATE,Program_Type VARCHAR(50),Volunteers_Count INT); INSERT INTO Conservation_Volunteer (Id,Volunteer_Date,Program_Type,Volunteers_Count) VALUES (1,'2021-01-01','Marine Conservation',50); INSERT INTO Conservation_Volunteer (Id,Volunteer_Date,Program_Type,Volunt...
SELECT SUM(Volunteers_Count) FROM Conservation_Volunteer WHERE YEAR(Volunteer_Date) = 2021 AND Program_Type = 'Marine Conservation';
What is the average data usage for broadband subscribers in each state?
CREATE TABLE broadband_subscribers (subscriber_id int,state varchar(20),data_usage float); INSERT INTO broadband_subscribers (subscriber_id,state,data_usage) VALUES (1,'WA',50),(2,'NY',75),(3,'IL',60); CREATE TABLE broadband_plans (plan_id int,plan_type varchar(10),max_data_usage float); INSERT INTO broadband_plans (pl...
SELECT state, AVG(data_usage) as avg_data_usage FROM broadband_subscribers sub INNER JOIN broadband_plans plan ON sub.state = plan.plan_type GROUP BY state;
Identify the top 2 countries with the highest average volunteer hours in H1 2022?
CREATE TABLE volunteer_hours_h1_2022 (id INT,name VARCHAR(50),volunteer_hours INT,country VARCHAR(50)); INSERT INTO volunteer_hours_h1_2022 (id,name,volunteer_hours,country) VALUES (1,'Alex Brown',25,'Canada'),(2,'Jamie Lee',30,'USA'),(3,'Sophia Chen',20,'China'),(4,'Pedro Martinez',35,'Brazil'),(5,'Nina Patel',40,'Ind...
SELECT country, AVG(volunteer_hours) as avg_hours FROM volunteer_hours_h1_2022 WHERE volunteer_date >= '2022-01-01' AND volunteer_date < '2022-07-01' GROUP BY country ORDER BY avg_hours DESC LIMIT 2;
Identify the top 3 suppliers with the highest number of services provided to the assembly department in the past 6 months.
CREATE TABLE suppliers (id INT,name TEXT,industry TEXT); CREATE TABLE services (id INT,supplier_id INT,department TEXT,date DATE); INSERT INTO suppliers (id,name,industry) VALUES (1,'Supplier A','Manufacturing'),(2,'Supplier B','Electronics'),(3,'Supplier C','Manufacturing'),(4,'Supplier D','Electronics'),(5,'Supplier ...
SELECT s.name, COUNT(*) as service_count FROM suppliers s JOIN services se ON s.id = se.supplier_id WHERE se.department = 'Assembly' AND se.date >= DATE_SUB(CURRENT_DATE, INTERVAL 6 MONTH) GROUP BY s.name ORDER BY service_count DESC LIMIT 3;
What is the average value of paintings produced by Mexican artists?
CREATE TABLE artists (artist_id INT,name VARCHAR(50),nationality VARCHAR(50)); INSERT INTO artists (artist_id,name,nationality) VALUES (1,'Frida Kahlo','Mexico'); CREATE TABLE art_pieces (art_piece_id INT,title VARCHAR(50),value INT,artist_id INT); INSERT INTO art_pieces (art_piece_id,title,value,artist_id) VALUES (1,'...
SELECT AVG(ap.value) FROM art_pieces ap INNER JOIN artists a ON ap.artist_id = a.artist_id WHERE a.nationality = 'Mexico' AND ap.title LIKE '%painting%';
What is the total budget for military innovations for each technology provider?
CREATE TABLE military_innovations (id INT,innovation VARCHAR(255),type VARCHAR(255),budget DECIMAL(10,2)); CREATE TABLE technology_providers (id INT,provider VARCHAR(255),specialization VARCHAR(255));
SELECT tp.provider, SUM(mi.budget) FROM military_innovations mi INNER JOIN technology_providers tp ON mi.id = tp.id GROUP BY tp.provider;
Show the electric vehicles that have had the most considerable increase in horsepower compared to their first model year
CREATE TABLE ev_cars_2 (car_id INT,car_name VARCHAR(255),horsepower INT,model_year INT);
SELECT t1.car_name, t1.horsepower, t1.model_year, t1.horsepower - t2.horsepower as horsepower_increase FROM ev_cars_2 t1 JOIN ev_cars_2 t2 ON t1.car_name = t2.car_name AND t1.model_year = t2.model_year + 1 WHERE t1.horsepower > t2.horsepower ORDER BY horsepower_increase DESC;
What is the total revenue for all sculptures exhibited in France since 2010?
CREATE TABLE ArtWorkSales (artworkID INT,saleDate DATE,artworkMedium VARCHAR(50),revenue DECIMAL(10,2)); CREATE TABLE Artists (artistID INT,artistName VARCHAR(50),country VARCHAR(50));
SELECT SUM(revenue) as total_revenue FROM ArtWorkSales aws JOIN Artists a ON aws.artistID = a.artistID WHERE artworkMedium = 'sculpture' AND a.country = 'France' AND YEAR(saleDate) >= 2010;
Delete excavation sites that have no artifacts
CREATE TABLE ExcavationSite (id INT,country VARCHAR(50),type VARCHAR(50)); INSERT INTO ExcavationSite (id,country,type) VALUES (1,'Egypt','Pottery'),(2,'Mexico',NULL);
DELETE FROM ExcavationSite WHERE id NOT IN (SELECT es.id FROM ExcavationSite es JOIN ArtifactAnalysis a ON es.id = a.excavation_site_id);
What's the average budget of movies released by studios located in Los Angeles, sorted by release date in descending order?
CREATE TABLE studio (studio_id INT,studio_name VARCHAR(50),city VARCHAR(50)); INSERT INTO studio (studio_id,studio_name,city) VALUES (1,'Studio A','Los Angeles'),(2,'Studio B','New York'); CREATE TABLE movie (movie_id INT,title VARCHAR(50),release_date DATE,studio_id INT); INSERT INTO movie (movie_id,title,release_date...
SELECT AVG(movie.budget) AS avg_budget FROM movie INNER JOIN studio ON movie.studio_id = studio.studio_id WHERE studio.city = 'Los Angeles' ORDER BY movie.release_date DESC;
What is the sum of donation amounts for each month in the year 2022?
CREATE TABLE Donations (donation_id INT,donation_amount FLOAT,donation_date DATE); INSERT INTO Donations (donation_id,donation_amount,donation_date) VALUES (1,500.00,'2022-01-01'),(2,300.00,'2022-01-15'),(3,400.00,'2022-02-20'),(4,250.00,'2022-03-10'),(5,600.00,'2022-03-15');
SELECT EXTRACT(MONTH FROM donation_date) AS month, SUM(donation_amount) FROM Donations WHERE YEAR(donation_date) = 2022 GROUP BY month;
List all programs in the 'programs' table that have no manager assigned.
CREATE TABLE programs (program_id INT,program_name TEXT,manager_name TEXT); INSERT INTO programs VALUES (1,'Education','Alice Johnson'),(2,'Health',NULL);
SELECT program_id, program_name FROM programs WHERE manager_name IS NULL;
What is the average R&D expenditure for 'CompanyZ' between 2017 and 2019?
CREATE TABLE rd_expenditures (company varchar(20),year int,amount int); INSERT INTO rd_expenditures (company,year,amount) VALUES ('CompanyZ',2017,4000000),('CompanyZ',2018,4500000),('CompanyZ',2019,5000000);
SELECT AVG(amount) FROM rd_expenditures WHERE company = 'CompanyZ' AND year BETWEEN 2017 AND 2019;
What is the total number of salmon farms in Norway and Scotland?
CREATE TABLE salmon_farms (id INT,name TEXT,country TEXT); INSERT INTO salmon_farms (id,name,country) VALUES (1,'Farm A','Norway'); INSERT INTO salmon_farms (id,name,country) VALUES (2,'Farm B','Norway'); INSERT INTO salmon_farms (id,name,country) VALUES (3,'Farm C','Scotland'); INSERT INTO salmon_farms (id,name,countr...
SELECT COUNT(*) FROM salmon_farms WHERE country IN ('Norway', 'Scotland');
Delete all records in the "ai_ethics_trainings" table where the "date" is before '2021-01-01'
CREATE TABLE ai_ethics_trainings (id INT PRIMARY KEY,date DATE,topic VARCHAR(255),description VARCHAR(255));
WITH deleted_data AS (DELETE FROM ai_ethics_trainings WHERE date < '2021-01-01' RETURNING *) SELECT * FROM deleted_data;
What is the maximum water consumption per day in Egypt?
CREATE TABLE daily_water_consumption (country VARCHAR(20),max_consumption FLOAT); INSERT INTO daily_water_consumption (country,max_consumption) VALUES ('Egypt',1200000);
SELECT max_consumption FROM daily_water_consumption WHERE country = 'Egypt';
How many disability support programs are offered by each organization, including those without any programs?
CREATE TABLE organization (org_id INT,org_name TEXT); CREATE TABLE support_program (program_id INT,program_name TEXT,org_id INT); INSERT INTO organization (org_id,org_name) VALUES (1,'DEF Organization'); INSERT INTO support_program (program_id,program_name,org_id) VALUES (1,'Accessible Tours',1); INSERT INTO support_pr...
SELECT O.org_name, COUNT(SP.program_id) AS num_programs FROM organization O LEFT JOIN support_program SP ON O.org_id = SP.org_id GROUP BY O.org_name;
List the top 3 CO2 emission states from the energy sector?
CREATE TABLE co2_emissions (state VARCHAR(20),sector VARCHAR(20),co2_emissions FLOAT); INSERT INTO co2_emissions (state,sector,co2_emissions) VALUES ('Texas','Energy',256.12),('California','Energy',176.54),('Pennsylvania','Energy',134.65),('Florida','Energy',121.98);
SELECT state, SUM(co2_emissions) as total_emissions FROM co2_emissions WHERE sector = 'Energy' GROUP BY state ORDER BY total_emissions DESC LIMIT 3;
Which beauty products contain the ingredient 'retinol'?
CREATE TABLE product_ingredients (product VARCHAR(255),ingredient VARCHAR(255)); INSERT INTO product_ingredients (product,ingredient) VALUES ('Ava Cleanser','Retinol'),('Ava Moisturizer','Hyaluronic Acid'),('Brizo Exfoliant','Glycolic Acid'),('Brizo Toner','Retinol');
SELECT product FROM product_ingredients WHERE ingredient = 'Retinol';
Show all cities where the number of events funded by "Government" is greater than 3
CREATE TABLE events (event_id INT,event_name VARCHAR(50),city VARCHAR(30),funding_source VARCHAR(30)); INSERT INTO events (event_id,event_name,city,funding_source) VALUES (1,'Theater Play','New York','Government'),(2,'Art Exhibit','Los Angeles','Private Donors'),(3,'Music Festival','New York','Government');
SELECT city FROM events WHERE funding_source = 'Government' GROUP BY city HAVING COUNT(*) > 3;
What is the total warehouse storage capacity for each warehouse in the warehouse database?
CREATE TABLE warehouse (warehouse VARCHAR(20),capacity INT); INSERT INTO warehouse (warehouse,capacity) VALUES ('Warehouse1',10000),('Warehouse2',12000),('Warehouse3',15000);
SELECT warehouse, SUM(capacity) FROM warehouse GROUP BY warehouse;
List all excavation sites in 'Spain' from the 'ExcavationSites' table, along with their start and end dates.
CREATE TABLE ExcavationSites (ID INT,Name VARCHAR(50),Country VARCHAR(50),StartDate DATE,EndDate DATE);
SELECT Name, StartDate, EndDate FROM ExcavationSites WHERE Country = 'Spain';