0

I have my Postgres database which I used hibernate sequence to generate ids. But the sequence was common for all tables. But now my plan is to have a separate sequence for each table. Bow the what I would like to use a command to pack the ids continuous for a table, but without breaking any of the references.

dinesh707
  • 12,106
  • 22
  • 84
  • 134

1 Answers1

0

You'll have to make sure that all of your FOREIGN KEY references have ON UPDATE CASCADE (to add it: How to add "on delete cascade" constraints? ), then you can use:

UPDATE mytable AS m
SET id = n.rank
FROM (SELECT id, rank() OVER (ORDER BY id) FROM mytable) AS n
WHERE m.id = n.id

Which will give you sequential IDs with the same order as the original ids:

> SELECT * FROM mytable ORDER BY id;
id | name
1  | Alex
5  | David
10 | Jane
> UPDATE …;
…
> SELECT * FROM mytable ORDER BY id;
id | name
1  | Alex
2  | David
3  | Jane
Community
  • 1
  • 1
David Wolever
  • 148,955
  • 89
  • 346
  • 502
  • 1
    There might be some tables, that are referencing other `id` fields without a proper `FOREIGN KEY`. – Ihor Romanchenko Nov 19 '13 at 10:14
  • There's no general solution to that, unfortunately — the only thing that can be done there is considering each column that contains an ad-hoc reference to another column and decide how to fix each one up on a case-by-case basis. – David Wolever Nov 19 '13 at 19:10
  • You may need to update your sequences after doing a mass update on your keys http://stackoverflow.com/questions/244243/how-to-reset-postgres-primary-key-sequence-when-it-falls-out-of-sync/13308052 – nclu Dec 14 '15 at 18:53