Skip to main content
Back to Academy🪟 0. Analytics Foundations (Start Here)
7 min read
Try Hands-on Lab
VISUAL LESSON0. Analytics Foundations (Start Here)

GROUP BY vs. Window Functions (ROW_NUMBER, RANK, LAG) Made Simple

A beginner-to-practitioner guide explaining when SQL collapses rows with GROUP BY versus when Window Functions (OVER PARTITION BY, ROW_NUMBER, RANK, LAG) keep every row intact with side-by-side sample tables and real examples.

SQL GROUP BY vs Window FunctionsOVER PARTITION BYROW_NUMBER vs RANK vs DENSE_RANKSQL LAG and LEADSQL aggregate functionsRunning Total SQL

Explain Like I'm New: Team Receipt vs. Line-by-Line Scoreboard

Imagine 3 coworkers buy lunch on separate receipts inside the Engineering and Sales departments.

  • If your finance manager asks, "Give me one total dollar amount per department," you collapse the 3 receipts down into 2 summary rows (1 for Engineering, 1 for Sales). That is `GROUP BY`.
  • If your manager asks, "Keep all 3 individual receipts on the page, but add an extra column on each receipt showing its department's total and its rank from highest to lowest," you cannot throw rows away. You need a `Window Function` (OVER (PARTITION BY ...)).
Key Beginner Takeaway: GROUP BY shrinks your table into fewer summary rows. Window functions keep every original row and paint extra summary or ranking columns beside each row.

Core Terminology & Keywords You Need to Know

Term / KeywordPlain-English MeaningBest Used For
`GROUP BY`Groups identical values together and collapses them into 1 row per group.Executive KPI summaries (SUM, COUNT, AVG per category/month).
Window Function (`OVER`)Looks across a "window" of related rows *without* collapsing the table.Running totals, top-N per group, day-over-day growth, deduplication.
`PARTITION BY`Slices rows into separate buckets inside OVER (...) (just like GROUP BY, without collapsing).Calculating rankings or subtotals separately per customer, store, or category.
`ORDER BY` inside `OVER`Controls sequence inside each bucket (critical for running sums and LAG/LEAD).Running cumulative sums, moving averages, previous-order comparisons.
`ROW_NUMBER()`Gives strictly unique 1, 2, 3... numbers even when values tie.Keeping only the latest record per user (WHERE rn = 1).
`RANK()` vs `DENSE_RANK()`Both give ties the same rank (1, 1), but RANK() skips 2 (1, 1, 3) while DENSE_RANK() continues (1, 1, 2).Leaderboards, top-3 earners per department.
`LAG()` & `LEAD()`Reads a column from the previous row (LAG) or next row (LEAD) in the same partition.Month-over-month growth, time between customer logins, price changes.

Step-by-Step Worked Example (With Real Tables)

Suppose we have an `orders` table with 5 rows:

order_idcustomer_idorder_dateamount
101C12026-05-0150.00
102C12026-05-04120.00
103C12026-05-1080.00
104C22026-05-02200.00
105C22026-05-09200.00

Pattern 1: Collapsing Rows with `GROUP BY`

When you only need one row per customer:

SELECT
  customer_id,
  COUNT(*)    AS order_count,
  SUM(amount) AS total_spent
FROM orders
GROUP BY customer_id;

Output (5 rows compressed into 2 rows):

customer_idorder_counttotal_spent
C13250.00
C22400.00

Pattern 2: Keeping Every Row with Window Functions

Notice we keep all 5 rows, add each customer's total, compute a running chronological total, and compare each order against their previous order using LAG():

SELECT
  order_id,
  customer_id,
  order_date,
  amount,
  SUM(amount) OVER (PARTITION BY customer_id) AS customer_total,
  SUM(amount) OVER (
    PARTITION BY customer_id
    ORDER BY order_date, order_id
  ) AS running_spend,
  LAG(amount) OVER (
    PARTITION BY customer_id
    ORDER BY order_date, order_id
  ) AS prev_order_amount,
  ROW_NUMBER() OVER (
    PARTITION BY customer_id
    ORDER BY amount DESC, order_id ASC
  ) AS spend_rn
