247

Currently I am having the following MySQL table: Employees (empID, empName, department);

I want to change the table to the following: Employees (empID, department, empName);

How can this be done using ALTER statements?

Note: I want to change only column positions.

sumit
  • 10,935
  • 24
  • 65
  • 83
  • 1
    May I ask why? The column order is pretty much just an esthetic problem... – deceze Jul 24 '11 at 07:08
  • 10
    @deceze perhaps not -- it defines the order of values in a `SELECT *` statement. (Granted, if the order of values is important, one should list them explicitly in the statement, but perhaps OP doesn't have total control here.) – Ted Hopp Jul 24 '11 at 07:12
  • 1
    I know it does not affect anything. My original table is having many columns so I just added 3 columns which are added in the last. But I want them to display at positions 3-4-5 to ease the use of `SELECT` statement – sumit Jul 24 '11 at 07:16
  • Ted Hopp's answer is spot on. However, I would like to direct iSumitG to this link: http://www.parseerror.com/sql/select*isevil.html – TehShrike Jul 24 '11 at 07:26
  • You should always identify your columns by name, not by their order. Hence order shouldn't matter. – deceze Jul 24 '11 at 07:31
  • 7
    @iSumitG: Also note that the `AFTER column` can be used with `ALTER TABLE ADD column` as well. (for next time you add some fields.) – ypercubeᵀᴹ Jul 24 '11 at 07:40
  • 3
    If loading a mysql dump, it uses insert into values. So if you for instance, you're loading data from prod into dev and the columns are out of order, you'll get an error. That's why one might want to do this. – Hooray Im Helping May 15 '13 at 17:48
  • Note about SQL: I would suggest to remove the SQL tag for this question. Unlike MySQL, it is not possible to change the order with a script and therefore this response is not relevant to SQL users. To do this with SQL, open SMSS, right click on the table, and select "design" (modify) then slide the column to the right position. Then save (ctrl+S). SMSS will rebuild the entire table to order the columns accordingly. – Yann Aug 15 '14 at 05:58
  • possible duplicate of [How to rearrange Mysql columns?](http://stackoverflow.com/questions/2934312/how-to-rearrange-mysql-columns) – Pang Aug 22 '14 at 09:36
  • @Yann You're badly confusing [SQL](https://en.wikipedia.org/wiki/SQL) with some server by some well-known company. I *do* use SQL for years, but I've never heart about SMSS or other tools related to the server you mean. – maaartinus Feb 25 '16 at 02:04
  • @maaartinus, not sure to understand, I was just saying that it is not possible to do that using SQL syntax, but it is possible with MySQL? So the SQL tag in the question is misleading.. SSMS stands for SQL Server management studio (Microsoft). This is not SQL, but I assume that this is one interface that most people use. – Yann Feb 26 '16 at 03:37
  • @Yann While this syntax is not part of SQL-2011, it's still called *SQL*, at least for a lack of a better word. Other databases support such a syntax too, e.g. [Firebird](http://www.firebirdsql.org/refdocs/langrefupd20-alter-table.html#langrefupd20-at-position). So the SQL tag is IMHO right, as commands send to a DB are called SQL and no single DB implements the standard exactly. – maaartinus Feb 26 '16 at 11:03
  • Great question! In case anyone isn't sure, [*yes, column order does affect performance!*](https://stackoverflow.com/a/64390258/2430549) – HoldOffHunger Mar 03 '21 at 20:40

6 Answers6

410

If empName is a VARCHAR(50) column:

ALTER TABLE Employees MODIFY COLUMN empName VARCHAR(50) AFTER department;

EDIT

Per the comments, you can also do this:

ALTER TABLE Employees CHANGE COLUMN empName empName VARCHAR(50) AFTER department;

Note that the repetition of empName is deliberate. You have to tell MySQL that you want to keep the same column name.

You should be aware that both syntax versions are specific to MySQL. They won't work, for example, in PostgreSQL or many other DBMSs.

Another edit: As pointed out by @Luis Rossi in a comment, you need to completely specify the altered column definition just before the AFTER modifier. The above examples just have VARCHAR(50), but if you need other characteristics (such as NOT NULL or a default value) you need to include those as well. Consult the docs on ALTER TABLE for more info.

Audwin Oyong
  • 2,247
  • 3
  • 15
  • 32
Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
  • 7
    Just a note: MODIFY is not supported until version 4. – Erre Efe Jul 24 '11 at 07:09
  • 4
    You need to repeat the column name, because the syntax assumes you may want to change the column name. Eg: ALTER TABLE Employees CHANGE COLUMN empName empName varchar(50) AFTER department; – brianjcohen Nov 14 '12 at 16:30
  • Have in mind that changed order will not be reflected in database SQL dumps. – skalee Jun 16 '15 at 04:07
  • 3
    @SalehEnamShohag - Yes, according to [the docs](http://dev.mysql.com/doc/refman/5.7/en/alter-table.html), the `COLUMN` keyword is optional in `ALTER TABLE` statements. I prefer to use it because I think it makes the statement more readable. – Ted Hopp Mar 29 '16 at 14:22
  • Is it mandatory to give datatype information? If I'm just rearranging a column without changing its default value, constraint etc, why do I need to mention its datatype since I don't need any change of datatype after rearranging ? – learner Apr 09 '16 at 04:13
  • @learner -- Yes, it's required. The docs (see my previous comment) indicates that the column definition is not optional for either `MODIFY COLUMN` or `CHANGE COLUMN`. I think that's because the most common use for those commands is to change the column definition. – Ted Hopp Apr 10 '16 at 01:50
  • 1
    Works fine for me, in my case I needed define that the column was `NOT NULL DEFAULT 1`, this is done just after the column type in the example `VARCHAR(50)` – Luiz Rossi Aug 03 '16 at 17:31
  • @LuizRossi - Excellent point. I updated my answer to incorporate this info. – Ted Hopp Aug 03 '16 at 17:47
82

Change column position:

ALTER TABLE Employees 
   CHANGE empName empName VARCHAR(50) NOT NULL AFTER department;

If you need to move it to the first position you have to use term FIRST at the end of ALTER TABLE CHANGE [COLUMN] query:

ALTER TABLE UserOrder 
   CHANGE order_id order_id INT(11) NOT NULL FIRST;
Igor Kostin
  • 821
  • 6
  • 4
  • 27
    Mentioning how to move it to first position was quite usefull – Tristian Jul 10 '13 at 00:22
  • 2
    Any idea how this would perform on a large table? Is it just changing some metadata, or does it actually have to reorganize data on the disk? – Kip Nov 12 '15 at 16:01
  • 8
    nevermind, answered my own question by trying it on a table i had with 3.9M rows, it took about 2 minutes. so it is definitely doing more than just swapping some metadata. – Kip Nov 12 '15 at 16:16
  • I was search for a `BEFORE` keyword. But `FIRST` was the solution. – Avatar Apr 05 '21 at 05:20
20

phpMyAdmin provides a GUI for this within the structure view of a table. Check to select the column you want to move and click the change action at the bottom of the column list. You can then change all of the column properties and you'll find the 'move column' function at the far right of the screen.

Of course this is all just building the queries in the perfectly good top answer but GUI fans might appreciate the alternative.

my phpMyAdmin version is 4.1.7

  • 3
    The question asks specifically "How can this be done using ALTER statements". Not everyone running MySQL uses phpMyAdmin. – Caleb Mar 05 '15 at 00:26
  • 3
    I learn much of what I do nowadays at a command line from observing the query output from GUI tools like phpMyAdmin. I'm happy for this post to get as many downvotes as ppl see fit on this basis: 1 person will see this, get their job done in an environment they feel comfortable in, learn a little and move on. –  Mar 05 '15 at 09:09
  • for this action phpmyadmi doens't show the command doing the action . Not found it – Tebe Dec 03 '16 at 15:54
2

I had to run this for a column introduced in the later stages of a product, on 10+ tables. So wrote this quick untidy script to generate the alter command for all 'relevant' tables.

SET @NeighboringColumn = '<YOUR COLUMN SHOULD COME AFTER THIS COLUMN>';

SELECT CONCAT("ALTER TABLE `",t.TABLE_NAME,"` CHANGE COLUMN `",COLUMN_NAME,"` 
`",COLUMN_NAME,"` ", c.DATA_TYPE, CASE WHEN c.CHARACTER_MAXIMUM_LENGTH IS NOT 
NULL THEN CONCAT("(", c.CHARACTER_MAXIMUM_LENGTH, ")") ELSE "" END ,"  AFTER 
`",@NeighboringColumn,"`;")
FROM information_schema.COLUMNS c, information_schema.TABLES t
WHERE c.TABLE_SCHEMA = '<YOUR SCHEMA NAME>'
AND c.COLUMN_NAME = '<COLUMN TO MOVE>'
AND c.TABLE_SCHEMA = t.TABLE_SCHEMA
AND c.TABLE_NAME = t.TABLE_NAME
AND t.TABLE_TYPE = 'BASE TABLE'
AND @NeighboringColumn IN (SELECT COLUMN_NAME 
    FROM information_schema.COLUMNS c2 
    WHERE c2.TABLE_NAME = t.TABLE_NAME);
uchamp
  • 2,492
  • 1
  • 20
  • 31
0

For those using TablePlus, you can just mark all tables, right click -> Copy, in the new table -> Paste.

Ricky Levi
  • 7,298
  • 1
  • 57
  • 65
0

In SQL :

If you want to move id column to the first place, we have a query for that, is like below:

ALTER TABLE `mydatabase` CHANGE `id` `id` INT NOT NULL AUTO_INCREMENT FIRST;

In this query, information is like below:

  • mydatabase : your table name.

But if you want to move a column after another column, mean maybe your A column is at the secound and you want to move it to the last place of your table after B column so use this query:

ALTER TABLE `mydatabase` CHANGE `title` `title` VARCHAR(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL AFTER `img_name`;

The information of this query is like below:

  • mydatabase: your database name is here.
  • title: is your column, that you want to move (A column).
  • img_name: the secound column (B column).
  • The title type is : VARCHAR(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL ( maybe yours is different type)

In PHPMYADMIN :

  • From sidebar, click on + inside of your table, click on COLUMNS.
  • It open a table with all name of columns. Click on change under column action (column you want to move). Now you see another page,
  • the last item is Move column. It is select option and choose place you want to move that column.
  • Choose and click on save button.

I hope it be usefull. if you found usefull, please upvote. Thanks.