Skip to content

Commit dfe9c00

Browse files
committed
Add Add Unique Constraint Using Existing Index as a Postgres TIL
1 parent 3e34636 commit dfe9c00

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
1010

1111
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
1212

13-
_1484 TILs and counting..._
13+
_1485 TILs and counting..._
1414

1515
---
1616

@@ -703,6 +703,7 @@ _1484 TILs and counting..._
703703
- [A Better Null Display Character](postgres/a-better-null-display-character.md)
704704
- [Add Foreign Key Constraint Without A Full Lock](postgres/add-foreign-key-constraint-without-a-full-lock.md)
705705
- [Add ON DELETE CASCADE To Foreign Key Constraint](postgres/add-on-delete-cascade-to-foreign-key-constraint.md)
706+
- [Add Unique Constraint Using Existing Index](postgres/add-unique-constraint-using-existing-index.md)
706707
- [Adding Composite Uniqueness Constraints](postgres/adding-composite-uniqueness-constraints.md)
707708
- [Aggregate A Column Into An Array](postgres/aggregate-a-column-into-an-array.md)
708709
- [Assumed Radius Of The Earth](postgres/assumed-radius-of-the-earth.md)
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# Add Unique Constraint Using Existing Index
2+
3+
Adding a unique constraint to an existing column on a production table can
4+
block updates. If we need to avoid this kind of locking for the duration of
5+
index creation, then we can first create the index concurrently and then use
6+
that existing index to back the unique constraint.
7+
8+
```sql
9+
create index concurrently users_email_idx on users (email);
10+
11+
-- wait for that to complete
12+
13+
alter table users
14+
add constraint unique_users_email unique using index users_email_idx;
15+
```
16+
17+
First, we concurrently create the index. The time this takes will depend on how
18+
large the table is. That's the blocking time we are avoiding with this
19+
approach. Then once that completes we can apply a unique constraint using that
20+
preexisting index.
21+
22+
Note: if a non-unique value exists in the table for that column, adding the
23+
constraint will fail. You'll need to deal with that _duplicate_ value first.
24+
25+
[source](https://dba.stackexchange.com/questions/81627/postgresql-9-3-add-unique-constraint-using-an-existing-unique-index)

0 commit comments

Comments
 (0)