MohitDecodes
Back to blogsData

SQL Window Functions Every Data Analyst Needs (ROW_NUMBER, RANK, LAG)

October 6, 2026 · 7 min read

`GROUP BY` collapses rows into summaries. Window functions (`OVER (...)`) let you compute rankings, running totals, and previous-row comparisons **without collapsing individual rows**.

Top 3 products per category with DENSE_RANK

WITH ranked AS (
  SELECT
    category,
    product_name,
    revenue,
    DENSE_RANK() OVER (PARTITION BY category ORDER BY revenue DESC) AS rnk
  FROM sales
)
SELECT * FROM ranked WHERE rnk <= 3;

Four window functions worth memorizing

  • `ROW_NUMBER()`: unique 1, 2, 3 numbering (great for deduplicating latest records).
  • `RANK()` vs `DENSE_RANK()`: handling ties cleanly in leaderboards.
  • `LAG()` / `LEAD()`: compare today's revenue with yesterday's for MoM/WoW growth.
  • `SUM(...) OVER (ORDER BY date)`: running cumulative totals.