Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 77/ 160
04. Subqueries & Common Table Expressions (CTEs)

Calculating Running Balances & Period-over-Period Growth

Compute running balances and period growth with CTEs and window helpers.

AdvancedRunning Balance · PoP Growth3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

Start with what you had, add each change, and write down the total at the end of every month.

Think of it like…

A savings jar: what's in it on 31 March is what was in it on 1 March plus that month's deposits and withdrawals, and if you didn't touch it in April, it still holds the same amount at the end of April.

Where you’ve seen it

A wallet app reports each user's month-end balance and monthly change: opening balances come from the account migration table, transactions are summed per month, a running SUM gives each month's closing balance, a month spine fills months with no activity by carrying the last balance forward, and closing - LAG(closing) gives the change.

Words you’ll hear

Opening balance
The balance before the first transaction in your data.
Closing balance
The balance at the end of a period: opening + cumulative net flow.
Flow vs stock
Flows (deposits, revenue) add up over time; stocks (balances) are snapshots.
Carry forward
Using the last known balance for periods with no transactions.

Visual diagram

Loading interactive diagram

Theory & example queries

Closing balances for every period

Aggregate transactions to net flow per account per month first; then the running total is a small window over monthly rows: opening + SUM(net) OVER (PARTITION BY account_id ORDER BY month ROWS UNBOUNDED PRECEDING). The opening balance comes from wherever history starts: a migration snapshot, an opening-balances table, or zero for accounts created inside the data.

