Blog ·
SQL Formatting Best Practices: A Readable Style Guide
SQL formatting best practices: uppercase keywords, one clause per line, explicit JOINs, qualified columns and steady indentation, with examples.
SQL Formatter
Format and beautify SQL queries for popular SQL dialects.
The best SQL formatting is the one your team applies the same way every time. Put each major clause on its own line, uppercase the keywords, qualify column names when more than one table is involved, and use explicit JOIN syntax with short aliases. Those few habits make most queries easy to scan, review and debug.
If you have a messy query to clean up, paste it into the SQL Formatter. It supports Standard SQL, MySQL, PostgreSQL, SQL Server and SQLite, so you can apply the rules below to the dialect you actually run.
Why formatting matters for SQL
SQL is read far more often than it is written. Queries get copied into tickets, reviewed in pull requests, and tuned months later by someone who was not there when they were written. A consistent layout lets the reader find the source tables, filters and output columns in seconds.
Formatting also helps you catch logic errors. A missing join condition or a filter applied to the wrong table is much easier to spot when every clause starts on its own line.
Core layout rules
- Start each major clause on a new line: SELECT, FROM, JOIN, WHERE, GROUP BY, HAVING, ORDER BY, LIMIT or FETCH.
- Indent the items under SELECT and the conditions under WHERE and ON by a consistent amount, usually two or four spaces.
- Put one column per line in the SELECT list. A long single line is hard to diff and hard to comment out.
- Keep one condition per line in WHERE and ON. Start continuation lines with AND or OR so the boolean operator is easy to see.
- End statements with a semicolon, even when a single statement runs alone. It prevents surprises when you later add a second statement to the same script.
SELECT o.id, o.order_date, o.total_amount, c.name AS customer_name FROM orders AS o JOIN customers AS c ON c.id = o.customer_id WHERE o.order_date >= '2024-01-01' AND o.status = 'shipped' ORDER BY o.order_date DESC;
Keywords, identifiers and case
Write SQL keywords in uppercase (SELECT, FROM, WHERE) and identifiers in one consistent case. Many teams use lowercase snake_case for table and column names, which matches how most schemas are designed. The exact choice matters less than being consistent within a project.
Be careful with quoting. In PostgreSQL, unquoted identifiers are folded to lowercase, so a column created as "OrderDate" with double quotes must always be referenced with the same quotes. In MySQL, whether table and database names are case-sensitive depends on the operating system and the lower_case_table_names setting. Column names are always case-insensitive in MySQL. Avoid mixed-case names that need quoting, and you avoid most of these problems.
Use explicit JOIN syntax and aliases
Write JOIN ... ON rather than listing tables separated by commas and putting the join condition in WHERE. The explicit form keeps each join condition next to the table it belongs to, and it is much harder to accidentally create a cross join.
Give tables short aliases that are meaningful, such as o for orders and c for customers. In PostgreSQL, MySQL, SQL Server and SQLite, you can write AS before both table and column aliases, which makes the alias visible. Oracle does not accept AS for table aliases, so there you write FROM orders o and use AS only for column aliases. Avoid single letters that do not match the table, such as using c for orders, because readers will stop trusting the names.
When a query uses more than one table, qualify every column with its alias. Unqualified names such as id or created_at become ambiguous quickly, and PostgreSQL, MySQL, SQL Server and SQLite reject them with an ambiguous column error when the name exists in more than one table.
-- Hard to review: implicit join, unqualified columns SELECT id, name, created_at FROM users, orders WHERE users.id = orders.user_id AND status = 'paid'; -- Easier to review: explicit join, qualified columns SELECT u.id, u.name, o.created_at FROM users AS u JOIN orders AS o ON o.user_id = u.id WHERE o.status = 'paid';
The first query is ambiguous only if both tables share column names such as id, created_at or status. Whether it fails depends on the schema. When a name exists in both tables, the database rejects the unqualified reference rather than picking one, so the first query may run today and break after someone adds a matching column. The second version removes that risk and shows the reader exactly where each column comes from.
Avoid SELECT * in saved queries
SELECT * is fine for a quick look at a table in a console. In queries that live in application code, reports or views, list the columns you need. Explicit columns make the output shape visible, avoid pulling large unused columns, and keep working when someone adds a column to the table later.
Structure complex queries with CTEs
Common table expressions (WITH clauses) let you name intermediate steps instead of nesting subqueries several levels deep. Each CTE reads top to bottom, and the final SELECT becomes short. Use one CTE per logical step, and name it after what it contains.
WITH paid_orders AS (
SELECT
o.user_id,
o.total_amount
FROM orders AS o
WHERE o.status = 'paid'
),
spend_per_user AS (
SELECT
p.user_id,
SUM(p.total_amount) AS total_spend
FROM paid_orders AS p
GROUP BY p.user_id
)
SELECT
u.name,
s.total_spend
FROM spend_per_user AS s
JOIN users AS u
ON u.id = s.user_id
ORDER BY s.total_spend DESC;Keep in mind that a CTE is a readability tool, not a performance guarantee. Depending on the database and version, the optimizer may treat CTEs differently from subqueries, so check the execution plan if performance matters.
Comments and formatting of expressions
- Use -- for single-line comments and /* ... */ for longer notes. Explain why a filter exists, not what the SQL obviously does.
- Put CASE expressions on multiple lines, with each WHEN on its own line.
- Keep function calls readable. Break long arguments across lines rather than wrapping an entire expression onto one line.
- Be explicit about NULL handling with IS NULL and IS NOT NULL. Comparing to NULL with = never returns true.
Pitfalls that hurt readability and correctness
- Mixing comma-first and comma-last styles in the same file. Pick one. Comma-last is the most common, and comma-first makes adding and removing lines easier in some teams.
- Hiding a filter in a JOIN when it belongs in WHERE, or the reverse. For a LEFT JOIN, a condition on the right-hand table placed in WHERE removes the unmatched rows, which often turns the join into an inner join without anyone noticing.
- Letting a formatter rewrite a query you wrote for a specific dialect. Check the output against the dialect your database uses, since syntax such as date literals, LIMIT and quoting differs.
- Leaving aliases that differ only by a number, such as t1 and t2, in large queries. Descriptive aliases cost a few keystrokes and save time in review.
A short checklist
- Keywords in uppercase, identifiers in one consistent case.
- Each major clause starts on its own line, with consistent indentation.
- One column per line in SELECT, one condition per line in WHERE and ON.
- Explicit JOIN ... ON with aliases, and every column qualified when multiple tables are involved.
- No SELECT * in saved queries.
- CTEs named after each logical step instead of deep nesting.
- A semicolon at the end of each statement.
Once a team agrees on these rules, put them in a shared document or a linter config so the decisions do not have to be made again in every review. Then run existing queries through the SQL Formatter to bring older code in line.
FAQ
Should SQL keywords always be uppercase?
Uppercase keywords are the most common convention and make the structure of a query easier to see. SQL itself is case-insensitive for keywords in most dialects, so this is a readability choice, not a requirement. Whatever you choose, apply it everywhere in the project.
Are leading commas or trailing commas better?
Neither is objectively better. Trailing commas are more common and read naturally. Leading commas make it easy to comment out the last column without editing the line above it. The important part is picking one style and keeping it.
Does formatting SQL change how it runs?
Whitespace and line breaks do not change the meaning of a query, except inside string literals and quoted identifiers, which a formatter should leave untouched. Always review the output of an automatic formatter before deploying it, especially for dialect-specific syntax.
Can I use the same style for every SQL dialect?
Yes, the layout rules above apply to Standard SQL, MySQL, PostgreSQL, SQL Server and SQLite alike. Only the syntax details differ, such as how identifiers are quoted, how LIMIT or TOP is written, which aliases may use AS, and which date and string functions exist.
SQL Formatter
Format and beautify SQL queries for popular SQL dialects.