0
1

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 1 year has passed since last update.

PostgreSQLで文字数と正規表現をまとめてCHECKする

Last updated at Posted at 2023-02-27

はじめに

初歩的ですが、いざやろうとするとパッと思い出せないとき用のメモ書きです。

ポイント

  • 文字列の長さはlength()
  • 正規表現に一致するかを比較する演算子は~(チルダ)
  • 文字数の制約はm文字以上、n文字以下で設定

SQL文

以下は英数字と@ . _からなる1~255文字の文字列という制約をかける場合です。

  CREATE FUNCTION check_str(str text, min int , max int) RETURNS boolean AS $$
    SELECT str ~ concat('^[0-9a-zA-Z@_.]{', min, ',', max, '}$') AS result; 
  $$ LANGUAGE SQL;

  CREATE TABLE users (
    username text PRIMARY KEY CHECK(check_str(username, 1, 255)),
  )
0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?