Re: Sequences question & problem

From: Michael Fuhr <mike(at)fuhr(dot)org>
To: "Lada 'Ray' Lostak" <ray(at)unreal64(dot)net>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: Sequences question & problem
Date: 2005-05-16 14:14:05
Message-ID: 20050516141405.GA82765@winnie.fuhr.org
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Mon, May 16, 2005 at 12:29:27PM +0200, Lada 'Ray' Lostak wrote:
>
> I am having small trouble with sequences. I am inserting row into table,
> and I need to get value of its 'id' column (sequencen type). As far I know
> it have to be done by
>
> SELECT last_value FORM seq_name
>
> (or next_val before insert).

The above queries are subject to race conditions. For example, if
transaction A inserts a record, then transaction B inserts a record,
then transaction A queries the sequence, then transaction A will
get the sequence value that was given to transaction B, which
probably isn't what you want. Use currval() or nextval() instead.

http://www.postgresql.org/docs/8.0/interactive/functions-sequence.html
http://www.postgresql.org/docs/faqs.FAQ.html#4.11.2
http://www.postgresql.org/docs/faqs.FAQ.html#4.11.3

> Normally, sequences are created by 'table' & 'column' & '_seq' eg.
> 'table_id_seq'.
>
> Now let's rename 'table' to 'table2'. Sequence name wan't renamed. And it's
> my problem... I can't simple assume 'sequence id' by table/column...

If you're using PostgreSQL 8.0 or later then you can get the sequence
name with the pg_get_serial_sequence() function:

test=> CREATE TABLE foo (id serial);
NOTICE: CREATE TABLE will create implicit sequence "foo_id_seq" for serial column "foo.id"
CREATE TABLE
test=> ALTER TABLE foo RENAME TO foo2;
ALTER TABLE
test=> ALTER TABLE foo2 RENAME id TO id2;
ALTER TABLE
test=> SELECT pg_get_serial_sequence('foo2', 'id2');
pg_get_serial_sequence
------------------------
public.foo_id_seq
(1 row)

--
Michael Fuhr
http://www.fuhr.org/~mfuhr/

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Randall Smith 2005-05-16 15:14:43 connecting to server process via sockets
Previous Message Adam Witney 2005-05-16 12:35:47 Distinguishing between connections in pg_hba.conf