Sql Primary Key Constraint  

Primary Key uniquely identifies each record in a table. Primary key must contain UNIQUE entries i.e. it cannot contain duplicate entries, and cannot contain NULL entries. A table can have only one primary key.

0 424 Technology | Sql Server
Tue Dec 25 , 2018

When multiple columns are used as a primary key, it is known as composite primary key.

Points to remember

  • Primary key enforces the entity integrity of the table.
  • Primary key always has unique entries.
  • Primary key length cannot be exceeded than 900 bytes.
  • Primary key cannot have null entries.
  • Primary key cannot contain duplicateentries.
  • A table can contain only one primary key constraint.
  • The main advantage of this uniqueness is that we get fast access.

Sql Primary Key for one column

CREATE TABLE Student
(
    RollNo int NOT NULL PRIMARY KEY,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255),
    Marks int
); 

Sql Primary Key for multiple columns

CREATE TABLE Student
(
    RollNo int NOT NULL PRIMARY KEY,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255),
    Marks int,
    CONSTRAINT pk_StudentRollNo PRIMARY KEY (RollNo , LastName)  
); 

Create a Primary Key

To create a Primary Key constraint on the RollNo column when the table Student is already created, you should use the following syntax:

    ALTER TABLE Student ADD PRIMARY KEY (RollNo);


Delete a Primary Key

If you want to DROP (remove) a primary keyconstraint, you should use the following syntax:

  ALTER TABLE Student DROP PRIMARY KEY ;



Subscribe & Get Regular Updates On Your E-mail