DEV Community

Sanjaya Sahu
Sanjaya Sahu

Posted on

SQL Formatting Rules That Make Code Review Painless

Formatting SQL is not cosmetic. Unreadable queries hide bugs, bloat diffs and slow reviews. What I enforce on every team:

1. One clause per line

SELECT, FROM, WHERE, GROUP BY start on their own lines, with columns indented beneath. Diffs then show exactly which column changed.

2. Never SELECT *

It breaks when columns are added, defeats covering indexes and ships data you don't need. List the columns.

3. Explicit JOIN syntax

Write JOIN ... ON instead of comma joins. A forgotten condition in a comma join silently produces a cartesian product.

4. Uppercase keywords, consistent aliases

Short meaningful aliases (o for orders) beat t1, t2, t3. Qualify every column in multi-table queries.

5. Leading commas or trailing, but pick one

Leading commas make adding or commenting out the last column a clean one-line diff.

6. Use CTEs for readability

Name your intermediate steps with WITH. A 6-level nested subquery is a bug waiting to happen.

7. Parameterize, never concatenate

Formatting won't save you from SQL injection. Use bound parameters.

Quick cleanup

Pasting a messy query into a local SQL Formatter fixes layout in a second, and since it runs in-browser, your production queries stay private.


Disclosure: I built WebDevToolbox, a free collection of 500+ browser-based dev tools.

Top comments (0)