KatInterview

Set Operations, Top-N Windows and SCD2 for Sensor Data

SQL & DataModel answer
MediumModel answerSQL & Datasqlwindow-functionsdata-warehouse

Last 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.

  1. Describe how UNION and UNION ALL differ in cost on a large warehouse. When would you choose each one?
  2. Write a query that returns every sensor_id found in active_sensors but absent from backup_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.

  1. Contrast a fact table with a dimension table in a star schema.
  2. A sensor goes through a major overhaul, so its location and manufacturer change while its sensor_id stays 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.