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.
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.
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 development languages
Related Q&A from Rudy Limeback
Using the SQL GROUP BY clause for counting combinations
Read SQL expert Rudy Limeback's advice for counting combinations in a table with SQL's GROUP BY clause Continue Reading
How to sort an SQL UNION query with special ORDER BY sequence
SQL expert Rudy Limeback explains how to sort an SQL UNION query using a special ORDERY BY sequence. Continue Reading
Using an SQL SELECT statement from a non-existing table
SQL expert Rudy Limeback explains how to formulate a query using an SQL SELECT statement from a non-existing table. Continue Reading