Set Operations, Top-N Windows and SCD2 for Sensor Data
SQL & DataModel answerLast updated
Compare UNION and UNION ALL, write a NULL-safe anti-join and a top-3-per-group query, then explain star-schema roles and Type 2 history tracking for a sensor dimension.
You are working with sensor data in a warehouse and need to answer three groups of questions. Explain your reasoning, not just the syntax.
Part 1: Set operations and anti-joins
Two tables, active_sensors and backup_sensors, each hold a single sensor_id INT column.
- Describe how
UNIONandUNION ALLdiffer in cost on a large warehouse. When would you choose each one? - Write a query that returns every
sensor_idfound inactive_sensorsbut absent frombackup_sensors. The query must handle NULL ids deliberately, and you should state what rule you chose for them.
Part 2: Top-N per group
A table sensor_readings has columns sensor_id, reading_value (FLOAT) and timestamp (TIMESTAMP). Write a query that returns, for each sensor, its 3 highest readings within the last 24 hours.
sensor_id | reading_value | timestamp
1 | 98.5 | 2023-10-01 10:00:00
1 | 99.2 | 2023-10-01 10:05:00
1 | 97.0 | 2023-10-01 09:00:00
2 | 50.1 | 2023-10-01 10:10:00
Mention how you handle ties, NULL readings, sensors with fewer than 3 readings, and the meaning of "last 24 hours".
Part 3: Warehouse modeling
You are designing storage for high-frequency telemetry.
- Contrast a fact table with a dimension table in a star schema.
- A sensor goes through a major overhaul, so its location and manufacturer change while its
sensor_idstays the same. Describe how you would model this with a Type 2 slowly changing dimension, including how readings link to the correct version.
Hints
Hint 1
Think about what the engine must do to guarantee uniqueness, and whether it must hold or shuffle rows to do it.
Hint 2
What does `x NOT IN (1, 2, NULL)` evaluate to? Consider NOT EXISTS, and decide up front whether a NULL id counts as a real sensor.
Hint 3
Filter to the time window before ranking. Choose between ROW_NUMBER, RANK and DENSE_RANK based on how ties should behave, and consider what 'now' means for the 2023 sample data.
Hint 4
For SCD2, you need a surrogate key per version, validity dates and a current flag. Decide whether facts store the surrogate key at load time or are joined by time range.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Part 1: Set operations and anti-joins
UNION vs UNION ALL
UNION ALLsimply concatenates the inputs. Rows stream through with no sort and no extra memory, so the cost is O(n + m).UNION(distinct) concatenates and then removes duplicates. The engine either sorts the combined rows, which is O((n+m) log(n+m)), or builds a hash aggregate, which is O(n+m) time with memory proportional to the number of distinct rows. In a distributed warehouse that usually means a hash shuffle across nodes, possible spilling to disk, and a blocking step, since a row cannot be emitted until the engine knows it is unique.
Choose UNION ALL when the inputs are disjoint by construction (different date partitions, or sources tagged with a source column), when duplicates are meaningful, or when a later GROUP BY or DISTINCT will collapse rows anyway. Choose UNION only when you need set semantics and duplicates can genuinely occur. Even then, deduplicating on a narrow key is cheaper than on wide rows. Some engines treat a bare UNION differently or reject it, so write the intent explicitly.
NULL-safe anti-join
The trap is NOT IN. If backup_sensors contains a single NULL, x NOT IN (..., NULL) becomes UNKNOWN for every row and the query returns nothing.
SELECT DISTINCT a.sensor_id
FROM active_sensors a
WHERE a.sensor_id IS NOT NULL
AND NOT EXISTS (
SELECT 1
FROM backup_sensors b
WHERE b.sensor_id = a.sensor_id
);
Rule chosen here: a NULL id is not a real sensor, so it is excluded from the result. If instead a NULL in active_sensors should be treated as covered by a NULL in backup_sensors, compare with b.sensor_id IS NOT DISTINCT FROM a.sensor_id (or the dialect's null-safe equality operator) and drop the IS NOT NULL filter.
Alternatives:
EXCEPTtreats NULLs as equal and deduplicates its output.LEFT JOIN ... WHERE b.sensor_id IS NULLis correct as long as the NULL test is on the right-hand join key, not on some nullable payload column.
Optimizers typically turn NOT EXISTS into a hash anti-join: O(n + m) time, memory proportional to the smaller side.
Part 2: Top 3 readings per sensor in the last 24 hours
Approach: filter to the window first so the window function only sees recent rows, rank within each sensor, then keep ranks 1 to 3.
WITH recent AS (
SELECT sensor_id, reading_value, "timestamp"
FROM sensor_readings
WHERE "timestamp" >= NOW() - INTERVAL '24 hours'
AND reading_value IS NOT NULL
),
ranked AS (
SELECT sensor_id, reading_value, "timestamp",
ROW_NUMBER() OVER (
PARTITION BY sensor_id
ORDER BY reading_value DESC, "timestamp" DESC
) AS rn
FROM recent
)
SELECT sensor_id, reading_value, "timestamp"
FROM ranked
WHERE rn <= 3
ORDER BY sensor_id, reading_value DESC;
Details worth stating:
- Ties:
ROW_NUMBER()gives exactly 3 rows per sensor, with the timestamp as a deterministic tiebreaker.RANK()andDENSE_RANK()can return more than 3 rows when values tie. Ask which the business wants. - Reference point for "last 24 hours": the sample data is from 2023, so
NOW()would return nothing. For historical or test data, anchor to(SELECT MAX("timestamp") FROM sensor_readings). - NULL readings: some engines sort NULLs first under
DESC. Filter them out or useNULLS LAST. - Reserved word: quote
timestampwhere the dialect requires it. - Sample result (anchored window): sensor 1 gives 99.2, 98.5, 97.0; sensor 2 gives 50.1. A sensor with fewer than 3 readings returns fewer rows.
Some engines offer a dedicated per-group limit clause (for example LIMIT 3 BY sensor_id in ClickHouse), which avoids a full window computation.
Complexity: O(k log k) for k rows in the window because of the per-partition sort. A per-partition top-N heap reduces this to about O(k log 3).
Part 3: Warehouse modeling
Fact vs dimension
| Fact table | Dimension table | |
|---|---|---|
| Contents | Measurable events, such as a reading at a time | Descriptive context: location, manufacturer, model |
| Shape | Very long and narrow, append-heavy | Short and wide, slow-changing |
| Keys | Foreign keys to dimensions plus measures | Surrogate key, natural key, attributes |
| Grain | One row per sensor per reading | One row per sensor (per version under SCD2) |
State the grain explicitly, for example "one row per reading".
SCD Type 2 for an overhaul
CREATE TABLE dim_sensor (
sensor_sk BIGINT PRIMARY KEY, -- unique per version
sensor_id INT NOT NULL, -- stable business key
location TEXT,
manufacturer TEXT,
valid_from TIMESTAMP NOT NULL,
valid_to TIMESTAMP NOT NULL DEFAULT '9999-12-31',
is_current BOOLEAN NOT NULL
);
On an overhaul, in one transaction or a single MERGE:
- Expire the current row: set
valid_toto the overhaul time andis_current = false. - Insert a new row with a new
sensor_sk, the samesensor_id, the new attributes,valid_fromequal to the overhaul time, andis_current = true.
To link readings to the right version, either:
- Stamp at load time: store the
sensor_skthat is current when each reading arrives. This is fast to query, but late-arriving data needs care, because a reading for a past date must resolve to the version valid then. - Join by time range: join on
sensor_idwithreading_ts >= valid_from AND reading_ts < valid_to. This is more flexible and handles late data correctly, but costs more at query time on a very large fact table.
Trade-offs: SCD2 preserves history, so old readings are reported against the old location and manufacturer, at the cost of extra rows and more complex joins. Use half-open intervals to avoid double matches at boundaries, and enforce one current row per sensor_id.
Common mistakes
- Using
NOT INagainst a nullable column. - Using
UNIONwhenUNION ALLis enough. - Ranking before filtering to the time window.
- Overwriting dimension attributes (Type 1) when history matters.
- Reusing the natural key as the fact foreign key under SCD2, which makes versions ambiguous.