All for Joomla All for Webmasters

UNIQUE KEY IN SQL

A unique key is a set of one or more than one fields/columns of a table that uniquely identify a record in a database table.

You can say that it is little like primary key but it can accept only one null value and it cannot have duplicate values.

The unique key and primary key both provide a guarantee for uniqueness for a column or a set of columns.

There is an automatically defined unique key constraint within a primary key constraint.

There may be many unique key constraints for one table, but only one PRIMARY KEY constraint for one table.

SQL UNIQUE KEY constraint on CREATE TABLE:

If you want to create a UNIQUE constraint on the ?S_Id? column when the ?students? table is created, use the following SQL syntax:

SQL Server / Oracle / MS Access:

(Defining a unique key constraint on single column):

  1. CREATE TABLE students
  2. (
  3. S_Id int NOT NULL UNIQUE,
  4. LastName varchar (255) NOT NULL,
  5. FirstName varchar (255),
  6. City varchar (255)
  7. )

MySQL:

  1. CREATE TABLE students
  2. CREATE TABLE students
  3. (
  4. S_Id int NOT NULL,
  5. LastName varchar (255) NOT NULL,
  6. FirstName varchar (255),
  7. City varchar (255),
  8. UNIQUE (S_Id)
  9. )

(Defining a unique key constraint on multiple columns):

MySQL / SQL Server / Oracle / MS Access:

  1.  CREATE TABLE students
  2. (
  3. S_Id int NOT NULL,
  4. LastName varchar (255) NOT NULL,
  5. FirstName varchar (255),
  6. City varchar (255),
  7. CONSTRAINT uc_studentId UNIQUE (S_Id, LastName)
  8. )

SQL UNIQUE KEY constraint on ALTER TABLE:

If you want to create a unique constraint on ?S_Id? column when the table is already created, you should use the following SQL syntax:

(Defining a unique key constraint on single column):

MySQL / SQL Server / Oracle / MS Access:

  1. ALTER TABLE students
  2. ADD UNIQUE (S_Id)

(Defining a unique key constraint on multiple columns):

MySQL / SQL Server / Oracle / MS Access:

  1. ALTER TABLE students
  2. ADD CONSTRAINT uc_StudentId UNIQUE  (S_Id, LastName)

DROP SYNTAX FOR A FOREIGN KEY constraint:

If you want to drop a UNIQUE constraint, use the following SQL syntax:

MySQL:

  1. ALTER TABLE students
  2. DROP INDEX uc_studentID

SQL Server / Oracle / MS Access:

  1. ALTER TABLE students
  2. DROP CONSTRAINT uc_studentID
PinIt
submit to reddit

Leave a Reply

Top