SQLite | データ検索 | LIKEによるパターンマッチ
LIKEは%と_を使って文字列パターンを照合する。
| 文字 | 意味 |
|---|---|
% |
任意の0文字以上 |
_ |
任意の1文字 |
a%bはabやaoneb、T%はTで始まる文字列、a_bはaxbに一致する。SQLiteのLIKEは通常、ASCII文字の大文字と小文字を区別しない。
create table user (id integer, name text, address text);
insert into user values (1, 'devkuma', 'Seoul');
insert into user values (2, 'kimkc', 'Busan');
insert into user values (3, 'araikuma', 'Paju');
insert into user values (4, 'happykuma', 'Paju');
insert into user values (5, 'mykuma', 'Daejeon');
insert into user values (6, 'yourkuma', 'Seongnam');
insert into user values (7, 'raccoon', 'Suwon');
select * from user where address like 'S%';
select * from user where address like '%e%e%';
select * from user where name like '_______';
select * from user where name not like '_______';
順にSで始まる住所、eを2つ含む住所、7文字の名前、7文字ではない名前を検索する。
特殊文字のエスケープ
%や_を文字として扱う場合はESCAPEを使う。
create table foods (id integer, name text);
insert into foods values (1, 'Water');
insert into foods values (2, 'Apple_Pie');
insert into foods values (3, 'Black_Coffee');
insert into foods values (4, 'Pizza');
insert into foods values (5, 'Sandwich');
insert into foods values (6, 'French_Bread');
select * from foods where name like '%$_%' escape '$';
$をエスケープ文字とし、リテラルのアンダースコアを含む3行を返す。