SQL Formatting Best Practices for Readable Queries
Consistent SQL formatting makes queries easier to review, debug and optimise. Here are the conventions most teams use, with before and after examples.
Why Formatting Matters
A 400-character query on one line is impossible to review. Formatting puts each clause on its own line, so joins, filters and grouping are visible at a glance and mistakes stand out.
Before
select u.id,u.name,count(o.id) as orders from users u left join orders o on o.user_id=u.id where u.active=1 group by u.id,u.name
After
SELECT
u.id,
u.name,
COUNT(o.id) AS orders
FROM
users u
LEFT JOIN orders o ON o.user_id = u.id
WHERE
u.active = 1
GROUP BY
u.id,
u.name
Conventions Most Teams Use
Format Automatically
The [SQL Formatter](/tools/sql-formatter) applies these rules for MySQL, PostgreSQL, SQL Server, Oracle PL/SQL, SQLite, BigQuery and MariaDB. When you need the opposite, for example to embed a query in a config file, the [SQL Minifier](/tools/sql-minify) removes comments and whitespace while leaving string literals untouched.
Have INSERT statements you want in a spreadsheet? [SQL to CSV](/tools/sql-to-csv) and [SQL to JSON](/tools/sql-to-json) parse them for you.
Summary
Pick a style, automate it and apply it in code review. Readable SQL is faster to debug, easier to optimise and safer to change.
Try our free tools
Put these tips into practice with 45+ free online tools - no signup, no login.
Browse Free Tools