Mysql – Better Indexing for MySQL

database-designMySQL

Is it better to index each column individually with it's own key or to index multiple columns under the primary key?

I've seen it done both ways in many different applications and I don't see a clear difference.

Best Answer

First of all, your PRIMARY KEY depends on the logical nature of your data and will be indexed automatically by the DBMS. If the PK happens to be composite, it will automatically generate a composite index underneath it. The same goes for UNIQUE constraints and FOREIGN KEYs.

On top of that, under InnoDB, PK also acts as a clustered index.

As for the non-key fields, index based on the expected queries. Assuming your table T has several fields: A, B, C, D (etc.), for a query such as...

SELECT * FROM T WHERE A = '...' AND B = '...'

...create a composite index on {A, B} (or {B, A}), but not on C, D etc.

For the...

SELECT * FROM YOUR_TABLE WHERE A = '...' OR B = '...'

...you'll need a separate indexes on {A} and on {B}.

For both...

SELECT * FROM T WHERE A = '...' AND B = '...'
SELECT * FROM T WHERE A = '...' OR B = '...'

...you'll need indexes on {A, B} and {B} (or {B, A} and {A}).

For both...

SELECT * FROM T WHERE A = '...' AND B = '...'
SELECT * FROM T WHERE A = '...'

...you'll only need an index on {A, B}.

For...

SELECT * FROM T WHERE A = '...' ORDER BY B

...you'll need an index on {A, B}.

Etc, etc...

Do not create indexes that you don't need, since they incur a penalty in storage space and in INSERT/UPDATE/DELETE performance. For more on indexing (and other database performance considerations), I warmly recommend reading: Use The Index, Luke!