Problem solve Get help with specific problems with your technologies, process and projects.

Add a column in a specific position in a table

I have created one table with three columns. I want to drop one column and add the column back to the same table in the same location.

I have created one table with three columns, for example no, name, age. Now I can drop the name column OK. But now I want add the column back to the same table in the same location. Is it possible? How? I can add it but the order becomes no, age, name. However, I want no, name, age.

There are two approaches.

  1. In a relational database table, the order of columns does not matter. All that matters is the order in which columns are mentioned in a SELECT. Therefore, just add the column at the end of the table, and you're done.

  2. The second approach actually accomplishes what you want, and there are several ways to go about it.

    In MySQL, you can say:

    ALTER TABLE tbl_name
    ADD [COLUMN] column_definition [ FIRST | AFTER col_name ]

    In other databases, it's a lot harder. Typically you would define a second, temporary table, which has the columns in the desired order, then INSERT/SELECT from your original table to get the values copied over, then drop the original table and rename the second one.

    But in my opinion, this is a lot of work for absolutely no good reason. See approach 1.

Dig Deeper on Oracle and SQL