SQL Unique Key sql-unique-key.pdf

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;



This article is contributed by Ankur Rastogi on Sun Mar 27 2016 18:23:47 GMT+0530 (IST)

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.