Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Duplicating column to same table in PostgreSQL

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?

like image 843
benwad Avatar asked Jul 03 '14 13:07

benwad


People also ask

Can a table have duplicate columns?

In fact, the SQL Standard specifies that there be an implementation dependent way to ensure the result of a table expression does not implicitly have duplicate column names (but as you point out in the question this does not perclude the user from explicitly using duplicate AS clauses).

How do you replicate a column in SQL?

Using SQL Server Management StudioOpen the table with columns you want to copy and the one you want to copy into by right-clicking the tables, and then clicking Design. Click the tab for the table with the columns you want to copy and select those columns. From the Edit menu, click Copy.

How do I clone a table in PostgreSQL?

To copy a table with partial data from an existing table, users can use the following statement: Syntax: CREATE TABLE new_table AS SELECT * FROM existing_table WHERE condition; The condition in the WHERE clause of the query defines which rows of the existing table will be copied to the new table.


1 Answers

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.

like image 155
benwad Avatar answered Sep 28 '22 03:09

benwad