Tech Tutorials

Essential SQL Patterns for Data Analytics & Backend Interviews

Window functions, CTEs, cohort retention, and query optimization—learn the exact SQL patterns tested in data analytics and backend developer technical rounds with runnable examples.

SQL queries, window functions, and database optimization tutorial
In This Guide
  1. Why SQL Is the Single Highest-ROI Skill in Tech
  2. Pattern 1: Top N Records Per Category Using DENSE_RANK()
  3. Pattern 2: Month-over-Month Growth Using LAG()
  4. Pattern 3: Filter Placement in LEFT JOINs

Why SQL Is the Single Highest-ROI Skill in Tech

Whether you apply for a Data Analyst, Data Scientist, Backend Developer, or Product Analyst role, SQL shows up in almost every technical screen. Basic SELECT, WHERE, and GROUP BY queries are table stakes. The questions that decide job offers almost always involve CTEs (Common Table Expressions), Window Functions, and tricky JOIN edge cases.

Pattern 1: Top N Records Per Category Using DENSE_RANK()

Classic interview prompt: "Find the top 2 highest-paid employees in each department, handling salary ties gracefully."

WITH ranked_salaries AS (
  SELECT
    department_id,
    employee_name,
    salary,
    DENSE_RANK() OVER (
      PARTITION BY department_id
      ORDER BY salary DESC
    ) AS salary_rank
  FROM employees
)
SELECT department_id, employee_name, salary
FROM ranked_salaries
WHERE salary_rank <= 2
ORDER BY department_id, salary DESC;

Know the difference between ROW_NUMBER() (always unique: 1, 2, 3), RANK() (skips after ties: 1, 1, 3), and DENSE_RANK() (no gaps after ties: 1, 1, 2)—interviewers ask this comparison constantly.

Pattern 2: Month-over-Month Growth Using LAG()

Business intelligence teams frequently calculate revenue growth compared to the previous month without ugly self-joins:

WITH monthly_rev AS (
  SELECT
    DATE_FORMAT(order_date, '%Y-%m') AS rev_month,
    SUM(order_amount) AS total_revenue
  FROM orders
  WHERE status = 'completed'
  GROUP BY 1
)
SELECT
  rev_month,
  total_revenue,
  LAG(total_revenue) OVER (ORDER BY rev_month) AS prev_month_revenue,
  ROUND(
    (total_revenue - LAG(total_revenue) OVER (ORDER BY rev_month))
    * 100.0 / NULLIF(LAG(total_revenue) OVER (ORDER BY rev_month), 0),
    2
  ) AS mom_growth_pct
FROM monthly_rev;

Wrapping the denominator in NULLIF(..., 0) is a subtle production best practice that prevents division-by-zero crashes.

Pattern 3: Filter Placement in LEFT JOINs

A classic trap: placing a condition on the right-hand table inside the WHERE clause silently turns a LEFT JOIN into an INNER JOIN because NULL rows get filtered out. To preserve unmatched left-table rows (e.g., customers with zero orders in 2026), place the right-table date filter inside the ON clause instead.