简体   繁体   中英

MySQL, Foreign Key vs Indexed ID column with NOT NULL

Lets say you have Users table and Posts table.

Users

id
name
email

Posts

id
contents
user_id

If I add index to "user_id" in Posts table, and set it as NOT NULL, Can I expect same effect as Foreign Key?

I know that I can set user_id as any number, whereas foreign_key will force you set valid id. Let's assume that user_id is valid. Is there any performance benefit when we set foreign_key?

The main benefit of foreign keys is that they enforce data consistency, meaning that they keep the database clean in other words Keys are Indexes that have Integrity rules applied to prevent corruption of data.

Index is a data structure built on columns of a table to speed up search for indexed records based on values of indexed columns. In other words you gain search speed in exchange of insert/delete speed and storage.

Is there any performance benefit when we set foreign_key?

In performance terms, you will face no improvement.

Foreign keys will impact INSERT, UPDATE and DELETE statements because of the data checking rules , but keep in mind that your data will be consistet .

In MySQL, defining a foreign key constraint automatically creates an index, unless it can use an index that already exists. That is, if you create an index and subsequently add a foreign key on the same column(s), MySQL does not create an extra index just for the foreign key.

If you run a query that needs that index, it doesn't matter if you created the index yourself or if the index was created as a side-effect of adding the foreign key. Either way, the index can help the query. The performance benefit is the same.

If you run a query that does not need that index, then there's no benefit to having index either way.

You didn't describe any specific SQL query, so there's no way for us to guess whether the index is needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM