PostgreSQL query to rename and change column type with single query

SqlPostgresql

Sql Problem Overview


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>

Sql Solutions


Solution 1 - Sql

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?

Solution 2 - Sql

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontaufiqueView Question on Stackoverflow
Solution 1 - SqlCraig RingerView Answer on Stackoverflow
Solution 2 - Sqljainvikram444View Answer on Stackoverflow