<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Outfit:wght@600;700;800&family=Plus+Jakarta+Sans:wght@400;500;600;700&display=swap">
πŸ’» Developer guide

SQL Formatting Style Guide: Readable Queries, CTEs, JOINs and When to Minify

Practical SQL style rules: keyword case, comma placement, JOIN and CTE layout, comments, when to minify, and the syntax errors a quick validator catches.

πŸ“… Published 2026-11-15⏱️ 5 min readπŸ› οΈ 4 free tools

SQL is read far more often than it is written. A query gets reviewed in a pull request, pasted into an incident channel, opened again six months later when a report looks wrong, and copied into a migration. Every one of those readers is slowed down by a query that arrives as a single 600-character line.

There is no official SQL style, but most teams converge on the same handful of conventions. This guide sets out those conventions with the reasoning behind each one, explains when it makes sense to strip formatting back out, and lists the syntax mistakes that formatting and validation catch before the database does.

The core rules most teams agree on

The goal of formatting is to make the structure of a query visible: which tables are involved, how they connect, what is filtered and what is returned. These rules do most of that work.

  • Put each major clause on its own line: SELECT, FROM, JOIN, WHERE, GROUP BY, HAVING, ORDER BY, LIMIT.
  • Write keywords in uppercase and identifiers in lowercase. Syntax highlighting makes this less essential than it was, but uppercase keywords still help in logs, tickets and plain-text diffs.
  • Put one selected column per line once there are more than three or four.
  • Indent conditions under WHERE and put AND or OR at the start of each line, so you can comment out a single condition and scan the logic down the left edge.
  • Use meaningful table aliases (o for orders, c for customers), not a, b, c, and always qualify columns with the alias when more than one table is involved.
  • Name columns and tables in snake_case, and avoid reserved words such as user, order and group as identifiers.

Leading or trailing commas

This is the most argued-about rule, and both sides have a point. Trailing commas read like normal prose. Leading commas make it obvious when a comma is missing, and let you comment out any column except the first without touching the line above.

Pick one per codebase and let your formatter enforce it. Mixed styles in the same file are worse than either choice. Leading commas are common in analytics and dbt projects; trailing commas are more common in application code and ORM output.

-- Trailing commas
SELECT
  o.id,
  o.created_at,
  c.email
FROM orders AS o
JOIN customers AS c
  ON c.id = o.customer_id
WHERE o.status = 'paid'
  AND o.created_at >= DATE '2026-01-01'
ORDER BY o.created_at DESC;

-- Leading commas
SELECT
    o.id
  , o.created_at
  , c.email
FROM orders AS o

Laying out JOINs, subqueries and CTEs

Write the JOIN type explicitly (INNER JOIN, LEFT JOIN) and put the ON condition on its own indented line. When a join has several conditions, give each its own line starting with AND. Never join with commas in the FROM clause and conditions in WHERE; it hides which conditions are join keys and which are filters, and it is how accidental cross joins happen.

For anything longer than a screen, prefer common table expressions (WITH ... AS) over nested subqueries. Each CTE gets a descriptive name and can be read top to bottom, like steps in a function. Separate CTEs with a blank line and keep the final SELECT short.

Subqueries are still fine for small, local things such as WHERE id IN (SELECT ...). Indent their contents one level deeper than the surrounding clause and put the closing bracket on its own line.

WITH paid_orders AS (
  SELECT customer_id, SUM(total) AS revenue
  FROM orders
  WHERE status = 'paid'
  GROUP BY customer_id
),

top_customers AS (
  SELECT customer_id, revenue
  FROM paid_orders
  WHERE revenue > 10000
)

SELECT c.email, t.revenue
FROM top_customers AS t
JOIN customers AS c
  ON c.id = t.customer_id
ORDER BY t.revenue DESC;

When to minify SQL

Formatted SQL belongs in source files, migrations, documentation and code review. A single-line version is useful in a narrower set of places: a SQL string embedded in a JSON or YAML config value, a shell command, a log line that must stay on one row for grep, or a URL parameter in an internal tool.

Minifying does not make a query faster. Databases parse whitespace in microseconds, and prepared statements are parsed once anyway. Treat minification purely as a transport format and keep the formatted version as the source of truth.

Be careful with comments. A -- line comment swallows everything after it on the same line, so naive line-joining breaks the query. Removing comments also removes optimizer hints written as comments, such as Oracle and MySQL /*+ ... */ hints, which changes the execution plan.

Syntax errors formatting and validation catch

Database error messages often point to where the parser gave up rather than where the mistake is, so "syntax error at or near FROM" can mean almost anything above that line. Formatting the query first makes most of these visible, and a quick lint pass catches the rest:

  • A trailing comma before FROM, left behind after deleting the last column.
  • Unbalanced brackets in nested function calls or subqueries.
  • An unclosed single quote, which turns the rest of the query into one long string. Apostrophes inside values must be doubled: ’O’’Brien’.
  • Double quotes used for string values. In standard SQL, PostgreSQL and SQLite, "text" is an identifier, not a string. MySQL accepts it by default, which is why queries break when moved between databases.
  • Missing commas between columns, which most databases silently read as a column alias (SELECT name email returns name labelled as email).
  • A HAVING clause with no GROUP BY, or a non-aggregated column missing from GROUP BY in strict modes.

Dialect differences to keep in mind

A style guide should not depend on one database, but a few syntax differences affect how queries look. Row limits are LIMIT n in PostgreSQL, MySQL and SQLite, TOP n or OFFSET ... FETCH in SQL Server, and FETCH FIRST n ROWS ONLY in standard SQL and Oracle. Identifiers are quoted with double quotes in standard SQL and PostgreSQL, backticks in MySQL, and square brackets in SQL Server. String concatenation is || in most databases but + in SQL Server and CONCAT() in MySQL by default.

A lightweight formatter or validator works on all of these because it does not need to understand the dialect fully, but it also cannot know which dialect you target. Test against the real database before relying on a query.

A simple workflow

When a query arrives from an ORM log or a colleague as one long line, paste it into the Neemtools SQL Query Formatter to see its structure, then run the SQL Validator to catch unbalanced quotes, brackets and stray commas before you send it to the database. When you need the query on one line for a config file or log message, use the SQL Minifier and keep the formatted original in version control.

For a team, write the agreed rules down in a short page in your repository and enforce them with a formatter in CI, such as sqlfluff or the formatter built into your SQL editor. Style arguments end quickly when the tool decides.

More guides you might like

Ready to try it?

Open the free SQL Query Formatter and apply what you just read. No sign-up, nothing uploaded.

Open SQL Query Formatter β†’

← All guides