Add Composite Primary Key in DB2: Quick Guide
To add a composite primary key in DB2, you can follow these steps:
First, make sure the table already exists and that there are no composite keys. If the table already has a primary key, it needs to be deleted first.
2. Use the ALTER TABLE statement to add a composite primary key. The syntax is as follows:
ALTER TABLE table_name
ADD CONSTRAINT constraint_name PRIMARY KEY (column1, column2, ...);
Among them, table_name is the name of the table to add the primary key, constraint_name is the name of the primary key, and column1, column2, etc. are the column names that make up the composite primary key.
For example, if we want to add a composite primary key to a table named users, consisting of the columns id and email, the statement is as follows:
ALTER TABLE users
ADD CONSTRAINT pk_users PRIMARY KEY (id, email);
By executing the above ALTER TABLE statement, you can successfully add a composite primary key. You can verify if the primary key has been successfully added by querying the table’s metadata.
Please note that adding a primary key may impact existing data in the table, so please make sure to backup the data before performing this operation.