17

I'm looking to rename a column in PostgreSQL with no downtime. My code will depend on the column name so I'd like to duplicate the column with a new name along with the contents and data type of the existing column, then push the code changes before deleting the original column. Is there a Postgres command for duplicating a column with its contents into the same table?

3
  • Is the table/field being updated by SQL updates at the same time as the migration will happen? If so, copying a column will lose changes when changing over since updates will happen on the old field until the code changes over. Commented Jul 3, 2014 at 13:47
  • lock table, alter table, update table setting new col to old col value, drop col. Too bad postgres doesn't support 'MERGE'. Commented Jul 3, 2014 at 13:50
  • @JoachimIsaksson: The field only gets updated by a cron job, so lost writes won't be an issue. The only problem is that Django will look at the models file, see that there's a missing column name, and throw up an error as soon as it starts up. Commented Jul 3, 2014 at 13:57

1 Answer 1

34

I found a relatively simple way to do this in two commands:

ALTER TABLE mytable ADD COLUMN "new_column" <DATA TYPE STUFF FROM OLD COLUMN>;
UPDATE mytable SET new_column = old_column;

Didn't realise it would be this easy. I didn't lock the table as that column isn't used too frequently so a small slowdown would be okay.

Sign up to request clarification or add additional context in comments.

1 Comment

Incredible solution! This comment made my day. Thanks @benwad.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.