diff --git a/README.md b/README.md index fac631c..8b3b9be 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186). -_1484 TILs and counting..._ +_1485 TILs and counting..._ --- @@ -703,6 +703,7 @@ _1484 TILs and counting..._ - [A Better Null Display Character](postgres/a-better-null-display-character.md) - [Add Foreign Key Constraint Without A Full Lock](postgres/add-foreign-key-constraint-without-a-full-lock.md) - [Add ON DELETE CASCADE To Foreign Key Constraint](postgres/add-on-delete-cascade-to-foreign-key-constraint.md) +- [Add Unique Constraint Using Existing Index](postgres/add-unique-constraint-using-existing-index.md) - [Adding Composite Uniqueness Constraints](postgres/adding-composite-uniqueness-constraints.md) - [Aggregate A Column Into An Array](postgres/aggregate-a-column-into-an-array.md) - [Assumed Radius Of The Earth](postgres/assumed-radius-of-the-earth.md) diff --git a/postgres/add-unique-constraint-using-existing-index.md b/postgres/add-unique-constraint-using-existing-index.md new file mode 100644 index 0000000..fe024c4 --- /dev/null +++ b/postgres/add-unique-constraint-using-existing-index.md @@ -0,0 +1,25 @@ +# Add Unique Constraint Using Existing Index + +Adding a unique constraint to an existing column on a production table can +block updates. If we need to avoid this kind of locking for the duration of +index creation, then we can first create the index concurrently and then use +that existing index to back the unique constraint. + +```sql +create index concurrently users_email_idx on users (email); + +-- wait for that to complete + +alter table users + add constraint unique_users_email unique using index users_email_idx; +``` + +First, we concurrently create the index. The time this takes will depend on how +large the table is. That's the blocking time we are avoiding with this +approach. Then once that completes we can apply a unique constraint using that +preexisting index. + +Note: if a non-unique value exists in the table for that column, adding the +constraint will fail. You'll need to deal with that _duplicate_ value first. + +[source](https://dba.stackexchange.com/questions/81627/postgresql-9-3-add-unique-constraint-using-an-existing-unique-index)