SQL problems
LeetCode database problems, solved in PostgreSQL. Select PostgreSQL in LeetCode's language menu before submitting: the default is MySQL, and some solutions here use PostgreSQL syntax (DELETE … USING, PL/pgSQL functions).
Every solution was run on PostgreSQL 17 with the example data from the problem. The lessons are in 15_sql_databases.
| Problem | Technique | Lesson |
|---|---|---|
| 175. Combine Two Tables | LEFT JOIN |
joins |
| 176. Second Highest Salary | scalar subquery for NULL, DISTINCT, OFFSET |
subqueries and CTEs |
| 177. Nth Highest Salary | PL/pgSQL function, OFFSET N - 1 |
subqueries and CTEs |
| 178. Rank Scores | dense_rank |
window functions |
| 180. Consecutive Numbers | lag twice |
window functions |
| 181. Employees Earning More Than Their Managers | self-join | joins |
| 183. Customers Who Never Order | anti-join with NOT EXISTS |
joins |
| 184. Department Highest Salary | rank per department |
window functions |
| 185. Department Top Three Salaries | dense_rank() <= 3 per department |
window functions |
| 196. Delete Duplicate Emails | DELETE … USING self-join |
changing data |
| 197. Rising Temperature | self-join on date minus one day | joins |
| 262. Trips and Users | joins as filters, average of a 1/0 flag | grouping |