Skip to content

TopK aggregation keeps the wrong groups when a computed column reuses the aggregate's name #27195

Open

Description

@jayzhan211

Describe the bug

ORDER BY <name> LIMIT n above a GROUP BY returns the wrong groups, with no error, when a computed column between them is aliased to the aggregate's generated name. It takes that exact name: -mn AS mn over min(x) AS mn is correct.

To Reproduce

CREATE TABLE a (g BIGINT, x BIGINT) AS VALUES (1, 100), (2, 90), (3, 10), (4, 5);

SELECT g, -"min(a.x)" AS "min(a.x)"
FROM (SELECT g, min(x) FROM a GROUP BY g)
ORDER BY "min(a.x)"
LIMIT 2;

Expected behavior

DataFusion returns Expected
(3, -10), (4, -5) (1, -100), (2, -90)

DuckDB returns the expected result for the same query, using its name for the column, min(x). Tested on main at 4bf32cb.

Additional context

TopKAggregation follows the sort key down through projections by name. It skips a computed expression (topk_aggregation.rs:73), so the key's name still matches the aggregate below, and the aggregate keeps the groups with the smallest min(x). enable_topk_aggregation = false gives the expected result.

Following the key by position, and stopping at a computed expression, fixes it. #25066 fixes a different bug in the same rule.

Willingness to contribute

I'm not planning to fix this myself, so anyone is welcome to pick it up. Feel free to ping me with questions about the cause or when you'd like a review.

Activity

  1. TinyMurky commented on Nov 7, 2026

    @TinyMurky
    Contributor

    take

  2. vikrantmehta123 commented on Nov 14, 2026

    @vikrantmehta123
    Contributor

    Hi @TinyMurky, are you planning to take this up? Would love to attempt this, in case you aren't taking it.

  3. TinyMurky commented on Nov 14, 2026

    @TinyMurky
    Contributor

    @vikrantmehta123 Hello! I have untake ot

  4. vikrantmehta123 commented on Nov 14, 2026

    @vikrantmehta123
    Contributor

    take

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

Metadata

Metadata

Labels

bugSomething isn't working

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions