Search code examples
mysqlsqlphpmyadminsql-timestamp

How to set a date for future in mysql


I am creating a table that has 3 columns one primary key id the other one reg_date to hold the date that the user has registered and the last one exp_date which is 4 years ahead of reg_date to hold the expiry date of the account.

How can I set the exp_date to reg_date + 4 years?

Here's the code I've written so far:

CREATE TABLE Accounts (
  id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  exp_date TIMESTAMP
)

Solution

  • Try this way,

    CREATE TABLE Accounts (
      id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
      reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
      exp_date TIMESTAMP generated always as (reg_date + interval 4 year)
    )