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)
If you are inserting data into a dependent table with foreign keys: Each non-null value you insert into a foreign key column must be equal to some value in the corresponding parent key of the parent table. If any column in the foreign key is null, the entire foreign key is considered null.
To create a new table containing a foreign key column that references another table, use the keyword FOREIGN KEY REFERENCES at the end of the definition of that column. Follow that with the name of the referenced table and the name of the referenced column in parentheses.
Referential integrity is the feature of a database ensuring implied relationships in the database are enforced. It is a feature of most database systems, and protects users from accidentally (or intentionally!) creating discrepencies in their database.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With