SQL Coding Standards for Production Work
Code review on SQL fails for the same reasons code review on any language fails: unclear intent, hidden behavior, and clever tricks that age badly.
- Name things once, consistently â tables, columns, aliases, and CTEs follow one scheme
- Say what you select â explicit columns instead of wildcards
- Layer with CTEs â each step does one job, top to bottom
- Treat NULLs and parameters as first-class design problems Style is not vanity; it is how a query survives its author leaving the team.
Prerequisites
- !Comfortable writing multi-table SELECT statements
- !Basic experience with GROUP BY and aggregate functions
- !Familiarity with at least one database client or IDE
What You'll Learn
- 1Apply a consistent naming and formatting scheme across a SQL codebase
- 2Restructure a tangled query into readable CTE layers
- 3Handle NULLs and empty strings deliberately instead of accidentally
- 4Write parameterized queries that are safe from injection and cache-friendly
Why Style Rules Pay for Themselves
A production query is read far more often than it is written. The person reading it six months from now â debugging a dashboard at 2 a.m., reviewing a migration, extending a report â has none of the context you had. Style rules compress that lost context. When every alias matches its table, when indentation shows the logical layers of the query, and when column lists are explicit, a reader can reconstruct intent without executing anything.
There is a mechanical argument too. SELECT * breaks when someone adds a column to a base table: views widen, insert-target mismatches fire, and network payloads grow silently. Inconsistent naming forces string-searching instead of navigation. Queries that concatenate user input endanger the entire database. The rules below are cheap to apply and expensive to ignore.
Treat SQL like any other code in your repository: version it, review it, lint it, and refuse to merge queries that violate the team's agreed baseline.
Naming and Formatting Conventions
Pick one scheme per codebase and enforce it everywhere. The following table describes a widely used baseline; adapt names if your organization already has a convention, but do not let two schemes coexist.
| Object | Convention | Example |
|---|---|---|
| Tables | plural, snake_case | order_lines, customer_addresses |
| Columns | singular where natural, snake_case | customer_id, created_at |
| Surrogate keys | <table>_id or bare id | order_id |
| Booleans | is_ or has_ prefix, never null | is_active, has_paid |
| Timestamps | _at suffix, UTC | created_at, updated_at |
| Aliases | short, match the table | o for orders, c for customers |
| CTE names | verb-first describing the step | paid_orders, top_customers |
| Parameters | colon or named style of the driver | :start_date, @customer_id |
Formatting matters as much as names. Put each major clause on its own line, one selected column per line with the comma at the end of the previous line, and indent nested subqueries so depth is visible. Keywords are conventionally uppercase (SELECT, FROM, INNER JOIN) while object names stay lowercase; the contrast makes the structure pop when scanning.
-- Before: dense, wildcard, unexplained logic
select * from customers c, orders o where c.id=o.customer_id and o.total>100 order by o.order_date desc;
-- After: explicit, join-typed, layered, scannable
WITH recent_paid_orders AS (
SELECT
o.customer_id,
o.order_id,
o.total,
o.order_date
FROM orders o
WHERE o.order_date >= CURRENT_DATE - INTERVAL '90 days'
AND o.total > 100
)
SELECT
c.customer_id,
c.first_name,
c.last_name,
rpo.order_id,
rpo.total,
rpo.order_date
FROM customers c
INNER JOIN recent_paid_orders rpo ON rpo.customer_id = c.customer_id
ORDER BY rpo.order_date DESC;
Explicit Columns Always Win
Wildcards are convenient while exploring data and harmful everywhere else. An explicit list documents which columns the query actually depends on. When a table gains a column â and it will â your query is unaffected. When someone reorders columns, your INSERT ... SELECT still lands values in the right places. Reviewers can see exactly what leaves the query, which matters for privacy: a wildcard can quietly ship a ssn column into a log table.
Explicit lists also help the planner in views and large schemas by making required columns obvious to the query optimizer's pruning logic, and they turn accidental cross-joins into visible mistakes because every unqualified column name must then be reconciled. There is a team-level argument as well: when a column is added to a base table for an internal feature, an explicit-list query is unaffected, while a wildcard-based view suddenly exposes the new column to every downstream consumer â including CSV exports and BI tools that mirror the view automatically. Explicitness turns schema evolution from a coordination problem into a non-event.
Layer Logic with CTEs, Not Nested Subqueries
Deeply nested subqueries are hard to read because each layer mixes two concerns: computing an intermediate result and consuming it. CTEs flatten that into named steps that read top to bottom like a recipe. Reserve inline subqueries for cases where you need a scalar value or a correlated lookup â anywhere a CTE would add ceremony without clarity.
-- Monthly cohort revenue with readable, named steps
WITH orders_by_month AS (
SELECT
customer_id,
DATE_TRUNC('month', order_date) AS order_month,
SUM(total) AS revenue
FROM orders
GROUP BY customer_id, DATE_TRUNC('month', order_date)
),
first_order AS (
SELECT
customer_id,
MIN(order_month) AS cohort_month
FROM orders_by_month
GROUP BY customer_id
),
cohort_revenue AS (
SELECT
f.cohort_month,
o.order_month,
EXTRACT(MONTH FROM AGE(o.order_month, f.cohort_month)) AS months_since,
SUM(o.revenue) AS revenue
FROM orders_by_month o
INNER JOIN first_order f ON f.customer_id = o.customer_id
GROUP BY f.cohort_month, o.order_month, EXTRACT(MONTH FROM AGE(o.order_month, f.cohort_month))
)
SELECT
cohort_month,
months_since,
revenue,
ROUND(100.0 * revenue / NULLIF(SUM(revenue) FILTER (WHERE months_since = 0)
OVER (PARTITION BY cohort_month), 0), 1) AS pct_of_month0
FROM cohort_revenue
ORDER BY cohort_month, months_since;
Notice how each CTE answers exactly one question â what did each customer buy per month, when did they first buy, how does revenue evolve after the first order â and the final select assembles the report. A reviewer can validate the steps independently and reuse orders_by_month for a different cut of the same data.
NULLs Deserve an Explicit Policy
NULL means unknown, and three-valued logic surprises people constantly. WHERE amount <> 100 silently drops NULL amounts because the comparison evaluates to unknown. Division by a nullable denominator yields NULL rather than an error. COUNT(column) skips NULLs while COUNT(*) counts rows â a difference that causes mismatched totals between dashboards.
Decide per domain whether NULL is allowed. If an optional numeric should default to zero for reporting, coalesce at the edge of the query, not deep inside a formula that other queries copy. Use NULLS FIRST or NULLS LAST deliberately in sorts. Prefer NOT EXISTS over NOT IN when the right side can contain NULLs, because NOT IN with a single NULL yields no rows at all â an error that is invisible without test data containing NULLs.
Parameterize Every Value That Comes from Outside
SQL injection is not an edge-case vulnerability; it is the default outcome of string-concatenating input into a statement. Beyond security, concatenated literals defeat statement caching: every distinct input produces a new plan. Bound parameters solve both problems at once â the database parses the statement shape once and sends values separately.
-- WRONG: user input concatenated into the statement (injection + no plan reuse)
-- SELECT * FROM users WHERE email = '" + email + "';
-- RIGHT: one parameterized statement, values bound at execution time
SELECT
user_id,
email,
last_login_at
FROM users
WHERE email = $1
AND is_active = TRUE;
-- RIGHT: dynamic IN lists via ANY with an array parameter (PostgreSQL)
SELECT order_id, total
FROM orders
WHERE customer_id = ANY($1::int[]);
-- RIGHT: prepared statement in psql for repeated execution
PREPARE recent_orders (date) AS
SELECT order_id, customer_id, total, order_date
FROM orders
WHERE order_date >= $1;
EXECUTE recent_orders('2024-01-01');
Apply the same discipline to identifiers. You cannot bind a table name as a parameter; if an identifier must be dynamic, validate it against an explicit allowlist of known values before interpolating.
Comment the Why, Not the What
A comment that restates WHERE status = 'cancelled' helps nobody. Comments earn their place when they capture business knowledge the SQL cannot express: why a cutoff is 13 months rather than 12, why a join excludes a particular state, which upstream job populates the source table. Mark known data quirks â for example, that deleted_at is populated by a nightly job rather than in-line â so future readers do not "fix" what is intentional.
Common Mistakes
Using SELECT * in views, INSERT INTO ... SELECT, and production queries
Fix: List columns explicitly; treat adding a column as a deliberate schema change that consumers opt into
Concatenating request input into SQL strings
Fix: Use driver-level bind parameters for values and allowlists for identifiers
Mixing COUNT(*) and COUNT(column) in the same report without noticing different NULL behavior
Fix: Pick the form that matches the question and document the choice in a comment
Ten-level nested subqueries with no names
Fix: Flatten into CTEs, one concept per step, named for what the step produces
Formatting that changes with every author
Fix: Adopt an automated formatter (sqlfmt, SQLFluff) so style never becomes a review topic
Best Practices
- Version-control all SQL and review it like application code
- Adopt a team-wide naming scheme and enforce it with a linter
- Write explicit column lists everywhere outside ad-hoc exploration
- Layer complex queries as CTEs that read top to bottom
- Parameterize external values and allowlist dynamic identifiers
- Test queries against data that includes NULLs and empty strings
Interview Questions
Q1: Why can NOT IN return no rows when you expect some?
If the subquery's result set contains even one NULL, NOT IN evaluates to unknown for every candidate row, so the filter eliminates everything. NOT EXISTS treats the comparison as a membership test that NULLs cannot poison.
Q2: What problems does SELECT * cause in a production codebase?
Schema changes break downstream consumers, INSERT ... SELECT can misalign columns, unnecessary columns leak across network and into logs, and reviewers cannot see which fields the business logic actually depends on.
Q3: How do bound parameters help performance as well as security?
With parameters, the database caches one parsed plan and reuses it for every execution. Concatenated literals produce a distinct statement per value, causing repeated parsing and plan cache bloat.
Key Takeaways
- Consistent naming and formatting make queries readable without execution
- Explicit column lists protect you from schema churn and accidental data exposure
- CTEs turn tangled subqueries into named, testable steps
- NULL semantics break naive filters â decide the policy per domain
- Bind parameters prevent injection and enable plan caching in one move