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 itsJOIN, and clear aliases. The result never changes, only your ability to read it.

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 ShopTable · customers9 columns · 20 rows
Table · customers

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

9 columns · 20 rows
customer_id intfirst_name textlast_name textemail textphone textcity textstate textsignup_date dateis_active bool
Your task

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.

SQL Workbench
query.sqlgarden_shop · SQL engine loading
⌘↵ to run
·
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
✓ Chapter 9 complete

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 reports