Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I specify both INDEX and UNIQUE INDEX?

Tags:

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); 
like image 406
Matt Huggins Avatar asked Dec 25 '10 21:12

Matt Huggins


People also ask

Do I need an index if I have a unique constraint?

Conclusion. Generally there is no functional difference between a unique index and a unique constraint.

How and when would you use unique key and unique index?

Unique Key: It is a constraint which imposes limitation on database. That limitation is it will not allow duplicate values . For example if you want to select one column as primary key it should be NOT NULL & UNIQUE. Unique Index: It is a index which improves the performance while executing queries on your data base.

Is Unique Key also an index?

Unique keys are indexes. If your values are guaranteed to be unique, this is the best choice. Unique Key: Unique Key enforces uniqueness of the column on which they are defined. Unique Key creates a non-clustered index on the column.

Do indexes need to be unique SQL?

So, when you create the clustered index - it must be unique. But, SQL Server doesn't require that your clustering key is created on a unique column. You can create it on any column(s) you'd like. Internally, if the clustering key is not unique then SQL Server will “uniquify” it by adding a 4-byte integer to the data.


1 Answers

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.

like image 159
Mark Byers Avatar answered Oct 04 '22 21:10

Mark Byers