SQL doesn't enforce any whitespace rules — the engine treats a one-liner and a 40-line query exactly the same. But your teammates and future self will thank you for the 40-line version.
Here's a concise SQL formatting guide that works across MySQL, PostgreSQL, SQLite, and SQL Server.
Core rules
1. Uppercase keywords, lowercase names
This single convention does the most work:
``sql
SELECT u.name, o.total
FROM users u
JOIN orders o ON u.id = o.user_id
WHERE o.status = 'completed'
ORDER BY o.total DESC;
`
SQL keywords stand out visually; your table and column names don't compete for attention.
2. One clause per line
Each major clause (SELECT, FROM, WHERE, JOIN, GROUP BY, HAVING, ORDER BY, LIMIT) starts on a new line at the left margin.
3. Indent continuation items
Items in a SELECT list or multiple WHERE conditions are indented one level:
<code>sql
<p>SELECT</p>
<p>u.name,</p>
<p>u.email,</p>
<p>o.total,</p>
<p>o.created_at</p>
<p>FROM users u</p>
<p>WHERE</p>
<p>o.status = 'completed'</p>
<p>AND o.created_at > '2024-01-01';</p>
</code>
4. Alias everything consistently
If you alias users as u, use u.column everywhere in that query. Mixing users.id and u.name in the same query causes unnecessary cognitive load.
5. Use CTEs for complex queries
Named CTEs (WITH ... AS (...)) replace nested subqueries with human-readable steps:
<code>sql
<p>WITH active_users AS (</p>
<p>SELECT id, name</p>
<p>FROM users</p>
<p>WHERE last_login > NOW() - INTERVAL '30 days'</p>
<p>),</p>
<p>their_orders AS (</p>
<p>SELECT user_id, COUNT(*) AS order_count</p>
<p>FROM orders</p>
<p>GROUP BY user_id</p>
<p>)</p>
<p>SELECT u.name, t.order_count</p>
<p>FROM active_users u</p>
<p>JOIN their_orders t ON u.id = t.user_id</p>
<p>ORDER BY t.order_count DESC;</p>
</code>
Each CTE reads like a named step. The final SELECT is obvious.
Formatting inherited SQL
When you receive SQL from an ORM, export tool, or legacy codebase, it often arrives as one long string. The SQL Formatter on SnappyTools takes minified or unformatted SQL and outputs properly indented, keyword-uppercased SQL for MySQL, PostgreSQL, SQLite, or T-SQL. Paste in one query or a full migration file — it runs in your browser with no upload.
What to avoid
- Mixed case keywords (Select
, WHERE, from) - Comma-first style (debated — choose one and stick to it)
- Deeply nested subqueries when a CTE would be clearer
- Aliases that are cryptic abbreviations (u2
, x, t3`)
SQL style is team infrastructure. Establish a convention in your team's contributing guide, enforce it with a formatter in CI, and you'll spend less time decoding queries and more time understanding what they do.