Thread: How can I get the last serial I inserted?

How can I get the last serial I inserted?

From
Date:
Dear all,

I would like to insert a row into a table with serial type id as other table's
reference key. After that insert, I would use the inserted serial to insert
into another table.

The problem is how can I find that serial value and ensuring other is inserting
at the same time?


Best regards,
Boris

Re: How can I get the last serial I inserted?

From
"Alex Bolenok"
Date:
----- Original Message -----
From: <database@gurubase.com>
To: "PostgreSQL General" <pgsql-general@postgresql.org>
Sent: Sunday, July 23, 2000 10:26 AM
Subject: [GENERAL] How can I get the last serial I inserted?


> Dear all,
>
> I would like to insert a row into a table with serial type id as other
table's
> reference key. After that insert, I would use the inserted serial to
insert
> into another table.
>
> The problem is how can I find that serial value and ensuring other is
inserting
> at the same time?
>
>
> Best regards,
> Boris

peroon=# CREATE TABLE t_first (fid SERIAL PRIMARY KEY, finfo TEXT);
NOTICE:  CREATE TABLE will create implicit sequence 't_first_fid_seq' for
SERIAL
 column 't_first.fid'
NOTICE:  CREATE TABLE/PRIMARY KEY will create implicit index 't_first_pkey'
for
table 't_first'
CREATE
peroon=# CREATE TABLE t_second (sid INT4 REFERENCES t_first, sinfo TEXT);
NOTICE:  CREATE TABLE will create implicit trigger(s) for FOREIGN KEY
check(s)
CREATE
peroon=# BEGIN WORK; INSERT INTO t_first(finfo) VALUES ('Some value');
INSERT IN
TO t_second VALUES (CURRVAL('t_first_fid_seq'), 'Other value'); COMMIT WORK;
BEGIN
NOTICE:  t_first_fid_seq.nextval: sequence was re-created
INSERT 252770 1
INSERT 252771 1
COMMIT
peroon=# SELECT * FROM t_first;
 fid |   finfo
-----+------------
   1 | Some value
(1 row)

peroon=# SELECT * FROM t_second;
 sid |    sinfo
-----+-------------
   1 | Other value
(1 row)

Is it what you are looking for?

Alex Bolenok.