Quick revision
The short answer
Use LAG to look at the two previous readings in id order and keep values equal to both: SELECT DISTINCT value FROM (SELECT value, LAG(value, 1) OVER (ORDER BY id) p1, LAG(value, 2) OVER (ORDER BY id) p2 FROM reading) t WHERE value = p1 AND value = p2. Because LAG follows row order rather than id arithmetic, gaps in the ids do not break it, while a self join on id = id - 1 silently misses runs that span a gap.
What to remember
In this answer, we used LAG to compare each reading with the two before it and kept values equal to both, which finds three in a row. We saw that LAG follows row order, so gaps in ids are harmless, while a self join on id + 1 misses runs across a gap. For any length we used the difference of two ROW_NUMBERs as an island key, and we saw that NULL runs need IS NOT DISTINCT FROM or the islands method.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
Use LAG to look at the two previous readings in id order and keep values equal to both: SELECT DISTINCT value FROM (SELECT value, LAG(value, 1) OVER (ORDER BY id) p1, LAG(value, 2) OVER (ORDER BY id) p2 FROM reading) t WHERE value = p1 AND value = p2. Because LAG follows row order rather than id arithmetic, gaps in the ids do not break it, while a self join on id = id - 1 silently misses runs that span a gap.
Why this question is asked
Consecutive-values questions come up whenever data arrives as a sequence: sensor readings, prices, login attempts, build results. Interviewers use this one to see whether we reach for window functions, and the second half of the question checks whether we understand the difference between the order of rows and the arithmetic of their ids. In this answer, we will recap how LAG works, write the three-in-a-row query, reproduce what breaks with the classic self join when ids have gaps, generalise to any run length with the islands method, and look at how NULL values behave.
1A Quick Recap of LAG
LAG is a window function, a function that looks at other rows related to the current row without collapsing them into one. LAG(value, n) OVER (ORDER BY id) returns the value from the row n positions earlier in that ordering, or NULL when there is no such row.
The important word is positions. LAG does not compute id - 1 and look it up. It sorts the rows by id and steps back n rows in that sorted list, whatever their ids are. That one property answers the second half of the question.
2Writing the Three-in-a-Row Query
For each reading we fetch the value one row back and two rows back. A value appears three times in a row exactly when the current value equals both.
At id 3 the current value is 1, p1 is 1 and p2 is 1, so the row qualifies. No other row has three equal values ending at it. We need DISTINCT because a run of five 1s would qualify at three different rows and return 1 three times.
Notice that the filter has to live in an outer query. Window functions are computed after WHERE, so we cannot write WHERE value = LAG(value) in the same SELECT.
3What Breaks When Ids Have Gaps
Ids are rarely contiguous in practice. Sequences skip numbers after a rollback, deleted rows leave holes, and many systems hand out ids in blocks. The classic self join solution assumes the next reading has exactly the next id.
| Approach | Looks for | Result on ids 1, 2, 4 |
|---|---|---|
| Self join on id + 1 | rows whose id is exactly one higher | misses the run, id 3 is absent |
| LAG over ORDER BY id | the previous rows in sorted order | finds the run of 9 |
The self join looks for id 3, finds nothing, and silently drops a real run. The LAG query sorts by id, sees 1, 2, 4 as three neighbouring rows and correctly returns 9. If we ever must use arithmetic, for example on an old database without window functions, we can first renumber with ROW_NUMBER() OVER (ORDER BY id) and join on that number instead of the id.
There is a related catch in the other direction. If ids do not reflect the real order, for example when they are random UUIDs or come from several writers, neither approach is correct. Then we must order by a column that does represent the sequence, such as a measured_at timestamp.
4Any Run Length With the Islands Method
LAG works well for three, but for runs of ten we would need ten LAG columns. The islands method handles any length k. We number all rows in id order, and separately number the rows of each value in id order. Within a run of equal values both numbers increase together, so their difference is constant for that run.
We must group by value as well as grp, because two different values can produce the same difference. The same query also answers the usual follow-up, the start and end id of each run, through MIN(id) and MAX(id).
5What Happens With NULL Values
In SQL, NULL = NULL is not true but unknown, and WHERE keeps only rows where the condition is true. So in the LAG query a run of three NULL readings is never found. If NULL runs matter, for example to detect a sensor that stopped reporting, we compare with IS NOT DISTINCT FROM, which treats two NULLs as equal.
Notice the rn >= 3 condition. LAG also returns NULL for the first two rows, which have no predecessors, so without it a single NULL in the first row would look like the end of a NULL run. The islands method needs no such care, because PARTITION BY and GROUP BY already place NULLs together in one group, so NULL runs are found there by default. It is worth saying in the interview which behaviour we want, because quietly ignoring NULL runs is often a bug.
6Follow-up questions
How would you return the start and end id of each run?
Use the islands method: compute ROW_NUMBER() OVER (ORDER BY id) minus ROW_NUMBER() OVER (PARTITION BY value ORDER BY id) as a group key, group by value and that key, and select MIN(id) as the start and MAX(id) as the end, keeping groups with HAVING COUNT(*) >= 3. With LAG alone we only know where a run reaches length three, not where it starts or ends.
Does this work in MySQL?
Yes. MySQL 8 supports LAG and ROW_NUMBER with the same syntax. Older MySQL 5.7 has no window functions, which is the main reason the self join and user-variable tricks still appear in old answers.
Is the LAG query efficient on a large table?
It needs the rows in id order, which the primary key index already provides, so it is a single ordered scan. The islands method needs a second sort by value and id, so on very large tables an index on (value, id) helps.
7Conclusion
In this answer, we used LAG to compare each reading with the two before it and kept values equal to both, which finds three in a row. We saw that LAG follows row order, so gaps in ids are harmless, while a self join on id + 1 misses runs across a gap. For any length we used the difference of two ROW_NUMBERs as an island key, and we saw that NULL runs need IS NOT DISTINCT FROM or the islands method.
Open with
I would use LAG. In an inner query I select the value together with LAG of value by one and by two over ORDER BY id, and in the outer query I keep rows where the value equals both, with DISTINCT so that a longer run does not return the value several times.
Then, if they want more
The filter must be outside because window functions are evaluated after WHERE. On the second part: LAG steps back by position in the sorted order, not by id arithmetic, so if ids are 1, 2 and 4 because a row was deleted or a sequence skipped, it still sees three neighbouring readings.
The classic self join on r2.id equals r1.id plus one would look for id 3, find nothing and silently miss the run. If I needed arithmetic I would renumber with ROW_NUMBER first.
For a general length k, I would use the islands method: row number over all rows minus row number partitioned by value gives a constant key per run, and grouping by value and key with HAVING COUNT at least k finds runs of any length, with MIN and MAX of id as start and end.
I would also mention NULLs: NULL equals NULL is unknown, so runs of NULL are not found unless I compare with IS NOT DISTINCT FROM, and I would ask whether those runs matter. And if ids did not reflect real order, I would order by a timestamp instead.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- MySQL 5.7, MySQL 8
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- PostgreSQL documentation, The SQL Language
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Table reading(id int primary key, value int), where id gives the order of readings....": https://scrivio-interview-library.netlify.app/databases/sql-coding-problems/63c87c116b/