10

How can I insert a new row in a table with a foreign key reference only if the foreign key (in this case model) exists?

Currently I have the following statement:

INSERT INTO furniture (model, type) VALUES (modelA, chair)
1
  • 4
    ... WHERE EXISTS (SELECT * FROM models WHERE model = modelA) Commented Aug 30, 2016 at 10:05

1 Answer 1

13

Use a SELECT that returns nothing if the 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 the referenced table is called. I assumed it's model - you need to adjust that to the real names.

Sign up to request clarification or add additional context in comments.

1 Comment

you may also want to add locking to the exists clause to avoid race conditions see: dba.stackexchange.com/a/252925

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.