0

Generate gen_random_uuid() for the column key if there count(key) < 1

My table name is keytable and column is key.

I am using the below insert statement to generate the uuid : that is the only value in the table.

INSERT INTO keytable VALUES(gen_random_uuid());

key 
--------------------------------------- 
5686473e-add1-4ab1-be85-7e62152ce539

I wanted to run this insert statement only when i dont have any values in my "key" column.

in other words, if count(key) < 1 then i want to run the INSERT INTO keytable VALUES(gen_random_uuid()); Please help.

Aby
  • 1
  • 1

2 Answers2

0

use INSERT ... SELECT construct instead

t=# begin; insert into keytable select gen_random_uuid() where (select count(key) from keytable) < 1;
BEGIN
INSERT 0 1
t=# insert into keytable select gen_random_uuid() where (select count(key) from keytable) < 1;
INSERT 0 0
t=# rollback;
ROLLBACK
Vao Tsun
  • 47,234
  • 13
  • 100
  • 132
0

Already Answered By Clodoaldo Neto (Link Below)

here is according to your perspective

insert into keytable
select gen_random_uuid()
where not exists ( select key from keytable );

It will only insert the result of select statement when

select key from keytable

this does not return anything!

for more info: https://stackoverflow.com/a/15710598/8506841

Sahil Jalan
  • 111
  • 6