Knowledgebase

Writing SQL Others Can Maintain Print

  • 0

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.


Was this answer helpful?
Back

Are you happy with your experience? Leave us a review on Trustpilot.


Trustpilot