Home > other >  Can a foreign key value be null when storing a record then update it when the value is known?
Can a foreign key value be null when storing a record then update it when the value is known?

Time:11-02

ERP diagram

This is a database for a web based libarary management system We have for roles for the users: admin,librarian, borrower.

A borrower who has an online account can reserve books online, then when he goes to the libraray to pick it up if the librarian confirms the reservation as "picked up", the data in the reservation table will be stored in the "borrow" table automatically (by the backend)

So a book reservation is basically a borrow in advance . In the borrow table we need to know the field (supervised_by(FK)) which is the librarian who did supervise that borrow and that will be already known if the borrower borrowed a book offline in the library.

But if the borrower reserved a book online, we still don't know who is the librarian who will supervise this reservation later so it cannot be filled at that time, but at the same time this field is needed so later when the data of the reservation is copied to the borrow table . How can i handle this?

Someone suggested to me to remove the supervisedby field and use log files , but then we willnot store the librarian who managed a borrow/reservation in the database

CodePudding user response:

Short answer: yes.

Long answer: as long as you allow NULLs in your foreign key column, you can fill them with NULLs and update them later.

Fun answer: just try it.

The foreign key constraint only makes sure you do not put a non-existing key in there.

  • Related