🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

Temporal Queries & SCD — Time Travel, Gap Filling, Sessionization

Advanced SQLTime Series⭐ Premium

Temporal Queries & SCD

Advanced SQL

Master Time in SQL

Temporal queries let you travel through time — answering "what was the state at point X?" and "how did values change?" SCD (Slowly Changing Dimensions) tracks historical changes. Together, they enable time-travel analysis, gap filling, sessionization, and point-in-time joins.

  • SCD Type 1 — Overwrite (no history)
  • SCD Type 2 — Preserve full history with effective/expiry dates
  • Gap Filling — Fill missing dates in time series
  • Sessionization — Group events into user sessions

Temporal data is the backbone of analytics — every fact table has a timestamp, and every dimension needs history.


What Are Temporal Queries?

Temporal queries operate on time-varying data, answering questions about the state of data at specific points in time or across time intervals.

Core Temporal Concepts

  • Bitemporal — Tracks both valid time (when it happened) and transaction time (when it was recorded)
  • SCD Type 2 — Creates new rows for each change, preserving history
  • Gap filling — Ensures continuous time series even when data is missing

Two conventions carry most of this work. Validity ranges are half-open — effective from a date inclusive, expiring on a date exclusive — so the instant one version ends is the instant the next begins and no timestamp can ever match two rows at once; the inclusive-both-ends alternative forces every point-in-time query to break ties by hand. The second convention is the surrogate key. customer_key exists because customer_id is deliberately mutable and reused, and a fact table that joins on the natural key picks up attribute changes made after the fact row was written — the classic bug that silently rewrites last quarter's revenue by region.


SCD Types Visualized

SCD Type 1 (Overwrite)No history preservedJan: John, BostonFeb: John, NYC ← Overwritten!Mar: John, SF ← Overwritten!Result: Only latest value"John lives in SF"No Boston or NYC historySCD Type 2 (Full History)Every change creates a new rowJan 1 – Jan 31John, BostonFeb 1 – Feb 28John, NYCMar 1 – 9999John, SF (current)Query for "What was John's city on Jan 15?"WHERE customer_id = 101AND '2024-01-15' BETWEEN effective_date AND expiry_dateResult: Boston ✓Full history preserved — can answer any point-in-time question

SCD Type 2 Implementation

-- Create SCD Type 2 dimension table
CREATE TABLE dim_customer (
  customer_key SERIAL PRIMARY KEY,
  customer_id INT,
  customer_name VARCHAR(255),
  email VARCHAR(255),
  city VARCHAR(100),
  effective_date DATE,
  expiry_date DATE,
  is_current BOOLEAN DEFAULT true
);

-- Insert new version on change (2-step process)
-- Step 1: Expire current record
UPDATE dim_customer
SET expiry_date = CURRENT_DATE - INTERVAL '1 day',
    is_current = false
WHERE customer_id = 101 AND is_current = true;

-- Step 2: Insert new version
INSERT INTO dim_customer (
  customer_id, customer_name, email, city,
  effective_date, expiry_date, is_current
)
VALUES (
  101, 'John Updated', '[email protected]', 'New York',
  CURRENT_DATE, '9999-12-31', true
);

What Keeps Type 2 Correct

Three details separate a working Type 2 from a subtly broken one. The expire-then-insert pair must run in a single transaction: a crash between the two statements leaves two rows claiming to be current, and every point-in-time query after that returns whichever one the planner finds first. The is_current flag is a convenience rather than a guarantee — nothing stops a second session from inserting its own current row, so the real protection is either an application-level lock on the natural key or a partial unique index over (customer_id) restricted to current rows.

History also grows without bounds. A dimension of 50,000 customers that changes four times a year adds 200,000 rows annually, and by year five the table is a million rows of which only 50,000 are current. Every point-in-time join therefore needs an index on (customer_id, effective_date, expiry_date); without it the planner nests loops the entire history once for each fact row, which is how a report that took two seconds last quarter takes ninety after eighteen months of tracking changes.

Point-in-Time Query

-- Find active record for a specific date
SELECT customer_id, customer_name, city
FROM dim_customer
WHERE customer_id = 101
  AND '2024-06-15'::DATE >= effective_date
  AND '2024-06-15'::DATE < expiry_date;

BigQuery Temporal Tables

-- BigQuery SYSTEM_TIME temporal table
CREATE TABLE `project.dataset.orders` (
  order_id INT64, customer_id INT64,
  total_amount NUMERIC, status STRING,
  valid_from TIMESTAMP, valid_to TIMESTAMP
);

