SQL Primary Key

SQL Primary Key constraint is used to implement the data Integrity in SQL tables. When you set a SQL Server Primary key on any column, the Database engine will automatically create a Unique index on that column. In real-time, we use these Primary key columns to identify the columns uniquely and to access the data quickly and effectively.

In general, every table has at least one column that contains unique values called the SQL Primary Key column. For example, an Employee table might have Employee ID, or Orders have an Order ID column. Before we get into the SQL Server Primary Key example, the following are the list of points you should remember:

  • A table can contain Only one Primary key in SQL Server.
  • You can’t insert any duplicate content into the primary key columns.
  • The SQL primary key column doesn’t allow NULL values. By default, NOT NULL will be assigned to the primary key column, even if you forgot at the time of creation.
  • If you forgot to mention the index as Clustered or Non clustered, then the SQL Server Database engine will assign clustered index by default.

Create SQL Primary Key

We can create a SQL Server primary key using both the Transact SQL query and the SQL Server Management Studio.

Create SQL Primary Key using T-SQL

Let us see how to create a Primary Key using a query. Here we will create a primary key at the creation of the table. Refer to Create Table article in SQL Server.

USE [SQL Tutorial]
GO

CREATE TABLE [CustmerRecords]
(
  [CustomerKey] [int] NOT NULL PRIMARY KEY,
  [FirstName] [varchar](50) NOT NULL ,
  [LastName] [varchar](50) NULL,
  [BirthDate] [date] NULL,
  [EmailAddress] [nvarchar](50) NULL,
  [Yearly Income] [money] NULL,
  [Profession] [nvarchar](100) NULL
)

We just added the PRIMARY KEY word to the Column declaration. SSMS is intelligent enough to create a primary key for you.

See the internal code generated by the SQL, by right-clicking on the table -> script as – > create to new query window option

SQL Primary Key 6

Create Primary Key on Existing table

Let us add SQL Server Primary Key on the existing table. For this, we create a new table

CREATE TABLE [CustmerRecords]
(
  [CustomerKey] [int] NOT NULL,
  [FirstName] [varchar](50) NOT NULL ,
  [LastName] [varchar](50) NULL,
  [BirthDate] [date] NULL,
  [EmailAddress] [nvarchar](50) NULL,
  [Yearly Income] [money] NULL,
  [Profession] [nvarchar](100) NULL
)

Now let me add the SQL Primary key constraint. For this, we are using the Alter Table Statement to alter the table content. And then, we used the ADD Constraint statement to add the primary key constraint.

USE [SQL Tutorial]
GO

ALTER TABLE [CustmerRecords]   
ADD CONSTRAINT PK_CustmerRecords_CustomerKey PRIMARY KEY CLUSTERED (CustomerKey);  
GO
SQL Primary Key 7

Insert rows into SQL Server Primary Constraint Column

Let me insert a few rows to check the primary key functionality.

INSERT INTO [dbo].[CustmerRecords] 
VALUES (1, 'Imran', 'Khan', '10-08-1985', '[email protected]', 15900, 'Skilled Professional')
      ,(2, 'Doe', 'Lara', '10-08-1985', '[email protected]', 15000, 'Management')
      ,(3, 'Ramesh', 'Kumar', '10-08-1985', '[email protected]', 65000, 'Professional')

SQL Messages

(3 row(s) affected)

Let us see the inserted data.

SQL Primary Key 9

Insert Duplicate into SQL Primary key Column

Above Insert Statement will work fine because we are inserting unique records for the customer Key. Let me insert the duplicate value into the Customer Key column. Please refer Unique index article.

INSERT INTO [dbo].[CustmerRecords] 
VALUES (1, 'Tutorial', 'Gateway', '10-08-1985', '[email protected]', 15900, 'Skilled Professional')
SQL Primary Key 10

It is throwing an error: Violation of PRIMARY KEY constraint ‘PK_CustmerRecords_CustomerKey’. Cannot insert duplicate key in object ‘dbo.CustmerRecords’. The duplicate key value is (1).

Insert Null in SQL Primary key Column

Let me insert the Null Value into the primary key column called customer.

INSERT INTO [dbo].[CustmerRecords] 
VALUES (NULL, 'Tutorial', 'Gateway', '10-08-1995', '[email protected]', 15900, 'Management')

It is also throwing an error.

SQL Primary Key 11

Set SQL Primary Constraint using SSMS

To create a Primary Constraint using the SQL Server Management Studio, please go to the Object Explorer. Right-click on the table on which you want to create a primary key (here it is Custrecords), and select the Design option

SQL Primary Key 1

Once you click the Design option, it will open the Custrecords table in design mode. It has 7 columns of different data types, and our job is to add a primary key to the Customer key column.

SQL Primary Key 2

Right-click on the Customer Key column and choose the Set Primary Key option.

SQL Primary Key 3

Once you select the Set Primary Key option, SSMS will set the Primary key for you.

SQL Primary Key 4

Modify SQL Primary Constraint

Please select the table on which your primary key holds, then go to the Indexes folder. Next, expand the Indexes folder to find the key available on that table, and Right-click on it will open the context menu. Please select the option as per the requirement

SQL Primary Key 12

NOTE: You can’t alter the constraint using the SQL query. To modify the existing primary key, you have to delete and recreate it.

Delete SQL Primary Key using DROP Constraint

If you know the primary key constraint name, use the DROP Constraint statement along with the ALTER TABLE Statement

ALTER TABLE [CustmerRecords]  
DROP CONSTRAINT PK_CustmerRecords_CustomerKey

If you don’t know the SQL Primary Key constraint name, use the first SELECT Statement to get the Constraint name.

-- To find the Constraint Name
SELECT name  
FROM sys.key_constraints  
WHERE type = 'PK' AND OBJECT_NAME(parent_object_id) = N'CustmerRecords';  
GO  
-- Delete or Drop the Constraint 
ALTER TABLE [CustmerRecords]  
DROP CONSTRAINT PK_CustmerRecords_CustomerKey
SQL Primary Key 13

OUTPUT 2

SQL Primary Key 14

Open the Customer records table in a designer mode to check whether we successfully removed the primary key on the Customer Key column or not.

SQL Primary Key 15

As you see, there is no primary on the key column.