CTE (WITH): A named, inline result set defined with WITH that you can reference like a table. Improves readability and enables recursion. A CTE, or common table expression, gives a subquery a name with WITH, so you can use it like a table in the rest of the query. WITH recent AS (SELECT ...) SELECT ... FROM recent reads top to bottom, step by step.
The main benefit is readability. A long report query with three nested subqueries becomes a sequence of named steps, each easy to understand and test on its own.
What should you keep in mind with CTE (WITH)?
CTEs can also be recursive with WITH RECURSIVE, which lets you walk tree structures in one query, such as categories with subcategories or an organisation chart. MySQL 8, PostgreSQL and SQLite all support them. In older database versions, CTEs were sometimes slower than equivalent subqueries, but current versions usually optimise them just as well.
What does an example of CTE (WITH) look like?
WITH recent AS ( SELECT * FROM orders WHERE created_at > now() - interval '7 days' ) SELECT user_id, COUNT(*) FROM recent GROUP BY user_id;