I want to insert into table1
multiple rows from table2
. The problem is that I have a field of same name in table2
and table1
and I don't want to insert data if there's already a record with same value in this field. Now I have something like this:
insert into table1 (id, sameField, constantField, superFied)
select gen_random_uuid(), "sameField", 'constant', "anotherField"
from table2;
And I assume I need to do something like this:
insert into table1 (id, sameField, constantField, superFied)
select gen_random_uuid(), "sameField", 'constant', "anotherField"
from table2
where not exists ... ?
What I need to write instead of ?
if I want this logic: check if there's already same value in sameField
in table1
when selecting sameField
from table2
? DBMS is Postgres.
You can use a sub-query to see whether the record exists. You will need to define the column(s) which should be unique.
2 rows affected
1 rows affected
1 rows affected
db<>fiddle here