On this page10 sections · 5 min
Most analysts learn GROUP BY early and then hit a wall.
The wall usually sounds like this:
- “Show each customer’s first order.”
- “Compare this month’s revenue with last month.”
- “Give me a running total by day.”
- “Rank products within each category.”
You can answer all of these with subqueries and self-joins. But the queries get long, slow and hard to review.
Window functions are the cleaner tool. Once they click, a whole class of business questions becomes a few readable lines of SQL.
This guide uses one table throughout so you can focus on the idea, not the schema.
The example table
Imagine a small Bangladesh e-commerce shop. Every row is one order.
-- orders
-- order_id | customer_id | order_date | category | amount_bdt
-- 1001 | C01 | 2026-01-03 | Electronics | 4200
-- 1002 | C02 | 2026-01-03 | Grocery | 850
-- 1003 | C01 | 2026-01-15 | Grocery | 1200
-- 1004 | C03 | 2026-01-20 | Fashion | 2600
-- 1005 | C02 | 2026-02-02 | Grocery | 900
-- 1006 | C01 | 2026-02-11 | Electronics | 6100
-- 1007 | C03 | 2026-02-25 | Fashion | 1800
The queries below are written in standard SQL. They run in PostgreSQL and BigQuery with little or no change.
GROUP BY vs window functions: the one idea that matters
GROUP BY collapses rows. Seven orders grouped by customer become three rows.
A window function keeps every row and adds a calculated column next to it.
SELECT
order_id,
customer_id,
amount_bdt,
SUM(amount_bdt) OVER (PARTITION BY customer_id) AS customer_total
FROM orders;
Every order is still there. Each one now also shows its customer’s total spend. That is the whole trick: calculate across a group without losing the detail.
The OVER (...) clause defines the “window”:
PARTITION BY— which rows belong together (like a group).ORDER BY— the order of rows inside that group.- A frame such as
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW— how far the window reaches.
1. ROW_NUMBER: first, last and deduplicated rows
Business question: “What was each customer’s first order?”
SELECT *
FROM (
SELECT
o.*,
ROW_NUMBER() OVER (
PARTITION BY customer_id
ORDER BY order_date, order_id
) AS order_seq
FROM orders o
) t
WHERE order_seq = 1;
ROW_NUMBER numbers each customer’s orders 1, 2, 3… by date. Keeping order_seq = 1 gives the first order. Sort DESC to get the latest.
Notice the tie-breaker: ORDER BY order_date, order_id. If a customer places two orders on the same day, the result is still deterministic. Leaving out a tie-breaker is one of the most common bugs in real dashboards — the “first order” can change between runs.
The same pattern removes duplicate rows, a very common data-quality job:
-- keep one row per order_id when the source sent duplicates
SELECT *
FROM (
SELECT
r.*,
ROW_NUMBER() OVER (PARTITION BY order_id ORDER BY loaded_at DESC) AS rn
FROM raw_orders r
) t
WHERE rn = 1;
2. RANK vs DENSE_RANK: leaderboards
Business question: “Rank categories by revenue.”
SELECT
category,
SUM(amount_bdt) AS revenue,
RANK() OVER (ORDER BY SUM(amount_bdt) DESC) AS rnk,
DENSE_RANK() OVER (ORDER BY SUM(amount_bdt) DESC) AS dense_rnk
FROM orders
GROUP BY category;
Yes, you can put an aggregate inside a window function. The GROUP BY runs first, then the window ranks the grouped rows.
With our three categories (Electronics ৳10,300, Fashion ৳4,400, Grocery ৳2,950) all three functions give 1, 2, 3. The difference only shows up with ties. Suppose a fourth category, Home, also made ৳4,400:
| revenue | ROW_NUMBER | RANK | DENSE_RANK |
|---|---|---|---|
| 10,300 | 1 | 1 | 1 |
| 4,400 | 2 | 2 | 2 |
| 4,400 | 3 | 2 | 2 |
| 2,950 | 4 | 4 | 3 |
ROW_NUMBERnever ties, even when values match.RANKties, then skips (1, 2, 2, 4).DENSE_RANKties without skipping (1, 2, 2, 3).
Interviewers love this question. The right answer is not just the definition — it’s knowing which one the business wants. “Top 3 products” with ties usually means DENSE_RANK; “pick exactly one winner” means ROW_NUMBER.
3. LAG and LEAD: compare with the previous row
Business question: “How many days pass between a customer’s orders?”
SELECT
customer_id,
order_id,
order_date,
LAG(order_date) OVER (
PARTITION BY customer_id ORDER BY order_date, order_id
) AS previous_order_date,
order_date - LAG(order_date) OVER (
PARTITION BY customer_id ORDER BY order_date, order_id
) AS days_since_previous
FROM orders;
For C01, the gaps are 12 days (Jan 3 → Jan 15) and 27 days (Jan 15 → Feb 11). The first order has no previous one, so it returns NULL — which is correct, not an error.
(In BigQuery, use DATE_DIFF(order_date, LAG(order_date) OVER (...), DAY) instead of subtracting.)
The classic use is month-over-month growth:
WITH monthly AS (
SELECT
DATE_TRUNC('month', order_date) AS month,
SUM(amount_bdt) AS revenue
FROM orders
GROUP BY 1
)
SELECT
month,
revenue,
LAG(revenue) OVER (ORDER BY month) AS prev_revenue,
ROUND(100.0 * (revenue - LAG(revenue) OVER (ORDER BY month))
/ NULLIF(LAG(revenue) OVER (ORDER BY month), 0), 1) AS mom_growth_pct
FROM monthly;
NULLIF(..., 0) protects you from dividing by zero when a previous month had no revenue.
One warning: LAG looks at the previous row, not the previous month. If a month has no orders at all, there is no row for it, and LAG quietly compares March with January. For trend reporting, build a complete calendar first (a date spine) and left-join your data onto it.
4. Running totals
Business question: “Show cumulative revenue through the year.”
SELECT
order_date,
amount_bdt,
SUM(amount_bdt) OVER (
ORDER BY order_date, order_id
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS running_revenue
FROM orders;
Add PARTITION BY customer_id and you get each customer’s lifetime spend as it grows — a simple input for customer-value analysis.
Why write the frame explicitly? When you use ORDER BY without a frame, most databases default to RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. With RANGE, rows that share the same order_date are treated as one block, so the running total jumps for all of them at once. ROWS moves one row at a time. Being explicit removes the surprise.
5. Moving averages
Daily numbers are noisy. A 7-day moving average shows the trend.
WITH daily AS (
SELECT order_date, SUM(amount_bdt) AS revenue
FROM orders
GROUP BY order_date
)
SELECT
order_date,
revenue,
AVG(revenue) OVER (
ORDER BY order_date
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
) AS revenue_7d_avg
FROM daily;
Two honest caveats:
- The first six days average fewer than seven days. Label them or filter them out.
6 PRECEDINGmeans six rows. If some days have no orders, the window covers more than seven calendar days. A date spine fixes this too.
6. Share of total, without a second query
Business question: “What percentage of each category’s revenue does each order represent?”
SELECT
order_id,
category,
amount_bdt,
ROUND(100.0 * amount_bdt
/ SUM(amount_bdt) OVER (PARTITION BY category), 1) AS pct_of_category
FROM orders;
Remove the PARTITION BY and you get each order’s share of all revenue. Percent-of-total is one of the most requested numbers in any business review, and this is the cleanest way to produce it.
Mistakes that show up in interviews (and in production)
Filtering on a window function in WHERE. This fails:
-- ❌ window functions are not allowed in WHERE
SELECT * FROM orders
WHERE ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date) = 1;
WHERE runs before window functions are calculated. Wrap the query in a subquery or CTE and filter outside, as in the examples above. (BigQuery and Snowflake also support QUALIFY, which does the same job in one step.)
No tie-breaker in ORDER BY. Results change between runs and nobody can reproduce last week’s number.
Confusing the grain. A window over order rows is not the same as a window over daily rows. Decide the grain first — order, customer, day — then aggregate to it, then apply the window.
Forgetting gaps in time. LAG and moving averages work on rows. Missing days or months silently distort them.
Practice
Reading about window functions is the easy part. Writing them under a little pressure is what interviews test.
- Try the SQL questions in the free Analyst Interview Lab. Sessions are randomized and explain each answer.
- For a structured path, the Advanced SQL for Analytics module goes deeper into windows, CTEs and query design.
- If you’re preparing for a specific interview, start with SQL interview practice for data analysts.
A good final exercise with the table above: for each customer, show every order, the running total of their spend, and the number of days since their previous order — in one query. If you can write that cleanly, you understand window functions.