views:

52

answers:

3

Hello,

I have problem with this query, complexity of this query is not good, i use this query from long time and now this database have many rows to get selecting by this method. All index'es is added propertly. I searching some other method to optimize this query by date comparsion because this is bottleneck in this solution.

SELECT (...) FROM table 
WHERE (YEAR(row_add_date) * 10000 + 
       MONTH(row_add_date) * 100 + 
       DAYOFMONTH(row_add_date)) >= (var_0 * 10000 + var_1 * 100 + var_2) and
      (YEAR(row_add_date) * 10000 + 
       MONTH(row_add_date) * 100 + 
       DAYOFMONTH(row_add_date)) <= (var_3 * 10000 + var_4 * 100 + var_5) 

Can anyone help me? Greetings

+2  A: 

Why are you breaking apart the date like that? Per-row functions do not scale well. It seems to me that the entire date section at the end can be replaced by:

where row_add_date = '2010-10-27'

Even if you want a range, you're still better of using the dates as they are.


Based on your edits to state that you're using variables, you should do the calculation on the right-hand side of the conditions. That's because this will be done once before the query start. With what you have, the calculation on the left side will be done once per row, a definite performance killer.

paxdiablo
Close, it could be replaced with `row_add_date >= '2010-10-27' and row_add_date < '2010-10-28'`
Andomar
Wow, you're right :) completely missed that. it looked so terrible I didn't to try and understand the calculation
Eran Galperin
I updated question, this values are variable and are not equal in query, sorry for miss this.
Svisstack
@Andomar, how is that different than `= '2010-10-27`? Unless you're suggesting the columns at timestamps rather than dates. I assumed otherwise.
paxdiablo
@paxdiablo: I assumed it was a `datetime` column, mainly because SQL Server 2005 doesn't have a `date` type I guess. But if it's a `date` column you are right
Andomar
+2  A: 

I'd suggest using built-in mysql date comparisons.

row_add_date <= '20101027' and row_add_date >= '20101027'

But note that this is a strange test in the first place: aren't just testing that the date is equal to October 27th, like this:

row_add_date = '20101027'
Ned Batchelder
'0'=0 this is '0'=var_1 in practice, i miss this.
Svisstack
Thanks this solved problem and query runs 372 times faster. I trying this but with '-' bettwen values but then this dont work.
Svisstack
A: 

I'm going to guess that row_add_date is of type datetime. If so, you need turn 20101027 into a datetime, and compare the column to that.

In other words:

row_add_date >= firstDateTime and row_add_date <= secondDateTime
egrunin