Two clocks on one row
Most tables answer only the question "what is true now". Business questions rarely stop there: what was this customer's tier on the day the order shipped, what did the price list say when the quote was issued, and what did the report show before the correction landed. Temporal modelling is the practice of recording time explicitly so those questions are answered by a query rather than reconstructed from memory and backup files.
The discipline begins with separating two independent timelines. Valid time is when the fact held in the real world â the contract ran from March to June, the rate applied for the 2025 season. Transaction time is when the database knew it â the row was inserted on the 4th and corrected on the 19th. They move independently, and conflating them is the classic modelling error: a price that was wrong for a week and then corrected needs both clocks, because on any given day you may need to ask either "what was true then" or "what did we believe then".
By the end of this lesson you should be able to choose between a hand-rolled temporal column set and a system-versioned table, write period-overlap predicates that use indexes, and construct the bitemporal query that answers an auditor's question about a specific belief date.
Valid time, transaction time, and what each answers
Each timeline supports a distinct family of queries, and knowing which one a stakeholder is actually asking for prevents an entire class of incorrect reports.
| Concept | Meaning | Stored as | Typical question | Who asks |
|---|---|---|---|---|
| Valid time | When the fact was true in the world | Explicit valid_from, valid_to | What was the tier on 3 May? | Operations, analytics |
| Transaction time | When the database recorded it | System columns, automatic | What did we believe on 3 May? | Audit, compliance |
| Bitemporal | Both, independently | Both sets of columns | What did we believe on 3 May about 3 May? | Regulators, forensics |
| Snapshot | State at a moment of observation | Full periodic copies | What did the extract contain? | Data warehousing |
| Event log | Ordered occurrences | Append-only facts | What happened, in order? | Product analytics |
An open interval needs a convention for infinity. Using a very large sentinel date such as 9999-12-31 keeps range indexes happy and works everywhere, but leaks into report filters if you forget it; using NULL for the open end reads better yet breaks index lookups written as equality tests. Whichever convention you pick, state it once in the schema and make every query honour it, because a half-closed convention produces exactly one class of wrong answer: rows silently missing from period joins.
System-versioned tables without surprises
Several engines support system-versioned tables, where the database itself keeps prior row versions in a history table and exposes two period columns for querying. SQL Server uses FOR SYSTEM_TIME, Db2 uses AS OF SYSTEM_TIME, and the semantics are close enough that the query patterns transfer.
-- SQL Server: declare history retention and query it declaratively
CREATE TABLE dbo.contracts (
contract_id bigint NOT NULL,
customer_id bigint NOT NULL,
tier varchar(20) NOT NULL,
monthly_fee decimal(12,2) NOT NULL,
valid_from date NOT NULL,
valid_to date NOT NULL,
CONSTRAINT ck_contracts_range CHECK (valid_to > valid_from),
CONSTRAINT pk_contracts PRIMARY KEY (contract_id, valid_from)
)
WITH (SYSTEM_VERSIONING = ON (
HISTORY_TABLE = dbo.contracts_history,
HISTORY_RETENTION_PERIOD = 5 YEARS
));
-- What did the table contain at 09:00 before the overnight correction?
SELECT contract_id, tier, monthly_fee
FROM dbo.contracts
FOR SYSTEM_TIME AS OF '2026-02-11T09:00:00'
WHERE customer_id = 4821;
-- Everything that ever changed, including rows since deleted
SELECT contract_id, tier, monthly_fee, valid_from, valid_to,
sys_start_time, sys_end_time
FROM dbo.contracts
FOR SYSTEM_TIME BETWEEN '2026-01-01' AND '2026-03-01'
WHERE contract_id = 4821
ORDER BY sys_start_time;
Retention is the setting people get wrong. Unlimited history turns the history table into a write-amplification liability: every update writes two rows, and the history table eventually dwarfs the live one, slowing every write and every scan that cannot prune. A retention period that matches your compliance obligation bounds that cost, and rows older than it should be archived to cold storage rather than deleted outright.
Bitemporal queries with period constructors
Bitemporal correctness comes from combining the valid-time predicate with the transaction-time predicate. Written carefully, the query becomes a range overlap rather than an equality test, and that difference is what makes it index-friendly.
-- PostgreSQL style: valid period overlapped with a belief date
-- belief_date: the moment we are asking from; fact_date: the moment we ask about
WITH belief AS (
SELECT CAST(:belief_date AS date) AS as_of
),
candidate AS (
SELECT c.contract_id,
c.tier,
c.monthly_fee,
c.valid_from,
c.valid_to,
c.txn_from,
c.txn_to
FROM contracts c
CROSS JOIN belief b
WHERE c.valid_from <= CAST(:fact_date AS date)
AND c.valid_to > CAST(:fact_date AS date) -- half-open overlap
AND c.txn_from <= b.as_of
AND c.txn_to > b.as_of
)
SELECT contract_id, tier, monthly_fee, valid_from, valid_to
FROM candidate;
The half-open form â valid_from less than or equal and valid_to strictly greater â guarantees adjacent periods never overlap and never leave a one-day gap. Writing both bounds inclusive double-counts boundary days; writing both exclusive loses them. Pair the predicate with a composite index on (valid_from, valid_to, txn_from) and the overlap scan prunes to a handful of pages.
Replaying history for audits
Once both clocks exist, audits become deterministic queries. The typical request is to show, for a reporting period, what the numbers would have been using only information available at the time â which means filtering on transaction time while grouping across valid time.
-- Rows as believed on the audit date, aggregated over the fact period
SELECT product_code,
SUM(net_amount) AS revenue_as_believed
FROM invoices_bitemporal
WHERE valid_from <= DATE '2026-03-31'
AND valid_to > DATE '2026-03-01'
AND txn_from <= DATE '2026-04-15' -- belief date: shortly after close
AND txn_to > DATE '2026-04-15'
AND status = 'posted'
GROUP BY product_code
ORDER BY revenue_as_believed DESC;
Running the same query with two different belief dates turns a correction into a diff: rows whose amounts changed show the correction, rows whose transaction periods changed show reclassifications, and rows that appear for the first time show records entered late. That diff is usually exactly what an auditor wants and what a warehouse without transaction time cannot produce at all.
Modelling choices: columns versus temporal tables
A system-versioned table is the right answer when the database must guarantee history and the queries are point-in-time lookups. Explicit valid-time columns are the right answer when the business owns the timeline â contracts, subscriptions, and slowly changing dimensions all have valid periods that exist independently of when they were entered. Full periodic snapshots are the right answer when downstream tools expect a flat table per day and can afford the storage.
| Approach | Who maintains history | Query style | Cost | Best fit |
|---|---|---|---|---|
| System-versioned table | Database | Declarative time syntax | Write amplification | Audit of recorded state |
| Explicit valid-time columns | Application or trigger | Range predicates | Index maintenance on updates | Business periods |
| Bitemporal columns | Both | Two overlapping ranges | Highest complexity | Regulated reporting |
| Periodic snapshot | ETL job | Simple date filter | Storage per day | Warehousing and BI |
A hybrid is common in practice: valid-time columns in the model, transaction-time tracking in a change table populated by the ingestion pipeline. It keeps the analytical queries readable while still supporting a "what did we believe" audit, at the cost of one join.
Maintenance, retention, and performance
Temporal tables have three operational hazards. Updates that should be rare become frequent version churn, so monitor the history table's growth rate and alert when it exceeds the live table. Overlapping periods must be impossible, which means a constraint or a trigger rather than discipline â a check constraint cannot express cross-row uniqueness, so a deferred constraint trigger or an application-level assertion is required. And queries that forget the transaction predicate will happily return current state while claiming to answer a historical question.
Index design follows the query shape. Leading columns should be the predicates used most: valid-time overlap queries want (valid_from, valid_to) while audits want (txn_from, txn_to). Covering indexes that include the frequently selected measures eliminate the lookup entirely, and partitioning the history table by transaction year lets old audits prune to one partition.
đĄName the clocks in the column names
Columns called start_date and end_date are ambiguous the moment a second clock exists. Prefer valid_from and txn_from: the names carry the semantics, reviews catch mixed clocks, and new engineers do not have to ask.
Common Mistakes
Using inclusive bounds on both ends of a period, double-counting boundary days
Fix: Standardise on half-open intervals: valid_from inclusive, valid_to exclusive
Leaving history retention unbounded so the history table outgrows the live table
Fix: Set retention to the compliance window and archive older versions to cold storage
Answering an audit question with only the valid-time predicate
Fix: Filter on both clocks, or the answer reflects current beliefs rather than beliefs at the time
Storing bitemporal facts with a single set of dates because it looks simpler
Fix: Keep the two clocks in separate columns and never reuse a date for both meanings
Best Practices
- Document the interval convention once and enforce it in every query and constraint
- Index each clock separately so point-in-time and belief-date queries both prune
- Partition history by transaction year to bound both storage growth and audit scans
- Prefer declarative system versioning where the engine supports it over hand-written triggers
- Add a reconciliation query that asserts no overlapping periods exist for the same key
Interview Questions
Q1: What is the difference between valid time and transaction time?
Valid time is when the fact held in reality; transaction time is when the database recorded it. They advance independently.
Q2: Why are temporal periods usually stored half-open?
So adjacent periods neither overlap nor gap: an inclusive-exclusive pair makes boundary handling unambiguous.
Q3: What question needs both clocks?
What did we believe on a given date about a fact that itself applied on another date â the regulator's question.
Q4: How do you prevent overlapping periods for the same key?
With a constraint trigger or application assertion, because a plain check constraint cannot see other rows.
Key Takeaways
- Separate valid time from transaction time before writing any schema DDL
- Use half-open intervals so period predicates compose without boundary bugs
- System-versioned tables give recorded-state audit cheaply; explicit columns give business-period modelling
- Bitemporal queries combine two range predicates and need composite indexes to stay fast
- Bound history retention, or write amplification will eventually dominate performance