Skip to main content

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
Wrong result? Report itA false positive, a missed case or a confusing message: it goes privately to the founder.

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

orders.sql · SQLReported on line 2
SELECT  COUNT(CASE WHEN paid THEN 1 ELSE 0 END) AS paid_ordersFROM orders;
pyproject.toml · TOML
[tool.skylos.sql]dialect = "postgresql"

What Skylos leaves alone

orders.sql · SQL
SELECT COUNT(*) FILTER (WHERE paid) AS paid_ordersFROM orders;

pyproject.toml: same as in the flagged example.

Why Skylos leaves it alone

The filter admits only paid orders to the count.

How Skylos decides

  1. 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).
  2. 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.

orders.sql · SQL · the fix, against the flagged file
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.

From the Skylos rule handbook, Skylos 5.8.0 (commit 5b880b0). All rules.