2

Is it possible to declare table column that is used as foreign key, but can be null?

I have a table messages that contains user_uuid as foreign key reference to user_profiles table.

SELECT * FROM messages;

id   user_uuid                              message
--   ---------                              -------
 1   f52acab5-6115-4a09-ad81-eac662292968   Hello user john smith
 2   null                                   Hello all

I want to allow nulls for broadcast messages, but if user_uuid is specified, i want to make sure it is validated against user_profile table, and also to perform cascade deletion of user messages in case when user gets deleted. Is there a way to do so by just database means?

p.s. I know the solution of making 0000000-0000-0000-0000-0000000000 fake record in a table and referencing it. But is there more civilized way?

2 Answers 2

3

You are already doing it correctly. If the foreign key column is NULL, referential integrity is not enforced for that row.

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

Comments

1

This is possible. Just check following threads:

The cascade deletion should also work, because at the end the column is a valid reference.

Comments

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.