Describe the bug
COUNT(... ORDER BY ...) incorrectly treats aggregate ordering keys as additional counted arguments. This has two user-visible consequences:
- A non-grouped count can return a value that is too small when an ordering key is null, even though the counted expression is non-null.
- A grouped, single-argument count can panic because its groups accumulator expects one input array but receives the counted expression and ordering key.
The query may also perform an unnecessary sort even though COUNT does not depend on input order.
To Reproduce
SELECT COUNT(a + 0 ORDER BY b)
FROM (VALUES (1, NULL), (2, 20)) AS t(a, b);
This returns 1 instead of 2: the first row is incorrectly excluded because b is null. The null-preserving a + 0 expression prevents the count from being answered from input statistics, ensuring the accumulator executes.
A grouped query can instead panic:
SELECT c, COUNT(a ORDER BY b)
FROM (VALUES (1, NULL, 10), (2, 20, 10)) AS t(a, b, c)
GROUP BY c;
The panic reports that CountGroupsAccumulator received two arguments instead of one.
Expected behavior
The first query should return 2, and the grouped query should return one row with a count of 2. Nulls in ordering keys must not affect COUNT; only nulls in counted expressions should exclude rows.
Describe the bug
COUNT(... ORDER BY ...)incorrectly treats aggregate ordering keys as additional counted arguments. This has two user-visible consequences:The query may also perform an unnecessary sort even though
COUNTdoes not depend on input order.To Reproduce
This returns
1instead of2: the first row is incorrectly excluded becausebis null. The null-preservinga + 0expression prevents the count from being answered from input statistics, ensuring the accumulator executes.A grouped query can instead panic:
The panic reports that
CountGroupsAccumulatorreceived two arguments instead of one.Expected behavior
The first query should return
2, and the grouped query should return one row with a count of2. Nulls in ordering keys must not affectCOUNT; only nulls in counted expressions should exclude rows.