Months with no transactions have no row, so they vanish from the report. Cross join a month spine with the accounts (from each account's first month), LEFT JOIN the monthly net flow and COALESCE it to 0; the running sum then naturally carries the balance forward. This is cheaper and more correct than trying to fill gaps after computing balances.

Month-end balances with a spineQuery example
1Input dataStart from the source rows or state that the statement sees.
accounts
2 rows
accounts sample rows
idownerbalance
1Maya1000
2Ravi500
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1WITH2  m AS (3    SELECT4      a.account_id,5      s.month6    FROM7      accounts a8      CROSS JOIN generate_series(9        '2026-01-01'::date,10        '2026-12-01',11        interval '1 month'12      ) AS s (MONTH)13    WHERE14      s.month >= date_trunc('month', a.opened_at)15  ),16  net AS (17    SELECT18      account_id,19      date_trunc('month', txn_at) AS MONTH,20      SUM(amount) AS net21    FROM22      transactions23    GROUP BY24      1,25      226  )27SELECT28  m.account_id,29  m.month,30  COALESCE(ob.amount, 0) + SUM(COALESCE(net.net, 0)) OVER (31    PARTITION BY32      m.account_id33    ORDER BY34      m.month35  ) AS closing36FROM37  m38  LEFT JOIN net USING (account_id, MONTH)39  LEFT JOIN opening_balances ob USING (account_id);
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · SQL expression

Read this line together with the surrounding statement as part of the same SQL expression.

1/39
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative account balance spine3 sample rows
Representative account balance spine
account_idmonthclosing
422026-01-011000
422026-02-011000
422026-03-011350

Note: The sample account opens with 1000, has no February net flow, and receives 350 in March. The COALESCE and running SUM therefore carry the January balance through February.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: Net per period, spine for empty periods, opening + running SUM.

Growth on balances vs flows

Balances are stocks: the balance for March is the closing value, and a quarter's balance is its last month's closing, not the sum of three months. Growth is (closing - LAG(closing) OVER w) / NULLIF(LAG(closing) OVER w, 0), where NULLIF avoids dividing by zero for accounts that started empty; report those as NULL or "new" rather than infinite growth.

Flows such as deposits or revenue are summed within a period, and growth compares period totals. Mixing the two is a classic error: comparing this month's deposits with last month's closing balance, or averaging daily balances by summing them. For an average balance, take the time-weighted average of daily closing balances, which again needs a daily spine.

Month-over-month change in total balancesQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  MONTH,3  SUM(closing) AS total_balance,4  SUM(closing) - LAG(SUM(closing)) OVER (5    ORDER BY6      MONTH7  ) AS change,8  ROUND(9    100.0 * (10      SUM(closing) - LAG(SUM(closing)) OVER (11        ORDER BY12          MONTH13      )14    ) / NULLIF(15      LAG(SUM(closing)) OVER (16        ORDER BY17          MONTH18      ),19      020    ),21    122  ) AS pct23FROM24  month_end_balances25GROUP BY26  MONTH27ORDER BY28  MONTH;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/28
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative monthly balance growth3 sample rows
Representative monthly balance growth
monthtotal_balancechangepct
2026-01-0120000NULLNULL
2026-02-012100010005
2026-03-0120500-500-2.4

Note: Sample totals are across accounts for each month. The first period has no previous balance, and NULLIF would return a NULL percentage if a previous total were zero.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Summing across accounts within a month is fine; summing across months isn't.

Key takeaway: Balances: last value per period, sum across accounts, never across time.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Source

Find the opening balance

Take each account's starting balance from a snapshot or opening-balances table, or 0 for new accounts.

Focus at this step

opening_balances(account_id, amount)

What to watch at this step
Missing
shifts every month
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

A running balance is an opening balance plus the cumulative sum of transactions; period-over-period growth compares one period's value with the previous one. Combining them correctly means three extra steps beyond a simple running total: start from the right opening balance, produce a closing balance for every period (including months with no transactions), and compute growth on balances, which are snapshots, differently from flows like revenue.

Why it matters: Wallets, loans, inventory, subscriptions and bank accounts all need "balance at the end of each month" and "how much did it grow". These reports go wrong in subtle ways: a missing opening balance shifts every number, months without activity disappear, and summing balances across months produces nonsense. Finance and fintech interviews test exactly these details.

When to reach for it

  • Wallet, loan and bank account statements
  • Inventory on hand at month end
  • Deferred revenue and outstanding balance reports

When to avoid or be careful

  • Summing balances across months or quarters
  • Dropping months with no transactions
  • Dividing by a previous balance of zero

Ways to produce period-end balances

Running SUM over monthly net flows
Best for: Reports straight from transaction history

Strengths: Always consistent with transactions; easy to recompute.

Watch out: Needs the opening balance and a spine for empty periods.

Stored daily balance snapshots
Best for: Large ledgers and average-balance reporting

Strengths: Fast reads; average balance is a simple AVG.

Watch out: Snapshots must be produced reliably and reconciled.

Running balance on every transaction row
Best for: Statements showing each line's balance

Strengths: Matches what users see on a statement.

Watch out: More rows than needed for monthly reporting.

Interview signals & numbers to know

When this topic comes up

  • “Month-end balance per customer”
  • “Balance growth month over month”
  • “Months with no transactions are missing”
  • Fintech and ledger questions
  • Stock vs flow metrics

Benchmarks & rules of thumb

opening + Σ net -
closing balance formula
NULLIF(prev, 0) -
safe growth denominator
last value -
how balances roll up over time

Common mistakes & follow-ups

Common interview mistakes

  • Starting the running sum at 0 for migrated accounts that had an opening balance.
  • Reporting a quarter's balance as the sum of its three month-end balances.
  • Running the window over raw transactions and then picking a 'month-end' row, which is wrong for months without activity.

Likely interviewer follow-ups

  • How would you report each account's balance at the end of every month, including inactive months?
  • Why can't you sum balances across months?
  • How do you compute an average daily balance?
Interview tip: Say the word "opening balance" and explain the spine for empty months early. Those two details are where most candidates' answers silently go wrong.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Calculating Running Balances & Period-over-Period Growth with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
Funnel Conversion Analysis Queries with CTEs
Next topic
Identifying Gaps and Islands in Sequential Data