Link to home
Start Free TrialLog in
Avatar of hidrau
hidrauFlag for Brazil

asked on

Better way to make a query with date filter.

Hello guys,

I am working In a company where there are many queries made with this kind of date filter

SELECT * FROM TABLE
WHERE CONVERT(VARCHAR(10),  DATE_ORDER, 112) = CONVERT(VARCHAR(10), GETDATE(), 112)

I am in douts that this is a bad practice, even if I have the field DATE_ORDER indexed, when the filter
is made that way, the index is put aside.

What is the better way to work with date fields and filters?

thanks
Alexandre
SOLUTION
Avatar of Shaun Kline
Shaun Kline
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
The index friendly way is to use this approach:
WHERE  Column >= {startDateAtMidnight}
AND       Column < {nextDayAtMidnight}

Open in new window


.. in other words:

WHERE DATE_ORDER >= CAST(GETDATE()AS DATE)
AND      DATE_ORDER < CAST(DateAdd(d, 1, GETDATE()) AS DATE)

Open in new window

Avatar of hidrau

ASKER

ID: 42007195

How would it be? is it right this way?

  Where CAST(DATE_ORDER AS DATE) >=  cast('20170105' as date) and CAST(DATE_ORDER AS DATE) <= cast('20170210' as date)

Open in new window

ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of hidrau

ASKER

thanks a lot