Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting default value for DATE type column to current date without time part?

NOTE: The question is about DATE type, not Datetime or 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() ...

like image 620
Dmitrij Kultasev Avatar asked Mar 02 '15 08:03

Dmitrij Kultasev


People also ask

Can we set a default value of integer for a table column of data type DateTime?

Explicit Default Handling Prior to MySQL 8.0. 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, for TIMESTAMP and DATETIME columns, you can specify CURRENT_TIMESTAMP as the default.

What should be the default value for date in MySQL?

MySQL retrieves and displays DATE values in 'YYYY-MM-DD' format. The supported range is '1000-01-01' to '9999-12-31'.


1 Answers

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

like image 71
1000111 Avatar answered Sep 25 '22 23:09

1000111