I have a User table and a Profile table - they do have a 1-to-1 relationship. Given the Primary-Foreign Key.
When I add a new row to user table, ideally, I like to also add a trigger or make a transaction to insert some default values into profile too. However because of the PK-FK on Profile, I need to preserve the gen_random_uuid ()
as a variable to insert into both table. is there anyway of doing that without writing an external uuid generator in application?
1 Answer 1
You can do that with a data modifying common table expression
with new_user as (
insert into "user" (userid, username)
values (gen_random_uuid(), 'Qi luo')
returning userid
)
insert into profile (userid, title)
select userid, 'Default Profile'
from new_user;
after insert
trigger has access to all inserted column values, so I'm not sure what problem you have withuserId
.