This guide will showcase how to rename a column in MySQL.
Renaming a column in MySQL
In MySQL, a database generally consists of multiple tables containing rows and columns that hold various data. For demonstration, we will rename the column name of a particular table.
For demonstration, I’ll be using this sample database. It’s a very big database that should suffice for almost any testing situation. For convenience, I’ll use phpMyAdmin to access the database and run queries. Learn more about installing and configuring phpMyAdmin and MySQL.
Basic structure
To rename a column, the query structure will look like this.
If there are multiple columns to be renamed, we can do that in a single query as well. In such a case, the query structure will look like this.
Alternatively, if you want to rename a table, then the query structure will look like this.
You can also rename multiple tables in a single go.
MySQL also allows using RENAME between multiple databases.
Renaming table column
Let’s have a look at the sample database table countries.
From this table, let’s rename country_name (varchar(40)) to country_label (varchar(40)). The query will look something like this.
Verify the change.
Renaming multiple columns
We’ll be renaming multiple columns in the table countries in the next example. Let’s change country_id to country_code, country_label to country_name, and region_id to region_code.
CHANGE country_id country_code char(2),
CHANGE country_label country_name varchar(40),
CHANGE region_id region_code int;
Verify the changes.
Renaming tables
Now, let’s try renaming the table. We’ll be renaming the table countries to independent_regions. First, note the current table names.
Run the following query to rename the target table.
Verify the change.
Renaming multiple tables
Now, let’s try changing multiple table names at the same time. Make a note of all the current tables.
Next, run the following query.
countries TO independent_regions,
jobs TO assigned_tasks,
departments TO sections;
Verify the changes.
Final thoughts
Congratulations! You’ve successfully renamed an existing column in MySQL. This tutorial also showcases renaming an existing table. For both renaming columns and tables, you need to understand the fundamentals of the statement ALTER TABLE.
Every MySQL table is based on a key design. In MySQL terminology, it’s known as a schema. It contains the necessary data about the pattern of the data placement in the table. This guide explores the concept of schema with practical examples.
Happy computing!