SQL CTEs: Common Table Expressions for Readable Complex Queries
CTEs turned my most tangled SQL into readable, layered queries. Here is how I use them and when I reach for recursion. Common Table Expressions, or CTEs, changed how I write complex SQL. Before CTEs, a query with several intermediate steps became a wall of nested subqueries, each harder to read than the last. With CTEs, I name each step and reference it by name, which turns a tangled mess into a sequence of readable transformations. After years of use, they are my default tool for any query with more than two steps. The Basic Syntax A CTE is defined with the WITH keyword, followed by a name, the AS keyword, and a query in parentheses. The CTE name can then be used in the main query like a regular table. WITH recent_orders AS ( SELECT * FROM orders WHERE created_at >= '2026-01-01' ) SELECT customer_id, COUNT(*) AS order_count FROM recent_orders GROUP BY customer_id ORDER BY order_count DESC; This example defines recent_orders as a filtered view of the orders table, then aggregates it in the main query. The intent reads top to bottom: first filter, then group, then sort. The equivalent subquery…