instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
List the top 5 clients by the total billing amount, and their respective primary contact information.
CREATE TABLE Clients (ClientID INT,ClientName VARCHAR(255),PrimaryContactName VARCHAR(255),PrimaryContactEmail VARCHAR(255),BillingAmount DECIMAL);
SELECT ClientName, PrimaryContactName, PrimaryContactEmail, SUM(BillingAmount) FROM Clients GROUP BY ClientName, PrimaryContactName, PrimaryContactEmail ORDER BY SUM(BillingAmount) DESC LIMIT 5;
Who are the top 5 brands with the highest revenue in the natural makeup segment?
CREATE TABLE makeup_sales (product_id INT,product_name VARCHAR(255),sale_price DECIMAL(10,2),brand_id INT,country VARCHAR(255)); CREATE TABLE brands (brand_id INT,brand_name VARCHAR(255),is_natural BOOLEAN); INSERT INTO makeup_sales (product_id,product_name,sale_price,brand_id,country) VALUES (1,'Foundation',35.99,1,'USA'),(2,'Mascara',25.99,2,'Canada'); INSERT INTO brands (brand_id,brand_name,is_natural) VALUES (1,'Pure Beauty',true),(2,'Luxe Cosmetics',false);
SELECT brands.brand_name, SUM(makeup_sales.sale_price) AS revenue FROM makeup_sales INNER JOIN brands ON makeup_sales.brand_id = brands.brand_id WHERE brands.is_natural = true GROUP BY brands.brand_name ORDER BY revenue DESC LIMIT 5;
Show production figures for wells in the Amazon Basin.
CREATE TABLE wells (well_id INT,country VARCHAR(50),production FLOAT); INSERT INTO wells (well_id,country,production) VALUES (1,'Brazil - Amazon Basin',1500),(2,'Peru - Amazon Basin',1000);
SELECT production FROM wells WHERE country LIKE '%Amazon Basin%';
What is the correlation between the budget allocated for ethical AI initiatives and the technology accessibility score by country?
CREATE TABLE Ethical_AI_Accessibility (country VARCHAR(255),budget INT,score INT); INSERT INTO Ethical_AI_Accessibility (country,budget,score) VALUES ('USA',5000000,85),('Canada',3000000,80),('Mexico',2000000,70);
SELECT country, CORR(budget, score) as correlation FROM Ethical_AI_Accessibility;
What are the defense project start and end dates for Contractor X?
CREATE TABLE ProjectTimelines (TimelineID INT,Contractor VARCHAR(255),StartDate DATE,EndDate DATE); INSERT INTO ProjectTimelines (TimelineID,Contractor,StartDate,EndDate) VALUES (1,'Contractor X','2021-01-01','2021-12-31');
SELECT Contractor, StartDate, EndDate FROM ProjectTimelines WHERE Contractor = 'Contractor X';
How many security incidents were resolved within the SLA for each department in the last month?
CREATE TABLE security_incidents (id INT,department VARCHAR(255),resolution_time INT,timestamp DATETIME,SLA_time INT);
SELECT department, COUNT(*) as total_incidents_SLA FROM security_incidents WHERE resolution_time <= SLA_time AND timestamp >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH) GROUP BY department;
What is the total amount donated by each donor in descending order, along with their record ID?
CREATE TABLE donors (id INT,name VARCHAR(50),donation_amount DECIMAL(10,2)); INSERT INTO donors (id,name,donation_amount) VALUES (1,'John Doe',500.00),(2,'Jane Smith',350.00),(3,'Alice Johnson',700.00);
SELECT ROW_NUMBER() OVER (ORDER BY donation_amount DESC) AS record_id, donation_amount FROM donors;
What is the maximum storage temperature for each chemical category?
CREATE TABLE chemical_storage_data (chemical_id INT,category VARCHAR(255),storage_temperature INT); INSERT INTO chemical_storage_data (chemical_id,category,storage_temperature) VALUES (1,'Solvents',25),(2,'Acids',15),(3,'Gases',0);
SELECT category, MAX(storage_temperature) FROM chemical_storage_data GROUP BY category;
How many natural disasters were reported in the state of Florida in the year 2020?
CREATE TABLE natural_disasters (id INT,state VARCHAR(20),year INT,disasters INT); INSERT INTO natural_disasters (id,state,year,disasters) VALUES (1,'Florida',2020,5),(2,'Florida',2020,3);
SELECT SUM(disasters) FROM natural_disasters WHERE state = 'Florida' AND year = 2020;
Which countries have the most marine protected areas?
CREATE TABLE marine_protected_areas (country VARCHAR(50),size FLOAT); INSERT INTO marine_protected_areas (country,size) VALUES ('Australia',6736333),('Brazil',1733268),('Indonesia',5426000),('United States',5930354),('France',647846);
SELECT country, SUM(size) as total_size FROM marine_protected_areas GROUP BY country ORDER BY total_size DESC;
Insert a new record into the 'Grants' table for a grant named 'Grant 1' with a grant amount of $10,000
CREATE TABLE Grants (id INT PRIMARY KEY,grant_name VARCHAR(255),grant_amount DECIMAL(10,2));
INSERT INTO Grants (grant_name, grant_amount) VALUES ('Grant 1', 10000.00);
Insert a new marine conservation initiative in the Great Barrier Reef.
CREATE TABLE marine_conservation_initiatives (name VARCHAR(255),location VARCHAR(255),start_date DATE,end_date DATE);
INSERT INTO marine_conservation_initiatives (name, location, start_date, end_date) VALUES ('Coral Restoration Project', 'Great Barrier Reef', '2025-01-01', '2030-12-31');
What is the average length of stay for Indian tourists in Paris?
CREATE TABLE TravelStats (Visitor VARCHAR(20),Destination VARCHAR(20),LengthOfStay INT); INSERT INTO TravelStats (Visitor,Destination,LengthOfStay) VALUES ('Anjali','Paris',5),('Ravi','Paris',4),('Priya','Rome',3);
SELECT AVG(LengthOfStay) AS AvgLoS FROM TravelStats WHERE Visitor = 'Anjali' OR Visitor = 'Ravi';
Update the delivery_date for the 'Tanks' equipment in the Army_Equipment table to 2023-01-01 where the delivery_date is currently 2022-12-31.
CREATE TABLE Army_Equipment (equipment VARCHAR(50),delivery_date DATE);
UPDATE Army_Equipment SET delivery_date = '2023-01-01' WHERE equipment = 'Tanks' AND delivery_date = '2022-12-31';
What is the maximum depth (in meters) of the ocean basins?
CREATE TABLE ocean_basins (basin_name TEXT,avg_depth REAL,max_depth REAL); INSERT INTO ocean_basins (basin_name,avg_depth,max_depth) VALUES ('Atlantic Ocean Basin',3646,8047),('Pacific Ocean Basin',4280,10994),('Indian Ocean Basin',3741,8047);
SELECT MAX(max_depth) FROM ocean_basins;
Update the 'rare_earth_market_trends' table to reflect the decreased dysprosium price in China
CREATE TABLE rare_earth_market_trends (id INT PRIMARY KEY,year INT,country VARCHAR(255),element VARCHAR(255),price_usd FLOAT);
WITH updated_price AS (UPDATE rare_earth_market_trends SET price_usd = 11.2 WHERE year = 2023 AND country = 'China' AND element = 'Dysprosium') SELECT * FROM rare_earth_market_trends WHERE country = 'China' AND element = 'Dysprosium';
How many Community Health Workers are there in each state?
CREATE TABLE States (StateID INT,StateName VARCHAR(50)); CREATE TABLE CommunityHealthWorkers (CHW_ID INT,StateID INT,MentalHealthScore INT); INSERT INTO States (StateID,StateName) VALUES (1,'Texas'),(2,'California'),(3,'New York'); INSERT INTO CommunityHealthWorkers (CHW_ID,StateID,MentalHealthScore) VALUES (1,1,85),(2,1,90),(3,2,75),(4,2,70),(5,3,80),(6,3,85);
SELECT s.StateName, COUNT(chw.CHW_ID) as CHW_Count FROM CommunityHealthWorkers chw JOIN States s ON chw.StateID = s.StateID GROUP BY s.StateName;
Find marine pollution control projects that started after 2015
CREATE TABLE pollution_control_projects (id INT PRIMARY KEY,project_name VARCHAR(255),start_date DATE,end_date DATE,budget FLOAT);
SELECT * FROM pollution_control_projects WHERE start_date > '2015-01-01';
How many public meetings were held in the last 30 days?
CREATE TABLE public_meetings (date DATE,location VARCHAR(255),topic VARCHAR(255));
SELECT COUNT(*) FROM public_meetings WHERE date >= DATE(NOW()) - INTERVAL 30 DAY;
Find the number of spacecraft manufactured by each company in the Spacecraft_Manufacturing table, ordered by the company names.
CREATE TABLE Spacecraft_Manufacturing(id INT,company VARCHAR(50),model VARCHAR(50),quantity INT);
SELECT company, COUNT(*) as Total_Spacecraft FROM Spacecraft_Manufacturing GROUP BY company ORDER BY company;
Which menu items generated more than $10,000 in revenue for the month of February 2021?
CREATE TABLE menu_items (menu_item_id INT,menu_item_name VARCHAR(255),menu_category VARCHAR(255)); CREATE TABLE menu_engineering (menu_item_id INT,revenue_date DATE,revenue DECIMAL(10,2)); INSERT INTO menu_engineering (menu_item_id,revenue_date,revenue) VALUES (1,'2021-02-01',5000),(1,'2021-02-02',6000),(2,'2021-02-01',10000),(2,'2021-02-02',11000),(3,'2021-02-01',1200),(3,'2021-02-02',1500);
SELECT menu_item_name, SUM(revenue) as total_revenue FROM menu_engineering WHERE revenue_date BETWEEN '2021-02-01' AND '2021-02-28' GROUP BY menu_item_name HAVING total_revenue > 10000;
How many mental health parity violations were reported in each region?
CREATE TABLE mental_health_parity (region VARCHAR(10),violations INT); INSERT INTO mental_health_parity (region,violations) VALUES ('Northeast',20),('Southeast',15),('Midwest',10),('Southwest',25),('West',30);
SELECT region, SUM(violations) FROM mental_health_parity GROUP BY region;
What is the average founding date for companies with at least one female founder?
CREATE TABLE companies (id INT,name TEXT,industry TEXT,founding_date DATE,founder_gender TEXT);
SELECT AVG(founding_date) FROM companies WHERE founder_gender = 'Female';
Delete a property from the properties table
CREATE TABLE public.properties (id SERIAL PRIMARY KEY,property_address VARCHAR(255),property_owner_name VARCHAR(255),property_owner_email VARCHAR(255)); INSERT INTO public.properties (property_address,property_owner_name,property_owner_email) VALUES ('123 Main St','John Smith','john.smith@example.com'),('456 Elm St','Jane Doe','jane.doe@example.com'),('789 Oak St','Mary Major','mary.major@example.com');
WITH deleted_property AS (DELETE FROM public.properties WHERE property_address = '789 Oak St' RETURNING *) INSERT INTO public.properties (property_address, property_owner_name, property_owner_email) SELECT property_address, property_owner_name, property_owner_email FROM deleted_property;
What is the total number of satellites launched by each country in the satellite_data table, grouped by launch decade?
CREATE TABLE satellite_data (satellite_id INT,name VARCHAR(100),launch_date DATE,country_of_origin VARCHAR(50),function VARCHAR(50),lifespan INT);
SELECT STRING_AGG(country_of_origin, ',') AS country_of_origin, EXTRACT(YEAR FROM launch_date)/10*10 AS launch_decade, COUNT(*) FROM satellite_data GROUP BY launch_decade;
How many defense diplomacy events were held in the United States in 2017?
CREATE SCHEMA if not exists diplomacy;CREATE TABLE if not exists events (id INT,event_name VARCHAR(255),event_location VARCHAR(255),event_date DATE); INSERT INTO events (id,event_name,event_location,event_date) VALUES (1,'Defense Innovation Summit','United States','2017-06-15');
SELECT COUNT(*) FROM events WHERE event_location = 'United States' AND event_date BETWEEN '2017-01-01' AND '2017-12-31';
How many healthcare providers are there in rural California?
CREATE TABLE healthcare_providers (id INT,name VARCHAR(50),location VARCHAR(50)); INSERT INTO healthcare_providers (id,name,location) VALUES (1,'Dr. Smith','Rural California'); INSERT INTO healthcare_providers (id,name,location) VALUES (2,'Dr. Johnson','Urban New York');
SELECT COUNT(*) FROM healthcare_providers WHERE location = 'Rural California';
What is the average CO2 emission for each garment type?
CREATE TABLE garment_emissions (id INT PRIMARY KEY,garment_type VARCHAR(20),co2_emission DECIMAL(5,2));
SELECT garment_type, AVG(co2_emission) FROM garment_emissions GROUP BY garment_type;
Which local vendors provide organic products?
CREATE TABLE vendors (vendor_id INT,vendor_name VARCHAR(30),location VARCHAR(20),product_type VARCHAR(20)); INSERT INTO vendors (vendor_id,vendor_name,location,product_type) VALUES (1,'Green Earth','local','organic'),(2,'Global Harvest','international','conventional');
SELECT vendor_name FROM vendors WHERE location = 'local' AND product_type = 'organic';
What is the average age of players who have made purchases in the last month from the 'Gaming_Players' table?
CREATE TABLE Gaming_Players (Player_ID INT,Player_Age INT,Last_Purchase DATE);
SELECT AVG(Player_Age) FROM Gaming_Players WHERE Last_Purchase >= DATE(NOW()) - INTERVAL 1 MONTH;
What is the number of cultural heritage sites in each country in Africa?
CREATE TABLE sites (id INT,name TEXT,location TEXT,country TEXT); INSERT INTO sites (id,name,location,country) VALUES (1,'Site 1','Marrakech','Morocco'),(2,'Site 2','Cairo','Egypt');
SELECT country, COUNT(*) FROM sites WHERE country IN (SELECT name FROM countries WHERE continent = 'Africa') GROUP BY country;
List wastewater plant capacities in California, ordered from smallest to largest.
CREATE TABLE WasteWaterPlants (PlantID INT,PlantName VARCHAR(50),Location VARCHAR(50),Capacity INT); INSERT INTO WasteWaterPlants (PlantID,PlantName,Location,Capacity) VALUES (1,'WaterWorks1','California',2000000),(2,'WaterWorks2','California',3000000),(3,'WaterWorks3','California',2500000),(4,'WaterWorks4','California',1500000);
SELECT PlantName, Capacity FROM WasteWaterPlants WHERE Location = 'California' ORDER BY Capacity ASC;
Who is the most popular artist in Japan based on concert ticket sales?
CREATE TABLE concerts (id INT,artist VARCHAR(50),city VARCHAR(50),revenue FLOAT); INSERT INTO concerts (id,artist,city,revenue) VALUES (1,'The Beatles','Tokyo',75000.0),(2,'Queen','Tokyo',80000.0);
SELECT artist, MAX(revenue) FROM concerts WHERE city = 'Tokyo';
What was the total revenue for each drug approved in H1 2020?
CREATE TABLE drug_approval (drug_name TEXT,half INT,year INT,revenue FLOAT); INSERT INTO drug_approval (drug_name,half,year,revenue) VALUES ('DrugE',1,2020,2000000.0),('DrugF',1,2020,2500000.0);
SELECT drug_name, SUM(revenue) FROM drug_approval WHERE half = 1 AND year = 2020 GROUP BY drug_name;
What is the total conservation budget for each program type, in descending order by the budget?
CREATE TABLE ProgramBudget (ProgramType VARCHAR(255),Budget INT); INSERT INTO ProgramBudget (ProgramType,Budget) VALUES ('Education',30000),('HabitatPreservation',40000),('AnimalPopulationStudy',50000);
SELECT ProgramType, SUM(Budget) as TotalBudget FROM ProgramBudget GROUP BY ProgramType ORDER BY TotalBudget DESC;
What is the minimum span length for suspension bridges in Ohio?
CREATE TABLE SuspensionBridges (BridgeID int,State varchar(2),SpanLength int); INSERT INTO SuspensionBridges (BridgeID,State,SpanLength) VALUES (1,'OH',850),(2,'NY',1200),(3,'OH',900);
SELECT MIN(SpanLength) FROM SuspensionBridges WHERE State = 'OH';
What is the average number of community health centers per state in the Midwest?
CREATE TABLE community_health_centers (center_id INT,state TEXT,center_type TEXT); INSERT INTO community_health_centers (center_id,state,center_type) VALUES (1,'Illinois','Community Health Center'),(2,'Indiana','Mental Health Center');
SELECT AVG(COUNT(*)) FROM community_health_centers GROUP BY state HAVING state LIKE '%Midwest%';
Which marine species were found in 'Australia' in 2020 and what pollution control initiatives were implemented there between 2015 and 2020?
CREATE TABLE Species_3 (id INT,name VARCHAR(255),region VARCHAR(255),year INT); INSERT INTO Species_3 (id,name,region,year) VALUES (1,'Kangaroo Fish','Australia',2020); INSERT INTO Species_3 (id,name,region,year) VALUES (2,'Blue-ringed Octopus','Australia',2020); CREATE TABLE Initiatives_3 (id INT,initiative VARCHAR(255),region VARCHAR(255),start_year INT,end_year INT); INSERT INTO Initiatives_3 (id,initiative,region,start_year,end_year) VALUES (1,'Coral Reef Restoration','Australia',2015,2020); INSERT INTO Initiatives_3 (id,initiative,region,start_year,end_year) VALUES (2,'Marine Debris Removal','Australia',2016,2020); INSERT INTO Initiatives_3 (id,initiative,region,start_year,end_year) VALUES (3,'Coastal Cleanups','Australia',2017,2020);
SELECT name FROM Species_3 WHERE region = 'Australia' AND year = 2020 UNION SELECT initiative FROM Initiatives_3 WHERE region = 'Australia' AND start_year BETWEEN 2015 AND 2020;
What was the average methane emission in 2019?
CREATE TABLE gas_emissions (year INT,methane_emissions FLOAT); INSERT INTO gas_emissions
SELECT AVG(methane_emissions) FROM gas_emissions WHERE year = 2019;
What is the average donation amount for the month of March?
CREATE TABLE donations (id INT,donor_id INT,organization_id INT,amount FLOAT,date DATE); INSERT INTO donations (id,donor_id,organization_id,amount,date) VALUES (1,1,101,250.00,'2020-01-01'); INSERT INTO donations (id,donor_id,organization_id,amount,date) VALUES (2,2,102,150.00,'2020-02-01');
SELECT AVG(amount) FROM donations WHERE EXTRACT(MONTH FROM date) = 3;
What is the percentage of mental health providers who speak a language other than English?
CREATE TABLE mental_health_providers (id INT,name VARCHAR(50),speaks_english BOOLEAN,speaks_spanish BOOLEAN,speaks_other_language BOOLEAN); INSERT INTO mental_health_providers (id,name,speaks_english,speaks_spanish,speaks_other_language) VALUES (1,'John Doe',true,true,false),(2,'Jane Smith',false,true,true),(3,'Alice Johnson',true,false,true);
SELECT (COUNT(*) FILTER (WHERE speaks_english = false)) * 100.0 / COUNT(*) as percentage FROM mental_health_providers;
What is the total cost of all NASA's Mars missions?
CREATE TABLE Missions (MissionID INT,Name VARCHAR(50),Agency VARCHAR(50),Cost INT); INSERT INTO Missions (MissionID,Name,Agency,Cost) VALUES (1,'Mars Pathfinder','NASA',265000000),(2,'Mars Exploration Rover','NASA',820000000);
SELECT SUM(Cost) FROM Missions WHERE Agency = 'NASA' AND Name LIKE '%Mars%';
Insert a new record into the design_standards table with the name 'Seismic Design Standard' and description 'Standard for seismic design' for the region 'Asia'
CREATE TABLE design_standards (id INT PRIMARY KEY,standard_name VARCHAR(255),description TEXT,region VARCHAR(255)); INSERT INTO design_standards (id,standard_name,description,region) VALUES (1,'Highway Design Standard','Standard for designing highways','North America'); INSERT INTO design_standards (id,standard_name,description,region) VALUES (2,'Railway Design Standard','Standard for designing railways','Europe');
INSERT INTO design_standards (standard_name, description, region) VALUES ('Seismic Design Standard', 'Standard for seismic design', 'Asia');
What is the maximum number of players and the corresponding game for each genre?
CREATE TABLE GameStats (GameID int,Genre varchar(20),MaxPlayers int); INSERT INTO GameStats (GameID,Genre,MaxPlayers) VALUES (1,'Action',200); INSERT INTO GameStats (GameID,Genre,MaxPlayers) VALUES (2,'Strategy',150);
SELECT Genre, MAX(MaxPlayers) as MaxPlayers, GameName FROM GameStats gs JOIN Games g ON gs.GameID = g.GameID GROUP BY Genre;
Find the top 3 countries with the highest average hotel star rating in the Asia Pacific region.
CREATE TABLE hotel_ratings (hotel_id INT,hotel_name TEXT,country TEXT,region TEXT,stars FLOAT); INSERT INTO hotel_ratings (hotel_id,hotel_name,country,region,stars) VALUES (1,'Hotel A','Australia','Asia Pacific',4.5),(2,'Hotel B','Japan','Asia Pacific',5.0),(3,'Hotel C','New Zealand','Asia Pacific',4.7);
SELECT country, AVG(stars) as avg_stars FROM hotel_ratings WHERE region = 'Asia Pacific' GROUP BY country ORDER BY avg_stars DESC LIMIT 3;
List all research in the astrophysics category with associated publications.
CREATE TABLE Research (id INT PRIMARY KEY,title VARCHAR(50),category VARCHAR(50),start_date DATE,end_date DATE); CREATE TABLE Publication (id INT PRIMARY KEY,research_id INT,title VARCHAR(50),publication_date DATE,FOREIGN KEY (research_id) REFERENCES Research(id));
SELECT Research.title, Publication.title, Publication.publication_date FROM Research INNER JOIN Publication ON Research.id = Publication.research_id WHERE Research.category = 'Astrophysics';
How many specialists are available in rural healthcare facilities in California, excluding facilities with a capacity below 50?
CREATE TABLE specialists (id INT,name TEXT,specialty TEXT,facility_id INT); INSERT INTO specialists (id,name,specialty,facility_id) VALUES (1,'Dr. Smith','Cardiology',101); CREATE TABLE facilities (id INT,name TEXT,location TEXT,capacity INT);
SELECT COUNT(*) as num_specialists FROM specialists JOIN facilities ON specialists.facility_id = facilities.id WHERE facilities.location LIKE '%California%' AND facilities.capacity >= 50;
What is the total salary paid to the 'Sales' department in 2020
CREATE TABLE salaries (id INT,employee_id INT,salary INT,salary_date DATE,department VARCHAR(255)); INSERT INTO salaries (id,employee_id,salary,salary_date,department) VALUES (1,201,50000,'2020-01-01','Sales'); INSERT INTO salaries (id,employee_id,salary,salary_date,department) VALUES (2,202,60000,'2019-12-01','Finance');
SELECT SUM(salary) FROM salaries JOIN hiring ON salaries.employee_id = hiring.employee_id WHERE department = 'Sales' AND YEAR(salary_date) = 2020;
List all concerts in Canada that had a higher revenue than the maximum revenue in Quebec.
CREATE TABLE Concerts (id INT,province VARCHAR(50),revenue FLOAT);
SELECT * FROM Concerts WHERE revenue > (SELECT MAX(revenue) FROM Concerts WHERE province = 'Quebec') AND province = 'Canada';
Identify mining operations with below-average labor productivity in the South American region.
CREATE TABLE mining_productivity (operation_id INT,region VARCHAR(20),productivity FLOAT); INSERT INTO mining_productivity (operation_id,region,productivity) VALUES (1001,'South America',2.5),(1002,'South America',3.0),(1003,'South America',2.8),(1004,'South America',3.2),(1005,'South America',2.2),(1006,'South America',2.9);
SELECT * FROM mining_productivity WHERE region = 'South America' AND productivity < (SELECT AVG(productivity) FROM mining_productivity WHERE region = 'South America');
Calculate the average number of streams per user for each genre.
CREATE TABLE genres (genre_id INT,genre VARCHAR(255)); CREATE TABLE songs (song_id INT,title VARCHAR(255),genre_id INT,release_date DATE); CREATE TABLE users (user_id INT,user_country VARCHAR(255)); CREATE TABLE streams (stream_id INT,song_id INT,user_id INT,stream_date DATE,revenue DECIMAL(10,2));
SELECT g.genre, AVG(st.stream_count) as avg_streams_per_user FROM genres g JOIN (SELECT song_id, user_id, COUNT(*) as stream_count FROM streams GROUP BY song_id, user_id) st ON g.genre_id = st.song_id GROUP BY g.genre;
How many articles were published in Spanish by local news outlets in Spain in 2021?
CREATE TABLE news_outlets (id INT,name VARCHAR(255),location VARCHAR(64),is_local BOOLEAN); CREATE TABLE articles (id INT,title VARCHAR(255),publication_language VARCHAR(64),publication_date DATE,outlet_id INT,PRIMARY KEY (id),FOREIGN KEY (outlet_id) REFERENCES news_outlets(id)); INSERT INTO news_outlets (id,name,location,is_local) VALUES (1,'Outlet1','Spain',true),(2,'Outlet2','Mexico',false),(3,'Outlet3','Spain',true); INSERT INTO articles (id,title,publication_language,publication_date,outlet_id) VALUES (1,'Article1','Spanish','2021-03-01',1),(2,'Article2','English','2021-04-15',2),(3,'Article3','Spanish','2021-05-31',3);
SELECT COUNT(*) FROM articles INNER JOIN news_outlets ON articles.outlet_id = news_outlets.id WHERE news_outlets.location = 'Spain' AND news_outlets.is_local = true AND articles.publication_language = 'Spanish' AND EXTRACT(YEAR FROM articles.publication_date) = 2021;
How many satellites were launched by each country in the 21st century?
CREATE TABLE satellites (satellite_id INT,satellite_name VARCHAR(100),country VARCHAR(50),launch_date DATE); INSERT INTO satellites (satellite_id,satellite_name,country,launch_date) VALUES (1,'Sentinel-1A','France','2012-04-03'); INSERT INTO satellites (satellite_id,satellite_name,country,launch_date) VALUES (2,'Chandrayaan-1','India','2008-10-22'); CREATE TABLE countries (country_id INT,country_name VARCHAR(100),launch_count INT); INSERT INTO countries (country_id,country_name,launch_count) VALUES (1,'United States',0); INSERT INTO countries (country_id,country_name,launch_count) VALUES (2,'China',0);
SELECT country, COUNT(*) as launch_count FROM satellites WHERE YEAR(launch_date) >= 2000 GROUP BY country; UPDATE countries SET launch_count = (SELECT COUNT(*) FROM satellites WHERE YEAR(launch_date) >= 2000 AND satellites.country = countries.country_name) WHERE TRUE; SELECT country_name, launch_count FROM countries;
What is the percentage of cases that resulted in a conviction, by month?
CREATE TABLE CaseOutcomes (CaseID INT,OutcomeDate DATE,Outcome VARCHAR(20)); INSERT INTO CaseOutcomes (CaseID,OutcomeDate,Outcome) VALUES (1,'2022-01-15','Conviction'),(2,'2022-02-20','Dismissal'),(3,'2022-03-05','Conviction'),(4,'2022-04-12','Dismissal');
SELECT DATEPART(month, OutcomeDate) AS Month, COUNT(*) FILTER (WHERE Outcome = 'Conviction') * 100.0 / COUNT(*) AS Percentage FROM CaseOutcomes WHERE OutcomeDate IS NOT NULL GROUP BY DATEPART(month, OutcomeDate);
What is the total number of volunteers from the 'Asia-Pacific' region who volunteered in the last month for any program?
CREATE TABLE region (id INT,name VARCHAR(255)); CREATE TABLE volunteer (id INT,region_id INT,program_id INT,name VARCHAR(255),last_volunteered DATE); INSERT INTO region (id,name) VALUES (1,'Asia-Pacific'),(2,'Americas'),(3,'Europe'); INSERT INTO volunteer (id,region_id,program_id,name,last_volunteered) VALUES (1,1,1,'Alice','2022-04-10'),(2,2,1,'Bina','2022-03-20'),(3,2,2,'Candela','2022-02-01'),(4,1,1,'Dinesh','2022-04-25'),(5,3,2,'Eve','2022-03-15');
SELECT COUNT(*) as total_volunteers FROM volunteer WHERE region_id = (SELECT id FROM region WHERE name = 'Asia-Pacific') AND last_volunteered >= DATE_SUB(CURDATE(), INTERVAL 1 MONTH);
What is the minimum salary for employees in the Finance department who identify as LGBTQ+ and have been with the company for more than 3 years?
CREATE TABLE Employees (EmployeeID INT,Department VARCHAR(20),Gender VARCHAR(20),IdentifiesAsLGBTQ BOOLEAN,Salary DECIMAL(10,2),YearsWithCompany INT); INSERT INTO Employees (EmployeeID,Department,Gender,IdentifiesAsLGBTQ,Salary,YearsWithCompany) VALUES (1,'Finance','Male',true,95000.00,4),(2,'IT','Female',false,75000.00,2),(3,'Finance','Non-binary',false,90000.00,1);
SELECT MIN(Salary) FROM Employees WHERE Department = 'Finance' AND IdentifiesAsLGBTQ = true AND YearsWithCompany > 3;
What is the name and text of the most recent comment made by a user from India?
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,3,'Excellent post!','2022-10-01');
SELECT c.text, c.user_id FROM comments c WHERE c.country = 'India' AND c.created_date = (SELECT MAX(created_date) FROM comments WHERE country = 'India')
Insert new records of arctic fox sightings in the 'Animal_Sightings' table, ensuring there are no duplicates based on date and location.
CREATE TABLE Animal_Sightings (id INT,animal VARCHAR(10),sighting_date DATE,location VARCHAR(20));
INSERT INTO Animal_Sightings (id, animal, sighting_date, location) SELECT 6, 'Arctic Fox', '2023-03-01', 'Tundra' FROM dual WHERE NOT EXISTS (SELECT 1 FROM Animal_Sightings WHERE animal = 'Arctic Fox' AND sighting_date = '2023-03-01' AND location = 'Tundra');
What is the total budget allocated for language preservation programs in Africa, and which programs have received more than 75% of the allocated budget?
CREATE TABLE LanguagePrograms(ProgramID INT,ProgramName VARCHAR(100),Region VARCHAR(50),Budget DECIMAL(10,2)); CREATE TABLE Allocations(ProgramID INT,AllocationID INT,AllocationAmount DECIMAL(10,2));
SELECT ProgramName, SUM(AllocationAmount) as AllocatedBudget FROM Allocations INNER JOIN LanguagePrograms ON Allocations.ProgramID = LanguagePrograms.ProgramID WHERE Region = 'Africa' GROUP BY ProgramName HAVING SUM(AllocationAmount) > (SELECT Budget FROM LanguagePrograms WHERE ProgramName = Programs.ProgramName) * 0.75;
Find the average R&D expenditure for trials in 'CountryX' in 2021?
CREATE TABLE rd_expenditure(trial_id TEXT,country TEXT,year INT,amount FLOAT); INSERT INTO rd_expenditure (trial_id,country,year,amount) VALUES ('Trial1','CountryX',2021,2500000),('Trial2','CountryY',2020,3000000);
SELECT AVG(amount) FROM rd_expenditure WHERE country = 'CountryX' AND year = 2021;
What is the maximum housing affordability score for each city?
CREATE TABLE housing_affordability (id INT,city VARCHAR(20),score FLOAT); INSERT INTO housing_affordability (id,city,score) VALUES (1,'SF',45.2),(2,'NYC',38.6),(3,'LA',51.1),(4,'SF',47.9),(5,'NYC',39.8);
SELECT city, MAX(score) as max_score FROM housing_affordability GROUP BY city;
Delete the diversity metric 'Age' from the database.
CREATE TABLE diversity_metrics (id INT,metric TEXT); INSERT INTO diversity_metrics (id,metric) VALUES (1,'Gender'); INSERT INTO diversity_metrics (id,metric) VALUES (2,'Race');
DELETE FROM diversity_metrics WHERE metric = 'Age';
What is the average water consumption per day for the 'commercial' category in the last 30 days?
CREATE TABLE daily_water_consumption (user_category VARCHAR(20),consumption FLOAT,consumption_date DATE); INSERT INTO daily_water_consumption (user_category,consumption,consumption_date) VALUES ('residential',15000,'2022-04-01'),('commercial',25000,'2022-04-01'),('residential',16000,'2022-04-02'),('commercial',24000,'2022-04-02');
SELECT AVG(consumption) FROM daily_water_consumption WHERE user_category = 'commercial' AND consumption_date >= DATEADD(day, -30, GETDATE());
What is the total number of heritage sites for each UNESCO World Heritage Committee member, excluding those that are not yet inscribed?
CREATE TABLE HeritageSites (id INT,name VARCHAR(50),country VARCHAR(50),is_inscribed BOOLEAN); CREATE TABLE UNESCO_Committee (id INT,country VARCHAR(50));
SELECT C.country, COUNT(H.id) as total_sites FROM HeritageSites H INNER JOIN UNESCO_Committee C ON H.country = C.country WHERE H.is_inscribed GROUP BY C.country;
Who are the top 3 beneficiaries of rural infrastructure projects in India by total expenditure?
CREATE TABLE rural_projects (id INT,beneficiary_id INT,country VARCHAR(50),project VARCHAR(50),expenditure DECIMAL(10,2),start_date DATE,end_date DATE); INSERT INTO rural_projects (id,beneficiary_id,country,project,expenditure,start_date,end_date) VALUES (1,3001,'India','Irrigation System',15000.00,'2019-04-01','2021-03-31'),(2,3002,'India','Road Construction',22000.00,'2018-07-01','2020-06-30');
SELECT beneficiary_id, SUM(expenditure) FROM rural_projects WHERE country = 'India' GROUP BY beneficiary_id ORDER BY SUM(expenditure) DESC LIMIT 3;
List the names and start dates of all projects in the 'transportation' schema, ordered by start date
CREATE SCHEMA IF NOT EXISTS transportation; CREATE TABLE transportation.projects (id INT,name VARCHAR(100),start_date DATE); INSERT INTO transportation.projects (id,name,start_date) VALUES (1,'Highway Repaving','2020-04-01'),(2,'Traffic Signal Installation','2019-10-15'),(3,'Pedestrian Bridge Construction','2021-02-20');
SELECT name, start_date FROM transportation.projects ORDER BY start_date;
What is the percentage of smokers in China and Indonesia?
CREATE TABLE smoking_rates (country VARCHAR(20),percentage_smokers DECIMAL(5,2)); INSERT INTO smoking_rates (country,percentage_smokers) VALUES ('China',30.0),('Indonesia',25.0);
SELECT AVG(percentage_smokers) FROM smoking_rates WHERE country IN ('China', 'Indonesia');
Calculate the veteran unemployment rate by state for the last quarter
CREATE TABLE veteran_unemployment (state VARCHAR(2),unemployment_date DATE,unemployment_rate FLOAT); INSERT INTO veteran_unemployment (state,unemployment_date,unemployment_rate) VALUES ('CA','2022-01-01',0.05),('NY','2022-01-01',0.06);
SELECT state, AVG(unemployment_rate) AS avg_unemployment_rate FROM veteran_unemployment WHERE unemployment_date >= DATE_SUB(CURDATE(), INTERVAL 3 MONTH) GROUP BY state;
How many public schools are there in Texas with an average teacher age above 45?
CREATE TABLE public_schools (id INT,name TEXT,location TEXT,num_students INT,avg_teacher_age FLOAT); INSERT INTO public_schools (id,name,location,num_students,avg_teacher_age) VALUES (1,'School 1','TX',500,48.3),(2,'School 2','TX',600,42.2),(3,'School 3','TX',700,46.1),(4,'School 4','TX',800,52.0);
SELECT COUNT(*) FROM public_schools WHERE location = 'TX' AND avg_teacher_age > 45;
Which clients have made donations of over 700 in Nigeria and Kenya?
CREATE TABLE donations (id INT,client_name VARCHAR(50),country VARCHAR(50),organization VARCHAR(50),amount DECIMAL(10,2),date DATE); INSERT INTO donations (id,client_name,country,organization,amount,date) VALUES (1,'Zainab','Nigeria','charity1',800,'2022-01-01'); INSERT INTO donations (id,client_name,country,organization,amount,date) VALUES (2,'Khalid','Kenya','charity2',750,'2022-01-02');
SELECT client_name, country, amount FROM donations WHERE country IN ('Nigeria', 'Kenya') AND amount > 700;
Identify users who streamed the same song on consecutive days in 'music_streaming' table?
CREATE TABLE music_streaming (user_id INT,song_id INT,duration FLOAT,date DATE);
SELECT a.user_id, a.song_id, a.date as first_date, b.date as second_date FROM music_streaming a INNER JOIN music_streaming b ON a.user_id = b.user_id AND a.song_id = b.song_id AND b.date = DATE_ADD(a.date, INTERVAL 1 DAY);
Identify the number of models and datasets in each AI domain (AI in Healthcare, AI in Finance, and AI in Agriculture).
CREATE TABLE ai_domains (id INT,domain VARCHAR(255),dataset VARCHAR(255),model VARCHAR(255)); INSERT INTO ai_domains (id,domain,dataset,model) VALUES (1,'AI in Healthcare','Medical Images','Deep Learning Model'),(2,'AI in Healthcare','Genomic Data','Random Forest Model'),(3,'AI in Finance','Stock Prices','LSTM Model'),(4,'AI in Finance','Loan Data','Logistic Regression Model'),(5,'AI in Agriculture','Crop Yield','Decision Tree Model');
SELECT domain, COUNT(DISTINCT dataset) as num_datasets, COUNT(DISTINCT model) as num_models FROM ai_domains GROUP BY domain;
Update the price of 'Blue Dream' strain to $12 per gram in 'Green Earth' dispensary.
CREATE TABLE strains (strain_id INT,name VARCHAR(255),price FLOAT); INSERT INTO strains (strain_id,name,price) VALUES (1,'Blue Dream',10); CREATE TABLE inventory (inventory_id INT,strain_id INT,dispensary_id INT,quantity INT); INSERT INTO inventory (inventory_id,strain_id,dispensary_id) VALUES (1,1,2); CREATE TABLE dispensaries (dispensary_id INT,name VARCHAR(255)); INSERT INTO dispensaries (dispensary_id,name) VALUES (2,'Green Earth');
UPDATE inventory SET price = 12 WHERE strain_id = (SELECT strain_id FROM strains WHERE name = 'Blue Dream') AND dispensary_id = (SELECT dispensary_id FROM dispensaries WHERE name = 'Green Earth');
What is the maximum and minimum capacity of accommodation facilities in India and Indonesia?
CREATE TABLE AccommodationFacilities (id INT,country VARCHAR(50),facility_type VARCHAR(50),capacity INT); INSERT INTO AccommodationFacilities (id,country,facility_type,capacity) VALUES (1,'India','Hotel',300),(2,'India','Hostel',50),(3,'Indonesia','Resort',200),(4,'Indonesia','Villa',100);
SELECT MAX(capacity) max_capacity, MIN(capacity) min_capacity FROM AccommodationFacilities WHERE country IN ('India', 'Indonesia');
Insert a new investment in the employment sector with an ESG score of 5, a risk score of 4, and an investment amount of 800,000.
CREATE TABLE investments (investment_id INT,sector VARCHAR(50),esg_score INT,risk_score INT,investment_amount INT);
INSERT INTO investments (investment_id, sector, esg_score, risk_score, investment_amount) VALUES (6, 'Employment', 5, 4, 800000);
Delete products that have not been restocked in the past 6 months
CREATE TABLE products (product_id INT,product_name VARCHAR(255),restocked_date DATE);
DELETE FROM products WHERE restocked_date < (CURRENT_DATE - INTERVAL '6 months');
List all sustainable tourism initiatives and their number of annual visitors from the United States.
CREATE TABLE SustainableTourism (InitiativeID INT,InitiativeName VARCHAR(255),Country VARCHAR(255)); INSERT INTO SustainableTourism (InitiativeID,InitiativeName,Country) VALUES (1,'Initiative1','United States'),(2,'Initiative2','United States'); CREATE TABLE VisitorCounts (InitiativeID INT,Year INT,VisitorCount INT); INSERT INTO VisitorCounts (InitiativeID,Year,VisitorCount) VALUES (1,2020,5000),(1,2019,5500),(2,2020,3000),(2,2019,3500);
SELECT SustainableTourism.InitiativeName, SUM(VisitorCounts.VisitorCount) FROM SustainableTourism INNER JOIN VisitorCounts ON SustainableTourism.InitiativeID = VisitorCounts.InitiativeID WHERE SustainableTourism.Country = 'United States' GROUP BY SustainableTourism.InitiativeName;
Which climate adaptation campaigns reached the most people in South America?
CREATE TABLE campaigns (id INT,name VARCHAR(255),type VARCHAR(255),country VARCHAR(255)); INSERT INTO campaigns (id,name,type,country) VALUES (1,'Climate Adaptation Seminar','Seminar','Brazil'),(2,'Climate Adaptation Conference','Conference','Argentina'); CREATE TABLE communication (id INT,campaign_id INT,medium VARCHAR(255),reach INT); INSERT INTO communication (id,campaign_id,medium,reach) VALUES (1,1,'Online',25000),(2,1,'Offline',15000),(3,2,'Online',30000),(4,2,'Offline',10000);
SELECT campaign_id, MAX(reach) as max_reach FROM communication GROUP BY campaign_id HAVING country = 'South America';
Which courses have a mental health support rating above 4 but less than 5?
CREATE TABLE courses (course_id INT,name TEXT,mental_health_rating FLOAT); INSERT INTO courses (course_id,name,mental_health_rating) VALUES (1,'Intro to Psychology',4.5),(2,'Yoga for Wellness',3.8),(3,'Mindfulness Meditation',4.7);
SELECT course_id, name FROM courses WHERE mental_health_rating > 4 AND mental_health_rating < 5;
What is the total number of publications in the Journal of Social Sciences by graduate students?
CREATE TABLE publications (id INT,author VARCHAR(50),year INT,journal VARCHAR(50),graduate_student VARCHAR(50)); INSERT INTO publications (id,author,year,journal,graduate_student) VALUES (1,'Jamal',2019,'Journal of Social Sciences','Yes'),(2,'Sophia',2018,'Journal of Natural Sciences','No'),(3,'Hiroshi',2019,'Journal of Social Sciences','Yes'),(4,'Fatima',2020,'Journal of Social Sciences','Yes');
SELECT COUNT(*) FROM publications WHERE journal = 'Journal of Social Sciences' AND graduate_student = 'Yes';
Update the sale_date of military equipment sales to China made in January 2020 to the first day of the month.
CREATE TABLE military_sales(id INT,country VARCHAR,sale_date DATE,equipment VARCHAR,value FLOAT); INSERT INTO military_sales(id,country,sale_date,equipment,value) VALUES (1,'China','2020-01-15','Tanks',12000000.00),(2,'China','2020-01-30','Aircraft',30000000.00),(3,'China','2020-02-01','Missiles',7000000.00);
UPDATE military_sales SET sale_date = '2020-01-01' WHERE country = 'China' AND sale_date >= '2020-01-01' AND sale_date < '2020-02-01';
What is the total number of flight hours for each aircraft model by year?
CREATE TABLE aircraft_flights (id INT,model VARCHAR(50),flight_hours DECIMAL(5,2),year INT); INSERT INTO aircraft_flights (id,model,flight_hours,year) VALUES (1,'Boeing 737',3500.5,2019),(2,'Airbus A320',3200.2,2019),(3,'Boeing 787',3800.8,2018);
SELECT model, YEAR(flight_date) as year, SUM(flight_hours) as total_flight_hours FROM aircraft_flights GROUP BY model, year;
What is the maximum exit strategy valuation for companies founded by Latinx individuals?
CREATE TABLE company (id INT,name VARCHAR(50),founder_ethnicity VARCHAR(50)); CREATE TABLE exit_strategy (id INT,company_id INT,valuation INT); INSERT INTO company (id,name,founder_ethnicity) VALUES (1,'Acme Corp','Latinx'); INSERT INTO exit_strategy (id,company_id,valuation) VALUES (1,1,1000000); INSERT INTO exit_strategy (id,company_id,valuation) VALUES (2,1,1500000);
SELECT MAX(es.valuation) AS max_exit_strategy_valuation FROM company c JOIN exit_strategy es ON c.id = es.company_id WHERE c.founder_ethnicity = 'Latinx';
List the salaries of employees who made no Shariah-compliant loans?
CREATE TABLE transactions (id INT,employee_id INT,loan_id INT,transaction_type TEXT,amount INT); INSERT INTO transactions (id,employee_id,loan_id,transaction_type,amount) VALUES (1,1,1,'Disbursement',15000),(2,1,NULL,'Salary',50000),(3,2,2,'Disbursement',25000),(4,2,NULL,'Salary',40000),(5,3,NULL,'Salary',50000);
SELECT employees.salary FROM employees LEFT JOIN loans ON employees.id = loans.employee_id WHERE loans.id IS NULL AND loans.is_shariah_compliant IS TRUE;
What is the number of male and female members in each city?
CREATE TABLE Members (MemberID INT,City VARCHAR(50),Gender VARCHAR(10)); INSERT INTO Members (MemberID,City,Gender) VALUES (1,'New York','Male'),(2,'Los Angeles','Female'),(3,'Chicago','Male');
SELECT City, Gender, COUNT(*) FROM Members GROUP BY City, Gender;
Show the number of rural and urban healthcare providers, separated by provider specialty.
CREATE TABLE rural_clinics (clinic_id INT,provider_name TEXT,provider_specialty TEXT); INSERT INTO rural_clinics (clinic_id,provider_name,provider_specialty) VALUES (1,'Dr. Smith','General Practitioner'),(2,'Dr. Johnson','Pediatrician'); CREATE TABLE urban_clinics (clinic_id INT,provider_name TEXT,provider_specialty TEXT); INSERT INTO urban_clinics (clinic_id,provider_name,provider_specialty) VALUES (1,'Dr. Lee','Cardiologist'),(2,'Dr. Garcia','Dermatologist');
SELECT 'Rural' AS location, provider_specialty, COUNT(*) AS provider_count FROM rural_clinics GROUP BY provider_specialty UNION SELECT 'Urban', provider_specialty, COUNT(*) FROM urban_clinics GROUP BY provider_specialty;
Show the number of restaurants serving vegetarian options in each city?
CREATE TABLE Restaurants(RestaurantID INT,Name VARCHAR(50),City VARCHAR(50),Vegetarian BOOLEAN);INSERT INTO Restaurants VALUES (1,'Veggie Delight','New York',TRUE),(2,'Budget Bites','Los Angeles',FALSE),(3,'Sushi Spot','San Francisco',FALSE),(4,'Greens','Chicago',TRUE);
SELECT City, COUNT(*) FROM Restaurants WHERE Vegetarian = TRUE GROUP BY City;
What is the total weight of ceramic artifacts in 'Collection Y'?
CREATE TABLE Collection_Y (Artifact_ID INT,Material VARCHAR(255),Weight INT); INSERT INTO Collection_Y (Artifact_ID,Material,Weight) VALUES (1,'Ceramic',500);
SELECT SUM(Weight) FROM Collection_Y WHERE Material = 'Ceramic';
What is the total value of Shariah-compliant assets held by investors in Asia?
CREATE TABLE investors (id INT,region TEXT,shariah_assets DECIMAL); INSERT INTO investors (id,region,shariah_assets) VALUES (1,'Middle East',15000),(2,'Asia',22000),(3,'Africa',10000);
SELECT SUM(shariah_assets) as total_assets FROM investors WHERE region = 'Asia';
What is the difference between the maximum and minimum safety violation costs for chemical plants in Brazil?
CREATE TABLE chemical_plants (plant_id INT,plant_name VARCHAR(50),country VARCHAR(50),safety_violation_cost DECIMAL(10,2)); INSERT INTO chemical_plants (plant_id,plant_name,country,safety_violation_cost) VALUES (1,'Plant A','Brazil',5000),(2,'Plant B','Brazil',8000),(3,'Plant C','USA',3000);
SELECT MAX(safety_violation_cost) - MIN(safety_violation_cost) FROM chemical_plants WHERE country = 'Brazil';
What is the total number of beauty products that contain natural ingredients and were sold in Canada?
CREATE TABLE natural_ingredients (id INT,product VARCHAR(255),natural_ingredients BOOLEAN,sales INT,country VARCHAR(255)); INSERT INTO natural_ingredients (id,product,natural_ingredients,sales,country) VALUES (1,'Shampoo',true,50,'Canada'),(2,'Conditioner',false,75,'Canada'),(3,'Lotion',true,100,'Canada');
SELECT SUM(sales) FROM natural_ingredients WHERE natural_ingredients = true AND country = 'Canada';
Add a new employee to the Employees table with the specified details.
CREATE TABLE Employees (EmployeeID INT,FirstName VARCHAR(50),LastName VARCHAR(50),Position VARCHAR(50),Department VARCHAR(50),Salary DECIMAL(10,2),FOREIGN KEY (EmployeeID) REFERENCES Projects(EmployeeID));
INSERT INTO Employees (EmployeeID, FirstName, LastName, Position, Department, Salary) VALUES (4, 'Aaliyah', 'Johnson', 'Architect', 'Green Building', 85000.00);
Who were the top 5 donors in terms of total donation amount for 2021?
CREATE TABLE donations (donation_id INT,donor_id INT,donation_amount DECIMAL(10,2),donation_date DATE);
SELECT donor_id, SUM(donation_amount) AS total_donation_amount FROM donations WHERE YEAR(donation_date) = 2021 GROUP BY donor_id ORDER BY total_donation_amount DESC LIMIT 5;
What is the minimum number of likes on posts by users from Nigeria, in the last month?
CREATE TABLE users (id INT,name TEXT,country TEXT); INSERT INTO users (id,name,country) VALUES (1,'Ade','Nigeria'),(2,'Bisi','Nigeria'),(3,'Chinwe','Nigeria'),(4,'Deji','South Africa'); CREATE TABLE posts (id INT,user_id INT,likes INT,timestamp DATETIME); INSERT INTO posts (id,user_id,likes,timestamp) VALUES (1,1,20,'2022-04-01 12:00:00'),(2,1,30,'2022-04-05 13:00:00'),(3,2,10,'2022-04-03 11:00:00'),(4,3,40,'2022-04-04 14:00:00'),(5,4,50,'2022-04-05 15:00:00');
SELECT MIN(posts.likes) FROM posts JOIN users ON posts.user_id = users.id WHERE users.country = 'Nigeria' AND posts.timestamp >= DATE_SUB(NOW(), INTERVAL 1 MONTH);
What is the maximum monthly data usage for customers in the state of California?
CREATE TABLE customers (id INT,name VARCHAR(50),data_usage FLOAT,state VARCHAR(50));
SELECT MAX(data_usage) FROM customers WHERE state = 'California';
Identify the top 3 sensors with the highest moisture levels in 'Field2' for the last month.
CREATE TABLE SensorData (ID INT,SensorID INT,Timestamp DATETIME,MoistureLevel FLOAT); CREATE VIEW LastMonthSensorData AS SELECT * FROM SensorData WHERE Timestamp BETWEEN DATEADD(month,-1,GETDATE()) AND GETDATE(); CREATE VIEW Field2Sensors AS SELECT * FROM SensorData WHERE FieldID = 2; CREATE VIEW Field2LastMonthSensorData AS SELECT * FROM LastMonthSensorData WHERE SensorData.SensorID = Field2Sensors.SensorID;
SELECT SensorID, MoistureLevel, RANK() OVER (PARTITION BY FieldID ORDER BY MoistureLevel DESC) AS MoistureRank FROM Field2LastMonthSensorData WHERE MoistureRank <= 3;
What is the total number of unique sectors and the number of disasters in each sector in the 'disaster_response' schema?
CREATE TABLE disaster_response.sectors_expanded (sector_id INT,sector_name VARCHAR(255),disaster_count INT); INSERT INTO disaster_response.sectors_expanded (sector_id,sector_name,disaster_count) VALUES (1,'Education',30),(2,'Health',50),(3,'Water',20),(4,'Shelter',40);
SELECT * FROM disaster_response.sectors_expanded;
Update user types based on post count
CREATE TABLE users (id INT,name TEXT,post_count INT); INSERT INTO users (id,name,post_count) VALUES (1,'Charlie',50); INSERT INTO users (id,name,post_count) VALUES (2,'Diana',200);
UPDATE users SET user_type = 'Power User' WHERE post_count > 100; UPDATE users SET user_type = 'Regular User' WHERE post_count <= 100;
Which training programs had more than 5 participants from underrepresented groups?
CREATE TABLE TrainingPrograms (ProgramID INT,ProgramName VARCHAR(20),Participants VARCHAR(20)); INSERT INTO TrainingPrograms (ProgramID,ProgramName,Participants) VALUES (1,'SQL','Female,Male,Non-binary'),(2,'Python','Female,Female,Male'),(3,'HR Analytics','Male,Female,Female,Non-binary'),(4,'Data Visualization','Female,Male,Non-binary,Latino,Asian');
SELECT ProgramName FROM TrainingPrograms WHERE ARRAY_LENGTH(STRING_TO_ARRAY(Participants, ',')) - ARRAY_LENGTH(STRING_TO_ARRAY(REPLACE(Participants, ',Non-binary', ''), ',')) > 5 AND ARRAY_LENGTH(STRING_TO_ARRAY(Participants, ',')) - ARRAY_LENGTH(STRING_TO_ARRAY(REPLACE(Participants, ',Female', ''), ',')) > 5 AND ARRAY_LENGTH(STRING_TO_ARRAY(Participants, ',')) - ARRAY_LENGTH(STRING_TO_ARRAY(REPLACE(Participants, ',Male', ''), ',')) > 5;
Show all the transportation systems in the database.
CREATE TABLE transportation_systems (id INT,system VARCHAR(50)); INSERT INTO transportation_systems (id,system) VALUES (1,'Subway'),(2,'Bus'),(3,'Tram'),(4,'Ferry');
SELECT * FROM transportation_systems;