Rename Table (MySQL Table & Views)
In MySQL, you can rename a table using the RENAME TABLE
command. This command allows you to change the name of a table, as well as move the table to a new database or schema. In this tutorial, we'll discuss how to rename a table in MySQL using the RENAME TABLE
command.
Syntax
The basic syntax for renaming a table in MySQL is as follows:
RENAME TABLE current_name TO new_name;
In this syntax, current_name
refers to the name of the table that you want to rename, and new_name
is the new name that you want to give the table.
If you want to move the table to a new database, you can specify the new database name before the table name, as follows:
RENAME TABLE current_database.current_name TO new_database.new_name;
Example
Let's say we have a table called employees
in the company
database, and we want to rename it to staff
. Here's how we can do it:
RENAME TABLE company.employees TO company.staff;
After running this command, the table will be renamed from employees
to staff
in the company
database.
Output
When we run the example code above, no output is displayed. However, if we query the company
database, we will see that the employees
table has been renamed to staff
.
Explanation
In the example above, we used the RENAME TABLE
command to rename the employees
table to staff
in the company
database. We specified the old table name (employees
) and the new table name (staff
) in the command, along with the database name (company
).
Use
Renaming a MySQL table can be useful when you want to change the name of a table to make it more meaningful, or when you want to move the table to a different database or schema.
Important Points
- When renaming a table, make sure that no other tables, views, or procedures depend on the renamed table.
- If you have foreign key constraints on the table, you may need to update them after renaming the table.
- When moving a table to a different database, make sure that the target database exists.
Summary
In this tutorial, we discussed how to rename a table in MySQL using the RENAME TABLE
command. We covered the syntax, example, output, explanation, use, and important points of renaming a MySQL table. With this knowledge, you can now rename MySQL tables to better suit your needs or move them to other databases or schemas.