Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expire date as default value for TIMESTAMP column

Is there any way to set the default value for a column as an expire date (some hours from CURRENT_TIMESTAMP)?

I have already tried:

ALTER TABLE `table` 
ADD COLUMN `expire` TIMESTAMP NOT NULL DEFAULT TIMESTAMPADD(HOUR, 5, CURRENT_TIMESTAMP);

But didn't work..

like image 376
Victor Avatar asked Mar 15 '12 14:03

Victor


People also ask

How do I add a default value to a TIMESTAMP column?

Use of DEFAULT CURRENT_TIMESTAMP and ON UPDATE CURRENT_TIMESTAMP is specific to TIMESTAMP. The DEFAULT clause also can be used to specify a constant (nonautomatic) default value; for example, DEFAULT 0 or DEFAULT '2000-01-01 00:00:00'.

What is the default value for TIMESTAMP?

A TIMESTAMP column that permits NULL values does not take on the current timestamp at insert time except under one of the following conditions: Its default value is defined as CURRENT_TIMESTAMP and no value is specified for the column.

What is the default value for date in MySQL?

MySQL retrieves and displays DATE values in 'YYYY-MM-DD' format. The supported range is '1000-01-01' to '9999-12-31'. even if they also say: Invalid DATE, DATETIME, or TIMESTAMP values are converted to the “zero” value of the appropriate type ('0000-00-00' or '0000-00-00 00:00:00').

Does TIMESTAMP contain date?

The TIMESTAMP data type is used for values that contain both date and time parts. TIMESTAMP has a range of '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC. A DATETIME or TIMESTAMP value can include a trailing fractional seconds part in up to microseconds (6 digits) precision.


1 Answers

You can't implement a complex default value like that in the table definition.

You can do it with a trigger if you want:

DELIMITER $$

DROP TRIGGER IF EXISTS tr_b_ins_table $$

CREATE TRIGGER tr_b_ins_table BEFORE INSERT ON table FOR EACH ROW BEGIN
  SET NEW.expire = NOW() + INTERVAL 5 HOUR;
END $$

DELIMITER ;
like image 174
Ike Walker Avatar answered Oct 17 '22 14:10

Ike Walker