sql_prompt
stringlengths
34
182
sql_context
stringlengths
67
736
sql
stringlengths
33
423
sql_explanation
stringlengths
79
722
Insert new records for the rare earth elements gadolinium and terbium into the production table
CREATE TABLE production ( id INT PRIMARY KEY, element VARCHAR(10), quantity INT, production_date DATE);
INSERT INTO production (element, quantity, production_date) VALUES ('gadolinium', 150, '2015-03-17'), ('terbium', 200, '2016-06-23');
This SQL query inserts two new records into the production table for the rare earth elements gadolinium and terbium. It uses the INSERT INTO statement and specifies the production table and the columns to insert data into. The VALUES clause specifies the data for each column in each new record.
What is the total number of electric vehicles sold in each city in Canada?
CREATE TABLE if not exists EVSales (Id int, Vehicle varchar(100), City varchar(100), Quantity int); INSERT INTO EVSales (Id, Vehicle, City, Quantity) VALUES (1, 'Tesla Model 3', 'Toronto', 1000), (2, 'Nissan Leaf', 'Vancouver', 800), (3, 'Chevrolet Bolt', 'Montreal', 1200), (4, 'Tesla Model X', 'Calgary', 600), (5, 'Te...
SELECT City, SUM(Quantity) FROM EVSales WHERE Country = 'Canada' GROUP BY City;
The query filters the EVSales table for records corresponding to Canada, groups the records by City, and calculates the total number of electric vehicles sold in each city using the SUM function.
What is the change in co-ownership cost per property between consecutive rows, ordered by the 'co_ownership' table's ID?
CREATE TABLE co_ownership (id INT, city VARCHAR(255), co_ownership_cost INT, property_id INT); INSERT INTO co_ownership (id, city, co_ownership_cost, property_id) VALUES (1, 'Seattle', 550000, 101), (2, 'Seattle', 560000, 102), (3, 'Portland', 420000, 103), (4, 'Portland', 430000, 104), (5, 'Portland', 440000, 105);
SELECT id, city, co_ownership_cost, LAG(co_ownership_cost) OVER (PARTITION BY city ORDER BY id) AS previous_co_ownership_cost, co_ownership_cost - LAG(co_ownership_cost) OVER (PARTITION BY city ORDER BY id) AS cost_change FROM co_ownership ORDER BY id;
Calculates the change in co-ownership cost per property between consecutive rows, ordered by the ID of the 'co_ownership' table. Uses a window function to access the previous row's co-ownership cost.
What is the number of repeat attendees for each event type in 2021?
CREATE TABLE Events (EventID INT, EventTypeID INT, EventDate DATE); CREATE TABLE EventAttendance (EventID INT, AudienceID INT); CREATE TABLE Audience (AudienceID INT, AudienceName VARCHAR(50)); INSERT INTO Events (EventID, EventTypeID, EventDate) VALUES (1, 1, '2021-01-01'), (2, 1, '2021-02-01'), (3, 2, '2021-03-01'); ...
SELECT et.EventTypeName, COUNT(DISTINCT ea.AudienceID) as NumRepeatAttendees FROM EventAttendance ea INNER JOIN Events e ON ea.EventID = e.EventID INNER JOIN EventTypes et ON e.EventTypeID = et.EventTypeID INNER JOIN (SELECT AudienceID, COUNT(EventID) as NumEvents FROM EventAttendance GROUP BY AudienceID HAVING COUNT(E...
This query joins the EventAttendance, Events, and EventTypes tables and filters the Events table to only include events that occurred in 2021. It then joins the result with a subquery that identifies repeat attendees and calculates the number of repeat attendees for each event type.
What is the average carbon offset amount for carbon offset programs in the 'Energy Production' sector?
CREATE TABLE Carbon_Offset_Programs (id INT, sector VARCHAR(20), year INT, carbon_offset_amount INT); INSERT INTO Carbon_Offset_Programs (id, sector, year, carbon_offset_amount) VALUES (1, 'Transportation', 2018, 50000), (2, 'Energy Production', 2019, 75000), (3, 'Transportation', 2020, 65000), (4, 'Manufacturing', 202...
SELECT AVG(carbon_offset_amount) FROM Carbon_Offset_Programs WHERE sector = 'Energy Production';
This SQL query calculates the average carbon offset amount for carbon offset programs in the 'Energy Production' sector by using the AVG() function and filtering the results with the WHERE clause.
How many unique one-time donors made donations in 'q4' of '2022'?
CREATE TABLE Donations (id INT, donor_type VARCHAR(10), donation_amount DECIMAL(10,2), donation_date DATE); INSERT INTO Donations (id, donor_type, donation_amount, donation_date) VALUES (1, 'one-time', 50.00, '2022-01-01'); INSERT INTO Donations (id, donor_type, donation_amount, donation_date) VALUES (2, 'recurring', 2...
SELECT COUNT(DISTINCT donor_id) FROM Donations WHERE donor_type = 'one-time' AND QUARTER(donation_date) = 4 AND YEAR(donation_date) = 2022;
This query counts the number of unique donor_ids for one-time donors in the fourth quarter of 2022 by filtering the Donations table for the appropriate donor_type, quarter, and year, and then applying the COUNT function to the distinct donor_ids.
What is the total number of financial transactions made by volunteers?
CREATE TABLE Volunteers (VolunteerID int, VolunteerName varchar(50), VolunteerNationality varchar(50), VolunteerSignUpDate date); CREATE TABLE FinancialTransactions (TransactionID int, TransactionAmount numeric(10,2), TransactionDate date, VolunteerID int); INSERT INTO Volunteers (VolunteerID, VolunteerName, VolunteerN...
SELECT COUNT(*) as TotalTransactions FROM FinancialTransactions INNER JOIN Volunteers ON FinancialTransactions.VolunteerID = Volunteers.VolunteerID;
This SQL query calculates the total number of financial transactions made by volunteers. It uses a JOIN to combine the Volunteers and FinancialTransactions tables and then calculates the total number of transactions using the COUNT function.
Delete users who haven't posted in the last 6 months from the "users" table
CREATE TABLE users (id INT, username VARCHAR(255), last_post_date DATE);
DELETE FROM users WHERE last_post_date < DATE_SUB(CURDATE(), INTERVAL 6 MONTH);
This query deletes records from the "users" table where the "last_post_date" is older than 6 months from the current date.
What's the total number of properties in each city with inclusive housing policies?
CREATE TABLE properties (property_id INT, price DECIMAL(10,2), size INT, city VARCHAR(50), inclusive_policy BOOLEAN); INSERT INTO properties (property_id, price, size, city, inclusive_policy) VALUES (1, 500000, 2000, 'Oakland', true), (2, 600000, 2500, 'San Francisco', false), (3, 450000, 1000, 'Oakland', true);
SELECT city, COUNT(*) FROM properties WHERE inclusive_policy = true GROUP BY city;
The SQL query returns the number of properties in each city that have an inclusive housing policy (represented by the inclusive_policy column). It does this by filtering for rows where inclusive_policy is true, and then grouping by the city column and counting the number of rows in each group.
Identify the total nitrogen levels and farm size for farms using a center pivot irrigation system, located in the Europe region.
CREATE TABLE farm (id INT, name VARCHAR(50), size FLOAT, irrigation_system VARCHAR(20), region VARCHAR(50), PRIMARY KEY(id)); INSERT INTO farm (id, name, size, irrigation_system, region) VALUES (1, 'Farm X', 80.3, 'center pivot', 'Europe'); INSERT INTO farm (id, name, size, irrigation_system, region) VALUES (2, 'Farm Y...
SELECT f.irrigation_system, f.region, SUM(f.size) AS total_area, AVG(n.nitrogen) AS avg_nitrogen FROM farm f INNER JOIN nitrogen n ON f.id = n.farm_id WHERE f.irrigation_system = 'center pivot' AND f.region = 'Europe' GROUP BY f.irrigation_system, f.region;
This query joins the farm and nitrogen tables on their common column farm_id. It filters the results to only show farms using a center pivot irrigation system (f.irrigation_system = 'center pivot') and located in the Europe region (f.region = 'Europe'). Then, it groups the results by irrigation system and region (f.irr...
Count the number of suppliers from the United States.
CREATE TABLE suppliers (id INT PRIMARY KEY, name VARCHAR(255), location VARCHAR(255), sustainable BOOLEAN); INSERT INTO suppliers (id, name, location, sustainable) VALUES (1, 'Eco Friendly', 'California', true);
SELECT COUNT(*) FROM suppliers WHERE location = 'California';
Count the number of suppliers from the United States (California in this case).
What is the latest end date of astronaut medical records in 2012?
CREATE TABLE MedicalRecords (id INT, astronaut_id INT, start_date DATE, end_date DATE); INSERT INTO MedicalRecords (id, astronaut_id, start_date, end_date) VALUES (1, 1, '2010-01-01', '2010-01-10'), (2, 2, '2012-05-01', '2012-12-31');
SELECT MAX(end_date) FROM MedicalRecords WHERE YEAR(end_date) = 2012;
This query retrieves the latest end date of astronaut medical records in 2012 by selecting the MAX function on the end_date column, filtering for rows with the year 2012.
Update records in the agricultural_innovations table with rural_innovation_id 2 to have a year of 2024
CREATE TABLE agricultural_innovations (id INT PRIMARY KEY, rural_innovation_id INT, name VARCHAR(255), description TEXT, year INT);
WITH cte AS (UPDATE agricultural_innovations SET year = 2024 WHERE rural_innovation_id = 2) SELECT * FROM cte;
The CTE updates records with rural_innovation_id 2 in the agricultural_innovations table to have a year of 2024, and then the SELECT statement returns all records from the CTE.
Find properties with size greater than 1500 sq ft in urban_properties table.
CREATE TABLE urban_properties (id INT, size FLOAT, location VARCHAR(255)); INSERT INTO urban_properties (id, size, location) VALUES (1, 1200.0, 'San Francisco'), (2, 1800.0, 'New York'), (3, 1300.0, 'Los Angeles');
SELECT * FROM urban_properties WHERE size > 1500;
This query selects all properties with a size greater than 1500 sq ft in the urban_properties table.
Which onshore wells in the Permian Basin have the highest production rate?
CREATE TABLE wells (well_id INT, well_name VARCHAR(255), well_type VARCHAR(255), location VARCHAR(255)); INSERT INTO wells VALUES (1, 'Well A', 'Offshore', 'Gulf of Mexico'); INSERT INTO wells VALUES (2, 'Well B', 'Onshore', 'Permian Basin');
SELECT well_id, well_name, production_rate FROM (SELECT well_id, well_name, production_rate, row_number() OVER (PARTITION BY well_type ORDER BY production_rate DESC) as rn FROM well_production WHERE well_type = 'Onshore' AND location = 'Permian Basin') WHERE rn = 1;
This query retrieves the onshore wells in the Permian Basin with the highest production rate, using the row_number() function to partition and order the results by production rate.
Calculate the average number of goals per game for the top 2 teams in the Indian Super League
CREATE TABLE teams (id INT PRIMARY KEY, name TEXT, league TEXT, goals_scored INT, goals_conceded INT, games_played INT); INSERT INTO teams (id, name, league, goals_scored, goals_conceded, games_played) VALUES (1, 'Mumbai City FC', 'Indian Super League', 22, 12, 16), (2, 'Hyderabad FC', 'Indian Super League', 20, 12, 16...
SELECT AVG(goals_scored/games_played) FROM (SELECT * FROM teams ORDER BY goals_scored DESC LIMIT 2) AS top_two_teams;
This query first selects the top 2 teams with the most goals scored and then calculates the average number of goals per game for those teams.
Show the total budget allocated to healthcare programs in each department from the 'government_budget' database.
CREATE TABLE departments (id INT PRIMARY KEY, name VARCHAR(255));CREATE TABLE programs (id INT PRIMARY KEY, name VARCHAR(255), department_id INT, FOREIGN KEY (department_id) REFERENCES departments(id), budget INT); INSERT INTO departments (id, name) VALUES (1, 'Health and Human Services'); INSERT INTO departments (id, ...
SELECT departments.name, SUM(programs.budget) as total_budget FROM departments INNER JOIN programs ON departments.id = programs.department_id WHERE programs.name LIKE '%healthcare%' GROUP BY departments.name;
This SQL query performs an inner join between the 'departments' and 'programs' tables on the 'department_id' foreign key. It then filters the results to only include healthcare programs and calculates the total budget allocated to each department.
How many climate mitigation initiatives were launched in Southeast Asia between 2015 and 2020 that involved women-led organizations?
CREATE TABLE climate_initiatives (initiative VARCHAR(50), region VARCHAR(50), start_year INT, end_year INT, gender_focus BOOLEAN); INSERT INTO climate_initiatives (initiative, region, start_year, end_year, gender_focus) VALUES ('Initiative A', 'Southeast Asia', 2015, 2020, TRUE); INSERT INTO climate_initiatives (initia...
SELECT COUNT(*) FROM climate_initiatives WHERE region = 'Southeast Asia' AND start_year BETWEEN 2015 AND 2020 AND gender_focus = TRUE;
This query retrieves the number of climate mitigation initiatives launched in Southeast Asia between 2015 and 2020 that involved women-led organizations. It counts the number of rows where the region is 'Southeast Asia', the start_year is between 2015 and 2020, and the gender_focus is TRUE.
What is the average age of patients who have been diagnosed with diabetes in the rural health clinic located in Texas?
CREATE TABLE rural_clinic (clinic_id INT, location VARCHAR(20), capacity INT); INSERT INTO rural_clinic (clinic_id, location, capacity) VALUES (1, 'Texas', 50); CREATE TABLE patient (patient_id INT, clinic_id INT, age INT, diagnosis VARCHAR(20)); INSERT INTO patient (patient_id, clinic_id, age, diagnosis) VALUES (1, 1,...
SELECT AVG(age) FROM patient WHERE diagnosis = 'diabetes' AND clinic_id = 1;
This query calculates the average age of patients diagnosed with diabetes in the rural clinic located in Texas by using the AVG function on the age column, filtered by the diagnosis and clinic_id.
List the top 3 donor names and their total donation amounts for the 'Education' sector in the 'Americas' region for the year 2019, ordered by the donation amount in descending order.
CREATE TABLE Donors (donor_id INT, donor_name VARCHAR(255), donation_amount INT, sector VARCHAR(255), region VARCHAR(255), donation_date DATE); INSERT INTO Donors (donor_id, donor_name, donation_amount, sector, region, donation_date) VALUES (1, 'DonorB', 125000, 'Education', 'Americas', '2019-01-01');
SELECT donor_name, SUM(donation_amount) AS total_donation FROM Donors WHERE sector = 'Education' AND region = 'Americas' AND donation_date >= '2019-01-01' AND donation_date < '2020-01-01' GROUP BY donor_name ORDER BY total_donation DESC LIMIT 3;
The SQL query filters the Donors table for rows where the sector is 'Education', the region is 'Americas', and the donation_date is in the year 2019. It then groups the filtered results by donor_name and calculates the total donation amount for each group. Finally, it orders the groups by total_donation in descending o...
What is the average CO2 emissions for the garment manufacturing process for each collection?
CREATE TABLE emissions (collection VARCHAR(20), co2_emissions INT); INSERT INTO emissions (collection, co2_emissions) VALUES ('Spring 2021', 10000), ('Fall 2021', 12000), ('Winter 2021', 15000), ('Spring 2022', 18000);
SELECT collection, AVG(co2_emissions) FROM emissions GROUP BY collection;
* This query calculates the average CO2 emissions for the garment manufacturing process for each collection from the emissions table.
Insert a new record into the 'energy_storage' table for a flow battery with 5 MWh capacity, located in 'Quebec'
CREATE TABLE energy_storage (id INT PRIMARY KEY, technology VARCHAR(255), capacity FLOAT, location VARCHAR(255));
INSERT INTO energy_storage (technology, capacity, location) VALUES ('flow', 5, 'Quebec');
This query inserts a new record into the energy_storage table for a flow battery with 5 MWh capacity, located in 'Quebec'. It uses the INSERT INTO statement with the VALUES clause to insert the new record.
What is the total amount donated on Giving Tuesday by donors in the Health industry?
CREATE TABLE donations(id INT, donor_name TEXT, donation_amount FLOAT, donation_date DATE, industry TEXT); INSERT INTO donations(id, donor_name, donation_amount, donation_date, industry) VALUES (1, 'James Lee', 50, '2022-11-29', 'Technology'), (2, 'Grace Kim', 100, '2022-12-01', 'Finance'), (3, 'Anthony Nguyen', 25, '2...
SELECT SUM(donation_amount) FROM donations WHERE donation_date = '2022-11-29' AND industry = 'Health';
This query first selects all donations made on Giving Tuesday (November 29th, 2022) by donors in the 'Health' industry. It then calculates the total donation amount in this filtered set.
What is the maximum safety score for chemical products manufactured in the Asian region?
CREATE TABLE Manufacturers (ManufacturerID INT, ManufacturerName TEXT, Region TEXT); INSERT INTO Manufacturers (ManufacturerID, ManufacturerName, Region) VALUES (1, 'ABC Chemicals', 'Asia'), (2, 'XYZ Chemicals', 'North America'), (3, ' DEF Chemicals', 'Asia'); CREATE TABLE ChemicalProducts (ProductID INT, Chemical TEXT...
SELECT MAX(CP.SafetyScore) AS MaxScore FROM ChemicalProducts CP INNER JOIN Manufacturers M ON CP.ManufacturerID = M.ManufacturerID WHERE M.Region = 'Asia';
The SQL query performs an inner join between the ChemicalProducts and Manufacturers tables, based on the ManufacturerID, and filters for the Asian region. It then calculates the maximum safety score for chemical products manufactured in the Asian region.
Identify cities with the highest citizen feedback ratings and the corresponding number of public services provided in each city.
CREATE TABLE cities (city_id INT, city_name VARCHAR(255), region VARCHAR(255)); CREATE TABLE public_services (service_id INT, service_name VARCHAR(255), city_id INT, rating INT);
SELECT c.city_name, MAX(ps.rating) as max_rating, COUNT(ps.service_id) as num_services FROM cities c JOIN public_services ps ON c.city_id = ps.city_id GROUP BY c.city_name HAVING MAX(ps.rating) >= ALL (SELECT MAX(ps2.rating) FROM public_services ps2 GROUP BY ps2.city_id);
Join the cities and public_services tables, group by city, and filter to show only cities with the highest citizen feedback ratings. Count the number of public services in each city.
What are the ethical AI principles for the technology projects in India?
CREATE TABLE EthicalAI (principle_id INT, principle_name VARCHAR(50), project_location VARCHAR(20)); INSERT INTO EthicalAI (principle_id, principle_name, project_location) VALUES (1, 'Fairness', 'India'), (2, 'Accountability', 'India'), (3, 'Transparency', 'India'), (4, 'Data Minimization', 'India'), (5, 'Explainabilit...
SELECT principle_name FROM EthicalAI WHERE project_location = 'India';
This query retrieves the ethical AI principles for the technology projects in India by selecting the principle_name values where the project_location is India.
List all the unique ports and countries where oil spills have occurred in the last 5 years.
CREATE TABLE oil_spills (id INT, port VARCHAR(30), country VARCHAR(30), date DATE); INSERT INTO oil_spills (id, port, country, date) VALUES (1, 'Port of Los Angeles', 'USA', '2020-01-01'); INSERT INTO oil_spills (id, port, country, date) VALUES (2, 'Port of Rotterdam', 'Netherlands', '2019-08-15');
SELECT DISTINCT port, country FROM oil_spills WHERE date >= DATE_SUB(CURRENT_DATE, INTERVAL 5 YEAR);
The SQL query selects the unique combination of ports and countries from the oil_spills table where the date of the oil spill is within the last 5 years. The DISTINCT keyword is used to ensure that only unique combinations of port and country are returned in the result set.
How many mental health parity complaints were filed in the last 12 months by state?
CREATE TABLE mental_health_parity_complaints (complaint_id INT, complaint_date DATE, state VARCHAR(20)); INSERT INTO mental_health_parity_complaints (complaint_id, complaint_date, state) VALUES (1, '2021-01-01', 'California'), (2, '2021-03-15', 'New York'), (3, '2020-12-31', 'Texas');
SELECT state, COUNT(*) as num_complaints FROM mental_health_parity_complaints WHERE complaint_date >= DATE_SUB(CURRENT_DATE, INTERVAL 12 MONTH) GROUP BY state;
This SQL query counts the number of mental health parity complaints filed in the last 12 months by state. It uses the COUNT function to count the number of complaints and the WHERE clause to filter the results to only include complaints filed in the last 12 months. The query then groups the results by state using the G...
What is the average mental health score for students in traditional courses?
CREATE TABLE students (student_id INT, course_id INT, mental_health_score INT); INSERT INTO students (student_id, course_id, mental_health_score) VALUES (6, 15, 80), (7, 16, 85), (8, 17, 70), (9, 18, 90), (10, 19, 65); CREATE TABLE courses (course_id INT, course_type VARCHAR(20)); INSERT INTO courses (course_id, course...
SELECT AVG(students.mental_health_score) FROM students JOIN courses ON students.course_id = courses.course_id WHERE courses.course_type = 'Traditional';
This query joins the students table with the courses table, filters for traditional courses, and then calculates the average mental health score for students in those courses.
What is the average experience of electrical engineers for each dam project?
CREATE TABLE dams (id INT, name VARCHAR(255), location VARCHAR(255), budget FLOAT, project_manager VARCHAR(255), engineer_specialty VARCHAR(255), engineer_experience INT);
SELECT d.name, AVG(d.engineer_experience) as avg_experience FROM dams d WHERE d.engineer_specialty = 'Electrical' GROUP BY d.name;
This SQL query filters the 'dams' table for rows with 'Electrical' as the engineer_specialty, then calculates the average experience for each dam name, providing an average experience for electrical engineers in each dam project.
What was the average funding for 'Climate Change' initiatives provided by the US in 2021?
CREATE TABLE USFunding (Funder VARCHAR(50), Sector VARCHAR(50), FundingAmount NUMERIC(15,2), Year INT); INSERT INTO USFunding (Funder, Sector, FundingAmount, Year) VALUES ('US', 'Climate Change', 450000, 2021), ('US', 'Climate Change', 500000, 2021), ('US', 'Climate Change', 350000, 2021);
SELECT AVG(FundingAmount) FROM USFunding WHERE Sector = 'Climate Change' AND Year = 2021 AND Funder = 'US';
Calculates the average (AVG) FundingAmount where Sector is 'Climate Change', Year is 2021, and Funder is 'US'.
What is the maximum response time for emergency calls in the city of Los Angeles?
CREATE TABLE emergency_calls (id INT, city VARCHAR(20), response_time INT);
SELECT MAX(response_time) FROM emergency_calls WHERE city = 'Los Angeles';
This SQL query calculates the maximum response time for emergency calls in the city of Los Angeles by using the MAX function on the response_time column and filtering for rows where the city is Los Angeles.
Find the total sales of vendors located in the Midwest region.
CREATE TABLE vendors (vendor_id INT, vendor_name TEXT, region TEXT); INSERT INTO vendors (vendor_id, vendor_name, region) VALUES (1, 'Green Vendors', 'Midwest'); CREATE TABLE sales (sale_id INT, sale_date DATE, vendor_id INT, amount DECIMAL(5,2)); INSERT INTO sales (sale_id, sale_date, vendor_id, amount) VALUES (1, '20...
SELECT SUM(amount) FROM sales JOIN vendors ON sales.vendor_id = vendors.vendor_id WHERE vendors.region = 'Midwest';
The SQL query joins the vendors and sales tables on vendor_id, filters for vendors located in the Midwest region, and then calculates the total sales using the SUM function.
What is the average monthly data usage for mobile subscribers in the city of Dallas?
CREATE TABLE mobile_subscribers (subscriber_id INT, city VARCHAR(255), data_usage_gb DECIMAL(5,2)); INSERT INTO mobile_subscribers (subscriber_id, city, data_usage_gb) VALUES (1, 'Dallas', 12.3), (2, 'Dallas', 10.5), (3, 'Austin', 11.7);
SELECT AVG(data_usage_gb) FROM mobile_subscribers WHERE city = 'Dallas';
The SQL query calculates the average (AVG) of the data_usage_gb column for rows with a city value of 'Dallas'.
Add a new treatment type 'art therapy' for patient 5 in Canada
CREATE SCHEMA mental_health; USE mental_health; CREATE TABLE patients (patient_id INT, diagnosis VARCHAR(50), age INT, country VARCHAR(50)); CREATE TABLE treatments (treatment_id INT, patient_id INT, treatment_type VARCHAR(50), treatment_date DATE, country VARCHAR(50)); INSERT INTO patients VALUES (5, 'depression', 45,...
INSERT INTO treatments VALUES (9, 5, 'art therapy', '2022-03-20', 'Canada');
This query inserts a new record into the treatments table with a treatment_id of 9, a patient_id of 5, a treatment_type of 'art therapy', a treatment_date of '2022-03-20', and a country of 'Canada'.
What is the average price of vegan cosmetics in the US?
CREATE TABLE cosmetics (product_id INT, product_name VARCHAR(50), is_vegan BOOLEAN, price FLOAT, country VARCHAR(50));
SELECT AVG(price) FROM cosmetics WHERE is_vegan = TRUE AND country = 'USA';
This query calculates the average price of vegan cosmetics sold in the US. It does this by averaging the 'price' column of all records in the 'cosmetics' table where the 'is_vegan' column is set to true and the 'country' column is set to 'USA'.
What is the minimum budget allocated for the 'Education' department in the year 2022?
CREATE TABLE Budget(year INT, department VARCHAR(20), amount INT); INSERT INTO Budget VALUES (2021, 'Healthcare', 7000000), (2021, 'Education', 5000000), (2022, 'Healthcare', 7800000), (2022, 'Education', 5300000), (2022, 'Education', 4800000);
SELECT MIN(amount) FROM Budget WHERE department = 'Education' AND year = 2022;
This query calculates the minimum budget allocated for the 'Education' department in the year 2022 by finding the minimum 'amount' column value where 'year' is 2022 and 'department' is 'Education'.
What is the total number of crime incidents reported in each sector, sorted by the number of incidents in descending order?
CREATE TABLE sector (id INT, name TEXT, location TEXT); INSERT INTO sector (id, name, location) VALUES (1, 'Sector A', 'Downtown'), (2, 'Sector B', 'Uptown'); CREATE TABLE incidents (id INT, sector_id INT, type TEXT, timestamp DATETIME); INSERT INTO incidents (id, sector_id, type, timestamp) VALUES (1, 1, 'Theft', '202...
SELECT sector.name, COUNT(incidents.id) AS incident_count FROM sector LEFT JOIN incidents ON sector.id = incidents.sector_id GROUP BY sector.name ORDER BY incident_count DESC;
The SQL query joins the 'sector' and 'incidents' tables on the 'sector_id' column and then groups the results by sector name. The COUNT function is used to count the number of incidents for each sector, and the results are sorted in descending order based on the number of incidents.
Which vessels have been involved in accidents in the Pacific Ocean?
CREATE TABLE vessels (vessel_id INT, name VARCHAR(100)); CREATE TABLE maritime_accidents (accident_id INT, vessel_id INT, country VARCHAR(100), ocean VARCHAR(100)); INSERT INTO vessels (vessel_id, name) VALUES (1, 'Sea Serpent'); INSERT INTO maritime_accidents (accident_id, vessel_id, country, ocean) VALUES (1, 1, 'Can...
SELECT vessels.name FROM vessels INNER JOIN maritime_accidents ON vessels.vessel_id = maritime_accidents.vessel_id WHERE maritime_accidents.ocean = 'Pacific Ocean';
This query joins the vessels and maritime_accidents tables on the vessel_id column and filters the results based on the ocean column. It then selects the names of the vessels that have been involved in accidents in the Pacific Ocean.
What is the total metal waste generation in Rio de Janeiro in 2021?
CREATE TABLE waste_generation (city VARCHAR(50), waste_type VARCHAR(50), generation_quantity INT, generation_date DATE); INSERT INTO waste_generation (city, waste_type, generation_quantity, generation_date) VALUES ('Rio de Janeiro', 'Metal', 900, '2021-01-01'), ('Rio de Janeiro', 'Organic', 1200, '2021-01-01'), ('Rio d...
SELECT SUM(generation_quantity) FROM waste_generation WHERE city = 'Rio de Janeiro' AND waste_type = 'Metal' AND generation_date >= '2021-01-01' AND generation_date <= '2021-12-31';
This SQL query calculates the total metal waste generation in Rio de Janeiro in 2021. It sums the generation_quantity for records where the city is 'Rio de Janeiro', waste_type is 'Metal', and the generation_date falls within the range of January 1, 2021 to December 31, 2021.
What are the names of the vessels that have complied with maritime law in the Pacific Ocean in the last 3 years?
CREATE TABLE vessels (vessel_name TEXT, compliance_status TEXT, ocean TEXT, year INT); INSERT INTO vessels (vessel_name, compliance_status, ocean, year) VALUES ('VesselA', 'compliant', 'Pacific', 2020), ('VesselB', 'non-compliant', 'Pacific', 2020), ('VesselC', 'compliant', 'Pacific', 2020), ('VesselA', 'compliant', 'P...
SELECT DISTINCT vessel_name FROM vessels WHERE compliance_status = 'compliant' AND ocean = 'Pacific' AND year BETWEEN 2019 AND 2021;
This query lists the names of the vessels that have complied with maritime law in the Pacific Ocean in the last 3 years by selecting the DISTINCT vessel_name column values where compliance_status is 'compliant', ocean is 'Pacific', and year is between 2019 and 2021.
What is the total revenue for 'Italian' category in '2023'?
CREATE TABLE RestaurantRevenue (category VARCHAR(20), year INT, revenue FLOAT); INSERT INTO RestaurantRevenue (category, year, revenue) VALUES ('Italian', 2023, 25000.00),('Italian', 2023, 28000.00),('Italian', 2023, 30000.00);
SELECT SUM(revenue) FROM RestaurantRevenue WHERE category = 'Italian' AND year = 2023;
The SQL query calculates the total revenue for the 'Italian' category in '2023' by summing the revenue values where the category is 'Italian' and the year is 2023.
What is the average carbon price in the 'carbon_prices' table, grouped by region?
CREATE TABLE carbon_prices (id INT, region VARCHAR(50), price FLOAT); INSERT INTO carbon_prices (id, region, price) VALUES (1, 'EU', 25), (2, 'US', 40), (3, 'EU', 22), (4, 'US', 38), (5, 'EU', 28);
SELECT c.region, AVG(c.price) as avg_price FROM carbon_prices c GROUP BY c.region;
This SQL query calculates the average carbon price in the 'carbon_prices' table by grouping the records based on the 'region' column and calculating the average of the 'price' column values for each group.
Count the number of products in the 'grocery' category
CREATE TABLE products (product_id INT, category VARCHAR(20), quantity INT); INSERT INTO products (product_id, category, quantity) VALUES (1, 'grocery', 10), (2, 'grocery', 20), (3, 'grocery', 30);
SELECT COUNT(*) FROM products WHERE category = 'grocery';
This SQL query counts the number of products in the 'grocery' category by selecting all columns (indicated by the *) from the 'products' table where the category is 'grocery' and counting the number of rows returned.
How many fair labor practice violations have been reported for each region in the ethical fashion industry?
CREATE TABLE labor_practices_violations (region VARCHAR(50), violations INT); INSERT INTO labor_practices_violations (region, violations) VALUES ('Africa', 250), ('Asia', 300), ('Latin America', 200);
SELECT region, violations FROM labor_practices_violations GROUP BY region;
This SQL query groups fair labor practice violations by region in the ethical fashion industry by selecting the 'region' and 'violations' columns in the 'labor_practices_violations' table and grouping the results by the 'region' column.
What is the total budget allocated for housing and transportation services in 2021 across all regions, excluding the South?
CREATE TABLE Budget (Year INT, Service VARCHAR(20), Region VARCHAR(20), Amount DECIMAL(10,2)); INSERT INTO Budget (Year, Service, Region, Amount) VALUES (2021, 'Housing', 'Northeast', 75000.00), (2021, 'Transportation', 'South', 80000.00), (2021, 'Housing', 'West', 90000.00);
SELECT SUM(Amount) FROM Budget WHERE Year = 2021 AND (Service IN ('Housing', 'Transportation') AND Region != 'South');
This query calculates the total budget allocated for housing and transportation services in 2021 by summing the 'Amount' column where the 'Year' is 2021, the 'Service' is either 'Housing' or 'Transportation', and the 'Region' is not 'South'.
What was the total revenue from cannabis-infused edibles sold by each dispensary in the city of San Francisco in the month of December 2021?
CREATE TABLE Dispensaries (id INT, name VARCHAR(255), city VARCHAR(255), state VARCHAR(255));CREATE TABLE Inventory (id INT, dispensary_id INT, revenue DECIMAL(10, 2), product_type VARCHAR(255), month INT, year INT);INSERT INTO Dispensaries (id, name, city, state) VALUES (1, 'Golden Gate Greens', 'San Francisco', 'CA')...
SELECT d.name, SUM(i.revenue) as total_revenue FROM Dispensaries d JOIN Inventory i ON d.id = i.dispensary_id WHERE d.city = 'San Francisco' AND i.product_type = 'edibles' AND i.month = 12 AND i.year = 2021 GROUP BY d.name;
This query joins the Dispensaries and Inventory tables on the dispensary_id and dispensary.id foreign keys. It then filters for cannabis-infused edible sales in San Francisco in December 2021, and groups by dispensary name to calculate the total revenue from cannabis-infused edibles sold by each dispensary.
What is the total amount of climate finance invested in renewable energy projects by public and private sectors in Africa?
CREATE TABLE renewable_energy_projects (project_id INT, sector TEXT, investor_type TEXT, region TEXT, amount FLOAT); INSERT INTO renewable_energy_projects (project_id, sector, investor_type, region, amount) VALUES (1, 'Renewable Energy', 'Public', 'Africa', 5000000); INSERT INTO renewable_energy_projects (project_id, s...
SELECT SUM(amount) FROM renewable_energy_projects WHERE sector = 'Renewable Energy' AND region = 'Africa';
This query calculates the total amount of climate finance invested in renewable energy projects in Africa by summing up the 'amount' column values for the rows with the sector 'Renewable Energy' and region 'Africa'.
What is the total number of indigenous food systems in Australia?
CREATE TABLE indigenous_food_systems (system_id INT, name TEXT, location TEXT, type TEXT, community TEXT, country TEXT); INSERT INTO indigenous_food_systems (system_id, name, location, type, community, country) VALUES (1, 'Bush Tucker Project', ' rural area', 'gardening', 'Aboriginal community', 'Australia');
SELECT COUNT(*) FROM indigenous_food_systems WHERE country = 'Australia';
This SQL query calculates the total number of indigenous food systems in Australia by counting all rows in the 'indigenous_food_systems' table, filtering by country.
List vegan skincare products with a price below 15 EUR, available in Spain
CREATE TABLE products (product_id INT, product_name TEXT, price DECIMAL(5,2), is_vegan BOOLEAN, country TEXT);
SELECT * FROM products WHERE is_vegan = TRUE AND price < 15 AND country = 'Spain';
1. Select all records from the 'products' table. 2. Filter records for vegan skincare products with a price below 15 EUR and available in Spain.
Delete broadband subscribers who have not used their service in the last 6 months.
CREATE TABLE broadband_subscribers_usage (subscriber_id INT, usage_date DATE); INSERT INTO broadband_subscribers_usage (subscriber_id, usage_date) VALUES (17, '2022-01-02'); INSERT INTO broadband_subscribers_usage (subscriber_id, usage_date) VALUES (18, '2022-02-03');
DELETE FROM broadband_subscribers WHERE subscriber_id NOT IN (SELECT subscriber_id FROM broadband_subscribers_usage WHERE usage_date >= DATE_SUB(CURRENT_DATE, INTERVAL 6 MONTH));
The SQL query first selects all subscriber_ids from the broadband_subscribers_usage table that have usage_date within the last 6 months, then deletes all records from the broadband_subscribers table that are not in the selected list.
What is the change in yield for each crop over time, for a specific farm?
CREATE TABLE farming (id INT, name TEXT, location TEXT, crop TEXT, yield INT, year INT); INSERT INTO farming VALUES (1, 'Smith Farm', 'Colorado', 'Corn', 120, 2020), (2, 'Brown Farm', 'Nebraska', 'Soybeans', 45, 2020), (3, 'Jones Farm', 'Iowa', 'Wheat', 80, 2020), (1, 'Smith Farm', 'Colorado', 'Corn', 130, 2021), (2, '...
SELECT crop, (yield - LAG(yield) OVER (PARTITION BY crop, name ORDER BY year)) as yield_change FROM farming WHERE name = 'Smith Farm';
This query calculates the change in yield for each crop over time for a specific farm by partitioning the farming table by the 'crop' and 'name' columns and then ordering the rows by the 'year' column. The LAG() function is used to access the yield of the previous year for each crop on the specific farm. The yield chan...
What is the minimum ride duration for ride-hailing services in Singapore?
CREATE TABLE ride_hailing (ride_id INT, ride_duration INT); INSERT INTO ride_hailing (ride_id, ride_duration) VALUES (1, 10), (2, 15), (3, 20), (4, 25);
SELECT MIN(ride_duration) as min_duration FROM ride_hailing;
Find the minimum ride duration for ride-hailing services in Singapore by selecting the minimum value of ride_duration from the ride_hailing table.
Which suppliers provide the most "Free-Range Chicken" and "Grass-Fed Beef"?
CREATE TABLE Suppliers(supplier VARCHAR(20), product VARCHAR(20), quantity INT); INSERT INTO Suppliers(supplier, product, quantity) VALUES('Supplier A', 'Free-Range Chicken', 100), ('Supplier B', 'Grass-Fed Beef', 150), ('Supplier A', 'Grass-Fed Beef', 75);
SELECT supplier, product, SUM(quantity) as total_quantity FROM Suppliers GROUP BY supplier, product ORDER BY SUM(quantity) DESC;
This SQL query groups the supplier data by supplier and product and calculates the total quantity of each product supplied. It then orders the results by the total quantity in descending order, to show which suppliers provide the most "Free-Range Chicken" and "Grass-Fed Beef".
What is the average budget for all projects in the infrastructure development database?
CREATE TABLE if not exists Projects (id INT, name VARCHAR(50), type VARCHAR(50), budget DECIMAL(10,2)); INSERT INTO Projects (id, name, type, budget) VALUES (1, 'Seawall', 'Resilience', 5000000.00), (2, 'Floodgate', 'Resilience', 3000000.00), (3, 'Bridge', 'Transportation', 8000000.00), (4, 'Highway', 'Transportation',...
SELECT AVG(budget) FROM Projects;
This query calculates the average budget for all projects in the infrastructure development database by averaging the budget column.
How many drought-impacted regions are in Egypt and their average impact scores?
CREATE TABLE drought_impact_EG (region VARCHAR(50), country VARCHAR(20), impact_score INT); INSERT INTO drought_impact_EG (region, country, impact_score) VALUES ('Region1', 'Egypt', 60), ('Region2', 'Egypt', 70);
SELECT COUNT(*), AVG(impact_score) FROM drought_impact_EG WHERE country = 'Egypt';
The SQL query counts the number of drought-impacted regions and calculates their average impact scores in Egypt by using COUNT(*) and AVG functions for the 'impact_score' column values in the 'Egypt' country.
How many biosensors were developed in 2021?
CREATE TABLE biosensor_development (name TEXT, year INT); INSERT INTO biosensor_development (name, year) VALUES ('BioSensor1', 2020); INSERT INTO biosensor_development (name, year) VALUES ('BioSensor2', 2021);
SELECT COUNT(*) FROM biosensor_development WHERE year = 2021;
The SQL query filters the biosensor_development table for entries in 2021 and then counts the number of records.
What is the maximum daily water usage in MWh for the industrial sector in October 2021?
CREATE TABLE max_daily_water_usage (year INT, month INT, sector VARCHAR(20), day INT, usage FLOAT); INSERT INTO max_daily_water_usage (year, month, sector, day, usage) VALUES (2021, 10, 'industrial', 1, 8000); INSERT INTO max_daily_water_usage (year, month, sector, day, usage) VALUES (2021, 10, 'industrial', 2, 8500); ...
SELECT MAX(usage) FROM max_daily_water_usage WHERE year = 2021 AND month = 10 AND sector = 'industrial';
This query calculates the maximum daily water usage (in MWh) for the industrial sector in October 2021 by selecting the maximum 'usage' value in the max_daily_water_usage table where the year is 2021, month is 10, and sector is 'industrial'.
Find and delete duplicate records in the resource_depletion table
CREATE TABLE resource_depletion (id INT, resource VARCHAR(255), depletion_rate DECIMAL(10,2));
DELETE t1 FROM resource_depletion t1 INNER JOIN (SELECT id, resource, depletion_rate, COUNT(*) FROM resource_depletion GROUP BY resource, depletion_rate HAVING COUNT(*) > 1) t2 ON t1.resource = t2.resource AND t1.depletion_rate = t2.depletion_rate AND t1.id < t2.id;
This query finds and deletes duplicate records in the resource_depletion table based on the resource and depletion_rate columns. It uses a self-join to match records with the same resource and depletion_rate, and then deletes the record with the lower id.
List all the Praseodymium production data from 2018 to 2020
CREATE TABLE production_praseodymium (year INT, quantity INT); INSERT INTO production_praseodymium (year, quantity) VALUES (2015, 800), (2016, 900), (2017, 1000), (2018, 1200), (2019, 1400), (2020, 1600), (2021, 1800);
SELECT * FROM production_praseodymium WHERE year BETWEEN 2018 AND 2020;
This query lists all the production data for Praseodymium from the years 2018 to 2020 by selecting all columns from the production_praseodymium table where the year is between 2018 and 2020.
Delete all comments made by users under 18 years old.
CREATE TABLE comments (id INT, user_id INT, article_id INT, comment TEXT, created_at DATETIME); INSERT INTO comments (id, user_id, article_id, comment, created_at) VALUES (1, 123, 456, 'Great article!', '2021-12-20 15:22:00');
DELETE FROM comments WHERE DATEDIFF('day', created_at, NOW()) < 18 * 365
Delete all comments made by users under 18 years old. Find the difference between the created_at date and the current date (NOW()) for each comment and delete those where this difference is less than 18 years (365 days * 18).
What is the minimum distance traveled by autonomous vehicles in the 'autonomous_vehicles' table, grouped by their 'vehicle_type'?
CREATE TABLE autonomous_vehicles (id INT, vehicle_type VARCHAR(255), manufacturer VARCHAR(255), distance_traveled INT);
SELECT vehicle_type, MIN(distance_traveled) FROM autonomous_vehicles GROUP BY vehicle_type;
The SQL query calculates the minimum distance traveled by autonomous vehicles in the 'autonomous_vehicles' table, grouped by their 'vehicle_type'. It uses the MIN() function to find the minimum distance traveled for each vehicle type and the GROUP BY clause to group the results by vehicle type.
What is the total number of projects in the 'climate_mitigation' table?
CREATE TABLE climate_mitigation (project_id INT, project_name VARCHAR(255), location VARCHAR(255), start_date DATE, end_date DATE);
SELECT COUNT(*) FROM climate_mitigation;
This SQL query counts all records in the 'climate_mitigation' table by using the COUNT(*) function.
Find the average soil moisture reading for each crop type in the month of May for 2021.
CREATE TABLE crop_data (id INT, crop_type VARCHAR(255), soil_moisture INT, measurement_date DATE); INSERT INTO crop_data (id, crop_type, soil_moisture, measurement_date) VALUES (1, 'Corn', 60, '2021-05-01'); INSERT INTO crop_data (id, crop_type, soil_moisture, measurement_date) VALUES (2, 'Soybean', 55, '2021-05-03');
SELECT crop_type, AVG(soil_moisture) as avg_moisture FROM crop_data WHERE measurement_date BETWEEN '2021-05-01' AND '2021-05-31' GROUP BY crop_type;
This query calculates the average soil moisture reading for each crop type in May 2021. It filters the crop_data table for records with measurement dates in May 2021, groups the results by crop_type, and calculates the average soil moisture for each group.
What is the name and production date of the machines in the 'circular_economy' category that have a production date after 2015?
CREATE TABLE machines (id INT, name VARCHAR(255), category VARCHAR(255), production_date DATE); INSERT INTO machines (id, name, category, production_date) VALUES (1, 'ABC Machine', 'circular_economy', '2016-01-01'), (2, 'XYZ Machine', 'circular_economy', '2014-01-01'), (3, 'DEF Machine', 'circular_economy', '2017-01-01...
SELECT name, production_date FROM machines WHERE category = 'circular_economy' AND production_date > '2015-01-01';
This SQL query finds the name and production date of the machines in the 'circular_economy' category that have a production date after 2015 by using the WHERE clause to filter the machines table to only show machines in the 'circular_economy' category that have a production date after 2015.
What is the count of incidents for each type at each location, and what is the percentage of the total count for each location?
CREATE TABLE incidents(id INT, location VARCHAR(255), type VARCHAR(255), timestamp TIMESTAMP);
SELECT location, type, COUNT(*) as incident_count, incident_count * 100.0 / SUM(COUNT(*)) OVER (PARTITION BY location) as percentage FROM incidents GROUP BY location, type;
This query calculates the count of incidents for each type at each location and calculates the percentage of the total count for each location using a window function. The PARTITION BY clause is used to reset the percentage for each location.
Find the difference in technology accessibility scores between the first and last quarters for each region.
CREATE TABLE accessibility (region VARCHAR(50), quarter INT, score INT); INSERT INTO accessibility (region, quarter, score) VALUES ('Americas', 1, 80), ('Americas', 2, 85), ('Americas', 3, 75), ('Americas', 4, 90), ('APAC', 1, 70), ('APAC', 2, 75), ('APAC', 3, 80), ('APAC', 4, 85);
SELECT region, LAG(score, 3) OVER (PARTITION BY region ORDER BY quarter) - score as diff FROM accessibility;
The SQL query uses the LAG() function with a window of 3 to get the technology accessibility score of the first quarter for each region. It then calculates the difference between the score of the first quarter and the score of the last quarter.
What is the maximum cost of a defense contract in Japan?
CREATE TABLE defense_contracts (id INT, country VARCHAR(50), cost FLOAT); INSERT INTO defense_contracts (id, country, cost) VALUES (1, 'Japan', 1750000), (2, 'Japan', 700000), (3, 'Japan', 1100000);
SELECT MAX(cost) FROM defense_contracts WHERE country = 'Japan';
This query finds the maximum cost of a defense contract in Japan by selecting the MAX function on the cost column, filtering the data where the country is Japan.
How many works were exhibited in the year 1950?
CREATE TABLE exhibitions (exhibition_id INT PRIMARY KEY, exhibition_name TEXT, year INT, location TEXT);CREATE TABLE exhibits (exhibit_id INT PRIMARY KEY, work_id INT, exhibition_id INT, FOREIGN KEY (work_id) REFERENCES works(work_id), FOREIGN KEY (exhibition_id) REFERENCES exhibitions(exhibition_id));INSERT INTO exhib...
SELECT COUNT(*) FROM exhibits e JOIN exhibitions ex ON e.exhibition_id = ex.exhibition_id WHERE ex.year = 1950;
The SQL query joins the exhibits and exhibitions tables on the exhibition_id foreign key. It then filters for exhibitions in the year 1950 and counts the number of corresponding exhibit records.
What is the average carbon sequestration per hectare for each region?
CREATE TABLE carbon_sequestration(region VARCHAR(255), sequestration FLOAT, area INT); INSERT INTO carbon_sequestration(region, sequestration, area) VALUES ('North', 5.6, 1000), ('South', 4.8, 1500), ('East', 6.2, 1200), ('West', 5.1, 1800);
SELECT region, AVG(sequestration) FROM carbon_sequestration;
The SQL query calculates the average carbon sequestration per hectare by dividing the total sequestration by the total area for each region using the AVG() function.
What is the difference in the average duration of closed cases between attorneys in the "criminal_defense" department, ordered by the difference?
CREATE TABLE attorneys (attorney_id INT, name VARCHAR(50), department VARCHAR(50)); INSERT INTO attorneys (attorney_id, name, department) VALUES (1, 'John Doe', 'criminal_defense'); INSERT INTO attorneys (attorney_id, name, department) VALUES (2, 'Jane Smith', 'criminal_defense'); CREATE TABLE cases (case_id INT, attor...
SELECT attorney_id, AVG(duration) - LAG(AVG(duration)) OVER (PARTITION BY attorney_id ORDER BY attorney_id) as difference FROM cases WHERE status = 'closed' GROUP BY attorney_id ORDER BY difference;
The SQL query calculates the difference in the average duration of closed cases between attorneys in the specified department and orders the results by the difference. The AVG function is used to calculate the average duration of closed cases for each attorney, and the LAG function with the OVER clause is used to get t...
What is the earliest launch date for each space mission?
CREATE TABLE SpaceMission (ID INT, Name VARCHAR(50), LaunchDate DATE);
SELECT Name, MIN(LaunchDate) AS EarliestLaunchDate FROM SpaceMission GROUP BY Name;
This query finds the earliest launch date for each space mission. It uses the MIN function to get the minimum launch date for each mission, grouped by the Name column.
What is the average water consumption in the agricultural sector in Australia for the year 2020?
CREATE TABLE water_consumption_kl (region VARCHAR(20), sector VARCHAR(20), year INT, value FLOAT); INSERT INTO water_consumption_kl (region, sector, year, value) VALUES ('Australia', 'Agricultural', 2020, 12000000);
SELECT AVG(value) FROM water_consumption_kl WHERE sector = 'Agricultural' AND region = 'Australia' AND year = 2020;
This query selects the average value from the water_consumption_kl table where the sector is 'Agricultural' and region is 'Australia' for the year 2020. The average value returned represents the average water consumption in the agricultural sector in Australia for the year 2020.
What is the number of flu cases in each region?
CREATE TABLE flu_cases(id INT, patient_id INT, region TEXT, date DATE);
SELECT region, COUNT(*) FROM flu_cases GROUP BY region;
This query groups flu_cases by region using the GROUP BY clause and then counts the number of flu cases in each region using the COUNT(*) aggregate function.
What is the distribution of trips by mode of transport?
CREATE TABLE trips (user_id INT, trip_date DATE, mode VARCHAR(50), trip_count INT);
SELECT mode, SUM(trip_count) as total_trips FROM trips GROUP BY mode;
The SQL query calculates the distribution of trips by mode of transport by summing the trip_count column and grouping by mode.
Delete records from the safety_records table where the status is 'Failed' and the inspection_date is after '2022-06-01'
CREATE TABLE safety_records (id INT PRIMARY KEY, vessel_id INT, inspection_date DATE, status VARCHAR(255)); INSERT INTO safety_records (id, vessel_id, inspection_date, status) VALUES (1, 1, '2022-03-01', 'Passed'), (2, 2, '2022-06-03', 'Failed'), (3, 3, '2021-03-01', 'Passed');
DELETE FROM safety_records WHERE status = 'Failed' AND inspection_date > '2022-06-01';
* The DELETE statement is used to remove records from the safety_records table.* The WHERE clause filters the records based on the status and inspection_date columns.* The condition status = 'Failed' AND inspection_date > '2022-06-01' selects records with a status of 'Failed' and an inspection_date after 2022-06-01.
Show the top 3 cities with the highest total ticket sales.
CREATE TABLE concerts (id INT, country VARCHAR(255), city VARCHAR(255), artist_name VARCHAR(255), tier VARCHAR(255), price DECIMAL(10,2), num_tickets INT); CREATE VIEW city_sales AS SELECT city, SUM(price * num_tickets) AS total_sales FROM concerts GROUP BY city;
SELECT city, total_sales FROM city_sales ORDER BY total_sales DESC LIMIT 3;
This query shows the top 3 cities with the highest total ticket sales by first creating a view of city and total sales, then selecting city and total sales and sorting by total sales in descending order, and limiting to the top 3 results.
Insert records for a new team, 'Seattle Kraken'
CREATE TABLE players (player_id INT, name VARCHAR(100), position VARCHAR(50), team_id INT); CREATE TABLE teams (team_id INT, name VARCHAR(100), city VARCHAR(100)); INSERT INTO players (player_id, name, position, team_id) VALUES (1, 'John Doe', 'Forward', 1), (2, 'Jane Smith', 'Goalie', 2); INSERT INTO teams (team_id, n...
INSERT INTO teams (team_id, name, city) VALUES (3, 'Seattle Kraken', 'Seattle');
This query inserts a new record into the teams table for the Seattle Kraken, assigning them a team_id of 3.
List all autonomous taxis and their makes, grouped by city, in the 'taxis' table.
CREATE TABLE taxis (id INT, make VARCHAR(20), model VARCHAR(20), year INT, city VARCHAR(20), autonomous BOOLEAN);
SELECT city, make FROM taxis WHERE autonomous = TRUE GROUP BY city;
The SQL query selects the 'city' and 'make' columns from the 'taxis' table where the 'autonomous' column is true, and groups the results by the 'city' column.
What is the total value of surrealist art pieces?
CREATE TABLE ArtPieces (id INT, title VARCHAR(50), galleryId INT, year INT, value INT, style VARCHAR(20)); INSERT INTO ArtPieces (id, title, galleryId, year, value, style) VALUES (1, 'Piece 1', 1, 2000, 10000, 'Impressionism'), (2, 'Piece 2', 1, 2010, 15000, 'Surrealism'), (3, 'Piece 3', 2, 2020, 20000, 'Cubism'), (4, ...
SELECT SUM(value) FROM ArtPieces WHERE style = 'Surrealism';
This query filters art pieces by the 'style' column and selects the sum of the 'value' column where 'style' is 'Surrealism'. It calculates the total value of surrealist art pieces.
What are the total quantities of items shipped to each continent?
CREATE TABLE Shipment (id INT, source_country VARCHAR(255), destination_continent VARCHAR(255), quantity INT); INSERT INTO Shipment (id, source_country, destination_continent, quantity) VALUES (1, 'China', 'Asia', 500), (2, 'United States', 'North America', 300), (3, 'Germany', 'Europe', 200), (4, 'Brazil', 'South Amer...
SELECT destination_continent, SUM(quantity) FROM Shipment GROUP BY destination_continent
This query groups the 'Shipment' table by the 'destination_continent' column and calculates the sum of the 'quantity' column for each group, returning the total quantities shipped to each continent.
What is the maximum speed recorded for vessels in the Baltic Sea, and which vessels achieved this speed?
CREATE TABLE vessel_speed (id INT, vessel_id INT, speed FLOAT, speed_date DATE, speed_location TEXT);
SELECT vessel_id, MAX(speed) FROM vessel_speed WHERE speed_location = 'Baltic Sea' GROUP BY vessel_id HAVING MAX(speed) = (SELECT MAX(speed) FROM vessel_speed WHERE speed_location = 'Baltic Sea');
This query calculates the maximum speed recorded for vessels in the Baltic Sea and the vessels that achieved this speed. It does this by filtering the vessel_speed table for rows where speed_location is 'Baltic Sea' and using the MAX function to find the maximum speed. It then uses the GROUP BY clause to group the rows...
Which female founders have received the most funding?
CREATE TABLE founders (founder_id INT, founder_name VARCHAR(50), gender CHAR(1), startup_id INT); CREATE TABLE startups (startup_id INT, funding_amount INT); INSERT INTO founders VALUES (1, 'Alice', 'F', 1), (2, 'Bob', 'M', 2), (3, 'Charlie', 'M', 3); INSERT INTO startups VALUES (1, 500000), (2, 750000), (3, 300000);
SELECT f.founder_name, SUM(s.funding_amount) as total_funding FROM founders f JOIN startups s ON f.startup_id = s.startup_id WHERE f.gender = 'F' GROUP BY f.founder_name ORDER BY total_funding DESC;
This query calculates the total funding received by female founders by joining the founders and startups tables based on the startup_id and summing up the funding_amount values. The result is ordered in descending order of total funding.
What is the total amount spent on each program type in the year 2019, sorted by the total amount spent in descending order?
CREATE TABLE Programs (ProgramType TEXT, Budget DECIMAL(10,2)); CREATE TABLE Spending (SpendingID INT, ProgramType TEXT, SpendingDate DATE, Amount DECIMAL(10,2));
SELECT P.ProgramType, SUM(S.Amount) as TotalSpending FROM Spending S JOIN Programs P ON S.ProgramType = P.ProgramType WHERE YEAR(SpendingDate) = 2019 GROUP BY P.ProgramType ORDER BY TotalSpending DESC;
This query first joins the Spending and Programs tables on the ProgramType field. It then filters for spending in the year 2019. For each program type, it calculates the total amount spent by summing the Amount field. Finally, it sorts the results by the total amount spent in descending order.
Which community health workers received more than two types of trainings?
CREATE TABLE CommunityHealthWorkerTrainings (WorkerID INT, Training VARCHAR(50)); INSERT INTO CommunityHealthWorkerTrainings (WorkerID, Training) VALUES (1, 'Cultural Competency'), (2, 'Mental Health First Aid'), (3, 'Crisis Prevention'), (4, 'Cultural Competency'), (5, 'Motivational Interviewing'), (1, 'Language Acces...
SELECT WorkerID FROM (SELECT WorkerID, COUNT(DISTINCT Training) as NumTrainings FROM CommunityHealthWorkerTrainings GROUP BY WorkerID) as distinct_trainings WHERE NumTrainings > 2;
This query first groups the CommunityHealthWorkerTrainings table by WorkerID and counts the number of distinct trainings received by each worker. It then filters the results to only include workers who have received more than two types of trainings.
Determine the average engagement time for virtual tours in each city.
CREATE TABLE virtual_tours (tour_id INT, city TEXT, engagement_time FLOAT); INSERT INTO virtual_tours (tour_id, city, engagement_time) VALUES (1, 'Tokyo', 15.5), (2, 'Tokyo', 12.3), (3, 'Osaka', 18.1);
SELECT city, AVG(engagement_time) FROM virtual_tours GROUP BY city;
This SQL query calculates the average engagement time for virtual tours in each city. It first groups the virtual_tours table by city, then calculates the average engagement_time for the matching rows for each group.
What is the average donation amount for each age group?
CREATE TABLE DonorAges (Id INT, AgeGroup VARCHAR(20), DonationAmount DECIMAL(10, 2)); INSERT INTO DonorAges (Id, AgeGroup, DonationAmount) VALUES (1, '18-35', 100.00), (2, '36-50', 150.00), (3, '51-65', 75.00), (4, '18-35', 50.00);
SELECT AgeGroup, AVG(DonationAmount) FROM DonorAges GROUP BY AgeGroup;
This query calculates the average donation amount for each age group by grouping the DonationAmount column by the AgeGroup column and then calculating the average of DonationAmount for each group.
Identify the artist with the most works in the 'Modern Art' gallery.
CREATE TABLE Art (artist TEXT, gallery TEXT, piece_name TEXT); INSERT INTO Art (artist, gallery, piece_name) VALUES ('Picasso', 'Modern Art', 'Guernica'); INSERT INTO Art (artist, gallery, piece_name) VALUES ('Van Gogh', 'Modern Art', 'Starry Night'); INSERT INTO Art (artist, gallery, piece_name) VALUES ('Matisse', 'Mo...
SELECT artist, COUNT(piece_name) AS piece_count FROM Art WHERE gallery = 'Modern Art' GROUP BY artist ORDER BY piece_count DESC LIMIT 1;
This SQL query identifies the artist with the most works in the 'Modern Art' gallery by selecting the artist column and using the COUNT function to count the number of piece_name entries for each artist. It filters the Art table to only include rows where the gallery column is equal to 'Modern Art' and groups the resul...
How many vendors offer gluten-free options in the downtown area?
CREATE TABLE VendorLocation (VendorID INT, Location VARCHAR(50)); INSERT INTO VendorLocation (VendorID, Location) VALUES (1, 'Downtown'), (2, 'Uptown'); CREATE TABLE MenuItems (MenuItemID INT, VendorID INT, MenuItemName VARCHAR(50), MenuItemType VARCHAR(50), GlutenFree VARCHAR(5)); INSERT INTO MenuItems (MenuItemID, Ve...
SELECT COUNT(*) FROM MenuItems WHERE VendorID IN (SELECT VendorID FROM VendorLocation WHERE Location = 'Downtown') AND GlutenFree = 'Yes';
This query calculates the number of vendors that offer gluten-free options in the downtown area by counting all records (COUNT*) in the MenuItems table where VendorID is in the VendorLocation table with Location 'Downtown' and GlutenFree is 'Yes'.
Delete all records from the CoralReefs table that represent reefs with a health status of "Degraded".
CREATE TABLE CoralReefs (Name VARCHAR(255), Location VARCHAR(255), Health_Status VARCHAR(255)); INSERT INTO CoralReefs (Name, Location, Health_Status) VALUES ('Great Barrier Reef', 'Australia', 'Degraded'), ('Palau Reef', 'Palau', 'Healthy'), ('Belize Barrier Reef', 'Belize', 'Vulnerable');
DELETE FROM CoralReefs WHERE Health_Status = 'Degraded';
The SQL query deletes all records from the CoralReefs table that represent reefs with a health status of "Degraded". It uses the WHERE clause to specifically target reefs with a degraded health status.
What is the average severity of vulnerabilities in the 'Malware' category?
CREATE TABLE vulnerabilities (id INT, name TEXT, category TEXT, severity TEXT, date_discovered DATE); INSERT INTO vulnerabilities (id, name, category, severity, date_discovered) VALUES (1, 'Remote Code Execution', 'Malware', 'Critical', '2022-01-01');
SELECT AVG(severity = 'Critical') + AVG(severity = 'High') * 0.75 + AVG(severity = 'Medium') * 0.5 + AVG(severity = 'Low') * 0.25 as average FROM vulnerabilities WHERE category = 'Malware';
This query calculates the average severity of vulnerabilities in the 'Malware' category. It uses the CASE statement to assign a weight to each severity level (Critical = 1, High = 0.75, Medium = 0.5, Low = 0.25). The query then calculates the average weight for all vulnerabilities in the 'Malware' category.
What is the average carbon footprint of products manufactured in each region?
CREATE TABLE regions (id INT, name TEXT); CREATE TABLE manufacturers (id INT, name TEXT, region_id INT, carbon_footprint INT); INSERT INTO regions (id, name) VALUES (1, 'Region 1'), (2, 'Region 2'), (3, 'Region 3'); INSERT INTO manufacturers (id, name, region_id, carbon_footprint) VALUES (1, 'Manufacturer 1', 1, 50), (...
SELECT regions.name, AVG(manufacturers.carbon_footprint) FROM regions INNER JOIN manufacturers ON regions.id = manufacturers.region_id GROUP BY regions.name;
The SQL query calculates the average carbon footprint of products manufactured in each region by performing an inner join between the regions and manufacturers table on the region_id column and grouping the rows by the name column in the regions table. It then computes the average of the carbon_footprint column from th...
Which cities have donors but no active programs?
CREATE TABLE Donors (id INT, donor_name VARCHAR(50), email VARCHAR(50), city VARCHAR(50)); INSERT INTO Donors (id, donor_name, email, city) VALUES (3, 'Maria Garcia', 'mariagarcia@example.com', 'Miami'), (4, 'Hiroshi Tanaka', 'hiroshitanaka@example.com', 'San Francisco'); CREATE TABLE Programs (id INT, program_name VAR...
SELECT city FROM Donors WHERE city NOT IN (SELECT city FROM Programs);
This query returns the cities of donors who live in cities without active programs by using the NOT IN operator to filter cities not present in the Programs table.
What is the average recycling rate in the state of California for the year 2020?
CREATE TABLE recycling_rates (state VARCHAR(20), year INT, recycling_rate FLOAT); INSERT INTO recycling_rates (state, year, recycling_rate) VALUES ('California', 2020, 55.5);
SELECT recycling_rate FROM recycling_rates WHERE state = 'California' AND year = 2020;
This query filters the recycling_rates table to the state of California and the year 2020 and returns the recycling rate.
What is the average delivery time for shipments to the Southeast region, grouped by shipment type?
CREATE SCHEMA IF NOT EXISTS logistics;CREATE TABLE IF NOT EXISTS shipments (shipment_id INT,region VARCHAR(20),shipment_type VARCHAR(20),delivery_time INT);INSERT INTO shipments (shipment_id, region, shipment_type, delivery_time) VALUES (1, 'Southeast', 'domestic', 3), (2, 'Northeast', 'international', 7), (3, 'Southea...
SELECT shipment_type, AVG(delivery_time) FROM logistics.shipments WHERE region = 'Southeast' GROUP BY shipment_type;
This query calculates the average delivery time for shipments to the Southeast region, grouped by shipment type. It does this by filtering the shipments table to only include rows where the region is 'Southeast'. It then calculates the average delivery time for each shipment type by grouping the results by shipment_typ...
What are the items with low stock levels and their cost that are not supplied by 'XYZ Corporation'?
CREATE TABLE Suppliers (SupplierID INT, Name VARCHAR(50), Item VARCHAR(50), Quantity INT, Cost DECIMAL(5,2)); CREATE VIEW LowStock AS SELECT SupplierID, Item FROM Suppliers WHERE Quantity < 10;
SELECT Suppliers.Item, Suppliers.Cost FROM Suppliers JOIN LowStock ON Suppliers.SupplierID = LowStock.SupplierID WHERE Suppliers.Name != 'XYZ Corporation';
This query first creates a view called LowStock that includes only the SupplierID and Item fields for suppliers who have less than 10 units of a given item. Then, it joins the Suppliers table with the LowStock view on the SupplierID field and filters for rows where the Suppliers.Name field is not equal to 'XYZ Corporat...
What is the count of bridges in California with seismic retrofit needs, categorized by bridge type and construction year?
CREATE TABLE Bridges (id INT, state VARCHAR(2), bridge_type VARCHAR(10), construction_year INT, seismic_retrofit_need BOOLEAN); INSERT INTO Bridges (id, state, bridge_type, construction_year, seismic_retrofit_need) VALUES (1, 'CA', 'Beam', 1960, TRUE), (2, 'CA', 'Arch', 1990, FALSE), (3, 'CA', 'Suspension', 2010, TRUE)...
SELECT bridge_type, construction_year, COUNT(*) as count FROM Bridges WHERE state = 'CA' AND seismic_retrofit_need = TRUE GROUP BY bridge_type, construction_year;
This query calculates the count of bridges in California with seismic retrofit needs, categorized by bridge type and construction year. It groups the data by bridge type and construction year, then calculates the count for each group.
Find the total budget allocated for public services in each state.
CREATE SCHEMA gov_data;CREATE TABLE gov_data.budget_allocation (state VARCHAR(20), service VARCHAR(20), budget INT); INSERT INTO gov_data.budget_allocation (state, service, budget) VALUES ('California', 'Education', 3000000), ('California', 'Healthcare', 4000000), ('Texas', 'Education', 2000000), ('Texas', 'Healthcare'...
SELECT state, SUM(budget) as total_budget FROM gov_data.budget_allocation GROUP BY state;
This query finds the total budget allocated for public services in each state by grouping the budget_allocation table by state and summing up the budget values for each state.
What is the average budget allocated per department for the years 2021 and 2022?
CREATE TABLE Department (id INT, name VARCHAR(255), budget FLOAT, year INT); INSERT INTO Department (id, name, budget, year) VALUES (1, 'Education', 5000000, 2021), (2, 'Healthcare', 7000000, 2021), (3, 'Transportation', 8000000, 2021), (4, 'Education', 6000000, 2022), (5, 'Healthcare', 8000000, 2022), (6, 'Transportat...
SELECT AVG(budget) FROM Department WHERE year IN (2021, 2022);
This query calculates the average budget allocated per department for the years 2021 and 2022 by averaging the budget values from the Department table where the year field is 2021 or 2022.
Delete the 'Forest Friends' program record in the 'education_programs' table
CREATE TABLE education_programs (id INT PRIMARY KEY, name VARCHAR(50), location VARCHAR(50), attendance INT, target_audience VARCHAR(50));
DELETE FROM education_programs WHERE name = 'Forest Friends';
This query deletes the 'Forest Friends' program record in the 'education_programs' table.