Let's see how to add primary key constraint while creating a new table or to an existing table in Sql Server.
Primary key constraint uniquely identifies each record in a database table. We can simply use create command to add primary key constraint to a column while creating new table or can use alter command to add it to an existing table. Let's see it one by one. You can also crreate composite primary key. For more info please click this link.
You can add primary key constraint while creating new table using create command.
CREATE TABLE MyTable(ID int PRIMARY KEY, FirstName varchar(50), LastName varchar(50))
You can also add like this using constraint keyword. This way we can easily put its name for future use.
CREATE TABLE MyTable(ID int not null, FirstName varchar(50), LastName varchar(50), CONSTRAINT PK_ID PRIMARY KEY(ID))
Use alter command to add primary key on an existing table.
ALTER TABLE MyTable ADD PRIMARY KEY(ID)
Remember that you cannot add primary key on nullable column. for that you should first make column not null.
ALTER TABLE MyTable ALTER COLUMN ID INT NOT NULL
--now you can add primary key constraint.
ALTER TABLE MyTable ADD CONSTRAINT PK_MyTable_ID PRIMARY KEY (id)
You can also delete this constraint using alter command. For more info please click on the link.
Hope it helps you. Use it in your code and enjoy.