Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare only date part when delivery date is today

Tags:

I'm trying to create a report that gets records from a SQL Server database where the delivery date is today.

I've tried

select * from (tablename)
where delivery_date = getdate()

Although that didn't give me any errors, it didn't give me any records either.

I'm assuming it is because all dates are like:

2016-03-15 00:00:00.000

Perhaps, I need to truncate the date to remove the time-stamp and then try?

like image 802
user1777929 Avatar asked Mar 15 '16 18:03

user1777929


People also ask

How can I compare only date parts in SQL?

To compare dates without the time part, don't use the DATEDIFF() or any other function on both sides of the comparison in a WHERE clause. Instead, put CAST() on the parameter and compare using >= and < operators. Let's use StackOverflow database to find all user profiles created on a particular date.

How do you compare only the date and not time?

If you want to compare just the date part without considering time, you need to use DateFormat class to format the date into some format and then compare their String value. Alternatively, you can use joda-time which provides a class LocalDate, which represents a Date without time, similar to Java 8's LocalDate class.

Can we compare date with timestamp?

A date, time, or timestamp value can be compared with another value of the same data type, a datetime constant of the same data type, or with a string representation of a value of that data type. Additionally, a TIMESTAMP WITHOUT TIME ZONE value can be compared with a TIMESTAMP WITH TIME ZONE value.


2 Answers

You can try a query like below

select * from (tablename)
where CAST(delivery_date as date) = CAST(getdate() as date)

Also if all delivery dates have time part like 00:00:00.000 for sure then

select * from (tablename)
where delivery_date = CAST(getdate() as date) 

would work as good.

like image 194
DhruvJoshi Avatar answered Oct 21 '22 10:10

DhruvJoshi


If delivery_date is always midnight (00:00:00.000), then compare it like this:

select * from (tablename)
where delivery_date = datediff(d, 0, getdate())

Using datediff like this is a quick way to truncate the time part of a datetime value.

like image 42
SlimsGhost Avatar answered Oct 21 '22 11:10

SlimsGhost