MySQL Index's

Robert Granlund
Robert Granlund used Ask the Experts™
MySQL Database.  How many INDEX's should a table have?  What indexs should they be? Primary, Foreign?  What is the best setup?
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2012
Distinguished Expert 2018

>>How many INDEX's should a table have?

As many as it needs.  Indexes are based on usage.  You need to look at how the applications use the data and created indexes to benefit the queries.

OVER INDEXING is almost just as bad as under indexing.

>>What indexs should they be? Primary, Foreign?

A table can only have one primary key.  Foreign keys are based on the tables relationships so as many as you need.

>>What is the best setup?

It is based on the applications
Most Valuable Expert 2018
Distinguished Expert 2018
There's no right or wrong answer in how many they should have. As pointed out above, it will all depend on your table, the realtionship of that table to other tables and how you query your table.

As a general rule of thumb, add one Primary Key Index - this is used to uniquely identify the record. It can be something meaningful, such as a Customer ID, Order ID etc, or something more arbitrary, like an AutoIncrementing ID Field.

Then think about the fields in your table that would allow you to link to another table. These will be the Foreign Keys (generally relating to  a Primary Key from another table). This should be Indexed.

Now think about the fields that you commonly search on. It makes sense to add an index to these columns, as it helps performance.

You can also add a Unique Index to a column (or group of columns) to enforce some data integrity. For example, you may add a Unique Index to an Email column to prevent 2 users registering the same address.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial