SQL and Python practice

Eight take-home style tasks on one made-up pay dataset. Each asks for some SQL, then some Python. Try it first, then open the worked answer.

New to SQL? Start with SQL from zero. New to Python? Start with Python from zero. These tasks assume you know a SELECT and a print, and explain everything past that. Want to see one take-home worked from brief to write-up first? Try A take-home, start to finish.

How to work a take-home

A take-home is a small data job you do on your own time: a brief, some files, a deadline. The checking matters as much as the code. A good routine:

  1. Read the brief twice. Write down, in one sentence, the question you are answering.
  2. Write down questions and assumptions. "Pay means base salary." "2025 means the date the offer was made." If you cannot ask, state the assumption and carry on.
  3. Check the data first. Row counts, missing values (nulls), duplicate rows, and values that cannot be real. Every task below assumes you did this once (Task 1).
  4. Keep SQL readable. Start each query with a comment on its purpose and its grain -- what one row of the result stands for. Use named steps (WITH clean AS (...)) instead of one giant query.
  5. State your caveats. Small samples, missing data, anything you removed and why.
  6. One headline per chart. The chart title says the finding, in plain words.
  7. Finish with three bullets of findings. What you found, how sure you are, what you would check next.

The data

Made-up data for practice. Every company, offer and number is invented. It describes job offers made by 42 fictional employers across 2024 and 2025. All pay is in euro, per year. It is messy on purpose, in the ways real data is messy.

offers.csv companies.csv roles.csv offers_2026.json make_data.py
FileOne row isColumns
offers.csvone job offer (689 rows)offer_id, company_id, job_family, level (Junior, Mid, Senior, Lead), base_salary, equity_value (per year), offered_at, accepted_at (empty if not accepted), status (accepted or declined)
companies.csvone employer (42 rows)company_id, name, industry, city, size_band
roles.csvone company, job family and quarter (379 rows)company_id, job_family, quarter (like 2025-Q3), open_roles
offers_2026.jsonone offer from a "new system" in Q1 2026 (60 offers, nested)see Task 2

make_data.py is the script that made the files. It uses a fixed random seed, so running it gives exactly the same data. Reading it will spoil some of the tasks.

Get set up

Every solution uses DuckDB, a small free database that runs inside Python and can read CSV and JSON files directly, plus pandas for tables and matplotlib for charts. Pick one of three ways to run them. Each one ends with the same setup code, which loads the three CSV files into tables called offers, companies and roles.

1. On your own computer, from Terminal
  1. Install Python 3 from python.org if you do not have it. On a Mac, open Terminal (press Cmd+Space, type Terminal). On Windows, open PowerShell and type py wherever you see python3 below.
  2. Make a folder for the work and move into it:
    mkdir pay-practice
    cd pay-practice
  3. Download the four data files above into that folder.
  4. Make a private Python environment for this folder, switch it on, and install the three tools. The first line makes a folder called .venv that keeps these installs separate from everything else on your computer:
    python3 -m venv .venv
    source .venv/bin/activate          # Windows: .venv\Scripts\activate
    pip install duckdb pandas matplotlib
  5. Check DuckDB can read a CSV. This runs one query and prints the result:
    python3 -c "import duckdb; print(duckdb.sql(\"SELECT COUNT(*) FROM 'offers.csv'\"))"
    You should see a little table with 689 in it. DuckDB treats the file name in quotes as a table, which is why FROM 'offers.csv' works.
  6. For each task, make a file such as task1.py in any text editor. Paste in the setup code below, then the task's Python. Run it with python3 task1.py. Charts open in a window and are also saved as PNG files in the folder. Next time, just cd pay-practice and source .venv/bin/activate again.
2. In a free online notebook (Google Colab)
  1. Go to colab.research.google.com, sign in with a Google account and start a new notebook. A notebook is a page of cells: you type code into a cell and press Shift+Enter to run it. The result appears under the cell.
  2. Open the files panel (the folder icon on the left) and upload the four data files. They land in the notebook's working folder, so 'offers.csv' finds them. Uploaded files are deleted when the session ends, so upload again next time.
  3. In the first cell, make sure DuckDB is installed (the ! runs a Terminal command from the notebook):
    !pip install duckdb
  4. In the next cell, paste the setup code below and run it. Then use one cell for each task's Python. Charts show under the cell.
3. Doing a take-home in Hex

Hex is a data notebook in the browser, used by many data teams. It mixes Python cells, SQL cells and text cells, and turns the result into a page you can share. Some take-homes are sent as a Hex project. Menu names in Hex change from time to time, so the steps below describe what to look for rather than exact buttons.

  1. Create a project. From your Hex home, start a new project. It opens as a notebook.
  2. Upload the files. Use the files panel in the project to upload the CSV and JSON files. They are then readable from Python by file name.
  3. Load the files in a Python cell. Add a Python cell and load each CSV into a dataframe (a table in Python). pandas is enough here:
    import pandas as pd
    import matplotlib.pyplot as plt
    
    offers    = pd.read_csv("offers.csv", parse_dates=["offered_at", "accepted_at"])
    companies = pd.read_csv("companies.csv")
    roles     = pd.read_csv("roles.csv")
    parse_dates tells pandas those two columns are dates, so the date functions in the SQL work.
  4. Query the dataframes in a SQL cell. Add a SQL cell and use its source picker to choose dataframes rather than a database connection. Hex runs SQL on dataframes with DuckDB, so the DuckDB SQL on this page works as written: FROM offers means the offers dataframe you just made. Give the cell's result a name (for example summary). That result is a new dataframe the next cells can use.
  5. Do the Python part in a Python cell. Use the named result directly. Skip the query = """...""" and duckdb.sql(query).df() lines in the solutions: in Hex, the SQL cell has already made that dataframe. matplotlib charts show under the cell.
  6. Write the headline and caveats in text cells. One text cell above each chart for the headline, one at the end for your three findings and caveats.
  7. Present it in the app view. Hex has a separate app view where you choose which cells show. Show the text, tables and charts, hide the code, and share that. The reviewer can still open the notebook to see your working.

For the JSON task, flatten the file in a Python cell first (Task 2 shows how), then point the SQL cell at the flat dataframe.

The setup code (every task starts with this)

Run it once per session, before any task. It loads each CSV through DuckDB into a pandas dataframe. After that, SQL can use offers, companies and roles like tables, because DuckDB can query a dataframe by its name.

import duckdb                     # runs SQL on files and dataframes
import pandas as pd               # tables in Python
import matplotlib.pyplot as plt   # charts

pd.set_option("display.width", 120)        # print wide tables on one line
pd.set_option("display.max_columns", 20)   # and show every column

# Load each CSV into a dataframe. DuckDB guesses the column types
# (numbers, dates, text) and turns empty cells into NULL.
offers    = duckdb.sql("SELECT * FROM 'offers.csv'").df()
companies = duckdb.sql("SELECT * FROM 'companies.csv'").df()
roles     = duckdb.sql("SELECT * FROM 'roles.csv'").df()

In each task, Part A is SQL. To run it from Python, paste the query between the triple quotes of query = """ ... """. Triple quotes let a piece of text run over many lines. duckdb.sql(query).df() then runs it and hands back a dataframe.

Other databases. The SQL is DuckDB's. Most of it is standard. The parts that differ: MEDIAN(x) is PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY x) in PostgreSQL and Snowflake, and APPROX_QUANTILES(x, 2)[OFFSET(1)] in BigQuery. date_trunc('quarter', d) is the same in PostgreSQL and Snowflake, and DATE_TRUNC(d, QUARTER) in BigQuery. QUARTER(d) is EXTRACT(QUARTER FROM d) almost everywhere. GROUP BY ALL works in DuckDB, Snowflake and Databricks; elsewhere, list the columns. Reading a file with FROM 'offers.csv' or read_json_auto is DuckDB only.

Task 1 · Warm-up · data checks

Can we trust this data?

"Here's two years of offer data from our recruiting system. Before anyone builds a report on it, can you tell me if it's usable? Anything odd we should know about?"

Part A -- SQL

In one query, count the rows and the distinct offer IDs, count missing values in level and accepted_at, and find the smallest, middle and largest base salary and the date range. Then count offers by status.

Part B -- Python

List the duplicate rows and any salary no real offer would have. Decide a cleaning rule you will use from now on. Plot the salaries to show why the odd values matter.

A good answer includes

In Hex: load the CSVs in a Python cell, put Part A's queries in SQL cells on dataframes and name the first result summary. The Python checks work unchanged on the offers dataframe.

Show the worked answer

Part A -- the SQL

