What is CTE?

A CTE is a named temporary result defined at the start of a query with WITH, which later parts of the query can refer to like a table.

CTE explained

CTEs break a long query into named steps: first total orders by customer, then rank them, then keep the top ten. Each step is easy to read and check on its own.

A recursive CTE can refer to itself, which is how SQL walks hierarchies such as an org chart or a category tree.

Example

WITH monthly AS (SELECT month, SUM(amount) AS sales FROM orders GROUP BY month) SELECT month, sales FROM monthly ORDER BY month.

Frequently asked questions

What is CTE?
A CTE is a named temporary result defined at the start of a query with WITH, which later parts of the query can refer to like a table.
Can you give an example of CTE?
WITH monthly AS (SELECT month, SUM(amount) AS sales FROM orders GROUP BY month) SELECT month, sales FROM monthly ORDER BY month.