File tree Expand file tree Collapse file tree 2 files changed +34
-1
lines changed Expand file tree Collapse file tree 2 files changed +34
-1
lines changed Original file line number Diff line number Diff line change @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
1010
1111For a steady stream of TILs, [ sign up for my newsletter] ( https://crafty-builder-6996.ck.page/e169c61186 ) .
1212
13- _ 1329 TILs and counting..._
13+ _ 1330 TILs and counting..._
1414
1515---
1616
@@ -613,6 +613,7 @@ _1329 TILs and counting..._
613613- [ Between Symmetric] ( postgres/between-symmetric.md )
614614- [ Capitalize All The Words] ( postgres/capitalize-all-the-words.md )
615615- [ Change The Current Directory For psql] ( postgres/change-the-current-directory-for-psql.md )
616+ - [ Change The Owner Of A Sequence] ( postgres/change-the-owner-of-a-sequence.md )
616617- [ Check If The Local Server Is Running] ( postgres/check-if-the-local-server-is-running.md )
617618- [ Check If User Role Exists For Database] ( postgres/check-if-user-role-exists-for-database.md )
618619- [ Check Table For Any Oprhaned Records] ( postgres/check-table-for-any-orphaned-records.md )
Original file line number Diff line number Diff line change 1+ # Change The Owner Of A Sequence
2+
3+ Sequence ownership is one of those things in PostgreSQL that is just under the
4+ surface and so it is easy to not know about it. If, however, you are doing a
5+ live migration where you are swapping out a column or entire table, you'll need
6+ to know about it.
7+
8+ For instance, consider migrating a primary key column from ` int ` to ` bigint ` .
9+ Let's say you construct and backfill the new ` bigint ` column and then swap it
10+ out with the ` int ` column.
11+
12+ Run a sequence ownership query like [ the ones discussed in this
13+ article] ( https://sadique.io/blog/2019/05/07/viewing-sequence-ownership-information-in-postgres/ )
14+ and you'll see that the original ` int ` column still owns the sequence.
15+
16+ If you try to drop ` old_id ` , you'll fortunately get a warning from Postgres:
17+
18+ ``` sql
19+ alter table cats drop column old_id;
20+ ERROR: cannot drop column old_id of table cats because other objects depend on it
21+ DETAIL: default value for column id of table cats depends on sequence cats_id_seq
22+ HINT: Use DROP ... CASCADE to drop the dependent objects too.
23+ ```
24+
25+ The ` DROP ... CASCADE ` suggestion is not the thing to do here. Instead, you'll
26+ want to update the ownership of the sequence to the _ new_ ` id ` column:
27+
28+ ``` sql
29+ alter sequence cats_id_seq owned by cats .id ;
30+ ```
31+
32+ [ source] ( https://www.postgresql.org/docs/current/sql-altersequence.html )
You can’t perform that action at this time.
0 commit comments