Please enable Javascript for better experience...
Adding primary key to a table in Sql Server
By Rahul Kumar Jha | Jan 5, 2015 | In Tips | Update: Nov 21, 2018 | Total Views [ 3454 ]
Taged In
(1 Like)
Rate

Let's see how to add primary key constraint while creating a new table or to an existing table in Sql Server.

Introduction

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.

Using create command

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))

Using alter command

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.

Share this

About the Author

Rahul Kumar Jha
Rahul Kumar Jha
Founder, Developer dotnet-concept.com

Public profile: user/profile/99900001


Has working experience in different phases of Software Development Life Cycle (SDLC) in CMS, Gaming, Health Care and Financial Services domain using Agile pattern. Working experience in Design patterns, ASP.NET, MVC, ANGULAR, ANGULAR JS, Windows application, WCF, ADO.NET, SQL Server and Test Driven Development (TDD) environment with JQuery, JavaScript, N-Unit, Entity Frameworks, LINQ, Code Refactoring and Business Objects Models.

User's Comments


 
Please SignUp/Login to comment...

Or comment as anonymous...
* Name
* Email ID
Comment
 
 
 
 
 
 
Sponsors