SQL Date Comparison – How to filter Datetime in SQL Server – SQL Training Online
In this video, I show you how to do a SQL Date Comparison in SQL Server when your Datetime has an actual time in it. I also include the latest trick that will make this easier if you are using SQL Server 2008 or SQL Server 2012.
How do you compare a Datetime in SQL Server?
A SQL Datetime stores both Date and Time. So when you are filtering using the SQL Where clause, you have to know if you Datetime is storing the time also.
Let’s take a look at the employee table in SQL Training Online Simple DB
The column we are looking at is the hire date. I want to go after the person who was hired on February, 22 2005. So, I use the following SQL.
Now, this works because we don’t have any times stored in this column. But, if I change the record from 2005-02-22 00:00:00.000 to 2005-02-22 08:22:25.000 and rerun the query, you see that I don’t get any results.
That is because the value of 02/22/2005 is really 2005-02-22 00:00:00.000 and I just changed the hire_date to include a time other than 00:00:00.000.
So, I have to tweak my query to use a greater than and less than sign.
This works. But, to really understand what is going on, let me show you what SQL Server really sees.
There are other ways, and in this StackOverflow article you can read more about these other ways. But, I want to point out a few.
If you are working in SQL Server 2005 or earlier, the following is supposed to be the fastest performing way to do this.
select datediff(dd,0, hire_date),*
where dateadd(dd,0, datediff(dd,0, hire_date)) = ‘2005-02-22’
But, if you are working in SQL Server 2008 or SQL Server 2012, they have introduced an actual Date datatype that doesn’t include the Time portion. Since this is the case, you can use the CAST function to remove the time from the Datetime.
Here is the SQL to do that.
where CAST(hire_date AS Date) = ‘2005-02-22’
And that’s it.
If you enjoy the video, please give it a like, comment, or subscribe to my channel.
You can visit me at any of the following:
SQL Training Online: