A consistent SQL formatter makes long queries easier to review, debug, and maintain without changing their behavior. This guide shows how to format SQL safely across MySQL, PostgreSQL, and SQL Server, with before-and-after examples, practical formatter settings, and a reusable review checklist.
Overview
SQL formatting is a readability workflow, not a query optimization technique. A formatter should reorganize whitespace, indentation, line breaks, and keyword casing while preserving the query's meaning. It should not silently rewrite joins, change filters, reorder expressions, or “fix” dialect-specific syntax without your approval.
Formatting matters most when a query is being reviewed, copied into a migration, investigated during an incident, or compared with a previous version. A readable query exposes relationships between tables, makes nested logic easier to follow, and helps reviewers spot missing conditions or accidental changes.
Before using a format SQL query online tool or a local SQL formatter, confirm how it handles sensitive data. Prefer schema-only examples, parameter placeholders, or a local editor integration when a query contains customer information, credentials, tokens, or proprietary business logic. Formatting is useful, but it should not require exposing production data.
Before formatting
select u.id,u.email,count(o.id) as order_count from users u left join orders o on o.user_id=u.id where u.status='active' and o.created_at >= '2025-01-01' group by u.id,u.email having count(o.id)>0 order by order_count desc;
After formatting
SELECT
u.id,
u.email,
COUNT(o.id) AS order_count
FROM users AS u
LEFT JOIN orders AS o
ON o.user_id = u.id
WHERE u.status = 'active'
AND o.created_at >= '2025-01-01'
GROUP BY
u.id,
u.email
HAVING COUNT(o.id) > 0
ORDER BY order_count DESC;
The second version is easier to scan, but formatting does not resolve a semantic issue: the condition on o.created_at may affect how the left join behaves. That is why formatting should be followed by a review of joins, filters, grouping, and expected results.
Checklist by scenario
For a long SELECT query
- Place major clauses such as
SELECT,FROM,WHERE,GROUP BY, andORDER BYon separate lines. - Put each selected column on its own line when the list is longer than a few expressions.
- Indent boolean conditions consistently, using a visible pattern for
ANDandOR. - Keep aliases explicit when a query contains several tables with similar column names.
- Check whether the formatter preserves comments and parameter placeholders.
For joins
- Put each join on its own line and align the
ONcondition beneath it. - Keep join predicates separate from filtering predicates when that distinction helps explain the query's logic.
- Use table aliases consistently; avoid switching between full table names and abbreviations.
- Review every join for its intended cardinality. A neatly formatted many-to-many join can still multiply rows.
- For outer joins, verify whether conditions belong in the
ONclause or theWHEREclause.
For subqueries and CTEs
- Indent the body of each subquery so its scope is immediately visible.
- Give common table expressions descriptive names rather than short, ambiguous abbreviations.
- Format each CTE as a complete query with its own clause structure.
- Check parentheses after formatting, especially around nested
EXISTS,IN, and conditional expressions. - Confirm that the formatter has not confused a CTE, derived table, or dialect-specific expression.
For migrations and deployment scripts
- Separate statements clearly and preserve statement terminators required by your execution environment.
- Keep transaction boundaries, locking clauses, and procedural blocks visible.
- Do not allow a formatter to normalize quoted identifiers without checking case sensitivity and reserved words.
- Review default values, nullability, indexes, constraints, and rollback steps independently of formatting.
- Run the migration against a disposable or staging database before applying it to a shared environment.
Formatter settings comparison
| Setting | Practical default | What to check |
|---|---|---|
| Dialect | Select the target database | Keywords, functions, quoting, and pagination syntax may differ. |
| Keyword case | Uppercase for SQL keywords | Use the convention already adopted by the repository. |
| Indentation | Four spaces or the project standard | Keep nested queries and expressions visually distinct. |
| Comma placement | One selected item per line | Choose leading or trailing commas consistently. |
| Line width | A moderate project-defined limit | Avoid wrapping short expressions while keeping long conditions readable. |
| Semicolons | Preserve them where the runner expects them | Check scripts containing multiple statements or procedural code. |
What to double-check
MySQL, PostgreSQL, and SQL Server share core SQL concepts, but they do not share every function, identifier rule, pagination pattern, or procedural feature. A generic SQL beautifier can improve indentation while still misunderstanding a database-specific construct. Select the correct dialect when a formatter offers that option, then validate the result using the target database or its parser.
Dialect-specific review
- MySQL: Check backtick-quoted identifiers, functions, session-specific syntax, and clauses that are not portable to other databases.
- PostgreSQL: Check double-quoted identifiers, schema-qualified names, casts, array or JSON expressions, and PostgreSQL-specific operators.
- SQL Server: Check bracketed identifiers, batch separators used by the surrounding tool, variables, and Transact-SQL extensions.
Formatting can also reveal logic that deserves a separate test. Compare row counts before and after a change, inspect a representative sample, and review execution plans when performance is part of the task. A formatter should not be treated as a validator, linter, or optimizer unless the specific tool explicitly provides those functions.
For team workflows, agree on a small set of conventions: keyword case, indentation, alias style, comma placement, handling of long WHERE clauses, and whether formatting runs automatically on save or in CI. If the project uses an editor extension, confirm that its dialect and configuration match the formatter used in code review. For broader query review practices, see the SQL Formatter and Query Review Guide.
Common mistakes
- Assuming pretty SQL is correct SQL. Indentation cannot detect a wrong join key, an incomplete filter, or an unintended aggregation.
- Using the wrong dialect. A formatter configured for one database may misread functions, quotes, casts, or pagination syntax from another.
- Formatting generated SQL as if it were hand-written. Generated statements may contain placeholders, escaped values, or machine-oriented aliases that require special handling.
- Changing logic while formatting. Avoid combining a cosmetic cleanup with a join rewrite, filter change, or renamed column unless the change is deliberate and separately reviewed.
- Flattening meaningful structure. Excessive compaction makes subqueries and boolean groups harder to audit, even if the query remains valid.
- Ignoring comments. Comments may explain temporary filters, business rules, or migration safety steps. Confirm that the formatter preserves their location and meaning.
- Trusting an online tool with sensitive queries. Remove real values and use placeholders when possible; otherwise choose a local or approved workflow.
When to revisit
Revisit your SQL formatting rules whenever the repository changes its editor setup, formatter configuration, linting workflow, or supported database dialects. A new database feature or formatter version may add syntax support, change defaults, or produce different line breaks. Treat those changes as workflow updates: test them on representative queries before applying them across a codebase.
It is also useful to review the style before a migration cycle, a major reporting or analytics project, or a period when many contributors will edit queries. Pick a few complex examples containing joins, CTEs, subqueries, window functions, and migration statements. Format them with the proposed settings, inspect the diff, and document exceptions rather than allowing each contributor to choose a different pattern.
Use this final checklist before committing a formatted query:
- Select the correct database dialect and formatter configuration.
- Remove sensitive values or use a trusted local workflow.
- Format without mixing in unrelated logic changes.
- Review joins, filters, grouping, subqueries, CTEs, and parentheses.
- Preserve comments, placeholders, statement terminators, and migration boundaries.
- Run syntax validation and, where appropriate, compare results and execution behavior.
- Inspect the final diff so the formatting change is consistent and reviewable.
Used this way, an SQL formatter is a dependable developer tool: it reduces visual noise while leaving correctness decisions with the person who understands the query's purpose and the target database.