Reflow a one-line SQL query: break at keywords, uppercase main clauses, align indentation. Handy for reading code and debugging slow queries.
SQL is forgiving about whitespace, which means badly formatted queries still run and still pass review. The cost shows up later: a query whose joins and conditions run together takes far longer to audit than one where each clause starts on its own line. Formatting is a reviewability tool first and a style preference second.
| Clause | Convention |
|---|---|
| Keywords | Uppercase — SELECT, FROM, WHERE |
| Identifiers | Lowercase, ideally snake_case |
| Leading commas | Comma-first column lists make it easy to comment out a line |
| Joins | Each JOIN on its own line, with ON indented beneath |
| Conditions | One predicate per line, with AND / OR leading |
| Subqueries | Indented one level, with the closing bracket aligned to its opening |
A query is read in the order it appears, but the database evaluates it differently:
FROM → JOIN → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT
This explains two things that otherwise look strange: an alias defined in SELECT usually cannot be used in WHERE, because WHERE runs first; and filtering in WHERE is far cheaper than filtering in HAVING, because HAVING runs after aggregation. Organising your formatting to mirror this order makes the logic easier to follow.
|| in standard SQL, CONCAT() in MySQL, + in SQL Server.LIMIT in MySQL and PostgreSQL, versus TOP or FETCH FIRST elsewhere.A formatter that assumes the wrong dialect can rewrite a query into something that no longer parses. Match the dialect to the target database.
Reformatting an existing query produces a diff in which every line changed, hiding the one edit that mattered. When a file is already in a different style, format it in a separate commit, or not at all. The same applies to stored procedures and migration files, where an opaque diff is genuinely risky.
Whitespace is usually insignificant in SQL, but not everywhere. A formatter is only safe if it recognises the places where it stops being cosmetic:
'…' changes the result rather than the layout — and the query still runs, so nothing flags it.-- comment occupies the rest of its line. Move the code that follows onto that line and it becomes part of the comment, silently deleting a predicate.$$ … $$ blocks, and stored-procedure bodies in general, must pass through untouched — they contain a different language that the formatter does not understand.DELIMITER is interpreted by the client, not the server, so a formatter that reorders statements around it produces a script that no longer loads.A cheap verification: format the file, then diff the result against the original with whitespace ignored. If anything other than whitespace moved, the formatter touched something it should not have.