A consistent SQL formatter and a small set of review rules can make a long query easier to understand without changing its behavior. This guide provides a reusable formatting template, dialect notes for PostgreSQL, MySQL, SQL Server, and SQLite, plus checklists for reviewing joins, NULL handling, window functions, subqueries, and dynamic SQL.
Overview
Formatting SQL is not merely a cosmetic exercise. Clear indentation and predictable clause order help reviewers identify accidental joins, hidden filters, duplicated rows, and unsafe inputs. A formatter can apply consistent whitespace and capitalization, but it cannot determine whether a query expresses the correct business rule. Treat formatting as the first pass, then review semantics separately.
Before using an online SQL formatter or adding one to a development workflow, remove credentials, tokens, customer data, and other sensitive values from the query. Prefer a local formatter for proprietary SQL. If an online tool is appropriate, inspect its handling of submitted text and avoid pasting production data. Formatting tools should improve readability without becoming a new data-handling risk.
A practical SQL style guide should answer five questions:
- How are keywords, identifiers, aliases, and functions capitalized?
- How are SELECT lists, JOIN conditions, and Boolean expressions aligned?
- How are common table expressions, subqueries, and window functions separated?
- Which syntax is portable, and which syntax belongs to a specific database dialect?
- How will reviewers confirm that formatting did not conceal a logic or security problem?
Choose rules that your team can apply consistently. For example, uppercase SQL keywords, one selected column per line, explicit JOIN syntax, and indentation by nesting level provide a useful baseline. The exact choices matter less than keeping them stable in pull requests and generated SQL comparisons.
Dialect comparison
SQL formatters need to parse a specific dialect. A query that formats correctly as PostgreSQL may contain syntax that a MySQL, SQL Server, or SQLite parser does not recognize. Select the closest dialect before formatting and validate the result against the actual database.
| Dialect | Syntax to identify | Formatting and review note |
|---|---|---|
| PostgreSQL | Double-quoted identifiers, :: casts, RETURNING, ILIKE | Preserve casts and identifier quoting; check whether formatter support matches the PostgreSQL version and extensions in use. |
| MySQL | Backtick identifiers, LIMIT forms, IFNULL, version-specific features | Keep backticks distinct from string quotes and review generated SQL for compatibility with the deployed MySQL or compatible server. |
| SQL Server | Bracketed identifiers, TOP, GETDATE(), ISNULL | Check bracketed reserved words, semicolon placement, and whether pagination or date functions match the target SQL Server version. |
| SQLite | Dynamic typing, LIMIT/OFFSET, date-function conventions | Do not assume behavior from another database, especially for types, date values, collations, or unsupported functions. |
Reserved words are another reason to inspect identifiers after formatting. Names such as user, order, group, select, and table may require quoting or renaming depending on the dialect. Quoting can preserve an existing schema, but it may also make every future reference more cumbersome. When changing a schema is possible, descriptive names that avoid reserved words are usually easier to maintain.
Checklist by scenario
When inheriting a long query
- Save the original query before formatting it, including comments and parameter placeholders.
- Confirm the database dialect and the application or reporting tool that generated the SQL.
- Format the query without changing identifiers, literals, operators, or clause order.
- Identify the main table, join path, filter conditions, grouping level, and intended result grain.
- Mark every nested subquery and CTE with a short description of the rows it returns.
- Run a safe comparison, such as row counts or a limited sample, before and after formatting.
When preparing a pull request
- Keep formatting-only changes separate from query logic changes where possible.
- Use one expression per SELECT line, with commas placed consistently.
- Put each JOIN on its own line and place its ON condition beneath it or on the same predictable indentation level.
- Group related WHERE predicates and indent nested
AND/ORconditions so their precedence is visible. - Give calculated expressions and window functions meaningful aliases.
- Explain unusual filters, intentional duplicates, timezone assumptions, or database-specific syntax in comments.
When writing a CTE- and window-function-heavy query
Use each CTE as a named stage rather than as a single dense block. The following template is deliberately generic; adapt identifier quoting and functions to the target dialect:
WITH filtered_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
AND o.created_at < :end_date
), ranked_orders AS (
SELECT
fo.customer_id,
fo.order_id,
fo.created_at,
fo.total_amount,
ROW_NUMBER() OVER (
PARTITION BY fo.customer_id
ORDER BY fo.created_at DESC, fo.order_id DESC
) AS order_rank
FROM filtered_orders AS fo
)
SELECT
ro.customer_id,
ro.order_id,
ro.total_amount,
summary.average_amount
FROM ranked_orders AS ro
JOIN (
SELECT
customer_id,
AVG(total_amount) AS average_amount
FROM filtered_orders
GROUP BY customer_id
) AS summary
ON summary.customer_id = ro.customer_id
WHERE ro.order_rank = 1
ORDER BY ro.customer_id;
This layout makes the data flow visible: filter first, rank second, aggregate in a separate subquery, then join the results. It also gives reviewers a place to question whether the window partition, ordering, and final filter match the intended result.
When comparing generated SQL
Format both statements with the same settings before comparing them. Normalize whitespace, capitalization, and line wrapping, but do not assume two similarly formatted queries are equivalent. Check selected columns, join predicates, filter grouping, grouping keys, ordering, limits, and parameter placement. For performance questions, pair the review with an execution-plan workflow rather than relying on visual inspection alone; an SQL EXPLAIN and query plan guide can help structure that investigation.
What to double-check
Ambiguous columns and aliases
Qualify columns whenever more than one table could contain the same name. SELECT id is harder to review than SELECT users.id or SELECT u.id. Use short, stable aliases such as u and o, but avoid aliases that obscure the table's role. In a multi-join query, an explicit qualifier can reveal that a filter is applied to the wrong table.
NULL handling
Remember that NULL is not equal to zero, an empty string, or another NULL. Use IS NULL and IS NOT NULL for tests. Review expressions involving COALESCE, aggregates, outer joins, and Boolean predicates. A condition in the WHERE clause can remove rows introduced by a LEFT JOIN, effectively changing the result into an inner join. If that is intentional, make it clear; if it is not, move the condition into the JOIN predicate or revise the logic.
Implicit joins and result grain
Prefer explicit JOIN clauses over comma-separated tables with conditions hidden in WHERE. Explicit joins show the relationship between tables and make missing predicates easier to spot. Before approving a query, state its expected grain in plain language: one row per customer, order, event, or combination. Then check whether every join preserves that grain. A one-to-many join can multiply rows even when the SQL is syntactically valid.
Window functions and subqueries
Check the difference between PARTITION BY and ORDER BY. A window function may calculate a value for every row, while a GROUP BY collapses rows. Review ties in ranking functions, the ordering used for running totals, and whether a later filter is applied before or after the window calculation. For subqueries, confirm whether the relationship is scalar, existence-based, or set-based. IN, EXISTS, and joins can have different NULL and duplicate-row behavior.
Dynamic SQL and parameters
Never build SQL by concatenating untrusted values into a query string. Use the parameter-binding mechanism provided by the database driver or framework. Values and identifiers are different: parameters usually represent values, while dynamic table names, column names, and sort directions require an allowlist and careful construction. A formatter can make unsafe dynamic SQL easier to read, but it cannot make concatenation safe. For broader request and input troubleshooting, pair query review with a documented API debugging workflow.
Common mistakes
- Treating formatting as validation: A formatted query may still return incorrect or unauthorized data. Test its semantics and access boundaries.
- Using the wrong dialect: A formatter may rewrite or reject syntax when configured for a different database. Confirm the parser setting first.
- Combining a large reformat with behavior changes: Reviewers have difficulty separating indentation changes from altered filters or joins. Make separate commits when practical.
- Hiding logic in long lines: A compact WHERE clause can conceal operator precedence. Use parentheses and indentation when mixed AND and OR conditions are required.
- Relying on SELECT *: It makes result shape change when a table changes and can pull unnecessary or sensitive columns. Name the required columns explicitly.
- Copying production data into a formatter: Replace literals with placeholders or representative values before using an online tool.
- Assuming comments survive every tool: Check how the formatter handles inline comments, optimizer hints, and dialect-specific annotations before applying it to critical SQL.
When to revisit
Revisit this SQL formatting and review checklist whenever a query is inherited, a database is migrated, a formatter or editor is replaced, or generated SQL changes shape. It is also useful before a recurring planning or release cycle, when teams often review reporting queries, cleanup jobs, and schema changes together.
At each review, confirm the formatter's dialect setting, reserved-word handling, identifier quoting, comment preservation, and parameter syntax. Recheck queries after database-version changes because supported syntax, functions, and compatibility modes may differ. If a query becomes slow, do not repeatedly reformat it as a performance solution: capture its execution plan, compare representative inputs, and inspect indexes, joins, filters, and row estimates separately.
For a practical final pass, keep this sequence:
- Copy and protect the original.
- Remove sensitive values and choose the correct dialect.
- Format consistently using the team's agreed style.
- Read the query from the FROM clause outward, tracing joins and result grain.
- Check ambiguous columns, NULL behavior, implicit joins, subqueries, and window ordering.
- Verify that all external values are parameterized and dynamic identifiers are allowlisted.
- Test results and, when relevant, compare an execution plan before merging.
A good SQL formatter reduces visual noise. A good review uses that improved structure to question what the query returns, which rows it can expose, and whether its behavior remains correct in the target database.