DB2UDB allows to define a unique constraint when an index is not
defined as unique.
It means that there is then an internal attribute saying the index is
unique when a unique constraint is defined on it.
The result is: as long as the constraint exists, no duplicates will be
allowed.
When the constrained is dropped, duplicates are allowed again.
Example:
CREATE TABLE T1 ( C1 char(10) not null);
CREATE INDEX MYINDEX1 ON T1(C1);
ALTER TABLE T1 ADD CONSTRAINT CONSTRAINT1 PRIMARY KEY (C1);
When creating the constraint db2 will return SQL0598W:
"SQL0598W Existing index "<name>" is used as the index for the
primary key or a unique key.
Explanation:
An index was required for an ALTER TABLE operation that defined a
primary key or a unique key, and the indicated index matches the
required index.
When creating a primary key or unique key index, an index
description matches if it identifies the same set of columns (in
any order) as the primary or unique key without regard to
ascending or descending specifications, and is specified as
unique.
The statement is processed successfully.
"
It is not correct that an index description matches, specified as
unique.
DB2 UDB allows this anyway, and will enforce correctly the constraint
(at creation time and at insert time).
Looks to be a feature.
Bernard Dhooghe
Ian wrote:
Mark A wrote:
I never said that a unique constraint was the same as a primary key. But one
of the differences between a unique constraint and unique index is that a
foreign key on another table can refer to a unique constraint, even if it is
not the primary key.
Mark,
That is a true statement - you can't define a foreign key without a
constraint (unique or primary key).
Regardless, I still hold that constraints are purely logical entities.
There are no physical manifestations of them (other than some entries in
the system catalog).
Unique indexes are the _physical_ implementation that DB2 uses to
enforce uniqueness (because it's a lot more efficient than trying to
scan an entire table to determine if a value already exists :-).