-- Purpose: a first look at the offers table before any analysis.
-- Grain of the result: one row for the whole table.
SELECT
    COUNT(*)                       AS row_count,
    COUNT(DISTINCT offer_id)       AS distinct_offers,
    COUNT(*) - COUNT(level)        AS missing_level,
    COUNT(*) - COUNT(accepted_at)  AS missing_accepted_at,
    MIN(base_salary)               AS min_base,
    MEDIAN(base_salary)            AS median_base,
    MAX(base_salary)               AS max_base,
    CAST(MIN(offered_at) AS DATE)  AS first_offer,
    CAST(MAX(offered_at) AS DATE)  AS last_offer
FROM offers
  • COUNT(*) counts every row. COUNT(DISTINCT offer_id) counts each ID once. If the second is smaller, some offers appear more than once.
  • COUNT(level) counts only rows where level has a value, so COUNT(*) - COUNT(level) is the number of missing levels. Same trick for accepted_at.
  • MIN, MEDIAN and MAX give the range. The median is the middle value when you sort them -- half the offers are above it, half below.
  • CAST(... AS DATE) turns a date-and-time into a plain date, so the output is easier to read.

What it returns

 row_count  distinct_offers  missing_level  missing_accepted_at  min_base  median_base  max_base first_offer last_offer
       689              686              5                  147        15      79500.0   1500000  2024-01-01 2025-12-27
-- Purpose: how many offers in each status?
-- Grain of the result: one row per status.
SELECT status, COUNT(*) AS offers
FROM offers
GROUP BY status
ORDER BY offers DESC

What it returns

  status  offers
accepted     542
declined     147

Already a story: 689 rows but 686 distinct offers, so 3 offers appear twice. A salary of €15 and one of €1,500,000 cannot be real. The 147 missing accepted_at values match the 147 declined offers exactly, so those are expected, not errors.

Part B -- the Python

query = """
-- paste the Part A query here
"""
summary = duckdb.sql(query).df()      # run Part A, get a dataframe back
print(summary.T)                      # .T flips it: one line per check

# 1. Duplicates: rows that appear more than once, every column the same.
dupes = offers[offers.duplicated(keep=False)]
print("\nDuplicate rows:", len(dupes))
print(dupes[["offer_id", "company_id", "job_family", "base_salary"]])

# 2. Outliers: salaries no real offer would have.
odd = offers[(offers["base_salary"] < 20000) | (offers["base_salary"] > 400000)]
print("\nImpossible salaries:")
print(odd[["offer_id", "job_family", "level", "base_salary"]])

# 3. Missing level.
print("\nRows with no level:", offers["level"].isna().sum())

# 4. The cleaning rule we will use in every later task.
clean = offers.drop_duplicates()
clean = clean[clean["base_salary"].between(20000, 400000)]
print("\nRows before cleaning:", len(offers), "| after:", len(clean))

# 5. A chart of the raw salaries, to see what one bad row does.
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.hist(offers["base_salary"], bins=60, color="#4A6FA5")
ax.set_title("One mistyped salary squashes every real offer into one bar", loc="left")
ax.set_xlabel("Base salary (euro)")
ax.set_ylabel("Number of offers")
ax.annotate("€1,500,000 -- an entry error", xy=(1500000, 1), xytext=(900000, 250),
            arrowprops=dict(arrowstyle="->"))
ax.ticklabel_format(style="plain", axis="x")
ax.spines[["top", "right"]].set_visible(False)
plt.savefig("t1.png", dpi=150, bbox_inches="tight")
plt.show()
  1. summary.T flips the one-row result on its side, so each check gets its own line.
  2. offers.duplicated(keep=False) marks every row that has an exact twin. keep=False marks both copies, so you can see the pair. Putting that inside offers[...] keeps only the marked rows.
  3. The | means "or". The line keeps rows where the salary is under €20,000 or over €400,000. Both limits are far outside any real offer here: the next highest salary is €239,500.
  4. .isna().sum() counts missing values: isna() gives True or False for each row, and True counts as 1.
  5. drop_duplicates() removes the second copy of each twin. .between(20000, 400000) keeps sensible salaries. Every later task applies this same rule in SQL: SELECT DISTINCT * and WHERE base_salary BETWEEN 20000 AND 400000.
  6. The chart: plt.subplots makes a blank chart, ax.hist draws a histogram (bars counting how many offers fall in each salary range), ax.annotate adds the arrow and note, ticklabel_format stops matplotlib writing the axis in scientific notation, and savefig saves the PNG.

What it prints

                                       0
row_count                            689
distinct_offers                      686
missing_level                          5
missing_accepted_at                  147
min_base                              15
median_base                      79500.0
max_base                         1500000
first_offer          2024-01-01 00:00:00
last_offer           2025-12-27 00:00:00

Duplicate rows: 6
    offer_id company_id       job_family  base_salary
40     O0041       C020   Data Scientist        59000
41     O0041       C020   Data Scientist        59000
201    O0201       C033  Product Manager       153000
202    O0201       C033  Product Manager       153000
400    O0399       C008     Data Analyst        95000
401    O0399       C008     Data Analyst        95000

Impossible salaries:
    offer_id       job_family   level  base_salary
29     O0030  Product Manager     Mid           15
376    O0375     Data Analyst  Senior      1500000

Rows with no level: 5

Rows before cleaning: 689 | after: 684
Histogram of base salaries: almost all offers sit under 250,000 euro, with one lone offer at 1,500,000 euro that stretches the axis.

Headline: The offer data is usable after two fixes: drop 3 duplicated rows and 2 impossible salaries. That leaves 684 offers from January 2024 to December 2025.

Caveats: 5 offers have no level; leave them in for totals and out of anything split by level. Declined offers have no acceptance date by design.

Task 2 · Easy · JSON

Flatten a JSON export

"We've moved to a new recruiting system. Its first export, for Q1 2026, came out as JSON. Can you tell me what an accepted offer is worth in total -- base, equity and bonus -- by job family? And which perks come up most?"

JSON from zero

JSON is a text format for data, used by most websites and apps to pass data around. Here is the first offer in offers_2026.json:

{
  "offer_id": "N001",
  "job_family": "Software Engineer",
  "level": "Lead",
  "status": "accepted",
  "offered_at": "2026-03-01",
  "company": {
    "id": "C035",
    "name": "Yarrowby Payroll",
    "city": "Amsterdam"
  },
  "comp": {
    "base": 137000,
    "equity": 26000,
    "bonus": 7000
  },
  "perks": [
    "health cover",
    "learning budget",
    "pension"
  ]
}

A table needs one value per cell. company holds three values and perks holds a varying number, so before you can count or average, you flatten: each nested key becomes its own column (company.name, comp.base). A list either becomes a count, or gets spread out to one row per item -- which changes the grain from one row per offer to one row per offer per perk.

Part A -- SQL

Use DuckDB to read the JSON file, flatten it into one row per offer with total comp, and count how often each perk appears in accepted offers.

Part B -- Python

Do the same flattening in pandas with json.load and pd.json_normalize. For accepted offers, average base, equity and bonus by job family, count the perks, and chart the parts of pay.

A good answer includes

In Hex: upload the JSON, then flatten it in a Python cell with pd.json_normalize and rename the dotted columns. Point a SQL cell on dataframes at the flat dataframe. Do the perk count in Python with explode.

Show the worked answer

Part A -- the SQL

This part runs straight on the file, so it does not need the setup code. Run it from Python with duckdb.sql(query).df() as usual.

-- Purpose: flatten the nested JSON into a normal table.
-- Grain of the result: one row per offer.
SELECT
    offer_id,
    job_family,
    level,
    status,
    company.name   AS company_name,   -- dot notation reaches inside "company"
    company.city   AS city,
    comp.base      AS base,
    comp.equity    AS equity,
    comp.bonus     AS bonus,
    comp.base + comp.equity + comp.bonus AS total_comp,
    len(perks)     AS perk_count     -- how many items are in the list
FROM read_json_auto('offers_2026.json')
ORDER BY offer_id
LIMIT 5
  • read_json_auto('offers_2026.json') reads the file and works out its shape. Each nested object becomes a struct column: one column holding several named fields.
  • company.name reaches inside the company struct for its name field. AS company_name names the new column.
  • len(perks) counts the items in the list.
  • LIMIT 5 shows just the first five rows while you check the shape. Drop it to get all 60.

What it returns

offer_id        job_family  level   status          company_name      city   base  equity  bonus  total_comp  perk_count
    N001 Software Engineer   Lead accepted      Yarrowby Payroll Amsterdam 137000   26000   7000      170000           3
    N002 Software Engineer    Mid accepted        Thimble Health    Galway  90500   25000  13500      129000           0
    N003    Data Scientist    Mid accepted Pebblebrook Insurance    Dublin  90000       0      0       90000           3
    N004   Product Manager   Lead accepted        Juniper Ledger    Lisbon 148500       0  22500      171000           2
    N005      Data Analyst Junior declined     Zephyr Lane Bikes    Lisbon  49500       0      0       49500           3
-- Purpose: which perks come up most often in accepted offers?
-- Grain of "one_row_per_perk": one row per offer per perk.
-- Grain of the result: one row per perk.
WITH one_row_per_perk AS (
    SELECT offer_id, UNNEST(perks) AS perk   -- a list of 3 becomes 3 rows
    FROM read_json_auto('offers_2026.json')
    WHERE status = 'accepted'
)
SELECT perk, COUNT(*) AS offers_with_perk
FROM one_row_per_perk
GROUP BY perk
ORDER BY offers_with_perk DESC, perk
  • UNNEST(perks) turns each list into rows: an offer with three perks becomes three rows, an offer with none disappears. The WITH block names that result one_row_per_perk.
  • Then a normal GROUP BY counts rows per perk. Sorting by perk as well settles ties in a fixed order.

What it returns

           perk  offers_with_perk
        pension                22
         remote                22
     relocation                18
learning budget                17
   health cover                15

Part B -- the Python

import json

# 1. Read the file into Python. json.load gives a list of dictionaries.
with open("offers_2026.json") as f:
    raw = json.load(f)
print("Offers in the file:", len(raw))
print("Keys in the first offer:", list(raw[0].keys()))

# 2. Flatten: json_normalize turns each nested key into its own column,
#    joining the names with a dot, e.g. comp -> base becomes "comp.base".
df = pd.json_normalize(raw)
print("\nColumns after flattening:", list(df.columns))

# 3. Rename to short names, and keep accepted offers only.
df = df.rename(columns={"comp.base": "base", "comp.equity": "equity",
                        "comp.bonus": "bonus", "company.name": "company_name",
                        "company.city": "city", "company.id": "company_id"})
acc = df[df["status"] == "accepted"].copy()
acc["total_comp"] = acc["base"] + acc["equity"] + acc["bonus"]

# 4. Average of each part of pay, by job family.
parts = acc.groupby("job_family")[["base", "equity", "bonus"]].mean().round(-2)
parts["offers"] = acc.groupby("job_family").size()
parts = parts.sort_values("base")
print("\nAverage pay parts, accepted offers, Q1 2026:")
print(parts)

# 5. The perks list: explode gives one row per perk, like UNNEST in SQL.
perks = acc.explode("perks")["perks"].value_counts()
print("\nPerks in accepted offers:")
print(perks)
share = (acc["bonus"] > 0).mean()
print(f"\nShare of accepted offers with a bonus: {share:.0%}")

# 6. A stacked bar: base, then equity, then bonus on top.
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.barh(parts.index, parts["base"], color="#4A6FA5", label="Base")
ax.barh(parts.index, parts["equity"], left=parts["base"], color="#7C3C24", label="Equity")
ax.barh(parts.index, parts["bonus"], left=parts["base"] + parts["equity"],
        color="#B8B2A0", label="Bonus")
ax.set_title("Base is most of every offer; equity and bonus add the rest", loc="left")
ax.set_xlabel("Average per accepted offer, Q1 2026 (euro)")
ax.legend(frameon=False, loc="lower right")
ax.spines[["top", "right"]].set_visible(False)
plt.savefig("t2.png", dpi=150, bbox_inches="tight")
plt.show()
  1. json.load(f) reads the file into Python's own types: the list of offers becomes a Python list, each offer a dictionary (Python's word for an object).
  2. pd.json_normalize(raw) flattens it. Nested keys become columns named with a dot. The perks list stays as a list in one column.
  3. rename swaps the dotted names for short ones. df[df["status"] == "accepted"] keeps accepted offers; .copy() makes it a separate table so adding a column does not warn.
  4. groupby("job_family")[[...]].mean() averages the three pay columns for each family. .round(-2) rounds to the nearest hundred. .size() counts offers per family.
  5. explode("perks") is pandas' UNNEST: one row per perk. value_counts() counts each. (acc["bonus"] > 0).mean() is the share with any bonus, because True counts as 1 and False as 0.
  6. The chart stacks three bars: left= tells each bar where to start, so equity starts where base ends and bonus where equity ends.

What it prints

Offers in the file: 60
Keys in the first offer: ['offer_id', 'job_family', 'level', 'status', 'offered_at', 'company', 'comp', 'perks']

Columns after flattening: ['offer_id', 'job_family', 'level', 'status', 'offered_at', 'perks', 'company.id', 'company.name', 'company.city', 'comp.base', 'comp.equity', 'comp.bonus']

Average pay parts, accepted offers, Q1 2026:
                       base  equity   bonus  offers
job_family                                         
Data Analyst        66700.0  5800.0  3500.0      12
Data Scientist      91400.0  9400.0  7700.0       7
Product Manager     97400.0  3800.0  5200.0      14
Software Engineer  101400.0  9200.0  6400.0      20

Perks in accepted offers:
perks
pension            22
remote             22
relocation         18
learning budget    17
health cover       15
Name: count, dtype: int64

Share of accepted offers with a bonus: 58%
Stacked bars of average base, equity and bonus per accepted offer in Q1 2026: Software Engineer highest at about 117,000 euro in total, Data Analyst lowest at about 76,000.

Headline: In Q1 2026, base salary was most of every accepted offer; equity and bonus added about 9 to 19% on top. A typical accepted Software Engineer offer was worth about €117,000 in total.

Caveats: one quarter, 53 accepted offers, and only 7 for Data Scientists. These are averages; equity values are the company's own estimate. No Designer offers were accepted in this export.

Task 3 · Easy · GROUP BY and MEDIAN

A pay ladder by level

"The careers team wants a simple pay ladder for 2025: what does a Junior, Mid, Senior and Lead typically earn in each job family?"

Part A -- SQL

Using the cleaning rule from Task 1, find the number of offers, median base and average base for each job family and level, for accepted offers made in 2025.

Part B -- Python

Reshape the result into a ladder (families down the side, levels across the top), work out Lead pay as a multiple of Junior pay, flag thin groups, and chart it.

A good answer includes

In Hex: SQL cell on dataframes, result named df. In the Python cell, start from order = [...].

Show the worked answer

Part A -- the SQL

-- Purpose: typical base salary by job family and level, 2025 hires.
-- Grain of "clean": one row per offer (duplicates and impossible salaries removed).
-- Grain of the result: one row per job family per level.
WITH clean AS (
    SELECT DISTINCT *
    FROM offers
    WHERE base_salary BETWEEN 20000 AND 400000
)
SELECT
    job_family,
    level,
    COUNT(*)                   AS offers,
    MEDIAN(base_salary)        AS median_base,
    ROUND(AVG(base_salary))    AS avg_base
FROM clean
WHERE status = 'accepted'
  AND YEAR(offered_at) = 2025
  AND level IS NOT NULL
GROUP BY job_family, level
ORDER BY job_family, median_base
  • The WITH clean AS (...) block is a named step, also called a CTE. It applies Task 1's rule once: SELECT DISTINCT * drops exact duplicate rows, and BETWEEN keeps sensible salaries. The main query then reads from clean as if it were a table.
  • YEAR(offered_at) = 2025 keeps offers made in 2025. level IS NOT NULL drops the offers with no level (you cannot use = NULL; SQL needs IS NULL).
  • GROUP BY job_family, level makes one row per pair, and COUNT, MEDIAN and AVG work within each pair.

What it returns

       job_family  level  offers  median_base  avg_base
     Data Analyst Junior      11      47000.0   47091.0
     Data Analyst    Mid      19      61000.0   59974.0
     Data Analyst Senior      12      79250.0   78958.0
     Data Analyst   Lead       9      92000.0   92333.0
   Data Scientist Junior      24      61000.0   60604.0
   Data Scientist    Mid      50      81500.0   86270.0
   Data Scientist Senior      41     110000.0  126183.0
   Data Scientist   Lead      20     133250.0  154425.0
         Designer Junior       3      52500.0   53500.0
         Designer    Mid       7      60000.0   59643.0
         Designer Senior       3      75000.0   80833.0
         Designer   Lead       4     102250.0   98750.0
  Product Manager Junior       6      59000.0   58000.0
  Product Manager    Mid      12      83750.0   83833.0
  Product Manager Senior       5      88000.0   92100.0
  Product Manager   Lead       2     124500.0  124500.0
Software Engineer Junior      14      61000.0   61071.0
Software Engineer    Mid      15      83000.0   85100.0
Software Engineer Senior      25      98000.0  102600.0
Software Engineer   Lead       9     128000.0  132111.0

Look at Data Scientist Senior and Lead: the average is well above the median. That means a few very high offers. Hold that thought for Task 8.

Part B -- the Python

query = """
-- paste the Part A query here
"""
df = duckdb.sql(query).df()

# 1. Pivot: one row per job family, one column per level.
order = ["Junior", "Mid", "Senior", "Lead"]
ladder = df.pivot(index="job_family", columns="level", values="median_base")[order]
print(ladder)

# 2. How much more does a Lead earn than a Junior, in each family?
ratio = (ladder["Lead"] / ladder["Junior"]).round(2).sort_values()
print("\nLead pay as a multiple of Junior pay:")
print(ratio)

# 3. Smallest groups -- a median from a handful of offers is shaky.
print("\nSmallest groups:")
print(df.nsmallest(3, "offers")[["job_family", "level", "offers"]])

# 4. Chart: levels along the bottom, one line per job family.
fig, ax = plt.subplots(figsize=(8, 4.5))
for family in ladder.index:
    ax.plot(order, ladder.loc[family], marker="o", label=family)
ax.set_title("Lead pay is about double Junior pay in every job family", loc="left")
ax.set_ylabel("Median base salary, 2025 (euro)")
ax.legend(frameon=False)
ax.spines[["top", "right"]].set_visible(False)
plt.savefig("t3.png", dpi=150, bbox_inches="tight")
plt.show()
  1. pivot reshapes the long table into a grid: index becomes the rows, columns the columns, values fills the cells. [order] puts the levels in career order rather than alphabetical.
  2. Dividing one column by another works row by row, so ladder["Lead"] / ladder["Junior"] gives each family's multiple.
  3. nsmallest(3, "offers") picks the three groups with the fewest offers.
  4. The for loop draws one line per family. ladder.loc[family] picks that family's row.

What it prints

level               Junior      Mid    Senior      Lead
job_family                                             
Data Analyst       47000.0  61000.0   79250.0   92000.0
Data Scientist     61000.0  81500.0  110000.0  133250.0
Designer           52500.0  60000.0   75000.0  102250.0
Product Manager    59000.0  83750.0   88000.0  124500.0
Software Engineer  61000.0  83000.0   98000.0  128000.0

Lead pay as a multiple of Junior pay:
job_family
Designer             1.95
Data Analyst         1.96
Software Engineer    2.10
Product Manager      2.11
Data Scientist       2.18
dtype: float64

Smallest groups:
         job_family   level  offers
15  Product Manager    Lead       2
8          Designer  Junior       3
10         Designer  Senior       3
Line chart of median 2025 base salary by level for five job families. Every line rises from Junior to Lead, ending at roughly double its starting point.

Headline: In 2025, a Lead's typical base salary was about double a Junior's in every job family -- from €47,000 to €92,000 for Data Analysts.

Caveats: medians of accepted 2025 offers. Several Designer and Product Manager groups have fewer than 5 offers (Product Manager Lead has 2), so treat those steps as rough. 5 offers with no level are left out.

Task 4 · Easy-medium · LEFT JOIN

Where do candidates say no?

"Recruiting wants to know which industries lose the most candidates at the offer stage. Can you rank them?"

Part A -- SQL

Starting from companies, join the offers and work out the share of offers declined in each industry. Keep companies with no offers in the count. Then list any company with no offers at all.

Part B -- Python

Work out the overall decline rate, flag industries with too little data to rank, and chart the result with the overall rate as a reference line.

A good answer includes

In Hex: two SQL cells on dataframes; name the first result df. The Python starts from overall = ....

Show the worked answer

Part A -- the SQL

-- Purpose: where do candidates turn offers down most often?
-- Grain of "offers_dedup": one row per offer.
-- Grain of the result: one row per industry.
WITH offers_dedup AS (
    SELECT DISTINCT * FROM offers
)
SELECT
    c.industry,
    COUNT(DISTINCT c.company_id)                       AS companies,
    COUNT(o.offer_id)                                  AS offers_made,
    COUNT(CASE WHEN o.status = 'declined' THEN 1 END)  AS offers_declined,
    ROUND(100.0 * COUNT(CASE WHEN o.status = 'declined' THEN 1 END)
          / NULLIF(COUNT(o.offer_id), 0), 1)           AS decline_rate_pct
FROM companies AS c
LEFT JOIN offers_dedup AS o            -- LEFT keeps companies with zero offers
    ON o.company_id = c.company_id
GROUP BY c.industry
ORDER BY decline_rate_pct DESC
  • FROM companies AS c gives the table a short name, c, so c.industry means "industry from companies". Same for o.
  • A LEFT JOIN keeps every row on the left (every company), even with no matching offer. Those rows get NULL for every offer column. An ordinary JOIN would drop them without telling you.
  • Because of that, count offers with COUNT(o.offer_id), which skips NULLs. COUNT(*) would count a company with no offers as one offer.
  • COUNT(CASE WHEN o.status = 'declined' THEN 1 END) counts only declined offers: the CASE gives 1 for a declined offer and NULL otherwise, and COUNT skips NULLs.
  • 100.0 * forces a decimal result. NULLIF(x, 0) turns a zero into NULL, so an industry with no offers gives an empty rate instead of a divide-by-zero error.

What it returns

 industry  companies  offers_made  offers_declined  decline_rate_pct
  Telecom          1           16                7              43.8
 Property          1           11                4              36.4
Education          1           37               13              35.1
   Travel          2           22                7              31.8
   Retail          7          101               27              26.7
   Energy          2           42               11              26.2
Logistics          2           77               18              23.4
 Software          9          117               24              20.5
   Health          4           84               13              15.5
  Fintech          5           92               13              14.1
    Media          3           62                8              12.9
   AI lab          5           25                1               4.0
-- Purpose: which companies have made no offers at all?
-- Grain of the result: one row per company with no offers.
SELECT c.company_id, c.name, c.industry
FROM companies AS c
LEFT JOIN offers AS o
    ON o.company_id = c.company_id
WHERE o.offer_id IS NULL          -- no match on the right-hand side

WHERE o.offer_id IS NULL after a LEFT JOIN keeps exactly the left rows that found no match. This is the standard way to ask "what has none?"

What it returns

company_id                name industry
      C042 Lanternfly Ceramics   Retail

Part B -- the Python

query = """
-- paste the first Part A query here
"""
df = duckdb.sql(query).df()
print(df)

# 1. Overall decline rate, to compare each industry against.
overall = df["offers_declined"].sum() / df["offers_made"].sum()
print(f"\nOverall decline rate: {overall:.1%}")

# 2. Flag thin data: under 30 offers, or only one company, a rate can
#    swing a lot by chance or say more about one employer than an industry.
df["small_sample"] = (df["offers_made"] < 30) | (df["companies"] < 2)
print(df[["industry", "companies", "offers_made", "decline_rate_pct", "small_sample"]])

# 3. Chart: bars sorted, the overall rate as a dashed line.
df = df.sort_values("decline_rate_pct")
colours = ["#B8B2A0" if s else "#4A6FA5" for s in df["small_sample"]]
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.barh(df["industry"], df["decline_rate_pct"], color=colours)
ax.axvline(overall * 100, color="#7C3C24", linestyle="--")
ax.text(overall * 100 + 0.5, 0, f"All industries {overall:.0%}", color="#7C3C24")
ax.set_title("Of the industries with enough data, retail loses the most offers", loc="left")
ax.set_xlabel("Offers declined, 2024-2025 (%)")
ax.spines[["top", "right"]].set_visible(False)
plt.savefig("t4.png", dpi=150, bbox_inches="tight")
plt.show()
  1. The overall rate is total declined divided by total offers. Averaging the industry rates would wrongly give a one-company industry the same weight as a nine-company one.
  2. (a) | (b) marks a row True if either test is True. Here: fewer than 30 offers, or only one company.
  3. The list in square brackets picks a colour per bar: grey if thin, blue if not. axvline draws the dashed overall line.

What it prints

     industry  companies  offers_made  offers_declined  decline_rate_pct
0     Telecom          1           16                7              43.8
1    Property          1           11                4              36.4
2   Education          1           37               13              35.1
3      Travel          2           22                7              31.8
4      Retail          7          101               27              26.7
5      Energy          2           42               11              26.2
6   Logistics          2           77               18              23.4
7    Software          9          117               24              20.5
8      Health          4           84               13              15.5
9     Fintech          5           92               13              14.1
10      Media          3           62                8              12.9
11     AI lab          5           25                1               4.0

Overall decline rate: 21.3%
     industry  companies  offers_made  decline_rate_pct  small_sample
0     Telecom          1           16              43.8          True
1    Property          1           11              36.4          True
2   Education          1           37              35.1          True
3      Travel          2           22              31.8          True
4      Retail          7          101              26.7         False
5      Energy          2           42              26.2         False
6   Logistics          2           77              23.4         False
7    Software          9          117              20.5         False
8      Health          4           84              15.5         False
9     Fintech          5           92              14.1         False
10      Media          3           62              12.9         False
11     AI lab          5           25               4.0          True
Bar chart of the share of offers declined by industry. Grey bars mark thin data: telecom, property, education, travel and AI labs. Among the rest, retail is highest at 27%, against 21% overall.

