I have almost no experience with backend and database design, so I’m wondering, is it good practise to minimize the number of foreign keys in your database?
For example, let’s consider logging on a search website:
USER --hasA--> SESSION --makes--> QUERY
In this case, there is a one-to-many relationship between the user and the session, and the session has a one-to-many relationship with query. It makes sense for session to have a foreign key for the user_id and for query to have a foreign_key for the session_id, but should the query table have a foreign key for the user_id? Why or why not?
Thanks in advance!
Adding the
user_idtoQUERYwould make the database redundant. That’s why this is mostly bad-practice. It can be necessary as a performance optimization in extreme cases (rarely).Minimizing the number of foreign keys is usually not a design goal because it does not help with anything.
The typical design goal is to have a clean database that models the business domain most naturally. In that sense, don’t add the
user_idtoQUERY. But absolutely do add all FKs which make sense. This does provide clear and noticeable benefit for development cost and application reliability.