0% found this document useful (0 votes)
8 views2 pages

SQL LeetCode Optimized Solutions Part1

The document outlines SQL LeetCode problems with both normal and optimized solutions. It includes examples for combining tables, finding the second and nth highest salaries, ranking scores, and identifying consecutive numbers. Each problem is presented with a standard approach followed by a more efficient SQL query solution.

Uploaded by

maheshu1216
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views2 pages

SQL LeetCode Optimized Solutions Part1

The document outlines SQL LeetCode problems with both normal and optimized solutions. It includes examples for combining tables, finding the second and nth highest salaries, ranking scores, and identifying consecutive numbers. Each problem is presented with a standard approach followed by a more efficient SQL query solution.

Uploaded by

maheshu1216
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

SQL LeetCode Problems with Optimized Solutions

1. Combine Two Tables

Normal Approach:

SELECT p.FirstName, p.LastName, a.City, a.State

FROM Person p

LEFT JOIN Address a ON p.PersonId = a.PersonId;

Optimized Approach:

SELECT p.FirstName, p.LastName, COALESCE(a.City, 'N/A') AS City, COALESCE(a.State, 'N/A')

AS State

FROM Person p

LEFT JOIN Address a ON p.PersonId = a.PersonId;

2. Second Highest Salary

Normal Approach:

SELECT DISTINCT Salary FROM Employee

ORDER BY Salary DESC LIMIT 1 OFFSET 1;

Optimized Approach:

SELECT MAX(Salary) AS SecondHighestSalary FROM Employee

WHERE Salary < (SELECT MAX(Salary) FROM Employee);

3. Nth Highest Salary

Normal Approach:

SELECT DISTINCT Salary FROM Employee

ORDER BY Salary DESC LIMIT 1 OFFSET N-1;


Optimized Approach:

SELECT Salary FROM (

SELECT Salary, DENSE_RANK() OVER (ORDER BY Salary DESC) AS Rank

FROM Employee

) tmp WHERE Rank = N;

4. Rank Scores

Normal Approach:

-- Manual increment of rank (not efficient)

Optimized Approach:

SELECT Score, DENSE_RANK() OVER (ORDER BY Score DESC) AS Rank FROM Scores;

5. Consecutive Numbers

Normal Approach:

SELECT DISTINCT L1.Num FROM Logs L1, Logs L2, Logs L3

WHERE L1.Id = L2.Id - 1 AND L2.Id = L3.Id - 1

AND L1.Num = L2.Num AND L2.Num = L3.Num;

Optimized Approach:

SELECT DISTINCT Num FROM (

SELECT Num, LAG(Num,1) OVER (ORDER BY Id) AS prev1,

LAG(Num,2) OVER (ORDER BY Id) AS prev2

FROM Logs

) tmp WHERE Num = prev1 AND Num = prev2;

You might also like