Databases & SQL · reviewed in July 2026
CTE (SQL)
A CTE (Common Table Expression) is a named temporary result defined with WITH at the start of a SQL query, which can be referenced as if it were a table within that same query. It's used to break complex queries into readable steps.
Frequently asked questions
How is a CTE different from a subquery?
They serve a similar purpose, but a CTE is defined once with a name and can be reused several times within the query, whereas a nested subquery has to be repeated every time it's needed.
What is a recursive CTE?
A CTE that references itself, useful for walking hierarchical structures like a category tree or an org chart, where each level depends on the one before it.
Can you chain several CTEs in one query?
Yes, by separating them with commas after WITH; each CTE can reference the ones defined before it in the same query.