Skip to main content

SKY-Q503 · Quality, structure and performance

Unused read-only PostgreSQL CTE

Low

A WITH clause names a read-only query whose result the statement never uses. The name introduces a common table expression (CTE).

Languages
PostgreSQL
Quality gate
listed, not counted by the gate (full and diff scans). This PostgreSQL check is report-only.
Finding type
review
Catalog name
Unused PostgreSQL SELECT CTE
Wrong result? Report itA false positive, a missed case or a confusing message: it goes privately to the founder.

Why it matters

An unused CTE can survive a rewrite and make a query harder to follow. If the author intended that CTE to filter the result, the statement may return the wrong rows.

What Skylos flags

query.sql · SQLReported on line 1
WITH open_orders AS (SELECT id FROM orders WHERE status = 'open')SELECT id FROM orders;
pyproject.toml · TOML
[tool.skylos.sql]dialect = "postgresql"

What Skylos leaves alone

query.sql · SQL
WITH open_orders AS (SELECT id FROM orders WHERE status = 'open')SELECT id FROM open_orders;

pyproject.toml: same as in the flagged example.

Why Skylos leaves it alone

The final query reads open_orders.

How Skylos decides

  1. Install the postgres extra and run skylos . --quality. Set dialect = "postgresql" under [tool.skylos.sql] in pyproject.toml for the folder containing the queries.
  2. Skylos follows references between CTEs and starts from the outer statement. If only an unused CTE reads another CTE, both are reported. Nested WITH scopes and recursive references are tracked separately.
  3. A data-changing CTE can write rows even when its result goes unread. Skylos also keeps CTEs containing function calls or row locks and the CTEs they read.

How to fix it

Read from the CTE if its rows are needed. Remove its definition if the final query already reads the intended rows.

query.sql · SQL · the fix, against the flagged file
WITH open_orders AS (SELECT id FROM orders WHERE status = 'open')Removed: SELECT id FROM orders;Added: SELECT id FROM open_orders;

When it can be wrong

  • A query template may add another reference before it reaches PostgreSQL.

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

  • Review the final SQL when a template adds references.

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