tags:

views:

34988

answers:

11

How do you set a default value for a MySQL Datetime column?

In SQL Server it's getdate(), what is the equivalant for MySQL? I'm using 5.x if that is a factor.

A: 

NOW()

MySQL :: MySQL 5.0 Reference Manual :: 11.6 Date and Time Functions

Chris Serra
that does not work. no offense but answers should at least be accurate if not tested.
Brian Boatright
A: 

You can use now() to set the value of a datetime column, but keep in mind that you can't use that as a default value.

KernelM
true. I just tried using now and got an error "Error Code: 1067. Invalid default value.". so what's the answer? ;-)
Brian Boatright
+1  A: 

If you are trying to set default value as NOW(), I don't think MySQL supports that. In MySQL, you cannot use a function or an expression as the default value for any type of column, except for the TIMESTAMP data type column, for which you can specify the CURRENT_TIMESTAMP as the default.

Vijesh VP
+20  A: 

You can't do that with datetime...

but you can do it with timestamp

mysql> create table test (str varchar(32), ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP);
Query OK, 0 rows affected (0.00 sec)

mysql> desc test;
+-------+-------------+------+-----+-------------------+-------+
| Field | Type        | Null | Key | Default           | Extra |
+-------+-------------+------+-----+-------------------+-------+
| str   | varchar(32) | YES  |     | NULL              |       | 
| ts    | timestamp   | NO   |     | CURRENT_TIMESTAMP |       | 
+-------+-------------+------+-----+-------------------+-------+
2 rows in set (0.00 sec)

mysql> insert into test (str) values ("demo");
Query OK, 1 row affected (0.00 sec)

mysql> select * from test;
+------+---------------------+
| str  | ts                  |
+------+---------------------+
| demo | 2008-10-03 22:59:52 | 
+------+---------------------+
1 row in set (0.00 sec)

mysql>
sebthebert
thanks for that example.
Brian Boatright
TIMESTAMP changes when you update the row. Different behavior than DATETIME -- you can't just substitute one for the other.
Preston
Preston, that is completely incorrect. It only changes the row if you set ON UPDATE CURRENT_TIMESTAMP. Otherwise, DEFAULT CURRENT_TIMESTAMP just sets it at row create time. I don't know who voted you up but they're wrong too. timestamp is internally an epoch time, so it can't be lower than the lowest epoch value (23:59, 31 Dec 1969, or whatever it is). datetime can take any date as it's not implemented as epoch.
Artem Russakovskii
One thing to note is that you can only have one timestamp with a "CURRENT_TIMESTAMP" in it. So you can't do things like have both an updated and created column in the table...
markwatson
@Artem, you are mistaken. The first (by default) "TIMESTAMP" column in a table is always updated with the current time when the row is updated. MySQL represents this behavior with the ON UPDATE CURRENT_TIMESTAMP gibberish. You can not add ON UPDATE CURRENT_TIMESTAMP to any columns OTHER than the one single TIMESTAMP in the table. Additionally, TIMESTAMP is not an epoch time. TIMESTAMP is a MySQL DATETIME that can have special behavior attached to it. Xref docs: http://dev.mysql.com/doc/refman/5.0/en/timestamp.html
Charles
@Charles, the page you linked to says "with a DEFAULT CURRENT_TIMESTAMP clause and no ON UPDATE clause, the column has the current timestamp for its default value but is not automatically updated", so your assertion that "the first [TIMESTAMP column] is always updated with the current time when the row is updated" is false.
Domster
Indeed, based on the current wording in the manual, my statement is not correct.
Charles
Thankyouthankyouthankyouthankyouthankyou
rlb.usa
it should be mentioned that the TIMESTAMP data type max value is set to '2038-01-19 03:14:07', so i really don't think this is an option. see also my answer i gave.
Fabian
+6  A: 

this is indeed terrible news.here is a long pending bug/feature request for this. that discussion also talks about the limitations of timestamp data type.

