Skip to content

COUNT(... ORDER BY ...) can panic or undercount with nullable ordering keys #25054

Description

@geoffreyclaude

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.

Activity

  1. geoffreyclaude commented on Sep 8, 2026

    @geoffreyclaude
    ContributorAuthor

    Superseded by #25055, which was created using the repository Bug Report form so the configured bug label and Bug type are applied.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions