Code your teammates can follow

How to write SQL and Python that a reviewer can check in ten minutes and a teammate can pick up next month. For students heading into data and analytics exams, take-homes and first jobs, including notebooks and Hex. The SQL runs in your browser on made-up data.

  1. Why it mattersThe reviewer and the teammate
  2. SQL styleTen rules, before and after
  3. Python styleNine habits for pandas
  4. Notebooks and HexThe order a reader needs
  5. Refactor thisThree exercises and a scorecard
  6. ChecklistOne page to print

1 Why it matters

Two people read your code more carefully than anyone else will.

Readable code lets someone else check your work quickly. Same query, both ways:

Hard to check

Show the result without running
Result: 2 rows
plancount(*)round(avg(x.c),1)
premium617.3
free87.6

Easy to check

Show the result without running
Result: 2 rows
planlistenersavg_full_plays
premium617.3
free87.6

Same result both ways: 2 rows, 3 columns.

Both are correct. Only the second can be checked in a minute: the reader sees what a play is, what one row means, and what each number is called.

This page covers style rules for SQL and Python, how to lay out a notebook or a Hex project, three refactoring exercises, and a checklist you can print. The SQL boxes run in your browser on the same made-up data as CTEs: write SQL in steps. The Python is shown as code to read. Every before and after pair was run, and gives the same result unless it says otherwise.

2 SQL style

Most rules have a BAD and a GOOD version that return the same result. Style changes how a query reads, never what it returns. If your tidy-up changes the result, you have changed the logic.

1. One clause per line

The eye finds SELECT, FROM, WHERE and GROUP BY down the left edge. Long lists of columns get one column per line.

BAD

Show the result without running
Result: 4 rows
categoryproductsavg_price
Outdoor384.83
Kitchen358.67
Games134.99
Books231.0

GOOD

Show the result without running
Result: 4 rows
categoryproductsavg_price
Outdoor384.83
Kitchen358.67
Games134.99
Books231.0

Same result both ways: 4 rows, 3 columns.

2. Pick a keyword case and stick to it

UPPERCASE keywords with lowercase names is the most common choice, and the one used across this site. Lowercase everything is fine too. Mixing is not: it looks like three people wrote it.

BAD

Show the result without running
Result: 7 rows
namecity
Aisling KeaneDublin
Aoife ByrneDublin
Ciara BrennanDublin
Fionn DalyDublin
Meabh CarrollDublin
Padraig HealyDublin
Saoirse DoyleDublin

GOOD

Show the result without running
Result: 7 rows
namecity
Aisling KeaneDublin
Aoife ByrneDublin
Ciara BrennanDublin
Fionn DalyDublin
Meabh CarrollDublin
Padraig HealyDublin
Saoirse DoyleDublin

Same result both ways: 7 rows, 2 columns.

SQLite does not care about case in names, so both run. A reader does.

3. Names that say what they hold

Step names and column names are the documentation nobody has to write separately. t1, cnt and x make the reader work it out every time.

BAD

Show the result without running
Result: 5 rows
titlecnt
Blue Hour1
Ferry Home1
Kite Weather1
Night Bus1
Wild Garlic1

GOOD

Show the result without running
Result: 5 rows
titleskips
Blue Hour1
Ferry Home1
Kite Weather1
Night Bus1
Wild Garlic1

Same result both ways: 5 rows, 2 columns.

With the bad version you have to read the WHERE to learn the count is skips. With the good one the name tells you.

4. Aliases that mean something

a, b, c force the reader to scroll up for every column. Use a short form of the table name: o for orders, p for products, c for customers.

BAD

Show the result without running
Result: 6 rows
nameunits
Cookbook: Brown Bread6
Cast Iron Pan5
Atlas of Islands2
Rain Jacket2
Trail Runner Shoes2
Novel: Low Tide1

GOOD

Show the result without running
Result: 6 rows
nameunits
Cookbook: Brown Bread6
Cast Iron Pan5
Atlas of Islands2
Rain Jacket2
Trail Runner Shoes2
Novel: Low Tide1

Same result both ways: 6 rows, 2 columns.

Write AS before each alias, too. It is optional, but it makes the alias easy to spot.

5. Leading or trailing commas: choose one

Both are fine. Leading commas make it easy to comment out a line and see a missing comma. Trailing commas read more like normal writing. Teams pick one; follow your team.

Trailing (used on this site)

SELECT customer_id,
       name,
       city
FROM customers;

Leading

SELECT customer_id
     , name
     , city
FROM customers;

