简体   繁体   中英

MySQL ALTER TABLE sort columns alphabetically

I am maintaining a legacy application with MySQL database with most of the tables having 20+ columns and few have 100+. To make the it friendlier I am trying to alter all the tables to arrange all the columns sorted alphabetically.

What would be the appropriate ALTER TABLE queries ?

There is no way for changing column order in a mysql table. However, you can create a new table with the columns in your order, using for example:

CREATE TABLE newtable SELECT a,b,c,d,e,f,g FROM old_table_name

This way, your newly created table will have columns in your defined order, and you can drop the old table and rename the newtable to old name.

In order to create the above mentioned query, you just need to get column names from your old table and sort them, to do that programatically you can use something like this:

SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA='database_name' AND TABLE_NAME = 'old_table_name' 
ORDER BY column_name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM