Loading...

Primary Key is used to uniquely identify the records in a SQL Table. Here we can say, primary key is a value of a column that value is unique in the table. Primary Key don't accept any null value. Primary Key is also play an important role to create relationship between two or more tables. A table can have only one Primary Key

When we set Primary Key on a column then Clustered index automatically created on that column. And SQL Table will automatically sorted by Primary Key column. We will discuss about Clustered Index on another post.


Student_ID

Student_Name

Father_Name

DOB

Gender

1

Rakesh Kumar

Mr. Upendra Singh

12-Jul-91

M

2

Suman Kumari

Mr. Rohit Pathak

10-Mar-90

F

3

Anil Yadav

Mr. Sunil Yadav

18-Mar-92

M

4

Ravi Singh

Mr. Vivek Singh

15-Dec-91

M

5

Prakash Kumar

Mr. Suraj Singh

23-Oct-93

M

6

Vijay Verma

Mr. Mohan Verma

1-Feb-90

M



Here, we taken an example of above table. In this table we created Primary Key on Student_ID and so, this table is already sorted on Student_ID. And there is no any null value in Student_ID.


SQL Query to create a Primary Key on New Table Student

Create table Student
(
Student_ID int Primary Key,
Student_Name varchar(50),
Father_Name varchar(50),
DOB Date,
Gender char(1)
)


SQL Query to create a Primary Key on existing table

alter table Student
ADD CONSTRAINT PK_Student PRIMARY KEY (Student_ID) 


Create a Primary Key on Table Student through Wizard

If you want to create Primary Key through Wizard then Right Click on table and click on Design. A Table Design window will be open. Select that column which you want to make Primary Key and right click on left corner of selected column a popup menu will come then choose Set Primary Key.

Primary Key



Here, remove the Primary Key

Primary Key