Search code examples
sqloraclesql-updatedml

Update every row with auto-generated value


I have a table:

CREATE TABLE "person" (
    "ID" NUMBER(38,0), 
    "NAME" VARCHAR2(50 CHAR)
)

Data:

id name 1 monica 2 null 3 null 4 stephan 5 null

I need update null values with value "person" and auto incremented value (from 1 - person1, person2, person3 etc):

1 monica 
2 person1
3 person2
4 stephan
5 person3

What sql (oracle) query should I use?


Solution

  • Analytic function is not needed. The update can be done simply like this:

    UPDATE person
       SET NAME = 'person' || ROWNUM
     WHERE name IS NULL;
    

    Update

    Since the person number needs to be sequential with the IDs of the person, this query can be used:

    UPDATE person p
       SET p.name =
                  'person'
               || (SELECT person_number
                     FROM (SELECT p2.id, ROW_NUMBER () OVER (ORDER BY p2.id) AS person_number
                             FROM person p2
                            WHERE name IS NULL)
                    WHERE id = p.id)
     WHERE p.name IS NULL;