cancel
Showing results for 
Search instead for 
Did you mean: 

Adding an identity column in an existing table in Sybase

Former Member
7,791

Hi All,

I have a table order with columns pin, orderPath, quantity. There are 5000 data in the table already. Now, I want to add an identy column, say OrderID, but with order by column pin.

Using the following query helps but not in the order as required.

ALTER TABLE order ADD OrderID numeric(6,0) identity

Here's what I got after executing the above statement:

Pin--OrderPath--Quantity--OrderID

22 kl/pod 100 1

11 xyz/pop 200 2

33 djh/dd 200 3

44 dj/po 300 4

But here's what I would like to see:

Pin--OrderPath--Quantity--OrderID

11 xyz/pop 200 1

22 kl/pod 100 2

33 djh/dd 200 3

44 dj/po 300 4

Please advice.

Accepted Solutions (0)

Answers (1)

Answers (1)

VolkerBarth
Contributor

If you really want to add a column that stores a particular order (instead of letting the engine order - and number - the results based on whatever criteria you need at that time), you can

  • add a column with the appropriate data type and
  • use an UPDATE statement to fill that for the existing rows, such as an self-joining UPDATE with an ROW_NUMBER() OLAP part, and
  • would possibly need a trigger to insert/update that column for new/changed rows.

If the order should be "chronologically" and if skipping values are allowed, you could also use an easier way by adding a DEFAULT AUTOINCREMENT column which will fill the values based on the row's PK order, methinks (and if not, you could adapt that for the existing rows with an UPDATE, since DEFAULT AUTOINCREMENT can still be over-written explicitly).


If, on the other hand, you just need a "numbered" result set (which I would highly recommend), you can easily do this with ROW_NUMBER(), such as the - untested -

SELECT Pin, OrderPath, Quantity,
   ROW_NUMBER() OVER (ORDER BY Pin) as OrderID
FROM MyTable
ORDER BY OrderID

Apparently, ORDER BY Pin would do, as well.