Please enable Javascript for better experience...
Adding primary key to a table in Sql Server
By Big | Jan 5, 2015 | In Tips | Update: Jan 5, 2015 | Total Views [ 1017 ]
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)

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

Big
Rahul Jha (Big)
Founder, Developer dotnet-concept.com
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, 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.

 
Please SignUp/Login to comment...

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