23

I have an index in my PostgreSQL 9.3 database:

CREATE INDEX index_foos_on_bar_and_baz ON foos USING btree (bar, baz);

(from a schema migration using Ruby on Rails)

The index is present and made things faster. Now that I've cleaned up duplicate foos, I'd like to make this index unique:

CREATE UNIQUE INDEX index_foos_on_bar_and_baz ON foos USING btree (bar, baz);

Is there a way to alter the existing index and make it unique? Or is it easier/faster to delete the existing index and create a new, unique one?

2 Answers 2

23

There is no way to change an index to unique index. You can see what you can change to index at alter index document.

In this case you need to drop and create new unique index.

Sign up to request clarification or add additional context in comments.

Comments

-4

You can alter an index to add the "UNIQUE" constraint with:

 ALTER TABLE distributors 
 ADD CONSTRAINT dist_id_zipcode_key
 UNIQUE (dist_id, zipcode);

See the official documentation here: https://www.postgresql.org/docs/current/sql-altertable.html

3 Comments

How does this alter the existing index? It seems to just create a new unique constraint.
This looks like it creates both the INDEX and UNIQUE constraint on it, pretty cool. Is this expected behavior? Also , the UNIQUE constraint must be dropped to remove the INDEX - you cannot directly remove the INDEX as postgres throws an error because the CONSTRAINT is dependent on the INDEX
When a unique constraint or primary key is defined for a table, PostgreSQL automatically creates a unique index, but your answer is incorrect for this question because it creates a new unique index, and the table now has two indexes, the first of which is no longer required.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.