6. Say the join type, and use ON

A comma between tables with the match in WHERE is an old style. It hides the join among the filters, and if you forget the WHERE line you get every row times every row. Write INNER JOIN or LEFT JOIN, with ON.

BAD

Show the result without running
Result: 7 rows
namematch_datehome_goalsaway_goals
Riverside Rovers2024-08-0322
Northside Wanderers2024-08-1712
Northside Wanderers2024-08-1701
Northside Wanderers2024-08-2410
Riverside Rovers2024-08-3121
Riverside Rovers2024-09-0711
Riverside Rovers2024-09-1421

GOOD

Show the result without running
Result: 7 rows
namematch_datehome_goalsaway_goals
Riverside Rovers2024-08-0322
Northside Wanderers2024-08-1712
Northside Wanderers2024-08-1701
Northside Wanderers2024-08-2410
Riverside Rovers2024-08-3121
Riverside Rovers2024-09-0711
Riverside Rovers2024-09-1421

Same result both ways: 7 rows, 4 columns.

Plain JOIN means INNER JOIN. Writing INNER tells the reader you chose it, not that you forgot about LEFT.

7. Comment the purpose and the grain

One line on what question the query answers. One line on what a row of the result means. A short grain comment on each CTE. Do not comment what the code already says: -- select the name wastes a line.

BAD

Show the result without running
Result: 4 rows
namen
Larkspur Freight2
Willowby Insurance2
Kettlebrook Bank1
Pixelmoor Games1

GOOD

Show the result without running
Result: 4 rows
namedeclined_offers
Larkspur Freight2
Willowby Insurance2
Kettlebrook Bank1
Pixelmoor Games1

Same result both ways: 4 rows, 2 columns.

8. No SELECT * in the final output

SELECT * is fine while you explore and inside a quick check. In anything you hand over, list the columns. The reader sees exactly what comes back, and a new column added to the table later does not sneak into your report.

BAD

Show the result without running
Result: 1 row
offer_idcompany_idjob_familylevelbase_salaryoffered_ataccepted_atstatus
310ProductMid610002023-01-16NULLpending

GOOD

Show the result without running
Result: 1 row
offer_idcompany_idjob_familylevelbase_salaryoffered_at
310ProductMid610002023-01-16

Not the same columns on purpose: the good one drops accepted_at and status, which tell you nothing for a pending offer.

9. No magic numbers

A bare 30 or 0.15 in the middle of a query is a question the reader has to answer. Name it. In SQL, a one-row params CTE at the top does the job; in Hex, an input parameter does.

BAD

Show the result without running
Result: 5 rows
listener_idplays
627
117
1117
316
1216

GOOD

Show the result without running
Result: 5 rows
listener_idplays
627
117
1117
316
1216

Same result both ways: 5 rows, 2 columns.

Longer, yes. But the rules are in one place, with names, and changing 30 to 60 is a one-line edit. For a short exam answer, a comment next to the number is a fair middle ground.

10. Qualify every column once there is a join

When two tables are in play, write o.customer_id, not customer_id. If the column is only in one table it still runs, but the reader has to check which. If it is in both, the query fails, or worse, picks the one you did not mean.

BAD

Show the result without running
Result: 8 rows
nameorder_datequantity
Eoin Murphy2025-01-291
Aoife Byrne2025-02-051
Ciara Brennan2025-02-071
Oisin Ryan2025-04-011
Fionn Daly2025-04-031
Sinead Moran2025-04-141
Grainne Lynch2025-06-012
Ciara Brennan2025-06-111

GOOD

Show the result without running
Result: 8 rows
nameorder_datequantity
Eoin Murphy2025-01-291
Aoife Byrne2025-02-051
Ciara Brennan2025-02-071
Oisin Ryan2025-04-011
Fionn Daly2025-04-031
Sinead Moran2025-04-141
Grainne Lynch2025-06-012
Ciara Brennan2025-06-111

Same result both ways: 8 rows, 3 columns.

Which table has name? Products has one too. Join products in later and the bad version breaks with ambiguous column name.

Order of the final query, for reference: purpose comment, params, cleaning steps, aggregate steps, final SELECT with listed columns, ORDER BY. CTEs: write SQL in steps covers how to build and test the steps.

3 Python style

The examples use pandas on the same made-up offers table (offer_id, company_id, job_family, level, base_salary, offered_at, accepted_at, status). Assume it is already loaded. Each BAD and GOOD pair was run and gives the same result, except rule 6, where the bad version is broken on purpose.

