Re: How to capture MAX id value into a variable - Mailing list pgsql-novice

From Michael Fuhr
Subject Re: How to capture MAX id value into a variable
Date
Msg-id 20041118003554.GA26441@winnie.fuhr.org
Whole thread Raw
In response to How to capture MAX id value into a variable  (Kumar S <ps_postgres@yahoo.com>)
List pgsql-novice
On Wed, Nov 17, 2004 at 03:51:47PM -0800, Kumar S wrote:
>
> INSERT INTO EMPLOYEE(<columns>) VALUES(col1,col2,col3);
> SELECT INTO X = SELECT MAX(employee_id) from employee;
> INSERT INTO DUTY(<cols>) VALUES(X, col4,col4,col6);

If employee_id gets a default value from a sequence (e.g., if you
defined it as SERIAL) then you can use currval() to get the most
recently obtained value from the sequence.

INSERT INTO EMPLOYEE (...) VALUES (...);
INSERT INTO DUTY (...) VALUES (currval('employee_employee_id_seq'), ...);

currval() returns the most recently obtained value in the current
connection, so it's safe to use even if other connections are
updating the sequence at the same time.

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

pgsql-novice by date:

Previous
From: Kumar S
Date:
Subject: How to capture MAX id value into a variable
Next
From: Marek Lewczuk
Date:
Subject: Re: Perfomance in comparism