views:

66

answers:

3

Hello, I have a database where everything is linked with foreign keys, so the Postgres knows exactly how the database is layed out..

Well, Lets say I have Table1 and Table2.

Table1 has 3 fields. RID, table2_rid,data

So table1.table2_rid references table2.RID and this is expressed with a foreign key. In both the RID field is the primary key and is a serial type.

What I would like to know is how to "condense" the primary keys? Like say you add 5 records and deleted record number 3. Your primary keys would look like

1
2
4
5 

Well, how do I get to update everywhere so that the primary key(and corresponding foreign keys) can be condensed into

1
2
3
4
A: 

Look into on update cascade and on delete cascade.

create table table_1 (
    id integer
        primary key,
    name char(30)
);
create table table_2 (
    id integer
        primary key,
    table_1_id integer
        references table_1
        on update cascade
        on delete cascade,
    detail char(30)
);
Justice
+1  A: 

It's best if a primary key never changes: Renumbering them is a PITA.

If you need an ID for humans, one that has no gaps, A. Elein Mustain shows how to create a gapless sequence.

Wayne Conrad
Well I'm thinking ahead cause we have a table or two that very commonly has transactions rolled back(which increment the primary key's value due to how `serial` works) and has lots of inserts and updates and I would just like to know if in a year or two we begin to face a roll-over problem with 32 bit, if there will be a way to combat it.
Earlz
2^31 is one insert per second for *68 years*. But if 32 bits might not be enough, then use serial8/bigserial instead of plain serial and you'll be able to do 1000 inserts per second for 0.1 terrayears.
Wayne Conrad
+1  A: 

Except for very rare scenarios, gaps in the PK sequence are just right, to intent to get rid of them is a bad idea.

leonbloy