SQL That Humans Can Review

Use consistent clauses, indentation, aliases, joins, and comments so a query can be reviewed and changed without altering what the database executes.

By utilkit 5 min read Developer
Database code displayed in a dark editor window
Photo by Chris Ried on Unsplash

A database can execute SQL with erratic capitalization and one giant line. People cannot review it as reliably. Formatting should make the query’s structure visible without pretending to improve its logic. The goal is a stable style that lets a reader find data sources, joins, filters, grouping, and output expressions quickly.

Paste non-sensitive SQL into our SQL Formatter for a consistent baseline. Review the result in the dialect your database uses. A formatter can rearrange whitespace and keyword case; it cannot prove that vendor-specific syntax, dynamic fragments, or templating remain valid.

Put major clauses on clear boundaries

Start SELECT, FROM, each JOIN, WHERE, GROUP BY, HAVING, ORDER BY, and LIMIT on recognizable lines. Break long select lists so each expression and alias can be scanned. Indent subordinate expressions under the clause that owns them.

Follow the logical structure rather than forcing a rigid line length. A short query can remain compact; a complex window function or case expression deserves vertical space. The current PostgreSQL SELECT documentation is a good reminder that clause behavior and order are semantic even when the style is your choice.

Make joins and aliases explain the model

Use explicit JOIN syntax and keep each ON condition near its table. Prefer meaningful aliases such as orders and customers unless the local codebase consistently uses short forms. One-letter aliases save typing but become costly when several tables share column names.

Qualify ambiguous columns and use the same alias everywhere. Do not hide a filtering condition in a join simply because the query becomes shorter; place it where its meaning is clearest and confirm that moving it would not change outer-join behavior.

Group boolean logic visibly

Put each important predicate on its own line and align AND or OR consistently. Add parentheses whenever mixed boolean logic could be misread, even if operator precedence technically makes them optional. A future edit should not require someone to remember precedence under pressure.

Comments should explain intent, source quirks, or a non-obvious constraint—not narrate WHERE status = 'paid'. Keep links to tickets or data definitions durable, and remove stale commented-out SQL from the production query.

Adopt the local dialect and style

  • Choose keyword case and indentation once.
  • Use trailing or leading commas consistently.
  • Standardize CTE, alias, and identifier naming.
  • Keep formatter configuration with the repository.
  • Review the execution plan separately from formatting.
  • Run tests or compare results after any non-whitespace change.

Review the query as a data contract

Before reviewing style, state what one output row represents. Is it one customer, order, account-day, or event? Then identify the expected keys and whether each join is one-to-one, many-to-one, or many-to-many. A readable query can still duplicate facts when a join assumption is wrong. Compare row counts and key uniqueness before and after each major join when the result matters.

Check filters for null behavior, time-zone boundaries, inclusive versus exclusive dates, and placement relative to outer joins. A condition in WHERE can turn a left join into an effective inner join; parentheses can change mixed AND and OR logic. Use representative fixtures containing missing relationships, duplicate keys, boundary timestamps, and values that should be excluded.

For a production query, record owner, purpose, dialect, parameters, expected refresh, and validation totals. Review the execution plan and bytes or rows scanned after correctness is established. Keep formatting changes separate from semantic changes when possible so reviewers can see what actually affects results. The final test should compare a few known outputs and aggregate checks with an independent source, not merely confirm that the query executes.

Keep generated and hand-written SQL distinguishable. If an ORM or report builder owns the query, improve the source expression or add an annotated captured example rather than formatting a generated string that will be replaced. For recurring analytical queries, store tests or assertions for grain, key uniqueness, accepted nulls, and important totals near the query. Readability helps a reviewer form a hypothesis; lightweight data tests keep that hypothesis checked as source tables evolve.

Use comments for business rules that the SQL cannot make obvious, not to narrate each clause. Explain why a date excludes the current partial day, why one source outranks another, or why a duplicate is intentionally retained. Link to a stable definition when a metric has organizational meaning. Remove comments that repeat the code or no longer match it. A good reviewer should be able to separate database mechanics from the business decision encoded in the query.

Before merging, have the author summarize the grain, changed business rule, validation result, and expected performance impact in the review description. That gives reviewers an independent statement to test against the SQL. If the explanation cannot be made concise, the query may need smaller named stages or a clearer metric definition before formatting can help.

Cloud and database products document their own lexical rules; for example, Google provides a BigQuery lexical reference. A team style should sit inside those rules and match existing code. Good formatting does not make a query fast or correct, but it makes mistakes and assumptions easier to see—and that improves every review that follows.