instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
Who are the female astronauts with the most missions for each agency?
CREATE TABLE Astronauts (id INT,name VARCHAR(255),gender VARCHAR(10),agency VARCHAR(255),missions INT); INSERT INTO Astronauts (id,name,gender,agency,missions) VALUES (1,'Eileen Collins','Female','NASA',4),(2,'Yi So-yeon','Female','Korea Aerospace Research Institute',1);
SELECT name, agency, missions, RANK() OVER (PARTITION BY agency ORDER BY missions DESC) as mission_rank FROM Astronauts WHERE gender = 'Female';
Delete all cases from the 'criminal_cases' table where the case outcome is 'not guilty' and the attorney's ID is 458.
CREATE TABLE criminal_cases (case_id INT PRIMARY KEY,client_name VARCHAR(255),attorney_id INT,case_outcome VARCHAR(50));
DELETE FROM criminal_cases WHERE case_outcome = 'not guilty' AND attorney_id = 458;
What is the total weight of items in the warehouse located in Tokyo?
CREATE TABLE warehouses (id INT,location VARCHAR(255),weight INT); INSERT INTO warehouses (id,location,weight) VALUES (1,'Houston',1000),(2,'New York',2000),(3,'Tokyo',3000);
SELECT SUM(weight) FROM warehouses WHERE location = 'Tokyo';
What is the number of students who have a higher mental health score than the average mental health score of students who have not participated in lifelong learning activities?
CREATE TABLE students (student_id INT,mental_health_score INT,participated_in_lifelong_learning BOOLEAN); INSERT INTO students (student_id,mental_health_score,participated_in_lifelong_learning) VALUES (1,80,FALSE),(2,70,FALSE),(3,90,TRUE),(4,60,FALSE);
SELECT COUNT(*) FROM students s1 WHERE s1.mental_health_score > (SELECT AVG(s2.mental_health_score) FROM students s2 WHERE s2.participated_in_lifelong_learning = FALSE);
What is the total quantity of garments sold per garment category?
CREATE TABLE garment_sales (sales_id INT PRIMARY KEY,garment_id INT,store_id INT,quantity INT,price DECIMAL(5,2),date DATE); CREATE TABLE garments (garment_id INT PRIMARY KEY,garment_name TEXT,garment_category TEXT,sustainability_score INT); INSERT INTO garments (garment_id,garment_name,garment_category,sustainability_score) VALUES (1,'Cotton Shirt','Tops',80),(2,'Denim Jeans','Bottoms',60),(3,'Silk Scarf','Accessories',90);
SELECT g.garment_category, SUM(gs.quantity) as total_quantity FROM garment_sales gs JOIN garments g ON gs.garment_id = g.garment_id GROUP BY g.garment_category;
What is the maximum research grant amount awarded in the Engineering department?
CREATE SCHEMA if not exists higher_ed;CREATE TABLE if not exists higher_ed.faculty(id INT,name VARCHAR(255),department VARCHAR(255),grant_amount DECIMAL(10,2));
SELECT MAX(grant_amount) FROM higher_ed.faculty WHERE department = 'Engineering';
What is the average property size in the sustainable_urbanism table?
CREATE TABLE sustainable_urbanism (property_id INT,size FLOAT,location VARCHAR(255)); INSERT INTO sustainable_urbanism (property_id,size,location) VALUES (1,1200,'Eco City'),(2,1500,'Green Valley');
SELECT AVG(size) FROM sustainable_urbanism;
Insert a new astronaut 'Hiroshi Tanaka' from Japan.
CREATE TABLE Astronauts (Astronaut_ID INT,Name VARCHAR(255),Country VARCHAR(255));
INSERT INTO Astronauts (Name, Country) VALUES ('Hiroshi Tanaka', 'Japan');
How many water conservation initiatives were implemented in Canada between 2015 and 2018?
CREATE TABLE conservation_initiatives (country VARCHAR(20),start_year INT,end_year INT,num_initiatives INT); INSERT INTO conservation_initiatives (country,start_year,end_year,num_initiatives) VALUES ('Canada',2015,2018,120);
SELECT num_initiatives FROM conservation_initiatives WHERE country = 'Canada' AND start_year <= 2018 AND end_year >= 2015;
Which cruelty-free certified products use ingredients sourced from the UK and France?
CREATE TABLE IngredientSources (ProductID INT,Ingredient VARCHAR(50),SourceCountry VARCHAR(50),PRIMARY KEY (ProductID,Ingredient)); INSERT INTO IngredientSources (ProductID,Ingredient,SourceCountry) VALUES (1,'Water','Canada'),(1,'Glycerin','UK'),(2,'Water','Mexico'),(2,'Glycerin','France'); CREATE TABLE CrueltyFreeCertifications (ProductID INT,CertificationDate DATE,Certifier VARCHAR(50),PRIMARY KEY (ProductID,CertificationDate)); INSERT INTO CrueltyFreeCertifications (ProductID,CertificationDate,Certifier) VALUES (1,'2020-12-01','Leaping Bunny'),(2,'2021-03-01','PETA');
SELECT ProductID FROM IngredientSources WHERE SourceCountry IN ('UK', 'France') GROUP BY ProductID HAVING COUNT(DISTINCT SourceCountry) = 2 INTERSECT SELECT ProductID FROM CrueltyFreeCertifications;
Calculate the average investment amount for companies in the 'renewable_energy' sector.
CREATE TABLE investments (investment_id INT,company_id INT,sector VARCHAR(20),investment_amount FLOAT); INSERT INTO investments (investment_id,company_id,sector,investment_amount) VALUES (101,1,'renewable_energy',50000),(102,2,'sustainable_agriculture',75000),(103,3,'green_transportation',60000);
SELECT AVG(investment_amount) FROM investments WHERE sector = 'renewable_energy';
What is the number of students who have improved their mental health score by more than 10 points?
CREATE TABLE student_mental_health_scores (student_id INT,mental_health_score INT,date DATE); INSERT INTO student_mental_health_scores (student_id,mental_health_score,date) VALUES (1,75,'2022-01-01'),(1,85,'2022-02-01'),(2,88,'2022-01-01'),(2,90,'2022-02-01'),(3,68,'2022-01-01'),(3,73,'2022-02-01'),(4,70,'2022-01-01'),(4,75,'2022-02-01'),(5,72,'2022-01-01'),(5,82,'2022-02-01');
SELECT COUNT(DISTINCT student_id) as num_students_improved FROM (SELECT student_id, mental_health_score, LAG(mental_health_score) OVER (PARTITION BY student_id ORDER BY date) as previous_mental_health_score FROM student_mental_health_scores) subquery WHERE mental_health_score > previous_mental_health_score + 10;
What is the total revenue of organic cotton products in the USA?
CREATE TABLE OrganicCottonSales (product_id INT,product_name VARCHAR(255),sale_date DATE,revenue DECIMAL(10,2)); INSERT INTO OrganicCottonSales (product_id,product_name,sale_date,revenue) VALUES (1,'Organic Cotton T-Shirt','2021-01-02',25.99),(2,'Organic Cotton Hoodie','2021-01-03',49.99);
SELECT SUM(revenue) FROM OrganicCottonSales WHERE sale_date BETWEEN '2021-01-01' AND '2021-12-31' AND product_name LIKE '%Organic Cotton%' AND country = 'USA';
Update the ticket price of concert 'Rock the Bay' in 'ticket_sales' table to $120.
CREATE TABLE ticket_sales (sale_id INT,user_id INT,concert_name VARCHAR(255),quantity INT,total_price DECIMAL(5,2),date_purchased DATE);
UPDATE ticket_sales SET ticket_price = 120 WHERE concert_name = 'Rock the Bay';
List the total quantity of garments sold, by size and gender, from the 'sales_data' view, for the month of April 2022.
CREATE VIEW sales_data AS SELECT o.order_id,c.customer_gender,g.garment_size,g.garment_type,g.price,g.quantity,o.order_date FROM orders o JOIN customers c ON o.customer_id = c.customer_id JOIN order_items oi ON o.order_id = oi.order_id JOIN garments g ON oi.garment_id = g.garment_id;
SELECT customer_gender, garment_size, SUM(quantity) FROM sales_data WHERE EXTRACT(MONTH FROM order_date) = 4 GROUP BY customer_gender, garment_size;
What is the total amount of funding received by Indigenous art programs in Canada?
CREATE TABLE funding (id INT,program VARCHAR(50),country VARCHAR(50),amount INT); INSERT INTO funding (id,program,country,amount) VALUES (1,'Indigenous Arts Program','Canada',50000);
SELECT SUM(amount) FROM funding WHERE program = 'Indigenous Arts Program' AND country = 'Canada';
What is the maximum ticket price for concerts in the 'Hip Hop' genre?
CREATE TABLE ConcertGenre (ConcertID INT,GenreID INT); INSERT INTO ConcertGenre VALUES (7,3),(8,1),(9,2),(13,5);
SELECT MAX(TicketPrice) FROM Concerts JOIN ConcertGenre ON Concerts.ConcertID = ConcertGenre.ConcertID JOIN Genre ON ConcertGenre.GenreID = Genre.GenreID WHERE Genre.Genre = 'Hip Hop';
What is the total quantity of size 2XL clothing sold in the last month?
CREATE TABLE Sales (id INT,product_id INT,size VARCHAR(10),quantity INT,sale_date DATE); INSERT INTO Sales (id,product_id,size,quantity,sale_date) VALUES (1,1,'2XL',5,'2022-05-01'),(2,2,'XS',3,'2022-05-15');
SELECT SUM(quantity) FROM Sales WHERE size = '2XL' AND sale_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH);
Delete the record for the species "Atlantic ridley sea turtle" from the marine_species table.
CREATE TABLE marine_species (id INTEGER,scientific_name TEXT,common_name TEXT); INSERT INTO marine_species (id,scientific_name,common_name) VALUES (1,'Loligo opalescens','California market squid'); INSERT INTO marine_species (id,scientific_name,common_name) VALUES (2,'Lepidochelys kempii','Atlantic ridley sea turtle');
DELETE FROM marine_species WHERE common_name = 'Atlantic ridley sea turtle';
Which cruelty-free makeup brands are most popular in the UK?
CREATE TABLE makeup_sales (id INT,brand VARCHAR(50),category VARCHAR(50),sales INT,country VARCHAR(50)); INSERT INTO makeup_sales (id,brand,category,sales,country) VALUES (1,'Elate Cosmetics','Eye Shadow',200,'UK');
SELECT brand, SUM(sales) FROM makeup_sales WHERE category IN ('Lipstick', 'Mascara', 'Eye Shadow') AND country = 'UK' AND brand NOT IN ('Brand A', 'Brand B') GROUP BY brand ORDER BY SUM(sales) DESC;
Insert records of 2 new players for 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 teams (team_id,name,city) VALUES (1,'Boston Bruins','Boston'),(2,'New York Rangers','New York'),(3,'Seattle Kraken','Seattle');
INSERT INTO players (player_id, name, position, team_id) VALUES (6, 'Sofia Garcia', 'Forward', 3), (7, 'Hiroshi Tanaka', 'Defense', 3);
What is the average account balance of low-income borrowers in Latin America who have taken out socially responsible loans?
CREATE TABLE Customers (CustomerID int,IncomeLevel varchar(50),Location varchar(50)); INSERT INTO Customers (CustomerID,IncomeLevel,Location) VALUES (1,'Low Income','Latin America'); CREATE TABLE Loans (LoanID int,CustomerID int,Type varchar(50),SociallyResponsible bit); INSERT INTO Loans (LoanID,CustomerID,Type,SociallyResponsible) VALUES (1,1,'Personal Loan',1); CREATE TABLE Accounts (AccountID int,CustomerID int,Balance decimal(10,2)); INSERT INTO Accounts (AccountID,CustomerID,Balance) VALUES (1,1,500.00);
SELECT AVG(A.Balance) FROM Accounts A INNER JOIN Customers C ON A.CustomerID = C.CustomerID INNER JOIN Loans L ON C.CustomerID = L.CustomerID WHERE C.Location = 'Latin America' AND C.IncomeLevel = 'Low Income' AND L.SociallyResponsible = 1;
List mines with environmental impact assessments conducted in 2021
CREATE TABLE mine (id INT,name TEXT,location TEXT,eia_date DATE); INSERT INTO mine (id,name,location,eia_date) VALUES (1,'Emerald Edge','OR','2021-04-01'),(2,'Sapphire Slope','WA','2021-06-15'),(3,'Ruby Ridge','ID','2020-12-31'),(4,'Topaz Terrace','UT','2021-08-30'),(5,'Amethyst Acre','NV','2022-02-14');
SELECT name FROM mine WHERE EXTRACT(YEAR FROM eia_date) = 2021;
Which spacecraft have a mass greater than 6000 tons?
CREATE TABLE SpacecraftManufacturing (id INT,company VARCHAR(255),mass FLOAT); INSERT INTO SpacecraftManufacturing (id,company,mass) VALUES (1,'Aerospace Inc.',5000.0),(2,'Galactic Corp.',7000.0),(3,'Space Tech',6500.0);
SELECT * FROM SpacecraftManufacturing WHERE mass > 6000;
Find the percentage of traditional artists who have engaged in community events in the last 12 months?
CREATE TABLE artists (id INT,name VARCHAR(50),is_traditional_artist BOOLEAN);CREATE TABLE artist_event (id INT,artist_id INT,event_date DATE);
SELECT 100.0 * COUNT(DISTINCT CASE WHEN artist_event.event_date >= DATEADD(year, -1, GETDATE()) THEN artists.id END) / COUNT(DISTINCT artists.id) as pct_last_12_months FROM artists LEFT JOIN artist_event ON artists.id = artist_event.artist_id;
Insert a new record into the customer_preferences table for a customer who prefers vegan options
CREATE TABLE customer_preferences (customer_preference_id INT,customer_id INT,preference VARCHAR(20),created_at TIMESTAMP);
INSERT INTO customer_preferences (customer_id, preference, created_at) VALUES (1, 'Vegan', NOW());
What is the total investment amount for the real estate sector?
CREATE TABLE investments (investment_id INT,sector VARCHAR(20),investment_amount DECIMAL(10,2)); INSERT INTO investments (investment_id,sector,investment_amount) VALUES (1,'Real Estate',250000.00),(2,'Technology',500000.00);
SELECT SUM(investment_amount) FROM investments WHERE sector = 'Real Estate';
What is the average quantity of goods, in metric tons, shipped from the United States to Canada via the Pacific Ocean?
CREATE TABLE shipping_routes (id INT,departure_country VARCHAR(50),arrival_country VARCHAR(50),departure_region VARCHAR(50),arrival_region VARCHAR(50),transportation_method VARCHAR(50),quantity FLOAT); INSERT INTO shipping_routes (id,departure_country,arrival_country,departure_region,arrival_region,transportation_method,quantity) VALUES (1,'United States','Canada','Pacific','Pacific','Ship',5000.3);
SELECT AVG(quantity) FROM shipping_routes WHERE departure_country = 'United States' AND arrival_country = 'Canada' AND departure_region = 'Pacific' AND arrival_region = 'Pacific' AND transportation_method = 'Ship';
What is the total weight of cruelty-free ingredients for each product?
CREATE TABLE product (product_id INT,product_name TEXT); CREATE TABLE ingredient (ingredient_id INT,product_id INT,weight FLOAT,cruelty_free BOOLEAN); INSERT INTO product VALUES (1,'Lipstick'),(2,'Moisturizer'); INSERT INTO ingredient VALUES (1,1,50.0,true),(2,1,25.0,false),(3,2,30.0,true);
SELECT p.product_name, SUM(i.weight) FROM product p JOIN ingredient i ON p.product_id = i.product_id WHERE i.cruelty_free = true GROUP BY p.product_name;
Update the start year of the student with id 2 to 2022.
CREATE TABLE students (id INT,region TEXT,start_year INT); INSERT INTO students (id,region,start_year) VALUES (1,'Nigeria',2019),(2,'Brazil',2020);
UPDATE students SET start_year = 2022 WHERE id = 2;
How many bookings were made through OTA channels for each region in Q2 of 2022?
CREATE TABLE bookings (booking_id INT,hotel_id INT,booking_date DATE,booking_channel TEXT); INSERT INTO bookings (booking_id,hotel_id,booking_date,booking_channel) VALUES (1,1,'2022-04-01','OTA'),(2,2,'2022-05-15','Direct'),(3,1,'2022-06-30','OTA'); CREATE TABLE hotels (hotel_id INT,region TEXT); INSERT INTO hotels (hotel_id,region) VALUES (1,'Northeast'),(2,'West Coast');
SELECT region, COUNT(*) FROM bookings b JOIN hotels h ON b.hotel_id = h.hotel_id WHERE EXTRACT(QUARTER FROM booking_date) = 2 AND booking_channel = 'OTA' GROUP BY region;
What is the distribution of aircraft manufacturing by company and year?
CREATE TABLE AircraftManufacturing (id INT,company VARCHAR(50),manufacture_year INT,quantity INT); INSERT INTO AircraftManufacturing (id,company,manufacture_year,quantity) VALUES (1,'Boeing',2010,200),(2,'Boeing',2015,250),(3,'Airbus',2017,300),(4,'Airbus',2018,350),(5,'Embraer',2020,200);
SELECT company, manufacture_year, SUM(quantity) as total_aircrafts FROM AircraftManufacturing GROUP BY company, manufacture_year;
Show the total value of digital assets owned by developers from Asia in June 2022.
CREATE TABLE developers (developer_id INT,developer_name VARCHAR(100),developer_country VARCHAR(50),date_of_birth DATE,assets_value FLOAT); CREATE TABLE assets (asset_id INT,developer_id INT,asset_name VARCHAR(100),asset_value FLOAT); INSERT INTO developers VALUES (1,'Han','China','1988-07-08',5000); INSERT INTO developers VALUES (2,'Kim','South Korea','1991-03-20',3000); INSERT INTO assets VALUES (1,1,'Asset1',1500); INSERT INTO assets VALUES (2,1,'Asset2',2000); INSERT INTO assets VALUES (3,2,'Asset3',2500);
SELECT d.developer_country, SUM(assets_value) as total_value FROM developers d JOIN assets a ON d.developer_id = a.developer_id WHERE d.date_of_birth BETWEEN '1980-01-01' AND '2000-12-31' AND d.developer_country IN ('China', 'South Korea', 'India', 'Japan', 'Singapore') AND a.assets_value IS NOT NULL GROUP BY d.developer_country;
What is the total revenue generated from fair trade products?
CREATE TABLE sales (sale_id INT,product_id INT,sale_amount DECIMAL(5,2)); INSERT INTO sales (sale_id,product_id,sale_amount) VALUES (1,1,25.99),(2,2,19.99),(3,3,39.99),(4,1,25.99); CREATE TABLE products (product_id INT,is_fair_trade BOOLEAN); INSERT INTO products (product_id,is_fair_trade) VALUES (1,TRUE),(2,FALSE),(3,FALSE),(4,TRUE);
SELECT SUM(sale_amount) FROM sales JOIN products ON sales.product_id = products.product_id WHERE products.is_fair_trade = TRUE;
What is the total CO2 emissions for flights between Australia and New Zealand in 2019?
CREATE TABLE flights(flight_id INT,origin TEXT,destination TEXT,year INT,distance INT,CO2_emissions INT);INSERT INTO flights (flight_id,origin,destination,year,distance,CO2_emissions) VALUES (1,'Sydney','Auckland',2019,2166,108300),(2,'Melbourne','Wellington',2019,1972,98600),(3,'Brisbane','Christchurch',2019,2235,111750),(4,'Adelaide','Queenstown',2019,2446,122300),(5,'Perth','Dunedin',2019,3882,194100);
SELECT SUM(CO2_emissions) FROM flights WHERE origin IN ('Sydney', 'Melbourne', 'Brisbane', 'Adelaide', 'Perth') AND destination IN ('Auckland', 'Wellington', 'Christchurch', 'Queenstown', 'Dunedin') AND year = 2019;
What is the total claim amount for policy type 'Auto' in the Claims department for all time?
CREATE TABLE Claims (ClaimID INT,PolicyType VARCHAR(20),ProcessingDepartment VARCHAR(20),ProcessingDate DATE,ClaimAmount INT); INSERT INTO Claims (ClaimID,PolicyType,ProcessingDepartment,ProcessingDate,ClaimAmount) VALUES (1,'Auto','Claims','2023-01-10',5000),(2,'Home','Risk Assessment','2023-02-15',20000);
SELECT PolicyType, SUM(ClaimAmount) as TotalClaimAmount FROM Claims WHERE ProcessingDepartment = 'Claims' AND PolicyType = 'Auto' GROUP BY PolicyType;
Compare the energy storage capacities of utility-scale batteries and pumped hydro storage systems in the United States.
CREATE TABLE us_battery_storage (storage_type VARCHAR(20),capacity INT); INSERT INTO us_battery_storage (storage_type,capacity) VALUES ('Utility-scale Batteries',25000),('Pumped Hydro Storage',150000);
SELECT capacity FROM us_battery_storage WHERE storage_type = 'Utility-scale Batteries' INTERSECT SELECT capacity FROM us_battery_storage WHERE storage_type = 'Pumped Hydro Storage';
Show the total number of followers gained and lost by users from India, grouped by month.
CREATE TABLE user_activity (id INT,user_id INT,activity_type VARCHAR(50),activity_date DATE,followers INT); INSERT INTO user_activity (id,user_id,activity_type,activity_date,followers) VALUES (1,1,'Followers Gained','2022-03-01',50),(2,2,'Followers Lost','2022-03-02',-30),(3,3,'Followers Gained','2022-03-03',25),(4,4,'Followers Lost','2022-03-04',-10),(5,5,'Followers Gained','2022-03-05',40); CREATE TABLE users (id INT,country VARCHAR(50)); INSERT INTO users (id,country) VALUES (1,'India'),(2,'India'),(3,'India'),(4,'India'),(5,'India');
SELECT DATE_FORMAT(activity_date, '%Y-%m') as month, SUM(CASE WHEN activity_type = 'Followers Gained' THEN followers ELSE -followers END) as net_followers FROM user_activity JOIN users ON user_activity.user_id = users.id WHERE users.country = 'India' GROUP BY month;
What is the minimum trip duration for American tourists visiting Europe in 2022?
CREATE TABLE tourism_stats (id INT PRIMARY KEY,year INT,country VARCHAR(255),destination VARCHAR(255),duration INT); INSERT INTO tourism_stats (id,year,country,destination,duration) VALUES (1,2022,'USA','France',7),(2,2022,'USA','Italy',10),(3,2022,'USA','Spain',5);
SELECT MIN(duration) FROM tourism_stats WHERE country = 'USA' AND destination LIKE 'Europe%' AND year = 2022;
Insert data about an excavation site into the Excavation_Sites table
CREATE TABLE Excavation_Sites (id INT PRIMARY KEY,name VARCHAR(255),location TEXT,country VARCHAR(255)); INSERT INTO Excavation_Sites (id,name,location,country) VALUES (1,'Pompeii','Near Naples,Italy','Italy');
INSERT INTO Excavation_Sites (id, name, location, country) VALUES (2, 'Machu Picchu', 'Andes Mountains, Peru', 'Peru');
What is the percentage of smokers in Japan?
CREATE TABLE Smoking (ID INT,Country VARCHAR(100),Year INT,SmokerPercentage FLOAT); INSERT INTO Smoking (ID,Country,Year,SmokerPercentage) VALUES (1,'Japan',2020,17.8);
SELECT SmokerPercentage FROM Smoking WHERE Country = 'Japan' AND Year = 2020;
What was the total cost of economic diversification projects in the 'Diversification' table implemented in 2016 or earlier, for projects in 'Africa'?
CREATE TABLE Diversification (id INT,project VARCHAR(255),country VARCHAR(255),year INT,cost FLOAT); INSERT INTO Diversification (id,project,country,year,cost) VALUES (1,'Agro-Processing Plant','Morocco',2015,4000000),(2,'Tourism Complex','Egypt',2017,8000000),(3,'Textile Factory','Tunisia',2016,5000000),(4,'IT Hub','Algeria',2018,9000000);
SELECT SUM(cost) as total_cost FROM Diversification WHERE year <= 2016 AND country LIKE 'Africa%';
What is the average duration of all missions to Mars?
CREATE TABLE Missions (MissionID INT,Name VARCHAR(100),Destination VARCHAR(50),Duration FLOAT);
SELECT AVG(Duration) FROM Missions WHERE Destination = 'Mars';
Find the average speed of Nigerian-flagged vessels traveling to Port L in the last 10 days of each month in 2019.
CREATE TABLE Vessels (id INT,name TEXT,speed FLOAT,flag_country TEXT,arrive_port TEXT,arrive_date DATE); INSERT INTO Vessels (id,name,speed,flag_country,arrive_port,arrive_date) VALUES (1,'Vessel1',24.5,'Nigeria','Port L','2019-01-25'); INSERT INTO Vessels (id,name,speed,flag_country,arrive_port,arrive_date) VALUES (2,'Vessel2',26.0,'Nigeria','Port L','2019-02-22');
SELECT arrive_port, AVG(speed) FROM Vessels WHERE flag_country = 'Nigeria' AND arrive_port = 'Port L' AND DATE_TRUNC('month', arrive_date) = DATE_TRUNC('month', arrive_date - INTERVAL '10 days') AND EXTRACT(YEAR FROM arrive_date) = 2019 GROUP BY arrive_port;
What is the number of hospitals in rural areas of Texas, California, and New York?
CREATE TABLE hospitals (id INT,name TEXT,location TEXT); INSERT INTO hospitals (id,name,location) VALUES (1,'Hospital A','Rural Texas'); INSERT INTO hospitals (id,name,location) VALUES (2,'Hospital B','Rural California'); INSERT INTO hospitals (id,name,location) VALUES (3,'Hospital C','Rural New York');
SELECT COUNT(*) FROM hospitals WHERE location IN ('Rural Texas', 'Rural California', 'Rural New York');
Show carbon offset programs in the 'Southeast' region and their respective offset amounts
CREATE TABLE southeast_offsets (id INT,program_name TEXT,region TEXT,offset_amount INT); INSERT INTO southeast_offsets (id,program_name,region,offset_amount) VALUES (1,'GreenTrees','Southeast',12000),(2,'Carbonfund','Southeast',18000),(3,'TerraPass','Southeast',24000);
SELECT program_name, offset_amount FROM southeast_offsets WHERE region = 'Southeast';
How many artists in the 'artists' table are from each continent?
CREATE TABLE artists (artist_id INT,name VARCHAR(50),age INT,country VARCHAR(50)); INSERT INTO artists (artist_id,name,age,country) VALUES (1,'Pablo Picasso',91,'Spain'); INSERT INTO artists (artist_id,name,age,country) VALUES (2,'Francis Bacon',82,'Ireland'); INSERT INTO artists (artist_id,name,age,country) VALUES (3,'Piet Mondrian',71,'Netherlands'); CREATE TABLE countries (country VARCHAR(50),continent VARCHAR(50)); INSERT INTO countries (country,continent) VALUES ('Spain','Europe'); INSERT INTO countries (country,continent) VALUES ('Ireland','Europe'); INSERT INTO countries (country,continent) VALUES ('Netherlands','Europe');
SELECT c.continent, COUNT(a.artist_id) as num_artists FROM artists a JOIN countries c ON a.country = c.country GROUP BY c.continent;
What is the total number of military bases and their respective countries?
CREATE TABLE military_bases (id INT,name VARCHAR(50),country VARCHAR(50)); INSERT INTO military_bases (id,name,country) VALUES (1,'Fort Bragg','USA'),(2,'Camp Pendleton','USA'),(3,'Canberra Deep Space Communication Complex','Australia');
SELECT COUNT(*) as total_bases, country FROM military_bases GROUP BY country;
How many different animals were observed in the 'arctic_animal_sightings' table for each month?
CREATE TABLE arctic_animal_sightings (id INT,date DATE,animal VARCHAR(255)); INSERT INTO arctic_animal_sightings (id,date,animal) VALUES (1,'2021-01-01','Polar Bear'),(2,'2021-02-01','Walrus'),(3,'2021-03-01','Fox');
SELECT MONTH(date) AS month, COUNT(DISTINCT animal) AS animal_count FROM arctic_animal_sightings GROUP BY month;
List all warehouses in Canada and the total quantity of items stored in each.
CREATE TABLE Warehouses(id INT,location VARCHAR(50),capacity INT); INSERT INTO Warehouses(id,location,capacity) VALUES (1,'Canada',1000); CREATE TABLE Inventory(id INT,warehouse_id INT,quantity INT); INSERT INTO Inventory(id,warehouse_id,quantity) VALUES (1,1,500);
SELECT Warehouses.location, SUM(Inventory.quantity) FROM Warehouses INNER JOIN Inventory ON Warehouses.id = Inventory.warehouse_id WHERE Warehouses.location = 'Canada' GROUP BY Warehouses.id;
Calculate the average geopolitical risk score for the Asia-Pacific region in Q2 2022.
CREATE TABLE geopolitical_risks(id INT,region VARCHAR(50),quarter INT,year INT,score FLOAT); INSERT INTO geopolitical_risks(id,region,quarter,year,score) VALUES (1,'Asia-Pacific',1,2022,4.5); INSERT INTO geopolitical_risks(id,region,quarter,year,score) VALUES (2,'Asia-Pacific',2,2022,5.0);
SELECT AVG(score) FROM geopolitical_risks WHERE region = 'Asia-Pacific' AND quarter = 2 AND year = 2022;
Update diplomacy staff salaries to be 5% higher than their current amount.
CREATE TABLE diplomacy_staff (staff_id INT,name VARCHAR(255),position VARCHAR(255),salary INT); INSERT INTO diplomacy_staff (staff_id,name,position,salary) VALUES (1,'John Doe','Ambassador',75000),(2,'Jane Smith','Consul',50000),(3,'Michael Johnson','Diplomatic Attaché',60000);
UPDATE diplomacy_staff SET salary = salary * 1.05;
What is the average well depth for wells in the 'North Sea' region?
CREATE TABLE wells (well_id INT,well_name VARCHAR(255),well_depth FLOAT,region VARCHAR(255)); INSERT INTO wells (well_id,well_name,well_depth,region) VALUES (1,'A1',3000,'North Sea'),(2,'B2',2500,'North Sea'),(3,'C3',4000,'Gulf of Mexico');
SELECT AVG(well_depth) FROM wells WHERE region = 'North Sea';
What is the average workplace safety score for manufacturing unions in Germany?
CREATE TABLE unions (id INT,name TEXT,location TEXT,type TEXT,safety_score INT); INSERT INTO unions (id,name,location,type,safety_score) VALUES (1,'Union A','Germany','Manufacturing',85),(2,'Union B','France','Manufacturing',80);
SELECT AVG(safety_score) FROM unions WHERE location = 'Germany' AND type = 'Manufacturing';
What is the total number of students in each school district?
CREATE TABLE school_districts (district_id INT,district_name TEXT,num_students INT);
SELECT district_name, SUM(num_students) as total_students FROM school_districts GROUP BY district_name;
What is the total funding allocated for climate communication initiatives in Europe in 2022?
CREATE TABLE climate_mitigation (id INT,initiative_name VARCHAR(50),location VARCHAR(50),allocated_funding FLOAT,funding_year INT); INSERT INTO climate_mitigation (id,initiative_name,location,allocated_funding,funding_year) VALUES (1,'Green Media Campaign','Europe',500000,2022);
SELECT SUM(allocated_funding) FROM climate_mitigation WHERE location = 'Europe' AND funding_year = 2022 AND initiative_name LIKE '%climate communication%';
What is the percentage of total streams for each artist?
CREATE TABLE AlbumStreams (AlbumID int,SongID int,StreamCount int,ArtistID int); INSERT INTO AlbumStreams (AlbumID,SongID,StreamCount,ArtistID) VALUES (1,1,1000,1),(2,2,2000,2),(3,3,1500,3),(4,4,2500,4),(5,5,1800,5);
SELECT Artists.ArtistName, (SUM(AlbumStreams.StreamCount) / (SELECT SUM(StreamCount) FROM AlbumStreams) * 100) as Percentage FROM Artists INNER JOIN AlbumStreams ON Artists.ArtistID = AlbumStreams.ArtistID GROUP BY Artists.ArtistName;
What is the total quantity of fair trade products sold in South America?
CREATE TABLE regions (id INT,name TEXT); INSERT INTO regions (id,name) VALUES (1,'North America'),(2,'South America'),(3,'Europe'),(4,'Asia'),(5,'Africa'); CREATE TABLE products (id INT,name TEXT,is_fair_trade BOOLEAN); INSERT INTO products (id,name,is_fair_trade) VALUES (1,'Product X',true),(2,'Product Y',false),(3,'Product Z',true),(4,'Product W',false); CREATE TABLE sales (id INT,product TEXT,quantity INT,region TEXT); INSERT INTO sales (id,product,quantity,region) VALUES (1,'Product X',100,'South America'),(2,'Product Y',150,'North America'),(3,'Product Z',80,'Europe'),(4,'Product W',120,'Asia');
SELECT SUM(sales.quantity) FROM sales INNER JOIN regions ON sales.region = regions.name INNER JOIN products ON sales.product = products.name WHERE products.is_fair_trade = true AND regions.name = 'South America';
Rank military equipment maintenance requests by the number of requests per month in descending order.
CREATE TABLE Maintenance_Requests (Equipment VARCHAR(50),Request_Month DATE,Quantity INT); INSERT INTO Maintenance_Requests (Equipment,Request_Month,Quantity) VALUES ('F-16','2022-01-01',3),('F-35','2022-01-01',5),('A-10','2022-01-01',2),('F-16','2022-02-01',4),('F-35','2022-02-01',6),('A-10','2022-02-01',1);
SELECT Equipment, ROW_NUMBER() OVER (ORDER BY SUM(Quantity) DESC) as Rank FROM Maintenance_Requests GROUP BY Equipment;
What is the maximum property tax rate for properties in each neighborhood?
CREATE TABLE Neighborhoods (NeighborhoodID INT,NeighborhoodName VARCHAR(255)); CREATE TABLE PropertyTaxRates (PropertyTaxRateID INT,NeighborhoodID INT,Rate DECIMAL(5,2));
SELECT N.NeighborhoodName, MAX(PTR.Rate) as MaxRate FROM Neighborhoods N JOIN PropertyTaxRates PTR ON N.NeighborhoodID = PTR.NeighborhoodID GROUP BY N.NeighborhoodName;
What is the total revenue generated from 'Premium' memberships in the 'Midwest' region for the year 2022?
CREATE SCHEMA fitness; CREATE TABLE memberships (id INT,member_name VARCHAR(50),region VARCHAR(50),membership_type VARCHAR(50),price DECIMAL(5,2),start_date DATE,end_date DATE); INSERT INTO memberships (id,member_name,region,membership_type,price,start_date,end_date) VALUES (1,'John Doe','Midwest','Premium',79.99,'2022-01-01','2022-12-31');
SELECT SUM(price) FROM fitness.memberships WHERE region = 'Midwest' AND membership_type = 'Premium' AND YEAR(start_date) = 2022 AND YEAR(end_date) = 2022;
Delete all comments made by a user from France before 2022-08-01.
CREATE TABLE comments (id INT,post_id INT,user_id INT,text TEXT,created_date DATE); INSERT INTO comments (id,post_id,user_id,text,created_date) VALUES (1,1,6,'Great article!','2022-07-01'),(2,2,6,'Thank you for sharing.','2022-08-15');
DELETE FROM comments WHERE user_id IN (SELECT user_id FROM comments WHERE country = 'France') AND created_date < '2022-08-01'
Delete properties with inclusive housing policies that have expired over a year ago.
CREATE TABLE Property (id INT PRIMARY KEY,address VARCHAR(255),city VARCHAR(255),state VARCHAR(255),zip INT,co_owners INT,sustainable_features VARCHAR(255),price INT); CREATE TABLE InclusiveHousing (id INT PRIMARY KEY,property_id INT,policy_type VARCHAR(255),start_date DATE,end_date DATE);
DELETE FROM Property WHERE id IN (SELECT Property.id FROM Property INNER JOIN InclusiveHousing ON Property.id = InclusiveHousing.property_id WHERE end_date < DATE_SUB(CURDATE(), INTERVAL 1 YEAR));
What is the average production of Lutetium per country in 2019?
CREATE TABLE production (country VARCHAR(255),element VARCHAR(255),quantity INT,year INT); INSERT INTO production (country,element,quantity,year) VALUES ('China','Lutetium',2000,2019),('China','Lutetium',2500,2019),('India','Lutetium',1000,2019),('India','Lutetium',1200,2019);
SELECT country, AVG(quantity) as avg_production FROM production WHERE element = 'Lutetium' AND year = 2019 GROUP BY country;
Find the percentage of patients who received therapy
CREATE TABLE patients_treatments (patient_id INT,treatment VARCHAR(20)); INSERT INTO patients_treatments (patient_id,treatment) VALUES (1,'therapy');
SELECT (COUNT(CASE WHEN treatment = 'therapy' THEN 1 END) * 100.0 / COUNT(*)) AS therapy_percentage FROM patients_treatments;
Delete records of community engagement events that have been cancelled or do not have a specified event type.
CREATE TABLE CommunityEvents (event_id INT,event_name VARCHAR(20),event_type VARCHAR(10),event_status VARCHAR(10)); CREATE TABLE EventDates (event_id INT,event_date DATE);
DELETE FROM CommunityEvents WHERE event_status = 'Cancelled' OR event_type IS NULL; DELETE FROM EventDates WHERE event_id NOT IN (SELECT event_id FROM CommunityEvents);
Number of travel advisories issued for Brazil in the past 6 months
CREATE TABLE advisories (country VARCHAR(255),issue_date DATE); INSERT INTO advisories (country,issue_date) VALUES ('Brazil','2022-05-12'),('Brazil','2022-03-28');
SELECT COUNT(*) FROM advisories WHERE country = 'Brazil' AND issue_date >= DATEADD(month, -6, GETDATE());
What is the revenue generated by each sustainable hotel in Portugal last month?
CREATE TABLE bookings (id INT,hotel_id INT,tourist_id INT,cost FLOAT,date DATE); CREATE TABLE hotels (id INT,name TEXT,location TEXT,country TEXT,sustainable BOOLEAN); INSERT INTO bookings (id,hotel_id,tourist_id,cost,date) VALUES (1,1,101,100.00,'2022-02-01'),(2,2,102,120.00,'2022-02-10'); INSERT INTO hotels (id,name,location,country,sustainable) VALUES (1,'Eco Hotel Lisbon','Lisbon','Portugal',true),(2,'Green Hotel Porto','Porto','Portugal',true);
SELECT hotel_id, SUM(cost) FROM bookings INNER JOIN hotels ON bookings.hotel_id = hotels.id WHERE country = 'Portugal' AND sustainable = true AND date >= DATEADD(day, -30, GETDATE()) GROUP BY hotel_id;
Delete all records from the 'space_events' table that occurred before the year 2000
CREATE TABLE space_events (id INT PRIMARY KEY,name VARCHAR(50),year INT); INSERT INTO space_events (id,name,year) VALUES (1,'First Satellite Launched',1957),(2,'First Human in Space',1961),(3,'First Spacewalk',1965),(4,'First Space Station',1971),(5,'First Image of a Black Hole',2019);
DELETE FROM space_events WHERE year < 2000;
Calculate the total sales for each day of the week
CREATE TABLE sales (day VARCHAR(255),sales DECIMAL(10,2)); INSERT INTO sales (day,sales) VALUES ('Monday',1500),('Tuesday',1700),('Wednesday',1200),('Thursday',2000),('Friday',2500),('Saturday',3000),('Sunday',1800);
SELECT day, SUM(sales) as total_sales FROM sales GROUP BY day;
What is the average annual military spending by 'Germany' in the last 5 years?
CREATE TABLE military_spending (country TEXT,year INT,amount INT); INSERT INTO military_spending (country,year,amount) VALUES ('Germany',2018,45000000);
SELECT AVG(amount) AS avg_annual_spending FROM military_spending WHERE country = 'Germany' AND year BETWEEN YEAR(DATE_SUB(CURDATE(), INTERVAL 5 YEAR)) AND YEAR(CURDATE());
What is the rank of military innovation events by country based on frequency?
CREATE TABLE MilitaryInnovation(Country NVARCHAR(50),EventType VARCHAR(50),Year INT);INSERT INTO MilitaryInnovation(Country,EventType,Year) VALUES ('United States','Drone Technology',2015),('China','Artificial Intelligence',2016),('United States','Cybersecurity',2017),('China','Hypersonic Weapons',2018),('United States','Quantum Computing',2019),('China','Robotics',2020);
SELECT Country, RANK() OVER(ORDER BY COUNT(*) DESC) AS Event_Rank FROM MilitaryInnovation GROUP BY Country;
Delete all records with accommodation type "mobility_aids" from the "accommodations" table
CREATE TABLE accommodations (id INT,student_id INT,accommodation_type VARCHAR(255),cost FLOAT); INSERT INTO accommodations (id,student_id,accommodation_type,cost) VALUES (1,123,'visual_aids',250.0),(2,456,'audio_aids',100.0),(3,789,'large_print_materials',120.0),(4,890,'mobility_aids',300.0);
DELETE FROM accommodations WHERE accommodation_type = 'mobility_aids';
What is the total number of labor hours spent on sustainable building projects in the state of California?
CREATE TABLE construction_labor (id INT,worker_name VARCHAR(50),hours_worked INT,project_type VARCHAR(20),state VARCHAR(20)); INSERT INTO construction_labor (id,worker_name,hours_worked,project_type,state) VALUES (1,'John Doe',100,'Sustainable','California');
SELECT SUM(hours_worked) FROM construction_labor WHERE project_type = 'Sustainable' AND state = 'California';
How many unique users posted content in April?
CREATE TABLE posts (id INT,user_id INT,post_date DATE); INSERT INTO posts (id,user_id,post_date) VALUES (1,1,'2022-01-01'),(2,2,'2022-01-02'),(3,3,'2022-04-01'),(4,4,'2022-03-01'),(5,5,'2022-04-15'),(6,6,'2022-04-30');
SELECT COUNT(DISTINCT user_id) FROM posts WHERE MONTH(post_date) = 4;
What is the average attendance for cultural events in the 'music' category, and how many events are there in total for this category?
CREATE TABLE event_attendance (id INT,event TEXT,category TEXT,attendees INT); INSERT INTO event_attendance (id,event,category,attendees) VALUES (1,'Concert','music',1000),(2,'Jazz Festival','music',2000),(3,'Theatre Play','theatre',1500);
SELECT category, AVG(attendees) as avg_attendance, COUNT(DISTINCT event) as num_events FROM event_attendance WHERE category = 'music' GROUP BY category;
What is the maximum budget allocated for healthcare services in each region?
CREATE TABLE HealthcareBudget (Region VARCHAR(50),Year INT,Budget FLOAT); INSERT INTO HealthcareBudget VALUES ('North',2018,12000000),('South',2019,13000000),('East',2020,14000000),('West',2021,15000000);
SELECT Region, MAX(Budget) OVER (PARTITION BY Year) AS MaxBudget FROM HealthcareBudget;
What is the number of policy advocacy initiatives implemented in each year by region?
CREATE TABLE policy_advocacy (initiative_id INT,initiative_name VARCHAR(50),implementation_year INT,region VARCHAR(50)); INSERT INTO policy_advocacy (initiative_id,initiative_name,implementation_year,region) VALUES (1,'Accessible Curriculum',2018,'Northeast');
SELECT region, implementation_year, COUNT(*) as initiatives_per_year FROM policy_advocacy GROUP BY region, implementation_year;
Insert a new record for an employee from the 'Operations' department who joined the 'Team Building' training program.
CREATE TABLE training_operations (id INT,name VARCHAR(50),department VARCHAR(50),program VARCHAR(50));
INSERT INTO training_operations (id, name, department, program) VALUES (2, 'Clara Garcia', 'Operations', 'Team Building');
Delete all records from the 'athlete_wellbeing' table where the 'wellbeing_program' is 'Yoga'
CREATE TABLE athlete_wellbeing (athlete_id INT,wellbeing_program VARCHAR(20)); INSERT INTO athlete_wellbeing (athlete_id,wellbeing_program) VALUES (1,'Yoga'),(2,'Meditation'),(3,'Stretching');
DELETE FROM athlete_wellbeing WHERE wellbeing_program = 'Yoga';
What is the average claim amount for each policy type, excluding policy types with fewer than 3 policies?
CREATE TABLE Claims (ClaimID INT,PolicyID INT,ClaimAmount DECIMAL(10,2)); CREATE TABLE Policy (PolicyID INT,PolicyType VARCHAR(20)); INSERT INTO Claims (ClaimID,PolicyID,ClaimAmount) VALUES (1,1,1500.00),(2,2,250.00),(3,3,500.00),(4,1,1000.00); INSERT INTO Policy (PolicyID,PolicyType) VALUES (1,'Homeowners'),(2,'Auto'),(3,'Renters'),(4,'Homeowners'),(5,'Homeowners');
SELECT Policy.PolicyType, AVG(Claims.ClaimAmount) AS AvgClaimAmount FROM Policy INNER JOIN Claims ON Policy.PolicyID = Claims.PolicyID GROUP BY Policy.PolicyType HAVING COUNT(DISTINCT Policy.PolicyID) >= 3;
List the names and research interests of all faculty members in the 'Social Sciences' department
CREATE TABLE faculty (id INT,name VARCHAR(30),department VARCHAR(20),research_interest TEXT); INSERT INTO faculty (id,name,department,research_interest) VALUES (1,'John Doe','Social Sciences','Inequality and Education'),(2,'Jane Smith','Natural Sciences','Climate Change');
SELECT name, research_interest FROM faculty WHERE department = 'Social Sciences';
How many individuals have accessed legal aid services in Texas and New York?
CREATE TABLE LegalAidServices (ServiceID INT,ClientName VARCHAR(50),State VARCHAR(20)); INSERT INTO LegalAidServices VALUES (1,'Client A','Texas'); INSERT INTO LegalAidServices VALUES (2,'Client B','Texas'); INSERT INTO LegalAidServices VALUES (3,'Client C','New York');
SELECT COUNT(*) FROM LegalAidServices WHERE State IN ('Texas', 'New York');
What is the average price of products for each brand, ranked by the average price?
CREATE TABLE brands (brand_id INT,brand_name VARCHAR(50)); INSERT INTO brands VALUES (1,'Lush'),(2,'The Body Shop'),(3,'Sephora'),(4,'Ulta'); CREATE TABLE products (product_id INT,product_name VARCHAR(50),price DECIMAL(5,2),brand_id INT); INSERT INTO products VALUES (1,'Face Wash',15.99,1),(2,'Moisturizer',25.49,1),(3,'Scrub',12.50,2),(4,'Lip Balm',4.99,2),(5,'Eye Shadow Palette',35.00,3),(6,'Mascara',14.99,3),(7,'Foundation',29.99,4),(8,'Blush',12.99,4);
SELECT brand_name, AVG(price) as avg_price FROM products JOIN brands ON products.brand_id = brands.brand_id GROUP BY brand_name ORDER BY avg_price DESC;
What is the number of military innovation projects and their total budget for each country in the Asia-Pacific region in the last 7 years?
CREATE TABLE Military_Innovation_Projects (id INT,country VARCHAR(50),year INT,project VARCHAR(50),budget INT);
SELECT country, COUNT(project) as projects, SUM(budget) as total_budget FROM Military_Innovation_Projects WHERE region = 'Asia-Pacific' AND year BETWEEN (YEAR(CURRENT_DATE) - 7) AND YEAR(CURRENT_DATE) GROUP BY country;
What is the minimum reservoir capacity of a dam in the 'dam_reservoirs' table?
CREATE TABLE dam_reservoirs (dam_id INT,dam_name VARCHAR(50),reservoir_name VARCHAR(50),reservoir_capacity INT);
SELECT MIN(reservoir_capacity) FROM dam_reservoirs;
Create a table for storing information about disability support programs
CREATE TABLE support_programs (program_id INT PRIMARY KEY,name VARCHAR(255),description TEXT,category VARCHAR(255));
CREATE TABLE if not exists support_programs_new AS SELECT * FROM support_programs WHERE 1=0;
Insert records in the vessel_safety table for vessel "Island Breeze" with the following data: (2022-02-01, 'A')
CREATE TABLE vessel_safety (last_inspection_date DATE,last_inspection_grade CHAR(1),vessel_name VARCHAR(255));
INSERT INTO vessel_safety (last_inspection_date, last_inspection_grade, vessel_name) VALUES ('2022-02-01', 'A', 'Island Breeze');
Find the average price of organic fruits in the 'Produce' table
CREATE TABLE Produce (id INT PRIMARY KEY,name VARCHAR(255),type VARCHAR(255),price DECIMAL(5,2)); INSERT INTO Produce (id,name,type,price) VALUES (1,'Apples','Organic',1.99),(2,'Bananas','Organic',1.49);
SELECT AVG(price) FROM Produce WHERE type = 'Organic' AND name LIKE 'Fruits%';
Show all aircraft models and their associated manufacturers and launch dates.
CREATE TABLE aircraft (aircraft_id INT,model VARCHAR(100),manufacturer VARCHAR(100),launch_date DATE); INSERT INTO aircraft (aircraft_id,model,manufacturer,launch_date) VALUES (1,'Aircraft Model 1','Aviation Inc.','2015-01-01'); INSERT INTO aircraft (aircraft_id,model,manufacturer,launch_date) VALUES (2,'Aircraft Model 2','Flight Corp.','2020-05-15');
SELECT model, manufacturer, launch_date FROM aircraft;
What is the average rating of public libraries in the city of "Los Angeles"?
CREATE TABLE libraries (library_id INT,library_name TEXT,city TEXT,rating INT); INSERT INTO libraries (library_id,library_name,city,rating) VALUES (1,'Los Angeles Central Library','Los Angeles',8),(2,'Los Angeles Public Library','Los Angeles',7),(3,'Baldwin Hills Library','Los Angeles',9);
SELECT AVG(rating) FROM libraries WHERE city = 'Los Angeles' AND type = 'Public';
What is the change in water conservation efforts by month in 2020?
CREATE TABLE conservation_initiatives (date DATE,water_conserved FLOAT); INSERT INTO conservation_initiatives (date,water_conserved) VALUES ('2020-01-01',100000),('2020-02-01',150000),('2020-03-01',120000),('2020-04-01',180000);
SELECT EXTRACT(MONTH FROM date) AS month, AVG(water_conserved) AS avg_conserved FROM conservation_initiatives WHERE date BETWEEN '2020-01-01' AND '2020-12-31' GROUP BY month;
What is the earliest launch date of any satellite that is still in orbit?
CREATE TABLE satellites (satellite_id INT,satellite_name VARCHAR(100),country VARCHAR(50),launch_date DATE,in_orbit BOOLEAN); INSERT INTO satellites (satellite_id,satellite_name,country,launch_date,in_orbit) VALUES (1,'Sputnik 1','Russia','1957-10-04',TRUE); INSERT INTO satellites (satellite_id,satellite_name,country,launch_date,in_orbit) VALUES (2,'Explorer 1','United States','1958-01-31',TRUE);
SELECT MIN(launch_date) FROM satellites WHERE in_orbit = TRUE;
Which mobile subscribers in the city of New York have a data usage greater than 15 GB?
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,'New York',18.3),(2,'New York',12.5),(3,'Los Angeles',16.7);
SELECT subscriber_id FROM mobile_subscribers WHERE city = 'New York' AND data_usage_gb > 15;
How many job applicants in the recruitment database are from underrepresented racial or ethnic groups?
CREATE TABLE recruitment_database (id INT,applicant_race TEXT,applicant_ethnicity TEXT,application_date DATE); INSERT INTO recruitment_database (id,applicant_race,applicant_ethnicity,application_date) VALUES (1,'Asian','Not Hispanic or Latino','2022-03-01'),(2,'White','Not Hispanic or Latino','2022-03-02'),(3,'Black or African American','Hispanic or Latino','2022-03-03');
SELECT COUNT(*) as count FROM recruitment_database WHERE (applicant_race = 'Black or African American' OR applicant_race = 'Hispanic or Latino' OR applicant_race = 'American Indian or Alaska Native' OR applicant_race = 'Native Hawaiian or Other Pacific Islander') OR (applicant_ethnicity = 'Hispanic or Latino');
List all regulatory frameworks for decentralized applications in the EU.
CREATE TABLE daaps (id INT,name VARCHAR(255),regulatory_framework VARCHAR(255)); INSERT INTO daaps (id,name,regulatory_framework) VALUES (1,'Uniswap','MiCA'),(2,'Aave','AMLD'),(3,'Compound','eIDAS'); CREATE TABLE regions (id INT,name VARCHAR(255)); INSERT INTO regions (id,name) VALUES (1,'EU'),(2,'US'),(3,'APAC');
SELECT name FROM daaps INNER JOIN regions ON daaps.regulatory_framework = regions.name WHERE regions.name = 'EU';
Who is the top donor in April 2022?
CREATE TABLE Donations (DonationID INT,DonorID INT,DonationDate DATE,DonationAmount FLOAT);
SELECT DonorID, MAX(DonationAmount) as 'Highest Donation' FROM Donations WHERE DonationDate BETWEEN '2022-04-01' AND '2022-04-30' GROUP BY DonorID ORDER BY 'Highest Donation' DESC LIMIT 1;
Identify the top 5 cities with the most attendees
CREATE TABLE city_attendees (city VARCHAR(20),attendee_id INT); INSERT INTO city_attendees (city,attendee_id) VALUES ('NYC',1),('LA',2),('NYC',3),('Chicago',4);
SELECT city, COUNT(attendee_id) AS num_attendees FROM city_attendees GROUP BY city ORDER BY num_attendees DESC LIMIT 5;
What is the average heart rate for each member during 'Yoga' workouts in January 2022?
CREATE TABLE memberships (id INT,member_type VARCHAR(50),region VARCHAR(50)); CREATE TABLE workout_data (member_id INT,workout_type VARCHAR(50),duration INT,heart_rate_avg INT,calories_burned INT,workout_date DATE);
SELECT m.id, AVG(w.heart_rate_avg) as avg_heart_rate FROM memberships m JOIN workout_data w ON m.id = w.member_id WHERE w.workout_type = 'Yoga' AND w.workout_date >= DATE '2022-01-01' AND w.workout_date < DATE '2022-02-01' GROUP BY m.id;
List all job titles that have less than 3 employees and the number of employees in the "employee" and "job" tables
CREATE TABLE employee (id INT,job_id INT); CREATE TABLE job (id INT,title TEXT);
SELECT j.title, COUNT(e.id) AS num_employees FROM job j LEFT JOIN employee e ON j.id = e.job_id GROUP BY j.title HAVING COUNT(e.id) < 3;