This topic describes how to perform simple primary key operations, including adding a primary key, modifying a primary key, and dropping a primary key.
Add a primary key
The syntax for adding a primary key is as follows:
ALTER TABLE table_name ADD PRIMARY KEY (column_name);
Here, table_name specifies the name of the table to which a primary key is to be added; column_name specifies the column that will serve as the primary key. For more information, see ALTER TABLE.
Assume that a table named tbl1 already exists in the database. Add a primary key index to the tbl1 table and apply this index to column c1. The execution example is as follows:
obclient> ALTER TABLE tbl1 ADD PRIMARY KEY(c1);
Modify primary key
The syntax for modifying the primary key is as follows:
ALTER TABLE table_name DROP PRIMARY KEY, ADD PRIMARY KEY (column_name);
Here, table_name specifies the name of the table whose primary key is to be modified; column_name specifies the column that will become the new primary key. For more information, see ALTER TABLE.
Assume that the table tbl1 already exists in the database and has a primary key. Modify the primary key in the tbl1 table to apply it to column c2. The execution example is as follows:
obclient> ALTER TABLE tbl1 DROP PRIMARY KEY, ADD PRIMARY KEY(c2);
Delete primary key
The syntax for dropping a primary key is as follows:
ALTER TABLE table_name DROP PRIMARY KEY;
Here, table_name specifies the name of the table from which the primary key is to be dropped. For more information, see ALTER TABLE.
This example assumes that a table named tbl1 exists in the database and that tbl1 has a primary key. The primary key of tbl1 is dropped. Example:
obclient> ALTER TABLE tbl1 DROP PRIMARY KEY;