SQL Formatting Guide: How to Format Queries for Readability
A well-formatted SQL query is easier to review, debug, and change safely. This guide covers a practical style for
SELECT statements, joins, filters, subqueries, common table expressions, and data modification statements.
1. Put the Query Structure on the Page
Start each major clause on its own line. A reader should be able to scan the query and see the data source,
filters, grouping, and sort order without searching through a wall of text.
SELECT
customer_id,
order_total,
created_at
FROM orders
WHERE status = 'paid'
ORDER BY created_at DESC;
This layout also makes it safer to add or remove a column. Each selected expression has a clear position and the
trailing comma convention is easy to review in a code diff.
2. Format Joins and Conditions Consistently
Keep the join type visible and place the join condition below it. Use short, meaningful aliases when a query
references several tables, but avoid aliases that hide the meaning of a column.
SELECT
u.email,
o.id AS order_id,
o.order_total
FROM users AS u
INNER JOIN orders AS o
ON o.user_id = u.id
WHERE u.active = true
AND o.created_at >= '2026-01-01';
Aligning additional predicates under the first condition makes it obvious whether a rule belongs to the join or
the final result filter. That distinction matters when changing an INNER JOIN to a LEFT JOIN.
3. Indent Subqueries and CTEs
A nested query should look like a nested piece of logic. Common table expressions are particularly useful when a
query has several stages that deserve names.
WITH recent_orders AS (
SELECT
user_id,
COUNT(*) AS order_count
FROM orders
WHERE created_at >= CURRENT_DATE - INTERVAL '30 days'
GROUP BY user_id
)
SELECT
u.email,
r.order_count
FROM users AS u
INNER JOIN recent_orders AS r
ON r.user_id = u.id
ORDER BY r.order_count DESC;
4. Formatting Is Not Query Optimization
A formatter changes presentation, not the database execution plan. Once the query is readable, inspect indexes,
filter selectivity, join cardinality, and the database's explain output. Readability is the step that makes those
performance questions easier to ask and answer.
- Use explicit columns instead of
SELECT * in application queries.
- Keep filters close to the clause where they apply.
- Use parentheses when mixed AND and OR conditions could be misread.
- Review generated SQL before putting it into a migration or deployment script.
5. A Practical Review Checklist
- Can a reader identify the main table and every join immediately?
- Are aliases consistent and meaningful?
- Are every selected column and condition easy to compare in a diff?
- Are nested queries and CTEs indented one level deeper?
- Have formatting and performance review been treated as separate tasks?
Continue with the
SQL Formatter for quick cleanup, then compare revisions with the
Diff Checker before committing a query change.