I am seriously wondering what is the issue with getting this thing implemented.

kinjal
A: 

alter table add DateTime default getdate()

That doesn't put in the time.
markwatson
that works on mssql server but the question is for mysql
marshall
+7  A: 

MySQL does not allow functions to be used for default DateTime values. TIMESTAMP is not suitable due to it's odd behavior and is not recommended for use as input data. (http://dev.mysql.com/doc/refman/5.0/en/data-type-defaults.html)

That said, you can accomplish this by creating a "Trigger" (samepath/trigger-syntax.html).

I have a table with a DateCreated field of type DateTime. I created a trigger on that table "Before Insert" and "SET NEW.DateCreated=NOW()" and it works great.

I hope this helps somebody.

Stephan Unrau
CREATE TRIGGER trigger_foo_SetCreatedAt BEFORE INSERT ON fooFOR EACH ROW SET NEW.created_at = UTC_TIMESTAMP();
Kurt
+2  A: 

I was able to solve this using this alter statement on my table that had two datetime fields.

ALTER TABLE `test_table`
  CHANGE COLUMN `created_dt` `created_dt` TIMESTAMP NOT NULL DEFAULT '0000-00-00 00:00:00',
  CHANGE COLUMN `updated_dt` `updated_dt` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;

This works as you would expect the now() function to work. Inserting nulls or ignoring the created_dt and updated_dt fields results in a perfect timestamp value in both fields. Any update to the row changes the updated_dt. If you insert records via the MySQL query browser you needed one more step, a trigger to handle the created_dt with a new timestamp.

CREATE TRIGGER trig_test_table_insert BEFORE INSERT ON `test_table`
    FOR EACH ROW SET NEW.created_dt = NOW();

The trigger can be whatever you want I just like the naming convention [trig]_[my_table_name]_[insert]

David Byrd
I meant to say, If you insert records via the MySQL query browser manually via the grid without an insert() statement the trigger is needed. If you always use an insert statement the trigger is completely unnecessary.
David Byrd
Whoops! I meant The trigger (name) can be whatever you want it to be because the trigger name doesn't affect the functionality at all. Most people will know that, but some folks new to MySQL might not know...
David Byrd
Here's what it looks like in a create table statement. create table `test` ( `created_dt` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', `updated_dt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `col3` varchar(255) DEFAULT NULL);INSERT INTO test VALUES (NULL,NULL,'test text1');INSERT INTO test VALUES (NULL,NULL,'test text2');UPDATE test SET col3='New value' where col3 = 'test text1';SELECT * FROM test;
David Byrd
Yikes, sorry about the lack of line breaks. Use the semi-colons to mark the end of each line.
David Byrd
A: 

MySQL 5.1.37-1ubuntu here.

CREATE TABLE `t1` (
  `updated_at` TIMESTAMP,
  `data` CHAR(255) DEFAULT
);

On record creation updated_at='0000-00-00' and on each update it changes to current datetime.

So I don't really care what documentation says, TIMESTAMP changes on each record update.

Unirgy
A: 

For all who use the TIMESTAMP column as a solution i want to second the following limitation from the manual:

http://dev.mysql.com/doc/refman/5.0/en/datetime.html

"The TIMESTAMP data type has a range of '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC. It has varying properties, depending on the MySQL version and the SQL mode the server is running in. These properties are described later in this section. "

So this will obviously break your software in about 28 years.

I believe the only solution on the database side is to use triggers like mentioned in other answers.

Fabian
A: 

You can reslove the defaul timestamp. First consider which character set you are using for example if u taken utf8 this character set support all languages and if u taken laten1 this charcter set support only for english. Next setp if you are working under any project you should know client time zone and select you are client zone. This step are mendatory.

Srinivas
DateTime columns cannot have default values. It's documented 'feature'. Not all developers have access to change their character encoding. And setting the server to it's _clients_ timezone is usually not a possibility, especially when clients are not all native to a single timezone area.
rlb.usa