Text Size: Normal / Large

8.4. Unique Indexes

Indexes may also be used to enforce uniqueness of a column's value, or the uniqueness of the combined values of more than one column.

CREATE UNIQUE INDEX name ON table (column [, ...]);

Currently, only B-tree indexes can be declared unique.

When an index is declared unique, multiple table rows with equal indexed values will not be allowed. NULL values are not considered equal.

PostgreSQL automatically creates unique indexes when a table is declared with a unique constraint or a primary key, on the columns that make up the primary key or unique columns (a multicolumn index, if appropriate), to enforce that constraint. A unique index can be added to a table at any later time, to add a unique constraint.

Note: The preferred way to add a unique constraint to a table is ALTER TABLE ... ADD CONSTRAINT. The use of indexes to enforce unique constraints could be considered an implementation detail that should not be accessed directly.


User Comments


Bernhard Weißhuhn <bkw AT weisshuhn.de>
22 Apr 2003 16:11:56

The problems that arise from NULL being ignored in UNIQUE indexes can be avoided by an additional partial index:

Say you have this table:

  CREATE TABLE nulldemo (a int, b int NULL);

And you want only to have unique pairs in it, the following is not enough:

  CREATE UNIQUE INDEX idx1 ON nulldemo (a,b);

since b allows NULL-values. So you need another index to take care of these cases:

CREATE UNIQUE INDEX idx2 ON nulldemo (a) WHERE b IS NULL;

Add Comment

Please use this form to add your own comments regarding your experience with particular features of PostgreSQL, clarifications of the documentation, or hints for other users. Please note, this is not a support forum, and your IP address will be logged. If you have a question or need help, please see the faq, try a mailing list, or join us on IRC. Note that submissions containing URLs or other keywords commonly found in 'spam' comments may be silently discarded. Please contact the webmaster if you think this is happening to you in error.

In order to submit a comment, you must have a community account.

* Comment
 

* denotes required field

Privacy Policy | Project hosted by hub.org | Designed by tinysofa
Copyright © 1996 – 2007 PostgreSQL Global Development Group