Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 40/ 160
02. Aggregations, Functions & Data Manipulation

Writing Clean, Readable & Maintainable SQL Style Guides

Adopt naming, formatting, and CTE habits that keep analytical SQL reviewable.

BeginnerFormatting · Naming3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

Everyone writes SQL the same tidy way, so it's easy for anyone to read.

Think of it like…

A newspaper's style guide: every journalist writes dates, numbers and names the same way, so readers never stumble over the format and can focus on the story.

Where you’ve seen it

A data team adopts SQLFluff in CI with rules for lowercase keywords, leading commas, explicit aliases and no implicit joins. Pull requests that break the rules fail with a message pointing at the line. After a month, reviewers say they spend their time on logic instead of commenting on formatting.

Words you’ll hear

Formatter
A tool that rewrites SQL into a standard layout automatically.
Linter
A tool that flags rule violations such as SELECT * or implicit joins (SQLFluff).
Naming convention
Agreed patterns: customer_id for keys, created_at for timestamps, is_active for booleans.
Explicit join
JOIN … ON with the condition next to the table, rather than FROM a, b WHERE ….

Visual diagram

Loading interactive diagram

Theory & example queries

Layout and naming

Put each selected column on its own line, indent clauses consistently, and align JOIN … ON blocks so each table sits next to its join condition. Choose upper- or lowercase keywords and leading or trailing commas, and stick with the choice everywhere; the exact choice matters far less than consistency. Qualify every column with its table alias in queries with joins, and use aliases that mean something (orders o, customers c) rather than a, b, c.

Names should say what they hold: snake_case everywhere, tables named consistently (all plural or all singular), keys as <table>_id, timestamps with _at (created_at), dates with _date, booleans with is_ or has_, and amounts with their unit or currency where it's ambiguous (amount_inr, duration_ms). Avoid reserved words and abbreviations only the author understands.

A query following a typical guideQuery example
1Input dataStart from the source rows or state that the statement sees.
customers
3 rows
customers sample rows
idnameemailcity
1Mayamaya@example.comPune
2Raviravi@example.comDelhi
3Noornoor@example.comMumbai
orders
3 rows
orders sample rows
idcustomer_idstatusamountcoupon_code
1011paid249NULL
1022paid120WELCOME10
1031shipped89.5NULL
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  o.customer_id,3  count(*) AS order_count,4  sum(o.amount_inr) AS revenue_inr5FROM6  orders AS o7  INNER JOIN customers AS c ON c.customer_id = o.customer_id8WHERE9  o.created_at >= '2026-01-01'10  AND c.is_test_account = FALSE11GROUP BY12  o.customer_id
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/12
3OutputInspect the representative rows, affected-row count, plan, or command status.
Formatted query result2 sample rows
Formatted query result
customer_idorder_countrevenue_inr
17648250
29431700

Note: Formatting does not change results; values assume two qualifying non-test customers in the sample.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

(written one clause and one column per line in the editor).

Key takeaway: Consistent layout, qualified columns, names that describe their contents.

Structure, comments and enforcement

Prefer CTEs over nested subqueries for anything beyond one level, list columns explicitly instead of SELECT * so schema changes don't silently change results, and write explicit JOIN syntax, which keeps join conditions out of WHERE and makes a missing condition obvious. Group by column names rather than ordinal positions (GROUP BY 1, 2) in production code, since adding a column shifts the numbers; many teams allow ordinals in quick analysis only.

Comments should explain decisions the SQL can't: why test accounts are excluded, why the date boundary is half-open, which ticket defined the metric. Write the rules down on one page with before and after examples, then enforce them with a formatter and linter in the editor and in CI. SQLFluff supports most dialects and dbt templating; tools enforce style so reviewers don't have to.

A comment worth writing

A comment above the filter saying "exclude internal test accounts (see ANALYTICS-412); they inflate November signups by ~3%" tells the next reader why c.is_test_account = false is there and that it's deliberate.

Key takeaway: CTEs, explicit columns and joins, comments for why, tools for enforcement.
Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Team

Agree the rules

Choose keyword case, comma style, indentation, alias and naming rules, starting from an existing guide.

Focus at this step

lowercase keywords · leading commas · snake_case

What to watch at this step
Length
one page
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

A SQL style guide is a team's agreed rules for formatting and naming, so every query looks like it was written by the same person. Typical rules: one selected column per line, consistent keyword case, explicit JOIN … ON instead of comma joins, meaningful table aliases, CTEs instead of deep nesting, snake_case names with suffixes like _id, _at and is_, and no SELECT * in production code. A formatter and linter such as SQLFluff enforce the rules automatically.

Why it matters: Analytical SQL is read far more often than it's written: in code review, when a metric looks wrong, and when someone inherits a report. Consistent style makes those reads fast and makes mistakes such as a wrong join condition or a missing filter easier to see. Take-home assignments are judged on readability too.

When to reach for it

  • Shared analytics repositories and dbt projects
  • Take-home assignments and interview whiteboards
  • Any SQL that other people will maintain

When to avoid or be careful

  • Comma joins with conditions in WHERE
  • SELECT * in production queries
  • Aliases like a, b, t1 in long queries

Ways to keep SQL consistent

Written guide only
Best for: Small teams starting out

Strengths: Quick to agree.

Watch out: Depends on people remembering; drifts over time.

Formatter (sqlfmt, SQLFluff fix)
Best for: Layout and casing

Strengths: Fixes formatting automatically; no arguments.

Watch out: Can't judge naming or structure.

Linter in CI (SQLFluff)
Best for: Enforcing rules across a team

Strengths: Catches SELECT *, implicit joins, inconsistent aliases.

Watch out: Needs configuring per dialect; some rules need tuning.

Interview signals & numbers to know

When this topic comes up

  • “Make this query readable”
  • Take-home graded on code quality
  • “How does your team review SQL?”
  • dbt projects
  • Naming conventions

Benchmarks & rules of thumb

1 -
column per line in SELECT lists
_id · _at · is_ -
common name suffixes and prefixes
1 level -
of nesting before switching to CTEs

Common mistakes & follow-ups

Common interview mistakes

  • Mixing comma joins and explicit joins in one query, so a join condition hides in a long WHERE clause.
  • Using GROUP BY 1, 2, 3 in a production model, then adding a column and grouping by the wrong one.
  • Naming a column date or status_flag2, which tells the reader nothing about its contents.

Likely interviewer follow-ups

  • What rules would you put in a SQL style guide?
  • Why prefer explicit JOIN syntax to comma joins?
  • How would you enforce a style guide across a team?
Interview tip: In a take-home, consistent formatting, explicit columns, meaningful aliases and CTEs are noticed before any of your logic is. Spend five minutes tidying before you submit.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Writing Clean, Readable & Maintainable SQL Style Guides with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
Set Differences & Intersections (INTERSECT, EXCEPT)
Next topic
Understanding Relationships (One-to-One, One-to-Many, Many-to-Many)