Headline: About 1 in 5 offers was declined in 2024-2025. Among industries with enough data, retail lost the most (27%) and media the fewest (13%).

Caveats: telecom, property and education are one company each, so their high rates describe one employer, not an industry. One retail company made no offers and adds nothing to the rate.

Task 5 · Medium · window function (LAG)

A quarterly pay tracker

"Leadership wants a quarterly pay tracker: median base salary for each job family, and the change on the quarter before. Flag anything big."

Part A -- SQL

For accepted, clean offers, find the number of offers and median base by job family and quarter. Use LAG to put last quarter's median (and offer count) next to each row, and work out the percentage change.

Part B -- Python

Find the biggest moves, then the biggest moves that rest on enough offers to trust. Chart all families with the one that matters picked out.

A good answer includes

In Hex: one SQL cell on dataframes, result named df. Window functions work the same, as it is DuckDB underneath.

Show the worked answer

Part A -- the SQL

-- Purpose: median base salary by job family each quarter, and the change on last quarter.
-- Grain of "clean": one row per accepted offer.
-- Grain of "quarterly" and of the result: one row per job family per quarter.
WITH clean AS (
    SELECT DISTINCT *
    FROM offers
    WHERE base_salary BETWEEN 20000 AND 400000
      AND status = 'accepted'
),
quarterly AS (
    SELECT
        job_family,
        CAST(date_trunc('quarter', offered_at) AS DATE) AS quarter_start,
        COUNT(*)            AS offers,
        MEDIAN(base_salary) AS median_base
    FROM clean
    GROUP BY job_family, quarter_start
),
with_previous AS (
    SELECT
        *,
        LAG(median_base) OVER (
            PARTITION BY job_family      -- start again for each job family
            ORDER BY quarter_start       -- "previous" means the quarter before
        ) AS prev_median,
        LAG(offers) OVER (PARTITION BY job_family ORDER BY quarter_start) AS prev_offers
    FROM quarterly
)
SELECT
    job_family,
    quarter_start,
    prev_offers,
    offers,
    median_base,
    prev_median,
    ROUND(100.0 * (median_base - prev_median) / prev_median, 1) AS pct_change
FROM with_previous
ORDER BY job_family, quarter_start
  • clean: Task 1's rule, plus accepted offers only.
  • quarterly: date_trunc('quarter', offered_at) rounds each date down to the first day of its quarter, so 14 August 2025 becomes 1 July 2025. Grouping on that gives one row per family per quarter.
  • with_previous: LAG(median_base) OVER (...) is a window function. It looks at other rows without collapsing them. PARTITION BY job_family splits the rows into one group per family; ORDER BY quarter_start sorts each group by date; LAG then fetches the value from the row before. The first row in each family has nothing before it, so it gets NULL.
  • You cannot use a new column name in the same SELECT that creates it, which is why the percentage is worked out in the final step, from with_previous.

What it returns

       job_family quarter_start  prev_offers  offers  median_base  prev_median  pct_change
     Data Analyst    2024-01-01         <NA>      14      65250.0          NaN         NaN
     Data Analyst    2024-04-01           14      15      67000.0      65250.0         2.7
     Data Analyst    2024-07-01           15      15      57500.0      67000.0       -14.2
     Data Analyst    2024-10-01           15      11      62000.0      57500.0         7.8
     Data Analyst    2025-01-01           11      12      73000.0      62000.0        17.7
     Data Analyst    2025-04-01           12      14      64750.0      73000.0       -11.3
     Data Analyst    2025-07-01           14      14      61750.0      64750.0        -4.6
     Data Analyst    2025-10-01           14      11      63500.0      61750.0         2.8
   Data Scientist    2024-01-01         <NA>      13      78000.0          NaN         NaN
   Data Scientist    2024-04-01           13      23      80500.0      78000.0         3.2
   Data Scientist    2024-07-01           23      28      82000.0      80500.0         1.9
   Data Scientist    2024-10-01           28      22      82500.0      82000.0         0.6
   Data Scientist    2025-01-01           22      33      80500.0      82500.0        -2.4
   Data Scientist    2025-04-01           33      31      82000.0      80500.0         1.9
   Data Scientist    2025-07-01           31      36     108250.0      82000.0        32.0
   Data Scientist    2025-10-01           36      37     100000.0     108250.0        -7.6
         Designer    2024-01-01         <NA>       4      58750.0          NaN         NaN
         Designer    2024-04-01            4       5      66000.0      58750.0        12.3
         Designer    2024-07-01            5       8      56750.0      66000.0       -14.0
         Designer    2024-10-01            8       2      63500.0      56750.0        11.9
         Designer    2025-04-01            2       6      62250.0      63500.0        -2.0
         Designer    2025-07-01            6       6      69500.0      62250.0        11.6
         Designer    2025-10-01            6       5      56000.0      69500.0       -19.4
  Product Manager    2024-01-01         <NA>       9      85000.0          NaN         NaN
  Product Manager    2024-04-01            9       4      78750.0      85000.0        -7.4
  Product Manager    2024-07-01            4       4     106500.0      78750.0        35.2
  Product Manager    2024-10-01            4       7      75500.0     106500.0       -29.1
  Product Manager    2025-01-01            7       3     120500.0      75500.0        59.6
  Product Manager    2025-04-01            3       6      74500.0     120500.0       -38.2
  Product Manager    2025-07-01            6      10      82500.0      74500.0        10.7
  Product Manager    2025-10-01           10       6      83750.0      82500.0         1.5
Software Engineer    2024-01-01         <NA>      13      75000.0          NaN         NaN
Software Engineer    2024-04-01           13      20      86000.0      75000.0        14.7
Software Engineer    2024-07-01           20      14      86250.0      86000.0         0.3
Software Engineer    2024-10-01           14      14      92000.0      86250.0         6.7
Software Engineer    2025-01-01           14      14      97500.0      92000.0         6.0
Software Engineer    2025-04-01           14      15      95000.0      97500.0        -2.6
Software Engineer    2025-07-01           15      11      83000.0      95000.0       -12.6
Software Engineer    2025-10-01           11      23      94000.0      83000.0        13.3

Two things to spot. Designer has no row for 2025-01-01 (no accepted Designer offers that quarter), so its 2025-04-01 change is against Q4 2024, not Q1 2025. Say so, or fill the gap first. And Product Manager swings 30 to 60% on 3 to 7 offers a quarter: that is noise.

Part B -- the Python

query = """
-- paste the Part A query here
"""
df = duckdb.sql(query).df()
print(df[df["job_family"] == "Data Scientist"])

# 1. The biggest moves, up or down, on the quarter before.
#    abs() ignores the sign, so a big fall counts as much as a big rise.
df["abs_change"] = df["pct_change"].abs()
print("\nBiggest quarter-on-quarter moves:")
cols = ["job_family", "quarter_start", "prev_offers", "offers", "pct_change"]
print(df.nlargest(5, "abs_change")[cols])

# 2. The same, but only where both quarters have at least 10 offers.
#    A median of 3 offers can jump 60% by chance.
solid = df[(df["offers"] >= 10) & (df["prev_offers"] >= 10)]
print("\nBiggest moves with 10+ offers in both quarters:")
print(solid.nlargest(3, "abs_change")[cols])

# 3. Same table, wide: one column per job family, for the chart.
wide = df.pivot(index="quarter_start", columns="job_family", values="median_base")

# 4. Chart: every family in grey, Data Scientist in colour.
fig, ax = plt.subplots(figsize=(8, 4.5))
for family in wide.columns:
    colour = "#4A6FA5" if family == "Data Scientist" else "#CCCCCC"
    ax.plot(wide.index, wide[family], marker="o", color=colour, label=family)
q3 = pd.Timestamp("2025-07-01")
ax.annotate("Data Scientist: +32% in Q3 2025, on 36 offers",
            xy=(q3, wide.loc[q3, "Data Scientist"]),
            xytext=(pd.Timestamp("2024-01-01"), 116000),
            arrowprops=dict(arrowstyle="->"))
ax.set_title("The grey lines jump about on small numbers; the blue one is different", loc="left")
ax.set_ylabel("Median base salary (euro)")
ax.spines[["top", "right"]].set_visible(False)
plt.savefig("t5.png", dpi=150, bbox_inches="tight")
plt.show()
  1. .abs() drops the minus sign, so a big fall ranks with a big rise. nlargest(5, ...) takes the top five.
  2. (a) & (b) means both must be True: at least 10 offers this quarter and last.
  3. pivot makes one column per family, which is the shape a line chart wants.
  4. In the loop, one family gets a colour and the rest are grey, so the eye goes to the point. pd.Timestamp("2025-07-01") makes a date the chart can use for the arrow.

