Temporal Tables & System-Versioned History Tracking
Track row history over time with temporal / system-versioned table patterns.
In plain words
Instead of rubbing out old values, keep them with the dates they were true.
Think of it like…
A shop's price board with a dated notebook underneath: the board shows today's price, and the notebook records every old price with the dates it was on the board, so you can answer what anything cost on any day.
Where you’ve seen it
An insurer stores policy coverage as policy_coverage(policy_id, plan, valid_during tstzrange, EXCLUDE USING gist (policy_id WITH =, valid_during WITH &&)). When a claim for an accident on 14 March arrives, SELECT plan FROM policy_coverage WHERE policy_id = 881 AND valid_during @> timestamptz '2026-03-14 10:30+05:30' returns the plan in force at that moment, even though the customer upgraded in April.
Words you’ll hear
- System time
- When a row version existed in the database; recorded automatically.
- Application (valid) time
- When a fact was true in the real world; set by the application.
- AS OF query
- Returns the data as it was at a point in time: FOR SYSTEM_TIME AS OF ….
- Bitemporal
- Tracking both: what was true, and when the database knew it.
Visual diagram
Theory & example queries
System-versioned tables
SQL:2011 defines system versioning, implemented by SQL Server, MariaDB and others. In SQL Server, a table declares ValidFrom datetime2 GENERATED ALWAYS AS ROW START, ValidTo … AS ROW END, PERIOD FOR SYSTEM_TIME (ValidFrom, ValidTo) and WITH (SYSTEM_VERSIONING = ON (HISTORY_TABLE = dbo.PricesHistory)). Every UPDATE or DELETE copies the old version into the history table automatically, and SELECT … FROM dbo.Prices FOR SYSTEM_TIME AS OF '2026-06-01' returns the table as it was.
MariaDB uses CREATE TABLE … WITH SYSTEM VERSIONING and the same FOR SYSTEM_TIME syntax; Oracle offers Flashback Query (AS OF TIMESTAMP) backed by undo data or Flashback Data Archive. PostgreSQL and MySQL have no built-in system versioning; the usual pattern is a history table filled by an AFTER UPDATE OR DELETE trigger that records the old row with a period.
CREATE FUNCTION prices_history_fn()RETURNS triggerLANGUAGE plpgsqlAS $$BEGININSERT INTO prices_history (product_id, price, valid_during)VALUES (OLD.product_id, OLD.price, tstzrange(OLD.valid_from, now()));RETURN NULL;END $$;CREATE TRIGGER prices_history AFTERUPDATE OR DELETE ON prices FOR EACH ROW EXECUTE FUNCTION prices_history_fn();PostgreSQL is the lesson baseline unless noted otherwise.
Identify the table or database object the statement will modify.
History objects created
Note: PostgreSQL-style command tags. History rows are inserted later, when UPDATE or DELETE events fire the trigger.
Key takeaway: SQL Server and MariaDB version automatically; PostgreSQL uses a trigger and history table.
Application time with ranges
For facts with real-world validity (coverage, prices scheduled in advance, employee assignments), store the period explicitly. PostgreSQL's range types fit perfectly: valid_during tstzrange with half-open bounds [start, end), so consecutive periods touch without overlapping. valid_during @> timestamptz '…' finds the version in force at a moment, and a GiST index makes it fast.
Prevent overlapping versions for the same entity with an exclusion constraint: EXCLUDE USING gist (policy_id WITH =, valid_during WITH &&), which needs the btree_gist extension for the equality part. PostgreSQL 18 adds WITHOUT OVERLAPS for primary keys and unique constraints, expressing the same rule more directly. Combining system time and application time gives bitemporal data: what was true, and when you recorded it.
CREATE EXTENSION IF NOT EXISTS btree_gist;CREATE TABLE policy_coverage ( policy_id bigint NOT NULL, plan text NOT NULL, valid_during tstzrange NOT NULL, EXCLUDE USING gist ( policy_id WITH =, valid_during WITH && ));PostgreSQL is the lesson baseline unless noted otherwise.
Identify the table or database object the statement will modify.
Extension and table created
Note: PostgreSQL/GiST-specific setup; creation succeeds when the extension is available and the table name is unused.
Key takeaway: Half-open ranges, @> for as-of lookups, an exclusion constraint against overlaps.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
Decide which time you need
Audit trail of database changes needs system time; real-world validity needs application time; some domains need both.
system time · application time · bitemporal
When to use it & trade-offs
What it is
A temporal table keeps every version of a row with the period it was valid, so you can ask "what was the price on 1 June?" or "who changed this record, and when?". System-versioned tables (SQL Server, MariaDB, Oracle Flashback) record automatically when each version existed in the database. Application-time (valid-time) tables store when a fact was true in the real world, such as a policy's coverage period. PostgreSQL builds both with range columns, triggers and exclusion constraints.
Why it matters: Audits, disputes and regulations need history: what a customer was charged, what an insurance policy covered on the day of a claim, or what an account's status was before a support agent changed it. Overwriting rows loses that forever. Temporal designs keep history queryable with ordinary SQL instead of digging through logs.
When to reach for it
- Prices, plans and coverage that change over time
- Compliance and dispute investigations
- Restoring or comparing past versions of records
When to avoid or be careful
- Closed-closed periods that overlap at the boundary
- Overwriting rows when history matters
- History tables without retention or indexes
Ways to keep row history
Strengths: Automatic; standard AS OF queries.
Watch out: Records database time only; history grows without limit unless managed.
Strengths: Database-enforced no-overlap rule; precise as-of queries.
Watch out: Application must close and open periods correctly.
Strengths: Captures user and reason; simple inserts.
Watch out: Reconstructing a past state needs replaying changes.
Interview signals & numbers to know
When this topic comes up
- “What was the price on 1 June?”
- “Which plan covered this claim date?”
- “Audit every change to customer records”
- AS OF queries
- Overlapping periods
Benchmarks & rules of thumb
- [start, end)
- half-open period bounds
- SQL:2011
- standard that defined temporal tables
- PostgreSQL 18
- WITHOUT OVERLAPS constraints
Common mistakes & follow-ups
Common interview mistakes
- Storing periods as inclusive on both ends, so 1 July belongs to two versions.
- Updating a period table without closing the previous version, leaving two current rows.
- Relying on system time to answer a business-validity question, such as a price change scheduled in advance.
Likely interviewer follow-ups
- How would you find the plan in force on a past date?
- How do you stop two versions of a record overlapping in time?
- What's the difference between system time and application time?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Temporal Tables & System-Versioned History Tracking with hands-on SQL practice and interview Q&A.