instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
What is the total amount of socially responsible loans issued in Texas?
CREATE TABLE employees (id INT,name TEXT,city TEXT,salary INT); INSERT INTO employees (id,name,city,salary) VALUES (1,'Fatima','Texas',60000); CREATE TABLE loans (id INT,employee_id INT,amount INT,is_shariah_compliant BOOLEAN,loan_type TEXT); INSERT INTO loans (id,employee_id,amount,is_shariah_compliant,loan_type) VALUES (1,1,30000,FALSE,'Socially responsible'),(2,1,20000,TRUE,'Shariah-compliant');
SELECT SUM(loans.amount) FROM loans JOIN employees ON loans.employee_id = employees.id WHERE employees.city = 'Texas' AND loans.loan_type = 'Socially responsible';
What is the minimum trip duration for all trips on the Tokyo metro in the past month?
CREATE TABLE tokyo_metro (trip_id INT,start_time TIMESTAMP,end_time TIMESTAMP,trip_date DATE);
SELECT MIN(end_time - start_time) AS min_duration FROM tokyo_metro WHERE trip_date >= DATE_SUB(NOW(), INTERVAL 1 MONTH);
Delete fairness AI trainings before '2021-08-01'
CREATE TABLE fairness_trainings (id INT,model_id INT,dataset_id INT,start_date DATETIME,end_date DATETIME); INSERT INTO fairness_trainings (id,model_id,dataset_id,start_date,end_date) VALUES (1,1,2,'2021-07-15 10:00:00','2021-07-20 15:00:00');
DELETE FROM fairness_trainings WHERE start_date < '2021-08-01 00:00:00';
Show the total number of vehicles in 'Tokyo', 'Delhi', and 'Sao Paulo'
CREATE TABLE public.vehicles (id INT,type VARCHAR(20),city VARCHAR(20)); INSERT INTO public.vehicles (id,type,city) VALUES (1,'electric_car','Tokyo'),(2,'conventional_car','Tokyo'),(3,'autonomous_bus','Delhi'),(4,'conventional_car','Delhi'),(5,'electric_bus','Sao Paulo'),(6,'conventional_bus','Sao Paulo');
SELECT SUM(cnt) FROM (SELECT city, COUNT(*) AS cnt FROM public.vehicles WHERE city IN ('Tokyo', 'Delhi', 'Sao Paulo') GROUP BY city) AS subquery;
Which country had the highest cosmetics sales revenue in Q2 2022?
CREATE TABLE cosmetics_sales (country VARCHAR(50),revenue FLOAT,quarter INT,year INT); INSERT INTO cosmetics_sales (country,revenue,quarter,year) VALUES ('United States',2500.50,2,2022),('Canada',1200.00,2,2022),('Mexico',1700.75,2,2022);
SELECT country, MAX(revenue) FROM cosmetics_sales WHERE quarter = 2 AND year = 2022 GROUP BY country;
What is the average billing amount for each attorney by case type?
CREATE TABLE cases (case_id INT,case_type VARCHAR(255)); INSERT INTO cases (case_id,case_type) VALUES (1,'Civil'),(2,'Criminal'); CREATE TABLE attorneys (attorney_id INT,attorney_name VARCHAR(255)); INSERT INTO attorneys (attorney_id,attorney_name) VALUES (1,'John Smith'),(2,'Jane Doe'); CREATE TABLE billing (bill_id INT,case_id INT,attorney_id INT,amount DECIMAL(10,2)); INSERT INTO billing (bill_id,case_id,attorney_id,amount) VALUES (1,1,1,500.00),(2,1,2,250.00),(3,2,1,750.00);
SELECT a.attorney_name, c.case_type, AVG(b.amount) as avg_billing FROM cases c INNER JOIN attorneys a ON c.attorney_id = a.attorney_id INNER JOIN billing b ON c.case_id = b.case_id AND a.attorney_id = b.attorney_id GROUP BY a.attorney_name, c.case_type;
What is the number of teachers who have attended at least 5 professional development workshops in each subject area?
CREATE TABLE teacher_training_subject (teacher_id INT,teacher_name TEXT,subject TEXT,num_workshops INT);
SELECT subject, COUNT(*) as num_teachers FROM teacher_training_subject WHERE num_workshops >= 5 GROUP BY subject;
What was the maximum weight of shipments from Japan to the United Kingdom in a single day in March 2021?
CREATE TABLE shipments (id INT,weight FLOAT,origin VARCHAR(255),destination VARCHAR(255),shipped_at TIMESTAMP); INSERT INTO shipments (id,weight,origin,destination,shipped_at) VALUES (1,300.0,'Japan','United Kingdom','2021-03-02 14:30:00'),(2,500.0,'Japan','United Kingdom','2021-03-05 09:00:00');
SELECT MAX(weight) FROM shipments WHERE origin = 'Japan' AND destination = 'United Kingdom' AND shipped_at >= '2021-03-01' AND shipped_at < '2021-03-02' GROUP BY DATE(shipped_at);
What is the total number of vessels that transported hazardous materials and their average speed?
CREATE TABLE Vessels (VesselID int,Name varchar(50),Type varchar(50),AverageSpeed float); CREATE TABLE Cargo (CargoID int,VesselID int,MaterialType varchar(50),Tonnage int,TransportDate date); INSERT INTO Vessels VALUES (1,'Vessel1','Transport',15); INSERT INTO Cargo VALUES (1,1,'Hazardous',100,'2022-01-01');
SELECT COUNT(DISTINCT V.VesselID) AS TotalVessels, AVG(V.AverageSpeed) AS AverageSpeed FROM Vessels V INNER JOIN Cargo C ON V.VesselID = C.VesselID WHERE C.MaterialType = 'Hazardous';
Find the top 3 favorite sports among fans, by ticket sales.
CREATE TABLE fan_demographics (fan_id INT,favorite_sport VARCHAR(20)); CREATE TABLE ticket_sales (ticket_id INT,fan_id INT,sport VARCHAR(20),sales INT);
SELECT sport, SUM(sales) as total_sales FROM ticket_sales td JOIN fan_demographics fd ON td.fan_id = fd.fan_id GROUP BY sport ORDER BY total_sales DESC LIMIT 3;
What is the average number of views for articles published in 'africa' region?
CREATE TABLE views_by_region (id INT,article_id INT,region VARCHAR(30),views INT); INSERT INTO views_by_region (id,article_id,region,views) VALUES (1,1,'africa',100),(2,2,'africa',200),(3,3,'africa',300),(4,4,'africa',400);
SELECT AVG(views) FROM views_by_region WHERE region = 'africa';
How many circular economy initiatives were implemented in Berlin in 2019?
CREATE TABLE circular_economy_initiatives_berlin (year INT,num_initiatives INT); INSERT INTO circular_economy_initiatives_berlin (year,num_initiatives) VALUES (2018,75),(2019,90),(2020,105),(2021,120);
SELECT num_initiatives FROM circular_economy_initiatives_berlin WHERE year = 2019;
What is the maximum production quantity (in metric tons) of Terbium by companies from Africa in 2020?
CREATE TABLE terbium_production (year INT,company_name TEXT,location TEXT,quantity INT); INSERT INTO terbium_production (year,company_name,location,quantity) VALUES (2020,'VWX Mining','South Africa',700),(2020,'YZA Mining','Morocco',800),(2020,'BCE Mining','Egypt',900);
SELECT MAX(quantity) as max_quantity FROM terbium_production WHERE year = 2020 AND location LIKE 'Africa%';
What is the maximum number of days taken to resolve a critical vulnerability in the government sector?
CREATE TABLE vulnerability_resolution (id INT,severity VARCHAR(255),sector VARCHAR(255),resolution_date DATE,detection_date DATE); INSERT INTO vulnerability_resolution (id,severity,sector,resolution_date,detection_date) VALUES (1,'critical','government','2021-03-01','2021-01-15');
SELECT MAX(DATEDIFF(resolution_date, detection_date)) FROM vulnerability_resolution WHERE severity = 'critical' AND sector = 'government';
What is the maximum and minimum water temperature in the farms located in the Arctic region?
CREATE TABLE temp_data (farm_id INT,location VARCHAR(20),temp FLOAT); INSERT INTO temp_data (farm_id,location,temp) VALUES (1,'Arctic region',5.5),(2,'Arctic region',4.8),(3,'Arctic region',6.1);
SELECT MAX(temp), MIN(temp) FROM temp_data WHERE location = 'Arctic region';
What is the total number of Freedom of Information Act requests submitted to the Department of Health and Human Services by residents of California in the year 2020?
CREATE TABLE foia_requests(request_id INT,requester_state VARCHAR(255),agency VARCHAR(255),year INT); INSERT INTO foia_requests(request_id,requester_state,agency,year) VALUES (1,'California','Department of Health and Human Services',2020);
SELECT COUNT(*) FROM foia_requests WHERE agency = 'Department of Health and Human Services' AND requester_state = 'California' AND year = 2020;
How many vessels have been inspected in each port in the Mediterranean in the last year?
CREATE TABLE VesselInspections (InspectionID INT,VesselID INT,InspectionDate DATE,Port VARCHAR(20)); INSERT INTO VesselInspections (InspectionID,VesselID,InspectionDate,Port) VALUES (1,1,'2021-02-15','Barcelona'),(2,2,'2021-03-20','Naples'),(3,3,'2021-04-05','Barcelona');
SELECT Port, COUNT(DISTINCT VesselID) FROM VesselInspections WHERE InspectionDate >= DATEADD(year, -1, GETDATE()) GROUP BY Port;
What are the average annual visitor numbers for cultural heritage sites in Japan?
CREATE TABLE Sites (site_id INT,site_name TEXT,country TEXT,annual_visitors INT); INSERT INTO Sites (site_id,site_name,country,annual_visitors) VALUES (1,'Temple of Heaven','Japan',1200000); INSERT INTO Sites (site_id,site_name,country,annual_visitors) VALUES (2,'Mount Fuji','Japan',2000000);
SELECT AVG(annual_visitors) FROM Sites WHERE country = 'Japan' AND site_name LIKE '%cultural%' OR site_name LIKE '%heritage%';
What is the total number of joint military exercises conducted by African and Asian nations in the past 2 years?
CREATE TABLE military_exercises(country1 VARCHAR(50),country2 VARCHAR(50),year INT,exercise VARCHAR(255)); INSERT INTO military_exercises(country1,country2,year,exercise) VALUES('Egypt','India',2021,'Joint military exercise'),('Algeria','China',2020,'Military drills'),('Nigeria','Japan',2019,'Joint naval exercise'),('South Africa','South Korea',2021,'Military training'),('Morocco','Singapore',2020,'Joint military exercise');
SELECT country1, country2, exercise FROM military_exercises WHERE (country1 IN ('Egypt', 'Algeria', 'Nigeria', 'South Africa', 'Morocco') AND country2 IN ('India', 'China', 'Japan', 'South Korea', 'Singapore')) OR (country1 IN ('India', 'China', 'Japan', 'South Korea', 'Singapore') AND country2 IN ('Egypt', 'Algeria', 'Nigeria', 'South Africa', 'Morocco')) AND year BETWEEN 2019 AND 2021;
Which drugs were approved between 2018 and 2020 and what is their approval status?
CREATE TABLE drug_approval (drug VARCHAR(255),approval_date DATE,company VARCHAR(255),approval_status VARCHAR(255)); INSERT INTO drug_approval (drug,approval_date,company,approval_status) VALUES ('Skyrizi','2019-04-23','AbbVie','Approved');
SELECT drug, approval_status FROM drug_approval WHERE approval_date BETWEEN '2018-01-01' AND '2020-12-31' AND approval_status = 'Approved';
Which countries in the 'museums' table have the highest and lowest number of museums?
CREATE TABLE museums (museum_id INT,name VARCHAR(50),country VARCHAR(50),num_exhibits INT); INSERT INTO museums (museum_id,name,country,num_exhibits) VALUES (1,'MoMA','USA',50); INSERT INTO museums (museum_id,name,country,num_exhibits) VALUES (2,'Tate Modern','UK',75); INSERT INTO museums (museum_id,name,country,num_exhibits) VALUES (3,'Louvre','France',80);
SELECT country, MIN(num_exhibits) as min_exhibits, MAX(num_exhibits) as max_exhibits FROM museums GROUP BY country;
Find the top 5 regions with the highest average monthly data usage for postpaid mobile subscribers, for each subscription type, in the past 6 months?
CREATE TABLE subscribers (subscriber_id INT,subscription_type VARCHAR(10),data_usage FLOAT,region VARCHAR(20),usage_date DATE); INSERT INTO subscribers (subscriber_id,subscription_type,data_usage,region,usage_date) VALUES (1,'postpaid',3.5,'North','2022-01-01'),(2,'postpaid',4.2,'South','2022-02-01'),(3,'postpaid',3.8,'North','2022-03-01');
SELECT subscription_type, region, AVG(data_usage) as avg_data_usage FROM subscribers WHERE subscription_type = 'postpaid' AND usage_date >= DATE_SUB(CURRENT_DATE, INTERVAL 6 MONTH) GROUP BY subscription_type, region ORDER BY subscription_type, avg_data_usage DESC LIMIT 5;
What is the maximum price per gram for hybrid strains?
CREATE TABLE Strains (strain_id INT,strain_type TEXT,thc_percentage DECIMAL(4,2),price_per_gram DECIMAL(5,2));
SELECT MAX(price_per_gram) FROM Strains WHERE strain_type = 'hybrid';
Show the number of vessels that visited each port
CREATE TABLE ports (port_id INT,port_name VARCHAR(50)); INSERT INTO ports (port_id,port_name) VALUES (1,'LA'),(2,'NY'); CREATE TABLE vessels (vessel_id INT,vessel_name VARCHAR(50)); INSERT INTO vessels (vessel_id,vessel_name) VALUES (1,'Vessel1'),(2,'Vessel2'),(3,'Vessel3'); CREATE TABLE port_visits (visit_id INT,vessel_id INT,port_id INT); INSERT INTO port_visits (visit_id,vessel_id,port_id) VALUES (1,1,1),(2,2,2),(3,3,1),(4,1,2);
SELECT p.port_name, COUNT(pv.vessel_id) FROM ports p JOIN port_visits pv ON p.port_id = pv.port_id GROUP BY p.port_name;
Update the ticket price for VIP tickets at upcoming basketball games to $250.
CREATE TABLE TicketSales (id INT,event_type VARCHAR(255),location VARCHAR(255),tickets_sold INT,price DECIMAL(5,2),ticket_type VARCHAR(50),date DATE); INSERT INTO TicketSales (id,event_type,location,tickets_sold,price,ticket_type,date) VALUES (1,'Concert','Indoor Arena',1500,150,'VIP','2021-11-01'),(2,'Sports Game','Outdoor Stadium',8000,50,'General Admission','2021-10-15'),(3,'Concert','Indoor Arena',2000,200,'VIP','2021-12-10'),(4,'Basketball Game','Indoor Arena',500,200,'VIP','2022-03-20'),(5,'Soccer Game','Outdoor Stadium',10000,75,'General Admission','2022-06-01');
UPDATE TicketSales SET price = 250 WHERE event_type = 'Basketball Game' AND ticket_type = 'VIP';
What is the maximum weight of containers shipped from the Port of Shanghai to the US in 2021?
CREATE TABLE ports (port_id INT,port_name TEXT,country TEXT);CREATE TABLE shipments (shipment_id INT,shipment_weight INT,ship_date DATE,port_id INT); INSERT INTO ports VALUES (1,'Port of Shanghai','China'),(2,'Port of Los Angeles','USA'); INSERT INTO shipments VALUES (1,2000,'2021-01-01',1),(2,1500,'2021-02-15',2);
SELECT MAX(shipment_weight) FROM shipments JOIN ports ON shipments.port_id = ports.port_id WHERE ports.country = 'USA' AND ports.port_name = 'Port of Los Angeles' AND ship_date BETWEEN '2021-01-01' AND '2021-12-31';
What is the name of the city with the most art exhibitions?
CREATE TABLE Exhibitions (name VARCHAR(255),city VARCHAR(255),date DATE); INSERT INTO Exhibitions (name,city,date) VALUES ('Modern Art','New York','2023-03-01'),('Contemporary Art','Los Angeles','2023-04-01'),('Classic Art','New York','2023-02-01'),('Impressionism','Paris','2023-05-01');
SELECT city FROM Exhibitions GROUP BY city HAVING COUNT(*) = (SELECT MAX(count) FROM (SELECT city, COUNT(*) as count FROM Exhibitions GROUP BY city) as subquery);
What is the total amount of Shariah-compliant finance transactions conducted by each customer in each quarter?
CREATE TABLE transactions (transaction_date DATE,transaction_amount DECIMAL(10,2),customer_id INT);
SELECT customer_id, QUARTER(transaction_date) AS quarter, SUM(transaction_amount) FROM transactions WHERE transaction_date >= '2022-01-01' AND transaction_type = 'Shariah-compliant' GROUP BY customer_id, quarter;
List all threat actors that have targeted systems in the healthcare sector in the past year.
CREATE TABLE threat_actors (threat_actor_id INT,threat_actor_name VARCHAR(255));CREATE TABLE targeted_systems (system_id INT,system_name VARCHAR(255),sector VARCHAR(255),threat_actor_id INT);CREATE TABLE scan_dates (scan_date DATE,system_id INT);
SELECT ta.threat_actor_name FROM threat_actors ta INNER JOIN targeted_systems ts ON ta.threat_actor_id = ts.threat_actor_id INNER JOIN scan_dates sd ON ts.system_id = sd.system_id WHERE ts.sector = 'healthcare' AND sd.scan_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR);
What is the number of orders that were shipped using carbon-neutral methods in the ethical fashion marketplace?
CREATE TABLE shipments (shipment_id INT,carbon_neutral BOOLEAN); INSERT INTO shipments (shipment_id,carbon_neutral) VALUES (1,true),(2,false),(3,true);
SELECT COUNT(*) FROM shipments WHERE carbon_neutral = true;
What is the average emergency response time for each neighborhood?
CREATE TABLE Neighborhoods (NeighborhoodID INT,Name VARCHAR(50)); CREATE TABLE EmergencyResponses (ResponseID INT,NeighborhoodID INT,ResponseTime INT);
SELECT N.Name, AVG(E.ResponseTime) as AvgResponseTime FROM Neighborhoods N INNER JOIN EmergencyResponses E ON N.NeighborhoodID = E.NeighborhoodID GROUP BY N.Name;
Find the top 10 destinations with the highest average delivery time in Asia?
CREATE TABLE Routes (id INT,origin_city VARCHAR(255),destination_city VARCHAR(255),distance INT,etd DATE,eta DATE);
SELECT destination_city, AVG(DATEDIFF(day, etd, eta)) AS avg_delay FROM Routes WHERE origin_city IN (SELECT city FROM Warehouse WHERE country = 'Asia') GROUP BY destination_city ORDER BY avg_delay DESC LIMIT 10;
What is the total number of donations and investments for each individual in the 'individuals' table, ordered by the total number of contributions in descending order?
CREATE TABLE individuals (individual_id INT,individual_name TEXT,num_donations INT,num_investments INT);
SELECT individual_name, COUNT(num_donations) + COUNT(num_investments) as total_contributions FROM individuals GROUP BY individual_name ORDER BY total_contributions DESC;
How many IoT sensors are currently active in US-based soybean farms?
CREATE TABLE farm_sensors (sensor_id INT,sensor_type TEXT,is_active BOOLEAN,farm_id INT); INSERT INTO farm_sensors (sensor_id,sensor_type,is_active,farm_id) VALUES (1001,'Soil Moisture',true,101),(1002,'Temperature',false,101),(1003,'Humidity',true,102); CREATE TABLE farms (farm_id INT,name TEXT,country TEXT,crop TEXT); INSERT INTO farms (farm_id,name,country,crop) VALUES (101,'Farm 1','USA','Soybean'),(102,'Farm 2','Canada','Barley');
SELECT COUNT(*) FROM farm_sensors JOIN farms ON farm_sensors.farm_id = farms.farm_id WHERE farms.crop = 'Soybean' AND farm_sensors.is_active = true;
Who are the top 5 users who have the most comments?
CREATE TABLE users (user_id INT,name TEXT,comment_count INT);
SELECT name FROM users ORDER BY comment_count DESC LIMIT 5;
Update the TotalVisitors column in the ExhibitionAnalytics table for the 'Classic Art' exhibition to 500.
CREATE TABLE ExhibitionAnalytics (ExhibitionID INT,ExhibitionName VARCHAR(50),TotalVisitors INT,TotalEngagement INT);
UPDATE ExhibitionAnalytics SET TotalVisitors = 500 WHERE ExhibitionName = 'Classic Art';
What are the total mineral extraction quantities for each country in 2020, sorted by quantity in descending order?
CREATE TABLE MineralExtraction (country VARCHAR(50),year INT,mineral VARCHAR(50),quantity INT); INSERT INTO MineralExtraction (country,year,mineral,quantity) VALUES ('Canada',2020,'Gold',120),('Mexico',2020,'Silver',150),('Brazil',2020,'Iron',200);
SELECT context.country, SUM(context.quantity) as total_quantity FROM context WHERE context.year = 2020 GROUP BY context.country ORDER BY total_quantity DESC;
Find the number of smart contracts that have been created for each regulatory framework in the last 30 days?
CREATE TABLE smart_contracts (sc_id INT,rf_id INT,creation_date DATE); CREATE TABLE regulatory_frameworks (rf_id INT,name VARCHAR(255));
SELECT rf_id, name, COUNT(sc_id) OVER (PARTITION BY rf_id) as num_smart_contracts FROM smart_contracts sc JOIN regulatory_frameworks rf ON sc.rf_id = rf.rf_id WHERE creation_date >= DATEADD(day, -30, CURRENT_DATE);
What was the total cost of all infrastructure projects in the agriculture domain in 2020, grouped by project type?
CREATE TABLE infrastructure_projects (id INT,project_name VARCHAR(100),project_type VARCHAR(50),project_domain VARCHAR(50),start_date DATE,end_date DATE,total_cost FLOAT);
SELECT project_type, SUM(total_cost) FROM infrastructure_projects WHERE project_domain = 'agriculture' AND YEAR(start_date) = 2020 GROUP BY project_type;
Insert data into the 'crops' table
CREATE TABLE crops (crop_id INT PRIMARY KEY,name VARCHAR(255),yield INT);
INSERT INTO crops (crop_id, name, yield) VALUES (1, 'Corn', 120), (2, 'Soybeans', 40);
What is the average age of coaches in the NFL?
CREATE TABLE coaches (id INT,name VARCHAR(50),age INT,sport VARCHAR(50),team VARCHAR(50)); INSERT INTO coaches (id,name,age,sport,team) VALUES (1,'John Doe',55,'NFL','Giants'); INSERT INTO coaches (id,name,age,sport,team) VALUES (2,'Jane Smith',42,'NFL','Lions');
SELECT AVG(age) FROM coaches WHERE sport = 'NFL' AND position = 'Coach';
Which animal species has the highest population in the 'animal_population' table?
CREATE TABLE animal_population (animal_id INT,animal_name VARCHAR(50),population INT); INSERT INTO animal_population (animal_id,animal_name,population) VALUES (1,'Tiger',2000),(2,'Elephant',5000),(3,'Lion',3000);
SELECT animal_name, MAX(population) FROM animal_population GROUP BY animal_name;
Get the count of policies, total claim amounts, and average claim amounts for policies in 'New York'
CREATE TABLE policies (policy_number INT,policyholder_state VARCHAR(20));CREATE TABLE claims (claim_id INT,policy_number INT,claim_amount DECIMAL(10,2),claim_date DATE);
SELECT p.policyholder_state, COUNT(DISTINCT p.policy_number) AS policy_count, SUM(c.claim_amount) AS total_claim_amount, AVG(c.claim_amount) AS avg_claim_amount FROM policies p INNER JOIN claims c ON p.policy_number = c.policy_number WHERE p.policyholder_state = 'New York' GROUP BY p.policyholder_state;
List genetic research projects with more than 10 participants.
CREATE TABLE research_projects (id INT,name VARCHAR(50),lead_researcher VARCHAR(50),participants INT,start_date DATE,end_date DATE);
SELECT name FROM research_projects WHERE participants > 10;
What was the total revenue for each dispensary in Colorado in Q4 2022?
CREATE TABLE Dispensaries (id INT,name TEXT,state TEXT); INSERT INTO Dispensaries (id,name,state) VALUES (1,'Dispensary A','Colorado'),(2,'Dispensary B','Colorado'); CREATE TABLE Sales (id INT,dispensary_id INT,revenue INT,sale_date DATE); INSERT INTO Sales (id,dispensary_id,revenue,sale_date) VALUES (1,1,200,'2022-10-01'),(2,1,250,'2022-10-02'),(3,2,150,'2022-10-01'),(4,2,250,'2022-10-02'),(5,1,300,'2022-11-01'),(6,1,350,'2022-11-02'),(7,2,200,'2022-11-01'),(8,2,250,'2022-11-02'),(9,1,400,'2022-12-01'),(10,1,450,'2022-12-02'),(11,2,300,'2022-12-01'),(12,2,350,'2022-12-02');
SELECT d.name, SUM(s.revenue) AS total_revenue FROM Dispensaries d INNER JOIN Sales s ON d.id = s.dispensary_id WHERE s.sale_date BETWEEN '2022-10-01' AND '2022-12-31' GROUP BY d.name;
Delete all records with accommodation type "audio_aids" from the "accommodations" table
CREATE TABLE accommodations (id INT,student_id INT,accommodation_type VARCHAR(255),cost FLOAT); INSERT INTO accommodations (id,student_id,accommodation_type,cost) VALUES (1,123,'visual_aids',250.0),(2,456,'audio_aids',100.0),(3,789,'large_print_materials',120.0);
DELETE FROM accommodations WHERE accommodation_type = 'audio_aids';
Which countries have the highest and lowest technology accessibility scores?
CREATE TABLE Country_Accessibility (country VARCHAR(255),score INT); INSERT INTO Country_Accessibility (country,score) VALUES ('USA',85),('Canada',80),('Mexico',70),('Brazil',65),('Argentina',75);
SELECT country, score FROM Country_Accessibility ORDER BY score DESC LIMIT 1; SELECT country, score FROM Country_Accessibility ORDER BY score ASC LIMIT 1;
What is the total number of emergency incidents reported by different districts in 2021, ordered from highest to lowest?
CREATE TABLE Districts (id INT,district_name VARCHAR(255)); CREATE TABLE EmergencyIncidents (id INT,district_id INT,incident_date DATE); INSERT INTO Districts (id,district_name) VALUES (1,'Downtown'),(2,'Uptown'),(3,'Harbor'),(4,'Parkside'); INSERT INTO EmergencyIncidents (id,district_id,incident_date) VALUES (1,1,'2021-01-01'),(2,2,'2021-01-05'),(3,3,'2021-01-03'),(4,4,'2021-01-04');
SELECT district_id, COUNT(*) as total_incidents FROM EmergencyIncidents WHERE incident_date BETWEEN '2021-01-01' AND '2021-12-31' GROUP BY district_id ORDER BY total_incidents DESC;
Decrease the value of military equipment sales by 5% for 'Middle East' in 2021
CREATE TABLE military_sales_6 (id INT,region VARCHAR,year INT,value FLOAT);
UPDATE military_sales_6 SET value = value * 0.95 WHERE region = 'Middle East' AND year = 2021;
Show the total number of rural infrastructure projects and economic diversification efforts in the 'rural_development' schema, excluding any duplicate project names.
CREATE SCHEMA rural_development; Use rural_development; CREATE TABLE infra_diversification (project_name VARCHAR(50)); INSERT INTO infra_diversification (project_name) VALUES ('Project A'),('Project B'),('Project A'),('Project C');
SELECT COUNT(DISTINCT project_name) FROM rural_development.infra_diversification;
Which country has the highest organic farming area in the region 'Europe'?
CREATE TABLE organic_farms (id INT,country VARCHAR(50),region VARCHAR(50),area_ha FLOAT); INSERT INTO organic_farms (id,country,region,area_ha) VALUES (1,'France','Europe',23456.7); INSERT INTO organic_farms (id,country,region,area_ha) VALUES (2,'Spain','Europe',15646.8); INSERT INTO organic_farms (id,country,region,area_ha) VALUES (3,'Italy','Europe',27890.1);
SELECT country, MAX(area_ha) FROM organic_farms WHERE region = 'Europe';
What are the total renewable energy generation stats for South America?
CREATE TABLE renewable_energy_generation (id INT,name VARCHAR(255),location VARCHAR(255),generation_mw INT);
SELECT SUM(generation_mw) FROM renewable_energy_generation WHERE location LIKE '%South America%';
What was the total spending on military innovation by Russia and India in 2019?
CREATE TABLE MilitaryExpenditure (Country VARCHAR(255),Year INT,Expenditure DECIMAL(10,2)); INSERT INTO MilitaryExpenditure (Country,Year,Expenditure) VALUES ('Russia',2019,65300000000),('India',2019,71000000000);
SELECT SUM(Expenditure) FROM MilitaryExpenditure WHERE Country IN ('Russia', 'India') AND Year = 2019;
What is the number of co-owned properties in each city?
CREATE TABLE co_owned_properties (id INT,city VARCHAR(20)); INSERT INTO co_owned_properties (id,city) VALUES (1,'Seattle'),(2,'Portland'),(3,'Seattle'),(4,'Portland');
SELECT city, COUNT(*) OVER (PARTITION BY city) FROM co_owned_properties;
Retrieve the number of bridges and total length (in meters) of each bridge from the 'bridges' and 'bridge_lengths' tables.
CREATE TABLE bridges (id INT,name VARCHAR(255),location VARCHAR(255)); CREATE TABLE bridge_lengths (bridge_id INT,length DECIMAL(10,2));
SELECT b.name, COUNT(b.id) as number_of_bridges, SUM(bl.length) as total_length FROM bridges b INNER JOIN bridge_lengths bl ON b.id = bl.bridge_id GROUP BY b.id;
Insert a new record into the 'rural_hospital' table with the name 'New Hospital' and address '101 Maple St'.
CREATE TABLE rural_hospital (id INT,name VARCHAR(50),address VARCHAR(100));
INSERT INTO rural_hospital (name, address) VALUES ('New Hospital', '101 Maple St');
What is the average financial wellbeing score for each age group?
CREATE TABLE age_groups (age_group_id INT,age_from INT,age_to INT,avg_income FLOAT);CREATE TABLE financial_wellbeing (person_id INT,age_group_id INT,score INT);
SELECT ag.age_group_id, AVG(fw.score) as avg_score FROM age_groups ag INNER JOIN financial_wellbeing fw ON ag.age_group_id = fw.age_group_id GROUP BY ag.age_group_id;
Delete records from the 'game_events' table where the event_type is 'level_up' and the player_level is less than 5
CREATE TABLE game_events (event_id INT,player_id INT,event_type TEXT,player_level INT); INSERT INTO game_events (event_id,player_id,event_type,player_level) VALUES (1,1,'level_up',3),(2,2,'level_up',7),(3,3,'level_up',2);
WITH low_level_ups AS (DELETE FROM game_events WHERE event_type = 'level_up' AND player_level < 5 RETURNING *) SELECT * FROM low_level_ups;
List the names of healthcare providers in Michigan and Illinois that offer both primary care and mental health services.
CREATE TABLE providers (id INT,name TEXT,service TEXT,location TEXT); INSERT INTO providers (id,name,service,location) VALUES (1,'Healthcare One','Primary Care','Michigan'); INSERT INTO providers (id,name,service,location) VALUES (2,'Care Central','Mental Health','Illinois'); INSERT INTO providers (id,name,service,location) VALUES (3,'Provider Plus','Primary Care','Illinois'); INSERT INTO providers (id,name,service,location) VALUES (4,'Community Care','Mental Health','Michigan');
SELECT name FROM providers WHERE (service = 'Primary Care' AND location = 'Michigan') OR (service = 'Mental Health' AND location = 'Illinois')
How many 'ferry' vehicles were serviced in May 2022?
CREATE TABLE public.vehicle (vehicle_id SERIAL PRIMARY KEY,vehicle_type VARCHAR(20),station_id INTEGER,FOREIGN KEY (station_id) REFERENCES public.station(station_id)); INSERT INTO public.vehicle (vehicle_type,station_id) VALUES ('ferry',1),('ferry',2); CREATE TABLE public.service (service_id SERIAL PRIMARY KEY,service_type VARCHAR(20),service_date DATE,vehicle_id INTEGER,FOREIGN KEY (vehicle_id) REFERENCES public.vehicle(vehicle_id)); INSERT INTO public.service (service_type,service_date,vehicle_id) VALUES ('routine maintenance','2022-05-03',1),('repair','2022-05-15',2);
SELECT COUNT(*) FROM public.service INNER JOIN public.vehicle ON public.service.vehicle_id = public.vehicle.vehicle_id WHERE vehicle_type = 'ferry' AND service_date >= '2022-05-01' AND service_date <= '2022-05-31'
What is the average network infrastructure investment for the 'coastal' region in the last 5 years?
CREATE TABLE investments (id INT,region VARCHAR(10),year INT,amount INT); INSERT INTO investments (id,region,year,amount) VALUES (1,'coastal',2017,150000),(2,'coastal',2018,160000),(3,'coastal',2019,170000),(4,'rural',2017,80000),(5,'rural',2018,90000),(6,'rural',2019,100000);
SELECT region, AVG(amount) FROM investments WHERE region = 'coastal' GROUP BY region, year HAVING COUNT(*) > 4;
What is the average daily ridership for public transportation in urban areas?
CREATE TABLE public_transportation_urban (mode VARCHAR(20),daily_ridership INT); INSERT INTO public_transportation_urban (mode,daily_ridership) VALUES ('bus',10000),('train',20000),('light_rail',5000);
SELECT AVG(daily_ridership) FROM public_transportation_urban WHERE mode IN ('bus', 'train', 'light_rail');
What is the percentage of factories meeting the living wage standard by country?
CREATE TABLE Factories (id INT,name TEXT,country TEXT,living_wage_standard BOOLEAN); INSERT INTO Factories (id,name,country,living_wage_standard) VALUES (1,'Factory A','USA',true),(2,'Factory B','Mexico',false),(3,'Factory C','India',true),(4,'Factory D','Bangladesh',false),(5,'Factory E','China',true);
SELECT country, 100.0 * COUNT(*) FILTER (WHERE living_wage_standard) / COUNT(*) AS percentage FROM Factories GROUP BY country;
What is the total revenue generated by the 'Luxury' hotel category for the month of January 2022?
CREATE TABLE hotels (hotel_category VARCHAR(20),daily_revenue DECIMAL(10,2)); INSERT INTO hotels (hotel_category,daily_revenue) VALUES ('Economy',150.00),('Economy',160.00),('Luxury',500.00),('Luxury',550.00);
SELECT SUM(daily_revenue) FROM hotels WHERE hotel_category = 'Luxury' AND MONTH(order_date) = 1 AND YEAR(order_date) = 2022;
What's the average age of farmers who grow corn?
CREATE TABLE Farmers (id INT PRIMARY KEY,name VARCHAR(50),age INT,country VARCHAR(50)); INSERT INTO Farmers (id,name,age,country) VALUES (1,'John Doe',35,'USA'); INSERT INTO Farmers (id,name,age,country) VALUES (2,'Jane Smith',40,'Canada'); CREATE TABLE Crops (id INT PRIMARY KEY,name VARCHAR(50),growth_stage VARCHAR(50),farmer_id INT,FOREIGN KEY (farmer_id) REFERENCES Farmers(id)); INSERT INTO Crops (id,name,growth_stage,farmer_id) VALUES (1,'Corn','Germination',1); INSERT INTO Crops (id,name,growth_stage,farmer_id) VALUES (2,'Soybeans','Vegetative',2);
SELECT AVG(Farmers.age) FROM Farmers INNER JOIN Crops ON Farmers.id = Crops.farmer_id WHERE Crops.name = 'Corn';
How many professional development courses were completed by teachers in the "Parkside" school in 2020?
CREATE TABLE teachers (teacher_id INT,school VARCHAR(20),courses_completed INT,year INT); INSERT INTO teachers (teacher_id,school,courses_completed,year) VALUES (1,'Parkside',10,2020),(2,'Parkside',12,2020),(3,'Westside',8,2020);
SELECT SUM(courses_completed) FROM teachers WHERE school = 'Parkside' AND year = 2020;
List forests, their managed methods, and associated carbon sequestration.
CREATE TABLE Forests (ForestID INT PRIMARY KEY,Name VARCHAR(50),Country VARCHAR(50),Hectares FLOAT); CREATE TABLE Management (ManagementID INT PRIMARY KEY,Method VARCHAR(50),ForestID INT,FOREIGN KEY (ForestID) REFERENCES Forests(ForestID)); CREATE TABLE Harvest (HarvestID INT PRIMARY KEY,Volume FLOAT,ForestID INT,HarvestDate DATE,FOREIGN KEY (ForestID) REFERENCES Forests(ForestID)); CREATE TABLE Carbon (CarbonID INT PRIMARY KEY,Sequestration FLOAT,HarvestID INT,FOREIGN KEY (HarvestID) REFERENCES Harvest(HarvestID));
SELECT Forests.Name, Management.Method, Carbon.Sequestration FROM Forests INNER JOIN Management ON Forests.ForestID = Management.ForestID INNER JOIN Harvest ON Forests.ForestID = Harvest.ForestID INNER JOIN Carbon ON Harvest.HarvestID = Carbon.HarvestID;
What is the clinic capacity by clinic name, ordered within each province?
CREATE TABLE ClinicBeds (ProvinceName VARCHAR(50),ClinicName VARCHAR(50),NumBeds INT); INSERT INTO ClinicBeds (ProvinceName,ClinicName,NumBeds) VALUES ('Ontario','ClinicA',200),('Ontario','ClinicB',250),('Quebec','ClinicX',150),('British Columbia','ClinicY',200),('British Columbia','ClinicZ',175);
SELECT ProvinceName, ClinicName, NumBeds, RANK() OVER (PARTITION BY ProvinceName ORDER BY NumBeds DESC) AS Rank FROM ClinicBeds
What is the maximum ESG score for investments in the education sector, broken down by year?
CREATE TABLE investments (investment_id INT,sector VARCHAR(50),esg_score INT,investment_date DATE); INSERT INTO investments (investment_id,sector,esg_score,investment_date) VALUES (1,'Education',4,'2022-01-01'),(2,'Education',5,'2022-02-01'),(3,'Education',3,'2022-03-01'),(4,'Education',6,'2022-04-01'),(5,'Education',2,'2022-05-01'),(6,'Education',7,'2023-01-01'),(7,'Education',8,'2023-02-01'),(8,'Education',9,'2023-03-01'),(9,'Education',10,'2023-04-01'),(10,'Education',1,'2023-05-01');
SELECT EXTRACT(YEAR FROM investment_date) as year, MAX(esg_score) as max_esg_score FROM investments WHERE sector = 'Education' GROUP BY year ORDER BY year ASC;
List the names and budgets of all water supply projects.
CREATE TABLE projects (id INT,name VARCHAR(255),category VARCHAR(255),budget FLOAT); INSERT INTO projects (id,name,category,budget) VALUES (2,'Water Treatment Plant Upgrade','Water Supply',2000000.00);
SELECT name, budget FROM projects WHERE category = 'Water Supply';
Calculate the moving average of crop yield for each farmer over the last 2 years.
CREATE TABLE moving_averages (farmer_id INT,year INT,crop_yield INT); INSERT INTO moving_averages (farmer_id,year,crop_yield) VALUES (1,2020,600),(1,2021,550),(2,2020,500),(2,2021,520);
SELECT farmer_id, year, crop_yield, AVG(crop_yield) OVER (PARTITION BY farmer_id ORDER BY year ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) AS moving_average FROM moving_averages;
List all the exits that occurred in the gaming industry in 2020.
CREATE TABLE exits(id INT,company_name TEXT,industry TEXT,exit_year INT); INSERT INTO exits VALUES (1,'Gaming Co','Gaming',2020); INSERT INTO exits VALUES (2,'Tech Inc','Technology',2019);
SELECT company_name FROM exits WHERE industry = 'Gaming' AND exit_year = 2020;
What is the average weight of pottery artifacts from the 'Indus Valley Civilization' period, excavated in India?
CREATE TABLE artifacts (id serial PRIMARY KEY,type text,weight numeric,historical_period text,excavation_id integer); INSERT INTO artifacts (type,weight,historical_period,excavation_id) VALUES ('pottery',0.5,'Indus Valley Civilization',1),('metal',0.3,'Indus Valley Civilization',1),('pottery',0.4,'Indus Valley Civilization',2);
SELECT AVG(weight) as avg_weight FROM artifacts WHERE type = 'pottery' AND historical_period = 'Indus Valley Civilization' AND excavation_id IN (SELECT id FROM excavations WHERE location = 'India');
What is the distribution of mental health parity violations by month for the past two years?
CREATE TABLE MentalHealthParity (ViolationID INT,ViolationDate DATE); INSERT INTO MentalHealthParity (ViolationID,ViolationDate) VALUES (1,'2021-01-01'),(2,'2021-02-01'),(3,'2021-03-01'),(4,'2021-04-01'),(5,'2021-05-01'),(6,'2021-06-01'),(7,'2021-07-01'),(8,'2021-08-01'),(9,'2021-09-01'),(10,'2021-10-01'),(11,'2021-11-01'),(12,'2021-12-01'),(13,'2022-01-01'),(14,'2022-02-01'),(15,'2022-03-01');
SELECT DATEPART(month, ViolationDate) as Month, COUNT(*) as ViolationCount FROM MentalHealthParity WHERE ViolationDate >= DATEADD(year, -2, GETDATE()) GROUP BY DATEPART(month, ViolationDate);
Update the region to 'South America' for all records with a revenue between 5000 and 7000 in the SkincareSales table.
CREATE TABLE SkincareSales (productID INT,productName VARCHAR(50),region VARCHAR(50),revenue DECIMAL(10,2)); INSERT INTO SkincareSales (productID,productName,region,revenue) VALUES (1,'Nourishing Cream','Europe',5000.00),(2,'Soothing Lotion','Europe',7000.00),(3,'Regenerating Serum','Europe',8000.00),(4,'Revitalizing Moisturizer','North America',6000.00),(5,'Purifying Cleanser','North America',9000.00);
UPDATE SkincareSales SET region = 'South America' WHERE revenue BETWEEN 5000 AND 7000;
What is the average playtime of VR games, grouped by genre and player's region?
CREATE TABLE vr_games (id INT,game_id INT,player_id INT,last_played DATE,region VARCHAR(20),playtime INT);
SELECT g.genre, p.region, AVG(v.playtime) FROM vr_games v JOIN games g ON v.game_id = g.id JOIN players p ON v.player_id = p.id WHERE g.vr_compatible = 'Yes' GROUP BY g.genre, p.region;
What is the total weight of items in the Brazil warehouse?
CREATE TABLE Warehouse (id INT,location VARCHAR(50),quantity INT,weight FLOAT); INSERT INTO Warehouse (id,location,quantity,weight) VALUES (1,'USA',300,12.5),(2,'Canada',250,11.0),(3,'France',500,13.2),(4,'Germany',400,14.7),(5,'UK',300,15.3),(6,'Japan',450,16.1),(7,'Brazil',200,17.5);
SELECT SUM(weight) FROM Warehouse WHERE location = 'Brazil';
Retrieve information about spacecraft that have not been launched yet and their associated medical conditions.
CREATE TABLE Spacecraft (id INT PRIMARY KEY,name VARCHAR(100),manufacturer VARCHAR(100),launch_date DATE); INSERT INTO Spacecraft (id,name,manufacturer,launch_date) VALUES (4,'James Webb','NASA','2023-01-01'); CREATE TABLE Medical_Data (id INT PRIMARY KEY,astronaut_id INT,medical_condition VARCHAR(100),last_checkup DATE); INSERT INTO Medical_Data (id,astronaut_id,medical_condition,last_checkup) VALUES (4,NULL,'Requires Servicing','2022-05-01');
SELECT s.name, m.medical_condition FROM Spacecraft s LEFT JOIN Medical_Data m ON s.id = m.astronaut_id WHERE s.launch_date > CURDATE();
What is the total revenue for music artists by genre?
CREATE TABLE Music_Artists_Genre (id INT,name VARCHAR(100),genre VARCHAR(50),revenue DECIMAL(10,2)); INSERT INTO Music_Artists_Genre (id,name,genre,revenue) VALUES (1,'Adele','Pop',1000000.00),(2,'Eminem','Rap',800000.00),(3,'Metallica','Rock',1200000.00);
SELECT genre, SUM(revenue) FROM Music_Artists_Genre GROUP BY genre;
Which marine species have been found in the deepest trenches?
CREATE TABLE deep_sea_discoveries (species TEXT,discovered_depth FLOAT); INSERT INTO deep_sea_discoveries (species,discovered_depth) VALUES ('Hadal snailfish',8178.0),('Amphipods',8076.0),('Hadal toothpaste sea cucumber',7443.0);
SELECT species FROM deep_sea_discoveries ORDER BY discovered_depth DESC LIMIT 1;
Which users have posted on consecutive days?
CREATE TABLE posts (id INT,user_id INT,post_date DATE); INSERT INTO posts (id,user_id,post_date) VALUES (1,1,'2022-01-01'),(2,2,'2022-01-02'),(3,1,'2022-01-03'),(4,2,'2022-01-04'),(5,3,'2022-01-05'),(6,3,'2022-01-06'),(7,1,'2022-01-07'),(8,2,'2022-01-08'),(9,2,'2022-01-09');
SELECT user_id FROM (SELECT user_id, post_date, DATEDIFF(day, LAG(post_date) OVER (PARTITION BY user_id ORDER BY post_date), post_date) AS gap FROM posts) AS t WHERE gap = 1 GROUP BY user_id;
What is the total installed capacity (in kW) of renewable energy projects for each city?
CREATE TABLE renewable_projects (id INT,project_name VARCHAR(255),city VARCHAR(255),installed_capacity FLOAT);
SELECT city, SUM(installed_capacity) FROM renewable_projects GROUP BY city;
Find the top 5 medical conditions affecting rural communities in 'Northwest' district?
CREATE TABLE medical_conditions (condition_id INT,name VARCHAR(255),prevalence FLOAT,district VARCHAR(255)); INSERT INTO medical_conditions (condition_id,name,prevalence,district) VALUES (1,'diabetes',0.12,'Northwest'),(2,'asthma',0.08,'Northwest'),(3,'heart disease',0.15,'Northwest'),(4,'stroke',0.06,'Northwest'),(5,'cancer',0.10,'Northwest');
SELECT name, prevalence FROM medical_conditions WHERE district = 'Northwest' ORDER BY prevalence DESC LIMIT 5;
Update artifact records with conservation status
CREATE TABLE ArtifactConservationStatus (StatusID INT,StatusName TEXT);
UPDATE Artifacts SET ConservationStatusID = (SELECT StatusID FROM ArtifactConservationStatus WHERE StatusName = 'Good') WHERE SiteID = 123;
List all virtual tours available in Australia and their respective ratings.
CREATE TABLE regions (region_id INT,region TEXT,country TEXT); CREATE TABLE virtual_tours (tour_id INT,title TEXT,region_id INT,rating FLOAT); INSERT INTO regions VALUES (1,'New South Wales','Australia'),(2,'Queensland','Australia'); INSERT INTO virtual_tours VALUES (1,'Sydney Harbour Tour',1,4.5),(2,'Great Barrier Reef Tour',2,4.7),(3,'Daintree Rainforest Tour',2,4.6);
SELECT regions.region, virtual_tours.title, virtual_tours.rating FROM regions INNER JOIN virtual_tours ON regions.region_id = virtual_tours.region_id WHERE country = 'Australia';
Delete the record for 'California' from the 'vaccination_stats' table
CREATE TABLE vaccination_stats (id INT PRIMARY KEY,state VARCHAR(50),total_vaccinations INT); INSERT INTO vaccination_stats (id,state,total_vaccinations) VALUES (1,'California',25000000);
DELETE FROM vaccination_stats WHERE state = 'California';
Find the name and age of the oldest individual in the 'ancient_burials' table.
CREATE TABLE ancient_burials (id INT,name VARCHAR(50),age INT,gender VARCHAR(10),grave_contents VARCHAR(255)); INSERT INTO ancient_burials (id,name,age,gender,grave_contents) VALUES (1,'John Doe',45,'Male','Pottery,coins'),(2,'Jane Doe',50,'Female','Beads,pottery');
SELECT name, age FROM ancient_burials WHERE age = (SELECT MAX(age) FROM ancient_burials);
What is the total length (in seconds) of all jazz songs released in the 1960s?
CREATE TABLE songs (song_id INT,title VARCHAR(255),release_year INT,genre VARCHAR(50),length FLOAT); INSERT INTO songs (song_id,title,release_year,genre,length) VALUES (1,'Song1',1961,'jazz',150.5),(2,'Song2',1965,'jazz',200.3),(3,'Song3',1969,'rock',180.7);
SELECT SUM(length) FROM songs WHERE genre = 'jazz' AND release_year >= 1960 AND release_year <= 1969;
What is the average mental health rating of courses for each teacher, and which teacher has the highest average rating?
CREATE TABLE course_ratings (course_id INT,teacher_id INT,mental_health_rating FLOAT); INSERT INTO course_ratings (course_id,teacher_id,mental_health_rating) VALUES (1,1,4.5),(2,1,3.8),(3,2,4.7),(4,2,4.2),(5,3,5.0),(6,3,4.0),(7,4,4.8),(8,4,4.5),(9,5,3.2); CREATE TABLE teachers (teacher_id INT,name TEXT); INSERT INTO teachers (teacher_id,name) VALUES (1,'Ms. Johnson'),(2,'Mr. Smith'),(3,'Ms. Garcia'),(4,'Mr. Rodriguez'),(5,'Mx. Nguyen');
SELECT t.teacher_id, t.name, AVG(cr.mental_health_rating) AS avg_rating FROM course_ratings cr JOIN teachers t ON cr.teacher_id = t.teacher_id GROUP BY t.teacher_id, t.name ORDER BY avg_rating DESC LIMIT 1;
Which stations have more than 10 standard bikes?
CREATE TABLE Bikeshare (id INT,station VARCHAR(30),bike_type VARCHAR(20),total_bikes INT,last_inspection DATE); INSERT INTO Bikeshare (id,station,bike_type,total_bikes,last_inspection) VALUES (7,'Staten Island','Standard',11,'2022-01-08'),(8,'Coney Island','Standard',12,'2022-01-07');
SELECT station, COUNT(*) as total_bikes FROM Bikeshare WHERE bike_type = 'Standard' GROUP BY station HAVING total_bikes > 10;
List all oil fields in the North Sea and their production quantities
CREATE TABLE oil_fields (field_name VARCHAR(50),location VARCHAR(50),production_qty INT); INSERT INTO oil_fields (field_name,location,production_qty) VALUES ('Ekofisk','North Sea',150000),('Statfjord','North Sea',220000);
SELECT field_name, production_qty FROM oil_fields WHERE location = 'North Sea';
What is the average threat intelligence score for European countries in the past month?
CREATE TABLE threat_intelligence (threat_id INT,score INT,country VARCHAR(50),last_updated DATE);
SELECT AVG(score) FROM threat_intelligence WHERE country IN ('Austria', 'Belgium', 'Czech Republic', 'Denmark', 'Estonia', 'Finland', 'France', 'Germany', 'Greece', 'Hungary', 'Ireland', 'Italy', 'Latvia', 'Lithuania', 'Luxembourg', 'Malta', 'Netherlands', 'Poland', 'Portugal', 'Slovakia', 'Slovenia', 'Spain', 'Sweden') AND last_updated >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH);
What is the maximum defense diplomacy event budget for each region in the 'defense_diplomacy' table, ordered by the maximum budget in descending order?
CREATE TABLE defense_diplomacy (id INT,region VARCHAR(50),budget INT);
SELECT region, MAX(budget) as max_budget FROM defense_diplomacy GROUP BY region ORDER BY max_budget DESC;
Insert a new record of citizen feedback for 'Housing' in the 'South East' region with a response time of 35 minutes on April 20, 2023.
CREATE TABLE Feedback(Timestamp DATETIME,Region VARCHAR(20),FeedbackType VARCHAR(20),ResponseTime INT);
INSERT INTO Feedback(Timestamp, Region, FeedbackType, ResponseTime) VALUES ('2023-04-20 10:00:00', 'South East', 'Housing', 35);
Number of female nurses in California by age in 2019.
CREATE TABLE Nurses (State VARCHAR(50),Age INT,Gender VARCHAR(50),Specialty VARCHAR(50)); INSERT INTO Nurses (State,Age,Gender,Specialty) VALUES ('California',25,'Female','Nurse'),('California',30,'Male','Nurse'),('California',40,'Female','Nurse');
SELECT Age, COUNT(*) FROM Nurses WHERE State = 'California' AND Gender = 'Female' AND Specialty = 'Nurse' GROUP BY Age;
What is the number of unique digital assets on the Ethereum network for each month in 2021?
CREATE TABLE asset (asset_id INT,launch_date TIMESTAMP);
SELECT DATE_FORMAT(launch_date, '%Y-%m') as month, COUNT(DISTINCT asset_id) as unique_assets FROM asset WHERE launch_date BETWEEN '2021-01-01' AND '2021-12-31' GROUP BY month;
How many infectious diseases were reported by month, for the last three years?
CREATE TABLE infectious_diseases (disease_id INT,report_date DATE,disease_name VARCHAR(255)); INSERT INTO infectious_diseases (disease_id,report_date,disease_name) VALUES (1,'2020-01-01','Flu'),(2,'2020-02-15','Measles'),(3,'2021-06-20','COVID-19');
SELECT YEAR(report_date) AS year, MONTH(report_date) AS month, COUNT(*) as disease_count FROM infectious_diseases WHERE report_date BETWEEN DATE_SUB(CURRENT_DATE, INTERVAL 3 YEAR) AND CURRENT_DATE GROUP BY YEAR(report_date), MONTH(report_date);
What is the total biomass of fish in farm B?
CREATE TABLE aquaculture_farms (id INT,name VARCHAR(255)); INSERT INTO aquaculture_farms (id,name) VALUES (1,'Farm A'),(2,'Farm B'); CREATE TABLE fish_biomass (id INT,farm_id INT,species VARCHAR(255),biomass DECIMAL(5,2)); INSERT INTO fish_biomass (id,farm_id,species,biomass) VALUES (1,1,'Tilapia',120.5),(2,1,'Catfish',150.3),(3,2,'Tilapia',95.1),(4,2,'Salmon',200.0);
SELECT SUM(biomass) FROM fish_biomass WHERE farm_id = 2;
Update 'Production' table and set 'OilQuantity' to null if it's less than 500
CREATE TABLE Production (WellID INT,GasQuantity INT,OilQuantity INT);
UPDATE Production SET OilQuantity = NULL WHERE OilQuantity < 500;
What is the daily trip distance of autonomous taxis in London, ranked by distance?
CREATE TABLE autonomous_taxis (id INT,taxi_id INT,trip_start_time TIMESTAMP,trip_end_time TIMESTAMP,trip_distance FLOAT); INSERT INTO autonomous_taxis (id,taxi_id,trip_start_time,trip_end_time,trip_distance) VALUES (1,111,'2022-01-01 08:00:00','2022-01-01 08:30:00',12.5),(2,222,'2022-01-01 09:00:00','2022-01-01 09:45:00',20.0);
SELECT taxi_id, trip_distance FROM autonomous_taxis WHERE DATE(trip_start_time) = '2022-01-01' ORDER BY trip_distance DESC;