Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL query to rename and change column type with single query

Tags:

sql

postgresql

In PostgreSQL if I need to rename and change a column data type, I run two separate queries to do so.

To rename:

ALTER TABLE tblName RENAME <oldColumn> TO <newColumn>  

and to change column type:

ALTER TABLE tblName ALTER COLUMN <newColumn> <columnType>. 

But is there any way to do both of these works with a single query like the following MySQL query:

ALTER TABLE tblName CHANGE COLUMN <oldColumn> <newColumn> <columnType> 
like image 746
taufique Avatar asked Aug 20 '14 07:08

taufique


People also ask

How do I change the datatype of a column in PostgreSQL?

First, specify the name of the table to which the column you want to change belongs in the ALTER TABLE clause. Second, give the name of column whose data type will be changed in the ALTER COLUMN clause. Third, provide the new data type for the column after the TYPE keyword.

How do I change the column name in a PostgreSQL query?

The syntax to rename a column in a table in PostgreSQL (using the ALTER TABLE statement) is: ALTER TABLE table_name RENAME COLUMN old_name TO new_name; table_name.

How do I rename multiple columns in PostgreSQL?

First, specify the table, which contains the column you want to rename, after the ALTER TABLE clause. Second, provide the column name after the RENAME COLUMN clause. Third, give the new column name after the TO keyword.


2 Answers

In PostgreSQL, ALTER TABLE can take a series of operations. So:

ALTER TABLE <tablename> RENAME <oldcolumn> TO <newcolumn>; ALTER TABLE <tablename> ALTER COLUMN <columnname> TYPE <newtype>; 

is the same as

ALTER TABLE <tablename>    ALTER COLUMN <columnname> TYPE <newtype>   RENAME <oldcolumn> TO <newcolumn>; 

However... why? IIRC the rename won't cause a full-table scan, so there's no benefit over just doing the two statements separately, within one transaction. What problem are you actually trying to solve with this?

like image 54
Craig Ringer Avatar answered Sep 24 '22 17:09

Craig Ringer


PostgreSQL: Alter table column name and data-type:

ALTER TABLE <TableName>     ALTER [ COLUMN ] column [ SET DATA ] TYPE data_type [ COLLATE collation ] [ USING expression ]   RENAME [ COLUMN ] column TO new_column; 

See ALTER TABLE.

like image 36
jainvikram444 Avatar answered Sep 20 '22 17:09

jainvikram444