What it prints

        job_family quarter_start  prev_offers  offers  median_base  prev_median  pct_change
8   Data Scientist    2024-01-01         <NA>      13      78000.0          NaN         NaN
9   Data Scientist    2024-04-01           13      23      80500.0      78000.0         3.2
10  Data Scientist    2024-07-01           23      28      82000.0      80500.0         1.9
11  Data Scientist    2024-10-01           28      22      82500.0      82000.0         0.6
12  Data Scientist    2025-01-01           22      33      80500.0      82500.0        -2.4
13  Data Scientist    2025-04-01           33      31      82000.0      80500.0         1.9
14  Data Scientist    2025-07-01           31      36     108250.0      82000.0        32.0
15  Data Scientist    2025-10-01           36      37     100000.0     108250.0        -7.6

Biggest quarter-on-quarter moves:
         job_family quarter_start  prev_offers  offers  pct_change
27  Product Manager    2025-01-01            7       3        59.6
28  Product Manager    2025-04-01            3       6       -38.2
25  Product Manager    2024-07-01            4       4        35.2
14   Data Scientist    2025-07-01           31      36        32.0
26  Product Manager    2024-10-01            4       7       -29.1

Biggest moves with 10+ offers in both quarters:
           job_family quarter_start  prev_offers  offers  pct_change
14     Data Scientist    2025-07-01           31      36        32.0
4        Data Analyst    2025-01-01           11      12        17.7
32  Software Engineer    2024-04-01           13      20        14.7
Median base salary by quarter for five job families. Four grey lines wobble up and down; the blue Data Scientist line is flat near 80,000 euro until Q3 2025, then jumps to about 108,000.

Headline: Median base pay for most job families moved within normal noise in 2024-2025. The exception: Data Scientists, up 32% in Q3 2025, on 36 offers.

Caveats: Product Manager and Designer have too few offers a quarter for a change to mean much. The Data Scientist jump needs checking before anyone quotes it -- see Task 8.

Task 6 · Medium · join grain

The fill rate that looked wrong

"What share of 2025's open roles did we fill, by job family? A colleague's query says only 27% of Data Scientist roles were filled, which surprised everyone. Can you check it?"

The colleague's query:

-- The colleague's query. It looks fine. It is not.
SELECT
    r.job_family,
    CAST(SUM(r.open_roles) AS INTEGER) AS open_roles,
    COUNT(o.offer_id)  AS accepted_offers,
    ROUND(100.0 * COUNT(o.offer_id) / SUM(r.open_roles), 1) AS fill_rate_pct
FROM roles AS r
JOIN offers AS o
    ON  o.company_id = r.company_id
    AND o.job_family = r.job_family
    AND concat(YEAR(o.offered_at), '-Q', QUARTER(o.offered_at)) = r.quarter
WHERE r.quarter LIKE '2025%'
  AND o.status = 'accepted'
GROUP BY r.job_family
ORDER BY r.job_family
Part A -- SQL

Check the grain of each table: what does one row of roles stand for, and one row of offers? Find what the join does to the numbers, then write a query that gives the right fill rate.

Part B -- Python

Put the right and wrong answers side by side, check the total open roles against the roles table, and chart the difference.

A good answer includes

In Hex: put the colleague's query and your fixed query in two SQL cells on dataframes, named wrong and right. The Python starts from both = ....

Show the worked answer

Part A -- the SQL

First, the grain check. offers is one row per offer. Is roles one row per company, family and quarter?

-- Purpose: check the grain. Is roles really one row per company, family and quarter?
-- If it is, the first two numbers match. The third is the total any right answer must keep.
SELECT
    COUNT(*) AS rows_in_roles,
    COUNT(DISTINCT (company_id, job_family, quarter)) AS distinct_keys,
    CAST(SUM(CASE WHEN quarter LIKE '2025%' THEN open_roles END) AS INTEGER) AS open_roles_2025
FROM roles

What it returns

 rows_in_roles  distinct_keys  open_roles_2025
           379            379              490

Yes: 379 rows, 379 different keys. So in 2025 there were 490 open roles. The colleague's query reports 907 across families. Here is why. Say one company had 3 open Data Scientist roles in Q3 and made 3 accepted offers. The join matches the single roles row to all 3 offers, making 3 rows, each carrying open_roles = 3. SUM(open_roles) then adds 3 + 3 + 3 = 9. The more offers a role row has, the worse the inflation, which is why Data Scientist, the busiest family, looks worst. On top of that, the inner JOIN silently drops every role row with no accepted offer.

The fix: bring offers to the same grain as roles first, then join.

-- Purpose: fill rate in 2025 = accepted offers / open roles, by job family.
-- Grain of "accepted": one row per company, job family and quarter (same as roles).
-- Grain of "joined": one row per role record in roles.
-- Grain of the result: one row per job family.
WITH accepted AS (
    SELECT
        company_id,
        job_family,
        concat(YEAR(offered_at), '-Q', QUARTER(offered_at)) AS quarter,
        COUNT(DISTINCT offer_id) AS accepted_offers
    FROM offers
    WHERE status = 'accepted'     -- salary typos don't matter for a count
    GROUP BY company_id, job_family, quarter
),
joined AS (
    SELECT
        r.job_family,
        r.open_roles,
        COALESCE(a.accepted_offers, 0) AS accepted_offers  -- no match means none filled
    FROM roles AS r
    LEFT JOIN accepted AS a
        ON  a.company_id = r.company_id
        AND a.job_family = r.job_family
        AND a.quarter    = r.quarter
    WHERE r.quarter LIKE '2025%'
)
SELECT
    job_family,
    CAST(SUM(open_roles) AS INTEGER)      AS open_roles,
    CAST(SUM(accepted_offers) AS INTEGER) AS accepted_offers,
    ROUND(100.0 * SUM(accepted_offers) / SUM(open_roles), 1) AS fill_rate_pct
FROM joined
GROUP BY job_family
ORDER BY job_family
  • accepted counts accepted offers per company, family and quarter -- the same grain as roles. Now each roles row can match at most one row. concat(...) builds a label like 2025-Q3 to match the quarter column. COUNT(DISTINCT offer_id) ignores the duplicated rows.
  • joined starts from roles and uses a LEFT JOIN, so roles with no offer stay in. COALESCE(x, 0) swaps a NULL for 0.
  • CAST(... AS INTEGER) keeps the totals as whole numbers. Without it, DuckDB's SUM returns a very large number type that pandas shows with a .0.

What it returns

       job_family  open_roles  accepted_offers  fill_rate_pct
     Data Analyst          92               52           56.5
   Data Scientist         184              137           74.5
         Designer          37               17           45.9
  Product Manager          51               25           49.0
Software Engineer         126               63           50.0

And the colleague's version, for comparison

       job_family  open_roles  accepted_offers  fill_rate_pct
     Data Analyst         120               53           44.2
   Data Scientist         515              137           26.6
         Designer          39               17           43.6
  Product Manager          65               25           38.5
Software Engineer         168               63           37.5

Part B -- the Python

wrong_query = """
-- paste the colleague's query here
"""
right_query = """
-- paste your fixed query here
"""
wrong = duckdb.sql(wrong_query).df()
right = duckdb.sql(right_query).df()

# 1. Put the two answers side by side.
both = right.merge(wrong, on="job_family", suffixes=("", "_wrong"))
print(both[["job_family", "open_roles", "open_roles_wrong",
            "fill_rate_pct", "fill_rate_pct_wrong"]])

# 2. Total open roles: the wrong query counts many roles more than once.
print("\nOpen roles in 2025 -- right:", right["open_roles"].sum(),
      "| wrong:", wrong["open_roles"].sum())

# 3. Chart: right and wrong next to each other for each family.
y = range(len(both))
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.barh([i + 0.2 for i in y], both["fill_rate_pct"], height=0.4,
        color="#4A6FA5", label="Right: offers counted at the roles' grain")
ax.barh([i - 0.2 for i in y], both["fill_rate_pct_wrong"], height=0.4,
        color="#B8B2A0", label="Wrong: open roles repeated once per offer")
ax.set_yticks(list(y))
ax.set_yticklabels(both["job_family"])
ax.set_title("The bad join made every fill rate look worse than it was", loc="left")
ax.set_xlabel("Fill rate, 2025 (%)")
ax.legend(frameon=False, loc="upper center", bbox_to_anchor=(0.4, -0.15), fontsize=9)
ax.spines[["top", "right"]].set_visible(False)
plt.savefig("t6.png", dpi=150, bbox_inches="tight")
plt.show()
  1. merge joins two dataframes on a shared column, like SQL's JOIN. Both are one row per family, so this join is safe. suffixes labels the clashing column names from the second table with _wrong.
  2. The total check: the right answer's 490 matches the roles table. Always check a total against its source after a join.
  3. range(len(both)) gives positions 0 to 4. Shifting each bar up or down by 0.2 puts the two bars side by side.

