function for creating random id - Mailing list pgsql-general

From Moritz Sinn
Subject function for creating random id
Date
Msg-id m3sn5xarja.fsf@freesources.org
Whole thread Raw
Responses Re: function for creating random id
List pgsql-general
hi,

i've got a table called "user". every user should have a userid, which
is the primary key. this userid is a random number with up to 6 digits.

to get this userid i wrote a function in plpgsql:

CREATE FUNCTION getuid(int) RETURNS int AS '
DECLARE
uid     INTEGER;
BEGIN
SELECT (random() * (pow(10.0, $1::float)-1))::int INTO uid;
RETURN uid;
END;' LANGUAGE 'plpgsql' WITH (isstrict);

user was created with:

CREATE TABLE "user" (id numeric(6,0) DEFAULT getuid(6), username
VARCHAR(20), password VARCHAR(20), name VARCHAR(30), forename
VARCHAR(30), CONSTRAINT "user_pk" PRIMARY KEY("id"));


but now the problem is that the id which is returned by getuid() could
already be in use.
so what is the best method to realize that?
i mean isn't there already a function which returns a boolean, saying if
this id is already in use or not?

thanks,
 moritz

--
Subject: Linux box finds it hard to wake up in the morning

I've heard of dogs being like their owners, but Linux boxen?
    -- Peter Hunter <peter.hunter@blackfriars.oxford.ac.uk>

pgsql-general by date:

Previous
From: Andrew Gould
Date:
Subject: Re: Export From Postresql to a DBF File Format
Next
From: Andrew Sullivan
Date:
Subject: Re: Why does postgres not take into account my index on a bigint column ?