PostgreSQL RENAME COLUMN: Renaming a column
Summary: in this tutorial, you will learn how to use the PostgreSQL RENAME COLUMN
clause in the ALTER TABLE
statement to rename one or more columns of a table.
Introduction to PostgreSQL RENAME COLUMN clause
To rename a column of a table, you use the ALTER TABLE
statement with RENAME COLUMN
clause as follows:
In this statement:
- First, specify the name of the table that contains the column which you want to rename after the
ALTER TABLE
clause. - Second, provide the name of the column that you want to rename after the
RENAME COLUMN
keywords. - Third, specify the new name for the column after the
TO
keyword.
The COLUMN
keyword in the statement is optional therefore you can omit it like this:
For some reason, if you try to rename a column that does not exist, PostgreSQL will issue an error. Unfortunately, PostgreSQL does not support the IF EXISTS
option for the RENAME
clause.
To rename multiple columns, you execute the ALTER TABLE RENAME COLUMN
statement multiple times, one column at a time:
If you rename a column referenced by other database objects such as views, foreign key constraints, triggers, and stored procedures, PostgreSQL will automatically change the column name in the dependent objects.
PostgreSQL RENAME COLUMN examples
Let’s take some examples of using the ALTER TABLE RENAME COLUMN
statement to rename a column.
Setting up sample tables
First, create two new tables customers
and customer_groups
.
Then, create a new view named customer_data
based on the customers
and customer_groups
tables.
1) Renaming one column example
The following statement uses the ALTER TABLE RENAME COLUMN
statement to rename the email
column of the customers
table to contact_email
:
2) Renaming a column that has dependent objects example
This example uses the ALTER TABLE RENAME COLUMN
statement to change the name
column of the customer_groups
table to group_name
:
Note that the name column is used in the customer_data
view.
Now, you can check whether the change in the name
column was cascaded to the customer_data
view:
Output:
The output indicates that the name
column has been changed to group_name
.
3) Using multiple RENAME COLUMN statements to rename multiple columns example
These statements rename two columns name
and phone
of the customers
table to customer_name
and contact_phone
respectively:
Summary
- Use the PostgreSQL
ALTER TABLE...RENAME COLUMN
statement to rename a column.