SQL LeetCode
Ranking
176. Second Highest Salary
1 | DROP TABLE IF EXISTS Employee; |
Approach: Using sub-query and LIMIT clause [Accepted] 273 ms
- ORDER BY Salary DESC
- The second one
- LIMIT 1 OFFSET 1
1 | SELECT |
However, this solution will be judged as ‘Wrong Answer’ if there is no such second highest salary since there might be only one record in this table. To overcome this issue, we can take this as a temp table.
1 | SELECT |
Approach: RANK() and CTE
1 | WITH CTE AS |
177. Nth Highest Salary
1 | Create table If Not Exists Employee (Id int, Salary int); |
Approach: FUNCTION, DENSE_RANK(), and CTE
1 | CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT |
184. Department Highest Salary
1 | DROP TABLE IF Exists Employee; |
Approach Using JOIN
and IN
clause [Accepted] 590 ms
1 | -- Select hightest salary group by DepartmentId |
185. Department Top Three Salaries
Schema
1 | Drop table IF Exists Employee; |
Approach: CTE and DENSE_RANK()
1 | WITH CTE AS |
178. Rank Scores
1 | DROP TABLE IF EXISTS Scores; |
Approach: Window Function 251 ms
1 | SELECT |
Approach: NO Window Function 861 ms
Get the distinct score rank
1 | SELECT |
Get the rank
1 | SELECT( |
Get the Score and Rank
1 | SELECT Score, |
511. Game Play Analysis I
1 | DROP TABLE IF EXISTS Activity; |
Approach: CTE and RANK
1 | WITH CTE AS |
512. Game Play Analysis II
1 | DROP TABLE IF EXISTS Activity; |
Approach: CTE and DENSE_RANK
1 | WITH CTE AS |
JOIN
175. Combine Two Tables
1 | DROP TABLE IF EXISTS Person; |
Approach: Using outer join [Accepted] 299 ms
Algorithm
Since the PersonId in table Address is the foreign key of table Person, we can join this two table to get the address information of a person.
Considering there might not be an address information for every person, we should use outer join instead of the default inner join.
1 | SELECT FirstName, LastName, City, State |
181. Employees Earning More Than Their Managers
1 | DROP TABLE IF EXISTS Employee; |
Approach: Using WHERE clause [Accepted] 289 ms
As this table has the employee’s manager information, we probably need to select information from it twice.
1 | SELECT |
Approach: Using JOIN clause [Accepted] 300 ms
Actually, JOIN is a more common and efficient way to link tables together, and we can use ON to specify some conditions.
1 | SELECT |
1587. Bank Account Summary II
1 | DROP TABLE IF EXISTS Users; |
Approach
1 | SELECT u.name, SUM(t.amount) AS `balance` |
Duplicate Records
196. Delete Duplicate Emails
1 | DROP TABLE IF EXISTS Person; |
Approach: Using WHERE clause 2000 ms
– By joining this table with itself on the Email column, we can get the following code.
1 | SELECT |
Then we need to find the bigger id having same email address with other records. So we can add a new condition to the WHERE clause like this.
1 | SELECT |
As we already get the records to be deleted, we can alter this statement to DELETE
in the end.
1 | DELETE |
Approach: Using GROUP BY Statement 1437 ms
SELECT * FROM Person with Minimum Id
1 | SELECT |
DELETE Records not in the above SELECT query
1 | DELETE FROM |
182. Duplicate Emails
1 | DROP TABLE IF EXISTS Person; |
Approach: Using Subquery 285 ms
1 | SELECT |
Approach: Using GROUP BY and a temporary table [Accepted] 253 ms
1 | SELECT |
Approach: Using GROUP BY and HAVING condition [Accepted]
1 | SELECT Email |
SWAP
627. Swap Salary 204 ms
1 | DROP TABLE IF EXISTS Salary; |
Approach: Using IF function 200 ms
1 | UPDATE |
Approach: Using UPDATE and CASE…WHEN [Accepted] 208 ms
1 | UPDATE Salary |
626. Exchange Seats
1 | DROP TABLE IF EXISTS seat; |
Approach: CASE 270 ms
1 | SELECT |
Reformat
1179. Reformat Department Table 440 ms
1 | DROP TABLE IF EXISTS Department; |
1 | SELECT id, |
1777. Product’s Price for Each Store
1 | DROP TABLE IF EXISTS Products; |
Approach 394 ms
1 | SELECT product_id, |
Difference
197. Rising Temperature
1 | DROP TABLE IF EXISTS Weather; |
Approach: Using Subquery and DATEDIFF() clause 408 ms
1 | SELECT |
Approach: Using JOIN and DATEDIFF() clause [Accepted] 394 ms
Algorithm
MySQL uses DATEDIFF to compare two date type values.
So, we can get the result by joining this table weather with itself and use this DATEDIFF() function.
1 | SELECT |
REGEXP
1517. Find Users With Valid E-Mails
1 | DROP TABLE IF EXISTS Users; |
Approach REGEXP 600 ms
1 | /* |
IN or NOT IN
183. Customers Who Never Order 373 ms
1 | DROP TABLE IF EXISTS Customers; |
Approach: Using NOT IN Clause
1 | SELECT |
IF, CASE
610. Triangle Judgement
1 | DROP TABLE If Exists triangle; |
Approach: Using CASE statement 224 ms
1 | SELECT x, y, z, |
Approach: Using IF function 227 ms
1 | SELECT |
Statistics
597. Friend Requests I: Overall Acceptance Rate
1 | Create table If Not Exists FriendRequest (sender_id int, send_to_id int, request_date date); |
Approach: Subquery 471 ms
1 | SELECT ROUND( |
Approach 430 ms
1 | SELECT |
1661. Average Time of Process per Machine
1 | Create table If Not Exists Activity (machine_id int, process_id int, activity_type ENUM('start', 'end'), timestamp float); |
Approach 186 ms
1 | -- Split the start, end in a table |
1173. Immediate Food Delivery I
1 | Create table If Not Exists Delivery (delivery_id int, customer_id int, order_date date, customer_pref_delivery_date date); |
1 | SELECT ROUND( |
1435. Create a Session Bar Chart
1 | Create table If Not Exists Sessions (session_id int, duration int); |
Approach 370 ms
1 | -- No counting 0 |
1211. Queries Quality and Percentage
1 | Create table If Not Exists Queries (query_name varchar(30), result varchar(50), position int, rating int); |
1 | SELECT |
1511. Customer Order Frequency
1 | Create table If Not Exists Customers (customer_id int, name varchar(30), country varchar(30)); |
Approach 716 ms
1 | -- Extract name, price, quantity, month |
WHERE
1757. Recyclable and Low Fat Products
1 | DROP TABLE IF EXISTS Products; |
Approach 428 ms
1 | SELECT product_id |
1141. User Activity for the Past 30 Days I
1 | Create table If Not Exists Activity (user_id int, session_id int, activity_date date, activity_type ENUM('open_session', 'end_session', 'scroll_down', 'send_message')); |
Approach 353 ms
1 | SELECT activity_date AS day, COUNT(DISTINCT user_id) AS active_users |
1142. User Activity for the Past 30 Days II
1 | Create table If Not Exists Activity (user_id int, session_id int, activity_date date, activity_type ENUM('open_session', 'end_session', 'scroll_down', 'send_message')); |
Approach 443ms
1 | SELECT IFNULL( |
603. Consecutive Available Seats
1 | Create table If Not Exists cinema (seat_id int primary key auto_increment, free bool); |
1 | SELECT seat_id |
620. Not Boring Movies
1 | Create table If Not Exists cinema (id int, movie varchar(255), description varchar(255), rating float(2, 1)); |
Approach 181 ms
1 | SELECT * |
1350. Students With Invalid Departments
1 | Create table If Not Exists Departments (id int, name varchar(30)); |
Approach 670 ms
1 | SELECT id, name |
1623. All Valid Triplets That Can Represent a Country
1 | Create table If Not Exists SchoolA (student_id int, student_name varchar(20)); |
1 | -- Union all records from three schools and give each a school label |
613. Shortest Distance in a Line
1 | DROP TABLE IF EXISTS point; |
Approach 200 ms
1 | -- Get the distances of each two points |
607. Sales Person
1 | Create table If Not Exists salesperson (sales_id int, name varchar(255), salary int,commission_rate int, hire_date varchar(255)); |
Approach 1 885 ms
1 | SELECT |
Approach 2 1253 ms
1 | SELECT |
GROUP BY
596. Classes More Than 5 Students
1 | DROP TABLE IF EXISTS courses; |
Approach
1 | SELECT class |
1241. Number of Comments per Post
1 | Create table If Not Exists Submissions (sub_id int, parent_id int); |
Approach 2510 ms
1 | SELECT |
1050. Actors and Directors Who Cooperated At Least Three Times
1050. Actors and Directors Who Cooperated At Least Three Times
1 | Create table If Not Exists ActorDirector (actor_id int, director_id int, timestamp int); |
Approach 409 ms
1 | SELECT actor_id, director_id |
1280. Students and Examinations
1 | Create table If Not Exists Students (student_id int, student_name varchar(20)); |
Approach 657 ms
1 | SELECT Students.student_id, Students.student_name, Subjects.subject_name, COUNT(Examinations.student_id) AS attended_exams |
1084. Sales Analysis III
1 | Create table If Not Exists Product (product_id int, product_name varchar(10), unit_price int); |
Approach
1 | SELECT product_id, product_name |
1113. Reported Posts
1 | Create table If Not Exists Actions (user_id int, post_id int, action_date date, action ENUM('view', 'like', 'reaction', 'comment', 'report', 'share'), extra varchar(10)); |
Approach 505 ms
1 | SELECT |
1083. Sales Analysis II
1 | Create table If Not Exists Product (product_id int, product_name varchar(10), unit_price int); |
Approach 1008 ms
1 | SELECT |
586. Customer Placing the Largest Number of Orders
1 | Create table If Not Exists orders (order_number int, customer_number int); |
Approach 520 ms
1 | SELECT |
1741. Find Total Time Spent by Each Employee
1 | Create table If Not Exists Employees(emp_id int, event_day date, in_time int, out_time int); |
Approach 434 ms
1 | SELECT |
1731. The Number of Employees Which Report to Each Employee
1 | Create table If Not Exists Employees(employee_id int, name varchar(20), reports_to int, age int); |
Approach 712 ms
1 | SELECT |
1212. Team Scores in Football Tournament
1 | DROP TABLE IF EXISTS Teams; |
Approach 512 ms
1 | SELECT |
String
1667. Fix Names in a Table
1 | Create table If Not Exists Users (user_id int, name varchar(40)); |
Approach 678 ms
1 | -- SELECT 1st String |
Date
1543. Fix Product Name Format
1 | Create table If Not Exists Sales (sale_id int, product_name varchar(30), sale_date date); |
Approach 241ms
1 | -- Format product_name and sale_date |
Window Function
1303. Find the Team Size
1 | Create table If Not Exists Employee (employee_id int, team_id int); |
Approach 244 ms
1 | SELECT |
1596. The Most Frequently Ordered Products for Each Customer
1596. The Most Frequently Ordered Products for Each Customer
1 | DROP TABLE IF EXISTS Customers; |
Approach Window Function 1900 ms
1 | -- Window function, very slow |
Approach CTE 1800 ms
1 | -- CTE slow |
UNION
1789. Primary Department for Each Employee
1 | Create table If Not Exists Employee (employee_id int, department_id int, primary_flag ENUM('Y','N')); |
Approach 495 ms
1 | SELECT |
WITH RECURSION
1270. All People Report to the Given Manager
Schema
1 | DROP TABLE IF EXISTS Employees; |
Table Employees
1 | +---------------+---------+ |
employee_id
is the primary key for this table.Each row of this table indicates that the employee with ID
employee_id
and name employee_name reports his work to his/her direct manager withmanager_id
The head of the company is the employee with
employee_id
= 1.Write an SQL query to find employee_id of all employees that directly or indirectly report their work to the head of the company.
The indirect relation between managers will not exceed 3 managers as the company is small.
Return result table in any order without duplicates.
The query result format is in the following example:
Employees
table:
1 | +-------------+---------------+------------+ |
Result table:
1 | +-------------+ |
The head of the company is the employee with employee_id 1.
The employees with employee_id 2 and 77 report their work directly to the head of the company.
The employee with employee_id 4 report his work indirectly to the head of the company 4 –> 2 –> 1.
The employee with employee_id 7 report his work indirectly to the head of the company 7 –> 4 –> 2 –> 1.
The employees with employee_id 3, 8 and 9 don’t report their work to head of company directly or indirectly.
Solution 1: With head and initial node
The curical concetp of MySQL Recursive CTE is the first non-recursive query and the rest recursive queries.
MySQL | Recursive CTE (Common Table Expressions) By Tanvi_Garg
Solution 1 non-recursive query: using the head
as root node.
employee_id
: 1manager_id
: 1
Solution 1 recursive query: the partent node from every pervious iteration.
Root Node
1 | -- Select the head as root node |
employee_id | manager_id |
1 | 1 |
Solution 1: Path
1 | -- Solution 1: Path |
employee_id | manager_id |
1 | 1 |
2 | 2-->1 |
4 | 4-->2-->1 |
7 | 7-->4-->2-->1 |
77 | 77-->1 |
Solution 1: Answer
1 | -- Solution 1: Answer |
employee_id |
2 |
4 |
7 |
77 |
Solution 2: Without head and initial node
Solution 2 non-recursive query: the two second level nodes as root nodes.
employee_id
: 2 & 77 (employee_id != 1
)manager_id
: 1 (manager_id = 1
)
Solution 2 recursive query: the partent node from every pervious iteration.
Root Node
1 | -- Select the two second level nodes as root nodes |
employee_id | manager_id |
2 | 1 |
77 | 1 |
Solution 2: Path
1 | -- Solution 2: Path |
employee_id | manager_id |
2 | 1 |
4 | 4-->1 |
7 | 7-->4-->1 |
77 | 1 |
Solution 2: Answer
1 | -- Solution 2: Answer |
employee_id |
2 |
4 |
7 |
77 |
Consecutive
180. Consecutive Numbers
Schema
1 | DROP TABLE IF EXISTS Logs; |
Logs table:
1 | +----+-----+ |
Explanation
My idea is to join the Num
three times.
- For the 1st table Logs l1, keep it unmodified.
- For the 2nd table Logs l2, move all
Num
downside 1 row, which is equal to add 1 to allId
. - For the 3rd table Logs l3, move all
Num
downside 2 rows, which is equal to add 2 to allId
.
l1: SELECT Id, Num FROM Logs AS l1;
1 | +----+-----+ |
l2: SELECT Id+1 AS Id, Num FROM Logs AS l2;
1 | +----+-----+ |
l3: SELECT Id+1 AS Id, Num FROM Logs AS l2;
1 | +----+-----+ |
JOIN the three tables.
NOTICE we will lost the last 2 rows but it is absolutely fine. Because the last two rows only can be the part of consecutive numbers of the last third row. And the last two Num
are in the last record of l2 and the last record of l3.
1 | SELECT |
n1 | n2 | n3 |
1 | 1 | 1 |
2 | 1 | 1 |
1 | 2 | 1 |
2 | 1 | 2 |
2 | 2 | 1 |
Approach: JOIN 376 ms faster than 90% of MySQL solutions
1 | SELECT |
ConsecutiveNums |
---|
1 |
Approach 2: Using IN 474 ms
1 | SELECT |
Approach 3: Using WHERE 440 ms
1 | SELECT |
1 | SELECT |