How to rename a table inside a schema?

Postgresql

Postgresql Problem Overview


I'm using PostgreSQL 9.x, I want to rename a table. This SQL code:

CREATE TABLE new (id int);
ALTER TABLE new RENAME TO old;
DROP TABLE old;

renames the table correctly. But this SQL code:

CREATE SCHEMA domain;
CREATE TABLE domain.old (id int);
ALTER TABLE domain.old RENAME TO domain.new;

fails, with error:

> ERROR: syntax error at or near "."

The "." underlined is the one between 'domain' and 'new'

Postgresql Solutions


Solution 1 - Postgresql

One way to do this:

ALTER TABLE domain.old RENAME TO new

Other way:

SET search_path TO domain;
ALTER TABLE old RENAME TO new;

Documentation for search_path.

Solution 2 - Postgresql

SET search_path TO domain;
ALTER TABLE IF EXISTS old_table_name RENAME TO new_table_name;

Solution 3 - Postgresql

  1. Switch to your database
machine$\c my_database
  1. Tename the db
my_databse=# alter table old_name rename to new_name;

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
QuestioncomteView Question on Stackoverflow
Solution 1 - PostgresqlBohuslav BurghardtView Answer on Stackoverflow
Solution 2 - PostgresqlsamznaView Answer on Stackoverflow
Solution 3 - Postgresql7guyoView Answer on Stackoverflow