Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL TIMESTAMP to default NULL, not CURRENT_TIMESTAMP

Using MySQL, I'm trying to make a timestamp column from a date column and a time column. If the date or time column contains a NULL value, MySQL automatically sets the corresponding value in the TIMESTAMP column to the CURRENT_TIMESTAMP.

Is there a way to make it default to a NULL, instead of the CURRENT_TIMESTAMP?

Something like:

ALTER TABLE customers ADD s_timestamp TIMESTAMP; UPDATE customers     SET s_timestamp = timestamp(s_date,s_time) DEFAULT NULL; 
like image 323
natsuki_2002 Avatar asked Dec 11 '13 13:12

natsuki_2002


People also ask

Can TIMESTAMP be null in MySQL?

If the explicit_defaults_for_timestamp system variable is disabled, TIMESTAMP columns by default are NOT NULL , cannot contain NULL values, and assigning NULL assigns the current timestamp. To permit a TIMESTAMP column to contain NULL , explicitly declare it with the NULL attribute.

Why is TIMESTAMP null?

TIMESTAMP Initialization and the NULL AttributeDEFAULT NULL can be used to explicitly specify NULL as the default value. (For a TIMESTAMP column not declared with the NULL attribute, DEFAULT NULL is invalid.) If a TIMESTAMP column permits NULL values, assigning NULL sets it to NULL , not to the current timestamp.

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'.

How do I insert a null in a TIMESTAMP?

In order to allow a TIMESTAMP to be nullable, create it using the NULL attribute, or alter the table and add the NULL attribute. In a create statement, it would resemble. CREATE TABLE t1 (tsvalue TIMESTAMP NULL, ... );


1 Answers

Use this query to add your column

ALTER TABLE `customers`  ADD COLUMN `s_timestamp` TIMESTAMP NULL DEFAULT NULL; 

And, if you want to get current timestamp on update only :

ALTER TABLE `customers`  ADD COLUMN `s_timestamp` TIMESTAMP NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP; 
like image 167
zessx Avatar answered Oct 05 '22 13:10

zessx