Overview

Unique Key is used to define uniqueness in data in any column of a table. Primary Key and Unique key both are used to maintain uniqueness in a table. 

Despite of lot of same functionalities in primary and unique keys. There are lot of differences as well.

Unique key can have null values where as primary key does not.

There can be lot of unique keys in a table but only one primary key.

A primary key by default has unique constraint in it.

Syntax

Create Table with Unique key

CREATE TABLE table_name (column1 data_type UNIQUE, column2 data_type, column3 data_type);

Alter Table add Unique Key

ALTER TABLE table_name ADD UNIQUE(column_name);

In MYSQL

ALTER TABLE table_name ADD CONSTRAINT unique_constraint_name UNIQUE(column_name);

Alter Table drop Unique Key

ALTER TABLE table_name DROP CONSTRAINT unique_constraint_name

IN MYSQL

Alter TABLE table_name DROP INDEX unique_constraint_name;

Examples

Create Table with Unique key

CREATE TABLE subject_list (student_id INT(3) NOT NULL UNIQUE, name VARCHAR(250) );

Alter Table add Unique Key

ALTER TABLE subject_list ADD CONSTRAINT unique_name UNIQUE(name);

Alter Table drop Unique Key

ALTER TABLE subject_list DROP CONSTRAINT unique_name;



If you want to add more comments to the article or you see any thing incorrect please write a comment below and we will surely get back to you.



Trending Articles


Incorrect table definition there can be only one TIMESTAMP column with CURRENT_TIMESTAMP in DEFAULT or ON UPDATE clause

Infix To Postfix Conversion Using Stack in Javascript

How to solve IE/Edge CORS error ?

Web Server vs Application Server Difference Explained

How to setup angular2 in visual studio ide

Binary Search Tree Insert node Implementation in Javascript

How to use ninject dependency injection in mvc

How to Add Comparison Feature in Replace in C-Sharp