Add Primary key To Existing Table Sql

Add Primary Key To Existing Table Sql

  • First of all, we have to tell which table we made changes.
  • Then We can specify adding the primary key to.

The Answer

Alter table books Add primary key(book_id)

Note: The primary key is a constraint. We can write the answer like below

Alter table books add constraint pk_books primary key(book_id)

Note: In the answer above, We named the constraint. At the first answer the program named the constraint

  • If we get the error message:Cannot define PRIMARY KEY constraint on nullable column in table ‘books’. Then we must execute the code below first. Because the column must not be nullable. If we have null values then we must delete that records or we must fill them. Then we can execute the code below.
Alter table books alter column book_id int not null



Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: