• Home
  • SQL UNIQUE Constraint

    The SQL UNIQUE Constraint uniquely identifies each record in a database table.

    The UNIQUE and PRIMARY KEY constraints both provide a guarantee for uniqueness for a column or set of columns.

    A PRIMARY KEY constraint automatically has a UNIQUE constraint defined on it.

    Note: that you can have many UNIQUE constraints per table, but only one PRIMARY KEY constraint per table.

    SQL UNIQUE Constraint on CREATE TABLE

    The following SQL creates a UNIQUE constraint on the "C_Id" column when the "Customer" table is created:

    SQL Server / Oracle / MS Access:

    CREATE TABLE Customer
    ( C_Id int NOT NULL UNIQUE,
    LastName varchar(100) NOT NULL,
    FirstName varchar(100),
    Address varchar(100),
    City varchar(100) );

    MySQL:

    CREATE TABLE Customer ( C_Id int NOT NULL,
    LastName varchar(100) NOT NULL,
    FirstName varchar(100),
    Address varchar(100),
    City varchar(100),
    UNIQUE (C_Id) );

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

    MySQL / SQL Server / Oracle / MS Access:

    CREATE TABLE Customer ( C_Id int NOT NULL,
    LastName varchar(100) NOT NULL,
    FirstName varchar(100),
    Address varchar(100),
    City varchar(100),
    CONSTRAINT UC_CID UNIQUE (C_Id,LastName) );

    SQL UNIQUE Constraint on ALTER TABLE

    To create a UNIQUE constraint on the "C_Id" column when the table is already created, use the following SQL:

    MySQL / SQL Server / Oracle / MS Access:

    ALTER TABLE Persons ADD UNIQUE (C_Id)

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

    MySQL / SQL Server / Oracle / MS Access:

    ALTER TABLE Persons ADD CONSTRAINT UC_CID UNIQUE (C_Id,LastName)

    To DROP a UNIQUE Constraint

    To drop a UNIQUE constraint, use the following SQL:

    SQL Server / Oracle / MS Access:

    ALTER TABLE Customer DROP CONSTRAINT UC_CID


    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