views:

83

answers:

4

Hi I have a MySQL table, let's say it is a helpdesk ticketing system. It has a CLOSED column, which I want to index. 99% of time, I will need to only select on OPEN tickets, so something like

"SELECT * FROM TICKET_TABLE where CLOSED='N'; "

And over time, more and more tickets are CLOSED, while a small constant number of OPEN tickets remain. OPEN/CLOSED ratio is like 1/99.

I have an index

ALTER TABLE TICKET_TABLE ADD INDEX ( CLOSED );

But this index is not chosen ( I have a bunch of other indexes, which get chosen when I do EXPLAIN ). I can understand this CLOSED index is not good when I query

"SELECT * FROM TICKET_TABLE where CLOSED='Y'; "

but it's perfect when I query

"SELECT * FROM TICKET_TABLE where CLOSED='N'; "

How should I index my table?

+1  A: 

create a single index that spans the closed column and whatever other column you are searching on.

I would recommend not creating any indexes until you figure out what queries are slow. Then come and ask what indexes to create to speed up those queries.

tster
+1  A: 

This is basic index theory.

Index will be utilized only when the data ratio in the query is small enough('selective") like closed='N'.

So in the case closed='Y', full table scan(which is not using index) will be faster than using index.

To make you query faster, try to restrict the condition further. Maybe closing date, or certain customer or area.

exiter2000
The case OP argues is that closed='N' restricts the data to just 1% of the table, but the index isnt' used. He already understands that the closed='Y' case is a bad choice for indexing
leeeroy
No - it is the other way around. closed="Y" has few hits and performs well. closed="N" is 99% of table and index is ignored.
Martin
+2  A: 

One option would be to archive all old tickets that have been closed for a while, to keep the number of rows down. When you need to search over all tickets, you can join the two tables quite easily.

DisgruntledGoat
+1  A: 

You can force mysql to use your index by doing e.g.

"SELECT * FROM TICKET_TABLE FORCE INDEX (name_of_index) where CLOSED='N'; "

mysql can only use 1 index per table for your where clause, maybe it figured one of the other indexes were more appropriate - mysql might select a "wrong" index if its statistics are not up to date. (try e.g. running analyze table on the table).

nos
From version 5.0, multiple indexes can be used in a query - seehttp://dev.mysql.com/doc/refman/5.0/en/index-merge-optimization.html(But I have never been able to make use of it. )
Martin