Is there a way to add column at a specified positi

2019-03-03 20:00发布

问题:

This question already has an answer here:

  • How to insert a column in a specific position in oracle without dropping and recreating the table? 4 answers

Consider this inital table I have created in Oracle 10G:

╔═════════════════════════════════╗
║  CUSTOMER_ID ACC_NO ACC_BALANCE ║
╠═════════════════════════════════╣
║         100    200        1000  ║
║         101    150        4000  ║
║         102    350        2000  ║
║         103    450        2500  ║
║         104    550        2200  ║
╚═════════════════════════════════╝

Now I want to add another column customer_name into the table. I used:

ALTER TABLE BANK_ACCOUNT 
  ADD (CUSTOMER_NAME VARCHAR2(30)); 

and the column is being inserted as the last column in the table whereas I want the column to be added to the table as the second column. Now the SQL code I mentioned is unable to do so. So how can I add the column at a specified position? Is it even possible in SQL?

回答1:

It really doesn't matter where the column is physically since select will allow you to specify the order (logically) in which they're retrieved.

And, if you're using select * which doesn't let you specify the order, you probably shouldn't be. There are precious few situations where you should be doing that (DB analysis tools, for example), most of the time it's better to select the individual columns you want, even if you want them all. This allows you to catch schema changes quickly so you can adapt your programs to them.

In any case, SQL itself makes no guarantees about the order in which columns are returned unless you explicitly list them. select * may give them to you in ordinal order today and alphabetic order tomorrow. Even if a particular implementation allows you to do it (by creating a new table with the column in the "right" place and copying the data across, or providing an SQL extension like alter table T insert column C1 before C2), I'd advise against it. It won't be portable to other implementations and I prefer to have my code as portable as practicable.

In addition, beyond what you can specify in SQL, a DBMS should be able to totally control how it stores data. It may be that your primary key is a composite of the seventh and forty-second column and it may be more efficient to have them at the front of the physical records.