SQL Formatting Best Practices Every Developer Should Know

Writing SQL is easy.

Maintaining SQL six months later is not.

Most developers have experienced opening an old query, staring at a wall of nested JOINs, subqueries, and conditions, and wondering what exactly the original author was trying to accomplish. Sometimes that author was yourself.

The reality is that SQL formatting is not about aesthetics. It is about readability, maintainability, debugging speed, and collaboration. A well-formatted query helps developers understand business logic faster, review pull requests more efficiently, and reduce mistakes when modifying production code.

In this guide, we'll walk through practical SQL formatting best practices used by professional development teams, explain why they matter, and show real examples that can immediately improve the quality of your SQL code.


Why SQL Formatting Matters

Databases don't care how your SQL looks.

People do.

Consider this query:

SELECT u.id,u.name,o.order_id,o.total,p.method FROM users u LEFT JOIN orders o ON u.id=o.user_id LEFT JOIN payments p ON o.order_id=p.order_id WHERE u.status='active' AND o.total>1000 ORDER BY o.created_at DESC;

Technically correct.

Practically painful.

Now compare it to:

SELECT
    u.id,
    u.name,
    o.order_id,
    o.total,
    p.method
FROM users u
LEFT JOIN orders o
    ON u.id = o.user_id
LEFT JOIN payments p
    ON o.order_id = p.order_id
WHERE
    u.status = 'active'
    AND o.total > 1000
ORDER BY o.created_at DESC;

The second version allows developers to:

  • Understand intent quickly
  • Identify join conditions immediately
  • Review changes more effectively
  • Debug logic faster

Formatting is essentially documentation without writing additional documentation.


Use Consistent Keyword Casing

One of the longest-running SQL debates involves keyword capitalization.

You'll find developers who prefer:

select *
from users
where active = true;

And others who prefer:

SELECT *
FROM users
WHERE active = TRUE;

After working across multiple teams, I've found that uppercase SQL keywords generally improve readability, especially in larger queries.

Keywords visually separate SQL syntax from business data.

For example:

SELECT
    customer_name,
    total_amount
FROM orders
WHERE status = 'completed';

The important part is consistency.

Mixing styles becomes confusing:

Select
    customer_name
FROM Orders
where status = 'completed';

Pick one style and apply it everywhere.


Put Each Selected Column on Its Own Line

A common mistake is cramming all selected fields into a single line.

Avoid:

SELECT id, name, email, created_at, updated_at
FROM users;

Instead:

SELECT
    id,
    name,
    email,
    created_at,
    updated_at
FROM users;

This approach provides several advantages:

  • Easier Git diffs
  • Cleaner code reviews
  • Faster field additions and removals

Imagine adding a single column.

The diff becomes obvious:

SELECT
    id,
    name,
    email,
    phone_number,
    created_at
FROM users;

Reviewers instantly see what changed.


Align JOIN Clauses Clearly

JOIN logic is often where SQL becomes difficult to read.

Poor formatting:

SELECT *
FROM users u LEFT JOIN orders o ON u.id=o.user_id INNER JOIN products p ON o.product_id=p.id;

Better formatting:

SELECT *
FROM users u
LEFT JOIN orders o
    ON u.id = o.user_id
INNER JOIN products p
    ON o.product_id = p.id;

Notice how each JOIN becomes a separate logical block.

When debugging incorrect results, this structure makes relationship issues much easier to identify.


Format WHERE Conditions Vertically

As conditions grow, readability drops quickly.

Instead of:

WHERE status = 'active' AND country = 'US' AND total_amount > 1000 AND deleted_at IS NULL

Use:

WHERE
    status = 'active'
    AND country = 'US'
    AND total_amount > 1000
    AND deleted_at IS NULL

Benefits include:

  • Faster scanning
  • Easier modifications
  • Cleaner diffs

When business requirements change, developers can edit individual conditions without affecting the entire clause.


Keep Nested Queries Readable

Subqueries are often unavoidable.

The mistake is treating them as a single block.

Bad:

SELECT * FROM users WHERE id IN (SELECT user_id FROM orders WHERE total > 1000);

Better:

SELECT *
FROM users
WHERE id IN (
    SELECT user_id
    FROM orders
    WHERE total > 1000
);

The indentation clearly communicates query hierarchy.

Developers immediately understand which conditions belong to which query.


Use Meaningful Table Aliases

Many developers shorten aliases excessively:

SELECT *
FROM users a
JOIN orders b
    ON a.id = b.user_id;

