Sql ошибка 1067 invalid default value for

The question is too broad for the answer. There are many problems regarding these questions, even more so when the incompatibility of the different MySQL-based engines is notorious.
For me the best option is to know the state of variables at the time of making the backup with the option —opt (mysqldump —opt) and apply it to our backup if it does not have it as usual, either because the original backup I did not have it, or because the one that has happened to us is incorrect.

If the backup does not contain the settings with which it was made, we will have to start investigating, but basically we can do it like this.

Add SETtings to header of backup

echo '
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!50503 SET NAMES utf8mb4 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!50606 SET @OLD_INNODB_STATS_AUTO_RECALC=@@INNODB_STATS_AUTO_RECALC */;
/*!50606 SET GLOBAL INNODB_STATS_AUTO_RECALC=OFF */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;' | cat - mybackup.sql > temp && mv temp  mybackup.sql 

Add restore SETtings to end

/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!50606 SET GLOBAL INNODB_STATS_AUTO_RECALC=@OLD_INNODB_STATS_AUTO_RECALC */;

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;' >> mybackup.sql 

If you don’t have those settings you can make a mysqldump backup with the —opt option on the original server, in order to get them.

If you don’t have it, you can go little by little, setting the necessary settings, both at the start and at the exit.

You may have noticed that date columns’ default dates in legacy systems are 0000-00-00. The data cannot be changed, therefore you’ll have to accept it. But in the current versions, particularly on AWS RDS, you’ll get the following problem when you attempt to create a table with the same default value (i.e. 0000-00-00).

> 1067 – Invalid default value for ‘DateColumn’
> Time: 0.001s

Prior to version 5.6, MySQL accepted the default date of 0000-00-00, but now it accepts dates in the range of 1000-01-01 to 9999-12-31. Although MySQL allows either strings or numbers to be assigned as values to DATE columns, it displays date data in the ‘YYYY-MM-DD’ format.

In a similar vein, the permitted range for date-time data type is “1000-01-01 00:00:00.000000” to “9999-12-31 23:59:59.999999”.

The time zone range for a timestamp is from “1970-01-01 00:00:01.000000” to “2038-01-19 03:14:07.999999” UTC.

Let’s reproduce the error:

DROP TABLE IF EXISTS tbEmp;

CREATE TABLE `tbEmp` (
`employeeId` int NOT NULL DEFAULT ‘0’,
`firstname` varchar(100) DEFAULT NULL,
`middleName` varchar(100) DEFAULT NULL,
`lastName` varchar(100) DEFAULT NULL,
`businessPhone` varchar(100) DEFAULT NULL,
`businessEmail` varchar(228) DEFAULT NULL,
`JoinDate` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`EOSDate` datetime NOT NULL DEFAULT ‘0000-00-00’
) ENGINE=InnoDB;

> 1067 – Invalid default value for ‘EOSDate’
> Time: 0.001s

Solution:
The SQL mode that enforces the guidelines for transactional tables is the root of the problem. The server’s ability to accept the date ‘0000-00-00’ depends on the strict mode setting. The character ‘0000-00-00’ is allowed and inserts do not trigger a warning if strict mode is not activated. If strict mode is set, the characters “0000-00-00” are not allowed, and insertion fail unless IGNORE is also specified. ‘0000-00-00’ is allowed for the INSERT IGNORE and UPDATE IGNORE commands, and inserts result in a warning.

DROP TABLE IF EXISTS tbEmp;

SET sql_mode = ”;

CREATE TABLE `tbEmp` (
`employeeId` int NOT NULL DEFAULT ‘0’,
`firstname` varchar(100) DEFAULT NULL,
`middleName` varchar(100) DEFAULT NULL,
`lastName` varchar(100) DEFAULT NULL,
`businessPhone` varchar(100) DEFAULT NULL,
`businessEmail` varchar(228) DEFAULT NULL,
`JoinDate` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`EOSDate` datetime NOT NULL DEFAULT ‘0000-00-00’
) ENGINE=InnoDB;

This will succeed.


При редактировании БД столкнулся с ошибкой:

#1067 — Некорректное значение по умолчанию для ‘post_date’
#1067 — Invalid default value

дефолтное значение стояло

0000-00-00 00:00:00

база выдает ошибку т.к. данная дата не валидна потому, что она не находится в допустимом диапазоне
1970-01-01 00:00:01 — 2038-01-19 03:14:07

Но даже при запросе смены дефолтного значения на NULL:

ALTER TABLE `wp_comments` CHANGE `comment_date` `comment_date` DATETIME NULL DEFAULT NULL;

