SQL Primary Key - The Coding Shala

Home >> Learn SQL >> SQL Primary key

SQL Primary Key

SQL Primary Key is a field that uniquely identifies each record in the database table. That means if a Primary Key is defined on a field then you cannot have two records having the same value of the fields. SQL Primary Key cannot contains NULL Values. A table can have only one Primary Key which may consist of one or more fields. If more than one column is used as a Primary Key then it is known as Composite Primary Key.
SQL Primary Key - The Coding Shala

Create Primary Key Syntax

The following syntax will create Table Persons having Primary Key as ID - 

 Create table Persons(  
    ID int,  
    Name varchar(30),  
    City varchar(30),  
    PRIMARY KEY (ID)  
    );

If Table is already created and we want to add primary key then we use alter command to add a primary key. The following syntax will add a primary key in the existing table - 

 ALTER TABLE PERSONS ADD PRIMARY KEY (ID) 

To create Primary Key constraints more than one columns then use the following SQL Command - 

 ALTER TABLE PERSONS   
   ADD CONSTRAINT PK_PID PRIMARY KEY (ID, NAME);  

Delete Primary Key

The following SQL Syntax is used to drop the primary key constraints from the existing table-  

 ALTER TABLE PERSONS DROP PRIMARY KEY ;  



Other Posts You May Like
Please leave a comment below if you like this post or found some error, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to find sum, product and average of given numbers - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Richest Customer Wealth LeetCode Solution - The Coding Shala

New Year Chaos Solution - The Coding Shala

Add two numbers in Scala - The Coding Shala