SQL Primary Key - The Coding Shala
Home >> Learn SQL >> SQL Primary key
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 -
To create Primary Key constraints more than one columns then use the following SQL Command -
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.
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
Comments
Post a Comment