Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to create date column in MySQL to take current date automatically when row inserted

    • 0
    • 2
    • 1
    • 3
    • 0
    • 0
    • 0
    • 0
    • 304
    Comment on it

    The TIMESTAMP data type is the only data type which is used to have MySQL automatically set the time when a row is inserted and/or updated. DATETIME columns cant do this.

    We can define more than one TIMESTAMP column in a table, but only one TIMESTAMP column in a table can set to be automatically initialized and automatically updated.

    We can use TIMESTAMP with 4 options as below:

      1. Auto-initialization and auto-update: We want to make column to be initialized and updated automatically.
     `modifiedDate` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    
      2. Auto-initialization only: We want to make column to be initialized automatically only.
     `modifiedDate` TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    
      3. Auto-update only: We want to make column to be updated automatically only.
      `modifiedDate` TIMESTAMP DEFAULT 0 ON UPDATE CURRENT_TIMESTAMP
    
      4. We don't want to do anything.
     `modifiedDate` TIMESTAMP DEFAULT 0
    

    Example: In the below example I've used TIMESTAMP on modifiedDate column.

    CREATE TABLE `user` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `name` varchar(45),
      `createdDate` DATETIME DEFAULT NULL,
      `modifiedDate` TIMESTAMP ON UPDATE CURRENT_IMESTAMP,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    

    Hope this will help you :)

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: