Temporal data refers to data that represents time-dependent values or captures changes over time. SQL provides robust features to work with such data, enabling applications like auditing, tracking historical records, and querying data as it existed in the past.
Temporal tables are a type of table in SQL that records historical versions of data. They allow:
DATE
: Stores only the calendar date.YYYY-MM-DD
2024-11-12
TIME
: Stores the time of day.HH:MM:SS
14:30:00
DATETIME
: Combines date and time.YYYY-MM-DD HH:MM:SS
2024-11-12 14:30:00
TIMESTAMP
: Includes date, time, and time zone information.YYYY-MM-DD HH:MM:SS.FFF
2024-11-12 14:30:00.123
CREATE TABLE Orders (
OrderID INT PRIMARY KEY,
CustomerName NVARCHAR(100),
OrderDate DATE,
OrderTime TIME,
OrderTimestamp TIMESTAMP
);
OrderDate
: Stores the calendar date of the order.OrderTime
: Tracks the time of order placement.OrderTimestamp
: Records precise time, including milliseconds.
SELECT *
FROM Orders
WHERE OrderDate = '2024-11-12';
OrderID | CustomerName | OrderDate | OrderTime | OrderTimestamp |
---|---|---|---|---|
1 | Alice | 2024-11-12 | 14:30:00 | 2024-11-12 14:30:00.123 |
SELECT *
FROM Orders
WHERE OrderTimestamp BETWEEN '2024-11-12 00:00:00'
AND '2024-11-12 23:59:59';
This query retrieves all orders placed on 2024-11-12
.
CURRENT_DATE
: Returns the current date.CURRENT_TIME
: Returns the current time.DATEADD
: Adds a specified interval to a date.DATEDIFF
: Calculates the difference between two dates.FORMAT
: Formats a date or time value.
SELECT DATEADD(DAY, 7, '2024-11-12') AS NewDate;
NewDate |
---|
2024-11-19 |
SELECT DATEDIFF(DAY, '2024-11-01', '2024-11-12') AS DaysDifference;
DaysDifference |
---|
11 |
Use the TIMESTAMP WITH TIME ZONE
data type to store time zone-aware data.
CREATE TABLE Events (
EventID INT PRIMARY KEY,
EventTime TIMESTAMP WITH TIME ZONE
);
SELECT EventTime AT TIME ZONE 'UTC' AS UTC_Time,
EventTime AT TIME ZONE 'America/New_York' AS NewYork_Time
FROM Events;
CREATE TABLE LogEntries (
EntryID INT PRIMARY KEY,
LogMessage NVARCHAR(255),
LogTime TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
INSERT INTO LogEntries (LogMessage)
VALUES ('User logged in');
LogTime
automatically captures the time of the event.EntryID | LogMessage | LogTime |
---|---|---|
1 | User logged in | 2024-11-12 14:45:00.000 |
Temporal data management is essential for modern applications that require time-based analysis, event logging, and historical data tracking. By leveraging SQL's robust temporal data types and functions, you can efficiently handle complex time-related requirements. Happy Coding!❤️