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

Return ID from partitioned table in postgres?

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

Problem

When I insert a record I need to return the inserted id by RETURNING. The problem is that the table is partitioned and in partitioned table I can't use RETURNING. I run multiple queries at once so I'm in dire need of RETURNING. Is there a way to accomplish this?

Solution

Assuming a parent's table like this:

CREATE TABLE parent AS (
  id not null default nextval('parent_id_seq'::regclass)
  ... other columns ...
);


Whether you're using a rule or a trigger to divert the INSERTs into the child tables, immediately after the INSERT you may use:

SELECT currval('parent_id_seq'::regclass);

to get the last id inserted by your session, independently of concurrent INSERTs, each session having its own copy of the last sequence value it has obtained.

Code Snippets

CREATE TABLE parent AS (
  id not null default nextval('parent_id_seq'::regclass)
  ... other columns ...
);

Context

StackExchange Database Administrators Q#58497, answer score: 4

Revisions (0)

No revisions yet.