Accounting for DevelopersModule 2: Data model and designIntermediate3 min read
Building a Trial Balance from Ledger Data
Build a trial balance from ledger postings using SQL and TypeScript: normal balances, as-of-date and period queries, invariants, tests and balance snapshots.
Course outline (16 lessons)
Before this lesson:Journal and General Ledger Database DesignTrial Balance
In this lesson · 8 sections
A trial balance is the first report you build on top of accounts, journal_entries and postings. It sums every account’s postings as of a cutoff date, places each net balance into a debit or credit column, and checks that both column totals match.
Σ debit_minor = Σ credit_minor (equivalently, Σ amount_minor = 0)
- amount_minor
- signed integer posting in minor units (debit > 0, credit < 0)
- debit_minor
- max(net_minor, 0) for each account
- credit_minor
- max(-net_minor, 0) for each account
As-of-date SQL aggregation
Using the debit-positive convention from journal and general ledger database design, an as-of trial balance sums postings up to an effective_date for one entity and one currency:
SELECT
a.id AS account_id,
a.code,
a.name,
a.type,
a.normal_balance,
SUM(p.amount_minor) AS net_minor,
GREATEST(SUM(p.amount_minor), 0) AS debit_minor,
GREATEST(-SUM(p.amount_minor), 0) AS credit_minor
FROM postings p
JOIN journal_entries e ON e.id = p.entry_id
JOIN accounts a ON a.id = p.account_id
WHERE e.entity_id = :entity_id
AND e.effective_date <= :as_of
AND p.currency = :currency
GROUP BY a.id, a.code, a.name, a.type, a.normal_balance
HAVING SUM(p.amount_minor) <> 0
ORDER BY a.code;
Notice that debit_minor and credit_minor depend on the sign of net_minor, not on normal_balance. An asset account with a temporary credit balance (such as an overdrawn bank account) belongs in the credit column, not as a negative number in the debit column.
Period filtering vs cumulative balances
Engineers often confuse two different views:
- Cumulative as-of trial balance (
effective_date <= :as_of) — sums from ledger inception through:as_of. This is required for permanent balance sheet accounts (assets, liabilities, equity). If prior years were closed to retained earnings, revenue and expense accounts only reflect the current fiscal year. - Period movement trial balance — splits each account into three pieces: opening balance (
effective_date < :period_start), period debits and credits (effective_date BETWEEN :period_start AND :period_end), and closing balance (effective_date <= :period_end).
SELECT
a.code,
a.name,
COALESCE(SUM(p.amount_minor) FILTER (WHERE e.effective_date < :start), 0) AS opening_minor,
COALESCE(SUM(p.amount_minor) FILTER (
WHERE e.effective_date >= :start AND p.amount_minor > 0), 0) AS period_debit_minor,
COALESCE(SUM(-p.amount_minor) FILTER (
WHERE e.effective_date >= :start AND p.amount_minor < 0), 0) AS period_credit_minor,
COALESCE(SUM(p.amount_minor), 0) AS closing_minor
FROM postings p
JOIN journal_entries e ON e.id = p.entry_id
JOIN accounts a ON a.id = p.account_id
WHERE e.entity_id = :entity_id
AND e.effective_date <= :end
AND p.currency = :currency
GROUP BY a.code, a.name
ORDER BY a.code;
Shaping the trial balance in TypeScript
Once SQL returns raw sums per account (or when aggregating in memory for tests), convert signed bigint minor units into debit/credit columns, flag abnormal balances against normalBalance, and assert the global invariant before returning the report.
type NormalSide = "debit" | "credit";
interface RawAccountTotal {
accountId: string;
code: string;
name: string;
normalBalance: NormalSide;
netMinor: bigint; // debit > 0, credit < 0
}
interface TrialBalanceRow {
code: string;
name: string;
debitMinor: bigint;
creditMinor: bigint;
isAbnormal: boolean;
}
interface TrialBalance {
currency: string;
asOf: string;
rows: TrialBalanceRow[];
totalDebitMinor: bigint;
totalCreditMinor: bigint;
}
function buildTrialBalance(
totals: RawAccountTotal[],
currency: string,
asOf: string,
): TrialBalance {
const rows: TrialBalanceRow[] = [];
let totalDebitMinor = 0n;
let totalCreditMinor = 0n;
for (const acc of totals) {
if (acc.netMinor === 0n) continue;
const debitMinor = acc.netMinor > 0n ? acc.netMinor : 0n;
const creditMinor = acc.netMinor < 0n ? -acc.netMinor : 0n;
const isAbnormal =
(acc.normalBalance === "debit" && acc.netMinor < 0n) ||
(acc.normalBalance === "credit" && acc.netMinor > 0n);
totalDebitMinor += debitMinor;
totalCreditMinor += creditMinor;
rows.push({ code: acc.code, name: acc.name, debitMinor, creditMinor, isAbnormal });
}
if (totalDebitMinor !== totalCreditMinor) {
throw new Error(
`Trial balance out of balance in ${currency}: Dr ${totalDebitMinor} != Cr ${totalCreditMinor}`,
);
}
return { currency, asOf, rows, totalDebitMinor, totalCreditMinor };
}
Worked example
Kestrel Cloud (fictional) — trial balance as of 31 March 2026 (USD)
During its first month, Kestrel Cloud posts eight balanced entries: owner capital invested ($20,000), equipment bought for cash ($4,500), depreciation recorded ($250), client invoices billed ($8,400), client cash collected ($6,200), annual prepayment received ($1,800), hosting billed on credit ($1,150) and salaries paid ($3,200).
Aggregating postings with effective_date <= '2026-03-31' in minor units (cents) produces:
| Code | Account | Normal side | Net (amount_minor) |
Debit | Credit |
|---|---|---|---|---|---|
| 1000 | Cash | Debit | +2,030,000 | $20,300.00 | |
| 1100 | Accounts Receivable | Debit | +220,000 | $2,200.00 | |
| 1500 | Equipment | Debit | +450,000 | $4,500.00 | |
| 1510 | Accumulated Depreciation | Credit | −25,000 | $250.00 | |
| 2000 | Accounts Payable | Credit | −115,000 | $1,150.00 | |
| 2100 | Unearned Revenue | Credit | −180,000 | $1,800.00 | |
| 3000 | Owner’s Capital | Credit | −2,000,000 | $20,000.00 | |
| 4000 | Subscription Revenue | Credit | −840,000 | $8,400.00 | |
| 5100 | Hosting Expense | Debit | +115,000 | $1,150.00 | |
| 5200 | Salaries Expense | Debit | +320,000 | $3,200.00 | |
| 5300 | Depreciation Expense | Debit | +25,000 | $250.00 | |
| Total | 0 | $31,600.00 | $31,600.00 |
Check both columns: $20,300 + $2,200 + $4,500 + $1,150 + $3,200 + $250 = $31,600, and $250 + $1,150 + $1,800 + $20,000 + $8,400 = $31,600. Notice 1510 Accumulated Depreciation is an asset account with a credit normal balance, so isAbnormal stays false. You can experiment with entries feeding a live trial balance in the Accounting Playground.
Scaling with balance snapshots
Summing millions of historical postings on every report request gets slow. Once an accounting period is locked, store its closing balances in an immutable snapshot table:
CREATE TABLE account_period_snapshots (
entity_id uuid NOT NULL,
period_end_date date NOT NULL,
account_id uuid NOT NULL REFERENCES accounts(id),
currency char(3) NOT NULL,
net_minor bigint NOT NULL,
PRIMARY KEY (entity_id, period_end_date, account_id, currency)
);
To build a trial balance for :as_of, find the latest closed snapshot <= :as_of, then UNION ALL those snapshot rows with postings whose effective_date lies strictly after the snapshot date and <= :as_of, and SUM by account. Because closed periods reject back-dated writes, the snapshot cannot go stale.
Invariants and tests
Automated tests should verify:
- Global balance: for any sequence of valid entries,
totalDebitMinor === totalCreditMinorfor every currency and everyasOfdate. - Currency isolation: postings in
USDandEURnever combine into one total. - Cutoff accuracy: an entry dated
2026-04-01does not appear in a2026-03-31trial balance, even if created on2026-03-31. - Abnormal balance detection: a debit balance on a credit-normal account sets
isAbnormal = trueand still lands indebitMinor. - Snapshot parity: the snapshot-accelerated query equals a full scan of
postingsdown to the last minor unit.
Real-world application
Finance teams run a trial balance at month-end before preparing the balance sheet and income statement, and auditors request it to tie subledgers back to the general ledger. For engineering teams, running a scheduled trial balance check across all active entities and currencies is also a high-signal health check: any imbalance alerts you immediately to a broken write path or stale snapshot.
Recap
- Aggregate signed
postingsper account witheffective_date <= :as_ofand a singlecurrency. - Split positive sums into
debit_minorand negative sums intocredit_minor; usenormal_balanceto flag abnormal signs. - Assert
totalDebitMinor === totalCreditMinorin code and in tests. - Use closed-period snapshots plus delta postings to keep queries fast, and verify snapshots against raw postings.
Try it yourself
Active recall
Quick check · Test yourself
Work out each answer in your head first, then reveal the explanation and mark whether you got it right.
1Why must a trial balance SQL query filter by effective_date and a single currency?
Show worked answer
Filtering by effective_date <= :as_of reproduces the books at a specific cutoff even when later entries exist. Filtering by a single currency prevents adding incompatible minor units (such as USD cents and JPY yen), because double-entry entries balance per currency.
2Accounts Payable (credit-normal) has a raw signed sum of +15000 minor units ($150.00). Which column does it go in, and why does normal_balance still matter?
Show worked answer
It goes in the Debit column as $150.00 because the net balance is positive (debit). Comparing the sign against normal_balance = 'credit' flags it as an abnormal balance — such as an overpaid supplier or unapplied vendor credit — for finance to investigate.
3A closing snapshot at 31 March holds Cash at +500000 minor units ($5,000.00). April postings to Cash sum to -120000 (-$1,200.00). What is Cash on the 30 April trial balance?
Show worked answer
+500000 + (-120000) = +380000 minor units, or $3,800.00 in the Debit column. Periodically verify the snapshot by summing all postings with effective_date <= '2026-03-31' and asserting the result equals +500000.
Key terms in this lesson
Lesson 5 of 16 · Accounting for Developers
Finished this lesson?
Mark it complete to track your progress through the course. Progress is saved in this browser only.
Previous lesson: Journal and General Ledger Database Design
Connected lessons
Educational content only—not accounting, tax, legal or investment advice. See our editorial policy or report an error via our corrections policy.