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.

A woman with glasses holding a lantern walks back along a path of glowing stepping stones, where a gold flag marks the oldest stone in the nearest run of steel blue stones.

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:

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:

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:

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:

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:

The two tables hold four versions of merchant 6:

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:

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:

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 coolname3 and CoolName3 as 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

  1. 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. ↩
  2. Answer 350991 - DBA Stack Exchange. My answer to the question, using LAG partitioned by merchant over a temporary table of 600,000 generated rows. ↩
  3. 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. ↩