3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Field 'created_at' doesn't have a default value解決方法

Last updated at Posted at 2021-09-25

#はじめに
MySQLで下記のテーブルにinsertを実行した際に
「Field 'created_at' doesn't have a default value」とエラーが発生した。

mysql> describe tables;
+------------+--------------+------+-----+---------+----------------+
| Field      | Type         | Null | Key | Default | Extra          |
+------------+--------------+------+-----+---------+----------------+
| id         | bigint       | NO   | PRI | NULL    | auto_increment |
| name       | varchar(255) | NO   |     | NULL    |                |
| created_at | datetime(6)  | NO   |     | NULL    |                |
| updated_at | datetime(6)  | NO   |     | NULL    |                |
+------------+--------------+------+-----+---------+----------------+
```

```
mysql> Insert into tables (name) values ('hoge');
ERROR 1364 (HY000): Field 'created_at' doesn't have a default value
```

#解決方法
「created_at」と「updated_at」にもinsertするようSQLを修正

```
Insert into tables (name, created_at, updated_at) values ('hoge', now(), now());
```
#まとめ
「created_at」と「updated_at」の「default」にNULLが設定されているため、insert時に省略すると、NULLを設定しようとする。しかし、2カラムともNULLは許可されていないため、エラーが発生する。
以降、テーブル新規作成する際は、「created_at」や「updated_at」には「now()」などのdefault設定をするよう心がける。

#参考
https://tackeyy.com/blog/posts/how-to-set-current-timestamp-to-datetime-columns

3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?