SQL formatting best practices for maintainable queries
SQL formatting is not cosmetic when a query becomes part of a product, dashboard, migration, or incident investigation. A readable query makes intent visible. It helps reviewers understand the shape of the data, the join path, the filters, and the assumptions behind the result set.
1. Put major clauses on separate lines
A dense one-line query hides its structure. Start the major clauses on their own lines so readers can find
the flow immediately: SELECT, FROM, JOIN, WHERE,
GROUP BY, HAVING, ORDER BY, and LIMIT.
SELECT
customer_id,
COUNT(*) AS order_count,
SUM(total_amount) AS lifetime_value
FROM orders
WHERE status = 'paid'
GROUP BY customer_id
ORDER BY lifetime_value DESC; 2. Indent nested logic consistently
Subqueries, CTEs, CASE expressions, and nested predicates should visually show their scope. Consistent indentation helps reviewers see where a block begins and ends.
WITH recent_orders AS (
SELECT
customer_id,
total_amount,
created_at
FROM orders
WHERE created_at >= CURRENT_DATE - INTERVAL '30 days'
)
SELECT
customer_id,
SUM(total_amount) AS recent_revenue
FROM recent_orders
GROUP BY customer_id; 3. Choose a keyword case and stick with it
Uppercase keywords are common because they separate SQL syntax from identifiers. Lowercase can also work when a team prefers it. The important part is consistency across files and reviews.
4. Prefer meaningful aliases
Aliases like u and o are readable in small queries. Longer reporting queries often
benefit from aliases such as customers, orders, or paid_orders. The
best alias is short enough to type and clear enough to review.
5. Keep join conditions close to the join
Join predicates belong next to the join they explain. Additional filtering belongs in the
WHERE clause unless it intentionally changes outer join behavior.
SELECT
customers.id,
orders.id AS order_id
FROM customers
LEFT JOIN orders
ON orders.customer_id = customers.id
AND orders.status = 'paid'
WHERE customers.is_active = true; 6. Comment intent, not syntax
Comments should explain business rules, unusual performance choices, or dialect-specific behavior. Avoid comments that restate the obvious.
Beautify before sharing SQL
Consistent layout gives every query a stable baseline. Paste a query into SQL Script, beautify it, add auto-comments if helpful, and copy the result into your pull request, ticket, or docs.