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.
Imagine 3 coworkers buy lunch on separate receipts inside the Engineering and Sales departments.
OVER (PARTITION BY ...)).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.| Term / Keyword | Plain-English Meaning | Best 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. |
Suppose we have an `orders` table with 5 rows:
| order_id | customer_id | order_date | amount |
|---|---|---|---|
| 101 | C1 | 2026-05-01 | 50.00 |
| 102 | C1 | 2026-05-04 | 120.00 |
| 103 | C1 | 2026-05-10 | 80.00 |
| 104 | C2 | 2026-05-02 | 200.00 |
| 105 | C2 | 2026-05-09 | 200.00 |
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_id | order_count | total_spent |
|---|---|---|
| C1 | 3 | 250.00 |
| C2 | 2 | 400.00 |
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_id | customer_id | amount | customer_total | running_spend | prev_order_amount | spend_rn |
|---|---|---|---|---|---|---|
| 101 | C1 | 50.00 | 250.00 | 50.00 | NULL | 3 |
| 102 | C1 | 120.00 | 250.00 | 170.00 | 50.00 | 1 |
| 103 | C1 | 80.00 | 250.00 | 250.00 | 120.00 | 2 |
| 104 | C2 | 200.00 | 400.00 | 200.00 | NULL | 1 |
| 105 | C2 | 200.00 | 400.00 | 400.00 | 200.00 | 2 |
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.
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;SELECT order_id, ROW_NUMBER() OVER (ORDER BY amount DESC) AS rn
FROM orders
WHERE ROW_NUMBER() OVER (ORDER BY amount DESC) = 1;WHERE runs *before* SELECT window functions exist!WITH cte AS (...) SELECT ... WHERE rn = 1), or use QUALIFY in Spark/Snowflake/DuckDB.WHERE rn = 1.Test your understanding of the concepts covered in this lesson.
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.