Skip to content
/ Chapter 9 · Query Debugging and Common Mistakes
Lesson 9.4 · garden_shop
Lesson 9.4

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.

Pattern
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
Table · customers

One row per customer. Some customers have no phone on file.

9 columns · 20 rows
customer_id int first_name text last_name text email text phone text city text state text signup_date date is_active bool
Table · orders

One row per order. Unshipped orders have a null shipped_date.

6 columns · 24 rows
order_id int customer_id int order_date date shipped_date date status text coupon_code text
Your task

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.
← Previous · 9.3 Wrong answers without errors
End of Chapter 9

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 subqueries