Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL insert if foreign key exists

Tags:

postgresql

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)
like image 392
Jens de Bruijn Avatar asked Aug 30 '16 10:08

Jens de Bruijn


People also ask

How do you insert data into a table that has a foreign key?

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.

How can I add foreign key values to a table in SQL Server?

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.

What is referential integrity in PostgreSQL?

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.


1 Answers

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.

like image 74
a_horse_with_no_name Avatar answered Sep 19 '22 02:09

a_horse_with_no_name