SQL Interview Problems: 12 Classic Questions Solved

Free SQL interview practice. 12 lessons solve the classic problems with window functions, joins and CTEs, using one practice database and real query outputs.

Intermediate · 12 lessons

Start Here

  1. How to Solve an SQL Interview Problem - A calm method for SQL interview problems, plus the practice database with employees, sales and logins used in every lesson of this course.

Ranking and Top Rows

  1. Nth Highest Salary: Five Ways and the Traps - Solve the classic second and Nth highest salary problem with LIMIT, a subquery and DENSE_RANK, and learn how ties and a missing answer change the result.
  2. Find and Delete Duplicate Rows in SQL - Find duplicates with GROUP BY and HAVING, label them with ROW_NUMBER, then delete the extra copies safely while keeping one row of each.
  3. Top N per Group: Highest Paid in Each Department - Find the highest paid person in each department, or the top two, with ROW_NUMBER, RANK, DENSE_RANK and a correlated subquery, and handle ties.

Missing Rows and Relationships

  1. Find Rows With No Match: LEFT JOIN, NOT EXISTS, NOT IN - Find employees with no sales and departments with no staff using LEFT JOIN, NOT EXISTS and NOT IN, and learn the NULL trap that breaks NOT IN.
  2. Self Joins and Hierarchies: Employees and Managers - Join a table to itself to list employees with their manager, find people who earn more than their boss, count direct reports and walk the whole org chart.

Windows and Dates

  1. Running Totals, Moving Averages and Percent of Total - Build a running total, a three-row moving average and a percent of total with window functions, and learn what the frame clause ROWS BETWEEN does.
  2. Month-over-Month Change with LAG and Date Grouping - Group sales by month, compare each month with the one before using LAG, calculate the percent change safely and find the best month.
  3. Consecutive Days, Streaks and Gaps (Gaps and Islands) - Find login streaks, the longest run of consecutive days, and the gaps between them, using the gaps and islands trick with ROW_NUMBER and dates.

Counting, Traps and Speed

  1. CASE and Conditional Aggregation: Rows to Columns - Count and sum with conditions using CASE inside SUM, build a pivot table from rows to columns, label values and order NULLs last.
  2. NULL, COUNT and Division Traps in SQL Interviews - Learn the NULL traps interviewers love: = NULL, not-equal that drops rows, COUNT variants, AVG with NULL, and integer division.
  3. Query Speed, Indexes and a Mock Interview Round - Read a query plan, see why a function on a column stops an index from helping, and finish with four timed practice problems and their answers.