sqlite3のデータ型について

いくつか驚いたことがあったので忘れないようにメモ。

結論

  • create文で存在しないデータ型を指定してもエラーにならない
  • integer型のカラムに数字に出来そうにない文字列(e.g. sqlite)をぶち込んでもエラーにならない(text型で格納される)
  • データ型は「その型しか入らない」ではなく、「その型に変換できないかがんばる」ためのものと捉えた方がいい

実験

まずは、 integer型のidと、text型のnameというフィールドを持つテーブルを試す。

sqlite> create table texttype (id integer, name text);
sqlite> insert into texttype values (1, 'alice');
sqlite> insert into texttype values ('2', 'bob');
sqlite> insert into texttype values ('c', 'cindy');
sqlite> insert into texttype values (2.5, 1234);
sqlite> select id, typeof(id), name, typeof(name) from texttype;
1|integer|alice|text
2|integer|bob|text
c|text|cindy|text
2.5|real|1234|text

integer型の場合
整数→integer
数字リテラル→integer (型変換)
非数字リテラル→text
小数→real

と、当たり前のように整数型以外が入った。
どうも、「型変換はがんばるが、無理ならそのまま入れる」みたいな作りらしい。

続いて、あり得ないデータ型(foo, bar)でつくってみる。

sqlite> create table othertype (id foo, name bar);
sqlite> insert into othertype values (1, 'alice');
sqlite> insert into othertype values ('2', 'bob');
sqlite> insert into othertype values ('c', 'cindy');
sqlite> insert into othertype values (2.5, 1234);
sqlite> select id, typeof(id), name, typeof(name) from othertype;
1|integer|alice|text
2|integer|bob|text
c|text|cindy|text
2.5|real|1234|integer

型変換なしで何でも入る模様。

これだと

create table jiro (yasai mashimashi, ninniku Chomolungma, choi karame )

とか出来ちゃうってことか。。。


んー。DBのデータ型って意識したことなかったけど、こんなものなのか・・・


他のDBMSも調べてみよう。