Home » Radim Marek: Same rows, different SUM

Radim Marek: Same rows, different SUM

By

–

Computer Server

Run one query on an untouched table three times and PostgreSQL hands back three different totals: 2500519211.7874823, then 2500519211.787477, then 2500519211.7874575. No update ran. No other writer touched the rows. The statement was the same character for character. Radim Marek built his June 28 post on the boringSQL blog, titled Same rows, different SUM, around exactly this exercise: five million floating-point readings, summed three times, answering three ways.

The puzzle, Marek writes, is not the rule every database developer has memorised. The warning against storing money as a double precision is “so well drilled that it has stopped being interesting,” and it is not where the trouble usually starts. By the time anyone weighs in, the float is already in the schema. A sensor column gets loaded for engineering work and later turns up in a revenue report. A vendor feed arrives as double precision because that is how the vendor sent it.

Addition that refuses to associate

On paper, (a + b) + c and a + (b + c) are the same number. In a database, each intermediate result gets rounded to fit 64 bits, so moving the parentheses moves the roundings. Marek’s demonstration is one line of SQL: add 1.0 to 1.0e20, then subtract 1.0e20. The answer should be 1. PostgreSQL returns 0. A double carries roughly 16 significant digits, and 1.0e20 plus 1 needs 21 of them, so the trailing 1 falls off before the subtraction ever runs. He calls this absorption, and the same expression returns 0 in C, Python and JavaScript, anywhere IEEE 754 doubles live.

A double precision value keeps 52 bits for the mantissa, about 15 to 17 decimal digits. When the running total grows large and the next number is small, the small one cannot fit into what is left, and rounding throws its tail away. Sum five million rows and the total dwarfs every single addition. The sum of a column, Marek concludes, depends not on which rows exist but on the order they are added.

Why parallel queries move the answer

Because the five-million-row table is big enough, Postgres parallelises the sum on its own. The plan gives two workers, each summing whatever blocks it grabs from a shared iterator, and a final step folds the partial sums together. Which blocks land with which worker is a race the operating system scheduler decides, so the split differs on every run. The partials then return in arrival order, and combining three of them, two workers plus the leader process, is itself an associativity question.

sum(float8) is marked parallel-safe. Safe, Marek writes, “in the sense that it will not crash or corrupt anything,” not in the sense “that the answer is a function of the input.” AVG, STDDEV and VARIANCE inherit the same order sensitivity.

The flakiness was never really about parallelism.

Switch it off and the total settles at 2500519211.787516, three runs in a row. That holds only because a serial scan walks the table in the same physical order each time. Even then there is a wrinkle: with synchronize_seqscan on by default, a second scan of a large table can start from the block where an earlier scan currently sits and wrap around, handing the sum a different starting point with no parallelism involved. It is, in Marek’s phrasing, “the same order-dependence, entering through a different door.” Forcing an order moves the number too: summing by id gives 2500519211.787516, by reading gives 2500519211.7876067, by reading descending gives 2500519211.7875423.

Stable is not the same as correct

Cast the column to numeric, which adds in exact decimal and defers rounding to the very end, and the true total is 2500519211.787503050078417764. Every floating-point result above misses it, by about 1.3e-5 in the serial case and about 1.0e-4 when the rows are summed smallest to largest. Order changes the error; it does not reliably shrink it. Compensated-summation algorithms such as Kahan’s exist, Marek notes, but a SQL aggregate offers no way to choose one.

Here is the encouraging part for anyone who needs the exact figure: one cast to numeric removes the rounding entirely. What parallelism took away was the comfort of “getting the same wrong answer every time,” a property people often mistake for correctness.

Where it actually bites

In the sixth decimal of a five-million-row test sum, nobody cares. Marek’s concern is the places where someone does. Finance teams meet the problem in reconciliation: a revenue column stored as double precision sums to one figure, and the same query an hour later, or the same logic in another tool at a different parallel degree, produces another. Nothing in the data changed, so the hunt runs to caching, replicas, a dirty read somewhere, long before anyone suspects the aggregate itself. Regression tests flap the same way, passing on a small serial fixture, then failing in continuous integration once a bigger dataset tips past the parallel threshold, though the code never changed. And wherever a float sum feeds an equality check, a join or a grouping key, Marek warns that you are “building on sand”: two totals differing in their last bits can silently drop rows.

That Postgres treats the hazard as real is, in Marek’s view, the strongest evidence it is not a corner case. Window functions can compute a moving sum cheaply by subtracting each value as it leaves the frame rather than re-summing the window. The shortcut works for numeric and integers. For the floating-point types, Postgres withholds it.

The discrepancy lives in the fifth and sixth decimal places: small enough to ignore in most dashboards, large enough to break a reconciliation. The encouraging part is that the exact total sits one cast away, in numeric, whenever the figure has to agree with itself an hour later. When the numbers feed money, talk to your database administrator.

Sources

Get breaking stories first on our Telegram channel.

More stories by

Most read

Crime & Fraud

People in the News

News

World News