SQL formatting best practices: 12 rules, with real before and after examples
By Hammad Rasool · November 7, 2026
Quick answer: good SQL formatting means one clause per line (SELECT, FROM, WHERE…), one column or condition per line, consistent keyword case, a fixed indent, explicit AS for aliases, explicit JOIN types, and CTEs instead of deeply nested subqueries. No rule matters as much as applying the same rules everywhere, which is why teams let a formatter handle layout and spend code review on logic.
Below are 12 rules, where the two most-cited public style guides agree and disagree, and what an automatic formatter can and cannot fix for you. Every "formatted" example on this page is real output from the ToolStash SQL formatter (sql-formatter 15.8, 2-space indent).
Does formatting change how a query runs?
No. Whitespace, line breaks and keyword case are not part of the query's meaning, so a formatted query returns exactly the same rows with the same plan. One nuance: some databases, such as Oracle and SQL Server, reuse a cached execution plan only when the statement text matches exactly. If the same query is sent from several places with different spacing, each version can get its own cache entry. That is an argument for one consistent format, not against formatting.
Before and after
A typical query copied from an ORM log or a one-line string in application code:
select o.id,c.name as customer,sum(oi.qty*oi.price) total from orders o join customers c on c.id=o.customer_id left join order_items oi on oi.order_id=o.id where o.status='paid' and o.created_at>='2026-01-01' group by o.id,c.name having sum(oi.qty*oi.price)>100 order by total desc limit 10
The same query after formatting:
SELECT o.id, c.name AS customer, sum(oi.qty * oi.price) total FROM orders o JOIN customers c ON c.id = o.customer_id LEFT JOIN order_items oi ON oi.order_id = o.id WHERE o.status = 'paid' AND o.created_at >= '2026-01-01' GROUP BY o.id, c.name HAVING sum(oi.qty * oi.price) > 100 ORDER BY total DESC LIMIT 10
The structure is now visible at a glance: three tables, two filters, one aggregate. Notice what the formatter did not do: the alias total still has no AS, the function is still lowercase sum, and the one-letter aliases are unchanged. Rules 5 to 8 below are choices you make when writing the query.
The 12 rules
1. Pick one keyword case and keep it
Both the Mozilla Data Documentation style guide and sqlstyle.guide ask for uppercase reserved keywords (SELECT, WHERE, AS). Uppercase separates the language from your table and column names, which matters most in plain-text places like logs and code review. Some analytics teams prefer all-lowercase because it is faster to type and editors already colour keywords. Either works; mixing them in one file does not. The formatter has an UPPERCASE / lowercase / Preserve switch for exactly this.
2. Put each major clause on its own line
SELECT, FROM, each JOIN, WHERE, GROUP BY, HAVING, ORDER BY and LIMIT each start a line. A reader scanning the left edge sees the shape of the query without reading it.
3. One column, one condition per line
Long SELECT lists and WHERE clauses become one item per line, with AND / OR at the start of the line. This makes diffs show exactly which column or filter changed, instead of one long changed line.
4. Use a fixed indent (2 or 4 spaces)
Mozilla's examples use 2 spaces; sqlstyle.guide prefers a "river" that right-aligns keywords instead of a fixed indent. A fixed indent is easier to keep consistent by hand and is what most formatters produce. Indent everything that belongs to a clause, and indent a subquery or CTE body one more level.
5. Always write AS for aliases
Both guides require it: c.name AS customer, orders AS ord. Without AS, a missing comma silently turns the next column into an alias: SELECT name email returns one column called email that contains names. With an AS habit, that line looks wrong immediately.
6. Give aliases real names
o, c and oi are fine in a three-line query and painful in a 200-line one. Short words (ord, cust, item) cost a few characters and save every future reader a lookup.
7. Write the JOIN type explicitly
Mozilla's guide asks for the JOIN type instead of relying on the default. JOIN means INNER JOIN in every major database, but writing INNER makes the choice visible next to the LEFT JOIN lines, where an accidental inner join is a common source of missing rows.
8. Prefer CTEs to nested subqueries
Mozilla's guide says not to nest queries and to use common table expressions (WITH) instead. Compare the same logic both ways, both formatted:
SELECT
name
FROM
(
SELECT
c.name,
count(*) n
FROM
customers c
JOIN orders o ON o.customer_id = c.id
GROUP BY
c.name
) t
WHERE
n > 5WITH
order_counts AS (
SELECT
customer_id,
count(*) AS n
FROM
orders
GROUP BY
customer_id
)
SELECT
c.name
FROM
customers c
INNER JOIN order_counts oc ON oc.customer_id = c.id
WHERE
oc.n > 5The CTE version reads top to bottom and gives the intermediate result a name. In most modern databases the two compile to the same plan; check EXPLAIN if performance matters, because older PostgreSQL versions (before 12) always materialised CTEs.
9. Name things in snake_case
Both guides use lowercase names with underscores (first_name, order_items) and advise against camelCase. Some databases fold unquoted names to upper or lower case, so FirstName may only work when quoted every time.
10. Avoid names that need quoting
Reserved words and spaces force dialect-specific quotes, which makes SQL harder to move between databases:
-- MySQL / MariaDB SELECT `order`, `select` FROM `my table`; -- SQL Server SELECT [order], [select] FROM [my table]; -- PostgreSQL, SQLite, Oracle and the SQL standard SELECT "order", "select" FROM "my table"; -- Better: names that never need quotes SELECT order_number, selection FROM my_table;
11. Comment the why, not the what
-- exclude test accounts created by QA helps; -- filter status above WHERE status = 'paid' does not. Use -- line comments; they work in every major dialect and do not break when someone comments out a block.
12. Let a tool do the layout
Paste the query into a SQL formatter before committing or sharing it, and choose the dialect so quoting and keywords are recognised (MySQL, T-SQL, PL/SQL). For a whole repository, a linter such as SQLFluff can check rules like explicit AS in CI.
Leading or trailing commas?
This is the one rule teams argue about. Mozilla's guide asks for commas at the end of the line, and sqlstyle.guide's examples use them too. Leading commas have one practical advantage: you can comment out any line, including the last one, without editing another line.
SELECT id, name, email -- , created_at <- commenting out the last column leaves "email" fine FROM customers
SELECT id , name , email -- , created_at <- any line can be commented out on its own FROM customers
Trailing commas read like normal prose and are what most formatters, including ours, output. If your team picks leading commas, write them by hand and keep them everywhere.
Where the two big style guides agree and differ
| Rule | Mozilla Data Docs | sqlstyle.guide |
|---|---|---|
| Keyword case | Uppercase | Uppercase |
| Commas | Trailing (stated rule) | Trailing in examples, no stated rule |
| Indentation | 2 spaces in examples | Right-aligned keyword "river" |
| Naming | snake_case, no camelCase | snake_case, no camelCase |
Explicit AS | Always | Always |
| CTEs vs subqueries | Use CTEs, no nested queries | Not stated |
| JOIN type | Always explicit | Examples use both INNER JOIN and JOIN |
Checked against both guides on November 6, 2026.
What a formatter fixes, and what it can't
| Fixed automatically | Still your job |
|---|---|
| Line breaks per clause, column and condition | Adding AS to aliases |
| Indentation of subqueries and CTEs | Meaningful alias and column names |
| Keyword case | Writing INNER / LEFT explicitly |
| Spacing around operators and commas | Turning nested subqueries into CTEs |
| Consistent output for the same input | Comments that explain intent |
Applying rules 5 to 8 by hand to the earlier example gives:
SELECT ord.id AS order_id, cust.name AS customer_name, SUM(item.qty * item.price) AS order_total FROM orders AS ord INNER JOIN customers AS cust ON cust.id = ord.customer_id LEFT JOIN order_items AS item ON item.order_id = ord.id WHERE ord.status = 'paid' AND ord.created_at >= '2026-01-01' GROUP BY ord.id, cust.name HAVING SUM(item.qty * item.price) > 100 ORDER BY order_total DESC LIMIT 10
Frequently asked questions
Is uppercase or lowercase SQL more correct?
Neither. SQL keywords are case-insensitive in every major database. Uppercase is the more common published convention; consistency inside a codebase is what actually helps readers.
Should I format SQL that lives inside application code?
Yes, if it is longer than a line or two. Multi-line string literals or separate .sql files keep the query readable and make diffs meaningful. For SQL that must fit on one line, such as a log message or a URL parameter, use a SQL minifier instead.
Does formatting work the same for PL/SQL and T-SQL?
The layout rules are the same, but procedural blocks (BEGIN … END, DECLARE, variables) need a formatter that knows the dialect. Choose PL/SQL or T-SQL in the formatter rather than the generic SQL option.
Is it safe to paste production queries into an online formatter?
Only if the formatter does not upload them. The ToolStash formatter runs in your browser; the query is not sent to a server. If a query contains customer data in literals, remove those values first anyway.
How do I get a team to follow one style?
Write the few rules you care about into the repository (a short README section is enough), format automatically before commit, and add a linter to CI for the rules a formatter cannot apply.
Summary
Put clauses, columns and conditions on their own lines, keep keyword case and indentation consistent, write AS and JOIN types explicitly, and prefer CTEs. Let the SQL formatter handle layout in seconds, and keep your attention for the choices only a person can make.