All articles

SQL formatting best practices

· 3 min read

SQL is often written in a hurry and read many times: in code review, while debugging a slow query, in a dashboard someone else built. A consistent format makes the structure visible at a glance. There's no single official SQL style, but most good guides agree on the essentials below.

Before and after

select u.id,u.email,count(o.id) as orders,sum(o.total) as revenue from users u left join orders o on o.user_id=u.id and o.status='paid' where u.created_at>='2026-01-01' group by u.id,u.email having count(o.id)>0 order by revenue desc limit 50;
SELECT
  u.id,
  u.email,
  COUNT(o.id) AS orders,
  SUM(o.total) AS revenue
FROM users AS u
LEFT JOIN orders AS o
  ON o.user_id = u.id
  AND o.status = 'paid'
WHERE u.created_at >= '2026-01-01'
GROUP BY u.id, u.email
HAVING COUNT(o.id) > 0
ORDER BY revenue DESC
LIMIT 50;

The second version shows the shape of the query (what's selected, from where, filtered how) without reading every token.

The core rules

One clause per line

Start SELECT, FROM, each JOIN, WHERE, GROUP BY, HAVING, ORDER BY and LIMIT on a new line, at the same indentation level. They're the outline of the query.

One column per line in SELECT

It makes adding, removing and commenting out columns a one-line change, and keeps diffs clean. Short lists in GROUP BY or ORDER BY can stay on one line.

Consistent keyword case

Uppercase keywords (SELECT, LEFT JOIN) and lowercase identifiers is the most common convention. Lowercase everything is also popular. Mixing them is the only wrong choice.

Indent with spaces

Two or four spaces, never tabs mixed with spaces. Indent the contents of each clause one level.

Spaces around operators

o.user_id = u.id, not o.user_id=u.id. It matters more than it seems in long WHERE clauses.

End statements with a semicolon

Required between statements in scripts, and harmless for a single one.

Naming and aliases

  • Use snake_case for tables and columns, and avoid quoted identifiers with spaces or mixed case. In PostgreSQL, "UserId" and userid are different columns.
  • Write AS for aliases; it's explicit and easy to search for.
  • Give tables meaningful aliases (orders AS o is fine, orders AS t2 isn't), and always qualify columns with the alias once more than one table is involved.
  • Name computed columns: COUNT(*) AS order_count, not an unnamed count.

Joins

Put each join on its own line with its condition indented below it:

FROM orders AS o
INNER JOIN customers AS c
  ON c.id = o.customer_id
LEFT JOIN refunds AS r
  ON r.order_id = o.id

Write INNER JOIN or LEFT JOIN explicitly rather than listing tables with commas and joining in WHERE. Join conditions belong in ON; filters on the main table belong in WHERE. For a LEFT JOIN, a condition on the right-hand table changes the result depending on where you put it, so placement is about correctness, not just style.

Leading or trailing commas?

SELECT              SELECT
  id,                 id
  email,            , email
  created_at        , created_at

Trailing commas read naturally. Leading commas make it easy to comment out the last column and spot a missing comma. Both are common; choose one per project.

CTEs over nested subqueries

Deeply nested subqueries are read inside out. Common table expressions name each step and read top to bottom:

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 > 1000
)

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

In most modern databases a CTE performs the same as the equivalent subquery. Check your database's documentation if you rely on older versions; PostgreSQL before 12, for example, always materialized CTEs.

CASE expressions and long conditions

CASE
  WHEN o.total >= 1000 THEN 'large'
  WHEN o.total >= 100 THEN 'medium'
  ELSE 'small'
END AS order_size

For long WHERE clauses, put one condition per line with AND or OR at the start, and use parentheses whenever both appear:

WHERE o.status = 'paid'
  AND (o.country = 'IN' OR o.country = 'US')
  AND o.created_at >= '2026-01-01'

Comments

Use -- for short notes and explain why, not what: -- exclude test accounts created by QA. A comment at the top of a long query describing its purpose saves the next reader time.

Automate it

Style rules only last if a tool applies them:

  • sql-formatter: a JavaScript library and CLI for many dialects; works with Prettier through a plugin.
  • SQLFluff: a linter and formatter for Python projects and dbt, with configurable rules and dialects.
  • pgFormatter: a PostgreSQL-focused formatter.
  • Editor extensions in VS Code, DataGrip and DBeaver format on save.

Run the formatter in CI or a pre-commit hook so reviews focus on logic instead of whitespace.

Dialect differences to watch

Formatters need to know the dialect to parse correctly:

Feature Example dialects
Identifier quotes "name" (PostgreSQL, standard), `name` (MySQL, BigQuery), [name] (SQL Server)
Row limit LIMIT 10 (PostgreSQL, MySQL), TOP 10 (SQL Server), FETCH FIRST 10 ROWS ONLY (standard, Oracle, Db2)
Comments # starts a comment in MySQL and BigQuery, but not in PostgreSQL

Choosing the wrong dialect can make a formatter misread a backtick or # and change your query, so always set it explicitly.

Frequently asked questions

Uppercase or lowercase SQL keywords?

Both are fine; consistency matters more. Uppercase keywords stand out from identifiers in plain text, while lowercase is easier to type and common in dbt projects. Pick one and let a formatter enforce it.

Does formatting affect query performance?

No. The database parses the query into the same plan regardless of whitespace and case. Only the logic matters.

Should I use SELECT * ?

Fine for exploring data, but avoid it in application code and views: it fetches columns you don't need and breaks when columns are added or reordered.

How do I format SQL inside application code?

Keep it in a multi-line string or a separate .sql file so it can be formatted and highlighted. Use parameters, never string concatenation, for values.

Further reading