dak ブログ

python、rubyなどのプログラミング、MySQL、サーバーの設定などの備忘録。レゴの写真も。

MySQL の check 制約

2024-03-08 09:41:00 | mysql
MySQL の check によるデータの制約を確認します。
以下は test_check_01 テーブルで、num が 1 <= num <= 10、str の文字列長 <= 5 の制約を設定しています。

■テーブル定義・データ登録
create table test_check_01 (
  id        varchar(32) not null,
  num       integer not null,
  str       varchar(8),

  primary key(id),
  check(num &gt;= 1 and num &lt;= 10),
  check(char_length(str) &lt;= 5)
);

insert into test_check_01 (id, num, str) values ('id_1', 1, 'abc');
insert into test_check_01 (id, num, str) values ('id_2', 2, 'def');
insert into test_check_01 (id, num, str) values ('id_3', 3, 'ghi');

■check の条件の確認
mysql&gt; select * from test_check_01;
+------+-----+------+
| id   | num | str  |
+------+-----+------+
| id_1 |   1 | abc  |
| id_2 |   2 | def  |
| id_3 |   3 | ghi  |
+------+-----+------+

mysql&gt; update test_check_01 set num = num * 4;;
ERROR 3819 (HY000): Check constraint 'test_check_01_chk_1' is violated.

mysql&gt; select * from test_check_01;
+------+-----+------+
| id   | num | str  |
+------+-----+------+
| id_1 |   1 | abc  |
| id_2 |   2 | def  |
| id_3 |   3 | ghi  |
+------+-----+------+

mysql&gt; update test_check_01 set str = concat(str, '___');
ERROR 3819 (HY000): Check constraint 'test_check_01_chk_2' is violated.

mysql&gt; select * from test_check_01;
+------+-----+------+
| id   | num | str  |
+------+-----+------+
| id_1 |   1 | abc  |
| id_2 |   2 | def  |
| id_3 |   3 | ghi  |
+------+-----+------+
3 rows in set (0.00 sec)


この記事についてブログを書く
« Elasticsearch で nested フ... | トップ | TypeScript で elastic cloud... »

mysql」カテゴリの最新記事