1. Names that say what they hold

df2, x, temp tell the reader nothing. A name should answer what is in here. Use snake_case. Plural for collections.

BAD

d = offers[offers["status"] == "accepted"]
x = d.groupby("job_family")["base_salary"].mean()
x2 = x[x > 50000]

GOOD

accepted = offers[offers["status"] == "accepted"]
avg_salary_by_family = accepted.groupby("job_family")["base_salary"].mean()
well_paid_families = avg_salary_by_family[avg_salary_by_family > 50000]

2. Constants at the top, in capitals

Thresholds, file names and dates belong in one place at the top, named in CAPITALS so everyone knows not to change them halfway down.

BAD

recent = offers[offers["offered_at"] >= "2024-01-01"]
senior = recent[recent["base_salary"] >= 60000]
print(len(senior))

GOOD

START_DATE = "2024-01-01"   # the period the question asks about
HIGH_SALARY = 60_000         # threshold from the brief

recent = offers[offers["offered_at"] >= START_DATE]
high_paid = recent[recent["base_salary"] >= HIGH_SALARY]
print(len(high_paid))

60_000 is the same number as 60000. The underscore is only there to help you read it.

3. Small functions with one job, a docstring and light type hints

If you can describe a block of code as clean the offers or median salary per family, it wants to be a function with that name. A one-line docstring says what it returns. Type hints on the arguments and return value are enough; you do not need them on every variable.

BAD

o = offers.drop_duplicates(subset=["company_id", "job_family", "level", "base_salary", "offered_at"])
o = o.dropna(subset=["base_salary"])
o = o[o["status"] == "accepted"]
result = o.groupby("job_family")["base_salary"].median()

GOOD

DUPLICATE_KEY = ["company_id", "job_family", "level", "base_salary", "offered_at"]


def clean_offers(offers: pd.DataFrame) -> pd.DataFrame:
    """Drop duplicate offers and offers with no salary."""
    return (
        offers
        .drop_duplicates(subset=DUPLICATE_KEY)
        .dropna(subset=["base_salary"])
    )


def median_salary_by_family(offers: pd.DataFrame) -> pd.Series:
    """Median accepted salary for each job family."""
    accepted = offers[offers["status"] == "accepted"]
    return accepted.groupby("job_family")["base_salary"].median()


result = median_salary_by_family(clean_offers(offers))

Longer, and better. Each function can be tested alone, and the last line reads like the question.

4. No copy-paste blocks

When you see the same three lines three times with one word changed, write it once and loop, or let groupby do it. Copies drift: you fix a bug in one and not the others.

BAD

data = offers[offers["job_family"] == "Data"]
data_avg = data["base_salary"].mean()
design = offers[offers["job_family"] == "Design"]
design_avg = design["base_salary"].mean()
product = offers[offers["job_family"] == "Product"]
product_avg = product["base_salary"].mean()
avgs = {"Data": data_avg, "Design": design_avg, "Product": product_avg}

GOOD

FAMILIES = ["Data", "Design", "Product"]

avgs = (
    offers[offers["job_family"].isin(FAMILIES)]
    .groupby("job_family")["base_salary"]
    .mean()
    .to_dict()
)

5. f-strings for text

Gluing strings together with + and str() is hard to read and easy to break. An f-string shows the sentence as it will print. The part after the colon formats the number.

BAD

for family, avg in offers.groupby("job_family")["base_salary"].mean().items():
    print("Average for " + family + ": " + str(int(round(avg))))

GOOD

avg_by_family = offers.groupby("job_family")["base_salary"].mean()
for family, avg in avg_by_family.items():
    print(f"Average for {family}: {avg:.0f}")

Want commas in big numbers? {avg:,.0f} prints 52,333.

6. Set values with .loc, never with chained brackets

df[mask]["col"] = value picks rows, makes a copy, then sets the value on the copy. Your table does not change. Older pandas warns; pandas 3 never changes the original. Use .loc[rows, column] in one go, or build the whole column at once.

BAD: changes nothing

offers["band"] = "standard"
offers[offers["base_salary"] >= 60000]["band"] = "high"
high_count = (offers["band"] == "high").sum()

GOOD

offers["band"] = "standard"
offers.loc[offers["base_salary"] >= 60000, "band"] = "high"
high_count = (offers["band"] == "high").sum()

The bad version runs with no error and high_count is 0. That is why it is dangerous. The same trap hits accepted = offers[mask] followed by accepted["x"] = ...: add .copy() when you take a slice you plan to change.

7. Method chains: one step per line

A chain in brackets, one method per line, reads like the CTE steps in SQL. Four throwaway names (df2 to df5) become one good one.

BAD

df2 = offers[offers["status"] == "accepted"]
df3 = df2.dropna(subset=["base_salary"])
df4 = df3.groupby("level", as_index=False)["base_salary"].median()
df5 = df4.sort_values("base_salary", ascending=False)

GOOD

median_by_level = (
    offers
    .query("status == 'accepted'")
    .dropna(subset=["base_salary"])
    .groupby("level", as_index=False)["base_salary"]
    .median()
    .sort_values("base_salary", ascending=False)
)

Keep chains to about six steps. Longer than that, split at a point you can name.

8. Asserts as sanity checks

An assert stops the notebook with a message if something you believe is not true. Put them after loading and after every join. They are the Python version of the row-count checks in the CTE guide.

merged = offers.merge(companies, on="company_id", how="left")

assert offers["offer_id"].is_unique, "offer_id should be unique"
assert len(merged) == len(offers), "the join changed the row count"
assert merged["name"].notna().all(), "an offer has no matching company"
assert offers["base_salary"].dropna().between(10_000, 500_000).all(), "salary out of range"

If an assert fails in a take-home, do not delete it. Write a comment on what you found and how you handled it. That is the kind of thing a reviewer is looking for.

9. PEP 8 basics

PEP 8 is the style guide most Python follows. Read it here. You do not need to learn it all. These cover most of what a reviewer notices:

A formatter such as black or ruff format fixes most of this for you. Many teams run one on every save.

4 Notebooks and Hex: lay it out for the reader

A notebook is read top to bottom by someone who did not watch you build it. Lay it out in the order they need, not the order you worked in.

The order you worked in

  1. Codeimport pandas as pd
  2. Codedf = pd.read_csv(...)
  3. Codedf.head()
  4. Codedf2 = df[df.x > 0]
  5. Codedf.describe() # old, unused
  6. Codeimport matplotlib...
  7. Codeplt.plot(...) # no title
  8. Codedf3 = ... # does it still run?
  9. Textsome results: 52k

The order a reader needs

  1. TextTitle and question. What are we answering, for whom, and when the data was pulled.
  2. TextFindings. Three bullets with the numbers. Written last, placed first.
  3. TextAssumptions. How you handled duplicates, missing values, dates and ties.
  4. CodeSetup. Imports and constants.
  5. CodeLoad. Read the data. Nothing else.
  6. CodeCheck. Shape, types, missing values, duplicates, asserts.
  7. CodeClean. One function or one chain, named.
  8. CodeAnalyse. One question per cell, with a markdown line above it.
  9. CodeChart. Title that states the finding, labelled axes.
  10. TextLimits and next steps. What you would check with more time.
A notebook as a list of cells. Text cells in cream, code cells in white.

Rules for any notebook

Hex in particular

A good check cell

# Check: what did we load?
print(f"{len(offers)} offers, {offers['offer_id'].nunique()} unique IDs")
print(offers.isna().sum().loc[lambda s: s > 0])
print(offers["status"].value_counts())

dupes = offers.duplicated(subset=["company_id", "job_family", "level", "base_salary", "offered_at"])
print(f"{dupes.sum()} exact duplicate offer(s)")

On the practice data this prints 45 offers, missing values in base_salary and accepted_at, and one duplicate. Each line becomes a sentence in the Assumptions cell.

5 Refactor this

Three pieces of working but messy code. Rewrite each one, then open the model answer. Yours does not have to match it word for word; it should be just as easy to check.

Shop Exercise 1: SQL

This runs and gives the right answer. Rewrite it in the box using the ten rules, and press Check: your version must still give the same result. Check compares values, not column names, so name them well.

  1. Refactor the query below without changing its result.

    Hint

    Start with the comma joins: turn them into INNER JOINs with ON. Then name the count and the sum, give the aliases meaning, and lift the price filter into a step.

    The original (for comparison)
Model clean version
Show the result without running
Result: 10 rows
nameordersnet_spend
Ciara Brennan3172.5
Aoife Byrne4167.99
Saoirse Doyle3163.5
Cian Walsh3122.0
Sinead Moran4-309.0
Orla Kavanagh3-528.5
Tadhg Burke3-560.0
Fionn Daly3-702.0
Niamh Kelly4-1216.0
Roisin Quinn3-1359.51

Same result as the original, row for row.

The planted wrong answer most people hit: dropping the COALESCE while tidying. Orders with no discount then give NULL, and SUM skips them. Tidying must not change logic.

