Easiliy enforcing referential integrity in Postgres

Suppose table A has a primary key id of the type SERIAL. This means that Postgres implicity creates a sequence called A_id_seq, which is automatically incremented on insert with no value or DEFAULT value.

To enforce referential integrity with B within a session we use it as follows:

insert into A (<not A>) values (<values>) insert into B values( CURRVAL(‘A_id_seq’), <other values;>)

Note that CURRVAL is defined per session so concurrent access is not a problem.

Leave a Reply