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
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
WITH open_orders AS (SELECT id FROM orders WHERE status = 'open')SELECT id FROM orders;[tool.skylos.sql]dialect = "postgresql"What Skylos leaves alone
WITH open_orders AS (SELECT id FROM orders WHERE status = 'open')SELECT id FROM open_orders;Why Skylos leaves it alone
The final query reads open_orders.
How Skylos decides
- Install the postgres extra and run
skylos . --quality. Setdialect = "postgresql"under[tool.skylos.sql]in pyproject.toml for the folder containing the queries. - 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.
- 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.
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.