Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 119/ 160
06. Database Design, Normalization & Semi-Structured SQL

Temporal Tables & System-Versioned History Tracking

Track row history over time with temporal / system-versioned table patterns.

AdvancedTemporal Tables · Valid Time3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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

Loading interactive 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.

A history trigger in PostgreSQLQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sqlReadable preview
1CREATE FUNCTION prices_history_fn()2RETURNS trigger3LANGUAGE plpgsql4AS $$5BEGIN6INSERT INTO prices_history (product_id,7  price,8  valid_during)9VALUES (OLD.product_id,10  OLD.price,11  tstzrange(OLD.valid_from,12  now()));13RETURN NULL;14END $$;1516CREATE TRIGGER prices_history AFTER17UPDATE18  OR DELETE ON prices FOR EACH ROW EXECUTE FUNCTION prices_history_fn();
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Choose the target

Identify the table or database object the statement will modify.

1/18
3OutputInspect the representative rows, affected-row count, plan, or command status.
History objects created
CREATE FUNCTION CREATE TRIGGER

Note: PostgreSQL-style command tags. History rows are inserted later, when UPDATE or DELETE events fire the trigger.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

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.

Non-overlapping coverage periodsQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1CREATE EXTENSION IF NOT EXISTS btree_gist;23CREATE TABLE policy_coverage (4  policy_id bigint NOT NULL,5  plan text NOT NULL,6  valid_during tstzrange NOT NULL,7  EXCLUDE USING gist (8    policy_id9    WITH10      =,11      valid_during12    WITH13      &&14  )15);
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Choose the target

Identify the table or database object the statement will modify.

1/15
3OutputInspect the representative rows, affected-row count, plan, or command status.
Extension and table created
CREATE EXTENSION CREATE TABLE

Note: PostgreSQL/GiST-specific setup; creation succeeds when the extension is available and the table name is unused.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: Half-open ranges, @> for as-of lookups, an exclusion constraint against overlaps.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Requirement

Decide which time you need

Audit trail of database changes needs system time; real-world validity needs application time; some domains need both.

Focus at this step

system time · application time · bitemporal

What to watch at this step
Audit
system time
Tip: use ← → to move between steps

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

Built-in system versioning
Best for: Audit history in SQL Server, MariaDB, Oracle

Strengths: Automatic; standard AS OF queries.

Watch out: Records database time only; history grows without limit unless managed.

Range columns + exclusion constraints
Best for: Real-world validity in PostgreSQL

Strengths: Database-enforced no-overlap rule; precise as-of queries.

Watch out: Application must close and open periods correctly.

Audit log table of changes
Best for: Who changed what, for compliance

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?
Interview tip: Clarify whether the question is about database history or real-world validity, then show half-open ranges with an exclusion constraint. That distinction is the expert part of the answer.

Knowledge check

Loading quiz

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.

Open SQL Practice →SQL interview Q&A
Previous topic
Geospatial SQL Basics (PostGIS Geometry, Geography & Distance Queries)
Next topic
Schema Evolution & Zero-Downtime Column Migrations