Common Table Expressions
suggest changeSyntax
- WITH QueryName [(ColumnName, …)] AS (
SELECT …
)
SELECT … FROM QueryName …;
- WITH RECURSIVE QueryName [(ColumnName, …)] AS (
SELECT …
UNION [ALL]
SELECT … FROM QueryName …
)
SELECT … FROM QueryName …;
Remarks
SQLite documents the WITH clause here. The RECURSIVE keyword is required by some dialects, such as PostgreSQL, and is not used by SQL Server.
A common table expression is a temporary result set, and it can be the result of a complex subquery. It is defined with a WITH clause. A CTE improves readability. It lasts only for the statement that defines it. In SQL Server it is not stored in tempdb the way a temporary table or table variable is.
Key concepts of Common Table Expressions:
- Can be used to break up complex queries, especially complex joins and sub-queries.
- Is a way of encapsulating a query definition.
- Lasts only for the statement that defines it, not until a later query.
- Correct use can lead to improvements in both code quality/maintainability and speed.
- Can be used to reference the resulting table multiple times in the same statement (eliminate duplication in SQL).
- Can be a substitute for a view when the general use of a view is not required; that is, you do not have to store the definition in metadata.
- Is evaluated when referenced, not when defined. If the CTE is referenced more than once, the engine may evaluate it again, so a non-deterministic CTE can return different results.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents