HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Can optional foreign key cause trouble in the long term?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
cantheforeignlongtermoptionalcausetroublekey

Problem

In a nutshell, we have two tables:

Document 1 (strong entity)

Document 2 (weak entity)

Document 1 has many Document 2 and Document 2 has only one Document 1.

That being said, sometimes we need to insert a Document 2 into the database but a Document 1 doesn't always exist and that's causing a foreign key error.

Is it OK if I remove the mandatory foreign key constraint, add a Document 2 and associate them later, when I finally insert the corresponding Document 1?

Will the association still formally be present?

Also, can that cause any trouble in the future, like a stored procedure or a view stop working?

Solution

Is it OK if I remove the mandatory foreign key constraint, add a Document 2 and associate them later, when I finally insert the corresponding Document 1?

Technically, this is doable, but obviously it breaks the data integrity between two tables Document 1 and Document 2, that your foreign key helps to enforce

You either have to:

A) add all possible records/values into Document 1 table beforehand, so by the time you insert a new row into Document 2, value already exists at Document 1, and foreign key is not violated

or

B) Don't insert values into Document 2, which don't exist at Document 1 yet

If you can't achieve any of above (A or B) - then what's the point of having foreign key at all ?

Context

StackExchange Database Administrators Q#301347, answer score: 3

Revisions (0)

No revisions yet.