08 · SQL II: CTEs, window functions and time-series queries

Run it in Colab View the .ipynb

You are reading this notebook. To run it, open it in Colab with the button above - no install, no GPU needed for most of them - or clone the repository and open it in Jupyter.

  1. 1. Purpose
  2. 2. Conceptual explanation
    1. 2.1 Intuition: a window function adds a column without collapsing rows
    2. 2.2 Logical evaluation order
    3. 2.3 Frames, and the default that bites
    4. 2.4 Offsets: LAG, LEAD and intervals from events
    5. 2.5 Gaps and islands: from samples to events
    6. 2.6 As-of joins and point-in-time correctness
    7. 2.7 The same operations in pandas
    8. 2.8 Industry example
    9. 2.9 Limits and misconceptions
  3. 3. Worked example: scan events on two packaging lines
  4. 4. Guided lab: six queries on cold-chain data
    1. Task 1 — q1_latest_status.sql: one row per device (5 min)
    2. Task 2 — q2_time_in_state.sql: events to intervals (8 min)
    3. Task 3 — q3_running_alerts.sql: a running count that survives ties (6 min)
    4. Task 4 — q4_rolling_features.sql: a time window on an irregular grid (8 min)
    5. Task 5 — q5_alert_episodes.sql: gaps and islands (8 min)
    6. Task 6 — q6_asof_calibration.sql: as-of join (8 min)
    7. Task 7 — pandas_equiv.py: three functions (15 min)
    8. Debugging guidance
  5. 5. Independent challenge: a point-in-time-correct feature table
    1. The challenge brief
      1. Scenario
      2. Task
      3. Acceptance criteria
      4. Then look at what you built (5 minutes, part of the task)
      5. Out of scope
  6. 6. Progressive hints

Week 2 · day 2 · 2 h essential path + up to 1 h optional · lab files: labs/w2d2_sql_windows_timeseries/

Objective. Use window functions for ranking, running statistics, gaps-and-islands and as-of joins on event and sensor tables; reproduce each result in pandas.

# --- Setup: works on your laptop AND in Google Colab ----------------------------
# In Colab this clones the course repository and installs the requirements (about a
# minute, first run only). On your own machine it just finds the repository. Every
# command in this notebook runs from the repository root. Safe to re-run.
import os
import subprocess
import sys
from pathlib import Path

if "google.colab" in sys.modules:
    if not Path("/content/mlengineering").exists():
        subprocess.run(["git", "clone", "--depth", "1",
                        "https://github.com/berdakh/mlengineering.git",
                        "/content/mlengineering"], check=True)
    os.chdir("/content/mlengineering")
    subprocess.run([sys.executable, "-m", "pip", "install", "-q",
                    "-r", "requirements.txt"], check=True)

REPO_ROOT = next(p for p in [Path.cwd(), *Path.cwd().parents]
                 if (p / "src" / "mlcourse").is_dir())
os.chdir(REPO_ROOT)
sys.path.insert(0, str(REPO_ROOT / "src"))
print("repo root:", REPO_ROOT)

Unit id: w2d2 · Week 2, day 2 · Content status: Execution verified (see Verification record) Handbook: H3.2 Window functions and time-series SQL Data: data/coldchain.db — SYNTHETIC, built to contain specific traps. Results in this lesson show that queries are correct; they say nothing about real equipment.


1. Purpose

Primary objective. Write window-function queries that are correct on tied, duplicated and irregularly sampled data — ranking, running statistics, run-length segmentation (gaps and islands) and as-of joins — and reproduce each result in pandas.

What you will learn

  • Where window functions sit in SQL’s logical evaluation order, and why that forces CTEs.
  • The three parts of a window (PARTITION BY, ORDER BY, frame) and the default-frame trap.
  • Gaps and islands: turning a per-sample flag into events, inside the database.
  • As-of joins and point-in-time correctness: the SQL form of “no future information”.
  • The pandas idiom for each pattern, and where the two disagree at boundaries.

Why an applied ML engineer needs it. Features and labels are usually born in SQL, before any Python runs. The three failures this lesson targets all produce queries that execute, return the right number of rows and are wrong: a “latest row” that is not unique, a rolling window that silently counts rows instead of time, and a join that reads a value that did not exist yet at prediction time. The last one is temporal leakage, and it is far easier to commit in a join than in a training loop. Window functions are also the most common SQL interview topic above the join-and-group level.

Prerequisites. W2D1: stating the grain of a result, join fan-out, NULL semantics. Python >= 3.11 whose sqlite3 module is linked against SQLite >= 3.28 (python -c "import sqlite3; print(sqlite3.sqlite_version)"; the checks tell you if it is too old). No sqlite3 command-line tool is needed.

Time budget — essential path 2 h

Activity Time
Read section 2 (2.2, 2.3 and 2.6 carefully; skim what you know) 25 min
Worked example: run it, predict each table before reading it 15 min
Guided lab: six queries (40 min), three pandas functions (15 min) 55 min
Independent challenge: specification, first working version 15 min
Assessment questions (written) 10 min

Optional extension — up to 1 h: finish the challenge until its checks pass (30 min), interview rep (15 min), handbook H3.2.6 on engine differences (15 min).


2. Conceptual explanation

2.1 Intuition: a window function adds a column without collapsing rows

