Open In App

PostgreSQL – Rename Table

PostgreSQL has a RENAME clause that is used with the ALTER TABLE statement to rename the name of an existing table.

Syntax:
ALTER TABLE table_name
RENAME TO new_table_name; 

In the above syntax:



Attempting to rename a table that doesn’t exist leads to PostgreSQL raising an error. To rename multiple tables, one has to execute multiple ALTER TABLE RENAME TO statements. It’s not possible to do it in a single statement.
For the purpose of example let’s first create a table using the below statements and then we will attempt to rename it:

CREATE TABLE vendors (
    id serial PRIMARY KEY,
    name VARCHAR NOT NULL
);

Now check if the table has been successfully created using the below statement:



SELECT * FROM vendors;

Now that our table is ready, let’s jump into an example.

Example:
In this we will rename the vendors table to suppliers, using the following ALTER TABLE RENAME TO statement:

ALTER TABLE vendors RENAME TO suppliers;

Now we can verify if the name has been changed using the below statement:

SELECT * FROM suppliers;

Output:

Article Tags :