Common Table Expression
CTE
A common table expression gives a set of rows a name so you can refer to it within a single SQL statement. You define it with `WITH`.
Also known as: WITH, рекурсивный запрос
What a CTE does
A common table expression (CTE) lets you name a query step and refer to its rows elsewhere in the same SQL statement. Think of a report that first counts orders per customer, then compares those counts with an overall average. Naming the first result customer_counts makes the comparison easier to follow than burying the counting logic inside a nested query.
How to write one
Start with WITH name AS (query), then write the statement that uses it. In a SELECT, you can refer to a CTE in FROM or JOIN, much as you would refer to a table. To define several CTEs, separate them with commas under a single WITH. A later CTE can refer to an earlier one, and the main query can use the same name more than once. That name goes out of scope when the statement ends.
Example: customers with above-average order counts
WITH customer_counts AS (
SELECT customer_id, COUNT(*) AS order_count
FROM orders
GROUP BY customer_id
)
SELECT customer_id, order_count
FROM customer_counts
WHERE order_count > (
SELECT AVG(1.0 * order_count) FROM customer_counts
);
The CTE produces one row per customer in the orders table. The outer query reads those rows, and the scalar subquery reads them again to calculate the threshold. The average is over customers who have placed at least one order; customers with no orders never enter the CTE.
Ordinary vs. recursive CTEs
Most CTEs simply name a query step. A recursive CTE refers to itself and is useful when you don't know in advance how many levels you need to visit, such as when finding everyone who reports to a manager directly or indirectly. The anchor query selects the starting manager. The recursive step joins the employees found in the previous round to their direct reports. Recursion stops when a round returns no rows. If the reporting data can contain cycles, a traversal using UNION ALL needs a cycle check, such as tracking employee IDs along each path. PostgreSQL uses WITH RECURSIVE; the syntax differs across database engines.
Common misconceptions and interview questions
A CTE isn't a temporary table you can query from a later statement, nor is it a view whose definition is stored in the database. Referencing a CTE twice also doesn't prove that the database computes it once. Depending on the engine and query, the optimizer may inline it into the surrounding statement or materialize its result. Use EXPLAIN to inspect the plan rather than assuming WITH makes a query faster or slower.
In an interview, you might be asked to rewrite a nested query using a CTE or walk a hierarchy. For a rewrite, explain what one row of the intermediate result represents. For a hierarchy, identify the starting rows, the join that advances to the next level, and what makes the recursion stop.