• Home
  • SQL PRIMARY KEY Constraint

    The PRIMARY KEY constraint uniquely identifies each record in a database table.

    Primary keys must contain UNIQUE values.

    A primary key column cannot contain NULL values.

    Most tables should have a primary key, and each table can have only ONE primary key.


    SQL PRIMARY KEY Constraint on CREATE TABLE

    The following SQL creates a PRIMARY KEY on the "C_Id" column when the "Employee" table is created:


    SQL Server / Oracle / MS Access:
    CREATE TABLE Customer
    (
    C_Idint NOT NULL PRIMARY KEY,
    LastName varchar(100) NOT NULL,
    FirstName varchar(100),
    Address varchar(100),
    City varchar(100)
    

    MySQL:
    CREATE TABLE Customer
    (
    C_Idint NOT NULL,
    LastName varchar(100) NOT NULL,
    FirstName varchar(100),
    Address varchar(100),
    City varchar(100),
    PRIMARY KEY (C_Id)
    );
    

    To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY constraint on multiple columns,use the following SQL syntax:


    MySQL / SQL Server / Oracle / MS Access:
    CREATE TABLE Customer
    (
    C_Idint NOT NULL,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255),
    Address varchar(255),
    City varchar(255),
    CONSTRAINT PK_CID PRIMARY KEY (C_Id,LastName)
    );
    

    Note: In the example above there is only ONE PRIMARY KEY (pk_PersonID). However, the VALUE of the primary key is made up of TWO COLUMNS (P_Id + LastName).


    SQL PRIMARY KEY Constraint on ALTER TABLE

    To create a PRIMARY KEY constraint on the "P_Id" column when the table is already created, use the following SQL:


    MySQL / SQL Server / Oracle / MS Access:

    ALTER TABLE Customer ADD PRIMARY KEY (C_Id)

    To allow naming of a PRIMARY KEY Constraint, and for defining a PRIMARY KEY Constraint on multiple columns, use the following SQL syntax:


    MySQL / SQL Server / Oracle / MS Access:

    ALTER TABLE Customer
    ADD CONSTRAINT PK_CID PRIMARY KEY (C_Id,LastName)

    Note: If you use the ALTER TABLE statement to add a primary key, the primary key column(s) must already have been declared to not contain NULL values (when the table was first created).


    To DROP a PRIMARY KEY Constraint

    To drop a PRIMARY KEY constraint, use the following SQL:

    SQL Server / Oracle / MS Access:

    ALTER TABLE Customer
    DROP CONSTRAINT PK_CID

    MySQL:

    ALTER TABLE Customer
    DROP PRIMARY KEY


    About the Author



    Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.

    We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc





     PreviousNext