Rename Table in PostgreSQL
Use the ALTER TABLE RENAME TO statement to change name of the existing table.
When you rename the table and give it a new name, Postges will automatically update all its dependent database objects like procedures, functions, views, foreign key constraints etc.
Postgres will raise an error If you try to rename a table that does not exists. Use IF EXISTS
clause to prevent error and ignore the ALTER statement if a table does not exists.
ALTER TABLE IF EXISTS <table_name>
RENAME TO <new_table_name>;
Consider that you have the following person table.
CREATE TABLE person(
Id INT PRIMARY KEY,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
gender CHAR(1),
birthdate DATE,
email VARCHAR(100)
);
To rename from person to employee, use the following ALTER TABLE statement:
ALTER TABLE person
RENAME TO employee;
The above will change the name from person to employee, as shown below.