CTE
A CTE gives a name to an intermediate result
A Common Table Expression is defined with WITH. It lets you move an intermediate query to the top, give it a meaningful name, and then refer to it like a temporary table within that SQL statement.
WITH paid_orders AS (
SELECT id, user_id, amount
FROM orders
WHERE status = 'PAID'
)
SELECT user_id, SUM(amount) AS total
FROM paid_orders
GROUP BY user_id;
First, the paid_orders set is defined, then the main query works with that named result. The logic is not necessarily different, but the structure of a complex query often becomes much easier to understand.
A CTE exists only within one statement
A CTE does not create a permanent database table. Its name is available only to the statement that follows the WITH block.
A CTE is primarily a query-structure tool.
Do not automatically assume that it is faster or slower than an equivalent subquery: actual execution depends on the database system and query plan.
Check yourself
Exercise review
The mentor knows the solution and will help you reach it independently
Sign in to use the Mentor
The Mentor uses the current exercise and your conversation history.
Sign in
Review the key nuances and the answer after making your own attempt.
Sign in to view the solution
The solution and explanation are available after signing in.
Sign in