What it prints

          job_family  open_roles  open_roles_wrong  fill_rate_pct  fill_rate_pct_wrong
0       Data Analyst          92               120           56.5                 44.2
1     Data Scientist         184               515           74.5                 26.6
2           Designer          37                39           45.9                 43.6
3    Product Manager          51                65           49.0                 38.5
4  Software Engineer         126               168           50.0                 37.5

Open roles in 2025 -- right: 490 | wrong: 907
Paired bars of 2025 fill rate by job family, right against wrong. Every right bar is higher. Data Scientist is 75% right against 27% wrong.

Headline: In 2025, about three in four open Data Scientist roles got an accepted offer (75%), not 27%. Other families sat between 46% and 57%.

Caveats: an offer is matched to roles in the quarter it was made; a role opened in one quarter and filled in the next counts as unfilled. The earlier figure came from a join that counted open roles up to several times over.

Task 7 · Medium-hard · debugging

Fix a published number

"Our 2025 pay report says: 'The average Data Analyst base salary in 2025 was €89,286.' A reader has emailed to say that looks far too high. Here's the query behind it. Find what went wrong, fix it, and draft the correction."

-- The query behind the published number
SELECT ROUND(AVG(base_salary)) AS avg_base
FROM offers
WHERE job_family = 'Data Analyst'
  AND YEAR(offered_at) = 2025
Part A -- SQL

Run the report's query to confirm the number. Look at the rows behind it. Rebuild the figure one fix at a time so you can show what each problem was worth.

Part B -- Python

Work out how far off the published number was, chart the path from wrong to right, and write a short correction.

A good answer includes

In Hex: one SQL cell per query; name the step-by-step result steps. The Python starts from published = ....

Show the worked answer

Part A -- the SQL

Running the report query gives the published figure, so the number came from this query:

 avg_base
  89286.0

Now look at the rows behind it, biggest first. Sorting by the number you are checking is the fastest way to find a problem.

-- Purpose: look at the rows behind the number. Biggest salaries first.
SELECT offer_id, company_id, level, base_salary, status
FROM offers
WHERE job_family = 'Data Analyst'
  AND YEAR(offered_at) = 2025
ORDER BY base_salary DESC
LIMIT 5

What it returns

offer_id company_id  level  base_salary   status
   O0375       C015 Senior      1500000 accepted
   O0431       C036   Lead       106500 accepted
   O0338       C027   Lead       105500 accepted
   O0399       C008   Lead        95000 accepted
   O0399       C008   Lead        95000 accepted

Three problems: a salary of €1,500,000 (a typing error), offer O0399 listed twice, and nothing in the query filters on status, so declined offers are in. Declined offers were never paid to anyone. Now rebuild it a step at a time:

-- Purpose: rebuild the number one fix at a time, so each fix shows its effect.
-- Grain of "da_2025": one row per row in offers (duplicates still in).
-- Grain of the result: one row per step.
WITH da_2025 AS (
    SELECT *
    FROM offers
    WHERE job_family = 'Data Analyst'
      AND YEAR(offered_at) = 2025
),
step1 AS (SELECT * FROM da_2025 WHERE base_salary BETWEEN 20000 AND 400000),
step2 AS (SELECT DISTINCT * FROM step1),
step3 AS (SELECT * FROM step2 WHERE status = 'accepted')
SELECT 1 AS step, 'As published'                AS label, COUNT(*) AS rows_used, ROUND(AVG(base_salary)) AS avg_base, MEDIAN(base_salary) AS median_base FROM da_2025
UNION ALL
SELECT 2, 'Remove the €1.5m entry error', COUNT(*), ROUND(AVG(base_salary)), MEDIAN(base_salary) FROM step1
UNION ALL
SELECT 3, 'Remove duplicate rows',        COUNT(*), ROUND(AVG(base_salary)), MEDIAN(base_salary) FROM step2
UNION ALL
SELECT 4, 'Keep accepted offers only',    COUNT(*), ROUND(AVG(base_salary)), MEDIAN(base_salary) FROM step3
ORDER BY step
  • Each named step builds on the one before: step1 removes the impossible salary, step2 the duplicate, step3 the declined offers.
  • UNION ALL stacks the results of several SELECTs into one table. Each must have the same columns in the same order, so the first one names them and the rest follow.

What it returns

 step                        label  rows_used  avg_base  median_base
    1                 As published         63   89286.0      64000.0
    2 Remove the €1.5m entry error         62   66532.0      63750.0
    3        Remove duplicate rows         61   66066.0      63500.0
    4    Keep accepted offers only         51   67373.0      64000.0

The typo did almost all the damage. Removing declined offers nudged the average up, because declined offers tended to be lower. And look at the median column: it barely moved at any step. A median would have survived all three mistakes.

Part B -- the Python

query = """
-- paste the step-by-step Part A query here
"""
steps = duckdb.sql(query).df()
print(steps)

# 1. How far off was the published number?
published = steps.loc[0, "avg_base"]
fixed = steps.loc[3, "avg_base"]
print(f"\nPublished: €{published:,.0f}  Corrected: €{fixed:,.0f}  "
      f"Overstated by €{published - fixed:,.0f} ({published / fixed - 1:.0%})")

# 2. Chart: the average after each fix. Bars start at zero so the gap is honest.
fig, ax = plt.subplots(figsize=(8, 4.5))
colours = ["#7C3C24", "#B8B2A0", "#B8B2A0", "#4A6FA5"]
ax.barh(steps["label"], steps["avg_base"], color=colours)
ax.invert_yaxis()                      # step 1 at the top
for i, v in enumerate(steps["avg_base"]):
    ax.text(v + 500, i, f"€{v:,.0f}", va="center")
ax.set_title("One typo did almost all the damage", loc="left")
ax.set_xlabel("Average Data Analyst base salary, 2025 (euro)")
ax.set_xlim(0, published * 1.2)
ax.spines[["top", "right"]].set_visible(False)
plt.savefig("t7.png", dpi=150, bbox_inches="tight")
plt.show()
  1. steps.loc[0, "avg_base"] picks one cell: row 0, column avg_base.
  2. In the f-string, {published:,.0f} means "comma for thousands, no decimals", and {x:.0%} means "as a percentage".
  3. ax.invert_yaxis() puts step 1 at the top, so the chart reads top to bottom like the steps. ax.text writes each value at the end of its bar. Bars start at zero so their lengths are honest.

What it prints

   step                         label  rows_used  avg_base  median_base
0     1                  As published         63   89286.0      64000.0
1     2  Remove the €1.5m entry error         62   66532.0      63750.0
2     3         Remove duplicate rows         61   66066.0      63500.0
3     4     Keep accepted offers only         51   67373.0      64000.0

Published: €89,286  Corrected: €67,373  Overstated by €21,913 (33%)
Four bars showing the average Data Analyst base salary after each fix: 89,286 euro as published, 66,532 after removing the entry error, 66,066 after removing the duplicate, 67,373 with accepted offers only.

Correction: We said the average Data Analyst base salary in 2025 was €89,286. The right figure is €67,373 (median €64,000). The original included one salary entered as €1,500,000, a duplicated record and offers that were declined.

To stop it happening again: run the Task 1 checks before every report, report the median next to any average, and fail the report if any salary falls outside a sensible range.

Task 8 · Hard · mix shift

Is the pay jump a story?

"Pay for a popular job family jumped sharply in one quarter; marketing wants a headline. Decide if it's a story." Marketing's draft: "Data Scientist pay up 53% in three months."

Part A -- SQL

Split Q3 2025's Data Scientist offers by employer: companies that were already hiring Data Scientists, and companies hiring them for the first time. Then compare Q2 and Q3 2025 for only the companies that hired Data Scientists in both quarters.

Part B -- Python

Name the new employers. Put the raw change next to the like-for-like change, chart the two, and write the headline you would stand behind.

A good answer includes

In Hex: two SQL cells on dataframes named groups and same, and a third for the new employers. The Python starts from the step 2 comment.

Show the worked answer

When an average jumps, there are two possible reasons. Either the same employers are paying more, or the mix changed: different employers, levels or places are in the numbers this time. This is called a mix shift, and it is the first thing to rule out before calling a jump a trend.

Part A -- the SQL

