Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance impact of adding unique constraint to existing postgres index

We have a fairly large table in a postgres and during some refactoring process we realized there was an Index on an existing UUID column but it was lacking a unique constraint.

Does anyone have any experience applying an ALTER TABLE ... ADD CONSTRAINT ala https://www.postgresql.org/docs/9.4/indexes-unique.html and what the runtime impact is?

Trying to evaluate the runtime impact of doing this live vs. taking downtime. We've tested it on db copies but it difficult to simulate production traffic load and just looking for something to check if anybody had experience.

like image 830
Selecsosi Avatar asked May 30 '19 15:05

Selecsosi


People also ask

Does unique constraint improve performance?

Of course the index created to enforce the unique constraint is a great source of performance improvement, too. Show activity on this post. A unique constraint will create an index. An index will drastically improve your query.

Does unique index improve performance Postgres?

Unique Indexes: These type of indexes are useful when you are focused on driving performance and data integrity. With a unique index, you ensure that your table has unique values for each row. It won't capture rows with the same values. As a result, you can look up your data very quickly.

Does unique index help in query performance?

In addition to enforcing the uniqueness of data values, a unique index can also be used to improve data retrieval performance during query processing.

Does adding a unique constraint create an index?

Yes, absolutely. A unique constraint creates a unique index.


1 Answers

To do it without downtime, you should do it in two steps:

  1.  CREATE UNIQUE INDEX CONCURRENTLY idx_name ON table_name (id);
    
  2.  ALTER TABLE table_name ADD CONSTRAINT constraint_name UNIQUE(id) 
     USING INDEX idx_name;
    
like image 90
Jeremy Avatar answered Oct 16 '22 10:10

Jeremy