Jobs Exercise 2: Python

Median accepted salary by level for offers made in 2024. Copy it into a notebook and tidy it. Look for: names, a constant, copy-paste, string gluing, and a function waiting to get out.

import pandas as pd
df = pd.read_csv("offers.csv")
df2 = df[df['status']=='accepted']
df2 = df2.dropna(subset=['base_salary'])
df3 = df2[df2['offered_at']>='2024-01-01']
a=df3[df3['level']=='Junior']['base_salary'].median()
b=df3[df3['level']=='Mid']['base_salary'].median()
c=df3[df3['level']=='Senior']['base_salary'].median()
print('Junior: '+str(a))
print('Mid: '+str(b))
print('Senior: '+str(c))
Model clean version
import pandas as pd

OFFERS_FILE = "offers.csv"
START_DATE = "2024-01-01"     # the question asks about 2024 offers
LEVELS = ["Junior", "Mid", "Senior"]


def accepted_offers_since(offers: pd.DataFrame, start: str) -> pd.DataFrame:
    """Accepted offers with a salary, made on or after start."""
    return offers[
        (offers["status"] == "accepted")
        & offers["base_salary"].notna()
        & (offers["offered_at"] >= start)
    ]


offers = pd.read_csv(OFFERS_FILE)
recent = accepted_offers_since(offers, START_DATE)
median_by_level = recent.groupby("level")["base_salary"].median()

for level in LEVELS:
    print(f"{level}: {median_by_level[level]}")

Both print the same three lines:

Junior: 42000.0
Mid: 55750.0
Senior: 71250.0

App Exercise 3: a notebook

A take-home asked: which signup channel brings the users most likely to subscribe? Here are the cells as submitted, in order. Put them in the order a reviewer needs, and say which to cut.

  1. Codeimport pandas as pd, matplotlib.pyplot as plt
  2. Codeevents = pd.read_csv('events.csv')
  3. Codeevents.head()
  4. Codeusers = pd.read_csv('app_users.csv')
  5. Codeusers.head()
  6. Codem = users.merge(events) # rows went up?
  7. Codeplt.bar(...) # chart, no title
  8. Codesubs = events[events.event_name == 'subscribe']
  9. TextFriend referrals convert best
  10. Code# old attempt, errors: KeyError
  11. Coderate = subs.groupby(...)...
Model order
  1. Text: the question, and a one-line answer: which referrer converts best, with the rate.
  2. Text: assumptions. Users with no referrer grouped as none. Counted people, not events (one event is logged twice).
  3. Code: imports and constants.
  4. Code: load both files.
  5. Code: check: row counts, missing referrers, duplicate events, with asserts.
  6. Code: one row per user with a subscribed flag. Assert the row count equals the number of users.
  7. Code: subscribe rate per referrer.
  8. Code: chart with a title that states the finding.
  9. Text: limits: small numbers per group, so treat differences with care.

Cut: both .head() cells, the old cell that errors, and the merge that multiplies rows (replace it with the one-row-per-user step). Fix: the findings cell moves to the top and says the rate, not just the winner.

The reviewer's scorecard

This is roughly what a reviewer runs through. Score your own work before you send it. Tick what is true.

0 of 12. Ten or more and a reviewer can trust your work quickly.

6 The one-page checklist

Print it, or keep it open next to your next take-home.

Code your teammates can follow: checklist

SQL

  • Purpose and grain comment at the top
  • One clause per line, one keyword case
  • CTEs named for what they hold, grain comment on each
  • Aliases that mean something, with AS
  • INNER or LEFT JOIN with ON, never commas
  • Every column qualified once there is a join
  • Thresholds named in a params step or commented
  • Columns listed in the final SELECT
  • Row counts checked after each join

Python

  • Names that say what they hold, snake_case
  • Constants at the top in CAPITALS
  • Small functions, one job, docstring, type hints
  • No copy-paste: loop or groupby
  • f-strings for text
  • .loc to set values, .copy() on slices you change
  • Method chains, one step per line
  • Asserts after loading and after joins
  • Formatter run (black or ruff)

Notebook or Hex

  • Title and question at the top
  • Findings next, with numbers
  • Assumptions written down
  • Load, check, clean, analyse, chart
  • One idea per cell, outputs named
  • Dead cells deleted
  • Charts titled with the finding
  • Restart and run all (Hex: Run all)
  • Read it once as the reviewer

davidcarr.me/guides/readable-code

▸ Where next