In this article, we will learn how to use the Primary Key constraint in SQL.

The PRIMARY KEY constraint is used to identify each record uniquely in a table.

Primary keys cannot contain NULL values and must contain UNIQUE values.

A table can have only one PRIMARY KEY but this primary key can be consist of single or multiple columns.

 

PRIMARY KEY – CREATE TABLE: 

Please check How To Create Table Using Query In SQL, to get a brief description of the CREATE TABLE statement.

Example-1

The subsequent statement would create a PRIMARY KEY constraint on the “ID” column when the “Article” table is created:

CREATE TABLE Article (
    ID int PRIMARY KEY,
    Title varchar(100),
    Author varchar(100),
    Views int 
);

Example-2

The subsequent statement would create a PRIMARY KEY constraint, which is made up of two columns (ID + Title) when the “Article” table is created:

CREATE TABLE Article (
    ID int,
    Title varchar(100),
    Author varchar(100),
    Views int,
    CONSTRAINT PKArticle PRIMARY KEY (ID, Title)
);

 

PRIMARY KEY – ALTER TABLE: 

Please check How To Alter Table Using Query In SQL, to get a brief description of the ALTER TABLE statement.

  • To ADD a PRIMARY KEY Constraint

Syntax

ALTER TABLE TABLE_NAME 
ADD CONSTRAINT CONSTRAINT_NAME PRIMARY KEY (column1, column2, ...columnN);

Example

The subsequent statement would add a PRIMARY KEY constraint on the “ID” column using ALTER TABLE statement:

ALTER TABLE Article 
ADD CONSTRAINT PKArticle PRIMARY KEY (ID);
  • To DROP a PRIMARY KEY Constraint

Syntax

ALTER TABLE TABLE_NAME 
DROP CONSTRAINT CONSTRAINT_NAME;

Example

The subsequent statement would delete a PRIMARY KEY constraint named “PKArticle” using ALTER TABLE statement:

ALTER TABLE Article 
DROP CONSTRAINT PKArticle;

 

Also, check How To Use UNIQUE Constraint In SQL