A well-formatted SQL query is easier to review, debug, test, and safely change. This checklist shows how to format SELECT, JOIN, CTE, INSERT, and migration statements, compare formatter options, and review the details that formatting alone cannot catch.
Overview
SQL formatting is more than placing keywords on separate lines. A consistent layout exposes relationships between tables, makes filters easier to inspect, and helps reviewers notice ambiguous columns, unsafe updates, unexpected null behavior, and expensive access patterns. A formatter can provide a reliable baseline, but it cannot determine whether a query expresses the correct business rule.
Before sharing or deploying a query, use two separate passes:
- Format the structure: apply consistent indentation, capitalization, line breaks, aliases, and clause ordering.
- Review the behavior: verify result meaning, edge cases, permissions, performance assumptions, and destructive effects.
SQL dialects differ. PostgreSQL, MySQL, SQL Server, SQLite, and other database systems may use different functions, quoting rules, pagination syntax, upsert patterns, and migration features. Choose a formatter that supports the dialect used by the target database, then confirm the output against the database documentation and your project’s linting rules. For broader formatting examples, see this SQL formatter and linter guide.
Formatter comparison checklist
| Formatter capability | Why it matters | What to verify |
|---|---|---|
| Dialect selection | Prevents syntax and quoting assumptions from another database. | PostgreSQL, MySQL, SQL Server, or the dialect your project uses. |
| Keyword and identifier casing | Creates a predictable visual hierarchy. | Whether keywords, functions, aliases, and names follow team conventions. |
| JOIN and subquery layout | Makes table relationships and nested logic visible. | Readable line breaks for ON, WHERE, GROUP BY, and nested expressions. |
| Comment preservation | Retains context about assumptions and exceptions. | Inline and block comments remain attached to the relevant code. |
| CI or editor integration | Reduces formatting drift between contributors. | Stable configuration, predictable output, and a check mode suitable for automation. |
Checklist by scenario
SELECT statements
Start with one selected expression per line when a query has more than a few columns. Use explicit column names instead of SELECT * in shared code, reports, and application queries where the result shape matters.
SELECT
o.id,
o.created_at,
o.status,
c.email AS customer_email
FROM orders AS o
JOIN customers AS c
ON c.id = o.customer_id
WHERE o.created_at >= :start_date
AND o.created_at < :end_date
ORDER BY o.created_at DESC;- Give tables short, meaningful aliases and use them consistently.
- Put commas in a consistent position according to the project standard.
- Use half-open date ranges, such as greater than or equal to a start and less than an end, when that matches the intended time window.
- Keep the final semicolon if the query will be stored, reviewed, or executed as a standalone statement.
JOIN statements
Place each JOIN on its own line and indent the ON condition beneath it. If a relationship needs multiple conditions, put each condition on a separate line. Confirm whether the relationship is one-to-one, one-to-many, or optional before choosing INNER JOIN or LEFT JOIN.
SELECT
p.id,
p.name,
COUNT(i.id) AS invoice_count
FROM projects AS p
LEFT JOIN invoices AS i
ON i.project_id = p.id
AND i.voided_at IS NULL
GROUP BY
p.id,
p.name;Notice that the invoice condition is in the ON clause. Moving it to WHERE would remove projects with no matching invoices and could change the left join into inner-join-like behavior.
CTEs and nested logic
Use a common table expression when it gives a meaningful name to an intermediate result or separates distinct reasoning steps. Each CTE should have a clear purpose, and the final query should make the flow easy to follow.
WITH recent_orders AS (
SELECT
customer_id,
COUNT(*) AS order_count
FROM orders
WHERE created_at >= :cutoff
GROUP BY customer_id
), eligible_customers AS (
SELECT
c.id,
c.email,
r.order_count
FROM customers AS c
JOIN recent_orders AS r
ON r.customer_id = c.id
WHERE r.order_count >= :minimum_orders
)
SELECT
id,
email,
order_count
FROM eligible_customers
ORDER BY order_count DESC;Review each CTE independently before reviewing the complete statement. Check its row grain: ask what one row represents at every stage.
INSERT and data changes
List target columns explicitly. This protects the statement from depending on the physical order of table columns and makes code review more precise.
INSERT INTO audit_events (
actor_id,
event_type,
resource_id,
created_at
)
VALUES (
:actor_id,
:event_type,
:resource_id,
CURRENT_TIMESTAMP
);For INSERT ... SELECT, format the source query as carefully as the target column list. Confirm that both lists have the same order, compatible types, and intended nullability.
Migration statements
Separate migration operations when possible so each change has a clear purpose and rollback or recovery plan. Before deploying a migration, check lock behavior, default values, existing rows, index build strategy, and whether the operation is safe for the expected table size.
ALTER TABLE accounts
ADD COLUMN last_login_at TIMESTAMP NULL;Do not treat a cleanly formatted migration as a safe migration. Schema changes can affect application versions, background jobs, reporting queries, and deployment order.
What to double-check
Meaning and row counts
- What does one output row represent?
- Can any JOIN multiply rows unexpectedly?
- Does the query return records that lack related data, or should those records be excluded?
- Are duplicates expected, removed intentionally, or hidden by
DISTINCT?
Null handling
Test nullable columns explicitly. Comparisons with NULL do not behave like comparisons with ordinary values; use IS NULL or IS NOT NULL where appropriate. Review COALESCE, conditional expressions, aggregates, and outer joins for cases where missing data should remain distinguishable from zero, an empty string, or a fallback value.
Filtering and dates
Check whether filters are applied before or after aggregation, and whether a condition belongs in WHERE, HAVING, or a JOIN’s ON clause. Confirm the time zone, precision, and inclusivity of date boundaries. If an application supplies timestamps, document the expected representation rather than relying on an implicit database or session setting. For related application-side date concerns, see JavaScript date and time zone handling.
Performance and indexes
Look for functions applied to filtered columns, leading-wildcard searches, unnecessary sorting, large unbounded result sets, and joins without appropriate supporting indexes. Use an execution plan in a safe environment to test assumptions. An index can help one access pattern while adding write cost or storage overhead, so review it alongside the query workload rather than in isolation.
Safety and permissions
- Parameterize user-provided values; do not build SQL by concatenating untrusted input.
- Before running
UPDATEorDELETE, run the corresponding predicate as aSELECTand inspect the affected rows. - Confirm that a destructive statement has a restrictive
WHEREclause and an appropriate transaction or recovery plan. - Check that the execution role has only the permissions needed for the operation.
Common mistakes
Formatting without understanding
A formatter can make incorrect logic look authoritative. Read the query in plain language after formatting: which records enter the result, which are excluded, and how are values grouped?
Using DISTINCT to hide a join problem
DISTINCT may remove visible duplicates while concealing an incorrect relationship or incomplete join condition. Identify why rows multiply before deciding whether deduplication is part of the requirement.
Relying on implicit behavior
Implicit column order, type conversion, identifier casing, default time zones, and database-specific functions make queries harder to migrate and review. Make important assumptions explicit, especially in shared scripts and migrations.
Ignoring the application contract
A query can be valid SQL yet break a caller by renaming a field, changing nullability, altering ordering, or returning a different data type. Compare the result with the API, report, or job that consumes it. When SQL is part of an automated workflow, add formatting and validation checks to CI; the GitHub Actions workflow guide covers the general automation pattern.
When to revisit
Return to this checklist whenever a query’s inputs, environment, or purpose changes. Review it before a seasonal planning cycle or reporting period, after adding a table or index, when a database dialect or formatter configuration changes, and whenever an inherited query is prepared for production use.
For a practical final pass, save the formatted query with its dialect and purpose, test representative normal and edge cases, inspect the execution plan where performance matters, and record any assumptions about nulls, time zones, permissions, and destructive effects. Re-run that review after schema migrations, application contract changes, or meaningful data-volume changes. Formatting is the starting point; a query is ready to share or deploy only when its structure and behavior are both understandable.