- Published on
LeetCode SQL Problem Solving Questions With Solutions
LeetCode
175. Combine Two Tables | Easy |Table: Person
Table: Address
Write a SQL query for a report that provides the following information for each person in the Person table, regardless if there is an address for each of those people:
Solution
LeetCode
176. Second Highest Salary | Easy |Write a SQL query to get the second highest salary from the Employee
table.
For example, given the above Employee table, the query should return 200
as the second highest salary. If there is no second highest salary, then the query should return null
.
Solution
LeetCode
177. Nth Highest Salary | Medium |Write a SQL query to get the nth highest salary from the Employee table.
For example, given the above Employee table, the nth highest salary where n = 2 is 200. If there is no nth highest salary, then the query should return null.
Solution
LeetCode
178. Rank Scores | Medium |Write a SQL query to rank scores. If there is a tie between two scores, both should have the same ranking. Note that after a tie, the next ranking number should be the next consecutive integer value. In other words, there should be no "holes" between ranks.
For example, given the above Scores
table, your query should generate the following report (order by highest score):
Important Note: For MySQL solutions, to escape reserved words used as column names, you can use an apostrophe before and after the keyword. For example Rank
.
Solution
LeetCode
180. Consecutive Numbers | Medium |Table: Logs
Write an SQL query to find all numbers that appear at least three times consecutively.
Return the result table in any order.
The query result format is in the following example:
Solution
LeetCode
181. Employees Earning More Than Their Managers | Easy |The Employee
table holds all employees including their managers. Every employee has an Id, and there is also a column for the manager Id.
Given the Employee
table, write a SQL query that finds out employees who earn more than their managers. For the above table, Joe is the only employee who earns more than his manager.
Solution
LeetCode
182. Duplicate Emails | Easy |Write a SQL query to find all duplicate emails in a table named Person
.
For example, your query should return the following for the above table:
Note: All emails are in lowercase.
Solution
LeetCode
183. Customers Who Never Order | Easy |Suppose that a website contains two tables, the Customers
table and the Orders
table. Write a SQL query to find all customers who never order anything.
Table: Customers
.
Table: Orders
.
Using the above tables as example, return the following:
Solution
LeetCode
184. Department Highest Salary | Medium |The Employee
table holds all employees. Every employee has an Id, a salary, and there is also a column for the department Id.
The Department
table holds all departments of the company.
Write a SQL query to find employees who have the highest salary in each of the departments. For the above tables, your SQL query should return the following rows (order of rows does not matter).
Explanation:
Max and Jim both have the highest salary in the IT department and Henry has the highest salary in the Sales department.
Solution
LeetCode
185. Department Top Three Salaries | Hard |The Employee
table holds all employees. Every employee has an Id, and there is also a column for the department Id.
The Department
table holds all departments of the company.
Write a SQL query to find employees who earn the top three salaries in each of the department. For the above tables, your SQL query should return the following rows (order of rows does not matter).
Explanation:
In IT department, Max earns the highest salary, both Randy and Joe earn the second highest salary, and Will earns the third highest salary. There are only two employees in the Sales department, Henry earns the highest salary while Sam earns the second highest salary.
Solution
LeetCode
196. Delete Duplicate Emails | Easy |Write a SQL query to delete all duplicate email entries in a table named Person
, keeping only unique emails based on its smallest Id.
Id is the primary key column for this table. For example, after running your query, the above Person
table should have the following rows:
Note:
Your output is the whole Person
table after executing your sql. Use delete
statement.
Solution
LeetCode
197. Rising Temperature | Easy |Table: Weather
Write an SQL query to find all dates' id
with higher temperature compared to its previous dates (yesterday).
Return the result table in any order.
The query result format is in the following example:
Solution
LeetCode
262. Trips and Users | Hard |Table: Trips
Table: Users
Write a SQL query to find the cancellation rate of requests with unbanned users (both client and driver must not be banned) each day between "2013-10-01"
and "2013-10-03"
.
The cancellation rate is computed by dividing the number of canceled (by client or driver) requests with unbanned users by the total number of requests with unbanned users on that day.
Return the result table in any order. Round Cancellation Rate
to two decimal points.
The query result format is in the following example:
Solution
LeetCode
511. Game Play Analysis I | Easy | 🔒Table: Activity
Write an SQL query that reports the first login date for each player.
The query result format is in the following example:
Solution
LeetCode
512. Game Play Analysis II | Easy | 🔒Table: Activity
Write a SQL query that reports the device that is first logged in for each player.
The query result format is in the following example:
Solution
LeetCode
534. Game Play Analysis III | Medium | 🔒Table: Activity
Write an SQL query that reports for each player and date, how many games played so far by the player. That is, the total number of games played by the player until that date. Check the example for clarity.
The query result format is in the following example:
Solution
LeetCode
550. Game Play Analysis IV | Medium | 🔒Table: Activity
Write an SQL query that reports the fraction of players that logged in again on the day after the day they first logged in, rounded to 2 decimal places. In other words, you need to count the number of players that logged in for at least two consecutive days starting from their first login date, then divide that number by the total number of players.
The query result format is in the following example:
Solution
LeetCode
569. Median Employee Salary | Hard | 🔒The Employee
table holds all employees. The employee table has three columns: Employee Id, Company Name, and Salary.
Write a SQL query to find the median salary of each company. Bonus points if you can solve it without using any built-in SQL functions.
Solution
LeetCode
570. Managers with at Least 5 Direct Reports | Medium | 🔒The Employee
table holds all employees including their managers. Every employee has an Id, and there is also a column for the manager Id.
Given the Employee
table, write a SQL query that finds out managers with at least 5 direct report. For the above table, your SQL query should return:
Note: No one would report to himself.
Solution
LeetCode
571. Find Median Given Frequency of Numbers | 🔒The Numbers
table keeps the value of number and its frequency.
In this table, the numbers are 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 3, so the median is (0 + 0) / 2 = 0.
Write a query to find the median of all numbers and name the result as median.
Solution
LeetCode
574. Winning Candidate | Medium | 🔒Table: Candidate
Table: Vote
id
is the auto-increment primary key, CandidateId
is the id appeared in Candidate table. Write a sql to find the name of the winning candidate, the above example will return the winner B.
Notes: You may assume there is no tie, in other words there will be at most one winning candidate.
Solution
LeetCode
577. Employee Bonus | Easy | 🔒Select all employee’s name and bonus whose bonus is < 1000.
Table:Employee
Table: Bonus
Example ouput:
Solution
LeetCode
578. Get Highest Answer Rate Question | Medium | 🔒Get the highest answer rate question from a table survey_log with these columns: uid, action, question_id, answer_id, q_num, timestamp.
uid means user id; action has these kind of values: “show”, “answer”, “skip”; answer_id is not null when action column is “answer”, while is null for “show” and “skip”; q_num is the numeral order of the question in current session.
Write a sql query to identify the question which has the highest answer rate.
Example: Input:
Output:
Explanation: question 285 has answer rate 1/1, while question 369 has 0/1 answer rate, so output 285.
Note: The highest answer rate meaning is: answer number’s ratio in show number in the same question.
Solution
LeetCode
579. Find Cumulative Salary of an Employee | Hard | 🔒The Employee
table holds the salary information in a year.
Write a SQL to get the cumulative sum of an employee’s salary over a period of 3 months but exclude the most recent month.
The result should be displayed by ‘Id’ ascending, and then by ‘Month’ descending.
Example Input
Output
Explanation Employee ‘1’ has 3 salary records for the following 3 months except the most recent month ‘4’: salary 40 for month ‘3’, 30 for month ‘2’ and 20 for month ‘1’ So the cumulative sum of salary of this employee over 3 months is 90(40+30+20), 50(30+20) and 20 respectively.
Employee ‘2’ only has one salary record (month ‘1’) except its most recent month ‘2’.
Employ ‘3’ has two salary records except its most recent pay month ‘4’: month ‘3’ with 60 and month ‘2’ with 40. So the cumulative salary is as following.
Solution
LeetCode
580. Count Student Number in Departments | Medium | 🔒A university uses 2 data tables, student
and department
, to store data about its students and the departments associated with each major.
Write a query to print the respective department name and number of students majoring in each department for all departments in the department table (even ones with no current students).
Sort your results by descending number of students; if two or more departments have the same number of students, then sort those departments alphabetically by department name.
The student
is described as follow:
where student_id is the student’s ID number, student_name is the student’s name, gender is their gender, and dept_id is the department ID associated with their declared major.
And the department table is described as below:
where dept_id is the department’s ID number and dept_name is the department name.
Here is an example input: student
table:
department
table:
The Output should be:
Solution
LeetCode
584. Find Customer Referee | Easy | 🔒Given a table customer
holding customers information and the referee.
Write a query to return the list of customers NOT referred by the person with id ‘2’.
For the sample data above, the result is:
Solution
LeetCode
585. Investments in 2016 | Medium | 🔒Write a query to print the sum of all total investment values in 2016 (TIV_2016), to a scale of 2 decimal places, for all policy holders who meet the following criteria:
- Have the same TIV_2015 value as one or more other policyholders.
- Are not located in the same city as any other policyholder (i.e.: the (latitude, longitude) attribute pairs must be unique). Input Format: The insurance table is described as follows:
where PID is the policyholder’s policy ID, TIV_2015 is the total investment value in 2015, TIV_2016 is the total investment value in 2016, LAT is the latitude of the policy holder’s city, and LON is the longitude of the policy holder’s city.
Sample Input
Sample Output
Explanation
Solution
LeetCode
586. Customer Placing the Largest Number of Orders | Easy | 🔒Query the customer_number from the orders table for the customer who has placed the largest number of orders.
It is guaranteed that exactly one customer will have placed more orders than any other customer.
The orders table is defined as follows:
Sample Input
Sample Output
Explanation
Solution
LeetCode
595. Big Countries | Easy |There is a table World
A country is big if it has an area of bigger than 3 million square km or a population of more than 25 million.
Write a SQL solution to output big countries' name, population and area.
For example, according to the above table, we should output:
Solution
LeetCode
596. Classes More Than 5 Students | Easy |There is a table courses
with columns: student and class
Please list out all classes which have more than or equal to 5 students.
For example, the table:
Should output:
Solution
LeetCode
597. Friend Requests I: Overall Acceptance Rate | Easy | 🔒In social network like Facebook or Twitter, people send friend requests and accept others’ requests as well. Now given two tables as below: Table: friend_request
Table: request_accepted
Write a query to find the overall acceptance rate of requests rounded to 2 decimals, which is the number of acceptance divide the number of requests. For the sample data above, your query should return the following result.
Note:
The accepted requests are not necessarily from the table friend_request. In this case, you just need to simply count the total accepted requests (no matter whether they are in the original requests), and divide it by the number of requests to get the acceptance rate. It is possible that a sender sends multiple requests to the same receiver, and a request could be accepted more than once. In this case, the ‘duplicated’ requests or acceptances are only counted once. If there is no requests at all, you should return 0.00 as the accept_rate. Explanation: There are 4 unique accepted requests, and there are 5 requests in total. So the rate is 0.80.
Follow-up:
Can you write a query to return the accept rate but for every month? How about the cumulative accept rate for every day?
Solution
LeetCode
601. Human Traffic of Stadium | Hard |Table: Stadium
visit_date is the primary key for this table. Each row of this table contains the visit date and visit id to the stadium with the number of people during the visit. No two rows will have the same visit_date, and as the id increases, the dates increase as well.
Write an SQL query to display the records with three or more rows with consecutive id
's, and the number of people is greater than or equal to 100 for each.
Return the result table ordered by visit_date
in ascending order.
The query result format is in the following example.
Solution
LeetCode
602. Friend Requests II: Who Has the Most Friends | Medium | 🔒In social network like Facebook or Twitter, people send friend requests and accept others’ requests as well. Table request_accepted
holds the data of friend acceptance, while requester_id and accepter_id both are the id of a person.
Write a query to find the the people who has most friends and the most friends number. For the sample data above, the result is:
Note:
It is guaranteed there is only 1 people having the most friends. The friend request could only been accepted once, which mean there is no multiple records with the same requester_id and accepter_id value. Explanation: The person with id ‘3’ is a friend of people ‘1’, ‘2’ and ‘4’, so he has 3 friends in total, which is the most number than any others.
Follow-up: In the real world, multiple people could have the same most number of friends, can you find all these people in this case?
LeetCode
603. Consecutive Available Seats | Easy | 🔒Several friends at a cinema ticket office would like to reserve consecutive available seats. Can you help to query all the consecutive available seats order by the seat_id using the following cinema table?
Your query should return the following result for the sample case above.
Note:
The seat_id is an auto increment int, and free is bool (‘1’ means free, and ‘0’ means occupied.). Consecutive available seats are more than 2(inclusive) seats consecutively available.
Solution
LeetCode
607.Sales Person | Easy | 🔒Description
Given three tables: salesperson
, company
, orders
. Output all the names in the table salesperson, who didn’t have sales to company ‘RED’.
Example Input
Table: salesperson
The table salesperson holds the salesperson information. Every salesperson has a sales_id and a name. Table: company
The table company holds the company information. Every company has a com_id and a name. Table: orders
The table orders holds the sales record information, salesperson and customer company are represented by sales_id and com_id. output
Explanation
According to order ‘3’ and ‘4’ in table orders, it is easy to tell only salesperson ‘John’ and ‘Alex’ have sales to company ‘RED’, so we need to output all the other names in table salesperson.
Solution
LeetCode
608. Tree Node | Medium | 🔒Given a table tree, id is identifier of the tree node and p_id is its parent node’s id.
Each node in the tree can be one of three types:
Leaf: if the node is a leaf node. Root: if the node is the root of the tree. Inner: If the node is neither a leaf node nor a root node. Write a query to print the node id and the type of the node. Sort your output by the node id. The result for the above sample is:
Explanation
Node ‘1’ is root node, because its parent node is NULL and it has child node ‘2’ and ‘3’. Node ‘2’ is inner node, because it has parent node ‘1’ and child node ‘4’ and ‘5’. Node ‘3’, ‘4’ and ‘5’ is Leaf node, because they have parent node and they don’t have child node. And here is the image of the sample tree as below:
Note
If there is only one node on the tree, you only need to output its root attributes.
Solution
LeetCode
610. Triangle Judgement | Easy | 🔒A pupil Tim gets homework to identify whether three line segments could possibly form a triangle. However, this assignment is very heavy because there are hundreds of records to calculate. Could you help Tim by writing a query to judge whether these three sides can form a triangle, assuming table triangle holds the length of the three sides x, y and z.
For the sample data above, your query should return the follow result:
Solution
LeetCode
612. Shortest Distance in a Plane | Medium | 🔒Table point_2d holds the coordinates (x,y) of some unique points (more than two) in a plane. Write a query to find the shortest distance between these points rounded to 2 decimals.
The shortest distance is 1.00 from point (-1,-1) to (-1,2). So the output should be:
Note: The longest distance among all the points are less than 10000.
Solution
LeetCode
613. Shortest Distance in a Line | Easy | 🔒Table point holds the x coordinate of some points on x-axis in a plane, which are all integers. Write a query to find the shortest distance between two points in these points.
The shortest distance is ‘1’ obviously, which is from point ‘-1’ to ‘0’. So the output is as below:
Note: Every point is unique, which means there is no duplicates in table point.
Follow-up: What if all these points have an id and are arranged from the left most to the right most of x axis?
Solution
LeetCode
614. Second Degree Follower | Medium | 🔒In facebook, there is a follow table with two columns: followee, follower.
Please write a sql query to get the amount of each follower’s follower if he/she has one.
For example:
should output:
Explanation: Both B and D exist in the follower list, when as a followee, B’s follower is C and D, and D’s follower is E. A does not exist in follower list.
Note: Followee would not follow himself/herself in all cases. Please display the result in follower’s alphabet order.
Solution
LeetCode
615. Average Salary: Departments VS Company | Hard | 🔒Given two tables as below, write a query to display the comparison result (higher/lower/same) of the average salary of employees in a department to the company’s average salary. Table: salary
The employee_id column refers to the employee_id in the following table employee.
So for the sample data above, the result is:
Explanation In March, the company’s average salary is (9000+6000+10000)/3 = 8333.33… The average salary for department ‘1’ is 9000, which is the salary of employee_id ‘1’ since there is only one employee in this department. So the comparison result is ‘higher’ since 9000 > 8333.33 obviously. The average salary of department ‘2’ is (6000 + 10000)/2 = 8000, which is the average of employee_id ‘2’ and ‘3’. So the comparison result is ‘lower’ since 8000 < 8333.33. With he same formula for the average salary comparison in February, the result is ‘same’ since both the department ‘1’ and ‘2’ have the same average salary with the company, which is 7000.
Solution
LeetCode
618. Students Report By Geography | Hard | 🔒A U.S graduate school has students from Asia, Europe and America. The students’ location information are stored in table student as below.
Pivot the continent column in this table so that each name is sorted alphabetically and displayed underneath its corresponding continent. The output headers should be America, Asia and Europe respectively. It is guaranteed that the student number from America is no less than either Asia or Europe. For the sample input, the output is:
Follow-up: If it is unknown which continent has the most students, can you write a query to generate the student report?
Solution
LeetCode
619. Biggest Single Number | Easy | 🔒Table number contains many numbers in column num including duplicated ones. Can you write a SQL query to find the biggest number, which only appears once.
For the sample data above, your query should return the following result:
Note: If there is no such number, just output null.
Solution
LeetCode
620. Not Boring Movies | Easy |X city opened a new cinema, many people would like to go to this cinema. The cinema also gives out a poster indicating the movies’ ratings and descriptions. Please write a SQL query to output movies with an odd numbered ID and a description that is not 'boring'. Order the result by rating.
For example, table cinema
:
For the example above, the output should be:
Solution
LeetCode
626. Exchange Seats | Medium |Mary is a teacher in a middle school and she has a table seat
storing students' names and their corresponding seat ids.
The column id is continuous increment.
Mary wants to change seats for the adjacent students.
Can you write a SQL query to output the result for Mary?
For the sample input, the output is:
Note:
If the number of students is odd, there is no need to change the last one's seat.
Solution
LeetCode
627. Swap Salary |Table: Salary
Write an SQL query to swap all 'f'
and 'm'
values (i.e., change all 'f'
values to 'm'
and vice versa) with a single update statement and no intermediate temp table(s).
Note that you must write a single update statement, DO NOT write any select statement for this problem.
The query result format is in the following example:
Solution
LeetCode
1045. Customers Who Bought All Products | Medium | 🔒Table: Customer
product_key is a foreign key to Product table. Table: Product
Write an SQL query for a report that provides the customer ids from the Customer table that bought all the products in the Product table.
For example:
Solution
LeetCode
1050. Actors and Directors Who Cooperated At Least Three Times | Easy | 🔒Table: ActorDirector
Write a SQL query for a report that provides the pairs (actor_id, director_id) where the actor have cooperated with the director at least 3 times.
Example:
Solution
LeetCode
1068. Product Sales Analysis I | Easy | 🔒Table: Sales
Table: Product
Write an SQL query that reports all product names of the products in the Sales table along with their selling year and price.
For example:
Solution
LeetCode
1069. Product Sales Analysis II | Easy | 🔒Table: Sales
Table: Product
Write an SQL query that reports the total quantity sold for every product id.
The query result format is in the following example:
Solution
LeetCode
1070. Product Sales Analysis III | Medium | 🔒Table: Sales
Table: Product
Write an SQL query that selects the product id, year, quantity, and price for the first year of every product sold.
The query result format is in the following example:
Solution
LeetCode
1075. Project Employees I | Easy | 🔒Table: Project
Table: Employee
Write an SQL query that reports the average experience years of all the employees for each project, rounded to 2 digits.
The query result format is in the following example:
Solution
LeetCode
1076. Project Employees II | Easy | 🔒Table: Project
Table: Employee
Write an SQL query that reports all the projects that have the most employees.
The query result format is in the following example:
LeetCode
1077. Project Employees III | Medium | 🔒Table: Project
Table: Employee
Write an SQL query that reports the most experienced employees in each project. In case of a tie, report all employees with the maximum number of experience years.
The query result format is in the following example:
Solution
LeetCode
1082. Sales Analysis I | Easy | 🔒Table: Product
Table: Sales
Write an SQL query that reports the best seller by total sales price, If there is a tie, report them all.
The query result format is in the following example:
Solution
LeetCode
1083. Sales Analysis II | Easy | 🔒Table: Product
Table: Sales
Write an SQL query that reports the buyers who have bought S8 but not iPhone. Note that S8 and iPhone are products present in the Product table.
The query result format is in the following example:
Solution
LeetCode
1084. Sales Analysis III | Easy | 🔒Reports the products that were only sold in spring 2019. That is, between 2019-01-01 and 2019-03-31 inclusive. Select the product that were only sold in spring 2019.
Solution
LeetCode
1097. Game Play Analysis V | Hard | 🔒We define the install date of a player to be the first login day of that player. We also define day 1 retention of some date X to be the number of players whose install date is X and they logged back in on the day right after X , divided by the number of players whose install date is X, rounded to 2 decimal places. Write an SQL query that reports for each install date, the number of players that installed the game on that day and the day 1 retention. The query result format is in the following example:
Solution
LeetCode
1098. Unpopular Books | Medium | 🔒Table: Books
Table: Orders
Write an SQL query that reports the books that have sold less than 10 copies in the last year, excluding books that have been available for less than 1 month from today. Assume today is 2019-06-23.
The query result format is in the following example:
Solution
LeetCode
1107. New Users Daily Count | Medium | 🔒Table: Traffic
Write an SQL query that reports for every date within at most 90 days from today, the number of users that logged in for the first time on that date. Assume today is 2019-06-30.