Learn SQL
-- advanced.temporal_timetravel_tables

Time-Travel & Temporal Tables in SQL

As-of snapshots without replaying everything

--concept

System-versioned temporal tables (FOR SYSTEM_TIME AS OF) answer as-of directly where supported. Portable validity ranges (valid_from/valid_to half-open containment: from <= t AND t < to) work everywhere. Event sourcing rebuilds by replay — full history at replay cost. Half-open containment is the portable core; append-only history keeps it trustworthy.

--how it works
1

Half-open portable

from <= t AND t < to tiles time without gaps/overlaps — everywhere.

2

Temporal AS OF

FOR SYSTEM_TIME AS OF queries snapshots directly where supported.

3

Trigger validity

Writes close/open ranges; history append-only and partitioned.

4

Replay rarely

Event sourcing rebuilds at replay cost — audit-critical only.

--visualization
from <= t < to tiles time — exactly one row contains June-1st
product_idprice
799
Stage 1 / 1
FOR SYSTEM_TIME AS OF automates where supported; ranges work everywhere.
--example
query.sql
1-- portable validity query:
2SELECT * FROM prices WHERE product_id = 7 AND valid_from <= '2024-06-01' AND '2024-06-01' < valid_to;
Result
product_idprice
799

June-1st falls inside exactly one validity row by half-open containment. Closed ends would double-count boundary instants or gap them.

--variants

June-1st price (portable)

Exactly one row contains the instant.

query.sql
1SELECT * FROM prices WHERE product_id = 7 AND valid_from <= '2024-06-01' AND '2024-06-01' < valid_to;
Result
product_idprice
799
1Half-open picks the covering row.
2Closed ends would gap/double at boundaries.
3Index (product, valid_from, valid_to) seeks it.

Native AS OF twin

Engine-kept history, same question.

query.sql
1-- SELECT * FROM orders FOR SYSTEM_TIME AS OF '2024-06-01';
Result
rowssource
as-of rowsengine history
1No manual ranges to maintain.
2Retention policy bounds history size.
3Portable ranges work when native absent.
--key facts
Half-openfrom <= t < to — portable core
TemporalAS OF where supported
Append-onlyhistory tamper-evident
--use cases
Billing disputes + audit as-of reconstruction
Slowly-changing dimensions in warehouses
--under the hood
Validity-range exclusion constraints (gist) prevent overlaps at the engine level.
History partitioning by valid_from keeps as-of scans bounded.

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Take the queries you just visualized and see the data structures that power real databases.