How to Format SQL Subqueries and Derived Tables
By Sharon Ben-Moshe · August 8, 2026 · 2 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.
A subquery buried inline in a WHERE clause or FROM list is unreadable the moment it grows past one line. Here's how to indent, align, and alias nested SELECTs so the outer query's structure stays visible.
Quick answer
A readable subquery is indented one level deeper than the keyword that introduces it, wrapped in its own parentheses on their own lines, and — when used in a FROM clause — always given an explicit alias placed right after the closing parenthesis, so the outer query's structure stays visible without unwinding the nested SELECT first.