Quick revision
The short answer
For change detection we compare each value with the previous one: value / NULLIF(LAG(value) OVER (PARTITION BY device_id ORDER BY ts), 0) above 1.2 or below 0.8. For state durations, LEAD(ts) OVER (PARTITION BY device_id ORDER BY ts) - ts gives the time until the next reading or state change. On 10 billion rows these queries must be restricted by time range and partition with an index on (device_id, ts), and real-time alerts belong in a stream processor that keeps the last value per device in state, with SQL used for batch reports; late and out-of-order readings must be handled explicitly in both.
What to remember
In this answer, we used LAG to compare each reading with the previous one for change detection, guarded with NULLIF, and combined LAG and LEAD to collapse runs of the same state and measure how long each lasted. On 10 billion rows, these queries run only on time-restricted partitions with an index on (device_id, ts), or on downsampled data. Real-time alerts belong in a stream processor such as Kafka Streams or Flink that keeps the last value per device in state, and both the SQL reports and the stream must handle late and out-of-order readings explicitly.
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.
For change detection we compare each value with the previous one: value / NULLIF(LAG(value) OVER (PARTITION BY device_id ORDER BY ts), 0) above 1.2 or below 0.8. For state durations, LEAD(ts) OVER (PARTITION BY device_id ORDER BY ts) - ts gives the time until the next reading or state change. On 10 billion rows these queries must be restricted by time range and partition with an index on (device_id, ts), and real-time alerts belong in a stream processor that keeps the last value per device in state, with SQL used for batch reports; late and out-of-order readings must be handled explicitly in both.
Why this question is asked
IoT data is the textbook case for LAG and LEAD, because almost every question about a sensor is about change: how much did the value move since the last reading, how long did the machine stay in this state. It is also where naive SQL meets very large tables and real-time expectations. Interviewers ask this scenario to see whether we can write the window logic and, just as important, decide what should run in the database and what should run in a stream. In this answer, we will recap LAG and LEAD, write the change detection and the state duration queries, make them workable on 10 billion rows, move the alerting into a stream processor, and handle late and out-of-order readings.
1A Quick Recap of LAG and LEAD
LAG(x) is a window function that returns x from the previous row in the window's order, and LEAD(x) returns it from the next row. With PARTITION BY device_id ORDER BY ts, the previous row means the previous reading of the same device. The first reading of each device has no previous row, so LAG returns NULL there, and the last has no next row, so LEAD returns NULL.
2Detecting a Change of More Than 20 Percent
The rule is that a reading is interesting when it is more than 20 percent above or below the previous reading of the same device. Dividing by the previous value gives the ratio, and NULLIF protects against a previous value of zero, which would otherwise abort the query with a division by zero error.
Notice that the filter is in an outer query, because window functions are computed after WHERE. Two refinements are worth mentioning in the interview. If values can be negative or cross zero, a ratio is misleading, and abs(value - prev) > 0.2 * abs(prev) states the rule better. And the first reading of the day has no previous reading inside our time range, so to judge it we extend the inner query's range slightly backwards, for example by an hour, and filter the output to the day.
3Measuring How Long Each Device Stayed in Each State
Suppose each reading maps to a state, for example idle below 10, running from 10 to 80, and overload above 80. A device reports every few seconds, so the same state repeats on many rows. We first collapse each run of the same state into one row, using LAG to mark where the state changes, and then use LEAD to find when the next state began.
IS DISTINCT FROM treats NULL as a value, so the first row of each device, whose prev_state is NULL, is kept as the start of a run. The last run of the day has no next change, so LEAD gives NULL and its duration is open; the report either shows it as ongoing or caps it at the end of the range. If we only want time until the next reading, not the next state change, LEAD(ts) over the raw readings gives that directly.
4Making It Work on 10 Billion Rows
A window function over the whole table would sort 10 billion rows by device and time. That is never what we want. Every query must be restricted to a time range first, and the table must be organised so that the restriction is cheap.
The usual layout is a table partitioned by time, daily or hourly, so that a one-day query reads only one partition. TimescaleDB does this automatically with chunks. Inside each partition an index on (device_id, ts) lets the window read each device's readings already in order, so the database can skip the sort. With 50,000 devices reporting every 5 seconds, one day is about 860 million rows, still large, so batch reports often run per device group or over a downsampled table of one-minute averages that is a hundred times smaller.
| Question | Where | Why |
|---|---|---|
| Alert on a jump of more than 20 percent | Stream processor | Needs seconds of latency, one value of state per device |
| Daily time in each state per device | SQL batch on a day partition | Set-based, needs the whole day |
| Monthly uptime report | SQL on downsampled data | Raw rows are too many for a month |
| Investigate one device's last hour | SQL with the (device_id, ts) index | Small, indexed, ad hoc |
5Real-Time Alerts Belong in a Stream Processor
Running the LAG query every minute to find new alerts means rescanning recent data constantly and still being up to a minute late. A stream processor does it naturally. Readings arrive on a Kafka topic keyed by device_id, so all readings of a device go to the same partition and the same processing task. The task keeps the last value per device in a local state store, compares each new reading with it, emits an alert if the change exceeds 20 percent, and updates the stored value. That is exactly what LAG does, but incrementally, one reading at a time, with millisecond latency.
6 messages in order. Play them, or step through them one at a time.
The state store is backed by a changelog topic, so if the task restarts it rebuilds the last value per device. Flink offers the same pattern with keyed state. SQL remains the right tool for the batch reports, where the question is about a whole day or month rather than the next reading.
6Late and Out-of-Order Readings
Devices buffer readings when their network drops and send them later, so readings do not always arrive in timestamp order. In SQL this is easy to get right because ORDER BY ts uses event time, the time the reading was taken, no matter when it arrived. But a report that ran before the late readings arrived was computed on incomplete data, so batch jobs should run after an agreed delay, or recompute recent days.
In the stream it is harder. If an old reading arrives after a newer one, comparing it with the stored 'last' value compares in the wrong order. The sketch above ignores readings older than the stored one, which is simple but drops them from alerting. Flink's event-time processing with watermarks, a moving estimate of how late data can be, lets us buffer readings for a few seconds and process them in timestamp order. The product decision is how late is too late, for example 30 seconds, after which a reading is stored for reports but not alerted on.
7Follow-up questions
Why not use a trigger on the readings table to raise alerts?
A row-level trigger would run on every insert, 10,000 a second here, adding latency to ingestion and coupling alerting to the database's availability. It also has to look up the previous reading with a query each time. A stream processor keeps that state in memory, scales by partition and isolates failures from the database.
How do you avoid an alert storm when a sensor is noisy?
Add hysteresis and suppression in the stream: require the change to persist for, say, three readings, or compare with a short moving average instead of the single previous value, and suppress repeated alerts for the same device for a few minutes. These rules are product decisions, but the state store makes them cheap.
Would you store raw readings forever?
Usually not at full resolution. A common policy keeps raw readings for 30 to 90 days, one-minute aggregates for a year or two, and hourly aggregates indefinitely. TimescaleDB continuous aggregates or a scheduled job produce the downsampled tables, and old raw partitions are dropped, which is cheap with time partitioning.
8Conclusion
In this answer, we used LAG to compare each reading with the previous one for change detection, guarded with NULLIF, and combined LAG and LEAD to collapse runs of the same state and measure how long each lasted. On 10 billion rows, these queries run only on time-restricted partitions with an index on (device_id, ts), or on downsampled data. Real-time alerts belong in a stream processor such as Kafka Streams or Flink that keeps the last value per device in state, and both the SQL reports and the stream must handle late and out-of-order readings explicitly.
Open with
For the change alert I'd compare each reading with the previous reading of the same device: LAG(value) OVER (PARTITION BY device_id ORDER BY ts), and flag rows where value divided by NULLIF of that previous value is above 1.2 or below 0.8, filtering in an outer query because windows run after WHERE.
Then, if they want more
For state durations, I'd map values to states, use LAG to keep only the rows where the state changes, and then LEAD(ts) minus ts gives how long each state lasted. On 10 billion rows I'd never run these over the whole table.
The table should be partitioned by time, or use TimescaleDB chunks, with an index on device_id and ts, and every query restricted to a time range, ideally on downsampled data for long periods. But I wouldn't do real-time alerting in SQL at all.
Readings go to Kafka keyed by device, and a Kafka Streams or Flink job keeps the last value per device in a state store and alerts the moment a jump arrives. That's LAG done incrementally. SQL stays for batch reports.
Finally, I'd handle out-of-order and late readings explicitly: event time in SQL, a delay or recompute for reports, and in the stream either watermarks with a small buffer or a rule for ignoring readings older than the last one.
About this answer
- Last updated
- 12 November 2026
- 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 "An IoT table readings(device_id, ts, value) has 10 billion rows. Product wants alerts...": https://scrivio-interview-library.netlify.app/databases/advanced-sql/fcc7cc0633/