SQL Query Formatting Guide: Readable Patterns for Joins, CTEs, and Nested Queries
SQLSQL formatterdatabasesquery reviewcode styledeveloper productivity

SQL Query Formatting Guide: Readable Patterns for Joins, CTEs, and Nested Queries

CCodeGuru Editorial Team
2026-11-27
7 min read

Learn practical SQL formatting patterns for joins, CTEs, nested queries, and window functions, with dialect checks and a review checklist.

A readable SQL query is easier to review, debug, and safely change. This guide shows how to format joins, common table expressions, nested queries, and window functions, then gives you a reusable checklist for reviewing complex SQL across PostgreSQL, MySQL, SQL Server, and SQLite.

Overview

SQL formatting does not change query logic, but it changes how quickly a person can understand that logic. Consistent indentation makes nesting visible, aligned clauses make missing conditions easier to spot, and deliberate line breaks separate business rules from implementation details. A good SQL style guide should support review rather than enforce decoration for its own sake.

Start with a predictable top-level structure. Put each major clause on its own line, place selected columns on separate lines, and indent expressions that belong to a clause. For example, this compressed query is difficult to scan:

SELECT o.id,o.created_at,c.name,SUM(oi.quantity*oi.unit_price) AS total FROM orders o JOIN customers c ON c.id=o.customer_id JOIN order_items oi ON oi.order_id=o.id WHERE o.status='paid' GROUP BY o.id,o.created_at,c.name HAVING SUM(oi.quantity*oi.unit_price)>100 ORDER BY o.created_at DESC;

The same query becomes easier to inspect when its relationships and filtering stages are visible:

SELECT
    o.id,
    o.created_at,
    c.name AS customer_name,
    SUM(oi.quantity * oi.unit_price) AS order_total
FROM orders AS o
JOIN customers AS c
    ON c.id = o.customer_id
JOIN order_items AS oi
    ON oi.order_id = o.id
WHERE o.status = 'paid'
GROUP BY
    o.id,
    o.created_at,
    c.name
HAVING SUM(oi.quantity * oi.unit_price) > 100
ORDER BY o.created_at DESC;

The formatting exposes useful review points: which table supplies each column, where the join keys are defined, and whether the aggregate filter belongs in HAVING rather than WHERE. Formatting is therefore part of a practical debugging workflow, alongside execution plans, test data, and query results.

Checklist by scenario

Formatting joins

  • Put each table source on its own line.
  • Use short, meaningful aliases consistently; avoid changing an alias halfway through a query.
  • Place the ON condition beneath the related JOIN.
  • Keep additional join predicates on separate indented lines.
  • Make the join type explicit when it matters. Use LEFT JOIN instead of relying on a reader to infer optionality.
FROM accounts AS a
LEFT JOIN subscriptions AS s
    ON s.account_id = a.id
    AND s.cancelled_at IS NULL
JOIN account_users AS au
    ON au.account_id = a.id
    AND au.is_primary = TRUE

Separating join predicates is especially useful during debugging. A condition accidentally moved from ON to WHERE can change the behavior of an outer join, and clear indentation makes that change more apparent.

Formatting common table expressions

Use a CTE when it gives a meaningful intermediate result a name or separates stages that would otherwise be difficult to reason about. Put each CTE on its own block and align the final query after the closing parenthesis.

WITH paid_orders AS (
    SELECT
        o.id AS order_id,
        o.customer_id,
        o.created_at,
        SUM(oi.quantity * oi.unit_price) AS order_total
    FROM orders AS o
    JOIN order_items AS oi
        ON oi.order_id = o.id
    WHERE o.status = 'paid'
    GROUP BY
        o.id,
        o.customer_id,
        o.created_at
),
customer_totals AS (
    SELECT
        customer_id,
        COUNT(*) AS order_count,
        SUM(order_total) AS lifetime_value
    FROM paid_orders
    GROUP BY customer_id
)
SELECT
    customer_id,
    order_count,
    lifetime_value
FROM customer_totals
WHERE lifetime_value > 1000
ORDER BY lifetime_value DESC;

Name CTEs after what they represent, not how they are implemented. Names such as paid_orders and customer_totals communicate intent more clearly than step_one and step_two.

Formatting nested queries

Indent a nested query one level and give its output an alias where the SQL dialect requires or benefits from one. Keep the inner query focused on one task, such as ranking rows or limiting a source set.

SELECT
    ranked.customer_id,
    ranked.order_id,
    ranked.order_total
FROM (
    SELECT
        o.customer_id,
        o.id AS order_id,
        SUM(oi.quantity * oi.unit_price) AS order_total,
        ROW_NUMBER() OVER (
            PARTITION BY o.customer_id
            ORDER BY o.created_at DESC
        ) AS order_rank
    FROM orders AS o
    JOIN order_items AS oi
        ON oi.order_id = o.id
    GROUP BY
        o.customer_id,
        o.id,
        o.created_at
) AS ranked
WHERE ranked.order_rank = 1;

