SQL Standard

Change the Table Name in SQL

In SQL, tables are some of the most fundamental and essential components of a relational database. However, like anything in the development world, you may encounter such instances where you need to change the name of an existing table.

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:

CREATE TABLE network_devices (

  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:

ALTER TABLE current_table_name

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”:

ALTER TABLE network_devices

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.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list