Home > database >  How to update oracle list column with sequence number
How to update oracle list column with sequence number

Time:05-20

Hi I have the oracle data table like that

seq_no name place
1 Rian Us
1 Moli Us
1 Molina Us

and i want to update automaticly the seq_no to be like that

seq_no name place
1 Rian Us
2 Moli Us
3 Molina Us

CodePudding user response:

If you have a table:

CREATE TABLE table_name (seq_no, name, place) AS
SELECT 1, 'Rian',   'Us' FROM DUAL UNION ALL
SELECT 1, 'Moli',   'Us' FROM DUAL UNION ALL
SELECT 1, 'Molina', 'Us' FROM DUAL;

and a sequence:

CREATE SEQUENCE your_sequence;

Then you can update the existing rows to the sequence values using:

UPDATE table_name
SET seq_no = your_sequence.NEXTVAL;

Then the table would contain:

SEQ_NO NAME PLACE
1 Rian Us
2 Moli Us
3 Molina Us

Then when you want to INSERT more rows, you can use:

INSERT INTO table_name (seq_no, name, place)
VALUES (your_sequence.NEXTVAL, 'New Name', 'New Place');

and the row:

SEQ_NO NAME PLACE
4 New Name New Place

Would be added with the next sequence number.

Alternatively, you could write a trigger to get the next sequence number or, from Oracle 12, use an IDENTITY column.

db<>fiddle here

CodePudding user response:

What does "automatically" mean?

You could have created table so that SEQ_NO is automatically populated by a database trigger (can't use an identity column as you're on 11g).

Or, if you want to update the table, a simple option is

update your_table set seq_no = rownum;
  • Related