Temporal tables in SQL enable you to track historical data changes by associating rows with specific validity periods. Validity periods specify the time intervals during which a row is valid, allowing you to maintain a history of changes in your data.
Validity periods represent time intervals during which a row in a temporal table is valid. These periods allow SQL to maintain a history of changes and provide insight into how data evolves over time.
System-time validity automatically tracks changes in rows with timestamps managed by the database system.
Application-time validity defines validity periods explicitly based on business rules or application requirements.
Combines system-time and application-time periods for comprehensive temporal data management.
Here’s how to create a temporal table with system-time validity:
CREATE TABLE Employees (
EmployeeID INT PRIMARY KEY,
Name NVARCHAR(100),
Position NVARCHAR(50),
Salary 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);
ValidFrom
and ValidTo
: Track the validity period.PERIOD FOR SYSTEM_TIME
: Marks the columns as system-time period.SYSTEM_VERSIONING = ON
: Enables automatic versioning.
INSERT INTO Employees (EmployeeID, Name, Position, Salary)
VALUES (1, 'Alice', 'Developer', 75000);
UPDATE Employees
SET Salary = 80000
WHERE EmployeeID = 1;
EmployeeID | Name | Position | Salary | ValidFrom | ValidTo |
---|---|---|---|---|---|
1 | Alice | Developer | 75000 | 2024-01-01 00:00:00 | 2024-06-01 00:00:00 |
1 | Alice | Developer | 80000 | 2024-06-01 00:00:00 | 9999-12-31 23:59:59 |
SELECT * FROM Employees FOR SYSTEM_TIME AS OF '2024-06-01';
EmployeeID | Name | Position | Salary | ValidFrom | ValidTo |
---|---|---|---|---|---|
1 | Alice | Developer | 80000 | 2024-06-01 00:00:00 | 9999-12-31 23:59:59 |
SELECT * FROM Employees FOR SYSTEM_TIME BETWEEN '2024-01-01' AND '2024-06-01';
EmployeeID | Name | Position | Salary | ValidFrom | ValidTo |
---|---|---|---|---|---|
1 | Alice | Developer | 75000 | 2024-01-01 00:00:00 | 2024-06-01 00:00:00 |
SELECT * FROM Employees
WHERE ValidFrom BETWEEN '2024-01-01' AND '2024-12-31'
AND ApplicationStartDate BETWEEN '2024-05-01' AND '2024-11-30';
Combines system-time and application-time conditions for detailed queries.
Track changes for compliance and troubleshooting.
Retrieve and analyze past states of data.
Ensure legal requirements for data retention and accuracy are met.
Validity periods in temporal tables provide a robust framework for managing time-sensitive data. By understanding system-time and application-time validity, and combining them for bi-temporal management, you can ensure comprehensive data auditing, analysis, and compliance. Happy Coding!❤️