← All SQL interview questions
Three consecutive high-temperature readings
HardWindow FunctionsOracleWalmart
Cold-chain monitoring raises an incident when a freezer records a temperature above 8 degrees on three or more consecutive readings (ordered by reading_time within each freezer_code).
From freezer_readings, return the distinct freezer_code values that triggered at least one such incident.
Sample data
Table: freezer_readings
18 row(s) · showing first 8
| reading_idINT | freezer_codeTEXT | reading_timeTIMESTAMP | temp_celsiusNUMERIC(5,2) |
|---|---|---|---|
| 1 | FZ-01 | 2026-02-10 | 4.20 |
| 2 | FZ-01 | 2026-02-10 | 9.10 |
| 3 | FZ-01 | 2026-02-10 | 9.80 |
| 4 | FZ-01 | 2026-02-10 | 10.40 |
| 5 | FZ-01 | 2026-02-10 | 5.00 |
| 6 | FZ-02 | 2026-02-10 | 8.50 |
| 7 | FZ-02 | 2026-02-10 | 3.90 |
| 8 | FZ-02 | 2026-02-10 | 8.90 |
freezer_readings
- reading_idINT
- freezer_codeTEXT
- reading_timeTIMESTAMP
- temp_celsiusNUMERIC(5,2)
- Step 1: Flag each reading as high or not with a `CASE` expression, and number the readings per freezer with `ROW_NUMBER() OVER (PARTITION BY freezer_code ORDER BY reading_time)`.
- Step 2: Apply the **gaps-and-islands** trick: subtract a second `ROW_NUMBER()` computed per (freezer, flag) from the first. Consecutive rows sharing the same flag produce a constant difference, which becomes a streak identifier.
- Step 3: Keep only high-temperature rows (`is_high = 1`) and group by freezer plus `streak_key` — each group is one uninterrupted run of high readings.
- Step 4: `HAVING COUNT(*) >= 3` keeps runs of three or more.
- Step 5: Select `freezer_code`; grouping already collapses each qualifying run, and a freezer with several runs still resolves to distinct codes in the result.
WITH flagged AS (
SELECT freezer_code,
reading_time,
CASE WHEN temp_celsius > 8 THEN 1 ELSE 0 END AS is_high,
ROW_NUMBER() OVER (PARTITION BY freezer_code ORDER BY reading_time) AS rn
FROM freezer_readings
),
streaks AS (
SELECT freezer_code,
is_high,
rn - ROW_NUMBER() OVER (
PARTITION BY freezer_code, is_high ORDER BY rn
) AS streak_key
FROM flagged
)
SELECT freezer_code
FROM streaks
WHERE is_high = 1
GROUP BY freezer_code, streak_key
HAVING COUNT(*) >= 3;Approach 2 — LAG / LEAD comparison
For a fixed window of exactly three, comparing each row with its two predecessors is shorter, though it does not generalise to N.
WITH ordered AS (
SELECT freezer_code,
temp_celsius,
LAG(temp_celsius, 1) OVER (PARTITION BY freezer_code ORDER BY reading_time) AS prev1,
LAG(temp_celsius, 2) OVER (PARTITION BY freezer_code ORDER BY reading_time) AS prev2
FROM freezer_readings
)
SELECT DISTINCT freezer_code
FROM ordered
WHERE temp_celsius > 8 AND prev1 > 8 AND prev2 > 8;Learn the concept first
Stuck on Window Functions? These free SQL lessons teach it step by step.
More Window Functions questions
Practising alone only goes so far — our live cohorts pair SQL depth with dashboards, agentic analytics projects and mock interviews.
Explore the program