
An editor wants the most recent observed book beside every session in a reader’s history. A default ordered frame can stop at the current row and make the result look deceptively obvious. 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.
Set up an in-memory example
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);Inspect the selected rows
SELECT reader,id,book,last_value(book) OVER(PARTITION BY reader
ORDER BY id ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS final_book
FROM reads
ORDER BY reader,id;| reader | id | book | final_book |
|---|---|---|---|
| Dev | 6 | Orbit | Orbit |
| Ira | 3 | Atlas | Orbit |
| Ira | 4 | Orbit | Orbit |
| Mira | 1 | Atlas | Orbit |
| Mira | 2 | Atlas | Orbit |
| Mira | 5 | Orbit | Orbit |
The explicit frame reaches the end of the partition. Its final book can change when another session arrives later.
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", 6, "Orbit", "Atlas"]. The former row ["Dev", 6, "Orbit", "Orbit"] no longer appears in exactly that form. 5 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 last_value · SQLite SQL syntax reference
Sources and further reading
Cover photograph: SAMSUNG SD CARD PRO PLUS 256 GB (2021 EDITION) REAR by Dinkun Chen. CC BY-SA 4.0. Cropped and typeset for this cover. The photograph illustrates the topic. This image adaptation uses the same share-alike license.
