Developer Formatting

SQL formatter

What to do

Processed in your browser · nothing is uploaded

Local · literals protected before keyword matching
Advertisement
320 × 100

Breaks a query onto its keyword boundaries and indents the AND and OR continuations, so a long WHERE clause becomes readable.

How to use the sql formatter

1 Paste the query.
2 It breaks onto SELECT, FROM, WHERE, the JOINs, GROUP BY and the rest, indenting AND, OR and ON under the clause above.
3 Strip any -- comments first. Rewriting the line breaks can pull the next words into one.
4 Copy the result, or save it as a file.

This formats structurally rather than by parsing the query, which is a deliberate limit worth stating: it does not know your dialect, will not indent a subquery to a deeper level, and validates nothing. What it does get right is the trap that catches naive formatters; a keyword inside a string literal. WHERE note = 'sent from accounts' contains the word FROM, and a formatter that breaks on it produces a query that no longer parses. Literals are set aside here before any keyword matching happens.

Comments are the sharp edge, because formatting decides where the lines fall. A -- comment runs to the end of its line, so text that was safely on the following line can end up inside it: SELECT id, -- the id followed by name FROM t comes back as SELECT id, -- the id name, with the column now commented out. Remove the line comments before formatting, or use the SQL minifier, which strips them properly.

The literal protection covers single and double quotes, and stops there. A PostgreSQL dollar-quoted body between $$ markers is not protected, so keywords inside a function definition will be broken on as though they were part of the statement. Keep function bodies out of it.

One cosmetic detail that reads as a bug and is not: keywords are written in upper case as they are broken on, but a keyword sitting at the very start of the query has no break to make, so select id from t comes back with a lowercase select and an uppercase FROM.

Questions

No. It reformats whatever you give it and never checks the query is correct.

PostgreSQL, SQL syntax
Advertisement
300 × 250
Was this tool any good?
Internal signal only · I use it to find the tools worth rebuilding