Skip to content

rule: W017 count-distinct-unbounded - warn on COUNT(DISTINCT col) without LIMIT/filter #7

@Pawansingh3889

Description

@Pawansingh3889

COUNT(DISTINCT col) on a large unfiltered table forces a full sort
and distinct pass. Often a perf surprise on prod. Warn when there's no
WHERE, LIMIT, or GROUP BY restricting the scope.

Should fail

SELECT COUNT(DISTINCT user_id) FROM events;

Should pass

SELECT COUNT(DISTINCT user_id) FROM events WHERE event_date >= CURRENT_DATE - 7;

Implementation hints

  • Multi-line rule.
  • Look for COUNT(DISTINCT ...) and require either WHERE or GROUP BY in
    the same statement.
  • Severity: warning.

Estimated LOC: ~30 code + ~20 test.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions