A consistent SQL formatting style makes complex queries easier to read, debug, review, and safely modify. This guide provides a practical SQL formatter checklist, before-and-after examples, dialect notes, and a repeatable workflow for joins, subqueries, window functions, and long filter conditions.
Overview
A SQL formatter, sometimes called a SQL prettifier, changes the layout of a query without changing its intended logic. It can add indentation, place clauses on separate lines, align related expressions, and make nested structures visible. Formatting does not optimize a query automatically, fix incorrect joins, or guarantee that two database systems will interpret every expression in the same way. It is a readability and review aid, not a substitute for testing.
A useful style guide should answer three questions:
- Where should major clauses, joins, and conditions appear?
- How can a reviewer see the query structure quickly?
- Which parts depend on the SQL dialect or formatter configuration?
Start with a formatter when you inherit a dense query, but review the result manually. Automatic formatting may preserve syntax while producing a layout that does not match your team’s conventions. The best final format makes the logical execution steps easy to follow: identify the source rows, apply joins, filter records, group or calculate values, and return the required columns.
Before: a query that is difficult to scan
SELECT u.id,u.email,COUNT(o.id) AS order_count FROM users u LEFT JOIN orders o ON o.user_id=u.id AND o.status='paid' WHERE u.created_at >= '2025-01-01' AND (u.country='US' OR u.country='CA') GROUP BY u.id,u.email HAVING COUNT(o.id) > 2 ORDER BY order_count DESC;
After: the same query with a clear structure
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
AND o.status = 'paid'
WHERE u.created_at >= '2025-01-01'
AND u.country IN ('US', 'CA')
GROUP BY
u.id,
u.email
HAVING COUNT(o.id) > 2
ORDER BY order_count DESC;
The second version exposes the join type, join condition, filter grouping, grouping columns, and final sort. That structure helps reviewers ask meaningful questions about logic rather than spending time reconstructing the query from a single line.
Checklist by scenario
Formatting a basic SELECT query
- Put
SELECT,FROM,WHERE,GROUP BY,HAVING, andORDER BYon separate lines. - Place each selected column on its own line when the list is longer than a few items.
- Use a consistent indentation width throughout the query.
- Use aliases consistently. An explicit
ASkeyword can make aliases easier to spot, although supported syntax varies by object type and dialect. - Qualify columns when more than one table contains a similarly named field.
Formatting joins
- Write each join on its own line and keep the join type visible.
- Indent the
ONcondition beneath the join. - Place additional predicates for that relationship on subsequent, aligned lines.
- Keep filters that apply to the entire result in
WHERE, unless moving a condition changes the intended behavior of an outer join. - Check whether a join can multiply rows before adding aggregation.
For a deeper review of join behavior, use the related SQL JOINs guide. Formatting can reveal a misplaced condition, but it cannot decide whether that condition belongs in ON or WHERE.
Formatting subqueries and common table expressions
Use a common table expression when naming an intermediate result makes the query easier to understand or test. Put each CTE on its own block and indent its internal query consistently.
WITH recent_orders AS (
SELECT
order_id,
user_id,
created_at,
total_amount
FROM orders
WHERE created_at >= :start_date
),
user_totals AS (
SELECT
user_id,
SUM(total_amount) AS total_amount
FROM recent_orders
GROUP BY user_id
)
SELECT
u.id,
u.email,
t.total_amount
FROM users AS u
JOIN user_totals AS t
ON t.user_id = u.id;
For a nested subquery, give the inner query enough vertical space to show its own clauses. Avoid compressing a subquery into one line merely to reduce the total line count.
Formatting window functions
Window functions become easier to review when the expression, partition, ordering, and frame are visually separated.
SELECT
account_id,
event_time,
amount,
SUM(amount) OVER (
PARTITION BY account_id
ORDER BY event_time
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS running_amount
FROM account_events;
Use the same style for ROW_NUMBER, RANK, LAG, and similar functions. If several window expressions share the same definition, check whether your database supports a named window clause before repeating a long specification.
Formatting long filter conditions
Put each major Boolean condition on its own line. Indent nested AND and OR groups so the precedence is apparent, and use parentheses instead of relying on a reader’s memory of operator precedence.
WHERE
account_status = 'active'
AND created_at >= :start_date
AND (
country IN ('US', 'CA')
OR (
country = 'GB'
AND marketing_opt_in = TRUE
)
)
Do not replace a long list with IN automatically if the values have different business meanings or if a lookup table would be clearer. Formatting should make logic explicit, not conceal it behind shorter syntax.
Formatting INSERT, UPDATE, and DELETE statements
For data-changing statements, place the target columns and values on matching lines where practical. Always format the filter so the affected rows are unmistakable.
UPDATE customer_preferences
SET
email_notifications = FALSE,
updated_at = CURRENT_TIMESTAMP
WHERE customer_id = :customer_id;
Before executing a destructive statement, run the corresponding SELECT with the same WHERE clause when appropriate. A clean layout makes this safety check easier to perform.
What to double-check
| Area | What can differ | Review action |
|---|---|---|
| Boolean values | Some systems support TRUE and FALSE directly; others use numeric or text conventions. | Confirm the column type and database syntax. |
| Identifier quoting | Quoted identifiers and the characters used for them vary by dialect and settings. | Use the quoting style accepted by the target database. |
| Date and time functions | Current-time functions, interval syntax, and date arithmetic are not universal. | Test expressions against the deployment database. |
| Pagination | Limit and offset syntax differs, and some systems prefer a different row-limiting form. | Keep the formatter’s dialect setting aligned with the query’s target. |
| String concatenation | Concatenation operators and functions vary across systems. | Do not treat formatter output as a portability guarantee. |
| Reserved words | A column name that works in one database may conflict with a reserved word in another. | Rename the identifier or quote it using the target dialect. |
Before using an online SQL formatter, remove credentials, private customer data, and other sensitive values. Prefer placeholders such as :user_id or representative test values. If a tool supports a dialect setting, select the actual database rather than relying on a generic SQL mode. Also inspect formatter settings for keyword casing, indentation, comma placement, line width, and identifier case.
Formatting and performance are separate concerns. After making a query readable, inspect its execution plan, indexes, row estimates, and returned row count in a safe environment. A SQL prettifier should not be credited with an optimization that came from a logical or schema change.
Common mistakes
- Changing logic while formatting. Replacing an expression, moving a condition, or changing a join is an edit, not formatting. Review these changes separately.
- Hiding outer-join behavior. A predicate moved from
ONtoWHEREcan change which unmatched rows remain. - Relying on implicit column order. Use an explicit column list instead of
SELECT *in durable application queries and data exports. - Using unclear aliases. Short aliases can reduce repetition, but meaningful aliases are easier to review in long queries.
- Ignoring duplicate rows. A neatly formatted query can still return duplicates because of a one-to-many join. Check the relationship cardinality.
- Over-formatting trivial queries. A short statement does not need a rigid multi-line layout. Apply the level of structure that improves scanning.
- Mixing team conventions. Inconsistent keyword case, commas, aliases, and indentation create noisy diffs. Record the chosen rules in a repository style guide or formatter configuration.
When to revisit
Revisit this SQL formatting checklist whenever your database engine, formatter, linting rules, or team conventions change. A database release may introduce new syntax, reserved words, functions, or formatter support. A migration is also a good time to check every dialect-specific expression instead of assuming that a visually consistent query is portable.
Use the checklist before committing a complex migration, reviewing a production incident query, publishing a report, or handing a data task to another developer. It is especially useful when a query gains a new join, CTE, window function, or group of conditional filters. Compare the formatted result with the previous version, inspect logical changes separately, and test representative edge cases.
A practical final pass is:
- Select the correct SQL dialect in your formatter or editor.
- Format the query and remove sensitive values before sharing it.
- Read the query from top to bottom, checking joins, filters, grouping, and ordering.
- Run a syntax check and test expected edge cases.
- Inspect the execution plan when performance matters.
- Save the agreed formatting rules with the project so future queries produce consistent diffs.
When a query is readable, debugging starts with the actual data and logic rather than with deciphering its layout. That is the central purpose of a SQL formatter: to make the next review, test, and maintenance task safer and faster.