Should I add an index for all fields in the WHERE clause? - MySQL

In my program I have very few inserts, and any which are run frequently are not needed instantly and therefore have been changed to INSERT DELAYED. Should I go through my code and see which fields are referenced in the WHERE clause and add an index for each of them? If so what type of index do I use? Is it just inserts that are slowed down?

Also can I use these indexes on any data type?


There are two major places where we can consider indexing: columns referenced in the WHERE clause and columns used in JOIN clauses. In short, such columns should be indexed against which you are required to search particular records.

  • Only index those columns that are required in WHERE and ORDER BY clauses. Indexing columns in abundance will result in some disadvantages.
  • Use the NOT NULL attribute for those columns in which you consider the indexing, so that NULL values will never be stored.
  • Use the --log-long-format option to log queries that aren’t using indexes. In this way, you can examine this log file and adjust your queries accordingly. Also slow-query log.
  • The EXPLAIN statement helps you to reveal that how MySQL will execute a query. It shows how and in what order tables are joined. This can be much useful for determining how to write optimized queries, and whether the columns are needed to be indexed.

This blog is good.

Don't go changing your queries before you see a performance problem - that's premature optimization. Instead, use MySQL query log to see which queries are taking a long time, and concentrate on improving those queries.

You should always add an index on any field to be used in a WHERE clause (whether for SELECT, UPDATE, or DELETE). The type of index depends on the type of data in the field and whether you need each row to have a unique value. Generally the default index type (Hash vs. Btree) is best left to the default settings unless you really know what you are doing.

Now whether you use individual indexes (one per field) or compound indexes kind of depends on how the application works and is a more advanced subject, so in general if just getting started just use and index for each field. Note that your primary keys automatically have indexes so you don't need to create another index on those.

Need Your Help

iOS scope bar font SIZE?

ios uitableview uisearchbar

I have implemented a search bar in my UITableview. I have also added a scope bar. However, the words that I am placing in the titles of the five different titles, don't fit. I looked on the Dev ...

ASP.NET MVC Single Sign-on and Roles

c# single-sign-on

I have basic Single Sign-On working across 2 MVC sites (call them SiteA and SiteB) using something along the lines of the following method: