How to Format SQL CTEs (Common Table Expressions)
By Sharon Ben-Moshe · June 21, 2026 · 4 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.
SQL CTEs turn into a wall of text fast. Here's how to format WITH clauses, multi-CTE chains, and recursive CTEs so the structure reads at a glance.
Quick answer
Indent the CTE body 2–4 spaces, put the closing parenthesis and comma on their own lines, and clearly separate the final SELECT. Use uppercase for SQL keywords and consistent snake_case for CTE names throughout the chain.