For example, you may be restructuring the database, improving the readability, etc. Whatever the reason, table renaming is a common occurrence in relational database.
In this tutorial, we will walk you through the syntax and usage of the process of renaming a table in SQL.
Sample Data:
Before we dive into the process of renaming a table in SQL, let us set up a basic table with a sample data for demonstration purposes.
Let’s create a basic table that stores the network information:
device_id INT PRIMARY KEY,
device_name VARCHAR(50),
device_type VARCHAR(50),
ip_address VARCHAR(15),
mac_address VARCHAR(17)
);
This should create a table that contains the network information such as the device ID, device name, type, IP address, and MAC address.
Rename a Table in SQL
In SQL, we can rename a table using the ALTER TABLE statement followed by the RENAME TO clause.
We can express the syntax as shown in the following:
RENAME TO new_table_name;
It is good to ensure that the specified table exists in the database. Otherwise, the query returns an error.
Example Usage:
Consider the following example that demonstrates the use of the ALTER TABLE clause to rename the table from “network_devices” to “network_mapping”:
RENAME TO network_mapping;
This should rename the specified table to the new name.
Conclusion
In this post, we explored the ALTER TABLE and RENAME TO clause to rename an existing table to a new table.
NOTE: It is good to keep in mind that using this clause does not affect any object that references the table. For example, if you have any foreign constraints that reference the table, you have to manually adjust the values to reflect the new name.