instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
Find the difference in the number of public hospitals between California and Florida.
CREATE TABLE hospitals (name VARCHAR(255),state VARCHAR(255)); INSERT INTO hospitals (name,state) VALUES ('Hospital1','California'),('Hospital2','California'),('Hospital3','Florida');
SELECT (SELECT COUNT(*) FROM hospitals WHERE state = 'California') - (SELECT COUNT(*) FROM hospitals WHERE state = 'Florida');
What is the maximum depth recorded by Indonesian organizations in the Indian Ocean in the past 3 years?
CREATE TABLE indian_ocean_mapping (id INT,organization VARCHAR(50),depth INT,date DATE,country VARCHAR(50)); INSERT INTO indian_ocean_mapping (id,organization,depth,date,country) VALUES (1,'Indonesian National Institute of Oceanography',7000,'2022-01-10','Indonesia'); INSERT INTO indian_ocean_mapping (id,organization,depth,date,country) VALUES (2,'Universitas Hasanuddin',6500,'2021-12-25','Indonesia');
SELECT MAX(depth) FROM indian_ocean_mapping WHERE country = 'Indonesia' AND date >= DATE_SUB(CURRENT_DATE, INTERVAL 3 YEAR);
Which rare earth element had the lowest production decrease between 2016 and 2017?
CREATE TABLE production (element VARCHAR(10),year INT,quantity FLOAT); INSERT INTO production (element,year,quantity) VALUES ('Neodymium',2015,2500),('Neodymium',2016,2000),('Neodymium',2017,1500),('Neodymium',2018,1000),('Neodymium',2019,500),('Praseodymium',2015,1500),('Praseodymium',2016,1000),('Praseodymium',2017,500),('Praseodymium',2018,1500),('Praseodymium',2019,2000);
SELECT element, MIN(diff) FROM (SELECT element, (LAG(quantity) OVER (PARTITION BY element ORDER BY year) - quantity) AS diff FROM production) AS subquery;
What is the total amount of gold extracted, for mines that are located in the state of California?
CREATE TABLE mine (id INT,name VARCHAR(255),state VARCHAR(255),gold_tons INT); INSERT INTO mine (id,name,state,gold_tons) VALUES (1,'Alaskan Gold Mine','Alaska',700),(2,'California Gold Mine','California',400),(3,'Nevada Silver Mine','Nevada',500);
SELECT SUM(gold_tons) as total_gold FROM mine WHERE state = 'California';
What is the total revenue generated from basketball ticket sales in 2022?
CREATE TABLE years (id INT,name VARCHAR(255)); INSERT INTO years (id,name) VALUES (1,'2021'),(2,'2022'),(3,'2023'); CREATE TABLE sports (id INT,name VARCHAR(255)); INSERT INTO sports (id,name) VALUES (1,'Basketball'),(2,'Soccer'),(3,'Football'); CREATE TABLE tickets (id INT,year_id INT,sport_id INT,revenue INT); INSERT INTO tickets (id,year_id,sport_id,revenue) VALUES (1,2,1,5000),(2,2,2,7000),(3,2,1,8000);
SELECT SUM(t.revenue) as total_revenue FROM tickets t JOIN years y ON t.year_id = y.id JOIN sports s ON t.sport_id = s.id WHERE y.name = '2022' AND s.name = 'Basketball';
Identify the federal agencies that have experienced the greatest increase in employee turnover in the last fiscal year.
CREATE TABLE agency_employees (employee_id INT,agency_id INT,hire_date DATE,termination_date DATE);
SELECT agency_id, agency_name, ((COUNT(*) FILTER (WHERE termination_date >= DATE_SUB(CURDATE(), INTERVAL 1 YEAR) AND termination_date < DATE_SUB(CURDATE(), INTERVAL 12 MONTH)) - COUNT(*) FILTER (WHERE hire_date >= DATE_SUB(CURDATE(), INTERVAL 1 YEAR) AND hire_date < DATE_SUB(CURDATE(), INTERVAL 12 MONTH))) * 100.0 / COUNT(*) FILTER (WHERE hire_date >= DATE_SUB(CURDATE(), INTERVAL 1 YEAR))) AS turnover_percentage FROM agency_employees JOIN agencies ON agency_employees.agency_id = agencies.agency_id GROUP BY agency_id, agency_name ORDER BY turnover_percentage DESC;
Insert a new rural infrastructure project in India that started on 2022-07-15 with a budget of 80000.00 USD.
CREATE TABLE infrastructure_projects (id INT,project_id INT,country VARCHAR(50),project VARCHAR(50),budget DECIMAL(10,2),start_date DATE,end_date DATE); INSERT INTO infrastructure_projects (id,project_id,country,project,budget,start_date,end_date) VALUES (1,8001,'India','Smart Irrigation System',80000.00,'2022-07-15','2023-06-30');
INSERT INTO infrastructure_projects (project_id, country, project, budget, start_date, end_date) VALUES (8002, 'India', 'Solar Powered Water Pump', 90000.00, '2022-12-01', '2024-11-30');
What is the highest wind speed recorded in 'Beijing'?
CREATE TABLE weather (city VARCHAR(255),wind_speed FLOAT,date DATE); INSERT INTO weather (city,wind_speed,date) VALUES ('Beijing',35,'2022-02-01'),('Beijing',40,'2022-04-10'),('Beijing',45,'2022-07-25');
SELECT MAX(wind_speed) FROM weather WHERE city = 'Beijing';
What is the average age of all male reporters in the "news_reporters" table, grouped by department?
CREATE TABLE news_reporters (id INT,name VARCHAR(50),gender VARCHAR(10),age INT,department VARCHAR(30));
SELECT department, AVG(age) FROM news_reporters WHERE gender = 'male' GROUP BY department;
What is the average budget allocated for military intelligence per year for the top 5 countries with the highest military spending?
CREATE TABLE countries (id INT,name VARCHAR(255)); CREATE TABLE military_spending (id INT,country_id INT,year INT,amount DECIMAL(10,2)); CREATE TABLE intelligence_budget (id INT,country_id INT,year INT,amount DECIMAL(10,2));
SELECT AVG(ib.amount) as avg_annual_intelligence_budget FROM (SELECT cs.country_id, cs.year, MAX(cs.amount) as max_spending FROM military_spending cs GROUP BY cs.country_id, cs.year) ms JOIN intelligence_budget ib ON ms.country_id = ib.country_id AND ms.year = ib.year AND ms.max_spending = ib.amount LIMIT 5;
What is the policy impact of the 'Waste Management' initiative in CityB?
CREATE TABLE PolicyImpact (CityName VARCHAR(50),Policy VARCHAR(50),Impact INT); INSERT INTO PolicyImpact (CityName,Policy,Impact) VALUES ('CityA','Waste Management',7),('CityA','Transportation',8),('CityB','Waste Management',9),('CityB','Transportation',6);
SELECT Impact FROM PolicyImpact WHERE CityName = 'CityB' AND Policy = 'Waste Management';
Insert a new diversity metric for a specific startup
CREATE TABLE companies (id INT,name TEXT,founded DATE); INSERT INTO companies (id,name,founded) VALUES (1,'Foobar Inc','2017-01-01'),(2,'Gizmos Inc','2019-06-15'),(3,'Widgets Inc','2015-09-27'); CREATE TABLE diversity (company_id INT,gender_diversity FLOAT,racial_diversity FLOAT);
INSERT INTO diversity (company_id, gender_diversity, racial_diversity) VALUES (1, 0.5, 0.3);
Display the number of threat intelligence records and their source by day
CREATE TABLE threat_daily (id INT,record_date DATE,source VARCHAR(10)); INSERT INTO threat_daily (id,record_date,source) VALUES (1,'2022-01-01','TI1'),(2,'2022-01-01','TI2'),(3,'2022-01-02','TI3'),(4,'2022-01-03','TI4'),(5,'2022-01-03','TI1'),(6,'2022-01-03','TI2');
SELECT EXTRACT(DAY FROM record_date) as day, source, COUNT(*) as records FROM threat_daily GROUP BY day, source;
List the organizations that have received donations from donors located in 'California', but have not received donations from donors located in 'New York'.
CREATE TABLE donors (id INT,name TEXT,state TEXT); INSERT INTO donors (id,name,state) VALUES (1,'John Doe','California'); CREATE TABLE donations (id INT,donor_id INT,org_id INT,donation_amount DECIMAL(10,2)); INSERT INTO donations (id,donor_id,org_id,donation_amount) VALUES (1,1,1,100.00);
SELECT organizations.name FROM organizations WHERE organizations.id IN (SELECT donations.org_id FROM donations JOIN donors ON donations.donor_id = donors.id WHERE donors.state = 'California') AND organizations.id NOT IN (SELECT donations.org_id FROM donations JOIN donors ON donations.donor_id = donors.id WHERE donors.state = 'New York');
What is the average calorie count for organic meals in our database?
CREATE TABLE OrganicMeals (id INT,name VARCHAR(50),calories INT); INSERT INTO OrganicMeals (id,name,calories) VALUES (1,'Quinoa Salad',350),(2,'Tofu Stir Fry',450),(3,'Lentil Soup',250);
SELECT AVG(calories) FROM OrganicMeals;
Retrieve the number of policies and claims processed each month for the past year.
CREATE TABLE policies (policy_id INT,policy_date DATE); CREATE TABLE claims (claim_id INT,claim_date DATE);
SELECT DATE_FORMAT(policies.policy_date, '%Y-%m') AS month, COUNT(policies.policy_id) AS policies_processed, COUNT(claims.claim_id) AS claims_processed FROM policies LEFT JOIN claims ON policies.policy_date = claims.claim_date WHERE policies.policy_date >= DATE_SUB(NOW(), INTERVAL 1 YEAR) GROUP BY month ORDER BY month;
Show mining operations and their respective environmental impact scores from the 'mining_operations' and 'environmental_impact' tables.
CREATE TABLE mining_operations (operation_id INT,operation_name VARCHAR(50)); INSERT INTO mining_operations (operation_id,operation_name) VALUES (1,'Open Pit Mine 1'),(2,'Underground Mine 2'); CREATE TABLE environmental_impact (operation_id INT,impact_score INT); INSERT INTO environmental_impact (operation_id,impact_score) VALUES (1,70),(2,55);
SELECT mining_operations.operation_name, environmental_impact.impact_score FROM mining_operations INNER JOIN environmental_impact ON mining_operations.operation_id = environmental_impact.operation_id;
determine if any employees have published articles under multiple topics
CREATE TABLE Employees (id INT,name VARCHAR(50)); CREATE TABLE Articles (id INT,author_id INT,topic VARCHAR(50),published_date DATE); INSERT INTO Employees (id,name) VALUES (1,'John Doe'); INSERT INTO Employees (id,name) VALUES (2,'Jane Smith'); INSERT INTO Articles (id,author_id,topic,published_date) VALUES (1,1,'Politics','2022-01-01'); INSERT INTO Articles (id,author_id,topic,published_date) VALUES (2,1,'Sports','2022-01-02'); INSERT INTO Articles (id,author_id,topic,published_date) VALUES (3,2,'Politics','2022-01-03');
SELECT author_id FROM Articles GROUP BY author_id HAVING COUNT(DISTINCT topic) > 1;
Insert a new record into the 'community_health_workers' table with the following information: ID 789, Name 'Javier Rodriguez', Age 40, State 'TX'
CREATE TABLE community_health_workers (id INT,name VARCHAR(255),age INT,state VARCHAR(2));
INSERT INTO community_health_workers (id, name, age, state) VALUES (789, 'Javier Rodriguez', 40, 'TX');
What's the average budget for Bollywood movies released after 2015?
CREATE TABLE movies (movie_id INT,title VARCHAR(100),release_year INT,production_budget INT,production_company VARCHAR(50)); INSERT INTO movies (movie_id,title,release_year,production_budget,production_company) VALUES (1,'Bahubali 2',2017,250000000,'Arka Media Works'),(2,'Dangal',2016,100000000,'Walt Disney Pictures');
SELECT production_company, AVG(production_budget) as avg_budget FROM movies WHERE production_company LIKE '%Bollywood%' AND release_year > 2015 GROUP BY production_company;
Delete all movies with a budget over 10 million.
CREATE TABLE movies (id INT,title VARCHAR(255),genre VARCHAR(255),budget DECIMAL(10,2)); INSERT INTO movies (id,title,genre,budget) VALUES (1,'Movie A','Action',12000000.00),(2,'Movie B','Comedy',4000000.00),(3,'Movie C','Drama',8000000.00);
DELETE FROM movies WHERE budget > 10000000.00;
List all climate mitigation initiatives in Africa that were implemented before 2010 and received funding from both public and private sources.
CREATE TABLE climate_mitigation (initiative VARCHAR(50),funding_source VARCHAR(50),year INT); INSERT INTO climate_mitigation (initiative,funding_source,year) VALUES ('Solar Energy Program','Public',2005),('Wind Farm Development','Private',2008),('Energy Efficiency Project','Public-Private',2009); CREATE TABLE initiatives (initiative VARCHAR(50),region VARCHAR(50)); INSERT INTO initiatives (initiative,region) VALUES ('Solar Energy Program','Africa'),('Wind Farm Development','Africa'),('Energy Efficiency Project','Africa');
SELECT i.initiative FROM initiatives i INNER JOIN climate_mitigation cm ON i.initiative = cm.initiative WHERE i.region = 'Africa' AND (cm.funding_source = 'Public' OR cm.funding_source = 'Private') AND cm.year < 2010;
List the waste generation metrics of the 'west' region for the last 30 days.
CREATE TABLE waste_metrics (id INT,region VARCHAR(50),generation_date DATE,waste_generated FLOAT);
SELECT * FROM waste_metrics WHERE region = 'west' AND generation_date >= CURDATE() - INTERVAL 30 DAY;
Delete records of fair-trade certified suppliers in Vietnam who provide organic cotton?
CREATE TABLE Suppliers (SupplierID INT,SupplierName VARCHAR(50),Country VARCHAR(50),Certification VARCHAR(50),Material VARCHAR(50)); INSERT INTO Suppliers (SupplierID,SupplierName,Country,Certification,Material) VALUES (1,'Supplier A','Vietnam','Fair Trade','Organic Cotton'),(2,'Supplier B','Bangladesh','Fair Trade','Organic Cotton'),(3,'Supplier C','Vietnam','Certified Organic','Organic Cotton'),(4,'Supplier D','India','Fair Trade','Recycled Polyester');
DELETE FROM Suppliers WHERE Country = 'Vietnam' AND Certification = 'Fair Trade' AND Material = 'Organic Cotton';
Calculate the percentage of beauty products in the UK that contain natural ingredients.
CREATE TABLE product_ingredients (product_id INT,has_natural_ingredients BOOLEAN); INSERT INTO product_ingredients (product_id,has_natural_ingredients) VALUES (1001,TRUE),(1002,FALSE),(1003,TRUE),(1004,TRUE),(1005,FALSE); CREATE TABLE products (product_id INT,country VARCHAR(50)); INSERT INTO products (product_id,country) VALUES (1001,'UK'),(1002,'Canada'),(1003,'UK'),(1004,'USA'),(1005,'UK');
SELECT 100.0 * SUM(has_natural_ingredients) / COUNT(*) as percentage FROM product_ingredients JOIN products ON product_ingredients.product_id = products.product_id WHERE country = 'UK';
What is the average weight of returned goods for each reason, grouped by warehouse?
CREATE TABLE Warehouse (id INT,location VARCHAR(255)); INSERT INTO Warehouse (id,location) VALUES (1,'New York'),(2,'Los Angeles'),(3,'Chicago'); CREATE TABLE Returned_Goods (id INT,warehouse_id INT,reason VARCHAR(255),returned_date DATE,weight INT); INSERT INTO Returned_Goods (id,warehouse_id,reason,returned_date,weight) VALUES (1,1,'Damaged','2021-01-15',50),(2,2,'Wrong product','2021-01-20',75),(3,3,'Missing parts','2021-01-25',60);
SELECT rg.reason, w.location, AVG(rg.weight) as avg_weight FROM Returned_Goods rg JOIN Warehouse w ON rg.warehouse_id = w.id GROUP BY rg.reason, w.location;
What is the average number of AI chatbots adopted by hotels in 'Europe'?
CREATE TABLE hotel_tech (hotel_id INT,hotel_name TEXT,region TEXT,ai_chatbot BOOLEAN); INSERT INTO hotel_tech (hotel_id,hotel_name,region,ai_chatbot) VALUES (1,'Hotel Ritz','Europe',TRUE),(2,'Hotel Bellagio','Europe',FALSE);
SELECT AVG(ai_chatbot) FROM hotel_tech WHERE region = 'Europe';
Compare the water conservation initiatives in California and Texas.
CREATE TABLE conservation_initiatives(state VARCHAR(20),initiative VARCHAR(50)); INSERT INTO conservation_initiatives(state,initiative) VALUES ('California','Water-saving appliances'),('California','Drought-resistant landscaping'),('Texas','Rainwater harvesting'),('Texas','Greywater recycling');
SELECT initiative FROM conservation_initiatives WHERE state IN ('California', 'Texas') ORDER BY state;
What is the number of male and female employees in the 'employees' table?
CREATE TABLE employees (id INT,name VARCHAR(255),gender VARCHAR(255),country VARCHAR(255)); INSERT INTO employees (id,name,gender,country) VALUES (1,'John Doe','Male','USA'); INSERT INTO employees (id,name,gender,country) VALUES (2,'Jane Smith','Female','Canada'); INSERT INTO employees (id,name,gender,country) VALUES (3,'Alice Johnson','Female','USA');
SELECT gender, COUNT(*) FROM employees GROUP BY gender;
What is the total number of volunteers per program, for programs that have more than 50 volunteers?
CREATE TABLE programs (id INT,name TEXT);CREATE TABLE volunteers (id INT,program_id INT,number INTEGER); INSERT INTO programs (id,name) VALUES (1,'Program A'),(2,'Program B'),(3,'Program C'); INSERT INTO volunteers (id,program_id,number) VALUES (1,1,35),(2,1,75),(3,2,100),(4,3,20);
SELECT p.name, SUM(v.number) FROM programs p INNER JOIN volunteers v ON p.id = v.program_id GROUP BY p.id HAVING SUM(v.number) > 50;
List the top 5 countries with the highest number of satellites in orbit as of 2022-01-01, ordered by the number of satellites in descending order.
CREATE TABLE countries(id INT,name VARCHAR(255),population INT,satellites_in_orbit INT,last_census_date DATE);
SELECT name, satellites_in_orbit FROM countries WHERE last_census_date <= '2022-01-01' GROUP BY name ORDER BY satellites_in_orbit DESC LIMIT 5;
Update product_category for products that are present in both 'products' and 'products_sustainability' tables
CREATE TABLE products (id INT,name TEXT,category TEXT);CREATE TABLE products_sustainability (id INT,name TEXT,sustainable_label TEXT);
UPDATE products p SET category = 'sustainable' WHERE p.id IN (SELECT ps.id FROM products_sustainability ps);
What was the total value of contract negotiations with 'NATO' in '2020'?
CREATE TABLE Contract_Negotiations (partner VARCHAR(255),year INT,value INT); INSERT INTO Contract_Negotiations (partner,year,value) VALUES ('NATO',2020,5000000),('NATO',2019,4000000);
SELECT SUM(value) FROM Contract_Negotiations WHERE partner = 'NATO' AND year = 2020;
What is the combined energy output of solar and wind power projects in Germany?
CREATE TABLE project_germany (project_name TEXT,type TEXT,capacity NUMERIC); INSERT INTO project_germany (project_name,type,capacity) VALUES ('Solar Park A','Solar',50000),('Solar Park B','Solar',60000),('Wind Farm C','Wind',80000),('Wind Farm D','Wind',90000);
SELECT SUM(capacity) FROM project_germany WHERE type IN ('Solar', 'Wind');
List the top 3 vendors by the number of defense contracts awarded in the Pacific region in descending order
CREATE TABLE defense_contracts (contract_id INT,vendor VARCHAR(50),vendor_region VARCHAR(10));
SELECT vendor, COUNT(*) as contract_count FROM defense_contracts WHERE vendor_region = 'Pacific' GROUP BY vendor ORDER BY contract_count DESC LIMIT 3;
Delete customer orders with a total cost over $500
CREATE TABLE customer_orders (order_id INT PRIMARY KEY,customer_id INT,total_cost DECIMAL(5,2),order_date TIMESTAMP);
DELETE FROM customer_orders WHERE total_cost > 500;
What is the average response time for fire emergencies in Houston?
CREATE TABLE emergencies (id INT,category VARCHAR(255),city VARCHAR(255),response_time INT); INSERT INTO emergencies (id,category,city,response_time) VALUES (1,'Medical','Houston',8),(2,'Fire','Houston',6),(3,'Medical','Houston',10);
SELECT AVG(response_time) as avg_response_time FROM emergencies WHERE city = 'Houston' AND category = 'Fire';
What is the total number of bookings for each hotel in the 'Hotel_Bookings' table?
CREATE TABLE Hotel_Bookings (hotel_name VARCHAR(50),bookings INT); INSERT INTO Hotel_Bookings (hotel_name,bookings) VALUES ('The Grand Hotel',1200),('Executive Suites',1500),('Harbor View',1800);
SELECT hotel_name, SUM(bookings) FROM Hotel_Bookings GROUP BY hotel_name;
What is the name of the most funded biotech startup in Africa?
CREATE SCHEMA if not exists biotech;CREATE TABLE if not exists biotech.startups (id INT PRIMARY KEY,name VARCHAR(100),country VARCHAR(50),funding DECIMAL(10,2)); INSERT INTO biotech.startups (id,name,country,funding) VALUES (1,'StartupA','South Africa',4000000.00),(2,'StartupB','USA',5000000.00),(3,'StartupC','Kenya',3500000.00);
SELECT name FROM biotech.startups WHERE country = 'Africa' AND funding = (SELECT MAX(funding) FROM biotech.startups WHERE country = 'Africa');
Determine the total funding for deep-sea expeditions in the Arctic region.
CREATE TABLE deep_sea_expeditions (expedition_id INT,region VARCHAR(255),funding INT); INSERT INTO deep_sea_expeditions (expedition_id,region,funding) VALUES (1,'Arctic',500000),(2,'Antarctic',750000),(3,'Arctic',600000);
SELECT SUM(funding) FROM deep_sea_expeditions WHERE region = 'Arctic';
List the top 3 most common types of sustainable urbanism projects in each city, ordered by the number of projects.
CREATE TABLE cities (city_id INT,name VARCHAR(255)); CREATE TABLE sustainable_projects (project_id INT,city_id INT,project_type VARCHAR(255),PRIMARY KEY (project_id),FOREIGN KEY (city_id) REFERENCES cities(city_id));
SELECT cities.name, project_type, COUNT(*) as project_count FROM cities JOIN sustainable_projects ON cities.city_id = sustainable_projects.city_id GROUP BY cities.name, project_type ORDER BY cities.name, project_count DESC LIMIT 3;
List all restaurants that received a food safety violation in the state of Texas between 2018 and 2020, along with the total number of violations per restaurant and the average severity of those violations.
CREATE TABLE restaurants (restaurant_id INT,state VARCHAR(255)); CREATE TABLE inspections (inspection_id INT,restaurant_id INT,violation_count INT,severity DECIMAL(3,2)); INSERT INTO restaurants VALUES (1,'Texas'); INSERT INTO restaurants VALUES (2,'California'); INSERT INTO inspections VALUES (1,1,3,2.5); INSERT INTO inspections VALUES (2,1,2,3.0); INSERT INTO inspections VALUES (3,2,1,1.5);
SELECT r.restaurant_id, r.state, COUNT(i.inspection_id) as total_violations, AVG(i.severity) as average_severity FROM restaurants r INNER JOIN inspections i ON r.restaurant_id = i.restaurant_id WHERE r.state = 'Texas' AND i.inspection_date BETWEEN '2018-01-01' AND '2020-12-31' GROUP BY r.restaurant_id;
What is the average age of patients with diabetes in rural Texas who are male?
CREATE TABLE patients (id INT,name VARCHAR(50),age INT,gender VARCHAR(10),diagnosis VARCHAR(50),location VARCHAR(50)); INSERT INTO patients (id,name,age,gender,diagnosis,location) VALUES (1,'Jane Doe',65,'Female','Diabetes','Texas'),(2,'John Doe',45,'Male','Diabetes','Texas'),(3,'Jim Brown',55,'Male','Diabetes','Texas');
SELECT AVG(age) FROM patients WHERE diagnosis = 'Diabetes' AND gender = 'Male' AND location = 'Texas';
List the names of the mines and the number of employees at each mine.
CREATE TABLE mines (id INT,name VARCHAR(255),number_of_employees INT); INSERT INTO mines (id,name,number_of_employees) VALUES (1,'Mine A',200),(2,'Mine B',250),(3,'Mine C',180),(4,'Mine D',220); CREATE TABLE employees (id INT,mine_id INT,name VARCHAR(255)); INSERT INTO employees (id,mine_id,name) VALUES (1,1,'John'),(2,1,'Jane'),(3,2,'Mike'),(4,2,'Lucy'),(5,3,'Tom'),(6,4,'Sara');
SELECT m.name, COUNT(e.id) as total_employees FROM mines m JOIN employees e ON m.id = e.mine_id GROUP BY m.name;
What is the total duration spent in the museum by visitors from Canada?
CREATE TABLE Countries (id INT,name VARCHAR(20)); ALTER TABLE Visitors ADD COLUMN country_id INT; ALTER TABLE Visitors ADD COLUMN total_duration INT;
SELECT SUM(Visitors.total_duration) FROM Visitors JOIN Countries ON Visitors.country_id = Countries.id WHERE Countries.name = 'Canada';
What are the patient outcomes for those who received therapy and medication?
CREATE TABLE patients (patient_id INT,name VARCHAR(50),therapy_completed BOOLEAN,medication_completed BOOLEAN);CREATE TABLE therapy_outcomes (patient_id INT,improvement_score INT);CREATE TABLE medication_outcomes (patient_id INT,improvement_score INT);
SELECT patients.name, therapy_outcomes.improvement_score AS therapy_score, medication_outcomes.improvement_score AS medication_score FROM patients INNER JOIN therapy_outcomes ON patients.patient_id = therapy_outcomes.patient_id INNER JOIN medication_outcomes ON patients.patient_id = medication_outcomes.patient_id WHERE therapy_completed = TRUE AND medication_completed = TRUE;
What is the distribution of case outcomes (won, lost, settled) for attorneys in the 'attorneys_outcomes' table, grouped by attorney age?
CREATE TABLE attorney_age (attorney_id INT,age INT); CREATE TABLE attorneys_outcomes (case_outcome VARCHAR(10),attorney_id INT);
SELECT a.age, o.case_outcome, COUNT(*) AS count FROM attorney_age a JOIN attorneys_outcomes o ON a.attorney_id = o.attorney_id GROUP BY a.age, o.case_outcome;
What is the average amount of funding received by companies founded by women?
CREATE TABLE Companies (id INT,name TEXT,founder_gender TEXT,funding_amount INT); INSERT INTO Companies (id,name,founder_gender,funding_amount) VALUES (1,'Blossom Inc','Female',500000); INSERT INTO Companies (id,name,founder_gender,funding_amount) VALUES (2,'Elevate Corp','Male',1000000);
SELECT AVG(funding_amount) FROM Companies WHERE founder_gender = 'Female';
Find the names of suppliers from Canada that supply more than 500 tons of vegan products.
CREATE TABLE suppliers (id INT,name TEXT,produce_type TEXT,quantity INT,is_vegan BOOLEAN,country TEXT); INSERT INTO suppliers (id,name,produce_type,quantity,is_vegan,country) VALUES (1,'Green Garden','Fruits',700,true,'Canada'); INSERT INTO suppliers (id,name,produce_type,quantity,is_vegan,country) VALUES (2,'Farm Fresh','Vegetables',400,true,'Canada');
SELECT name FROM suppliers WHERE produce_type = 'Fruits' OR produce_type = 'Vegetables' AND is_vegan = true AND country = 'Canada' AND quantity > 500;
Identify the number of wastewater treatment plants in California that exceed their permitted discharge limits?
CREATE TABLE Wastewater_Treatment_Plants (ID INT,Plant_Name VARCHAR(50),State VARCHAR(20),Permit_Discharge FLOAT,Exceeded_Limit INT);
SELECT COUNT(*) FROM Wastewater_Treatment_Plants WHERE State = 'California' AND Exceeded_Limit = 1;
What is the average transaction amount by customer demographics in the past month?
CREATE TABLE customers (customer_id INT,name VARCHAR(50),region VARCHAR(50),age INT,gender VARCHAR(10)); CREATE TABLE transactions (transaction_id INT,customer_id INT,amount DECIMAL(10,2),transaction_date DATE);
SELECT c.region, c.gender, AVG(t.amount) as avg_amount FROM customers c INNER JOIN transactions t ON c.customer_id = t.customer_id WHERE t.transaction_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH) GROUP BY c.region, c.gender;
Which users have posted more than 5 times in the east_coast region?
CREATE TABLE users (id INT,region VARCHAR(10)); INSERT INTO users (id,region) VALUES (1,'west_coast'),(2,'east_coast'),(3,'west_coast'); CREATE TABLE posts (id INT,user_id INT,content TEXT); INSERT INTO posts (id,user_id,content) VALUES (1,1,'AI is cool'),(2,2,'I love SQL'),(3,2,'Data science'),(4,2,'Machine learning'),(5,3,'Hello');
SELECT DISTINCT u.id, u.region FROM users u JOIN posts p ON u.id = p.user_id WHERE p.user_id IN (SELECT user_id FROM posts GROUP BY user_id HAVING COUNT(*) > 5);
What is the total number of engines produced by each engine manufacturer?
CREATE TABLE Engine_Manufacturers (manufacturer VARCHAR(255),engine_model VARCHAR(255),quantity INT); INSERT INTO Engine_Manufacturers (manufacturer,engine_model,quantity) VALUES ('Pratt & Whitney','PW1000G',500),('Rolls-Royce','Trent XWB',600),('General Electric','GE9X',700);
SELECT manufacturer, SUM(quantity) FROM Engine_Manufacturers GROUP BY manufacturer;
List artifact types present in excavation sites from South America that were analyzed after 2000.
CREATE TABLE excavations (id INT,location VARCHAR(255)); INSERT INTO excavations (id,location) VALUES (1,'Brazil'),(2,'Argentina'),(3,'USA');
SELECT DISTINCT a.artifact_type FROM artifacts a INNER JOIN excavations e ON a.excavation_id = e.id WHERE e.location LIKE 'South America%' AND a.analysis_date > '2000-01-01';
What are the names and production quantities of the top 3 producing wells in the 'North Sea' region?
CREATE TABLE wells (well_id INT,well_name VARCHAR(50),region VARCHAR(50),production_qty FLOAT); INSERT INTO wells VALUES (1,'Well A','North Sea',15000); INSERT INTO wells VALUES (2,'Well B','North Sea',12000); INSERT INTO wells VALUES (3,'Well C','Gulf of Mexico',18000);
SELECT well_name, production_qty FROM wells WHERE region = 'North Sea' ORDER BY production_qty DESC LIMIT 3;
What is the total diversity and inclusion training completion rate for employees hired in the EMEA region in 2022?
CREATE TABLE employees (id INT,first_name VARCHAR(50),last_name VARCHAR(50),hire_date DATE,country VARCHAR(50)); CREATE TABLE diversity_training (id INT,employee_id INT,training_name VARCHAR(50),completed_date DATE);
SELECT COUNT(DISTINCT e.id) * 100.0 / (SELECT COUNT(DISTINCT employee_id) FROM diversity_training WHERE employee_id IN (SELECT id FROM employees WHERE hire_date >= '2022-01-01' AND hire_date < '2023-01-01' AND country IN (SELECT region FROM regions WHERE region_name = 'EMEA'))) as completion_rate FROM diversity_training WHERE employee_id IN (SELECT id FROM employees WHERE hire_date >= '2022-01-01' AND hire_date < '2023-01-01' AND country IN (SELECT region FROM regions WHERE region_name = 'EMEA'));
What is the number of animals in the rehabilitation center per species?
CREATE TABLE animal_species (species_id INT,species_name VARCHAR(255)); INSERT INTO animal_species (species_id,species_name) VALUES (1,'Tiger'),(2,'Lion'),(3,'Elephant'); CREATE TABLE rehabilitation_center (animal_id INT,species_id INT,admission_date DATE); INSERT INTO rehabilitation_center (animal_id,species_id,admission_date) VALUES (1,1,'2021-01-05'),(2,2,'2021-01-12'),(3,3,'2021-02-18');
SELECT s.species_name, COUNT(r.animal_id) FROM rehabilitation_center r JOIN animal_species s ON r.species_id = s.species_id GROUP BY s.species_name;
Display the total quantity of sativa strains sold in each dispensary for the month of January 2022.
CREATE TABLE DispensarySales (dispensary_id INT,strain_type TEXT,quantity_sold INT,sale_date DATE);
SELECT dispensary_id, SUM(quantity_sold) FROM DispensarySales WHERE strain_type = 'sativa' AND sale_date >= '2022-01-01' AND sale_date <= '2022-01-31' GROUP BY dispensary_id;
Find the average score difference (home minus away) for each team, in the hockey_scores dataset.
CREATE TABLE hockey_scores (team VARCHAR(50),home_score INT,away_score INT);
SELECT team, AVG(home_score - away_score) as avg_score_difference FROM hockey_scores GROUP BY team;
What is the total budget for agencies that have a budget greater than $2,500,000?
CREATE TABLE Agency (id INT,name VARCHAR(50),budget INT); INSERT INTO Agency (id,name,budget) VALUES (1,'Transportation',2000000); INSERT INTO Agency (id,name,budget) VALUES (2,'Education',3000000);
SELECT SUM(budget) FROM Agency WHERE budget > 2500000;
Find the total amount of socially responsible loans issued in Europe in 2021.
CREATE TABLE loans (id INT,type TEXT,value DECIMAL,issued_date DATE); INSERT INTO loans (id,type,value,issued_date) VALUES (1,'Socially Responsible',10000,'2021-04-22'),(2,'Conventional',8000,'2021-02-15');
SELECT SUM(value) FROM loans WHERE type = 'Socially Responsible' AND issued_date BETWEEN '2021-01-01' AND '2021-12-31';
Show the number of consecutive days with no flights for each airport.
CREATE TABLE AirportFlights (Airport VARCHAR(20),FlightDate DATE); INSERT INTO AirportFlights (Airport,FlightDate) VALUES ('LAX','2022-01-01'),('LAX','2022-01-02'),('JFK','2022-01-01'),('JFK','2022-01-03');
SELECT Airport, COUNT(*) AS ConsecutiveDays FROM (SELECT Airport, FlightDate, ROW_NUMBER() OVER (PARTITION BY Airport ORDER BY FlightDate) - ROW_NUMBER() OVER (ORDER BY Airport, FlightDate) AS Grp FROM AirportFlights) a GROUP BY Airport, Grp HAVING COUNT(*) > 1 ORDER BY Airport;
Find the total number of tickets sold for outdoor events in the last month, grouped by event type.
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');
SELECT event_type, SUM(tickets_sold) as total_tickets_sold FROM TicketSales WHERE location = 'Outdoor Stadium' AND date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH) GROUP BY event_type;
Delete the community development initiative with ID 2 from the 'community_development' table.
CREATE TABLE community_development(id INT,region TEXT,initiative_name TEXT,status TEXT); INSERT INTO community_development (id,region,initiative_name,status) VALUES (1,'Amazonas','Cultural Center','planning'); INSERT INTO community_development (id,region,initiative_name,status) VALUES (2,'Brazil','Sustainable Forestry','planning');
DELETE FROM community_development WHERE id = 2;
What is the average annual income in urban areas, grouped by region?
CREATE TABLE UrbanAreas (ID INT,City VARCHAR(50),Income FLOAT,Region VARCHAR(50)); INSERT INTO UrbanAreas (ID,City,Income,Region) VALUES (1,'CityA',35000,'North'),(2,'CityB',40000,'North'),(3,'CityC',50000,'South');
SELECT Region, AVG(Income) as AvgAnnualIncome FROM UrbanAreas WHERE City LIKE '%urban%' GROUP BY Region;
What is the average flight altitude for Boeing 747 aircraft?
CREATE TABLE Flight_Data (flight_date DATE,aircraft_model VARCHAR(255),flight_altitude INTEGER); INSERT INTO Flight_Data (flight_date,aircraft_model,flight_altitude) VALUES ('2020-01-01','Boeing 747',35000),('2020-02-01','Boeing 737',30000),('2020-03-01','Boeing 747',36000),('2020-04-01','Airbus A380',40000),('2020-05-01','Boeing 747',33000);
SELECT AVG(flight_altitude) AS avg_flight_altitude FROM Flight_Data WHERE aircraft_model = 'Boeing 747';
What is the total market access for drugs with a manufacturing cost of less than $100 per unit?
CREATE TABLE drug_approval (drug_name TEXT,approval_status TEXT); INSERT INTO drug_approval (drug_name,approval_status) VALUES ('Drug1','approved'),('Drug2','approved'),('Drug3','pending'),('Drug4','approved'); CREATE TABLE manufacturing_costs (drug_name TEXT,cost_per_unit INTEGER); INSERT INTO manufacturing_costs (drug_name,cost_per_unit) VALUES ('Drug1',125),('Drug2',175),('Drug3',190),('Drug4',85); CREATE TABLE drug_market_access (drug_name TEXT,market_access INTEGER); INSERT INTO drug_market_access (drug_name,market_access) VALUES ('Drug1',60000000),('Drug2',70000000),('Drug3',0),('Drug4',85000000);
SELECT SUM(market_access) FROM drug_market_access INNER JOIN drug_approval ON drug_market_access.drug_name = drug_approval.drug_name INNER JOIN manufacturing_costs ON drug_market_access.drug_name = manufacturing_costs.drug_name WHERE manufacturing_costs.cost_per_unit < 100 AND drug_approval.approval_status = 'approved';
Show the cultural competency scores of healthcare providers by city in descending order.
CREATE TABLE HealthcareProviders (ProviderId INT,CulturalCompetencyScore INT,City VARCHAR(255)); INSERT INTO HealthcareProviders (ProviderId,CulturalCompetencyScore,City) VALUES (1,85,'Los Angeles'); INSERT INTO HealthcareProviders (ProviderId,CulturalCompetencyScore,City) VALUES (2,90,'New York'); INSERT INTO HealthcareProviders (ProviderId,CulturalCompetencyScore,City) VALUES (3,80,'Chicago'); INSERT INTO HealthcareProviders (ProviderId,CulturalCompetencyScore,City) VALUES (4,95,'Miami');
SELECT City, CulturalCompetencyScore FROM HealthcareProviders ORDER BY CulturalCompetencyScore DESC;
What is the average age of offenders who have participated in restorative justice programs, by gender?
CREATE TABLE offenders (offender_id INT,age INT,gender VARCHAR(10)); INSERT INTO offenders (offender_id,age,gender) VALUES (1,34,'Male'),(2,28,'Female'); CREATE TABLE restorative_justice (offender_id INT,program_id INT); INSERT INTO restorative_justice (offender_id,program_id) VALUES (1,5),(2,5); CREATE TABLE programs (program_id INT,program_name VARCHAR(20)); INSERT INTO programs (program_id,program_name) VALUES (5,'Restorative Circles');
SELECT AVG(offenders.age) as avg_age, offenders.gender FROM offenders INNER JOIN restorative_justice ON offenders.offender_id = restorative_justice.offender_id INNER JOIN programs ON restorative_justice.program_id = programs.program_id WHERE programs.program_name = 'Restorative Circles' GROUP BY offenders.gender;
What is the maximum orbital height for satellites launched by India?
CREATE TABLE satellite_info (id INT,name VARCHAR(255),country VARCHAR(255),orbital_height INT);
SELECT MAX(orbital_height) FROM satellite_info WHERE country = 'India';
What is the average CO2 sequestration potential for boreal forests in 2030?
CREATE TABLE co2_sequestration_boreal (id INT,year INT,sequestration FLOAT);
SELECT AVG(sequestration) FROM co2_sequestration_boreal WHERE year = 2030 AND id = (SELECT MAX(id) FROM co2_sequestration_boreal WHERE year < 2030);
What is the total number of acres for habitat preservation?
CREATE TABLE habitat_preservation (id INT,habitat_name VARCHAR(50),acres FLOAT); INSERT INTO habitat_preservation (id,habitat_name,acres) VALUES (1,'Forest',500.5),(2,'Wetlands',300.2),(3,'Grasslands',700.1);
SELECT SUM(acres) FROM habitat_preservation;
Display the number of unique animal species in each region
CREATE TABLE animal_population (id INT PRIMARY KEY,species VARCHAR(255),region VARCHAR(255));
SELECT region, COUNT(DISTINCT species) FROM animal_population GROUP BY region;
What is the minimum age of patients who tested positive for gonorrhea in Canada?
CREATE TABLE patients (id INT,age INT,gender TEXT,state TEXT,disease TEXT); INSERT INTO patients (id,age,gender,state,disease) VALUES (1,20,'Female','Canada','Gonorrhea'); INSERT INTO patients (id,age,gender,state,disease) VALUES (2,35,'Male','Canada','Gonorrhea');
SELECT MIN(age) FROM patients WHERE state = 'Canada' AND disease = 'Gonorrhea';
What is the total biomass of fish in the fish_stock table?
CREATE TABLE fish_stock (species VARCHAR(50),biomass INT); INSERT INTO fish_stock (species,biomass) VALUES ('Tilapia',500),('Tilapia',700),('Salmon',800);
SELECT SUM(biomass) FROM fish_stock;
Which agricultural innovation metrics have been implemented in the 'Plateau Central' region, and what are their respective metric values?
CREATE TABLE regions (region_id INT,region_name VARCHAR(255)); CREATE TABLE metrics (metric_id INT,metric_name VARCHAR(255),region_id INT,metric_value INT);
SELECT m.metric_name, m.metric_value FROM regions r JOIN metrics m ON r.region_id = m.region_id WHERE r.region_name = 'Plateau Central';
What is the total revenue generated by sustainable tourism in Kenya?
CREATE TABLE tourism_revenue (revenue_id INT,revenue_amount INT,revenue_source TEXT); INSERT INTO tourism_revenue (revenue_id,revenue_amount,revenue_source) VALUES (1,8000000,'Sustainable Tourism'),(2,9000000,'Cultural Tourism'),(3,1000000,'Virtual Tourism');
SELECT SUM(revenue_amount) FROM tourism_revenue WHERE revenue_source = 'Sustainable Tourism' AND country = 'Kenya';
Show the number of athletes in each sport with the highest and lowest average salaries.
CREATE TABLE salaries(athlete_id INT,name VARCHAR(50),sport VARCHAR(20),salary INT);
SELECT sport, COUNT(*) FROM salaries WHERE salary IN (SELECT MAX(salary) FROM salaries GROUP BY sport) OR salary IN (SELECT MIN(salary) FROM salaries GROUP BY sport) GROUP BY sport;
Update the salary of an employee in the HR department
CREATE SCHEMA hr; CREATE TABLE employees (id INT,name VARCHAR(50),department VARCHAR(50),salary DECIMAL(10,2)); INSERT INTO employees (id,name,department,salary) VALUES (1,'John Doe','IT',70000.00),(2,'Jane Smith','IT',75000.00),(3,'Mike Johnson','HR',60000.00);
UPDATE employees SET salary = 70000.00 WHERE name = 'Mike Johnson' AND department = 'HR';
What is the average weight of cargo for each vessel?
CREATE TABLE vessels (vessel_id INT,vessel_name VARCHAR(255)); INSERT INTO vessels (vessel_id,vessel_name) VALUES (1,'Vessel1'),(2,'Vessel2'),(3,'Vessel3'),(4,'Vessel4'); CREATE TABLE cargo (cargo_id INT,vessel_id INT,weight FLOAT); INSERT INTO cargo (cargo_id,vessel_id,weight) VALUES (1,1,3000),(2,1,5000),(3,2,8000),(4,2,6000),(5,3,4000),(6,4,9000),(7,1,7000);
SELECT vessels.vessel_name, AVG(cargo.weight) FROM vessels INNER JOIN cargo ON vessels.vessel_id = cargo.vessel_id GROUP BY vessels.vessel_name;
What is the average number of virtual tours in each city in Europe?
CREATE TABLE cities (city_id INT,name VARCHAR(255),country VARCHAR(255)); CREATE TABLE virtual_tours (tour_id INT,city_id INT,type VARCHAR(255));
SELECT c.name, AVG(COUNT(vt.tour_id)) as avg_tours FROM cities c LEFT JOIN virtual_tours vt ON c.city_id = vt.city_id WHERE c.country LIKE 'Europe%' GROUP BY c.name;
What is the total revenue generated by each train line in Tokyo during rush hour?
CREATE TABLE trains (route_id INT,fare DECIMAL(5,2)); CREATE TABLE routes (route_id INT,line VARCHAR(10)); CREATE TABLE schedules (route_id INT,hour INT);
SELECT r.line, SUM(t.fare) FROM trains t JOIN routes r ON t.route_id = r.route_id JOIN schedules s ON t.route_id = s.route_id WHERE s.hour BETWEEN 7 AND 9 GROUP BY r.line;
What is the total mass of space debris objects in low Earth orbits?
CREATE TABLE debris_mass (id INT,object_name VARCHAR(255),orbit_type VARCHAR(255),mass FLOAT);
SELECT SUM(mass) FROM debris_mass WHERE orbit_type = 'low Earth';
What is the total assets value for Shariah-compliant financial institutions in the Middle East, with more than 50 branches?
CREATE TABLE shariah_compliant_finance (id INT,institution_name VARCHAR(255),region VARCHAR(255),branches INT,assets_value INT);
SELECT SUM(assets_value) FROM shariah_compliant_finance WHERE region = 'Middle East' AND branches > 50;
What is the maximum R&D expenditure for drugs approved between 2015 and 2020?
CREATE TABLE rd_expenditure (drug_id VARCHAR(10),approval_year INT,expenditure NUMERIC(12,2));
SELECT MAX(expenditure) FROM rd_expenditure WHERE approval_year BETWEEN 2015 AND 2020;
What is the total production of crops in organic farms?
CREATE TABLE organic_farms (id INT,name VARCHAR(50),location VARCHAR(50),crop VARCHAR(50),production INT); INSERT INTO organic_farms (id,name,location,crop,production) VALUES (1,'Farm 1','US','Corn',1000),(2,'Farm 1','US','Wheat',1500),(3,'Farm 2','Canada','Soybean',2000),(4,'Farm 2','Canada','Barley',2500);
SELECT SUM(production) FROM organic_farms WHERE crop IS NOT NULL;
What is the total play time and player count for each game in the 'Role-playing' genre, grouped by platform?
CREATE TABLE Games (Id INT,Name VARCHAR(100),Genre VARCHAR(50),Platform VARCHAR(50),PlayTime FLOAT,Players INT); INSERT INTO Games VALUES (1,'GameA','Role-playing','PC',120,5000),(2,'GameB','Simulation','Console',150,7000),(3,'GameC','Role-playing','Console',90,3000),(4,'GameD','Strategy','PC',105,6000),(5,'GameE','Role-playing','VR',180,8000),(6,'GameF','Strategy','Console',110,4000);
SELECT Platform, Genre, SUM(PlayTime) AS Total_Play_Time, COUNT(*) AS Player_Count FROM Games WHERE Genre = 'Role-playing' GROUP BY Platform, Genre;
What is the average rating of eco-friendly hotels in Rome?
CREATE TABLE eco_hotels_italy (hotel_id INT,name TEXT,city TEXT,rating FLOAT); INSERT INTO eco_hotels_italy (hotel_id,name,city,rating) VALUES (1,'Eco Hotel Rome','Rome',8.0),(2,'Green Hotel Rome','Rome',8.5);
SELECT AVG(rating) FROM eco_hotels_italy WHERE city = 'Rome';
Insert a new contractor with "contractor_id" 1001, "name" "ABC Construction", "location" "New York, NY", and "license_number" "1234567890" into the "Contractors" table.
CREATE TABLE Contractors (contractor_id INT,name VARCHAR(255),location VARCHAR(255),license_number VARCHAR(50));
INSERT INTO Contractors (contractor_id, name, location, license_number) VALUES (1001, 'ABC Construction', 'New York, NY', '1234567890');
How many crimes were committed by each type in the last month?
CREATE TABLE crimes (cid INT,crime_type TEXT,committed_date TEXT); INSERT INTO crimes VALUES (1,'Theft','2022-01-05'); INSERT INTO crimes VALUES (2,'Burglary','2022-02-10'); INSERT INTO crimes VALUES (3,'Vandalism','2022-03-01'); INSERT INTO crimes VALUES (4,'Theft','2022-03-15');
SELECT crime_type, COUNT(*) FROM crimes WHERE committed_date >= DATEADD(month, -1, GETDATE()) GROUP BY crime_type;
What are the product names and their ratings for products with a rating greater than 4.5?
CREATE TABLE products (product_id INT,product_name TEXT,rating FLOAT); INSERT INTO products (product_id,product_name,rating) VALUES (1,'Product A',4.5),(2,'Product B',4.2),(3,'Product C',4.8);
SELECT product_name, rating FROM products WHERE rating > 4.5;
What are the production figures for well 'W012' located in the East Siberian Sea?
CREATE TABLE wells (well_id varchar(10),region varchar(20),production_figures int); INSERT INTO wells (well_id,region,production_figures) VALUES ('W012','East Siberian Sea',4500);
SELECT production_figures FROM wells WHERE well_id = 'W012' AND region = 'East Siberian Sea';
What is the total quantity of product A sold in New York in the last month?
CREATE TABLE sales(product_id VARCHAR(20),store_location VARCHAR(20),sale_date DATE,quantity INTEGER); INSERT INTO sales (product_id,store_location,sale_date,quantity) VALUES ('Product A','New York','2021-10-01',10),('Product A','New York','2021-10-02',15);
SELECT SUM(quantity) FROM sales WHERE product_id = 'Product A' AND store_location = 'New York' AND sale_date BETWEEN DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH) AND CURRENT_DATE;
Which mobile customers in Florida have a data usage less than 3.5 GB?
CREATE TABLE mobile_customers_fl (customer_id INT,data_usage FLOAT,state VARCHAR(50)); INSERT INTO mobile_customers_fl (customer_id,data_usage,state) VALUES (11,3.2,'FL'),(12,4.8,'FL'),(13,2.1,'FL'),(14,5.9,'FL'),(15,3.7,'FL');
SELECT customer_id FROM mobile_customers_fl WHERE data_usage < 3.5 AND state = 'FL';
List all operators and their average gas production per well in the Gulf of Mexico
CREATE TABLE operators (operator_id INT,operator_name TEXT); INSERT INTO operators (operator_id,operator_name) VALUES (1,'Operator A'),(2,'Operator B'); CREATE TABLE wells (well_id INT,operator_id INT,year INT,gas_production FLOAT); INSERT INTO wells (well_id,operator_id,year,gas_production) VALUES (1,1,2020,500000),(2,1,2021,600000),(3,2,2020,700000),(4,2,2021,800000);
SELECT o.operator_name, AVG(w.gas_production / NULLIF(w.year, 0)) AS avg_gas_production_per_well FROM wells w JOIN operators o ON w.operator_id = o.operator_id WHERE o.operator_name IN ('Operator A', 'Operator B') AND w.year BETWEEN (SELECT MAX(year) - 5 FROM wells) AND MAX(year) GROUP BY o.operator_id;
How many Mexican movies have a rating higher than 8?
CREATE TABLE mexican_movies (id INT,title VARCHAR(255),rating FLOAT); INSERT INTO mexican_movies (id,title,rating) VALUES (1,'Movie1',8.5),(2,'Movie2',7.8),(3,'Movie3',8.2);
SELECT COUNT(*) FROM mexican_movies WHERE rating > 8;
What is the total number of marine species discovered in the Indian Ocean?
CREATE TABLE Species (species_name VARCHAR(50),ocean_name VARCHAR(50)); INSERT INTO Species (species_name,ocean_name) VALUES ('Species A','Indian Ocean'),('Species B','Indian Ocean');
SELECT COUNT(DISTINCT species_name) FROM Species WHERE ocean_name = 'Indian Ocean';
Identify the number of UNESCO World Heritage sites in Japan with a focus on virtual tourism.
CREATE TABLE world_heritage_sites (site_id INT,country VARCHAR(50),unesco_site BOOLEAN,virtual_tour BOOLEAN); INSERT INTO world_heritage_sites (site_id,country,unesco_site,virtual_tour) VALUES (1,'Japan',true,true),(2,'Japan',true,false),(3,'China',true,true);
SELECT COUNT(*) FROM world_heritage_sites whs WHERE whs.country = 'Japan' AND whs.unesco_site = true AND whs.virtual_tour = true;
How many patients in South Africa were diagnosed with Hepatitis B in 2019?
CREATE TABLE Patients (ID INT,Gender VARCHAR(10),Disease VARCHAR(20),Country VARCHAR(30),Diagnosis_Date DATE); INSERT INTO Patients (ID,Gender,Disease,Country,Diagnosis_Date) VALUES (1,'Male','Hepatitis B','South Africa','2019-01-01');
SELECT COUNT(*) FROM Patients WHERE Disease = 'Hepatitis B' AND Country = 'South Africa' AND YEAR(Diagnosis_Date) = 2019;
Update the names of all authors from the 'Freelance' category to 'Independent Contributor'.
CREATE TABLE authors (id INT,name TEXT,category TEXT); INSERT INTO authors (id,name,category) VALUES (1,'Jane Doe','Freelance');
UPDATE authors SET category = 'Independent Contributor' WHERE category = 'Freelance';