instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
Display the species and total population of fish in the 'FishPopulationBySpecies' table with a population greater than 10000
CREATE TABLE FishPopulationBySpecies (id INT,species VARCHAR(255),population INT); INSERT INTO FishPopulationBySpecies (id,species,population) VALUES (1,'Tilapia',15000); INSERT INTO FishPopulationBySpecies (id,species,population) VALUES (2,'Carps',12000); INSERT INTO FishPopulationBySpecies (id,species,population) VALUES (3,'Goldfish',8000); INSERT INTO FishPopulationBySpecies (id,species,population) VALUES (4,'Catfish',11000);
SELECT species, SUM(population) FROM FishPopulationBySpecies WHERE population > 10000 GROUP BY species;
What is the total amount donated by individual donors who have donated more than once in the last year?
CREATE TABLE Donors (DonorID INT,Name VARCHAR(50),TotalDonations DECIMAL(10,2),LastDonation DATE);
SELECT SUM(TotalDonations) FROM (SELECT DonorID, SUM(DonationAmount) AS TotalDonations FROM Donations JOIN Donors ON Donations.DonorID = Donors.DonorID WHERE Donations.DonationDate > DATE_SUB(CURDATE(), INTERVAL 1 YEAR) AND DonorID IN (SELECT DonorID FROM Donors GROUP BY DonorID HAVING COUNT(*) > 1) GROUP BY DonorID);
What are the names and design standards of the dams located in 'California' from the 'dams' and 'design_standards' tables?
CREATE TABLE dams (id INT,name VARCHAR(255),location VARCHAR(255)); CREATE TABLE design_standards (dam_id INT,standard VARCHAR(255));
SELECT d.name, ds.standard FROM dams d INNER JOIN design_standards ds ON d.id = ds.dam_id WHERE d.location = 'California';
What were the total sales of drug 'Dolorol' in the United States for 2021?
CREATE TABLE sales (drug_name TEXT,country TEXT,sales_amount INT,sale_date DATE); INSERT INTO sales (drug_name,country,sales_amount,sale_date) VALUES ('Dolorol','USA',5000,'2021-01-01');
SELECT SUM(sales_amount) FROM sales WHERE drug_name = 'Dolorol' AND country = 'USA' AND sale_date BETWEEN '2021-01-01' AND '2021-12-31';
How many wastewater treatment facilities are there in Nigeria as of 2021?
CREATE TABLE facilities(name VARCHAR(50),country VARCHAR(50),build_year INT); INSERT INTO facilities(name,country,build_year) VALUES ('Facility1','Nigeria',2019),('Facility2','Nigeria',2018),('Facility3','Nigeria',2020);
SELECT COUNT(*) FROM facilities WHERE country = 'Nigeria' AND build_year <= 2021;
What are the names and types of renewable energy projects in Canada?
CREATE TABLE projects (name TEXT,type TEXT,country TEXT); INSERT INTO projects (name,type,country) VALUES ('Project 1','Wind','Canada'),('Project 2','Solar','Canada');
SELECT name, type FROM projects WHERE country = 'Canada'
Which sites have no recorded pollution control initiatives?
CREATE TABLE pollution_initiatives (initiative_id INT,site_id INT,initiative_date DATE,initiative_description TEXT); INSERT INTO pollution_initiatives (initiative_id,site_id,initiative_date,initiative_description) VALUES (1,1,'2022-08-01','Installed new filters'),(2,3,'2022-07-15','Regular cleaning schedule established');
SELECT site_id FROM marine_sites WHERE site_id NOT IN (SELECT site_id FROM pollution_initiatives);
What is the percentage of electric taxis in Singapore?
CREATE TABLE taxis (taxi_id INT,type VARCHAR(20),city VARCHAR(20)); INSERT INTO taxis (taxi_id,type,city) VALUES (1,'Electric Taxi','Singapore'),(2,'Taxi','Singapore'),(3,'Electric Taxi','Singapore'),(4,'Taxi','Singapore');
SELECT city, COUNT(*) * 100.0 / SUM(city = 'Singapore') OVER () AS percentage_etaxis FROM taxis WHERE type = 'Electric Taxi';
What is the average budget for all Mars rover missions launched by any space agency between 2000 and 2010, inclusive?
CREATE TABLE mars_rovers(id INT,agency VARCHAR(255),mission_name VARCHAR(255),launch_date DATE,budget DECIMAL(10,2));
SELECT AVG(budget) FROM mars_rovers WHERE agency IN (SELECT agency FROM mars_rovers WHERE launch_date BETWEEN '2000-01-01' AND '2010-12-31' GROUP BY agency) AND mission_name LIKE '%Mars Rover%';
Which mines have a labor productivity higher than the average?
CREATE TABLE Mines (MineID INT,Name TEXT,Location TEXT,TotalWorkers INT,TotalProduction INT); INSERT INTO Mines (MineID,Name,Location,TotalWorkers,TotalProduction) VALUES (1,'Golden Mine','California',250,150000),(2,'Silver Ridge','Nevada',300,210000),(3,'Copper Quarry','Arizona',400,250000); CREATE TABLE AverageScores (AvgLaborProductivity DECIMAL(5,2)); INSERT INTO AverageScores (AvgLaborProductivity) VALUES ((SELECT AVG(TotalProduction/TotalWorkers) FROM Mines));
SELECT Name, TotalProduction/TotalWorkers AS LaborProductivity FROM Mines WHERE TotalProduction/TotalWorkers > (SELECT AvgLaborProductivity FROM AverageScores);
What are the open pedagogy initiatives and their corresponding budgets?
CREATE TABLE initiatives (initiative_id INT,initiative_name VARCHAR(50),initiative_type VARCHAR(50)); CREATE TABLE budgets (budget_id INT,initiative_id INT,budget_amount INT); INSERT INTO initiatives (initiative_id,initiative_name,initiative_type) VALUES (101,'Open Source Textbooks','Open Pedagogy'),(102,'Peer Learning Networks','Open Pedagogy'),(103,'Project-Based Learning','Open Pedagogy'); INSERT INTO budgets (budget_id,initiative_id,budget_amount) VALUES (201,101,10000),(202,102,15000),(203,103,12000);
SELECT i.initiative_name, b.budget_amount FROM initiatives i INNER JOIN budgets b ON i.initiative_id = b.initiative_id;
What is the total value of all artworks in our Asian art collection?
CREATE TABLE Artworks (id INT,title VARCHAR(50),value DECIMAL(10,2),collection VARCHAR(50)); CREATE TABLE Collections (id INT,name VARCHAR(50),category VARCHAR(50));
SELECT SUM(Artworks.value) FROM Artworks INNER JOIN Collections ON Artworks.collection = Collections.name WHERE Collections.category = 'Asian Art';
Find the total size of fish farms in 'estuaries' schema where the size is greater than 35.
CREATE SCHEMA estuaries; CREATE TABLE fish_farms (id INT,size FLOAT,location VARCHAR(20)); INSERT INTO fish_farms (id,size,location) VALUES (1,40.2,'estuary'),(2,39.5,'estuary'),(3,52.3,'estuary');
SELECT SUM(size) FROM estuaries.fish_farms WHERE size > 35;
Insert a new record into the "researchers" table with the following information: "researcher_id": 401, "name": "Hiroshi Tanaka", "region": "Asia", "experience": 10.
CREATE TABLE researchers (researcher_id INT PRIMARY KEY,name VARCHAR(255),region VARCHAR(255),experience INT);
INSERT INTO researchers (researcher_id, name, region, experience) VALUES (401, 'Hiroshi Tanaka', 'Asia', 10);
What is the total climate finance investment in renewable energy in Asia?
CREATE TABLE finance (region VARCHAR(255),sector VARCHAR(255),amount FLOAT); INSERT INTO finance (region,sector,amount) VALUES ('Asia','Renewable Energy',8000000),('Africa','Renewable Energy',6000000),('Europe','Renewable Energy',10000000);
SELECT SUM(amount) FROM finance WHERE region = 'Asia' AND sector = 'Renewable Energy';
How many ocean acidification monitoring stations exist in each country and their average readings?
CREATE TABLE ocean_acidification_stations (station_name TEXT,country TEXT,reading FLOAT);
SELECT ocean_acidification_stations.country, COUNT(ocean_acidification_stations.station_name) AS num_stations, AVG(ocean_acidification_stations.reading) AS avg_reading FROM ocean_acidification_stations GROUP BY ocean_acidification_stations.country;
What is the total number of streams for each artist, their respective genres, and the total sales for those streams?
CREATE TABLE Artists (ArtistID INT,ArtistName VARCHAR(50)); CREATE TABLE Genres (GenreID INT,Genre VARCHAR(50)); CREATE TABLE Streams (StreamID INT,ArtistID INT,GenreID INT,Streams INT,Sales INT);
SELECT A.ArtistName, G.Genre, SUM(S.Streams) as TotalStreams, SUM(S.Sales) as TotalSales FROM Streams S JOIN Artists A ON S.ArtistID = A.ArtistID JOIN Genres G ON S.GenreID = G.GenreID GROUP BY A.ArtistName, G.Genre;
What is the average timber production, in cubic meters, for each country in the Asia-Pacific region?
CREATE TABLE timber_production (id INT,country VARCHAR(255),region VARCHAR(255),year INT,cubic_meters FLOAT); INSERT INTO timber_production (id,country,region,year,cubic_meters) VALUES (1,'China','Asia-Pacific',2020,789456.12),(2,'Indonesia','Asia-Pacific',2020,678345.12),(3,'Japan','Asia-Pacific',2020,567890.12);
SELECT country, AVG(cubic_meters) FROM timber_production WHERE region = 'Asia-Pacific' GROUP BY country;
Show the total budget allocated to healthcare services in each state for the year 2020.
CREATE TABLE Budget (State VARCHAR(255),Category VARCHAR(255),Amount DECIMAL(18,2)); INSERT INTO Budget (State,Category,Amount) VALUES ('MO','Healthcare',1000000.00),('MO','Education',800000.00),('IL','Healthcare',1500000.00);
SELECT State, SUM(Amount) FROM Budget WHERE Category = 'Healthcare' AND YEAR(Date) = 2020 GROUP BY State;
List all factories with their respective workforce size, categorized by region and employee gender?
CREATE TABLE factories (factory_id INT,factory_name TEXT,region TEXT); INSERT INTO factories (factory_id,factory_name,region) VALUES (1,'Factory D','West'),(2,'Factory E','North'),(3,'Factory F','South'); CREATE TABLE employees (employee_id INT,factory_id INT,department TEXT,gender TEXT); INSERT INTO employees (employee_id,factory_id,department,gender) VALUES (1,1,'Production','Female'),(2,1,'Engineering','Male'),(3,2,'Production','Non-binary'),(4,2,'Management','Female'),(5,3,'Production','Male'),(6,3,'Engineering','Female');
SELECT factories.factory_name, region, gender, COUNT(*) AS employee_count FROM factories JOIN employees ON factories.factory_id = employees.factory_id GROUP BY factories.factory_name, region, gender;
What is the minimum donation amount received from a single donor in France in the year 2017?
CREATE TABLE donations (id INT,donor_id INT,donation_amount DECIMAL(10,2),donation_date DATE); CREATE TABLE donors (id INT,country VARCHAR(50)); INSERT INTO donations (id,donor_id,donation_amount,donation_date) VALUES (1,1,20.00,'2017-01-01'); INSERT INTO donors (id,country) VALUES (1,'France');
SELECT MIN(donation_amount) FROM donations JOIN donors ON donations.donor_id = donors.id WHERE donors.country = 'France' AND YEAR(donation_date) = 2017;
What's the average age of employees in the 'mining_operations' table?
CREATE TABLE mining_operations (id INT,name VARCHAR(50),position VARCHAR(50),age INT);
SELECT AVG(age) FROM mining_operations;
What is the average number of public transportation trips per month in Sydney, Australia?
CREATE TABLE public_trips (trip_id INT,trip_date DATE,trip_city VARCHAR(50)); INSERT INTO public_trips (trip_id,trip_date,trip_city) VALUES (1,'2022-01-01','Sydney'),(2,'2022-01-02','Sydney');
SELECT AVG(trips) FROM (SELECT COUNT(*) AS trips FROM public_trips WHERE trip_city = 'Sydney' GROUP BY EXTRACT(MONTH FROM trip_date)) AS subquery;
What is the total revenue for concerts in 'Berlin'?
CREATE TABLE concerts (id INT,artist_id INT,city VARCHAR(50),revenue FLOAT); INSERT INTO concerts (id,artist_id,city,revenue) VALUES (1,1,'Los Angeles',500000),(2,1,'New York',700000),(3,2,'Seoul',800000),(4,2,'Tokyo',900000),(5,1,'Berlin',400000),(6,3,'Paris',1000000);
SELECT SUM(revenue) as total_revenue FROM concerts WHERE city = 'Berlin';
Show the top 3 materials with the highest waste generation across all manufacturers
CREATE TABLE WasteData (manufacturer_id INT,material VARCHAR(50),waste_quantity INT); INSERT INTO WasteData (manufacturer_id,material,waste_quantity) VALUES (1,'Material1',120),(1,'Material2',150),(2,'Material1',80),(2,'Material3',100); CREATE TABLE Manufacturers (manufacturer_id INT,manufacturer_name VARCHAR(50),region VARCHAR(50)); INSERT INTO Manufacturers (manufacturer_id,manufacturer_name,region) VALUES (1,'ManufacturerA','North America'),(2,'ManufacturerB','Europe');
SELECT material, SUM(waste_quantity) AS total_waste FROM WasteData GROUP BY material ORDER BY total_waste DESC LIMIT 3;
Insert a new graduate student named 'Ivan' with an email address '[email protected]' into the Graduate Students table.
CREATE TABLE graduate_students (id INT,name VARCHAR(50),email VARCHAR(50)); INSERT INTO graduate_students VALUES (1,'Fiona','[email protected]'),(2,'George','[email protected]'),(3,'Hannah','[email protected]');
INSERT INTO graduate_students (name, email) VALUES ('Ivan', '[email protected]');
What are the average labor costs for each construction trade in the state of California?
CREATE TABLE construction_trades (trade_id INT,trade_name VARCHAR(255),hourly_rate DECIMAL(10,2)); INSERT INTO construction_trades (trade_id,trade_name,hourly_rate) VALUES (1,'Carpentry',35.50),(2,'Electrical Work',42.25),(3,'Plumbing',46.75); CREATE TABLE labor_statistics (trade_id INT,state VARCHAR(255),avg_cost DECIMAL(10,2));
SELECT ct.trade_name, AVG(ls.avg_cost) as avg_cost_ca FROM construction_trades ct INNER JOIN labor_statistics ls ON ct.trade_id = ls.trade_id WHERE ls.state = 'California' GROUP BY ct.trade_name;
What is the total number of hours volunteered by each volunteer in the Youth programs in Q2 of 2022?
CREATE TABLE Volunteers (VolunteerID INT,VolunteerName VARCHAR(50)); INSERT INTO Volunteers (VolunteerID,VolunteerName) VALUES (1,'James Smith'),(2,'Jessica Johnson'); CREATE TABLE VolunteerHours (VolunteerHourID INT,VolunteerID INT,Program VARCHAR(50),VolunteerHours DECIMAL(10,2),VolunteerDate DATE); INSERT INTO VolunteerHours (VolunteerHourID,VolunteerID,Program,VolunteerHours,VolunteerDate) VALUES (1,1,'Youth',2.00,'2022-04-01'),(2,2,'Youth',3.00,'2022-05-01');
SELECT VolunteerName, SUM(VolunteerHours) as TotalHours FROM Volunteers INNER JOIN VolunteerHours ON Volunteers.VolunteerID = VolunteerHours.VolunteerID WHERE VolunteerHours.Program = 'Youth' AND QUARTER(VolunteerDate) = 2 AND Year(VolunteerDate) = 2022 GROUP BY VolunteerName;
What was the total revenue for each artwork medium in Q1 of 2021?
CREATE TABLE ArtWorkSales (artworkID INT,saleDate DATE,artworkMedium VARCHAR(50),revenue DECIMAL(10,2));
SELECT artworkMedium, SUM(revenue) as q1_revenue FROM ArtWorkSales WHERE saleDate BETWEEN '2021-01-01' AND '2021-03-31' GROUP BY artworkMedium;
What is the maximum number of streams for any rock song in California?
CREATE TABLE Streams (song_genre VARCHAR(255),state VARCHAR(255),stream_count INT,stream_date DATE); INSERT INTO Streams (song_genre,state,stream_count,stream_date) VALUES ('hip-hop','Texas',5000,'2022-01-01'),('rock','California',8000,'2022-01-02');
SELECT MAX(stream_count) FROM Streams WHERE song_genre = 'rock' AND state = 'California';
Calculate the percentage of security incidents related to phishing attacks, for each month in the last year?
CREATE TABLE security_incidents (id INT,incident_type VARCHAR(255),timestamp TIMESTAMP);CREATE VIEW phishing_incidents AS SELECT EXTRACT(MONTH FROM timestamp) as month,COUNT(*) as phishing_count FROM security_incidents WHERE incident_type = 'phishing' GROUP BY month;
SELECT month, phishing_count, ROUND(phishing_count * 100.0 / total_incidents, 2) as phishing_percentage FROM phishing_incidents JOIN (SELECT EXTRACT(MONTH FROM timestamp) as month, COUNT(*) as total_incidents FROM security_incidents GROUP BY month) total_incidents ON phishing_incidents.month = total_incidents.month ORDER BY month;
What is the average quantity of seafood sold per transaction in the Midwest region?
CREATE TABLE sales (id INT,location VARCHAR(20),quantity INT,price DECIMAL(5,2)); INSERT INTO sales (id,location,quantity,price) VALUES (1,'Northeast',50,12.99),(2,'Midwest',75,19.99),(3,'West',35,14.49);
SELECT AVG(quantity) FROM sales WHERE location = 'Midwest';
How many properties in each neighborhood have a sustainable urbanism score greater than 80?
CREATE TABLE Property (id INT,neighborhood VARCHAR(20),sustainable_score INT); INSERT INTO Property (id,neighborhood,sustainable_score) VALUES (1,'GreenCommunity',85),(2,'SolarVillage',70),(3,'GreenCommunity',90);
SELECT Property.neighborhood, COUNT(Property.id) FROM Property WHERE Property.sustainable_score > 80 GROUP BY Property.neighborhood;
Insert data into 'customer_size' table
CREATE TABLE customer_size (id INT PRIMARY KEY,size VARCHAR(10),customer_count INT); INSERT INTO customer_size (id,size,customer_count) VALUES (1,'XS',500),(2,'S',800),(3,'M',1200),(4,'L',1500);
INSERT INTO customer_size (id, size, customer_count) VALUES (1, 'XS', 500), (2, 'S', 800), (3, 'M', 1200), (4, 'L', 1500);
How many space missions have been led by astronauts from Canada with a duration greater than 500 days?
CREATE TABLE space_missions_canada (id INT,mission_name VARCHAR(255),mission_duration INT,lead_astronaut VARCHAR(255)); INSERT INTO space_missions_canada (id,mission_name,mission_duration,lead_astronaut) VALUES (1,'Mission1',600,'AstronautA'),(2,'Mission2',400,'AstronautB');
SELECT COUNT(*) FROM space_missions_canada WHERE lead_astronaut IN ('AstronautA', 'AstronautC', 'AstronautD') AND mission_duration > 500;
Show the number of threat intelligence reports generated by each agency in the past 30 days
CREATE TABLE threat_intelligence_reports (report_id INT,report_date DATE,threat_category VARCHAR(255),generating_agency VARCHAR(255));
SELECT generating_agency, COUNT(*) as report_count FROM threat_intelligence_reports WHERE report_date >= DATEADD(day, -30, CURRENT_DATE) GROUP BY generating_agency;
Delete all records from the "media_ethics" table where the "topic" is "Data privacy"
CREATE TABLE media_ethics (id INT,topic TEXT,description TEXT,created_at DATE);
DELETE FROM media_ethics WHERE topic = 'Data privacy';
Update the hotel_tech_adoption_table and set ai_integration to 'Yes' for all records from the Americas region
CREATE TABLE hotel_tech_adoption (hotel_id INT,region VARCHAR(50),ai_integration VARCHAR(50));
UPDATE hotel_tech_adoption SET ai_integration = 'Yes' WHERE region = 'Americas';
Delete all records in the 'ocean_acidification' table where the 'level' is above 8.0
CREATE TABLE ocean_acidification (id INT,date DATE,location VARCHAR(50),level DECIMAL(3,1)); INSERT INTO ocean_acidification (id,date,location,level) VALUES (1,'2021-08-15','Caribbean Sea',7.9); INSERT INTO ocean_acidification (id,date,location,level) VALUES (2,'2022-03-02','Sargasso Sea',8.1);
DELETE FROM ocean_acidification WHERE level > 8.0;
What is the total production quantity for each company, and what is the percentage of that quantity that is produced using renewable energy?
CREATE TABLE companies (company_id INT,name TEXT);CREATE TABLE production (company_id INT,total_qty INT,renewable_qty INT);
SELECT c.name, SUM(p.total_qty) AS total_produced, (SUM(p.renewable_qty) / SUM(p.total_qty)) * 100 AS pct_renewable FROM companies c INNER JOIN production p ON c.company_id = p.company_id GROUP BY c.name;
How many satellites were launched per year?
CREATE TABLE satellite_launches (id INT,launch_year INT,satellites INT); INSERT INTO satellite_launches (id,launch_year,satellites) VALUES (1,2000,50),(2,2001,75),(3,2002,85),(4,2003,100);
SELECT launch_year, SUM(satellites) as total_satellites FROM satellite_launches GROUP BY launch_year;
What is the average severity of vulnerabilities for each software product?
CREATE TABLE vulnerabilities (id INT,product VARCHAR(255),severity FLOAT); INSERT INTO vulnerabilities (id,product,severity) VALUES (1,'ProductA',5.0),(2,'ProductB',7.5),(3,'ProductA',3.0);
SELECT product, AVG(severity) as avg_severity FROM vulnerabilities GROUP BY product;
What was the average ad revenue in Q2 for users with over 10k followers?
CREATE TABLE users (id INT,followers INT,ad_revenue DECIMAL(10,2)); INSERT INTO users (id,followers,ad_revenue) VALUES (1,15000,500.00),(2,12000,450.00),(3,18000,600.00),(4,9000,300.00);
SELECT AVG(ad_revenue) FROM users WHERE followers > 10000 AND QUARTER(registration_date) = 2;
Update "collective_bargaining" table where the "union_id" is 3
CREATE TABLE collective_bargaining (union_id INT,agreement_date DATE,agreement_duration INT); INSERT INTO collective_bargaining (union_id,agreement_date,agreement_duration) VALUES (1,'2021-01-01',24); INSERT INTO collective_bargaining (union_id,agreement_date,agreement_duration) VALUES (2,'2022-05-15',36);
UPDATE collective_bargaining SET agreement_duration = 48 WHERE union_id = 3;
How many smart city projects are there in the African continent?
CREATE TABLE SmartCities (id INT,country VARCHAR(50),project_count INT); INSERT INTO SmartCities (id,country,project_count) VALUES (1,'Nigeria',12),(2,'Egypt',8),(3,'South Africa',15),(4,'Morocco',9);
SELECT SUM(project_count) FROM SmartCities WHERE country IN ('Nigeria', 'Egypt', 'South Africa', 'Morocco', 'Tunisia');
What is the total biomass for fish species B in the Atlantic Ocean?
CREATE TABLE species (species_id INT,species_name TEXT); INSERT INTO species (species_id,species_name) VALUES (1,'Fish species A'),(2,'Fish species B'); CREATE TABLE biomass (biomass_id INT,species_id INT,region_id INT,biomass FLOAT); INSERT INTO biomass (biomass_id,species_id,region_id,biomass) VALUES (1,1,1,150.3),(2,1,2,160.5),(3,2,1,140.2),(4,2,2,130.1),(5,2,3,120.9); CREATE TABLE region (region_id INT,region_name TEXT); INSERT INTO region (region_id,region_name) VALUES (1,'North Atlantic'),(2,'South Atlantic'),(3,'Indian Ocean');
SELECT SUM(biomass) FROM biomass WHERE species_id = (SELECT species_id FROM species WHERE species_name = 'Fish species B') AND region_id IN (SELECT region_id FROM region WHERE region_name LIKE '%Atlantic%');
What is the average price of vegan cosmetics sold in the United States?
CREATE TABLE products (product_id INT,name TEXT,is_vegan BOOLEAN,price DECIMAL,country TEXT); INSERT INTO products (product_id,name,is_vegan,price,country) VALUES (1,'Lipstick',TRUE,15.99,'USA'); INSERT INTO products (product_id,name,is_vegan,price,country) VALUES (2,'Eye Shadow',FALSE,12.49,'Canada');
SELECT AVG(price) FROM products WHERE is_vegan = TRUE AND country = 'USA';
What is the total number of Ethereum transactions with a gas price above 50 wei in Q2 2021?
CREATE TABLE ethereum_transactions (tx_hash VARCHAR(255),block_number INT,timestamp TIMESTAMP,from_address VARCHAR(42),to_address VARCHAR(42),gas_price DECIMAL(18,9));
SELECT COUNT(*) AS num_transactions FROM ethereum_transactions WHERE gas_price > 50 AND timestamp >= '2021-04-01 00:00:00' AND timestamp < '2021-07-01 00:00:00';
List the unique tech_used values and their corresponding counts from the legal_tech table, but only for 'NY' and 'TX' locations.
CREATE TABLE legal_tech (record_id INT,location VARCHAR(20),tech_used VARCHAR(20),date DATE); INSERT INTO legal_tech (record_id,location,tech_used,date) VALUES (1,'NY','AI','2021-01-01'),(2,'NY','Natural_Language_Processing','2021-01-02'),(3,'TX','AI','2021-01-01'),(4,'TX','Natural_Language_Processing','2021-01-02'),(5,'TX','AI','2021-01-01'),(6,'TX','Natural_Language_Processing','2021-01-02'),(7,'IL','AI','2021-01-01'),(8,'IL','Natural_Language_Processing','2021-01-02');
SELECT tech_used, COUNT(*) FROM legal_tech WHERE location IN ('NY', 'TX') GROUP BY tech_used;
What are the cybersecurity strategies of Japan in the past year?
CREATE TABLE CybersecurityStrategies (ID INT,Country TEXT,Year INT,Strategy TEXT); INSERT INTO CybersecurityStrategies (ID,Country,Year,Strategy) VALUES (1,'Japan',2021,'Quantum Cryptography'),(2,'Japan',2020,'AI-driven Threat Intelligence'),(3,'USA',2021,'Zero Trust Architecture');
SELECT Strategy FROM CybersecurityStrategies WHERE Country = 'Japan' AND Year = 2021;
What are the Savings accounts with a balance greater than $4000?
CREATE TABLE Accounts (AccountId INT,AccountType VARCHAR(20),Balance DECIMAL(10,2)); INSERT INTO Accounts (AccountId,AccountType,Balance) VALUES (1,'Checking',2500.00),(2,'Savings',6000.00);
SELECT AccountId, AccountType, Balance FROM Accounts WHERE AccountType = 'Savings' AND Balance > 4000.00;
Update the 'discovery_date' column in the 'fields' table for field 'F-01' to '2010-01-01'
CREATE TABLE fields (field_id INT,field_name VARCHAR(255),operator VARCHAR(255),discovery_date DATE);
UPDATE fields SET discovery_date = '2010-01-01' WHERE field_name = 'F-01';
Update the program of 'Biodiversity' in the 'community_education' table to 'Biodiversity and Wildlife Conservation'.
CREATE TABLE community_education (id INT,program VARCHAR(255),attendance INT); INSERT INTO community_education (id,program,attendance) VALUES (1,'Biodiversity',30),(2,'Climate Change',40),(3,'Habitat Restoration',60);
UPDATE community_education SET program = 'Biodiversity and Wildlife Conservation' WHERE program = 'Biodiversity';
What is the most common type of crime in Paris, and how many times did it occur?
CREATE TABLE crimes (id INT,city VARCHAR(255),date DATE,type VARCHAR(255),description TEXT); INSERT INTO crimes (id,city,date,type,description) VALUES (1,'Paris','2022-01-01','Theft','Bicycle theft'),(2,'Paris','2022-02-01','Vandalism','Graffiti');
SELECT type, COUNT(*) FROM crimes WHERE city = 'Paris' GROUP BY type ORDER BY COUNT(*) DESC LIMIT 1;
What is the maximum number of animals in a protected habitat for each animal species?
CREATE TABLE Protected_Habitats (id INT,animal_species VARCHAR(50),habitat_id INT,animal_count INT);
SELECT animal_species, MAX(animal_count) FROM Protected_Habitats GROUP BY animal_species;
List the number of cultivation licenses issued per month in 2021.
CREATE TABLE Licenses (License_ID INT,License_Type TEXT,Issue_Date DATE); INSERT INTO Licenses (License_ID,License_Type,Issue_Date) VALUES (1,'Cultivation','2021-01-01');
SELECT DATE_TRUNC('month', Issue_Date) as Month, COUNT(*) as Count FROM Licenses WHERE License_Type = 'Cultivation' AND YEAR(Issue_Date) = 2021 GROUP BY Month ORDER BY Month;
Create a new table 'customer_complaints' with columns 'customer_id', 'complaint_type', 'complaint_date'
CREATE SCHEMA telecom; CREATE TABLE customer_complaints (customer_id INT,complaint_type TEXT,complaint_date DATE);
CREATE TABLE telecom.customer_complaints (customer_id INT, complaint_type TEXT, complaint_date DATE);
What is the number of research grants awarded to female graduate students in the Physics department since 2016?
CREATE TABLE graduate_students (student_id INT,name VARCHAR(50),department VARCHAR(50),gender VARCHAR(10)); INSERT INTO graduate_students VALUES (1,'Alice Johnson','Physics','Female'); INSERT INTO graduate_students VALUES (2,'Bob Brown','Physics','Male'); INSERT INTO graduate_students VALUES (3,'Charlie Davis','Chemistry','Male'); CREATE TABLE grants_graduate_students (grant_id INT,student_id INT,amount DECIMAL(10,2),year INT); INSERT INTO grants_graduate_students VALUES (1,1,50000,2016); INSERT INTO grants_graduate_students VALUES (2,2,75000,2017); INSERT INTO grants_graduate_students VALUES (3,2,60000,2018); INSERT INTO grants_graduate_students VALUES (4,1,65000,2019);
SELECT COUNT(*) FROM grants_graduate_students g INNER JOIN graduate_students s ON g.student_id = s.student_id WHERE s.department = 'Physics' AND s.gender = 'Female' AND g.year >= 2016;
What is the budget allocation for 'Parks and Recreation' in the district with the highest budget allocation?
CREATE TABLE Budget_Allocation (budget_id INT,category VARCHAR(50),amount DECIMAL(10,2),district_id INT,allocated_date DATE); INSERT INTO Budget_Allocation (budget_id,category,amount,district_id,allocated_date) VALUES (5,'Parks and Recreation',25000.00,7,'2021-04-10');
SELECT ba.amount FROM Budget_Allocation ba WHERE ba.category = 'Parks and Recreation' AND ba.district_id = (SELECT MAX(ba2.district_id) FROM Budget_Allocation ba2);
List all digital assets and their respective smart contract names in the Gaming category.
CREATE TABLE Asset_Smart_Contracts (id INT PRIMARY KEY,digital_asset_id INT,smart_contract_id INT,FOREIGN KEY (digital_asset_id) REFERENCES Digital_Assets(id),FOREIGN KEY (smart_contract_id) REFERENCES Smart_Contracts(id)); INSERT INTO Asset_Smart_Contracts (id,digital_asset_id,smart_contract_id) VALUES (1,1,2); INSERT INTO Asset_Smart_Contracts (id,digital_asset_id,smart_contract_id) VALUES (2,2,4);
SELECT da.name, sc.name FROM Digital_Assets da INNER JOIN Asset_Smart_Contracts asc ON da.id = asc.digital_asset_id INNER JOIN Smart_Contracts sc ON asc.smart_contract_id = sc.id WHERE sc.category = 'Gaming';
Which countries had a decrease in visitors to their capital cities from 2021 to 2022?
CREATE TABLE if not exists VisitorStatisticsByYear (Year INT,Country VARCHAR(50),Visitors INT); INSERT INTO VisitorStatisticsByYear (Year,Country,Visitors) VALUES (2021,'Germany',1000000),(2022,'Germany',950000),(2021,'Spain',800000),(2022,'Spain',780000),(2021,'France',900000),(2022,'France',920000);
SELECT a.Country, (b.Visitors - a.Visitors) AS VisitorChange FROM VisitorStatisticsByYear a, VisitorStatisticsByYear b WHERE a.Country = b.Country AND a.Year = 2021 AND b.Year = 2022;
Which sensors in the precision agriculture system have not sent data in the past week?
CREATE TABLE Sensors (SensorID varchar(5),SensorName varchar(10),LastDataSent timestamp); INSERT INTO Sensors (SensorID,SensorName,LastDataSent) VALUES ('1','Sensor 1','2022-06-22 12:30:00'),('2','Sensor 2','2022-06-25 16:45:00'),('3','Sensor 3','2022-06-28 09:10:00');
SELECT SensorName FROM Sensors WHERE LastDataSent < NOW() - INTERVAL '7 days';
What is the average property price for each neighborhood in the last 6 months?
CREATE TABLE Neighborhoods (NeighborhoodID INT,NeighborhoodName VARCHAR(255)); CREATE TABLE Properties (PropertyID INT,NeighborhoodID INT,Sold DATE,PropertyPrice INT);
SELECT NeighborhoodName, AVG(PropertyPrice) AS AvgPropertyPrice FROM Properties JOIN Neighborhoods ON Properties.NeighborhoodID = Neighborhoods.NeighborhoodID WHERE Sold >= DATEADD(month, -6, CURRENT_TIMESTAMP) GROUP BY NeighborhoodName;
What was the average delay in minutes for vessels arriving in Japan in Q3 2021?
CREATE TABLE vessel_arrivals (vessel_id INT,arrival_date DATE,arrival_delay INT,port VARCHAR(255));
SELECT AVG(arrival_delay) FROM vessel_arrivals WHERE port = 'Japan' AND QUARTER(arrival_date) = 3 AND YEAR(arrival_date) = 2021;
What is the percentage of organic ingredients used in each dish, excluding dishes with fewer than 5 organic ingredients?
CREATE TABLE dishes (dish_id INT,dish_name VARCHAR(255)); CREATE TABLE ingredients (ingredient_id INT,ingredient_name VARCHAR(255),dish_id INT,is_organic BOOLEAN); INSERT INTO dishes VALUES (1,'Caprese Salad'); INSERT INTO ingredients VALUES (1,'Fresh Mozzarella',1,false); INSERT INTO ingredients VALUES (2,'Tomatoes',1,true);
SELECT dish_name, ROUND(COUNT(ingredient_id) * 100.0 / (SELECT COUNT(ingredient_id) FROM ingredients i2 WHERE i2.dish_id = i.dish_id), 2) as organic_percentage FROM ingredients i WHERE is_organic = true GROUP BY dish_id HAVING COUNT(ingredient_id) >= 5;
Update the Gender of the community health worker with Age 55 to 'Non-binary'.
CREATE TABLE CommunityHealthWorkers (WorkerID INT,Age INT,Gender VARCHAR(10),Region VARCHAR(2)); INSERT INTO CommunityHealthWorkers (WorkerID,Age,Gender,Region) VALUES (1,35,'F','NY'),(2,40,'M','CA'),(3,45,'F','NY'),(4,50,'M','IL'),(5,55,'M','IL');
UPDATE CommunityHealthWorkers SET Gender = 'Non-binary' WHERE Age = 55;
In which rural counties are specific medical conditions most prevalent?
use rural_health; CREATE TABLE medical_conditions (id int,patient_id int,county text,condition text); INSERT INTO medical_conditions (id,patient_id,county,condition) VALUES (1,1,'Green','Diabetes'); INSERT INTO medical_conditions (id,patient_id,county,condition) VALUES (2,1,'Green','Hypertension'); INSERT INTO medical_conditions (id,patient_id,county,condition) VALUES (3,2,'Blue','Asthma');
SELECT county, condition, COUNT(*) as count FROM rural_health.medical_conditions GROUP BY county, condition ORDER BY count DESC;
How many regulatory frameworks related to blockchain have been implemented in the Middle East and North Africa?
CREATE TABLE frameworks (id INT,country VARCHAR(50),date DATE,type VARCHAR(50)); INSERT INTO frameworks (id,country,date,type) VALUES (1,'UAE','2021-01-01','Blockchain'),(2,'Saudi Arabia','2021-02-01','Blockchain'),(3,'Egypt','2021-03-01','Cryptocurrency');
SELECT COUNT(*) FROM frameworks WHERE country IN ('UAE', 'Saudi Arabia', 'Egypt') AND type = 'Blockchain';
Identify the top 5 most active countries in terms of exhibition visits in the last quarter.
CREATE TABLE Exhibition (id INT,name VARCHAR(100),Visitor_id INT,country VARCHAR(50)); INSERT INTO Exhibition (id,name,Visitor_id,country) VALUES (1,'Ancient Civilizations',1,'USA'),(2,'Modern Art',2,'Canada'),(3,'Nature Photography',3,'Mexico'),(4,'Wildlife',4,'Brazil'),(5,'Robotics',5,'USA');
SELECT Exhibition.country, COUNT(DISTINCT Exhibition.Visitor_id) as visit_count FROM Exhibition WHERE Exhibition.interaction_date >= CURDATE() - INTERVAL 3 MONTH GROUP BY Exhibition.country ORDER BY visit_count DESC LIMIT 5;
What is the maximum soil moisture level recorded for each crop type in the past week?
CREATE TABLE SoilMoistureData (moisture FLOAT,time DATETIME,crop VARCHAR(255));
SELECT crop, MAX(moisture) FROM SoilMoistureData WHERE time > DATE_SUB(CURRENT_TIMESTAMP(), INTERVAL 1 WEEK) GROUP BY crop;
What is the total number of clients who have made an investment in each month of the past year?
CREATE TABLE clients (id INT,registered_date DATE);CREATE TABLE investments (id INT,client_id INT,investment_date DATE); INSERT INTO clients (id,registered_date) VALUES (1,'2020-01-01'),(2,'2019-01-01'),(3,'2018-01-01'),(4,'2017-01-01'),(5,'2016-01-01'); INSERT INTO investments (id,client_id,investment_date) VALUES (1,1,'2021-02-01'),(2,1,'2021-03-01'),(3,2,'2020-04-01'),(4,3,'2019-05-01'),(5,4,'2018-06-01'),(6,1,'2021-02-02'),(7,1,'2021-02-03'),(8,5,'2021-03-01'),(9,2,'2021-02-01'),(10,3,'2021-03-01');
SELECT DATE_TRUNC('month', investment_date) AS investment_month, COUNT(DISTINCT c.id) AS num_clients FROM clients c JOIN investments i ON c.id = i.client_id WHERE i.investment_date >= c.registered_date + INTERVAL '1 year' GROUP BY investment_month;
What is the average number of students in each district, and what is the minimum mental health score for students in each district, grouped by student gender?
CREATE TABLE districts (district_id INT,district_name TEXT); INSERT INTO districts (district_id,district_name) VALUES (1,'Rural'),(2,'Urban'),(3,'Suburban'); CREATE TABLE students (student_id INT,student_name TEXT,district_id INT,mental_health_score INT,student_gender TEXT); INSERT INTO students (student_id,student_name,district_id,mental_health_score,student_gender) VALUES (1,'Alex',1,75,'Female'),(2,'Bella',2,80,'Female'),(3,'Charlie',3,70,'Male'),(4,'Danielle',1,60,'Female'),(5,'Eli',3,65,'Male');
SELECT students.student_gender, districts.district_name, AVG(students.student_id) AS avg_students, MIN(students.mental_health_score) AS min_mental_health_score FROM districts JOIN students ON districts.district_id = students.district_id GROUP BY students.student_gender, districts.district_name;
Which military innovations are not associated with any technology provider?
CREATE TABLE military_innovations (id INT,innovation VARCHAR(255),type VARCHAR(255)); CREATE TABLE technology_providers (id INT,provider VARCHAR(255),specialization VARCHAR(255));
SELECT innovation FROM military_innovations mi LEFT JOIN technology_providers tp ON mi.id = tp.id WHERE tp.id IS NULL;
How many parks were opened in 'CityI' in the year 2019?
CREATE TABLE Parks (City VARCHAR(20),Year INT,Number INT); INSERT INTO Parks (City,Year,Number) VALUES ('CityI',2019,5);
SELECT Number FROM Parks WHERE City = 'CityI' AND Year = 2019;
What is the name of the first female astronaut from Russia?
CREATE TABLE Astronauts (name VARCHAR(30),gender VARCHAR(10),nationality VARCHAR(20)); INSERT INTO Astronauts (name,gender,nationality) VALUES ('Valentina Tereshkova','Female','Russia');
SELECT name FROM Astronauts WHERE gender = 'Female' AND nationality = 'Russia' LIMIT 1;
Add a new column year to the funding table and update values
CREATE TABLE funding(id INT,organization VARCHAR(255),amount FLOAT,year INT);
ALTER TABLE funding ADD COLUMN year INT;
Get the number of successful satellite launches per country
CREATE TABLE satellites (satellite_id INT PRIMARY KEY,name VARCHAR(100),country VARCHAR(50),launch_date DATETIME,launch_failure BOOLEAN);
SELECT country, COUNT(*) AS successful_launches FROM satellites WHERE launch_failure = FALSE GROUP BY country;
What is the total number of patients who have been prescribed medication?
CREATE TABLE medications (patient_id INT,medication VARCHAR(20)); INSERT INTO medications (patient_id,medication) VALUES (1,'Prozac'); INSERT INTO medications (patient_id,medication) VALUES (2,'Lexapro'); INSERT INTO medications (patient_id,medication) VALUES (3,'Zoloft');
SELECT COUNT(DISTINCT patient_id) FROM medications;
What is the maximum number of defense projects that Boeing has been involved in simultaneously in any given year?
CREATE TABLE defense_projects (contractor VARCHAR(255),project VARCHAR(255),start_date DATE,end_date DATE); INSERT INTO defense_projects (contractor,project,start_date,end_date) VALUES ('Boeing','Project A','2015-01-01','2017-12-31'),('Boeing','Project B','2016-07-01','2018-06-30'),('Boeing','Project C','2017-03-01','2019-02-28'),('Boeing','Project D','2018-09-01','2020-08-31'),('Boeing','Project E','2019-11-01','2021-10-31');
SELECT COUNT(project) FROM defense_projects dp1 WHERE YEAR(dp1.start_date) <= YEAR(dp1.end_date) AND NOT EXISTS (SELECT 1 FROM defense_projects dp2 WHERE dp2.contractor = dp1.contractor AND dp2.project != dp1.project AND YEAR(dp2.start_date) < YEAR(dp1.end_date) AND YEAR(dp2.end_date) > YEAR(dp1.start_date));
What is the total 'carbon footprint' of 'manufacturing' in 'China'?
CREATE TABLE processes (id INT,name TEXT,type TEXT,carbon_footprint FLOAT); INSERT INTO processes (id,name,type,carbon_footprint) VALUES (1,'manufacturing','manufacturing',1000.0),(2,'transportation','transportation',2000.0),(3,'manufacturing','manufacturing',1500.0);
SELECT SUM(carbon_footprint) FROM processes WHERE type = 'manufacturing' AND location = 'China';
What is the breakdown of customer usage patterns by age group and network type?
CREATE TABLE customer_demographics (customer_id INT,age_group VARCHAR(255),network_type VARCHAR(255)); INSERT INTO customer_demographics (customer_id,age_group,network_type) VALUES (1,'18-24','3G'),(2,'25-34','4G'); CREATE TABLE usage_patterns (customer_id INT,usage_minutes INT); INSERT INTO usage_patterns (customer_id,usage_minutes) VALUES (1,300),(2,450);
SELECT a.age_group, b.network_type, AVG(usage_minutes) FROM customer_demographics a JOIN usage_patterns b ON a.customer_id = b.customer_id GROUP BY a.age_group, b.network_type;
What is the total number of tickets sold for the dance performance in the last year?
CREATE TABLE TicketSales (ticketID INT,saleDate DATE,performance VARCHAR(20),numTickets INT); INSERT INTO TicketSales (ticketID,saleDate,performance,numTickets) VALUES (1,'2022-04-01','Dance Performance',100),(2,'2022-05-10','Theater Play',50),(3,'2022-06-20','Dance Performance',150);
SELECT SUM(numTickets) FROM TicketSales WHERE performance = 'Dance Performance' AND saleDate >= '2022-04-01' AND saleDate <= '2022-03-31';
What is the name and description of each biosensor technology project in Canada and Australia?
CREATE TABLE biosensor_technology (id INT,project_name VARCHAR(50),description TEXT,location VARCHAR(50)); INSERT INTO biosensor_technology (id,project_name,description,location) VALUES (1,'Project1','Biosensor for glucose detection','Canada'); INSERT INTO biosensor_technology (id,project_name,description,location) VALUES (2,'Project2','Biosensor for protein detection','Australia');
SELECT project_name, description FROM biosensor_technology WHERE location IN ('Canada', 'Australia');
Show artifacts found in the 'Indus Valley' that were preserved using the 'Coating' method.
CREATE TABLE Site (site_id INT,site_name VARCHAR(255),country VARCHAR(255),start_date DATE,end_date DATE); INSERT INTO Site (site_id,site_name,country,start_date,end_date) VALUES (1,'Mohenjo-Daro','Indus Valley','2500 BC','1900 BC'),(2,'Harappa','Indus Valley','2600 BC','1900 BC'); CREATE TABLE Artifact (artifact_id INT,artifact_name VARCHAR(255),site_id INT,date_found DATE); INSERT INTO Artifact (artifact_id,artifact_name,site_id,date_found) VALUES (1,'Bronze Dagger',1,'1922-02-01'),(2,'Terracotta Bull',2,'1920-12-12'); CREATE TABLE Preservation (preservation_id INT,method VARCHAR(255),artifact_id INT); INSERT INTO Preservation (preservation_id,method,artifact_id) VALUES (1,'Coating',1),(2,'Conservation',2); CREATE VIEW ArtifactPreservation AS SELECT * FROM Artifact JOIN Preservation ON Artifact.artifact_id = Preservation.artifact_id;
SELECT * FROM ArtifactPreservation WHERE country = 'Indus Valley' AND method = 'Coating';
What are the names of all ingredients that are used in both cruelty-free certified products and products not certified as cruelty-free?
CREATE TABLE ingredients (ingredient_name VARCHAR(50)); INSERT INTO ingredients (ingredient_name) VALUES ('Water'),('Mineral Powder'),('Chemical X'),('Chemical Y');
SELECT ingredients.ingredient_name FROM ingredients JOIN product_ingredients ON ingredients.ingredient_name = product_ingredients.ingredient WHERE product_ingredients.ingredient_source IN (SELECT ingredient_source FROM product_ingredients WHERE product_ingredients.product_name IN (SELECT products.product_name FROM products WHERE products.is_cruelty_free = true)) AND ingredients.ingredient_name IN (SELECT ingredient FROM product_ingredients WHERE product_ingredients.product_name NOT IN (SELECT products.product_name FROM products WHERE products.is_cruelty_free = true)) GROUP BY ingredients.ingredient_name HAVING COUNT(DISTINCT product_ingredients.ingredient_source) > 1;
Update the 'crop_type' column to 'corn' for all records in the 'field_1' table
CREATE TABLE field_1 (id INT PRIMARY KEY,x_coordinate INT,y_coordinate INT,crop_type TEXT,area_hectares FLOAT); INSERT INTO field_1 (id,x_coordinate,y_coordinate,crop_type,area_hectares) VALUES (1,100,200,'soybeans',5.3),(2,150,250,'wheat',3.2),(3,200,300,'cotton',7.1);
UPDATE field_1 SET crop_type = 'corn';
What are the total sales for drugs with a manufacturing cost of more than $200 per unit and in the neurology therapeutic area?
CREATE TABLE drug_approval (drug_name TEXT,approval_status TEXT); INSERT INTO drug_approval (drug_name,approval_status) VALUES ('DrugA','approved'),('DrugB','approved'),('DrugC','pending'),('DrugD','approved'); CREATE TABLE manufacturing_costs (drug_name TEXT,cost_per_unit INTEGER); INSERT INTO manufacturing_costs (drug_name,cost_per_unit) VALUES ('DrugA',185),('DrugB',210),('DrugC',150),('DrugD',256); CREATE TABLE drug_sales (drug_name TEXT,sales INTEGER,therapeutic_area TEXT); INSERT INTO drug_sales (drug_name,sales,therapeutic_area) VALUES ('DrugA',30000000,'neurology'),('DrugB',45000000,'neurology'),('DrugC',0,'neurology'),('DrugD',55000000,'neurology');
SELECT SUM(sales) FROM drug_sales INNER JOIN drug_approval ON drug_sales.drug_name = drug_approval.drug_name INNER JOIN manufacturing_costs ON drug_sales.drug_name = manufacturing_costs.drug_name WHERE drug_approval.approval_status = 'approved' AND manufacturing_costs.cost_per_unit > 200 AND drug_sales.therapeutic_area = 'neurology';
Delete a record from the "PublicServices" table based on the provided criteria
CREATE TABLE PublicServices (ID INT,Service TEXT,Description TEXT,Availability TEXT);
WITH service_to_delete AS (DELETE FROM PublicServices WHERE ID = 4001 AND Service = 'Senior Transportation' RETURNING ID, Service, Description, Availability) SELECT * FROM service_to_delete;
How many refugees were helped in Colombia in 2017?
CREATE TABLE refugees (id INT,country TEXT,year INT,num_refugees INT); INSERT INTO refugees
SELECT COUNT(*) FROM refugees WHERE country = 'Colombia' AND year = 2017;
What is the average claim amount for homeowners insurance in Texas?
CREATE TABLE insured_homes (id INT,state VARCHAR(2),policy_type VARCHAR(20),claim_amount DECIMAL(10,2)); INSERT INTO insured_homes (id,state,policy_type,claim_amount) VALUES (1,'TX','Homeowners',5000),(2,'TX','Homeowners',12000),(3,'TX','Renters',800);
SELECT AVG(claim_amount) FROM insured_homes WHERE state = 'TX' AND policy_type = 'Homeowners';
List the chemical names and the total greenhouse gas emissions for each chemical.
CREATE TABLE EnvironmentalImpact (ChemicalID INT,CO2Emissions INT,CH4Emissions INT,N2OEmissions INT); INSERT INTO EnvironmentalImpact (ChemicalID,CO2Emissions,CH4Emissions,N2OEmissions) VALUES (1,100,20,30),(2,150,30,40),(3,50,10,20);
SELECT ChemicalID, CO2Emissions + CH4Emissions + N2OEmissions AS TotalEmissions, ChemicalName FROM EnvironmentalImpact INNER JOIN Chemicals ON EnvironmentalImpact.ChemicalID = Chemicals.ChemicalID;
What is the total funding from private and public sources for each program category?
CREATE TABLE program_funding (program_category VARCHAR(15),funding_source VARCHAR(15),amount INT);
SELECT program_category, SUM(CASE WHEN funding_source = 'private' THEN 1 ELSE 0 END) + SUM(CASE WHEN funding_source = 'public' THEN 1 ELSE 0 END) AS total_funding FROM program_funding GROUP BY program_category;
List all clients who have paid their bills in full for cases with a billing amount greater than $10,000.
CREATE TABLE clients (client_id INT,name TEXT); INSERT INTO clients (client_id,name) VALUES (1,'Jane Doe'),(2,'John Smith'),(3,'Sara Connor'),(4,'Tom Williams'); CREATE TABLE cases (case_id INT,client_id INT,billing_amount INT,paid_in_full BOOLEAN); INSERT INTO cases (case_id,client_id,billing_amount,paid_in_full) VALUES (1,1,12000,TRUE),(2,2,8000,FALSE),(3,3,20000,TRUE),(4,4,5000,FALSE);
SELECT clients.name FROM clients INNER JOIN cases ON clients.client_id = cases.client_id WHERE cases.billing_amount > 10000 AND cases.paid_in_full = TRUE;
List all regulatory frameworks in the European Union.
CREATE TABLE regulations (id INT PRIMARY KEY,name VARCHAR(255),region VARCHAR(255)); INSERT INTO regulations (id,name,region) VALUES (1,'Regulation1','European Union'),(2,'Regulation2','United States');
SELECT name FROM regulations WHERE region = 'European Union';
What is the average ticket price for women's soccer team home games?
CREATE TABLE ticket_prices (price DECIMAL(5,2),team_id INT,game_id INT,game_type VARCHAR(255)); INSERT INTO ticket_prices (price,team_id,game_id,game_type) VALUES (25.00,4,201,'Regular Season'),(30.00,4,202,'Regular Season'),(35.00,5,203,'Regular Season'),(20.00,5,204,'Regular Season'); CREATE TABLE teams (team_id INT,team_name VARCHAR(255),sport VARCHAR(255)); INSERT INTO teams (team_id,team_name,sport) VALUES (4,'Spirit','Soccer'),(5,'Courage','Soccer'); CREATE TABLE games (game_id INT,home_team_id INT,game_type VARCHAR(255)); INSERT INTO games (game_id,home_team_id,game_type) VALUES (201,4,'Home'),(202,4,'Home'),(203,5,'Home'),(204,5,'Home');
SELECT t.team_name, AVG(price) avg_price FROM ticket_prices tp JOIN teams t ON tp.team_id = t.team_id JOIN games g ON tp.game_id = g.game_id WHERE t.team_id = g.home_team_id AND tp.game_type = 'Home' AND t.sport = 'Soccer' AND tp.price IS NOT NULL GROUP BY t.team_name;
What is the number of articles published per day for the last week?
CREATE TABLE articles (article_id INT,publication_date DATE); INSERT INTO articles (article_id,publication_date) VALUES (1,'2022-01-01'),(2,'2022-01-02'),(3,'2022-01-03');
SELECT DATEPART(day, publication_date) AS day_of_week, COUNT(article_id) FROM articles WHERE publication_date >= DATEADD(week, -1, GETDATE()) GROUP BY DATEPART(day, publication_date);
What is the minimum response time for emergency calls in the city of Toronto?
CREATE TABLE emergency_calls (id INT,city VARCHAR(20),response_time FLOAT); INSERT INTO emergency_calls (id,city,response_time) VALUES (1,'Toronto',4.5),(2,'Toronto',3.9),(3,'Montreal',5.1);
SELECT MIN(response_time) FROM emergency_calls WHERE city = 'Toronto';
Show the number of male and female reporters in the 'news_reporters' table, grouped by their age.
CREATE TABLE news_reporters (reporter_id INT,name VARCHAR(50),age INT,gender VARCHAR(10),hire_date DATE);
SELECT gender, age, COUNT(*) FROM news_reporters GROUP BY gender, age;
What is the total amount donated by each donor in the 'donors' and 'donations' tables?
CREATE TABLE donors (id INT,name TEXT,total_donations DECIMAL(10,2)); INSERT INTO donors (id,name,total_donations) SELECT donor_id,donor_name,SUM(amount) FROM donations GROUP BY donor_id; CREATE TABLE donations (id INT,donor_id INT,donor_name TEXT,amount DECIMAL(10,2));
SELECT d.name, SUM(d2.amount) FROM donors d INNER JOIN donations d2 ON d.id = d2.donor_id GROUP BY d.name;
Find the sensor with the minimum water level in the 'sensor_data' table
CREATE TABLE sensor_data (sensor_id INT,water_level FLOAT,timestamp TIMESTAMP);
SELECT sensor_id, MIN(water_level) as min_water_level FROM sensor_data;