SoFunction
Updated on 2025-03-02

MySQL rename table name implementation example

In MySQL, renaming table names can be done in two ways:RENAME TABLECommand or useALTER TABLEOrder. Below are examples of using these two methods.

Use RENAME TABLE

RENAME TABLEis the most direct way to rename a table. It can rename multiple tables at once, and the syntax is simple and intuitive.

Example

Suppose you have a name calledemployeestable, you want to rename it tostaff

RENAME TABLE employees TO staff;

This command willemployeesRename the table tostaff

Use ALTER TABLE

AlthoughALTER TABLEMainly used to modify table structure, but it can also be used to rename tables. useALTER TABLEWhen renaming a table, you need to specify the old table name first, and then useRENAME TOclause to specify the new table name.

Example

useALTER TABLERename the same tableemployeesarrivestaff

ALTER TABLE employees RENAME TO staff;

Things to note

  • Permissions: Make sure you have sufficient permissions to perform the rename operation.
  • Foreign key constraints: If there are foreign key constraints on the table, please make sure that these constraints do not cause problems before renaming.
  • Backup: It is best to back up the relevant data before making any structural changes.

Complete example

Let's show how to use it with a complete exampleRENAME TABLEandALTER TABLERename tables:

-- Create a sample table
CREATE TABLE employees (
    id INT AUTO_INCREMENT,
    name VARCHAR(50),
    position VARCHAR(50),
    hire_date DATE,
    PRIMARY KEY (id)
);

-- Insert some sample data
INSERT INTO employees (name, position, hire_date)
VALUES ('John Doe', 'Developer', '2023-01-01'),
       ('Jane Smith', 'Manager', '2023-02-15');

-- use RENAME TABLE Rename table
RENAME TABLE employees TO staff;

-- 或者use ALTER TABLE Rename table
-- ALTER TABLE employees RENAME TO staff;

-- Verify that the table name has been changed
DESCRIBE staff;

In this example, we first create a name calledemployeestable and insert some data into it. Then, we useRENAME TABLECommand renames the table tostaff. You can also choose to useALTER TABLECommand to achieve the same effect.

This is the end of this article about the implementation example of MySQL rename table name. For more related content on MySQL rename table name, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!