I have read thousands of SQL queries over the years. The ones that are easy to debug, review, and maintain all share something simple: they are formatted well. Badly formatted SQL is not just ugly. It hides bugs, slows down code reviews, and makes onboarding new team members harder than it needs to be.
This guide covers practical SQL formatting rules you can apply today. No theory, no fluff. Just the conventions that make queries readable and the tools that enforce them automatically.
Why SQL Formatting Matters
SQL is declarative. You describe what data you want, not how to get it. This means the same query can be written in dozens of ways and still produce identical results. Without formatting conventions, every developer on your team writes SQL differently, and reading someone else's query feels like deciphering a foreign language.
Here is the same query written two ways. Same logic, same output. But one is readable in five seconds, the other takes thirty.
Before formatting:
select u.id,u.name,o.total from users u join orders o on u.id=o.user_id where o.status='paid' and o.total>100 order by o.total desc limit 20
After formatting:
SELECT u.id,
u.name,
o.total
FROM users AS u
JOIN orders AS o
ON u.id = o.user_id
WHERE o.status = 'paid'
AND o.total > 100
ORDER BY o.total DESC
LIMIT 20;
The formatted version makes the structure obvious. You can see the SELECT columns, the JOIN condition, the WHERE filter, and the ORDER BY at a glance. The unformatted version forces you to parse the entire string mentally before you understand what it does.
Core SQL Formatting Rules
These rules come from widely adopted style guides, including the popular SQL Style Guide by Simon Holywell. Pick what works for your team and stick with it.
1. Uppercase SQL Keywords
Keywords like SELECT, FROM, WHERE, JOIN, GROUP BY, ORDER BY should always be uppercase. This visually separates SQL syntax from table names, column names, and values.
-- Bad
select id, name from users where active = 1;
-- Good
SELECT id,
name
FROM users
WHERE active = 1;
2. One Column Per Line
When your SELECT list has more than two or three columns, put each one on its own line. This makes it trivial to add, remove, or comment out a column without touching the others.
-- Bad
SELECT id, name, email, created_at, status FROM users;
-- Good
SELECT id,
name,
email,
created_at,
status
FROM users;
For short queries with one or two columns, keeping them on one line is fine. Use judgment.
3. Indent to Show Hierarchy
Indentation should reflect the logical structure of the query. The FROM, WHERE, GROUP BY, ORDER BY, and LIMIT clauses sit at the base indentation. Their contents are indented one level deeper. Join conditions go one level deeper still.
SELECT u.id,
u.name,
COUNT(o.id) AS order_count
FROM users AS u
LEFT JOIN orders AS o
ON u.id = o.user_id
WHERE u.created_at >= '2026-01-01'
AND u.status = 'active'
GROUP BY u.id, u.name
HAVING COUNT(o.id) > 5
ORDER BY order_count DESC
LIMIT 50;
Notice how ON sits one indent deeper than LEFT JOIN, and the second WHERE condition aligns with AND. This alignment makes complex WHERE clauses scannable.
4. Use Table Aliases Consistently
Aliases shorten queries and make column references unambiguous. Use short, meaningful aliases and apply them consistently. Always prefix columns with the alias when joining tables.
-- Bad: no aliases, ambiguous columns
SELECT users.id, orders.total
FROM users
JOIN orders ON users.id = orders.user_id;
-- Good: clear aliases, prefixed columns
SELECT u.id,
o.total
FROM users AS u
JOIN orders AS o
ON u.id = o.user_id;
Avoid single-letter aliases like a and b unless the table name is already one word and obvious. u for users and o for orders work. a for accounts and b for billing do not.
5. Right-Align Keywords (Optional but Nice)
Some teams right-align the leading keywords (SELECT, FROM, WHERE) so they form a clean left edge for the column and table names. This is a stylistic preference, not a rule, but it looks great.
SELECT u.id,
u.name
FROM users AS u
WHERE u.active = 1
ORDER BY u.name;
I personally use left-aligned keywords because it is easier to maintain with automated formatters. Right-alignment requires manual effort or a formatter that supports it.
Common SQL Formatting Mistakes
I see the same mistakes over and over in code reviews. Here are the top ones and how to fix them.
Inconsistent Keyword Casing
Mixing select and SELECT in the same query is jarring. Pick one convention (uppercase is standard) and enforce it.
-- Bad
select id, name From users Where active = 1;
-- Good
SELECT id,
name
FROM users
WHERE active = 1;
Cramming Everything on One Line
If your query has a JOIN, a WHERE clause with multiple conditions, and a GROUP BY, it does not belong on one line. Break it up.
-- Bad
SELECT u.id, u.name, COUNT(o.id) AS cnt FROM users u JOIN orders o ON u.id = o.user_id WHERE u.active = 1 GROUP BY u.id, u.name HAVING cnt > 5 ORDER BY cnt DESC;
-- Good (see the formatted version in the previous section)
Missing AS for Aliases
Some databases let you omit AS for table aliases (users u instead of users AS u). Always include AS. It removes ambiguity about whether u is a column or an alias.
-- Ambiguous
FROM users u
-- Clear
FROM users AS u
Not Formatting Subqueries
Subqueries should be indented and formatted just like the outer query. A subquery jammed onto one line inside parentheses is a readability nightmare.
-- Bad
SELECT * FROM (SELECT id, name, email FROM users WHERE active = 1) AS active_users WHERE name LIKE 'A%';
-- Good
SELECT *
FROM (
SELECT id,
name,
email
FROM users
WHERE active = 1
) AS active_users
WHERE name LIKE 'A%';
Using a Free Online SQL Formatter
Formatting SQL by hand works for short queries, but when you are dealing with a 200-line analytics query with multiple subqueries and CTEs, doing it manually is a waste of time. A good SQL formatter does the work in seconds.
Our free online SQL formatter handles this for you. Paste your SQL, pick your dialect (MySQL, PostgreSQL, SQL Server, Oracle, etc.), and the tool returns properly formatted, indented, and capitalized SQL. It supports:
- Multiple SQL dialects including MySQL, PostgreSQL, T-SQL, PL/SQL, and more
- Configurable indentation (2 spaces, 4 spaces, or tabs)
- Keyword casing (uppercase, lowercase, or preserve original)
- Line width limits to wrap long SELECT lists
- Minification mode for squeezing SQL into a single line when needed
The tool runs entirely in your browser. No data is sent to a server, which matters when you are working with queries that contain sensitive table names or business logic.
SQL Formatting in Your Development Workflow
A formatter is most useful when it runs automatically. Here is how to integrate SQL formatting into your workflow so you never have to think about it.
IDE and Editor Integration
Most modern editors support SQL formatting plugins. For VS Code, the SQL Formatter extension by Dorin Botan is popular and supports multiple dialects. For JetBrains IDEs (DataGrip, IntelliJ), built-in SQL formatting is available under Code > Reformat Code.
-- VS Code: format SQL with Ctrl+Shift+I (or Cmd+Shift+I on Mac)
-- JetBrains: format with Ctrl+Alt+L (or Cmd+Alt+L on Mac)
Pre-Commit Hooks
If you use Git, add a pre-commit hook that formats SQL files before they are committed. This ensures no unformatted SQL ever reaches your repository. Tools like pre-commit and husky make this straightforward.
# .pre-commit-config.yaml example
repos:
- repo: https://github.com/sqlfluff/sqlfluff
rev: 3.0.0
hooks:
- id: sqlfluff-fix
args: [--dialect, postgres]
CI/CD Checks
Run a SQL linter like SQLFluff in your CI pipeline. It checks formatting, style, and even semantic issues like ambiguous column references. Failing the build on formatting violations forces everyone to comply.
SQL Formatting Quick Reference
Here is a summary you can print or share with your team:
| Rule | Do | Don't |
|---|---|---|
| Keywords | Uppercase (SELECT, FROM) |
Mix casing |
| Columns | One per line | Cram on one line |
| Indentation | 2 or 4 spaces, consistent | Tabs and spaces mixed |
| Aliases | Use AS, short names |
Omit AS, single letters |
| JOINs | ON on own line, indented |
Inline with JOIN |
| Subqueries | Indent and format like main query | One-line subqueries |
| Semicolons | Always terminate statements | Omit semicolons |
Related Formatting Tools
SQL is not the only code that benefits from consistent formatting. If you work with data formats alongside SQL, these free online tools can help:
- JSON Formatter — beautify and validate JSON data, useful for API payloads that pair with SQL queries
- XML Formatter — structure and validate XML documents
- Code Formatter — format JavaScript, CSS, HTML, and other languages
- JSON to YAML Converter — convert between JSON and YAML for configuration files
If you need to diff two versions of a formatted query, our Code Diff tool highlights changes line by line.
Wrapping Up
Consistent SQL formatting is a small habit with outsized benefits. It makes queries easier to read, review, and maintain. It reduces bugs by making structure visible. And it saves time during code reviews because reviewers spend their energy on logic, not parsing.
The rules are simple: uppercase keywords, one column per line, consistent indentation, use aliases with AS, and format subqueries. Run an automated formatter so you do not have to think about it. Start with our free SQL formatter tool to clean up your queries in seconds, and integrate a linter into your workflow so the formatting sticks.
Your future self, and everyone who reads your SQL after you, will thank you.