「MySQL 8.0.29」ALTER TABLE文を使ってUNIQUEインデックスを作成する

環境
Ubuntu 22.04 LTS
MySQL 8.0.29-0ubuntu0.22.04.2

書式
ALTER TABLE テーブル名 ADD UNIQUE INDEX [インデックス名] (カラム名, …)
対象となるテーブル名とカラム名および インデックス名を指定してインデックスを作成します。

UNIQUE インデックスを作成する手順
1.テーブルを作成します

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
mysql> create table emtbl(eid int, ename varchar(20));
Query OK, 0 rows affected (1.62 sec)
mysql> create table emtbl(eid int, ename varchar(20)); Query OK, 0 rows affected (1.62 sec)
mysql> create table emtbl(eid int, ename varchar(20));
Query OK, 0 rows affected (1.62 sec)

2.作成したテーブルのeid カラムを対象に UNIQUE インデックスを作成します

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
mysql> alter table emtbl add unique index eid_index (eid);
Query OK, 0 rows affected (0.95 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> alter table emtbl add unique index eid_index (eid); Query OK, 0 rows affected (0.95 sec) Records: 0 Duplicates: 0 Warnings: 0
mysql> alter table emtbl add unique index eid_index (eid);
Query OK, 0 rows affected (0.95 sec)
Records: 0  Duplicates: 0  Warnings: 0

3.作成されたインデックスを確認します

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
mysql> show index from emtbl\G
*************************** 1. row ***************************
Table: emtbl
Non_unique: 0
Key_name: eid_index
Seq_in_index: 1
Column_name: eid
Collation: A
Cardinality: 0
Sub_part: NULL
Packed: NULL
Null: YES
Index_type: BTREE
Comment:
Index_comment:
Visible: YES
Expression: NULL
1 row in set (0.26 sec)
mysql> show index from emtbl\G *************************** 1. row *************************** Table: emtbl Non_unique: 0 Key_name: eid_index Seq_in_index: 1 Column_name: eid Collation: A Cardinality: 0 Sub_part: NULL Packed: NULL Null: YES Index_type: BTREE Comment: Index_comment: Visible: YES Expression: NULL 1 row in set (0.26 sec)
mysql> show index from emtbl\G
*************************** 1. row ***************************
        Table: emtbl
   Non_unique: 0
     Key_name: eid_index
 Seq_in_index: 1
  Column_name: eid
    Collation: A
  Cardinality: 0
     Sub_part: NULL
       Packed: NULL
         Null: YES
   Index_type: BTREE
      Comment:
Index_comment:
      Visible: YES
   Expression: NULL
1 row in set (0.26 sec)

 

MySQL

Posted by arkgame