GROUP BY answers “one number per group” and destroys the rows. A window function answers “for each row, a number computed from related rows” and keeps every row. Time-series work does this constantly: a z-score against a unit’s own baseline, a moving RMS over the preceding second, the sample index within a trial. In pandas these are groupby(...).transform(...), rolling(...), groupby(...).cumcount(). SQL spells them all the same way:

function(args) OVER (PARTITION BY <who are my relatives> ORDER BY <in what sequence> <frame: which of them>)
Part Meaning Signal-processing analogue
PARTITION BY rows are only compared within the same partition per subject / per channel / per trial
ORDER BY the sequence inside a partition the time axis
frame which rows around the current one feed the function the analysis window

2.2 Logical evaluation order

A SELECT is evaluated, logically, in this order:

FROM / JOIN  ->  WHERE  ->  GROUP BY  ->  HAVING  ->  window functions  ->  SELECT list / DISTINCT  ->  ORDER BY  ->  LIMIT

Three consequences you will meet today:

  1. A window function cannot appear in WHERE, GROUP BY or HAVING, because those run earlier. “Keep the row with rn = 1” therefore needs two levels: compute rn in a CTE or subquery, filter outside. SQLite’s message when you forget is misuse of aliased window function rn.
  2. WHERE changes what a window sees. A filter removes rows before the window is computed, so LAG returns the previous surviving row. Filtering to alert = 1 and then asking for the previous reading gives the previous alerting reading, which is rarely what you meant.
  3. Windows run after aggregation, so RANK() OVER (ORDER BY SUM(x) DESC) in a grouped query is legal and ranks the groups.

A CTE (WITH name AS (...)) is the tool for staging these levels. Treat each CTE as one step with a stated grain, exactly as you would name intermediate DataFrames.

The same order as a diagram, with the place where each kind of filter can live:

Diagram 1 of notebook 08

2.3 Frames, and the default that bites

The frame is the subset of the partition used for the current row. Two units matter here:

  • ROWS BETWEEN 6 PRECEDING AND CURRENT ROW counts physical rows.
  • RANGE BETWEEN 1800 PRECEDING AND CURRENT ROW measures the ORDER BY value: all rows whose key lies in [current − 1800, current]. It needs exactly one ordering key, numeric to be meaningful (hence ts_epoch, not the text ts).

With irregular sampling these are different windows. “Seven rows” is thirty minutes only if no sample was lost. On the lab data the two definitions give a different mean for 2,929 of 4,707 rows.

Peers. Rows with equal ORDER BY values are peers. Under RANGE, CURRENT ROW means “the current row and all its peers”. Under ROWS it means the physical row.

The default frame. If you write ORDER BY inside OVER and no frame, the frame is

RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW

so a running total includes the current row’s peers. Two rows that tie get the same total, each containing the other. With no ORDER BY at all, the frame is the whole partition.

For a cumulative sum \(S_i = \sum_{j \le i} x_j\) to be well defined, the index \(i\) must be a total order. So the rule is: make the ordering total (add a tie-breaker such as an id) and write the frame explicitly when you mean rows.

The ranking functions express the three possible attitudes to ties:

Function Ties Values for scores 70, 55, 55, 40
ROW_NUMBER() broken arbitrarily unless the ordering is total 1, 2, 3, 4
RANK() share a rank, then skip 1, 2, 2, 4
DENSE_RANK() share a rank, no skip 1, 2, 2, 3

“Top 1 per group” with RANK() = 1 (or WHERE ts = (SELECT MAX(ts) ...)) returns several rows when the top is tied. If the result is then joined on the group key, every downstream row is duplicated. Use ROW_NUMBER() with a deterministic tie-breaker when the contract is “exactly one”. ROW_NUMBER() with a non-total ordering is worse than RANK(): it returns one row, but which one may change between runs or engines.

