Select * from [User] U where U.DateCreated = '2014-02-07'
but in the database the user was created on 2014-02-07 12:30:47.220
and when I only put '2014-02-07'
It does not show any data
The right way to compare date only values with a DateTime column is by using <= and > condition. This will ensure that you will get rows where date starts from midnight and ends before midnight e.g. dates starting with '00:00:00.000' and ends at "59:59:59.999".
like: select USER_NAME,USER_EMAIL from table1 where Expiry_Date='2016-03-12';
Use the datetime Module and the < / > Operator to Compare Two Dates in Python. datetime and simple comparison operators < or > can be used to compare two dates. The datetime module provides the timedelta method to manipulate dates and times.
DON'T be tempted to do things like this:
Select * from [User] U where convert(varchar(10),U.DateCreated, 120) = '2014-02-07'
This is a better way:
Select * from [User] U where U.DateCreated >= '2014-02-07' and U.DateCreated < dateadd(day,1,'2014-02-07')
see: What does the word “SARGable” really mean?
EDIT + There are 2 fundamental reasons for avoiding use of functions on data in the where clause (or in join conditions).
2014-02-07
. It is far more efficient to alter the criteria to suit the data instead. "Amending the criteria to suit the data" is my way of describing "use SARGABLE
predicates"
And do not use between either.
the best practice with date and time ranges is to avoid BETWEEN and to always use the form:
WHERE col >= '20120101' AND col < '20120201' This form works with all types and all precisions, regardless of whether the time part is applicable.
http://sqlmag.com/t-sql/t-sql-best-practices-part-2 (Itzik Ben-Gan)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With