In many applications, storing only the latest version of a record is not enough. Businesses often need to know what a record looked like in the past, when a value changed, or which information existed before an update or deletion.
Consider an employee management application. An employee's department, job title, salary, or address may change several times during their employment. If the application updates the employee record directly, the previous values are normally lost unless the application maintains a separate audit table or history mechanism.
SQL Server provides a built-in solution called system-versioned temporal tables. This feature automatically maintains historical versions of records whenever data is updated or deleted. Developers can query the current data and historical records using standard SQL with the FOR SYSTEM_TIME clause.
Temporal tables are useful for auditing, historical reporting, investigating data changes, and recovering information after accidental updates or deletions.
This article explains how SQL Server temporal tables work, how to create them, how to query historical records, and how to use them in real-world applications.
What Are SQL Server Temporal Tables?
A system-versioned temporal table is a SQL Server table that automatically maintains a history of its data over time.
It consists of two related tables:
- Current table: Stores the latest version of each record.
- History table: Stores previous versions of records when they are updated or deleted.
SQL Server manages the movement of old row versions into the history table. Developers do not need to write triggers or manually copy records whenever a change occurs.
For example, suppose an employee initially works in the Engineering department with a salary of ₹60,000. Later, the employee moves to the Architecture department with a salary of ₹75,000.
The current table contains the latest information, while the history table retains the earlier version.
<text weight="medium">Example employee history</text>
| EmployeeId | Name | Department | Salary | ValidFrom | ValidTo |
|---|
| 101 | Rahul | Engineering | 60000 | Jan 10 | Mar 15 |
| 101 | Rahul | Architecture | 75000 | Mar 15 | Dec 31, 9999 |
The first row represents the historical version. The second row represents the current version.
The actual period values are stored as datetime2 values, and SQL Server uses UTC time to manage them.
How System-Versioned Temporal Tables Work
SQL Server uses two period columns to track the validity of each row.
ValidFrom: Represents the beginning of the period during which the row version is valid.ValidTo: Represents the end of that period.
These columns are configured as the row start and row end of a system-time period.
For a current record, the ValidTo value is normally the maximum datetime2 value, which is:
9999-12-31 23:59:59.9999999
When a record is inserted, SQL Server sets the start time and marks the end time as the maximum value.
When the record is updated, SQL Server moves the previous version into the history table and sets its end time. The new version becomes the current record.
When the record is deleted, the previous version is moved into the history table. The record is removed from the current table.
The important point is that SQL Server manages these operations automatically when system versioning is enabled.
What happens during an INSERT?
When a new employee is inserted, SQL Server creates the current row and assigns its period values.
INSERT INTO dbo.Employees
(
EmployeeId,
Name,
Department,
Salary
)
VALUES
(
101,
'Rahul',
'Engineering',
60000
);
SQL Server assigns the ValidFrom and ValidTo values automatically.
No historical record is created because the employee did not have an earlier version.
What happens during an UPDATE?
Suppose the employee changes departments and receives a salary increase.
UPDATE dbo.Employees
SET
Department = 'Architecture',
Salary = 75000
WHERE EmployeeId = 101;
SQL Server automatically copies the previous employee record into the history table and updates the current record.
The history table now contains the previous department and salary.
What happens during a DELETE?
Suppose the employee record is deleted:
DELETE FROM dbo.Employees
WHERE EmployeeId = 101;
SQL Server moves the previous row version into the history table before removing it from the current table.
This allows the application to retrieve the employee's information even after deletion.
Temporal tables therefore preserve historical row versions without requiring developers to create separate INSERT, UPDATE, and DELETE triggers.
Create a System-Versioned Temporal Table
Let's create a practical example using an employee management database.
The employee table will store the employee's name, department, salary, and employment information. SQL Server will automatically maintain its historical versions.
Create the current table
Execute the following SQL statement:
CREATE TABLE dbo.Employees
(
EmployeeId INT NOT NULL PRIMARY KEY,
Name NVARCHAR(150) NOT NULL,
Department NVARCHAR(100) NOT NULL,
Salary DECIMAL(12, 2) NOT NULL,
ValidFrom DATETIME2 GENERATED ALWAYS AS ROW START
NOT NULL,
ValidTo DATETIME2 GENERATED ALWAYS AS ROW END
NOT NULL,
PERIOD FOR SYSTEM_TIME (ValidFrom, ValidTo)
)
WITH
(
SYSTEM_VERSIONING = ON
(
HISTORY_TABLE = dbo.EmployeeHistory
)
);
This statement creates a system-versioned temporal table.
The GENERATED ALWAYS AS ROW START and GENERATED ALWAYS AS ROW END definitions tell SQL Server to manage the period columns.
The PERIOD FOR SYSTEM_TIME clause identifies the two columns that define the validity period.
Finally, SYSTEM_VERSIONING = ON enables automatic history tracking.
The HISTORY_TABLE option specifies the name of the table that stores previous versions.
If the history table is not specified, SQL Server creates one automatically.
Hide the period columns
Sometimes, applications do not need the period columns in normal query results.
SQL Server supports the HIDDEN keyword for these columns:
ValidFrom DATETIME2 GENERATED ALWAYS AS ROW START
HIDDEN NOT NULL,
ValidTo DATETIME2 GENERATED ALWAYS AS ROW END
HIDDEN NOT NULL,
Hidden columns are excluded from queries such as SELECT *, but they can still be referenced explicitly.
This is useful when existing application code expects the original table structure and should not receive additional period columns unexpectedly.
Insert and Update Employee Records
Once the temporal table is created, developers can use it like a normal SQL Server table.
Insert a few employee records:
INSERT INTO dbo.Employees
(
EmployeeId,
Name,
Department,
Salary
)
VALUES
(
101,
'Rahul',
'Engineering',
60000
),
(
102,
'Priya',
'Finance',
65000
),
(
103,
'Amit',
'Marketing',
55000
);
Retrieve the current employee information:
SELECT
EmployeeId,
Name,
Department,
Salary,
ValidFrom,
ValidTo
FROM dbo.Employees;
Now update Rahul's department and salary:
UPDATE dbo.Employees
SET
Department = 'Architecture',
Salary = 75000
WHERE EmployeeId = 101;
SQL Server automatically stores the previous version in EmployeeHistory.
Update the record again:
UPDATE dbo.Employees
SET
Department = 'Management',
Salary = 90000
WHERE EmployeeId = 101;
The history table now contains the earlier versions, while the current table contains the latest values.
You do not need to execute a separate INSERT statement against the history table.
Query Historical Records Using FOR SYSTEM_TIME
The most useful feature of temporal tables is the ability to query data from a specific point in time.
SQL Server provides the FOR SYSTEM_TIME clause with several temporal subclauses.
The main options are:
| Temporal query | Purpose |
|---|
AS OF | Returns the row versions valid at a specific point in time |
FROM ... TO | Returns versions that overlap a specified period |
BETWEEN ... AND | Similar to FROM and TO, but includes the upper boundary |
CONTAINED IN | Returns versions whose complete validity periods fall within the specified period |
ALL | Returns current and historical row versions |
These queries allow applications to investigate how data changed over time.
Query records AS OF a specific date
The AS OF subclause retrieves the state of a table at a specific point in time.
For example:
SELECT
EmployeeId,
Name,
Department,
Salary
FROM dbo.Employees
FOR SYSTEM_TIME AS OF '2026-03-01 10:00:00'
WHERE EmployeeId = 101;
SQL Server checks both the current and history tables and returns the version that was valid at the specified time.
This is useful when an application needs to answer questions such as:
- Which department did an employee belong to last month?
- What was the employee's salary before the latest revision?
- What information existed before an incorrect update?
The timestamp supplied to temporal queries is interpreted as UTC. Convert application timestamps to UTC before passing them to SQL Server.
Retrieve all historical versions
Use FOR SYSTEM_TIME ALL to retrieve every available version from the current and history tables.
SELECT
EmployeeId,
Name,
Department,
Salary,
ValidFrom,
ValidTo
FROM dbo.Employees
FOR SYSTEM_TIME ALL
WHERE EmployeeId = 101
ORDER BY ValidFrom;
This query returns the employee's current and previous versions.
It is useful for displaying a record's change history in an application or investigating when particular values were valid.
Query records between two timestamps
The FROM ... TO subclause retrieves row versions that were active during at least part of the specified interval.
SELECT
EmployeeId,
Name,
Department,
Salary,
ValidFrom,
ValidTo
FROM dbo.Employees
FOR SYSTEM_TIME
FROM '2026-01-01 00:00:00'
TO '2026-04-01 00:00:00'
WHERE EmployeeId = 101
ORDER BY ValidFrom;
The upper boundary is exclusive.
This query is useful for reviewing changes that overlapped a reporting period.
Use BETWEEN ... AND
The BETWEEN ... AND subclause is similar to FROM ... TO, but it includes versions that became active exactly at the upper boundary.
SELECT
EmployeeId,
Name,
Department,
Salary,
ValidFrom,
ValidTo
FROM dbo.Employees
FOR SYSTEM_TIME
BETWEEN '2026-01-01 00:00:00'
AND '2026-04-01 00:00:00'
WHERE EmployeeId = 101;
The difference between FROM ... TO and BETWEEN ... AND matters when a record version begins exactly at the end timestamp.
Choose the correct operator based on whether the upper boundary should be included.
Query versions completely contained in a period
The CONTAINED IN subclause returns versions whose complete validity periods fall within the specified time range.
SELECT
EmployeeId,
Name,
Department,
Salary,
ValidFrom,
ValidTo
FROM dbo.Employees
FOR SYSTEM_TIME
CONTAINED IN
(
'2026-01-01 00:00:00',
'2026-04-01 00:00:00'
)
WHERE EmployeeId = 101;
This differs from FROM ... TO, which returns versions that overlap the interval.
Use CONTAINED IN when the requirement is to retrieve only versions that started and ended within the selected period.
Compare Current Data With Historical Data
Temporal tables are also useful for identifying differences between the current state and an earlier version.
For example, a business may need to determine how an employee's department and salary changed between two dates.
DECLARE @PreviousDate DATETIME2 =
'2026-02-01 00:00:00';
SELECT
Previous.EmployeeId,
Previous.Name,
Previous.Department AS PreviousDepartment,
Current.Department AS CurrentDepartment,
Previous.Salary AS PreviousSalary,
Current.Salary AS CurrentSalary
FROM dbo.Employees
FOR SYSTEM_TIME AS OF @PreviousDate AS Previous
INNER JOIN dbo.Employees AS Current
ON Previous.EmployeeId = Current.EmployeeId
WHERE
Previous.Department <> Current.Department
OR Previous.Salary <> Current.Salary;
The first reference retrieves employee information as it existed on the earlier date. The second reference retrieves the current employee information.
The query compares the two versions and returns employees whose department or salary changed.
This technique is useful for change reports, historical comparisons, and business analysis.
For applications that must also identify records that were deleted after the selected date, use an appropriate join strategy rather than relying only on an inner join.
Recover Accidentally Updated or Deleted Records
One practical use of temporal tables is recovering data after accidental modifications.
Suppose an administrator accidentally updates an employee's salary from ₹90,000 to ₹9,000.
The previous value is available in the history table.
First, retrieve the earlier record:
SELECT *
FROM dbo.Employees
FOR SYSTEM_TIME ALL
WHERE EmployeeId = 101
ORDER BY ValidFrom DESC;
After identifying the correct version, the application can restore the relevant values.
For example:
UPDATE dbo.Employees
SET
Department = 'Management',
Salary = 90000
WHERE EmployeeId = 101;
This creates another temporal version. The incorrect current version is preserved in the history table, and the corrected values become current.
The same principle works when a record has been deleted. The historical record can be retrieved and inserted again into the current table.
INSERT INTO dbo.Employees
(
EmployeeId,
Name,
Department,
Salary
)
SELECT
EmployeeId,
Name,
Department,
Salary
FROM dbo.EmployeeHistory
WHERE EmployeeId = 101
AND ValidTo = '2026-03-15 10:00:00';
This is an illustrative recovery query. In a real application, identify the exact historical version using its period values and review the primary key and current table state before restoring it.
Temporal tables are not a replacement for database backups. They help recover historical row values, but they do not independently protect against database corruption, infrastructure failure, or loss of the entire database.
Create Temporal Tables Using EF Core
EF Core supports SQL Server temporal tables through its SQL Server provider.
You can configure a temporal table using the IsTemporal() method.
For example, consider the following entity:
public class Employee
{
public int EmployeeId { get; set; }
public string Name { get; set; } = string.Empty;
public string Department { get; set; } = string.Empty;
public decimal Salary { get; set; }
}
Configure the entity in OnModelCreating:
protected override void OnModelCreating(
ModelBuilder modelBuilder)
{
modelBuilder.Entity<Employee>()
.ToTable(
"Employees",
table => table.IsTemporal());
}
EF Core creates the period columns and configures system versioning through the migration.
You can customize the period column and history table names:
modelBuilder.Entity<Employee>()
.ToTable(
"Employees",
table => table.IsTemporal(temporal =>
{
temporal.HasPeriodStart("ValidFrom");
temporal.HasPeriodEnd("ValidTo");
temporal.UseHistoryTable(
"EmployeeHistory",
"dbo");
}));
Create and apply the migration:
dotnet ef migrations add AddEmployeeTemporalTable
dotnet ef database update
EF Core generates the required SQL Server temporal table configuration.
Query historical data using EF Core
EF Core provides specialized temporal query operators.
To retrieve an employee's state at a particular time:
var date = new DateTime(
2026, 3, 1, 10, 0, 0,
DateTimeKind.Utc);
var employee = await context.Employees
.TemporalAsOf(date)
.FirstOrDefaultAsync(e => e.EmployeeId == 101);
To retrieve all historical versions:
var history = await context.Employees
.TemporalAll()
.Where(e => e.EmployeeId == 101)
.OrderBy(e => EF.Property<DateTime>(
e, "ValidFrom"))
.ToListAsync();
EF Core also supports TemporalFromTo, TemporalBetween, and TemporalContainedIn.
By default, period columns are represented as shadow properties in the EF Core model. Use EF.Property<T>() to access them in queries.
These operators make temporal querying easier to integrate into existing .NET applications without manually writing every FOR SYSTEM_TIME query.
Manage Historical Data and Retention
Historical data can grow quickly in applications where records are updated frequently.
For example, an order management application may update order status several times. Each update creates another historical version.
If the application retains every version indefinitely, the history table can become significantly larger than the current table.
SQL Server supports temporal history retention policies in supported versions and Azure SQL services.
For example, a table can be configured with a retention period:
ALTER TABLE dbo.Employees
SET
(
SYSTEM_VERSIONING = ON
(
HISTORY_TABLE = dbo.EmployeeHistory,
HISTORY_RETENTION_PERIOD = 12 MONTHS
)
);
The exact retention capabilities depend on the SQL Server or Azure SQL platform and version. Check the target environment before applying this configuration.
A retention policy allows the database engine to remove historical records that exceed the configured retention period.
For larger history tables, consider partitioning and a sliding-window maintenance strategy. Partitioning can help manage archival and cleanup without requiring large delete operations.
Do not configure retention only to reduce storage costs. First identify legal, compliance, reporting, and business requirements for historical data.
Performance Considerations
Temporal tables simplify history management, but they introduce additional storage and database work.
Every update or delete creates a historical row. Applications that frequently modify large records may generate substantial history data.
Consider the following practices:
- Index the current table based on normal application queries.
- Create suitable indexes on the history table for historical queries.
- Filter temporal queries by primary key and time range where possible.
- Avoid retrieving every historical version when only one timestamp is needed.
- Monitor history table size and query performance.
- Use partitioning for large history tables when appropriate.
- Review the impact of large text and binary columns because previous versions of those values are also stored.
For example, a query that retrieves all versions for one employee should normally filter by EmployeeId rather than scan the entire history table.
SQL Server's default history table has an index based on the period columns. For larger workloads, evaluate whether a clustered columnstore index or additional rowstore indexes better match the query patterns.
If the requirement is to query historical versions only, a direct query against the history table may sometimes perform better than a temporal query that checks both current and historical data. However, direct history-table access needs careful handling of retention policies and period semantics.
Temporal Tables vs Traditional Audit Tables
Traditional audit tables and temporal tables solve related but different problems.
| Feature | Temporal tables | Traditional audit tables |
|---|
| Historical row versions | Automatically maintained | Must be implemented |
| Update tracking | Automatic | Usually requires triggers or application logic |
| Delete tracking | Automatic | Must be implemented |
| Point-in-time queries | Built-in temporal syntax | Custom SQL required |
| User who made a change | Not captured automatically | Can be captured |
| Reason for a change | Not captured automatically | Can be captured |
| Custom audit events | Limited to row versions | Highly customizable |
| Maintenance | Managed by SQL Server | Depends on implementation |
Temporal tables are suitable when the requirement is to preserve previous versions of database rows.
Traditional audit tables are more appropriate when the business needs additional information such as the user who changed a record, the application source, the reason for the change, or the operation that triggered it.
Some applications use both approaches: temporal tables preserve row history, while a separate audit system records business and security events.
Common Mistakes to Avoid
| Mistake | Why it causes problems | Recommended approach |
|---|
| Treating temporal history as a complete audit log | User identity and change reasons are not captured automatically | Add a separate audit mechanism when required |
| Ignoring UTC timestamps | Historical queries may return unexpected results | Convert application timestamps to UTC |
| Keeping history indefinitely without planning | Storage usage can grow substantially | Define a retention and archival policy |
Using FROM ... TO when the upper boundary must be included | The upper boundary is exclusive | Use BETWEEN ... AND when appropriate |
| Restoring records without checking their versions | The wrong historical values may be restored | Identify the exact version before recovery |
| Ignoring history table indexes | Historical queries may become slow | Review query plans and indexing |
| Assuming temporal tables replace backups | They do not protect against database-level failures | Maintain regular database backups |
| Updating period columns manually | SQL Server controls the system-time period | Let the database engine manage period values |
Advantages and Disadvantages
| Advantages | Disadvantages |
|---|
| Automatically preserves previous row versions | Requires additional storage |
| No need to create manual history triggers | Does not capture the user or reason behind a change |
| Supports point-in-time queries | Historical queries can become expensive on large tables |
| Tracks updates and deletes | Requires retention and archival planning |
| Integrates with EF Core | Some advanced database operations require special handling |
| Helps investigate accidental data changes | Does not replace database backups or full auditing |
Conclusion
SQL Server temporal tables provide a reliable way to maintain and query historical versions of database records. Once system versioning is enabled, SQL Server automatically preserves previous row versions whenever records are updated or deleted.
The FOR SYSTEM_TIME clause makes historical data accessible through familiar SQL queries. Developers can retrieve records as they existed at a specific time, compare historical and current values, and investigate changes without building a separate history mechanism for every table.
EF Core also supports temporal table configuration and historical queries, making the feature straightforward to integrate into .NET applications.
However, temporal tables should be used with a clear understanding of their purpose. They preserve row versions, but they do not automatically record who made a change or why it happened. They also require storage planning, indexing, and retention management.
For applications that need historical reporting, point-in-time data analysis, and recovery from accidental record changes, system-versioned temporal tables provide a practical built-in SQL Server capability.
Join the conversation! Your thoughts help the community grow.