SQL Formatting Conventions That Make Queries Readable
The database does not care how your SQL is laid out, but the next person who reads it does, and that person is often you in six months. A consistent format makes a 60-line query skimmable, makes bugs easier to spot and keeps version-control diffs small. This guide collects the conventions that work well in practice and is honest about which are matters of taste.
Start with a before and after
Here is a query as it often arrives from a log file or an ORM:
select c.id, c.name, count(o.id) as order_count, sum(o.total) as revenue from customers c, orders o where c.id=o.customer_id and o.status='paid' and o.created_at>='2026-01-01' group by c.id, c.name having sum(o.total)>1000 order by revenue desc limit 10
It runs fine and is miserable to review. The same query, formatted:
SELECT
c.id,
c.name,
COUNT(o.id) AS order_count,
SUM(o.total) AS revenue
FROM customers AS c
INNER JOIN orders AS o
ON o.customer_id = c.id
WHERE o.status = 'paid'
AND o.created_at >= '2026-01-01'
GROUP BY
c.id,
c.name
HAVING SUM(o.total) > 1000
ORDER BY revenue DESC
LIMIT 10;
Notice what changed: nothing about the result. Every improvement below is about reading, not execution.
Keyword case, clauses and indentation
Keyword case. Upper-case keywords (SELECT, FROM) with lower-case identifiers is the most common convention, because it lets the eye separate language from schema. Some teams go all lower-case and rely on syntax highlighting. Both are fine. Pick one and apply it everywhere. Our SQL Formatter upper-cases the keywords it recognises (SELECT, JOIN, GROUP BY, CASE, WITH and so on), and leaves identifiers as typed.
One clause per line. Start FROM, WHERE, GROUP BY, HAVING, ORDER BY and LIMIT on their own lines, flush left. You can see the skeleton of a query by scanning the left margin.
Indentation. Indent continuation lines by two or four spaces; do not mix. Indent the ON condition under its JOIN. Put AND/OR at the start of the line so conditions line up and a commented-out line does not break the one above it.
Mind the parentheses with OR. AND binds tighter than OR, so a AND b OR c means (a AND b) OR c. Add explicit parentheses and indent inside them; formatting makes this class of bug visible.
Commas: trailing or leading
Trailing commas (the style above) read like prose. Leading commas (, c.name) make it trivial to comment out or reorder one column without touching the line before, and produce one-line diffs when you append a column. Neither is wrong, but trailing commas are what most formatters and style guides choose by default. Whatever the team picks, enforce it automatically. Our formatter puts each comma-separated item on its own indented line with the comma trailing.
Aligning the AS keywords, as in the example, looks neat but creates noisy diffs when a longer column name arrives and realigns every line. Many teams skip alignment for exactly that reason.
Explicit JOINs, aliases and column lists
- Use explicit JOIN ... ON, not comma joins.
FROM customers c, orders o WHERE c.id = o.customer_idmixes join logic with filters. Forget the condition and you get a Cartesian product: 10,000 customers times 1,000,000 orders is ten billion rows. WithJOIN ... ONthe relationship sits next to the table, and an outer join is only possible with this syntax. - Write INNER, LEFT and so on explicitly. Bare
JOINis an inner join, but spelling it out removes doubt. - Alias tables briefly but meaningfully.
cforcustomersandoforordersis fine in a two-table query; in a ten-table one usecust,ord,ship. Avoid meaninglesst1,t2. Always qualify columns with the alias once more than one table is involved, so a later schema change cannot make a name ambiguous. - Avoid
SELECT *in application code. It pulls columns you do not need (including large text or blob columns), breaks when someone adds or reorders a column, and prevents covering-index reads. It is perfectly fine for ad hoc exploration. In anINSERT ... SELECTor a view, always list the columns. - Alias computed columns with
AS, using snake_case names the consumer can rely on.
CTEs versus nested subqueries
Deeply nested subqueries force the reader to start in the middle and read outwards. A common table expression (WITH) lets you name each step and read top to bottom:
WITH paid_orders AS (
SELECT customer_id, total
FROM orders
WHERE status = 'paid'
),
customer_revenue AS (
SELECT customer_id, SUM(total) AS revenue
FROM paid_orders
GROUP BY customer_id
)
SELECT c.name, r.revenue
FROM customer_revenue AS r
INNER JOIN customers AS c
ON c.id = r.customer_id
WHERE r.revenue > 1000
ORDER BY r.revenue DESC;
Give each CTE a name that describes its rows, not its mechanics. One caution is performance-related: some databases historically treated CTEs as optimisation fences and materialised them, while others inline them. PostgreSQL before version 12 always materialised them; newer versions inline simple ones and allow MATERIALIZED hints. Check how your engine behaves if a CTE-heavy query is slow, rather than assuming either way.
Naming and comments
Pick a naming scheme and keep it: snake_case, singular or plural table names (the point is consistency), customer_id rather than a bare id repeated everywhere in joins. Avoid reserved words as identifiers, which forces quoting. If you need to convert existing names between conventions, the Case Converter does that in bulk.
Comment the why, not the what: -- exclude test accounts created by the QA import is useful; -- select customers is noise. Use -- for line comments and /* ... */ for blocks, and note that any tool that collapses whitespace turns the rest of the query into part of a -- comment. Our formatter and its minify button both collapse whitespace first, so remove line comments (or convert them to /* ... */) before pasting, and expect it to break after every comma, including commas inside function calls such as COALESCE(a, b). Tidy those by hand.
Formatting is not performance
Whitespace, case and line breaks are discarded when the statement is parsed. The query plan depends on the parsed structure, statistics and indexes, never on layout, so reformatting will not make a slow query fast. What formatting does is reveal problems that cause slowness: a missing join condition, a function wrapped around an indexed column in the WHERE clause, or a SELECT * over a wide table. Use your database's EXPLAIN to see actual plans.
Dialects, team style and version control
Dialects differ in quoting ("name" in PostgreSQL, backticks in MySQL, brackets in SQL Server), row limiting (LIMIT versus TOP versus FETCH FIRST), string concatenation and date functions. A formatter that only handles the keyword structure, as ours does, has no dialect switch; it reflows generic SQL and may mishandle exotic syntax such as procedural blocks, so review its output. For large codebases use a dialect-aware tool in CI.
The biggest payoff of consistency is in version control. When everyone formats the same way, a diff shows the real change instead of whitespace churn. Agree on a short written style guide covering case, indentation, comma style and join syntax, auto-format before committing, and review changes with a diff viewer such as our Text Diff Checker to confirm a formatting-only commit really did not alter logic. For related hygiene on structured text, see Common JSON Syntax Errors, and if you filter text in query strings, Regex Patterns and Pitfalls. When you generate test rows with identifiers, UUID Versions Explained covers choosing keys that index well.