instruction
stringlengths
0
1.06k
input
stringlengths
11
5.3k
response
stringlengths
2
4.44k
List users from the 'gaming' page who have not liked any posts, display their user IDs.
CREATE TABLE users (id INT,name VARCHAR(255)); CREATE TABLE posts (id INT,user_id INT,page_name VARCHAR(255),content TEXT); CREATE TABLE likes (id INT,user_id INT,post_id INT); CREATE TABLE hashtags (id INT,post_id INT,tag VARCHAR(255));
SELECT DISTINCT users.id FROM users LEFT JOIN likes ON users.id = likes.user_id WHERE likes.id IS NULL AND users.page_name = 'gaming';
What is the total budget for the health and education departments in 2022?
CREATE TABLE Departments (Department TEXT,Budget DECIMAL); INSERT INTO Departments VALUES ('Health',20000.00),('Education',15000.00),('Operations',10000.00);
SELECT SUM(CASE WHEN Department IN ('Health', 'Education') THEN Budget ELSE 0 END) as TotalBudget2022 FROM Departments WHERE YEAR(CONCAT('2022-', '01-01')) = 2022;
What is the percentage of mental health parity violations resolved in each state, in the last 6 months, for violations that occurred before 2021?
CREATE TABLE MentalHealthParityViolations (ViolationID INT,State VARCHAR(255),ViolationDate DATE,ResolutionDate DATE); INSERT INTO MentalHealthParityViolations (ViolationID,State,ViolationDate,ResolutionDate) VALUES (1,'California','2020-04-01','2020-06-01'); INSERT INTO MentalHealthParityViolations (ViolationID,State,ViolationDate,ResolutionDate) VALUES (2,'Texas','2019-01-15','2019-03-10'); INSERT INTO MentalHealthParityViolations (ViolationID,State,ViolationDate,ResolutionDate) VALUES (3,'California','2021-03-05','2021-05-15');
SELECT State, AVG(CASE WHEN EXTRACT(MONTH FROM ResolutionDate) IN (1,2,3,4,5,6) THEN 1 ELSE 0 END) as ResolutionPercentage FROM MentalHealthParityViolations WHERE ResolutionDate >= DATE_SUB(CURRENT_DATE, INTERVAL 6 MONTH) AND ViolationDate < '2021-01-01' GROUP BY State;
What is the distribution of military technology categories?
CREATE TABLE tech_categories (id INT,tech VARCHAR(255),category VARCHAR(255)); INSERT INTO tech_categories (id,tech,category) VALUES (1,'Stealth aircraft','Aircraft'),(2,'Cyber defense systems','Cybersecurity'),(3,'Missile defense systems','Weapons'),(4,'Unmanned aerial vehicles','Aircraft');
SELECT category, COUNT(*) as category_count FROM tech_categories GROUP BY category;
What is the average production of 'cereals' for each continent?
CREATE TABLE crops (crop_id INT,crop_name VARCHAR(255),continent VARCHAR(255),production INT); INSERT INTO crops (crop_id,crop_name,continent,production) VALUES (1,'cereals','Africa',200),(2,'cereals','Asia',300),(3,'cereals','Europe',400),(4,'cereals','South America',500),(5,'cereals','North America',600);
SELECT continent, AVG(production) as avg_production FROM crops WHERE crop_name = 'cereals' GROUP BY continent;
Show the total number of matches won by the 'cricket_teams' table in ascending order.
CREATE TABLE cricket_teams (team_id INT,team_name VARCHAR(30),wins INT);
SELECT team_name, SUM(wins) as total_wins FROM cricket_teams GROUP BY team_name ORDER BY total_wins ASC;
What is the minimum cargo handling time for all ports?
CREATE TABLE ports (port_id INT,cargo_handling_time INT); INSERT INTO ports (port_id,cargo_handling_time) VALUES (1,120),(2,150),(3,180);
SELECT MIN(cargo_handling_time) FROM ports;
Delete all records from the 'Service Workers United' union in the 'Service' industry in Texas.
CREATE TABLE unions (id INT,name TEXT,industry TEXT,state TEXT); INSERT INTO unions (id,name,industry,state) VALUES (1,'Service Workers United','Service','Texas');
DELETE FROM unions WHERE name = 'Service Workers United' AND industry = 'Service' AND state = 'Texas';
What is the percentage of plastic waste recycled in the Caribbean region in 2021 Q4?
CREATE TABLE WasteTypes (waste_type_id INT,waste_type VARCHAR(255),region VARCHAR(255),quarter DATE,recycling_rate DECIMAL(5,2)); INSERT INTO WasteTypes (waste_type_id,waste_type,region,quarter,recycling_rate) VALUES (1,'Plastic','Caribbean','2021-10-01',0.25),(2,'Glass','Caribbean','2021-10-01',0.30),(3,'Metal','Caribbean','2021-10-01',0.40);
SELECT recycling_rate*100 AS 'Percentage of Plastic Waste Recycled' FROM WasteTypes WHERE waste_type = 'Plastic' AND region = 'Caribbean' AND quarter = '2021-10-01';
Update the sales revenue for a specific transaction in Oregon dispensaries since January 2021
CREATE TABLE ORDispensaries (DispensaryID INT,Name VARCHAR(100),Location VARCHAR(100),State VARCHAR(100)); CREATE TABLE ORSalesRevenue (RevenueID INT,DispensaryID INT,SalesRevenue DECIMAL(10,2),RevenueDate DATE,TransactionID INT);
UPDATE ORSalesRevenue SET SalesRevenue = 500 WHERE TransactionID = 1234 AND DispensaryID IN (SELECT DispensaryID FROM ORDispensaries WHERE State = 'Oregon') AND RevenueDate >= '2021-01-01';
List all products that have never been sold in a sustainable package, excluding those that have been discontinued.
CREATE TABLE products (id INT,name TEXT,discontinued BOOLEAN,sustainable_package BOOLEAN);
SELECT name FROM products WHERE discontinued = FALSE AND id NOT IN (SELECT product_id FROM sustainable_packages);
What is the total revenue generated from postpaid mobile and broadband services for customers in the 'North' region for the year 2021?
CREATE TABLE subscribers (id INT,service VARCHAR(10),region VARCHAR(10)); INSERT INTO subscribers (id,service,region) VALUES (1,'postpaid','North'); CREATE TABLE revenue (id INT,subscriber_id INT,service VARCHAR(10),year INT,amount INT); INSERT INTO revenue (id,subscriber_id,service,year,amount) VALUES (1,1,'postpaid',2021,500);
SELECT SUM(revenue.amount) FROM revenue JOIN subscribers ON revenue.subscriber_id = subscribers.id WHERE subscribers.service IN ('postpaid', 'broadband') AND subscribers.region = 'North' AND revenue.year = 2021;
What is the total energy consumption (in kWh) of green buildings per city and their energy source?
CREATE TABLE energy_consumption (building_id INT,building_name VARCHAR(255),city VARCHAR(255),energy_source VARCHAR(255),energy_consumption_kWh INT); INSERT INTO energy_consumption (building_id,building_name,city,energy_source,energy_consumption_kWh) VALUES (1,'Green Building 1','NYC','Solar',1000); INSERT INTO energy_consumption (building_id,building_name,city,energy_source,energy_consumption_kWh) VALUES (2,'Green Building 2','LA','Wind',2000); INSERT INTO energy_consumption (building_id,building_name,city,energy_source,energy_consumption_kWh) VALUES (3,'Green Building 3','NYC','Hydro',3000);
SELECT city, energy_source, SUM(energy_consumption_kWh) as total_energy_consumption_kWh FROM energy_consumption GROUP BY city, energy_source;
Identify users from underrepresented communities with more than 5 transactions in Q3 2019, and rank them by transaction value.
CREATE TABLE users (user_id INT,user_category VARCHAR(30)); CREATE TABLE transactions (transaction_id INT,user_id INT,transaction_value FLOAT,transaction_date DATE); INSERT INTO users (user_id,user_category) VALUES (1,'Minority Female'); INSERT INTO transactions (transaction_id,user_id,transaction_value,transaction_date) VALUES (1,1,100.00,'2019-09-01');
SELECT user_id, RANK() OVER (ORDER BY SUM(transaction_value) DESC) as rank FROM transactions INNER JOIN users ON transactions.user_id = users.user_id WHERE EXTRACT(MONTH FROM transaction_date) BETWEEN 9 AND 11 HAVING COUNT(*) > 5 GROUP BY user_id;
Insert a record of a new threat actor in the 'threat_actors' table
CREATE TABLE threat_actors (id INT,name VARCHAR,alias TEXT,country VARCHAR);
INSERT INTO threat_actors (id, name, alias, country) VALUES (1, 'APT33', 'Iranian APT group', 'Iran');
Find the total installed capacity (in MW) of wind power projects in the 'North America' region, excluding the United States?
CREATE TABLE wind_projects (project_id INT,project_name VARCHAR(100),region VARCHAR(100),installed_capacity FLOAT); INSERT INTO wind_projects (project_id,project_name,region,installed_capacity) VALUES (1,'Wind Farm 1','North America',100.0),(2,'Wind Farm 2','United States',200.0),(3,'Wind Farm 3','North America',150.0);
SELECT SUM(installed_capacity) FROM wind_projects WHERE region = 'North America' AND country NOT IN (SELECT country FROM countries WHERE name = 'United States');
Who are the top 10 users by number of posts, with a location in "California"?
CREATE TABLE users (id INT,location VARCHAR(255)); CREATE TABLE posts (id INT,user_id INT,post_date DATE); INSERT INTO users (id,location) VALUES (1,'California'); INSERT INTO posts (id,user_id,post_date) VALUES (1,1,'2022-03-15');
SELECT users.id, users.location, COUNT(posts.id) AS post_count FROM users JOIN posts ON users.id = posts.user_id WHERE users.location = 'California' GROUP BY users.id, users.location ORDER BY post_count DESC LIMIT 10;
Display the number of unique users who have created playlists with at least 2 songs.
CREATE TABLE playlist_users (playlist_id INT,user_id INT); INSERT INTO playlist_users (playlist_id,user_id) VALUES (1,1),(2,2),(3,1),(4,3),(5,4),(6,5),(7,5); CREATE TABLE playlist_songs (playlist_id INT,song_id INT); INSERT INTO playlist_songs (playlist_id,song_id) VALUES (1,1),(1,2),(2,3),(2,4),(5,6),(5,7),(6,8),(7,8),(7,9);
SELECT COUNT(DISTINCT user_id) AS num_users FROM playlist_users JOIN (SELECT playlist_id FROM playlist_songs GROUP BY playlist_id HAVING COUNT(DISTINCT song_id) >= 2) AS playlists_2_songs ON playlist_users.playlist_id = playlists_2_songs.playlist_id;
What is the minimum property tax in London?
CREATE TABLE property_tax (tax FLOAT,city VARCHAR(20));
SELECT MIN(tax) FROM property_tax WHERE city = 'London';
What is the total number of police officers in each rank, including reserve officers?
CREATE TABLE ranks (rid INT,rank_name VARCHAR(255)); CREATE TABLE officers (oid INT,rid INT,officer_type VARCHAR(255),is_active BOOLEAN);
SELECT r.rank_name, COUNT(o.oid) FROM ranks r LEFT JOIN officers o ON r.rid = o.rid AND o.is_active = TRUE AND o.officer_type IN ('active', 'reserve') GROUP BY r.rank_name;
What is the most common mental health parity violation in Texas?
CREATE TABLE MentalHealthParity (ID INT,Violation VARCHAR(255),State VARCHAR(255)); INSERT INTO MentalHealthParity VALUES (1,'Non-compliance with mental health coverage','Texas'); INSERT INTO MentalHealthParity VALUES (2,'Lack of mental health coverage parity','Texas');
SELECT Violation, COUNT(*) AS Count FROM MentalHealthParity WHERE State = 'Texas' GROUP BY Violation ORDER BY Count DESC LIMIT 1;
What is the market share of electric vehicles by make in 2025?
CREATE TABLE ev_sales (id INT,make VARCHAR,model VARCHAR,year INT,sold INT); CREATE VIEW ev_market_share AS SELECT make,SUM(sold) as total_sold FROM ev_sales GROUP BY make;
SELECT make, total_sold/SUM(total_sold) OVER (PARTITION BY NULL) as market_share FROM ev_market_share WHERE year = 2025;
Show the travel advisory levels and destinations for South America.
CREATE TABLE travel_advisories (id INT,level INT,destination VARCHAR(50)); INSERT INTO travel_advisories (id,level,destination) VALUES (1,2,'Brazil'); INSERT INTO travel_advisories (id,level,destination) VALUES (2,3,'Argentina'); INSERT INTO travel_advisories (id,level,destination) VALUES (3,1,'Chile');
SELECT level, destination FROM travel_advisories WHERE destination LIKE 'South%';
What is the total revenue for the month of July?
CREATE TABLE revenue (id INT,month INT,amount DECIMAL(5,2)); INSERT INTO revenue (id,month,amount) VALUES (1,6,5000.00),(2,7,6000.00),(3,8,7000.00),(4,9,8000.00);
SELECT SUM(amount) FROM revenue WHERE month = 7;
List all projects with a start date in the year 2022 from the "Projects" table.
CREATE TABLE Projects (project_id INT,contractor_id INT,start_date DATE,end_date DATE);
SELECT * FROM Projects WHERE YEAR(start_date) = 2022;
What is the total installed capacity of wind projects in the 'renewable_projects' table?
CREATE TABLE renewable_projects (project_id INT,project_name VARCHAR(255),project_type VARCHAR(255),installed_capacity FLOAT); INSERT INTO renewable_projects (project_id,project_name,project_type,installed_capacity) VALUES (1,'Wind Farm 1','Wind',100.5),(2,'Solar Farm 1','Solar',150.0);
SELECT SUM(installed_capacity) FROM renewable_projects WHERE project_type = 'Wind';
What is the average income of households with children in Japan?
CREATE TABLE household_data (id INT,children BOOLEAN,country VARCHAR(20),income INT); INSERT INTO household_data (id,children,country,income) VALUES (1,true,'Japan',70000),(2,false,'Japan',60000),(3,true,'Japan',75000);
SELECT AVG(income) FROM household_data WHERE country = 'Japan' AND children = true;
Delete all 'Fighter Jet' sales records in 'Oceania' for the year '2027'
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,'Oceania',2027,'Fighter Jet',12,5000000),(2,'Oceania',2027,'Tank',25,12000000),(3,'Oceania',2027,'Helicopter',10,8000000);
DELETE FROM military_sales WHERE region = 'Oceania' AND equipment_name = 'Fighter Jet' AND year = 2027;
Update the capacity_bod in the wastewater_facilities table where the name is 'Facility A' and the region is 'Northeast'
CREATE TABLE wastewater_facilities (id INT PRIMARY KEY,name VARCHAR(50),facility_type VARCHAR(50),region VARCHAR(20),capacity_bod INT,operational_status VARCHAR(20)); INSERT INTO wastewater_facilities (id,name,facility_type,region,capacity_bod,operational_status) VALUES (1,'Facility A','Sewage Treatment Plant','Northeast',500000,'Operational'),(2,'Facility B','Screening Facility','Southeast',250000,'Operational'),(3,'Facility C','Sewage Treatment Plant','Midwest',750000,'Operational');
UPDATE wastewater_facilities SET capacity_bod = 600000 WHERE name = 'Facility A' AND region = 'Northeast';
What is the name and organization of volunteers who have not provided support in any sector?
CREATE TABLE volunteers (id INT,name TEXT,organization TEXT,sector TEXT); INSERT INTO volunteers (id,name,organization,sector) VALUES (1,'John Doe','UNICEF','Education'),(2,'Jane Smith','Save the Children','Health'),(3,'Mohammad Ali',NULL,NULL);
SELECT name, organization FROM volunteers WHERE sector IS NULL;
Show the number of fields discovered by 'Shell'
CREATE TABLE fields (field_id INT,field_name VARCHAR(255),operator VARCHAR(255),discovery_date DATE);
SELECT COUNT(*) FROM fields WHERE operator = 'Shell';
What is the highest cost of accessibility features for each venue?
CREATE TABLE Accessibility_Features (id INT,venue_id INT,feature VARCHAR(255),cost DECIMAL(5,2)); INSERT INTO Accessibility_Features (id,venue_id,feature,cost) VALUES (1,1,'Wheelchair Ramp',2000.00); INSERT INTO Accessibility_Features (id,venue_id,feature,cost) VALUES (2,2,'Elevator',5000.00); INSERT INTO Accessibility_Features (id,venue_id,feature,cost) VALUES (3,3,'Accessible Parking',1000.00);
SELECT venue_id, MAX(cost) as 'Highest Cost' FROM Accessibility_Features GROUP BY venue_id;
What is the percentage of crop yield by country in 'crop_distribution' table?
CREATE TABLE crop_distribution (country VARCHAR(50),crop VARCHAR(50),yield INT); INSERT INTO crop_distribution (country,crop,yield) VALUES ('Canada','corn',1000),('Canada','wheat',2000),('USA','corn',3000),('USA','wheat',4000),('Mexico','corn',2500),('Mexico','wheat',1500);
SELECT country, crop, ROUND(100.0 * yield / SUM(yield) OVER (PARTITION BY crop), 2) as yield_percentage FROM crop_distribution;
Update the ethnicity of worker 5 to 'Hispanic'
CREATE TABLE community_health_workers (worker_id INT,ethnicity VARCHAR(50)); INSERT INTO community_health_workers (worker_id,ethnicity) VALUES (1,'Not Specified'),(2,'African American'),(3,'Asian'),(4,'Caucasian'),(5,'Prefer not to say');
UPDATE community_health_workers SET ethnicity = 'Hispanic' WHERE worker_id = 5;
What is the total number of hospitals in 'rural_healthcare' schema?
CREATE SCHEMA if not exists rural_healthcare; USE rural_healthcare; CREATE TABLE Hospitals (id INT,name VARCHAR(100),location VARCHAR(100),beds INT); INSERT INTO Hospitals VALUES (1,'Rural General Hospital','Smalltown',50),(2,'Mountain View Clinic','Mountain Village',15),(3,'Seaside Health Center','Coastal City',25);
SELECT COUNT(*) FROM Hospitals;
Find the average donation amount per donor for donations made in the 'disaster relief' category.
CREATE TABLE donors (id INT,name VARCHAR(255)); INSERT INTO donors (id,name) VALUES (1,'Global Hope'),(2,'Caring Hearts'),(3,'Relief Aid'); CREATE TABLE donation_details (donor_id INT,category VARCHAR(255),amount DECIMAL(10,2)); INSERT INTO donation_details (donor_id,category,amount) VALUES (1,'disaster relief',1000),(1,'disaster relief',2000),(2,'disaster relief',500),(2,'disaster relief',1500),(3,'education',3000);
SELECT donors.name, AVG(donation_details.amount) AS avg_donation FROM donors INNER JOIN donation_details ON donors.id = donation_details.donor_id WHERE category = 'disaster relief' GROUP BY donors.id;
How many users have a body fat percentage over 25%?
CREATE TABLE UserMetrics (UserID INT,BodyFatPercentage DECIMAL(3,2)); INSERT INTO UserMetrics (UserID,BodyFatPercentage) VALUES (1,20.00),(2,27.50),(3,18.00),(4,22.50),(5,19.50);
SELECT COUNT(*) FROM UserMetrics WHERE BodyFatPercentage > 25.00;
What is the average energy efficiency rating for buildings in London?
CREATE TABLE buildings (id INT,city TEXT,rating FLOAT); INSERT INTO buildings (id,city,rating) VALUES (1,'London',4.0),(2,'London',4.5),(3,'London',5.0),(4,'London',5.5),(5,'London',6.0);
SELECT AVG(rating) FROM buildings WHERE city = 'London';
What is the percentage of positive citizen feedback for public service A?
CREATE TABLE feedback (id INT,service VARCHAR(20),rating INT); INSERT INTO feedback VALUES (1,'Public Service A',5),(2,'Public Service A',3),(3,'Public Service A',4);
SELECT (COUNT(*) * 100.0 / (SELECT COUNT(*) FROM feedback WHERE service = 'Public Service A')) FROM feedback WHERE rating >= 4 AND service = 'Public Service A';
Delete records for menu items that have not been ordered in the last 6 months.
CREATE TABLE orders (order_id INT,menu_id INT,order_date DATE); INSERT INTO orders (order_id,menu_id,order_date) VALUES (1,1,'2021-01-01'),(2,2,'2021-02-01'),(3,1,'2021-06-01');
DELETE FROM orders WHERE order_date < DATE_SUB(CURDATE(), INTERVAL 6 MONTH);
What is the maximum number of police officers on duty in each shift?
CREATE TABLE shifts (shift_id INT,shift_start TIME,shift_end TIME); INSERT INTO shifts (shift_id,shift_start,shift_end) VALUES (1,'07:00:00','15:00:00'),(2,'15:00:00','23:00:00'),(3,'23:00:00','07:00:00'); CREATE TABLE police_officers (officer_id INT,shift_id INT,on_duty BOOLEAN); INSERT INTO police_officers (officer_id,shift_id,on_duty) VALUES (1,1,TRUE),(2,1,TRUE),(3,1,TRUE),(4,2,TRUE),(5,2,TRUE),(6,3,TRUE),(7,3,TRUE);
SELECT shift_id, MAX(COUNT(*)) FROM police_officers JOIN shifts ON police_officers.shift_id = shifts.shift_id WHERE on_duty = TRUE GROUP BY shift_id;
Find the transaction ID and regulatory framework for transactions with a gas limit greater than 1,000,000 on the Solana blockchain.
CREATE TABLE solana_transactions (transaction_id INTEGER,regulatory_framework VARCHAR(20),gas_limit INTEGER);
SELECT transaction_id, regulatory_framework FROM solana_transactions WHERE gas_limit > 1000000;
How many albums were released each year by music artists?
CREATE TABLE Music_Albums (id INT,title VARCHAR(100),release_year INT,artist VARCHAR(100)); INSERT INTO Music_Albums (id,title,release_year,artist) VALUES (1,'Back in Black',1980,'AC/DC'),(2,'Thriller',1982,'Michael Jackson'),(3,'The Dark Side of the Moon',1973,'Pink Floyd');
SELECT release_year, COUNT(*) FROM Music_Albums GROUP BY release_year;
What is the minimum number of relief supplies received by urban areas in 2020?
CREATE TABLE relief_supplies (id INT PRIMARY KEY,area VARCHAR(20),year INT,quantity INT); INSERT INTO relief_supplies (id,area,year,quantity) VALUES (1,'urban',2018,200),(2,'rural',2018,300),(3,'urban',2019,150),(4,'urban',2020,500),(5,'rural',2020,450);
SELECT MIN(quantity) FROM relief_supplies WHERE area = 'urban' AND year = 2020;
What are the combined salaries of all employees working for Boeing, Airbus, or SpaceX, grouped by job title?
CREATE TABLE Employee_Salaries (company VARCHAR(50),employee_id INT,job_title VARCHAR(50),salary DECIMAL(10,2)); INSERT INTO Employee_Salaries (company,employee_id,job_title,salary) VALUES ('Boeing',1,'Engineer',80000.00),('Airbus',2,'Engineer',85000.00),('SpaceX',3,'Engineer',90000.00);
SELECT job_title, SUM(salary) FROM Employee_Salaries WHERE company IN ('Boeing', 'Airbus', 'SpaceX') GROUP BY job_title;
Show all the users who haven't played any game in the last year?
CREATE TABLE user_game_history (id INT,user_id INT,game_id INT,last_played DATE); INSERT INTO user_game_history (id,user_id,game_id,last_played) VALUES (1,1,1,'2022-01-01'),(2,2,2,'2022-02-01'),(3,1,3,'2021-01-01');
SELECT u.id, u.name, u.country FROM users u LEFT JOIN user_game_history ug ON u.id = ug.user_id WHERE ug.last_played < (CURRENT_DATE - INTERVAL '1 year') OR ug.last_played IS NULL;
Delete records of languages not actively spoken
CREATE TABLE Languages (Id INT,Language TEXT,Speakers INT,Status TEXT); INSERT INTO Languages (Id,Language,Speakers,Status) VALUES (1,'Latin',0,'Inactive');
DELETE FROM Languages WHERE Status = 'Inactive';
Who are the farmers who received training in 'Conservation Agriculture' in the 'Nile Delta' region in 2021?
CREATE TABLE farmers (id INT,name VARCHAR(255),region VARCHAR(255),training_year INT,training_topic VARCHAR(255)); INSERT INTO farmers (id,name,region,training_year,training_topic) VALUES (1,'Ahmed Hassan','Nile Delta',2021,'Conservation Agriculture'),(2,'Fatima Ali','Nile Delta',2020,'Precision Agriculture');
SELECT name FROM farmers WHERE region = 'Nile Delta' AND training_topic = 'Conservation Agriculture' AND training_year = 2021;
Calculate the percentage of organic fabric usage, per country, in garments.
CREATE TABLE Garments (GarmentID INT,Fabric VARCHAR(255),Country VARCHAR(255)); INSERT INTO Garments (GarmentID,Fabric,Country) VALUES (1,'Organic Cotton','USA');
SELECT Country, SUM(CASE WHEN Fabric LIKE '%Organic%' THEN 1 ELSE 0 END) * 100.0 / COUNT(*) as OrganicPercentage FROM Garments GROUP BY Country;
What is the trend in energy efficiency over time for wind projects?
CREATE TABLE project (id INT,name TEXT,date TEXT,project_type TEXT,energy_efficiency FLOAT); INSERT INTO project (id,name,date,project_type,energy_efficiency) VALUES (1,'Wind Farm','2020-01-01','Wind',0.45);
SELECT date, energy_efficiency, ROW_NUMBER() OVER (ORDER BY date) AS rank FROM project WHERE project_type = 'Wind' ORDER BY date;
How many size 14 garments were sold in the past week?
CREATE TABLE sales (id INT,garment_id INT,size INT,sale_date DATE); INSERT INTO sales (id,garment_id,size,sale_date) VALUES (1,501,14,'2022-03-01'),(2,502,16),(3,503,8,'2022-03-05'),(4,504,10,'2022-03-07');
SELECT COUNT(*) FROM sales WHERE size = 14 AND sale_date BETWEEN DATE_SUB(CURDATE(), INTERVAL 7 DAY) AND CURDATE();
List impact investment strategies in the 'technology' sector with ESG scores above 80.
CREATE TABLE investment_strategies (strategy_id INT,sector VARCHAR(20),ESG_score FLOAT); INSERT INTO investment_strategies (strategy_id,sector,ESG_score) VALUES (101,'renewable_energy',77.5),(102,'sustainable_agriculture',82.3),(103,'green_transportation',90.1),(104,'technology',85.0);
SELECT * FROM investment_strategies WHERE sector = 'technology' AND ESG_score > 80;
How many garments with the category 'Tops' were sold in the first quarter of 2021?
CREATE TABLE sales (sale_id INT,sale_date DATE,category VARCHAR(20),quantity INT); INSERT INTO sales (sale_id,sale_date,category,quantity) VALUES (1,'2021-01-05','Tops',30),(2,'2021-02-10','Bottoms',25),(3,'2021-03-20','Tops',40),(4,'2021-01-15','Accessories',10),(5,'2021-02-25','Tops',35),(6,'2021-03-05','Bottoms',20);
SELECT SUM(quantity) FROM sales WHERE category = 'Tops' AND sale_date BETWEEN '2021-01-01' AND '2021-03-31';
What is the average severity score of vulnerabilities in the technology sector?
CREATE TABLE vulnerabilities (id INT,sector VARCHAR(20),severity FLOAT); INSERT INTO vulnerabilities (id,sector,severity) VALUES (1,'Technology',7.5);
SELECT AVG(severity) FROM vulnerabilities WHERE sector = 'Technology';
What is the maximum response time for emergency calls in each precinct for the month of August 2021?
CREATE TABLE emergency_calls (id INT,precinct VARCHAR(20),response_time INT,call_date DATE); INSERT INTO emergency_calls (id,precinct,response_time,call_date) VALUES (1,'downtown',12,'2021-08-01');
SELECT precinct, MAX(response_time) FROM emergency_calls WHERE call_date BETWEEN '2021-08-01' AND '2021-08-31' GROUP BY precinct;
Find all suppliers from India with an order count greater than 10.
CREATE TABLE suppliers (id INT,name VARCHAR(255),country VARCHAR(255)); CREATE TABLE orders (id INT,supplier_id INT,quantity INT); INSERT INTO suppliers (id,name,country) VALUES (1,'Spices of India','India'),(2,'Tasty Imports','USA'); INSERT INTO orders (id,supplier_id,quantity) VALUES (1,1,10),(2,1,20),(3,2,5);
SELECT suppliers.name FROM suppliers JOIN orders ON suppliers.id = orders.supplier_id GROUP BY suppliers.name HAVING COUNT(orders.id) > 10 AND suppliers.country = 'India';
Find the clients who have taken out the most socially responsible loans, excluding clients from Saudi Arabia and the UAE?
CREATE TABLE socially_responsible_loans(client_id INT,client_country VARCHAR(25));INSERT INTO socially_responsible_loans(client_id,client_country) VALUES (1,'Bahrain'),(2,'UAE'),(3,'Indonesia'),(4,'Saudi Arabia'),(1,'Bahrain'),(2,'UAE'),(7,'Indonesia'),(8,'Saudi Arabia'),(1,'Bahrain'),(2,'UAE');
SELECT client_id, COUNT(*) as num_loans FROM socially_responsible_loans WHERE client_country NOT IN ('Saudi Arabia', 'UAE') GROUP BY client_id ORDER BY num_loans DESC;
What is the total network infrastructure investment for the 'Europe' region in the last 5 years?
CREATE TABLE network_investments (id INT,investment FLOAT,year INT,region VARCHAR(15)); INSERT INTO network_investments (id,investment,year,region) VALUES (1,500000,2018,'Europe'); INSERT INTO network_investments (id,investment,year,region) VALUES (2,600000,2019,'Europe');
SELECT SUM(investment) FROM network_investments WHERE region = 'Europe' AND year BETWEEN 2017 AND 2021;
Which textile suppliers have the highest and lowest environmental impact scores?
CREATE TABLE TextileSuppliers (id INT,supplier_name VARCHAR(255),environmental_impact_score INT); INSERT INTO TextileSuppliers (id,supplier_name,environmental_impact_score) VALUES (1,'Green Textiles',90),(2,'Blue Fabrics',70),(3,'Eco-Friendly Fibers',95),(4,'Sustainable Silk',80);
SELECT supplier_name, environmental_impact_score FROM TextileSuppliers ORDER BY environmental_impact_score DESC LIMIT 1; SELECT supplier_name, environmental_impact_score FROM TextileSuppliers ORDER BY environmental_impact_score ASC LIMIT 1;
Identify the number of sustainable tourism initiatives implemented in the 'Americas' region by year.
CREATE TABLE sustainable_tourism (id INT,initiative_name VARCHAR(100),region VARCHAR(50),implementation_year INT); INSERT INTO sustainable_tourism (id,initiative_name,region,implementation_year) VALUES (1,'Green Lodging','Americas',2018),(2,'Solar-Powered Sightseeing','Europe',2020);
SELECT implementation_year, COUNT(*) as num_initiatives FROM sustainable_tourism WHERE region = 'Americas' GROUP BY implementation_year;
What is the percentage of posts by users in the United Kingdom that contain hashtags, for the past month?
CREATE TABLE users (user_id INT,user_name VARCHAR(255),country VARCHAR(255));CREATE TABLE posts (post_id INT,user_id INT,hashtags TEXT,timestamp TIMESTAMP); INSERT INTO users (user_id,user_name,country) VALUES (1,'Alice','USA'),(2,'Bob','Canada'),(3,'Carlos','UK'); INSERT INTO posts (post_id,user_id,hashtags,timestamp) VALUES (1,1,'#hello','2022-01-01 10:00:00'),(2,1,'','2022-01-02 10:00:00'),(3,2,'#world','2022-01-01 10:00:00'),(4,3,'#hi','2022-01-01 10:00:00');
SELECT (COUNT(DISTINCT CASE WHEN posts.hashtags != '' THEN users.user_id END) / COUNT(DISTINCT users.user_id)) * 100 AS hashtag_percentage FROM users INNER JOIN posts ON users.user_id = posts.user_id WHERE users.country = 'UK' AND posts.timestamp >= NOW() - INTERVAL 1 MONTH;
Calculate the average number of employees in companies with a focus on circular economy initiatives in Asia.
CREATE TABLE companies (id INT,name TEXT,country TEXT,circular_economy BOOLEAN,num_employees INT); INSERT INTO companies (id,name,country,circular_economy,num_employees) VALUES (1,'LMN Corp','China',TRUE,500),(2,'OPQ Inc','Japan',FALSE,700),(3,'RST Co','India',TRUE,600);
SELECT AVG(num_employees) FROM companies WHERE country IN ('China', 'Japan', 'India') AND circular_economy = TRUE;
What is the total number of schools in Kenya and Uganda, ordered by the country name?
CREATE TABLE Kenya (id INT,name TEXT,type TEXT,location TEXT); INSERT INTO Kenya (id,name,type,location) VALUES (1,'School A','Primary','Nairobi'); INSERT INTO Kenya (id,name,type,location) VALUES (2,'School B','Secondary','Mombasa'); CREATE TABLE Uganda (id INT,name TEXT,type TEXT,location TEXT); INSERT INTO Uganda (id,name,type,location) VALUES (1,'School C','Primary','Kampala'); INSERT INTO Uganda (id,name,type,location) VALUES (2,'School D','Secondary','Jinja');
SELECT SUM(country_total) AS total_schools FROM (SELECT 'Kenya' AS country, COUNT(*) AS country_total FROM Kenya UNION ALL SELECT 'Uganda' AS country, COUNT(*) AS country_total FROM Uganda) AS total_by_country ORDER BY country;
Find the average streaming time per user, for users who have streamed music more than 20 hours in the last month.
CREATE TABLE Streaming_Sessions (user_id INT,duration INT,session_date DATE); INSERT INTO Streaming_Sessions (user_id,duration,session_date) VALUES (1,30,'2022-01-01'),(2,25,'2022-01-02'),(1,45,'2022-01-03');
SELECT AVG(duration) as avg_duration FROM Streaming_Sessions WHERE user_id IN (SELECT user_id FROM Streaming_Sessions GROUP BY user_id HAVING SUM(duration) > 20 * 60);
How many tourists visited the 'Mayan Ruins' site in Mexico in 2021?
CREATE TABLE IF NOT EXISTS tourism_sites (id INT PRIMARY KEY,name TEXT,country TEXT,year INT,visitor_count INT); INSERT INTO tourism_sites (id,name,country,year,visitor_count) VALUES (1,'Mayan Ruins','Mexico',2021,150000),(2,'Eiffel Tower','France',2019,6000000),(3,'Taj Mahal','India',2018,7000000);
SELECT SUM(visitor_count) FROM tourism_sites WHERE name = 'Mayan Ruins' AND year = 2021;
What is the average weight of shipments to Africa in the month of March?
CREATE TABLE ShipmentsAfrica (id INT,weight FLOAT,destination VARCHAR(20),ship_date DATE); INSERT INTO ShipmentsAfrica (id,weight,destination,ship_date) VALUES (1,50.3,'Africa','2022-03-05'),(2,60.1,'Africa','2022-03-10');
SELECT AVG(weight) FROM ShipmentsAfrica WHERE destination = 'Africa' AND MONTH(ship_date) = 3;
What is the maximum length of any road in the "roads" table?
CREATE TABLE IF NOT EXISTS public.roads3 (id SERIAL PRIMARY KEY,name TEXT,length REAL); INSERT INTO public.roads3 (name,length) SELECT 'ExampleRoad5',2000.0 FROM generate_series(1,10); INSERT INTO public.roads3 (name,length) SELECT 'ExampleRoad6',1500.0 FROM generate_series(1,10);
SELECT MAX(length) FROM public.roads3;
What is the difference in water usage between residential and industrial sectors in New York in 2020?
CREATE TABLE residential_water_usage (state VARCHAR(20),year INT,usage FLOAT); INSERT INTO residential_water_usage (state,year,usage) VALUES ('New York',2020,12345.6); CREATE TABLE industrial_water_usage (state VARCHAR(20),year INT,sector VARCHAR(30),usage FLOAT); INSERT INTO industrial_water_usage (state,year,sector,usage) VALUES ('New York',2020,'Agriculture',1234.5),('New York',2020,'Manufacturing',2345.6),('New York',2020,'Mining',3456.7);
SELECT SUM(residential_water_usage.usage) - SUM(industrial_water_usage.usage) FROM residential_water_usage, industrial_water_usage WHERE residential_water_usage.state = 'New York' AND residential_water_usage.year = 2020 AND industrial_water_usage.state = 'New York' AND industrial_water_usage.year = 2020;
Insert new record into 'geological_survey' table with 'survey_date' as '2022-04-22' and 'survey_type' as 'Ground Penetrating Radar'
CREATE TABLE geological_survey (survey_date DATE,survey_type VARCHAR(255),PRIMARY KEY (survey_date,survey_type));
INSERT INTO geological_survey (survey_date, survey_type) VALUES ('2022-04-22', 'Ground Penetrating Radar');
List all the unique species of marine life observed in the Arctic Ocean and their corresponding counts in the last 3 years.
CREATE TABLE arctic_marine_life (id INT,species VARCHAR(50),count INT,date DATE); INSERT INTO arctic_marine_life (id,species,count,date) VALUES (1,'Beluga Whale',250,'2022-01-03'); INSERT INTO arctic_marine_life (id,species,count,date) VALUES (2,'Narwhal',120,'2021-12-17');
SELECT species, count(*) as total_count FROM arctic_marine_life WHERE date >= DATE_SUB(CURRENT_DATE, INTERVAL 3 YEAR) AND region = 'Arctic Ocean' GROUP BY species;
How many players play games on console in the UK?
CREATE TABLE Players (PlayerID INT,Age INT,Gender VARCHAR(10),Country VARCHAR(20),Console BOOLEAN,PC BOOLEAN); INSERT INTO Players (PlayerID,Age,Gender,Country,Console,PC) VALUES (1,25,'Male','USA',TRUE,TRUE),(2,30,'Female','UK',TRUE,FALSE),(3,35,'Female','Mexico',TRUE,FALSE),(4,20,'Male','UK',TRUE,FALSE),(5,50,'Male','UK',TRUE,FALSE);
SELECT COUNT(*) FROM Players WHERE Players.Country = 'UK' AND Players.Console = TRUE;
How many marine research projects were conducted in the Pacific?
CREATE TABLE Research (id INT,project VARCHAR(255),location VARCHAR(255),start_date DATE,end_date DATE); INSERT INTO Research (id,project,location,start_date,end_date) VALUES (3,'Pacific Ocean Research','Pacific','2021-01-01','2021-12-31'); INSERT INTO Research (id,project,location,start_date,end_date) VALUES (4,'Marine Life Study','Atlantic','2022-01-01','2022-12-31');
SELECT location, COUNT(*) FROM Research WHERE location = 'Pacific' GROUP BY location;
Delete records in the accounts table where the balance is less than 0
CREATE TABLE accounts (account_number INT,balance DECIMAL(10,2),customer_name VARCHAR(50),created_at TIMESTAMP);
DELETE FROM accounts WHERE balance < 0;
Display the total number of electric vehicles sold by each manufacturer
CREATE TABLE ev_manufacturers (manufacturer VARCHAR(50),ev_sold INT); INSERT INTO ev_manufacturers (manufacturer,ev_sold) VALUES ('Tesla',25000),('Nissan',18000),('Chevrolet',15000),('BMW',20000),('Mercedes',12000);
SELECT manufacturer, SUM(ev_sold) as total_ev_sold FROM ev_manufacturers GROUP BY manufacturer;
Update the quantity of item_id 1 to 100 in the Inventory table
CREATE TABLE Inventory (item_id INT,item_name VARCHAR(50),quantity INT,warehouse_id INT);
UPDATE Inventory SET quantity = 100 WHERE item_id = 1;
What is the maximum financial capability score for each age group?
CREATE TABLE financial_capability (age INT,score INT,survey_date DATE);
SELECT age, MAX(score) FROM financial_capability GROUP BY age;
How many cases were handled by attorneys in each region, grouped by case outcome?
CREATE TABLE Attorneys (AttorneyID int,Name varchar(50),Region varchar(10)); INSERT INTO Attorneys VALUES (1,'Sofia Rodriguez','Northeast'),(2,'Minh Nguyen','Southwest'); CREATE TABLE Cases (CaseID int,AttorneyID int,Outcome varchar(10)); INSERT INTO Cases VALUES (1,1,'Won'),(2,1,'Lost'),(3,2,'Won'),(4,2,'Won');
SELECT A.Region, C.Outcome, COUNT(C.CaseID) as NumCases FROM Attorneys A JOIN Cases C ON A.AttorneyID = C.AttorneyID GROUP BY A.Region, C.Outcome;
What is the number of players who use VR technology, grouped by their age?
CREATE TABLE VRPlayers (PlayerID INT,Age INT,VRUser BOOLEAN); INSERT INTO VRPlayers (PlayerID,Age,VRUser) VALUES (1,25,true),(2,30,false),(3,22,true);
SELECT Age, COUNT(*) as PlayerCount FROM VRPlayers WHERE VRUser = true GROUP BY Age;
What is the total amount of climate finance provided to projects in 'Asia'?
CREATE TABLE climate_finance (project_name TEXT,location TEXT,amount INTEGER); INSERT INTO climate_finance (project_name,location,amount) VALUES ('Project A','Asia',500000),('Project B','Europe',300000);
SELECT SUM(amount) FROM climate_finance WHERE location = 'Asia';
Add new records of Arctic species population to the existing table
CREATE TABLE SpeciesPopulation (species TEXT,year INT,population INT); INSERT INTO SpeciesPopulation (species,year,population) VALUES ('Arctic Fox',2015,15000),('Arctic Fox',2016,15500),('Muskoxen',2014,85000),('Muskoxen',2015,87000),('Muskoxen',2016,90000);
INSERT INTO SpeciesPopulation (species, year, population) VALUES ('Reindeer', 2013, 300000), ('Reindeer', 2014, 305000), ('Reindeer', 2015, 310000), ('Reindeer', 2016, 315000);
Which community education programs have seen a decrease in animal count in the past year?
CREATE TABLE education_programs (id INT,name VARCHAR(255)); CREATE TABLE education_animals (program_id INT,animal_count INT,year INT);
SELECT e.name FROM education_programs e JOIN education_animals ea ON e.id = ea.program_id WHERE ea.year = (SELECT MAX(year) FROM education_animals) AND ea.animal_count < (SELECT LAG(animal_count) OVER (PARTITION BY program_id ORDER BY year) FROM education_animals WHERE program_id = ea.program_id AND year = (SELECT MAX(year) - 1 FROM education_animals));
Show the number of victories for each team in the NBA
CREATE TABLE teams (id INT PRIMARY KEY,name TEXT,league TEXT,wins INT,losses INT,draws INT); INSERT INTO teams (id,name,league,wins,losses,draws) VALUES (1,'Golden State Warriors','NBA',26,7,0),(2,'Phoenix Suns','NBA',25,8,0),(3,'Brooklyn Nets','NBA',24,9,0),(4,'Milwaukee Bucks','NBA',23,10,0),(5,'Philadelphia 76ers','NBA',22,11,0);
SELECT name, wins FROM teams;
What are the total efforts for preserving tigers and lions?
CREATE TABLE habitat_preservation (id INT,species VARCHAR(50),efforts INT);
SELECT species, SUM(efforts) FROM habitat_preservation WHERE species IN ('tiger', 'lion') GROUP BY species;
What is the minimum savings of customers living in 'New York'?
CREATE TABLE savings (customer_id INT,name TEXT,state TEXT,savings DECIMAL(10,2)); INSERT INTO savings (customer_id,name,state,savings) VALUES (3,'Mary Smith','New York',4000.00),(4,'David Johnson','New York',3000.00);
SELECT MIN(savings) FROM savings WHERE state = 'New York';
List all mitigation projects that started after June 2022
CREATE TABLE mitigation_projects (id INT PRIMARY KEY,name VARCHAR(255),location VARCHAR(255),budget FLOAT,start_date DATE,end_date DATE); INSERT INTO mitigation_projects (id,name,location,budget,start_date,end_date) VALUES (1,'Solar Farm','San Francisco,USA',1000000,'2022-01-01','2023-12-31'),(2,'Wind Turbines','Rio de Janeiro,Brazil',1500000,'2022-05-15','2024-04-30'),(3,'Energy Efficiency','Nairobi,Kenya',500000,'2022-07-01','2023-06-30');
SELECT * FROM mitigation_projects WHERE start_date > '2022-06-01';
Add a new column for community languages
CREATE TABLE community (id INT,name VARCHAR(255),population INT,languages VARCHAR(255));
ALTER TABLE community ADD languages VARCHAR(255);
What is the number of community gardens in each state?
CREATE TABLE states (id INT,name VARCHAR(255)); CREATE TABLE community_gardens (state_id INT,num_gardens INT);
SELECT s.name, SUM(cg.num_gardens) as total_gardens FROM states s JOIN community_gardens cg ON s.id = cg.state_id GROUP BY s.id, s.name;
How many female employees have been hired in each department since 2018?
CREATE TABLE Employees (EmployeeID INT,Gender VARCHAR(10),HireDate DATE,Department VARCHAR(50)); INSERT INTO Employees (EmployeeID,Gender,HireDate,Department) VALUES (1,'Male','2020-01-01','HR'); INSERT INTO Employees (EmployeeID,Gender,HireDate,Department) VALUES (2,'Female','2019-01-01','IT'); INSERT INTO Employees (EmployeeID,Gender,HireDate,Department) VALUES (3,'Male','2020-05-01','IT'); INSERT INTO Employees (EmployeeID,Gender,HireDate,Department) VALUES (4,'Female','2018-01-01','Finance');
SELECT Department, COUNT(*) as Num_Female_Employees FROM Employees WHERE Gender = 'Female' AND YEAR(HireDate) >= 2018 GROUP BY Department;
What is the total donation amount for each cause, ordered by the total donation amount in descending order?
CREATE TABLE cause (cause_id INT,cause_name VARCHAR(50),donation_amount DECIMAL(10,2)); INSERT INTO cause (cause_id,cause_name,donation_amount) VALUES (1,'Education',25000.00),(2,'Health',30000.00),(3,'Environment',15000.00);
SELECT cause_name, SUM(donation_amount) AS total_donation_amount FROM cause GROUP BY cause_name ORDER BY total_donation_amount DESC;
List all missions that have had astronauts from both the USA and China.
CREATE TABLE Astronauts (Astronaut_ID INT,Name VARCHAR(255),Country VARCHAR(255)); CREATE TABLE Missions (Mission_ID INT,Astronaut_ID INT); INSERT INTO Astronauts (Astronaut_ID,Name,Country) VALUES (1,'Alice Johnson','USA'),(2,'Bruce Lee','China'),(3,'Carla Rodriguez','USA'),(4,'Diego Luna','Mexico'); INSERT INTO Missions (Mission_ID,Astronaut_ID) VALUES (1,1),(1,2),(2,3),(2,4);
SELECT Missions.Mission_ID FROM Astronauts INNER JOIN Missions ON Astronauts.Astronaut_ID = Missions.Astronaut_ID WHERE Astronauts.Country IN ('USA', 'China') GROUP BY Missions.Mission_ID HAVING COUNT(DISTINCT Astronauts.Country) = 2;
Delete sustainable urbanism projects with a cost over $500,000.
CREATE TABLE SustainableUrbanismProjects (ProjectID INT,ProjectName VARCHAR(50),Cost DECIMAL(10,2)); INSERT INTO SustainableUrbanismProjects (ProjectID,ProjectName,Cost) VALUES (1,'Project X',450000.00),(2,'Project Y',650000.00),(3,'Project Z',525000.00);
DELETE FROM SustainableUrbanismProjects WHERE Cost > 500000.00;
What was the number of disaster response operations in Colombia in 2019?
CREATE TABLE disaster_response (disaster_name VARCHAR(255),country VARCHAR(255),operation_start_date DATE,operation_end_date DATE); INSERT INTO disaster_response (disaster_name,country,operation_start_date,operation_end_date) VALUES ('Flood','Colombia','2019-01-01','2019-04-30'),('Earthquake','Colombia','2019-10-01','2019-12-31');
SELECT COUNT(*) FROM disaster_response WHERE country = 'Colombia' AND YEAR(operation_start_date) = 2019 AND YEAR(operation_end_date) = 2019;
Calculate the average biomass for marine life research projects in the Atlantic Ocean
CREATE TABLE marine_life_research (id INT,project_name TEXT,biomass FLOAT,ocean TEXT);
SELECT AVG(biomass) FROM marine_life_research WHERE ocean = 'Atlantic';
What AI algorithms were created between 2018 and 2019?
CREATE TABLE safe_algorithm (id INT,name VARCHAR(50),description TEXT,created_date DATE); INSERT INTO safe_algorithm (id,name,description,created_date) VALUES (1,'SHAP','An explainable AI technique...','2018-05-01'),(2,'Lime','Another explainable AI technique...','2019-02-03');
SELECT * FROM safe_algorithm WHERE created_date BETWEEN '2018-01-01' AND '2019-12-31';
List all tables in the "public" schema that have more than 100 rows?
CREATE TABLE IF NOT EXISTS public.example_table2 (id SERIAL PRIMARY KEY,data TEXT); INSERT INTO public.example_table2 (data) SELECT 'example' FROM generate_series(1,150);
SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' AND table_type = 'BASE TABLE' AND (SELECT COUNT(*) FROM information_schema.columns WHERE table_schema = table_name.table_schema AND table_name = table_name.table_name) > 0 GROUP BY table_name HAVING COUNT(*) > 100;
What is the total number of players who use VR technology in Asia?
CREATE TABLE players (id INT,location VARCHAR(20),uses_vr BOOLEAN); INSERT INTO players (id,location,uses_vr) VALUES (1,'China',TRUE),(2,'Japan',FALSE),(3,'India',TRUE);
SELECT COUNT(*) FROM players WHERE location LIKE 'Asia%' AND uses_vr = TRUE;
Insert a new record for 'New York' with a temperature of 32 degrees on '2022-12-25'.
CREATE TABLE weather (city VARCHAR(255),temperature FLOAT,date DATE);
INSERT INTO weather (city, temperature, date) VALUES ('New York', 32, '2022-12-25');
What is the average flight time for each aircraft model in the Indian and Brazilian fleets, grouped by the manufacturer?
CREATE TABLE indian_fleet(model VARCHAR(255),flight_time INT);CREATE TABLE brazilian_fleet(model VARCHAR(255),flight_time INT);
SELECT 'Indian' as Manufacturer, AVG(flight_time) as Avg_Flight_Time FROM indian_fleet GROUP BY Manufacturer UNION ALL SELECT 'Brazilian' as Manufacturer, AVG(flight_time) as Avg_Flight_Time FROM brazilian_fleet GROUP BY Manufacturer;
How many size 2XL and 3XL sustainable clothing items were sold in 2021?
CREATE TABLE SalesData (SalesID INT,Salesperson TEXT,ItemID INT,SalesDate DATE,Size INT,Sustainable BOOLEAN); INSERT INTO SalesData (SalesID,Salesperson,ItemID,SalesDate,Size,Sustainable) VALUES (1,'John Doe',1,'2021-01-01',2,true),(2,'Jane Smith',2,'2021-02-01',3,true),(3,'Bob Johnson',3,'2021-03-01',2,false),(4,'Alice Williams',4,'2021-04-01',1,true),(5,'Charlie Brown',5,'2021-05-01',3,false);
SELECT SUM(CASE WHEN Size IN (2,3) AND Sustainable = true THEN 1 ELSE 0 END) as CountOfSales FROM SalesData WHERE SalesDate BETWEEN '2021-01-01' AND '2021-12-31';
Identify the top 5 countries with the highest social impact investments in 2022
CREATE TABLE country_investments (id INT,country VARCHAR(50),investment_amount FLOAT,investment_date DATE); INSERT INTO country_investments (id,country,investment_amount,investment_date) VALUES (1,'United States',500000,'2022-01-01'); INSERT INTO country_investments (id,country,investment_amount,investment_date) VALUES (2,'Canada',350000,'2022-02-15'); INSERT INTO country_investments (id,country,investment_amount,investment_date) VALUES (3,'Mexico',220000,'2022-03-27');
SELECT country, SUM(investment_amount) as total_investment FROM country_investments GROUP BY country ORDER BY total_investment DESC LIMIT 5;