Reference
SQL Query Formatting Guide
Readable SQL is easier to debug, review, and change. A few simple habits go a long way.
SQL ignores whitespace, so formatting is purely for humans. Consistent layout makes it obvious what a query does and where to make a change.
The habits that matter most
- Put each major clause (
SELECT,FROM,WHERE,GROUP BY,ORDER BY) on its own line. - One column per line in
SELECTonce you have more than two or three. - Indent
JOINandAND/ORconditions under their clause. - Use short, meaningful table aliases (
cfor customers,ofor orders). - Pick one case convention. Lowercase keywords are common and easy to read.
Before
Hard to scan
select c.first_name,c.last_name,count(*) from customers c join orders o on o.customer_id=c.customer_id where c.is_active=true group by c.first_name,c.last_name having count(*)>2 order by count(*) descAfter
Same query, readable
select c.first_name,
c.last_name,
count(*) as order_count
from customers as c
join orders as o on o.customer_id = c.customer_id
where c.is_active = true
group by c.first_name, c.last_name
having count(*) > 2
order by order_count descDialect note
The Playground has a Formatbutton that tidies your query automatically (powered bysql-formatter in DuckDB mode). Handy for cleaning up a query you pasted in.