If a nested query becomes several screens long, consider a CTE. The choice is not purely stylistic: a named stage is often easier to test independently and explain during review.

Formatting window functions

Break a window expression across lines when it contains a partition, ordering rule, or frame. The ordering inside the window is separate from the final result ordering, so formatting should make both visible.

SELECT
    customer_id,
    order_id,
    created_at,
    SUM(order_total) OVER (
        PARTITION BY customer_id
        ORDER BY created_at
        ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
    ) AS running_total
FROM customer_orders
ORDER BY
    customer_id,
    created_at;

What to double-check

Dialect differences

An online SQL formatter can improve layout without understanding every feature of your database. Confirm the formatter's dialect setting before using it on production queries. PostgreSQL, MySQL, SQL Server, and SQLite differ in areas such as identifier quoting, pagination syntax, boolean expressions, date functions, casts, and support for particular window or JSON features.

  • PostgreSQL: double quotes are used for case-sensitive identifiers, while single quotes represent strings. PostgreSQL also supports several casting styles, so preserve the style your team uses.
  • MySQL: backticks are commonly used for identifiers, and functions or pagination patterns may differ from PostgreSQL and SQL Server.
  • SQL Server: bracketed identifiers, TOP, and OFFSET ... FETCH are dialect-specific patterns that generic formatters may not handle as expected.
  • SQLite: its compact feature set and type behavior differ from server databases. Test formatted queries against the SQLite version and application library you actually use.

Formatting should never be treated as validation. After reformatting, run the query in a safe environment and compare results, row counts, and execution behavior. For a broader review workflow, see the SQL query formatting and review guide.

Formatter choice

Use an online SQL formatter when you need a quick, disposable layout pass or are inspecting a small query. Before pasting SQL into any online developer tool, remove credentials, tokens, personal data, and proprietary business logic unless your organization's rules explicitly allow that workflow.

An editor extension or command-line formatter is usually a better fit for a repository. It can be applied consistently, reviewed in pull requests, and integrated into a repeatable workflow. Whichever option you choose, configure the SQL dialect, indentation width, keyword casing, comma style, alias behavior, and line-length preferences. A formatter that produces different output on every machine creates more review noise than it removes.

Logic after layout changes

Compare the formatted query with the original before committing it. Check joins, parentheses, quoted strings, comments, operator precedence, and any vendor-specific syntax. Then compare representative results. Formatting should preserve behavior, but the review step protects against accidental edits made while cleaning up a query.

Common mistakes

  • Using SELECT * in reviewed or shared queries: Explicit columns document the intended shape and reduce surprises when a table changes.
  • Hiding join logic on one long line: Put each meaningful predicate where a reviewer can see whether it belongs to the relationship or the filter.
  • Overusing CTEs: CTEs can clarify stages, but a separate block for every simple expression may make the query harder to follow. Add names where they improve understanding.
  • Mixing casing and comma styles: Choose a convention, such as uppercase keywords and leading or trailing commas, and apply it consistently.
  • Confusing formatting with optimization: A neatly arranged query can still scan too many rows, use an unsuitable index, or produce duplicate records. Use execution plans and measured tests for performance decisions.
  • Ignoring comments: Explain why a non-obvious workaround, filter, or business rule exists. Do not use comments to restate obvious SQL.
  • Formatting without testing: A formatter may preserve text while your manual cleanup changes a condition. Validate results after edits.

When to revisit

Return to this checklist whenever you inherit a complex query, prepare SQL for review, refactor reporting logic, or change database tooling. Revisit the team convention when a project adds a new database dialect, adopts an editor extension, changes its CI workflow, or upgrades a formatter. Formatter behavior and dialect support can change, so check the tool configuration after upgrades rather than assuming the previous output remains identical.

Before committing a reformatted query, use this short action list:

  1. Identify the SQL dialect and configure the formatter accordingly.
  2. Format top-level clauses, joins, CTEs, nested queries, and window expressions as separate readable blocks.
  3. Review aliases, join conditions, grouping columns, filters, and parentheses manually.
  4. Compare the output with the original query and inspect representative results.
  5. Run an execution plan or targeted performance test when the query is used on substantial data.
  6. Save the agreed style in the repository's formatter configuration or contribution documentation.

Readable SQL is a shared maintenance tool. When formatting exposes the query's stages and relationships, future reviewers can spend less time reconstructing intent and more time checking whether the intent is correct.

Related Topics

#SQL#SQL formatter#databases#query review#code style#developer productivity
C

CodeGuru Editorial Team

Developer Resources Editor

Senior editor and content strategist. Writing about technology, design, and the future of digital media. Follow along for deep dives into the industry's moving parts.