Description
The ALTER TABLE statement can be used to alter or modify an existing table.
- It can be used to add, modify, or delete table columns.
- It can be used to add and drop table constraints.
- It can be used to rename a table.
After creating a table, we may get into a situation where we need to modify the table definition of a table that is in use. In such situations, the ALTER TABLE statement comes handy to do such changes on an existing table without corrupting the table data.
Let's look at an example of the ALTER TABLE statement to rename a table.
Table Data
Before executing the query, consider the below table data.
customer_id | customer_name | address | city | country | postal_code |
1 | Maria Anders | Obere Str. 57 | Berlin | Germany | 12209 |
2 | Yoshi Nagase | 9-8 Sekimai Musashino-shi | Tokyo | Japan | 100 |
3 | Dominique Perrier | 25, rue Lauriston | Paris | France | 75016 |
4 | Martin Blank | Via Monte Bianco 34 | Turin | Italy | 10100 |
5 | Thomas Hardy | 89 Chiaroscuro Rd. | Portland | USA | 97219 |
Example
The below SQL ALTER TABLE statement renames the table from "customers" to "customer.
ALTER TABLE customers
RENAME customer;
After successful execution, the table "customers" will no more exist, and the new table "customer" contains the below data.
customer_id | customer_name | city | country | postal_code |
1 | Maria Anders | Berlin | Germany | 12209 |
2 | Yoshi Nagase | Tokyo | Japan | 100 |
3 | Dominique Perrier | Paris | France | 75016 |
4 | Martin Blank | Turin | Italy | 10100 |
5 | Thomas Hardy | Portland | USA | 97219 |
Overall
We now know how to use ALTER TABLE statement to rename a table.