sqladvanced
Temporal Tables for Data Versioning
Track historical changes to rows using system-versioned temporal tables.
sqlPress ⌘/Ctrl + Shift + C to copy
-- SQL Server: Create system-versioned temporal table
CREATE TABLE products (
product_id INT PRIMARY KEY,
name NVARCHAR(100),
price DECIMAL(10,2),
valid_from DATETIME2 GENERATED ALWAYS AS ROW START,
valid_to DATETIME2 GENERATED ALWAYS AS ROW END,
PERIOD FOR SYSTEM_TIME (valid_from, valid_to)
)
WITH (SYSTEM_VERSIONING = ON (
HISTORY_TABLE = dbo.products_history
));
-- Query data as of a specific point in time
SELECT * FROM products
FOR SYSTEM_TIME AS OF '2025-01-15 10:00:00';
-- Query all versions of a row
SELECT * FROM products
FOR SYSTEM_TIME ALL
WHERE product_id = 42
ORDER BY valid_from;
-- Query changes within a time range
SELECT * FROM products
FOR SYSTEM_TIME BETWEEN '2025-01-01' AND '2025-03-31';Use Cases
- Audit trail
- Point-in-time queries
- Regulatory compliance
- Data recovery
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
sqlbeginner
Audit - Technique 49
Track data mutations
Best for: database operations
#sql#database
sqlintermediate
SQL Schema Migration Pattern
Versioned schema migration scripts with forward and rollback support for database evolution.
Best for: Managing database schema changes across environments
#sql#migration
sqladvanced
Audit Log Trigger Function
Automatically record all INSERT, UPDATE, and DELETE operations into an audit log table via PostgreSQL triggers.
Best for: Compliance logging
#audit#trigger
sqladvanced
Recursive CTE for Hierarchical Data
Query hierarchical data like org charts, categories, and file trees using recursive CTEs.
Best for: Querying organizational hierarchies
#sql#cte