Double Entry Ledger Invariant Check
Grouping ledger entries by transaction and comparing SUM(debit) with SUM(credit) in HAVING exposes the unbalanced entries a running balance view would hide.
Code
-- 复式记账 (double-entry):每笔交易的平衡不变式 (invariant) 用 HAVING 检查 (check)
CREATE TABLE ledger_entries (
entry_id bigint GENERATED ALWAYS AS IDENTITY,
txn_id int NOT NULL,
account text NOT NULL,
debit_cents numeric NOT NULL DEFAULT 0,
credit_cents numeric NOT NULL DEFAULT 0
);
INSERT INTO ledger_entries (txn_id, account, debit_cents, credit_cents) VALUES
(1, 'cash', 500.00, 0),
(1, 'revenue', 0, 500.00),
(2, 'cash', 120.00, 0),
(2, 'revenue', 0, 119.99); -- 故意差一分
-- 余额视图会正常滚动,只有按笔对账才能暴露不平账
SELECT txn_id,
SUM(debit_cents) AS total_debit,
SUM(credit_cents) AS total_credit
FROM ledger_entries
GROUP BY txn_id
HAVING SUM(debit_cents) <> SUM(credit_cents);
DROP TABLE ledger_entries;Inside the snippet
What runs here is SELECT / INSERT / CREATE — ledger_entries are the objects involved.
Breaking the statements into their working parts: SUM aggregation; a GROUP BY that collapses matching rows into one output row per group; NOT NULL qualifiers on the required columns; DEFAULT values filling omitted columns; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.
Putting it to use
The ledger_entries table is the working surface here.
Core lines
SELECT txn_id,
SUM(debit_cents) AS total_debit,
SUM(credit_cents) AS total_credit
FROM ledger_entries
GROUP BY txn_id
HAVING SUM(debit_cents) <> SUM(credit_cents);
CREATE TABLE ledger_entries (
entry_id bigint GENERATED ALWAYS AS IDENTITY,
txn_id int NOT NULL,
account text NOT NULL,
debit_cents numeric NOT NULL DEFAULT 0,
credit_cents numeric NOT NULL DEFAULT 0
);
INSERT INTO ledger_entries (txn_id, account, debit_cents, credit_cents) VALUES
(1, 'cash', 500.00, 0),
(1, 'revenue', 0, 500.00),
(2, 'cash', 120.00, 0),
(2, 'revenue', 0, 119.99); -- 故意差一分
Interactive Tools for This Topic
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- What objects does the SQL involve?
- `ledger_entries` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.