SQL queries grow in complexity fast. A 10-table JOIN with CTEs, subqueries, and window functions becomes nearly impossible to read or review when written as a single line. Formatted SQL:
AND conditions and wrong JOIN types jump out when indented.| Convention | Example | Why |
|---|---|---|
| UPPERCASE keywords | SELECT not select | Visual separation between keywords and identifiers |
| One clause per line | SELECT โฆFROM โฆWHERE โฆ | Each clause is independently scannable |
| Indent JOIN conditions | ON u.id = o.user_id | Clarifies which JOIN the condition belongs to |
| Align commas | col_a, col_b, col_c | Easy to comment out any single column |
Common Table Expressions (WITH โฆ AS (โฆ)) are almost always preferable to nested subqueries. They name the intermediate result, making the query self-documenting, and modern query planners handle them at least as efficiently. Use subqueries only for simple, single-use expressions in WHERE or SELECT clauses where a CTE would be overkill.