How to Add Primary Key in DB2
To add a primary key to a table in the DB2 database, you can use the ALTER TABLE statement with the ADD CONSTRAINT clause. Here are the steps to add a primary key.
- Identify the column to be used as the primary key: First, determine which column in the table will become the primary key.
- Use the ALTER TABLE command to modify the table structure and add a primary key constraint.
- Add primary key constraint: Use the ADD CONSTRAINT clause in the ALTER TABLE command and specify the name of the primary key along with the columns involved.
The following example code demonstrates how to add a primary key to a table in a DB2 database.
-- 创建一个名为students的表
CREATE TABLE students (
id INT,
name VARCHAR(50),
age INT
);
-- 为students表添加主键约束
ALTER TABLE students
ADD CONSTRAINT pk_students_id PRIMARY KEY (id);
In the example above, we first created a table called “students”, then used the ALTER TABLE command and ADD CONSTRAINT clause to add a primary key constraint to the table. The primary key is named pk_students_id, and the column associated with the primary key is specified as id.