An application in production evolves by adding new features. You may also detect inconsistencies from previous developments that you want to improve, such as the naming in your database schema or adjustments in casing.
You can rename columns in MySQL easily and this tutorial shows you how.
MySQL Series Overview
- Truncate a Foreign Key Constrained Table
- Add Days to a Datetime
- Find Value in Column with Comma-Separated Values
- Ideas to Debug High-Load Situations
- Rename a Column
- Order By Columns Whichever is Not Null
- Add New Column After an Existing Column (Coming soon)
- Add New Column as the First Column in a Table (Coming soon)
MySQL 8.x (and later)
You can rename columns in MySQL 8.0 (and above) using the ALTER TABLE
command. The following syntax renames a column:
ALTER TABLE users RENAME COLUMN first_name TO firstname;
The ALTER TABLE … RENAME COLUMN
command is readable and understandable. It changes the column name but doesn’t allow you to the definition. For example, if you need to change the length of the VARCHAR field, you need to use the ALTER TABLE … CHANGE
syntax. Read the next section for MySQL 5.6/5.7 for that syntax.
MySQL 5.6 and 5.7
In MySQL 5.x you must use the ALTER TABLE … CHANGE
syntax to rename a column. You must provide the full column definition:
ALTER TABLE users CHANGE first_name firstname VARCHAR(100) NOT NULL;
# change column name + definition
ALTER TABLE users CHANGE first_name firstname VARCHAR(150) NOT NULL;
Notice: any unstated attribute from the existing column definition goes back to default if you’re not restating the full column definition when renaming a column. For example, omitting NOT NULL
in the definition will result in allowing NULL values.
That’s it!