# ALTER TABLE ... RENAME TO

The `RENAME TO` statement is part of `ALTER TABLE`, and changes the name of a table. It can also be used to move a table from one database to another.

Note:

It is not possible to rename a table referenced by a view. For more details, see View Dependencies.

Note:

This statement performs a schema change. For more information about how online schema changes work in CockroachDB, see Online Schema Changes.

## Required privileges

The user must have the `DROP` privilege on the table and the `CREATE` on the parent database. When moving a table from one database to another, the user must have the `CREATE` privilege on both the source and target databases.

## Synopsis

## Parameters

Parameter | Description
--- | ---
`IF EXISTS` | Rename the table only if a table with the current name exists; if one does not exist, do not return an error.
`current_name` | The current name of the table.
`new_name` | The new name of the table, which must be unique within its database and follow these identifier rules. When the parent database is not set as the default, the name must be formatted as `database.name`. The `UPSERT` and `INSERT ON CONFLICT` statements use a temporary table called `excluded` to handle uniqueness conflicts during execution. It's therefore not recommended to use the name `excluded` for any of your tables.

## Viewing schema changes

This schema change statement is registered as a job. You can view long-running jobs with `SHOW JOBS`.

## Examples

### Rename a table

    > SHOW TABLES FROM db1;

    +------------+
    | table_name |
    +------------+
    | t1         |
    | t2         |
    +------------+
    (2 rows)

    > ALTER TABLE db1.t1 RENAME TO db1.t3

    > SHOW TABLES FROM db1;

    +------------+
    | table_name |
    +------------+
    | t2         |
    | t3         |
    +------------+
    (2 rows)

To avoid an error in case the table does not exist, you can include `IF EXISTS`:

    > ALTER TABLE IF EXISTS db1.table1 RENAME TO db1.table2;

### Move a table

To move a table from one database to another, use the above syntax but specify the source database after `ALTER TABLE` and the target database after `RENAME TO`:

    > SHOW TABLES FROM db1;

    +------------+
    | table_name |
    +------------+
    | t2         |
    | t3         |
    +------------+
    (2 rows)

    > SHOW TABLES FROM db2;

    +------------+
    | table_name |
    +------------+
    +------------+
    (0 rows)

    > ALTER TABLE db1.t3 RENAME TO db2.t3;

    > SHOW TABLES FROM db1;

    +--------+
    | Table  |
    +--------+
    | table2 |
    +--------+

    > SHOW TABLES FROM db2;

    +------------+
    | table_name |
    +------------+
    | t3         |
    +------------+
    (1 row)

## See also

- `CREATE TABLE`
- `ALTER TABLE`
- `SHOW TABLES`
- `DROP TABLE`
- `SHOW JOBS`
- Other SQL Statements