Skip to content

Money and ledgers

Money tasks look like ordinary sums, and they fail in quiet ways: a balance computed over a date window, a float that loses cents, rounding on every row. The examples use the advances program of the practice data: its ledger is one table of signed entries, and every balance is a SUM over it.

The platform pays a merchant early, against a marketplace payout that has not arrived yet. An advance is at most 70 % of the proceeds expected for that channel and month, and the merchant pays a fee of 3 % of the advance. When the payout arrives, it repays the advance and the fee. The details are on the dataset page; two tables matter here:

  • advances: one row per advance, with amount_usd and fee_usd.
  • ledger_entries: one row per money movement.
entry_typesignwhen it is written
advance+the platform pays the merchant
fee+at the same moment as the advance
repayment−when the channel payout arrives

One advance, adv_0001, in the ledger:

SELECT entry_id, entry_type, amount_usd, created_at
FROM ledger_entries
WHERE advance_id = 'adv_0001'
ORDER BY created_at, entry_id;
entry_identry_typeamount_usdcreated_at
le_00001advance68.382026-07-02 10:00:00
le_00002fee2.052026-07-02 10:00:00
le_00003repayment-70.432026-08-02 09:00:00

The entries add up to 0, so this advance is repaid. For all 38 advances, fee_usd equals ROUND(amount_usd * 0.03, 2).

A flow is a sum over a period: revenue for a month, advances paid in August, fees per quarter. It always has a window: created_at >= start AND created_at < end.

A balance is a state at a moment: what a merchant owes, the money on an account, the subscriptions active today. It is the sum of everything before that moment. It has an upper bound and no lower bound.

For mer_01, a flow and a balance:

SELECT SUM(amount_usd) AS advanced_usd -- flow: a window of one month
FROM ledger_entries
WHERE merchant_id = 'mer_01'
AND entry_type = 'advance'
AND created_at >= TIMESTAMP '2026-08-01'
AND created_at < TIMESTAMP '2026-09-01';
SELECT SUM(amount_usd) AS owed_usd -- balance: all history up to the moment
FROM ledger_entries
WHERE merchant_id = 'mer_01'
AND created_at < TIMESTAMP '2026-09-01';
advanced_usd
145.09
owed_usd
50.21

The usual mistake is a window on a balance:

SELECT SUM(amount_usd) AS owed_usd -- wrong: a window on a balance
FROM ledger_entries
WHERE merchant_id = 'mer_01'
AND created_at >= TIMESTAMP '2026-09-01' - INTERVAL '30 days'
AND created_at < TIMESTAMP '2026-09-01';

The answer is −20.22. The window cuts off the advances paid on 2 July but keeps the repayment of adv_0001 on 2 August. A negative debt is a sign that the window is wrong. When the task is unclear, ask: “Is this a total for a period, or a state at a moment?”

A running sum over the ledger shows how the balance moves. It is a window function, as on Shares and running totals:

SELECT created_at, advance_id, entry_type, amount_usd,
SUM(amount_usd) OVER (ORDER BY created_at, entry_id) AS balance_usd
FROM ledger_entries
WHERE merchant_id = 'mer_01'
AND created_at < TIMESTAMP '2026-09-01'
ORDER BY created_at, entry_id;

Rows 6 to 11 of 11:

created_atadvance_identry_typeamount_usdbalance_usd
2026-08-02 09:00:00adv_0001repayment-70.430.00
2026-08-02 10:00:00adv_0002advance48.7548.75
2026-08-02 10:00:00adv_0002fee1.4650.21
2026-08-02 10:00:00adv_0005advance96.34146.55
2026-08-02 10:00:00adv_0005fee2.89149.44
2026-08-15 09:00:00adv_0005repayment-99.2350.21

The balance falls to 0.00 when the payout for June repays adv_0001. The last balance, 50.21, is the same number as the query above: it is adv_0002, which waits for the July North Market payout. entry_id as the second sort key keeps the order stable when entries share a timestamp.

The ledger never changes a row. Every movement is a new row, and a correction is a new entry with the opposite sign, not an UPDATE. This gives three things:

  • History. The balance at any past moment is the same query with another date.
  • Audit. Every cent of a balance can be traced to the rows behind it.
  • Safe retries. A retry must not write a second advance. advances.idempotency_key (merchant:channel:month) with a unique index stops it in the database: see Duplicates and idempotency.

Many systems also keep the current balance in its own column, for fast reads. They update it in the same transaction as the new entry, so the two never disagree (see Database concepts).

double precision and real are binary fractions. Most decimal amounts, such as 0.1, have no exact binary form, and the error shows up in sums:

SELECT 0.1::float8 + 0.2::float8 AS float_sum,
0.1::float8 + 0.2::float8 = 0.3::float8 AS float_equal,
0.1::numeric + 0.2::numeric AS numeric_sum,
0.1::numeric + 0.2::numeric = 0.3 AS numeric_equal;
float_sumfloat_equalnumeric_sumnumeric_equal
0.30000000000000004false0.3true

Added up a thousand times, 0.1 gives 99.9999999999986 as a float and 100.0 as NUMERIC.

