How to add a column in an already existing table and fill IDs in it ordered by a column on Oracle Server?

366 Views Asked by At

In table TEST, I want to add a column ID and fill IDs in it incremented by 1 for each row. I need the IDs sorted with respect to column COL. So far, I have done this:

ALTER TABLE TEST ADD ID INTEGER;
UPDATE TEST SET ID = ROWNUM;

The problem in this method is IDs are not sorted with respect to COL. I need something like this:

UPDATE TEST SET ID = (SELECT ROWNUM FROM TEST ORDER BY COL);

but get an error. I have also tried CTE like this:

WITH CTE AS (
    SELECT * FROM TEST ORDER BY COL
) UPDATE CTE SET ROWNUM = ID;

Getting the error missing SELECT keyword.

2

There are 2 best solutions below

3
palindrom On
update test
  set id = (
    with cte as (
      select row_number() over (order by col) id, rowid rid from test
    )
    select id from cte where test.rowid = cte.rid
  );
0
AudioBubble On

Usually such tasks are more easily solved with a merge statement. For example:

merge into test t
using (select rowid as rid, row_number() over (order by col) as rn from test) s
   on (s.rid = t.rowid)
when matched then update set id = rn;