база выдавала ошибку т.к. были другие столбцы в таблице с неверным значением.

Решение

Пришлось править конфиг mySQL, чтобы разрешить работу с некорректным значением по-умолчанию:

[mysqld]
sql-mode=NO_ENGINE_SUBSTITUTION

перезапустить БД, после этого поменять значения на NULL или валидные, затем вернуть конфиг обратно.

The post_date default value is 0000-00-00 00:00:00. If you check the sql_mode variable like this:

show variables like 'sql_mode'; 

… it will show you the sql_mode variable, that will be sth like this: ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION

You have to set up again sql_mode variable without
NO_ZERO_IN_DATE,NO_ZERO_DATE

So in the previous example you should set the sql_mode like this:

SET sql_mode = 'ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';

Then check the sql_mode variable again to be sure it has changed correctly:

show variables like 'sql_mode';

Then the restriction is gone ;D

Found the solution here: https://stackoverflow.com/a/37696251/504910

The ERROR 1067 (42000): Invalid default value for ‘created_at’ is a common error encountered in MySQL. This error occurs when the user tries to create a table with a default value for the column that is not acceptable to the database system. The default value for the column can either be a constant, a function or an expression, but if it is not in the correct format, MySQL will return this error. This error can be resolved by understanding the root cause and applying the appropriate solution.

Method 1: Correct the Default Value

To fix the ERROR 1067 (42000): Invalid default value for 'created_at' error in MySQL, you can correct the default value of the created_at field.

First, you need to check the data type of the created_at field. It should be set to TIMESTAMP or DATETIME.

Then, you can set the default value of the created_at field to CURRENT_TIMESTAMP using the DEFAULT keyword.

Here is an example SQL query to correct the default value of the created_at field:

ALTER TABLE `table_name` 
CHANGE COLUMN `created_at` `created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP;

This query will change the created_at field to a TIMESTAMP data type, set it to NOT NULL, and set the default value to CURRENT_TIMESTAMP.

Note that this query assumes that the table_name and created_at field names are correct. You should replace them with the actual names used in your database.

Method 2: Disable Strict Mode

To fix the «Mysql: how to fix ERROR 1067 (42000): Invalid default value for ‘created_at’?» error with «Disable Strict Mode», follow these steps:

  1. Open the my.cnf file using your favorite editor. For example:

    sudo nano /etc/mysql/my.cnf
  2. Add the following line under the [mysqld] section:

    sql_mode=NO_ENGINE_SUBSTITUTION
  3. Save and close the file.

  4. Restart MySQL server.

    sudo service mysql restart
  5. Connect to MySQL server and run the following command to disable strict mode:

    SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));
  6. Now, you can create a table with a default value for ‘created_at’ column without any error. For example:

    CREATE TABLE example (
        id INT(11) NOT NULL AUTO_INCREMENT,
        name VARCHAR(255) NOT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (id)
    );

    This will create a table with three columns: id, name, and created_at. The created_at column will have a default value of the current timestamp.

  7. Insert a row into the table without specifying a value for the created_at column:

    INSERT INTO example (name) VALUES ('John');

    This will insert a row into the table with the name ‘John’ and the current timestamp as the value for the created_at column.

That’s it! You have successfully fixed the «Mysql: how to fix ERROR 1067 (42000): Invalid default value for ‘created_at’?» error with «Disable Strict Mode».

Method 3: Update MySQL Version

To fix the «Invalid default value for ‘created_at'» error in MySQL, you can update the MySQL version. Here are the steps to follow:

  1. Check the current version of MySQL by running the following command:

  2. Download the latest version of MySQL from the official website.

  3. Stop the MySQL server by running the following command:

  4. Uninstall the current version of MySQL by running the following command:

    sudo apt-get remove mysql-server
  5. Install the new version of MySQL by running the following command:

    sudo dpkg -i mysql-apt-config_0.8.13-1_all.deb
    sudo apt-get update
    sudo apt-get install mysql-server
  6. Start the MySQL server by running the following command:

  7. Open the MySQL command line by running the following command:

  8. Select the database that you want to fix by running the following command:

  9. Alter the table that is causing the error by running the following command:

    ALTER TABLE your_table_name
    MODIFY COLUMN created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP;
  10. Exit the MySQL command line by running the following command:

That’s it! You have successfully fixed the «Invalid default value for ‘created_at'» error in MySQL by updating the MySQL version.

Понравилась статья? Поделить с друзьями:
  • Sql ошибка 104
  • Sql отправка писем при ошибок создания резервной копии
  • Sql откат транзакции при ошибке
  • Sql обработчик ошибок
  • Spore ошибка запуска