NUMERIC keeps decimal digits exactly. In a table, give it a precision: NUMERIC(12, 2) holds 12 digits, 2 of them after the point. Such a column rounds on insert: 10.005 is stored as 10.01 and 10.004 as 10.00. A value that does not fit fails with numeric field overflow. In Python, the same role is played by Decimal (see Money and Decimal).

What the merchant gets for a sale is charged_usd * (1 - fee_rate). A 2.99 sale at 15 % gives 2.5415. Round each row to cents, and each such row loses 0.0015:

SELECT channel,
COUNT(*) AS n,
ROUND(SUM(charged_usd * (1 - fee_rate)), 2) AS round_once,
SUM(ROUND(charged_usd * (1 - fee_rate), 2)) AS round_each_row
FROM transactions
WHERE NOT is_test
AND channel IN ('north_market', 'south_market', 'web')
AND start_time >= TIMESTAMP '2026-09-01'
AND start_time < TIMESTAMP '2026-10-01'
GROUP BY channel
ORDER BY channel;
channelnround_onceround_each_row
north_market2542490.742490.32
south_market1511858.891858.64
web55732.84732.83

The North Market total is 42 cents short after one month. Keep full precision inside the query and round only the number you report. If the business rounds per transaction, it will say so; ask.

ROUND(x, 2) exists only for NUMERIC. With a double precision value, for example from PERCENTILE_CONT or a float column, the call fails: function round(double precision, integer) does not exist. Cast first: ROUND(CAST(x AS NUMERIC), 2).

The two types also round halves differently:

expressionresult
ROUND(0.125, 2)0.13
ROUND(2.5)3
ROUND(2.5::float8)2
ROUND(CAST(0.125::float8 AS NUMERIC), 2)0.13

PostgreSQL rounds NUMERIC halves away from zero. Python’s round() on a Decimal rounds halves to even, so round(Decimal("0.125"), 2) is 0.12. When SQL and Python must agree, use quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) in Python.

SQLWrite a query

Fee income from advances per month in 2026 from ledger_entries (entry_type = 'fee'), entries before 2026-09-30. Month as DATE.

Output columns: month, fees_usdOrder: ORDER BY month

Tables, columns and how they connect

ledger_entries — ledger of money movements for advances; rows are only added, never changed

  • entry_type — advance (+) / fee (+) / repayment (−)
  • amount_usd — signed amount; the merchant's debt = SUM(amount_usd)
  • created_at — when it was recorded
entry_typeamount_usdcreated_at
advance68.382026-07-02 10:00:00
advance48.752026-08-02 10:00:00
advance96.342026-09-02 10:00:00

"Today" is 2026-09-30 00:00 UTC. All times are UTC. Every run is rolled back, so you cannot break the data.

-- your query here
Show answer

Reference

SELECT CAST(date_trunc('month', created_at) AS DATE) AS month,
SUM(amount_usd) AS fees_usd
FROM ledger_entries
WHERE entry_type = 'fee'
AND created_at >= TIMESTAMP '2026-01-01'
AND created_at < TIMESTAMP '2026-09-30'
GROUP BY 1
ORDER BY 1;

Expected output

monthfees_usd
2026-06-016.42
2026-07-0152.68
2026-08-0143.90
2026-09-0141.71
4 rows

This is a flow: the sum of fee entries per month. The month comes from the entry date, CAST(date_trunc('month', created_at) AS DATE), and only entries of 2026 before today count. A balance would be a different question: the sum of all entries, with no month in it.

SQLWrite a querycore

Outstanding balance per merchant from the ledger (all entries before 2026-09-30), only merchants who owe more than 0. Highest first.

Output columns: merchant_id, outstanding_usdOrder: ORDER BY outstanding_usd DESC, merchant_id

Tables, columns and how they connect

ledger_entries — ledger of money movements for advances; rows are only added, never changed

  • merchant_id — → merchants.id
  • amount_usd — signed amount; the merchant's debt = SUM(amount_usd)
  • created_at — when it was recorded
merchant_idamount_usdcreated_at
mer_012.052026-07-02 10:00:00
mer_01-70.432026-08-02 09:00:00
mer_0168.382026-07-02 10:00:00

"Today" is 2026-09-30 00:00 UTC. All times are UTC. Every run is rolled back, so you cannot break the data.

-- your query here
Show answer

Reference

SELECT merchant_id, SUM(amount_usd) AS outstanding_usd
FROM ledger_entries
WHERE created_at < TIMESTAMP '2026-09-30'
GROUP BY merchant_id
HAVING SUM(amount_usd) > 0
ORDER BY outstanding_usd DESC, merchant_id;

Expected output

merchant_idoutstanding_usd
mer_11619.68
mer_09241.30
mer_04172.03
mer_01129.21
mer_03116.39
mer_07105.31
6 rows

The ledger is append-only: advance and fee are positive, repayment is negative. The balance is the sum of all entries before today. It is a balance, not a flow, so there is no 30-day window. HAVING SUM(amount_usd) > 0 keeps the merchants who still owe, after grouping. Keep the sign: SUM(ABS(amount_usd)) would count every repayment as more debt. merchant_id as the second sort key makes the order stable.

Site content: CC BY 4.0. Code: MIT. The exercises run in your browser: PostgreSQL by PGlite, Python by Pyodide.