Databases·6 min read·By the developer of StackUtils

SQL Formatting Best Practices: Write SQL That Others Can Read

Unformatted SQL is a maintenance nightmare. This guide covers indentation conventions, JOIN alignment, CTE style, and how consistent formatting prevents logic bugs in complex queries.

Formatting is about finding bugs, not taste

SQL engines ignore whitespace, so a query on one line and the same query on twenty lines are identical to the database. The difference is entirely for the person reading it, and the most useful thing a consistent layout does is make certain bugs visible: a filter in the wrong clause, an OR that escaped its parentheses, a missing comma. This guide starts with a real example of that, then covers a layout convention and the mistakes it helps you catch.

One query, two bugs, before and after

The intent: list Spanish customers (plus all VIPs) with their number of paid orders, including customers with none.

select c.id,c.email,count(o.id) as orders from customers c left join orders o on o.customer_id=c.id where o.status='paid' and c.country='ES' or c.is_vip=true group by c.id,c.email order by orders desc limit 10

The same query after running it through the SQL formatter (PostgreSQL dialect, uppercase keywords):

SELECT
  c.id,
  c.email,
  count(o.id) AS orders
FROM
  customers c
  LEFT JOIN orders o ON o.customer_id = c.id
WHERE
  o.status = 'paid'
  AND c.country = 'ES'
  OR c.is_vip = TRUE
GROUP BY
  c.id,
  c.email
ORDER BY
  orders DESC
LIMIT
  10

With one condition per line, both bugs are now in plain sight:

  1. AND binds tighter than OR. The WHERE clause means (paid AND Spain) OR vip. Any VIP row passes, whatever the order status. When AND and OR appear at the same indentation level, add parentheses.
  2. A WHERE filter on the right side of a LEFT JOIN turns it into an inner join. Customers without orders have o.status = NULL, the comparison is not true, and the row is removed. The "including customers with none" requirement is silently broken. Move the condition into the join: LEFT JOIN orders o ON o.customer_id = c.id AND o.status = 'paid'.

Running both versions against a three-row test table (in SQLite) shows the difference: the original join-plus-WHERE returns 1 customer, the version with the condition in ON returns all 3, two of them with no paid orders. The corrected query:

SELECT
  c.id,
  c.email,
  COUNT(o.id) AS paid_orders
FROM customers AS c
LEFT JOIN orders AS o
  ON  o.customer_id = c.id
  AND o.status = 'paid'
WHERE
  (c.country = 'ES' OR c.is_vip = TRUE)
GROUP BY
  c.id,
  c.email
ORDER BY paid_orders DESC
LIMIT 10;

A layout convention that scales

There is no official SQL style. These rules are close to what most formatters produce by default, so you can adopt them without fighting your tools:

  1. Each clause starts a line: SELECT, FROM, each JOIN, WHERE, GROUP BY, HAVING, ORDER BY, LIMIT.
  2. One selected column per line once there are more than two or three. Diffs then show exactly which column changed.
  3. Each join gets its own ON, with multi-column join conditions on separate lines starting with AND.
  4. Boolean operators lead the line in WHERE and HAVING, so mixed AND/OR is easy to spot.
  5. Explicit AS for aliases, and aliases that mean something (c for customers, not t1).
  6. One case style for keywords. Uppercase keywords with lowercase identifiers is the most common choice; all-lowercase is fine too. Mixing them is the only wrong answer.
  7. Terminate statements with ; in scripts and migrations, where several statements share a file.

Leading or trailing commas?

-- trailing (formatter default)   -- leading
SELECT                              SELECT
  id,                                   id
  email,                              , email
  created_at                          , created_at
FROM users;                         FROM users;

Leading commas make it easy to comment out any column except the first; trailing commas read more like prose and are what most formatters emit. Both are fine. Pick one for the repository and let a tool enforce it.

CTEs instead of nested subqueries

Deeply nested subqueries must be read inside-out. A WITH clause lets you name each step and read top to bottom. Each CTE should do one thing and have a name that says what rows it holds:

