Re: Return value of 'serial' column on insert

From: Bruno Wolff III <bruno(at)wolff(dot)to>
To: Madison Kelly <linux(at)alteeve(dot)com>
Cc: postgresql <pgsql-general(at)postgresql(dot)org>
Subject: Re: Return value of 'serial' column on insert
Date: 2005-01-27 06:41:55
Message-ID: 20050127064155.GA25654@wolff.to
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Thu, Jan 27, 2005 at 00:35:25 -0500,
Madison Kelly <linux(at)alteeve(dot)com> wrote:
> Hi all,
>
> I have several tables with an 'id' column which is a simple 'serial
> unique' type. Often when I insert a record the next thing I need is to
> add or edit another table elsewhere using the ID of the entry I just
> added. Currently what I do is:
>
> SELECT <table>_id FROM <table> ORDER BY <table>_id DESC LIMIT 1;
>
> and assume (safely thus far) that the returned value is the one I
> just created. Obviously this is bulky and, should by chance another
> column be added in that time between insert and read, I would get the
> wrong value.
>
> Is there a way to do an INSERT (in perl, btw) where pgSQL returns the
> value just created by the same INSERT? Thanks!

You can use the currval function to get the id. Normally the sequence
will have a name like table_column_seq. In 8.0, there is a function
you can use to get the sequence name, which is a bit more robust than
hard coding it.

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Sim Zacks 2005-01-27 06:51:09 Re: Export a column in a view without "announcing" it?
Previous Message Max 2005-01-27 05:46:36 Re: Splitting queries across servers