The Master Guide to SQL Common Table Expressions (CTEs): Syntax, Optimization Fences, and Recursion
By Sharon Ben-Moshe · October 13, 2026 · 1 min read
Sharon Ben-Moshe is the founder of sqlfmt, a browser-based SQL formatter and validator with misspelled-keyword suggestions across PostgreSQL, MySQL, SQLite, SQL Server, and BigQuery.
The definitive guide to SQL Common Table Expressions (CTEs). Master chaining, recursive hierarchies, data-modifying CTEs, and optimization fences.
Quick answer
A Common Table Expression (CTE) is a named temporary result set defined using the WITH clause that exists only for the duration of a single SQL statement. CTEs improve readability over nested subqueries, can be referenced multiple times, support recursion for hierarchical data, and can be explicitly materialized or inlined by query optimizers.