Re: [GENERAL] getting val of serial field after insert

From: Herouth Maoz <herouth(at)oumail(dot)openu(dot)ac(dot)il>
To: gerald(at)interface-business(dot)de, Christian Rudow <Christian(dot)Rudow(at)thinx(dot)ch>
Cc: PostgreSQL General <pgsql-general(at)hub(dot)org>, Jim Archer <jim(at)archer(dot)net>
Subject: Re: [GENERAL] getting val of serial field after insert
Date: 1999-07-11 15:57:12
Message-ID: l03130307b3ae6d29cc1d@[147.233.159.109]
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

At 16:32 +0300 on 09/07/1999, postgres(at)taifun(dot)interface-business(dot)de wrote:

> The type SERIAL is internal represented as SEQUENCE and the
> name of that sequence is build temporary from the name of
> the relation, the name of the attribute and a trailing 'seq'.
> Use currval(), nextval() or setval() to query or modify the value.
> Or simple query
>
> SELECT last_value FROM distributors_id_seq;
>
> to obtain the last value of 'id'.

BEEEEEEP... Wrong, wrong, wrong!

The last_value in the sequence table may not be the value you just
inserted, because another user may have also added a row at the same time,
and got another number, and that will be the last one...

The proper way to get the actual number that *you* entered, is to use the
function currval( 'distributors_id_seq' ). This function returns the last
value issued from the sequence to your session.

We have discussed it several times before, either on the SQL list or here.
It would be a good idea to look in the list archives before asking a
question.

There really should be a FAQ item about this - this subject is raised again
and again. It is certainly frequently asked.

Herouth

--
Herouth Maoz, Internet developer.
Open University of Israel - Telem project
http://telem.openu.ac.il/~herutma

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Herouth Maoz 1999-07-11 16:07:52 Re: [GENERAL] rules failed
Previous Message Kaare Rasmussen 1999-07-11 15:23:33 Re: [GENERAL] New FAQ item