Skip to content
Astera Technology

Why does a flagged sample lose its actual previous reading?

Calculate LAG on the full history before filtering displayed rows.

Download complete case notes and answer keys ↓

Prepare the report input

Original report shows flagged samples beside their immediate previous recorded reading by id. Filtering flagged=1 inside the window input removes unflagged history. Compute LAG in a full-history CTE and then select flagged rows.

Every record and report rule below is original and fictional. Reproduce the setup in a fresh SQLite test database; input previews include every table in this small fixture.

Synthetic input: samples
idreadingflagged
150
281
391
Download editable CSV ↓
Complete CREATE and INSERT fixture
CREATE TABLE samples(id INTEGER PRIMARY KEY,reading INTEGER NOT NULL,flagged INTEGER NOT NULL CHECK(flagged IN(0,1))); INSERT INTO samples VALUES(1,5,0),(2,8,1),(3,9,1);

Compare misleading and corrected results

Misleading SELECT: reproduce the defect
SELECT id,reading,LAG(reading) OVER(ORDER BY id) AS previous FROM samples WHERE flagged=1 ORDER BY id;
Literal misleading result
idreadingprevious
28NULL (unknown or absent)
398
Download editable CSV ↓
Corrected SELECT
WITH history AS (SELECT *,LAG(reading) OVER(ORDER BY id) AS previous FROM samples) SELECT id,reading,previous FROM history WHERE flagged=1 ORDER BY id;
Literal corrected result
idreadingprevious
285
398
Download editable CSV ↓

Sample 2 should show previous 5, but the bad query shows NULL because sample 1 was removed. Sample 3 correctly follows sample 2 in both results.

Check a fresh boundary case

Flag the first sample too. It legitimately has no prior row and remains NULL, while later prior values stay five/eight.

Recreate the original setup in another fresh database, then apply the change and corrected query below. For an empty result, the table displays a labelled empty-result marker rather than a data record.

Boundary change and corrected query
UPDATE samples SET flagged=1 WHERE id=1;
WITH history AS (SELECT *,LAG(reading) OVER(ORDER BY id) AS previous FROM samples) SELECT id,reading,previous FROM history WHERE flagged=1 ORDER BY id;
Literal boundary result
idreadingprevious
15NULL (unknown or absent)
285
398
Download editable CSV ↓

Which NULL is legitimate in the boundary result?

Show the worked answer

The first sample’s previous value. Sample 2 has real prior sample 1 and must show five.

Related resources