GROUP BY vs window: the key difference
GROUP BY department
Rows collapse: one per group
Data → avg 128,750
Sales → avg 126,250
AVG() OVER (PARTITION BY department)
Every row stays, with its group's value
Rohan · Data · 180,000 · 128,750
Amit · Data · 120,000 · 128,750
Ishaan · Sales · 170,000 · 126,250
| Part | Meaning |
|---|---|
| function() | ROW_NUMBER, RANK, SUM, AVG, LAG, … |
| OVER (…) | Makes it a window function |
| PARTITION BY x | Separate windows per x (optional: none = whole table) |
| ORDER BY y | Order inside each window (needed for ranks, running totals, LAG) |
| ROWS BETWEEN … | The frame: which nearby rows to include (optional) |
Running total
WITH daily AS (
SELECT o.order_date, SUM(oi.quantity * oi.unit_price) AS revenue
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
WHERE o.status = 'DELIVERED' AND o.order_date < '2026-04-16'
GROUP BY o.order_date
)
SELECT order_date,
revenue,
SUM(revenue) OVER (ORDER BY order_date) AS running_total
FROM daily
ORDER BY order_date;| order_date | revenue | running_total |
|---|---|---|
| 2026-04-01 | 7596.00 | 7596.00 |
| 2026-04-03 | 1497.00 | 9093.00 |
| 2026-04-07 | 2498.00 | 11591.00 |
| 2026-04-10 | 1299.00 | 12890.00 |
| 2026-04-15 | 5298.00 | 18188.00 |
SUM(revenue) OVER (ORDER BY order_date) adds up everything from the first day to the current one.
ROW_NUMBER, RANK, DENSE_RANK
SELECT name, salary,
ROW_NUMBER() OVER (ORDER BY salary DESC) AS row_number,
RANK() OVER (ORDER BY salary DESC) AS rank,
DENSE_RANK() OVER (ORDER BY salary DESC) AS dense_rank
FROM employees
WHERE department = 'Data';| name | salary | row_number | rank | dense_rank |
|---|---|---|---|---|
| Rohan | 180000 | 1 | 1 | 1 |
| Amit | 120000 | 2 | 2 | 2 |
| Divya | 120000 | 3 | 2 | 2 |
| Karan | 95000 | 4 | 4 | 3 |
Amit and Divya tie at 120,000. ROW_NUMBER still gives them 2 and 3 (which one gets 2 is arbitrary, so add a tie-breaker like ORDER BY salary DESC, name). RANK skips to 4 after the tie; DENSE_RANK continues with 3.
Top N per group
WITH ranked AS (
SELECT department, name, salary,
DENSE_RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS rnk
FROM employees
)
SELECT department, name, salary
FROM ranked
WHERE rnk = 1
ORDER BY department;| department | name | salary |
|---|---|---|
| Data | Rohan | 180000 |
| Leadership | Kavya | 300000 |
| Sales | Ishaan | 170000 |
The pattern: rank inside a CTE with PARTITION BY, then filter outside. Change rnk = 1 to rnk <= 3 for top 3.
Latest row per key (de-duplication)
WITH numbered AS (
SELECT customer_id, order_id, order_date,
ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date DESC) AS rn
FROM orders
)
SELECT customer_id, order_id, order_date
FROM numbered
WHERE rn = 1
ORDER BY customer_id;| customer_id | order_id | order_date |
|---|---|---|
| 1 | 109 | 2026-05-02 |
| 2 | 112 | 2026-05-11 |
| 3 | 110 | 2026-05-04 |
| 4 | 111 | 2026-05-09 |
| 5 | 115 | 2026-05-28 |
| 6 | 113 | 2026-05-20 |
| 8 | 114 | 2026-05-22 |
This exact pattern removes duplicates in every data pipeline: keep rn = 1 ordered by the newest timestamp.
LAG and LEAD: compare with the previous row
WITH monthly AS (
SELECT DATE_TRUNC('month', o.order_date)::date AS month,
SUM(oi.quantity * oi.unit_price) AS revenue
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
WHERE o.status = 'DELIVERED'
GROUP BY 1
)
SELECT month,
revenue,
LAG(revenue) OVER (ORDER BY month) AS prev_month,
ROUND(100.0 * (revenue - LAG(revenue) OVER (ORDER BY month))
/ LAG(revenue) OVER (ORDER BY month), 1) AS growth_pct
FROM monthly
ORDER BY month;| month | revenue | prev_month | growth_pct |
|---|---|---|---|
| 2026-04-01 | 18188.00 | NULL | NULL |
| 2026-05-01 | 18988.00 | 18188.00 | 4.4 |
Delivered revenue grew 4.4% from April to May. April has no previous month, so LAG returns NULL. LEAD looks at the next row instead. Both take an offset and a default: LAG(revenue, 1, 0).
Window frames: moving average
WITH daily AS (
SELECT o.order_date, SUM(oi.quantity * oi.unit_price) AS revenue
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
WHERE o.status = 'DELIVERED' AND o.order_date < '2026-04-16'
GROUP BY o.order_date
)
SELECT order_date, revenue,
ROUND(AVG(revenue) OVER (ORDER BY order_date
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW), 0) AS avg_last_3
FROM daily
ORDER BY order_date;| order_date | revenue | avg_last_3 |
|---|---|---|
| 2026-04-01 | 7596.00 | 7596 |
| 2026-04-03 | 1497.00 | 4547 |
| 2026-04-07 | 2498.00 | 3864 |
| 2026-04-10 | 1299.00 | 1765 |
| 2026-04-15 | 5298.00 | 3032 |
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW means “this row and the two before it”. The first rows average fewer values because there are no earlier rows.
Share of total
SELECT p.category,
SUM(oi.quantity * oi.unit_price) AS revenue,
ROUND(100.0 * SUM(oi.quantity * oi.unit_price)
/ SUM(SUM(oi.quantity * oi.unit_price)) OVER (), 1) AS pct_of_total
FROM order_items oi
JOIN products p ON p.product_id = oi.product_id
GROUP BY p.category;| category | revenue | pct_of_total |
|---|---|---|
| Electronics | 34990.00 | 77.1 |
| Accessories | 10380.00 | 22.9 |
SUM(SUM(...)) OVER () looks odd: the inner SUM is the GROUP BY aggregate per category; the outer window SUM with an empty OVER () adds those up across all rows. Electronics brings 77.1% of revenue.
FIRST_VALUE and NTILE
SELECT name, department, salary,
FIRST_VALUE(name) OVER (PARTITION BY department ORDER BY salary DESC) AS top_earner,
NTILE(2) OVER (ORDER BY salary DESC) AS salary_half
FROM employees
WHERE department IN ('Data', 'Sales')
ORDER BY department, salary DESC;| name | department | salary | top_earner | salary_half |
|---|---|---|---|---|
| Rohan | Data | 180000 | Rohan | 1 |
| Divya | Data | 120000 | Rohan | 2 |
| Amit | Data | 120000 | Rohan | 1 |
| Karan | Data | 95000 | Rohan | 2 |
| Ishaan | Sales | 170000 | Ishaan | 1 |
| Neha | Sales | 160000 | Ishaan | 1 |
| Pooja | Sales | 90000 | Ishaan | 2 |
| Farhan | Sales | 85000 | Ishaan | 2 |
FIRST_VALUE takes the first row's value in each window; NTILE(2) splits rows into 2 equal buckets (use 4 for quartiles). LAST_VALUE needs a full frame (ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) to work as expected.
QUALIFY (Databricks, Snowflake, BigQuery)
-- Databricks SQL and Snowflake: QUALIFY filters on a window function directly
SELECT department, name, salary
FROM employees
QUALIFY DENSE_RANK() OVER (PARTITION BY department ORDER BY salary DESC) = 1;QUALIFY filters on a window function without a CTE. PostgreSQL and MySQL don't have it, so we used a CTE above.
🎯 Interview questions on this topic
Try to answer out loud first, then tap to check.
Q1Difference between ROW_NUMBER, RANK and DENSE_RANK?Fresher+
Q2Write a query for the top 3 products by revenue in each category.1–3 yrs+
Q3How do you remove duplicates but keep the latest record?1–3 yrs+
Q4Calculate month-over-month growth.1–3 yrs+
Q5What's the default window frame and why does it matter?3+ yrs+
Q6Why can't you use a window function in WHERE, and what are the alternatives?3+ yrs+
Key takeaways
- ✓Window functions keep every row while adding group-level calculations.
- ✓ROW_NUMBER powers de-duplication and top-N; LAG/LEAD power comparisons.
- ✓Frames control moving windows; know the default.
- ✓Next: changing data safely with INSERT, UPDATE, MERGE and transactions.
Frequently asked questions
What is a window function in simple words?
A function that looks at a group of related rows (the 'window') for each row, without collapsing them into one row like GROUP BY does. Example: show each order and the customer's running total next to it.
What does PARTITION BY mean?
It splits rows into groups for the window function, like GROUP BY but without merging rows. ROW_NUMBER() OVER (PARTITION BY customer_id ...) restarts numbering for each customer.
ROW_NUMBER vs RANK vs DENSE_RANK?
With a tie for 2nd place: ROW_NUMBER gives 1, 2, 3 (unique, tie broken arbitrarily), RANK gives 1, 2, 2, 4 (skips), DENSE_RANK gives 1, 2, 2, 3 (no gaps).
Can I use a window function in WHERE?
No, window functions are calculated in the SELECT step, after WHERE. Wrap the query in a CTE and filter outside, or use QUALIFY in Databricks SQL, Snowflake and BigQuery.
What is a window frame?
Which rows around the current row are included, e.g. ROWS BETWEEN 2 PRECEDING AND CURRENT ROW for a 3-row moving average. With ORDER BY and no frame, the default runs from the start of the partition to the current row.
🧠 Quick check: window functions
1. Salaries 180k, 120k, 120k, 95k. DENSE_RANK of 95k?
2. Best function to keep exactly ONE latest row per customer?
3. LAG(revenue) OVER (ORDER BY month) returns...
4. Where do you filter on ROW_NUMBER() = 1 in PostgreSQL?
Checking your access…