Search code examples
sqloracleoracle11g

How to update oracle list column with sequence number


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

Solution

  • 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