Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to define a timestamp column that is not null and has no default and no special behavior on update?

When I create a table with a timestamp column, that column is magically defined as NOT NULL DEFAULT CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP. Ignoring how weird this is so far, I would like to change it to have no default and no special "on update" behavior.

I found that if I change the column to be NULL, the default is magically set to NULL and the "on update" magically disappears. This is great, however I would like the column to be NOT NULL. When I change it back, both the default and "on update" (set to CURRENT_TIMESTAMP) magically reappear.

I know I could use datetime instead of timestamp, but I'm interested in timestamp because it is timezone-aware (seems to be like "timestamp with time zone" in Postgres).

like image 416
aditsu quit because SE is EVIL Avatar asked Mar 17 '12 09:03

aditsu quit because SE is EVIL


People also ask

Can TIMESTAMP column NULL?

To permit a TIMESTAMP column to contain NULL , explicitly declare it with the NULL attribute. In this case, the default value also becomes NULL unless overridden with a DEFAULT clause that specifies a different default value. DEFAULT NULL can be used to explicitly specify NULL as the default value.

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.

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 in Oracle?

TIMESTAMP has a default of 0 unless defined with the NULL attribute, in which case the default is NULL .


1 Answers

Timestamp columns are a special case. See here: By default, TIMESTAMP columns are NOT NULL, cannot contain NULL values, and assigning NULL assigns the current timestamp.

For more detailed information read up on Data Type Default Values.

Specifically that situation applies when not running in strict mode. If running in strict mode, inserting a NULL will throw an error.

This should take care of it:

ALTER TABLE tableName ALTER COLUMN columnName DROP DEFAULT; 

If that doesn't work, doing this is supposed to leave you with the default (easily overwritten) but remove the ON UPDATE:

ALTER TABLE tableName CHANGE columnName columnName NOT NULL DEFAULT CURRENT_TIMESTAMP; 

Note the repeated column name.

like image 108
Ilion Avatar answered Sep 19 '22 16:09

Ilion