In this tutorial, I am going to discuss Primary Key in SQL Server. Primary Key is used to identify a record uniquely.

After completing this tutorial you will be able to understand:

  • What is Primary Key in SQL Server?
  • How to Create Primary Key in SQL Server?
  • Drop a Primary Key in SQL Server.
  • Enabling and Disabling a Primary Key in SQL Server.

Introduction:

Primary is a SQL Constraint that is used to Uniquely Identifies record a field with a field or a combination of the field.

Primary Key

The key point about Primary Key:

  • We can define a Primary Key for the table either in CREATE TABLE Statement or ALTER TABLE Statement.
  • Primary Key can not NULL values.
  • We can create only one Primary Key on each table.

The syntax for creating a Primary Key:

You can create a primary key in two ways. Here is the Syntax for both:

Sytanx1:

Syntax2:

);

The example of Primary Key:

Here we will see how to create a Primary Key as an example. Look at the following table structure.

In the above table structure, you can see we have created Primary Key on EmployeeID column because the Employee is uniquely identified with his EmployeeID.

We can also create a Primary Key on the table using Syntax2.

We can also create a Primary key on a combination of columns. This combination is called as Composite Key.

Example:

Create Primary Key after Table Creation:

If you want to create a Primary Key after the creation of table you can use ALTER TABLE Statement to create a Primary Key on the Table. You can create a Primary on a column or a group of columns that are already defined as NOT NULL. You can not create a Primary Key on a column that can accept NULL values. For creating a Primary Key on such columns that accept NULL Values you need to drop it and recreate it.

The syntax for Creating Primary Key after Table Creation:

Example:

You can create a Primary Key using ALTER TABLE Statement in the following ways:

You can also create a Primary Key using ALTER TABLE Statement for the group of columns using the below example.

Drop Primary Key:

You can drop a Primary Key using the ALTER TABLE Statement.

The syntax for Dropping a Primary Key:

The example of Dropping a Primary Key:

Disabling a Primary Key:

You can also Disable a Primary Key on the Table.

The syntax for disabling a Primary Key on the table.

Example:

Enabling a Primary Key:

You can Enable a Primary Key on the Table.

The syntax for disabling a Primary Key on the table.

Example:

Conclusion:

Hope this tutorial is helpful for you when you have just started learning SQL Server. I will appreciate your Comments, Suggestions and Feedback.

View More:

Thank You.

Leave a Comment