Back to Blog
Reference 2026-04-17

SQL Formatting Conventions

Make SQL queries readable. Conventions for case, indentation, and aliasing.

SQL is read more than written. A 200-line analytics query is reviewed dozens of times — formatting pays for itself.

Keyword Case

Two camps:

  • UPPER: SELECT id FROM users WHERE created_at > NOW()
  • lower: select id from users where created_at > now()

UPPER is older but visually noisy. Lower is cleaner with modern syntax highlighting. Pick one team-wide and enforce with a formatter.

Indentation

Align the leading keyword of each clause:

SELECT

u.id,

u.email,

COUNT(o.id) AS order_count

FROM

users u

LEFT JOIN orders o ON o.user_id = u.id

WHERE

u.created_at > NOW() - INTERVAL '30 days'

GROUP BY

u.id, u.email

HAVING

COUNT(o.id) > 5

ORDER BY

order_count DESC

LIMIT 10;

Each major clause starts at column 0. Inner items indent.

Aliases

  • Always alias tables in multi-table queries: users u not users
  • Alias derived columns explicitly: COUNT(*) AS user_count
  • Avoid single-letter aliases that conflict with reserved words

JOIN Style

Always specify the JOIN type. Avoid implicit comma joins:

-- Good

FROM users u

INNER JOIN orders o ON o.user_id = u.id

-- Avoid

FROM users u, orders o WHERE o.user_id = u.id

CTEs Beat Subqueries

WITH active_users AS (

SELECT id FROM users WHERE last_seen > NOW() - INTERVAL '7 days'

),

recent_orders AS (

SELECT user_id, COUNT(*) AS n FROM orders WHERE created_at > NOW() - INTERVAL '7 days' GROUP BY user_id

)

SELECT u.id, COALESCE(o.n, 0)

FROM active_users u

LEFT JOIN recent_orders o ON o.user_id = u.id;

CTEs are linear top-to-bottom; nested subqueries are right-to-left and harder to follow.

Trailing vs Leading Commas

Leading commas make adding/removing columns clean and surface mistakes:

SELECT

id

, email

, name

FROM users;

Pure preference; pick one and enforce.

Auto-formatters

  • sqlfluff — Python, opinionated, configurable rules
  • pg_format — Postgres-aware
  • prettier-plugin-sql — for projects already using Prettier

Run on pre-commit; do not let formatting churn dominate code reviews.

Format queries online with the [SQL Formatter](https://sdk.is/sql-formatter).