Common Table Expressions

A CTE is a named subquery written before the query that uses it. Same result as nesting, read top to bottom instead of inside out.

Once a query has two or three stages, this is the difference between something a colleague can follow and something they have to unpick.

Try it

Add a second CTE after the first, separated by a comma, that filters counts to those above one. Then the main query does nothing but join.

loading editor…
real SQLite, in your browser

The CTE computes the counts; the main query joins them to names. Each stage does one thing and can be read on its own.

A recursive CTE can walk a hierarchy, such as a category tree or a reply chain. It is genuinely useful and it has one rule: it must have a stopping condition.

Without one it runs forever. In this course that shows up as a timeout after eight seconds. Against a real production database it shows up as an incident.

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Practice Test →
← Back