When working with databases, it’s common to have columns that track when records are created or modified. In MySQL, this often involves setting default values for DATETIME
or TIMESTAMP
columns. This tutorial will guide you through the methods available for setting these defaults in MySQL, highlighting differences across versions and providing solutions using triggers where necessary.
Overview of DATETIME and TIMESTAMP
Before diving into default settings, let’s distinguish between DATETIME
and TIMESTAMP
:
-
DATETIME: Stores values without time zone information. It allows a range from ‘1000-01-01 00:00:00’ to ‘9999-12-31 23:59:59’.
-
TIMESTAMP: Automatically converts stored values from the current timezone to UTC for storage, and back to the current timezone for retrieval. It has a narrower range from ‘1970-01-01 00:00:01’ UTC to ‘2038-01-19 03:14:07’ UTC in MySQL versions before 5.6.
Setting Defaults Before MySQL 5.6
In MySQL versions prior to 5.6, setting a default value for DATETIME
using functions like CURRENT_TIMESTAMP
wasn’t directly supported. However, you could use the TIMESTAMP
data type with its built-in capabilities:
CREATE TABLE test (
str VARCHAR(32),
ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
When inserting into this table without specifying a value for ts
, MySQL automatically fills it with the current timestamp:
INSERT INTO test (str) VALUES ("demo");
SELECT * FROM test;
-- Output: +------+---------------------+
-- | str | ts |
-- +------+---------------------+
-- | demo | [current_timestamp] |
-- +------+---------------------+
MySQL 5.6 and Later
From version 5.6 onwards, you can set default values for DATETIME
columns directly using CURRENT_TIMESTAMP
. This simplifies scenarios where you want automatic timestamps without resorting to triggers:
CREATE TABLE foo (
creation_time DATETIME DEFAULT CURRENT_TIMESTAMP,
modification_time DATETIME ON UPDATE CURRENT_TIMESTAMP
);
Using Triggers as a Workaround
For versions before 5.6 or when additional flexibility is needed, triggers can be employed. A trigger will execute specified actions in response to certain events on a table (e.g., insertions).
Here’s how you could set up a trigger for default DATETIME
values:
CREATE TRIGGER myTable_BeforeInsert
BEFORE INSERT ON tblMyTable
FOR EACH ROW SET NEW.dateAdded = IFNULL(NEW.dateAdded, NOW());
This approach ensures that if no value is provided during an insert operation, the current timestamp will be used. Conversely, it allows explicit values to be set without being overridden.
Considerations
-
Triggers: While useful, triggers add complexity and may affect performance on large datasets.
-
TIMESTAMP Behavior: Remember,
TIMESTAMP
columns automatically update when a row is modified ifON UPDATE CURRENT_TIMESTAMP
is specified. This can be both an advantage for automatic updates or a nuisance if the timestamp isn’t intended to change with every modification. -
Altering Existing Tables: To add these defaults after a table has been created, you can use the
ALTER TABLE
statement:
ALTER TABLE test_table
CHANGE COLUMN created_dt created_dt TIMESTAMP NOT NULL DEFAULT '0000-00-00 00:00:00',
CHANGE COLUMN updated_dt updated_dt TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;
Best Practices
-
Version Awareness: Be aware of your MySQL version to leverage new features or employ workarounds effectively.
-
Data Integrity: Ensure that triggers do not inadvertently overwrite important data. Use
IFNULL
or similar logic to preserve user-provided values. -
Performance Considerations: Test the impact of using triggers, especially in high-volume environments, to avoid performance degradation.
By understanding these concepts and utilizing the appropriate techniques based on your MySQL version, you can effectively manage default datetime values within your database schema.