FROM orders;

Output (all 5 rows remain visible!):

order_idcustomer_idamountcustomer_totalrunning_spendprev_order_amountspend_rn
101C150.00250.0050.00NULL3
102C1120.00250.00170.0050.001
103C180.00250.00250.00120.002
104C2200.00400.00200.00NULL1
105C2200.00400.00400.00200.002

Notice why `C2`'s `amount = 200.00` is such a great teacher: - ROW_NUMBER() gives 1 and 2 (always unique). - RANK() would give 1 and 1 (both are tied for highest!). - If there were a $90 order below them, RANK() would number it 3, whereas DENSE_RANK() would number it 2.


Real-World Pattern: Top-N Per Group Without Complex Subqueries

One of the top 3 SQL interview and analytics tasks is: "Find each customer's most recent order." Beginners try GROUP BY customer_id, MAX(order_date) and then realize SQL won't return order_id or amount reliably without another join!

With ROW_NUMBER() inside a CTE (Common Table Expression):

WITH ranked_orders AS (
  SELECT
    order_id,
    customer_id,
    order_date,
    amount,
    ROW_NUMBER() OVER (
      PARTITION BY customer_id
      ORDER BY order_date DESC, order_id DESC
    ) AS rn
  FROM orders
)
SELECT order_id, customer_id, order_date, amount
FROM ranked_orders
WHERE rn = 1;

In Databricks / Spark SQL, there is also an even cleaner shorthand called QUALIFY:

SELECT order_id, customer_id, order_date, amount
FROM orders
QUALIFY ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date DESC) = 1;

Common Beginner Mistakes (And How to Fix Them)

Mistake 1: Filtering a Window Function Directly in `WHERE` - **Broken:**

SELECT order_id, ROW_NUMBER() OVER (ORDER BY amount DESC) AS rn
  FROM orders
  WHERE ROW_NUMBER() OVER (ORDER BY amount DESC) = 1;
  • Why it breaks: In SQL execution order, WHERE runs *before* SELECT window functions exist!
  • Fix: Wrap it in a CTE (WITH cte AS (...) SELECT ... WHERE rn = 1), or use QUALIFY in Spark/Snowflake/DuckDB.

Mistake 2: Omitting Tie-Breakers in Running Totals If two orders share the same `order_date`, `SUM(amount) OVER (PARTITION BY c ORDER BY order_date)` uses default `RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW`, which adds **both tied rows simultaneously** instead of stepping one row at a time! Always include a unique tie-breaker like `ORDER BY order_date, order_id` or `ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW`.

Mistake 3: Forgetting Non-Aggregated Columns in `GROUP BY` Every column in your `SELECT` list that is NOT inside `SUM/COUNT/MIN/MAX/AVG` MUST appear in `GROUP BY`.


Quick Decision Cheat Sheet

  1. Need 1 row per category (totals dashboard)? Use `GROUP BY`.
  2. Need every row preserved with percentages, rankings, or running totals? Use `OVER (PARTITION BY ...)`.
  3. Need latest row per user or deduplication? Use `ROW_NUMBER() OVER (...)` in a CTE + WHERE rn = 1.
  4. Need previous vs. current row comparison? Use `LAG()` or `LEAD()`.

Comprehension & Architecture Check (3 Questions)

Test your understanding of the concepts covered in this lesson.

1. What is the main difference between GROUP BY and a Window Function (`OVER (...)`)?
2. To keep only the newest event per order_id, how should you sort inside `ROW_NUMBER() OVER (...)`?
3. Why do we wrap `ROW_NUMBER()` inside a `WITH` CTE before filtering `WHERE rn = 1`?
Practice What You Learned

FOUNDATIONS-6: Bronze → Silver → Gold: The Data Prep Line

Use a CTE with ROW_NUMBER() OVER (PARTITION BY order_id ORDER BY updated_at DESC) AS rn on bronze.orders_events to keep only the latest event per order_id (rn = 1), excluding rows where amount <= 0. Return order_id, customer_id, status, and amount ordered by order_id ASC.

Solve Challenge