PostgreSQL Rename Table: A Step-by-Step Guide
Summary: in this tutorial, you will show how to rename a table using the PostgreSQL ALTER TABLE RENAME TO
statement.
Introduction to PostgreSQL RENAME TABLE statement
To change the name of an existing table, you use the ALTER TABLE... RENAME TO
statement as follows:
In this statement:
- First, specify the name of the table which you want to rename after the
ALTER TABLE
clause. - Second, assign the new table name after the
RENAME TO
clause.
If you rename a table that does not exist, PostgreSQL will issue an error.
To avoid the error, you can use the the IF EXISTS
option:
In this case, if the table_name
does not exist, PostgreSQL will issue a notice instead.
To rename multiple tables, you have to execute multiple ALTER TABLE ... RENAME TO
statements. It’s not possible to rename multiple tables using a single ALTER TABLE
statement.
PostgreSQL rename table examples
Let’s take some examples of using the ALTER TABLE ... RENAME TO
statement.
1) Basic PostgreSQL rename table statement example
First, create a new table called vendors
for the demonstration purpose:
Second, describe the vendors
table using the \d
command in psql
:
Output:
Third, change the name of the vendors
table to suppliers
using the ALTER TABLE...RENAME TO
statement:
Finally, describe the suppliers
table:
Notice that the name of the table changed but the sequence (vendors_id_seq
) remains intact.
1) Renaming a table that has dependent objects
First, create new tables called customers
and groups
:
Second, create a view based on the customers
and customer_groups
tables:
When you rename a table, PostgreSQL will automatically update its dependent objects such as foreign key constraints, views, and indexes.
Third, rename the customer_groups
table to groups
:
Fourth, verify the foreign key constraint in the customers
table by showing the table via \d
command in psql
:
Output:
The output indicates that the foreign key constraint was updated and referenced the groups
table instead of the customer_groups
table.
Fifth, show the customer_data
view in psql:
Output:
The output shows that the supplier_groups
table in the SELECT
statement of the view was also updated to groups
table.
Summary
- Use the
ALTER TABLE ... RENAME TO
statement to rename a table.