A growing collection of SQL problem solutions and database setup scripts designed for practice, review, and continued learning in relational database querying.
This repository focuses on real-world SQL patterns such as joins, filtering, aggregation, and edge-case handling, with examples aligned to LeetCode-style data challenges.
Each problem folder contains:
schema.sql— table definitions and sample datasolution.sql— the query logic used to solve the challenge
The repository currently includes solutions for thirteen classic SQL problems:
Combine Two TablesSecond Highest SalaryNth Highest SalaryRank ScoresConsecutive NumbersEmployees Earning More Than Their ManagersDuplicate EmailsCustomers Who Never OrderDepartment Highest SalaryDepartment Top Three SalariesDelete Duplicate EmailsRising TemperatureTrips and Users
advanced-sql-queries/
├── README.md
└── LeetCode/
├── 0175_combine_two_tables/
│ ├── schema.sql
│ └── solution.sql
├── 0176_second_highest_salary/
│ ├── schema.sql
│ └── solution.sql
├── 0177_nth_highest_salary/
│ ├── schema.sql
│ └── solution.sql
├── 0178_rank_scores/
│ ├── schema.sql
│ └── solution.sql
├── 0180_consecutive_numbers/
│ ├── schema.sql
│ └── solution.sql
├── 0181_employees_earning_more_than_their_managers/
│ ├── schema.sql
│ └── solution.sql
├── 0182_duplicate_emails/
│ ├── schema.sql
│ └── solution.sql
├── 0183_customers_who_never_order/
│ ├── schema.sql
│ └── solution.sql
├── 0184_department_highest_salary/
│ ├── schema.sql
│ └── solution.sql
├── 0185_department_top_three_salaries/
│ ├── schema.sql
│ └── solution.sql
├── 0196_delete_duplicate_emails/
│ ├── schema.sql
│ └── solution.sql
├── 0197_rising_temperature/
├── schema.sql
└── solution.sql
└── 0262_trips_and_users/
├── schema.sql
└── solution.sql
This problem demonstrates the effective use of a LEFT JOIN to preserve all records from the Person table while returning matched Address data when it exists.
Key concept:
- Keep every person in the result set
- Return
NULLvalues forcityandstatewhen no address row matches
The solution is implemented in:
LeetCode/0175_combine_two_tables/solution.sql
This problem demonstrates how to retrieve the second-highest distinct salary while handling the edge case where no second salary exists.
Key concept:
- Use
DISTINCTto eliminate duplicate salary values - Sort in descending order and skip the top result with
LIMIT 1 OFFSET 1 - Wrap the query in an outer
SELECTso the result becomesNULLwhen the subquery is empty
The solution is implemented in:
LeetCode/0176_second_highest_salary/solution.sql
This problem demonstrates how to retrieve the Nth-highest distinct salary while returning NULL if fewer than N distinct salaries exist.
Key concept:
- Reject non-positive N values by returning
NULL - Decrement N to convert the requested rank to a zero-based offset
- Use
DISTINCTand descending order to find the requested salary
The solution is implemented in:
LeetCode/0177_nth_highest_salary/solution.sql
This problem demonstrates how to rank scores in descending order while assigning tied scores the same rank and leaving no gaps.
Key concept:
- Use
DENSE_RANK()as a window function to assign consecutive ranks across ties - Order the final results by score descending
The solution is implemented in:
LeetCode/0178_rank_scores/solution.sql
This problem demonstrates how to detect values that appear at least three times in consecutive rows based on the id ordering.
Key concept:
- Use window functions such as
LAG()andLEAD()to compare each record with its immediate neighbors - Filter for rows where the current value matches both adjacent values
- Remove duplicates with
DISTINCTto keep the result set clean
The solution is implemented in:
LeetCode/0180_consecutive_numbers/solution.sql
This problem demonstrates how to compare employee salaries with those of their managers using a self-join.
Key concept:
- Join
Employeeto itself to connect each employee with the row identified bymanagerId - Exclude top-level employees whose
managerIdisNULL - Filter for employees whose salary is greater than their manager's salary
The solution is implemented in:
LeetCode/0181_employees_earning_more_than_their_managers/solution.sql
This problem demonstrates how to identify email addresses that occur more than once.
Key concept:
- Group rows by email
- Use
HAVING COUNT(*) > 1to return only duplicate email addresses
The solution is implemented in:
LeetCode/0182_duplicate_emails/solution.sql
This problem demonstrates how to find records from one table that have no matching row in another table.
Key concept:
- Use a
LEFT JOINto preserve every customer - Match orders through
customerId - Filter with
o.id IS NULLto keep customers who have never placed an order
The solution is implemented in:
LeetCode/0183_customers_who_never_order/solution.sql
This problem demonstrates how to rank employee salaries within each department and return every highest-paid employee.
Key concept:
- Use
RANK()withPARTITION BY departmentIdto rank salaries independently per department - Order salaries descending inside each department
- Filter for rank
1to include top earners, including salary ties
The solution is implemented in:
LeetCode/0184_department_highest_salary/solution.sql
This problem demonstrates how to return employees earning one of the three highest distinct salaries in each department.
Key concept:
- Use
DENSE_RANK()withPARTITION BY departmentIdto rank salaries independently per department - Order salaries descending so employees with the same salary share a rank
- Filter for ranks
1through3to include ties without skipping salary ranks
The solution is implemented in:
LeetCode/0185_department_top_three_salaries/solution.sql
This problem demonstrates how to remove duplicate rows while keeping the row with the smallest ID for each email address.
Key concept:
- Self-join the
Persontable on matching email addresses - Delete the row with the larger ID in each matching pair
- Preserve the row with the smallest ID for every email
The solution is implemented in:
LeetCode/0196_delete_duplicate_emails/solution.sql
This problem demonstrates how to compare each day's temperature with the temperature on the previous calendar day.
Key concept:
- Self-join the
Weathertable to match each date with the date exactly one day earlier - Use
DATEDIFF()so missing calendar dates do not get treated as consecutive days - Return the ID of each day whose temperature is higher than the previous day's
The solution is implemented in:
LeetCode/0197_rising_temperature/solution.sql
This problem demonstrates how to calculate a daily cancellation rate while excluding trips involving banned clients or drivers.
Key concept:
- Join
TripstoUsersseparately for the client and driver - Keep only trips where both users are not banned
- Use conditional aggregation to count canceled trips and divide by all eligible trips for each day
- Round the daily rate to two decimal places
The solution is implemented in:
LeetCode/0262_trips_and_users/solution.sql
Run the schema script first to create the required tables and sample data for a challenge:
SOURCE LeetCode/0175_combine_two_tables/schema.sql;Then run the matching solution query:
SOURCE LeetCode/0175_combine_two_tables/solution.sql;To work with the second-highest-salary challenge instead:
SOURCE LeetCode/0176_second_highest_salary/schema.sql;
SOURCE LeetCode/0176_second_highest_salary/solution.sql;For the Nth-highest-salary challenge:
SOURCE LeetCode/0177_nth_highest_salary/schema.sql;
SOURCE LeetCode/0177_nth_highest_salary/solution.sql;For the rank-scores challenge:
SOURCE LeetCode/0178_rank_scores/schema.sql;
SOURCE LeetCode/0178_rank_scores/solution.sql;For the consecutive-numbers challenge:
SOURCE LeetCode/0180_consecutive_numbers/schema.sql;
SOURCE LeetCode/0180_consecutive_numbers/solution.sql;For the employees-earning-more-than-managers challenge:
SOURCE LeetCode/0181_employees_earning_more_than_their_managers/schema.sql;
SOURCE LeetCode/0181_employees_earning_more_than_their_managers/solution.sql;For the duplicate-emails challenge:
SOURCE LeetCode/0182_duplicate_emails/schema.sql;
SOURCE LeetCode/0182_duplicate_emails/solution.sql;For the customers-who-never-order challenge:
SOURCE LeetCode/0183_customers_who_never_order/schema.sql;
SOURCE LeetCode/0183_customers_who_never_order/solution.sql;For the department-highest-salary challenge:
SOURCE LeetCode/0184_department_highest_salary/schema.sql;
SOURCE LeetCode/0184_department_highest_salary/solution.sql;For the department-top-three-salaries challenge:
SOURCE LeetCode/0185_department_top_three_salaries/schema.sql;
SOURCE LeetCode/0185_department_top_three_salaries/solution.sql;For the delete-duplicate-emails challenge:
SOURCE LeetCode/0196_delete_duplicate_emails/schema.sql;
SOURCE LeetCode/0196_delete_duplicate_emails/solution.sql;For the rising-temperature challenge:
SOURCE LeetCode/0197_rising_temperature/schema.sql;
SOURCE LeetCode/0197_rising_temperature/solution.sql;For the trips-and-users challenge:
SOURCE LeetCode/0262_trips_and_users/schema.sql;
SOURCE LeetCode/0262_trips_and_users/solution.sql;If you are using a MySQL client directly, the equivalent commands are:
mysql -u <username> -p < LeetCode/0175_combine_two_tables/schema.sql
mysql -u <username> -p < LeetCode/0175_combine_two_tables/solution.sql
mysql -u <username> -p < LeetCode/0176_second_highest_salary/schema.sql
mysql -u <username> -p < LeetCode/0176_second_highest_salary/solution.sql
mysql -u <username> -p < LeetCode/0177_nth_highest_salary/schema.sql
mysql -u <username> -p < LeetCode/0177_nth_highest_salary/solution.sql
mysql -u <username> -p < LeetCode/0178_rank_scores/schema.sql
mysql -u <username> -p < LeetCode/0178_rank_scores/solution.sql
mysql -u <username> -p < LeetCode/0180_consecutive_numbers/schema.sql
mysql -u <username> -p < LeetCode/0180_consecutive_numbers/solution.sql
mysql -u <username> -p < LeetCode/0181_employees_earning_more_than_their_managers/schema.sql
mysql -u <username> -p < LeetCode/0181_employees_earning_more_than_their_managers/solution.sql
mysql -u <username> -p < LeetCode/0182_duplicate_emails/schema.sql
mysql -u <username> -p < LeetCode/0182_duplicate_emails/solution.sql
mysql -u <username> -p < LeetCode/0183_customers_who_never_order/schema.sql
mysql -u <username> -p < LeetCode/0183_customers_who_never_order/solution.sql
mysql -u <username> -p < LeetCode/0184_department_highest_salary/schema.sql
mysql -u <username> -p < LeetCode/0184_department_highest_salary/solution.sql
mysql -u <username> -p < LeetCode/0185_department_top_three_salaries/schema.sql
mysql -u <username> -p < LeetCode/0185_department_top_three_salaries/solution.sql
mysql -u <username> -p < LeetCode/0196_delete_duplicate_emails/schema.sql
mysql -u <username> -p < LeetCode/0196_delete_duplicate_emails/solution.sql
mysql -u <username> -p < LeetCode/0197_rising_temperature/schema.sql
mysql -u <username> -p < LeetCode/0197_rising_temperature/solution.sql
mysql -u <username> -p < LeetCode/0262_trips_and_users/schema.sql
mysql -u <username> -p < LeetCode/0262_trips_and_users/solution.sqlSELECT
p.firstName,
p.lastName,
a.city,
a.state
FROM Person p
LEFT JOIN Address a
ON p.personId = a.personId;This ensures:
- all records from
Personare returned - matching
Addressvalues appear when available - missing addresses remain
NULL
SELECT (
SELECT DISTINCT salary
FROM Employee
ORDER BY salary DESC
LIMIT 1 OFFSET 1
) AS "SecondHighestSalary";This ensures:
- only distinct salaries are considered
- the highest salary is skipped to reach the second value
- the result is
NULLwhen no second salary exists
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
IF N <= 0 THEN
RETURN NULL;
END IF;
SET N = N - 1;
RETURN (
SELECT DISTINCT salary
FROM Employee
ORDER BY salary DESC
LIMIT 1 OFFSET N
);
ENDThis ensures:
- only distinct salaries are ranked
- the requested rank maps to the correct zero-based offset
NULLis returned for non-positive N or when fewer than N distinct salaries exist
SELECT
score,
DENSE_RANK() OVER (ORDER BY score DESC) AS 'rank'
FROM Scores
ORDER BY score DESC;This ensures:
- tied scores share the same rank
- ranks remain consecutive with no gaps
- results are returned in descending score order
WITH ConsecutiveCheck AS (
SELECT
num,
LAG(num, 1) OVER (ORDER BY id) AS prev_num,
LEAD(num, 1) OVER (ORDER BY id) AS next_num
FROM Logs
)
SELECT DISTINCT
num AS ConsecutiveNums
FROM ConsecutiveCheck
WHERE num = prev_num
AND num = next_num;This ensures:
- each value is compared with the values immediately before and after it
- only repeated values that remain unchanged across three consecutive rows are kept
DISTINCTprevents duplicate values from appearing multiple times in a run
SELECT
e.name AS Employee
FROM Employee e
INNER JOIN Employee m
ON e.managerId = m.id
WHERE e.salary > m.salary;This ensures:
- each employee is paired with the matching manager row
- employees without a manager are excluded naturally
- only employees earning more than their manager are returned
SELECT
email AS Email
FROM Person
GROUP BY email
HAVING COUNT(*) > 1;This ensures:
- each email address is considered as a group
- only email addresses occurring more than once are returned
SELECT
c.name AS Customers
FROM Customers c
LEFT JOIN Orders o
ON c.id = o.customerId
WHERE o.id IS NULL;This ensures:
- every customer is considered
- customers with matching orders are excluded
- customers with no matching order remain in the result set
WITH RankedSalaries AS (
SELECT
d.name AS Department,
e.name AS Employee,
e.salary AS Salary,
RANK() OVER (
PARTITION BY e.departmentId
ORDER BY e.salary DESC
) AS rnk
FROM Employee e
INNER JOIN Department d
ON e.departmentId = d.id
)
SELECT Department, Employee, Salary
FROM RankedSalaries
WHERE rnk = 1;This ensures:
- salaries are ranked independently for each department
- the highest salary earns rank
1 - employees tied for the highest salary are all returned
WITH RankedSalaries AS (
SELECT
d.name AS Department,
e.name AS Employee,
e.salary AS Salary,
DENSE_RANK() OVER (
PARTITION BY e.departmentId
ORDER BY e.salary DESC
) AS rnk
FROM Employee e
INNER JOIN Department d
ON e.departmentId = d.id
)
SELECT Department, Employee, Salary
FROM RankedSalaries
WHERE rnk <= 3;This ensures:
- salaries are ranked independently for each department
- employees with equal salaries share a rank
- the top three distinct salary levels are returned, including all ties
DELETE p1
FROM Person p1
INNER JOIN Person p2
ON p1.email = p2.email
AND p1.id > p2.id;This ensures:
- rows with the same email are matched
- the row with the larger ID is deleted
- the row with the smallest ID is retained for each email
SELECT
w1.id
FROM Weather w1
INNER JOIN Weather w2
ON DATEDIFF(w1.recordDate, w2.recordDate) = 1
WHERE w1.temperature > w2.temperature;This ensures:
- each date is compared only with the exact previous calendar day
- missing dates do not cause non-consecutive records to be compared
- only IDs with a higher temperature than the previous day are returned
SELECT
t.request_at AS Day,
ROUND(
1.0 * SUM(CASE WHEN t.status != 'completed' THEN 1 ELSE 0 END) / COUNT(*),
2
) AS "Cancellation Rate"
FROM Trips t
INNER JOIN Users c
ON t.client_id = c.users_id
AND c.banned = 'No'
INNER JOIN Users d
ON t.driver_id = d.users_id
AND d.banned = 'No'
WHERE t.request_at BETWEEN '2013-10-01' AND '2013-10-03'
GROUP BY t.request_at;This ensures:
- trips involving a banned client or driver are excluded
- canceled trips are counted against all eligible trips on each day
- each daily cancellation rate is rounded to two decimal places
This repository is intended to:
- strengthen SQL fundamentals
- practice reading and writing production-style queries
- compare common patterns such as joins, window functions, and subqueries
- build confidence solving LeetCode-style SQL challenges in a structured way
- build a reusable archive of challenge-based solutions
- document problem-solving logic clearly and consistently
This project is designed to expand over time with additional LeetCode problem solutions, each organized in its own folder with schema and answer scripts.
This repository is provided for educational and learning purposes.