Practical Timestamp Scenarios
Real-World Timestamp Applications
User Activity Tracking
graph LR
A[User Activity] --> B[Login Timestamps]
A --> C[Session Duration]
A --> D[Last Active Time]
CREATE TABLE user_sessions (
user_id INT,
login_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
logout_time TIMESTAMP NULL,
session_duration INT GENERATED ALWAYS AS (
TIMESTAMPDIFF(SECOND, login_time, logout_time)
) STORED
);
Audit Log Management
Tracking Changes
CREATE TABLE audit_log (
log_id INT PRIMARY KEY,
table_name VARCHAR(50),
record_id INT,
action_type ENUM('INSERT', 'UPDATE', 'DELETE'),
changed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
changed_by VARCHAR(100)
);
Scheduled Task Management
Scenario |
Timestamp Technique |
Example Use Case |
Periodic Jobs |
Interval Checking |
Backup scheduling |
Expiration Tracking |
Date Comparison |
Subscription management |
Event Logging |
Precise Timing |
System monitoring |
Time-Based Data Retention
-- Automatically delete old records
DELETE FROM user_logs
WHERE created_at < DATE_SUB(NOW(), INTERVAL 1 YEAR);
Query Execution Tracking
CREATE TABLE query_performance (
query_id INT AUTO_INCREMENT PRIMARY KEY,
query_text TEXT,
execution_start TIMESTAMP(6),
execution_end TIMESTAMP(6),
execution_time DECIMAL(10,2) GENERATED ALWAYS AS (
TIMESTAMPDIFF(MICROSECOND, execution_start, execution_end) / 1000
) STORED
);
Temporal Data Analysis
graph TD
A[Timestamp Analysis] --> B[Trend Identification]
A --> C[Periodic Reporting]
A --> D[Predictive Insights]
E-Commerce Order Tracking
CREATE TABLE orders (
order_id INT PRIMARY KEY,
customer_id INT,
order_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
payment_time TIMESTAMP NULL,
shipping_time TIMESTAMP NULL,
status ENUM('PENDING', 'PAID', 'SHIPPED', 'DELIVERED')
);
LabEx Learning Tip
Explore these practical scenarios in LabEx's MySQL environment to gain hands-on experience with real-world timestamp applications.
Best Practices
- Use appropriate precision
- Consider time zone implications
- Implement efficient indexing
- Validate timestamp data
- Use generated columns for complex calculations