SQL Formatting Best Practices
Free Online SQL Formatter
Beautify raw SQL queries instantly. Supports MySQL, PostgreSQL, and more.
Open SQL Formatter →Why SQL formatting matters
SQL queries can grow to hundreds of lines involving multiple joins, subqueries, CTEs, and window functions. Without consistent formatting, a complex query becomes nearly impossible to review in a pull request, debug in production, or hand off to another developer.
Good SQL formatting makes the logical structure of a query immediately visible — which tables are involved, what conditions apply, how data is grouped and ordered.
Keyword casing — UPPERCASE vs lowercase
The most visible formatting choice is whether SQL keywords are uppercase or lowercase. Both are valid SQL — it's a style choice. The two dominant conventions are:
| Style | Example | Common in |
|---|---|---|
| UPPERCASE keywords | SELECT id FROM users WHERE active = true | Traditional SQL, enterprise teams, most style guides |
| lowercase keywords | select id from users where active = true | Modern teams, ORM-generated SQL |
The tinybench.dev SQL formatter lets you choose your preferred keyword casing — UPPERCASE, lowercase, or preserve original.
Indentation and line breaks
Each major clause should start on a new line. Use consistent indentation (2 or 4 spaces) for sub-clauses.
SELECT u.id, u.name, COUNT(o.id) AS orders FROM users u LEFT JOIN orders o ON u.id = o.user_id WHERE u.active = true GROUP BY u.id, u.name HAVING COUNT(o.id) > 0 ORDER BY orders DESC LIMIT 10
SELECT
u.id,
u.name,
COUNT(o.id) AS orders
FROM users u
LEFT JOIN orders o
ON u.id = o.user_id
WHERE u.active = true
GROUP BY
u.id,
u.name
HAVING COUNT(o.id) > 0
ORDER BY orders DESC
LIMIT 10Commas — leading vs trailing
Two schools of thought exist on where to place commas in SELECT lists:
SELECT
id,
name,
email,
created_at
FROM usersSELECT
id
, name
, email
, created_at
FROM usersLeading commas make it easy to comment out a line without worrying about trailing commas. Pick one style and be consistent within a project.
Aliasing tables and columns
- Use meaningful aliases —
uforusers,ofororders - Always use the
ASkeyword explicitly —COUNT(id) AS order_countis clearer thanCOUNT(id) order_count - Qualify all column names with table aliases in multi-table queries to avoid ambiguity
CTE formatting
Common Table Expressions (CTEs) should be formatted with each CTE clearly separated and named descriptively:
WITH
active_users AS (
SELECT id, name
FROM users
WHERE active = true
),
order_counts AS (
SELECT user_id, COUNT(*) AS total
FROM orders
GROUP BY user_id
)
SELECT
u.name,
COALESCE(o.total, 0) AS orders
FROM active_users u
LEFT JOIN order_counts o
ON u.id = o.user_id
ORDER BY orders DESCFrequently asked questions
Try it now — free & private
Runs entirely in your browser. No sign-up, no uploads, no tracking.
Open SQL Formatter →