Designing a Temporal Table for Time-Based Data Management
Designing a Temporal Table for Time-Based Data Tracking
Write a SQL query to design a temporal table for tracking time-based data changes.
Solution:
-- Temporal table for tracking employee data changes.
CREATE TABLE Employees (
EmployeeID INT PRIMARY KEY,
Name VARCHAR(100),
Salary DECIMAL(10, 2),
SysStartTime DATETIME2 GENERATED ALWAYS AS ROW START,
SysEndTime DATETIME2 GENERATED ALWAYS AS ROW END,
PERIOD FOR SYSTEM_TIME (SysStartTime, SysEndTime)
) WITH (SYSTEM_VERSIONING = ON (HISTORY_TABLE = dbo.EmployeeHistory));
Explanation:
- Purpose of the Query :
- The goal is to design a temporal table to track changes to data over time.
- Key Components :
- SysStartTime and SysEndTime: Track the validity period of each row.
- SYSTEM_VERSIONING: Automatically maintains a history table for tracking changes.
- Why use Temporal Tables? :
- Temporal tables provide built-in support for tracking historical data.
- They simplify compliance and auditing requirements.
- Real-World Application :
- In HR systems, temporal tables track changes to employee salaries or roles.
Notes:
- Temporal tables are supported in modern relational databases like SQL Server and PostgreSQL.
- Use them for scenarios requiring point-in-time analysis or auditing.
- Important Considerations:
- Regularly monitor storage usage for history tables.
For more Practice: Solve these Related Problems:
- Write a SQL query to design a temporal table for tracking changes to product inventory levels over time.
- Write a SQL query to create a temporal table for managing historical data of customer account balances.
- Write a SQL query to design a temporal table for tracking changes to employee work hours and schedules.
- Write a SQL query to create a temporal table for auditing modifications to supplier contracts and terms.
Go to:
PREV : Designing a Polymorphic Association for Flexible Relationships.
NEXT : SQL DDL Exercises Home.
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.