HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlModerate

A way to reference the ID in a multi insert transaction? (postgres)

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
referencetheinsertmultipostgreswaytransaction

Problem

Assuming table "entity.eid" is auto incrementing, I want to be able to reference the autoincrement value assigned later in the same transaction. The way I have been doing this is by doing multiple transactions which I think is not optimal.

START TRANSACTION;
INSERT INTO entity ...;
INSERT INTO t2 (eid, ...) VALUES (?NEW EID REF HERE?, ...), (...), (...);
COMMIT;

Solution

There are different ways to do this.

The easiest way is to use the lastval() function which will return the value generated by the "last" sequence nextval.

START TRANSACTION;
INSERT INTO entity ...;
INSERT INTO t2 (eid, ...) VALUES (lastval(), ...), (...), (...);
COMMIT;


If you know the name of the sequence for the entity table you could also use the currval function:

START TRANSACTION;
INSERT INTO entity ...;
INSERT INTO t2 (eid, ...) VALUES (currval('entity_eid_seq'), ...), (...), (...);
COMMIT;


This can be written in a more general way by using the pg_get_serial_sequence() function, avoiding to hardcode the sequence name:

START TRANSACTION;
INSERT INTO entity ...;
INSERT INTO t2 (eid, ...) VALUES (currval(pg_get_serial_sequence('entity', 'eid')), ...), (...);
COMMIT;


For more details, please see the manual: http://www.postgresql.org/docs/current/static/functions-sequence.html

Code Snippets

START TRANSACTION;
INSERT INTO entity ...;
INSERT INTO t2 (eid, ...) VALUES (lastval(), ...), (...), (...);
COMMIT;
START TRANSACTION;
INSERT INTO entity ...;
INSERT INTO t2 (eid, ...) VALUES (currval('entity_eid_seq'), ...), (...), (...);
COMMIT;
START TRANSACTION;
INSERT INTO entity ...;
INSERT INTO t2 (eid, ...) VALUES (currval(pg_get_serial_sequence('entity', 'eid')), ...), (...);
COMMIT;

Context

StackExchange Database Administrators Q#52244, answer score: 11

Revisions (0)

No revisions yet.