instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
What is the total number of posts made by users with the role "influencer" in the "users_roles_table"?
CREATE TABLE users_roles_table (user_id INT,role VARCHAR(20)); INSERT INTO users_roles_table (user_id,role) VALUES (1,'regular_user'),(2,'influencer'),(3,'partner'),(4,'influencer'),(5,'regular_user');
SELECT SUM(post_count) FROM (SELECT COUNT(*) AS post_count FROM users_table JOIN users_roles_table ON users_table.user_id = users_roles_table.user_id WHERE users_roles_table.role = 'influencer' GROUP BY users_table.user_id) AS subquery;
What is the average rating of theater performances, in the past year, broken down by age group and language?
CREATE TABLE Events (id INT,date DATE,language VARCHAR(50),event_type VARCHAR(50)); INSERT INTO Events (id,date,language,event_type) VALUES (1,'2021-01-01','English','Theater'),(2,'2021-02-01','Spanish','Theater'); CREATE TABLE Ratings (id INT,event_id INT,age_group VARCHAR(20),rating DECIMAL(3,2)); INSERT INTO Ratings (id,event_id,age_group,rating) VALUES (1,1,'18-24',4.5),(2,1,'25-34',4.0),(3,2,'35-44',4.7);
SELECT e.language, r.age_group, AVG(r.rating) AS avg_rating FROM Events e INNER JOIN Ratings r ON e.id = r.event_id WHERE e.date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR) AND e.event_type = 'Theater' GROUP BY e.language, r.age_group;
Display the names and consumer ratings of all cosmetics products that are not certified as organic.
CREATE TABLE product_details (product_name TEXT,is_organic_certified BOOLEAN,consumer_rating REAL); INSERT INTO product_details (product_name,is_organic_certified,consumer_rating) VALUES ('Product 1',true,4.2),('Product 2',false,3.5),('Product 3',true,4.8),('Product 4',false,1.8),('Product 5',true,2.5);
SELECT product_name, consumer_rating FROM product_details WHERE is_organic_certified = false;
What is the total revenue by product category for dispensaries in Los Angeles?
CREATE TABLE dispensaries (dispensary_id INT,name VARCHAR(255),city VARCHAR(255),state VARCHAR(255)); INSERT INTO dispensaries (dispensary_id,name,city,state) VALUES (1,'Dispensary A','Los Angeles','CA'),(2,'Dispensary B','San Francisco','CA'); CREATE TABLE sales (sale_id INT,dispensary_id INT,product_category VARCHAR(255),amount DECIMAL(10,2)); INSERT INTO sales (sale_id,dispensary_id,product_category,amount) VALUES (1,1,'flower',120.00),(2,1,'edibles',300.50),(3,2,'concentrates',75.25),(4,2,'flower',150.76);
SELECT d.city, p.product_category, SUM(s.amount) FROM dispensaries d INNER JOIN sales s ON d.dispensary_id = s.dispensary_id INNER JOIN (SELECT DISTINCT product_category FROM sales) p ON s.product_category = p.product_category WHERE d.city = 'Los Angeles' GROUP BY d.city, p.product_category;
What is the minimum severity score of vulnerabilities for each sector that has at least one high-severity vulnerability?
create table vulnerabilities (id int,sector varchar(255),severity int); insert into vulnerabilities values (1,'retail',7); insert into vulnerabilities values (2,'retail',5); insert into vulnerabilities values (3,'healthcare',8); insert into vulnerabilities values (4,'financial services',2); insert into vulnerabilities values (5,'financial services',9);
SELECT sector, MIN(severity) FROM vulnerabilities WHERE sector IN (SELECT sector FROM vulnerabilities WHERE severity = 9) GROUP BY sector;
Delete the record of the employee with ID 4 from the 'Diversity Metrics' table if they are from the 'Human Resources' department.
CREATE TABLE diversity_metrics (id INT,name VARCHAR(50),department VARCHAR(50),metric VARCHAR(50));
DELETE FROM diversity_metrics WHERE id = 4 AND department = 'Human Resources';
What is the total quantity of each item sold?
CREATE TABLE sales (sale_id INT,item_name VARCHAR(50),quantity INT); INSERT INTO sales (sale_id,item_name,quantity) VALUES (1,'Tomato',20),(2,'Chicken Breast',30),(3,'Vanilla Ice Cream',25);
SELECT item_name, SUM(quantity) FROM sales GROUP BY item_name;
Update the travel_advisory table to set the status to 'Safe' for the record with the location 'Japan'
CREATE TABLE travel_advisory (location VARCHAR(255),status VARCHAR(255),last_updated DATE);
UPDATE travel_advisory SET status = 'Safe' WHERE location = 'Japan';
What is the number of community health centers in each state, categorized by urban and rural areas?
CREATE TABLE states (state_id INT,state_name VARCHAR(255),region VARCHAR(255)); CREATE TABLE community_health_centers (center_id INT,center_name VARCHAR(255),state_id INT,location VARCHAR(255)); INSERT INTO states (state_id,state_name,region) VALUES (1,'California','West'),(2,'Texas','South'),(3,'New York','East'),(4,'Alaska','North'); INSERT INTO community_health_centers (center_id,center_name,state_id,location) VALUES (1,'Center A',1,'Urban'),(2,'Center B',2,'Rural'),(3,'Center C',3,'Urban'),(4,'Center D',4,'Rural');
SELECT s.region, CHC.location, COUNT(CHC.center_id) as center_count FROM community_health_centers CHC JOIN states s ON CHC.state_id = s.state_id GROUP BY s.region, CHC.location;
List the teams and the number of games they have lost in the "nba_games" table
CREATE TABLE nba_games (team VARCHAR(255),won INTEGER,games_played INTEGER);
SELECT team, SUM(games_played - won) as total_losses FROM nba_games GROUP BY team;
Find the average CO2 emissions (in kg) for garment manufacturers in France and Germany, for manufacturers with an emission rate higher than 5 kg per garment.
CREATE TABLE Manufacturers (id INT,country VARCHAR(50),co2_emission_rate DECIMAL(5,2)); INSERT INTO Manufacturers (id,country,co2_emission_rate) VALUES (1,'France',4.5),(2,'Germany',6.0),(3,'Italy',3.5),(4,'France',7.5),(5,'Germany',5.0),(6,'France',6.5);
SELECT AVG(m.co2_emission_rate) as avg_emission_rate FROM Manufacturers m WHERE m.country IN ('France', 'Germany') AND m.co2_emission_rate > 5;
What is the total revenue of all drugs approved in 2021?
CREATE TABLE drug_approval (drug_name TEXT,approval_year INTEGER);
SELECT SUM(revenue) FROM sales s INNER JOIN drug_approval a ON s.drug_name = a.drug_name WHERE a.approval_year = 2021;
List the number of investments in startups founded by Indigenous people in the renewable energy sector since 2017.
CREATE TABLE investment (id INT,company_id INT,investment_date DATE,investment_amount INT); INSERT INTO investment (id,company_id,investment_date,investment_amount) VALUES (1,1,'2018-01-01',500000);
SELECT COUNT(*) FROM investment INNER JOIN company ON investment.company_id = company.id WHERE company.industry = 'Renewable Energy' AND company.founder_gender = 'Indigenous' AND investment_date >= '2017-01-01';
What are the average salaries of players who switched teams in the last season?
CREATE TABLE players (player_id INT,name VARCHAR(50),last_name VARCHAR(50),current_team VARCHAR(50),previous_team VARCHAR(50),salary DECIMAL(10,2)); INSERT INTO players (player_id,name,last_name,current_team,previous_team,salary) VALUES (1,'John','Doe','Red Sox','Yankees',20000000),(2,'Jane','Smith','Cubs','Dodgers',18000000);
SELECT AVG(salary) FROM players WHERE current_team <> previous_team AND game_date >= DATEADD(year, -1, GETDATE());
What is the average donation amount per donor from 'Mexico' in the year 2020?
CREATE TABLE Donors (DonorID int,DonorName varchar(100),Country varchar(50),DonationAmount decimal(10,2)); INSERT INTO Donors (DonorID,DonorName,Country,DonationAmount) VALUES (1,'John Doe','Mexico',500.00);
SELECT AVG(DonationAmount) FROM Donors WHERE Country = 'Mexico' AND YEAR(DonationDate) = 2020;
Which ethical AI organizations have the most initiatives in Asia?
CREATE TABLE ethics_org (name VARCHAR(50),initiatives INT,region VARCHAR(50)); INSERT INTO ethics_org (name,initiatives,region) VALUES ('Ethics Asia',12,'Asia'),('AI Watchdog',15,'Asia');
SELECT name FROM ethics_org WHERE region = 'Asia' ORDER BY initiatives DESC;
How many news articles were published in each month of 2021?
CREATE TABLE news_publication_dates (title VARCHAR(100),publication_date DATE); INSERT INTO news_publication_dates (title,publication_date) VALUES ('Article 1','2021-01-01'),('Article 2','2021-02-03'),('Article 3','2021-02-15'),('Article 4','2021-03-05'),('Article 5','2021-04-10');
SELECT EXTRACT(MONTH FROM publication_date) AS month, COUNT(*) AS articles_published FROM news_publication_dates GROUP BY month;
What is the maximum budget for projects in Los Angeles with 'Residential' in their names?
CREATE TABLE Project_Budget (id INT,project_name TEXT,location TEXT,budget INT); INSERT INTO Project_Budget (id,project_name,location,budget) VALUES (1,'Residential Tower','Los Angeles',7000000),(2,'Commercial Building','Los Angeles',9000000);
SELECT MAX(budget) FROM Project_Budget WHERE location = 'Los Angeles' AND project_name LIKE '%Residential%';
How many high severity vulnerabilities were reported by each source in July 2021, which have not been mitigated yet?
CREATE TABLE vulnerabilities (id INT PRIMARY KEY,source VARCHAR(255),severity VARCHAR(255),mitigation_date DATE); INSERT INTO vulnerabilities (id,source,severity,mitigation_date) VALUES (1,'NSA','High','2021-08-01');
SELECT source, COUNT(*) as num_vulnerabilities FROM vulnerabilities WHERE severity = 'High' AND mitigation_date > '2021-07-01' GROUP BY source HAVING num_vulnerabilities > 0;
Display the average hotel rating and the number of eco-friendly hotels in each region.
CREATE TABLE hotels (hotel_id INT,name TEXT,country TEXT,stars FLOAT,is_eco_friendly BOOLEAN); CREATE TABLE countries (country_id INT,name TEXT,region TEXT);
SELECT c.region, AVG(h.stars) AS avg_rating, SUM(h.is_eco_friendly) AS eco_friendly_hotels FROM hotels h INNER JOIN countries c ON h.country = c.name GROUP BY c.region;
How many wells are there in total?
CREATE TABLE well_counts (well_name TEXT); INSERT INTO well_counts (well_name) VALUES ('Well A'),('Well B'),('Well C'),('Well D'),('Well E'),('Well F');
SELECT COUNT(*) FROM well_counts;
Find the total number of visitors to sustainable destinations in Europe, grouped by their nationality and the month of their visit in 2021.
CREATE TABLE SustainableDestinations (DestinationID INT,Destination VARCHAR(20)); INSERT INTO SustainableDestinations (DestinationID,Destination) VALUES (1,'Eco-Village'),(2,'GreenCity'); CREATE TABLE Visits (VisitorID INT,Nationality VARCHAR(20),DestinationID INT,VisitMonth INT,VisitYear INT); INSERT INTO Visits (VisitorID,Nationality,DestinationID,VisitMonth,VisitYear) VALUES (1,'French',1,3,2021),(2,'German',2,5,2021);
SELECT Nationality, VisitMonth, COUNT(*) as Total FROM Visits JOIN SustainableDestinations ON Visits.DestinationID = SustainableDestinations.DestinationID WHERE VisitYear = 2021 AND Destination IN ('Eco-Village', 'GreenCity') GROUP BY Nationality, VisitMonth;
What is the total area of properties in the city of Austin with a walkability score above 70?
CREATE TABLE properties (id INT,area FLOAT,city VARCHAR(20),walkability_score INT); INSERT INTO properties (id,area,city,walkability_score) VALUES (1,1500,'Austin',80),(2,1200,'Austin',75),(3,1800,'Austin',78),(4,1100,'Denver',60),(5,1400,'Austin',72);
SELECT SUM(area) FROM properties WHERE city = 'Austin' AND walkability_score > 70;
How many users have achieved their daily step goal for the past week, and what is the average age of these users?
CREATE TABLE Users (ID INT PRIMARY KEY,Age INT,DailySteps INT,Date DATE);
SELECT AVG(Age), COUNT(*) FROM Users WHERE DailySteps >= (SELECT AVG(DailySteps) FROM Users WHERE Date = (SELECT MAX(Date) FROM Users)) AND Date >= DATEADD(week, -1, GETDATE());
List the station names and their corresponding latitudes and longitudes, ordered by name.
CREATE TABLE stations (station_id INT,name VARCHAR(255),latitude DECIMAL(9,6),longitude DECIMAL(9,6)); CREATE VIEW station_info AS SELECT name,latitude,longitude FROM stations;
SELECT name, latitude, longitude FROM station_info ORDER BY name;
Delete the environmental impact records of mines located in Colorado.
CREATE TABLE environmental_impact (id INT,mine_id INT,pollution_level FLOAT,FOREIGN KEY (mine_id) REFERENCES mines(id)); INSERT INTO environmental_impact (id,mine_id,pollution_level) VALUES (7,11,2.8); INSERT INTO environmental_impact (id,mine_id,pollution_level) VALUES (8,12,2.3); CREATE TABLE mines (id INT,name VARCHAR(50),location VARCHAR(50),PRIMARY KEY(id)); INSERT INTO mines (id,name,location) VALUES (11,'Colorado Gold','Colorado'); INSERT INTO mines (id,name,location) VALUES (12,'Crystal Peak','Colorado');
DELETE e FROM environmental_impact e JOIN mines m ON e.mine_id = m.id WHERE m.location = 'Colorado';
What is the minimum age of players who have played Valorant and are from Oceania?
CREATE TABLE Players (PlayerID INT,PlayerAge INT,Game VARCHAR(50),Country VARCHAR(50)); INSERT INTO Players (PlayerID,PlayerAge,Game,Country) VALUES (1,22,'Valorant','Australia'); INSERT INTO Players (PlayerID,PlayerAge,Game,Country) VALUES (2,25,'Valorant','Canada'); INSERT INTO Players (PlayerID,PlayerAge,Game,Country) VALUES (3,19,'Valorant','Australia');
SELECT MIN(PlayerAge) as MinAge FROM Players WHERE Game = 'Valorant' AND Country = 'Australia';
What is the total number of mental health counseling sessions provided to students in the "East" region?
CREATE TABLE counseling (session_id INT,student_id INT,region VARCHAR(20),session_date DATE); INSERT INTO counseling (session_id,student_id,region,session_date) VALUES (1,1,'East','2021-03-01'),(2,2,'North','2021-04-15'),(3,3,'East','2020-12-31'),(4,4,'West','2021-06-05'),(5,5,'South','2021-11-30');
SELECT COUNT(*) FROM counseling WHERE region = 'East';
Which destinations in Canada have the highest increase in visitors from 2019 to 2022?
CREATE TABLE canada_tourism (destination VARCHAR(50),year INT,visitors INT); INSERT INTO canada_tourism (destination,year,visitors) VALUES ('Banff',2019,500000),('Banff',2022,700000),('Whistler',2019,300000),('Whistler',2022,500000);
SELECT destination, MAX(visitors) - MIN(visitors) AS increase FROM canada_tourism WHERE year IN (2019, 2022) GROUP BY destination ORDER BY increase DESC;
What is the average yield per harvest for each cultivation facility in Washington, grouped by facility?
CREATE TABLE cultivation_facilities (facility_id INT,name TEXT,state TEXT); INSERT INTO cultivation_facilities (facility_id,name,state) VALUES (1,'Facility A','Washington'),(2,'Facility B','Washington'); CREATE TABLE harvests (harvest_id INT,facility_id INT,yield INT); INSERT INTO harvests (harvest_id,facility_id,yield) VALUES (1,1,500),(2,1,700),(3,2,300);
SELECT f.name, AVG(h.yield) AS avg_yield FROM cultivation_facilities f JOIN harvests h ON f.facility_id = h.facility_id WHERE f.state = 'Washington' GROUP BY f.name;
What is the average fairness score of all algorithms created in the Middle East?
CREATE TABLE Algorithms (AlgorithmId INT,Name TEXT,FairnessScore FLOAT,Country TEXT); INSERT INTO Algorithms (AlgorithmId,Name,FairnessScore,Country) VALUES (1,'AlgorithmA',0.85,'Saudi Arabia'),(2,'AlgorithmB',0.9,'UAE'),(3,'AlgorithmC',0.75,'Israel');
SELECT AVG(FairnessScore) FROM Algorithms WHERE Country = 'Middle East';
What is the total biomass of fish in farms located in Country A?
CREATE TABLE Farm (FarmID int,FarmName varchar(50),Location varchar(50)); INSERT INTO Farm (FarmID,FarmName,Location) VALUES (1,'Farm A','Country A'); INSERT INTO Farm (FarmID,FarmName,Location) VALUES (2,'Farm B','Country B'); CREATE TABLE FishStock (FishStockID int,FishSpecies varchar(50),FarmID int,Biomass numeric); INSERT INTO FishStock (FishStockID,FishSpecies,FarmID,Biomass) VALUES (1,'Tilapia',1,500); INSERT INTO FishStock (FishStockID,FishSpecies,FarmID,Biomass) VALUES (2,'Salmon',2,700); INSERT INTO FishStock (FishStockID,FishSpecies,FarmID,Biomass) VALUES (3,'Tilapia',1,600);
SELECT SUM(Biomass) FROM FishStock WHERE FarmID IN (SELECT FarmID FROM Farm WHERE Location = 'Country A');
Which policyholders have policies in both the car and life insurance categories, and what are their policy numbers?
CREATE TABLE car_insurance (policyholder_name TEXT,policy_number INTEGER); CREATE TABLE life_insurance (policyholder_name TEXT,policy_number INTEGER); INSERT INTO car_insurance VALUES ('Alice',123),('Bob',456),('Charlie',789),('Dave',111); INSERT INTO life_insurance VALUES ('Bob',999),('Eve',888),('Alice',222),('Dave',333);
SELECT policyholder_name, policy_number FROM car_insurance WHERE policyholder_name IN (SELECT policyholder_name FROM life_insurance);
What is the average salary of workers in the 'textiles' department across all factories?
CREATE TABLE factories (factory_id INT,department VARCHAR(20)); CREATE TABLE workers (worker_id INT,factory_id INT,salary DECIMAL(5,2),department VARCHAR(20)); INSERT INTO factories (factory_id,department) VALUES (1,'textiles'),(2,'metalwork'),(3,'electronics'); INSERT INTO workers (worker_id,factory_id,salary,department) VALUES (1,1,35000,'textiles'),(2,1,40000,'textiles'),(3,2,50000,'metalwork'),(4,3,60000,'electronics');
SELECT AVG(w.salary) FROM workers w INNER JOIN factories f ON w.factory_id = f.factory_id WHERE f.department = 'textiles';
What is the average attendance for events in the 'Midwest' region with an attendance of over 400?
CREATE TABLE Events (event_id INT,region VARCHAR(20),attendee_count INT); INSERT INTO Events (event_id,region,attendee_count) VALUES (1,'Midwest',600),(2,'Southeast',400),(3,'Northeast',350);
SELECT AVG(attendee_count) FROM Events WHERE region = 'Midwest' AND attendee_count > 400
How many users unsubscribed from the music streaming service in India?
CREATE TABLE Users (user_id INT,username VARCHAR(50),registration_date DATE,unsubscription_date DATE,country VARCHAR(50)); INSERT INTO Users (user_id,username,registration_date,unsubscription_date,country) VALUES (11,'UserK','2022-01-01','2022-02-01','India'); INSERT INTO Users (user_id,username,registration_date,unsubscription_date,country) VALUES (12,'UserL','2022-01-02',NULL,'USA'); INSERT INTO Users (user_id,username,registration_date,unsubscription_date,country) VALUES (13,'UserM','2022-01-03','2022-03-01','India');
SELECT COUNT(*) FROM Users WHERE unsubscription_date IS NOT NULL AND country = 'India';
Compare military equipment maintenance requests in the Pacific and Atlantic regions for Q2 2022
CREATE TABLE maintenance_requests (region TEXT,quarter NUMERIC,num_requests NUMERIC); INSERT INTO maintenance_requests (region,quarter,num_requests) VALUES ('Pacific',2,50),('Atlantic',2,60),('Pacific',3,55),('Atlantic',1,45);
SELECT region, num_requests FROM maintenance_requests WHERE region IN ('Pacific', 'Atlantic') AND quarter = 2;
What is the combined budget for energy efficiency projects in Colombia and Indonesia?
CREATE TABLE energy_efficiency_projects (project_name VARCHAR(50),country VARCHAR(20),budget DECIMAL(10,2)); INSERT INTO energy_efficiency_projects (project_name,country,budget) VALUES ('Project E','Colombia',60000.00),('Project F','Indonesia',75000.00);
SELECT SUM(budget) FROM energy_efficiency_projects eep WHERE eep.country IN ('Colombia', 'Indonesia');
What is the total number of community policing scores in the city of Los Angeles?
CREATE TABLE public.community_policing (id serial PRIMARY KEY,city varchar(255),score int); INSERT INTO public.community_policing (city,score) VALUES ('Los Angeles',80),('Los Angeles',85),('Los Angeles',90);
SELECT COUNT(*) FROM public.community_policing WHERE city = 'Los Angeles';
Display the names of therapists who have conducted therapy sessions for patients diagnosed with 'Anxiety Disorder'
CREATE TABLE therapists (therapist_id INT PRIMARY KEY,therapist_name TEXT,specialization TEXT); CREATE TABLE patients (patient_id INT PRIMARY KEY,patient_name TEXT,date_of_birth DATE,diagnosis TEXT); CREATE TABLE therapy_sessions (session_id INT PRIMARY KEY,patient_id INT,therapist_id INT,session_date DATE,session_duration TIME);
SELECT therapists.therapist_name FROM therapists INNER JOIN (SELECT patients.patient_id, therapy_sessions.therapist_id FROM patients INNER JOIN therapy_sessions ON patients.patient_id = therapy_sessions.patient_id WHERE patients.diagnosis = 'Anxiety Disorder') AS therapy_sessions_filtered ON therapists.therapist_id = therapy_sessions_filtered.therapist_id;
What is the average rainfall in millimeters for each region in the 'rainfall_data_2021' table for the month of June?
CREATE TABLE rainfall_data_2021 (id INT,region VARCHAR(20),rainfall DECIMAL(5,2),capture_date DATE); INSERT INTO rainfall_data_2021 (id,region,rainfall,capture_date) VALUES (1,'North',50.2,'2021-06-01'),(2,'South',75.6,'2021-07-01'),(3,'North',34.8,'2021-06-15');
SELECT region, AVG(rainfall) FROM rainfall_data_2021 WHERE MONTH(capture_date) = 6 GROUP BY region;
Which members had a heart rate over 150 during their last workout?
CREATE TABLE member_workouts (workout_id INT,member_id INT,heart_rate INT,date DATE); INSERT INTO member_workouts VALUES (1,1,155,'2022-01-15'); INSERT INTO member_workouts VALUES (2,2,145,'2022-01-16');
SELECT member_workouts.member_id, member_workouts.heart_rate FROM member_workouts INNER JOIN (SELECT member_id, MAX(date) AS max_date FROM member_workouts GROUP BY member_id) AS max_dates ON member_workouts.member_id = max_dates.member_id AND member_workouts.date = max_dates.max_date WHERE member_workouts.heart_rate > 150;
What is the running total of Europium production for the top 3 producers in 2021?
CREATE TABLE europium_production (id INT,year INT,producer VARCHAR(255),europium_prod FLOAT); INSERT INTO europium_production (id,year,producer,europium_prod) VALUES (1,2021,'China',123.4),(2,2021,'USA',234.5),(3,2021,'Australia',345.6),(4,2021,'Myanmar',456.7),(5,2021,'India',567.8);
SELECT producer, SUM(europium_prod) OVER (PARTITION BY producer ORDER BY europium_prod) AS running_total FROM europium_production WHERE year = 2021 AND producer IN ('China', 'USA', 'Australia') ORDER BY europium_prod;
Add a new table workout_schedule with columns id, member_id, workout_date, workout_duration and insert records for 3 members with id 21, 22, 23 with workout_date as '2023-03-01', '2023-03-02', '2023-03-03' and workout_duration as '60', '45', '90' respectively
CREATE TABLE workout_schedule (id INT,member_id INT,workout_date DATE,workout_duration INT);
INSERT INTO workout_schedule (id, member_id, workout_date, workout_duration) VALUES (1, 21, '2023-03-01', 60), (2, 22, '2023-03-02', 45), (3, 23, '2023-03-03', 90);
What is the number of articles published per month for each author in the 'articles' table?
CREATE TABLE articles (pub_date DATE,title TEXT,author TEXT);
SELECT DATE_TRUNC('month', pub_date) AS month, author, COUNT(*) FROM articles GROUP BY month, author;
Add a new record to the "hospitals" table for a hospital located in "NY" with 600 total beds
CREATE TABLE hospitals (id INT PRIMARY KEY,name TEXT,state TEXT,total_beds INT);
INSERT INTO hospitals (name, state, total_beds) VALUES ('Hospital NY', 'NY', 600);
Find the number of peacekeeping operations where the Marine Corps and Army participated together.
CREATE TABLE peacekeeping (id INT,operation VARCHAR(50),service1 VARCHAR(10),service2 VARCHAR(10),year INT); INSERT INTO peacekeeping (id,operation,service1,service2,year) VALUES (1,'Op1','Marine Corps','Army',2017);
SELECT COUNT(*) FROM peacekeeping WHERE (service1 = 'Marine Corps' AND service2 = 'Army') OR (service1 = 'Army' AND service2 = 'Marine Corps');
Which region has the highest number of textile workers in fair trade certified factories?
CREATE TABLE FactoryWorkers (id INT,factory_id INT,worker_count INT,region TEXT,certification TEXT); INSERT INTO FactoryWorkers (id,factory_id,worker_count,region,certification) VALUES (1,1,1000,'Asia','Fair Trade'),(2,2,750,'Africa','Global Organic Textile Standard'),(3,3,1500,'South America','Fair Trade'),(4,4,800,'Europe','Global Recycled Standard'),(5,5,1200,'North America','Fair Trade');
SELECT region, COUNT(*) AS count FROM FactoryWorkers WHERE certification = 'Fair Trade' GROUP BY region ORDER BY count DESC LIMIT 1;
Find the average budget for schools in 'District3'
CREATE TABLE Districts (DistrictName VARCHAR(20),AvgSchoolBudget DECIMAL(5,2)); INSERT INTO Districts (DistrictName,AvgSchoolBudget) VALUES ('District3',5500.00),('District4',6500.00);
SELECT AVG(AvgSchoolBudget) FROM Districts WHERE DistrictName = 'District3';
What are the average prices of cosmetics in the luxury and drugstore segments?
CREATE TABLE products (product_id INT,product_name TEXT,segment TEXT,price DECIMAL); CREATE TABLE sales (sale_id INT,product_id INT,sale_price DECIMAL); INSERT INTO products VALUES (1,'Shampoo','Luxury',30),(2,'Conditioner','Luxury',40),(3,'Lipstick','Drugstore',10),(4,'Mascara','Drugstore',12); INSERT INTO sales VALUES (1,1,35),(2,2,42),(3,3,11),(4,4,13);
SELECT segment, AVG(sale_price) as avg_price FROM sales s JOIN products p ON s.product_id = p.product_id GROUP BY segment;
What is the average delivery time for shipments that were delayed due to customs issues?
CREATE TABLE Shipments (id INT,weight INT,delay_reason VARCHAR(50),delivery_date DATE,shipped_date DATE); INSERT INTO Shipments (id,weight,delay_reason,delivery_date,shipped_date) VALUES (1,100,'Customs','2022-01-05','2022-01-03'),(2,150,'Mechanical','2022-01-07','2022-01-06'),(3,200,'Customs','2022-02-12','2022-02-10');
SELECT AVG(DATEDIFF(delivery_date, shipped_date)) AS avg_delivery_time FROM Shipments WHERE delay_reason = 'Customs';
Find the total number of network infrastructure investments in the Western region
CREATE TABLE network_investments (investment_id INT,region VARCHAR(10),investment_amount FLOAT);
SELECT SUM(investment_amount) FROM network_investments WHERE region = 'Western';
What is the total value of defense contracts awarded to companies in California in Q1 2022?
CREATE TABLE defense_contracts (contract_id INT,company_name TEXT,state TEXT,value FLOAT,contract_date DATE); INSERT INTO defense_contracts (contract_id,company_name,state,value,contract_date) VALUES (1,'ABC Corp','California',500000,'2022-01-05'),(2,'XYZ Inc','California',750000,'2022-03-15');
SELECT SUM(value) FROM defense_contracts WHERE state = 'California' AND contract_date >= '2022-01-01' AND contract_date < '2022-04-01';
How many volunteers signed up in each state?
CREATE TABLE volunteers (id INT,state VARCHAR(2)); INSERT INTO volunteers (id,state) VALUES (1,'NY'),(2,'CA'),(3,'TX');
SELECT state, COUNT(*) AS num_volunteers FROM volunteers GROUP BY state;
What is the total amount of minerals extracted in each location for the month 1 in 2020?
CREATE TABLE extraction(id INT,location TEXT,month INT,year INT,minerals_extracted FLOAT);INSERT INTO extraction(id,location,month,year,minerals_extracted) VALUES (1,'north',1,2020,1500),(2,'north',2,2020,1800),(3,'south',1,2020,1200),(4,'east',1,2020,1000);
SELECT location, SUM(minerals_extracted) FROM extraction WHERE month = 1 AND year = 2020 GROUP BY location;
What is the total value of defense contracts signed with company 'Z' in 2021?
CREATE TABLE defense_contracts (id INT,contract_date DATE,contract_value INT,company VARCHAR(50)); INSERT INTO defense_contracts (id,contract_date,contract_value,company) VALUES (1,'2021-01-15',5000000,'Z'),(2,'2021-03-30',8000000,'Y'),(3,'2021-04-12',3000000,'Z');
SELECT SUM(contract_value) FROM defense_contracts WHERE company = 'Z' AND YEAR(contract_date) = 2021;
What is the earliest visit date for vessels that have visited 'Port A'?
CREATE TABLE ports (port_id INT,port_name TEXT,country TEXT); INSERT INTO ports (port_id,port_name,country) VALUES (1,'Port A','USA'),(2,'Port B','Canada'); CREATE TABLE visits (visit_id INT,vessel_id INT,port_id INT,visit_date DATE); INSERT INTO visits (visit_id,vessel_id,port_id,visit_date) VALUES (1,1,1,'2021-02-01'),(2,2,1,'2021-03-01'),(3,1,2,'2021-04-01');
SELECT MIN(visit_date) FROM visits WHERE port_id = (SELECT port_id FROM ports WHERE port_name = 'Port A');
What is the average budget for AI projects in the education sector?
CREATE TABLE ai_projects (sector VARCHAR(20),budget INT); INSERT INTO ai_projects (sector,budget) VALUES ('Education',200000),('Healthcare',500000),('Finance',1000000);
SELECT AVG(budget) FROM ai_projects WHERE sector = 'Education';
Who are the founders of companies that have received more than $1M in funding and are located in the Bay Area?
CREATE TABLE company (id INT,name TEXT,founder_name TEXT,city TEXT); INSERT INTO company (id,name,founder_name,city) VALUES (1,'InnoTech','John Doe','San Francisco'); INSERT INTO company (id,name,founder_name,city) VALUES (2,'GreenEnergy','Jane Smith','Berkeley'); INSERT INTO company (id,name,founder_name,city) VALUES (3,'EduTech','Alice Johnson','New York'); CREATE TABLE funding (company_id INT,amount INT); INSERT INTO funding (company_id,amount) VALUES (1,1500000); INSERT INTO funding (company_id,amount) VALUES (2,1200000); INSERT INTO funding (company_id,amount) VALUES (3,800000);
SELECT company.founder_name FROM company INNER JOIN funding ON company.id = funding.company_id WHERE funding.amount > 1000000 AND company.city = 'San Francisco';
What is the total billing amount for each attorney, based on the 'attorney_id' column in the 'attorneys' table?
CREATE TABLE attorneys (attorney_id INT,attorney_state VARCHAR(255)); CREATE TABLE cases (case_id INT,attorney_id INT); CREATE TABLE billing (bill_id INT,case_id INT,amount DECIMAL(10,2));
SELECT a.attorney_id, SUM(b.amount) FROM attorneys a INNER JOIN cases c ON a.attorney_id = c.attorney_id INNER JOIN billing b ON c.case_id = b.case_id GROUP BY a.attorney_id;
Which cities have the most eco-friendly hotels?
CREATE TABLE eco_hotels(id INT,name TEXT,city TEXT,sustainable BOOLEAN); INSERT INTO eco_hotels(id,name,city,sustainable) VALUES (1,'EcoHotel Roma','Rome',true),(2,'Paris Sustainable Suites','Paris',true),(3,'Barcelona Green Living','Barcelona',true);
SELECT city, COUNT(*) FROM eco_hotels WHERE sustainable = true GROUP BY city ORDER BY COUNT(*) DESC;
What is the number of cultural events attended by 'Alex' from Canada?
CREATE TABLE attendees (id INT,name VARCHAR(50),country VARCHAR(50),events INT); INSERT INTO attendees (id,name,country,events) VALUES (1,'Alex','Canada',20),(2,'Bella','United States',15),(3,'Charlie','Canada',25);
SELECT events FROM attendees WHERE name = 'Alex' AND country = 'Canada';
Which estuary in Europe has the lowest salinity?"
CREATE TABLE estuaries (id INT,name TEXT,location TEXT,salinity FLOAT,area_size FLOAT); INSERT INTO estuaries (id,name,location,salinity,area_size) VALUES (1,'Gironde Estuary','Europe',0.5,665);
SELECT name, MIN(salinity) FROM estuaries WHERE location = 'Europe';
What are the total quantities of metal waste generated in 2019, grouped by location?
CREATE TABLE WasteGeneration (WasteID INT,WasteType VARCHAR(20),Location VARCHAR(20),Quantity INT,Year INT); INSERT INTO WasteGeneration (WasteID,WasteType,Location,Quantity,Year) VALUES (1,'Metal','New York',1500,2019),(2,'Metal','Los Angeles',1200,2019);
SELECT Location, SUM(Quantity) as TotalQuantity FROM WasteGeneration WHERE WasteType = 'Metal' AND Year = 2019 GROUP BY Location;
What is the difference between the earliest and latest delivery times in Japan?
CREATE TABLE Warehouses (WarehouseID INT,WarehouseName VARCHAR(50),Country VARCHAR(50)); INSERT INTO Warehouses (WarehouseID,WarehouseName,Country) VALUES (1,'Japan Warehouse','Japan'); CREATE TABLE Shipments (ShipmentID INT,WarehouseID INT,DeliveryTime INT);
SELECT MAX(DeliveryTime) - MIN(DeliveryTime) FROM Shipments WHERE WarehouseID = (SELECT WarehouseID FROM Warehouses WHERE Country = 'Japan');
list all countries that farm both salmon and trout
CREATE TABLE AquacultureCountries (CountryName TEXT,Species TEXT); INSERT INTO AquacultureCountries (CountryName,Species) VALUES ('Norway','Salmon'),('Norway','Trout'),('Chile','Salmon'),('Chile','Trout'),('Scotland','Salmon'),('Scotland','Trout'),('Canada','Salmon'),('Canada','Trout'),('Ireland','Salmon'),('Ireland','Trout');
SELECT CountryName FROM AquacultureCountries WHERE Species IN ('Salmon', 'Trout') GROUP BY CountryName HAVING COUNT(DISTINCT Species) = 2;
Insert a new client named 'Jamal Smith' into the 'clients' table and assign them a unique client_id.
CREATE TABLE clients (client_id INT PRIMARY KEY AUTO_INCREMENT,client_name VARCHAR(255));
INSERT INTO clients (client_name) VALUES ('Jamal Smith');
What is the average age of coaches in the NBA?
CREATE TABLE nba_teams (team_id INT,team_name VARCHAR(100),coach_age INT); INSERT INTO nba_teams (team_id,team_name,coach_age) VALUES (1,'Golden State Warriors',50),(2,'Boston Celtics',45);
SELECT AVG(coach_age) FROM nba_teams;
What is the total number of 'cardio' workouts for each month of the year 2022?'
CREATE TABLE workouts (id INT,workout_date DATE,activity_type VARCHAR(50),duration INT); INSERT INTO workouts (id,workout_date,activity_type,duration) VALUES (1,'2022-01-01','cardio',60),(2,'2022-01-02','strength',45),(3,'2022-02-03','cardio',75),(4,'2022-02-04','yoga',60),(5,'2022-03-05','cardio',90),(6,'2022-03-06','strength',45);
SELECT DATE_FORMAT(workout_date, '%Y-%m') AS month, COUNT(*) AS total_workouts FROM workouts WHERE activity_type = 'cardio' GROUP BY month;
What is the total number of schools that offer lifelong learning programs in the 'school_data' table?
CREATE TABLE school_data (school_id INT,school_name VARCHAR(50),offers_lifelong_learning BOOLEAN);
SELECT COUNT(*) FROM school_data WHERE offers_lifelong_learning = TRUE;
Insert a new record into the "organizations" table with the name "Green Code Initiative", type "Non-profit", and country "Nigeria"
CREATE TABLE organizations (id INT PRIMARY KEY,name VARCHAR(100),type VARCHAR(50),country VARCHAR(50));
INSERT INTO organizations (name, type, country) VALUES ('Green Code Initiative', 'Non-profit', 'Nigeria');
Identify the average CO2 emission reduction (in metric tons) of projects in the 'wind' technology type.
CREATE TABLE projects (id INT,technology VARCHAR(20),CO2_reduction_tons INT); INSERT INTO projects (id,technology,CO2_reduction_tons) VALUES (1,'wind',1500),(2,'solar',1200),(3,'wind',2000),(4,'hydro',2500);
SELECT AVG(CO2_reduction_tons) AS avg_reduction FROM projects WHERE technology = 'wind';
What is the percentage of cosmetic products in the German market that contain parabens, and how many products were rated?
CREATE TABLE cosmetics_ingredients (product_id INT,ingredient TEXT,country TEXT); CREATE VIEW paraben_products AS SELECT product_id FROM cosmetics_ingredients WHERE ingredient = 'parabens'; CREATE VIEW all_products AS SELECT product_id FROM cosmetics_ingredients;
SELECT 100.0 * COUNT(*) FILTER (WHERE product_id IN (SELECT product_id FROM paraben_products)) / COUNT(*) as paraben_percentage FROM all_products WHERE country = 'Germany';
Identify the top 3 regions with the highest number of accessible technology programs for people with disabilities.
CREATE TABLE regions (id INT,name VARCHAR(50)); CREATE TABLE accessible_tech_programs (id INT,region_id INT,participants INT); INSERT INTO regions (id,name) VALUES (1,'Americas'),(2,'Asia'),(3,'Europe'),(4,'Africa'); INSERT INTO accessible_tech_programs (id,region_id,participants) VALUES (1,1,500),(2,1,700),(3,2,800),(4,3,1000),(5,3,1200),(6,4,1500);
SELECT regions.name, COUNT(accessible_tech_programs.id) as program_count FROM regions INNER JOIN accessible_tech_programs ON regions.id = accessible_tech_programs.region_id GROUP BY regions.name ORDER BY program_count DESC LIMIT 3;
Display vessels with a maximum speed of over 30 knots and their corresponding details.
CREATE TABLE vessels (vessel_id INT,vessel_name VARCHAR(255),length INT,year_built INT,max_speed FLOAT);
SELECT * FROM vessels WHERE max_speed > 30;
Insert new records for a brand from Kenya that has just started using organic cotton and recycled polyester.
CREATE TABLE brands (brand_id INT,brand_name TEXT,country TEXT); INSERT INTO brands (brand_id,brand_name,country) VALUES (1,'EcoBrand','India'),(4,'AfricanEthicalFashion','Kenya'); CREATE TABLE material_usage (brand_id INT,material_type TEXT,quantity INT,co2_emissions INT); INSERT INTO material_usage (brand_id,material_type,quantity,co2_emissions) VALUES (1,'recycled_polyester',1200,2500),(1,'organic_cotton',800,1000);
INSERT INTO material_usage (brand_id, material_type, quantity, co2_emissions) VALUES (4, 'organic_cotton', 1500, 1200), (4, 'recycled_polyester', 1800, 2000);
What is the difference in the number of members between unions 'N' and 'O'?
CREATE TABLE UnionN(member_id INT); INSERT INTO UnionN(member_id) VALUES(14001),(14002),(14003); CREATE TABLE UnionO(member_id INT); INSERT INTO UnionO(member_id) VALUES(15001),(15002);
SELECT COUNT(*) FROM UnionN EXCEPT SELECT COUNT(*) FROM UnionO;
What is the average fuel efficiency for compact cars?
CREATE TABLE vehicles (vehicle_id INT,model VARCHAR(20),manufacture VARCHAR(20),fuel_efficiency FLOAT,vehicle_type VARCHAR(20));
SELECT AVG(fuel_efficiency) FROM vehicles WHERE vehicle_type = 'compact';
What is the total revenue generated by each artist from digital sales?
CREATE TABLE ArtistRevenue (Artist VARCHAR(20),Revenue FLOAT); INSERT INTO ArtistRevenue (Artist,Revenue) VALUES ('Taylor Swift','4000000'),('Eminem','3500000'),('The Beatles','5000000'),('BTS','6000000');
SELECT Artist, SUM(Revenue) FROM ArtistRevenue GROUP BY Artist;
Which cities have more than 2 properties?
CREATE TABLE properties (property_id INT,city VARCHAR(50)); INSERT INTO properties (property_id,city) VALUES (1,'Portland'),(2,'Seattle'),(3,'Portland'),(4,'Oakland'),(5,'Seattle'),(6,'Oakland'),(7,'Oakland');
SELECT city, COUNT(*) FROM properties GROUP BY city HAVING COUNT(*) > 2;
Create a new table 'teacher_skills' with columns 'teacher_id', 'skill_name' and insert at least 3 records.
CREATE TABLE teacher_skills (teacher_id INT,skill_name VARCHAR(20)); INSERT INTO teacher_skills (teacher_id,skill_name) VALUES (1,'Python'),(2,'Java'),(3,'SQL');
SELECT * FROM teacher_skills;
What are the top 5 countries with the highest energy efficiency ratings for renewable energy projects?
CREATE TABLE Renewable_Energy_Projects (project_id INT,location VARCHAR(50),energy_efficiency_rating INT); INSERT INTO Renewable_Energy_Projects (project_id,location,energy_efficiency_rating) VALUES (1,'Germany',90),(2,'Spain',88),(3,'Denmark',85),(4,'China',82),(5,'United States',80),(6,'India',78);
SELECT location, energy_efficiency_rating, RANK() OVER (ORDER BY energy_efficiency_rating DESC) as country_rank FROM Renewable_Energy_Projects WHERE location IN ('Germany', 'Spain', 'Denmark', 'China', 'United States', 'India') GROUP BY location, energy_efficiency_rating HAVING country_rank <= 5;
What is the average age of patients diagnosed with diabetes in the rural county of 'Briarwood'?
CREATE TABLE patients (patient_id INT,diagnosis VARCHAR(255),age INT,county VARCHAR(255)); INSERT INTO patients (patient_id,diagnosis,age,county) VALUES (1,'diabetes',60,'Briarwood'),(2,'asthma',30,'Briarwood'),(3,'diabetes',55,'Briarwood');
SELECT AVG(age) FROM patients WHERE diagnosis = 'diabetes' AND county = 'Briarwood';
How many community programs were created in the Pacific region in the past year?
CREATE TABLE region (region_id INT,name VARCHAR(255)); INSERT INTO region (region_id,name) VALUES (1,'Pacific'); CREATE TABLE community_program (program_id INT,name VARCHAR(255),region_id INT,creation_date DATE); INSERT INTO community_program (program_id,name,region_id,creation_date) VALUES (1,'Program1',1,'2021-01-01'),(2,'Program2',1,'2022-05-15');
SELECT COUNT(*) FROM community_program WHERE region_id = (SELECT region_id FROM region WHERE name = 'Pacific') AND creation_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR);
Delete records of customers from the 'finance' schema with a balance less than 5000
CREATE TABLE finance.customers (id INT,name VARCHAR(255),country VARCHAR(255),balance DECIMAL(10,2)); INSERT INTO finance.customers (id,name,country,balance) VALUES (1,'John Doe','USA',4000.00),(2,'Jane Smith','Canada',7000.00),(3,'Alice Johnson','UK',6000.00);
DELETE FROM finance.customers WHERE balance < 5000;
What is the average number of mental health parity violations recorded per provider, in the 'providers' and 'violations' tables?
CREATE TABLE providers (id INT,name VARCHAR(50),language VARCHAR(50),parity_violations INT); INSERT INTO providers (id,name,language,parity_violations) VALUES (1,'Dr. Maria Garcia','Spanish',7),(2,'Dr. John Smith','English',3); CREATE TABLE violations (id INT,provider_id INT,date DATE); INSERT INTO violations (id,provider_id,date) VALUES (1,1,'2022-01-01'),(2,1,'2022-02-01');
SELECT AVG(p.parity_violations) FROM providers p;
What is the minimum price of a product in the 'home goods' category?
CREATE TABLE products (product_id INT,category VARCHAR(20),price DECIMAL(5,2)); INSERT INTO products (product_id,category,price) VALUES (1,'home goods',35.99),(2,'home goods',45.00),(3,'home goods',29.99);
SELECT MIN(price) FROM products WHERE category = 'home goods';
List the number of mobile and broadband subscribers in each region for the second quarter.
CREATE TABLE mobile_subscribers (subscriber_id INT,region_id INT,join_date DATE); INSERT INTO mobile_subscribers (subscriber_id,region_id,join_date) VALUES (1,1,'2021-04-01'),(2,2,'2021-06-01'),(3,3,'2021-05-01'),(4,4,'2021-04-15'); CREATE TABLE broadband_subscribers (subscriber_id INT,region_id INT,join_date DATE); INSERT INTO broadband_subscribers (subscriber_id,region_id,join_date) VALUES (5,1,'2021-04-15'),(6,2,'2021-06-15'),(7,3,'2021-05-15'),(8,4,'2021-04-20');
SELECT r.region_name, COUNT(m.subscriber_id) AS mobile_count, COUNT(b.subscriber_id) AS broadband_count FROM regions r LEFT JOIN mobile_subscribers m ON r.region_id = m.region_id LEFT JOIN broadband_subscribers b ON r.region_id = b.region_id WHERE QUARTER(m.join_date) = 2 AND YEAR(m.join_date) = 2021 GROUP BY r.region_id;
How many bioprocess engineering projects were completed in Q3 2019?
CREATE TABLE projects (id INT,name VARCHAR(255),start_date DATE,end_date DATE); INSERT INTO projects (id,name,start_date,end_date) VALUES (1,'ProjectA','2019-06-01','2019-09-30'); INSERT INTO projects (id,name,start_date,end_date) VALUES (2,'ProjectB','2019-10-01','2019-12-31');
SELECT COUNT(*) FROM projects WHERE start_date <= '2019-09-30' AND end_date >= '2019-07-01';
List athletes who have never missed a game due to injury.
CREATE TABLE athlete_games (athlete_id INT,game_date DATE,played BOOLEAN);
SELECT athlete_id FROM athlete_games WHERE NOT EXISTS (SELECT 1 FROM athlete_games WHERE athlete_id = athlete_games.athlete_id AND played = FALSE);
What is the average depth of marine protected areas, partitioned by conservation status?
CREATE TABLE marine_protected_areas (name VARCHAR(255),depth FLOAT,status VARCHAR(255)); INSERT INTO marine_protected_areas (name,depth,status) VALUES ('Area1',123.4,'Conserved'),('Area2',234.5,'Threatened');
SELECT status, AVG(depth) as avg_depth FROM marine_protected_areas GROUP BY status;
What is the total area of 'Tropical Forests' under sustainable management?
CREATE TABLE TropicalForests (region VARCHAR(20),area FLOAT,management_status VARCHAR(10)); INSERT INTO TropicalForests (region,area,management_status) VALUES ('Tropical Forests',12345.67,'sustainable'),('Tropical Forests',8765.43,'unsustainable');
SELECT SUM(area) FROM TropicalForests WHERE region = 'Tropical Forests' AND management_status = 'sustainable';
Insert a new painting 'The Starry Night Over the Rhone' by 'Vincent van Gogh' in 1888.
CREATE TABLE Artists (ArtistID INT,Name VARCHAR(50),Nationality VARCHAR(50)); INSERT INTO Artists (ArtistID,Name,Nationality) VALUES (1,'Vincent van Gogh','Dutch'); CREATE TABLE Paintings (PaintingID INT,Title VARCHAR(50),ArtistID INT,YearCreated INT);
INSERT INTO Paintings (PaintingID, Title, ArtistID, YearCreated) VALUES (3, 'The Starry Night Over the Rhone', 1, 1888);
What is the child immunization rate in Asia?
CREATE TABLE Immunization (Region TEXT,ChildImmunizationRate FLOAT); INSERT INTO Immunization VALUES ('Asia',85);
SELECT ChildImmunizationRate FROM Immunization WHERE Region = 'Asia';
What is the average billing amount per case for cases with a favorable outcome?
CREATE TABLE cases (case_id INT,state VARCHAR(2),billing_amount DECIMAL(10,2),outcome VARCHAR(10)); INSERT INTO cases (case_id,state,billing_amount,outcome) VALUES (1,'CA',5000.00,'Favorable'),(2,'CA',7000.00,'Unfavorable'),(3,'NY',3000.00,'Favorable'),(4,'NY',4000.00,'Favorable'),(5,'TX',8000.00,'Unfavorable'),(6,'TX',9000.00,'Unfavorable');
SELECT AVG(billing_amount) FROM cases WHERE outcome = 'Favorable';
What is the average number of games played per day by players from 'Japan' in the 'Action' genre?
CREATE TABLE PlayerDailyGames (PlayerID INT,PlayDate DATE,GamesPlayed INT); INSERT INTO PlayerDailyGames (PlayerID,PlayDate,GamesPlayed) VALUES (1,'2021-04-01',3),(1,'2021-04-02',2),(2,'2021-04-01',1),(2,'2021-04-03',4),(3,'2021-04-02',5),(3,'2021-04-03',3); CREATE TABLE GameGenres (GameID INT,Genre VARCHAR(20)); INSERT INTO GameGenres (GameID,Genre) VALUES (1,'Role-playing'),(2,'Action'),(3,'Strategy'),(4,'Adventure'),(5,'Simulation'),(6,'Virtual Reality'); CREATE TABLE Players (PlayerID INT,Country VARCHAR(20)); INSERT INTO Players (PlayerID,Country) VALUES (1,'Canada'),(2,'Brazil'),(3,'Japan');
SELECT AVG(GamesPlayed) FROM PlayerDailyGames INNER JOIN (SELECT PlayerID FROM PlayerGameGenres INNER JOIN GameGenres ON PlayerGameGenres.GameGenre = GameGenres.Genre WHERE GameGenres.Genre = 'Action') AS ActionPlayers ON PlayerDailyGames.PlayerID = ActionPlayers.PlayerID INNER JOIN Players ON PlayerDailyGames.PlayerID = Players.PlayerID WHERE Players.Country = 'Japan';
Get the number of electric vehicle adoption records in each state in the USA
CREATE TABLE electric_vehicles (state VARCHAR(255),adoption_count INT); INSERT INTO electric_vehicles (state,adoption_count) VALUES ('California',500000); INSERT INTO electric_vehicles (state,adoption_count) VALUES ('Texas',350000); INSERT INTO electric_vehicles (state,adoption_count) VALUES ('Florida',400000);
SELECT state, adoption_count, ROW_NUMBER() OVER (ORDER BY adoption_count DESC) AS rank FROM electric_vehicles;
What is the number of patients treated by gender?
CREATE TABLE Patients (PatientID int,Gender varchar(10)); INSERT INTO Patients (PatientID,Gender) VALUES (1,'Male'),(2,'Female');
SELECT Gender, COUNT(*) FROM Patients GROUP BY Gender;
Update the capacity of the cargo ship named 'Sea Titan' to 175,000.
CREATE TABLE cargo_ships (id INT,name VARCHAR(50),capacity INT,owner_id INT); INSERT INTO cargo_ships (id,name,capacity,owner_id) VALUES (1,'Sea Titan',150000,1),(2,'Ocean Marvel',200000,1),(3,'Cargo Master',120000,2);
UPDATE cargo_ships SET capacity = 175000 WHERE name = 'Sea Titan';
What is the engagement rate (likes + comments) for posts in the music category?
CREATE TABLE post_stats (post_id INT,category VARCHAR(50),likes INT,comments INT); INSERT INTO post_stats (post_id,category,likes,comments) VALUES (1,'fashion',100,25),(2,'fashion',200,50),(3,'beauty',150,75),(4,'music',100,50);
SELECT post_id, (likes + comments) AS engagement_rate FROM post_stats WHERE category = 'music';