-- Query as of specific timestamp
SELECT *
FROM `project.dataset.orders`
FOR SYSTEM_TIME AS OF '2024-06-15 10:00:00'
WHERE order_id = 12345;

-- Query between two timestamps
SELECT *
FROM `project.dataset.orders`
FOR SYSTEM_TIME BETWEEN '2024-01-01' AND '2024-06-30'
WHERE customer_id = 101;

System-versioned storage answers a different question from the one a Type 2 dimension answers. FOR SYSTEM_TIME AS OF returns rows as the warehouse knew them at that instant — including rows that were later corrected or deleted — while the same query without the clause returns the current state. A restated order and a superseded order are indistinguishable from the outside, and only the temporal clause tells them apart. Two operational facts matter before you enable it: history rows are charged as stored data for as long as the retention window keeps them, so a high-churn table with unbounded history becomes a real line item; and the temporal column is managed by the system, so filters written against valid_from in a normal WHERE clause do not implicitly become point-in-time queries.


Gap Filling for Time Series

-- Fill missing dates in time series (PostgreSQL)
WITH date_range AS (
  SELECT generate_series(
    '2024-01-01'::DATE,
    '2024-12-31'::DATE,
    '1 day'::INTERVAL
  )::DATE AS sale_date
)
SELECT
  dr.sale_date,
  COALESCE(daily.total_sales, 0) AS total_sales,
  COALESCE(daily.order_count, 0) AS order_count
FROM date_range dr
LEFT JOIN (
  SELECT sale_date, SUM(amount) AS total_sales, COUNT(*) AS order_count
  FROM sales
  WHERE sale_date >= '2024-01-01' AND sale_date <= '2024-12-31'
  GROUP BY sale_date
) daily ON dr.sale_date = daily.sale_date
ORDER BY dr.sale_date;

Two decisions decide whether the result is trustworthy. The spine must be generated at the granularity the report actually uses — a daily spine for a daily chart, a monthly spine for a monthly one — and the join key must match the data type exactly: joining a timestamp spine against a date column fails on every row, the LEFT JOIN produces nothing, and the dashboard renders a full year of zeros that looks like a real outage. Matching types is the difference between a bug you chase for an afternoon and a query you never think about again.

The second decision is what zero means. COALESCE(total_sales, 0) is correct for revenue, where an empty day genuinely earned nothing, and wrong for a measurement series, where a missing reading is an absence of observation rather than an observation of nothing — a sensor that was offline must not drag an average down to zero. Keeping the NULL through the query and filling at presentation time preserves that distinction; filling inside the SQL throws it away.


Sessionization

-- Group events into sessions (30-min inactivity = new session)
WITH events_with_gap AS (
  SELECT
    user_id, event_time, event_type,
    LAG(event_time) OVER (PARTITION BY user_id ORDER BY event_time) AS prev_event_time
  FROM events
),
session_assignments AS (
  SELECT *,
    SUM(CASE
      WHEN event_time - prev_event_time > INTERVAL '30 minutes'
        OR prev_event_time IS NULL
      THEN 1 ELSE 0
    END) OVER (PARTITION BY user_id ORDER BY event_time) AS session_id
  FROM events_with_gap
)
SELECT
  user_id, session_id,
  MIN(event_time) AS session_start,
  MAX(event_time) AS session_end,
  MAX(event_time) - MIN(event_time) AS session_duration,
  COUNT(*) AS event_count
FROM session_assignments
GROUP BY user_id, session_id;

The pattern works because it converts a comparison into a running count. LAG measures the interval between events, the CASE expression turns "more than thirty minutes, or no previous event" into the value 1, and the SUM across the ordered partition accumulates those flags into a session number that only increases when a new session begins. No cursor, no loop, and one pass over the events.

Two edges decide whether the numbers survive review. The first event for each user has a NULL prev_event_time, and that case must return 1 — skip it and the opening session of every visitor is never created, losing the shortest and most common sessions from the distribution. The threshold itself is a product decision rather than a technical one: thirty minutes suits a content site, five minutes suits chat, and one minute suits a checkout funnel. Changing the interval literal changes the metric, so the value belongs in a documented constant rather than buried in the query text.


Event Sequencing with Gaps

-- Find gaps in event sequences
WITH numbered_events AS (
  SELECT
    event_id, event_type, event_time,
    LAG(event_time) OVER (PARTITION BY event_type ORDER BY event_time) AS prev_event_time
  FROM events
)
SELECT
  event_type,
  prev_event_time AS gap_start,
  event_time AS gap_end,
  event_time - prev_event_time AS gap_duration,
  CASE
    WHEN event_time - prev_event_time > INTERVAL '1 hour' THEN 'LARGE_GAP'
    ELSE 'NORMAL'
  END AS gap_type
