tags:

views:

57

answers:

2

How can get my index work when i query using Between command?

when i explain the query:

explain select * from table where Date between date1 and date2;

the return actual key be used is NULL, how to used my index in this case?

I have read some documentation from MYSQL, they said BTree index should be used here in order for > < or between query, however it doesnt work in my case.

Pls help

EDIT

explain  select * from table where Date between '2010-05-10 00:00:00' and '2010-06-10 00:00:00';
+----+-------------+--------+------+---------------+------+---------+------+--------+-------------+

| id | select_type | table  | type | possible_keys | key  | key_len | ref  | rows   | Extra       |
+----+-------------+--------+------+---------------+------+---------+------+--------+-------------+

|  1 | SIMPLE      | table| ALL  | date_index    | NULL | NULL    | NULL | 109024 | Using where |
+----+-------------+--------+------+---------------+------+---------+------+--------+-------------+
A: 

you have to make your table lock type "AllPages";

alter table [table] lock allpages
go

after that, you have to create an index on that column (if you can create clustered index);

create nonclustered index ndx1 on [table] (col1, ...)
go

that run;

sp_recompile [table]
go

and finally look at your q-plan again. It should use an index.

Burçin Yazıcı
The OP is using MySQL
nos
yes, I missed that:) I sopposed using sybase
Burçin Yazıcı
A: 

You are comparing a datetime field with strings in a greater_than/less_than comparison. If you use a cast or function (like UNIX_TIMESTAMP()) and transform also the other dates to unixtimestamp, that would do the trick but will destroy the use of the index. Maybe a better solution would be to store the date as unix timestamp in the table and put an index on that. Then, you would only need to do:

select * 
from table 
where DateInUnixTimeStampFormat 
between UNIX_TIMESTAMP(date1) and UNIX_TIMESTAMP(date2)

OR

select * 
from table 
where DateInUnixTimeStampFormat 
> UNIX_TIMESTAMP(date1) and DateInUnixTimeStampFormat < UNIX_TIMESTAMP(date2)
jdelard
Using this query is the same. The actual index used in NULL
sean
I edited my answer. Let me know if it helps you.
jdelard
Yes it work if change to UnixTimeStamp. However i prefer using the datetime datatype, therefore i try using STR_TO_DATE('(2010-3-31 16:24)', '(%Y-%c-%e %H:%i)') to convert it into datetime, but still not working, pls advise
sean
I need to understand more about your use case. Do you always need to limit by day only (i saw you using time of 00:00:00)? or is it between any date and any time? are you using the results of this query to do another join? do all the results contain specific times , i mean, with minutes, seconds, etc or are at certain intervals like only every five minutes?
jdelard