DELAPARRA
Index
Color
NL
Category: SQL

CTE (WITH)

Explained by Updated

What is CTE (WITH)?

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.

Definition source Coders Lingo, CC BY 4.0

Frequently asked questions about CTE (WITH)

How is CTE (WITH) used in practice?

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;

At a glance

CategorySQL
Explained by
Updated

More SQL terms

All terms starting with C

Skills

Download all skills (zip)

Manuals

Related services

Need any help?

Stuck on one of these in your own project? Tell me what you are working on and I will tell you how I would approach it.