How to rearrange MySQL columns?

Mysql

Mysql Problem Overview


I need to move the position of existing columns (for better visibility).

How can this be done without affecting the data?

Mysql Solutions


Solution 1 - Mysql

Modify also works. Have a look:

ALTER TABLE foo MODIFY bar bartype AFTER baz;

Solution 2 - Mysql

The only way I know is to change the column. You would first extract your column definition using SHOW CREATE TABLE and issue an ALTER TABLE:

ALTER TABLE foo
CHANGE COLUMN bar
bar COLUMN_DEFINITION_HERE
FIRST;

Or if you want it after a certain other column:

... AFTER OTHER_COLUMN;

Solution 3 - Mysql

  1. Alter Table table_name modify column_name column_datatype first;
  2. Alter Table table_name modify column_name column_datatype After other_column_name;

Solution 4 - Mysql

Based on @VKGS answer:

If your table called language is:

|      description    |         name     |
|---------------------|------------------|
|      fbi agent      |         jane     |
|---------------------|------------------|
|      mi6 agent      |         kurt     |
|---------------------|------------------|

And you want to make the column name the first column or before description, execute this:

ALTER TABLE language MODIFY description varchar(100) AFTER name;

Don't forget type of the column.

Solution 5 - Mysql

Here is the sql query:

ALTER TABLE table_name MODIFY COLUMN misplaced_column Column-definition AFTER other_column;

Here in Column-definition is full column definition. To see the column definition if you are using phpMyAdmin click on structure tab. Then click on change link on desired column. Then without modifying any thing click save. It will show you the sql. Copy the sql and just add AFTER other_column at the end.

If you like to bring the misplaced_column to the first position then:

ALTER TABLE table_name MODIFY COLUMN misplaced_column Column-definition FIRST;

Solution 6 - Mysql

Go to Structure and click Move Columns and then just drag the columns to rearrange.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionYetiView Question on Stackoverflow
Solution 1 - MysqlvkGunasekaranView Answer on Stackoverflow
Solution 2 - MysqlsoulmergeView Answer on Stackoverflow
Solution 3 - MysqlshubhamView Answer on Stackoverflow
Solution 4 - MysqlJRichardszView Answer on Stackoverflow
Solution 5 - Mysqlzahid9iView Answer on Stackoverflow
Solution 6 - MysqlHassan JafferView Answer on Stackoverflow