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



  Tutorials

Popular Links

Contact Us

address Plot No-741,2ND Floor
Opp. Bhagabati Temple,Jayadev Vihar
      Bhubaneswar-751013
      Email: info@silantechnology.com
      Phone: 0674-2361252
address
39877, sundale dr, apt#101, Fremont, California 94538, USA
       Phone: +1(262)388-7619

facebook twitter google linked in

© 2018 Silan Technology. All Rights Reserved