SQL Server 2016 temporal tables: reading an earlier row at the right time
Use SQL Server 2016 system-versioned tables to inspect an earlier state, test UTC boundaries, and understand the scope of the resulting history.
Archive retrospective · Topic year 2016
In this article
Find out whether a guide was public that day
A help desk publishes guides and sometimes keeps them internal. A reader asks whether a guide was already public when an old link was sent. The current row does not answer that question. The application could maintain its own history, but every write path would have to participate. SQL Server 2016 system-versioned temporal tables offered engine-managed row history with validity intervals. In this example we update a synthetic guide's visibility and inspect both versions. This answers which table row was valid for a chosen UTC instant. Actual viewer experience may also have depended on permissions, related records, and caching. Identifying the editor or the time a page propagated to a CDN needs separate evidence. Name the report for the historical statement it can support.
Understand what the engine keeps
The primary table holds the current guide record. datetime2 columns mark the system's start and end of the validity period. PERIOD FOR SYSTEM_TIME connects the two columns, and SYSTEM_VERSIONING causes an update or delete to preserve the outgoing version in history. The old end and new start reflect the same change boundary. The explicitly named history table lets operators observe where the count grows. The current table needs an identifying primary key; history can have many versions of that same identifier. Updates made through different interfaces still pass through the table's versioning rule. Run the example in a separate test database. Production index choices, existing writers, and historical data expectations require measurement and preparation.
CREATE TABLE dbo.GuidePublication (
GuideId int NOT NULL PRIMARY KEY,
Visibility varchar(12) NOT NULL,
ValidFrom datetime2(7) GENERATED ALWAYS AS ROW START NOT NULL,
ValidUntil datetime2(7) GENERATED ALWAYS AS ROW END NOT NULL,
PERIOD FOR SYSTEM_TIME (ValidFrom, ValidUntil)
)
WITH (
SYSTEM_VERSIONING = ON (HISTORY_TABLE = dbo.GuidePublicationHistory)
);
Read AS OF in UTC
AS OF selects a UTC instant. A version is valid from its start, including that instant, until its end, excluding that instant. When a report starts with a local clock reading, establish the zone and resolve it to UTC. A clock reading can be ambiguous during a transition. The fixture instead reads the first version's actual ValidFrom value. A brief delay separates changes in independent transactions for the demonstration. The database's period times are tied to transaction start in UTC, which matters when a transaction runs longer than the update statement. In the historical query the AS OF clause precedes the alias. The current state continues to use the same table under ordinary SELECT.
Check both versions under separate transactions
The example inserts guide 4 as draft, records the first start, then updates it to public. A current query should return public. The query for the first instant should return draft. An ALL query shows the closed version and the active version. Run the example in autocommit rather than placing the entire script in a single transaction. Several changes in one transaction can share timestamps, yielding zero-duration versions excluded from ordinary temporal query output. Record finer-grained business events separately when they matter. Test deletion in another trial. The current row disappears while a historical query still finds the earlier entry. Query just at the update boundary and confirm the new row wins there.
-- Run in a test database under autocommit, outside an explicit transaction.
INSERT dbo.GuidePublication (GuideId, Visibility) VALUES (4, 'draft');
DECLARE @firstVersion datetime2(7);
SELECT @firstVersion = ValidFrom
FROM dbo.GuidePublication WHERE GuideId = 4;
WAITFOR DELAY '00:00:00.100';
UPDATE dbo.GuidePublication SET Visibility = 'public' WHERE GuideId = 4;
SELECT Visibility FROM dbo.GuidePublication WHERE GuideId = 4;
SELECT p.Visibility
FROM dbo.GuidePublication FOR SYSTEM_TIME AS OF @firstVersion AS p
WHERE p.GuideId = 4;
SELECT Visibility, ValidFrom, ValidUntil
FROM dbo.GuidePublication FOR SYSTEM_TIME ALL
WHERE GuideId = 4 ORDER BY ValidFrom;
Keep history separate from the context of an edit
Temporal history captures previous column values. A change request, editor identity, and approval rationale are not automatically added. Decide where those events belong if the help desk needs them. A join can also mix times unintentionally. An old visibility joined with a department's current name can produce a useful retrospective with present-day labels, but the report should identify that choice. Use a consistent temporal query across eligible tables when historical context is needed. Confirm which tables a view's AS OF clause affects. Read historical data with its own access expectations. The fact that a user can see today's guide does not establish that they can see earlier private versions.
Measure growth alongside accuracy and access
Frequently changed rows can grow their history faster than the current table. After the basic fixture, run a representative set of updates and compare a point lookup with a broad range query. Record result sizes, indexes, and the actual plan. Plan retention with the deployment version and the institution's requirements rather than assuming capabilities of later SQL Server releases are already available. Check the previous instant, exact transition, deletion, and authorized history cases separately. A principal benefit of the 2016 feature is that the row's time interval becomes queryable without custom changes to every caller. As that history grows, verification of the returned data, its access boundary, and the workload together makes reports easier to defend.
Reader discussion
What would you change first for maintainability and testing in your own project?
No comments yet. Be the first to contribute.
Write a comment