2020年3月13日金曜日

SQLite 3 insert時にキーが重複していたら無視する (insert or ignore)

概要

insert or ignore構文を使う方法のメモ

insert or ignoreを使うと Primary keyUniqueで 重複するレコードを挿入しようとした場合、以下のような処理分岐をしてくれる。

重複するレコードがある場合 何もしない
重複するレコードがない場合 そのまま「新規挿入(insert)」

環境

  • Windows 10
  • sqlite3 (3.30.0) Command-Line Shell

実行例

サンプルテーブル(product)
id
primary key
autoincrement
name
not null
quantity
default 0
remark
1 tomato 100
2 potato 120
3 pumpkin 50 (Comment...)

キーの重複が無ければ、そのまま新規挿入される


insert or ignore into product
    ( id  ,name     ,quantity ,remark )
values
    ( 4   ,'carrot' ,30       ,''     )
;
                    
結果
id
primary key
autoincrement
name
not null
quantity
default 0
remark
1 tomato 100
2 potato 120
3 pumpkin 50 (Comment...)
4 carrot 30

キーの重複があった場合、新規挿入されず無視される


insert or ignore into product
    ( id ,name     ,quantity ,remark )
values
    ( 3  ,'carrot' ,30       ,''     )
;
                
結果
id
primary key
autoincrement
name
not null
quantity
default 0
remark
1 tomato 100
2 potato 120
3 pumpkin 50 (Comment...)

ignore文にしなかった場合、エラーになる


insert into product
    ( id ,name     ,quantity ,remark )
values
    ( 3  ,'carrot' ,30       ,''     )
;

Error: table product has no column named id
                

複数データを追加する場合、キーの重複が無いデータだけ登録される


insert or ignore into product
      ( id ,name      ,quantity ,remark )
values
      ( 3  ,'carrot'  , 30      ,''     )
    , ( 4  ,'apple'   , 40      ,''     )
    , ( 5  ,'spinach' ,130      ,''     )
;
                    
結果
id
primary key
autoincrement
name
not null
quantity
default 0
remark
1 tomato 100
2 potato 120
3 pumpkin 50 (Comment...)
4 apple 40
5 spinach 130

参考・関連 URL