MySQL: Multiple Timestamps in One Table for DateAdded, DateUpdated - mysql

I want to have multiple Timestamps in one table for columns DateAdded and DateUpdated. I have this incorrect definition where DateAdded is at '0000-00-00 00:00:00' and only works for DateUpdated.
`DateAdded` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`DateUpdated` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
When I try to edit to have 2 Timestamps I get this error:
Incorrect table definition; there can be only one TIMESTAMP column with CURRENT_TIMESTAMP in DEFAULT or ON UPDATE clause
Please help me with correct workaround. I can see the issue is known but I am not seeing a solution anywhere.

I would replace invalid timestamp:
ALTER TABLE tab MODIFY `DateAdded` timestamp DEFAULT CURRENT_TIMESTAMP;
-- or any other valid value
DBFiddle Demo

Related

MySQL sets field to current date when value is null

I have a table with two timestamp fields. They are not nullable. The problem is that whenever I insert null into those fields, the current date is automatically saved, instead of throwing an error saying "Column 'first_data_dt' cannot be null", just like it happens when I insert a value into another non-nullable field.
There are no triggers associated to this table.
Does anybody know why this is happening?
EDIT to add table definition:
CREATE TABLE `ui_mytable` (
`id` int(11) NOT NULL,
`first_data_dt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`last_data_dt` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
I understand now why first_data_dt is updated to the current timestamp anytime I insert null. But what about last_data_dt?
That's what a TIMESTAMP column does:
The TIMESTAMP data type offers automatic initialization and updating to the current date and time (that is, the current timestamp). [...] You can initialize or update any TIMESTAMP column to the current date and time by assigning it a NULL value, unless it has been defined with the NULL attribute to permit NULL values.
Source: MySQL documentation
Maybe you want to use a DATETIME instead?

Database timestamps in sql

Creating a database table in MySQL. I have created two fields to grab timestamps.
created_at timestamp default '0000-00-00 00:00:00',
updated_at timestamp default now() on update now(),
When I update the database, both fields are updating to the current timestamp. Any thoughts on how to prevent this from happening? I am not providing the 'created_at' field when I update -- I am also providing 'null' for the updated_at field to auto update.
Depending on the version of MySQL you should be able to use the following for your default value on the updated_at field:
CURRENT_TIMESTAMP on UPDATE CURRENT_TIMESTAMP
Your created_at field should just have CURRENT_TIMESTAMP as the default.
I would also set both to the datatype datetime instead of timestamp.
Timestamp initialisation can be an ugly beast in mysql!
Based on the commment below you have mysql v5.6.4 or earlier:
I can't have two current_timestamps declared without getting an error -- and although it's default is 0 -- it is producing a current timestamp upon creation(without me feeding in the timestamp) – Spencer Rohan
You can have a single timestamp field that are initialised and/or updated to the current timestamp when you insert / update your record. In earlier versions this had to be the 1st timestamp field in the table.
I would simply set the created_at to be a nullable column with a default value of null because according to mysql documentation on timestamp initialization:
In other words, a TIMESTAMP column defined to permit NULL values auto-initializes only if its definition includes DEFAULT CURRENT_TIMESTAMP
By changing the default value to null you go around any problems you may have with zero dates and various sql modes.
created_at timestamp null default null,

How to give current date as default in MySQL 5.5? [duplicate]

I have two columns in table users namely registerDate and lastVisitDate which consist of datetime data type. I would like to do the following.
Set registerDate defaults value to MySQL NOW()
Set lastVisitDate default value to 0000-00-00 00:00:00 Instead of null which it uses by default.
Because the table already exists and has existing records, I would like to use Modify table. I've tried using the two piece of code below, but neither works.
ALTER TABLE users MODIFY registerDate datetime DEFAULT NOW()
ALTER TABLE users MODIFY registerDate datetime DEFAULT CURRENT_TIMESTAMP;
It gives me Error : ERROR 1067 (42000): Invalid default value for 'registerDate'
Is it possible for me to set the default datetime value to NOW() in MySQL?
As of MySQL 5.6.5, you can use the DATETIME type with a dynamic default value:
CREATE TABLE foo (
creation_time DATETIME DEFAULT CURRENT_TIMESTAMP,
modification_time DATETIME ON UPDATE CURRENT_TIMESTAMP
)
Or even combine both rules:
modification_time DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
Reference:
http://dev.mysql.com/doc/refman/5.7/en/timestamp-initialization.html
http://optimize-this.blogspot.com/2012/04/datetime-default-now-finally-available.html
Prior to 5.6.5, you need to use the TIMESTAMP data type, which automatically updates whenever the record is modified. Unfortunately, however, only one auto-updated TIMESTAMP field can exist per table.
CREATE TABLE mytable (
mydate TIMESTAMP
)
See: http://dev.mysql.com/doc/refman/5.1/en/create-table.html
If you want to prevent MySQL from updating the timestamp value on UPDATE (so that it only triggers on INSERT) you can change the definition to:
CREATE TABLE mytable (
mydate TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
I use a trigger as a workaround to set a datetime field to NOW() for new inserts:
CREATE TRIGGER `triggername` BEFORE INSERT ON `tablename`
FOR EACH ROW
SET NEW.datetimefield = NOW()
it should work for updates too
Answers by Johan & Leonardo involve converting to a timestamp field. Although this is probably ok for the use case presented in the question (storing RegisterDate and LastVisitDate), it is not a universal solution. See datetime vs timestamp question.
My solution
ALTER TABLE `table_name` MODIFY COLUMN `column_name` TIMESTAMP NOT
NULL DEFAULT CURRENT_TIMESTAMP;
EUREKA !!!
For all those who lost heart trying to set a default DATETIME value in MySQL, I know exactly how you feel/felt. So here it is:
`ALTER TABLE `table_name` CHANGE `column_name` DATETIME NOT NULL DEFAULT 0
Carefully observe that I haven't added single quotes/double quotes around the 0.
Important update:
This answer was posted long back. Back then, it worked on my (probably latest) installation of MySQL and I felt like sharing it. Please read the comments below before you decide to use this solution now.
On versions mysql 5.6.5 and newer, you can use precise datetimes and set default values as well. There is a subtle bit though, which is to pass in the precision value to both the datetime and the NOW() function call.
This Example Works:
ALTER TABLE my_table MODIFY created datetime(6) NOT NULL DEFAULT NOW(6);
This Example Does not Work:
ALTER TABLE my_table MODIFY created datetime(6) NOT NULL DEFAULT NOW();
mysql 5.6 docs say that CURRENT_TIMESTAMP can be used as default for both TIMESTAMP and DATETIME data types:
http://dev.mysql.com/doc/refman/5.6/en/timestamp-initialization.html
`ALTER TABLE `table_name` CHANGE `column_name`
timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
ON UPDATE CURRENT_TIMESTAMP
Can be used to update the timestamp on update.
The best way is using "DEFAULT 0".
Other way:
/************ ROLE ************/
drop table if exists `role`;
create table `role` (
`id_role` bigint(20) unsigned not null auto_increment,
`date_created` datetime,
`date_deleted` datetime,
`name` varchar(35) not null,
`description` text,
primary key (`id_role`)
) comment='';
drop trigger if exists `role_date_created`;
create trigger `role_date_created` before insert
on `role`
for each row
set new.`date_created` = now();
This worked for me, using MySQL:
ALTER TABLE `table_name` MODIFY `column_name` datetime NOT NULL DEFAULT NOW();
ALTER TABLE table_name
CHANGE COLUMN date_column_name date_column_name DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP;
Finally, This worked for me!
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`dateCreated` datetime DEFAULT CURRENT_TIMESTAMP,
`dateUpdated` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `mobile_UNIQUE` (`mobile`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
Not sure if this is still active but here goes.
Regarding setting the defaults to Now(), I don't see that to be possible for the DATETIME data type. If you want to use that data type, set the date when you perform the insert like this:
INSERT INTO Yourtable (Field1, YourDateField) VALUES('val1', (select now()))
My version of mySQL is 5.5
This worked for me - just changed INSERT to UPDATE for my table.
INSERT INTO Yourtable (Field1, YourDateField) VALUES('val1', (select now()))

Behavior difference between TIMESTAMP and DATE

I have a table that has two TIMESTAMP columns (Creation_Date and Edit_date) that auto fill on INSERT (both columns get CURRENT_TIMESTAMP) and UPDATE (only the Edit_date column is changed)
The action is done by this code:
... CreationDate timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
EditDate timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE
CURRENT_TIMESTAMP, ...
I need to change the type from TIMESTAMP to DATE and have tried:
...
`CREATED_DATE` date NOT NULL DEFAULT '0000-00-00',
`EDITED_DATE` date NOT NULL DEFAULT CURRENT_DATE ON UPDATE CURRENT_DATE,
...
How can I get the same behavior. Any responses would be appreciated.
No its not possible unless you are using mysql 5.6.5
The only option was available until 5.6.5 is to use field type as timestamp and then set a default which is not constant.
The DEFAULT value clause in a data type specification indicates a
default value for a column. With one exception, the default value must
be a constant; it cannot be a function or an expression. This means,
for example, that you cannot set the default for a date column to be
the value of a function such as NOW() or CURRENT_DATE. The exception
is that you can specify CURRENT_TIMESTAMP as the default for a
TIMESTAMP
If you are using mysql 5.6.5 then you can set this behaviour for DATETIME datatype
http://dev.mysql.com/doc/refman/5.6/en/timestamp-initialization.html

Set NOW() as Default Value for datetime datatype?

I have two columns in table users namely registerDate and lastVisitDate which consist of datetime data type. I would like to do the following.
Set registerDate defaults value to MySQL NOW()
Set lastVisitDate default value to 0000-00-00 00:00:00 Instead of null which it uses by default.
Because the table already exists and has existing records, I would like to use Modify table. I've tried using the two piece of code below, but neither works.
ALTER TABLE users MODIFY registerDate datetime DEFAULT NOW()
ALTER TABLE users MODIFY registerDate datetime DEFAULT CURRENT_TIMESTAMP;
It gives me Error : ERROR 1067 (42000): Invalid default value for 'registerDate'
Is it possible for me to set the default datetime value to NOW() in MySQL?
As of MySQL 5.6.5, you can use the DATETIME type with a dynamic default value:
CREATE TABLE foo (
creation_time DATETIME DEFAULT CURRENT_TIMESTAMP,
modification_time DATETIME ON UPDATE CURRENT_TIMESTAMP
)
Or even combine both rules:
modification_time DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
Reference:
http://dev.mysql.com/doc/refman/5.7/en/timestamp-initialization.html
http://optimize-this.blogspot.com/2012/04/datetime-default-now-finally-available.html
Prior to 5.6.5, you need to use the TIMESTAMP data type, which automatically updates whenever the record is modified. Unfortunately, however, only one auto-updated TIMESTAMP field can exist per table.
CREATE TABLE mytable (
mydate TIMESTAMP
)
See: http://dev.mysql.com/doc/refman/5.1/en/create-table.html
If you want to prevent MySQL from updating the timestamp value on UPDATE (so that it only triggers on INSERT) you can change the definition to:
CREATE TABLE mytable (
mydate TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
I use a trigger as a workaround to set a datetime field to NOW() for new inserts:
CREATE TRIGGER `triggername` BEFORE INSERT ON `tablename`
FOR EACH ROW
SET NEW.datetimefield = NOW()
it should work for updates too
Answers by Johan & Leonardo involve converting to a timestamp field. Although this is probably ok for the use case presented in the question (storing RegisterDate and LastVisitDate), it is not a universal solution. See datetime vs timestamp question.
My solution
ALTER TABLE `table_name` MODIFY COLUMN `column_name` TIMESTAMP NOT
NULL DEFAULT CURRENT_TIMESTAMP;
EUREKA !!!
For all those who lost heart trying to set a default DATETIME value in MySQL, I know exactly how you feel/felt. So here it is:
`ALTER TABLE `table_name` CHANGE `column_name` DATETIME NOT NULL DEFAULT 0
Carefully observe that I haven't added single quotes/double quotes around the 0.
Important update:
This answer was posted long back. Back then, it worked on my (probably latest) installation of MySQL and I felt like sharing it. Please read the comments below before you decide to use this solution now.
On versions mysql 5.6.5 and newer, you can use precise datetimes and set default values as well. There is a subtle bit though, which is to pass in the precision value to both the datetime and the NOW() function call.
This Example Works:
ALTER TABLE my_table MODIFY created datetime(6) NOT NULL DEFAULT NOW(6);
This Example Does not Work:
ALTER TABLE my_table MODIFY created datetime(6) NOT NULL DEFAULT NOW();
mysql 5.6 docs say that CURRENT_TIMESTAMP can be used as default for both TIMESTAMP and DATETIME data types:
http://dev.mysql.com/doc/refman/5.6/en/timestamp-initialization.html
`ALTER TABLE `table_name` CHANGE `column_name`
timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
ON UPDATE CURRENT_TIMESTAMP
Can be used to update the timestamp on update.
The best way is using "DEFAULT 0".
Other way:
/************ ROLE ************/
drop table if exists `role`;
create table `role` (
`id_role` bigint(20) unsigned not null auto_increment,
`date_created` datetime,
`date_deleted` datetime,
`name` varchar(35) not null,
`description` text,
primary key (`id_role`)
) comment='';
drop trigger if exists `role_date_created`;
create trigger `role_date_created` before insert
on `role`
for each row
set new.`date_created` = now();
This worked for me, using MySQL:
ALTER TABLE `table_name` MODIFY `column_name` datetime NOT NULL DEFAULT NOW();
ALTER TABLE table_name
CHANGE COLUMN date_column_name date_column_name DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP;
Finally, This worked for me!
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`dateCreated` datetime DEFAULT CURRENT_TIMESTAMP,
`dateUpdated` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `mobile_UNIQUE` (`mobile`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
Not sure if this is still active but here goes.
Regarding setting the defaults to Now(), I don't see that to be possible for the DATETIME data type. If you want to use that data type, set the date when you perform the insert like this:
INSERT INTO Yourtable (Field1, YourDateField) VALUES('val1', (select now()))
My version of mySQL is 5.5
This worked for me - just changed INSERT to UPDATE for my table.
INSERT INTO Yourtable (Field1, YourDateField) VALUES('val1', (select now()))