- Can duplicate values be inserted if we have a unique index on a column and no unique constraint?
No, the values of the columns within the index must create a unique set of data within that index.
- What about existing duplicates in any on the column - will it allow to create unique index or unique constraint?
No, you cannot create a Unique Index on a table that has duplicate values.
This easiest way to have found this out would be to try (I suggest for things like that doing so, it's a great way of learning):
CREATE TABLE dbo.SomeTable (SomeInt int, AnotherInt int);
GO
INSERT INTO dbo.SomeTable (SomeInt,
AnotherInt)
VALUES (1,1),
(1,2),
(2,1);
GO
--Create a unique index on a column with duplicate values
CREATE UNIQUE INDEX UQ_SomeInt ON dbo.SomeTable(SomeInt); --fails
GO
--Create a unique index on the 2 columns, as they are unique
CREATE UNIQUE INDEX UQ_Some_AnotherInt ON dbo.SomeTable(SomeInt, AnotherInt); --Succeeds
GO
--Try to insert a duplicate value
INSERT INTO dbo.SomeTable (SomeInt,
AnotherInt)
VALUES(2,1); --fails
GO
SELECT *
FROM dbo.SomeTable
GO
DROP TABLE dbo.SomeTable;
IGNORE_DUP_KEY
does not allow duplicate values to exist in the index. A unique index never has duplicate values. InsteadIGNORE_DUP_KEY
simply causes attempts to insert duplicate values to be ignored (with a warning message) instead of causing an error. – Ceasar