Skip to content

Commit

Permalink
Add missing sequence alteration step
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
radanskoric committed Oct 10, 2023
1 parent 92e777b commit 27e29ba
Showing 1 changed file with 8 additions and 1 deletion.
9 changes: 8 additions & 1 deletion _posts/2022-02-23-zero-downtime-migration.markdown
Original file line number Diff line number Diff line change
@@ -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
---
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit 27e29ba

Please sign in to comment.