There's something very irritating going on with my TIMESTAMPS ...
I have a "createdat", "deletedat" and "updatedat" column in my Table... I've set my deletedat and updated at to NULL and DEFAULT NULL ... however, when a new record is added, the NOW() function is always executed for deletedat and updatedat instead of just leaving it as NULL.
So I end up with: 00:00:00 ...
Why isn't it just defaulting to NULL?
Here's my Table:
Here's when Inserting (notice the NOW function is selected):
The following SQL is executed:
INSERT INTO `MYTABLE_DEV`.`messages` (`id`, `fromUserId`, `toUserId`, `subject`, `body`, `createdat`, `updatedat`, `deletedat`) VALUES (NULL, '1', '3', 'Message', 'This is another message.', CURRENT_TIMESTAMP, NOW(), NOW());
You are executing NOW() instead of setting null. Use this query:
INSERT INTO `MYTABLE_DEV`.`messages` (`id`, `fromUserId`, `toUserId`, `subject`, `body`) VALUES (NULL, '1', '3', 'Message', 'This is another message.');
or with all fields...
INSERT INTO `MYTABLE_DEV`.`messages` (`id`, `fromUserId`, `toUserId`, `subject`, `body`, `createdat`, `updatedat`, `deletedat`) VALUES (NULL, '1', '3', 'Message', 'This is another message.', CURRENT_TIMESTAMP, NULL, NULL);
This is expected behaviour.
Unlike other databases, in MySQL TIMESTAMP
columns are ALWAYS updated with now()
whenever the row is updated. This is a deliberate feature of the TIMESTAMP datatype.
Edit: Note that I am talking here about TIMESTAMP
, not TIMESTAMP DEFAULT NULL
or any other variations.
What you want is a DATETIME
datatype - they behave as normal columns.
Here's some test SQL to show its behaviour:
create table timestamp_datatype (id int, dt datetime, ts timestamp);
-- test 1: leaving ts to default - you get now()
insert into timestamp_datatype (id, dt) values (1, '2011-01-01 01:01:01');
-- test 2: trying to give ts a value - this works
insert into timestamp_datatype (id, dt, ts) values (2, '2011-01-01 01:01:01', '2011-01-01 01:01:01');
-- test 3: specifying null for ts - this doesn't work - you get now()
insert into timestamp_datatype (id, dt, ts) values (3, '2011-01-01 01:01:01', null);
-- test 4: updating the row - ts is updated too
insert into timestamp_datatype (id, dt, ts) values (4, '2011-01-01 01:01:01', '2011-01-01 01:01:01');
update timestamp_datatype set dt = now() where id = 4; -- ts is updated to now()
select * from timestamp_datatype;
+------+---------------------+---------------------+
| id | dt | ts |
+------+---------------------+---------------------+
| 1 | 2011-01-01 01:01:01 | 2011-07-05 09:50:24 |
| 2 | 2011-01-01 01:01:01 | 2011-01-01 01:01:01 |
| 3 | 2011-01-01 01:01:01 | 2011-07-05 09:50:24 |
| 4 | 2011-07-05 09:50:24 | 2011-07-05 09:50:24 |
+------+---------------------+---------------------+
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With