Readable SQL is easier to review, debug, migrate, and maintain. This guide provides a repeatable way to format and lint queries across PostgreSQL, MySQL, and SQL Server, with practical examples, tool-selection guidance, and a checklist for preventing formatting changes from affecting query behavior.
Overview
SQL formatting and SQL linting solve related but different problems. A formatter changes the presentation of a query: indentation, line breaks, keyword casing, comma placement, and sometimes alias layout. A linter checks the query against rules, such as requiring explicit column names, warning about ambiguous references, discouraging SELECT *, or detecting inconsistent naming.
A useful workflow treats formatting as a low-risk consistency step and linting as a review aid. Neither tool replaces execution tests. A query can be beautifully formatted and still return incorrect results, perform poorly, or behave differently across database engines.
Before choosing an SQL formatter online, editor extension, or command-line tool, identify three inputs:
- Dialect: PostgreSQL, MySQL, SQL Server, or another engine. Syntax and reserved words vary.
- Context: application queries, migration files, stored procedures, reporting SQL, or ad hoc investigation.
- Team rules: casing, indentation, alias conventions, line length, comma style, and rules that should produce warnings or errors.
Keep the formatter configuration with the repository whenever possible. A shared configuration makes pull requests more predictable and prevents each developer's editor from producing a different version of the same query.
Checklist by scenario
Formatting a single unfamiliar query
- Make a copy of the original query before formatting it.
- Confirm the target database dialect and whether the query includes vendor-specific syntax.
- Run the query, or capture its existing result shape, before making changes.
- Format the statement with a tool that explicitly supports the dialect, or apply the team style manually.
- Compare keywords, identifiers, string literals, comments, parameters, and operators before and after.
- Run the query again and compare results, affected rows, and execution behavior where practical.
Standardizing a repository
- Inventory SQL files, embedded queries, migration scripts, views, procedures, and generated files.
- Exclude files that should not be rewritten automatically, such as vendor SQL or generated output.
- Write a short SQL style guide covering indentation, keyword case, aliases, joins, CTEs, and ordering.
- Run the formatter once in a dedicated change so functional edits are not mixed with style changes.
- Review the diff for accidental token changes, comment movement, altered quoting, or broken templating syntax.
- Add linting to the development workflow after the baseline is understood.
Choosing a SQL formatter or linting tool
| Option | Useful for | Check before adopting |
|---|---|---|
| Online formatter | Quickly making a pasted query readable | Data privacy, dialect selection, maximum input size, and whether comments or parameters are preserved |
| Editor extension | Formatting while writing or reviewing SQL | Workspace configuration, keyboard commands, dialect support, and interaction with SQL embedded in code |
| Command-line formatter | Repeatable formatting in scripts and repositories | Stable configuration, exit behavior, file selection, and compatibility with CI |
| SQL linter | Enforcing conventions and identifying risky patterns | Rule severity, false positives, templated SQL support, and database dialect coverage |
| Database-specific formatter | Engine-aware syntax and stored database objects | Supported server version, vendor extensions, quoting behavior, and procedure handling |
Tools such as SQLFluff, pgFormatter, and editor-integrated SQL formatters are examples of categories to evaluate, not automatic recommendations for every project. Verify current dialect support and configuration syntax in the tool's documentation before adding it to a production workflow.
Formatting a complex query
Use one logical clause per line and make the query's structure visible. A consistent layout is more valuable than a particular comma preference.
WITH recent_orders AS (
SELECT
o.customer_id,
o.order_id,
o.created_at,
o.total_amount
FROM orders AS o
WHERE o.created_at >= :start_date
), ranked_orders AS (
SELECT
ro.*,
ROW_NUMBER() OVER (
PARTITION BY ro.customer_id
ORDER BY ro.created_at DESC
) AS order_rank
FROM recent_orders AS ro
)
SELECT
r.customer_id,
r.order_id,
r.total_amount
FROM ranked_orders AS r
WHERE r.order_rank = 1
ORDER BY r.created_at DESC;
This layout separates the CTEs, exposes selected columns, places join and filter conditions where they can be reviewed, and gives a window function enough space to show its partition and ordering rules.
What to double-check
Joins and aliases
Use short, meaningful aliases consistently and qualify columns when more than one table contains similar names. Keep each join condition close to its join:
SELECT
c.customer_id,
c.email,
COUNT(o.order_id) AS order_count
FROM customers AS c
LEFT JOIN orders AS o
ON o.customer_id = c.customer_id
AND o.status = 'paid'
GROUP BY
c.customer_id,
c.email;
Pay particular attention to filters on an outer-joined table. Moving a condition from the ON clause to the WHERE clause may change which rows are retained.
Subqueries and CTEs
Give each CTE a descriptive name and expose only the columns needed by the next stage. Check whether a formatter has changed parentheses or comments around nested expressions. Readability should make data flow easier to follow, not conceal it behind deeply nested one-line expressions.
Window functions and ordering
Review every PARTITION BY and ORDER BY after formatting. An added or removed expression can alter ranking, running totals, or duplicate handling. If the order must be deterministic, include a suitable tie-breaker rather than relying on an unspecified row order.
Quoting, parameters, and comments
SQL engines differ in how they interpret quoted identifiers, string literals, and parameter placeholders. A formatter should not rewrite values or application placeholders. Also inspect comments near conditional blocks, migration guards, and templating markers; some tools do not understand every application-level SQL syntax.
Formatting is not performance tuning
Indentation does not normally improve a query plan. After a substantial rewrite or lint-driven change, use the database's normal testing process to check correctness and performance. Review indexes, predicates, cardinality, and execution plans separately from style.
Common mistakes
- Using the wrong dialect: A generic SQL formatter may mishandle vendor-specific operators, quoting, functions, or procedural syntax.
- Formatting sensitive data in an unknown service: Do not paste credentials, customer data, tokens, or proprietary queries into an online tool unless its handling is acceptable to your organization.
- Combining a full reformat with logic changes: Separate style-only commits from behavioral edits so reviewers can inspect both.
- Treating lint warnings as proof of a bug: A rule is a signal that requires context. Configure severity deliberately and document justified exceptions.
- Ignoring generated and templated SQL: Formatting source templates may produce invalid output if the tool does not understand the template language.
- Relying on
SELECT *in durable interfaces: It can make result shapes change when tables evolve. Explicit columns are usually easier to review and safer for APIs and reports. - Assuming identical syntax across engines: Test migrations, quoting, date functions, pagination, and upsert behavior against the actual target database.
- Skipping validation after an automated rewrite: Run syntax checks, targeted tests, migrations in a safe environment, and representative queries before merging.
For repository automation, pair SQL checks with a controlled Git workflow. The guide to Git hooks for code quality covers ways to run checks before commits and pushes. If the formatter is invoked by a shell script, also account for arguments, exit codes, logging, and cleanup as described in shell script reliability patterns.
When to revisit
Review your SQL formatting and linting workflow before a repository-wide cleanup, a seasonal planning or reporting cycle, a database migration, or a change to the application framework that generates queries. Revisit it whenever the team adopts a new database engine, adds a dialect-specific feature, changes editor tooling, or begins storing SQL in a new format.
A practical maintenance checklist is:
- Confirm the formatter and linter versions used locally and in automation.
- Verify dialect and database-version settings against the systems you actually deploy.
- Run the tools on representative queries containing joins, CTEs, window functions, parameters, comments, and migrations.
- Inspect a sample diff instead of assuming the tool is behavior-preserving.
- Update the team style guide when a rule changes, and record intentional exceptions near the affected SQL.
- Keep formatting, linting, query tests, and performance checks as distinct steps in the review process.
When you inherit an unreadable query, start with a copy, identify the dialect, format only the presentation, and validate the result before changing logic. That small discipline turns an SQL formatter from a cosmetic convenience into a dependable developer productivity tool.