Exploring Temporal Tables in SQL Server

Learn SQL with Udemy

For an instructor lead, in-depth look at learning SQL click below.


Temporal tables, also known as system-versioned temporal tables, are a new feature in SQL Server 2016. They are designed to keep a full history of data changes, allowing you to query ‘point in time’ data, which is incredibly useful in scenarios such as data auditing, data forensics, and trend analysis.

Creating Temporal Tables

Temporal tables consist of two parts: the current table (also known as the ‘real’ table) and the history table. Let’s look at how to create a temporal table.

This query will create a new ‘Employees’ table along with its corresponding history table ‘EmployeesHistory’. The ‘Startdate’ and ‘Enddate’ columns are special; they represent the period for which a row is valid in the ‘real’ table. SQL Server will automatically manage these columns for you.

Querying Temporal Tables

Querying data from temporal tables is easy and straightforward. You can query it as the same way like querying a non-temporal table. The difference will come when you query the data from a specific point of time or within a period of time.

This query will return all the ‘HR’ department employees as of the first moment of 2022.

Updating and Deleting Data

Anytime a record is updated or deleted, SQL Server will automatically move the old version of the record to the history table. The following example changes an employee’s department and will create a record in the EmployeesHistory table:

Temporal tables are powerful tools when it comes to tracking data changes over time. They can also serve as a form of backup or data recovery, as they make it quick and easy to restore a table to a previous state.

Conclusion

Overall, temporal tables in SQL Server provides a simple and efficient way to keep track of data history and enable point-in-time analysis. This is just the tip of the iceberg of what you can do with temporal tables. There’s a lot more to explore!

Leave a Comment