PostgreSQL insert if foreign key exists

How can I insert a new row into a table with a link to a foreign key only if there is a foreign key (in this case, a model)?

I currently have the following statement:

INSERT INTO furniture (model, type) VALUES (modelA, chair)
+4
source share
1 answer

Use SELECT, which returns nothing if FK does not exist.

INSERT INTO furniture (model, type) 
select 'modelA', 'chair'
where exists (select * 
              from model 
              where model.model = 'modelA');

You did not tell us what is called a reference table. I suggested that this modelis - you need to configure this for real names.

+4
source

Source: https://habr.com/ru/post/1652979/


All Articles