kush87
kush87

Reputation: 551

AutoGenerate a uuid and use a part of it to update another column in a single postgres query statement

I have two columns in lets say employees table. 1) emp_id which is a uuid autogenerated. 2) emp_name which is a string.

Now i want to put some default values in emp_name column at the time of insert and i want lets say first 6 characters of the corresponding emp_id added after 'emp_' string. And i want all of it as a single insert query statement. Is there a way to do such a thing in postgres.

Upvotes: 3

Views: 1016

Answers (2)

Joe
Joe

Reputation: 610

Try this:

WITH emp as (SELECT public.gen_random_uuid() AS uuid)
insert into employees(emp_id, emp_name) (select 
emp.uuid,'emp_'||substring(emp.uuid::varchar from 0 for 6) from emp);

Upvotes: 3

TeoVr81
TeoVr81

Reputation: 1009

You can generate the uuid, save it in a variable and use it in the insert statement. To understand how you can create it and the different type of uuid, you can read this page:

http://www.postgresqltutorial.com/postgresql-uuid/

Upvotes: 1

Related Questions