Should I specify both INDEX and UNIQUE INDEX?

Matt Huggins picture Matt Huggins · Dec 25, 2010 · Viewed 8.5k times · Source

On one of my PostgreSQL tables, I have a set of two fields that will be defined as being unique in the table, but will also both be used together when selecting data. Given this, do I only need to define a UNIQUE INDEX, or should I specify an INDEX in addition to the UNIQUE INDEX?

This?

CREATE UNIQUE INDEX mytable_col1_col2_idx ON mytable (col1, col2);

Or this?

CREATE UNIQUE INDEX mytable_col1_col2_uidx ON mytable (col1, col2);
CREATE INDEX mytable_col1_col2_idx ON mytable (col1, col2);

Answer

Mark Byers picture Mark Byers · Dec 25, 2010

If you have a UNIQUE INDEX then you don't also need the INDEX - it would be redundant. A UNIQUE INDEX is both a unique constraint and an index that can be used like any other index.

From the documentation:

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. One should, however, be aware that there's no need to manually create indexes on unique columns; doing so would just duplicate the automatically-created index.

Emphasis mine.