views:

29

answers:

1

Say I have a query like the following:

SELECT * FROM users WHERE username = 'test' AND somethingelse = 'test'

I'm wondering if it's necessary to index both columns for optimization. Does MySQL first find all username columns with the value 'test', and then search those results for somethingelse columns with 'test'? Or does it happen simultaneously?

+3  A: 

Yes, you should. Every column and combination of columns that appears in a WHERE clause should have an index for efficient searching.

You get away with it for primary key fields because an index is created for those by virtue of being declared a primary key. Other columns require that you index them.

So you'll have an index for username and somethingelse columns.

If username has to be unique, it might have its own index.

duffymo
Is the username+somethingelse you refer to a composite index?
soren.qvist
If you have a username+somethingelse key, you don't also need a username key (for searching; you might need it for a unique constraint).
Brian Hooper
@soren.qvist - yes, that's an index over both.
duffymo
@Brian Hooper - agreed. I'm jumping the gun. I'll edit my answer to reflect that.
duffymo