instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
Delete all donations made before the start of the current year.
CREATE TABLE Donations (DonationID INT,DonorID INT,ProgramID INT,DonationAmount DECIMAL(10,2),DonationDate DATE); INSERT INTO Donations (DonationID,DonorID,ProgramID,DonationAmount,DonationDate) VALUES (1,1,1,1000.00,'2021-01-10'),(2,2,2,500.00,'2020-12-15');
DELETE FROM Donations WHERE DonationDate < DATEADD(year, DATEDIFF(year, 0, GETDATE()), 0)
Display the total wins, draws, and losses, and calculate the percentage of wins and losses for each team, in the soccer_league dataset.
CREATE TABLE soccer_league (team VARCHAR(50),result VARCHAR(50));
SELECT team, SUM(CASE WHEN result = 'win' THEN 1 ELSE 0 END) as wins, SUM(CASE WHEN result = 'draw' THEN 1 ELSE 0 END) as draws, SUM(CASE WHEN result = 'loss' THEN 1 ELSE 0 END) as losses, (SUM(CASE WHEN result = 'win' THEN 1 ELSE 0 END) * 100.0 / COUNT(*)) as win_percentage, (SUM(CASE WHEN result = 'loss' THEN 1 ELSE 0 END) * 100.0 / COUNT(*)) as loss_percentage FROM soccer_league GROUP BY team;
What is the total amount of treated wastewater in the Los Angeles region?
CREATE TABLE wastewater_treatment (id INT,region VARCHAR(255),treated_wastewater_volume FLOAT); INSERT INTO wastewater_treatment (id,region,treated_wastewater_volume) VALUES (1,'Los Angeles',500000),(2,'San Diego',400000),(3,'San Francisco',300000);
SELECT SUM(treated_wastewater_volume) FROM wastewater_treatment WHERE region = 'Los Angeles';
How many research grants were awarded to faculty members in the College of Engineering in 2018?
CREATE TABLE if not exists FACULTY(id INT,name TEXT,department TEXT,position TEXT,salary INT);CREATE TABLE if not exists GRANTS(id INT,faculty_id INT,grant_name TEXT,grant_amount INT,grant_date DATE,college TEXT);
SELECT COUNT(*) FROM GRANTS WHERE college = 'College of Engineering' AND grant_date LIKE '2018-%';
Insert a new donation record
CREATE TABLE Donations (id INT,amount FLOAT,donation_date DATE);
INSERT INTO Donations (id, amount, donation_date) VALUES (4, 300.0, '2021-10-01');
List the names of soccer teams in the Premier League that have more than 50% of their players born outside of the UK.
CREATE TABLE IF NOT EXISTS players (id INT,name VARCHAR(50),position VARCHAR(50),team VARCHAR(50),country VARCHAR(50)); CREATE VIEW IF NOT EXISTS uk_players AS SELECT team,COUNT(*) AS count FROM players WHERE country = 'UK' GROUP BY team;
SELECT team FROM players JOIN uk_players ON players.team = uk_players.team WHERE players.team IN (SELECT team FROM uk_players WHERE count < COUNT(*) * 0.5) AND players.country != 'UK' GROUP BY team HAVING COUNT(*) > (SELECT COUNT(*)/2 FROM players WHERE team = players.team);
What is the maximum, minimum, and average budget for support programs by disability type?
CREATE TABLE support_programs (program_id INT,program_name VARCHAR(50),budget INT,disability_type VARCHAR(50)); INSERT INTO support_programs (program_id,program_name,budget,disability_type) VALUES (1,'Accessible Technology',75000,'Visual');
SELECT disability_type, MAX(budget) as max_budget, MIN(budget) as min_budget, AVG(budget) as avg_budget FROM support_programs GROUP BY disability_type;
What is the maximum cost of an accommodation per disability type?
CREATE TABLE Accommodations (id INT,student_id INT,disability_type VARCHAR(50),cost FLOAT);
SELECT disability_type, MAX(cost) as max_cost FROM Accommodations GROUP BY disability_type;
Calculate the average sustainability score for products in the "Skincare" category.
CREATE TABLE products (id INT PRIMARY KEY,name VARCHAR(255),category VARCHAR(255),price DECIMAL(5,2)); CREATE TABLE sustainability_scores (id INT PRIMARY KEY,product_id INT,score INT); CREATE VIEW avg_sustainability_score AS SELECT product_id,AVG(score) as avg_score FROM sustainability_scores GROUP BY product_id;
SELECT category, AVG(avg_score) as avg_sustainability_score FROM avg_sustainability_score JOIN products ON avg_sustainability_score.product_id = products.id WHERE category = 'Skincare' GROUP BY category;
What was the total climate finance provided to small island nations in 2020?
CREATE TABLE climate_finance (year INT,country VARCHAR(255),amount FLOAT); INSERT INTO climate_finance VALUES (2020,'Maldives',700000),(2020,'Fiji',800000);
SELECT SUM(amount) FROM climate_finance WHERE YEAR(STR_TO_DATE(country, '%Y')) = 2020 AND LENGTH(country) = 4;
Update the safety rating of vehicle with id '123' in 'Vehicle Safety Testing' table to 'Excellent'.
CREATE TABLE Vehicle_Safety_Testing (vehicle_id INT,safety_rating VARCHAR(20));
UPDATE Vehicle_Safety_Testing SET safety_rating = 'Excellent' WHERE vehicle_id = 123;
What is the maximum investment in bioprocess engineering in Japan?
CREATE SCHEMA if not exists biotech; CREATE TABLE if not exists biotech.investment (id INT PRIMARY KEY,type VARCHAR(255),country VARCHAR(255),amount FLOAT); INSERT INTO biotech.investment (id,type,country,amount) VALUES (1,'Biosensor Technology Development','Japan',1200000); INSERT INTO biotech.investment (id,type,country,amount) VALUES (2,'Bioprocess Engineering','Japan',1800000);
SELECT MAX(amount) FROM biotech.investment WHERE country = 'Japan' AND type = 'Bioprocess Engineering';
How many crops are grown in 'family_farms' table for region '06'?
CREATE TABLE family_farms (id INT,region VARCHAR(10),crop VARCHAR(20));
SELECT COUNT(DISTINCT crop) FROM family_farms WHERE region = '06';
What is the minimum donation amount made by a donor from Australia?
CREATE TABLE Donors (DonorID INT,DonorName TEXT,Country TEXT); INSERT INTO Donors (DonorID,DonorName,Country) VALUES (1,'John Doe','USA'),(2,'Jane Smith','Australia'); CREATE TABLE Donations (DonationID INT,DonorID INT,DonationAmount INT); INSERT INTO Donations (DonationID,DonorID,DonationAmount) VALUES (1,1,100),(2,1,200),(3,2,30),(4,2,50);
SELECT MIN(DonationAmount) FROM Donations JOIN Donors ON Donations.DonorID = Donors.DonorID WHERE Donors.Country = 'Australia';
Identify rural hospitals that have had an increase in ER visits between 2019 and 2020
CREATE TABLE hospitals (hospital_name TEXT,location TEXT,type TEXT); INSERT INTO hospitals (hospital_name,location,type) VALUES ('Pocahontas Memorial Hospital','Pocahontas,IA','rural'),('Memorial Hospital of Converse County','Douglas,WY','rural'); CREATE TABLE visits (hospital TEXT,visit_date DATE,visit_type TEXT); INSERT INTO visits (hospital,visit_date,visit_type) VALUES ('Pocahontas Memorial Hospital','2019-06-12','ER'),('Pocahontas Memorial Hospital','2020-07-02','ER'),('Memorial Hospital of Converse County','2019-05-28','ER'),('Memorial Hospital of Converse County','2020-05-25','ER'),('Memorial Hospital of Converse County','2020-06-20','ER');
SELECT h.hospital_name, COUNT(v2.hospital) - COUNT(v1.hospital) as er_increase FROM hospitals h JOIN visits v1 ON h.hospital_name = v1.hospital AND YEAR(v1.visit_date) = 2019 AND v1.visit_type = 'ER' JOIN visits v2 ON h.hospital_name = v2.hospital AND YEAR(v2.visit_date) = 2020 AND v2.visit_type = 'ER' GROUP BY h.hospital_name HAVING COUNT(v2.hospital) - COUNT(v1.hospital) > 0;
What is the daily sales trend for each product category in the last month?
CREATE TABLE Product (id INT,name VARCHAR(255),category VARCHAR(255),revenue FLOAT,sale_date DATE);
SELECT category, sale_date, SUM(revenue) as daily_sales FROM Product WHERE sale_date >= (CURRENT_DATE - INTERVAL '1 month') GROUP BY ROLLUP(category, sale_date) ORDER BY category, sale_date DESC;
What is the total number of medium-risk vulnerabilities found in the HR department this year?
CREATE TABLE DepartmentVulnerabilities (id INT,department VARCHAR(255),vulnerability_risk VARCHAR(255),vulnerability_date DATE);
SELECT SUM(*) as total_medium_vulnerabilities FROM DepartmentVulnerabilities WHERE department = 'HR' AND vulnerability_risk = 'medium' AND vulnerability_date >= DATEADD(year, -1, GETDATE());
List the top 3 esports teams with the highest total earnings, along with the number of tournaments they have participated in.
CREATE TABLE esports_teams (id INT,name VARCHAR(50),total_earnings DECIMAL(10,2));CREATE TABLE tournaments (id INT,team_id INT,prize_money DECIMAL(10,2));
SELECT e.name, SUM(t.prize_money) AS total_earnings, COUNT(t.id) AS tournaments_participated FROM esports_teams e INNER JOIN tournaments t ON e.id = t.team_id GROUP BY e.id ORDER BY total_earnings DESC, tournaments_participated DESC LIMIT 3;
Delete space debris records in the "space_debris_mitigation" table that are not within the latitude range -90 to 90.
CREATE TABLE space_debris_mitigation (id INT,debris_name VARCHAR(50),latitude FLOAT,longitude FLOAT); INSERT INTO space_debris_mitigation (id,debris_name,latitude,longitude) VALUES (1,'Debris1',50,20); INSERT INTO space_debris_mitigation (id,debris_name,latitude,longitude) VALUES (2,'Debris2',-100,40);
DELETE FROM space_debris_mitigation WHERE latitude NOT BETWEEN -90 AND 90;
Display the total sales revenue for halal skincare products in Malaysia.
CREATE TABLE cosmetics_sales(product_id INT,country VARCHAR(255),product_type VARCHAR(255),sales_quantity INT,sales_revenue DECIMAL(10,2)); CREATE TABLE product_details(product_id INT,product_type VARCHAR(255),is_halal BOOLEAN);
SELECT SUM(sales_revenue) FROM cosmetics_sales cs JOIN product_details pd ON cs.product_id = pd.product_id WHERE cs.country = 'Malaysia' AND pd.is_halal = TRUE AND cs.product_type = 'skincare';
Delete records in the "humanitarian_assistance" table for "Food Aid" in Kenya from 2017
CREATE TABLE humanitarian_assistance (assistance_id INT PRIMARY KEY,assistance_type VARCHAR(50),country VARCHAR(50),year INT); INSERT INTO humanitarian_assistance (assistance_id,assistance_type,country,year) VALUES (1,'Food Aid','Kenya',2016),(2,'Water Supply','Pakistan',2017),(3,'Medical Aid','Syria',2018);
DELETE FROM humanitarian_assistance WHERE assistance_type = 'Food Aid' AND country = 'Kenya' AND year = 2017;
Add a new record to the "GovernmentAgencies" table with the name "Environmental Protection Agency" and the abbreviation "EPA"
CREATE TABLE GovernmentAgencies (Name VARCHAR(255),Abbreviation VARCHAR(255));
INSERT INTO GovernmentAgencies (Name, Abbreviation) VALUES ('Environmental Protection Agency', 'EPA');
What is the total number of veterans employed in the top 10 industries for veteran employment, and what is the average number of veterans employed in these industries?
CREATE TABLE Veteran_Employment (Veteran_ID INT,Employment_Status VARCHAR(50),Industry VARCHAR(50),Employment_Start_Date DATE,Company_Name VARCHAR(50)); CREATE VIEW Top_Industries AS SELECT Industry,COUNT(*) as Number_of_Veterans FROM Veteran_Employment GROUP BY Industry ORDER BY Number_of_Veterans DESC;
SELECT Industry, AVG(Number_of_Veterans) as Average_Number_of_Veterans FROM Top_Industries WHERE ROWNUM <= 10 GROUP BY Industry; SELECT SUM(Number_of_Veterans) as Total_Number_of_Veterans FROM Top_Industries WHERE ROWNUM <= 10;
What is the average water consumption of organic cotton production in different regions?
CREATE TABLE water_consumption (region VARCHAR(50),water_consumption INT); INSERT INTO water_consumption (region,water_consumption) VALUES ('North America',2000),('South America',2500),('Asia',1500),('Europe',1800),('Africa',2200);
SELECT region, AVG(water_consumption) FROM water_consumption GROUP BY region;
How many defense contracts were awarded each month in 2020?
CREATE TABLE ContractMonths (ContractID INT,ContractDate DATE); INSERT INTO ContractMonths (ContractID,ContractDate) VALUES (1,'2020-01-15'),(2,'2020-02-10'),(3,'2020-03-20'),(4,'2020-04-25'),(5,'2020-05-10'),(6,'2020-06-18'),(7,'2020-07-05'),(8,'2020-08-12'),(9,'2020-09-20'),(10,'2020-10-30'),(11,'2020-11-15'),(12,'2020-12-28');
SELECT EXTRACT(MONTH FROM ContractDate) AS Month, COUNT(*) FROM ContractMonths WHERE ContractDate BETWEEN '2020-01-01' AND '2020-12-31' GROUP BY Month ORDER BY Month;
What are the names of the autonomous vehicles that participated in safety testing?
CREATE TABLE Vehicle (id INT,name TEXT,is_autonomous BOOLEAN); CREATE TABLE SafetyTesting (id INT,vehicle_id INT); INSERT INTO Vehicle (id,name,is_autonomous) VALUES (1,'Waymo',true),(2,'Tesla',true),(3,'Camry',false); INSERT INTO SafetyTesting (id,vehicle_id) VALUES (1,1),(2,2),(3,3);
SELECT Vehicle.name FROM Vehicle INNER JOIN SafetyTesting ON Vehicle.id = SafetyTesting.vehicle_id WHERE is_autonomous = true;
What is the number of startups founded by people from underrepresented communities in the AI sector that have received Series A funding or higher?
CREATE TABLE companies (id INT,name TEXT,industry TEXT,founder_community TEXT,funding_round TEXT,funding FLOAT);
SELECT COUNT(*) FROM companies WHERE industry = 'AI' AND founder_community IN ('underrepresented1', 'underrepresented2', 'underrepresented3') AND funding_round IN ('Series A', 'Series B', 'Series C', 'Series D', 'Series E', 'Series F', 'Series G', 'Series H');
What is the average life expectancy in each country for people with a college degree?
CREATE TABLE life_expectancy (country VARCHAR(255),education VARCHAR(255),life_expectancy INT); INSERT INTO life_expectancy (country,education,life_expectancy) VALUES ('US','College',80),('US','High School',75),('Canada','College',82),('Canada','High School',78);
SELECT country, AVG(life_expectancy) FROM life_expectancy WHERE education = 'College' GROUP BY country;
Update the soil moisture for 'Field_4' to 50 in the 'soil_moisture' table.
CREATE TABLE soil_moisture (field VARCHAR(255),moisture FLOAT,timestamp TIMESTAMP);
UPDATE soil_moisture SET moisture = 50 WHERE field = 'Field_4';
What is the average number of labor rights violations in workplaces in Italy?
CREATE TABLE workplaces (id INT,country VARCHAR(50),num_lrvs INT,num_employees INT); INSERT INTO workplaces (id,country,num_lrvs,num_employees) VALUES (1,'Italy',2,100),(2,'Italy',5,200),(3,'Italy',3,150);
SELECT AVG(num_lrvs/num_employees) FROM workplaces WHERE country = 'Italy';
What is the minimum wage in the 'hospitality' industry across all unionized workplaces?
CREATE TABLE if NOT EXISTS workplaces (id INT,industry VARCHAR(20),wage DECIMAL(5,2),is_unionized BOOLEAN); INSERT INTO workplaces (id,industry,wage,is_unionized) VALUES (1,'hospitality',12.00,true),(2,'hospitality',15.00,false),(3,'retail',10.00,false);
SELECT MIN(wage) FROM workplaces WHERE industry = 'hospitality' AND is_unionized = true;
What is the total number of AI safety incidents reported in each month?
CREATE TABLE ai_safety_incidents (id INT,incident_name VARCHAR(50),date_reported DATE); INSERT INTO ai_safety_incidents (id,incident_name,date_reported) VALUES (1,'Autopilot Crash','2022-03-15'),(2,'Cancer Misdiagnosis','2021-11-27'),(3,'Financial Loss','2022-01-10'),(4,'Algorithmic Discrimination','2022-02-12'),(5,'AI Ethics Violation','2021-12-01');
SELECT EXTRACT(MONTH FROM date_reported) AS month, COUNT(*) FROM ai_safety_incidents GROUP BY month;
What is the average funding amount for series B rounds in the "fintech" sector?
CREATE TABLE investments (company_id INT,round TEXT,amount INT); INSERT INTO investments (company_id,round,amount) VALUES (1,'series A',3000000),(1,'series B',8000000),(2,'series A',2000000),(3,'series B',12000000),(3,'series A',1500000);
SELECT AVG(amount) FROM investments JOIN company ON investments.company_id = company.id WHERE company.industry = 'fintech' AND round = 'series B';
Who are the top-rated female artists from Africa and their highest-rated artworks?
CREATE TABLE Artists (ArtistID INT,ArtistName TEXT,Gender TEXT,Region TEXT); INSERT INTO Artists (ArtistID,ArtistName,Gender,Region) VALUES (1,'Nina Kankondi','Female','Africa'); INSERT INTO Artists (ArtistID,ArtistName,Gender,Region) VALUES (2,'Grace Kagwira','Female','Africa'); CREATE TABLE Artworks (ArtworkID INT,ArtworkName TEXT,ArtistID INT,AverageRating DECIMAL(3,2)); INSERT INTO Artworks (ArtworkID,ArtworkName,ArtistID,AverageRating) VALUES (1,'Sunset Over Kilimanjaro',1,4.8); INSERT INTO Artworks (ArtworkID,ArtworkName,ArtistID,AverageRating) VALUES (2,'Dance of the Maasai',2,4.7);
SELECT A.ArtistName, MAX(AverageRating) as HighestRating FROM Artworks A JOIN Artists B ON A.ArtistID = B.ArtistID WHERE B.Gender = 'Female' AND B.Region = 'Africa' GROUP BY A.ArtistName;
Find the policy type with the highest total claim amount in the Risk Assessment department in Q1 2023?
CREATE TABLE Claims (ClaimID INT,PolicyType VARCHAR(20),ProcessingDepartment VARCHAR(20),ProcessingDate DATE,ClaimAmount INT); INSERT INTO Claims (ClaimID,PolicyType,ProcessingDepartment,ProcessingDate,ClaimAmount) VALUES (1,'Auto','Risk Assessment','2023-01-10',5000),(2,'Home','Risk Assessment','2023-02-15',20000),(3,'Auto','Risk Assessment','2023-03-20',70000);
SELECT PolicyType, SUM(ClaimAmount) as TotalClaimAmount FROM Claims WHERE ProcessingDepartment = 'Risk Assessment' AND ProcessingDate BETWEEN '2023-01-01' AND '2023-03-31' GROUP BY PolicyType ORDER BY TotalClaimAmount DESC LIMIT 1;
What is the percentage of union members who are female, for each union?
CREATE TABLE union_members (union_name TEXT,member_gender TEXT); INSERT INTO union_members (union_name,member_gender) VALUES ('Union A','Male'),('Union A','Male'),('Union A','Female'),('Union B','Male'),('Union B','Female'),('Union C','Male'),('Union C','Male'),('Union C','Male'),('Union D','Male'),('Union D','Female'),('Union D','Female'),('Union E','Male'),('Union E','Female'),('Union E','Female'),('Union E','Female');
SELECT union_name, 100.0 * SUM(CASE WHEN member_gender = 'Female' THEN 1 ELSE 0 END) / COUNT(*) as pct_female_members FROM union_members GROUP BY union_name;
What is the average safety rating for AI models in the 'ai_safety' table that have a bias score greater than 0.5?
CREATE TABLE ai_safety (app_id INT,app_name TEXT,bias_score FLOAT,safety_rating FLOAT);
SELECT AVG(safety_rating) FROM ai_safety WHERE bias_score > 0.5;
What is the total funding received by startups founded by people from underrepresented racial or ethnic groups?
CREATE TABLE company (id INT,name TEXT,founder_race TEXT); INSERT INTO company (id,name,founder_race) VALUES (1,'GreenTech','Hispanic'); INSERT INTO company (id,name,founder_race) VALUES (2,'SmartCities','African American');
SELECT SUM(funding_amount) FROM funding INNER JOIN company ON funding.company_id = company.id WHERE company.founder_race IN ('Hispanic', 'African American', 'Native American', 'Pacific Islander', 'South Asian', 'East Asian');
What are the energy efficiency ratings of the top 3 countries?
CREATE TABLE country_energy_efficiency (country VARCHAR(50),rating FLOAT); INSERT INTO country_energy_efficiency (country,rating) VALUES ('Brazil',82.4),('Canada',87.1),('Australia',78.9),('India',75.6),('China',70.5);
SELECT country, rating FROM country_energy_efficiency ORDER BY rating DESC LIMIT 3;
What is the average amount of donations given by individual donors from the United States?
CREATE TABLE donors (id INT,name VARCHAR(100),country VARCHAR(50),donation DECIMAL(10,2)); INSERT INTO donors (id,name,country,donation) VALUES (1,'John Doe','USA',50.00),(2,'Jane Smith','USA',100.00),(3,'Alice Johnson','Canada',75.00);
SELECT AVG(donation) FROM donors WHERE country = 'USA';
What is the total economic impact of sustainable tourism in South America?
CREATE TABLE sustainable_tourism (tourism_id INT,location VARCHAR(50),economic_impact INT); INSERT INTO sustainable_tourism VALUES (1,'Maasai Mara',15000),(2,'Victoria Falls',20000),(3,'Sahara Desert',10000),(4,'Serengeti',25000),(5,'Angkor Wat',30000),(6,'Galapagos Islands',40000);
SELECT SUM(economic_impact) FROM sustainable_tourism WHERE location LIKE '%South America%';
List all suppliers from the "SupplyChain" table who provide vegan ingredients
CREATE TABLE SupplyChain (id INT,supplier_name VARCHAR(50),ingredient VARCHAR(50),vegan BOOLEAN); INSERT INTO SupplyChain (id,supplier_name,ingredient,vegan) VALUES (1,'Supplier1','Tofu',true),(2,'Supplier2','Chicken',false);
SELECT DISTINCT supplier_name FROM SupplyChain WHERE vegan = true;
What is the average budget (in USD) for UN peacekeeping operations in Asia for the years 2016-2020?
CREATE TABLE peacekeeping_operations(id INT,operation_name VARCHAR(255),region VARCHAR(255),budget INT,operation_year INT); INSERT INTO peacekeeping_operations(id,operation_name,region,budget,operation_year) VALUES (1,'MINUSTAH','Americas',50000000,2016),(2,'MONUSCO','Africa',100000000,2017),(3,'UNFICYP','Asia',60000000,2018),(4,'UNMIK','Europe',70000000,2019),(5,'UNMOGIP','Asia',80000000,2020);
SELECT AVG(budget) FROM peacekeeping_operations WHERE region = 'Asia' AND operation_year BETWEEN 2016 AND 2020;
What is the total weight of pottery and jewelry artifacts for each site?
CREATE TABLE ExcavationSites (SiteID INT,SiteName TEXT,Country TEXT); INSERT INTO ExcavationSites (SiteID,SiteName,Country) VALUES (1,'Pompeii','Italy'); INSERT INTO ExcavationSites (SiteID,SiteName,Country) VALUES (2,'Giza','Egypt'); CREATE TABLE ArtifactTypes (TypeID INT,ArtifactID INT,ArtifactType TEXT); INSERT INTO ArtifactTypes (TypeID,ArtifactID,ArtifactType) VALUES (1,1,'Pottery'); INSERT INTO ArtifactTypes (TypeID,ArtifactID,ArtifactType) VALUES (2,2,'Jewelry'); CREATE TABLE ArtifactWeights (WeightID INT,ArtifactID INT,Weight DECIMAL(5,2)); INSERT INTO ArtifactWeights (WeightID,ArtifactID,Weight) VALUES (1,1,2.3); INSERT INTO ArtifactWeights (WeightID,ArtifactID,Weight) VALUES (2,2,3.4); INSERT INTO ArtifactWeights (WeightID,ArtifactID,Weight) VALUES (3,3,1.9); INSERT INTO ArtifactWeights (WeightID,ArtifactID,Weight) VALUES (4,4,2.7);
SELECT e.SiteName, SUM(CASE WHEN a.ArtifactType IN ('Pottery', 'Jewelry') THEN w.Weight ELSE 0 END) AS TotalWeight FROM ExcavationSites e JOIN ArtifactAnalysis a ON e.SiteID = a.SiteID JOIN ArtifactWeights w ON a.ArtifactID = w.ArtifactID GROUP BY e.SiteName;
What is the total play time and average score for each platform?
CREATE TABLE PlayerPlatforms (PlayerID int,GameName varchar(50),PlayTime int,Score int,Platform varchar(20)); INSERT INTO PlayerPlatforms (PlayerID,GameName,PlayTime,Score,Platform) VALUES (3,'GameE',180,85,'PC'); INSERT INTO PlayerPlatforms (PlayerID,GameName,PlayTime,Score,Platform) VALUES (4,'GameF',220,90,'Console');
SELECT Platform, SUM(PlayTime) as TotalPlayTime, AVG(Score) as AvgScore FROM PlayerPlatforms pp JOIN Games g ON pp.GameName = g.GameName GROUP BY Platform;
Identify the top 3 community development initiatives with the highest budget in Asia, including the project name, country, and budget.
CREATE TABLE community_development (project_name VARCHAR(50),country VARCHAR(50),project_start_date DATE,budget DECIMAL(10,2),region VARCHAR(50));
SELECT project_name, country, budget FROM community_development WHERE region = 'Asia' ORDER BY budget DESC LIMIT 3;
How many graduate students are enrolled in each department in the College of Health and Human Services?
CREATE TABLE grad_enrollment (id INT,student_id INT,student_major VARCHAR(50)); INSERT INTO grad_enrollment (id,student_id,student_major) VALUES (1,1001,'Nursing'),(2,1002,'Public Health'),(3,1003,'Social Work'),(4,1004,'Occupational Therapy'),(5,1005,'Physical Therapy');
SELECT student_major, COUNT(*) FROM grad_enrollment WHERE student_major LIKE '%Health and Human Services%' GROUP BY student_major;
How many geothermal power plants are there in New Zealand and Indonesia?
CREATE TABLE geothermal_plants (id INT,name TEXT,country TEXT); INSERT INTO geothermal_plants (id,name,country) VALUES (1,'Wairakei','New Zealand'),(2,'Ohaaki','New Zealand'),(3,'Broadlands','New Zealand'),(4,'Dieng','Indonesia'),(5,'Salak','Indonesia'),(6,'Wayang Windu','Indonesia');
SELECT COUNT(*) FROM geothermal_plants WHERE country IN ('New Zealand', 'Indonesia');
What is the average cost of cybersecurity software in the 'cybersecurity_software' table?
CREATE TABLE cybersecurity_software (id INT,software_name TEXT,type TEXT,cost FLOAT);
SELECT AVG(cost) FROM cybersecurity_software WHERE type = 'Software';
What is the average time between vehicle maintenance events for each maintenance center?
CREATE TABLE VEHICLE_MAINTENANCE_TIME (maintenance_center TEXT,maintenance_date DATE,vehicle_id INT); INSERT INTO VEHICLE_MAINTENANCE_TIME (maintenance_center,maintenance_date,vehicle_id) VALUES ('North','2022-02-01',123),('North','2022-02-03',123),('South','2022-02-02',456),('East','2022-02-04',789),('West','2022-02-05',111);
SELECT maintenance_center, AVG(time_between_maintenance) FROM (SELECT maintenance_center, vehicle_id, maintenance_date, maintenance_date - lag(maintenance_date) OVER (PARTITION BY vehicle_id ORDER BY maintenance_date) AS time_between_maintenance FROM VEHICLE_MAINTENANCE_TIME) subquery GROUP BY maintenance_center;
Create a table named 'ethical_ai_research'
CREATE TABLE ethical_ai_research (id INT PRIMARY KEY,title VARCHAR(255),abstract TEXT,author_name VARCHAR(255),author_affiliation VARCHAR(255),publication_date DATETIME);
CREATE TABLE ethical_ai_research (id INT PRIMARY KEY, title VARCHAR(255), abstract TEXT, author_name VARCHAR(255), author_affiliation VARCHAR(255), publication_date DATETIME);
What is the maximum funding received by a biotech startup in the first quarter of 2022?
CREATE TABLE BiotechStartupFunding (startup_id INT,funding_date DATE,funding_amount FLOAT); INSERT INTO BiotechStartupFunding (startup_id,funding_date,funding_amount) VALUES (1,'2022-01-10',8000000.00),(2,'2022-03-15',12000000.50),(3,'2022-02-28',9000000.25),(4,'2022-04-01',7000000.00),(5,'2022-01-05',10000000.00);
SELECT MAX(funding_amount) FROM BiotechStartupFunding WHERE funding_date BETWEEN '2022-01-01' AND '2022-03-31';
What is the total value of military equipment sold to Southeast Asian countries by Boeing in 2022?
CREATE TABLE MilitaryEquipmentSales (seller VARCHAR(255),buyer VARCHAR(255),equipment VARCHAR(255),sale_value FLOAT,sale_date DATE); INSERT INTO MilitaryEquipmentSales (seller,buyer,equipment,sale_value,sale_date) VALUES ('Boeing','Indonesia','Chinook Helicopter',35000000,'2022-03-22');
SELECT SUM(sale_value) FROM MilitaryEquipmentSales WHERE seller = 'Boeing' AND buyer LIKE 'Southeast%' AND sale_date BETWEEN '2022-01-01' AND '2022-12-31';
Increase the number of mental health parity violations for California by 10?
CREATE TABLE mental_health_parity (state VARCHAR(50),violations INT); INSERT INTO mental_health_parity (state,violations) VALUES ('California',150),('Texas',120),('New York',180);
UPDATE mental_health_parity SET violations = violations + 10 WHERE state = 'California';
Update the 'price' column for all records in the 'products' table with a 'category_id' of 4 to 25% off the original price
CREATE TABLE products (product_id INT,product_name VARCHAR(255),category_id INT,price DECIMAL(5,2));
UPDATE products SET price = price * 0.75 WHERE category_id = 4;
Insert a new record in the "renewable_energy" table with values "biomass" for "source" and 100 for "capacity_mw"
CREATE TABLE renewable_energy (id INT PRIMARY KEY,source VARCHAR(50),capacity_mw INT);
INSERT INTO renewable_energy (source, capacity_mw) VALUES ('biomass', 100);
What is the average time between maintenance for each type of vehicle in the 'fleet' table?
CREATE TABLE fleet (id INT,type TEXT,last_maintenance DATE,next_maintenance DATE); INSERT INTO fleet (id,type,last_maintenance,next_maintenance) VALUES (1,'bus','2022-01-01','2022-04-01'),(2,'bus','2022-02-01','2022-05-01'),(3,'tram','2022-03-01','2022-06-01'),(4,'train','2022-04-01','2022-07-01');
SELECT type, AVG(DATEDIFF(day, last_maintenance, next_maintenance)) as avg_days_between_maintenance FROM fleet GROUP BY type;
How many volunteers signed up for each program in Q2 2021?
CREATE TABLE Programs (ProgramID int,ProgramName varchar(50)); CREATE TABLE Volunteers (VolunteerID int,VolunteerName varchar(50),ProgramID int);
SELECT ProgramName, COUNT(VolunteerID) as NumVolunteers FROM Programs P JOIN Volunteers V ON P.ProgramID = V.ProgramID WHERE QUARTER(VolunteerDate) = 2 AND YEAR(VolunteerDate) = 2021 GROUP BY ProgramName;
Identify the number of female faculty members who have been principal investigators on research grants in the past year, grouped by department.
CREATE TABLE faculty (faculty_id INT PRIMARY KEY,name VARCHAR(50),gender VARCHAR(50),department VARCHAR(50),pi_on_grant BOOLEAN); INSERT INTO faculty (faculty_id,name,gender,department,pi_on_grant) VALUES (1,'Anna','Female','Biology',TRUE); CREATE TABLE grants (grant_id INT PRIMARY KEY,faculty_id INT,grant_date DATE); INSERT INTO grants (grant_id,faculty_id,grant_date) VALUES (1,1,'2022-01-01');
SELECT f.department, COUNT(*) as num_female_pis FROM faculty f INNER JOIN grants g ON f.faculty_id = g.faculty_id WHERE f.gender = 'Female' AND g.grant_date >= DATEADD(year, -1, GETDATE()) AND f.pi_on_grant = TRUE GROUP BY f.department;
What is the most common mental health condition treated in the Northern region?
CREATE TABLE condition_region (patient_id INT,region TEXT,condition TEXT); INSERT INTO condition_region (patient_id,region,condition) VALUES (7,'Northern','Depression'); INSERT INTO condition_region (patient_id,region,condition) VALUES (8,'Northern','Anxiety Disorder'); INSERT INTO condition_region (patient_id,region,condition) VALUES (9,'Southern','Depression');
SELECT condition, COUNT(*) FROM condition_region WHERE region = 'Northern' GROUP BY condition ORDER BY COUNT(*) DESC LIMIT 1;
Which genetic research projects have received funding in the last 3 years?
CREATE SCHEMA if not exists genetic;CREATE TABLE if not exists genetic.projects (id INT PRIMARY KEY,name VARCHAR(100),start_date DATE);CREATE TABLE if not exists genetic.funding (id INT PRIMARY KEY,project_id INT,amount FLOAT,funding_date DATE);INSERT INTO genetic.projects (id,name,start_date) VALUES (1,'ProjectX','2018-01-01'),(2,'ProjectY','2020-05-15'),(3,'ProjectZ','2017-08-08');INSERT INTO genetic.funding (id,project_id,amount,funding_date) VALUES (1,1,2000000.0,'2021-03-22'),(2,2,3000000.0,'2020-06-01'),(3,3,1500000.0,'2019-09-09');
SELECT projects.name FROM genetic.projects INNER JOIN genetic.funding ON projects.id = funding.project_id WHERE funding_date >= DATE_SUB(CURRENT_DATE, INTERVAL 3 YEAR);
Determine the number of times each dish was ordered in the month of January 2022.
CREATE TABLE orders (id INT,dish_id INT,order_date DATE);
SELECT dish_id, COUNT(*) FROM orders WHERE order_date BETWEEN '2022-01-01' AND '2022-01-31' GROUP BY dish_id;
What is the total donation amount for donors from historically underrepresented communities?
CREATE TABLE donors (id INT,name VARCHAR(50),community VARCHAR(50),donation DECIMAL(10,2));
SELECT SUM(donation) FROM donors WHERE community IN ('Indigenous', 'Black', 'Latinx');
List unique countries that received military innovation support from the Air Force in 2018 and 2020.
CREATE TABLE military_innovation (id INT,service VARCHAR(10),year INT,country VARCHAR(50)); INSERT INTO military_innovation (id,service,year,country) VALUES (1,'Air Force',2018,'Brazil'); INSERT INTO military_innovation (id,service,year,country) VALUES (2,'Air Force',2020,'Nigeria');
SELECT DISTINCT country FROM military_innovation WHERE service = 'Air Force' AND year IN (2018, 2020);
What is the total number of words spoken by female and male characters in a TV show?
CREATE TABLE tv_show (id INT,scene VARCHAR(255),character VARCHAR(50),lines VARCHAR(255)); INSERT INTO tv_show (id,scene,character,lines) VALUES (1,'Scene1','Female','50 words'),(2,'Scene2','Male','75 words'),(3,'Scene3','Female','80 words');
SELECT SUM(LENGTH(lines) - LENGTH(REPLACE(lines, ' ', '')) + 1) as words_spoken, character FROM tv_show GROUP BY character;
What is the total number of 'Prepaid' customers in the 'Northern' and 'Southern' regions?
CREATE TABLE Customers (CustomerID INT,Plan VARCHAR(20),Region VARCHAR(20)); INSERT INTO Customers (CustomerID,Plan,Region) VALUES (1,'Postpaid','Central'),(2,'Prepaid','Northern'),(3,'Postpaid','Southern'),(4,'Prepaid','Northern'),(5,'Prepaid','Southern');
SELECT COUNT(*) as TotalCustomers FROM Customers WHERE Plan = 'Prepaid' AND (Region = 'Northern' OR Region = 'Southern');
What is the average number of hospitals per state, ordered from highest to lowest?
CREATE TABLE States (StateName VARCHAR(50),NumberOfHospitals INT); INSERT INTO States (StateName,NumberOfHospitals) VALUES ('Alabama',126),('Alaska',12),('Arizona',118),('Arkansas',95),('California',481);
SELECT AVG(NumberOfHospitals) AS AvgHospitalsPerState FROM States
Which element had the lowest production decrease from 2018 to 2019 in North America?
CREATE TABLE production (year INT,region VARCHAR(10),element VARCHAR(10),quantity INT); INSERT INTO production (year,region,element,quantity) VALUES (2015,'North America','Lutetium',1200),(2016,'North America','Lutetium',1400),(2017,'North America','Lutetium',1500),(2018,'North America','Lutetium',1700),(2019,'North America','Lutetium',1600);
SELECT element, MIN(quantity_diff) FROM (SELECT element, (quantity - LAG(quantity) OVER (PARTITION BY element ORDER BY year)) AS quantity_diff FROM production WHERE region = 'North America' AND year BETWEEN 2018 AND 2019) subquery WHERE quantity_diff IS NOT NULL GROUP BY element;
Show the total cost of military equipment maintenance requests in H1 2022
CREATE TABLE military_equipment_maintenance (request_id INT,cost FLOAT,request_date DATE); INSERT INTO military_equipment_maintenance (request_id,cost,request_date) VALUES (1,5000,'2022-01-01'),(2,10000,'2022-06-30');
SELECT SUM(cost) FROM military_equipment_maintenance WHERE request_date >= '2022-01-01' AND request_date < '2022-07-01';
List the policy types and premiums for policyholder 1004 for policies issued in 2020 or later.
CREATE TABLE Policies (id INT,policyholder_id INT,policy_type VARCHAR(50),issue_date DATE,expiration_date DATE,premium DECIMAL(10,2)); INSERT INTO Policies (id,policyholder_id,policy_type,issue_date,expiration_date,premium) VALUES (3,1003,'Auto','2021-01-15','2022-01-14',1500.00); INSERT INTO Policies (id,policyholder_id,policy_type,issue_date,expiration_date,premium) VALUES (4,1004,'Renters','2020-07-01','2023-06-30',800.00);
SELECT policyholder_id, policy_type, premium FROM Policies WHERE policyholder_id = 1004 AND issue_date >= '2020-01-01';
List all the bus stops in the city of Cape Town, South Africa, that do not have any recorded issues.
bus_stops (id,name,city,country,issues)
SELECT bus_stops.* FROM bus_stops WHERE bus_stops.issues IS NULL AND bus_stops.city = 'Cape Town';
How many courses are taught by each instructor, and what are their average start dates?
CREATE TABLE courses (id INT,name VARCHAR(50),instructor VARCHAR(50),start_date DATE,end_date DATE); INSERT INTO courses (id,name,instructor,start_date,end_date) VALUES (1,'Python Programming','Alice Smith','2023-01-01','2023-06-30');
SELECT instructor, COUNT(name) as num_courses, AVG(start_date) as avg_start_date FROM courses GROUP BY instructor;
Which countries had geopolitical risk assessments in Q3 2022?
CREATE TABLE RiskAssessments (country_name VARCHAR(255),assessment_date DATE); INSERT INTO RiskAssessments (country_name,assessment_date) VALUES ('USA','2022-07-15'),('Canada','2022-08-01'),('Mexico','2022-09-10'),('Brazil','2022-07-25');
SELECT DISTINCT country_name FROM RiskAssessments WHERE assessment_date BETWEEN '2022-07-01' AND '2022-09-30';
Find the number of FOIA requests submitted and fulfilled by department in the last year
CREATE TABLE FOIARequests (RequestID INT,Department TEXT,RequestDate DATE,FulfillmentDate DATE); INSERT INTO FOIARequests (RequestID,Department,RequestDate,FulfillmentDate) VALUES (1,'Police','2022-01-01','2022-02-15'),(2,'Education','2022-03-01','2022-04-01'),(3,'Health','2022-02-10','2022-03-15');
SELECT Department, COUNT(*) FROM FOIARequests WHERE RequestDate >= DATEADD(year, -1, GETDATE()) AND FulfillmentDate IS NOT NULL GROUP BY Department;
What is the percentage of female and male students in the university?
CREATE TABLE university (id INT,name VARCHAR(255)); CREATE TABLE department (id INT,name VARCHAR(255),university_id INT); CREATE TABLE student (id INT,department_id INT,gender VARCHAR(10)); INSERT INTO university (id,name) VALUES (1,'University of Example'); INSERT INTO department (id,name,university_id) VALUES (1,'Engineering',1),(2,'Humanities',1); INSERT INTO student (id,department_id,gender) VALUES (1,1,'Female'),(2,1,'Male'),(3,2,'Female');
SELECT 'Female' as gender, 100.0 * COUNT(CASE WHEN student.gender = 'Female' THEN 1 END) / COUNT(student.id) as percentage FROM student; SELECT 'Male' as gender, 100.0 * COUNT(CASE WHEN student.gender = 'Male' THEN 1 END) / COUNT(student.id) as percentage FROM student;
What are the names and local economic impacts of sustainable tourism activities in India?
CREATE TABLE SustainableTourismActivities (activity_id INT,activity_name TEXT,country TEXT,local_economic_impact FLOAT); INSERT INTO SustainableTourismActivities (activity_id,activity_name,country,local_economic_impact) VALUES (1,'Yoga Retreat','India',20000.0),(2,'Spice Tour','India',18000.0);
SELECT activity_name, local_economic_impact FROM SustainableTourismActivities WHERE country = 'India';
Insert records into the 'creative_applications' table for a new AI tool called 'MusicalMind' that generates music and has been evaluated by 4 judges
CREATE TABLE creative_applications (id INT PRIMARY KEY,application_name VARCHAR(50),art_form VARCHAR(20),num_judges INT,total_score INT);
INSERT INTO creative_applications (id, application_name, art_form, num_judges, total_score) VALUES (1, 'MusicalMind', 'music', 4, 0); UPDATE creative_applications SET total_score = total_score + (judge1_score + judge2_score + judge3_score + judge4_score) WHERE application_name = 'MusicalMind';
What is the average age of patients who completed a mindfulness-based cognitive therapy (MBCT) program, compared to those who did not?
CREATE TABLE patients (patient_id INT,age INT,gender TEXT,state TEXT); INSERT INTO patients (patient_id,age,gender,state) VALUES (1,35,'Female','California'); INSERT INTO patients (patient_id,age,gender,state) VALUES (2,45,'Male','Texas'); CREATE TABLE treatments (treatment_id INT,patient_id INT,treatment TEXT,date DATE,completion_date DATE); INSERT INTO treatments (treatment_id,patient_id,treatment,date,completion_date) VALUES (1,1,'MBCT','2021-01-01','2021-03-01'); INSERT INTO treatments (treatment_id,patient_id,treatment,date) VALUES (2,2,'Medication','2021-01-02');
SELECT AVG(CASE WHEN treatments.completion_date IS NOT NULL THEN patients.age ELSE NULL END) AS mbct_completers_avg_age, AVG(CASE WHEN treatments.completion_date IS NULL THEN patients.age ELSE NULL END) AS mbct_non_completers_avg_age FROM patients INNER JOIN treatments ON patients.patient_id = treatments.patient_id WHERE treatments.treatment = 'MBCT';
How many artworks are there in each category?
CREATE TABLE Artworks (artwork_name TEXT,category TEXT);
SELECT category, COUNT(*) as artwork_count FROM Artworks GROUP BY category;
What are the total number of accidents for each aircraft manufacturer?
CREATE TABLE accidents (id INT PRIMARY KEY,manufacturer VARCHAR(50),accident_year INT); INSERT INTO accidents (id,manufacturer,accident_year) VALUES (1,'Boeing',2000),(2,'Airbus',2005),(3,'Boeing',2010),(4,'Airbus',2015);
SELECT manufacturer, COUNT(*) FROM accidents GROUP BY manufacturer;
Calculate the total amount of resources depleted in the mining industry, broken down by resource type.
CREATE TABLE resource_depletion (id INT,mining_operation_id INT,resource_type VARCHAR(50),amount_depleted FLOAT);
SELECT resource_type, SUM(amount_depleted) FROM resource_depletion GROUP BY resource_type;
Identify the total number of community education programs and total number of attendees for each program
CREATE TABLE community_education_program (id INT,name VARCHAR(50),location VARCHAR(50),total_attendees INT); INSERT INTO community_education_program (id,name,location,total_attendees) VALUES (1,'Wildlife Art Camp','New York',50),(2,'Endangered Species Day','Los Angeles',75),(3,'Bird Watching Tour','Yellowstone',30);
SELECT cep.name, cep.total_attendees, SUM(registration.attendees) as total_attendees_registered FROM community_education_program cep LEFT JOIN registration ON cep.id = registration.community_education_program_id GROUP BY cep.name;
Show the number of military innovation projects per category and year
CREATE TABLE military_innovation (id INT,project_category VARCHAR(50),year INT); INSERT INTO military_innovation (id,project_category,year) VALUES (1,'Artificial Intelligence',2018),(2,'Cybersecurity',2019),(3,'Robotics',2018),(4,'Energy',2019),(5,'Biotechnology',2018),(6,'Space',2019);
SELECT year, project_category, COUNT(*) as num_projects FROM military_innovation GROUP BY year, project_category;
Find the top 3 customers with the highest total transaction amount in Shariah-compliant finance by region.
CREATE TABLE shariah_compliant_finance (id INT,customer_name VARCHAR(50),region VARCHAR(20),amount DECIMAL(10,2)); INSERT INTO shariah_compliant_finance (id,customer_name,region,amount) VALUES (1,'Ahmed','Middle East',1000.00),(2,'Fatima','Africa',2000.00),(3,'Zainab','Asia',3000.00);
SELECT customer_name, region, SUM(amount) as total_amount FROM shariah_compliant_finance GROUP BY region ORDER BY total_amount DESC LIMIT 3;
What is the percentage of students who prefer open pedagogy by country?
CREATE TABLE student_pedagogy_country (student_id INT,country VARCHAR(255),prefers_open_pedagogy BOOLEAN); INSERT INTO student_pedagogy_country (student_id,country,prefers_open_pedagogy) VALUES (1,'USA',TRUE),(2,'Canada',FALSE),(3,'Mexico',TRUE),(4,'Brazil',FALSE);
SELECT country, 100.0 * AVG(CASE WHEN prefers_open_pedagogy THEN 1 ELSE 0 END) as percentage_prefers_open_pedagogy FROM student_pedagogy_country GROUP BY country;
What is the total number of mental health parity violations per year in each state?
CREATE TABLE mental_health_parity (year INT,state VARCHAR(2),violations INT);
SELECT state, year, SUM(violations) FROM mental_health_parity GROUP BY state, year;
What is the number of new hires in each quarter of the last year?
CREATE TABLE Employees (EmployeeID INT,HireDate DATE);
SELECT DATEPART(QUARTER, HireDate) as Quarter, COUNT(*) as NewHires FROM Employees WHERE HireDate BETWEEN DATEADD(YEAR, -1, GETDATE()) AND GETDATE() GROUP BY DATEPART(QUARTER, HireDate);
Delete a housing policy from the housing_policies table
CREATE TABLE public.housing_policies (id SERIAL PRIMARY KEY,policy_name VARCHAR(255),policy_description TEXT,policy_start_date DATE,policy_end_date DATE); INSERT INTO public.housing_policies (policy_name,policy_description,policy_start_date,policy_end_date) VALUES ('Inclusive Housing Act','Requires 10% of new residential developments to be inclusive housing units.','2022-01-01','2026-12-31');
WITH deleted_policy AS (DELETE FROM public.housing_policies WHERE policy_name = 'Inclusive Housing Act' RETURNING *) INSERT INTO public.housing_policies (policy_name, policy_description, policy_start_date, policy_end_date) SELECT policy_name, policy_description, policy_start_date, policy_end_date FROM deleted_policy;
What is the average ticket price for each team, split by venue?
CREATE TABLE teams (team_id INT,team_name VARCHAR(255),venue_id INT); CREATE TABLE venues (venue_id INT,venue_name VARCHAR(255),avg_ticket_price DECIMAL(10,2)); INSERT INTO teams VALUES (1,'TeamA',1001),(2,'TeamB',1002); INSERT INTO venues VALUES (1001,'VenueA',75.00),(1002,'VenueB',100.00);
SELECT v.venue_name, t.team_name, v.avg_ticket_price FROM teams t JOIN venues v ON t.venue_id = v.venue_id;
Determine the number of intelligence personnel in each country, ordered by the total number of personnel in descending order.
CREATE TABLE intelligence_personnel (personnel_id INT,personnel_name VARCHAR(50),agency VARCHAR(50),country VARCHAR(50),rank VARCHAR(50)); INSERT INTO intelligence_personnel VALUES (1,'John Smith','CIA','United States','Analyst');
SELECT country, COUNT(*) FROM intelligence_personnel GROUP BY country ORDER BY COUNT(*) DESC;
What is the total budget allocated for public transportation in the city of Toronto?
CREATE TABLE city_budgets (city TEXT,category TEXT,budget FLOAT); INSERT INTO city_budgets (city,category,budget) VALUES ('Toronto','Public Transportation',8000000),('Toronto','Education',12000000),('Toronto','Healthcare',15000000);
SELECT SUM(budget) FROM city_budgets WHERE city = 'Toronto' AND category = 'Public Transportation';
What is the maximum number of satellites launched by a single country?
CREATE TABLE satellites_by_country (country VARCHAR(255),num_satellites INT); INSERT INTO satellites_by_country (country,num_satellites) VALUES ('USA',1500),('Russia',1200),('China',500),('India',400),('Japan',350),('Germany',250),('Italy',200);
SELECT MAX(num_satellites) FROM satellites_by_country;
How many biosensor technology patents have been filed in Mexico since 2016?
USE biotech; CREATE TABLE if not exists patents (id INT,name VARCHAR(255),country VARCHAR(255),filed_date DATE); INSERT INTO patents (id,name,country,filed_date) VALUES (1,'Patent1','Mexico','2016-01-01'),(2,'Patent2','USA','2014-01-01'),(3,'Patent3','Mexico','2018-01-01'),(4,'Patent4','Germany','2016-01-01');
SELECT COUNT(*) FROM patents WHERE country = 'Mexico' AND filed_date >= '2016-01-01';
What is the average yield per acre for each crop type in the 'Agroecology' schema?
CREATE SCHEMA Agroecology; CREATE TABLE crop_types_yields (crop_type TEXT,acres NUMERIC,yield NUMERIC); INSERT INTO crop_types_yields (crop_type,acres,yield) VALUES ('Wheat',2.1,13000),('Rice',3.5,18000),('Corn',4.2,25000),('Soybeans',2.9,16000);
SELECT crop_type, AVG(yield/acres) as avg_yield_per_acre FROM Agroecology.crop_types_yields GROUP BY crop_type;
How many tree species are present in the tropical rainforests of South America?
CREATE TABLE tree_species (forest_type VARCHAR(30),species_count INT); INSERT INTO tree_species (forest_type,species_count) VALUES ('Tropical Rainforest - South America',1234);
SELECT species_count FROM tree_species WHERE forest_type = 'Tropical Rainforest - South America';
Which organic ingredients have the least quantity in the inventory?
CREATE TABLE Inventory (item_id INT,name VARCHAR(50),is_organic BOOLEAN,quantity INT); INSERT INTO Inventory (item_id,name,is_organic,quantity) VALUES (1,'Apples',true,100),(2,'Broccoli',true,50),(3,'Beef',false,75),(4,'Organic Beans',true,25),(5,'Carrots',false,80);
SELECT name, quantity FROM Inventory WHERE is_organic = true ORDER BY quantity ASC;
What is the total number of natural disasters recorded in the 'rural' schema?
CREATE SCHEMA if not exists rural; CREATE TABLE if not exists rural.disaster_stats (id INT,disaster_type VARCHAR(255),disaster_count INT); INSERT INTO rural.disaster_stats (id,disaster_type,disaster_count) VALUES (1,'Tornado',25),(2,'Flood',45),(3,'Earthquake',32);
SELECT SUM(disaster_count) FROM rural.disaster_stats;
Determine the number of volunteers who have not made any donations.
CREATE TABLE volunteers (id INT,name TEXT); INSERT INTO volunteers (id,name) VALUES (1,'John Doe'),(2,'Jane Smith'),(3,'Mike Johnson'); CREATE TABLE donations (id INT,volunteer_id INT,amount INT); INSERT INTO donations (id,volunteer_id,amount) VALUES (1,1,100),(2,2,200),(3,4,300);
SELECT COUNT(*) FROM volunteers LEFT JOIN donations ON volunteers.id = donations.volunteer_id WHERE donations.volunteer_id IS NULL;
What is the number of teachers who have completed professional development in data science, by school district?
CREATE TABLE districts (district_id INT,district_name VARCHAR(255)); CREATE TABLE teachers (teacher_id INT,district_id INT,years_of_experience INT); CREATE TABLE workshops (workshop_id INT,district_id INT,workshop_topic VARCHAR(255),teacher_id INT); INSERT INTO districts (district_id,district_name) VALUES (1,'Downtown'),(2,'Uptown'); INSERT INTO teachers (teacher_id,district_id,years_of_experience) VALUES (1,1,5),(2,1,10),(3,2,3),(4,2,8); INSERT INTO workshops (workshop_id,district_id,workshop_topic,teacher_id) VALUES (1,1,'Data Science',1),(2,1,'Data Science',2),(3,2,'Data Science',3),(4,2,'Data Science',4);
SELECT sd.district_name, COUNT(w.teacher_id) as num_teachers FROM districts sd JOIN workshops w ON sd.district_id = w.district_id WHERE w.workshop_topic = 'Data Science' GROUP BY sd.district_name;
Display the total assets of all financial institutions in the database that are Shariah-compliant and offer socially responsible lending.
CREATE TABLE FinancialInstitutions (InstitutionID int,Name varchar(50),ShariahCompliant bit,SociallyResponsible bit); INSERT INTO FinancialInstitutions (InstitutionID,Name,ShariahCompliant,SociallyResponsible) VALUES (1,'Institution A',1,1); CREATE TABLE Assets (AssetID int,InstitutionID int,Amount decimal(10,2)); INSERT INTO Assets (AssetID,InstitutionID,Amount) VALUES (1,1,5000000.00);
SELECT SUM(A.Amount) FROM Assets A INNER JOIN FinancialInstitutions FI ON A.InstitutionID = FI.InstitutionID WHERE FI.ShariahCompliant = 1 AND FI.SociallyResponsible = 1;