How to change the column position of MySQL table without losing column data?
MysqlSqlMysql Problem Overview
I want to change the column positions of my database table without losing data.
For example:
Current table:
+----+------+-------+----------+
| id | name | email | password |
+----+------+-------+----------+
to
+----+----------+------+-------+
| id | password | name | email |
+----+----------+------+-------+
Mysql Solutions
Solution 1 - Mysql
Try this:
ALTER TABLE table_name MODIFY password varchar(20) AFTER id
Solution 2 - Mysql
Hearaman's answer is correct; but if you are using phpMyAdmin, there is a visual and practical way to do that.
- Open the table
- Choose the "Structure" tab
- Click on "Move columns"
- Drag and drop column names
Solution 3 - Mysql
If you are using MySQL workbench,
- Right-click on table
- Alter table
- drag columns and re-order
- click apply and finish
Solution 4 - Mysql
Also, you can do it like this:
ALTER TABLE table_name CHANGE COLUMN column_name column_name data_type AFTER another_column_name;
Solution 5 - Mysql
You can use modify/change keyword.
ALTER TABLE [table] CHANGE COLUMN [column] [column] [column definition] AFTER [column]
ALTER TABLE [table] MODIFY COLUMN [column] [column definition] AFTER [column]
Eg:
ALTER TABLE table_name MODIFY password varchar(20) AFTER id
ALTER TABLE table_name MODIFY password varchar(20) varchar(20) AFTER id
Solution 6 - Mysql
If you are like me, using MySQL workbench and got lost trying to implement @Mohemmed Niyaz answer, you can follow these steps,
- On your top left, click Schemas
- find and select your database, then find and select the table you want to modify
- When you hover over the table name you would see three icons, click on settings (that is the one in the middle) or you can right-click and select
Alter Table
, - then click on the column and drag it to the position you want your column to be.
- on your bottom right you will see apply (click and apply).