Tutorial Gateway

  • C
  • C#
  • Java
  • Python
  • SQL
  • MySQL
  • Js
  • BI Tools
    • Informatica
    • Talend
    • Tableau
    • Power BI
    • SSIS
    • SSRS
    • SSAS
    • MDX
    • R Tutorial
    • Alteryx
    • QlikView
  • More
    • C Programs
    • C++ Programs
    • Python Programs
    • Java Programs

SQL Primary Key

by suresh

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.

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.

SQL Primary Key 5

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 Primary Key 8

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.

Placed Under: SQL

  • Install SQL Server
  • Install SQL Management Studio
  • Uninstall Management Studio
  • Install AdventureWorks Database
  • SQL Management Studio Intro
  • Connect SQL with sqlcmd utility
  • SQL Attach Database
  • SQL Detach Database
  • SQL Restore Database
  • Restore Database using BAK
  • SQL Rename Database with Files
  • Get SQL Database Names
  • SQL Create Table
  • SQL Rename Table
  • SQL Alter Table
  • SQL Add Column
  • SQL Rename Column
  • Get SQL Table Names in a DB
  • Find SQL Table Dependencies
  • Rename SQL Table & Column
  • SQL Global & Local Temp Table
  • SQL Table Variable
  • SQL Derived Table
  • SQL DATALENGTH
  • SQL Data Types
  • DML, DDL, DCL & TCL Cmds
  • SQL Query Builder
  • SQL ALIAS
  • SQL SELECT Statement
  • SQL SELECT DISTINCT
  • SQL SELECT INTO Statement
  • SQL INSERT Statement
  • SQL INSERT INTO SELECT
  • SQL BULK INSERT or BCP
  • SQL UPDATE Statement
  • SQL UPDATE from SELECT
  • SQL DELETE Statement
  • SQL TRUNCATE Table
  • SQL CASE Statement
  • SQL MERGE Statement
  • SQL Subquery
  • SQL CTE
  • SQL PIVOT
  • SQL UNPIVOT
  • SQL Clauses Examples
  • SQL TOP Clause
  • SQL WHERE Clause
  • SQL ORDER BY Clause
  • SQL GROUP BY Clause
  • SQL HAVING Clause
  • SQL Primary Key
  • SQL Foreign Key
  • SQL Referential Integrity
  • SQL Check Constraint
  • SQL Unique Constraint
  • SQL Default Constraint
  • SQL Clustered Index
  • SQL Non Clustered Index
  • SQL Filtered Indexes
  • SQL COALESCE Function
  • SQL IS NOT NULL
  • SQL IS NULL Function
  • SQL ISNULL
  • SQL JOINS
  • SQL CROSS JOIN
  • SQL FULL JOIN
  • SQL SELF JOIN
  • SQL Outer Joins
  • SQL Cross Join Vs Inner Join
  • SQL LEFT JOIN
  • SQL RIGHT JOIN
  • SQL AND & OR Operators
  • SQL Arithmetic Operators
  • SQL BETWEEN Operator
  • SQL Comparison Operators
  • SQL LIKE
  • SQL EXCEPT
  • SQL EXISTS Operator
  • SQL NOT EXISTS Operator
  • SQL INTERSECT
  • SQL IN Operator
  • SQL NOT IN Operator
  • SQL UNION
  • SQL UNION ALL
  • SQL IF ELSE
  • SQL ELSE IF
  • SQL WHILE LOOP
  • SQL Nested While Loop
  • SQL BREAK Statement
  • SQL CONTINUE Statement
  • SQL GOTO Statement
  • SQL IIF Function
  • SQL CHOOSE Function
  • SQL Change Data Capture
  • SQL Table Partitioning
  • SQL Table Partition using SSMS
  • SQL TRY CATCH
  • SQL VIEWS
  • SQL User Defined Functions
  • SQL Alter User Defined Functions
  • SQL Stored Procedure Intro
  • Useful System Stored Procedures
  • SQL SELECT Stored Procedure
  • SQL INSERT Stored Procedure
  • SQL UPDATE Stored Procedure
  • Stored Procedure Return Values
  • Stored Procedure Output Params
  • Stored Procedure Input Params
  • Insert SP result into Temp Table
  • SQL Triggers Introduction
  • SQL AFTER INSERT Triggers
  • SQL AFTER UPDATE Triggers
  • SQL AFTER DELETE Triggers
  • SQL INSTEAD OF INSERT
  • SQL INSTEAD OF UPDATE
  • SQL INSTEAD OF DELETE
  • SQL STATIC CURSOR
  • SQL DYNAMIC CURSOR
  • SQL FORWARD_ONLY Cursor
  • SQL FAST_FORWARD CURSOR
  • SQL KEYSET CURSOR
  • SQL TRANSACTIONS
  • SQL Nested Transactions
  • SQL ACID Properties
  • Create SQL Windows Login
  • Create SQL Server Login
  • SQL Server Login Error
  • Create SQL Server Roles
  • SQL Maintenance Plan
  • Backup SQL Database
  • SQL Ranking Functions Intro
  • SQL RANK Function
  • SQL PERCENT_RANK Function
  • SQL DENSE_RANK Function
  • SQL NTILE Function
  • SQL ROW_NUMBER
  • SQL Aggregate Functions
  • SQL Date Functions
  • SQL Mathematical Functions
  • SQL String Functions
  • SQL CAST Function
  • SQL TRY CAST
  • SQL CONVERT
  • SQL TRY CONVERT
  • SQL PARSE Function
  • SQL TRY_PARSE Function
  • SQL Calculate Running Total
  • SQL Find Nth Highest Salary
  • SQL Reverse String
  • SQL FOR XML PATH
  • SQL FOR XML AUTO
  • SQL FOR XML RAW
  • C Tutorial
  • C# Tutorial
  • Java Tutorial
  • JavaScript Tutorial
  • Python Tutorial
  • MySQL Tutorial
  • SQL Server Tutorial
  • R Tutorial
  • Power BI Tutorial
  • Tableau Tutorial
  • SSIS Tutorial
  • SSRS Tutorial
  • Informatica Tutorial
  • Talend Tutorial
  • C Programs
  • C++ Programs
  • Java Programs
  • Python Programs
  • MDX Tutorial
  • SSAS Tutorial
  • QlikView Tutorial

Copyright © 2021 | Tutorial Gateway· All Rights Reserved by Suresh

Home | About Us | Contact Us | Privacy Policy