← Back to SQL, page 5

sql-0088 · Hard senior

What happens when SUM goes past the largest 64-bit integer in SQLite and in PostgreSQL?

SQLite's SUM raises an 'integer overflow' error when an all-integer sum exceeds 2^63 - 1, while TOTAL() switches to floating point and loses precision silently. PostgreSQL's SUM of bigint returns numeric, which has arbitrary precision, so it returns the exact result. Arithmetic with + on bigints in PostgreSQL does raise an out-of-range error.

Full answer

The largest signed 64-bit integer is 9223372036854775807. Totals of large values, such as amounts in the smallest currency unit over many years, can approach it.

sql
CREATE TABLE ledger (amount INTEGER);
INSERT INTO ledger VALUES (9223372036854775807), (1);

SQLite's SUM refuses to give a wrong answer:

sql
SELECT SUM(amount) FROM ledger;  -- error on purpose
text
Error: integer overflow

SQLite's TOTAL() uses floating point, so it returns a result, but the low digits are lost:

sql
SELECT TOTAL(amount) AS total_float FROM ledger;
total_float
9.223372036854776e+18

PostgreSQL's SUM over bigint returns numeric, so it is exact:

sql
SELECT SUM(amount) AS exact_sum, pg_typeof(SUM(amount)) AS type FROM ledger;
exact_sumtype
9223372036854775808numeric

Plain addition of two bigints in PostgreSQL still overflows:

sql
SELECT 9223372036854775807::bigint + 1::bigint;  -- error on purpose
text
Error: bigint out of range

So the engines differ on which operation is safe. For money totals, PostgreSQL's numeric result is convenient. In SQLite, an overflow error is better than a silent rounding, and the usual remedy is choosing units so totals stay far from the limit.

sql
CREATE TABLE ledger (amount INTEGER);
INSERT INTO ledger VALUES (9223372036854775807), (1);

-- error on purpose
SELECT SUM(amount) FROM ledger;

SELECT TOTAL(amount) AS total_float FROM ledger;

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • Max 64-bit signed integer is 9223372036854775807
  • SQLite SUM raises integer overflow; TOTAL() returns an imprecise float
  • PostgreSQL SUM(bigint) returns exact numeric
  • PostgreSQL bigint + bigint can still overflow

Common mistakes

  • Assuming every engine silently promotes to a bigger type
  • Using a floating-point total for money and losing cents

Follow-ups

  • What type does SUM(integer) return in PostgreSQL?
  • How would you store large monetary amounts safely?

Tips

  • Mention the exact limit; it shows you know what 'large' means here