AnalystPath

Carry Forward the Thermostat Setting

SQLMediumMid level~15 min

Problem

A smart thermostat writes a log row every time it is checked, ordered by an increasing `reading_seq`. It only records a `target_temp` when someone changes the setting; if the setting was left untouched, the row stores NULL.

Write a query that fills in every NULL `target_temp` with the most recent non-NULL `target_temp` from an earlier reading (the setting that was still in effect). The first reading is guaranteed to have a non-NULL value.

Return the columns `reading_seq` and `target_temp`, in order of `reading_seq`.

Tables

Example rows — the live problem includes the full dataset.

ThermostatLog
reading_seqtarget_temp
1Warm 72F
2
3

Expected output

Your answer should return 6 rows with the columns reading_seq, target_temp.

Starter code (SQL)

SELECT *
FROM ThermostatLog;

Solve this SQL question free

Write SQL and run it instantly in your browser — even on your phone. No signup needed to try.

Solution & explanation

Create a free account to unlock the optimal solution, a step-by-step explanation, and the hidden test cases that grade your answer.

Sign up free to unlock

Related SQL questions