Skip to content

Instantly share code, notes, and snippets.

@6aditya8
Last active April 1, 2020 14:05
Show Gist options
  • Save 6aditya8/b64ce6bcc69db7db439f12414ad4450d to your computer and use it in GitHub Desktop.
Save 6aditya8/b64ce6bcc69db7db439f12414ad4450d to your computer and use it in GitHub Desktop.
Adding created_at and modified_at columns in MySQL5.5 and below as DATETIME fields. These versions didn't allow default for any date/datetime column to be the value of a function such as NOW() or CURRENT_DATE. This can be alternatively achieved using triggers.
-- Add the columns created_at & modified_at to your required table.
ALTER TABLE
table_name
ADD
COLUMN created_at DATETIME NULL
ADD
COLUMN modified_at DATETIME NULL;
-- Initialize the data with the current timestamp.
UPDATE
TABLE table_name
SET
created_at = NOW(),
modified_at = NOW()
WHERE
1;
-- Create a trigger which ensures that when new rows are added, the default value is NOW().
CREATE TRIGGER table_name__before_insert BEFORE
INSERT
ON table_name FOR EACH ROW
SET
NEW.created_at = NOW(),
NEW.modified_at = NOW();
-- Create a similar trigger for updating rows.
CREATE TRIGGER table_name__before_update BEFORE
UPDATE
ON table_name FOR EACH ROW
SET
NEW.created_at = OLD.created_at,
NEW.modified_at = NOW();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment