1

I need to renumber the rows of my database. After I delete some rows I have to renumber certain column. How can I do that using postgresql?

UPDATE: For example: I have a table like this:

ac_n_circ     name

1               x 
2               y
8               c
15              b

And I want to renumber this table like this:

ac_n_circ     name

1               x 
2               y
3               c
4               b

Is there any algorithm or something like that to do this in posgresql?

Thanks!

mailazs
  • 341
  • 6
  • 22
  • can you be more specific? do the new numbers be in any order? please provide an example of what you have and what you expect to get. – luksch Apr 23 '13 at 18:31

1 Answers1

3

Caution:

This only makes sense if ac_n_circ is NOT the primary key column.

If you are sure you need this (are you really?), then something like the following should work:

with new_numbers as  (
   select row_number() over (order by ac_n_circ) as new_nr,
          ac_n_circ, 
          id
   from foo
) 
update foo
   set ac_n_circ = nn.new_nr
from new_numbers nn 
 where nn.id = foo.id;

Alternatively:

update foo 
  set ac_n_circ = nn.new_number
from (
   select id, 
          ac_n_circ,
          row_number() over (order by ac_n_circ) as new_number
   from foo
) nn
where nn.id = foo.id;

Both statements assume that there is a primary key column named id.

Community
  • 1
  • 1