FROM numbered_events
WHERE prev_event_time IS NOT NULL
  AND event_time - prev_event_time > INTERVAL '30 minutes';

Temporal Joins (Point-in-Time)

-- Join two temporal tables for point-in-time analysis
SELECT
  o.order_id, o.order_date,
  c.customer_name, c.city,
  p.product_name, p.category
FROM orders o
INNER JOIN dim_customer c
  ON o.customer_id = c.customer_id
  AND o.order_date >= c.effective_date
  AND o.order_date < c.expiry_date
INNER JOIN dim_product p
  ON o.product_id = p.product_id
  AND o.order_date >= p.effective_date
  AND o.order_date < p.expiry_date;

Each fact row here has to find the single dimension version whose validity window contains the order date, so the join condition carries an equality on the natural key plus a range test on the window. The planner implements that as an index range scan over (customer_id, effective_date) with expiry as a residual filter, and it is why the window bounds must stay half-open: >= effective_date together with < expiry_date guarantees exactly one matching version, while an inclusive end lets an order written at the exact moment a new version took effect match two rows. The symptom in reporting is a total that is a few tenths of a percent too high on days when attributes changed, which is high enough to fail reconciliation and low enough that nobody suspects the join.


Month-over-Month Growth

-- Calculate month-over-month growth
WITH monthly_sales AS (
  SELECT
    DATE_TRUNC('month', sale_date)::DATE AS month,
    SUM(amount) AS total_sales
  FROM sales
  GROUP BY 1
)
SELECT
  month, total_sales,
  LAG(total_sales) OVER (ORDER BY month) AS prev_month,
  total_sales - LAG(total_sales) OVER (ORDER BY month) AS absolute_growth,
  ROUND(
    (total_sales - LAG(total_sales) OVER (ORDER BY month)) * 100.0 /
    NULLIF(LAG(total_sales) OVER (ORDER BY month), 0), 2
  ) AS growth_pct
FROM monthly_sales
ORDER BY month;

Two edge cases appear in every real series. The first month has no predecessor, so LAG returns NULL, absolute growth is NULL and the percentage is NULL; rendering that as zero percent growth asserts something the data does not say, and averaging it into the chart drags the series toward the floor. The NULLIF in the denominator covers the opposite edge — a zero-sales base month makes the ratio divide by zero, and the guard turns an error into a NULL. Both cases belong in the visualisation layer as "no comparison available" rather than being COALESCE'd into the SQL.

There is also a boundary worth naming. DATE_TRUNC collapses every sale into its calendar month before grouping, so the comparison is always between two complete months. Run the same query on a current month that has only three days of data and growth reads as a collapse, then flips to a spike once the month fills in. Any dashboard built on this query needs a "current month excluded" flag.


Quiz: Test Your Knowledge


Follow-Up Questions

  1. How do you handle timezone conversions in temporal queries?
  2. What's the difference between SCD Type 1, 2, and 3?
  3. How would you implement a Type 6 SCD (hybrid approach)?
  4. Explain the concept of bitemporal data and how to query it.
  5. How do you efficiently gap-fill time series data with irregular intervals?

Common Mistakes

Storing expiry dates inclusive at both ends, so a point-in-time query returns two versions of the same row

Fix: Keep the window half-open — inclusive on effective_date, exclusive on expiry_date — so version boundaries cannot overlap

Running the expire and insert statements of a Type 2 change as two separate implicit transactions

Fix: Wrap both in one transaction, and enforce current-row uniqueness with a partial unique index rather than trusting the is_current flag

COALESCEing missing days to zero in the gap-fill query before anyone decided what a missing day means

Fix: Leave the NULL through the query and fill at presentation time, because a zero is correct for revenue and wrong for measurements

Key Takeaways

  • SCD Type 1 overwrites — use when history doesn't matter
  • SCD Type 2 preserves full history — use for audit trails and point-in-time queries
  • Gap filling — LEFT JOIN against a generated date series to fill missing dates
  • Sessionization — Use LAG + cumulative SUM of gap flags to assign session IDs
  • Temporal joins — Join with BETWEEN effective_date AND expiry_date for point-in-time analysis
  • BigQuery supports FOR SYSTEM_TIME AS OF natively
🔒

Premium Content

Temporal Queries & SCD — Time Travel, Gap Filling, Sessionization

You've previewed the first section. Unlock this full lesson and 900+ advanced tutorials with a Premium plan.

🎯End-to-end Projects
💼Interview Prep
📜Certificates
🤝Community Access

Already a member? Log in

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-16

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Advertisement