SQL Interview Preparation

Expert

⏱️ 30 mins read

What You'll Learn

SQL interviews at top companies test: window functions (RANK, LAG, ROW_NUMBER), CTEs, self-joins, date math, deduplication, and business logic translation. The interview process: clarify requirements → think aloud → write simple → optimize → discuss edge cases (NULLs, ties, empty tables).

Syntax

-- Pattern 1: Top-N per group using ROW_NUMBER
-- Pattern 2: Consecutive events using date - ROW_NUMBER
-- Pattern 3: YoY growth using self-join or LAG
-- Pattern 4: Deduplication using ROW_NUMBER

Example

-- Pattern 1: 2nd highest salary per dept
WITH ranked AS (
  SELECT name, salary, department,
    DENSE_RANK() OVER
      (PARTITION BY department ORDER BY salary DESC) AS rnk
  FROM employees
)
SELECT * FROM ranked WHERE rnk = 2;

-- Pattern 2: Consecutive login streak >= 3 days
WITH numbered AS (
  SELECT user_id, login_date,
    DATE_SUB(login_date, INTERVAL
      ROW_NUMBER() OVER
        (PARTITION BY user_id ORDER BY login_date) DAY) AS grp
  FROM logins
)
SELECT user_id, COUNT(*) AS streak
FROM numbered GROUP BY user_id, grp
HAVING COUNT(*) >= 3;

-- Pattern 3: Year-over-year revenue growth
SELECT
  curr.yr, curr.revenue, prev.revenue AS prev_yr,
  ROUND((curr.revenue-prev.revenue)*100.0
    /prev.revenue,1) AS yoy_pct
FROM annual_revenue curr
LEFT JOIN annual_revenue prev ON curr.yr = prev.yr + 1;

-- Pattern 4: Keep only latest record per user
WITH ranked AS (
  SELECT *,
    ROW_NUMBER() OVER
      (PARTITION BY user_id ORDER BY created_at DESC) AS rn
  FROM events
)
SELECT * FROM ranked WHERE rn = 1;

Common Mistakes

Jumping to complex CTEs immediately — start with the simplest query that works, then refactor. Not handling ties in RANK/ROW_NUMBER as the question requires. Forgetting to check for NULLs in edge cases. Not testing with sample data mentally.

Interview Tips

Step 1: Clarify the question. Step 2: State your approach before writing. Step 3: Start simple, refactor to complex. Step 4: Check NULLs, ties, empty inputs. Step 5: Discuss performance and alternative approaches. Interviewers value communication as much as the final query.

Practice

Solve the Meta interview question: 'Find all users who logged in for at least 7 consecutive days.' Use the date-minus-row-number grouping trick. Then solve: 'Find the top 3 products by revenue in each category using DENSE_RANK.'