From: | Patrick B <patrickbakerbr(at)gmail(dot)com> |
---|---|
To: | Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us> |
Cc: | pgsql-general <pgsql-general(at)postgresql(dot)org> |
Subject: | Re: get inserted id from transaction - PG 9.2 |
Date: | 2017-02-15 01:29:42 |
Message-ID: | CAJNY3itCX43skHo4CF+LOTrxUi5Pz9dt6TpcAaUzOc=x68=egQ@mail.gmail.com |
Views: | Raw Message | Whole Thread | Download mbox | Resend email |
Thread: | |
Lists: | pgsql-general |
2017-02-15 12:19 GMT+13:00 Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>:
> Patrick B <patrickbakerbr(at)gmail(dot)com> writes:
> > I'm simply doing an insert and I want to get the inserted id with a
> select.
> > I'm doing this all in the same transactions.
>
> > Example:
> > BEGIN;
> > INSERT INTO test (id,name,description) VALUES (default,'test 1','testing
> > insert');
> > SELECT FROM test ORDER BY id DESC; -- I don't see the inserted row here
>
> Maybe you meant "SELECT * FROM test", or at least "SELECT id FROM test"?
> Because that row certainly should be visible here.
>
> Having said that, the above coding seems rather broken, because it's just
> assuming that the new row will have the highest ID in the table. Even if
> that's true at the instant of insertion, you have a race condition:
> another transaction could insert and commit a new row with a higher ID
> between your INSERT and your SELECT.
>
> The usual solution for this problem in PG is RETURNING:
>
> INSERT INTO test (id,name,description)
> VALUES (default,'test 1','testing insert')
> RETURNING id;
>
>
Thanks guys!
RETURNING id - it's what i was looking for.
Thanks a lot!
Patrick
> That will get you the generated column's value reliably, and it avoids
> one query roundtrip besides.
>
> regards, tom lane
>
From | Date | Subject | |
---|---|---|---|
Next Message | Shawn Thomas | 2017-02-15 04:47:16 | Re: Can't restart Postgres |
Previous Message | James Sewell | 2017-02-15 01:23:18 | Re: PostgreSQL corruption |