One partition with a tied timestamp, three frames for the current row (marked >). Brackets show the rows inside the frame; the right column is SUM(x) over it.

 ts_epoch   x     ROWS 2 PRECEDING        RANGE 600 PRECEDING       default (ORDER BY, no frame)
                  AND CURRENT ROW         AND CURRENT ROW           = RANGE UNBOUNDED PRECEDING .. CURRENT ROW
   1000     1                                                        [
   1300     2     [                                                  [
   2100     4     [                        [                         [
>  2400     8     [  = 2 + 4 + 8 = 14      [                         [
   2400    16                              [  = 4 + 8 + 16 = 28      [  = 1 + 2 + 4 + 8 + 16 = 31
   2900    32

 ROWS  counts physical rows: the peer at ts 2400 (x = 16) is outside.
 RANGE measures the ORDER BY value: every row with ts in [1800, 2400] is inside, peers included.
 The default frame is a RANGE frame, so a "running total" of the first 2400 row already contains the second.

2.4 Offsets: LAG, LEAD and intervals from events

LAG(x) and LEAD(x) read the previous and next row of the partition; they ignore the frame. Two standard uses:

  • Differences and gaps: ts_epoch - LAG(ts_epoch) OVER (PARTITION BY device_id ORDER BY ts_epoch).
  • Events to intervals: a status log stores changes. The state that begins at one event ends at the next one, so LEAD(ts_epoch) gives the interval end. The last event has no successor; you must decide where it ends (a report horizon) and say so. Summing durations by state gives time-in-state. A cheap invariant: per device the durations must add up to the observed span.

2.5 Gaps and islands: from samples to events

In NumPy this is a familiar pattern: np.diff on a thresholded detector output, pair up rising and falling edges, get events with onset and offset. The SQL form has the same two steps.

  1. Mark starts. A row starts an island if it is flagged and the previous row of the same partition is not: alert = 1 AND COALESCE(LAG(alert) OVER (...), 0) = 0.
  2. Number islands. A running sum of the start marks is constant within an island and increases by one at each new start. Group by it.
alert        0 0 1 1 1 0 1 0 0 1 1
start        0 0 1 0 0 0 1 0 0 1 0
cumsum       0 0 1 1 1 1 2 2 2 3 3     <- on flagged rows this is the island number

An equivalent trick subtracts two row numbers (ROW_NUMBER() over all rows minus ROW_NUMBER() over flagged rows is constant within a run). The start-mark version generalises better: change the start condition to “gap since previous row > 30 minutes” and the same query sessionises by time gap; change it to “status differs from previous” and it collapses repeated states.

Where the analogy with signal-based event detection breaks: detectors on a uniform sample grid (in physiology or audio, say) usually merge events closer than a refractory gap and discard events shorter than a minimum duration. Here “consecutive” means adjacent rows, and a lost sample between two flagged rows does not split the run. Whether that is right is a definition you owe the reader; state it (the lab does).

The classic error is forgetting the partition in step 1. LAG then looks at the previous row of another device, which is the same bug as running event extraction across concatenated channels.

The reference query for Task 5 on one device and one day of the lab database:

Line chart of reported temperature for device D01 on 2 March with 21 flagged samples grouped into 5 shaded episodes

Twenty-one flagged samples become five episodes. Two of them are a single sample wide: whether those deserve to be events is the minimum-duration decision the text above says you owe the reader. SYNTHETIC data; regenerate with python labs/w2d2_sql_windows_timeseries/figures/make_figures.py.

2.6 As-of joins and point-in-time correctness

Some tables describe what was true from when: a calibration, a price list, a customer’s plan, a model version. For a fact at time \(t\) you need the dimension row in force at \(t\):

\[\text{match}(t) = \arg\max_{k} \{\, v_k : v_k \le t \,\}\]

where \(v_k\) are the valid_from times of that entity’s rows. This is an as-of join. Standard SQL has no single keyword for it; the portable pattern is: join on the entity key and valid_from <= t, then keep the latest match per fact row with ROW_NUMBER(). Use a LEFT JOIN so that facts older than the first dimension row survive with NULLs rather than vanishing.

The same construction defines a point-in-time-correct feature. For a label observed at prediction time \(t_\ell\), a feature may be any function of rows with timestamp \(\le t_\ell\) and of nothing else:

\[f_\ell = g\big(\{\, r : \text{entity}(r) = \text{entity}(\ell),\ t_r \le t_\ell \,\}\big)\]

This gives a property you can test without knowing the right answer: edit every row after \(t_\ell\) arbitrarily; \(f_\ell\) must not change. The challenge checks use exactly this.

Three ways a join reads the future, all common:

Mistake What it looks like
Join to the current dimension row JOIN calibration USING (device_id) on a “latest” view
Symmetric window ABS(r.ts - l.label_ts) <= 3600, a centred window carried over from offline analysis
Nearest instead of previous ORDER BY ABS(r.ts - l.label_ts), or merge_asof(direction="nearest")

There is one more that no query can detect: a row whose timestamp is in the past but which was written later (a backfilled or corrected value, such as the re-sent readings in today’s data). Point-in-time correctness is about when information became available, which needs an ingestion time. Today’s data has only reading_id as a proxy for arrival order; H3.2.5 discusses this.

Diagram 2 of notebook 08

On the lab database, device D01 changes calibration four times in three days. Each reading is corrected with the offset, and compared with the threshold, that were in force when it was measured:

Two stacked panels for device D01: the calibration offset applied steps through five values; the corrected temperature is compared against an alert threshold that steps between 7.5, 8.0 and 8.5 degrees

Joining every reading to the latest calibration row instead would re-score three days of history with an offset and threshold that did not exist yet. SYNTHETIC data, same script.

2.7 The same operations in pandas

SQL pandas Boundary to watch
ROW_NUMBER() OVER (PARTITION BY g ORDER BY k) df.sort_values(k).groupby(g).cumcount() + 1 sort first; ties need a total order in both
RANK() / DENSE_RANK() groupby(g)[k].rank(method="min" / "dense") default method="average" matches neither
LAG(x) / LEAD(x) groupby(g)[x].shift(1) / shift(-1) a bare df.x.shift() crosses groups
running sum, ROWS frame groupby(g)[x].cumsum() row order is whatever the frame currently has
RANGE BETWEEN 1800 PRECEDING AND CURRENT ROW rolling("1800s", closed="both") on a datetime index pandas’ default is closed="right": (t−30 min, t]
aggregate OVER (PARTITION BY g) groupby(g)[x].transform("mean") —
as-of join pd.merge_asof(left, right, on=..., by=..., direction="backward") both frames sorted by the on key; allow_exact_matches=True means <=
top-1 per group sort_values(...).groupby(g).head(1) or drop_duplicates(g, keep="last") —

Pushing work into SQL is not a matter of taste: the database filters and aggregates next to the data, and the feature definition lives where the serving path can reuse it. Pandas is the better place to prototype and to test. Doing both and asserting equality, as today, is a cheap way to find the boundary cases neither version handles on its own.

2.8 Industry example

A logistics company bills cold-chain customers for temperature compliance. The compliance report is three of today’s queries: the current status of each unit (latest row per device), hours spent in each state last month (events to intervals), and excursion episodes with duration and peak (gaps and islands on calibrated readings joined as of each reading’s time). A re-calibration in the middle of the month must not rewrite last week’s excursions; that is the as-of join. When the same company later trains a failure-prediction model, the feature table is the challenge query, and the first model review asks precisely whether any feature could see past the inspection time.

2.9 Limits and misconceptions

  • “The query ran and the row count is right, so it is right.” Every mutant kept for this lesson satisfies both. Check the grain, check ties, check a boundary case.
  • “ROW_NUMBER makes it deterministic.” Only if the ordering is total.
  • “ORDER BY in the window sorts the output.” It orders rows for the function only; the result order is undefined without a final ORDER BY.
  • “A window function is slow / always fast.” It needs a sort per distinct window; an index on (partition key, order key) can supply it. The range-join form of an as-of join is quadratic per entity in the worst case. Fine for today’s data; see H3.2.6 for what engines offer.
  • “SQLite behaves like the warehouse.” The window semantics used today are standard. Time arithmetic, types and named as-of syntax differ by engine.

3. Worked example: scan events on two packaging lines

File: example/window_tour.py. Fourteen hand-typed scan events (SYNTHETIC, small enough to follow by eye) in an in-memory SQLite table:

Column Type Meaning
event_id int log order
line text packaging line, A or B
ts text scan time
operator text who scanned
units int units in the scanned batch

Planted on purpose: events 2 and 3 share a timestamp and a unit count; event 9 is an exact re-send of event 8; there are gaps of more than 30 minutes.

!python labs/w2d2_sql_windows_timeseries/example/window_tour.py

The script runs five patterns and asserts that each equals its pandas equivalent. Output of the run on 2026-11-21 (SQLite 3.53.1, pandas 3.0.5), abridged to the three tables worth studying:

--- 1. ranking functions on line A, ORDER BY units DESC ---
 event_id line  units  row_number  rank  dense_rank
        5    A     70           1     1           1
        2    A     55           2     2           2
        3    A     55           3     2           2
        1    A     40           4     4           3
        4    A     30           5     5           4
        6    A     20           6     6           5

--- 3. running total on line A: default frame versus explicit ROWS ---
 event_id                  ts  units  default_frame  rows_frame
        1 2026-05-04 08:00:00     40             40          40
        2 2026-05-04 08:10:00     55            150          95
        3 2026-05-04 08:10:00     55            150         150
        4 2026-05-04 08:25:00     30            180         180
        5 2026-05-04 09:40:00     70            250         250
        6 2026-05-04 09:55:00     20            270         270

--- 4. de-duplicated, sessionised by a 30-minute gap ---
line  session_no            start_ts              end_ts  n_scans  units
   A           1 2026-05-04 08:00:00 2026-05-04 08:25:00        4    180
   A           2 2026-05-04 09:40:00 2026-05-04 09:55:00        2     90
   B           1 2026-05-04 08:05:00 2026-05-04 08:45:00        3    160
   B           2 2026-05-04 10:30:00 2026-05-04 10:40:00        2     50
   B           3 2026-05-04 11:30:00 2026-05-04 11:35:00        2    105
...
All five SQL results equal their pandas equivalents.

Reading the output

  • Table 1. The three functions agree until the tie at 55 units. Which of events 2 and 3 gets row_number 2 is not determined by ORDER BY units DESC; it happened to be event 2.
  • Table 3. Event 2’s default_frame total is 150, not 95: it already contains event 3, its peer. Nothing fails, and the last row of the partition is correct in both columns, which is why this bug survives a glance at totals.
  • Table 4. Line B, session 1 has three scans, not four, because the exact duplicate was removed first. De-duplicating after sessionising would have given 250 units instead of 160.

Code decisions worth noticing

  • The top-1 query (pattern 2 in the script) is shown twice, with RANK and with ROW_NUMBER plus event_id as tie-breaker. Line B has two rows in the first version.
  • Sessionisation is three CTEs — dedup, gaps, numbered — each with one job. The start condition is gap_min IS NULL OR gap_min > 30: the first row of a partition has no predecessor and must start a session explicitly, because NULL > 30 is not true.
  • The pandas version of the ranking uses rank(method="min") and rank(method="dense"). The default, method="average", would give 2.5 for the tied rows and matches no SQL function.
  • Every comparison sorts both results by a key first. SQL results have no inherent order.

Reproduce: the script has no inputs and no randomness; the output above should match exactly apart from the version line.


4. Guided lab: six queries on cold-chain data

You produce: six SQL files in lab/queries/ and three functions in lab/pandas_equiv.py. Each starter file contains the full specification (source, grain, columns, rules) and a placeholder statement.

Read data/README.md first (3 minutes): it lists the tables and the properties built into the data. Then explore:

!python labs/w2d2_sql_windows_timeseries/lab/run_query.py --sql "SELECT * FROM device_status_events LIMIT 8"
!python labs/w2d2_sql_windows_timeseries/lab/run_query.py q1
!python labs/w2d2_sql_windows_timeseries/lab/run_query.py q5 --where "device_id = 'D03'" --rows 30
!python wb.py check w2d2
!python -m pytest labs/w2d2_sql_windows_timeseries/checks -q -k q1

The checks run every query on the shipped database and on a second database generated from a different seed, and compare with results computed independently in plain Python. Column names must match the specification; column order and row order do not matter.

Before each query, write its grain in a comment at the top (you did this in W2D1). It is the fastest way to notice a wrong result.

Task 1 — q1_latest_status.sql: one row per device (5 min)

Latest status per device, with log order deciding between equal timestamps.

Checkpoint: exactly 6 rows. Then run this and explain the difference to yourself:

!python labs/w2d2_sql_windows_timeseries/lab/run_query.py --sql "SELECT device_id, COUNT(*) FROM device_status_events e WHERE ts_epoch = (SELECT MAX(ts_epoch) FROM device_status_events WHERE device_id = e.device_id) GROUP BY 1"

Task 2 — q2_time_in_state.sql: events to intervals (8 min)

Seconds per device and status. LEAD has a three-argument form, LEAD(expr, offset, default), which is the neat way to close the last interval.

Checkpoint: 24 rows (6 devices × 4 statuses in the shipped data). For each device the seconds must sum to the time from its first event to the report end; all six devices start at 2026-03-01 00:00:00, so each total is 259,200.

Task 3 — q3_running_alerts.sql: a running count that survives ties (6 min)

This one runs on the raw table, where a measurement can appear twice with the same timestamp.

Checkpoint: 4,811 rows. Write the obvious version first (SUM(alert) OVER (PARTITION BY device_id ORDER BY ts_epoch)), then find a row where it is wrong:

python labs/w2d2_sql_windows_timeseries/lab/run_query.py q3 --where "reading_id IN (SELECT MIN(reading_id) FROM sensor_readings GROUP BY device_id, ts_epoch HAVING COUNT(*) > 1 AND MIN(alert) <> MAX(alert))" --rows 5

Compare the count on such a row with the count on the row just before it in (ts_epoch, reading_id) order.

Task 4 — q4_rolling_features.sql: a time window on an irregular grid (8 min)

From here on use the view readings_dedup. Look at its definition first:

!python labs/w2d2_sql_windows_timeseries/lab/run_query.py --sql "SELECT sql FROM sqlite_master WHERE name = 'readings_dedup'"

Two windows are needed (one for the 30-minute frame, one for LAG). A WINDOW clause after FROM lets you name them once: WINDOW seq AS (...), w30 AS (...).

Checkpoint: 4,707 rows; n_30m ranges from 1 to 8; gap_s has median 302 and maximum 7,734; delta_prev and gap_s are NULL on exactly 6 rows.

Task 5 — q5_alert_episodes.sql: gaps and islands (8 min)

Checkpoint: 113 episodes in the shipped data, the longest 15 samples. Sanity check you can compute yourself: the sum of n_samples equals SELECT SUM(alert) FROM readings_dedup.

Task 6 — q6_asof_calibration.sql: as-of join (8 min)

Checkpoint: 4,707 rows — the same as readings_dedup; if you have fewer, a join dropped rows; if more, you kept more than one calibration row per reading. 68 rows (all D06, before 06:00 on the first day) have NULL in the three computed columns.

Task 7 — pandas_equiv.py: three functions (15 min)

Implement rolling_features, alert_episodes and asof_calibration. The checks compare each with the specification and with your own SQL result.

Checkpoint: python wb.py check w2d2 passes all 26 checks, in about 2 seconds.

Debugging guidance

Symptom Likely cause
misuse of aliased window function rn You filtered on a window result in the same SELECT. Move the window into a CTE (section 2.2).
more than one row per ['device_id'] Ties: your ordering is not total, or you used RANK.
q2 totals do not sum to the span The last interval is not closed, or LEAD is ordered by ts_epoch alone and a tied pair is taken in the wrong order.
q3 differs on “26 of 4811 rows” or similar small count Default frame; peers are being added to each other.
q4 temp_mean_30m differs on thousands of rows A ROWS frame where time was meant.
q4 differs on a handful of rows Window boundary: is t − 1800 itself included?
q5 has several times too many episodes LAG without PARTITION BY device_id.
q6 has NULLs in different rows than expected Inner join dropped the uncalibrated period, or a later calibration was applied to earlier readings.
pandas ValueError: left keys must be sorted merge_asof needs both frames sorted by the on key (globally, not within by).
pandas rolling result is misaligned After groupby(...).rolling(...) the result has a (group, time) index; align by position only if your frame is sorted the same way.
pandas ValueError: index values must be monotonic Sort by time within each group before a time-based rolling.

Do not print whole tables to find a wrong row. Filter the result with --where, or select the rows around one timestamp for one device.


# Run the automated checks on your guided lab.
# A fresh starter is expected to FAIL; passing means guided practice, not mastery.
from mlcourse.checks import check

check("w2d2")

5. Independent challenge: a point-in-time-correct feature table

Specification and acceptance criteria: challenge/README.md. You write one query, challenge/features.sql, producing five features for each of the 38 rows of maintenance_labels, using only information available at the label time.

!python wb.py check w2d2 --challenge

No solution is linked from here. The check that matters rewrites everything after each label’s timestamp and requires that label’s features to stay exactly the same.


The challenge brief

Type: independent transfer task. No walkthrough, no starter beyond a placeholder. Time: 15 minutes inside the essential path to get a first version; about 30 more to pass the checks. Data: data/coldchain.db, SYNTHETIC (see ../data/README.md).

Scenario

The operations team inspects refrigeration units. Each row of maintenance_labels is one inspection: label_ts is the moment a prediction would have been made, and failed says whether the unit failed within the following hour. You are asked for the feature table a first failure model would be trained on. The model will run at inspection time, so a feature may use only what was recorded at or before label_ts for that unit.

Task

Write one SQL statement in features.sql that returns exactly one row per label with these columns:

Column Definition (all for the label’s own device)
label_id from maintenance_labels
failed from maintenance_labels, unchanged
last_temperature temperature of the most recent reading with ts_epoch <= label_ts_epoch; NULL if there is none
mean_temp_60m mean temperature of readings with label_ts_epoch - 3600 < ts_epoch <= label_ts_epoch; NULL if there are none
n_alerts_24h number of readings with alert = 1 and label_ts_epoch - 86400 < ts_epoch <= label_ts_epoch; 0 if there are none
seconds_since_fault label_ts_epoch minus the ts_epoch of the most recent fault status event at or before the label; NULL if there is none
status_at_label the device status in force at label_ts (latest status event at or before it; log order breaks ties); NULL if there is none

“Reading” means a row of the view readings_dedup. Status events come from device_status_events.

Acceptance criteria

  1. python wb.py check w2d2 --challenge passes. The checks require that
    • the result matches the definitions above on the shipped database and on a re-seeded one;
    • every label yields exactly one row, including a label whose device has no history at all;
    • for every label, rewriting all readings and status events later than its label_ts leaves that label’s five features unchanged.
  2. Each CTE in your query has a one-line comment stating its grain.
  3. In progress/notes.md (python wb.py note w2d2 "..."), three or four sentences answering: which single condition in your query is responsible for point-in-time correctness of each feature, and how would you convince a reviewer who does not read SQL?

Then look at what you built (5 minutes, part of the task)

Compute, for each feature, how well it separates failed = 1 from failed = 0 (for example the ROC AUC of the raw feature with scikit-learn). Write down what you see and what you conclude, keeping in mind there are 38 labels. Then change one of your windows to look one hour past the label and repeat. This comparison is discussed in the assessment answers; do it before reading them.

Out of scope

No model training, no pandas version (optional: reproduce the table with merge_asof and rolling, and assert equality with your SQL result).

# Run the automated checks on your independent challenge.
# A fresh starter is expected to FAIL; passing means guided practice, not mastery.
from mlcourse.checks import check

check("w2d2", challenge=True)

6. Progressive hints

Open them in order, and only after a real attempt. They apply to the challenge; the lab has its own debugging table above.

  1. Hint 1 — concept
  2. Hint 2 — approach
  3. Hint 3 — partial implementation

The full reference solution is in solutions/labs/w2d2_sql_windows_timeseries/. Opening it before your own version passes means the independent flag stays unset for this unit.


Open one hint at a time, only after a real attempt.

Hint 1 concept Every feature in the challenge is a function of "this device's rows up to the label time". Build that set once per source table and everything else is ordinary aggregation or top-1-per-group. * The label table drives the query: the result has **its** grain, one row per `label_id`. Any join that can produce zero matches for a label must be a `LEFT JOIN`, or the label disappears. * The time condition belongs **in the join condition** (`ON ... AND r.ts_epoch <= l.label_ts_epoch`), not in a later `WHERE`. In a `LEFT JOIN`, a `WHERE` on the right-hand table removes the NULL-extended rows and silently turns the join into an inner join. * Two of the five features are "the latest row at or before t" (as-of lookups), two are aggregates over a trailing interval, and one is an as-of lookup restricted to one kind of event. Decide the category of each before writing anything. * Half-open intervals: `(t − W, t]` means `>` on the old side and `<=` on the label side. A reading exactly at the label time is in; the data contains such readings on purpose. If your query passes the "matches specification" checks but fails the future-change check, some condition is symmetric in time (an `ABS`, a `BETWEEN` around the label, a "nearest") or a join is missing its time bound.
Hint 2 approach Write one CTE per feature family, each keyed by `label_id`, then left-join them all back to `maintenance_labels` at the end. Test each CTE on its own with `run_query.py --sql` before combining; state its grain in a comment. 1. **`reading_window`** (grain: label). `maintenance_labels l LEFT JOIN readings_dedup r` on device and on `r.ts_epoch` in the trailing **24-hour** interval. Group by `l.label_id`. - `n_alerts_24h` is a sum over everything joined; wrap it in `COALESCE(..., 0)`. - `mean_temp_60m` is an average over the last hour only. A conditional aggregate does that without a second join: `AVG(CASE WHEN THEN r.temperature END)`. `AVG` ignores NULLs, and returns NULL when nothing qualifies, which is what the specification asks. 2. **`last_reading`** (grain: label). Join labels to readings at or before the label, number them per label by time descending, keep number 1. This is q6 from the lab with a different right side. 3. **`past_events`** (grain: label × past event). Join labels to status events at or before the label and number them per label, latest first, with `event_id` as tie-breaker. Two features read from it: - `status_at_label`: the row numbered 1. - `seconds_since_fault`: among rows with `status = 'fault'`, the smallest `label_ts_epoch - ts_epoch`. 4. **Final select** from `maintenance_labels` with four `LEFT JOIN`s on `label_id`. Check the grain at the end: `SELECT COUNT(*), COUNT(DISTINCT label_id)` over your result must give 38 and 38. </details>
Hint 3 partial The skeleton below is complete for the reading-based features and leaves the two status features to you. The comments mark where point-in-time correctness is decided. ```sql WITH reading_window AS ( -- grain: one row per label SELECT l.label_id, AVG(CASE WHEN r.ts_epoch > l.label_ts_epoch - 3600 THEN r.temperature END) AS mean_temp_60m, COALESCE(SUM(r.alert), 0) AS n_alerts_24h FROM maintenance_labels AS l LEFT JOIN readings_dedup AS r ON r.device_id = l.device_id AND r.ts_epoch <= l.label_ts_epoch -- nothing after the label AND r.ts_epoch > l.label_ts_epoch - 86400 GROUP BY l.label_id ), last_reading AS ( -- grain: one row per label that has any earlier reading SELECT label_id, temperature AS last_temperature FROM ( SELECT l.label_id, r.temperature, ROW_NUMBER() OVER (PARTITION BY l.label_id ORDER BY r.ts_epoch DESC) AS rn FROM maintenance_labels AS l JOIN readings_dedup AS r ON r.device_id = l.device_id AND r.ts_epoch <= l.label_ts_epoch -- nothing after the label ) WHERE rn = 1 ), past_events AS ( -- grain: one row per (label, status event at or before it) SELECT l.label_id, l.label_ts_epoch, e.status, e.ts_epoch, ROW_NUMBER() OVER (PARTITION BY l.label_id ORDER BY /* latest first, total order */) AS rn FROM maintenance_labels AS l JOIN device_status_events AS e ON e.device_id = l.device_id AND /* time bound */ ) -- TODO: status_now (label_id, status_at_label) from past_events -- TODO: last_fault (label_id, seconds_since_fault) from past_events SELECT l.label_id, l.failed, lr.last_temperature, rw.mean_temp_60m, rw.n_alerts_24h -- , seconds_since_fault, status_at_label FROM maintenance_labels AS l LEFT JOIN reading_window AS rw ON rw.label_id = l.label_id LEFT JOIN last_reading AS lr ON lr.label_id = l.label_id; ``` Why `last_reading` may use an inner join while `reading_window` may not: `last_reading` is left-joined to the labels in the final select, so a label without readings still appears; `reading_window` computes a count that must be 0 rather than missing, so the label has to survive inside the CTE.
## 7. Assessment `assessment.md` (section 7 of this notebook): five short reasoning questions, one design-choice explanation, the rubric, and a 10–15 minute SQL interview rep. Write your answers before opening `solutions/labs/w2d2_sql_windows_timeseries/assessment_answers.md`. Automated checks: `python wb.py check w2d2` (lab, 26 checks) and `python wb.py check w2d2 --challenge` (4 checks). --- ### Assessment questions Write your answers (a few sentences each, plus SQL where asked) before opening `solutions/labs/w2d2_sql_windows_timeseries/assessment_answers.md`. Automated checks cover the lab and the challenge; these questions cover the reasoning the checks cannot see. #### Reasoning questions **Q1 — frames by hand.** A table has four rows `(id, t, x)`: `(1, 1, 10)`, `(2, 2, 20)`, `(3, 2, 5)`, `(4, 3, 1)`. Without running anything, give the four values of each expression, listed by `id`: - (a) `SUM(x) OVER (ORDER BY t)` - (b) `SUM(x) OVER (ORDER BY t, id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)` - (c) `SUM(x) OVER ()` Then say in one sentence why (a) and (b) differ. **Q2 — evaluation order.** This query is meant to return, for each alerting reading, the time since the device's previous reading: ```sql SELECT reading_id, ts_epoch - LAG(ts_epoch) OVER (PARTITION BY device_id ORDER BY ts_epoch) AS gap_s FROM readings_dedup WHERE alert = 1; ``` What does it actually return, why, and how do you fix it? **Q3 — "latest row".** Three colleagues compute the latest status per device with (i) `WHERE ts = (SELECT MAX(ts) ...)`, (ii) `RANK() ... = 1`, (iii) `ROW_NUMBER() OVER (PARTITION BY device_id ORDER BY ts DESC) = 1`. For data with tied timestamps, describe the result of each and the consequence for a downstream `JOIN ... USING (device_id)`. Which would you accept in review? **Q4 — changing the definition of an event.** Operations asks that two alert runs separated by a *single* non-alert reading be reported as one episode. Describe the change to the gaps-and-islands query from the lab (the start condition is enough; SQL is welcome). How does this relate to event merging rules in signal-based detectors (a refractory gap, a minimum duration)? **Q5 — is it point-in-time correct?** For each feature attached to a label at time `t`, say whether it can read the future and why: - (a) the device's mean temperature over the calendar month containing `t`; - (b) temperature z-scored with the mean and standard deviation of the whole `sensor_readings` table; - (c) `last_temperature` as defined in the challenge, computed from `readings_dedup`. #### Design-choice explanation **Q6.** The calibration as-of join must go to production on a warehouse table with about 500 million readings and 2,000 calibration rows. Three designs are proposed: 1. the lab's pattern: join on `valid_from <= ts`, then `ROW_NUMBER()` and keep 1; 2. first turn `calibration` into intervals `[valid_from, valid_to)` with `LEAD`, then join on `valid_from <= ts AND ts < valid_to`; 3. export both tables and use `pandas.merge_asof`. Choose one and justify it in 6–10 sentences. Address correctness (ties, boundaries, readings before the first calibration), cost, and how the result will be tested. #### Rubric | Criterion | Not yet | Adequate | Strong | |---|---|---|---| | Frame semantics (Q1) | values guessed or (a) = (b) | all values right | explains peers and the default frame, and why the last row hides the error | | Evaluation order (Q2) | "LAG is wrong" without mechanism | identifies that `WHERE` runs before the window; gives a two-level fix | also notes the same hazard for any filter (time range, device subset) and for pandas `df[mask].shift()` | | Uniqueness contracts (Q3) | prefers (i) or (ii) | picks `ROW_NUMBER`, notes fan-out | demands a total order, states that (iii) as written is non-deterministic, proposes a uniqueness test | | Transfer of islands (Q4) | restarts from scratch or changes the grouping | correct new start condition | relates it to merge-gap / minimum-duration rules and notes the definition is in rows, not seconds | | Leakage reasoning (Q5) | judges by whether a timestamp is "used" | (a) and (b) leak, with reasons | also catches (c): values corrected after `t`; names the missing column | | Design explanation (Q6) | chooses by familiarity | defensible choice with cost and correctness | states the invariants to test (row count, future-invariance, boundary inclusion) and what would change the decision | #### Interview rep — SQL (10–15 minutes, timed) Conditions for Week 2: first attempt untimed is allowed, but time yourself. Write the query before running anything; then build a six-row table and test it. Say the grain of every intermediate result aloud. > Table `logins(user_id TEXT, login_date TEXT)` holds one row per login, with dates as > `YYYY-MM-DD`. A user may log in several times a day. For each user return the length in days of > their longest streak of consecutive calendar days with at least one login, and the first day of > that streak. If a user has two longest streaks of equal length, return the earlier one. > One row per user. Follow-up questions an interviewer would ask: What is the grain after your first step? What does your query do at a month boundary? How would it change if "consecutive" allowed one missed day? Log the rep in `progress/notes.md`: time taken, what went wrong, the pattern behind the error. ## 8. Reflection and review **You should now be able to, without help** - return exactly one "latest" row per entity on data with tied timestamps, and say why it is exactly one; - write a running or moving statistic with an explicit frame and justify `ROWS` versus `RANGE`; - convert a per-row flag into events (or sessions) with start, end and size, per entity; - join a fact to the dimension row in force at the fact's time, keeping unmatched facts; - state and test the invariant that makes a feature point-in-time correct; - reproduce each of these in pandas and name the boundary case where a naive translation differs. **Reflection prompt** (3 minutes, in `progress/notes.md` via `python wb.py note w2d2 "..."`): In your own research pipelines, where was a "centred" or "nearest" operation applied to data that would later be used to predict something? Would that operation have been available online? **Retrieval question — answer from memory at the Week 2 review (w2d7) and again in Week 3:** A colleague's feature query uses `AVG(x) OVER (PARTITION BY device_id ORDER BY ts)` and reports "mean of the last readings". (a) Exactly which rows are averaged for a given row? (b) Name two data conditions under which this differs from what they probably meant. (c) What test would you run to show that no feature in their table reads the future? **Next:** [W2D3 — pandas ingestion, schemas and data-quality checks](09_data_quality_ingestion.html) (`w2d3_data_quality_ingestion`). Today's de-duplication view and tie rules are data-quality decisions that were made *for* you; tomorrow you write such rules as code that fails loudly, on the project dataset. The point-in-time idea returns in `w2d5` (causal rolling features) and `w3d1` (leakage taxonomy). --- ## Verification record Executed on 2026-11-21 with Python 3.13.18, SQLite 3.53.1, pandas 3.0.5, NumPy 2.5.3, pytest 9.1.1. | What | Result | |---|---| | `python labs/w2d2_sql_windows_timeseries/example/window_tour.py` | ran; output above copied from this run; all five SQL-versus-pandas assertions hold | | `python labs/w2d2_sql_windows_timeseries/data/make_db.py --check` | regenerated table contents identical to the committed database | | Reference SQL and pandas versus the independent plain-Python oracle | equal on the shipped database and on a re-seeded one (seed 77) | | `python tools/verify_checks.py labs/w2d2_sql_windows_timeseries` | lab: solution passes, 7 mutants rejected; challenge: solution passes, 3 mutants rejected | | Shipped starter | lab checks: 26 of 26 fail; challenge checks: 4 of 4 fail | | Check runtime | lab about 2 s, challenge about 2 s | | Interview-rep reference query | executed against a hand-checked table; expected rows returned | Row counts and other numbers in sections 2–4 were read from these runs. Not verified: any SQLite older than 3.53.1 (the 3.28 minimum is from memory of the SQLite release history; the SQLite documentation site was unreachable from the authoring environment), Python 3.11 and 3.12, and behaviour on other database engines. ## Record your progress Tick only what is true. Passing the supplied checks is *guided practice*; mark *independent* only for work done without hints or solutions. ```python from mlcourse.progress import mark, note # mark("w2d2", "reading") # mark("w2d2", "guided") # mark("w2d2", "independent") # note("w2d2", "what tripped me up today") ```

Back to top

Applied ML Engineering course materials. Code is MIT licensed; prose is CC BY 4.0. The SKAB dataset is GPL-3.0 and is downloaded from its source, not redistributed here.