-- Purpose: did Data Scientist pay jump, or did the mix of employers change?
-- Grain of "ds": one row per accepted Data Scientist offer.
-- Grain of "first_seen": one row per company.
-- Grain of the result: one row per quarter per group (new employer or not).
WITH ds AS (
    SELECT DISTINCT *
    FROM offers
    WHERE job_family = 'Data Scientist'
      AND status = 'accepted'
      AND base_salary BETWEEN 20000 AND 400000
),
first_seen AS (
    SELECT company_id, MIN(offered_at) AS first_ds_offer
    FROM ds
    GROUP BY company_id
)
SELECT
    CAST(date_trunc('quarter', ds.offered_at) AS DATE) AS quarter_start,
    CASE WHEN f.first_ds_offer >= DATE '2025-07-01'
         THEN 'new in Q3 2025' ELSE 'hiring before' END AS employer_group,
    COUNT(*)                   AS offers,
    MEDIAN(ds.base_salary)     AS median_base
FROM ds
JOIN first_seen AS f USING (company_id)
WHERE ds.offered_at >= DATE '2025-01-01'
GROUP BY ALL
ORDER BY quarter_start, employer_group
  • ds: clean, accepted Data Scientist offers.
  • first_seen: for each company, the date of its first Data Scientist offer.
  • The CASE labels each offer by whether its employer first appeared in Q3 2025 or before. DATE '2025-07-01' writes a date in SQL. JOIN ... USING (company_id) is a short way to join on a column with the same name in both tables.
  • GROUP BY ALL groups by every column that is not a sum or count -- here, quarter and group.

What it returns

quarter_start employer_group  offers  median_base
   2025-01-01  hiring before      33      80500.0
   2025-04-01  hiring before      31      82000.0
   2025-07-01  hiring before      22      85500.0
   2025-07-01 new in Q3 2025      14     191250.0
   2025-10-01  hiring before      27      91500.0
   2025-10-01 new in Q3 2025      10     167750.0

Employers that were already hiring paid a median of €85,500 in Q3, against €82,000 in Q2. New employers paid €191,250 -- more than double -- and made 14 of the 36 Q3 offers. Now the like-for-like check:

-- Purpose: compare like with like -- only companies that hired Data Scientists
-- in BOTH Q2 and Q3 2025.
-- Grain of "q2", "q3": one row per offer. Grain of "same_companies": one row per company.
-- Grain of the result: one row per comparison.
WITH ds AS (
    SELECT DISTINCT *
    FROM offers
    WHERE job_family = 'Data Scientist'
      AND status = 'accepted'
      AND base_salary BETWEEN 20000 AND 400000
),
q2 AS (SELECT * FROM ds WHERE offered_at >= DATE '2025-04-01' AND offered_at < DATE '2025-07-01'),
q3 AS (SELECT * FROM ds WHERE offered_at >= DATE '2025-07-01' AND offered_at < DATE '2025-10-01'),
same_companies AS (
    SELECT company_id FROM q2
    INTERSECT
    SELECT company_id FROM q3
)
SELECT
    'All companies' AS comparison,
    (SELECT COUNT(DISTINCT company_id) FROM q3) AS companies,
    (SELECT MEDIAN(base_salary) FROM q2) AS q2_median,
    (SELECT MEDIAN(base_salary) FROM q3) AS q3_median,
    (SELECT ROUND(AVG(base_salary)) FROM q2) AS q2_avg,
    (SELECT ROUND(AVG(base_salary)) FROM q3) AS q3_avg
UNION ALL
SELECT
    'Same companies, both quarters',
    (SELECT COUNT(*) FROM same_companies),
    (SELECT MEDIAN(base_salary) FROM q2 WHERE company_id IN (SELECT company_id FROM same_companies)),
    (SELECT MEDIAN(base_salary) FROM q3 WHERE company_id IN (SELECT company_id FROM same_companies)),
    (SELECT ROUND(AVG(base_salary)) FROM q2 WHERE company_id IN (SELECT company_id FROM same_companies)),
    (SELECT ROUND(AVG(base_salary)) FROM q3 WHERE company_id IN (SELECT company_id FROM same_companies))
  • q2 and q3 hold each quarter's offers. Using >= the first day and < the first day of the next quarter is a safe way to pick a date range.
  • INTERSECT keeps the company IDs that appear in both lists: companies hiring Data Scientists in both quarters.
  • Each (SELECT ...) in brackets returns a single number. company_id IN (...) keeps only the same companies.

What it returns

                   comparison  companies  q2_median  q3_median  q2_avg   q3_avg
                All companies         16    82000.0   108250.0 85274.0 130486.0
Same companies, both quarters         11    82500.0    85500.0 87732.0  88045.0

Part B -- the Python

groups_query = """
-- paste the first Part A query (employer groups) here
"""
same_query = """
-- paste the second Part A query (same companies) here
"""
groups = duckdb.sql(groups_query).df()
same = duckdb.sql(same_query).df()
print(groups)

# 1. Who are the new employers? Join back to companies to see their industry.
new_ids = duckdb.sql("""
    SELECT o.company_id, c.name, c.industry
    FROM offers o JOIN companies c USING (company_id)
    WHERE o.job_family = 'Data Scientist' AND o.status = 'accepted'
    GROUP BY o.company_id, c.name, c.industry
    HAVING MIN(o.offered_at) >= DATE '2025-07-01'
    ORDER BY o.company_id
""").df()
print("\nNew Data Scientist employers in Q3 2025:")
print(new_ids)

# 2. The headline numbers: the raw jump against the like-for-like change.
same["median_change_pct"] = (100 * (same["q3_median"] / same["q2_median"] - 1)).round(1)
same["avg_change_pct"] = (100 * (same["q3_avg"] / same["q2_avg"] - 1)).round(1)
print()
print(same[["comparison", "companies", "q2_median", "q3_median",
            "median_change_pct", "avg_change_pct"]])

# 3. Chart: Q2 against Q3, for all companies and for the same companies.
labels = ["All companies", "Same companies\nin both quarters"]
x = [0, 1]
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.bar([i - 0.2 for i in x], same["q2_median"], width=0.4, color="#B8B2A0", label="Q2 2025")
ax.bar([i + 0.2 for i in x], same["q3_median"], width=0.4, color="#4A6FA5", label="Q3 2025")
for i in x:
    ax.text(i + 0.2, same.loc[i, "q3_median"] + 1500,
            f"{same.loc[i, 'median_change_pct']:+.0f}%", ha="center", fontweight="bold")
ax.set_xticks(x)
ax.set_xticklabels(labels)
ax.set_title("Like for like, Data Scientist pay barely moved", loc="left")
ax.set_ylabel("Median base salary (euro)")
ax.legend(frameon=False)
ax.spines[["top", "right"]].set_visible(False)
plt.savefig("t8.png", dpi=150, bbox_inches="tight")
plt.show()
  1. The extra query joins to companies to name the new employers. HAVING filters groups after GROUP BY, the way WHERE filters rows before it: here, companies whose first accepted Data Scientist offer came in Q3 2025 or later.
  2. The change is q3 / q2 - 1, times 100 for a percentage. Working it out for both rows at once puts the raw and like-for-like numbers side by side.
  3. The chart pairs Q2 and Q3 bars for each comparison and writes the change above the Q3 bar. f"{x:+.0f}%" always shows the sign.

What it prints

  quarter_start  employer_group  offers  median_base
0    2025-01-01   hiring before      33      80500.0
1    2025-04-01   hiring before      31      82000.0
2    2025-07-01   hiring before      22      85500.0
3    2025-07-01  new in Q3 2025      14     191250.0
4    2025-10-01   hiring before      27      91500.0
5    2025-10-01  new in Q3 2025      10     167750.0

New Data Scientist employers in Q3 2025:
  company_id                 name industry
0       C037        Kestrel Minds   AI lab
1       C038          Orrery Labs   AI lab
2       C039  Fennel Intelligence   AI lab
3       C040     Tidewater AI Lab   AI lab
4       C041        Quarry Neural   AI lab

                      comparison  companies  q2_median  q3_median  median_change_pct  avg_change_pct
0                  All companies         16    82000.0   108250.0               32.0            53.0
1  Same companies, both quarters         11    82500.0    85500.0                3.6             0.4
Paired bars of median Data Scientist base salary, Q2 against Q3 2025. All companies: up 32%. The same 11 companies in both quarters: up 4%.

Is it a story? Not the one in the draft. At the 11 employers hiring Data Scientists in both quarters, median base pay rose about 4% (the average was flat). The 53% jump in the average came from five AI labs that started hiring in Q3 2025 at more than double the going rate.

The honest headline: "Five new AI labs are hiring Data Scientists at twice the going rate." That is a real story, and it is about who is hiring, not a pay rise for everyone.

Caveats: the same-company check rests on 11 employers. Level mix can also move a median; a stricter check compares the same company and level.

All data on this page is made up for practice. Answers were produced by running the code shown on the files above. See also Data interview questions.

Back to the top