Re: creating "job numbers" - Mailing list pgsql-sql

From Richard Huxton
Subject Re: creating "job numbers"
Date
Msg-id 004201c0b2d8$5d3c8020$1001a8c0@archonet.com
Whole thread Raw
In response to creating "job numbers"  ("postgresql" <pgsql@symcom.com>)
List pgsql-sql
From: "postgresql" <pgsql@symcom.com>

> In my current setup I have only one workstation  that is actually
> inputting new jobs. So, I took the expedient way to create the  job
> number. Ask PG to count the rows, add a magic number and insert
> this data. This all happens in one connection. What are the odds of
> two people hitting the db at the same time? In the current set up nil.
> There is only one entry computer. I want to change the system to use
> a job number generated by PG. I created a test  table and I  am
> playing with inserting and the sequence function works great.
> However, I am at a loss of how to pick up this next (last) job. I have
> read the docs and I still am confused. I can not first ask with the
> number will be, and asking for the previous oid after  the fact can
> also lead to  the same problem. so that leaves me  with, 1 ask for
> that last oid from this  workstation ip, or 2 since a job is inserted with
> data, I could do a select of this data after the insert (not very
elegant).

I wouldn't use oid's for this - create a jobnum field and use a sequence.

Sequences are smarter than you think, use:
select currval('mysequence') to get the current value and
select nextval('mysequence') to get the next value *for this backend*

So - each client will be guaranteed a unique number. Note that if you "use
up" a number and e.g. an insert fails there will be gaps in your numbering.

Also check out the SERIAL data-type which can provide automatic numbering
for the fields.

I'm sure there are examples in Bruce's book (there's a link on
www.postgresql.org)

- Richard Huxton



pgsql-sql by date:

Previous
From: juerg.rietmann@pup.ch
Date:
Subject: how to build this string ?
Next
From: Johannes Grødem
Date:
Subject: Foreign key referencing subclasses.