Skip to content

unused-cte

Default severity: warn

What it does

Reports a CTE that neither a later CTE nor the statement reads, on its name. Editors fade it as unnecessary code.

from sqlty import SQL

# error: [unused-cte] "CTE `unused` is never read"
q = SQL[tuple[int]]("--sql\nWITH unused AS (SELECT 1) SELECT 2")
Open in playground

A data-modifying CTE runs whether read or not, so it is not reported:

from sqlty import SQL

# error: [missing-where] "`DELETE` without `WHERE` removes every row of `users`: add a `WHERE`, or `WHERE true` to mean it"
q = SQL[tuple[int]]("--sql\nWITH gone AS (DELETE FROM users RETURNING id) SELECT 1")
Open in playground

Why is this bad?

The database never runs an unread SELECT CTE (PostgreSQL): it is dead code, often left over from an edit, that readers still have to follow.

How to fix

Remove the CTE, or read it where it was meant to be read.

Configuration

A warning by default: the query runs. Turn it into an error or off:

[tool.sqlty.rules]
unused-cte = "error"

Needs no schema. A name resolves to the innermost CTE of that name. A recursive CTE reading only itself is reported: PostgreSQL never runs it. In SQLite any CTE of a WITH may read any other.