I am going to create a table with a column storing Created_date which is of datetime datatype. And my aim is to set its default value as sysdate().
I tried
CREATE TABLE tbl_table (
created_date datetime DEFAULT sysdate())
This gives me error saying not a valid default statement. I used similar logic in Oracle.
Please help me to resolve this.
Thanks in advance.
Try
CREATE TABLE tbl_table ( created_date TIMESTAMP DEFAULT NOW())
But: NOW is different from sysdate and TIMESTAMP is different from datetime, keep this in mind.
Normaly you only can use constants for default-values. TIMESTAMP is the only column-type which supports a function like NOW(). See here for further information on the MySQL Bugtracker.
CREATE TABLE tbl_table(
created_datetime DATETIME DEFAULT CURRENT_TIMESTAMP,
modified_datetime DATETIME ON UPDATE CURRENT_TIMESTAMP
)
Should do the trick.
Related
It is possible to set default value on DATE (NOT DATETIME) column in MySQL 5.7 to current date?
I try this (generated by Workbench):
ALTER TABLE `db`.`table` CHANGE COLUMN `column` `column` DATE NOT NULL DEFAULT CURDATE() ;
but not works for me.
(no data in table)
No, you cannot. The documentation is pretty clear on this:
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 TIMESTAMP and DATETIME columns. See Section 12.3.5, “Automatic
Initialization and Updating for TIMESTAMP and DATETIME”.
You can do one of the following:
Set up a column with a default value for the DATETIME. Create view that extracts the date as a separate column.
Create an insert trigger to set the date column.
There is a way you can do this if you have another column that has a for example a datetime field with a default of NOW(). See this post:
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()))
NOTE: The question is about DATE type, not Datetime nor Timestamp
How to alter column of date data type to use current date by default?
I saw a lot of examples for datetime (with time part), but not for date. I have tried:
ALTER TABLE `accounting` ALTER `accounting_date`
SET DEFAULT CURRENT_DATE;
ALTER TABLE `accounting` CHANGE `accounting_date`
`accounting_date` DATE NOT NULL DEFAULT CURRENT_DATE;
I also tried with CURDATE(), NOW(), CURRENT_DATE() ...
MySQL 8.0+:
CREATE TABLE foo (
`creation_time` DATE DEFAULT (DATE_FORMAT(NOW(), '%Y-%m-%d'))
)
I use version 8.0.26, this is working:
datecolumn date DEFAULT (CURDATE())
It does not work, if you don't use the brackets!
Probably you cannot set default value for 'date' data type in mysql. You need to change the type to timestamp or datetime.
You may have a look at this similar question.
Invalid default value for 'Date'
EDIT:
In version 5.6.5, it is possible to set a default value on a datetime column, and even make a column that will update when the row is updated. The type definition:
CREATE TABLE foo (
`creation_time` DATETIME DEFAULT CURRENT_TIMESTAMP,
`modification_time` DATETIME ON UPDATE CURRENT_TIMESTAMP
)
Reference: http://optimize-this.blogspot.com/2012/04/datetime-default-now-finally-available.html
As noted in this question Invalid default value for 'create_date' timestamp field, this error may happen when MySQL is in strict mode (which is default behavior, I believe).
If you want to override it, just disable all these checks when creating your table:
SET SQL_MODE='ALLOW_INVALID_DATES';
The warning will be still generated, however it will allow to create the table.
It seems to work in sqlite:
"date" DATE NOT NULL DEFAULT (DATE(CURRENT_TIMESTAMP))
No, you cannot. The documentation is pretty clear on this:
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 TIMESTAMP and DATETIME columns.
In an existing database, I've age column (INT). Now I need to set it as dob (DATETIME).
I try doing so through PHPMyAdmin, giving CURRENT_TIMESTAMP as default value as defined by answer with 138 upvotes. However PHPMyAdmin is complaining #1067 - invalid default value for 'dob' as in attached screenshot:
Can someone please suggest why I'm getting that error and how to fix that?
You can't set CURRENT_TIMESTAMP as default value with DATETIME.
But you can do it with TIMESTAMP.
See the difference here.
Words from this blog
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 column.
Set the type of the field as TIMESTAMP too.
I don't think you can achieve that with mysql date. You have to use timestamp or try this approach..
CREATE TRIGGER table_OnInsert BEFORE INSERT ON `DB`.`table`
FOR EACH ROW SET NEW.dateColumn = IFNULL(NEW.dateColumn, NOW());
You're getting that error because the default value current_time is not valid for the type DATETIME. That's what it says, and that's whats going on.
The only field you can use current_time on is a timestamp.
The best way for DateTime is use a Trigger:
/************ 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();
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()))