Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare datetime with only date in SQL Server

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

like image 697
Muhabutti Avatar asked Aug 29 '14 08:08

Muhabutti


People also ask

Can we compare date with datetime in SQL?

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".

How compare only date not time in SQL query?

like: select USER_NAME,USER_EMAIL from table1 where Expiry_Date='2016-03-12';

How do you compare datetime dates?

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.


1 Answers

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).

  1. In most cases using a function on data to filter or join removes the ability of the optimizer to access an index on that field, hence making the query slower (or more "costly")
  2. The other is, for every row of data involved there is at least one calculation being performed. That could be adding hundreds, thousands or many millions of calculations to the query so that we can compare to a single criteria like 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)

like image 156
Paul Maxwell Avatar answered Oct 01 '22 14:10

Paul Maxwell