WITH
paid_orders AS (
  SELECT customer_id, COUNT(*) AS n, SUM(total) AS revenue
  FROM orders
  WHERE status = 'paid'
    AND created_at >= CURRENT_DATE - INTERVAL '30 days'
  GROUP BY customer_id
),
active_customers AS (
  SELECT id, email
  FROM customers
  WHERE is_active
)
SELECT
  ac.email,
  COALESCE(po.n, 0)       AS orders_30d,
  COALESCE(po.revenue, 0) AS revenue_30d
FROM active_customers AS ac
LEFT JOIN paid_orders AS po ON po.customer_id = ac.id
ORDER BY revenue_30d DESC;

CTEs are also the easiest way to debug: temporarily replace the final SELECT with SELECT * FROM paid_orders to inspect an intermediate step. The date arithmetic above is PostgreSQL syntax; MySQL writes it as CURRENT_DATE - INTERVAL 30 DAY.

Mistakes that layout helps you catch

Each of these was run against SQLite; the behaviour is the same in PostgreSQL and MySQL.

A missing comma creates an alias

SELECT id, email country FROM customers WHERE id = 1;
→ [{ id: 1, country: "ana@x.es" }]

email country is valid SQL: it selects email and names it country. No error, wrong column. With one column per line, a line without a trailing comma stands out.

NOT IN with a NULL in the subquery

SELECT id FROM customers
WHERE id NOT IN (SELECT customer_id FROM orders);
→ [2, 3]   … until one order has customer_id = NULL, then → []

SELECT id FROM customers AS c
WHERE NOT EXISTS (
  SELECT 1 FROM orders AS o WHERE o.customer_id = c.id
);
→ [2, 3]   (unaffected by NULLs)

x NOT IN (1, NULL) evaluates to unknown rather than true, so every row is filtered out. Prefer NOT EXISTS for anti-joins.

Comparing with NULL using =

WHERE is_vip = NULL matches nothing, ever. Use IS NULL / IS NOT NULL, or a NULL-safe comparison when NULL should compare as a value: IS DISTINCT FROM (standard SQL, PostgreSQL, SQLite 3.39+) or <=> (MySQL).

Grouping by something you did not select

Since MySQL 5.7.5, ONLY_FULL_GROUP_BY is enabled by default and rejects columns that are neither aggregated nor functionally dependent on the GROUP BY columns. Grouping by a primary key and selecting other columns of that table is allowed in both MySQL and PostgreSQL. Older MySQL setups with the mode disabled return an arbitrary value instead of an error, which is why the same query can "work" on one server and fail on another.

Choose the right dialect before formatting

Formatters tokenize the query, so they need to know which dialect they are reading. A PostgreSQL cast like id::text or a $1 placeholder is fine with the PostgreSQL setting; with the MySQL setting the sql-formatter library stops with Parse error: Unexpected "::text". Other differences to keep in mind:

  • Quoted identifiers: "order" in PostgreSQL and standard SQL, `order` in MySQL, [order] in SQL Server.
  • Row limits: LIMIT 10 (PostgreSQL, MySQL, SQLite), TOP 10 (SQL Server), FETCH FIRST 10 ROWS ONLY (standard, PostgreSQL, Oracle).
  • Case of unquoted identifiers: PostgreSQL folds them to lowercase, so SELECT UserId looks for userid. Uppercasing identifiers during formatting can therefore change meaning for quoted names; keep keyword case and identifier case as separate settings.

Automate it

Style discussions in code review are a waste of time once a tool decides. Options that run in CI or as a pre-commit hook include the sql-formatter npm package (the library behind the StackUtils formatter), pgFormatter for PostgreSQL, and SQLFluff, which also lints for problems like ambiguous column references. For one-off queries pasted from logs or an ORM's debug output, the browser formatter is quicker: nothing is uploaded, so it is safe for queries that contain real table names.

If the SQL you need is a batch of INSERT statements for test data, generating it beats typing it: the CSV to SQL converter turns a spreadsheet export into CREATE TABLE and INSERT statements.

Format a query in your browser

Paste a one-line query from a log, pick the dialect and keyword case, and get a readable version back.