What are window functions and how do they differ from GROUP BY?
A window function computes over a group of rows but keeps every row, while GROUP BY collapses a group into one row. It adds the value as a separate column: function() OVER (PARTITION BY … ORDER BY …). Window functions run after WHERE, GROUP BY and HAVING, so they are written only in SELECT and ORDER BY, and filtering by them needs a CTE or subquery.
SQL · Window functions
You need to show each employee and the total of their department. GROUP BY hides rows. What now?
A report has to show every salary separately with the department total beside it. A plain GROUP BY leaves one row per department and the details vanish. Then people add a JOIN to a grouped subquery and the query grows. A window function solves it in one line: it computes over a group but does not collapse the rows.
How it works and why. An ordinary aggregate reduces a group of rows to one. A window function computes the same over a "window" of rows but writes the result into every row as a separate column. The syntax: function() OVER (PARTITION BY … ORDER BY …). PARTITION BY splits rows into groups like GROUP BY but without collapsing. ORDER BY inside OVER sets the order within a group (needed for ranks and running totals). Empty parentheses OVER () mean the window is the whole result. The sample data: five employees.
name
dept
salary
Anna
Dev
9000
Bohdan
Dev
8000
Clara
Dev
8000
Dmytro
Dev
7000
Eva
QA
7000
-- GROUP BY: one row per department, the details are goneSELECT dept, SUM(salary) AS dept_total
FROM employees
GROUPBY dept;
-- OVER: all rows stay, the total sits next to themSELECT name, dept, salary,
SUM(salary) OVER (PARTITION BY dept) AS dept_total
FROM employees;
Collapsing against a window
GROUP BY dept
dept
dept_total
Dev
32000
QA
7000
OVER (PARTITION BY dept)
name
dept
dept_total
Anna
Dev
32000
Bohdan
Dev
32000
Clara
Dev
32000
Dmytro
Dev
32000
Eva
QA
7000
Figure 1. GROUP BY gives two rows, the window keeps all five and adds the department total to each.
The total for Dev: 9000 + 8000 + 8000 + 7000 = 32000, QA has one employee with 7000. The window returns these numbers next to every row and the number of rows does not change.
Where the window fits in a query. Logically window functions are computed after FROM, WHERE, GROUP BY and HAVING but before ORDER BY and LIMIT. So they can be written only in SELECT and ORDER BY, not in WHERE: at that moment the window is not computed yet.
SELECT name FROM employees
WHERESUM(salary) OVER (PARTITION BY dept) > 20000;
-- ERROR: window functions are not allowed in WHERE
To filter by the value of a window function, wrap it in a CTE or a subquery and filter outside.
Reading the error: a window in WHERE
1ERROR: window functions are not allowed in WHERE
LINE 2: WHERE SUM(salary) …
^ 2
What: a window function was put in WHERE. The row filter runs before windows are computed, so the value to filter by does not exist yet.
Where:LINE 2 and ^ point at the start of the function call. The long query line is shortened here.
What to do
Compute the window in a CTE or subquery with an alias and filter outside: WHERE dept_total > 20000.
Figure 2. The PostgreSQL error text (shortened) for the query above.
Example: from JOIN to a window. Show the difference between a salary and the department average. Without window functions:
-- without window functions: a JOIN to a grouped tableSELECT e.name, e.salary, s.avg_salary
FROM employees e
JOIN (SELECT dept, AVG(salary) AS avg_salary
FROM employees GROUPBY dept) s ON s.dept = e.dept;
With a window function the same meaning needs no subquery:
-- with a window function; difference from the average: 1000, 0, 0, -1000, 0SELECT name, dept, salary,
salary - AVG(salary) OVER (PARTITION BY dept) AS diff_from_avg
FROM employees;
Two models of the same calculation
GROUP BY
Rows collapse
One row per group. The details must be brought back separately with a JOIN to the result.
OVER
Rows stay
Every row is kept and gets the group value. The aggregate and the details in one query.
Figure 3. Both compute per group, the difference is what stays in the result.
Limits and alternatives. If only a summary table is needed (one row per group), GROUP BY is simpler and usually faster. Window functions are used when the details must stay in the result. Several functions with the same window are convenient to describe once through WINDOW:
-- a named window: one definition for several functionsSELECT name, dept,
SUM(salary) OVER w AS dept_total,
COUNT(*) OVER w AS dept_size
FROM employees
WINDOW w AS (PARTITION BY dept);
Aggregates in a window work with any number of rows, while special functions (ROW_NUMBER, RANK, LAG, LEAD) exist only in the window form. Window functions are part of the SQL standard and are supported in PostgreSQL, MySQL 8.0+, SQL Server and Oracle. MySQL before 8.0 has none.
Typical mistakes.
A window function in WHERE or HAVING: an error, a CTE or subquery is needed.
Mixing a window function with an ordinary column in a query with GROUP BY: window functions work over the already grouped result and ungrouped columns are unavailable.
Forgetting PARTITION BY: the window becomes the whole result and the sum is computed over the entire table.
Believing a window function "removes" duplicates: it deletes nothing.
Check yourself
The query SELECT dept, name, COUNT(*) FROM employees GROUP BY dept fails. How to get the department headcount next to each name?
Answer
The column name is neither in GROUP BY nor an aggregate, so the database refuses. A window function is needed: SELECT name, dept, COUNT(*) OVER (PARTITION BY dept) AS dept_size FROM employees.
Why can SUM(salary) OVER (PARTITION BY dept) not be placed in WHERE?
Answer
Window functions are computed after WHERE, so at the WHERE stage they do not exist yet. To filter by their value, wrap the query in a CTE or a subquery and add a WHERE outside.
Related lessons: “How do ROW_NUMBER, RANK and DENSE_RANK differ?”, “How do you find the top N records in each group?”, “What is a CTE (WITH) and why is it needed?”.
In an interview.Junior: A window function computes a value over a group of rows but, unlike GROUP BY, does not collapse them: every row stays and gets an extra column. PARTITION BY sets the groups, ORDER BY the order inside. Middle/Senior: Window functions are computed after WHERE, GROUP BY and HAVING, so they can be written only in SELECT and ORDER BY, and filtering by them needs a CTE. If only totals are needed I use GROUP BY: simpler and faster. I use a window when the details must stay beside the aggregate, for example the difference from the department average. A repeated window goes into WINDOW.
How do ROW_NUMBER, RANK and DENSE_RANK differ?
ROW_NUMBER, RANK and DENSE_RANK number rows by an ordering and differ only in how they treat equal values. ROW_NUMBER gives every row a unique number, RANK gives equal rows the same rank and skips the following numbers, and DENSE_RANK gives the same rank without gaps. ROW_NUMBER is used for deduplication, DENSE_RANK for the Nth value with ties, and a unique key is added to the ORDER BY of ROW_NUMBER.
SQL · Window functions
Two people share the second salary. Who is third by salary: somebody or nobody?
In the interview query "the third highest salary" two employees have the same second amount. One function returns a result, another an empty set, and a third gives a person whose salary is not the third highest by value. All three number rows by an ordering and differ only in what they do with equal values.
How it works and why. All three functions sort the window rows by ORDER BY inside OVER and assign a number. For different values the result is the same. The difference appears on equal values (called ties). ROW_NUMBER ignores equality and gives every row a unique number, RANK gives equal rows the same rank and skips the following numbers, DENSE_RANK gives equal rows the same rank without gaps.
salary
ROW_NUMBER
RANK
DENSE_RANK
9000
1
1
1
8000
2
2
2
8000
3
2
2
7000
4
4
3
SELECT name, salary,
ROW_NUMBER() OVER (ORDERBY salary DESC, name) AS rn,
RANK() OVER (ORDERBY salary DESC) AS rnk,
DENSE_RANK() OVER (ORDERBY salary DESC) AS drnk
FROM employees
WHERE dept = 'Dev';
-- salaries 9000, 8000, 8000, 7000: rn 1,2,3,4; rnk 1,2,2,4; drnk 1,2,2,3
For the two 8000s RANK says "both are second" and skips third place, so the next one gets rank four (the number of rows above plus one). DENSE_RANK skips nothing: 7000 gets rank three. The order among equals in ROW_NUMBER is not defined: the example adds name as a second key so that Bohdan always goes before Clara.
Example: the Nth highest salary. The sample data: in Dev the salaries are 9000, 8000, 8000, 7000. The task "the third highest salary, count repeats as one":
-- the third highest salary with repeats allowed: 7000 (Dmytro)WITH r AS (
SELECT name, salary,
DENSE_RANK() OVER (ORDERBY salary DESC) AS drnk
FROM employees
WHERE dept = 'Dev'
)
SELECT name, salary FROM r WHERE drnk = 3;
-- with RANK the result would be empty: there is no rank 3 (1, 2, 2, 4)
The answer is 7000 (Dmytro): there are three distinct values at the top, and 7000 is the third. With RANK the ranks would be 1, 2, 2, 4 and rank 3 simply does not exist, so the result is empty. With ROW_NUMBER the third would be Clara with 8000, although she does not have a third salary by value.
A tie and a second sort key
Unstable
ORDER BY salary DESC
For two salaries of 8000 ROW_NUMBER numbers them as it happens. Between runs and plans the order can change, and the test becomes flaky.
Stable
ORDER BY salary DESC, name
An extra unique key makes the order unambiguous. The same result every time.
Figure 1. ROW_NUMBER needs a deterministic order.
-- without a second key the order of equal salaries is arbitrary
ROW_NUMBER() OVER (ORDERBY salary DESC)
-- with an extra key the result is stable
ROW_NUMBER() OVER (ORDERBY salary DESC, name)
So the choice depends on the question. "Give one row per group" or "remove duplicates" is ROW_NUMBER. "A place in a ranking with equal places and a gap" is RANK. "The Nth by value, counting repeats once" is DENSE_RANK.
Limits and alternatives. The order of NULL depends on the database. In PostgreSQL NULL sorts as larger than any value, so ORDER BY salary DESC puts it first and it gets rank 1. In MySQL and SQL Server it is the opposite: NULL is treated as the smallest. Explicit NULLS FIRST and NULLS LAST (standard, available in PostgreSQL and Oracle) remove the question:
-- PostgreSQL: NULL goes first with DESC and gets rank 1
RANK() OVER (ORDERBY salary DESC)
-- explicit: NULL last
RANK() OVER (ORDERBY salary DESC NULLS LAST)
For a simple "Nth largest" without windows people sometimes write ORDER BY salary DESC LIMIT 1 OFFSET N-1, but it does not remove repeats and does not work "per group". There are also NTILE (splits into a given number of groups) and PERCENT_RANK, but interviews most often ask about the three main ones.
Typical mistakes.
ROW_NUMBER without a unique sort key: the result differs between runs.
RANK for "the Nth by value": a gap after a tie, the wanted rank is missing.
NULL in the sort column without NULLS LAST: an empty salary becomes "the highest".
Forgetting PARTITION BY in a "for each department" task: the whole list is ranked.
Adding WHERE rnk = 2 in the same query: the window function is not computed yet, a CTE is needed.
Check yourself
Salaries 9000, 8000, 8000, 7000. Which ranks do RANK and DENSE_RANK give for 7000?
Answer
RANK gives 4 because three rows with higher or equal salaries come before it. DENSE_RANK gives 3 because it counts only distinct values above: 9000, 8000, 7000.
Why is ROW_NUMBER used for deduplication by key and not RANK?
Answer
ROW_NUMBER always gives unique numbers, so the condition rn = 1 keeps exactly one row per group. RANK gives rank 1 to several rows on a tie, and duplicates would remain.
Related lessons: “How do you find the top N records in each group?”, “What are window functions and how do they differ from GROUP BY?”, “What do LAG and LEAD do?”.
In an interview.Junior: All three number rows by an ordering, the difference is in equal values. ROW_NUMBER always gives unique numbers, RANK gives equal rows the same rank with a gap after them, DENSE_RANK without a gap. For "the second highest salary" with repeats I take DENSE_RANK, for deduplication ROW_NUMBER. Middle/Senior: In ROW_NUMBER I add a unique key to ORDER BY so the order on ties is deterministic. I remember NULL: in PostgreSQL it goes first with DESC, so I write NULLS LAST. I filter by rank in an outer query because a window function cannot go in WHERE.
How do you find the top N records in each group?
The top N per group takes two steps: number rows within each group, then keep numbers up to N. A window function with PARTITION BY does the numbering, and it goes into a CTE or subquery because it cannot stand in WHERE. ROW_NUMBER gives at most N rows per group, RANK or DENSE_RANK keep ties, so the requirement is clarified first.
SQL · Window functions
You need the three largest transactions of each account. LIMIT 3 gives three for the whole table. How per group?
A query with ORDER BY amount DESC LIMIT 3 returns the three largest transactions for the whole table, but three per account are needed. LIMIT does not help here: it knows nothing about groups. The classic solution: number the rows inside each group and keep the numbers up to N.
How it works and why. A two-step scheme. First a window function with PARTITION BY numbers the rows in each group in the needed order. Then the outer query keeps rows with a number not above N. Two steps are needed because a window function cannot stand in WHERE: it is computed later.
SELECT dept, name FROM employees
WHERE ROW_NUMBER() OVER (PARTITION BY dept ORDERBY salary DESC) <= 2;
-- ERROR: window functions are not allowed in WHERE
So the first step goes into a CTE (or a subquery) and the filter is applied outside. The sample data: in Dev Anna 9000, Bohdan 8000, Clara 8000, Dmytro 7000, in QA Eva 7000 and Fedir 6000. The two largest salaries of each department:
-- the two largest salaries in each departmentWITH ranked AS (
SELECT dept, name, salary,
ROW_NUMBER() OVER (
PARTITION BY dept
ORDERBY salary DESC, name
) AS rn
FROM employees
)
SELECT dept, name, salary
FROM ranked
WHERE rn <= 2ORDERBY dept, rn;
For Dev these are Anna and Bohdan, for QA Eva and Fedir. Clara, with the same salary as Bohdan, did not get in because ROW_NUMBER gives unique numbers and the second key name settled the tie in favour of Bohdan.
Two functions, two answers
ROW_NUMBER ≤ 2
dept
name
salary
Dev
Anna
9000
Dev
Bohdan
8000
QA
Eva
7000
QA
Fedir
6000
RANK ≤ 2
dept
name
salary
Dev
Anna
9000
Dev
Bohdan
8000
Dev
Clara
8000
QA
Eva
7000
QA
Fedir
6000
Figure 1. ROW_NUMBER cuts exactly N rows per group, RANK keeps all equal values.
If by meaning a tie must be kept ("everyone in the top 2 by salary"), RANK or DENSE_RANK is needed:
-- with RANK the tie stays: Clara is second tooWITH ranked AS (
SELECT dept, name, salary,
RANK() OVER (PARTITION BY dept ORDERBY salary DESC) AS rnk
FROM employees
)
SELECT dept, name, salary FROM ranked WHERE rnk <= 2;
The choice between the functions is a question of requirements, and it is worth clarifying before writing the query: "exactly N" or "everyone in the top".
A QA example. The latest transaction of each account: ROW_NUMBER() OVER (PARTITION BY account_id ORDER BY created_at DESC, id DESC) and the condition rn = 1. The second key id DESC is needed for the case when two transactions share the same time: without it "the latest" may change between runs.
LIMIT against numbering in groups
Wrong
ORDER BY … LIMIT 2
Two rows for the whole table, not for each department. Groups are not taken into account.
Right
ROW_NUMBER() … rn <= 2
Numbering inside each group, the filter outside. Two rows per department.
Figure 2. For "top N in each group" PARTITION BY is needed.
Limits and alternatives. PostgreSQL has two other ways. LATERAL applies LIMIT to each group separately and works well when there is an index on the group key and the sort. DISTINCT ON quickly gives the first row of each group, but only one:
-- PostgreSQL: LATERAL applies LIMIT for each department separatelySELECT d.dept, e.name, e.salary
FROM (SELECTDISTINCT dept FROM employees) d
CROSSJOIN LATERAL (
SELECT name, salary
FROM employees x
WHERE x.dept = d.dept
ORDERBY salary DESC, name
LIMIT2
) e;
-- PostgreSQL: only the largest in a group (Anna, Eva)SELECTDISTINCTON (dept) dept, name, salary
FROM employees
ORDERBY dept, salary DESC, name;
Some databases (Snowflake, BigQuery, DuckDB) have QUALIFY, which lets you filter by a window function without a CTE. PostgreSQL and MySQL do not have it. On large tables numbering the whole set costs a sort, so an index on (dept, salary DESC) speeds the query up, and EXPLAIN shows whether it is used.
Typical mistakes.
LIMIT without grouping: the result is for the whole table, not for a group.
A window function in WHERE: an error.
Numbering without a unique sort key: on ties the result differs between runs.
RANK instead of ROW_NUMBER where exactly N rows are needed: a tie gives more rows than expected.
Forgetting ORDER BY in the outer query: the row order after a CTE is not guaranteed.
Check yourself
You are given a query with WHERE rn <= 2 that uses ROW_NUMBER. How does the result in the sample Dev department change if ROW_NUMBER is replaced with RANK?
Answer
With ROW_NUMBER there are two rows, Anna and Bohdan. With RANK the two employees with 8000 both have rank 2, so three rows come back: Anna, Bohdan and Clara.
Why is "top N in each group" not written as one query with LIMIT?
Answer
LIMIT cuts the whole result, not each group. To compute the place inside a group a window function with PARTITION BY is needed, and since it cannot go in WHERE, the filter moves to a CTE or a subquery, or LATERAL is used.
Related lessons: “How do ROW_NUMBER, RANK and DENSE_RANK differ?”, “What is a CTE (WITH) and why is it needed?”, “What are window functions and how do they differ from GROUP BY?”.
In an interview.Junior: I number rows inside each group with ROW_NUMBER, PARTITION BY and an ordering, and in the outer query I take numbers from one to N. A window function cannot be filtered directly in WHERE, so a CTE or a subquery is needed. Middle/Senior: First I clarify the requirement: exactly N per group or everyone tied in the top, which decides ROW_NUMBER or RANK. I add a unique key to the sort so the result does not change between runs. In PostgreSQL I can take LATERAL with LIMIT or DISTINCT ON for one row per group, and on large tables I check the plan and the index.
What do LAG and LEAD do?
LAG returns the value from the previous row of the window and LEAD from the next, so a row can be compared with its neighbour within a group. ORDER BY inside OVER defines previous and next, PARTITION BY the groups. In a group's first row LAG gives NULL unless a third argument sets a default. Filtering by the result is done in a CTE.
SQL · Window functions
Two identical transactions three seconds apart. How to find such pairs with one query?
A user pressed a button twice and the account got two identical payments three seconds apart. Among a million transactions such pairs cannot be found by hand. For that you have to compare a row with the previous one within the same account, and this is exactly how LAG and LEAD work.
How it works and why.LAG(col) returns the column value from the previous row of the window, LEAD(col) from the next one. "Previous" and "next" are defined by the same ORDER BY inside OVER, and the group boundaries by PARTITION BY. The second argument sets the offset (1 by default), the third the value substituted if there is no such row:
-- LAG(expr, offset, default)
LAG(amount) OVER w -- the previous row, NULL in the first
LAG(amount, 2) OVER w -- two rows back
LAG(amount, 1, 0) OVER w -- instead of NULL in the first row there is 0
LEAD(status) OVER w -- the next row
In the first row of each group there is no previous one, so LAG gives NULL (for LEAD the same in the last row). This is not an error but the norm. A difference with NULL is NULL too, and a comparison condition drops it. The sample data: transactions of account 10.
What LAG sees
transactions, account 10
id
time
amount
1
10:00:00
100
2
10:00:03
100
3
10:10:00
300
query result
id
amount
prev_amount
gap
1
100
NULL
NULL
2
100
100
00:00:03
3
300
100
00:09:57
Figure 1. The first row has no previous one and gives NULL. The difference between 10:10:00 and 10:00:03 is 9 minutes 57 seconds.
-- the gap between consecutive transactions of an accountSELECT id, amount,
LAG(amount) OVER w AS prev_amount,
created_at - LAG(created_at) OVER w AS gap
FROM transactions
WHERE account_id = 10
WINDOW w AS (PARTITION BY account_id ORDERBY created_at, id);
Row 2 has the same amount as the previous one and a three-second gap: a candidate for a double submit. This is the sign the next query looks for. Filtering by the value of a window function needs a CTE because it cannot go in WHERE:
-- double submit: the same amount within 5 seconds; result id 2WITH g AS (
SELECT id, account_id, amount, created_at,
LAG(amount) OVER w AS prev_amount,
LAG(created_at) OVER w AS prev_at
FROM transactions
WINDOW w AS (PARTITION BY account_id ORDERBY created_at, id)
)
SELECT id, account_id, amount
FROM g
WHERE amount = prev_amount
AND created_at - prev_at < INTERVAL '5 seconds';
The result: the transaction with id 2. Pairs from different accounts do not mix because PARTITION BY account_id limits the window to one account. The second key id in ORDER BY is needed so that on equal time the order is unambiguous.
Another example: a sequence of statuses.LEAD lets you look forward, for example to find orders with a transition that is not among the allowed ones:
-- order status changes: each row together with the next statusSELECT order_id, status, changed_at,
LEAD(status) OVER (PARTITION BY order_id ORDERBY changed_at, id) AS next_status
FROM order_status_log;
Now every row has a pair "status and next status", easy to compare with a table of allowed transitions.
With a window and without one
Wrong
LAG without PARTITION BY
The previous row is a row of another account. At group boundaries foreign transactions are compared.
Right
PARTITION BY account_id ORDER BY …
The previous is taken only within the account, the first row of a group gets NULL.
Figure 2. PARTITION BY sets the group boundaries, ORDER BY sets the order.
Limits and alternatives.LAG and LEAD do not depend on the window frame: they always take the row at the offset in the ordered group. Without ORDER BY in OVER the "previous" row is undefined. Instead of the functions you can do a self join on t2.created_at < t1.created_at, but it is more complex and slower, and the result needs extra filtering. To compare not with the neighbour but with the nearest row meeting a condition, other tools are needed. If a double submit is defined by an idempotency key rather than by time, a GROUP BY with HAVING COUNT(*) > 1 is enough.
Typical mistakes.
No PARTITION BY: the "previous" row belongs to another group.
No ORDER BY or a non-unique key: the previous row is undefined, the result unstable.
Ignoring NULL in the first row of a group: a filter without a check drops it silently, or arithmetic with it yields NULL.
LAG in WHERE: an error, a CTE is needed.
Comparing timestamps as strings instead of timestamp: the interval is computed wrongly.
Check yourself
What does LAG(amount) return for the first row of each account and how do you get 0 instead?
Answer
NULL because there is no previous row in the group. The third argument sets a default value: LAG(amount, 1, 0) returns 0.
Why does the query for finding double payments need both PARTITION BY account_id and a CTE?
Answer
PARTITION BY stops transactions of different accounts from being compared: the previous row is taken only within its own account. A CTE is needed because the result of LAG cannot be used in the WHERE of the same query where it is computed.
Related lessons: “What are window functions and how do they differ from GROUP BY?”, “How do you compute a running total?”, “How do you find anomalies and data integrity violations?”.
In an interview.Junior: LAG returns the value from the previous row of the window, LEAD from the next one. I use them to compare an event with the previous one: for example to find identical transactions from one account a few seconds apart, a typical sign of a double submit. Middle/Senior: I set PARTITION BY so groups do not mix and a unique ORDER BY so the previous row is defined. I remember NULL in the first row of a group and set the third argument when needed. I filter by the result in a CTE. A self join with an offset works but is more complex and slower.
How do you compute a running total?
A running total is SUM with OVER and ORDER BY, adding everything from the start of the group to each row. PARTITION BY separates accounts. The default RANGE frame adds rows with equal sort values together, so a unique key goes into ORDER BY, or ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW is used. Only completed operations are counted and money is kept in NUMERIC.
SQL · Window functions
The transaction history exists but the balance at each moment is not stored. How to rebuild it with one query?
An account shows the balance after each operation, while the database holds only the operations. To check that the balance never went negative or to find the moment of a mismatch, you have to compute "the sum from the first operation to this one". A running total does this with a window function, without loops and without a self-join.
How it works and why.SUM(…) OVER (… ORDER BY …) adds the values from the start of the group to the current row. If OVER has an ORDER BY and no frame is given, the window for each row is "from the start of the group to the current row and all its peers by the sort" (by the standard RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW). This matters, and the consequences are below. The sample data: the completed operations of account 10, where a deposit adds and a withdrawal subtracts.
History and balance
transactions
id
type
amount
1
deposit
500
2
withdrawal
200
3
deposit
100
4
withdrawal
450
balance
id
balance
1
500
2
300
3
400
4
-50
Figure 1. The balance after each operation. After the fourth it went negative.
SELECT id, type, amount,
SUM(CASEWHEN type = 'deposit'THEN amount ELSE -amount END)
OVER (PARTITION BY account_id
ORDERBY created_at, id) AS balance
FROM transactions
WHERE account_id = 10AND status = 'completed'ORDERBY created_at, id;
-- balance: 500, 300, 400, -50
Check by hand: 500, 500 − 200 = 300, 300 + 100 = 400, 400 − 450 = −50. A finding is already visible here: the fourth withdrawal should have been rejected, yet the balance went below zero. Such moments are convenient to find with a CTE:
-- the moment the balance went negative: id 4WITH h AS (
SELECT id, created_at,
SUM(CASEWHEN type = 'deposit'THEN amount ELSE -amount END)
OVER (PARTITION BY account_id ORDERBY created_at, id) AS balance
FROM transactions
WHERE account_id = 10AND status = 'completed'
)
SELECT id, created_at, balance FROM h WHERE balance < 0;
Another scenario: compare the last value of the running total with the current accounts.balance. If they differ, somewhere in the history an operation is lost or doubled.
The trap of the default frame. If several rows have the same value in ORDER BY, the default frame adds them all at once. Take three operations: a deposit of 100 at 10:00, then two of 50 and 25 at 10:05 (the same time).
Equal time in ORDER BY
ORDER BY created_at
id
time
amount
running
1
10:00
100
100
2
10:05
50
175
3
10:05
25
175
ORDER BY created_at, id
id
time
amount
running
1
10:00
100
100
2
10:05
50
150
3
10:05
25
175
Figure 2. Rows 2 and 3 share a time, so the default frame gives them the same sum 175. A unique order key separates them.
The left result should look suspicious: the intermediate balance 175 in both rows is untrue: after row 2 it should be 150. There are two fixes: add a unique key to ORDER BY or specify a row frame.
-- the default frame: rows with the same created_at go togetherSUM(amount) OVER (ORDERBY created_at)
-- an explicit row frame: each row is added separatelySUM(amount) OVER (ORDERBY created_at, id
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
-- a moving sum over the last three rowsSUM(amount) OVER (ORDERBY created_at, id
ROWS BETWEEN2 PRECEDING AND CURRENT ROW)
The default frame and a row frame
Wrong
ORDER BY created_at
Rows equal in time are computed together, the intermediate balance is the same. A test comparing with the real balance may diverge.
Right
ORDER BY created_at, id
A unique order gives one row per step. The balance after every operation is reproduced exactly.
Figure 3. For a running total the order must be unique.
Limits and alternatives. For moving sums and averages the frame is set explicitly: by rows ROWS BETWEEN 2 PRECEDING AND CURRENT ROW (the last three rows), by time RANGE BETWEEN INTERVAL '2 days' PRECEDING AND CURRENT ROW (the last three days). ROWS counts physical rows, RANGE a logical range of sort values, including peers. PostgreSQL also has GROUPS. Money uses NUMERIC, not FLOAT, otherwise the sums accumulate error. If the history is large, a running total should not be computed on every request but balance snapshots stored: for a test, a query is enough.
Typical mistakes.
ORDER BY by time without a unique key: equal rows get the same sum.
Forgetting PARTITION BY account_id: the balance accumulates across all accounts together.
Adding all operation types with a plus sign: a withdrawal must subtract (CASE).
Including failed and cancelled operations: the balance is counted only over completed ones.
A filter by balance in the WHERE of the same query: a CTE is needed.
Check yourself
Account operations: +500, −200, +100, −450. What is the balance after each, and what does it hint at to a tester?
Answer
500, 300, 400, −50. The balance went negative after the last operation. If overdraft is forbidden by the requirements, the withdrawal of 450 should have been rejected, and that is a bug candidate.
Why does SUM(amount) OVER (ORDER BY created_at) give the same result for two rows with the same time?
Answer
The default RANGE frame includes all rows equal to the current one by ORDER BY, so they are computed together. For every row to be added separately, add a unique key to ORDER BY or specify ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW.
Related lessons: “What do LAG and LEAD do?”, “How do you check that a balance matches the transaction history?”, “What are window functions and how do they differ from GROUP BY?”.
In an interview.Junior: A running total is computed by SUM with OVER and ORDER BY: everything before is added to each row within the group. This is how I rebuild an account balance at each moment from the transaction history and can find the point where it went negative or diverged from the expected one. Middle/Senior: I remember the default frame: with ORDER BY it is RANGE, so rows with the same sort value are added together. So I add a unique key to the order or write ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. I count only completed operations, keep money in NUMERIC and compare the last value with the account balance.