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

From: Christian Rudow <Christian(dot)Rudow(at)thinx(dot)ch>
To: Jim Archer <jim(at)archer(dot)net>
Cc: PostgreSQL General <pgsql-general(at)hub(dot)org>
Subject: Re: [GENERAL] getting val of serial field after insert
Date: 1999-07-09 08:12:00
Message-ID: 3785AED0.9F25BAC0@thinx.ch
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Jim Archer wrote:

> I have been inserting records into a table using the SQL insert statement
> via the perl5 Pg module. One of the field types is serial, and I have been
> trying to figure out how to get the value that was assigned in the field as
> a result of the insert. The serial typed field is the only one guaranteed
> to be unique, so I can't really do a search, and there are several people
> adding data at once, so I can't reliable guess. Can anyone help?

>From the SQL reference manual
-----------------------------
Usage

Create an ascending sequence called serial, starting at 101:

CREATE SEQUENCE serial START 101;

Select the next number from this sequence

SELECT NEXTVAL ('serial');

nextval
-------
114

Use this sequence in an INSERT:

INSERT INTO distributors VALUES (NEXTVAL('serial'),'nothing');

Set the sequence value after a COPY FROM:

CREATE FUNCTION distributors_id_max() RETURNS INT4
AS 'SELECT max(id) FROM distributors'
LANGUAGE 'sql';
BEGIN;
COPY distributors FROM 'input_file';
SELECT setval('serial', distributors_id_max());
END;

--
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Christian Rudow E-Mail: Christian(dot)Rudow(at)thinx(dot)ch
ThinX networked business services Stahlrain 10, CH-5200 Brugg
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Dustin Sallings 1999-07-09 08:35:37 Re: [GENERAL] Does Apache has PostgreSQL module?
Previous Message Jonathan davis 1999-07-09 07:46:42 Re: [GENERAL] just little BUG