How to Format SQL for Readability
Learn the best practices for formatting SQL queries for readability. Covers uppercase keywords, indentation rules, aliases, and our free SQL Beautifier tool.
SQL code is read 10 times more often than it is written. When you’re debugging a production issue at 2 AM, deciphering a single-line SQL query with 15 JOINs is a recipe for disaster.
A consistent SQL style guide isn’t just about aesthetics. It’s about maintainability and error prevention.
The Golden Rules of SQL Formatting
1. Uppercase Keywords
SQL is case-insensitive, but capitalizing keywords makes them stand out from table and column names.
Bad:
select name from users where id = 1
Good:
SELECT name FROM users WHERE id = 1
2. New Lines for Major Clauses
Never write a query on one line unless it’s trivial. Start a new line for these clauses:
SELECTFROMJOINWHEREGROUP BYORDER BY
3. Indentation for Hierarchy
Indentation shows how parts of the query relate. Conditions in a WHERE clause or multiple tables in a JOIN should be indented.
SELECT
users.name,
orders.amount
FROM
users
INNER JOIN orders ON users.id = orders.user_id
WHERE
users.active = 1
AND orders.status = 'completed'
4. Trailing Commas
Put commas at the end of the line or at the start of the next line, depending on preference. Our formatter defaults to end-of-line commas, which is the most common standard.
Advanced Formatting Techniques
5. Aligning Column Names
For better readability, align column names vertically when selecting multiple columns.
SELECT
users.id,
users.name,
users.email,
orders.order_date,
orders.total_amount
FROM
users
INNER JOIN orders ON users.id = orders.user_id
6. Subquery Indentation
Subqueries should be indented further to show hierarchy.
SELECT
name,
(
SELECT COUNT(*)
FROM orders
WHERE orders.user_id = users.id
) AS total_orders
FROM
users
WHERE
active = 1
7. CTEs (Common Table Expressions)
Format WITH clauses with clear separation between each CTE.
WITH active_users AS (
SELECT id, name
FROM users
WHERE active = 1
),
recent_orders AS (
SELECT user_id, SUM(amount) AS total
FROM orders
WHERE order_date > NOW() - INTERVAL '30 days'
GROUP BY user_id
)
SELECT
au.name,
ro.total
FROM
active_users au
LEFT JOIN recent_orders ro ON au.id = ro.user_id
Common Mistakes to Avoid
Mixing Tabs and Spaces
Mixing tabs and spaces creates inconsistent indentation that looks fine in one editor but broken in another.
Bad:
SELECT name
→ FROM users -- This line uses a tab
WHERE id = 1 -- This line uses 4 spaces
Good: Pick one, with spaces being more portable, and stick with it.
Overusing Single-Line Queries
A query that fits on one line in your editor might be 200 characters wide and impossible to read on a laptop screen.
Bad:
SELECT users.name, users.email, orders.order_date, orders.total FROM users INNER JOIN orders ON users.id = orders.user_id WHERE users.active = 1 AND orders.status = 'completed' ORDER BY orders.order_date DESC
Good: Break it up as shown in the examples above.
Inconsistent Capitalization
Mixing SELECT and select in the same query looks unprofessional.
Bad:
SELECT name from USERS where ID = 1
Good: All keywords uppercase, all identifiers lowercase.
Not Using Table Aliases
Long table names clutter queries. Use short, meaningful aliases.
Bad:
SELECT
customer_orders.order_id,
customer_orders.total,
customer_information.customer_name
FROM
customer_orders
INNER JOIN customer_information
ON customer_orders.customer_id = customer_information.id
Good:
SELECT
co.order_id,
co.total,
ci.customer_name
FROM
customer_orders co
INNER JOIN customer_information ci ON co.customer_id = ci.id
Inconsistent Comma Placement
Some teams put commas at the start of lines, known as leading commas, while others put them at the end, known as trailing commas. Pick one standard.
Trailing commas, which are most common:
SELECT
name,
email,
phone
Leading commas, which make it easier to spot missing commas:
SELECT
name
, email
, phone
Both are fine. Just be consistent.
Pro Tips
Use a Style Guide
Different teams have different preferences. Document your standards in a style guide. Common choices:
Format Before Code Review
Run your SQL through a formatter before submitting a pull request. Reviewers shouldn’t have to decipher formatting. They should focus on logic.
Optimize for Readability, Not Compactness
Your database doesn’t care about whitespace. Humans do. A 50-line well-formatted query is easier to debug than a 10-line mess.
Use Comments for Complex Logic
Explain non-obvious business logic with comments.
SELECT
name,
email
FROM
users
WHERE
-- Exclude test accounts created before 2023
(created_at >= '2023-01-01' OR email NOT LIKE '%test%')
AND active = 1
Avoid SELECT *
Explicitly list columns. SELECT * breaks when table schemas change and makes queries harder to understand.
Bad:
SELECT * FROM users WHERE id = 1
Good:
SELECT id, name, email FROM users WHERE id = 1
Format Large INSERT Statements
For multi-row inserts, align values vertically.
INSERT INTO users (id, name, email) VALUES
(1, 'Alice', 'alice@example.com'),
(2, 'Bob', 'bob@example.com'),
(3, 'Carol', 'carol@example.com')
Real-World Scenarios
Debugging a Production Issue
At 2 AM, when your app is down and you’re staring at query logs, formatted SQL is the difference between fixing the issue in 5 minutes vs. 50 minutes.
Raw Log:
SELECT u.name,o.total FROM users u JOIN orders o ON u.id=o.user_id WHERE o.status='pending' AND u.region='US' ORDER BY o.created_at DESC LIMIT 100
Formatted:
SELECT
u.name,
o.total
FROM
users u
JOIN orders o ON u.id = o.user_id
WHERE
o.status = 'pending'
AND u.region = 'US'
ORDER BY
o.created_at DESC
LIMIT 100
Instantly obvious: This query might be slow because there’s no index on status + region.
Onboarding New Developers
When a new developer joins your team, well-formatted SQL helps them understand your data model faster.
Poorly formatted queries: You’ll ask yourself, “What tables are we joining? What’s the filter logic?”
Well formatted queries: You can see exactly what the query does.
Code Reviews
Formatted SQL makes diffs meaningful. Without formatting, code reviews devolve into “please add spaces around the WHERE clause” instead of catching actual bugs.
Frequently Asked Questions
Does formatting affect query performance?
No. The database engine ignores whitespace and capitalization. Formatting is purely for human readability.
Should I format SQL in stored procedures?
Absolutely. Stored procedures are code and should follow the same standards as your application code.
What about ORMs like Prisma or TypeORM?
ORMs generate SQL automatically, so you don’t format it manually. However, for raw queries or debugging, formatting still matters.
Can I automate formatting in my CI/CD pipeline?
Yes. Tools like sqlfluff (Python) or sql-formatter (JavaScript) can auto-format SQL in your build pipeline, similar to Prettier for JavaScript.
Is there a standard SQL formatting tool?
There’s no official standard, but popular tools include these options: sqlfluff for opinionated formatting with linting, sql-formatter for lightweight JavaScript formatting, and pg_format specifically for PostgreSQL.
Why Use an Automated Formatter?
Manual formatting is tedious. It’s easy to miss a space or forget to capitalize a JOIN.
Our Free SQL Formatter enforces these rules automatically. Just paste your raw query, and it will apply standard indentation and casing instantly, turning spaghetti code into professional SQL. It handles complex queries with subqueries, CTEs, and multiple joins, ensuring your code is always review-ready.
Related Calculators
Related Articles
- Color Theory Basics for Web Design
Master color theory for web design including the color wheel, complementary palettes, WCAG contrast requirements, and color psychology to create effective interfaces.
- How to Minify CSS for Faster Websites
Learn what CSS minification does, why it speeds up your website, what it removes from your stylesheets, and best practices for minifying CSS in production.
- Cron Job Examples for Common Tasks (Copy-Paste Ready)
Practical cron job examples with clear explanations. Copy-paste ready crontab schedules for backups, reports, cleanup, monitoring, and automation tasks.
- Common JSON Syntax Errors and How to Fix Them
Fix JSON syntax errors fast with this developer guide. Learn the top 5 JSON parsing errors, before/after examples, and debugging techniques to validate JSON instantly.
Share this article
Have suggestions for this article?