instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
What is the total energy savings by energy efficiency policies in France?
CREATE TABLE energy_savings (id INT,policy_id INT,country VARCHAR(50),savings_amount FLOAT);
SELECT SUM(savings_amount) FROM energy_savings WHERE country = 'France';
What is the name and type of all satellites launched by China since 2015?
CREATE TABLE satellite (id INT,name VARCHAR(255),type VARCHAR(255),country VARCHAR(255),launch_date DATE); INSERT INTO satellite VALUES (1,'Beidou-2 G1','Navigation','China','2009-01-01'),(2,'Beidou-2 G2','Navigation','China','2010-01-01');
SELECT name, type FROM satellite WHERE country = 'China' AND launch_date > '2014-12-31';
What is the name and total supply of the top 3 digital assets by market cap?
CREATE TABLE digital_assets (asset_id INT,name VARCHAR(255),total_supply INT); CREATE TABLE market_caps (asset_id INT,market_cap INT); INSERT INTO digital_assets (asset_id,name,total_supply) VALUES (1,'CryptoCoin',21000000),(2,'DecentralizedApp',1000000),(3,'SmartContract',500000),(4,'DataToken',100000000); INSERT INTO...
SELECT name, total_supply FROM top_three_assets;
What is the maximum amount of funding received by a single organization in the year 2021?
CREATE TABLE funding (id INT,organization VARCHAR(255),year INT,amount DECIMAL(10,2));
SELECT MAX(amount) FROM funding WHERE year = 2021 GROUP BY organization HAVING COUNT(*) = 1;
What is the total number of crimes committed in each district, categorized by crime type?
CREATE TABLE Districts (DistrictID INT,Name VARCHAR(50)); CREATE TABLE Crimes (CrimeID INT,DistrictID INT,CrimeType VARCHAR(50),NumberOfOccurrences INT);
SELECT D.Name, C.CrimeType, SUM(C.NumberOfOccurrences) as TotalCrimes FROM Districts D INNER JOIN Crimes C ON D.DistrictID = C.DistrictID GROUP BY D.Name, C.CrimeType;
Update cultural competency training for community health workers in New York
CREATE TABLE cultural_competency_training (chw_id INT,state VARCHAR(2),year INT,completed BOOLEAN);
UPDATE cultural_competency_training SET completed = TRUE WHERE chw_id = 123 AND state = 'NY' AND year = 2022;
What are the names of vehicles that failed safety tests in Brazil in 2019?
CREATE TABLE VehicleSafetyTestsBrazil (vehicle_id INT,model VARCHAR(100),passed BOOLEAN,country VARCHAR(50),year INT); INSERT INTO VehicleSafetyTestsBrazil (vehicle_id,model,passed,country,year) VALUES (1,'Model S',false,'Brazil',2019),(2,'Gol',true,'Brazil',2019);
SELECT model FROM VehicleSafetyTestsBrazil WHERE passed = false AND country = 'Brazil' AND year = 2019;
Who has conducted the most space missions in collaboration with NASA?
CREATE TABLE space_missions (id INT,mission_name VARCHAR(50),partner_country VARCHAR(50),year INT); INSERT INTO space_missions (id,mission_name,partner_country,year) VALUES (1,'Apollo','Germany',1969),(2,'Mir','Russia',1986),(3,'Shenzhou','China',2003),(4,'Artemis','Canada',2024);
SELECT partner_country, COUNT(id) as missions_with_nasa FROM space_missions WHERE partner_country = 'USA' GROUP BY partner_country ORDER BY missions_with_nasa DESC;
What is the total investment in women-led businesses in rural areas of Mexico, grouped by business sector?
CREATE TABLE rural_areas (id INT,name VARCHAR(50),country VARCHAR(50)); INSERT INTO rural_areas (id,name,country) VALUES (1,'Chiapas','Mexico'); CREATE TABLE women_led_businesses (id INT,sector VARCHAR(50),investment FLOAT,rural_area_id INT); INSERT INTO women_led_businesses (id,sector,investment,rural_area_id) VALUES ...
SELECT w.sector, SUM(w.investment) as total_investment FROM women_led_businesses w INNER JOIN rural_areas ra ON w.rural_area_id = ra.id WHERE ra.country = 'Mexico' GROUP BY w.sector;
What is the total number of accessible technology initiatives in rural areas with a population over 20,000 in Asia?
CREATE TABLE Areas (id INT,name TEXT,country TEXT,population INT,num_accessible_tech_initiatives INT); INSERT INTO Areas (id,name,country,population,num_accessible_tech_initiatives) VALUES (1,'VillageA','India',25000,3),(2,'TownB','China',30000,5),(3,'CityC','Japan',40000,8),(4,'RuralD','Indonesia',22000,1),(5,'HamletE...
SELECT SUM(num_accessible_tech_initiatives) FROM Areas WHERE population > 20000 AND type = 'rural';
How many affordable housing units are available in Oakland?
CREATE TABLE affordable_housing (property_id INT,city VARCHAR(50),units INT,cost INT); INSERT INTO affordable_housing VALUES (1,'Oakland',10,1500),(2,'Oakland',15,1700),(3,'San_Francisco',20,2000);
SELECT SUM(units) FROM affordable_housing WHERE city = 'Oakland' AND cost <= 1800;
Get the names of publishers who have never published an article on 'Sunday'.
CREATE TABLE articles (id INT,title TEXT,publication_day TEXT,publisher TEXT);
SELECT DISTINCT publisher FROM articles WHERE publication_day != 'Sunday';
What is the average budget for accessible technology initiatives in Southeast Asia?
CREATE TABLE Initiatives (InitiativeID INT,Initiative VARCHAR(50),Budget DECIMAL(10,2),Region VARCHAR(50)); INSERT INTO Initiatives VALUES (1,'Initiative1',15000.00,'Southeast Asia'),(2,'Initiative2',20000.00,'Southeast Asia'),(3,'Initiative3',18000.00,'Southeast Asia');
SELECT AVG(Budget) FROM Initiatives WHERE Region = 'Southeast Asia';
List the 'return_reason' and the total 'return_quantity' for each 'return_reason' in the 'reverse_logistics' table
CREATE TABLE reverse_logistics (return_id INT,return_reason VARCHAR(50),return_quantity INT); INSERT INTO reverse_logistics (return_id,return_reason,return_quantity) VALUES (1,'Damaged',50),(2,'Wrong Item',75),(3,'Return to Stock',100);
SELECT return_reason, SUM(return_quantity) FROM reverse_logistics GROUP BY return_reason;
Identify projects without incentives.
CREATE TABLE Projects (id INT,name TEXT,location TEXT,capacity FLOAT,type TEXT,PRIMARY KEY (id)); INSERT INTO Projects (id,name,location,capacity,type) VALUES (1,'Solar Farm A','California',50.0,'Solar'),(2,'Wind Farm B','Texas',100.0,'Wind'); CREATE TABLE Incentives (id INT,project_id INT,incentive_name TEXT,PRIMARY K...
SELECT Projects.name FROM Projects LEFT JOIN Incentives ON Projects.id = Incentives.project_id WHERE Incentives.incentive_name IS NULL;
How many donors are from the 'Global South' and have donated more than $500?
CREATE TABLE Donors (DonorID INT,Name VARCHAR(50),Age INT,Gender VARCHAR(20),DonationAmount DECIMAL(10,2),Location VARCHAR(50)); INSERT INTO Donors (DonorID,Name,Age,Gender,DonationAmount,Location) VALUES (2,'Sofia Garcia',45,'Female',700.00,'Brazil'); CREATE TABLE Countries (CountryID INT,CountryName VARCHAR(50),Conti...
SELECT COUNT(DISTINCT Donors.DonorID) FROM Donors INNER JOIN Countries ON Donors.Location = Countries.CountryName WHERE Continent = 'South America' AND DonationAmount > 500.00;
Update the names and departments of all graduate students in the graduate_students table who have a department of 'Arts' to 'Liberal Arts'.
CREATE TABLE graduate_students (id INT,name VARCHAR(50),department VARCHAR(50)); INSERT INTO graduate_students VALUES (1,'Fiona','Art History'),(2,'George','Mathematics'),(3,'Hannah','Physics'),(4,'Ivan','Arts'); UPDATE graduate_students SET department = 'Liberal Arts' WHERE department = 'Arts';
UPDATE graduate_students SET department = 'Liberal Arts' WHERE department = 'Arts';
What is the number of workers employed in factories that use renewable energy sources in Germany and France?
CREATE TABLE factories (factory_id INT,country VARCHAR(50),energy_source VARCHAR(50)); CREATE TABLE workers (worker_id INT,factory_id INT,position VARCHAR(50)); INSERT INTO factories (factory_id,country,energy_source) VALUES (1,'Germany','renewable'),(2,'France','fossil fuel'),(3,'Germany','renewable'); INSERT INTO wor...
SELECT COUNT(workers.worker_id) FROM workers INNER JOIN factories ON workers.factory_id = factories.factory_id WHERE factories.country IN ('Germany', 'France') AND factories.energy_source = 'renewable';
Update the solar energy production record for California in 2023 to 20000 MWh
CREATE TABLE solar_energy (id INT,region VARCHAR(50),year INT,production FLOAT);
UPDATE solar_energy SET production = 20000 WHERE region = 'California' AND year = 2023;
How many electric vehicles are there in Tokyo, by type, as of 2022?
CREATE TABLE electric_vehicles (id INT,vehicle_id INT,vehicle_type VARCHAR(50),registration_date TIMESTAMP); INSERT INTO electric_vehicles (id,vehicle_id,vehicle_type,registration_date) VALUES (1,1234,'Car','2022-01-01'),(2,5678,'Motorcycle','2022-01-02');
SELECT vehicle_type, COUNT(*) as total FROM electric_vehicles WHERE YEAR(registration_date) = 2022 AND EXTRACT(MONTH FROM registration_date) BETWEEN 1 AND 12 GROUP BY vehicle_type;
What is the total area of agroecology practices by region in the 'agroecology' table?
CREATE TABLE agroecology (id INT,region VARCHAR(255),area_ha INT); INSERT INTO agroecology (id,region,area_ha) VALUES (1,'Central America',120000),(2,'South America',350000),(3,'Africa',280000),(4,'Asia',420000);
SELECT region, SUM(area_ha) as TotalArea FROM agroecology GROUP BY region;
List all military innovation projects and their start dates in Europe.
CREATE TABLE MilitaryInnovationProjects (id INT,project VARCHAR(50),country VARCHAR(50),start_date DATE); INSERT INTO MilitaryInnovationProjects (id,project,country,start_date) VALUES (1,'Stealth Technology','France','2010-01-01'),(2,'Cyber Warfare','Germany','2015-01-01'),(3,'Artificial Intelligence','UK','2018-01-01'...
SELECT project, country, start_date FROM MilitaryInnovationProjects WHERE country LIKE '%Europe%';
What is the average donation amount for donations made in 'q4_2021'?
CREATE TABLE donations (id INT,donation_amount FLOAT,donation_period TEXT); INSERT INTO donations (id,donation_amount,donation_period) VALUES (1,50.00,'q4_2021'),(2,40.00,'q4_2021'),(3,30.00,'q4_2021');
SELECT AVG(donation_amount) FROM donations WHERE donation_period = 'q4_2021';
How many vessels are registered for each type of operation?
CREATE TABLE vessels (id INT,name TEXT,type TEXT); INSERT INTO vessels (id,name,type) VALUES (1,'Fishing Vessel 1','Fishing'),(2,'Research Vessel 1','Research'),(3,'Tourist Vessel 1','Tourism'),(4,'Fishing Vessel 2','Fishing'),(5,'Research Vessel 2','Research'),(6,'Tourist Vessel 2','Tourism');
SELECT type, COUNT(type) FROM vessels GROUP BY type;
What is the minimum age of astronauts at their first spaceflight?
CREATE TABLE astronauts (id INT,name VARCHAR(255),birth_date DATE,first_flight_date DATE); INSERT INTO astronauts (id,name,birth_date,first_flight_date) VALUES (1,'Alan Shepard','1923-11-18','1961-05-05'),(2,'Gus Grissom','1926-04-03','1961-07-21');
SELECT MIN(DATEDIFF(first_flight_date, birth_date)) FROM astronauts;
What are the details of the most recent cargo inspections, including the cargo type, vessel name, and inspection date?
CREATE TABLE cargo_inspections (inspection_id INT,cargo_id INT,vessel_id INT,inspection_date DATE); CREATE TABLE cargo (cargo_id INT,cargo_type VARCHAR(50)); CREATE TABLE vessels (vessel_id INT,vessel_name VARCHAR(100)); INSERT INTO cargo VALUES (1,'Container'); INSERT INTO cargo VALUES (2,'Bulk'); INSERT INTO vessels ...
SELECT cargo.cargo_type, vessels.vessel_name, MAX(cargo_inspections.inspection_date) as latest_inspection_date FROM cargo_inspections INNER JOIN cargo ON cargo_inspections.cargo_id = cargo.cargo_id INNER JOIN vessels ON cargo_inspections.vessel_id = vessels.vessel_id GROUP BY cargo.cargo_type, vessels.vessel_name;
Who is the director with the most number of films in the African cinema?
CREATE TABLE african_cinema (id INT,title VARCHAR(255),director VARCHAR(255)); INSERT INTO african_cinema (id,title,director) VALUES (1,'Movie1','Director1'),(2,'Movie2','Director2'),(3,'Movie3','Director1');
SELECT director, COUNT(*) FROM african_cinema GROUP BY director ORDER BY COUNT(*) DESC LIMIT 1;
What are the drug names and total revenue for drugs approved after 2019?
CREATE TABLE drug_approvals (drug_name VARCHAR(255),approval_date DATE); INSERT INTO drug_approvals (drug_name,approval_date) VALUES ('DrugB','2021-01-01');
SELECT a.drug_name, SUM(d.revenue) as total_revenue FROM drug_approvals a JOIN drug_sales d ON a.drug_name = d.drug_name WHERE a.approval_date > '2019-12-31' GROUP BY a.drug_name;
What is the average ticket price for dance performances in New York museums?
CREATE TABLE museums (id INT,name TEXT,city TEXT,state TEXT); INSERT INTO museums (id,name,city,state) VALUES (1,'Museum of Modern Art','New York','NY'),(2,'Guggenheim Museum','New York','NY'); CREATE TABLE performances (id INT,museum_id INT,name TEXT,category TEXT,price DECIMAL(5,2)); INSERT INTO performances (id,muse...
SELECT AVG(price) FROM performances WHERE category = 'Dance' AND museum_id IN (SELECT id FROM museums WHERE city = 'New York');
Who are the top 2 material producers in the 'circular_economy' table, ordered by quantity?
CREATE TABLE circular_economy (id INT,producer VARCHAR(20),material VARCHAR(20),quantity INT); INSERT INTO circular_economy (id,producer,material,quantity) VALUES (1,'EcoFabrics','cotton',5000),(2,'GreenYarn','wool',3000),(3,'EcoFabrics','polyester',7000),(4,'GreenYarn','cotton',4000),(5,'SustainaFiber','silk',6000),(6...
SELECT producer, SUM(quantity) AS total_quantity FROM circular_economy GROUP BY producer ORDER BY total_quantity DESC LIMIT 2;
Find the number of items in each fabric category
CREATE TABLE fabrics (id INT,fabric_category VARCHAR(20),is_sustainable BOOLEAN,quantity INT); INSERT INTO fabrics (id,fabric_category,is_sustainable,quantity) VALUES (1,'cotton',true,1000),(2,'polyester',false,1500),(3,'linen',true,1200),(4,'silk',false,800),(5,'wool',true,1400),(6,'nylon',false,1000);
SELECT CASE WHEN is_sustainable = true THEN 'Sustainable' ELSE 'Non-Sustainable' END AS fabric_category, COUNT(*) FROM fabrics GROUP BY fabric_category;
What is the name of the employee who was hired most recently?
CREATE TABLE Employees (EmployeeID INT,FirstName VARCHAR(50),LastName VARCHAR(50),Department VARCHAR(50),Gender VARCHAR(10),HireDate DATE); INSERT INTO Employees (EmployeeID,FirstName,LastName,Department,Gender,HireDate) VALUES (1,'John','Doe','IT','Male','2020-01-01'),(2,'Jane','Doe','HR','Female','2021-01-01'),(3,'Mi...
SELECT * FROM Employees ORDER BY HireDate DESC LIMIT 1;
What is the CO2 emission per mode of transportation for the 'transportation' table, ordered by CO2 emission in ascending order?
CREATE TABLE transportation (transportation_id INT,transportation_mode TEXT,co2_emission DECIMAL(5,2)); INSERT INTO transportation (transportation_id,transportation_mode,co2_emission) VALUES (1,'Train',10),(2,'Bus',20),(3,'Car',30),(4,'Plane',50);
SELECT transportation_mode, co2_emission FROM transportation ORDER BY co2_emission ASC;
What is the average policy impact score for education services in the state of Texas?
CREATE SCHEMA gov_data;CREATE TABLE gov_data.policy_impact_scores (state VARCHAR(20),service VARCHAR(20),score INT); INSERT INTO gov_data.policy_impact_scores (state,service,score) VALUES ('Texas','Education',80),('Texas','Healthcare',70),('Texas','Public Transportation',60);
SELECT AVG(score) FROM gov_data.policy_impact_scores WHERE state = 'Texas' AND service = 'Education';
Show the number of network devices that were installed in each region in the last year?
CREATE TABLE network_devices (id INT,name VARCHAR(255),region VARCHAR(255),installed_at TIMESTAMP);
SELECT region, COUNT(*) as total_devices FROM network_devices WHERE installed_at >= DATE_SUB(CURRENT_TIMESTAMP, INTERVAL 1 YEAR) GROUP BY region;
What is the total amount spent on raw materials for the entire year of 2020 and 2021?
CREATE TABLE expenses (expense_id INT,date DATE,category VARCHAR(20),amount FLOAT); INSERT INTO expenses (expense_id,date,category,amount) VALUES (1,'2021-01-01','textile',2500),(2,'2021-05-15','tooling',1500),(3,'2020-12-31','textile',3000),(4,'2021-12-31','textile',5000);
SELECT SUM(amount) FROM expenses WHERE date BETWEEN '2020-01-01' AND '2021-12-31' AND category = 'textile';
How many pollution incidents have been reported in the Mediterranean sea?
CREATE TABLE Pollution_reports (report_id INTEGER,incident_location TEXT,reported_date DATE); INSERT INTO Pollution_reports (report_id,incident_location,reported_date) VALUES (1,'Mediterranean Sea','2021-01-01'),(2,'Mediterranean Sea','2021-02-15'),(3,'Atlantic Ocean','2021-03-12');
SELECT COUNT(*) FROM Pollution_reports WHERE incident_location = 'Mediterranean Sea';
What is the market share of the top five gas companies in the world, as of 2021?
CREATE TABLE world_gas_companies (company VARCHAR(255),market_share DECIMAL(10,2),year INT);
SELECT company, market_share FROM world_gas_companies wgc WHERE wgc.year = 2021 ORDER BY market_share DESC LIMIT 5;
Identify the number of military equipment types maintained by each maintenance department.
CREATE TABLE military_equipment (equipment_id INT,type VARCHAR(255),department VARCHAR(255));INSERT INTO military_equipment (equipment_id,type,department) VALUES (1,'Aircraft','Aerospace Engineering'),(2,'Vehicle','Ground Vehicle Maintenance'),(3,'Ship','Naval Architecture'),(4,'Vehicle','Ground Vehicle Maintenance');
SELECT department, COUNT(DISTINCT type) as equipment_types FROM military_equipment GROUP BY department;
What is the total number of mining sites in each state?
CREATE TABLE mining_sites (site_id INT,site_name VARCHAR(50),state VARCHAR(20));
SELECT s.state, COUNT(*) FROM mining_sites s GROUP BY s.state;
What is the total number of building permits issued in each county for green building projects?
CREATE TABLE permit_county_data (county VARCHAR(255),permit INT,green BOOLEAN); INSERT INTO permit_county_data (county,permit,green) VALUES ('LA',500,TRUE),('Orange',400,FALSE),('Ventura',600,TRUE);
SELECT county, SUM(permit) FROM permit_county_data WHERE green = TRUE GROUP BY county;
How many ports are listed in the 'port_operations' table?
CREATE TABLE port_operations (id INT,name VARCHAR(50),location VARCHAR(50),capacity INT);
SELECT COUNT(*) FROM port_operations;
What is the minimum depth of the ocean?
CREATE TABLE ocean_depths (id INT,depth FLOAT); INSERT INTO ocean_depths (id,depth) VALUES (1,360),(2,660),(3,1000),(4,4000),(5,6000);
SELECT MIN(depth) FROM ocean_depths;
Determine the number of work-related injuries in the mining industry by gender
CREATE TABLE work_injuries(gender VARCHAR(20),year INT,operation VARCHAR(20),num_injuries INT); INSERT INTO work_injuries VALUES ('male',2018,'mining',100),('male',2019,'mining',110),('male',2020,'mining',120),('female',2018,'mining',10),('female',2019,'mining',15),('female',2020,'mining',20);
SELECT gender, SUM(num_injuries) FROM work_injuries WHERE year BETWEEN 2018 AND 2020 AND operation = 'mining' GROUP BY gender;
Which mammals were sighted in 'Habitat G' during 2023-01-01 and 2023-12-31?
CREATE TABLE Habitat (id INT,name VARCHAR(20)); INSERT INTO Habitat (id,name) VALUES (1,'Habitat A'),(2,'Habitat B'),(3,'Habitat C'),(4,'Habitat D'),(5,'Habitat E'),(6,'Habitat F'),(7,'Habitat G'); CREATE TABLE Animal (id INT,name VARCHAR(20),species VARCHAR(20)); CREATE TABLE Sighting (id INT,animal_id INT,habitat_id ...
SELECT Animal.name FROM Animal JOIN Sighting ON Animal.id = Sighting.animal_id JOIN Habitat ON Sighting.habitat_id = Habitat.id WHERE Habitat.name = 'Habitat G' AND Animal.species LIKE '%Mammal%' AND Sighting.sighting_date BETWEEN '2023-01-01' AND '2023-12-31';
How many autonomous driving research papers were published by authors from the US and UK?
CREATE TABLE Research_Papers_2 (Author_Country VARCHAR(10),Paper_Count INT); INSERT INTO Research_Papers_2 (Author_Country,Paper_Count) VALUES ('USA',200),('China',150),('Germany',120),('Japan',90),('UK',80),('France',70);
SELECT SUM(Paper_Count) FROM Research_Papers_2 WHERE Author_Country IN ('USA', 'UK');
List policy numbers with the highest claim amount in the last quarter.
CREATE TABLE Policy (PolicyNumber INT,PolicyholderName VARCHAR(50)); CREATE TABLE Claim (ClaimID INT,PolicyNumber INT,ClaimDate DATE,ClaimAmount DECIMAL(10,2)); INSERT INTO Policy VALUES (1,'John Doe'),(2,'Jane Smith'); INSERT INTO Claim VALUES (1,1,'2021-01-01',5000),(2,1,'2021-02-01',3000),(3,2,'2021-04-01',7000),(4,...
SELECT PolicyNumber, MAX(ClaimAmount) as MaxClaimAmount FROM Claim WHERE ClaimDate >= DATEADD(QUARTER, -1, GETDATE()) GROUP BY PolicyNumber ORDER BY MaxClaimAmount DESC;
What is the total number of assistive technology items provided for students with visual or hearing impairments?
CREATE TABLE Assistive_Tech (Student_ID INT,Student_Name TEXT,Disability_Type TEXT,Assistive_Tech_Item TEXT); INSERT INTO Assistive_Tech (Student_ID,Student_Name,Disability_Type,Assistive_Tech_Item) VALUES (7,'Alex Thompson','Hearing Impairment','Hearing Aid'),(8,'Jasmine Chen','Visual Impairment','Screen Reader'),(9,'...
SELECT SUM(CASE WHEN Disability_Type IN ('Visual Impairment', 'Hearing Impairment') THEN 1 ELSE 0 END) FROM Assistive_Tech WHERE Assistive_Tech_Item IS NOT NULL;
What is the average investment per project in the 'infrastructure_projects' table?
CREATE TABLE infrastructure_projects (id INT,project VARCHAR(50),investment FLOAT); INSERT INTO infrastructure_projects (id,project,investment) VALUES (1,'Road Construction',25000.0); INSERT INTO infrastructure_projects (id,project,investment) VALUES (2,'Water Supply',30000.0);
SELECT AVG(investment) FROM infrastructure_projects;
What is the percentage of sales revenue for each brand of garment, partitioned by the percentage of sales revenue and ordered within each partition by the percentage of sales revenue in descending order?
CREATE TABLE Brands (BrandID INT,BrandName VARCHAR(255));CREATE TABLE Garments (GarmentID INT,BrandID INT,SalePrice DECIMAL(10,2));CREATE TABLE Sales (SaleID INT,GarmentID INT,SaleDate DATE,Quantity INT);
SELECT b.BrandName, 100.0 * SUM(g.SalePrice * s.Quantity) / SUM(g.SalePrice * s.Quantity) OVER (PARTITION BY NULL) AS PercentageRevenue, ROW_NUMBER() OVER (PARTITION BY 100.0 * SUM(g.SalePrice * s.Quantity) / SUM(g.SalePrice * s.Quantity) OVER (PARTITION BY NULL) ORDER BY 100.0 * SUM(g.SalePrice * s.Quantity) / SUM(g.S...
Delete fish stock records from the 'Pacific Ocean' location that are older than 2019-01-01?
CREATE TABLE FishStock (StockID INT,Location VARCHAR(50),StockDate DATE,Quantity INT); INSERT INTO FishStock (StockID,Location,StockDate,Quantity) VALUES (1,'Pacific Ocean','2018-12-31',1000),(2,'Pacific Ocean','2019-01-01',2000),(3,'Atlantic Ocean','2018-12-31',1500);
DELETE FROM FishStock WHERE Location = 'Pacific Ocean' AND StockDate < '2019-01-01';
Delete models from Italy with a safety score less than 0.75.
CREATE TABLE models_italy (model_id INT,name VARCHAR(255),country VARCHAR(255),safety_score FLOAT); INSERT INTO models_italy (model_id,name,country,safety_score) VALUES (1,'ModelA','Italy',0.82),(2,'ModelB','Italy',0.68),(3,'ModelC','Italy',0.90);
DELETE FROM models_italy WHERE safety_score < 0.75 AND country = 'Italy';
How many artworks were created by artists from Asia in the 17th century?
CREATE TABLE Artworks (ArtworkID int,ArtworkName varchar(100),Artist varchar(100),CreationDate date); INSERT INTO Artworks (ArtworkID,ArtworkName,Artist,CreationDate) VALUES (1,'Artwork A','Artist A (Asia)','1600-01-01'),(2,'Artwork B','Artist B (Europe)','1700-01-01'),(3,'Artwork C','Artist C (Asia)','1650-12-31');
SELECT COUNT(*) FROM Artworks WHERE Artist LIKE '%Asia%' AND YEAR(CreationDate) BETWEEN 1600 AND 1699;
How many species are present in 'asia' that are not endangered?
CREATE TABLE species (name VARCHAR(255),region VARCHAR(255),endangered BOOLEAN); INSERT INTO species (name,region,endangered) VALUES ('tiger','asia',FALSE); INSERT INTO species (name,region,endangered) VALUES ('leopard','asia',TRUE);
SELECT COUNT(*) FROM species WHERE region = 'asia' AND endangered = FALSE;
What is the total number of articles published by each gender in the 'news_reporting' table?
CREATE TABLE news_reporting (article_id INT,author VARCHAR(50),title VARCHAR(100),published_date DATE,category VARCHAR(30),author_gender VARCHAR(10)); INSERT INTO news_reporting (article_id,author,title,published_date,category,author_gender) VALUES (1,'John Doe','Article 1','2021-01-01','Politics','Male'),(2,'Jane Smit...
SELECT author_gender, COUNT(article_id) AS total_articles FROM news_reporting GROUP BY author_gender;
What is the total waste generation by business type in London?
CREATE TABLE waste_generation_london (business_type VARCHAR(50),waste_amount INT); INSERT INTO waste_generation_london (business_type,waste_amount) VALUES ('Restaurant',200),('Retail',150),('Office',180);
SELECT business_type, SUM(waste_amount) FROM waste_generation_london WHERE business_type IN ('Restaurant', 'Retail', 'Office') GROUP BY business_type;
What is the average cost of public works projects in Florida for each year since 2015?
CREATE TABLE Public_Works (Project_ID INT,Project_Name VARCHAR(255),Cost FLOAT,Year INT,State VARCHAR(255));
SELECT Year, AVG(Cost) FROM Public_Works WHERE State = 'Florida' GROUP BY Year;
Update the rating of the eco-friendly hotel in Sydney to 4.8.
CREATE TABLE hotel (hotel_id INT,name TEXT,city TEXT,country TEXT,rating FLOAT); INSERT INTO hotel (hotel_id,name,city,country,rating) VALUES (2,'Eco Hotel Sydney','Sydney','Australia',4.5);
UPDATE hotel SET rating = 4.8 WHERE city = 'Sydney' AND name = 'Eco Hotel Sydney';
What is the total number of primary care clinics and their average rating, grouped by state?
CREATE TABLE public.healthcare_access (id SERIAL PRIMARY KEY,state TEXT,city TEXT,facility_type TEXT,patients_served INT,rating INT); INSERT INTO public.healthcare_access (state,city,facility_type,patients_served,rating) VALUES ('California','San Diego','Primary Care Clinic',7000,8),('New York','New York City','Primary...
SELECT state, facility_type, AVG(rating) AS avg_rating, COUNT(*) FILTER (WHERE facility_type = 'Primary Care Clinic') AS clinic_count FROM public.healthcare_access GROUP BY state, facility_type;
Which countries have more than 5 news committees and what is the average number of members in those committees?
CREATE TABLE NewsCommittees (CommitteeID int,Name varchar(50),MembersCount int,Country varchar(50)); INSERT INTO NewsCommittees (CommitteeID,Name,MembersCount,Country) VALUES (1,'Committee 1',5,'USA'); INSERT INTO NewsCommittees (CommitteeID,Name,MembersCount,Country) VALUES (2,'Committee 2',7,'Canada'); INSERT INTO Ne...
SELECT Country, AVG(MembersCount) as AvgMembers FROM NewsCommittees GROUP BY Country HAVING COUNT(CommitteeID) > 5;
List all fair labor practice certifications held by factories in Italy.
CREATE TABLE factories (factory_id INT,country VARCHAR(50),certification_1 VARCHAR(50),certification_2 VARCHAR(50),certification_3 VARCHAR(50)); INSERT INTO factories (factory_id,country,certification_1,certification_2,certification_3) VALUES (1,'Italy','Fair Trade','SA8000','BSCI'),(2,'Spain','GOTS','SA8000',''),(3,'P...
SELECT DISTINCT country, certification_1, certification_2, certification_3 FROM factories WHERE country = 'Italy';
Calculate the average attendance for each cultural event in the past year, partitioned by event name and ordered by average attendance in descending order.
CREATE TABLE cultural_events (event_id INT,event_name VARCHAR(255),event_date DATE); CREATE TABLE events_attendance (event_id INT,attendance INT,attendance_date DATE);
SELECT event_name, AVG(attendance) as avg_attendance FROM events_attendance JOIN cultural_events ON events_attendance.event_id = cultural_events.event_id WHERE events_attendance.attendance_date >= DATEADD(year, -1, CURRENT_DATE) GROUP BY event_name ORDER BY avg_attendance DESC;
Show the number of military equipment sales to 'Brazil' for each equipment type from the 'sales' table
CREATE TABLE sales (id INT,equipment_type VARCHAR(255),sale_date DATE,quantity INT,country VARCHAR(255)); INSERT INTO sales (id,equipment_type,sale_date,quantity,country) VALUES (1,'tank','2019-07-15',5,'US'); INSERT INTO sales (id,equipment_type,sale_date,quantity,country) VALUES (2,'fighter_jet','2020-11-27',12,'UK')...
SELECT equipment_type, SUM(quantity) FROM sales WHERE country = 'Brazil' GROUP BY equipment_type;
Find excavation sites with 'Bronze Age' artifacts.
CREATE TABLE ExcavationSites (SiteID varchar(5),SiteName varchar(10),ArtifactPeriod varchar(15)); INSERT INTO ExcavationSites (SiteID,SiteName,ArtifactPeriod) VALUES ('E001','Site E','Bronze Age');
SELECT SiteID, SiteName FROM ExcavationSites WHERE ArtifactPeriod = 'Bronze Age';
What is the total installed capacity of solar energy projects in the state of New York, grouped by project location?
CREATE TABLE solar_projects (id INT,project_name VARCHAR(100),state VARCHAR(50),project_location VARCHAR(50),installed_capacity INT); INSERT INTO solar_projects (id,project_name,state,project_location,installed_capacity) VALUES (1,'Solar Project A','New York','Upstate',20000),(2,'Solar Project B','New York','Long Islan...
SELECT project_location, SUM(installed_capacity) FROM solar_projects WHERE state = 'New York' GROUP BY project_location;
What is the distribution of crime types across different time periods (morning, afternoon, evening)?
CREATE TABLE time_periods (id INT,period TEXT); CREATE TABLE crime_stats (id INT,time_period_id INT,crime_type TEXT,frequency INT);
SELECT tp.period, cs.crime_type, cs.frequency FROM time_periods tp JOIN crime_stats cs ON tp.id = cs.time_period_id;
What is the number of rural pharmacies and clinics in each province, ordered by the number of rural pharmacies and clinics?
CREATE TABLE pharmacies (pharmacy_id INT,name TEXT,type TEXT,rural BOOLEAN); CREATE TABLE provinces (province_code TEXT,province_name TEXT); INSERT INTO pharmacies (pharmacy_id,name,type,rural) VALUES (1,'Rural Pharmacy','Pharmacy',TRUE),(2,'Rural Clinic','Clinic',TRUE); INSERT INTO provinces (province_code,province_na...
SELECT provinces.province_name, SUM(CASE WHEN pharmacies.type = 'Pharmacy' THEN 1 ELSE 0 END) as num_pharmacies, SUM(CASE WHEN pharmacies.type = 'Clinic' THEN 1 ELSE 0 END) as num_clinics, SUM(CASE WHEN pharmacies.type IN ('Pharmacy', 'Clinic') THEN 1 ELSE 0 END) as total_rural_healthcare_services FROM pharmacies INNER...
How many artworks were created per year in the 'Baroque' movement?
CREATE TABLE Artworks (id INT,creation_year INT,movement VARCHAR(20));
SELECT creation_year, COUNT(*) FROM Artworks WHERE movement = 'Baroque' GROUP BY creation_year;
List the number of containers handled by each stevedoring company per month.
CREATE TABLE stevedoring_companies (company_id INT,company_name VARCHAR(50));CREATE TABLE containers (container_id INT,container_quantity INT,loading_unloading_date DATE,stevedoring_company_id INT); INSERT INTO stevedoring_companies VALUES (1,'StevedoringCo1'),(2,'StevedoringCo2'),(3,'StevedoringCo3');
SELECT s.company_name, EXTRACT(MONTH FROM c.loading_unloading_date) AS month, EXTRACT(YEAR FROM c.loading_unloading_date) AS year, COUNT(c.container_id) AS containers_handled FROM containers c JOIN stevedoring_companies s ON c.stevedoring_company_id = s.company_id GROUP BY s.company_name, month, year ORDER BY s.company...
Count the number of EVs in the electric_vehicles table by make
CREATE TABLE electric_vehicles (id INT PRIMARY KEY,make VARCHAR(255),model VARCHAR(255),year INT,ev_type VARCHAR(255));
SELECT make, COUNT(*) FROM electric_vehicles GROUP BY make;
Find the total funding for each biosensor technology category and their respective companies.
CREATE TABLE biotech_funding (company_id INT,category TEXT,amount INT); INSERT INTO biotech_funding (company_id,category,amount) VALUES (1,'Optical Biosensors',3000000); INSERT INTO biotech_funding (company_id,category,amount) VALUES (2,'Electrochemical Biosensors',4000000); INSERT INTO biotech_funding (company_id,cate...
SELECT b.category, c.name, SUM(f.amount) AS total_funding FROM biotech_companies b INNER JOIN biotech_funding f ON b.company_id = f.company_id GROUP BY b.category, c.name;
What is the average accommodation cost per month for students with visual impairments?
CREATE TABLE Accommodations (student_id INT,accommodation_type VARCHAR(255),cost FLOAT,month INT);
SELECT AVG(cost) FROM Accommodations WHERE accommodation_type = 'Visual Impairment' GROUP BY month;
List the top 2 employees with the most safety violations in the 'East' plant in 2022.
CREATE TABLE employee_safety (employee_id int,name varchar(20),plant varchar(10),violation_date date); INSERT INTO employee_safety (employee_id,name,plant,violation_date) VALUES (1,'John Doe','North Plant','2022-01-01'),(2,'Jane Smith','East Plant','2022-02-01'),(3,'Bob Johnson','East Plant','2022-03-01'),(4,'Alice Wil...
SELECT e.name, COUNT(*) as total_violations FROM employee_safety e JOIN (SELECT employee_id, plant FROM employee_safety WHERE plant = 'East Plant' GROUP BY employee_id, plant HAVING COUNT(*) >= 2) f ON e.employee_id = f.employee_id AND e.plant = f.plant GROUP BY e.name ORDER BY total_violations DESC LIMIT 2;
Alter the 'community_policing' table to add a column 'date'
CREATE TABLE community_policing (policing_type VARCHAR(255),frequency INT,location VARCHAR(255));
ALTER TABLE community_policing ADD COLUMN date DATE;
Insert new records for the artist 'Rihanna' in the pop genre.
CREATE TABLE artists (artist_id INT,artist_name VARCHAR(100),genre VARCHAR(50)); INSERT INTO artists (artist_id,artist_name,genre) VALUES (1,'Adele','pop'),(2,'Taylor Swift','country'),(3,'Metallica','metal'),(4,'Eminem','hip-hop'); CREATE TABLE songs (song_id INT,song_name VARCHAR(100),artist_id INT); INSERT INTO song...
INSERT INTO artists (artist_id, artist_name, genre) VALUES (5, 'Rihanna', 'pop'); INSERT INTO songs (song_id, song_name, artist_id) VALUES (7, 'Diamonds', 5), (8, 'Work', 5), (9, 'We Found Love', 5);
Count the number of incidents for each vessel type in a specific country
CREATE TABLE VesselTypes (id INT,vessel_type VARCHAR(50)); CREATE TABLE IncidentLog (id INT,vessel_id INT,country VARCHAR(50),time TIMESTAMP);
SELECT vt.vessel_type, il.country, COUNT(*) FROM VesselTypes vt JOIN IncidentLog il ON vt.id = il.vessel_id GROUP BY vt.vessel_type, il.country;
Food items with allergens by category
CREATE TABLE Allergen (ItemID INT,Allergen VARCHAR(50)); INSERT INTO Allergen (ItemID,Allergen) VALUES (1,'Peanuts'),(1,'Gluten'),(2,'Dairy'); CREATE TABLE FoodCategory (ItemID INT,Category VARCHAR(50)); INSERT INTO FoodCategory (ItemID,Category) VALUES (1,'Vegetables'),(2,'Fruits');
SELECT c.Category, a.Allergen FROM FoodItem f INNER JOIN Allergen a ON f.ItemID = a.ItemID INNER JOIN FoodCategory c ON f.ItemID = c.ItemID;
What are the top 5 countries with the highest number of security incidents in the last 30 days, ordered by the count of incidents in descending order?
CREATE TABLE security_incidents (id INT,country VARCHAR(50),timestamp TIMESTAMP);
SELECT country, COUNT(*) as incident_count FROM security_incidents WHERE timestamp >= NOW() - INTERVAL 30 DAY GROUP BY country ORDER BY incident_count DESC LIMIT 5;
Which destination has the highest hotel rating?
CREATE TABLE Hotels (hotel_id INT,hotel_name TEXT,country TEXT,rating FLOAT); INSERT INTO Hotels (hotel_id,hotel_name,country,rating) VALUES (1,'Hotel A','Spain',4.3),(2,'Hotel B','Spain',4.5),(3,'Hotel C','France',4.7);
SELECT hotel_name, rating, RANK() OVER (ORDER BY rating DESC) AS rank FROM Hotels;
Insert a new record for a disability support program named 'Mobility Training' offered by 'XYZ Foundation'.
CREATE TABLE support_program (program_id INT,program_name TEXT,org_id INT); INSERT INTO support_program (program_id,program_name,org_id) VALUES (1,'Adaptive Sports',1); INSERT INTO support_program (program_id,program_name,org_id) VALUES (2,'Assistive Technology',2);
INSERT INTO support_program (program_id, program_name, org_id) VALUES (3, 'Mobility Training', 2);
What is the total number of legal tech patents filed in India and Singapore between 2010 and 2020?
CREATE TABLE legal_tech_patents (id INT,patent_name VARCHAR(255),country VARCHAR(255),filing_year INT); INSERT INTO legal_tech_patents (id,patent_name,country,filing_year) VALUES (1,'AI Document Review System','United States',2018),(2,'Smart Contract Platform','China',2019),(3,'Legal Chatbot','India',2017),(4,'Blockcha...
SELECT COUNT(*) AS total_patents FROM legal_tech_patents WHERE country IN ('India', 'Singapore') AND filing_year BETWEEN 2010 AND 2020;
Insert a new record into the "chemical_safety_incidents" table for incident 5678 with chemical C006 on March 11, 2022, with the description "Equipment failure".
CREATE TABLE chemical_safety_incidents (incident_id int,incident_date date,incident_description varchar(255),chemical_id varchar(10));
INSERT INTO chemical_safety_incidents (incident_id,incident_date,incident_description,chemical_id) VALUES (5678,'2022-03-11','Equipment failure','C006');
Update fish stock with correct nutritional data
CREATE TABLE FoodItems (FoodItemID INT,FoodItemName TEXT,Calories INT,Protein INT,Fat INT);
UPDATE FoodItems SET Calories = 110, Protein = 20, Fat = 1 WHERE FoodItemName = 'Tilapia';
Find the number of digital interactions and the percentage change from the previous month for each exhibition, sorted by the highest percentage increase.
CREATE TABLE Exhibition (Id INT,Name VARCHAR(100)); CREATE TABLE DigitalInteraction (Id INT,ExhibitionId INT,InteractionDate DATE,Quantity INT);
SELECT ExhibitionId, Name, LAG(Quantity, 1, 0) OVER (PARTITION BY ExhibitionId ORDER BY InteractionDate) as PreviousMonthQuantity, Quantity, (Quantity - LAG(Quantity, 1, 0) OVER (PARTITION BY ExhibitionId ORDER BY InteractionDate))*100.0 / LAG(Quantity, 1, 0) OVER (PARTITION BY ExhibitionId ORDER BY InteractionDate) as...
What is the total number of art pieces in museums that are not part of a permanent collection?
CREATE TABLE Museums (MuseumID INT,Name TEXT,PermanentCollection BOOLEAN); INSERT INTO Museums (MuseumID,Name,PermanentCollection) VALUES (1,'Metropolitan Museum of Art',TRUE); INSERT INTO Museums (MuseumID,Name,PermanentCollection) VALUES (2,'Museum of Modern Art',TRUE); INSERT INTO Museums (MuseumID,Name,PermanentCol...
SELECT COUNT(*) FROM Museums WHERE PermanentCollection = FALSE;
List all legal technology patents filed in California between 2015 and 2017.
CREATE TABLE patents (patent_id INT,filing_date DATE,state VARCHAR(20)); INSERT INTO patents (patent_id,filing_date,state) VALUES (1,'2015-01-01','California'); INSERT INTO patents (patent_id,filing_date,state) VALUES (2,'2017-01-01','Texas');
SELECT patent_id, filing_date FROM patents WHERE state = 'California' AND filing_date BETWEEN '2015-01-01' AND '2017-12-31';
What is the total number of mining permits issued in the year 2020?
CREATE TABLE Permits (PermitID INT,MineID INT,Year INT,Status VARCHAR(255)); INSERT INTO Permits (PermitID,MineID,Year,Status) VALUES (1,1,2019,'Issued'); INSERT INTO Permits (PermitID,MineID,Year,Status) VALUES (2,1,2018,'Pending'); INSERT INTO Permits (PermitID,MineID,Year,Status) VALUES (3,2,2019,'Issued'); INSERT I...
SELECT COUNT(p.PermitID) as NumPermitsIssued FROM Permits p WHERE p.Year = 2020 AND p.Status = 'Issued';
List the number of cybersecurity incidents reported by contractors in the defense industry, in the last 6 months, sorted by severity.
CREATE TABLE cybersecurity_incidents(id INT,contractor VARCHAR(255),severity INT,date DATE);
SELECT contractor, severity, COUNT(*) as count FROM cybersecurity_incidents WHERE date > DATE_SUB(NOW(), INTERVAL 6 MONTH) GROUP BY contractor, severity ORDER BY severity DESC;
Create a table 'game_revenue' with game_date, team, revenue columns
CREATE TABLE game_revenue (game_date DATE,team VARCHAR(50),revenue DECIMAL(10,2));
CREATE TABLE game_revenue AS SELECT g.game_date, t.team, SUM(ticket_price * ticket_quantity) AS revenue FROM game_schedule g JOIN ticket_sales ts ON g.schedule_id = ts.schedule_id JOIN team_data t ON g.team_id = t.team_id GROUP BY g.game_date, t.team;
What was the total revenue for men's footwear in the United States in Q1 2021?
CREATE TABLE sales (product_category VARCHAR(255),geography VARCHAR(255),sales_amount DECIMAL(10,2),quarter INT,year INT); INSERT INTO sales (product_category,geography,sales_amount,quarter,year) VALUES ('Men''s Footwear','United States',15000.00,1,2021);
SELECT SUM(sales_amount) FROM sales WHERE product_category = 'Men''s Footwear' AND geography = 'United States' AND quarter = 1 AND year = 2021;
List the names and total production for all oil fields that produced more than the average production for all oil fields.
CREATE TABLE oil_fields (field_name VARCHAR(50),year INT,production INT); INSERT INTO oil_fields (field_name,year,production) VALUES ('Ghawar',2020,5000000),('Burgan',2020,3000000),('Safaniya',2020,2500000);
SELECT field_name, SUM(production) as total_production FROM oil_fields GROUP BY field_name HAVING total_production > (SELECT AVG(production) FROM (SELECT SUM(production) as production FROM oil_fields GROUP BY field_name) t);
Find the maximum number of investments for a single client in the financial services sector.
CREATE TABLE sectors (sector_id INT,sector VARCHAR(20)); INSERT INTO sectors (sector_id,sector) VALUES (1,'Financial Services'),(2,'Technology'),(3,'Healthcare'); CREATE TABLE investments (investment_id INT,client_id INT,sector_id INT); INSERT INTO investments (investment_id,client_id,sector_id) VALUES (1,1,1),(2,1,2),...
SELECT COUNT(investments.investment_id) FROM investments JOIN sectors ON investments.sector_id = sectors.sector_id WHERE sectors.sector = 'Financial Services' AND investments.client_id = (SELECT client_id FROM investments JOIN sectors ON investments.sector_id = sectors.sector_id WHERE sectors.sector = 'Financial Servic...
What are the details of the 10 most recent phishing attacks, including the email subject and the targeted department?
CREATE TABLE phishing_attacks (attack_id INT,attack_date DATE,email_subject VARCHAR(200),targeted_department VARCHAR(50));
SELECT * FROM phishing_attacks ORDER BY attack_date DESC LIMIT 10;
Delete records in the "equipment" table where the "equipment_id" is 0101.
CREATE TABLE equipment (equipment_id varchar(10),equipment_name varchar(255),equipment_model varchar(255),equipment_status varchar(50));
DELETE FROM equipment WHERE equipment_id = '0101';
List all freight forwarding routes with their total costs for January 2023
CREATE TABLE FreightForwarding (id INT,route VARCHAR(50),cost INT,date DATE); INSERT INTO FreightForwarding (id,route,cost,date) VALUES (1,'Route 1',500,'2023-01-01'),(2,'Route 2',600,'2023-01-05'),(3,'Route 3',400,'2023-01-10');
SELECT route, SUM(cost) FROM FreightForwarding WHERE date BETWEEN '2023-01-01' AND '2023-01-31' GROUP BY route;
What is the number of workers in each mining operation who identify as AAPI (Asian American Pacific Islander)?
CREATE TABLE workforce (id INT,mining_operation_id INT,worker_type VARCHAR(50),role VARCHAR(50)); INSERT INTO workforce (id,mining_operation_id,worker_type,role) VALUES (1,1,'AAPI','Engineer'); INSERT INTO workforce (id,mining_operation_id,worker_type,role) VALUES (2,1,'Non-AAPI','Manager'); INSERT INTO workforce (id,m...
SELECT mining_operation_id, COUNT(*) FROM workforce WHERE worker_type = 'AAPI' GROUP BY mining_operation_id;
How many patients have been treated with CBT or medication management in Illinois?
CREATE TABLE patients (id INT,name TEXT,state TEXT);CREATE TABLE treatments (id INT,patient_id INT,therapy TEXT);INSERT INTO patients (id,name,state) VALUES (1,'James Smith','Illinois');INSERT INTO treatments (id,patient_id,therapy) VALUES (1,1,'CBT'),(2,1,'Medication Management');
SELECT COUNT(DISTINCT patients.id) FROM patients INNER JOIN treatments ON patients.id = treatments.patient_id WHERE patients.state = 'Illinois' AND treatments.therapy IN ('CBT', 'Medication Management');
Who are the artists with more than 5 songs in the 'songs' table?
CREATE TABLE artists_songs (id INT,artist_id INT,song_id INT); INSERT INTO artists_songs (id,artist_id,song_id) VALUES (1,1,1),(2,1,2),(3,2,3),(4,2,4),(5,3,5),(6,3,6),(7,3,7),(8,3,8),(9,3,9),(10,3,10);
SELECT artist_id FROM artists_songs GROUP BY artist_id HAVING COUNT(song_id) > 5;
What is the earliest and latest time a post was made by a user in the 'social_media' schema?
CREATE TABLE user (id INT,name VARCHAR(50),age INT,gender VARCHAR(10),created_at TIMESTAMP); INSERT INTO user (id,name,age,gender,created_at) VALUES (1,'John Doe',25,'Male','2021-01-01 10:00:00'); CREATE TABLE post (id INT,user_id INT,content TEXT,posted_at TIMESTAMP); INSERT INTO post (id,user_id,content,posted_at) VA...
SELECT MIN(posted_at) as earliest, MAX(posted_at) as latest FROM post;
Update the impact score of a program if it is funded by a public source.
CREATE TABLE programs (name VARCHAR(25),impact_score INT,funding_source VARCHAR(15));
UPDATE programs SET impact_score = impact_score + 10 WHERE funding_source = 'public';