Timestamp mysql ошибка

i am getting error in my database. i am encountering invalid default value for timestamp.

here’s my database:

CREATE TABLE IF NOT EXISTS `post` (
`id` int(11) NOT NULL,
  `text` varchar(10000) NOT NULL,
  `threadId` int(11) NOT NULL,
  `userId` int(11) NOT NULL,
  `dateCreated` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `timestamp` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `isModified` tinyint(4) NOT NULL DEFAULT '0'
) ENGINE=InnoDB AUTO_INCREMENT=171 DEFAULT CHARSET=latin1;



CREATE TABLE IF NOT EXISTS `category` (
`id` int(11) NOT NULL,
  `name` varchar(100) NOT NULL,
  `timestamp` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `color` varchar(10) DEFAULT '#00bcd4',
  `icon` varchar(100) NOT NULL DEFAULT 'https://mymonas.com/forum/category_icon/ic_question.png'
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=latin1;

Isaac Bennetch's user avatar

asked Apr 20, 2016 at 14:32

Denver Bautista's user avatar

5

I was having the same problem, I changed type from «datetime» to «timestamp» and It worked. I have mysql 5.5.52.

Mysql_error

answered Sep 23, 2016 at 19:40

Raul A.'s user avatar

Raul A.Raul A.

811 silver badge5 bronze badges

0

I have the same issue in sql_mode.

Make query:

show variables like 'sql_mode' ; 

You need to remove the «NO_ZERO_IN_DATE,NO_ZERO_DATE» from sql_mode.

SET sql_mode = '';

answered Oct 22, 2018 at 12:37

Max Sherbakov's user avatar

Use CURRENT_TIMESTAMP() instead CURRENT_TIMESTAMP

i.e.

CREATE TABLE IF NOT EXISTS `post` (
`id` int(11) NOT NULL,
  `text` varchar(10000) NOT NULL,
  `threadId` int(11) NOT NULL,
  `userId` int(11) NOT NULL,
  `dateCreated` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP(),
  `timestamp` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP() ON UPDATE CURRENT_TIMESTAMP(),
  `isModified` tinyint(4) NOT NULL DEFAULT '0'
) ENGINE=InnoDB AUTO_INCREMENT=171 DEFAULT CHARSET=latin1;

Now() works as well

answered Apr 20, 2016 at 14:37

Pavel Zimogorov's user avatar

8

From the MySQL 5.5 manual:

«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.»

The changes in MYSQL 5.6.x that allow the functionality are documented here:

«As of MySQL 5.6.5, TIMESTAMP and DATETIME columns can be automatically initializated and updated to the current date and time (that is, the current timestamp). Before 5.6.5, this is true only for TIMESTAMP, and for at most one TIMESTAMP column per table.»

So, this means you are using an older version of mysql, either you can use datetime data type of upgrade your mysql version

answered Feb 19, 2018 at 7:43

Krish's user avatar

KrishKrish

3792 silver badges8 bronze badges

Answered by @max Sherbakov worked but I think its risky,

if you execute SET sql_mode = ''; query.

Because if you or other users SET any different variables in sql_mode

like NO_ENGINE_SUBSTITUTION check other SQL MODES

by changing sql_mode values in my.ini file

OR

using SET sql_mode = 'YOUR_VARIABLE_LIST'; query

it worked for you current situation

but create problem in other projects.

  • To view current sql mode use following query

    show variables like 'sql_mode' ;

answered Mar 16, 2020 at 6:23

Satish's user avatar

SatishSatish

6961 gold badge11 silver badges22 bronze badges

i am getting error in my database. i am encountering invalid default value for timestamp.

here’s my database:

CREATE TABLE IF NOT EXISTS `post` (
`id` int(11) NOT NULL,
  `text` varchar(10000) NOT NULL,
  `threadId` int(11) NOT NULL,
  `userId` int(11) NOT NULL,
  `dateCreated` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `timestamp` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `isModified` tinyint(4) NOT NULL DEFAULT '0'
) ENGINE=InnoDB AUTO_INCREMENT=171 DEFAULT CHARSET=latin1;



CREATE TABLE IF NOT EXISTS `category` (
`id` int(11) NOT NULL,
  `name` varchar(100) NOT NULL,
  `timestamp` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `color` varchar(10) DEFAULT '#00bcd4',
  `icon` varchar(100) NOT NULL DEFAULT 'https://mymonas.com/forum/category_icon/ic_question.png'
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=latin1;

Isaac Bennetch's user avatar

asked Apr 20, 2016 at 14:32

Denver Bautista's user avatar

5

I was having the same problem, I changed type from «datetime» to «timestamp» and It worked. I have mysql 5.5.52.

Mysql_error

answered Sep 23, 2016 at 19:40

Raul A.'s user avatar

Raul A.Raul A.

811 silver badge5 bronze badges

0

I have the same issue in sql_mode.

Make query:

show variables like 'sql_mode' ; 

You need to remove the «NO_ZERO_IN_DATE,NO_ZERO_DATE» from sql_mode.

SET sql_mode = '';

answered Oct 22, 2018 at 12:37

Max Sherbakov's user avatar

Use CURRENT_TIMESTAMP() instead CURRENT_TIMESTAMP

i.e.

CREATE TABLE IF NOT EXISTS `post` (
`id` int(11) NOT NULL,
  `text` varchar(10000) NOT NULL,
  `threadId` int(11) NOT NULL,
  `userId` int(11) NOT NULL,
  `dateCreated` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP(),
  `timestamp` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP() ON UPDATE CURRENT_TIMESTAMP(),
  `isModified` tinyint(4) NOT NULL DEFAULT '0'
) ENGINE=InnoDB AUTO_INCREMENT=171 DEFAULT CHARSET=latin1;

Now() works as well

answered Apr 20, 2016 at 14:37

Pavel Zimogorov's user avatar

8

From the MySQL 5.5 manual:

«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.»

The changes in MYSQL 5.6.x that allow the functionality are documented here:

«As of MySQL 5.6.5, TIMESTAMP and DATETIME columns can be automatically initializated and updated to the current date and time (that is, the current timestamp). Before 5.6.5, this is true only for TIMESTAMP, and for at most one TIMESTAMP column per table.»

So, this means you are using an older version of mysql, either you can use datetime data type of upgrade your mysql version

answered Feb 19, 2018 at 7:43

Krish's user avatar

KrishKrish

3792 silver badges8 bronze badges

Answered by @max Sherbakov worked but I think its risky,

if you execute SET sql_mode = ''; query.

Because if you or other users SET any different variables in sql_mode

like NO_ENGINE_SUBSTITUTION check other SQL MODES

by changing sql_mode values in my.ini file

OR

using SET sql_mode = 'YOUR_VARIABLE_LIST'; query

it worked for you current situation

but create problem in other projects.

  • To view current sql mode use following query

    show variables like 'sql_mode' ;

answered Mar 16, 2020 at 6:23

Satish's user avatar

SatishSatish

6961 gold badge11 silver badges22 bronze badges

A friend’s application started failing with MySQL causing error about timestamp columns and it needs urgent fixing from the database side. A timestamp column was not accepting the null values and they were sort of down.

ERROR 1048 (23000): Column 'start_date' cannot be null

In this blog we will learn how MySQL is telling you, to follow what you say. When you define the column NOT NULL it means NOT NULL and (latest) MySQL is going to error if you don’t respect that.

Also, there’s golden bullet to solve any production problem like this towards the end of this blog: make sure to read through completely.

He shared the table definition with me and it looked pretty OK to me.

CREATE TABLE notnull (
id int NOT NULL AUTO_INCREMENT,
start_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
end_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id)
) ENGINE=InnoDB;

Testing timestamp behaviour in MySQL 5.7

I started my lab (Percona Server 5.7) and tested:

mysql> CREATE TABLE notnull ( id int NOT NULL AUTO_INCREMENT, start_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, end_date timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ;
Query OK, 0 rows affected (0.01 sec)

mysql> insert into notnull values (null, null, null);
Query OK, 1 row affected (0.00 sec)
mysql> select * from notnull;
+----+---------------------+---------------------+
| id | start_date | end_date |
+----+---------------------+---------------------+
| 1 | 2023-02-24 12:37:35 | 2023-02-24 12:37:35 |
+----+---------------------+---------------------+
1 row in set (0.00 sec)

It works! What’s the problem? I further asked his SQL_MODE and MySQL Version.

A workaround that wasn’t good

We also discussed further about this issue and one solution proposed was using a BEFORE TRIGGER. Since the timestamp value are inserted as NULL, we will provide a NON NULL value before the INSERT is actually processed.

CREATE TRIGGER start_date_trigger BEFORE INSERT ON notnull FOR EACH ROW SET NEW.start_date = CURRENT_TIMESTAMP;
CREATE TRIGGER end_date_trigger BEFORE INSERT ON notnull FOR EACH ROW SET NEW.end_date = CURRENT_TIMESTAMP;

MySQL [test]> insert into notnull values(null,null,null);
Query OK, 1 row affected (0.051 sec)

MySQL [test]> select * from notnull ;
| 29 | 2023-02-24 11:57:34 | 2023-02-24 11:57:35 |
| 30 | 2023-02-24 13:33:24 | 2023-02-24 13:33:24 |

But we both agreed, that it’s not a correct way.

Reproducing the error on MySQL 8

Anyways, he further confirmed that the Server version was 8.0.26 and SQL_MODE remained NO_ENGINE_SUBSTITUTION. So, I started MySQL 8 lab, and retried to produce the error and succeeded to generate a failure.

mysql [localhost:8028] {msandbox} (test) > insert into notnull values (null,null,null);
ERROR 1048 (23000): Column 'start_date' cannot be null

On MySQL 8 we see what’s the problem. One of the many changes that has been implemented in MySQL 8 (8.0.22+) is the alteration of the default value of explicit_defaults_for_timestamp from OFF to ON. This may seem like a small change, but it has significant implications for the way NOT NULL and default timestamps work.
The note says: As of MySQL 8.0.22, attempting to insert NULL into a generated column declared as TIMESTAMP NOT NULL is rejected with an error.

So the (temporary) solution to the problem here is to make the change and retain in config.

SET GLOBAL explicit_defaults_for_timestamp = OFF;

Explanation of the issue

Let’s understand a little more about explicit_defaults_for_timestamp. This system variable controls whether or not MySQL should use explicit DEFAULT expressions for timestamp columns that have no explicit DEFAULT value defined.

When explicit_defaults_for_timestamp is set to OFF, MySQL does not use explicit DEFAULT expressions for timestamp columns, and instead, it assigns a value of ‘0000-00-00 00:00:00’ if the column is defined as NOT NULL, or NULL if it’s defined as NULLABLE.

However, with the variable set to ON, MySQL uses explicit DEFAULT expressions for timestamp columns, even if they are not explicitly defined.

As of MySQL 8.0.22, attempting to insert NULL into a generated column declared as TIMESTAMP NOT NULL is rejected with an error.

mysql [localhost:8028] {msandbox} (test) > set explicit_defaults_for_timestamp=ON;
Query OK, 0 rows affected (0.00 sec)

mysql [localhost:8028] {msandbox} (test) > insert into notnull values (2,null,null);
ERROR 1048 (23000): Column 'start_date' cannot be null

But when we turn this variable OFF:

mysql [localhost:8028] {msandbox} (test) > set explicit_defaults_for_timestamp=OFF;
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql [localhost:8028] {msandbox} (test) > show warnings;
+---------+------+------------------------------------------------------------------------------------------+
| Level | Code | Message |
+---------+------+------------------------------------------------------------------------------------------+
| Warning | 1287 | 'explicit_defaults_for_timestamp' is deprecated and will be removed in a future release. |
+---------+------+------------------------------------------------------------------------------------------+

mysql [localhost:8028] {msandbox} (test) > insert into notnull values (3,null,null);
Query OK, 1 row affected (0.00 sec)

mysql [localhost:8028] {msandbox} (test) > select * from notnull;
+----+---------------------+---------------------+
| id | start_date | end_date |
+----+---------------------+---------------------+
| 1 | 2023-03-19 19:16:01 | 2023-03-19 19:16:01 |
| 3 | 2023-03-19 19:18:12 | 2023-03-19 19:18:12 |
+----+---------------------+---------------------+

I hope you did not miss the WARNING above “explicit_defaults_for_timestamp’ is deprecated and will be removed in a future release.”.

Also, not providing the column names should allow it to pick up the defaults.

mysql [localhost:8028] {msandbox} (test) > insert into notnull(id) values (null);
Query OK, 1 row affected (0.00 sec)

mysql [localhost:8028] {msandbox} (test) > select * from notnull;
+----+---------------------+---------------------+
| id | start_date | end_date |
+----+---------------------+---------------------+
| 1 | 2023-03-19 19:16:01 | 2023-03-19 19:16:01 |
| 3 | 2023-03-19 19:18:12 | 2023-03-19 19:18:12 |
| 4 | 2023-03-19 19:20:20 | 2023-03-19 19:20:20 |
+----+---------------------+---------------------+
3 rows in set (0.00 sec)

Conclusion

Well, the issue was solved for my friend by setting explicit_defaults_for_timestamp OFF but remember that this MySQL variable is going away. So respect your definition – NOT NULL means NOT NULL.

Refer the MySQL worklog for detail information and high level architecture for the fixture.

Okay so for those who believed in golden bullet, :faceplam: , but I surely have a secret pro-tip.

How did this issue start? My friend confirmed that they did a MySQL Migration. They migrated from MariaDB to MySQL 8, on a Friday! Without testing! If you can’t believe that a day is Friday, use any of the methods used here to prove a Friday and act accordingly.

ProTip: Never, I repeat, Never do any production change on a Friday, your engineers will love you.

При создании таблицы вот такой строкой:

`begin_date` timestamp NOT NULL DEFAULT '1975-01-01 00:00:00',

вываливается ошибка «Incorrect datetime value»
А если поменять дату на, например:
1975-01-01 01:00:00
или
1974-01-01 00:00:00
или
1975-01-02 00:00:00
ошибка уже не вылезает и таблица успешно создается.
Почему MySQL не устраивает дата из изначального запроса?


  • Вопрос задан

  • 2822 просмотра

Пригласить эксперта

`begin_date` datetime NOT NULL DEFAULT ‘1975-01-01 00:00:00’,
И первый раз вижу что хранят именно ‘1975-01-01 00:00:00’ а не 000-00-00 00:00:00
И при создании таблицы необязательно писать DEFAULT ‘1975-01-01 00:00:00’,
Достаточно написать `begin_date` datetime NOT NULL

The TIMESTAMP data type is used for values that contain both date and time parts. TIMESTAMP has a range of ‘1970-01-01 00:00:01’ UTC to ‘2038-01-19 03:14:07’ UTC.

То есть, если установлен часовой пояс UTC+00:00, то локальное время ‘1970-01-01 00:00:00’ будет некорректным.


  • Показать ещё
    Загружается…

21 сент. 2023, в 20:54

10000 руб./за проект

21 сент. 2023, в 20:40

20000 руб./за проект

21 сент. 2023, в 20:29

2000 руб./за проект

Минуточку внимания

Running MySQL 5.5, got the error above when I tried to import a .sql file

I’ve checked the SQL_MODE of my server and nothing similar to ‘NO_ZERO_DATE’ is found

As well, I’ve took out the text of ‘STRICT_MODE’ from my my.ini file and restarted the server, yet this error still persists

Here’s the .sql file being imported

CREATE TABLE  `street_segment` (
  `ID` int(8) NOT NULL,
  `PROVINCE_CODE` varchar(2) NOT NULL,
  `POSTAL_CODE` varchar(6) NOT NULL,
  `MUNICIPALITY_NAME` varchar(30) default NULL,
  `STATUS` varchar(16) NOT NULL,
  `LAST_UPDATED` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `DIRECTORY_AREA_NAME` varchar(30) default NULL,
  `STREET_NAME` varchar(255) default NULL,
  `STREET_TYPE_CODE` varchar(6) default NULL,
  `STREET_DIRECTION_CODE` varchar(2) default NULL,
  `ADDRESS_SEQ_CODE` int(8) default NULL,
  `STREET_ADDRESS_FROM_NUMBER` varchar(6) default NULL,
  `STREET_ADDRESS_TO_NUMBER` varchar(6) default NULL,
  `NUMBER_SUFFIX_FROM` varchar(6) default NULL,
  `NUMBER_SUFFIX_TO` varchar(6) default NULL,
  `SUITE_NUMBER_FROM` varchar(6) default NULL,
  `SUITE_NUMBER_TO` varchar(6) default NULL,
  `STREET_NAME_ACCENT_F` int(1) default 0,
  PRIMARY KEY  (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Понравилась статья? Поделить с друзьями:
  • Tlauncher ошибка unable to open archive file
  • Timer мигает 6 раз произошла ошибка передачи сигнала
  • Tlauncher ошибка java virtual machine launcher
  • Timeout ошибка http
  • Tlauncher ошибка fabric