sun(), total(), avg() overflow in the window function
(1) By ChiZhang on 2026-05-15 12:02:16 [source]
Hi,
I found the sum(), total(), and avg() can overflow in the window function.
This test case can reproduce this:
WITH t(id,x) AS (
VALUES
(1,-1),
(2,9223372036854775807),
(3,1),
(4,0.5)
)
SELECT id,
sum(x) OVER (
ORDER BY id ROWS BETWEEN CURRENT ROW AND 2 FOLLOWING
) AS win_sum,
total(x) OVER (
ORDER BY id ROWS BETWEEN CURRENT ROW AND 2 FOLLOWING
) AS win_total,
avg(x) OVER (
ORDER BY id ROWS BETWEEN CURRENT ROW AND 2 FOLLOWING
) AS win_avg,
(SELECT total(x) FROM t t2 WHERE t2.id BETWEEN t1.id AND t1.id+2)
AS ref_total,
(SELECT avg(x) FROM t t2 WHERE t2.id BETWEEN t1.id AND t1.id+2)
AS ref_avg
FROM t t1
ORDER BY id;
This is the output:
╭────┬─────────────────────────┬─────────────────────────┬─────────────────────────┬────────────────────────┬────────────────────────╮
│ id │ win_sum │ win_total │ win_avg │ ref_total │ ref_avg │
╞════╪═════════════════════════╪═════════════════════════╪═════════════════════════╪════════════════════════╪════════════════════════╡
│ 1 │ 9223372036854775807 │ 9.2233720368547758e+18 │ 3.0744573456182584e+18 │ 9.2233720368547758e+18 │ 3.0744573456182584e+18 │
│ 2 │ 0.5 │ 0.5 │ 0.16666666666666666 │ 9.2233720368547758e+18 │ 3.0744573456182584e+18 │
│ 3 │ -9.2233720368547758e+18 │ -9.2233720368547758e+18 │ -4.6116860184273879e+18 │ 1.5 │ 0.75 │
│ 4 │ -9.2233720368547758e+18 │ -9.2233720368547758e+18 │ -9.2233720368547758e+18 │ 0.5 │ 0.5 │
╰────┴─────────────────────────┴─────────────────────────┴─────────────────────────┴────────────────────────┴────────────────────────╯
I can reproduce this with the trunk version 83d3a0d39b