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 its
JOIN, and clear aliases. Pure formatting should preserve the query's meaning
while making that meaning easier to inspect.
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 desc Schema · Garden Shop Tables · customers, orders 2 tables
One row per customer. Some customers have no phone on file.
One row per order. Unshipped orders have a null shipped_date.
The starter is a correct query crammed onto a single line. Reformat it for
readability. It should still return each customer's first_name, last_name, and order count as
orders, most orders first. The rows won't change; only the
layout will.
Run your query to inspect the result.
Expected answer
- 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.
That's the last lesson in “Query Debugging and Common Mistakes.”
The next chapter builds on what this one covered.
Start Chapter 10: Subqueries and EXISTS → Begins with 10.1 Scalar subqueriesRelated
Indentation, casing, and aliasing conventions.
One-to-many joins can inflate totals.
Paste an error message and find the fix, from GROUP BY to constraint failures.
Debug filters that match nothing.
Group or aggregate every selected column.
Right-table WHERE filters remove unmatched rows.