How to Format SQL Queries

Readable SQL makes filters, join conditions and aggregation easier to review. Start by separating the top-level clauses and then indent logical groups. Keep the query’s dialect and semantics intact, especially when a reformatted query is part of a production change.

Start with a query that has one purpose

This query counts open orders by customer. Put SELECT, FROM, WHERE, GROUP BY and ORDER BY on their own lines. When adding columns, keep the formatting consistent so a diff shows the exact field added. Uppercase keywords if that matches your team’s convention.

A formatting tool handles basic layout. You can then make an editorial pass for clarity. For instance, a descriptive alias such as open_orders helps a reviewer connect the SELECT expression to the final sort. Make alias changes separately if another part of the application consumes the original column name.

SQL
SELECT customer_id, COUNT(*) AS open_orders
FROM orders
WHERE status = 'open'
GROUP BY customer_id
ORDER BY open_orders DESC;

Keep logic visible around joins

Indent join predicates under the JOIN so the reader can see how tables connect. Retain parentheses around combinations of AND and OR. For an outer join, moving a condition from ON to WHERE can change which rows are returned. Leave clauses in their original locations during a formatting pass.

Also keep quoted strings and identifiers intact. Whitespace inside a quoted string can be user data, and case inside quoted identifiers can matter for the database. Dollar-quoted procedures, optimizer hints and dialect-specific parameters deserve a formatter that explicitly supports them.

Verify the result in context

Compare the original and formatted query on a small fixture database when semantics matter. Keep parameters and their types the same for both runs. Check row counts and a few representative rows, including rows with nulls and missing join partners.

Formatting does not replace an execution plan. If the real problem is runtime, examine the plan, filters, indexes and row estimates in your database’s tooling. Use formatting to make the plan discussion easier to follow.

Frequently asked questions

Should I format generated SQL from a log?
Yes, after removing log prefixes and redacting values that are sensitive. Keep bound parameters separate from the query text.
Does the tool run a query?
The formatter transforms the source text in your browser. It does not connect to a database.

Try it with these tools

Related developer guides