1

I have the following sql:

UPDATE TABLE1 SET SORT_COLUMN=ROWNUM WHERE ACTIVE_RECORD='Y'

That works but it sets the order to the current order of rows and I need to order by date, something like this:

UPDATE TABLE1 SET SORT_COLUMN=ROWNUM WHERE ACTIVE_RECORD='Y' ORDER BY START_DATE

But this, obviously, would not work. How can I update the SORT column based on the date?

Coding Duchess
  • 6,445
  • 20
  • 113
  • 209
  • https://stackoverflow.com/questions/6094039/oracle-updating-a-table-column-using-rownum-in-conjunction-with-order-by-clause – ZorgoZ Mar 04 '19 at 20:33

1 Answers1

2

Here's what I wrote, based on your previous question (which has been deleted). A subquery might be the answer you're looking for:

SQL> create table test
  2    (start_date date,
  3     sort       number);

Table created.

SQL> insert into test (start_date)
  2    select date '2019-03-04' from dual union all
  3    select date '2019-01-12' from dual union all
  4    select date '2019-12-17' from dual;

3 rows created.

SQL> update test t set
  2    t.sort = (select x.rn
  3              from (select start_date,
  4                           row_number() over (order by start_date) rn
  5                    from test
  6                   ) x
  7              where x.start_date = t.start_date);

3 rows updated.

SQL> select * From test;

START_DATE       SORT
---------- ----------
04.03.2019          2
12.01.2019          1
17.12.2019          3

SQL>

A new column, ACTIVE_RECORD, doesn't change things much - adding it to that example should be trivial.

Littlefoot
  • 131,892
  • 15
  • 35
  • 57