SKY-Q510 · Quality, structure and performance
PostgreSQL COUNT includes every CASE result
Medium
A CASE expression inside COUNT has a non-null value for every outcome. The built-in aggregate counts every row admitted to it, including rows for which the condition is false.
- Languages
- PostgreSQL
- Quality gate
- listed, not counted by the gate (full and diff scans). This PostgreSQL check is report-only.
- Finding type
- review
Why it matters
A report intended to count paid orders can return the total number of orders. Both numbers can look reasonable on a small sample.
What Skylos flags
SELECT COUNT(CASE WHEN paid THEN 1 ELSE 0 END) AS paid_ordersFROM orders;[tool.skylos.sql]dialect = "postgresql"What Skylos leaves alone
SELECT COUNT(*) FILTER (WHERE paid) AS paid_ordersFROM orders;Why Skylos leaves it alone
The filter admits only paid orders to the count.
How Skylos decides
- With --quality, Skylos looks for count or pg_catalog.count taking a single CASE. Every THEN and the explicit ELSE must be a non-null literal from the same family (integer, decimal, string or boolean).
- Window and filtered counts can still have this issue. An absent ELSE, nullable or computed results, DISTINCT and ordered counts are outside this rule.
How to fix it
Put the condition in FILTER when only matching rows should count.
Removed: SELECTRemoved: COUNT(CASE WHEN paid THEN 1 ELSE 0 END) AS paid_ordersAdded: SELECT COUNT(*) FILTER (WHERE paid) AS paid_ordersFROM orders;When it can be wrong
- An unqualified count may resolve to a user-defined overload.
- A query may intentionally count every row.
Seeing a case that isn't listed here? Report the wrong result so the rule can be fixed. Don't paste company code: describe the shape of it.
How to silence it
Check which aggregate is selected and what the report should count.