Finding Where the Latest Run Began in a Temporal Table
A merchant uses the name CoolName3 for two days, switches to CoolName2, goes back to CoolName3 for two more days, then settles on CoolName2. You want the date the most recent CoolName3 run began. The first CoolName3 row is too early, because the merchant used a different name in between.

Someone asked this on DBA Stack Exchange. The table keeps one row per version of a merchant, the history lives in a temporal table, and the asker wanted a function that walks back through the history to the start of the most recent unbroken run of a given name.[1] I answered it with a plain table and LAG.[2] Then I wanted to see the same query against a real system-versioned table, so I built a small repro and a 1.3 million row version of it.
The Data
Here are the question’s ten rows for merchant 5. RowNumber 1 is the current row, followed by older rows. The question calls the date column UpdatedDate, and I’ve renamed it ValidFrom to match the temporal table:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
RowNumber MerchantName ValidFrom --------- ------------ ---------- 1 CoolName2 2026-11-10 2 CoolName2 2026-11-09 3 CoolName3 2026-11-08 4 CoolName3 2026-11-07 5 CoolName2 2026-11-06 6 CoolName3 2026-11-05 7 CoolName3 2026-11-04 8 CoolName2 2026-11-03 9 CoolName1 2026-11-02 10 CoolName1 2026-11-01 |
The question expects row 4 for CoolName3. By the same rule, CoolName2 gives row 2, CoolName1 gives row 10, and a name the merchant never used gives nothing.
Loading Backdated History into a Temporal Table
Once system versioning is on, the engine sets the period columns itself. It sets ValidFrom to the begin time of the transaction, in UTC, and copies the old version to the history table on every update.[3] Every row you create through it starts at the time of your transaction, not at a date in the past.
To get ten days of history, create both tables as ordinary tables, insert the rows with whatever dates you need, then add the period and turn system versioning on:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
CREATE TABLE [dbo].[Merchant] ( [MerchantId] int NOT NULL CONSTRAINT [Merchant_pk] PRIMARY KEY CLUSTERED , [MerchantName] varchar(200) NOT NULL , [RowNumber] int NOT NULL , [ValidFrom] datetime2(7) NOT NULL , [ValidTo] datetime2(7) NOT NULL ); CREATE TABLE [dbo].[MerchantHistory] ( [MerchantId] int NOT NULL , [MerchantName] varchar(200) NOT NULL , [RowNumber] int NOT NULL , [ValidFrom] datetime2(7) NOT NULL , [ValidTo] datetime2(7) NOT NULL , INDEX [MerchantHistory_ValidTo_ValidFrom] CLUSTERED ( [ValidTo] , [ValidFrom] ) , INDEX [MerchantHistory_MerchantId_ValidFrom] ( [MerchantId] , [ValidFrom] ) INCLUDE ( [MerchantName] , [RowNumber] ) ); INSERT INTO [dbo].[Merchant] ( [MerchantId] , [MerchantName] , [RowNumber] , [ValidFrom] , [ValidTo] ) VALUES (5, 'CoolName2', 1, '2026-11-10', '9999-12-31 23:59:59.9999999') , (6, 'OtherName1', 101, '2026-11-10', '9999-12-31 23:59:59.9999999'); INSERT INTO [dbo].[MerchantHistory] ( [MerchantId] , [MerchantName] , [RowNumber] , [ValidFrom] , [ValidTo] ) VALUES (5, 'CoolName2', 2, '2026-11-09', '2026-11-10') , (5, 'CoolName3', 3, '2026-11-08', '2026-11-09') , (5, 'CoolName3', 4, '2026-11-07', '2026-11-08') , (5, 'CoolName2', 5, '2026-11-06', '2026-11-07') , (5, 'CoolName3', 6, '2026-11-05', '2026-11-06') , (5, 'CoolName3', 7, '2026-11-04', '2026-11-05') , (5, 'CoolName2', 8, '2026-11-03', '2026-11-04') , (5, 'CoolName1', 9, '2026-11-02', '2026-11-03') , (5, 'CoolName1', 10, '2026-11-01', '2026-11-02'); ALTER TABLE [dbo].[Merchant] ADD PERIOD FOR SYSTEM_TIME ([ValidFrom], [ValidTo]); ALTER TABLE [dbo].[Merchant] SET ( SYSTEM_VERSIONING = ON ( HISTORY_TABLE = [dbo].[MerchantHistory] , DATA_CONSISTENCY_CHECK = ON ) ); |
The second index on the history table puts each merchant’s versions together in ValidFrom order. With only ten rows, the function’s plan scans the clustered index instead, but the volume test below seeks on the second index.
The Function
LAG compares each version’s name to the name of the version before it. A row starts a run when the names differ, or when no earlier version exists. Of the run starts for the requested name, the newest one is the answer:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
CREATE OR ALTER FUNCTION [dbo].[GetMerchantNameRunStart] ( @MerchantId int , @MerchantName varchar(200) ) RETURNS TABLE AS RETURN WITH [src] AS ( SELECT [m].[MerchantId] , [m].[MerchantName] , [m].[RowNumber] , [m].[ValidFrom] , [m].[ValidTo] , [NameChanged] = CASE WHEN LAG([m].[MerchantName]) OVER ( PARTITION BY [m].[MerchantId] ORDER BY [m].[ValidFrom] , [m].[ValidTo] ) = [m].[MerchantName] THEN 0 ELSE 1 END FROM [dbo].[Merchant] FOR SYSTEM_TIME ALL AS [m] WHERE [m].[MerchantId] = @MerchantId ) SELECT TOP (1) [s].[MerchantId] , [s].[MerchantName] , [s].[RowNumber] , [s].[ValidFrom] , [s].[ValidTo] FROM [src] AS [s] WHERE [s].[MerchantName] = @MerchantName AND [s].[NameChanged] = 1 ORDER BY [s].[ValidFrom] DESC , [s].[ValidTo] DESC; |
The merchant filter sits inside the CTE, not outside it. MerchantId is the partition column, so filtering it first can’t change any LAG value, and SQL Server only has to read one merchant’s versions. The name filter has to stay outside. Filtering by name first would remove the rows between runs, and LAG would see two separate CoolName3 runs as one.
The first version of each merchant has no previous row, so LAG returns NULL. NULL = 'CoolName1' isn’t true, so the CASE falls through to 1 and marks the first version as a run start.
It’s an inline table-valued function, so the optimizer expands it into the calling query, the same way it expands a view.
The results for merchant 5 match the question:
|
1 2 3 4 5 6 |
RequestedMerchantName RowNumber ValidFrom --------------------- --------- ---------- CoolName1 10 2026-11-01 CoolName2 2 2026-11-09 CoolName3 4 2026-11-07 CoolName4 NULL NULL |
Two Updates in One Transaction
The repro also gives merchant 6 three real updates after system versioning is on. The first runs in its own transaction. The other two run together in a second one:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
UPDATE [dbo].[Merchant] SET [MerchantName] = 'OtherName2' , [RowNumber] = 102 WHERE [MerchantId] = 6; WAITFOR DELAY '00:00:00.100'; BEGIN TRANSACTION; UPDATE [dbo].[Merchant] SET [MerchantName] = 'OtherName3' , [RowNumber] = 103 WHERE [MerchantId] = 6; UPDATE [dbo].[Merchant] SET [MerchantName] = 'OtherName2' , [RowNumber] = 104 WHERE [MerchantId] = 6; COMMIT TRANSACTION; |
The two tables hold four versions of merchant 6:
|
1 2 3 4 5 6 |
Source MerchantName RowNumber ValidFrom ValidTo ------- ------------ --------- --------------------------- --------------------------- current OtherName2 104 2026-11-16 19:37:54.8289631 9999-12-31 23:59:59.9999999 history OtherName3 103 2026-11-16 19:37:54.8289631 2026-11-16 19:37:54.8289631 history OtherName2 102 2026-11-16 19:37:54.7243317 2026-11-16 19:37:54.8289631 history OtherName1 101 2026-11-10 00:00:00.0000000 2026-11-16 19:37:54.7243317 |
Both updates in the second transaction got the same timestamp, so the OtherName3 version starts and ends at the same instant. FOR SYSTEM_TIME leaves out rows where ValidFrom equals ValidTo.[3] The actual plan for the small repro shows it as ValidFrom <> ValidTo on the history table scan.
So FOR SYSTEM_TIME ALL returns three versions of merchant 6, and the function’s answers follow from that:
|
1 2 3 4 5 |
RequestedMerchantName RowNumber ValidFrom --------------------- --------- --------------------------- OtherName1 101 2026-11-10 00:00:00.0000000 OtherName2 102 2026-11-16 19:37:54.7243317 OtherName3 NULL NULL |
OtherName3 returns nothing, even though the history table holds an OtherName3 row. OtherName2 returns version 102, because with 103 gone, versions 102 and 104 form one run.
I think that’s the result the asker wants. No query outside that transaction could have seen OtherName3 as the merchant’s name. If your audit rules need to count that version anyway, query the history table directly instead of using FOR SYSTEM_TIME.[3]
1.3 Million History Rows
The volume script loads 130 merchants with 10,000 backdated versions each, one hour apart, and picks each version’s name at random from three. That’s 1,300,000 history rows. It turns system versioning on, then runs one real update on every merchant, which adds 130 more.
The measured batch asks for all three names for merchant 42:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
DECLARE @MerchantId int = 42; SELECT [RequestedMerchantName] = [v].[MerchantName] , [r].[RowNumber] , [r].[ValidFrom] , [r].[ValidTo] FROM ( VALUES ('Merchant0042-1') , ('Merchant0042-2') , ('Merchant0042-3') ) AS [v]([MerchantName]) OUTER APPLY [dbo].[GetMerchantNameRunStart](@MerchantId, [v].[MerchantName]) AS [r] ORDER BY [v].[MerchantName]; |
On a local SQL Server 2019 instance (15.0.4510.2), the actual plan’s query time stats reported 70 ms elapsed and 70 ms CPU, in a serial plan. STATISTICS TIME for the same batch reported 86 ms elapsed and 78 ms CPU. STATISTICS IO showed 216 logical reads on MerchantHistory and 6 on Merchant.
The OUTER APPLY runs the function once per name. Each run is one seek on the current table’s primary key and one seek on MerchantHistory_MerchantId_ValidFrom. The history seek returned 10,001 rows each time, and it applied the zero-length filter as ValidFrom < ValidTo OR ValidFrom > ValidTo. A Concatenation joins the two inputs, and a Sort puts them in ValidFrom, ValidTo order for LAG. The largest self times were the Stream Aggregate at 22 ms, then the Window Spool and the Sort at 14 ms each. The plan carried no warnings, and the query used 856 KB of a 2,120 KB memory grant.
Without the second index, SQL Server would have to scan the history table’s clustered index, which is in ValidTo order, to find one merchant’s rows. I didn’t measure that.
The history seek returns its rows in ValidFrom, ValidTo order already, because the nonclustered index automatically includes the clustering key. The Sort sits above the Concatenation that combines the current row with the history rows. I didn’t attempt to remove it since the query returns pretty quickly as-is.
Gotchas To Be Aware Of
- This test was performed on one instance, SQL Server 2019 build 15.0.4510.2, and one run of the measured batch. Your timings may differ.
- Random names make the run lengths in the volume test vary from load to load. Merchant 42’s answers can change each time you run the script.
- The function compares names using the column’s collation. A case-insensitive collation treats
coolname3andCoolName3as the same name, and so does the function. - I didn’t test deletes. A deleted merchant has no current row, and its last history row ends at the delete time.[3]
Try It Yourself
Try the small repro on dbfiddle.uk.
Run the small repro, then rerun the merchant 6 queries with only one update in the second transaction. The OtherName3 version should come back, because its period no longer has zero length.
If you track history with temporal tables and have hit the zero-length version in your own reports, I’d like to hear how you handled it. Find me on Bluesky or LinkedIn.
References
- MS SQL temporal table using a function: crawl through history to find specific - DBA Stack Exchange. The question this post is built from, including the sample rows for merchant 5 and the expected answer of row 4 for CoolName3. ↩
- Answer 350991 - DBA Stack Exchange. My answer to the question, using LAG partitioned by merchant over a temporary table of 600,000 generated rows. ↩
- Temporal tables - Microsoft Learn. States that the period columns record the begin time of the transaction in UTC, that an update copies the previous version to the history table, that FOR SYSTEM_TIME filters out rows with a zero-duration period (ValidFrom = ValidTo), that multiple updates to the same key in one transaction produce those rows, and that you can query the history table directly to include them. ↩