File tree 2 files changed +27
-1
lines changed 2 files changed +27
-1
lines changed Original file line number Diff line number Diff line change @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
10
10
11
11
For a steady stream of TILs, [ sign up for my newsletter] ( https://crafty-builder-6996.ck.page/e169c61186 ) .
12
12
13
- _ 1484 TILs and counting..._
13
+ _ 1485 TILs and counting..._
14
14
15
15
---
16
16
@@ -703,6 +703,7 @@ _1484 TILs and counting..._
703
703
- [ A Better Null Display Character] ( postgres/a-better-null-display-character.md )
704
704
- [ Add Foreign Key Constraint Without A Full Lock] ( postgres/add-foreign-key-constraint-without-a-full-lock.md )
705
705
- [ 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 )
706
707
- [ Adding Composite Uniqueness Constraints] ( postgres/adding-composite-uniqueness-constraints.md )
707
708
- [ Aggregate A Column Into An Array] ( postgres/aggregate-a-column-into-an-array.md )
708
709
- [ Assumed Radius Of The Earth] ( postgres/assumed-radius-of-the-earth.md )
Original file line number Diff line number Diff line change
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 )
You can’t perform that action at this time.
0 commit comments