Why formatting matters in SQL specifically
SQL is read far more often than it's written, and query shape affects semantics in ways whitespace doesn't hint at — an indented JOIN that's actually a Cartesian product, a WHERE clause that binds to the wrong alias. Consistent formatting makes review catch real bugs instead of style debates.
Conventions that survive any dialect
- Keywords uppercase (
SELECT,WHERE), identifiers lowercase_snake — the visual grammar separates structure from data. - One column per line in SELECTs over three columns: diffs, comments, and blame all become line-accurate.
- Leading commas (or always trailing — pick one): leading commas make errors land on the broken line, not the previous one.
- JOIN on its own line with its ON directly beneath, indented under the FROM table it extends. Nested subqueries get one indent level each.
- CTEs over deep nesting — a three-level nested SELECT becomes three named WITH clauses that read top to bottom.
A before/after
-- before
select u.id, u.name, o.total from users u join orders o on o.user_id=u.id where o.status='paid' and o.total>100 order by o.total desc;
-- after
SELECT
u.id
, u.name
, o.total
FROM users AS u
JOIN orders AS o
ON o.user_id = u.id
WHERE o.status = 'paid'
AND o.total > 100
ORDER BY
o.total DESC;
The second version reviews itself: the join condition is visible, the AND grouping is explicit, and adding a column is a one-line diff.
Things formatting can't fix
- SELECT * in production code — breaks on schema change and blocks index-only scans' column pruning. Name what you need.
- Implicit cross joins — comma-JOINs with a WHERE-based condition. Formatting to explicit JOIN/ON surfaces the mistake.
- OR conditions across joins that prevent index use — sometimes UNION of two queries beats one OR query.
Dialect notes matter: Postgres wants AS on column aliases before FROM; MySQL treats unquoted aliases case-insensitively; T-SQL uses TOP not LIMIT. Format, then convert dialects, in the SQL Formatter and SQL Dialect Converter.