I tried to find it out in google but not satisfactory answer is given out there. Can anybody explain the solid difference.
actually if Primary key is used to sele
Both are representing a unique identification to a row in a table but there is little bit difference is that
PRIMARY key does not allows NULL values
while
UNIQUE key allows only one NULL values.
that is the main difference ..
Just to add another example:
Think of a table holding user data, where each user has an email address. No two users can have the same email address, so that column becomes a unique key. While it could be the primary key (I have never made a string a primary key), it doesn't have to be.
A primary key does not allow nulls, a unique key will allow one null (on sql server and multiple nulls on Oracle) A table can only have one primary key but many unique keys
use primary keys when you want to set up foreign key relationships
Here is a small example with just one column in each table
--primary key table
CREATE TABLE PrimaryTest (id INT PRIMARY KEY NOT NULL)
GO
-- foreign key table
CREATE TABLE ForeignTest (Pkid INT NOT NULL)
GO
--relationship
ALTER TABLE dbo.ForeignTest ADD CONSTRAINT
FK_ForeignTest_PrimaryTest FOREIGN KEY
(
Pkid
) REFERENCES dbo.PrimaryTest
(
id
) ON UPDATE NO ACTION
ON DELETE NO ACTION
GO
insert a row in the primary key table
insert PrimaryTest values(1)
insert a row in the foreign key table with a value that exist in the primary key table
insert ForeignTest values(1)
Now this will fail because value 2 does not exist in the primary key table
insert ForeignTest values(2)
Msg 547, Level 16, State 0, Line 1 The INSERT statement conflicted with the FOREIGN KEY constraint "FK_ForeignTest_PrimaryTest". The conflict occurred in database "aspnetdb", table "dbo.PrimaryTest", column 'id'. The statement has been terminated.
A unique key will served with other key while a primary key does not serve any other key with it. The primary key is used without any association of any other key.
Primary Key constraint
1. A primary key cannot allow null.
2. Multiple primary keys are NOT allowed.
3. On some RDBMS a primary key generates a clustered index by default.
Unique constraint
1. A unique constraint can be defined on columns that allow nulls.
2. Multiple unique keys are allowed.
3. On some RDBMS a unique key generates a nonclustered index by default.
Source Wikipedia