Home » Mysql » How to rearrange Mysql columns?

How to rearrange Mysql columns?

Posted by: admin November 1, 2017 Leave a comment

Questions:

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

How can this be done without affecting the data?

Answers:

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;

Questions:
Answers:

Modify also works. Have a look:

ALTER TABLE foo MODIFY bar bartype AFTER baz;

Questions:
Answers:
  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;
Questions:
Answers:

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 withour modifyig any things click save. It will show you the sql. Copy the sql and just add *AFTER other_column* at the end. It will be all.

If you like to bring the *misplaced_column* to the first position then
ALTER TABLE table_name MODIFY COLUMN misplaced_column Column-definition FIRST;

However, It seems it is a duplicate question.