Who changed that salary, and when? With a temporal table (system-versioned table) SQL Server keeps the history of your rows for you. Every UPDATE and DELETE moves the old version of the row into a history table, and you can look at any past moment with FOR SYSTEM_TIME.
Part of the SQL Server for Beginners series. This article is the written version of lesson 17 of the Bigland Network video course. All examples were run in SQL Server Management Studio on a test instance. Run every example on a test server, not on production.
Watch lesson 17 as a video or open it on YouTube. The written lesson below follows the same steps and the same sample data.
Contents
- 1. How a temporal table works
- 2. Create a temporal table
- 3. INSERT, UPDATE and DELETE
- 4. Travel in time: AS OF and ALL
- 5. Undo a mistake
- 6. Read only history and retention
- 7. Mistakes and best practices
- 8. Practice and clean up
1. How a temporal table works
A temporal table is a team of two tables: the main table holds what is true now, and the history table holds what was true before. Two DATETIME2 columns (in UTC) say when each version was true: ValidFrom and ValidTo. A current row has ValidTo = 9999-12-31 23:59:59.9999999. You never write to the history table yourself.
2. Create a temporal table
CREATE TABLE dbo.StaffT (
Id INT PRIMARY KEY,
FirstName VARCHAR(50) NOT NULL,
Salary INT,
ValidFrom DATETIME2 GENERATED ALWAYS AS ROW START HIDDEN,
ValidTo DATETIME2 GENERATED ALWAYS AS ROW END HIDDEN,
PERIOD FOR SYSTEM_TIME (ValidFrom, ValidTo))
WITH (SYSTEM_VERSIONING = ON (HISTORY_TABLE = dbo.StaffT_History));
CREATE TABLE dbo.Marks (Label VARCHAR(30), T DATETIME2); -- helper: remembers moments
SELECT name, temporal_type_desc
FROM sys.tables
WHERE name LIKE 'StaffT%'
ORDER BY name;
| name | temporal_type_desc |
|---|---|
| StaffT | SYSTEM_VERSIONED_TEMPORAL_TABLE |
| StaffT_History | HISTORY_TABLE |
3. INSERT, UPDATE and DELETE
INSERT INTO dbo.StaffT (Id, FirstName, Salary) VALUES
(1, 'Amina', 4200), (2, 'Youssef', 5200), (3, 'Karim', 3100);
-- save the time, then give Amina a raise
INSERT INTO dbo.Marks VALUES ('before_raise', SYSUTCDATETIME());
UPDATE dbo.StaffT SET Salary = 4500 WHERE Id = 1;
DELETE FROM dbo.StaffT WHERE Id = 3;
SELECT Id, FirstName, Salary, ValidFrom, ValidTo
FROM dbo.StaffT_History
ORDER BY Id;
The history table now holds two rows: Amina with 4200 (the version before the raise) and Karim with 3100 (the deleted row). The ValidFrom and ValidTo values are the real UTC times of your own run, so they differ from ours.
4. Travel in time: AS OF and ALL
AS OF t: the table exactly as it was at time t.ALL: every version, old and current.BETWEEN a AND b: versions that were true at some point in the range.CONTAINED IN (a, b): versions that started and ended inside the range.
DECLARE @t DATETIME2 =
(SELECT T FROM dbo.Marks WHERE Label = 'before_raise');
SELECT Id, FirstName, Salary
FROM dbo.StaffT FOR SYSTEM_TIME AS OF @t
ORDER BY Id;
SELECT Id, FirstName, Salary, ValidFrom, ValidTo
FROM dbo.StaffT FOR SYSTEM_TIME ALL
ORDER BY Id, ValidFrom;
| Id | FirstName | Salary |
|---|---|---|
| 1 | Amina | 4200 |
| 2 | Youssef | 5200 |
| 3 | Karim | 3100 |
The ALL query returns four rows: Amina twice (4200, then 4500), Youssef once and Karim once.
5. Undo a mistake
DECLARE @t DATETIME2 =
(SELECT T FROM dbo.Marks WHERE Label = 'before_raise');
INSERT INTO dbo.StaffT (Id, FirstName, Salary)
SELECT Id, FirstName, Salary
FROM dbo.StaffT FOR SYSTEM_TIME AS OF @t
WHERE Id = 3;
SELECT Id, FirstName, Salary FROM dbo.StaffT ORDER BY Id;
Result: Amina 4500, Youssef 5200 and Karim 3100 are all back in the main table.
6. Read only history and retention
The history table cannot be changed: an UPDATE or DELETE on it fails with an error (13561: Cannot update rows in a temporal history table). To stop the history from growing forever, set a retention period:
ALTER TABLE dbo.StaffT
SET (SYSTEM_VERSIONING = ON (HISTORY_RETENTION_PERIOD = 6 MONTHS));
SELECT name, history_retention_period, history_retention_period_unit_desc
FROM sys.tables
WHERE name = 'StaffT';
Result: StaffT, 6, MONTH.
7. Mistakes and best practices
- Trying to UPDATE or DELETE the history table: it is blocked.
- Trying to DROP a temporal table before turning versioning off.
- Forgetting that the times are UTC, not your local time.
- Keeping history forever on a busy table: it grows and grows.
- Thinking history is a backup. It is not: it lives in the same database.
- Best practice: name the history table yourself, set a retention period, use temporal tables for data people ask questions about (prices, salaries, status), use AS OF for reports that must match a past date, and keep real backups too.
8. Practice and clean up
- Show every version of Amina, oldest first.
- Count the versions of each employee.
- Give Youssef 5500, then read his old salary from the history table.
-- 1 (2 rows: 4200 then 4500)
SELECT Id, FirstName, Salary, ValidFrom, ValidTo
FROM dbo.StaffT FOR SYSTEM_TIME ALL
WHERE Id = 1
ORDER BY ValidFrom;
-- 2 (Amina 2, Youssef 1, Karim 2)
SELECT Id, FirstName, COUNT(*) AS versions
FROM dbo.StaffT FOR SYSTEM_TIME ALL
GROUP BY Id, FirstName
ORDER BY Id;
-- 3 (old salary 5200)
UPDATE dbo.StaffT SET Salary = 5500 WHERE Id = 2;
SELECT Id, FirstName, Salary AS old_salary
FROM dbo.StaffT_History
WHERE Id = 2;
-- clean up: versioning OFF first, then drop both tables
ALTER TABLE dbo.StaffT SET (SYSTEM_VERSIONING = OFF);
DROP TABLE dbo.StaffT;
DROP TABLE dbo.StaffT_History;
DROP TABLE dbo.Marks;
Frequently asked questions
Is a temporal table the same as an audit table with triggers?
No. A trigger-based audit table (lesson 10) is code you write and maintain. A temporal table is built into SQL Server: the engine moves the old row version for you and gives you FOR SYSTEM_TIME to query it.
Can I convert an existing table?
Yes. Add the two period columns and the PERIOD clause with ALTER TABLE, then turn SYSTEM_VERSIONING on with a history table name.
Is the history a backup?
No. It lives in the same database, so a disaster takes both. Keep regular backups (lesson 12).
What to learn next
The next lesson, Lesson 18: Partitioning and Large Tables, covers partitioning: partition functions, schemes, SPLIT and SWITCH. Previous lesson: Lesson 16: Working with JSON.
The whole series
- Lesson 1: SELECT, WHERE and ORDER BY
- Lesson 2: JOINs
- Lesson 3: GROUP BY, HAVING and Subqueries
- Lesson 4: INSERT, UPDATE, DELETE and Transactions
- Lesson 5: CREATE TABLE, Data Types and Constraints
- Lesson 6: Indexes, Views and Stored Procedures
- Lesson 7: CTEs and Window Functions
- Lesson 8: Built-in Functions
- Lesson 9: Functions, Temp Tables and Table Variables
- Lesson 10: Triggers and Audit Tables
- Lesson 11: Security: Logins, Users and Roles
- Lesson 12: Backup, Restore and Recovery Models
- Lesson 13: Query Performance Tuning
- Lesson 14: SQL Server Agent Jobs and Maintenance
- Lesson 15: Encryption and Auditing Basics
- Lesson 16: Working with JSON
- Lesson 17: Temporal Tables and Row History (this article)
- Lesson 18: Partitioning and Large Tables
- lesson 19: Full Text Search
- lesson 20: Query Store and Slow Queries
Sources and further reading
- Microsoft Learn, Transact-SQL reference (Database Engine), on learn.microsoft.com: the official syntax for the statements used here.
- Microsoft Learn, temporal tables, SYSTEM_VERSIONING and FOR SYSTEM_TIME, for the full details of each feature.
More tutorials like this
Msg 208 Invalid Object Name in SQL Server: Causes and Fix
Fix SQL Server Msg 208 Invalid object name: check the spelling, the database and the schema, with real SSMS examples and scripts to find…
SQL Server Query Store Tutorial: Find Slow Queries, Compare Plans and Force a Plan
Turn on Query Store, find the most expensive queries with the sys.query_store views and the SSMS reports, compare the plans of one query and…
SQL Server Full Text Search Tutorial: CONTAINS, FORMSOF and CONTAINSTABLE
Search words inside text columns fast: create a full text catalog and index, use CONTAINS, word forms, phrases and rank the best matches with…
