text型のカラムを明示的にINSETRTしなかったときのNULL値の挙動

後輩に訊かれてどうだったっけ?と思って調べたので、まとめておく。

まとめ

  • text型でINSERT時に明示的に情報を入れない場合、カラムがNOT NULLであったときは、""が入る。NOT NULLでない場合はNULLが入る。

作業ログ

# not null制約をつけている場合
mysql> create table fuga ( id int unsigned not null AUTO_INCREMENT primary key, text text not null ) Engine=InnoDB;
Query OK, 0 rows affected (0.13 sec)

mysql> insert into fuga () values ();
Query OK, 1 row affected, 1 warning (0.06 sec)

mysql> select * from fuga;
+----+------+
| id | text |
+----+------+
|  1 |      |
+----+------+
1 row in set (0.00 sec)

mysql> select @@version;
+-----------+
| @@version |
+-----------+
| 5.1.58    |
+-----------+
1 row in set (0.02 sec)

# not null制約をつけなかった場合
mysql> create table foo ( id int unsigned not null AUTO_INCREMENT primary key, text text );                                                                                                               

Query OK, 0 rows affected (1.28 sec)

mysql> insert into foo () values ();                                                                                                                                                                      
Query OK, 1 row affected (0.02 sec)

mysql> select * from foo;
+----+------+
| id | text |
+----+------+
|  1 | NULL |
+----+------+
1 row in set (0.00 sec)

mysql> 
mysql> select * from foo;
+----+------+
| id | text |
+----+------+
|  1 | NULL |
+----+------+
1 row in set (0.00 sec)