Search code examples
mysqldatabasedatabase-designdatabase-optimization

Worth adding indexes on a column just to make them a foreign key?


I have an invitations table in my database, which has got a from and to columns, which are both foreign keys for the userId column in my users table.

For example, if User # 1 invited User # 2 to do something, then in the invitations table, from will be 1, and to will be 2.

I will use the to column in where statements, such as:

SELECT * FROM invitations WHERE `to` = $currentUserId

But the from column will never be used in WHERE statements.

From what I've read, you should only add an index on the columns which will be used in WHERE statements, however I've also read that you should always create Foreign keys.

Does it make sense for me to create an index on from just to add a foreign key?


Solution

  • In the case of foreign keys, you should add one depending on what you do with users.

    Internally, your fkeys will fire an action on any insert/update/delete of invitations, but also on any update/delete of users(id).

    The first of these will use the index on users(id) to check if the user exists.

    The other will essentially run a query that goes: do whatever you defined to do on update/delete from invitations where to/from = :id.

    So, if you change the id of users (very unlikely) you can make use of an index. And if you occasionally delete users (only slightly more likely), you can make use of the index.

    And as point out in the other answer, indexes are also useful for queries with an order by/limit clause.