5
Arfmann
90d

I'm studying Databases and I'm getting confused about Foreign Key.
A Foreign Key made reference to Primary Key of another table. But what's the point? Can't I simply use a value and select requested data where TableA value is equal to TableB value?
Sorry if I didn't explain it well, I'm so confused lmao

Comments
  • 11
    Foreign keys are used to enforce certain data-integrity rules.
    Eg, every Post is linked to a user by their UID.
    But what if the user removes their account?
    Without a foreign key, you'd now have a post with a dangling reference to a user that doesn't exist anymore.
    However, if you set post.userid as a foreign key to users.id the DB can autoremove/correct the post entry.
    Also, noone can fuck with the DB and create a Post without a valid userid.
  • 4
    @metamourge so basically a foreign key is used to maintain data integrity. Thanks for the explanation!
  • 4
    @Arfmann
    Pretty much.
    They are used to model table-relations, which are then in turn used to maintain data-integrity and stuff.
  • 0
    @metamourge you are so good at explaining stuff
  • 1
  • 2
    @metamourge pretty good explanation.
  • 0
    Try messing around with Liferay's database. You'll understand WHY very quickly.

    No integrity, no protection from removing data required to other entities, no data map at all. By looking at such databases w/o relations I cannot tell how tf are portletitem and layout tables related. I know they are, but no idea how. Can I update portletitem safely? Can I update layouts w/o killing portlets... ? Who's to say...
Add Comment