How do I maintain referential integrity? #74
-
There are no foreign keys, so how do I relate data:
What is the alternative for there being no foreign keys? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 5 replies
-
@shreyfirst 👋 good question. First, taking the opportunity to explain why we don't support foreign key constraints:
Now to answer your specific questions: Duplicating data
Making sure every reference still existsA bit background before I share my opinion, if you will: When using foreign key constraints, the user chooses between:
Here is my opinion, which I put to practice:
Now let's consider what happened here. The app had to take ownership of the the entire I'd like to clarify I don't mean to downplay foreign keys here. I do want to highlight that it's still very much the app's responsibility to take care of proper and orderly cleanup, with or without foreign keys. The app knows (or should know) your data better than the database; there's a myriad of other constraints the database cannot maintain for you, that may have to do with your specific application logic. It's the app's responsibility to own the data. This is my personal opinion and observation, and it is how I implement apps backed by a relational database. EtcI mentioned how a seemingly small transaction can end up being huge. When you don't have foreign keys, you can go in two different ways:
Let's elaborate on (2). The idea is that it OK to have orphaned rows here and there. The simplest reasoning is that when joined to their respective parent tables, the Eventually those rows pile up, though, and you want to reclaim the space. You can then run cleanup scripts (e.g. in the MySQL world you'd use DELETE FROM child_table LEFT JOIN parent_table ON (child_table.parent_id=parent_table.id) WHERE parent_table.id IS NULL You probably want to only run this a bunch of rows at a time, thus Common practice is to run those cleanups during low traffic time. Hope this helps! |
Beta Was this translation helpful? Give feedback.
@shreyfirst 👋 good question.
First, taking the opportunity to explain why we don't support foreign key constraints:
Now to answer your specific questions:
Duplicating data
I'm not sure the existence/absence of foreign key constraints should have effect on data duplication. You will still model your tables & columns in exactly the same w…