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
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(*) desc After
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 desc
The Playground has a Format
button that tidies your query automatically (powered by
sql-formatter in DuckDB mode). Handy for cleaning up a query
you pasted in.
Related
Use error messages as clues.
One-to-many joins can inflate totals.
Paste an error message and find the fix, from GROUP BY to constraint failures.
Shrink a query and check one piece at a time.
Debug filters that match nothing.
Group or aggregate every selected column.