DO NOT be tempted to do such things:
Select * from [User] U where convert(varchar(10),U.DateCreated, 120) = '2014-02-07'
This is the best way:
Select * from [User] U where U.DateCreated >= '2014-02-07' and U.DateCreated < dateadd(day,1,'2014-02-07')
see Sargable (page has been removed from Wikipedia)
EDIT + There are two main reasons to avoid using functions in the data in the where clause (or in join conditions).
- In most cases, using the function for filtering or combining removes the optimizerโs ability to access the index in this field, making the query slower (or more "expensive").
- Another is that at least one calculation is performed for each data row. This can add hundreds, thousands or many millions of calculations to the query, so that we can compare them with one criterion, for example,
2014-02-07 . Itโs much more efficient to change the criteria to match the data.
"Changing the criteria matching the data" is my way of describing "use SARGABLE predicates"
And do not use between them.
best practice with date and time ranges is to avoid BETWEEN and always use the form:
WHERE col> = '20120101' And col <'20120201' This form works with all types and all patches, regardless of whether the temporary part is applicable.
http://sqlmag.com/t-sql/t-sql-best-practices-part-2 (Itzik Ben-Gan)
Used_By_Already Aug 29 '14 at 8:32 2014-08-29 08:32
source share