withclauses
With clauses are a SQL construct that introduces one or more common table expressions (CTEs) to be referenced by the following statement. They help organize complex queries, improve readability, and enable modular data transformations. Many databases also support recursive CTEs using the same syntax.
Syntax: WITH [RECURSIVE] cte_name [(column_list)] AS ( subquery ) [, ...] main_query
In a with clause, each CTE defines a named result set that exists only for the duration
Recursive CTEs let a query build a result set by referencing the CTE within its own definition.
Non-recursive: WITH totals AS ( SELECT customer_id, SUM(amount) AS total FROM orders GROUP BY customer_id ) SELECT * FROM
Recursive: WITH RECURSIVE nums(n) AS ( SELECT 1 UNION ALL SELECT n+1 FROM nums WHERE n < 5 )
Performance and optimization: Depending on the engine, CTEs may be inlined or materialized, which influences performance.