According to the prominent diagram here, the main table in a temporal table set-up is populated during the insert, and the history table is populated during update or delete.
However when I look at a query plan inserting or merging a temporal table tblWhatever
, considerable cost is associated with the operator Table Insert [tblWhateverHistory]
and when I re-create the clustered index on the history table, dropped before populating the temporal table, the allocated storage jumps considerably.
It all leads me to believe, that the history table is populated with a copy of every record in the temporal table initially, but those history copies are not accessible until and unless the temporal records are touched by updates or deletes. Can anyone confirm or prove me wrong?
Best Answer
I wanted to see if I could reproduce your observation of activity on the history table during inserts to the temporal table. To isolate the two tables I will place each on its own filegroup. I started with a new database in its own directory:
Then I created a temporal table and its history table.
The
Information
column is just over half a page long and fixed length so one row consumes a page and relatively few rows can cause a lot of page allocation. At this point the File Explorer shows the directory thus:Now I populate the temporal table:
The only file growth has been on the temporal table. Or at least write activity on the History filegroup is less than the 1MB initially allocated to it.
As a further test I ran SysInternals Process Monitor (PM) while performing the inserts. The
checkpoint
statements throughout the code are to ensure activity is flushed to disk so PM can observe it. I captured all events on the directory holding the DB's files. It registered 145 WriteFile operations, amongst others, against Data.ndf and no operations at all against History.ndf.The execution plan for the INSERT is this:
It shows no activity on the history table, only the temporal table.
Building a clustered index on the history table again showed no activity on History.ndf in Process Monitor.
I think this disproves your hypothesis, at least for my minimal setup. I'm not surprised to see file growth on a clustered index build. In SQL Server the clustered index leaf pages are the data. So to get the data in clustered sequence the storage engine copies the data from its current location to its new. Likely there would be a lot of free space left in that file after the clustered index had build, being the space where the data used to be.
I cannot guess why you saw the insert operators referencing the history table.