0

I'm trying to generate new IDs for a large table. The ID's have to be consecutive and need to start at 0 (So I can't use sequence). What I come up with so far is the following function:

CREATE OR REPLACE FUNCTION genIds() RETURNS integer AS $$
DECLARE
   edge RECORD;
   i INTEGER := 0;
BEGIN
    FOR edge IN SELECT * FROM network LOOP
        UPDATE network SET id = i WHERE id = edge.id;
        i := i + 1;
    END LOOP;
    RETURN i;
END;
$$ LANGUAGE plpgsql;

I would much rather like to not care about id = edge.id since I don't really care about the id's anyway. Is there a way to avoid having count(network) updates?

Cheers, Daniel

3
  • Btw: you can make a sequence start at 0: create sequence foo_seq start with 0 minvalue 0; Commented Mar 31, 2016 at 9:36
  • I thought sequences aren't guaranteed to be gapless? Commented Mar 31, 2016 at 11:51
  • They are not that's correct (I thought you just didn't want to use them because you couldn't make them start at 0). Commented Mar 31, 2016 at 11:55

1 Answer 1

1

Is there a way to avoid having count(network) updates?

If your question is: can this done with a single statement instead of a loop, then yes this is possible:

This can be done without a loop in a single statement:

with numbered as (
  select id as old_id, 
         row_number() over (order by id) as new_id
  from network
)
update network nt
  set id = nb.new_id - 1 // -1 to start at 0
from numbered nb
where nb.old_id = nt.id;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.