instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
Remove fish farms with poor health scores
CREATE TABLE farms (id INT,name VARCHAR(50),country VARCHAR(50),certification VARCHAR(50)); INSERT INTO farms
DELETE FROM farms WHERE certification NOT IN ('ASC', 'BAP', 'MSC');
What is the price of properties without sustainable features?
CREATE TABLE Property (id INT PRIMARY KEY,address VARCHAR(255),city VARCHAR(255),state VARCHAR(255),zip INT,co_owners INT,sustainable_features VARCHAR(255),price INT);
SELECT Property.price FROM Property WHERE sustainable_features = '';
What is the percentage of veterans employed in each state?
CREATE TABLE veteran_employment (state TEXT,num_veterans INT,total_employees INT); INSERT INTO veteran_employment VALUES ('California',10000,50000),('Texas',12000,60000);
SELECT state, (num_veterans::DECIMAL(10,2) / total_employees::DECIMAL(10,2)) * 100 AS veteran_percentage FROM veteran_employment;
Calculate the average age of players who have played RPG games with more than 50 hours of playtime, grouped by continent.
CREATE TABLE Players (PlayerID INT,Name VARCHAR(100),Age INT,Country VARCHAR(50)); INSERT INTO Players VALUES (1,'Jessica Brown',27,'Australia'); INSERT INTO Players VALUES (2,'Daniel Kim',31,'Japan'); CREATE TABLE Countries (Country VARCHAR(50),Continent VARCHAR(50)); INSERT INTO Countries VALUES ('Australia','Oceania'); INSERT INTO Countries VALUES ('Japan','Asia'); CREATE TABLE GameDesign (GameID INT,GameName VARCHAR(100),Genre VARCHAR(50)); INSERT INTO GameDesign VALUES (1,'GameX','RPG'); INSERT INTO GameDesign VALUES (2,'GameY','Strategy');
SELECT C.Continent, AVG(P.Age) as AvgAge FROM Players P JOIN Countries C ON P.Country = C.Country JOIN (SELECT PlayerID, Genre FROM Players P JOIN GameDesign GD ON P.PlayerID = GD.GameID WHERE GD.Genre = 'RPG' AND P.TotalHoursPlayed > 50) AS GameRPG ON P.PlayerID = GameRPG.PlayerID GROUP BY C.Continent;
What is the total freight charge for each customer in the 'East' region?
CREATE TABLE CustomersRegion (CustomerID INT,CustomerName VARCHAR(255),Region VARCHAR(50),TotalFreightCharges DECIMAL(10,2)); INSERT INTO CustomersRegion (CustomerID,CustomerName,Region,TotalFreightCharges) VALUES (1,'ABC Corp','East',5000.00),(2,'XYZ Inc','West',7000.00),(3,'LMN Ltd','East',6000.00),(4,'DEF Co','West',8000.00),(5,'GHI Pvt','East',9000.00);
SELECT CustomerName, TotalFreightCharges FROM CustomersRegion WHERE Region = 'East';
What is the total number of traditional art pieces by type and continent?
CREATE TABLE Art (ArtID INT,Type VARCHAR(255),Region VARCHAR(255),Continent VARCHAR(255),Quantity INT); INSERT INTO Art (ArtID,Type,Region,Continent,Quantity) VALUES (1,'Painting','Asia','Asia',25),(2,'Sculpture','Africa','Africa',18),(3,'Textile','South America','South America',30),(4,'Pottery','Europe','Europe',20),(5,'Jewelry','North America','North America',12);
SELECT Type, Continent, SUM(Quantity) as Total_Quantity FROM Art GROUP BY Type, Continent;
What is the average salary for workers in the 'service_database' database who are members of a union and work in the 'cleaning' department?
CREATE TABLE cleaners (id INT,name VARCHAR(50),salary DECIMAL(10,2),is_union_member BOOLEAN,department VARCHAR(50)); INSERT INTO cleaners (id,name,salary,is_union_member,department) VALUES (1,'Olivia',90000.00,true,'cleaning'),(2,'Owen',95000.00,true,'cleaning'),(3,'Olga',80000.00,true,'management');
SELECT AVG(salary) FROM cleaners WHERE is_union_member = true AND department = 'cleaning';
What is the minimum mental health score per school for students who have enrolled in lifelong learning courses?
CREATE TABLE students (student_id INT,school_id INT,mental_health_score INT); CREATE TABLE enrollments (student_id INT,course_type VARCHAR,enrollment_date DATE);
SELECT s.school_id, MIN(s.mental_health_score) as min_score FROM students s INNER JOIN enrollments e ON s.student_id = e.student_id WHERE e.course_type = 'lifelong learning' GROUP BY s.school_id;
Insert records for all states into MentalHealthParity
CREATE TABLE MentalHealthParity (ID INT PRIMARY KEY,State VARCHAR(2),ParityStatus VARCHAR(10));
INSERT INTO MentalHealthParity (ID, State, ParityStatus) VALUES (1, 'AK', 'Yes'), (2, 'AL', 'No'), (3, 'AR', 'No'), (4, 'AZ', 'Yes'), (5, 'CA', 'Yes'), (6, 'CO', 'Yes'), (7, 'CT', 'Yes'), (8, 'DC', 'Yes'), (9, 'DE', 'Yes'), (10, 'FL', 'No'), (11, 'GA', 'No'), (12, 'HI', 'Yes');
What is the average water temperature in salmon farms in Norway?
CREATE TABLE salmon_farms (id INT,name TEXT,country TEXT); CREATE TABLE temperature_readings (id INT,farm_id INT,temperature FLOAT); INSERT INTO salmon_farms (id,name,country) VALUES (1,'Farm X','Norway'),(2,'Farm Y','Norway'),(3,'Farm Z','Canada'); INSERT INTO temperature_readings (id,farm_id,temperature) VALUES (1,1,12.5),(2,1,13.0),(3,2,11.0),(4,2,11.5),(5,3,7.0);
SELECT AVG(temperature) FROM temperature_readings TR JOIN salmon_farms SF ON TR.farm_id = SF.id WHERE SF.country = 'Norway';
What is the average rating of organic products, categorized by brand?
CREATE TABLE products (product_id INT,product VARCHAR(255),brand_id INT,price DECIMAL(5,2),organic BOOLEAN,rating INT); CREATE TABLE brands (brand_id INT,brand VARCHAR(255)); INSERT INTO products (product_id,product,brand_id,price,organic,rating) VALUES (1,'Organic Shampoo',1,12.99,TRUE,4),(2,'Non-organic Shampoo',1,9.99,FALSE,3),(3,'Organic Conditioner',1,14.99,TRUE,5),(4,'Non-organic Conditioner',1,10.99,FALSE,4),(5,'Organic Face Cream',2,15.99,TRUE,5),(6,'Non-organic Face Cream',2,13.99,FALSE,4); INSERT INTO brands (brand_id,brand) VALUES (1,'Brand A'),(2,'Brand B');
SELECT b.brand, AVG(p.rating) as avg_organic_rating FROM products p JOIN brands b ON p.brand_id = b.brand_id WHERE p.organic = TRUE GROUP BY b.brand;
What is the average grant amount awarded to graduate students from underrepresented communities?
CREATE TABLE graduate_students (id INT,name VARCHAR(50),community VARCHAR(50),grant_amount DECIMAL(10,2)); INSERT INTO graduate_students (id,name,community,grant_amount) VALUES (1,'John Doe','Underrepresented',25000.00),(2,'Jane Smith','Not Underrepresented',30000.00);
SELECT AVG(grant_amount) FROM graduate_students WHERE community = 'Underrepresented';
What is the total manufacturing cost for each spacecraft model?
CREATE TABLE Spacecraft (Id INT,Model VARCHAR(255),ManufacturingCost DECIMAL(10,2)); INSERT INTO Spacecraft (Id,Model,ManufacturingCost) VALUES (1,'Voyager',100000.00),(2,'Cassini',300000.00),(3,'Galileo',250000.00);
SELECT Model, SUM(ManufacturingCost) as TotalManufacturingCost FROM Spacecraft GROUP BY Model;
What is the total size of properties in the 'properties' table?
CREATE TABLE properties (id INT,size FLOAT,PRIMARY KEY (id)); INSERT INTO properties (id,size) VALUES (1,1200.0),(2,800.0),(3,1500.0),(4,1000.0);
SELECT SUM(size) FROM properties;
What was the average age of visitors who attended the Impressionist Art exhibition?
CREATE TABLE exhibitions (exhibition_id INT,name VARCHAR(255)); INSERT INTO exhibitions (exhibition_id,name) VALUES (1,'Art of the Renaissance'),(2,'Modern Art'),(3,'Impressionist Art'); CREATE TABLE visitors (visitor_id INT,exhibition_id INT,age INT); INSERT INTO visitors (visitor_id,exhibition_id,age) VALUES (1,1,25),(2,1,42),(3,2,28),(4,3,29),(5,3,22),(6,3,35);
SELECT AVG(age) as avg_age FROM visitors WHERE exhibition_id = 3;
Which industries have the most diverse founding teams in terms of gender?
CREATE TABLE company (id INT,name VARCHAR(50),industry VARCHAR(50),founder_gender VARCHAR(10)); INSERT INTO company (id,name,industry,founder_gender) VALUES (1,'Acme Inc','Tech','Female'),(2,'Beta Corp','Finance','Male'),(3,'Gamma Startup','Tech','Female'),(4,'Delta Company','Finance','Non-binary');
SELECT industry, COUNT(DISTINCT founder_gender) AS diversity_score FROM company GROUP BY industry ORDER BY diversity_score DESC;
What is the minimum depth in the Southern Ocean where phytoplankton are present?
CREATE TABLE phytoplankton_depth (id INT,location VARCHAR(50),depth FLOAT,phytoplankton_present BOOLEAN); INSERT INTO phytoplankton_depth (id,location,depth,phytoplankton_present) VALUES (1,'Southern Ocean',50.0,TRUE); INSERT INTO phytoplankton_depth (id,location,depth,phytoplankton_present) VALUES (2,'Southern Ocean',75.0,TRUE);
SELECT MIN(depth) FROM phytoplankton_depth WHERE location = 'Southern Ocean' AND phytoplankton_present = TRUE;
How many instances of disinformation were detected in a specific language during a specific time period?
CREATE TABLE disinformation_language (id INT,detected_at TIMESTAMP,language VARCHAR,confirmed BOOLEAN); INSERT INTO disinformation_language (id,detected_at,language,confirmed) VALUES (1,'2021-01-01 12:00:00','English',true); INSERT INTO disinformation_language (id,detected_at,language,confirmed) VALUES (2,'2021-01-02 13:00:00','Spanish',false);
SELECT COUNT(*) FROM disinformation_language WHERE detected_at BETWEEN '2021-01-01' AND '2021-01-07' AND language = 'Spanish' AND confirmed = true;
Which OTA has the lowest number of bookings in 'Asia'?
CREATE TABLE online_travel_agencies(id INT,name TEXT,country TEXT,bookings INT);
SELECT name, MIN(bookings) FROM online_travel_agencies WHERE country = 'Asia' GROUP BY name;
What was the total budget for 2022?
CREATE TABLE Budget (BudgetID int,BudgetYear int,BudgetAmount decimal(10,2)); INSERT INTO Budget (BudgetID,BudgetYear,BudgetAmount) VALUES (1,2022,50000),(2,2023,60000);
SELECT SUM(BudgetAmount) FROM Budget WHERE BudgetYear = 2022;
how many education programs are there in total in the 'community_education' table?
CREATE TABLE community_education (education_id INT,education_name VARCHAR(50),start_date DATE,end_date DATE); INSERT INTO community_education (education_id,education_name,start_date,end_date) VALUES (1,'Animal Tracking','2021-01-01','2021-12-31'),(2,'Habitat Conservation','2021-04-01','2021-12-31'),(3,'Wildlife Photography','2021-07-01','2021-10-31');
SELECT COUNT(*) FROM community_education;
What is the average prize pool for esports events related to the 'Battle Royale' genre?
CREATE TABLE EsportsEvents (EventID INT PRIMARY KEY,EventName VARCHAR(50),GameID INT,PrizePool DECIMAL(10,2),GameGenre VARCHAR(20)); INSERT INTO EsportsEvents (EventID,EventName,GameID,PrizePool,GameGenre) VALUES (6,'Fortnite World Cup',5,30000000.00,'Battle Royale'); INSERT INTO EsportsEvents (EventID,EventName,GameID,PrizePool,GameGenre) VALUES (7,'PUBG Global Championship',6,2000000.00,'Battle Royale');
SELECT AVG(PrizePool) FROM EsportsEvents WHERE GameGenre = 'Battle Royale';
What are the names and descriptions of all the security policies that have been updated in the last month?
CREATE TABLE security_policies (id INT,name VARCHAR(255),description TEXT,last_updated TIMESTAMP);
SELECT name, description FROM security_policies WHERE last_updated >= NOW() - INTERVAL 1 MONTH;
Show all reservoirs with capacity > 1000
CREATE TABLE oil_reservoirs (reservoir_id INT,reservoir_name VARCHAR(100),location VARCHAR(100),oil_capacity FLOAT); INSERT INTO oil_reservoirs (reservoir_id,reservoir_name,location,oil_capacity) VALUES (1,'Girassol','Angola',800),(2,'Jazireh-e-Jafar','Iran',1500),(3,'Thunder Horse','Gulf of Mexico',1200),(4,'Kashagan','Caspian Sea',1100);
SELECT * FROM oil_reservoirs WHERE oil_capacity > 1000;
List the number of volunteers who have joined each organization in the last 6 months.
CREATE TABLE volunteers (id INT,name TEXT,organization TEXT,join_date DATE); INSERT INTO volunteers (id,name,organization,join_date) VALUES (1,'Volunteer 1','Organization A','2021-01-01'),(2,'Volunteer 2','Organization B','2021-03-15');
SELECT organization, COUNT(*) AS num_volunteers FROM volunteers WHERE join_date >= DATE_SUB(CURRENT_DATE, INTERVAL 6 MONTH) GROUP BY organization;
What is the maximum number of headshots achieved by players who have more than 50 headshots in the "SniperElite" table?
CREATE TABLE SniperElite (PlayerID INT,Headshots INT,ShotsFired INT); INSERT INTO SniperElite (PlayerID,Headshots,ShotsFired) VALUES (1,60,200),(2,55,180),(3,65,220),(4,62,210),(5,58,190);
SELECT MAX(Headshots) FROM SniperElite WHERE Headshots > 50;
What is the total amount of waste produced by companies in the circular economy in the past year?
CREATE TABLE companies (id INT,name TEXT,industry TEXT,circular_economy TEXT,waste_production_tonnes FLOAT,year INT); INSERT INTO companies (id,name,industry,circular_economy,waste_production_tonnes,year) VALUES (1,'Circular Solutions','Manufacturing','Circular Economy',500,2021); INSERT INTO companies (id,name,industry,circular_economy,waste_production_tonnes,year) VALUES (2,'Eco Manufacturing','Manufacturing','Circular Economy',600,2021); INSERT INTO companies (id,name,industry,circular_economy,waste_production_tonnes,year) VALUES (3,'Green Tech','Technology','Circular Economy',400,2021);
SELECT SUM(waste_production_tonnes) as total_waste FROM companies WHERE circular_economy = 'Circular Economy' AND year = 2021;
How many users have posted content in each country?
CREATE TABLE users_extended (id INT,country VARCHAR(255)); CREATE TABLE posts_extended (id INT,user_id INT,content TEXT,country VARCHAR(255)); INSERT INTO users_extended (id,country) VALUES (1,'USA'),(2,'Canada'),(3,'Mexico'); INSERT INTO posts_extended (id,user_id,content,country) VALUES (1,1,'Hello','USA'),(2,1,'World','USA'),(3,2,'AI','Canada');
SELECT users_extended.country, COUNT(DISTINCT posts_extended.user_id) FROM users_extended JOIN posts_extended ON users_extended.id = posts_extended.user_id GROUP BY users_extended.country;
What is the total number of articles and videos in the media database, excluding any duplicate entries?
CREATE TABLE articles (id INT,title TEXT,content TEXT); CREATE TABLE videos (id INT,title TEXT,url TEXT); INSERT INTO articles (id,title,content) VALUES (1,'Article 1','Content 1'); INSERT INTO articles (id,title,content) VALUES (2,'Article 2','Content 2'); INSERT INTO videos (id,title,url) VALUES (1,'Video 1','URL 1'); INSERT INTO videos (id,title,url) VALUES (2,'Video 2','URL 2'); INSERT INTO articles (id,title,content) VALUES (1,'Article 1','Content 1');
SELECT COUNT(DISTINCT a.id) + COUNT(DISTINCT v.id) FROM articles a JOIN videos v ON TRUE;
What's the average environmental score for investments in the education sector?
CREATE TABLE investments (id INT,amount DECIMAL(10,2),sector VARCHAR(255)); INSERT INTO investments (id,amount,sector) VALUES (1,50000,'Education'); CREATE TABLE esg_factors (id INT,investment_id INT,environmental_score DECIMAL(10,2),social_score DECIMAL(10,2),governance_score DECIMAL(10,2)); INSERT INTO esg_factors (id,investment_id,environmental_score,social_score,governance_score) VALUES (1,1,80,85,90);
SELECT AVG(esg_factors.environmental_score) FROM esg_factors INNER JOIN investments ON esg_factors.investment_id = investments.id WHERE investments.sector = 'Education';
Delete the 'ocean_species' table
DROP TABLE ocean_species;
DROP TABLE ocean_species;
What is the average heart rate for members with a platinum membership, categorized by gender?
CREATE TABLE member_demographics (member_id INT,age INT,gender VARCHAR(10)); INSERT INTO member_demographics (member_id,age,gender) VALUES (1,27,'Female'),(2,32,'Trans Male'),(3,46,'Non-binary'); CREATE TABLE wearable_data (member_id INT,heart_rate INT,timestamp TIMESTAMP,membership_type VARCHAR(20)); INSERT INTO wearable_data (member_id,heart_rate,timestamp,membership_type) VALUES (1,120,'2022-01-01 10:00:00','Platinum'),(1,115,'2022-01-01 11:00:00','Platinum'),(2,130,'2022-01-01 10:00:00','Platinum'),(2,135,'2022-01-01 11:00:00','Platinum'),(3,105,'2022-01-01 10:00:00','Platinum'),(3,100,'2022-01-01 11:00:00','Platinum');
SELECT gender, AVG(heart_rate) as avg_heart_rate FROM wearable_data w JOIN member_demographics m ON w.member_id = m.member_id WHERE membership_type = 'Platinum' GROUP BY gender;
What are the names and websites of organizations contributing to the conservation of marine turtles?
CREATE TABLE marine_species (id INT PRIMARY KEY,species_name VARCHAR(255),conservation_status VARCHAR(255)); CREATE TABLE conservation_efforts (id INT PRIMARY KEY,species_id INT,location VARCHAR(255),FOREIGN KEY (species_id) REFERENCES marine_species(id)); CREATE TABLE organizations (id INT PRIMARY KEY,effort_id INT,organization_name VARCHAR(255),organization_website VARCHAR(255),FOREIGN KEY (effort_id) REFERENCES conservation_efforts(id)); INSERT INTO marine_species (id,species_name,conservation_status) VALUES (1,'Marine Turtle','vulnerable');
SELECT marine_species.species_name, organizations.organization_name, organizations.organization_website FROM marine_species INNER JOIN conservation_efforts ON marine_species.id = conservation_efforts.species_id INNER JOIN organizations ON conservation_efforts.id = organizations.effort_id WHERE marine_species.species_name = 'Marine Turtle';
Count the number of exhibitions for the Cubism art movement.
CREATE TABLE exhibition_data (id INT,exhibition_name VARCHAR(50),art_movement VARCHAR(50));
SELECT COUNT(*) as num_exhibitions FROM exhibition_data WHERE art_movement = 'Cubism';
Which restorative justice programs in California have more than 50 participants?
CREATE TABLE restorative_justice_programs (id INT,name VARCHAR(50),location VARCHAR(50),start_date DATE); CREATE TABLE participants (id INT,program_id INT,participant_name VARCHAR(50),participation_date DATE);
SELECT restorative_justice_programs.name, COUNT(participants.id) as num_participants FROM restorative_justice_programs JOIN participants ON restorative_justice_programs.id = participants.program_id WHERE restorative_justice_programs.location = 'CA' GROUP BY restorative_justice_programs.name HAVING num_participants > 50;
What is the minimum mental health score for students in each school that has more than one student?
CREATE TABLE student_mental_health (student_id INT,school_id INT,score INT); INSERT INTO student_mental_health (student_id,school_id,score) VALUES (1,100,80),(2,100,75),(3,200,90),(4,200,85),(5,300,70);
SELECT school_id, MIN(score) as min_score FROM student_mental_health GROUP BY school_id HAVING COUNT(student_id) > 1;
How many times has the Food Security Program been held in each community?
CREATE TABLE Communities (CommunityID INT,Name TEXT); CREATE TABLE Programs (ProgramID INT,Name TEXT,CommunityID INT);
SELECT C.Name as CommunityName, COUNT(P.ProgramID) as ProgramCount FROM Communities C INNER JOIN Programs P ON C.CommunityID = P.CommunityID WHERE P.Name = 'Food Security Program' GROUP BY C.CommunityID, C.Name;
What are the average innovation scores for each product category, grouped by month?
CREATE TABLE Product(Id INT,Category VARCHAR(50),ManufacturerId INT); CREATE TABLE InnovationScore(Id INT,Score INT,ProductId INT,ScoreDate DATE);
SELECT p.Category, DATE_FORMAT(i.ScoreDate, '%Y-%m') AS Month, AVG(i.Score) AS AverageScore FROM InnovationScore i JOIN Product p ON i.ProductId = p.Id GROUP BY p.Category, Month;
What is the total number of basketball matches played by teams from the USA after 2021-12-31?
CREATE TABLE Teams (TeamID INT PRIMARY KEY,TeamName VARCHAR(100),Sport VARCHAR(50),Country VARCHAR(50)); INSERT INTO Teams (TeamID,TeamName,Sport,Country) VALUES (1,'Boston Celtics','Basketball','USA'); CREATE TABLE Matches (MatchID INT PRIMARY KEY,HomeTeamID INT,AwayTeamID INT,MatchDate DATETIME); INSERT INTO Matches (MatchID,HomeTeamID,AwayTeamID,MatchDate) VALUES (1,1,2,'2022-01-01 15:00:00');
SELECT COUNT(*) as TotalMatches FROM Matches JOIN Teams ON Matches.HomeTeamID = Teams.TeamID WHERE Teams.Country = 'USA' AND MatchDate > '2021-12-31';
Calculate the total amount of grants awarded to SMEs in the 'grants_awarded' table, grouped by region and year, with amounts greater than $10,000?
CREATE TABLE grants_awarded (id INT,recipient_name VARCHAR(50),recipient_type VARCHAR(50),region VARCHAR(50),year INT,grant_amount DECIMAL(10,2));
SELECT region, year, SUM(grant_amount) FROM grants_awarded WHERE recipient_type = 'SME' AND grant_amount > 10000 GROUP BY region, year;
Calculate the percentage of tenured faculty members in the English department.
CREATE TABLE faculty (id INT,name VARCHAR(100),department VARCHAR(50),tenure VARCHAR(10));
SELECT (COUNT(*) FILTER (WHERE tenure = 'Yes')) * 100.0 / COUNT(*) AS tenure_percentage FROM faculty WHERE department = 'English';
What is the average yield of crops grown by female farmers?
CREATE TABLE Farmers (id INT,name VARCHAR(50),age INT,gender VARCHAR(10),location VARCHAR(50)); INSERT INTO Farmers (id,name,age,gender,location) VALUES (1,'John Doe',35,'Male','USA'); INSERT INTO Farmers (id,name,age,gender,location) VALUES (2,'Jane Smith',40,'Female','Canada'); CREATE TABLE Crops (id INT,farmer_id INT,crop_name VARCHAR(50),yield INT,price FLOAT); INSERT INTO Crops (id,farmer_id,crop_name,yield,price) VALUES (1,1,'Corn',120,2.5); INSERT INTO Crops (id,farmer_id,crop_name,yield,price) VALUES (2,2,'Wheat',150,3.2);
SELECT AVG(c.yield) AS average_yield FROM Crops c JOIN Farmers f ON c.farmer_id = f.id WHERE f.gender = 'Female';
List all genetic research projects in the 'genetic_research' table.
CREATE TABLE genetic_research (id INT,name TEXT,description TEXT); INSERT INTO genetic_research (id,name,description) VALUES (1,'ProjectX','Genome sequencing'),(2,'ProjectY','CRISPR study'),(3,'ProjectZ','Gene therapy');
SELECT * FROM genetic_research;
What is the total quantity of Yttrium imported by China from mines with a production capacity over 1500 tons?
CREATE TABLE YttriumShipments (id INT PRIMARY KEY,mine_id INT,import_year INT,quantity INT,FOREIGN KEY (mine_id) REFERENCES YttriumMines(id)); CREATE TABLE YttriumMines (id INT PRIMARY KEY,name VARCHAR(100),production_capacity INT);
SELECT SUM(quantity) FROM YttriumShipments INNER JOIN YttriumMines ON YttriumShipments.mine_id = YttriumMines.id WHERE YttriumShipments.country = 'China' AND YttriumMines.production_capacity > 1500;
What is the highest mental health score for patients who identify as Caucasian or Asian?
CREATE TABLE patient (id INT,name TEXT,mental_health_score INT,community TEXT); INSERT INTO patient (id,name,mental_health_score,community) VALUES (1,'John Doe',60,'Straight'),(2,'Jane Smith',70,'LGBTQ+'),(3,'Ana Garcia',50,'Latino'),(4,'Sara Johnson',85,'African American'),(5,'Hiroshi Tanaka',90,'Asian'),(6,'Peter Brown',80,'Caucasian');
SELECT MAX(mental_health_score) FROM patient WHERE community IN ('Caucasian', 'Asian');
What is the total value of military equipment sales to the United States from January 2020 to the present?
CREATE TABLE Military_Equipment_Sales(sale_id INT,sale_date DATE,equipment_type VARCHAR(50),country VARCHAR(50),sale_value DECIMAL(10,2));
SELECT SUM(sale_value) FROM Military_Equipment_Sales WHERE country = 'United States' AND sale_date >= '2020-01-01';
How many arts organizations in Colorado and Georgia have received funding and their total number of events?
CREATE TABLE arts_orgs (id INT,state VARCHAR(2),org_name VARCHAR(20)); CREATE TABLE org_events (id INT,org_name VARCHAR(20),num_events INT); CREATE TABLE funding_info (id INT,org_name VARCHAR(20),amount INT); INSERT INTO arts_orgs (id,state,org_name) VALUES (1,'CO','OrgA'),(2,'GA','OrgB'); INSERT INTO org_events (id,org_name,num_events) VALUES (1,'OrgA',3),(2,'OrgB',4); INSERT INTO funding_info (id,org_name,amount) VALUES (1,'OrgA',10000),(2,'OrgB',15000);
SELECT COUNT(DISTINCT ao.org_name), SUM(oe.num_events) FROM arts_orgs ao INNER JOIN org_events oe ON ao.org_name = oe.org_name INNER JOIN funding_info fi ON ao.org_name = fi.org_name WHERE ao.state IN ('CO', 'GA');
What is the average time taken to resolve restorative justice programs in Washington?
CREATE TABLE restorative_justice_programs (program_id INT,state VARCHAR(2),duration INT); INSERT INTO restorative_justice_programs (program_id,state,duration) VALUES (1,'WA',30),(2,'WA',45);
SELECT AVG(duration) FROM restorative_justice_programs WHERE state = 'WA';
List all unique vessel types for vessels with safety incidents in the North Sea.
CREATE TABLE Vessels (ID INT,Name VARCHAR(50),Type VARCHAR(50)); CREATE TABLE SafetyIncidents (ID INT,VesselID INT,Location VARCHAR(50),IncidentType VARCHAR(50)); INSERT INTO Vessels (ID,Name,Type) VALUES (1,'Ocean Titan','Cargo'); INSERT INTO SafetyIncidents (ID,VesselID,Location,IncidentType) VALUES (1,1,'North Sea','Collision'); INSERT INTO SafetyIncidents (ID,VesselID,Location,IncidentType) VALUES (2,2,'North Sea','Grounding');
SELECT DISTINCT v.Type FROM Vessels v INNER JOIN SafetyIncidents si ON v.ID = si.VesselID WHERE si.Location = 'North Sea';
What are the top 3 countries with the highest sales of cruelty-free makeup products?
CREATE TABLE makeup_sales (product_cruelty_free BOOLEAN,sale_country VARCHAR(20),sales_quantity INT); INSERT INTO makeup_sales (product_cruelty_free,sale_country,sales_quantity) VALUES (TRUE,'USA',250),(FALSE,'USA',180),(TRUE,'Canada',120),(FALSE,'Canada',90),(TRUE,'Mexico',80),(FALSE,'Mexico',110);
SELECT sale_country, SUM(sales_quantity) AS total_sales FROM makeup_sales WHERE product_cruelty_free = TRUE GROUP BY sale_country ORDER BY total_sales DESC LIMIT 3;
Show the number of policy types for each broker.
CREATE TABLE PolicyBroker (PolicyID INT,PolicyType VARCHAR(20),Broker VARCHAR(20)); INSERT INTO PolicyBroker (PolicyID,PolicyType,Broker) VALUES (1,'Auto','BrokerSmith'),(2,'Home','BrokerJones'),(3,'Auto','BrokerSmith');
SELECT Broker, COUNT(DISTINCT PolicyType) FROM PolicyBroker GROUP BY Broker;
Calculate the market share of the top 2 drugs by sales in the neurology department that were approved by the FDA before 2018, excluding companies from North America.
CREATE TABLE drugs (id INT,name VARCHAR(255),company VARCHAR(255),department VARCHAR(255),fda_approval_date DATE,sales FLOAT); INSERT INTO drugs (id,name,company,department,fda_approval_date,sales) VALUES (1,'DrugA','African Pharma','Neurology','2016-01-01',10000000),(2,'DrugB','European BioTech','Neurology','2017-06-15',12000000),(3,'DrugC','Asian Pharma','Neurology','2018-03-23',8000000),(4,'DrugD','Oceanic Pharma','Cardiology','2014-11-11',14000000),(5,'DrugE','South American Pharma','Neurology','2015-09-10',9000000);
SELECT (a.sales / (SELECT SUM(sales) FROM drugs WHERE department = 'Neurology' AND fda_approval_date < '2018-01-01' AND company NOT IN ('North America')) * 100) AS market_share FROM drugs a WHERE a.name IN (SELECT name FROM (SELECT name FROM drugs WHERE department = 'Neurology' AND fda_approval_date < '2018-01-01' AND company NOT IN ('North America') GROUP BY name ORDER BY SUM(sales) DESC LIMIT 2) b);
What is the total property price for co-owned properties in the co_ownership table?
CREATE TABLE co_ownership (id INT,property_price FLOAT,num_owners INT); INSERT INTO co_ownership (id,property_price,num_owners) VALUES (1,800000,2),(2,900000,3),(3,700000,2);
SELECT SUM(property_price) FROM co_ownership WHERE num_owners > 1;
List the names and ages of all employees in the employees table who have a higher salary than the average salary in their respective department.
CREATE TABLE employees (employee_name VARCHAR(50),age INT,department_name VARCHAR(50),salary DECIMAL(10,2));
SELECT employee_name, age FROM employees WHERE salary > (SELECT AVG(salary) FROM employees WHERE employees.department_name = department_name) GROUP BY department_name;
How many collective bargaining agreements were signed in the "union_database" in 2020 and 2021?
CREATE TABLE cb_agreements (id INT,year INT,num_agreements INT); INSERT INTO cb_agreements (id,year,num_agreements) VALUES (1,2018,30),(2,2019,40),(3,2020,50),(4,2021,60);
SELECT SUM(num_agreements) FROM cb_agreements WHERE year IN (2020, 2021);
Find the difference in the number of trees between the tree species with the highest and lowest wildlife habitat scores in the state_parks schema.
CREATE TABLE state_parks.wildlife_habitat (species VARCHAR(255),score DECIMAL(5,2));
SELECT species_high.species AS high_species, species_low.species AS low_species, species_high.score - species_low.score AS difference FROM (SELECT species, MAX(score) AS score FROM state_parks.wildlife_habitat GROUP BY species) AS species_high FULL OUTER JOIN (SELECT species, MIN(score) AS score FROM state_parks.wildlife_habitat GROUP BY species) AS species_low ON species_high.score = species_low.score;
What is the total number of public health policy changes in the last 5 years, categorized by type?
CREATE TABLE public_health_policy (id INT,policy_type VARCHAR(20),change_date DATE); INSERT INTO public_health_policy (id,policy_type,change_date) VALUES (1,'Regulation','2017-08-01'); INSERT INTO public_health_policy (id,policy_type,change_date) VALUES (2,'Funding','2018-12-25'); INSERT INTO public_health_policy (id,policy_type,change_date) VALUES (3,'Legislation','2019-04-10');
SELECT policy_type, COUNT(*) as policy_changes FROM public_health_policy WHERE change_date >= DATEADD(year, -5, GETDATE()) GROUP BY policy_type;
What is the average time spent on spacewalks by each astronaut?
CREATE TABLE Spacewalks (id INT,astronaut VARCHAR(255),duration INT); INSERT INTO Spacewalks (id,astronaut,duration) VALUES (1,'Neil Armstrong',216); INSERT INTO Spacewalks (id,astronaut,duration) VALUES (2,'Buzz Aldrin',151);
SELECT astronaut, AVG(duration) FROM Spacewalks GROUP BY astronaut;
What is the average account balance for financial capability accounts in the Southeast region?
CREATE TABLE southeast_region (region VARCHAR(20),account_type VARCHAR(30),account_balance DECIMAL(10,2)); INSERT INTO southeast_region (region,account_type,account_balance) VALUES ('Southeast','Financial Capability',7000.00),('Southeast','Financial Capability',8000.00),('Southeast','Financial Literacy',6000.00);
SELECT AVG(account_balance) FROM southeast_region WHERE account_type = 'Financial Capability';
What is the average citizen satisfaction score for healthcare services in urban areas?
CREATE TABLE Citizen_Feedback (Service VARCHAR(255),Location VARCHAR(255),Satisfaction_Score DECIMAL(3,1)); INSERT INTO Citizen_Feedback (Service,Location,Satisfaction_Score) VALUES ('Healthcare','Urban',8.5),('Healthcare','Urban',9.0),('Healthcare','Rural',7.5),('Education','Urban',8.0),('Education','Rural',8.0);
SELECT AVG(Satisfaction_Score) FROM Citizen_Feedback WHERE Service = 'Healthcare' AND Location = 'Urban';
What is the total funding received by biotech startups based in the United States?
CREATE SCHEMA if not exists biotech; CREATE TABLE if not exists biotech.startups (id INT PRIMARY KEY,name VARCHAR(255),location VARCHAR(255),funding FLOAT); INSERT INTO biotech.startups (id,name,location,funding) VALUES (1,'StartupA','USA',5000000),(2,'StartupB','USA',7000000),(3,'StartupC','Canada',3000000);
SELECT SUM(funding) FROM biotech.startups WHERE location = 'USA';
How many total artifacts were found in each year, by artifact type?
CREATE TABLE artifacts (id INT,find_year INT,artifact_type VARCHAR(255),artifact_weight FLOAT);
SELECT artifact_type, find_year, COUNT(*) AS total_artifacts FROM artifacts GROUP BY artifact_type, find_year;
How many animals have been released in 'Community Education Center B' since 2018?
CREATE TABLE ReleasedAnimals (ReleaseID INT,AnimalID INT,ReleaseDate DATE,EducationCenterID INT); INSERT INTO ReleasedAnimals (ReleaseID,AnimalID,ReleaseDate,EducationCenterID) VALUES (3,3,'2018-01-01',2); INSERT INTO ReleasedAnimals (ReleaseID,AnimalID,ReleaseDate,EducationCenterID) VALUES (4,4,'2017-12-31',2);
SELECT COUNT(*) FROM ReleasedAnimals WHERE EducationCenterID = 2 AND ReleaseDate >= '2018-01-01';
List all volunteers who have not been assigned to a project.
CREATE TABLE volunteers (id INT,name VARCHAR(100),project_id INT); INSERT INTO volunteers (id,name,project_id) VALUES (1,'Jane Smith',NULL),(2,'Pedro Rodriguez',1),(3,'John Doe',NULL);
SELECT name FROM volunteers WHERE project_id IS NULL;
Delete records of broadband subscribers in the Seattle region who have not used their service in the last 3 months.
CREATE TABLE broadband_subscribers (subscriber_id INT,name VARCHAR(50),plan VARCHAR(50),last_usage DATE,region VARCHAR(50)); INSERT INTO broadband_subscribers (subscriber_id,name,plan,last_usage,region) VALUES (1,'Bruce Willis','100 Mbps','2022-03-15','Seattle');
DELETE FROM broadband_subscribers WHERE region = 'Seattle' AND last_usage <= DATE_SUB(CURRENT_DATE, INTERVAL 3 MONTH);
Which mobile plans have had more than 10,000 complaints in the state of California?
CREATE TABLE mobile_complaints (id INT,plan_type VARCHAR(10),state VARCHAR(20),complaints INT);
SELECT plan_type, state FROM mobile_complaints WHERE state = 'California' AND complaints > 10000;
Which heritage sites are located in South America?
CREATE TABLE HeritageSites (SiteID int,SiteName varchar(50),Country varchar(50)); INSERT INTO HeritageSites (SiteID,SiteName,Country) VALUES (1,'Giza Pyramids','Egypt'),(2,'African Renaissance Monument','Senegal'),(3,'Taj Mahal','India'),(4,'Angkor Wat','Cambodia'),(5,'Machu Picchu','Peru');
SELECT SiteName FROM HeritageSites WHERE Country = 'Peru';
What is the average number of community policing events per week in 'eastside' in the second half of 2021?
CREATE TABLE community_policing (id INT,event_type VARCHAR(20),location VARCHAR(20),event_date DATE); INSERT INTO community_policing (id,event_type,location,event_date) VALUES (1,'meeting','eastside','2021-07-01');
SELECT AVG(COUNT(*)) FROM community_policing WHERE location = 'eastside' AND event_date BETWEEN '2021-07-01' AND '2021-12-31' GROUP BY (event_date - INTERVAL '7 days')::interval;
What are the names of the companies that produced devices in the 'Africa' region?
CREATE TABLE AfricaDevices (id INT,company VARCHAR(255),region VARCHAR(255)); INSERT INTO AfricaDevices (id,company,region) VALUES (1,'TechAfrica','Africa'),(2,'InnoAfrica','Africa');
SELECT company FROM AfricaDevices WHERE region = 'Africa';
What is the percentage of workplaces with successful collective bargaining in the retail sector?
CREATE TABLE workplaces (id INT,name TEXT,location TEXT,sector TEXT,total_employees INT,union_members INT,successful_cb BOOLEAN,cb_year INT);
SELECT (COUNT(*) * 100.0 / (SELECT COUNT(*) FROM workplaces WHERE sector = 'retail')) AS percentage FROM workplaces WHERE sector = 'retail' AND successful_cb = TRUE;
What is the maximum salary of employees who work in the IT department?
CREATE TABLE Employees (EmployeeID INT,Gender VARCHAR(10),Department VARCHAR(20),Salary FLOAT); INSERT INTO Employees (EmployeeID,Gender,Department,Salary) VALUES (1,'Male','IT',80000),(2,'Female','IT',85000),(3,'Male','IT',82000),(4,'Female','IT',88000),(5,'Non-binary','IT',83000);
SELECT MAX(Salary) FROM Employees WHERE Department = 'IT';
List all menu items that contain 'salad' in their name from the 'Menu' table.
CREATE TABLE Menu (id INT,name VARCHAR(255),price DECIMAL(5,2),vegetarian BOOLEAN); INSERT INTO Menu (id,name,price,vegetarian) VALUES (1,'Chicken Burger',7.99,FALSE),(2,'Veggie Wrap',6.49,TRUE),(3,'Chicken Caesar Salad',9.99,FALSE);
SELECT name FROM Menu WHERE name LIKE '%salad%';
Which spacecraft have been used in space missions by astronauts aged 40 or older?
CREATE TABLE spacecraft_experience (astronaut_id INT,spacecraft TEXT); INSERT INTO spacecraft_experience (astronaut_id,spacecraft) VALUES (1,'SpaceX Dragon'),(2,'Soyuz'),(3,'Space Shuttle'); CREATE TABLE astronauts (id INT,name TEXT,age INT); INSERT INTO astronauts (id,name,age) VALUES (1,'Maria',45),(2,'James',35),(3,'Anna',42); CREATE TABLE space_missions (id INT,astronaut_id INT,spacecraft TEXT); INSERT INTO space_missions (id,astronaut_id,spacecraft) VALUES (1,1,'SpaceX Dragon'),(2,2,'Soyuz'),(3,3,'Space Shuttle');
SELECT spacecraft FROM spacecraft_experience se JOIN astronauts a ON se.astronaut_id = a.id WHERE a.age >= 40;
Add a new vegan and cruelty-free product to the database.
CREATE TABLE products (product_id INT,product_name TEXT,is_vegan BOOLEAN,is_cruelty_free BOOLEAN);
INSERT INTO products (product_id, product_name, is_vegan, is_cruelty_free) VALUES (123, 'New Vegan Product', TRUE, TRUE);
List all underrepresented farmers and their ages in the 'rural_development' database, sorted by age in descending order.
CREATE TABLE underrepresented_farmer (farmer_id INT,name VARCHAR(50),age INT,ethnicity VARCHAR(50),location VARCHAR(50)); INSERT INTO underrepresented_farmer (farmer_id,name,age,ethnicity,location) VALUES (1,'Sanaa',35,'Latina','Rural Area');
SELECT * FROM underrepresented_farmer ORDER BY age DESC;
What are the names and research interests of professors who have not advised any graduate students in the past year?
CREATE TABLE professor_advising (id INT,professor TEXT,num_students INT,year INT); INSERT INTO professor_advising (id,professor,num_students,year) VALUES (15,'Carl',0,2021); INSERT INTO professor_advising (id,professor,num_students,year) VALUES (16,'Dana',2,2020);
SELECT professor, research_interest FROM professors p LEFT JOIN professor_advising pa ON p.name = pa.professor WHERE pa.num_students IS NULL;
How many accessibility-related technology patents were filed by females in the USA and Europe in 2021?
CREATE TABLE Patent (PatentID int,PatentName varchar(255),FilerName varchar(255),FilingDate date,Country varchar(255)); INSERT INTO Patent (PatentID,PatentName,FilerName,FilingDate,Country) VALUES (1,'AI-based accessibility tool','Jane Doe','2021-01-01','USA'),(2,'Voice recognition software','Alice Smith','2021-05-15','UK'),(3,'Adaptive learning platform','Jane Doe','2021-12-31','USA');
SELECT COUNT(*) as NumPatents FROM Patent WHERE YEAR(FilingDate) = 2021 AND (Country = 'USA' OR Country = 'UK') AND FilerName LIKE '%[fF]%';
What is the total number of hours spent on VR games by players from Japan?
CREATE TABLE Players (PlayerID INT,Age INT,Gender VARCHAR(10),Country VARCHAR(20),TotalHoursPlayed INT,FavoriteGame VARCHAR(10)); INSERT INTO Players (PlayerID,Age,Gender,Country,TotalHoursPlayed,FavoriteGame) VALUES (1,25,'Male','Japan',10,'VR'); INSERT INTO Players (PlayerID,Age,Gender,Country,TotalHoursPlayed,FavoriteGame) VALUES (2,30,'Female','Japan',15,'VR');
SELECT SUM(TotalHoursPlayed) FROM Players WHERE Country = 'Japan' AND FavoriteGame = 'VR';
What is the difference in yield between the highest and lowest yielding crop for each location?
CREATE TABLE farming (id INT,name TEXT,location TEXT,crop TEXT,yield INT); INSERT INTO farming VALUES (1,'Smith Farm','Colorado','Corn',120),(2,'Brown Farm','Nebraska','Soybeans',45),(3,'Jones Farm','Iowa','Wheat',80);
SELECT location, MAX(yield) - MIN(yield) as yield_diff FROM farming GROUP BY location;
Identify the number of tree species that have a critically endangered status.
CREATE TABLE tree_species (name VARCHAR(255),status VARCHAR(255));
SELECT COUNT(*) FROM tree_species WHERE status = 'critically endangered';
What is the average population of countries with a GDP less than 1.5 and more than 30 million visitors in the international_visitors table?
CREATE TABLE countries (country_id INT,name VARCHAR(50),population INT,gdp FLOAT); INSERT INTO countries (country_id,name,population,gdp) VALUES (1,'Brazil',210147125,1.432); INSERT INTO countries (country_id,name,population,gdp) VALUES (2,'Indonesia',273523615,1.019);
SELECT AVG(c.population) FROM countries c INNER JOIN (SELECT country_id, SUM(visitors) as total_visitors FROM international_visitors GROUP BY country_id) iv ON c.country_id = iv.country_id WHERE c.gdp < 1.5 AND total_visitors > 30000000;
What is the total number of vulnerabilities found for each severity level in the 'vulnerability_assessments' table?
CREATE TABLE vulnerability_assessments (id INT,vulnerability VARCHAR(50),severity VARCHAR(10));
SELECT severity, SUM(1) FROM vulnerability_assessments GROUP BY severity;
What is the total cost of all 'humanitarian_aid' operations before 2000 in the 'aid_operations' table?
CREATE TABLE aid_operations (id INT,operation_name VARCHAR(50),start_date DATE,end_date DATE,cost FLOAT); INSERT INTO aid_operations (id,operation_name,start_date,end_date,cost) VALUES (1,'Operation Provide Comfort','1991-04-05','1996-12-31',100000000); INSERT INTO aid_operations (id,operation_name,start_date,end_date,cost) VALUES (2,'Operation Lifeline Sudan','1989-05-20','2000-03-31',50000000);
SELECT SUM(cost) FROM aid_operations WHERE start_date < '2000-01-01';
What is the total number of employees in mining operations by country?
CREATE TABLE employee (id INT,name TEXT,department TEXT,role TEXT,location TEXT); INSERT INTO employee (id,name,department,role,location) VALUES (1,'John Doe','Mining','Operator','Colorado,USA'),(2,'Jane Smith','Environment','Analyst','Colorado,USA');
SELECT SUBSTRING(location, 1, INSTR(location, ',') - 1) as country, COUNT(*) as num_employees FROM employee WHERE department LIKE '%Mining%' GROUP BY country;
What is the total reclamation cost and number of employees for mines in the Asia-Pacific region with more than 500 employees?
CREATE TABLE production_data (id INT PRIMARY KEY,mine_id INT,year INT,monthly_production INT);CREATE TABLE reclamation_data (id INT PRIMARY KEY,mine_id INT,year INT,reclamation_cost INT);CREATE TABLE mine_employees (id INT PRIMARY KEY,mine_id INT,employee_id INT,employment_start_date DATE,employment_end_date DATE);CREATE TABLE employee_demographics (id INT PRIMARY KEY,employee_id INT,gender VARCHAR(255),ethnicity VARCHAR(255));CREATE VIEW employee_stats AS SELECT mine_id,COUNT(employee_id) as employee_count FROM mine_employees GROUP BY mine_id;CREATE VIEW operation_duration AS SELECT mine_id,COUNT(DISTINCT year) as operation_years FROM production_data GROUP BY mine_id;
SELECT r.mine_id, SUM(r.reclamation_cost) as total_reclamation_cost, e.employee_count FROM reclamation_data r JOIN employee_stats e ON r.mine_id = e.mine_id WHERE r.mine_id IN (SELECT mine_id FROM employee_stats WHERE employee_count > 500) AND e.mine_id IN (SELECT mine_id FROM employee_stats WHERE employee_count > 500) AND r.mine_id IN (SELECT mine_id FROM operation_duration WHERE operation_years > 5) GROUP BY r.mine_id;
Delete records from the 'crop_yields' table where 'crop' is 'Corn' and yield is below 100 bushels per acre.
CREATE TABLE crop_yields (id INT,crop VARCHAR(50),yield FLOAT,state VARCHAR(50)); INSERT INTO crop_yields (id,crop,yield,state) VALUES (1,'Corn',115,'IA'),(2,'Corn',98,'IN'),(3,'Soybeans',45,'IL'),(4,'Wheat',75,'KS');
DELETE FROM crop_yields WHERE crop = 'Corn' AND yield < 100;
What are the top 2 cosmetic brands with the most product recalls in India?
CREATE TABLE ProductRecalls (BrandID INT,ProductID INT,RecallDate DATE,Country VARCHAR(50)); CREATE TABLE Brands (BrandID INT,BrandName VARCHAR(50)); INSERT INTO ProductRecalls (BrandID,ProductID,RecallDate,Country) VALUES (3001,300,'2022-01-01','India'),(3002,301,'2022-02-01','India'),(3003,302,'2022-03-01','India'),(3001,303,'2022-04-01','India'),(3004,304,'2022-05-01','India'); INSERT INTO Brands (BrandID,BrandName) VALUES (3001,'BrandA'),(3002,'BrandB'),(3003,'BrandC'),(3004,'BrandD');
SELECT B.BrandName, COUNT(*) AS RecallCount FROM ProductRecalls PR INNER JOIN Brands B ON PR.BrandID = B.BrandID WHERE PR.Country = 'India' GROUP BY B.BrandName ORDER BY RecallCount DESC LIMIT 2;
What is the total number of workplace safety inspections in Pennsylvania with more than 5 violations?
CREATE TABLE WorkplaceSafetyInspections (id INT,location VARCHAR,inspection_date DATE,violations INT);
SELECT COUNT(id) as num_inspections FROM WorkplaceSafetyInspections WHERE location = 'Pennsylvania' AND violations > 5;
What is the waste generation by city for cities with a population above 750,000 that are not part of a circular economy initiative?
CREATE TABLE Cities (CityID INT,CityName VARCHAR(50),WasteGeneration FLOAT,Population INT,CircularEconomy BOOLEAN); INSERT INTO Cities VALUES (1,'CityA',1200,800000,FALSE),(2,'CityB',1800,1200000,TRUE),(3,'CityC',1500,1000000,FALSE),(4,'CityD',2000,900000,FALSE);
SELECT CityName, WasteGeneration FROM Cities WHERE Population > 750000 AND CircularEconomy = FALSE;
What is the total CO2 emissions of each manufacturing process in Germany?
CREATE TABLE manufacturing_processes (id INT,name TEXT,co2_emissions INT); INSERT INTO manufacturing_processes (id,name,co2_emissions) VALUES (1,'Cutting',50),(2,'Sewing',30),(3,'Dyeing',70); CREATE TABLE manufacturers (id INT,name TEXT,country TEXT); INSERT INTO manufacturers (id,name,country) VALUES (1,'ManufacturerA','Germany'),(2,'ManufacturerB','Germany'); CREATE TABLE process_emissions (process_id INT,manufacturer_id INT,emissions INT); INSERT INTO process_emissions (process_id,manufacturer_id,emissions) VALUES (1,1,100),(2,1,80),(3,1,150),(1,2,120),(2,2,70),(3,2,180);
SELECT mp.name, SUM(pe.emissions) FROM manufacturing_processes mp JOIN process_emissions pe ON mp.id = pe.process_id JOIN manufacturers m ON pe.manufacturer_id = m.id WHERE m.country = 'Germany' GROUP BY mp.name;
What is the number of unique customers who have made purchases using a mobile device in Canada?
CREATE TABLE customers (id INT,name VARCHAR(50),device VARCHAR(20)); CREATE TABLE orders (id INT,customer_id INT,order_value DECIMAL(10,2)); INSERT INTO customers (id,name,device) VALUES (1,'Customer A','mobile'),(2,'Customer B','desktop'),(3,'Customer C','mobile'); INSERT INTO orders (id,customer_id,order_value) VALUES (1,1,100.00),(2,2,75.20),(3,1,50.00);
SELECT COUNT(DISTINCT customers.id) FROM customers INNER JOIN orders ON customers.id = orders.customer_id WHERE customers.device = 'mobile' AND customers.country = 'Canada';
How many volunteers signed up in each month of 2020 from the 'volunteers' table?
CREATE TABLE volunteers (volunteer_id INT,signup_date DATE); INSERT INTO volunteers (volunteer_id,signup_date) VALUES (1,'2020-01-05'),(2,'2020-02-12'),(3,'2020-03-20'),(4,'2019-12-31');
SELECT DATEPART(YEAR, signup_date) as year, DATEPART(MONTH, signup_date) as month, COUNT(*) as num_volunteers FROM volunteers WHERE YEAR(signup_date) = 2020 GROUP BY DATEPART(YEAR, signup_date), DATEPART(MONTH, signup_date);
What is the total investment amount made in each country?
CREATE TABLE Investments (InvestmentID INT,Country VARCHAR(20),Amount INT); INSERT INTO Investments (InvestmentID,Country,Amount) VALUES (1,'USA',4000),(2,'Canada',3000),(3,'Mexico',5000),(4,'Brazil',6000),(5,'USA',7000),(6,'Canada',8000);
SELECT Country, SUM(Amount) as TotalInvestment FROM Investments GROUP BY Country;
What is the population rank of the state with the most public libraries in the United States?
CREATE TABLE State (StateName VARCHAR(50),Country VARCHAR(50),NumberOfPublicLibraries INT,Population INT); INSERT INTO State (StateName,Country,NumberOfPublicLibraries,Population) VALUES ('California','United States',1500,39500000),('Texas','United States',500,29500000),('New York','United States',1000,20000000);
SELECT ROW_NUMBER() OVER (ORDER BY NumberOfPublicLibraries DESC) AS PopulationRank, StateName FROM State WHERE Country = 'United States';
Get the average salary for Engineers in the Aerospace Department
CREATE TABLE Employees (EmployeeID INT,FirstName VARCHAR(50),LastName VARCHAR(50),Position VARCHAR(50),Department VARCHAR(50),Salary DECIMAL(10,2)); INSERT INTO Employees (EmployeeID,FirstName,LastName,Position,Department,Salary) VALUES (1,'John','Doe','Engineer','Aerospace',75000.00); INSERT INTO Employees (EmployeeID,FirstName,LastName,Position,Department,Salary) VALUES (2,'Jane','Doe','Manager','Flight Safety',85000.00);
SELECT AVG(Salary) FROM Employees WHERE Position = 'Engineer' AND Department = 'Aerospace';
How many education programs are in the 'community_education' table?
CREATE TABLE community_education (id INT PRIMARY KEY,program_name VARCHAR,num_participants INT);
SELECT COUNT(*) FROM community_education;
Which countries have the lowest and highest technology accessibility scores in the world?
CREATE TABLE technology_accessibility_scores (id INT,country VARCHAR(255),score FLOAT); CREATE VIEW lowest_tech_accessibility AS SELECT country,score FROM technology_accessibility_scores WHERE score = (SELECT MIN(score) FROM technology_accessibility_scores); CREATE VIEW highest_tech_accessibility AS SELECT country,score FROM technology_accessibility_scores WHERE score = (SELECT MAX(score) FROM technology_accessibility_scores);
SELECT * FROM lowest_tech_accessibility; SELECT * FROM highest_tech_accessibility;
What is the market share of eco-friendly cosmetics brands in the US?
CREATE TABLE brands (brand_name VARCHAR(50),country VARCHAR(50),is_eco_friendly BOOLEAN); INSERT INTO brands (brand_name,country,is_eco_friendly) VALUES ('Brand X','US',true),('Brand Y','Canada',false);
SELECT COUNT(*) * 100.0 / (SELECT COUNT(*) FROM brands WHERE country = 'US') FROM brands WHERE is_eco_friendly = true;
What is the total cost of all utility services for property 3?
CREATE TABLE public.property_utilities (id serial PRIMARY KEY,property_id integer,utility_type varchar,utility_cost integer,utility_start_date date,utility_end_date date);
SELECT SUM(utility_cost) FROM property_utilities WHERE property_id = 3;
List the co-owners and their shared property addresses in Vancouver, BC.
CREATE TABLE co_owners (id INT,name VARCHAR(30),property_id INT); CREATE TABLE properties (id INT,address VARCHAR(50),city VARCHAR(20)); INSERT INTO co_owners (id,name,property_id) VALUES (1,'Alex',101),(2,'Bella',101),(3,'Charlie',102); INSERT INTO properties (id,address,city) VALUES (101,'1234 SE Stark St','Vancouver'),(102,'5678 NE 20th Ave','Vancouver');
SELECT co_owners.name, properties.address FROM co_owners INNER JOIN properties ON co_owners.property_id = properties.id WHERE properties.city = 'Vancouver';