From 27e29ba6427ea9d75b8fcb74242065f87a0de467 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Radan=20Skori=C4=87?= Date: Tue, 10 Oct 2023 10:53:12 +0200 Subject: [PATCH] Add missing sequence alteration step I was alerted to this omission by e-mail from Jeff Nettleton. When I was performing the change at Silverfin, the sequence was actually created as bigint so this was not needed. However, this is not guaranteed so it should be mentioned for completion. --- _posts/2022-02-23-zero-downtime-migration.markdown | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/_posts/2022-02-23-zero-downtime-migration.markdown b/_posts/2022-02-23-zero-downtime-migration.markdown index 1a8ee44..2be4023 100644 --- a/_posts/2022-02-23-zero-downtime-migration.markdown +++ b/_posts/2022-02-23-zero-downtime-migration.markdown @@ -1,7 +1,8 @@ --- layout: post title: "PostgreSQL zero-downtime migration of a primary key from int to bigint (with Ruby on Rails specific notes)!" -date: 2022-02-23 +date: 2022-02-23 +modified_date: 2023-10-10 categories: articles tags: postgresql rails --- @@ -232,6 +233,12 @@ ALTER SEQUENCE table_id_seq OWNED BY table.id; ALTER TABLE table ALTER COLUMN old_id DROP DEFAULT; ``` +If the sequence was created as an `int` sequence it will have an int value for its `MAXVALUE`. To take care of that run: +```sql +ALTER SEQUENCE table_id_seq AS bigint; +``` +If the sequence is already a `bigint`, this will not do anything so it is safe to run just to be sure. + Now finally you can move the primary key from the old to the new field. Normally adding a primary key constraint requires an underlying unique index to be built. However, you can tell it to use an existing unique index which makes the operation a fast metadata only change. This is also why it was important that we built this index before: ```sql ALTER TABLE table