Queries others can read.
WHAT MAKES SQL HARD TO READ
Everything on one line Inconsistent capitalisation No aliases, or meaningless ones Deeply nested subqueries No comments on non-obvious logic
WHAT TO DO ABOUT EACH
One clause per line Keywords consistently cased Aliases that mean something Common table expressions instead of nesting A comment explaining why, not what
WHAT COMMON TABLE EXPRESSIONS PROVIDE
Named intermediate results, read top to bottom.
WHY THAT HELPS
A query becomes a sequence of steps rather than a nested puzzle.
WHAT TO NAME THEM
After what they contain.
WHAT TO AVOID
Selecting every column Relying on column order Implicit joins in the condition list Reserved words as identifiers
WHY IMPLICIT JOINS MATTER
Omitting a condition silently produces every combination.
WHAT TO KEEP IN VERSION CONTROL
Queries used in reporting, and anything complex.
WHY
They are frequently the least documented and most relied upon.
WHAT TO DOCUMENT
Assumptions the query makes about the data.
WHAT TO TEST
That it returns what you expect against known data.
WHAT TO REVIEW
Queries, as code, before they reach production.