I have a table that is as follows:
CREATE TABLE SomeTable (
id int unsigned NOT NULL AUTO_INCREMENT,
status enum('broken','repaired') NOT NULL,
from datetime NOT NULL,
until datetime NOT NULL,
brought_in timestamp,
brought_by varchar(255) NOT NULL,
repair_status enum('unpayed', 'payed') DEFAULT NULL,
payed_when timestamp,
delivered_when timestamp,
primary key(id)
);
When I create the table if I do a SHOW CREATE TABLE
then I see that the column brought_in
is defined to have the current timestamp ON INSERT
and ON UPDATE
.
But I did not add such an instruction in my create table.
Why doesn't it let it be empty like the other columns?
Now on every insert or update of another column it adds the current timestamp. I don't want that.
It does not do that with the other columns. What am I doing wrong?
Best Answer
This is the default behaviour of the (first)
timestamp
column. Many more details can be read in the documentation: Automatic Initialization and Updating forTIMESTAMP
.If you don't want this, you have to explicitly tell MySQL when you create the table. You can declare a default value (or default null) and the automatic properties will be supressed. Any of the following will do (with differences in behaviour explained):
Option 1:
not null
anddefault 0
These two options are identical. The column is defined as
NOT NULL
and has a default value of0
. Note thatTIMESTAMP
is the only datatype that has a default property ofNOT NULL
, in contrast with all other datatypes and with the ISO/ANSI standard.If you try to insert
NULL
in the column, theCURRENT_TIMESTAMP
is inserted (surprise, another MySQL feature.)Option 2:
null
anddefault null
These are identical, they allow
NULL
(and both result in default beingNULL
as well.)If you try to insert
NULL
in the column, it is allowed and inserted fine (no surprises here.)Option 3:
null
anddefault 0
or some other constantThis is similar to option 2 but has a different default value.
If you try to insert
NULL
in the column, it is allowed and inserted fine, too (no surprises here either.)