Temporal tables are a powerful feature in SQL that allows tracking and analyzing data changes over time. They enable you to query historical data as it existed at a specific point or within a time range, making them invaluable for auditing, debugging, and data recovery.
Temporal tables are a type of table in SQL that records historical versions of data. They allow:
These tables automatically track changes, maintaining a history of all updates and deletions.
These tables allow specifying a custom time period for data validity, enabling user-defined temporal constraints.
CREATE TABLE Employee (
EmployeeID INT PRIMARY KEY,
Name NVARCHAR(100),
Position NVARCHAR(50),
Salary DECIMAL(10, 2),
ValidFrom DATETIME2 GENERATED ALWAYS AS ROW START NOT NULL,
ValidTo DATETIME2 GENERATED ALWAYS AS ROW END NOT NULL,
PERIOD FOR SYSTEM_TIME (ValidFrom, ValidTo)
)
WITH (SYSTEM_VERSIONING = ON (HISTORY_TABLE = dbo.EmployeeHistory));
ValidFrom
and ValidTo
: Automatically track the start and end times for each row.PERIOD FOR SYSTEM_TIME
: Indicates the columns for tracking system time.SYSTEM_VERSIONING = ON
: Activates system versioning, linking the current table with a history table.Employee
table tracks current data.EmployeeHistory
table stores historical versions of each row.
-- Insert data into Employee table
INSERT INTO Employee (EmployeeID, Name, Position, Salary)
VALUES (1, 'Alice', 'Developer', 60000);
-- Update the salary
UPDATE Employee
SET Salary = 65000
WHERE EmployeeID = 1;
Employee
table.EmployeeHistory
with timestamps and updates the current table.EmployeeID | Name | Position | Salary | ValidFrom | ValidTo |
---|---|---|---|---|---|
1 | Alice | Developer | 60000 | 2024-11-10 10:00:00 | 2024-11-11 12:00:00 |
EmployeeID | Name | Position | Salary | ValidFrom | ValidTo |
---|---|---|---|---|---|
1 | Alice | Developer | 65000 | 2024-11-11 12:00:00 | 9999-12-31 23:59:59.999 |
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 Employee ADD Department NVARCHAR(50);
You can update the history table manually for corrections:
ValidFrom
and ValidTo
for efficient queries.Temporal tables in SQL provide robust capabilities for tracking and analyzing data changes over time. By leveraging features like system-versioning and application-defined periods, you can ensure data integrity, simplify auditing, and support historical queries effortlessly. Happy Coding!❤️