instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
What is the maximum trip distance for public transportation in Sydney?
CREATE TABLE public_transportation (trip_id INT,trip_distance FLOAT,city VARCHAR(50)); INSERT INTO public_transportation (trip_id,trip_distance,city) VALUES (1,23.5,'Sydney'),(2,34.7,'Sydney'),(3,12.8,'Sydney');
SELECT MAX(trip_distance) FROM public_transportation WHERE city = 'Sydney';
What is the total CO2 savings of public transportation in New York in a year?
CREATE TABLE public_transportation (transport_id INT,ride_id INT,start_time TIMESTAMP,end_time TIMESTAMP,co2_savings INT);
SELECT SUM(co2_savings) FROM public_transportation WHERE YEAR(start_time) = 2022 AND city = 'New York';
What is the total quantity of unsold garments for each manufacturer based in 'Italy' or 'Spain'?
CREATE TABLE manufacturers (id INT PRIMARY KEY,name VARCHAR(255),country VARCHAR(255)); CREATE TABLE garments (id INT PRIMARY KEY,manufacturer_id INT,quantity_manufactured INT,quantity_sold INT);
SELECT m.name, SUM(g.quantity_manufactured - g.quantity_sold) as total_unsold_quantity FROM manufacturers m JOIN garments g ON m.id = g.manufacturer_id WHERE m.country IN ('Italy', 'Spain') GROUP BY m.name;
How many policies are there for each Underwriting team in NY?
CREATE TABLE Policies (PolicyID INT,Team VARCHAR(20),State VARCHAR(20)); INSERT INTO Policies VALUES (1,'Team A','New York'),(2,'Team B','California'),(3,'Team A','Texas'),(4,'Team C','New York');
SELECT Team, COUNT(*) FROM Policies WHERE State = 'New York' GROUP BY Team;
What is the total number of policies issued per agent in the 'Eastern' region?
CREATE TABLE Agents (AgentID INT,AgentRegion VARCHAR(10)); INSERT INTO Agents (AgentID,AgentRegion) VALUES (1,'Eastern'),(2,'Western'),(3,'Eastern'); CREATE TABLE Policies (PolicyID INT,AgentID INT); INSERT INTO Policies (PolicyID,AgentID) VALUES (1,1),(2,1),(3,2),(4,3),(5,1);
SELECT Agents.AgentRegion, COUNT(Policies.PolicyID) AS TotalPolicies FROM Agents INNER JOIN Policies ON Agents.AgentID = Policies.AgentID WHERE Agents.AgentRegion = 'Eastern' GROUP BY Agents.AgentID;
What are the total number of labor rights violations in the 'manufacturing' sector and the 'technology' sector?
CREATE TABLE labor_rights (id INT,sector VARCHAR(20),num_violations INT); INSERT INTO labor_rights (id,sector,num_violations) VALUES (1,'manufacturing',5),(2,'technology',10),(3,'manufacturing',8);
SELECT sector, SUM(num_violations) as total_violations FROM labor_rights WHERE sector IN ('manufacturing', 'technology') GROUP BY sector;
List the names and registration countries of all vessels.
CREATE TABLE Vessels (ID VARCHAR(10),Name VARCHAR(20),Type VARCHAR(20),Registered_Country VARCHAR(20)); INSERT INTO Vessels (ID,Name,Type,Registered_Country) VALUES ('1','Vessel A','Cargo','USA'),('2','Vessel B','Tanker','Canada'),('3','Vessel C','Bulk Carrier','Mexico'),('4','Vessel D','Container','Brazil');
SELECT Vessels.Name, Vessels.Registered_Country FROM Vessels;
What is the average length of stay in minutes for returning visitors from the Asia-Pacific region?
CREATE TABLE Visitors (VisitorID INT,Region VARCHAR(255),IsReturning BOOLEAN,LengthOfStay INT); INSERT INTO Visitors (VisitorID,Region,IsReturning,LengthOfStay) VALUES (1,'Asia-Pacific',true,120); INSERT INTO Visitors (VisitorID,Region,IsReturning,LengthOfStay) VALUES (2,'Europe',false,90); INSERT INTO Visitors (VisitorID,Region,IsReturning,LengthOfStay) VALUES (3,'Asia-Pacific',true,150);
SELECT AVG(V.LengthOfStay) as AverageLengthOfStay FROM Visitors V WHERE V.Region = 'Asia-Pacific' AND V.IsReturning = true;
Add a new workout by 'John Doe' at 'Greenwich' gym
CREATE TABLE gyms (gym_id INT,name TEXT,city TEXT); INSERT INTO gyms (gym_id,name,city) VALUES (1,'Park City','New York'),(2,'Central Park','New York'),(3,'Greenwich','London'); CREATE TABLE members (member_id INT,name TEXT,age INT,gender TEXT); INSERT INTO members (member_id,name,age,gender) VALUES (1,'John Doe',30,'Male'),(2,'Jane Doe',28,'Female'); CREATE TABLE workouts (workout_id INT,member_id INT,gym_id INT,workout_date DATE,calories INT);
INSERT INTO workouts (workout_id, member_id, gym_id, workout_date, calories) VALUES (4, 1, 3, '2022-01-04', 600);
How many members have a membership type of 'Premium'?
CREATE TABLE Members (MemberID INT,Age INT,Gender VARCHAR(10),MembershipType VARCHAR(20)); INSERT INTO Members (MemberID,Age,Gender,MembershipType) VALUES (1,35,'Female','Premium'),(2,45,'Male','Basic'),(3,30,'Female','Premium');
SELECT COUNT(*) FROM Members WHERE MembershipType = 'Premium';
What is the average heart rate for users from the United States, partitioned by gender?
CREATE TABLE user_data (id INT,user_name TEXT,country TEXT,gender TEXT,heart_rate INT); INSERT INTO user_data (id,user_name,country,gender,heart_rate) VALUES (1,'John Doe','USA','Male',75),(2,'Jane Smith','USA','Female',80);
SELECT country, gender, AVG(heart_rate) as avg_heart_rate FROM user_data WHERE country = 'USA' GROUP BY country, gender;
Identify the organizations that have not conducted any algorithmic fairness evaluations.
CREATE TABLE organizations (id INT,name TEXT); INSERT INTO organizations (id,name) VALUES (1,'Org1'),(2,'Org2'),(3,'Org3'); CREATE TABLE evaluations (id INT,organization_id INT,name TEXT); INSERT INTO evaluations (id,organization_id,name) VALUES (1,1,'FairnessEval1'),(2,1,'FairnessEval2'),(3,2,'FairnessEval3');
SELECT organizations.name FROM organizations LEFT JOIN evaluations ON organizations.id = evaluations.organization_id WHERE evaluations.id IS NULL;
List the creative AI applications with their safety scores and total citations from the 'AI_Fairness' schema, sorted by citations in descending order.
CREATE SCHEMA AI_Fairness;CREATE TABLE Creative_AI (app_id INT,safety_score FLOAT,citations INT); INSERT INTO AI_Fairness.Creative_AI (app_id,safety_score,citations) VALUES (1,0.8,10),(2,0.9,20),(3,0.7,15);
SELECT app_id, safety_score, SUM(citations) AS total_citations FROM AI_Fairness.Creative_AI GROUP BY app_id ORDER BY total_citations DESC;
What is the maximum training time for models used in AI safety applications?
CREATE TABLE training_data (model_id INT,model_name VARCHAR(50),application VARCHAR(50),training_time FLOAT);
SELECT MAX(training_time) FROM training_data WHERE application = 'AI safety';
Who are the top 3 contributors to explainable AI research by total word count?
CREATE TABLE if not exists explainable_ai_research (author VARCHAR(255),word_count INT); INSERT INTO explainable_ai_research (author,word_count) VALUES ('Alice',5000),('Bob',3000),('Carol',7000),('Dave',4000),('Eve',6000);
SELECT author, word_count, RANK() OVER (ORDER BY word_count DESC) as rank FROM explainable_ai_research WHERE rank <= 3;
What is the average farm size in meters for small-scale farmers in the 'rural_development' schema?
CREATE TABLE small_scale_farmers (id INT,name TEXT,location TEXT,farm_size_meters INT); INSERT INTO small_scale_farmers (id,name,location,farm_size_meters) VALUES (1,'John Doe','Village A',2000),(2,'Jane Smith','Village B',1500);
SELECT AVG(farm_size_meters) FROM small_scale_farmers WHERE farm_size_meters < 3000;
Which community development initiatives in Sub-Saharan Africa have the highest economic diversification efforts, and what is the average economic diversification score for these initiatives?
CREATE TABLE Initiatives_SSA (InitiativeID INT,Country VARCHAR(20),Type VARCHAR(20),Score FLOAT); INSERT INTO Initiatives_SSA (InitiativeID,Country,Type,Score) VALUES (1,'Kenya','Education',0.8),(2,'Tanzania','Healthcare',0.7),(3,'Nigeria','Agriculture',0.6),(4,'South Africa','Energy',0.9),(5,'Ghana','Housing',0.5),(6,'Uganda','Transportation',0.7);
SELECT AVG(Score) as Avg_Score FROM (SELECT Score FROM Initiatives_SSA WHERE Country IN ('Kenya', 'Tanzania', 'Nigeria', 'South Africa', 'Ghana', 'Uganda') AND Type = 'Economic Diversification' ORDER BY Score DESC LIMIT 3) as Subquery;
Insert a new record into the flight_safety table with the following data: flight_number = 'FL456', safety_rating = 'good', last_inspection_date = '2019-12-15'
CREATE TABLE flight_safety (flight_number VARCHAR(50) PRIMARY KEY,safety_rating VARCHAR(20),last_inspection_date DATE);
INSERT INTO flight_safety (flight_number, safety_rating, last_inspection_date) VALUES ('FL456', 'good', '2019-12-15');
Show the top 2 countries with the highest population, including joined data from the 'countries' table.
CREATE TABLE countries (country VARCHAR(50),population INT); INSERT INTO countries (country,population) VALUES ('China',1439323776),('India',1380004385),('USA',331002651),('Indonesia',273523615),('Pakistan',220892340);
SELECT country, population FROM countries ORDER BY population DESC LIMIT 2;
What is the average altitude reached by SpaceX's Falcon 9 rocket?
CREATE TABLE Max_Altitude (rocket VARCHAR(50),altitude INT); INSERT INTO Max_Altitude (rocket,altitude) VALUES ('Falcon Heavy',20000000),('Falcon 9',15000000);
SELECT altitude FROM Max_Altitude WHERE rocket = 'Falcon 9';
What is the maximum cost of a space exploration mission led by the ESA?
CREATE TABLE SpaceExploration (id INT,agency VARCHAR(255),country VARCHAR(255),cost FLOAT,flights INT,year INT); INSERT INTO SpaceExploration VALUES (1,'NASA','USA',22000000000,500,2010),(2,'ESA','Europe',18000000000,300,2015),(3,'Roscosmos','Russia',15000000000,400,2012),(4,'ISRO','India',7000000000,100,2005),(5,'ESA','Europe',20000000000,200,2020);
SELECT MAX(cost) FROM SpaceExploration WHERE agency = 'ESA';
What is the total number of aircraft manufactured by company 'AeroCorp'?
CREATE TABLE Aircraft (id INT,name VARCHAR(50),manufacturer VARCHAR(50)); INSERT INTO Aircraft (id,name,manufacturer) VALUES (1,'F-16','AeroCorp'),(2,'F-35','AeroCorp'),(3,'A-10','OtherCorp');
SELECT COUNT(*) FROM Aircraft WHERE manufacturer = 'AeroCorp';
What is the number of aquaculture farms in each country in Europe and their total production?
CREATE TABLE Europe_Aquaculture_Farms (id INT,country VARCHAR(255),production INT); INSERT INTO Europe_Aquaculture_Farms (id,country,production) VALUES (1,'Norway',500000),(2,'United Kingdom',400000),(3,'France',300000),(4,'Spain',600000);
SELECT country, COUNT(*), SUM(production) FROM Europe_Aquaculture_Farms GROUP BY country;
List the names and case numbers of cases in 'cases' table that have no billing records in 'billing' table
CREATE TABLE cases (case_id INT,case_number VARCHAR(50),client_name VARCHAR(50),attorney_id INT); CREATE TABLE billing (billing_id INT,attorney_id INT,client_id INT,hours_billed INT,billing_rate DECIMAL(5,2));
SELECT cases.case_number, cases.client_name FROM cases LEFT JOIN billing ON cases.client_id = billing.client_id WHERE billing.client_id IS NULL;
Count the number of chemicals in 'chemical_inventory' table
CREATE TABLE chemical_inventory (id INT,chemical_name VARCHAR(50),safety_stock INT);
SELECT COUNT(chemical_name) FROM chemical_inventory;
Find the top 2 chemical plants with the highest safety violation cost in Japan.
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','Japan',5000),(2,'Plant B','Japan',8000),(3,'Plant C','USA',3000);
SELECT * FROM (SELECT plant_id, plant_name, safety_violation_cost, ROW_NUMBER() OVER (ORDER BY safety_violation_cost DESC) as rn FROM chemical_plants WHERE country = 'Japan') tmp WHERE rn <= 2;
Delete clinical trial records for a specific drug and region where the outcome is 'failed' and the trial was conducted before 2010-01-01.
CREATE TABLE clinical_trial (trial_id INT,drug_name TEXT,trial_region TEXT,trial_outcome TEXT,trial_date DATE); INSERT INTO clinical_trial (trial_id,drug_name,trial_region,trial_outcome,trial_date) VALUES (1,'DrugA','Europe','failed','2009-12-31'),(2,'DrugA','US','successful','2011-05-01'),(3,'DrugB','Europe','successful','2015-08-12');
DELETE FROM clinical_trial WHERE drug_name = 'DrugA' AND trial_region = 'Europe' AND trial_outcome = 'failed' AND trial_date < '2010-01-01';
What was the market share of DrugZ in Q3 2021?
CREATE TABLE sales_data (drug_name VARCHAR(100),sales_quantity INT,quarter INT,year INT); INSERT INTO sales_data (drug_name,sales_quantity,quarter,year) VALUES ('DrugX',1200,2,2021),('DrugY',800,2,2021),('DrugZ',1300,3,2021),('DrugW',950,3,2021);
SELECT (SUM(sales_quantity) FILTER (WHERE drug_name = 'DrugZ') OVER (PARTITION BY year)) * 100.0 / NULLIF(SUM(sales_quantity) OVER (PARTITION BY year), 0) AS market_share FROM sales_data WHERE year = 2021 AND quarter = 3;
How many infectious disease cases were reported in Africa?
CREATE TABLE infectious_disease (id INT,disease VARCHAR(50),cases INT,year INT,location VARCHAR(50)); INSERT INTO infectious_disease (id,disease,cases,year,location) VALUES (1,'Malaria',500,2020,'Africa'); INSERT INTO infectious_disease (id,disease,cases,year,location) VALUES (2,'Tuberculosis',300,2020,'Asia');
SELECT SUM(cases) FROM infectious_disease WHERE location = 'Africa';
Number of infectious disease cases in each district of Delhi, ordered by the highest number of cases.
CREATE TABLE infectious_disease_delhi (district VARCHAR(20),cases INT); INSERT INTO infectious_disease_delhi (district,cases) VALUES ('East Delhi',100),('South Delhi',150),('New Delhi',200),('West Delhi',50);
SELECT district, cases, RANK() OVER (ORDER BY cases DESC) AS rank FROM infectious_disease_delhi;
What are the total number of patients and providers for each clinic location?
CREATE TABLE clinics (clinic_id INT,clinic_name VARCHAR(50),city VARCHAR(50)); CREATE TABLE patients (patient_id INT,clinic_id INT,patient_name VARCHAR(50)); CREATE TABLE providers (provider_id INT,clinic_id INT,provider_name VARCHAR(50));
SELECT clinics.clinic_name, COUNT(DISTINCT patients.patient_id) AS patient_count, COUNT(DISTINCT providers.provider_id) AS provider_count FROM clinics LEFT JOIN patients ON clinics.clinic_id = patients.clinic_id LEFT JOIN providers ON clinics.clinic_id = providers.clinic_id GROUP BY clinics.clinic_name;
Find the average funding amount per startup in the "west_coast" region
CREATE TABLE companies (id INT,name TEXT,region TEXT,funding FLOAT); INSERT INTO companies (id,name,region,funding) VALUES (1,'Startup A','west_coast',5000000),(2,'Startup B','east_coast',3000000),(3,'Startup C','west_coast',7000000);
SELECT AVG(funding) FROM companies WHERE region = 'west_coast';
List the number of BIPOC-led startups in the green technology sector with Series B funding or higher
CREATE TABLE founders (id INT,company_id INT,ethnicity VARCHAR(255)); CREATE TABLE companies (id INT,industry VARCHAR(255),funding_round VARCHAR(255)); INSERT INTO founders SELECT 1,1,'BIPOC'; INSERT INTO founders SELECT 2,2,'White'; INSERT INTO founders SELECT 3,3,'BIPOC'; INSERT INTO companies (id,industry,funding_round) SELECT 2,'Finance','Series A'; INSERT INTO companies (id,industry,funding_round) SELECT 3,'Green Technology','Series B'; INSERT INTO companies (id,industry,funding_round) SELECT 4,'Retail','Series C';
SELECT COUNT(DISTINCT companies.id) FROM founders JOIN companies ON founders.company_id = companies.id WHERE companies.industry = 'Green Technology' AND founders.ethnicity = 'BIPOC' AND companies.funding_round >= 'Series B';
What is the number of female founders each year?
CREATE TABLE founders (founder_id INT,company_id INT,gender VARCHAR(255)); CREATE TABLE companies (company_id INT,founding_year INT); INSERT INTO founders (founder_id,company_id,gender) VALUES (1,1,'Female'),(2,2,'Male'),(3,3,'Female'),(4,4,'Non-binary'); INSERT INTO companies (company_id,founding_year) VALUES (1,2018),(2,2017),(3,2019),(4,2018);
SELECT founding_year, COUNT(f.founder_id) as num_female_founders FROM founders f JOIN companies c ON f.company_id = c.company_id WHERE f.gender = 'Female' GROUP BY founding_year;
How many startups were founded in 2018 by people with disabilities?
CREATE TABLE startups (id INT,name TEXT,founding_year INT,founder_ability TEXT);
SELECT COUNT(*) FROM startups WHERE founding_year = 2018 AND founder_ability IS NOT NULL AND founder_ability <> 'No disability';
Show conservation efforts for endangered marine species.
CREATE TABLE marine_species (id INT,conservation_status VARCHAR(255)); INSERT INTO marine_species (id,conservation_status) VALUES (1,'Endangered'),(2,'Least Concern'); CREATE TABLE conservation_efforts (id INT,species_id INT,description VARCHAR(255)); INSERT INTO conservation_efforts (id,species_id,description) VALUES (1,1,'Habitat protection'),(2,2,'Research and monitoring');
SELECT marine_species.conservation_status, conservation_efforts.description FROM marine_species INNER JOIN conservation_efforts ON marine_species.id = conservation_efforts.species_id WHERE marine_species.conservation_status = 'Endangered';
How many wildlife species are present in 'Caribbean Forests'?
CREATE TABLE CaribbeanForests (region VARCHAR(20),species_count INT); INSERT INTO CaribbeanForests (region,species_count) VALUES ('Caribbean Forests',901);
SELECT species_count FROM CaribbeanForests WHERE region = 'Caribbean Forests';
List the temperate rainforests with an area greater than 2000 square kilometers and timber volume above average
CREATE TABLE rainforests_area_volume (id INT,type VARCHAR(20),area FLOAT,volume FLOAT); INSERT INTO rainforests_area_volume (id,type,area,volume) VALUES (1,'Temperate',2500,2500000);
SELECT type FROM rainforests_area_volume WHERE area > 2000 AND volume > (SELECT AVG(volume) FROM rainforests_area_volume WHERE type = 'Temperate');
Insert new records into the 'veteran_employment' table for 'company_name' 'TechCo' with 'job_title' 'Software Engineer', 'employment_status' 'full-time' and 'start_date' '2022-05-01'
CREATE TABLE veteran_employment (company_name VARCHAR(255),job_title VARCHAR(255),employment_status VARCHAR(255),start_date DATE);
INSERT INTO veteran_employment (company_name, job_title, employment_status, start_date) VALUES ('TechCo', 'Software Engineer', 'full-time', '2022-05-01');
What is the total number of manufacturing plants in Mexico that have received workforce development grants?
CREATE TABLE plants (id INT,name VARCHAR(50),country VARCHAR(50),workforce_development INT);
SELECT COUNT(*) FROM plants WHERE country = 'Mexico' AND workforce_development = 1;
What is the most common age range for patients diagnosed with heart disease in rural Australia, and how many nurses serve those patients?
CREATE TABLE patients (patient_id INT,age INT,diagnosis VARCHAR(255),location VARCHAR(255)); INSERT INTO patients (patient_id,age,diagnosis,location) VALUES (4,58,'heart disease','rural Australia'); INSERT INTO patients (patient_id,age,diagnosis,location) VALUES (5,62,'heart disease','rural Australia'); CREATE TABLE nurses (nurse_id INT,specialty VARCHAR(255),location VARCHAR(255)); INSERT INTO nurses (nurse_id,specialty,location) VALUES (40,'cardiac nurse','rural Australia'); INSERT INTO nurses (nurse_id,specialty,location) VALUES (41,'cardiac nurse','rural Australia');
SELECT FLOOR(AVG(age)) AS common_age_range, COUNT(nurses.nurse_id) AS nurses_count FROM patients INNER JOIN nurses ON patients.location = nurses.location WHERE patients.diagnosis = 'heart disease' AND patients.location LIKE 'rural% Australia' GROUP BY patients.location;
What is the average ESG rating for companies in the financial sector?
CREATE TABLE companies (id INT,name VARCHAR(255),sector VARCHAR(255),ESG_rating FLOAT); INSERT INTO companies (id,name,sector,ESG_rating) VALUES (1,'JPMorgan Chase','Financial',7.2),(2,'Visa','Financial',7.8),(3,'Starbucks','Consumer Discretionary',6.9);
SELECT AVG(ESG_rating) FROM companies WHERE sector = 'Financial';
What is the code name and launch date of the most recent military satellite in the 'satellite_data' table?
CREATE TABLE satellite_data (id INT PRIMARY KEY,sat_name VARCHAR(100),launch_date DATE,country VARCHAR(50),purpose VARCHAR(50)); INSERT INTO satellite_data (id,sat_name,launch_date,country,purpose) VALUES (1,'KH-11','2021-04-01','USA','Reconnaissance'),(2,'Yaogan-34','2020-10-10','China','Remote Sensing');
SELECT sat_name, launch_date FROM satellite_data ORDER BY launch_date DESC LIMIT 1;
Identify the number of unique artists who have released music in the Pop and Hip Hop genres.
CREATE TABLE ArtistGenre2 (ArtistID INT,Genre VARCHAR(20)); INSERT INTO ArtistGenre2 (ArtistID,Genre) VALUES (1,'Pop'),(2,'Rock'),(3,'Jazz'),(4,'Pop'),(4,'Hip Hop'),(5,'Pop'),(6,'Hip Hop');
SELECT COUNT(DISTINCT ArtistID) FROM (SELECT ArtistID FROM ArtistGenre2 WHERE Genre = 'Pop' INTERSECT SELECT ArtistID FROM ArtistGenre2 WHERE Genre = 'Hip Hop') T;
Identify teachers who require professional development in 'Computer Science', ordered by their hire date.
CREATE TABLE teachers (teacher_id INT,name VARCHAR(255),hire_date DATE,subject VARCHAR(255)); INSERT INTO teachers (teacher_id,name,hire_date,subject) VALUES (1,'John Doe','2010-01-01','Mathematics'),(2,'Jane Smith','2015-01-01','Computer Science'),(3,'Mike Johnson','2005-01-01','English');
SELECT teacher_id, name, hire_date FROM teachers WHERE subject = 'Computer Science' ORDER BY hire_date;
How many employees from each region have completed the 'Diversity and Inclusion' course in the 'training' table?
CREATE TABLE employees (id INT,name VARCHAR(255),country VARCHAR(255),region VARCHAR(255)); CREATE TABLE training (id INT,employee_id INT,course VARCHAR(255)); INSERT INTO employees (id,name,country,region) VALUES (1,'John Doe','USA','North America'); INSERT INTO employees (id,name,country,region) VALUES (2,'Jane Smith','Canada','North America'); INSERT INTO employees (id,name,country,region) VALUES (3,'Alice Johnson','USA','North America'); INSERT INTO employees (id,name,country,region) VALUES (4,'Kai Rogers','UK','Europe'); INSERT INTO training (id,employee_id,course) VALUES (1,1,'SQL'); INSERT INTO training (id,employee_id,course) VALUES (2,1,'Python'); INSERT INTO training (id,employee_id,course) VALUES (3,3,'SQL'); INSERT INTO training (id,employee_id,course) VALUES (4,4,'Diversity and Inclusion');
SELECT e.region, COUNT(t.id) FROM employees e JOIN training t ON e.id = t.employee_id WHERE t.course = 'Diversity and Inclusion' GROUP BY e.region;
Update the 'HR' department's training program end date to '2023-06-30'
CREATE TABLE trainings (id SERIAL PRIMARY KEY,department VARCHAR(50),title VARCHAR(100),description TEXT,start_date DATE,end_date DATE); INSERT INTO trainings (department,title,description,start_date,end_date) VALUES ('HR','Diversity & Inclusion','Promoting inclusivity in the workplace','2023-01-01','2023-05-31');
UPDATE trainings SET end_date = '2023-06-30' WHERE department = 'HR';
What is the number of job applicants by source for each department in the past year, including sources with no applicants?
CREATE TABLE JobApplications (ApplicationDate DATE,Department VARCHAR(20),Source VARCHAR(20)); INSERT INTO JobApplications (ApplicationDate,Department,Source) VALUES ('2022-01-01','HR','LinkedIn'),('2022-02-01','HR','Indeed'),('2022-03-01','IT','LinkedIn'),('2022-01-01','Finance','Glassdoor');
SELECT Department, Source, COUNT(*) as Num_Applicants FROM JobApplications WHERE ApplicationDate >= DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR) GROUP BY Department, Source ORDER BY Department, Num_Applicants ASC;
Insert records for a new team, 'Seattle Kraken'
CREATE TABLE players (player_id INT,name VARCHAR(100),position VARCHAR(50),team_id INT); CREATE TABLE teams (team_id INT,name VARCHAR(100),city VARCHAR(100)); INSERT INTO players (player_id,name,position,team_id) VALUES (1,'John Doe','Forward',1),(2,'Jane Smith','Goalie',2); INSERT INTO teams (team_id,name,city) VALUES (1,'Boston Bruins','Boston'),(2,'New York Rangers','New York');
INSERT INTO teams (team_id, name, city) VALUES (3, 'Seattle Kraken', 'Seattle');
What is the average number of strikeouts per game for each baseball team?
CREATE TABLE baseball_teams (team_name TEXT,strikeouts INT); INSERT INTO baseball_teams (team_name,strikeouts) VALUES ('Yankees',1200),('Red Sox',1100),('Dodgers',1300);
SELECT team_name, AVG(strikeouts) FROM baseball_teams GROUP BY team_name;
What is the maximum number of assists made by a player in the HockeyMatches and HockeyPlayerAssists tables, for players who have played more than 50 games?
CREATE TABLE HockeyMatches (MatchID INT,HomeTeam VARCHAR(50),AwayTeam VARCHAR(50)); CREATE TABLE HockeyPlayerAssists (PlayerID INT,MatchID INT,Assists INT);
SELECT MAX(Assists) FROM HockeyPlayerAssists INNER JOIN (SELECT PlayerID, COUNT(*) as GamesPlayed FROM HockeyPlayerAssists GROUP BY PlayerID HAVING COUNT(*) > 50) as Subquery ON HockeyPlayerAssists.PlayerID = Subquery.PlayerID;
What is the maximum number of goals scored by any player in the ice hockey team 'Montreal Canadiens' in a single match?
CREATE TABLE goals (player_name TEXT,team TEXT,goals_scored INTEGER); INSERT INTO goals (player_name,team,goals_scored) VALUES ('Alice Johnson','Montreal Canadiens',3); INSERT INTO goals (player_name,team,goals_scored) VALUES ('Bob Brown','Montreal Canadiens',5);
SELECT MAX(goals_scored) FROM goals WHERE team = 'Montreal Canadiens';
Delete all records in the "digital_divide_stats" table where the "country" is 'United States'
CREATE TABLE digital_divide_stats (id INT PRIMARY KEY,country VARCHAR(255),year INT,internet_users INT,total_population INT);
WITH deleted_data AS (DELETE FROM digital_divide_stats WHERE country = 'United States' RETURNING *) SELECT * FROM deleted_data;
What is the number of wheelchair accessible vehicles per fleet?
CREATE TABLE Fleets (FleetID INT,FleetName VARCHAR(50),VehicleType VARCHAR(50),Capacity INT); INSERT INTO Fleets (FleetID,FleetName,VehicleType,Capacity) VALUES (1,'FleetA','Bus',50),(2,'FleetB','Train',100),(3,'FleetC','Wheelchair Bus',20),(4,'FleetD','Bike Rack Train',80);
SELECT FleetName, SUM(CASE WHEN VehicleType LIKE '%Wheelchair%' THEN Capacity ELSE 0 END) AS WheelchairAccessibleVehicles FROM Fleets GROUP BY FleetName;
How many ethical fashion brands are headquartered in each continent?
CREATE TABLE fashion_brands (id INT,continent VARCHAR(50),ethical_practices BOOLEAN); INSERT INTO fashion_brands (id,continent,ethical_practices) VALUES (1,'Africa',true),(2,'Asia',false),(3,'Europe',true);
SELECT continent, COUNT(*) FROM fashion_brands WHERE ethical_practices = true GROUP BY continent;
What is the total carbon footprint of recycled paper packaging?
CREATE TABLE materials (id INT,name VARCHAR(255),type VARCHAR(255),carbon_footprint DECIMAL(10,2),PRIMARY KEY(id)); INSERT INTO materials (id,name,type,carbon_footprint) VALUES (15,'Recycled Paper','Packaging',2.50); CREATE TABLE products (id INT,name VARCHAR(255),category VARCHAR(255),material_id INT,PRIMARY KEY(id),FOREIGN KEY (material_id) REFERENCES materials(id)); INSERT INTO products (id,name,category,material_id) VALUES (16,'Recycled Paper Box','Packaging',15);
SELECT SUM(carbon_footprint) FROM materials INNER JOIN products ON materials.id = products.material_id WHERE products.name = 'Recycled Paper Box';
Which financial wellbeing programs in Africa were launched before 2015 and had a budget greater than $500,000?
CREATE TABLE FinancialWellbeing (id INT,program_name VARCHAR(50),location VARCHAR(50),launch_date DATE,budget DECIMAL(10,2));
SELECT program_name, budget FROM FinancialWellbeing WHERE location LIKE '%Africa%' AND launch_date < '2015-01-01' AND budget > 500000;
What is the total number of hours volunteered by each volunteer in the last month?
CREATE TABLE volunteer_hours (hour_id INT,volunteer_id INT,hours_volunteered DECIMAL(10,2),volunteer_date DATE);
SELECT volunteer_id, SUM(hours_volunteered) FROM volunteer_hours WHERE volunteer_date >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH) GROUP BY volunteer_id;
Identify the suppliers with the highest and lowest sustainability ratings in the supplier_ratings table.
CREATE TABLE supplier_ratings (supplier_id INT,sustainability_rating INT); INSERT INTO supplier_ratings (supplier_id,sustainability_rating) VALUES (100,95),(101,60),(102,90);
SELECT supplier_id, sustainability_rating FROM (SELECT supplier_id, sustainability_rating, RANK() OVER (ORDER BY sustainability_rating DESC) AS rank, RANK() OVER (ORDER BY sustainability_rating ASC) AS reverse_rank FROM supplier_ratings) WHERE rank = 1 OR reverse_rank = 1;
What are the top 3 cuisine types with the lowest calorie content?
CREATE TABLE cuisine (id INT,type VARCHAR(50),calories INT); INSERT INTO cuisine (id,type,calories) VALUES (1,'Italian',500),(2,'Mexican',600),(3,'Japanese',400),(4,'Chinese',450),(5,'Indian',550),(6,'Thai',480);
SELECT type, calories, RANK() OVER (ORDER BY calories ASC) as rank FROM cuisine WHERE rank <= 3;
What is the total number of meals in the meals table with a calorie count above 500?
CREATE TABLE meals (meal_id INT,meal_name VARCHAR(50),calories INT); INSERT INTO meals (meal_id,meal_name,calories) VALUES (1,'Quinoa Salad',350),(2,'Lentil Soup',280),(3,'Chickpea Curry',420),(4,'Tofu Stir Fry',380),(5,'Grilled Chicken Salad',450),(6,'Beef Tacos',520),(7,'Vegetable Stir Fry',360),(8,'Chicken Caesar Salad',390),(9,'Prawn Curry',410),(10,'Vegetable Curry',370),(11,'Fish and Chips',600),(12,'Chocolate Cake',500);
SELECT COUNT(*) FROM meals WHERE calories > 500;
What is the total revenue generated from domestic shipments in the Northeast region for the year 2021?
CREATE TABLE shipments (id INT,region VARCHAR(20),revenue FLOAT); INSERT INTO shipments (id,region,revenue) VALUES (1,'Northeast',5000),(2,'Southeast',7000),(3,'Northeast',8000); CREATE TABLE regions (id INT,name VARCHAR(20)); INSERT INTO regions (id,name) VALUES (1,'Northeast'),(2,'Southeast');
SELECT SUM(s.revenue) FROM shipments s JOIN regions r ON s.region = r.name WHERE r.name = 'Northeast' AND YEAR(s.id) = 2021 AND s.region LIKE 'Northeast%';
Which are the top 5 heaviest items in the inventory?
CREATE TABLE Inventory(id INT,item_name VARCHAR(50),weight INT); INSERT INTO Inventory(id,item_name,weight) VALUES (1,'Box A',200),(2,'Box B',150),(3,'Box C',300);
SELECT item_name, weight, ROW_NUMBER() OVER (ORDER BY weight DESC) as rank FROM Inventory WHERE rank <= 5;
What is the total funding received by startups in the 'Genetic Research' sector?
CREATE SCHEMA if not exists biotech;CREATE TABLE if not exists biotech.startups (id INT,name VARCHAR(50),sector VARCHAR(50),total_funding DECIMAL(10,2)); INSERT INTO biotech.startups (id,name,sector,total_funding) VALUES (1,'StartupA','Genetic Research',5000000.00),(2,'StartupB','Biosensor Technology',3000000.00);
SELECT SUM(total_funding) FROM biotech.startups WHERE sector = 'Genetic Research';
What is the total budget allocated to agencies in the 'Transportation' sector for the fiscal year 2021?
CREATE TABLE Agency (id INT,Name VARCHAR(50),Budget INT,Sector VARCHAR(50)); INSERT INTO Agency (id,Name,Budget,Sector) VALUES (1,'DOT',7000000,'Transportation'); INSERT INTO Agency (id,Name,Budget,Sector) VALUES (2,'FRA',4000000,'Transportation');
SELECT SUM(Budget) FROM Agency WHERE Sector = 'Transportation' AND FiscalYear = 2021;
Identify underrepresented communities with no healthcare providers in LA and MS.
CREATE TABLE healthcare_providers (provider_id INT,name TEXT,state TEXT); INSERT INTO healthcare_providers (provider_id,name,state) VALUES (1,'Dr. Keisha Brown','LA'); CREATE TABLE underrepresented_communities (community TEXT,state TEXT);
SELECT u.community, u.state FROM underrepresented_communities u LEFT JOIN healthcare_providers h ON u.state = h.state WHERE h.provider_id IS NULL AND u.state IN ('LA', 'MS');
What is the total number of mental health parity violations by month and year?
CREATE TABLE mental_health_parity_reports (report_id INT,violation_date DATE); INSERT INTO mental_health_parity_reports (report_id,violation_date) VALUES (1,'2022-01-01'),(2,'2022-02-15'),(3,'2022-03-05'),(4,'2022-04-20'),(5,'2021-06-12'),(6,'2021-07-28');
SELECT EXTRACT(MONTH FROM violation_date) AS month, EXTRACT(YEAR FROM violation_date) AS year, COUNT(*) FROM mental_health_parity_reports GROUP BY month, year;
Find the top 3 countries with the most virtual tourism sessions in Q3 2023, excluding the 'Europe' region.
CREATE TABLE virtual_tourism (id INT,country VARCHAR(50),num_sessions INT,session_date DATE,region VARCHAR(50)); INSERT INTO virtual_tourism (id,country,num_sessions,session_date,region) VALUES (1,'USA',2500,'2023-01-01','North America'),(2,'Canada',1800,'2023-01-02','North America');
SELECT country, SUM(num_sessions) as total_sessions FROM virtual_tourism WHERE session_date BETWEEN '2023-07-01' AND '2023-09-30' AND region != 'Europe' GROUP BY country ORDER BY total_sessions DESC LIMIT 3;
How many patients have participated in group therapy?
CREATE TABLE treatments (treatment_id INT,type VARCHAR(20),participants INT); INSERT INTO treatments (treatment_id,type,participants) VALUES (1,'Group Therapy',12); INSERT INTO treatments (treatment_id,type,participants) VALUES (2,'Individual Therapy',5); INSERT INTO treatments (treatment_id,type,participants) VALUES (3,'Family Therapy',3);
SELECT SUM(participants) FROM treatments WHERE type = 'Group Therapy';
What is the total number of mental health campaigns launched in each country?
CREATE TABLE campaigns (campaign_id INT,country VARCHAR(50),launch_date DATE); INSERT INTO campaigns (campaign_id,country,launch_date) VALUES (1,'United States','2022-01-01'),(2,'Canada','2022-02-01'),(3,'Mexico','2022-03-01');
SELECT country, COUNT(*) as campaign_count FROM campaigns GROUP BY country;
Add a new column 'material_origin' to the 'infrastructure_materials' table with a default value of 'Domestic'
CREATE TABLE infrastructure_materials (material_id INT,material_name TEXT,material_durability TEXT,material_cost TEXT);
ALTER TABLE infrastructure_materials ADD material_origin TEXT DEFAULT 'Domestic';
Get the average resilience score for each project type in the Resilience_Scores view
CREATE VIEW Resilience_Scores AS SELECT project_id,project_name,project_type,resilience_score FROM Infrastructure_Data WHERE year >= 2010; CREATE TABLE Project_Types (project_type VARCHAR(255),type_description VARCHAR(255));
SELECT project_type, AVG(resilience_score) FROM Resilience_Scores JOIN Project_Types ON Resilience_Scores.project_type = Project_Types.project_type GROUP BY project_type;
Update the "population" column for 'Canada' in the "countries" table
CREATE TABLE countries (id INT PRIMARY KEY,name TEXT,continent TEXT,area FLOAT,population INT); INSERT INTO countries (id,name,continent,area,population) VALUES (1,'Canada','North America',9984670.0,38005238);
UPDATE countries SET population = 38050000 WHERE name = 'Canada';
What is the average age of tourists visiting Kyoto from the United States?
CREATE TABLE if not exists destinations (destination_id INT,name TEXT,country TEXT); INSERT INTO destinations (destination_id,name,country) VALUES (1,'Kyoto','Japan'); CREATE TABLE if not exists visitors (visitor_id INT,age INT,destination_id INT,nationality TEXT); INSERT INTO visitors (visitor_id,age,destination_id,nationality) VALUES (1,25,1,'USA'),(2,30,1,'USA'),(3,45,1,'Canada');
SELECT AVG(visitors.age) FROM visitors JOIN destinations ON visitors.destination_id = destinations.destination_id WHERE visitors.nationality = 'USA' AND destinations.name = 'Kyoto';
What is the total number of visitors to Canada in 2020 who engaged in sustainable tourism activities?
CREATE TABLE visitors (id INT,year INT,country TEXT,engaged_in_sustainable_tourism BOOLEAN); INSERT INTO visitors (id,year,country,engaged_in_sustainable_tourism) VALUES (1,2020,'Canada',true),(2,2019,'Canada',false);
SELECT SUM(engaged_in_sustainable_tourism) FROM visitors WHERE year = 2020 AND country = 'Canada';
What was the average CO2 emission per international tourist by continent in 2022?
CREATE TABLE international_tourists (id INT,continent VARCHAR(50),country VARCHAR(50),visitors INT,co2_emission INT,visit_date DATE); INSERT INTO international_tourists (id,continent,country,visitors,co2_emission,visit_date) VALUES (1,'Europe','France',3000,1500,'2022-01-01');
SELECT AVG(co2_emission) as avg_co2, continent FROM international_tourists WHERE visit_date = '2022-01-01' GROUP BY continent;
List the total number of cases for each Ethnicity in the DiversityInJustice table.
CREATE TABLE DiversityInJustice (JusticeID INT,Ethnicity VARCHAR(30)); CREATE TABLE JusticeCases (CaseID INT,JusticeID INT,Date DATE); INSERT INTO DiversityInJustice (JusticeID,Ethnicity) VALUES (1,'African American'),(2,'Hispanic'),(3,'Asian'),(4,'Caucasian'); INSERT INTO JusticeCases (CaseID,JusticeID,Date) VALUES (1,1,'2021-09-01'),(2,1,'2021-07-20'),(3,2,'2021-08-12'),(4,3,'2021-08-15'),(5,3,'2021-09-01'),(6,4,'2021-09-10');
SELECT Ethnicity, COUNT(*) as TotalCases FROM JusticeCases JOIN DiversityInJustice ON JusticeCases.JusticeID = DiversityInJustice.JusticeID GROUP BY Ethnicity;
What is the average age of volunteers who have participated in restorative justice programs?
CREATE TABLE restorative_justice_programs (program_id INT,volunteer_age INT); INSERT INTO restorative_justice_programs (program_id,volunteer_age) VALUES (1,25),(2,30),(3,22);
SELECT AVG(volunteer_age) FROM restorative_justice_programs;
What is the total number of legal aid hours provided, by type of service, location, and ethnicity?
CREATE TABLE legal_aid_hours_ethnicity (hour_id INT,hour_type VARCHAR(255),location VARCHAR(255),ethnicity VARCHAR(255),hours DECIMAL(10,2)); INSERT INTO legal_aid_hours_ethnicity (hour_id,hour_type,location,ethnicity,hours) VALUES (1,'Consultation','California','Hispanic',5.5),(2,'Representation','New York','African American',8.0);
SELECT hour_type, location, ethnicity, SUM(hours) as total_hours FROM legal_aid_hours_ethnicity GROUP BY hour_type, location, ethnicity;
Find the total number of vessels in the South China sea by category
CREATE TABLE scs_vessels (vessel_id INT,vessel_name VARCHAR(255),category VARCHAR(255),longitude DECIMAL(9,6),latitude DECIMAL(9,6)); CREATE VIEW scs_vessels_view AS SELECT * FROM scs_vessels WHERE longitude BETWEEN 100 AND 125 AND latitude BETWEEN 1 AND 22;
SELECT category, COUNT(*) FROM scs_vessels_view GROUP BY category;
What is the average number of marine species found in the Mediterranean Sea?
CREATE TABLE mediterranean_sea (id INT,location TEXT,species_count INT); INSERT INTO mediterranean_sea (id,location,species_count) VALUES (1,'Crete',500);
SELECT AVG(species_count) FROM mediterranean_sea WHERE location = 'Crete';
What is the total revenue for vegetarian and non-vegetarian items?
CREATE TABLE MenuItems (MenuItemID INT,MenuItemName VARCHAR(255),Category VARCHAR(255),Price DECIMAL(5,2),SupplierID INT); INSERT INTO MenuItems (MenuItemID,MenuItemName,Category,Price,SupplierID) VALUES (5,'Falafel Wrap','Vegetarian',7.99,4); INSERT INTO MenuItems (MenuItemID,MenuItemName,Category,Price,SupplierID) VALUES (6,'Pork Tacos','Meat',11.49,5);
SELECT CASE WHEN Category = 'Vegetarian' THEN 'Vegetarian' ELSE 'Non-Vegetarian' END AS Category, SUM(Price) as Revenue FROM MenuItems GROUP BY Category
Create a view named 'risk_assessment_summary' with columns 'region', 'total_risk_score', 'average_risk_score
CREATE VIEW risk_assessment_summary AS SELECT region,SUM(risk_score) AS total_risk_score,AVG(risk_score) AS average_risk_score FROM risk_assessment GROUP BY region;
CREATE VIEW risk_assessment_summary AS SELECT region, SUM(risk_score) AS total_risk_score, AVG(risk_score) AS average_risk_score FROM risk_assessment GROUP BY region;
Insert a new defense project "Project Z" with status "Not Started" and planned start date 2023-02-15.
CREATE TABLE defense_projects (id INT PRIMARY KEY AUTO_INCREMENT,project_name VARCHAR(255),status VARCHAR(255),planned_start_date DATE);
INSERT INTO defense_projects (project_name, status, planned_start_date) VALUES ('Project Z', 'Not Started', '2023-02-15');
What are the total amounts of copper and silver extracted by each company operating in North America?
CREATE TABLE company (id INT,name VARCHAR(255),country VARCHAR(255));CREATE TABLE copper_extraction (company_id INT,amount INT);CREATE TABLE silver_extraction (company_id INT,amount INT);
SELECT c.name, SUM(ce.amount) as total_copper, SUM(se.amount) as total_silver FROM company c LEFT JOIN copper_extraction ce ON c.id = ce.company_id LEFT JOIN silver_extraction se ON c.id = se.company_id WHERE c.country LIKE '%North America%' GROUP BY c.name;
Show the total CO2 emissions for each state, grouped by state.
CREATE TABLE coal_mines (id INT,name VARCHAR(50),location VARCHAR(50),size INT,co2_emissions INT,state VARCHAR(20)); INSERT INTO coal_mines VALUES (1,'Coal Mine 1','West Virginia',450,25000,'West Virginia'); INSERT INTO coal_mines VALUES (2,'Coal Mine 2','Wyoming',600,30000,'Wyoming'); INSERT INTO coal_mines VALUES (3,'Coal Mine 3','Kentucky',200,15000,'Kentucky');
SELECT state, SUM(co2_emissions) FROM coal_mines GROUP BY state;
What is the total number of employees working in mining operations in the European region?
CREATE TABLE Employees (EmployeeID INT,Name VARCHAR(50),OperationID INT,Department VARCHAR(50)); INSERT INTO Employees (EmployeeID,Name,OperationID,Department) VALUES (1,'John Doe',1,'Mining'); INSERT INTO Employees (EmployeeID,Name,OperationID,Department) VALUES (2,'Jane Smith',2,'Mining');
SELECT COUNT(DISTINCT Employees.EmployeeID) FROM Employees INNER JOIN MiningOperations ON Employees.OperationID = MiningOperations.OperationID WHERE Employees.Department = 'Mining' AND MiningOperations.Country IN (SELECT Country FROM Countries WHERE Region = 'Europe');
What is the total amount donated on Giving Tuesday by donors in the Health industry?
CREATE TABLE donations(id INT,donor_name TEXT,donation_amount FLOAT,donation_date DATE,industry TEXT); INSERT INTO donations(id,donor_name,donation_amount,donation_date,industry) VALUES (1,'James Lee',50,'2022-11-29','Technology'),(2,'Grace Kim',100,'2022-12-01','Finance'),(3,'Anthony Nguyen',25,'2022-11-29','Health');
SELECT SUM(donation_amount) FROM donations WHERE donation_date = '2022-11-29' AND industry = 'Health';
What was the average donation amount in each city in H2 2021?
CREATE TABLE Donations (DonationID int,City varchar(50),AmountDonated numeric(10,2),DonationDate date); INSERT INTO Donations (DonationID,City,AmountDonated,DonationDate) VALUES (1,'Los Angeles',100.00,'2021-07-01'),(2,'Houston',150.00,'2021-12-31');
SELECT City, AVG(AmountDonated) as AvgDonation FROM Donations WHERE DonationDate BETWEEN '2021-07-01' AND '2021-12-31' GROUP BY City;
Find the average depth of all underwater volcanoes in the Atlantic Ocean.
CREATE TABLE underwater_volcanoes (id INT,name VARCHAR(50),depth FLOAT,ocean VARCHAR(20)); INSERT INTO underwater_volcanoes (id,name,depth,ocean) VALUES (1,'Lost City',800,'Atlantic'); INSERT INTO underwater_volcanoes (id,name,depth,ocean) VALUES (2,'Eyjafjallajokull',1650,'Atlantic');
SELECT AVG(depth) FROM underwater_volcanoes WHERE ocean = 'Atlantic';
Identify the number of whale sightings per month for the Pacific Ocean.
CREATE TABLE WHALE_SIGHTINGS (SIGHTING_DATE DATE,LOCATION VARCHAR(20)); INSERT INTO WHALE_SIGHTINGS (SIGHTING_DATE,LOCATION) VALUES ('2022-01-01','Pacific Ocean'),('2022-01-02','Pacific Ocean'),('2022-02-01','Pacific Ocean'),('2022-03-01','Pacific Ocean'),('2022-03-02','Pacific Ocean');
SELECT TO_CHAR(SIGHTING_DATE, 'YYYY-MM'), COUNT(*) FROM WHALE_SIGHTINGS WHERE LOCATION = 'Pacific Ocean' GROUP BY TO_CHAR(SIGHTING_DATE, 'YYYY-MM') ORDER BY TO_CHAR(SIGHTING_DATE, 'YYYY-MM');
Insert a new record in the table "maritime_safety" with values 1, 'Arctic', 3, '2022-03-03'
CREATE TABLE maritime_safety (id INT,region VARCHAR(50),incidents INT,date DATE);
INSERT INTO maritime_safety (id, region, incidents, date) VALUES (1, 'Arctic', 3, '2022-03-03');
What is the maximum number of marine species observed in a single deep-sea expedition?
CREATE TABLE deep_sea_expeditions (expedition_id INTEGER,location TEXT,species_count INTEGER);
SELECT MAX(species_count) FROM deep_sea_expeditions;
What is the minimum game score for players who have played the "QuantumDefenders" game more than 5 times?
CREATE TABLE QuantumDefenders (PlayerID INT,GameScore INT,PlayCount INT); INSERT INTO QuantumDefenders (PlayerID,GameScore,PlayCount) VALUES (1,8500,7),(2,9000,6),(3,7000,8),(4,9500,3),(5,8000,9);
SELECT MIN(GameScore) FROM QuantumDefenders WHERE PlayCount > 5;
Show the change in average soil pH levels for each farm from 2018 to 2019.
CREATE TABLE soil_samples (id INT,sample_id INT,farm_id INT,sample_date DATE,ph VARCHAR(20),n VARCHAR(20),p VARCHAR(20),k VARCHAR(20)); INSERT INTO soil_samples (id,sample_id,farm_id,sample_date,ph,n,p,k) VALUES (1,1,1,'2018-04-01','6.0','High','Medium','Low'); INSERT INTO soil_samples (id,sample_id,farm_id,sample_date,ph,n,p,k) VALUES (2,2,1,'2019-04-02','6.5','Medium','Medium','Medium'); INSERT INTO soil_samples (id,sample_id,farm_id,sample_date,ph,n,p,k) VALUES (3,3,2,'2018-05-01','5.5','Low','High','Low');
SELECT farm_id, AVG(CAST(ph AS FLOAT)) - LAG(AVG(CAST(ph AS FLOAT)), 1, 0) OVER (PARTITION BY farm_id ORDER BY YEAR(sample_date)) AS ph_change FROM soil_samples GROUP BY farm_id, YEAR(sample_date) HAVING YEAR(sample_date) IN (2018, 2019);
Delete records of neodymium magnet production from the table 'production' where the year is 2020
CREATE TABLE production (id INT,element VARCHAR(10),year INT,quantity INT); INSERT INTO production (id,element,year,quantity) VALUES (1,'neodymium',2018,500),(2,'neodymium',2019,600),(3,'neodymium',2020,700),(4,'neodymium',2021,800);
DELETE FROM production WHERE element = 'neodymium' AND year = 2020;
Delete the production record for 'India' in 2020.
CREATE TABLE production (country VARCHAR(255),year INT,amount INT); INSERT INTO production (country,year,amount) VALUES ('China',2019,120000),('China',2020,140000),('USA',2020,38000),('Australia',2020,20000),('India',2020,5000);
DELETE FROM production WHERE country = 'India' AND year = 2020;
Delete the row with the lowest quantity of Gadolinium produced in 2020.
CREATE TABLE gadolinium_production (id INT,name VARCHAR(255),element VARCHAR(10),country VARCHAR(100),production_date DATE,quantity FLOAT); INSERT INTO gadolinium_production (id,name,element,country,production_date,quantity) VALUES (1,'Company A','Gd','China','2020-01-01',15.0),(2,'Company B','Gd','Australia','2020-01-15',20.0),(3,'Company C','Gd','Malaysia','2020-02-01',25.0),(4,'Company D','Gd','China','2020-02-15',30.0),(5,'Company E','Gd','Australia','2020-03-01',35.0);
DELETE FROM gadolinium_production WHERE (name, element, production_date, quantity) IN (SELECT name, element, production_date, MIN(quantity) FROM gadolinium_production WHERE element = 'Gd' AND YEAR(production_date) = 2020 GROUP BY name, element, production_date);
Identify the percentage of properties in each borough of New York that have inclusive housing policies.
CREATE TABLE new_york_properties (property_id INT,borough VARCHAR(20),inclusive_housing BOOLEAN); INSERT INTO new_york_properties (property_id,borough,inclusive_housing) VALUES (1,'Manhattan',TRUE),(2,'Brooklyn',FALSE),(3,'Queens',TRUE),(4,'Bronx',TRUE),(5,'Staten Island',FALSE);
SELECT borough, 100.0 * COUNT(*) FILTER (WHERE inclusive_housing = TRUE) / COUNT(*) AS pct_inclusive FROM new_york_properties GROUP BY borough ORDER BY pct_inclusive DESC;
What is the average listing price for green-certified properties in the 'sustainable_homes' table?
CREATE TABLE sustainable_homes (listing_id INT,listing_price DECIMAL,green_certified BOOLEAN);
SELECT AVG(listing_price) FROM sustainable_homes WHERE green_certified = TRUE;