Formatting SQL Queries for Readability
Clean formatting doesn't change what a query returns, but it makes mistakes far easier to spot.
A query crammed onto one line still runs, but good luck spotting the bug in it. Formatting is a debugging tool: when each clause sits on its own line, a missing comma or a misplaced condition jumps out.
The habits are simple: one column per line, each clause (FROM, JOIN, GROUP BY) starting a new line, the join condition indented under itsJOIN, and clear aliases. The result never changes, only your ability to read it.
select col_a,
col_b,
count(*) as n
from table_one as t
join table_two as u
on t.id = u.t_id
group by col_a, col_b
order by n descSchema · Garden ShopTable · customers9 columns · 20 rows
One row per customer. Some customers have no phone on file.
The starter is a correct query crammed onto a single line. Reformat it for readability. It should still return each customer'sfirst_name, last_name, and order count asorders, most orders first. The rows won't change; only the layout will.
- Columns: first_name, last_name, orders.
- Rows: 16 customers who have placed orders.
- The reformatted query returns exactly the same rows as the cramped one.
You finished “Query Debugging and Common Mistakes.”
Nice work. Ready to start the next one?
Start Chapter 10: Practical Analytics Patterns →Begins with 10.1 Top-N reportsRelated
Use error messages as clues.
Shrink a query and check one piece at a time.
Catch silent query logic bugs.
Paste an error message and find the fix, from GROUP BY to constraint failures.