How to format SQL so others can read it
Readable SQL is easier to review, debug and change. These simple rules cover most queries.
1. One clause per line
Start SELECT, FROM, WHERE, GROUP BY, HAVING and ORDER BY on new lines, and indent what belongs to them. Put JOINs under FROM with their ON condition.
2. Prefer CTEs to deep nesting
WITH clauses give each step a name and read top to bottom. A query with three named CTEs is far easier to follow than three nested subqueries.
3. Be consistent
- Pick a keyword case and stick to it.
- Use table aliases that mean something, like c for customers.
- Put each condition of a long WHERE on its own line.
- End every statement with a semicolon.