TIL

Today I Learned. 知ったこと、学んだことを書いていく

【MySQL】MySQLでのBooleanの扱い

Mysqlのboolean型について調べてみた - Qiita の内容を自分の手で確かめてみた

環境

> docker-compose exec mysql mysql --version
mysql  Ver 8.0.16 for Linux on x86_64 (MySQL Community Server - GPL)

まとめ

  • booleantinyint(1)のどちらともtinyint(1)で CREATE TABLE される
  • true1false0で INSERT される
  • 値の比較は=isで変わる
    • where col = true1のデータ、where col = false0のデータ(想定通り)
    • where col is true0以外のデータ、where col is false0のデータ(想定と違う)

CREATE

booleanとtinyint(1)のテーブルを作成し、全く同じデータを入れてみた

> create table test_boolean (bool_col boolean);
> create table test_tinyint (bool_col tinyint(1));

booleantinyint(1)のどちらともtinyint(1)でカラムが作成される

> show create table test_boolean;
+--------------+--------------------------------------+
| Table        | Create Table                         |
+--------------+--------------------------------------+
| test_boolean | CREATE TABLE `test_boolean` (        |
|              |   `bool_col` tinyint(1) DEFAULT NULL |
|              | ) ENGINE=InnoDB DEFAULT CHARSET=utf8 |
+--------------+--------------------------------------+

> show create table test_tinyint;
+--------------+--------------------------------------+
| Table        | Create Table                         |
+--------------+--------------------------------------+
| test_tinyint | CREATE TABLE `test_tinyint` (        |
|              |   `bool_col` tinyint(1) DEFAULT NULL |
|              | ) ENGINE=InnoDB DEFAULT CHARSET=utf8 |
+--------------+--------------------------------------+

INSERT

falseをINSERTすると0

> insert into test_boolean values (false);
> select * from test_boolean;
+----------+
| bool_col |
+----------+
| 0        |
+----------+

trueをINSERTすると1

> truncate test_boolean;
> insert into test_boolean values (true);
> select * from test_boolean;
+----------+
| bool_col |
+----------+
| 1        |
+----------+

WHERE

  • where col = true1のデータ、where col = false0のデータが抽出できる
  • where col is true0以外のデータ、where col is false0のデータが抽出できる
    • これ知ってないとハマりそう。でも、基本、isじゃなくて、=で比較すればいいのかも?

以下のようなデータを用意

> insert into test_tinyint values (false), (true), (1), (0), (100), (-100);
> select * from test_tinyint;
+----------+
| bool_col |
+----------+
| 0        |
| 1        |
| 1        |
| 0        |
| 100      |
| -100     |
+----------+

=を使った抽出

> select * from test_tinyint where bool_col = true;
+----------+
| bool_col |
+----------+
| 1        |
| 1        |
+----------+

> select * from test_tinyint where bool_col = false;
+----------+
| bool_col |
+----------+
| 0        |
| 0        |
+----------+

isを使った抽出

> select * from test_tinyint where bool_col is true;
+----------+
| bool_col |
+----------+
| 1        |
| 1        |
| 100      |
| -100     |
+----------+

> select * from test_tinyint where bool_col is false;
+----------+
| bool_col |
+----------+
| 0        |
| 0        |
+----------+

参考文献