Skip to content

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

Closed

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.

Although someone is unlikely to order a COUNT deliberately, this form can appear after a mechanical “count this query” rewrite. For example, a tool may turn SELECT a FROM t ORDER BY b into SELECT COUNT(a ORDER BY b) FROM t to inspect its cardinality, rather than use SELECT COUNT(*) FROM (SELECT a FROM t ORDER BY b) q. The inherited ordering is irrelevant to the count and should be harmless.

The query may also perform an unnecessary sort even though COUNT does not depend on input order.

To Reproduce

A non-grouped count returns the wrong result in DataFusion CLI v55.0.0:

$ datafusion-cli --format table -c "SELECT COUNT(a + 0 ORDER BY b) AS count FROM (VALUES (1, NULL), (2, 20)) AS t(a, b);"
DataFusion CLI v55.0.0
+-------+
| count |
+-------+
| 1     |
+-------+
1 row(s) fetched.

The result should be 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. added a commit that references this issue on Sep 11, 2026
    224cc56
  2. added a commit that references this issue on Sep 27, 2026
    e72572d
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

    bugSomething isn't working

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions