FormatList
SQL

SQL Formatting Best Practices

Clean, well-formatted SQL is a hallmark of professional database development. Whether you are writing ad-hoc queries for analysis, building complex reporting views, or maintaining an application's data access layer, consistent formatting improves readability, reduces errors, and makes collaboration smoother. This guide covers the essential formatting rules, common styles, and tools that help you write SQL that your team will thank you for.

Why SQL Formatting Matters

SQL queries are read far more often than they are written. A well-formatted query communicates its structure and intent at a glance. When every JOIN is aligned, every subquery is indented, and every clause starts on its own line, anyone on your team can understand the query's logic without mentally parsing a wall of text.

Formatting also helps catch bugs. Misplaced commas, missing parentheses, and ambiguous WHERE clause bindings are much easier to spot in a cleanly formatted query. In code reviews, consistent formatting means reviewers focus on query logic rather than arguing over indentation or keyword casing.

Finally, formatted SQL is more maintainable. When you need to add a column, change a JOIN condition, or refactor a subquery, a well-structured query makes the edit obvious and reduces the chance of introducing errors.

Key Formatting Rules

The following rules form the foundation of most SQL style guides. Apply them consistently across all your queries.

Uppercase SQL Keywords

Write all SQL keywords in uppercase: SELECT, FROM, WHERE, JOIN, ON, GROUP BY, ORDER BY, HAVING, and LIMIT. This visually separates the query structure from your schema objects (table names, column names, aliases), which should be lowercase.

-- Good: uppercase keywords, lowercase identifiers
SELECT u.name, u.email, o.total
FROM users u
JOIN orders o ON o.user_id = u.id
WHERE u.active = true
ORDER BY o.total DESC;

Line Breaks After Major Clauses

Each major clause should start on a new line. This makes the logical structure of the query immediately visible:

-- Good: each clause on its own line
SELECT
  p.name,
  p.price,
  c.name AS category_name
FROM
  products p
  JOIN categories c ON c.id = p.category_id
WHERE
  p.active = true
  AND p.price > 0
ORDER BY
  p.name ASC;

Consistent Indentation

Use 2 or 4 spaces for indentation (pick one and stick with it). Indent the SELECT column list, JOIN conditions, WHERE predicates, and subqueries to show their hierarchical relationship:

-- Good: indentation shows query structure
SELECT
    u.id,
    u.name,
    u.email,
    (
        SELECT COUNT(*)
        FROM orders o
        WHERE o.user_id = u.id
    ) AS order_count
FROM
    users u
WHERE
    u.created_at >= '2026-01-01'
    AND u.status IN ('active', 'pending');

Aligned Columns in SELECT

Align the SELECT column list with consistent indentation. Some developers prefer one column per line (recommended for queries with many columns), while others group related columns together:

-- One column per line (recommended)
SELECT
    order_id,
    customer_id,
    order_date,
    total_amount,
    shipping_address,
    order_status
FROM
    orders
WHERE
    order_date >= '2026-01-01';

JOINs and Table Aliases

Always use explicit JOIN syntax (not comma-separated FROM clauses). Use short, meaningful table aliases and qualify all column references with the alias:

-- Good: explicit JOINs, aliased columns
SELECT
    o.id AS order_id,
    c.name AS customer_name,
    o.total
FROM
    orders o
    INNER JOIN customers c ON c.id = o.customer_id
    LEFT JOIN payments p ON p.order_id = o.id
WHERE
    o.status IN ('shipped', 'delivered');

Before and After Examples

Seeing the difference that formatting makes is the best way to appreciate its value. Here is the same query, poorly formatted and then properly formatted.

Before: Poorly Formatted

SELECT u.name,u.email,o.total,
p.name as product_name FROM users u join orders o on
u.id=o.user_id join order_items oi on oi.order_id=o.id
join products p on p.id=oi.product_id where o.status='completed'
and o.total>50 group by u.name,u.email,o.total,p.name
having count(*)>1 order by o.total desc;

This query is a wall of text. It is difficult to see where each clause begins, which columns are being selected, how the tables are joined, and what the filtering conditions are. A missing comma or misplaced condition would be easy to overlook.

After: Well-Formatted

SELECT
    u.name,
    u.email,
    o.total,
    p.name AS product_name
FROM
    users u
    JOIN orders o ON o.user_id = u.id
    JOIN order_items oi ON oi.order_id = o.id
    JOIN products p ON p.id = oi.product_id
WHERE
    o.status = 'completed'
    AND o.total > 50
GROUP BY
    u.name,
    u.email,
    o.total,
    p.name
HAVING
    COUNT(*) > 1
ORDER BY
    o.total DESC;

The formatted version reveals the query's structure immediately. You can see the four JOINed tables, the two WHERE conditions, the GROUP BY columns, the HAVING filter, and the sort order — all at a glance. This query is much easier to review, debug, and modify.

Common Formatting Styles

There is no single official SQL formatting standard. Different teams and organizations adopt different conventions. Here are the most common styles:

Comma-First Style

Commas are placed at the beginning of each line, making it easy to comment out or reorder columns. Popular in the PostgreSQL community:

SELECT
    user_id
    , user_name
    , email
    , created_at
FROM users
WHERE active = true;

Comma-Last Style

Commas are placed at the end of each line. This is the most common style and the default in most SQL editors and formatters:

SELECT
    user_id,
    user_name,
    email,
    created_at
FROM users
WHERE active = true;

Compact Style

For short queries, some developers prefer a more compact format that keeps everything on fewer lines:

SELECT u.name, u.email, COUNT(o.id) AS order_count
FROM users u
JOIN orders o ON o.user_id = u.id
WHERE u.active = true
GROUP BY u.name, u.email
HAVING COUNT(o.id) > 5;

The most important rule is to choose one style and apply it consistently across your entire codebase. Document your style in a project README or use a formatter tool to enforce it automatically.

SQL Formatting Tools

Automated tools can handle SQL formatting for you, eliminating style debates and ensuring consistency. Here are some popular options:

  • FormatList Tools: Use the SQL Formatter to pretty-print queries in your browser, the SQL IN Clause Generator for list values, and the JSON Formatter for JSON columns in SQL.
  • sqlformat.org: A popular online SQL formatter that supports multiple styles and dialect-specific formatting rules.
  • VS Code Extensions: Extensions like "SQL Formatter" and "Poor Man's T-SQL Formatter" provide on-save formatting for SQL files.
  • Prettier with SQL Plugin: The Prettier code formatter has a SQL plugin that supports most major dialects and integrates with CI/CD pipelines.
  • JetBrains IDEs: DataGrip and IntelliJ IDEA have built-in SQL formatting that can be configured for your team's style guide.

Use Cases

  • Code Reviews: Well-formatted SQL makes code reviews faster and more effective. Reviewers can immediately understand the query logic instead of deciphering formatting.
  • Shared Queries: When queries are shared across teams — in documentation, runbooks, or Slack — clean formatting ensures they are readable by everyone.
  • Documentation and Runbooks: SQL examples in documentation should follow consistent formatting so readers can easily adapt them to their own use cases.
  • Data Analysis Notebooks: SQL queries in Jupyter notebooks, Hex, or Mode Analytics benefit from good formatting that makes them presentable in reports and dashboards.
  • Open Source Projects: Consistent SQL formatting signals professionalism and makes it easier for contributors to understand and modify database layers.

Frequently Asked Questions

Why does SQL formatting matter?

SQL formatting matters because well-formatted queries are easier to read, debug, and maintain. They reduce errors during code reviews, make it easier to spot syntax mistakes, and improve team collaboration by establishing a consistent style that everyone can understand.

Should I use uppercase or lowercase for SQL keywords?

Most SQL style guides recommend uppercase for SQL keywords (SELECT, FROM, WHERE, JOIN) and lowercase for column and table names. This visual distinction makes it easy to separate language keywords from your schema objects at a glance.

How should I indent my SQL queries?

Use 2 or 4 spaces for indentation — never tabs. Indent subqueries, JOIN conditions, and column lists to show the query's hierarchical structure visually. Each major clause (FROM, WHERE, JOIN) should start at the same indentation level.

What is the best SQL formatting style?

There is no single best style, but the most popular approaches are comma-first (commas at the start of lines), comma-last (commas at the end), and compact style (everything on fewer lines). Consistency matters more than which specific style you choose. Pick one and document it for your team.

Are there automated SQL formatting tools?

Yes, there are many automated SQL formatters. FormatList's Newline to Comma tool helps format lists within your queries. VS Code has multiple SQL formatter extensions. Prettier has a SQL plugin. JetBrains IDEs have built-in formatting. Choose one that integrates with your workflow and enforce it with a CI check.

Related Tools

Related Articles

Format Your SQL Lists Instantly

Use FormatList's free Newline to Comma tool to format lists and values within your SQL queries. Clean, consistent formatting in one click.