man sql/product
Multiplying rows in SQL: SQLite has no PRODUCT()
Adding up a column in SQL is sum(x). Multiplying a column has no
built-in:
$ sqlite3 :memory: "SELECT product(x) FROM (SELECT 2 AS x);"
Parse error in 2nd command line argument: no such function: product
SQLite’s list of built-in aggregate functions
has avg, count, group_concat, max, median, min, percentile,
percentile_cont, percentile_disc, string_agg, sum and total. No
product. So how do you multiply rows, and which of the usual answers give the
right number? This article tries three, on the sqlite3 CLI that ships with
macOS (Apple’s build of SQLite 3.54.0), and reads the 3.54.0 source for what
each one does.
The logarithm trick
The answer you find first turns a product into a sum:
log(a·b·c) = log a + log b + log c, so exp(sum(ln(x))) is the product.
SQLite has ln() and exp() among its math functions, which this build
compiles in (ENABLE_MATH_FUNCTIONS in PRAGMA compile_options).
$ sqlite3 :memory: "CREATE TABLE f(x INTEGER); INSERT INTO f VALUES (2),(3),(7);" \
"SELECT exp(sum(ln(x))) FROM f;" "SELECT round(exp(sum(ln(x)))) FROM f;"
42.000000000000007
42.0
The result is a float, slightly off, and round() fixes this one. It
doesn’t fix large ones. I generated 200,000 groups of three random integers
between 10 and 99,999, and compared the rounded trick with the exact
product, computed as min*max*(sum-min-max), which is exact for three
integers. The generator:
import random
r = random.Random(7)
with open("triples_rows.csv", "w") as f:
for g in range(200_000):
for x in r.sample(range(10, 100_000), 3):
f.write(f"{g},{x}\n")
And the comparison:
$ sqlite3 :memory: 'CREATE TABLE t(g INTEGER, x INTEGER);' '.import --csv triples_rows.csv t' \
"WITH p AS (SELECT g, exp(sum(ln(x))) AS f, min(x)*max(x)*(sum(x)-min(x)-max(x)) AS exact
FROM t GROUP BY g)
SELECT count(*), sum(CAST(round(f) AS INTEGER) <> exact),
min(CASE WHEN CAST(round(f) AS INTEGER) <> exact THEN exact END) FROM p;"
200000|29914|86521489955620
29,914 wrong out of 200,000, 15%. The smallest wrong one is 17093 × 57691 × 87740 = 86,521,489,955,620, where the trick gives 86,521,489,955,619.48 and rounds down.
The reason is the spacing of doubles. The logarithm of that product is about
32.09, and doubles between 32 and 64 are 2^-47 ≈ 7.1 × 10^-15 apart. exp
turns an absolute error in its input into a relative error in its output,
and 7.1 × 10^-15 of 8.65 × 10^13 is 0.61. So one spacing step in the log sum
is worth 0.61 in the result. Each of the three ln calls, the additions and
the final exp can round by up to half a step, and together they pass the
0.5 that round() can absorb. Here the miss was 0.52. The summation itself
is careful. sum() in func.c switches to Kahan-Babuska-Neumaier
compensated summation as soon as it sees a non-integer.
Two more traps, both silent. SQLite’s math functions “return NULL for domain
errors”, and sum() skips NULLs:
$ sqlite3 :memory: "WITH t(x) AS (VALUES (2),(0),(3)) SELECT exp(sum(ln(x))) FROM t;"
6.0
$ sqlite3 :memory: "WITH t(x) AS (VALUES (-2),(3)) SELECT exp(sum(ln(x))) FROM t;"
3.0000000000000004
A zero disappears from the product instead of making it zero, and a negative number disappears instead of flipping the sign.
A recursive CTE as a fold
To multiply exactly, multiply. SQL has no loop, but a recursive common table
expression is one: it starts from a row and keeps deriving new rows from the
last one. Number the rows, start the fold at (0, 1), and multiply in row
i + 1 at each step:
CREATE TABLE f(x INTEGER);
INSERT INTO f VALUES (2), (3), (7), (11);
WITH RECURSIVE
numbered(i, x) AS (SELECT row_number() OVER (), x FROM f),
fold(i, p) AS (
SELECT 0, 1
UNION ALL
SELECT numbered.i, fold.p * numbered.x
FROM fold JOIN numbered ON numbered.i = fold.i + 1
)
SELECT i, p FROM fold;
$ sqlite3 :memory: < fold.sql
0|1
1|2
2|6
3|42
4|462
The last row is the product. row_number() OVER () numbers rows in the
order they arrive, which is no particular order, and that is fine because
multiplication doesn’t care.
SQLite’s documentation of recursive CTEs
gives the algorithm: “Run the initial-select and add the results to a
queue. While the queue is not empty: extract a single row from the queue,
insert that single row into the recursive table, pretend that the single
row just extracted is the only row in the recursive table and run the
recursive-select, adding all results to the queue.” In select.c this is
generateWithRecursiveQuery(), which codes the queue as a temporary table.
queue: (0,1)
take (0,1) -> join numbered i=1 -> queue (1,2)
take (1,2) -> join numbered i=2 -> queue (2,6)
take (2,6) -> join numbered i=3 -> queue (3,42)
take (3,42) -> join numbered i=4 -> queue (4,462)
take (4,462) -> no i=5 -> queue empty, stop
The numbering has to live in its own CTE. generateWithRecursiveQuery()
starts by refusing window functions:
$ sqlite3 :memory: "WITH RECURSIVE c(n) AS (SELECT 1 UNION ALL
SELECT row_number() OVER () FROM c WHERE n < 3) SELECT * FROM c"
Parse error in 2nd command line argument: cannot use window functions in recursive queries
The recursive part runs once per queue row
That algorithm has a cost that is easy to miss. The recursive-select runs
once for every row taken from the queue, and everything it references runs
with it. If numbered is a cheap table, nobody notices. Here the rows to
multiply are the three most frequent values of a 100,000-row table in a
file art.db:
CREATE TABLE visits(user_id INTEGER);
WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 100000)
INSERT INTO visits
SELECT (i * 7919 % 100003) * (i * 104729 % 99991) % 50000 FROM n;
The fold, saved as foldtop.sql:
WITH RECURSIVE
top(i, user_id) AS (
SELECT row_number() OVER (), user_id
FROM (SELECT user_id FROM visits GROUP BY user_id ORDER BY count(*) DESC LIMIT 3)
),
fold(i, p) AS (
SELECT 0, 1
UNION ALL
SELECT top.i, fold.p * top.user_id
FROM fold JOIN top ON top.i = fold.i + 1
)
SELECT p FROM fold ORDER BY i DESC LIMIT 1;
$ sqlite3 art.db ".scanstats on" ".read foldtop.sql"
12840000000000
QUERY PLAN
|--CO-ROUTINE fold
| |--SETUP
| | `--SCAN CONSTANT ROW
| `--RECURSIVE STEP
| |--CO-ROUTINE top
| | |--CO-ROUTINE (subquery-6)
| | | |--CO-ROUTINE (subquery-1)
| | | | |--SCAN visits 4 400K
| | | | |--USE TEMP B-TREE FOR GROUP BY 4 400K
...
SCAN visits ran 4 times, once per queue row (i = 0, 1, 2, 3; the fourth
finds nothing to join). top is used once in the query text, so SQLite
didn’t materialize it. fromClauseTermCanBeCoroutine() in select.c lists
the conditions for a co-routine. One of them is that the subquery is not a
CTE that should be materialized because “the AS MATERIALIZED keyword is
used, or the CTE is used multiple times and does not have the NOT
MATERIALIZED keyword”. A
co-routine produces its rows on demand and starts over each time the
recursive step needs them.
AS MATERIALIZED makes SQLite compute top once into a temporary table:
$ sed 's/top(i, user_id) AS (/top(i, user_id) AS MATERIALIZED (/' foldtop.sql > foldtop_m.sql
$ sqlite3 art.db ".scanstats on" ".read foldtop_m.sql"
12840000000000
QUERY PLAN
|--CO-ROUTINE fold
| |--SETUP
| | `--SCAN CONSTANT ROW
| `--RECURSIVE STEP
| |--MATERIALIZE top
| | |--CO-ROUTINE (subquery-6)
| | | |--CO-ROUTINE (subquery-1)
| | | | |--SCAN visits 1 100K
...
The docs advise against the hint “unless you have a compelling reason”. Scanning a table four times instead of once is one.
When the integers overflow
The fold multiplies 64-bit integers, so it is exact until the product
passes 2^63 - 1. Then SQLite does not raise an error. In vdbe.c,
OP_Multiply tries sqlite3MulInt64() and on overflow jumps to fp_math,
which redoes the operation in doubles:
$ sqlite3 :memory: "SELECT 3037000500 * 3037000500, typeof(3037000500 * 3037000500);"
9.2233720370002493e+18|real
The exact answer is 9,223,372,037,000,250,000. sum() behaves the other
way: the docs say it “will throw an ‘integer overflow’ exception if all
inputs are integers or NULL and an integer overflow occurs”:
$ sqlite3 :memory: "WITH t(x) AS (VALUES (9223372036854775807), (1)) SELECT sum(x) FROM t;"
Error in 2nd command line argument: integer overflow
So a fold of 1 to 25 is an integer up to 20! and a float after it:
$ sqlite3 :memory: "WITH RECURSIVE c(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM c WHERE i < 25),
fold(i, p) AS (SELECT 0, 1 UNION ALL SELECT c.i, fold.p * c.i FROM fold JOIN c ON c.i = fold.i + 1)
SELECT i, p, typeof(p) FROM fold WHERE i IN (20, 21, 25);"
20|2432902008176640000|integer
21|5.109094217170944e+19|real
25|1.5511210043330986e+25|real
For exact big products, the CLI has one more tool. Its source includes
SQLite’s decimal extension (INCLUDE ../ext/misc/decimal.c in
shell.c.in), which works on decimal strings. It has decimal_mul() and a
decimal_sum() aggregate, and no product aggregate, but the same fold works
with it:
$ sqlite3 :memory: "WITH RECURSIVE c(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM c WHERE i < 25),
fold(i, p) AS (SELECT 0, '1' UNION ALL SELECT c.i, decimal_mul(fold.p, c.i) FROM fold JOIN c ON c.i = fold.i + 1)
SELECT i, p FROM fold WHERE i IN (21, 25);"
21|51090942171709440000
25|15511210043330985984000000
Both match Python’s math.factorial.
When the count is fixed
If there are always exactly N rows, no recursion is needed. Number them and
pick each one out with FILTER (SQLite 3.30.0 and later):
WITH numbered AS (SELECT x, row_number() OVER () AS i FROM f)
SELECT max(x) FILTER (WHERE i = 1)
* max(x) FILTER (WHERE i = 2)
* max(x) FILTER (WHERE i = 3)
FROM numbered;
For exactly three integers, min(x) * max(x) * (sum(x) - min(x) - max(x))
works too, since the middle value is the sum minus the other two. It is
what I used above as the exact reference.
An application that embeds SQLite can also register its own aggregate with
sqlite3_create_function(),
giving it a step and a final callback. That is how product() would get
into a particular program.
Curious facts
exp(sum(ln(x)))drops zeros and negative numbers without an error, becauseln()returns NULL for them andsum()ignores NULLs.- Integer
*overflows into a float silently. Integersum()overflows into an error.total()never errors: on the same input it returns9.2233720368547758e+18. sum(),total()andavg()share one step function,sumStep(), and one inverse function,sumInverse(), which subtracts a row’s value when the row leaves a window frame.- In a recursive CTE, a non-recursive CTE referenced once from the recursive part is recomputed for every queue row, unless it is materialized.
- The CLI’s
decimal_sum()is registered withsqlite3_create_window_function(), so it also works as a window function.
History
- 3.8.3 (2014-02-03): common table expressions and the
WITHclause. - 3.25.0 (2018-09-15): window functions, including
row_number(). - 3.25.3 (2018-11-05): window functions are disallowed in the recursive part of a CTE.
- 3.30.0 (2019-10-04): the
FILTERclause on aggregate functions. - 3.35.0 (2021-03-12): built-in math functions such as
ln()andexp()(behind-DSQLITE_ENABLE_MATH_FUNCTIONS), and theMATERIALIZEDandNOT MATERIALIZEDhints. The same release changed the default to materialize CTEs “that are used more than once”.
Sources
src/func.cat version-3.54.0 (GitHub mirror): SumCtx and Kahan-Babuska-Neumaier, sumStep and sumInverse, sum, total, avg registrationsrc/vdbe.cat version-3.54.0: OP_Multiply and fp_mathsrc/select.cat version-3.54.0: generateWithRecursiveQuery, fromClauseTermCanBeCoroutineext/misc/decimal.cat version-3.54.0: function registration;src/shell.c.inincludes it- Docs: built-in aggregate functions, math functions, the WITH clause (sections 3 and 4), window functions, sqlite3_create_function, release history: 3.8.3, 3.25.0, 3.25.3, 3.30.0, 3.35.0
grep -rl /lib/sql/product/
ls sql/
- draft How SQLite runs GROUP BY and ORDER BY ... LIMITWhat EXPLAIN QUERY PLAN's "USE TEMP B-TREE" lines really are in SQLite 3.54: GROUP BY is a merge sort, ORDER BY with a LIMIT keeps only LIMIT rows in a small B-tree, and the GROUP BY quietly borrows the ORDER BY's direction.