instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
What is the number of art pieces in each collection by artist?
CREATE TABLE ArtCollections (id INT,name VARCHAR(255),location VARCHAR(255)); CREATE TABLE ArtPieces (id INT,collection_id INT,artist VARCHAR(255),title VARCHAR(255));
SELECT c.name, p.artist, COUNT(p.id) FROM ArtCollections c JOIN ArtPieces p ON c.id = p.collection_id GROUP BY c.name, p.artist;
What is the release year of the first music album by a female artist?
CREATE TABLE Music_Albums (artist VARCHAR(255),release_year INT,gender VARCHAR(6)); INSERT INTO Music_Albums (artist,release_year,gender) VALUES ('Artist1',2015,'Female'),('Artist2',2016,'Male'),('Artist3',2017,'Female'),('Artist4',2018,'Male'),('Artist5',2019,'Female');
SELECT release_year FROM Music_Albums WHERE gender = 'Female' ORDER BY release_year ASC LIMIT 1;
How many public libraries are there in each state?
CREATE TABLE states (state_id INT,state_name VARCHAR(255)); INSERT INTO states (state_id,state_name) VALUES (1,'California'),(2,'Texas'),(3,'Florida'),(4,'New York'); CREATE TABLE libraries (library_id INT,state_id INT); INSERT INTO libraries (library_id,state_id) VALUES (1,1),(2,2),(3,3),(4,1),(5,2),(6,4);
SELECT state_name, COUNT(*) FROM libraries JOIN states ON libraries.state_id = states.state_id GROUP BY state_name;
Insert a new employee record with ID 6, department 'Diversity & Inclusion', and salary 75000.
CREATE TABLE Employees (EmployeeID INT,Department VARCHAR(20),Salary DECIMAL(10,2)); INSERT INTO Employees (EmployeeID,Department,Salary) VALUES (1,'IT',70000.00),(2,'Marketing',55000.00),(3,'Marketing',58000.00),(4,'HR',60000.00),(5,'HR',62000.00);
INSERT INTO Employees (EmployeeID, Department, Salary) VALUES (6, 'Diversity & Inclusion', 75000.00);
What are the countries of origin for developers who have created digital assets with a market cap greater than $1 billion?
CREATE TABLE Developers (DeveloperId INT,DeveloperName VARCHAR(50),Country VARCHAR(50)); CREATE TABLE DigitalAssets (AssetId INT,AssetName VARCHAR(50),DeveloperId INT,MarketCap INT); INSERT INTO Developers (DeveloperId,DeveloperName,Country) VALUES (1,'Carla','Mexico'); INSERT INTO Developers (DeveloperId,DeveloperName,Country) VALUES (2,'Deepak','India'); INSERT INTO DigitalAssets (AssetId,AssetName,DeveloperId,MarketCap) VALUES (1,'AssetA',1,2000000000); INSERT INTO DigitalAssets (AssetId,AssetName,DeveloperId,MarketCap) VALUES (2,'AssetB',2,500000000); INSERT INTO DigitalAssets (AssetId,AssetName,DeveloperId,MarketCap) VALUES (3,'AssetC',1,2500000000);
SELECT d.Country FROM Developers d INNER JOIN DigitalAssets da ON d.DeveloperId = da.DeveloperId WHERE da.MarketCap > 1000000000;
Which countries have the most extensive maritime law coverage, as measured by the number of articles in their maritime law codes? Provide the top 5 countries and their corresponding law codes.
CREATE TABLE countries (id INT,name VARCHAR(100),maritime_law_code VARCHAR(100)); CREATE TABLE law_articles (id INT,country_id INT,article_number INT,text VARCHAR(1000));
SELECT c.name, COUNT(la.article_number) as num_articles FROM countries c INNER JOIN law_articles la ON c.id = la.country_id GROUP BY c.name ORDER BY num_articles DESC LIMIT 5;
What is the name and ID of the dam in the 'Dams' table with the oldest construction date?
CREATE TABLE Dams (ID INT,Name VARCHAR(50),Location VARCHAR(50),Length FLOAT,YearBuilt INT); INSERT INTO Dams (ID,Name,Location,Length,YearBuilt) VALUES (1,'Hoover Dam','Nevada/Arizona border',247.0,1936); INSERT INTO Dams (ID,Name,Location,Length,YearBuilt) VALUES (2,'Oroville Dam','Butte County,CA',2302.0,1968);
SELECT Name, ID FROM Dams WHERE YearBuilt = (SELECT MIN(YearBuilt) FROM Dams);
What is the average funding per round for series A rounds?
CREATE TABLE investment_rounds (startup_id INT PRIMARY KEY,round_type VARCHAR(255),funding_amount FLOAT);
SELECT AVG(funding_amount) FROM investment_rounds WHERE round_type = 'series A';
Who is the most prolific artist in the 'painting' category?
CREATE TABLE artworks (id INT,name VARCHAR(50),artist_id INT,category VARCHAR(20)); CREATE TABLE artists (id INT,name VARCHAR(50),country VARCHAR(50)); INSERT INTO artworks (id,name,artist_id,category) VALUES (1,'Painting',1,'painting'),(2,'Sculpture',2,'sculpture'),(3,'Drawing',3,'drawing'),(4,'Painting',1,'painting'),(5,'Painting',2,'painting'); INSERT INTO artists (id,name) VALUES (1,'John Doe'),(2,'Jane Smith'),(3,'Bob Johnson');
SELECT artists.name, COUNT(*) AS num_artworks FROM artworks JOIN artists ON artworks.artist_id = artists.id WHERE artworks.category = 'painting' GROUP BY artists.name ORDER BY num_artworks DESC LIMIT 1;
What is the most common treatment type for patients with 'PTSD' in 'clinic_TX'?
CREATE TABLE clinic_TX (patient_id INT,name VARCHAR(50),primary_diagnosis VARCHAR(50),treatment_type VARCHAR(50)); INSERT INTO clinic_TX (patient_id,name,primary_diagnosis,treatment_type) VALUES (1,'John Doe','PTSD','EMDR'),(2,'Jane Smith','PTSD','CBT'),(3,'Alice Johnson','PTSD','EMDR');
SELECT treatment_type, COUNT(*) as count FROM clinic_TX WHERE primary_diagnosis = 'PTSD' GROUP BY treatment_type ORDER BY count DESC LIMIT 1;
Find the account address and balance for accounts with a balance greater than 500,000 on the Cosmos Hub blockchain.
CREATE TABLE cosmos_hub_accounts (account_address VARCHAR(42),balance INTEGER);
SELECT account_address, balance FROM cosmos_hub_accounts WHERE balance > 500000;
Insert a new satellite 'Tanpopo' launched by Japan in 2013 into the 'satellites' table
CREATE TABLE satellites (id INT PRIMARY KEY,name VARCHAR(50),launch_year INT,country VARCHAR(50));
INSERT INTO satellites (id, name, launch_year, country) VALUES (6, 'Tanpopo', 2013, 'Japan');
What is the minimum price of gadolinium produced in Japan?
CREATE TABLE GadoliniumProduction (country VARCHAR(20),price DECIMAL(5,2),year INT); INSERT INTO GadoliniumProduction (country,price,year) VALUES ('Japan',150.00,2019),('Japan',140.00,2018);
SELECT MIN(price) FROM GadoliniumProduction WHERE country = 'Japan';
Find the number of industry 4.0 technologies implemented in each region and the average implementation cost, sorted by the average cost in ascending order.
CREATE TABLE industry_4_0_technologies (id INT PRIMARY KEY,region VARCHAR(255),technology_count INT,implementation_cost DECIMAL(6,2)); INSERT INTO industry_4_0_technologies (id,region,technology_count,implementation_cost) VALUES (1,'Region A',10,5000),(2,'Region B',12,4500),(3,'Region C',8,5500),(4,'Region D',15,4000),(5,'Region E',11,4800);
SELECT region, AVG(implementation_cost) as avg_cost FROM industry_4_0_technologies GROUP BY region ORDER BY avg_cost ASC;
What is the average age of all the trees in the Trees table?
CREATE TABLE Trees (id INT,species VARCHAR(255),age INT); INSERT INTO Trees (id,species,age) VALUES (1,'Oak',50),(2,'Pine',30),(3,'Maple',40);
SELECT AVG(age) FROM Trees;
What is the maximum billing amount for cases handled by attorneys with the name 'John'?
CREATE TABLE Attorneys (attorney_id INT,name TEXT,region TEXT); INSERT INTO Attorneys (attorney_id,name,region) VALUES (1,'John Doe','New York'),(2,'Jane Smith','California'); CREATE TABLE Cases (case_id INT,attorney_id INT,billing_amount INT); INSERT INTO Cases (case_id,attorney_id,billing_amount) VALUES (1,1,5000),(2,1,7000),(3,2,6000);
SELECT MAX(Cases.billing_amount) FROM Cases INNER JOIN Attorneys ON Cases.attorney_id = Attorneys.attorney_id WHERE Attorneys.name = 'John';
What is the total revenue generated from ads on Facebook in Q2 2021, for users in the 'celebrity' category?
CREATE TABLE ads (ad_id INT,user_id INT,platform VARCHAR(255),ad_revenue DECIMAL(10,2)); INSERT INTO ads (ad_id,user_id,platform,ad_revenue) VALUES (1,1,'Facebook',1500.50),(2,2,'Twitter',800.00),(3,3,'Facebook',1200.75);
SELECT SUM(ad_revenue) FROM ads WHERE platform = 'Facebook' AND MONTH(ad_date) BETWEEN 4 AND 6 AND YEAR(ad_date) = 2021 AND user_id IN (SELECT user_id FROM users WHERE category = 'celebrity');
Update the value of all 'Tank' equipment sales records in 'Asia' to 15000000 for the year '2022'
CREATE TABLE military_sales (id INT PRIMARY KEY,region VARCHAR(20),year INT,equipment_name VARCHAR(30),quantity INT,value FLOAT); INSERT INTO military_sales (id,region,year,equipment_name,quantity,value) VALUES (1,'Asia',2022,'Tank',20,10000000),(2,'Asia',2022,'Helicopter',15,11000000),(3,'Asia',2022,'Fighter Jet',22,16000000);
UPDATE military_sales SET value = 15000000 WHERE region = 'Asia' AND equipment_name = 'Tank' AND year = 2022;
How many investments were made in each country?
CREATE TABLE Investments (InvestmentID INT,Country VARCHAR(20),Amount INT); INSERT INTO Investments (InvestmentID,Country,Amount) VALUES (1,'USA',4000),(2,'Canada',3000),(3,'Mexico',5000),(4,'Brazil',6000),(5,'USA',7000),(6,'Canada',8000);
SELECT Country, COUNT(*) as NumberOfInvestments FROM Investments GROUP BY Country;
Which military equipment types have been decommissioned since 2010?
CREATE TABLE equipment_status (id INT,equipment_type VARCHAR(50),status VARCHAR(50),decommission_date DATE);
SELECT equipment_type FROM equipment_status WHERE status = 'Decommissioned' AND YEAR(decommission_date) >= 2010;
List the green building certifications and their corresponding carbon offset values for all buildings in the state of California.
CREATE TABLE green_buildings (building_id INT,building_name VARCHAR(255),state VARCHAR(255),certification_level VARCHAR(255),carbon_offset_tons INT);
SELECT certification_level, carbon_offset_tons FROM green_buildings WHERE state = 'California';
How many inspections were conducted at each facility?
CREATE TABLE FoodInspections (id INT PRIMARY KEY,facility_name VARCHAR(255),inspection_date DATE); INSERT INTO FoodInspections (id,facility_name,inspection_date) VALUES (1,'Tasty Burgers','2021-03-15'),(2,'Fresh Greens','2021-03-17'),(3,'Pizza Palace','2021-03-18'),(4,'Tasty Burgers','2021-03-19');
SELECT facility_name, COUNT(*) FROM FoodInspections GROUP BY facility_name;
Which country has the maximum CO2 offset for carbon offset initiatives?
CREATE TABLE IF NOT EXISTS carbon_offset_initiatives (initiative_id INT,initiative_name VARCHAR(255),co2_offset FLOAT,country VARCHAR(255),PRIMARY KEY (initiative_id)); INSERT INTO carbon_offset_initiatives (initiative_id,initiative_name,co2_offset,country) VALUES (1,'Tree Planting',50,'USA'),(2,'Solar Power Installation',100,'Canada'),(3,'Wind Farm Development',150,'Mexico');
SELECT country, MAX(co2_offset) FROM carbon_offset_initiatives GROUP BY country;
How many patients have participated in the Cognitive Behavioral Therapy program in each year?
CREATE TABLE patient (patient_id INT,name VARCHAR(50),age INT,gender VARCHAR(10),condition VARCHAR(50)); INSERT INTO patient (patient_id,name,age,gender,condition) VALUES (1,'John Doe',45,'Male','Anxiety'),(2,'Jane Smith',35,'Female','Depression'); CREATE TABLE treatment (treatment_id INT,patient_id INT,treatment_name VARCHAR(50),start_date DATE,end_date DATE); INSERT INTO treatment (treatment_id,patient_id,treatment_name,start_date,end_date) VALUES (1,1,'Cognitive Behavioral Therapy','2021-01-01','2021-03-31'),(2,2,'Cognitive Behavioral Therapy','2021-04-01','2021-06-30');
SELECT YEAR(start_date) AS year, COUNT(patient_id) AS num_patients FROM treatment WHERE treatment_name = 'Cognitive Behavioral Therapy' GROUP BY year;
Find the number of unique users who have streamed a song on each day.
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);
SELECT stream_date, COUNT(DISTINCT user_id) as unique_users FROM streams GROUP BY stream_date;
Find the top 3 suppliers with the highest ethical labor score.
CREATE TABLE supplier (supplier_id INT,name VARCHAR(255),ethical_score INT); INSERT INTO supplier (supplier_id,name,ethical_score) VALUES (1,'Green Supplies',90),(2,'Eco Distributors',85),(3,'Fair Trade Corp',95);
SELECT supplier_id, name, ethical_score FROM (SELECT supplier_id, name, ethical_score, RANK() OVER (ORDER BY ethical_score DESC) as rank FROM supplier) AS supplier_ranks WHERE rank <= 3;
Show the average billing amount for cases in the 'Personal Injury' category
CREATE TABLE cases (case_id INT,category VARCHAR(50),billing_amount INT); INSERT INTO cases (case_id,category,billing_amount) VALUES (1,'Personal Injury',5000),(2,'Civil Litigation',7000);
SELECT AVG(billing_amount) FROM cases WHERE category = 'Personal Injury';
Count the number of seafood species in the aquaculture database.
CREATE TABLE species (id INT,name VARCHAR(30),is_aquaculture BOOLEAN); INSERT INTO species (id,name,is_aquaculture) VALUES (1,'Salmon',true),(2,'Shrimp',true),(3,'Tuna',false),(4,'Tilapia',true);
SELECT COUNT(*) FROM species WHERE is_aquaculture = true;
What was the total donation amount by organizations in India in Q3 2021?
CREATE TABLE Donations (id INT,donor_name VARCHAR(255),donation_amount DECIMAL(10,2),donation_date DATE); INSERT INTO Donations (id,donor_name,donation_amount,donation_date) VALUES (1,'ABC Corporation',300.00,'2021-07-10'),(2,'XYZ Foundation',400.00,'2021-10-01');
SELECT SUM(donation_amount) FROM Donations WHERE donor_name LIKE '%India%' AND donation_date BETWEEN '2021-07-01' AND '2021-09-30';
What is the total number of transactions and their sum for each customer in the "online_customers" table?
CREATE TABLE online_customers (id INT,name VARCHAR(50),age INT,gender VARCHAR(10),city VARCHAR(50)); INSERT INTO online_customers (id,name,age,gender,city) VALUES (1,'Aisha Williams',32,'Female','Chicago'); INSERT INTO online_customers (id,name,age,gender,city) VALUES (2,'Hiroshi Tanaka',45,'Male','Tokyo'); INSERT INTO online_customers (id,name,age,gender,city) VALUES (3,'Clara Rodriguez',29,'Female','Madrid'); CREATE TABLE online_transactions (id INT,customer_id INT,type VARCHAR(50),amount DECIMAL(10,2),date DATE); INSERT INTO online_transactions (id,customer_id,type,amount,date) VALUES (1,1,'purchase',50.00,'2021-01-01'); INSERT INTO online_transactions (id,customer_id,type,amount,date) VALUES (2,1,'refund',10.00,'2021-01-05'); INSERT INTO online_transactions (id,customer_id,type,amount,date) VALUES (3,2,'purchase',100.00,'2021-01-02');
SELECT o.customer_id, o.name, COUNT(ot.id) as total_transactions, SUM(ot.amount) as total_amount FROM online_customers o JOIN online_transactions ot ON o.id = ot.customer_id GROUP BY o.customer_id, o.name;
Delete a cultural heritage site that no longer exists
CREATE TABLE cultural_heritage_sites (id INT PRIMARY KEY,name VARCHAR(255),country VARCHAR(255),status VARCHAR(255));
DELETE FROM cultural_heritage_sites WHERE name = 'Temple of Bel' AND country = 'Iraq';
Add a new ocean 'Southern Pacific Ocean' with an average depth of 4000 meters.
CREATE TABLE oceans (ocean_name VARCHAR(50),avg_depth NUMERIC(10,2));
INSERT INTO oceans (ocean_name, avg_depth) VALUES ('Southern Pacific Ocean', 4000);
Get the total number of articles published per month, for the last 2 years
CREATE TABLE articles (id INT PRIMARY KEY,title TEXT NOT NULL,published_at DATE);
SELECT YEAR(published_at) as year, MONTH(published_at) as month, COUNT(id) as total_articles FROM articles WHERE published_at >= DATE_SUB(CURDATE(), INTERVAL 2 YEAR) GROUP BY year, month;
What is the average speed of shared electric scooters in New York city?
CREATE TABLE shared_scooters (scooter_id INT,speed FLOAT,city VARCHAR(50));
SELECT AVG(speed) FROM shared_scooters WHERE city = 'New York';
What is the average daily energy storage capacity (in MWh) for geothermal power plants, grouped by continent?
CREATE TABLE geothermal_power_plants (name VARCHAR(50),location VARCHAR(50),capacity FLOAT,continent VARCHAR(50)); INSERT INTO geothermal_power_plants (name,location,capacity,continent) VALUES ('Plant E','USA',1200,'North America'),('Plant F','Indonesia',1500,'Asia'),('Plant G','Philippines',900,'Asia'),('Plant H','Kenya',700,'Africa');
SELECT continent, AVG(capacity) as avg_capacity FROM geothermal_power_plants GROUP BY continent;
What is the minimum number of trees planted in the Brazilian Amazon as part of reforestation projects in the last 5 years?
CREATE TABLE BrazilianReforestation (ID INT,Year INT,TreesPlanted INT); INSERT INTO BrazilianReforestation (ID,Year,TreesPlanted) VALUES (1,2017,10000),(2,2018,12000),(3,2019,15000),(4,2020,18000),(5,2021,20000);
SELECT MIN(TreesPlanted) FROM BrazilianReforestation WHERE Year BETWEEN (SELECT YEAR(CURDATE()) - 5) AND YEAR(CURDATE());
Identify the top 3 community health workers with the highest mental health scores in California.
CREATE TABLE community_health_workers (worker_id INT,worker_name TEXT,state TEXT,mental_health_score INT); INSERT INTO community_health_workers (worker_id,worker_name,state,mental_health_score) VALUES (1,'John Doe','NY',75),(2,'Jane Smith','CA',82),(3,'Alice Johnson','TX',68);
SELECT * FROM community_health_workers WHERE state = 'CA' ORDER BY mental_health_score DESC LIMIT 3;
What is the total number of research vessels registered in countries with a coastline of over 5000 kilometers, grouped by vessel type?
CREATE TABLE research_vessels (vessel_id INTEGER,vessel_name TEXT,vessel_type TEXT,vessel_flag TEXT,coastline_length FLOAT);
SELECT vessel_type, COUNT(vessel_id) FROM research_vessels WHERE coastline_length > 5000 GROUP BY vessel_type;
Identify the total number of public libraries in urban areas
CREATE TABLE areas (area_id INT,area_type TEXT);CREATE TABLE libraries (library_id INT,area_id INT,library_name TEXT);
SELECT COUNT(*) FROM libraries l INNER JOIN areas a ON l.area_id = a.area_id WHERE a.area_type = 'urban';
What is the total number of properties with inclusive housing units in the city of Seattle?
CREATE TABLE properties (id INT,city VARCHAR(255),inclusive BOOLEAN); INSERT INTO properties (id,city,inclusive) VALUES (1,'Seattle',TRUE),(2,'Seattle',FALSE),(3,'Portland',TRUE),(4,'Seattle',TRUE);
SELECT COUNT(*) FROM properties WHERE city = 'Seattle' AND inclusive = TRUE;
What is the distribution of vulnerabilities by severity for each product in the last quarter?
CREATE TABLE vulnerabilities (id INT,product VARCHAR(50),severity VARCHAR(10),quarter_year VARCHAR(10));
SELECT product, severity, COUNT(*) as vulnerability_count FROM vulnerabilities WHERE quarter_year = DATEADD(quarter, -1, GETDATE()) GROUP BY product, severity;
What is the total installed capacity of wind and solar power plants in Germany and France, by year?
CREATE TABLE wind_power (country text,year integer,capacity integer);CREATE TABLE solar_power (country text,year integer,capacity integer);
SELECT w.year, SUM(w.capacity + s.capacity) FROM wind_power w INNER JOIN solar_power s ON w.country = s.country AND w.year = s.year WHERE w.country IN ('Germany', 'France') GROUP BY w.year;
What is the average price of outdoor grown cannabis per pound in California dispensaries?
CREATE TABLE Dispensaries (id INT,dispensary_name VARCHAR(255),state VARCHAR(255),income DECIMAL(10,2)); INSERT INTO Dispensaries (id,dispensary_name,state,income) VALUES (1,'Sunshine State Dispensary','California',150000.00); CREATE TABLE Cannabis_Inventory (id INT,dispensary_id INT,inventory_type VARCHAR(255),weight DECIMAL(10,2),price DECIMAL(10,2)); INSERT INTO Cannabis_Inventory (id,dispensary_id,inventory_type,weight,price) VALUES (1,1,'Outdoor',10.00,2500.00);
SELECT AVG(price / 16) as avg_price FROM Dispensaries d JOIN Cannabis_Inventory i ON d.id = i.dispensary_id WHERE d.state = 'California' AND i.inventory_type = 'Outdoor';
How many clinical trials were 'ONGOING' for drug 'D003'?
CREATE TABLE clinical_trials (drug_id VARCHAR(10),trial_status VARCHAR(10));
SELECT COUNT(*) FROM clinical_trials WHERE drug_id = 'D003' AND trial_status = 'ONGOING';
Which ingredients have been sourced from India for cosmetic products in the past year?
CREATE TABLE ingredient_sourcing (ingredient_name VARCHAR(255),sourcing_location VARCHAR(255),last_updated DATE); INSERT INTO ingredient_sourcing (ingredient_name,sourcing_location,last_updated) VALUES ('Neem','India','2022-03-01'),('Turmeric','India','2022-02-15'),('Sandalwood','India','2022-04-05');
SELECT ingredient_name FROM ingredient_sourcing WHERE sourcing_location = 'India' AND last_updated >= DATEADD(year, -1, GETDATE());
What is the total number of cyber threats detected in the last 6 months?
CREATE TABLE Threat_Detection (ID INT,Month VARCHAR(50),Year INT,Threats INT); INSERT INTO Threat_Detection (ID,Month,Year,Threats) VALUES (1,'January',2020,500),(2,'February',2020,600),(3,'March',2020,700);
SELECT Year, Month, SUM(Threats) FROM Threat_Detection WHERE Year = 2020 AND Month IN ('January', 'February', 'March', 'April', 'May', 'June') GROUP BY Year, Month;
What is the average donation amount for donors from India?
CREATE TABLE Donors (DonorID int,DonorName varchar(50),DonorNationality varchar(50),AmountDonated numeric(10,2),DonationYear int); INSERT INTO Donors (DonorID,DonorName,DonorNationality,AmountDonated,DonationYear) VALUES (1,'James Smith','American',600,2021),(2,'Aisha Khan','Pakistani',400,2021),(3,'Park Ji-min','Indian',500,2021);
SELECT AVG(AmountDonated) as AverageDonation FROM Donors WHERE DonorNationality = 'Indian';
Which team has the highest percentage of female fans?
CREATE TABLE teams (team_id INT,team_name VARCHAR(255)); INSERT INTO teams (team_id,team_name) VALUES (1,'Atlanta Hawks'),(2,'Boston Celtics'); CREATE TABLE fan_demographics (fan_id INT,team_id INT,gender VARCHAR(10)); INSERT INTO fan_demographics (fan_id,team_id,gender) VALUES (1,1,'Female'),(2,1,'Male'),(3,2,'Female'),(4,2,'Female');
SELECT t.team_name, 100.0 * COUNT(CASE WHEN fd.gender = 'Female' THEN 1 END) / COUNT(*) as pct_female_fans FROM teams t INNER JOIN fan_demographics fd ON t.team_id = fd.team_id GROUP BY t.team_name ORDER BY pct_female_fans DESC LIMIT 1;
What was the total number of volunteer hours in environmental programs in Q1 2022?
CREATE TABLE Programs (program_id INT,program_name VARCHAR(50),category VARCHAR(20)); CREATE TABLE Volunteer_Hours (volunteer_id INT,program_id INT,hours DECIMAL(5,2),volunteer_date DATE);
SELECT SUM(hours) FROM Volunteer_Hours v JOIN Programs p ON v.program_id = p.program_id WHERE p.category = 'environmental' AND v.volunteer_date BETWEEN '2022-01-01' AND '2022-03-31';
Delete all maintenance records for buses older than 2018
CREATE TABLE maintenance (record_id INT,bus_id INT,year INT); INSERT INTO maintenance (record_id,bus_id,year) VALUES (1,101,2015),(2,102,2017),(3,101,2018),(4,103,2019);
DELETE FROM maintenance WHERE year < 2018;
Which biotech startups have the word 'gene' in their name?
CREATE TABLE startups (id INT,name VARCHAR(50),location VARCHAR(50),funding FLOAT); INSERT INTO startups (id,name,location,funding) VALUES (1,'Genetech','California',12000000); INSERT INTO startups (id,name,location,funding) VALUES (2,'Zymergen','California',25000000);
SELECT name FROM startups WHERE name LIKE '%gene%';
What is the current landfill capacity utilization in percentage for each region?
CREATE TABLE landfill_capacity_utilization(region VARCHAR(255),capacity_cu_m FLOAT,current_utilization FLOAT,current_date DATE);
SELECT region, current_utilization FROM landfill_capacity_utilization WHERE current_date = GETDATE();
Increase the budget of a specific renewable energy project by 10%
CREATE TABLE renewable_energy_projects (id INT,name TEXT,budget FLOAT); INSERT INTO renewable_energy_projects (id,name,budget) VALUES (1,'Solar Farm',5000000.00),(2,'Wind Farm',7000000.00);
WITH project_update AS (UPDATE renewable_energy_projects SET budget = budget * 1.10 WHERE id = 1) SELECT * FROM project_update;
Insert a new policy with policy number 222333, policy type 'Commercial', state 'NY', and coverage amount 400000.
CREATE TABLE policies (policy_number INT,policy_type VARCHAR(50),coverage_amount INT,state VARCHAR(2));
INSERT INTO policies (policy_number, policy_type, coverage_amount, state) VALUES (222333, 'Commercial', 400000, 'NY');
List the names of the services for which the budget has decreased in the last 2 years.
CREATE TABLE Budget(Year INT,Service VARCHAR(20),Budget FLOAT); INSERT INTO Budget VALUES(2020,'Education',15000000),(2020,'Healthcare',20000000),(2021,'Education',14000000),(2021,'Healthcare',21000000),(2020,'Public Transport',10000000),(2021,'Public Transport',10500000);
SELECT DISTINCT Service FROM Budget WHERE (Budget - LAG(Budget, 1) OVER (PARTITION BY Service ORDER BY Year)) < 0 AND Year IN (2020, 2021);
What is the total number of security incidents and unique IP addresses involved in those incidents for each country in the last month?
CREATE TABLE security_incidents (id INT,country VARCHAR(50),incident_count INT,incident_date DATE); CREATE TABLE ip_addresses (id INT,incident_id INT,ip_address VARCHAR(50),PRIMARY KEY (id,incident_id)); INSERT INTO security_incidents (id,country,incident_count,incident_date) VALUES (1,'USA',25,'2022-01-01'),(2,'Canada',10,'2022-01-02'); INSERT INTO ip_addresses (id,incident_id,ip_address) VALUES (1,1,'192.168.1.1'),(2,1,'192.168.1.2');
SELECT security_incidents.country, SUM(security_incidents.incident_count) as total_incidents, COUNT(DISTINCT ip_addresses.ip_address) as unique_ips FROM security_incidents INNER JOIN ip_addresses ON security_incidents.id = ip_addresses.incident_id WHERE security_incidents.incident_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH) GROUP BY security_incidents.country;
What is the total amount of research grants awarded to faculty members in the Biology department?
CREATE TABLE Faculty (FacultyID INT,Name VARCHAR(50),Department VARCHAR(50),Gender VARCHAR(10),Salary INT); INSERT INTO Faculty (FacultyID,Name,Department,Gender,Salary) VALUES (1,'Alice','Biology','Female',80000); INSERT INTO Faculty (FacultyID,Name,Department,Gender,Salary) VALUES (2,'Bob','Biology','Male',85000); CREATE TABLE ResearchGrants (GrantID INT,FacultyID INT,Amount INT); INSERT INTO ResearchGrants (GrantID,FacultyID,Amount) VALUES (1,1,90000); INSERT INTO ResearchGrants (GrantID,FacultyID,Amount) VALUES (2,2,95000);
SELECT SUM(rg.Amount) FROM ResearchGrants rg INNER JOIN Faculty f ON rg.FacultyID = f.FacultyID WHERE f.Department = 'Biology';
What is the maximum number of peacekeeping personnel deployed for each peacekeeping operation?
CREATE TABLE peacekeeping_operations (id INT,name TEXT,start_date DATE,end_date DATE); CREATE TABLE peacekeeping_personnel (id INT,operation_id INT,year INT,personnel INT); INSERT INTO peacekeeping_operations (id,name,start_date,end_date) VALUES (1,'Operation1','2010-01-01','2015-01-01'),(2,'Operation2','2015-01-01','2020-01-01'),(3,'Operation3','2020-01-01','2022-01-01'); INSERT INTO peacekeeping_personnel (id,operation_id,year,personnel) VALUES (1,1,2010,1000),(2,1,2011,1200),(3,2,2016,1500),(4,3,2021,2000);
SELECT peacekeeping_operations.name, MAX(peacekeeping_personnel.personnel) FROM peacekeeping_operations JOIN peacekeeping_personnel ON peacekeeping_operations.id = peacekeeping_personnel.operation_id GROUP BY peacekeeping_operations.name;
What are the total expenses for the SpaceX satellite deployment projects and the NASA space exploration research programs?
CREATE TABLE SpaceX_Projects (project_id INT,name VARCHAR(50),type VARCHAR(50),expenses DECIMAL(10,2));CREATE TABLE NASA_Research (research_id INT,name VARCHAR(50),type VARCHAR(50),expenses DECIMAL(10,2)); INSERT INTO SpaceX_Projects (project_id,name,type,expenses) VALUES (1,'Starlink','Satellite Deployment',3000000.00),(2,'Starship','Space Exploration',5000000.00); INSERT INTO NASA_Research (research_id,name,type,expenses) VALUES (1,'Mars Rover','Space Exploration',2000000.00),(2,'ISS Upgrades','Space Station',1500000.00);
SELECT SUM(expenses) FROM SpaceX_Projects WHERE type IN ('Satellite Deployment', 'Space Exploration') UNION ALL SELECT SUM(expenses) FROM NASA_Research WHERE type IN ('Space Exploration', 'Space Station');
What are the names of all economic diversification efforts in the 'rural_development' schema, excluding those related to 'tourism'?
CREATE SCHEMA IF NOT EXISTS rural_development;CREATE TABLE IF NOT EXISTS rural_development.economic_diversification (name VARCHAR(255),id INT);INSERT INTO rural_development.economic_diversification (name,id) VALUES ('renewable_energy',1),('handicraft_promotion',2),('local_food_production',3),('tourism_development',4);
SELECT name FROM rural_development.economic_diversification WHERE name NOT LIKE '%tourism%';
What was the total construction spending for each month in the state of Florida in 2019?
CREATE TABLE construction_spending (spending_id INT,amount FLOAT,state VARCHAR(50),spend_date DATE); INSERT INTO construction_spending (spending_id,amount,state,spend_date) VALUES (9,120000,'Florida','2019-01-01'); INSERT INTO construction_spending (spending_id,amount,state,spend_date) VALUES (10,180000,'Florida','2019-02-01');
SELECT EXTRACT(MONTH FROM spend_date) AS month, SUM(amount) AS total_spending FROM construction_spending WHERE state = 'Florida' AND YEAR(spend_date) = 2019 GROUP BY month;
Determine the number of customers who have an account balance greater than the 75th percentile for their account type.
CREATE TABLE accounts (customer_id INT,account_type VARCHAR(20),balance DECIMAL(10,2));
SELECT COUNT(DISTINCT customer_id) FROM accounts WHERE balance > PERCENTILE_CONT(0.75) WITHIN GROUP (ORDER BY balance) OVER (PARTITION BY account_type);
List all eco-friendly housing policies in cities with a population over 1 million
CREATE TABLE housing_policies (id INT,city VARCHAR(50),eco_friendly BOOLEAN); INSERT INTO housing_policies VALUES (1,'NYC',TRUE); INSERT INTO housing_policies VALUES (2,'LA',FALSE); INSERT INTO housing_policies VALUES (3,'Chicago',TRUE);
SELECT city FROM housing_policies WHERE eco_friendly = TRUE INTERSECT SELECT city FROM cities WHERE population > 1000000;
How many public consultations were held in Nairobi, Kenya between January 1, 2022 and March 31, 2022?
CREATE TABLE public_consultations (consultation_id INT,consultation_date DATE,consultation_city VARCHAR(50)); INSERT INTO public_consultations (consultation_id,consultation_date,consultation_city) VALUES (1,'2022-02-01','Nairobi');
SELECT COUNT(*) FROM public_consultations WHERE consultation_city = 'Nairobi' AND consultation_date BETWEEN '2022-01-01' AND '2022-03-31';
What was the total organic matter (in kg) in soil samples from each region in 2020?
CREATE TABLE soil_samples (id INT,region_id INT,organic_matter_kg FLOAT,date DATE);
SELECT region_id, SUM(organic_matter_kg) FROM soil_samples WHERE YEAR(date) = 2020 GROUP BY region_id;
What is the total installed capacity of renewable energy projects for each country, ranked by the total capacity?
CREATE TABLE CountryProjects (ProjectID INT,ProjectName VARCHAR(255),Country VARCHAR(255),Capacity FLOAT); INSERT INTO CountryProjects (ProjectID,ProjectName,Country,Capacity) VALUES (1,'SolarFarm1','USA',5000),(2,'WindFarm2','Germany',7000),(3,'HydroPlant3','Brazil',6000),(4,'GeoThermal4','China',8000),(5,'Biomass5','Canada',4000);
SELECT Country, SUM(Capacity) AS Total_Capacity FROM CountryProjects GROUP BY Country ORDER BY Total_Capacity DESC;
List all unique digital initiatives by museums located in the Asia-Pacific region.
CREATE TABLE Digital_Initiatives (id INT,museum VARCHAR(255),initiative VARCHAR(255)); INSERT INTO Digital_Initiatives (id,museum,initiative) VALUES (1,'National Museum of Australia','Virtual Tour'),(2,'British Museum','Online Collection'),(3,'Metropolitan Museum of Art','Digital Archive'),(4,'National Museum of China','Interactive Exhibit');
SELECT DISTINCT initiative FROM Digital_Initiatives WHERE museum LIKE 'National Museum%';
Find the top 5 cities with the highest avg salary in the 'reporters' table
CREATE TABLE reporters (id INT,city VARCHAR(255),salary DECIMAL(10,2)); INSERT INTO reporters (id,city,salary) VALUES (1,'NYC',80000.00),(2,'LA',70000.00),(3,'Chicago',75000.00),(4,'Miami',72000.00),(5,'Dallas',78000.00)
SELECT city, AVG(salary) as avg_salary FROM reporters GROUP BY city ORDER BY avg_salary DESC LIMIT 5;
What is the total number of public transportation trips in New York City for the year 2020?
CREATE TABLE public_trips (trip_id INT,trip_date DATE,trip_city VARCHAR(50)); INSERT INTO public_trips (trip_id,trip_date,trip_city) VALUES (1,'2020-01-01','New York City'),(2,'2020-01-02','New York City');
SELECT SUM(trips) FROM (SELECT COUNT(*) AS trips FROM public_trips WHERE trip_city = 'New York City' AND trip_date BETWEEN '2020-01-01' AND '2020-12-31' GROUP BY EXTRACT(MONTH FROM trip_date)) AS subquery;
What is the average salary of employees in each department, excluding any departments with fewer than 5 employees?
CREATE TABLE employees (employee_id INT,department TEXT,salary DECIMAL); INSERT INTO employees (employee_id,department,salary) VALUES (1,'Marketing',50000.00),(2,'IT',60000.00),(3,'HR',55000.00);
SELECT department, AVG(salary) FROM employees GROUP BY department HAVING COUNT(*) >= 5;
How many volunteers signed up in each program in 2020?
CREATE TABLE Volunteers (VolunteerID INT,ProgramID INT,SignUpDate DATE); CREATE TABLE Programs (ProgramID INT,ProgramName VARCHAR(255));
SELECT ProgramID, ProgramName, COUNT(VolunteerID) as NumVolunteers FROM Volunteers INNER JOIN Programs ON Volunteers.ProgramID = Programs.ProgramID WHERE YEAR(SignUpDate) = 2020 GROUP BY ProgramID, ProgramName;
Find the top 3 countries with the highest number of sustainable material suppliers?
CREATE TABLE Suppliers (SupplierID INT,SupplierName VARCHAR(50),Country VARCHAR(50),Certification VARCHAR(50),Material VARCHAR(50)); INSERT INTO Suppliers (SupplierID,SupplierName,Country,Certification,Material) VALUES (1,'Supplier A','Vietnam','Fair Trade','Organic Cotton'),(2,'Supplier B','Bangladesh','Fair Trade','Organic Cotton'),(3,'Supplier C','Vietnam','Certified Organic','Organic Cotton'),(4,'Supplier D','India','Fair Trade','Recycled Polyester'),(5,'Supplier E','China','Certified Organic','Recycled Polyester'),(6,'Supplier F','Indonesia','Fair Trade','Hemp'),(7,'Supplier G','India','Certified Organic','Hemp');
SELECT Country, COUNT(*) AS NumberOfSuppliers FROM Suppliers GROUP BY Country ORDER BY NumberOfSuppliers DESC LIMIT 3;
What is the total number of eco-friendly hotels in each continent?
CREATE TABLE hotels (hotel_id INT,name TEXT,country TEXT,continent TEXT,eco_friendly BOOLEAN); INSERT INTO hotels (hotel_id,name,country,continent,eco_friendly) VALUES (1,'Green Hotel','Brazil','South America',true),(2,'Eco Lodge','France','Europe',true),(3,'Polluting Hotel','USA','North America',false),(4,'Sustainable Hotel','Japan','Asia',true);
SELECT continent, COUNT(*) FROM hotels WHERE eco_friendly = true GROUP BY continent;
Show the name and construction date of the oldest dam
CREATE TABLE dams (id INT,name TEXT,construction_date DATE); INSERT INTO dams (id,name,construction_date) VALUES (1,'Dam A','1950-05-15'),(2,'Dam B','1965-08-27');
SELECT name, MIN(construction_date) FROM dams;
What are the total sales for each drug in Q3 2020?
CREATE TABLE drugs (drug_id INT,drug_name TEXT); INSERT INTO drugs (drug_id,drug_name) VALUES (1001,'Ibuprofen'),(1002,'Paracetamol'),(1003,'Aspirin'); CREATE TABLE sales (sale_id INT,drug_id INT,sale_date DATE,revenue FLOAT); INSERT INTO sales (sale_id,drug_id,sale_date,revenue) VALUES (1,1001,'2020-07-05',1800.0),(2,1002,'2020-08-10',2300.0),(3,1003,'2020-09-15',1400.0),(4,1001,'2020-10-20',1900.0),(5,1002,'2020-11-25',2400.0);
SELECT drug_name, SUM(revenue) as total_sales FROM sales JOIN drugs ON sales.drug_id = drugs.drug_id WHERE sale_date BETWEEN '2020-07-01' AND '2020-09-30' GROUP BY drug_name;
Update the endangered status of the Polar Bear to true
CREATE TABLE species(id INT,name VARCHAR(255),common_name VARCHAR(255),population INT,endangered BOOLEAN);
UPDATE species SET endangered = true WHERE common_name = 'Polar Bear';
List all deep-sea expeditions led by Japanese researchers.
CREATE TABLE deep_sea_expeditions (leader VARCHAR(255),country VARCHAR(255)); INSERT INTO deep_sea_expeditions (leader,country) VALUES ('Dr. Shinsuke Kawagucci','Japan'),('Dr. Makoto Kuwahara','Japan');
SELECT * FROM deep_sea_expeditions WHERE country = 'Japan';
List the top 5 cities where most users posted about vegan food in the past month.
CREATE TABLE users (id INT,name VARCHAR(255),city VARCHAR(255)); CREATE TABLE posts (id INT,post_text TEXT,post_date DATETIME);
SELECT city, COUNT(*) AS post_count FROM posts p JOIN users u ON p.user_id = u.id WHERE p.post_text LIKE '%vegan food%' AND DATE(p.post_date) > DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH) GROUP BY city ORDER BY post_count DESC LIMIT 5;
How many tickets were sold for basketball games in Los Angeles and Chicago in the last quarter?
CREATE TABLE tickets (ticket_id INT,game_id INT,price INT,sale_date DATE); INSERT INTO tickets (ticket_id,game_id,price,sale_date) VALUES (1,1,50,'2021-09-01'),(2,2,60,'2021-10-01'); CREATE TABLE games (game_id INT,sport VARCHAR(20),city VARCHAR(20),game_date DATE); INSERT INTO games (game_id,sport,city,game_date) VALUES (1,'Basketball','Los Angeles','2021-09-01'),(2,'Basketball','Chicago','2021-10-01');
SELECT COUNT(tickets.ticket_id) FROM tickets INNER JOIN games ON tickets.game_id = games.game_id WHERE games.sport = 'Basketball' AND (games.city = 'Los Angeles' OR games.city = 'Chicago') AND tickets.sale_date >= DATEADD(quarter, -1, GETDATE());
What is the average age of community health workers by their gender identity?
CREATE TABLE CommunityHealthWorkers (WorkerID INT,Age INT,GenderIdentity VARCHAR(255)); INSERT INTO CommunityHealthWorkers (WorkerID,Age,GenderIdentity) VALUES (1,35,'Transgender Woman'); INSERT INTO CommunityHealthWorkers (WorkerID,Age,GenderIdentity) VALUES (2,42,'Cisgender Man'); INSERT INTO CommunityHealthWorkers (WorkerID,Age,GenderIdentity) VALUES (3,50,'Non-binary'); INSERT INTO CommunityHealthWorkers (WorkerID,Age,GenderIdentity) VALUES (4,30,'Genderqueer');
SELECT GenderIdentity, AVG(Age) FROM CommunityHealthWorkers GROUP BY GenderIdentity;
Find the number of successful satellite launches by company ABC
CREATE TABLE satellites (id INT,name VARCHAR(50),launch_status VARCHAR(50),manufacturer VARCHAR(50),launch_date DATE);
SELECT COUNT(*) FROM satellites WHERE launch_status = 'Success' AND manufacturer = 'ABC';
What is the monthly energy production (in MWh) for each wind farm, ranked by the highest production?
CREATE TABLE wind_farms (name VARCHAR(50),location VARCHAR(50),capacity FLOAT,production_mwh FLOAT); INSERT INTO wind_farms (name,location,capacity,production_mwh) VALUES ('Farm I','Texas',300,5000),('Farm J','Oklahoma',250,4500),('Farm K','Kansas',350,5200),('Farm L','Iowa',280,4800);
SELECT name, production_mwh, ROW_NUMBER() OVER (ORDER BY production_mwh DESC) as rank FROM wind_farms;
Identify the number of mental health parity violations by state?
CREATE TABLE mental_health_parity_violations (id INT,state VARCHAR(50),violation_count INT); INSERT INTO mental_health_parity_violations (id,state,violation_count) VALUES (1,'California',10),(2,'Florida',5),(3,'Illinois',15);
SELECT state, SUM(violation_count) as total_violations FROM mental_health_parity_violations GROUP BY state;
Update the "providers" table to add a new column for "email" and update the "name" column to "full_name"
CREATE TABLE providers (provider_id INT,name VARCHAR(50),zip_code VARCHAR(10));
ALTER TABLE providers ADD COLUMN email VARCHAR(50); UPDATE providers SET full_name = name;
What is the average walkability score for properties in the urban_neighborhoods view?
CREATE VIEW urban_neighborhoods AS SELECT * FROM properties WHERE neighborhood_type = 'urban';
SELECT AVG(walkability_score) FROM urban_neighborhoods;
What is the total number of flu shots administered in Los Angeles County in 2019?
CREATE TABLE Flu_Shots (ID INT,Quantity INT,Location VARCHAR(50),Year INT); INSERT INTO Flu_Shots (ID,Quantity,Location,Year) VALUES (1,500,'Los Angeles County',2019); INSERT INTO Flu_Shots (ID,Quantity,Location,Year) VALUES (2,300,'Los Angeles County',2019);
SELECT SUM(Quantity) FROM Flu_Shots WHERE Location = 'Los Angeles County' AND Year = 2019;
Find the top 3 countries with the highest number of spacecraft manufactured, along with the number of spacecraft manufactured by each.
CREATE TABLE Spacecraft (SpacecraftID INT,Name VARCHAR(50),ManufacturingCountry VARCHAR(50)); INSERT INTO Spacecraft (SpacecraftID,Name,ManufacturingCountry) VALUES (1,'Space Shuttle Atlantis','USA'); INSERT INTO Spacecraft (SpacecraftID,Name,ManufacturingCountry) VALUES (2,'Space Shuttle Discovery','USA'); INSERT INTO Spacecraft (SpacecraftID,Name,ManufacturingCountry) VALUES (3,'Space Shuttle Endeavour','USA'); INSERT INTO Spacecraft (SpacecraftID,Name,ManufacturingCountry) VALUES (4,'Soyuz TMA-14M','Russia'); INSERT INTO Spacecraft (SpacecraftID,Name,ManufacturingCountry) VALUES (5,'Shenzhou 11','China');
SELECT ManufacturingCountry, COUNT(*) AS SpacecraftCount FROM Spacecraft GROUP BY ManufacturingCountry ORDER BY SpacecraftCount DESC LIMIT 3;
What is the total amount invested in organizations located in 'New York, NY' with a 'High' operational risk level?
CREATE TABLE risk (id INT PRIMARY KEY,investment_id INT,type VARCHAR(255),level VARCHAR(255)); INSERT INTO risk (id,investment_id,type,level) VALUES (3,3,'Operational Risk','High'); CREATE TABLE investment (id INT PRIMARY KEY,organization_id INT,amount FLOAT,date DATE); INSERT INTO investment (id,organization_id,amount,date) VALUES (3,3,12000,'2020-05-15'); CREATE TABLE organization (id INT PRIMARY KEY,name VARCHAR(255),sector VARCHAR(255),location VARCHAR(255)); INSERT INTO organization (id,name,sector,location) VALUES (3,'Code to Inspire','Nonprofit','New York,NY');
SELECT investment.amount FROM investment INNER JOIN organization ON investment.organization_id = organization.id INNER JOIN risk ON investment.id = risk.investment_id WHERE organization.location = 'New York, NY' AND risk.type = 'Operational Risk' AND risk.level = 'High';
What is the minimum severity of vulnerabilities found in the last week?
CREATE TABLE vulnerabilities (id INT,severity FLOAT); INSERT INTO vulnerabilities (id,severity) VALUES (1,7.5);
SELECT MIN(severity) FROM vulnerabilities WHERE vulnerabilities.id IN (SELECT MAX(id) FROM vulnerabilities WHERE incident_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 WEEK));
List all abstract expressionist artists and their highest-selling artwork.
CREATE TABLE artworks (id INT,art_name VARCHAR(50),style VARCHAR(50),artist_name VARCHAR(50)); CREATE TABLE sales (id INT,artwork_id INT,price DECIMAL(10,2));
SELECT a.artist_name, MAX(s.price) as highest_selling_price FROM artworks a JOIN sales s ON a.id = s.artwork_id WHERE a.style = 'Abstract Expressionism' GROUP BY a.artist_name;
What is the average monthly energy production (in MWh) for each renewable energy source in 2019?
CREATE TABLE energy_production (source VARCHAR(255),month INT,year INT,production FLOAT);
SELECT source, AVG(production) FROM energy_production WHERE year = 2019 GROUP BY source, month;
Which performing arts events had the highest and lowest attendance by gender?
CREATE TABLE performing_arts_events (id INT,event_name VARCHAR(255),event_date DATE,attendee_gender VARCHAR(255));
SELECT event_name, attendee_gender, COUNT(attendee_gender) as attendance FROM performing_arts_events GROUP BY event_name, attendee_gender ORDER BY attendance DESC, event_name;
Count the number of cases in 'cases' table for each attorney
CREATE TABLE cases (case_id INT,case_number VARCHAR(50),client_name VARCHAR(50),attorney_id INT);
SELECT attorney_id, COUNT(*) FROM cases GROUP BY attorney_id;
List the number of nuclear power plants in France, Russia, and the United Kingdom, as of 2020.
CREATE TABLE nuclear_plants (country VARCHAR(50),operational BOOLEAN,year INT); INSERT INTO nuclear_plants (country,operational,year) VALUES ('France',true,2020),('Russia',true,2020),('United Kingdom',true,2020),('Germany',false,2020);
SELECT country, COUNT(*) FROM nuclear_plants WHERE country IN ('France', 'Russia', 'United Kingdom') AND operational = true GROUP BY country;
Find the total number of cases in the 'CriminalJustice' table and the number of cases with 'case_status' of 'pending' or 'in_progress'
CREATE TABLE CriminalJustice (case_id INT,case_status VARCHAR(10)); INSERT INTO CriminalJustice (case_id,case_status) VALUES (1,'pending'),(2,'closed'),(3,'pending'),(4,'in_progress'),(5,'closed'),(6,'in_progress');
SELECT COUNT(*) AS total_cases, SUM(CASE WHEN case_status IN ('pending', 'in_progress') THEN 1 ELSE 0 END) AS pending_or_in_progress_cases FROM CriminalJustice;
Determine the average daily water usage for 'residential' purposes in 'September 2021' from the 'water_usage' table
CREATE TABLE water_usage (id INT,usage FLOAT,purpose VARCHAR(20),date DATE); INSERT INTO water_usage (id,usage,purpose,date) VALUES (1,50,'residential','2021-09-01'); INSERT INTO water_usage (id,usage,purpose,date) VALUES (2,60,'residential','2021-09-02');
SELECT AVG(usage) FROM (SELECT usage FROM water_usage WHERE purpose = 'residential' AND date BETWEEN '2021-09-01' AND '2021-09-30' GROUP BY date) as daily_usage;
Who are the top 2 oldest athletes in 'NHL' and 'NBA' wellbeing programs?
CREATE TABLE Athletes (athlete_id INT,athlete_name VARCHAR(255),age INT,team VARCHAR(255)); CREATE VIEW WellbeingPrograms AS SELECT athlete_id,team FROM Programs WHERE program_type IN ('NHL','NBA');
SELECT Athletes.athlete_name, Athletes.age FROM Athletes INNER JOIN WellbeingPrograms ON Athletes.athlete_id = WellbeingPrograms.athlete_id WHERE (Athletes.team = 'NHL' OR Athletes.team = 'NBA') GROUP BY Athletes.athlete_name ORDER BY Athletes.age DESC LIMIT 2;
What is the maximum price of a product sold by vendors with a circular supply chain?
CREATE TABLE vendors(vendor_id INT,vendor_name TEXT,circular_supply_chain BOOLEAN); INSERT INTO vendors(vendor_id,vendor_name,circular_supply_chain) VALUES (1,'VendorA',TRUE),(2,'VendorB',FALSE),(3,'VendorC',TRUE);
SELECT MAX(transactions.price) FROM transactions JOIN vendors ON transactions.vendor_id = vendors.vendor_id WHERE vendors.circular_supply_chain = TRUE;
What is the maximum investment amount for 'gender_equality' focused projects?
CREATE TABLE impact_projects (id INT,focus_area VARCHAR(20),investment_amount FLOAT); INSERT INTO impact_projects (id,focus_area,investment_amount) VALUES (1,'gender_equality',45000),(2,'gender_equality',52000),(3,'gender_equality',39000);
SELECT MAX(investment_amount) FROM impact_projects WHERE focus_area = 'gender_equality';
Insert a new financial institution 'Green Finance Corporation' in the 'Canada' region.
CREATE TABLE financial_institutions (name TEXT,region TEXT); INSERT INTO financial_institutions (name,region) VALUES ('Bank of America','USA'),('Barclays Bank','UK');
INSERT INTO financial_institutions (name, region) VALUES ('Green Finance Corporation', 'Canada');