This becomes confusing in large queries.

Prefer descriptive aliases:

SELECT *
FROM users user_tbl
JOIN orders order_tbl
    ON user_tbl.id = order_tbl.user_id;

Or concise but meaningful aliases:

SELECT *
FROM users u
JOIN orders o
    ON u.id = o.user_id;

The goal is clarity, not brevity.


Organize Complex CTEs Properly

Common Table Expressions (CTEs) can dramatically improve readability when formatted correctly.

Poor example:

WITH recent_orders AS (SELECT * FROM orders WHERE created_at > CURRENT_DATE - INTERVAL '30 days'), high_value_orders AS (SELECT * FROM recent_orders WHERE total > 1000) SELECT * FROM high_value_orders;

Readable version:

WITH recent_orders AS (
    SELECT *
    FROM orders
    WHERE created_at > CURRENT_DATE - INTERVAL '30 days'
),

high_value_orders AS (
    SELECT *
    FROM recent_orders
    WHERE total > 1000
)

SELECT *
FROM high_value_orders;

Each CTE becomes a self-contained logical unit.


Standardize ORDER BY and GROUP BY Sections

Developers often overlook these clauses.

Instead of:

GROUP BY country, city, category
ORDER BY total_sales DESC;

Consider:

GROUP BY
    country,
    city,
    category

ORDER BY
    total_sales DESC;

This style becomes increasingly useful as grouping complexity grows.


Let Tools Enforce Consistency

Even experienced developers struggle to maintain formatting consistency manually.

This is where SQL formatters become valuable.

Popular options include:

  • SQLFluff
  • Prettier SQL
  • pgFormatter
  • DataGrip Formatter

A practical workflow looks like:

  1. Write SQL naturally.
  2. Format automatically before commit.
  3. Run linting checks in CI.
  4. Review logic rather than whitespace.

If you're looking for a formatter, check out:

Automating formatting eliminates style discussions and keeps teams focused on solving business problems.


Common Formatting Mistakes That Hurt Readability

Overusing SELECT *

SELECT *
FROM orders;

Prefer:

SELECT
    order_id,
    customer_id,
    total_amount
FROM orders;

Explicit columns improve maintainability.


Mixing Indentation Styles

Avoid:

SELECT
  id,
        name,
    email
FROM users;

Choose a consistent indentation rule and follow it everywhere.


Writing Everything on One Line

One-line queries are difficult to review and nearly impossible to maintain.

If a query spans multiple logical operations, its formatting should reflect that structure.


Real-World Team SQL Style Guide

Many engineering teams eventually settle on these rules:

  • SQL keywords uppercase
  • One column per line
  • One JOIN per line
  • Multi-line WHERE clauses
  • Four-space indentation
  • Explicit column names
  • CTEs for complex transformations
  • Automatic formatting before merge

The exact rules matter less than applying them consistently.

Consistency reduces cognitive overhead across the entire codebase.


Frequently Asked Questions

What is the most important SQL formatting rule?

Consistency.

Even a style you personally dislike is easier to maintain than a codebase with five competing styles.


Should SQL keywords always be uppercase?

Not necessarily.

Uppercase keywords improve readability for many developers, but consistent usage is more important than the chosen casing style.


Does SQL formatting affect performance?

No.

Formatting only changes how queries look. The database optimizer ignores whitespace and indentation.


How should I format long WHERE clauses?

Place each condition on its own line and align logical operators vertically.

Example:

WHERE
    status = 'active'
    AND region = 'US'
    AND total_sales > 1000

What is the best SQL formatter?

Popular choices include:

  • SQLFluff
  • Prettier SQL
  • pgFormatter
  • DataGrip Formatter

The best option depends on your database platform and development workflow.


Should I use tabs or spaces for SQL?

Most teams prefer spaces because they render consistently across editors and code review platforms.

Four spaces remains the most common choice.


Final Thoughts

Good SQL formatting is one of the highest-leverage habits a developer can adopt.

It doesn't make queries run faster, but it makes teams work faster. It reduces misunderstandings during code reviews, shortens debugging sessions, and makes complex business logic significantly easier to maintain.

The best formatting style is ultimately the one your team agrees on and enforces automatically. Once formatting becomes part of your workflow, you'll spend less time arguing about code appearance and more time improving query performance and application behavior.

If you're cleaning up legacy queries or standardizing SQL across a project, try the SQL Formatter on DevFormatters. It's a simple way to transform difficult-to-read queries into structured, maintainable SQL that developers can understand at a glance.