The Math Behind Idle Time: Merging Time Intervals in SQL

Two reports sat side by side in the meeting room. The monthly idling time the customer's fuel department had calculated by hand in Excel: 218 hours. What our platform reported for the same fleet: 342 hours. A 57 percent difference. The customer rightly asked, "Which one of you should I believe?" I still stand by the answer I gave at the table that day: "We're both wrong, but for different reasons." Their Excel was missing short idling periods; our SQL, meanwhile, was sometimes counting the same idle period three times. This post is the story of the fix that came out of that embarrassment — and of the lovely SQL problem underneath it.

Why Idling Is Hard: The Stuttering Signal

By definition, idling is simple: the engine is running and the vehicle is moving... sorry, not moving. Ignition on, speed zero. The device already sends a record every 10-30 seconds, with speed and ignition data inside. "Add up the duration of records with zero speed and ignition on" — that was the logic of the first version, and it was leaking in two places.

First, the signal stutters. While a vehicle is waiting at a light, the GPS speed jitters: 0, 2, 0, 3, 0 km/h (readers of my earlier Kalman post will find this familiar). In the naive algorithm, every jump off zero "ends" the idle period, and every return to zero "starts" a new one. A single five-minute wait shows up in the report as four separate two-minute idle periods; the customer's "list idle periods longer than 3 minutes" filter misses all of them. Second, the data has holes. GPRS dropouts create gaps of 40-50 seconds in the records; are the idle periods on either side of the gap separate, or the same one? If you don't have an answer, your report is arbitrary.

Abstract the problem and you run into its name in the literature: gaps and islands. You have timestamped rows; you want to group the consecutive ones that are "in the same state" into islands, and handle the gaps between the islands. The idling calculation is the sum of the islands' durations. SQL can solve this problem in a single query with no loops — as long as you have window functions.

Excel misses short idle periods, while SQL counts the same idle period more than once; both numbers are wrong for different reasons.
The 57 percent difference came from not having a definition of an island.

The Little Miracle of Row Number Differences

The heart of the classic solution is a clever observation. Give the records a sequence number by time (ROW_NUMBER, over all records), and also give a separate sequence number to the idle records only. In consecutive idle records, the two numbers increase together; their difference stays constant. When the idle chain breaks and starts again, the difference changes. So the value (overall sequence − idle sequence) is an identifier unique to each island; with GROUP BY, you collect the islands in one go. The first time I saw it, I could only convince myself by drawing three examples on paper — and when I explained it to the team, everyone drew the same three sketches. (SQL that's copied without being understood blows up in production without being understood; make people draw it.)

In production we used the LAG variant of this, because our island definition isn't just "same state": the time gap in between must also not exceed a tolerance. The query's backbone has three layers. The first layer uses LAG to fetch the previous record's time and state for each record. The second layer computes the "new island start" flag: 1 if the state changed or if the gap from the previous record is more than 90 seconds, otherwise 0. The third layer takes the running total of this flag — SUM(bayrak) OVER (PARTITION BY arac_id ORDER BY zaman) (bayrak being the flag, arac_id the vehicle, and zaman the timestamp) — and there's your island number. A running total is a counter that goes up by one at each flag; rows without a flag stick to the previous island. The outer query groups by island number: MIN(zaman) is the start, MAX(zaman) the end, plus the count and the duration.

The 90-second tolerance was also chosen with data, not at a desk: our record interval is 30 seconds in the worst case, and 95 percent of GPRS dropouts are under 60 seconds. 90 seconds forgives both, but doesn't merge a genuine "turned the engine off and started it again five minutes later" event. When we tried raising the tolerance to 300 seconds, total idling went up 9 percent — so this single parameter visibly moves the number that goes to the customer. We had the parameters printed in the report's footnote; when two numbers are competing, methodological transparency is the only source of credibility.

LAG fetches the previous record, a new-island flag is computed, the running total gives the island number, and rows are grouped by island.
The 90-second tolerance was chosen with data.

Who Will Silence the Speed Jitter?

Back to the stuttering signal problem: we solved it not in SQL, but before SQL. State detection (idling, driving, or parked) now happens in the processing pipeline, with hysteresis: to enter idling, speed has to stay below 3 km/h for 20 seconds; to exit, it has to stay above 5 km/h for 10 seconds. Having two different thresholds is deliberate — a single threshold would make a signal jittering right around it stutter all over again. Once a clean state column arrived at the SQL layer, the query got simpler too. There's a general lesson here: the layer where you can solve a problem and the layer where you should solve it are different; signal processing isn't SQL's job.

Opening Windows Over 1.9 Billion Rows

Now the performance chapter: window functions came to MySQL with 8.0, and this need was at the top of our reasons for migrating from 5.7 to 8.0. (On 5.7 we had a version that did the same job with user variables — the @prev := ... trick; it worked, but since the optimizer makes no guarantees about the order of variable evaluation, our hearts were in our mouths at every version upgrade.) The monthly report scans about 25 million rows for a 300-vehicle fleet; the windowed query took 4 minutes on the first try. Two fixes brought it down to 19 seconds: making sure partition pruning worked (a date filter on the bare column), and a composite index that exactly matches the PARTITION BY arac_id ORDER BY zaman ordering — the window function's sorting cost evaporates if the index is already sorted. We also added a job that precomputes the report at night and writes it to a summary table; the morning report now looks at ready-made islands instead of 25 million rows.

The MySQL 8.0 migration, partition pruning, a composite index, and a nightly summary table cut query time from 4 minutes to 19 seconds.
The monthly report scans about 25 million rows for a 300-vehicle fleet.

Another member of the family comes in handy often: merging overlapping intervals. Say you have events as start-end pairs (maintenance records, driver shift slots) and you want to collapse the ones that overlap into a single interval. The trick here is to sort the rows by start and carry the largest end seen so far with a window: MAX(bitis) OVER (ORDER BY baslangic ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) (bitis being the end, baslangic the start). If the new row's start is greater than this value, a new group begins; the rest is again flag + running total. The most elegant thing about this family of patterns is that the skeleton stays the same and only the definition of "island start" changes.

The second meeting with the customer was three weeks after the fix. Our new number was 246 hours; we showed them, with their own data, what their Excel method was missing (short idle periods), and we explained our own old double-counting bug without hiding it. The contract was renewed. That day, both sides learned that the numbers should converge not on each other, but on the definitions.

We also picked up a habit on the testing side: these queries are so sneaky that we keep the edge cases in a fixed "torture dataset." An idle period that starts and ends on a day boundary, a single-record island, a gap exactly at the tolerance limit, an interval that cuts across midnight, a vehicle with no idling at all. Every time the query is touched, this set is compared against the expected outputs. With window-function queries, it's nearly impossible to see by eye what a "small" change has broken; a fixed dataset is the only reliable referee.

Merging time intervals isn't a trick limited to idling; with the same query skeleton, we extract working time during shifts, dwell intervals inside a zone, and even outage windows from server logs. If you have a problem of the "turn consecutive rows into events" kind, write to me, and I'll send you the query skeleton along with sample data; and don't skip drawing three examples on paper.