Monday, January 14, 2013

How to create a column in MySQL that is automatically set to row creation or update time

  1. Column that is automatically set to current time when row is created:
    column TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    
  2. Column that is is automatically set to current time when row is updated:
    column TIMESTAMP DEFAULT 0 ON UPDATE CURRENT_TIMESTAMP
    
  3. Column that is automatically set to current time when row is created or updated:
    column TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    
Complete example:
CREATE TABLE table (
id                INTEGER(10) UNSIGNED AUTO_INCREMENT,
last_updated      TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
created           DATETIME DEFAULT NULL,
);

No comments:

Post a Comment