Temporal tables are a powerful feature in SQL that allow you to maintain historical data and track changes over time. Managing temporal tables effectively is critical to ensure data consistency, performance, and compliance with business and regulatory requirements.
Temporal tables, also known as system-versioned tables, store both current and historical data by automatically tracking changes over time. They consist of two main parts:
To create a temporal table, define a primary table and its associated history table.
CREATE TABLE Products (
ProductID INT PRIMARY KEY,
ProductName NVARCHAR(100),
Price DECIMAL(10, 2),
ValidFrom DATETIME2 GENERATED ALWAYS AS ROW START,
ValidTo DATETIME2 GENERATED ALWAYS AS ROW END,
PERIOD FOR SYSTEM_TIME (ValidFrom, ValidTo)
) WITH (SYSTEM_VERSIONING = ON (HISTORY_TABLE = dbo.ProductsHistory));
ValidFrom
and ValidTo
: Columns for storing validity periods.PERIOD FOR SYSTEM_TIME
: Specifies the time period columns.SYSTEM_VERSIONING = ON
: Enables automatic history tracking.HISTORY_TABLE
: Specifies the table for storing historical records.
INSERT INTO Products (ProductID, ProductName, Price)
VALUES (1, 'Laptop', 1200.00);
ProductID | ProductName | Price | ValidFrom | ValidTo |
---|---|---|---|---|
1 | Laptop | 1200.00 | 2024-01-01 00:00:00 | 9999-12-31 23:59:59 |
UPDATE Products
SET Price = 1100.00
WHERE ProductID = 1;
ProductID | ProductName | Price | ValidFrom | ValidTo |
---|---|---|---|---|
1 | Laptop | 1100.00 | 2024-02-01 00:00:00 | 9999-12-31 23:59:59 |
ProductID | ProductName | Price | ValidFrom | ValidTo |
---|---|---|---|---|
1 | Laptop | 1200.00 | 2024-01-01 00:00:00 | 2024-02-01 00:00:00 |
SELECT *
FROM Employee FOR SYSTEM_TIME ALL
WHERE EmployeeID = 1;
EmployeeID | Name | Position | Salary | ValidFrom | ValidTo |
---|---|---|---|---|---|
1 | Alice | Developer | 60000 | 2024-11-10 10:00:00 | 2024-11-11 12:00:00 |
1 | Alice | Developer | 65000 | 2024-11-11 12:00:00 | 9999-12-31 23:59:59.999 |
Retrieve data at a specific point:
SELECT *
FROM Employee FOR SYSTEM_TIME AS OF '2024-11-10 11:00:00';
EmployeeID | Name | Position | Salary | ValidFrom | ValidTo |
---|---|---|---|---|---|
1 | Alice | Developer | 60000 | 2024-11-10 10:00:00 | 2024-11-11 12:00:00 |
ALTER TABLE Products ADD Stock INT;
ALTER TABLE Products SET (SYSTEM_VERSIONING = OFF);
DELETE FROM ProductsHistory
WHERE ValidTo < '2023-01-01';
Move data to an archive table:
INSERT INTO ProductsArchive
SELECT * FROM ProductsHistory
WHERE ValidTo < '2023-01-01';
Create indexes on temporal columns:
CREATE INDEX idx_ValidFrom ON Products (ValidFrom);
Managing temporal tables is a critical skill for ensuring accurate historical data tracking and compliance with business and legal requirements. By mastering the creation, querying, and maintenance of temporal tables, you can build robust SQL systems capable of supporting complex data analysis and auditing needs. Happy Coding!❤️