13
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

BigQueryでLIKE文の複数条件指定をORから正規表現に直す

Posted at

概要

BigQueryでLIKE文の複数条件指定をORから正規表現に置き換えます。

事の発端

IN演算子のLIKE版はありませんか?という質問を受けたので調べました。

Address IN ('東京', '新潟', '香川')

素直にORを使えば良いと思いますが、正規表現があるよ!
というアンサーはイマイチな気もしています。
※ORと正規表現でどれくらい抽出速度が変わるのか?までは調べられておりません

SQL

ORで書く場合

SELECT * FROM
(
  SELECT '東京都XXX' AS Address
  UNION ALL
  SELECT '神奈川県XXX' AS Address
  UNION ALL
  SELECT '新潟県XXX' AS Address
  UNION ALL
  SELECT '香川県XXX' AS Address
)
WHERE
  Address LIKE '東京%'
  OR Address LIKE '新潟%'
  OR Address LIKE '香川%'

正規表現で書く場合

BigQueryで正規表現を書くとき REGEXP_CONTAINS が使えます。

REGEXP_CONTAINS(value, regexp)
説明
value が正規表現 regexp に対して部分一致である場合、TRUE を返します。
regexp の引数が無効な場合は、関数はエラーを返します。

公式ドキュメントより引用
https://cloud.google.com/bigquery/docs/reference/standard-sql/functions-and-operators?hl=ja#regexp_contains

SELECT * FROM
(
  SELECT '東京都XXX' AS Address
  UNION ALL
  SELECT '神奈川県XXX' AS Address
  UNION ALL
  SELECT '新潟県XXX' AS Address
  UNION ALL
  SELECT '香川県XXX' AS Address
)
WHERE
  REGEXP_CONTAINS(Address, r'^(東京|新潟|香川)')
13
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?