
A navigation engineer wants to distinguish a sequential next section from the first observed session. The absence of a previous section should be visible rather than treated as section zero. The table records a reading session, not the current state of a book. One reader may revisit several sections. Finished marks this session’s section completion and does not imply that the whole book was finished.
Build the small reproduction
The fixture uses a fresh SQLite database. Its small size allows the result to be checked by hand before the query is applied to an export with thousands of rows. The unit of observation matters here because a query can execute cleanly and still answer a different editorial or operational question.
CREATE TABLE reads (
id INTEGER PRIMARY KEY,
reader TEXT,
book TEXT,
section INTEGER,
seconds INTEGER,
finished INTEGER
);
INSERT INTO reads VALUES
(1, 'Mira', 'Atlas', 1, 60, 1),
(2, 'Mira', 'Atlas', 2, 130, 1),
(3, 'Ira', 'Atlas', 1, 95, 1),
(4, 'Ira', 'Orbit', 1, 22, 0),
(5, 'Mira', 'Orbit', 1, 75, 1),
(6, 'Dev', 'Orbit', 2, NULL, 0);Run the query and inspect its grain
WITH x AS (SELECT id,reader,book,section,lag(section) OVER(PARTITION BY reader,book
ORDER BY id) AS prev
FROM reads) SELECT reader,book,section,section-prev AS step
FROM x
ORDER BY id;| reader | book | section | step |
|---|---|---|---|
| Mira | Atlas | 1 | NULL |
| Mira | Atlas | 2 | 1 |
| Ira | Atlas | 1 | NULL |
| Ira | Orbit | 1 | NULL |
| Mira | Orbit | 1 | NULL |
| Dev | Orbit | 2 | NULL |
A step larger than one means the recorded section advanced by several numbers. Missing events can produce the same pattern as an intentional jump.
What changes with one more record?
Append this single row to the same fixture and rerun the query. Its named fields are id = 7, reader = Dev, book = Atlas, section = 1, seconds = 90, finished = 1. Keep the other rows intact so a comparison isolates the effect of this one insert.
INSERT INTO reads VALUES (7, 'Dev', 'Atlas', 1, 90, 1);The original query returned 6 rows. After the insert it returns 7. One resulting row is ["Dev", "Atlas", 1, null]. 6 earlier output rows still appear unchanged.
Before exporting the result, document what one displayed row represents and which fields decide its order. Look for the same shape of input in an anonymized sample from the application. A query validated only against an empty development database cannot show what happens when a record is missing, repeated or tied with another record.
SQLite reference for window LAG delta · SQLite SQL syntax reference
Sources and further reading
Cover photograph: StorageTek tape library (51993015872) by Jorge Franganillo. CC BY 2.0. Cropped and typeset for this cover. The photograph illustrates the topic.
