Re: UUID vs serial and currval('sequence_id') - Mailing list pgsql-general

From David G. Johnston
Subject Re: UUID vs serial and currval('sequence_id')
Date
Msg-id CAKFQuwYD1niYAB1RRAMEJUrePqXxQ1tzgFnFdOjQ-xpLhqpzzg@mail.gmail.com
Whole thread Raw
In response to UUID vs serial and currval('sequence_id')  (Robert Stanford <rstanford@gmail.com>)
Responses Re: UUID vs serial and currval('sequence_id')
List pgsql-general
On Mon, May 2, 2022 at 3:33 PM Robert Stanford <rstanford@gmail.com> wrote:

--insert statement as single transaction returning contactid
INSERT INTO contact(
    firstname, lastname)
  VALUES('John', 'Smith');
INSERT INTO contactinterests(
    contactid, interest)
  VALUES (currval('contact_contactid_seq'),'Fishing') 
returning currval('contact_contactid_seq');

Which is very nice as it gives us back the contactid.

Is it possible to get similar functionality using gen_random_uuid() or uuid-ossp?


You basically have to use "INSERT ... RETURNING" or variables.  Which/how depends on the language you are writing in.  Pure SQL without client involvement requires that you use chained CTEs of INSERT...RETURNING (or I suppose you could leverage set_config(), haven't tried that way myself).  In pl/pgsql you can also use variables, and the same goes for psql - though that requires client involvement and so isn't generally that great a choice.

David J.

pgsql-general by date:

Previous
From: Robert Stanford
Date:
Subject: UUID vs serial and currval('sequence_id')
Next
From: Mladen Gogala
Date:
Subject: Re: External psql editor