I have a date picker FROM DATE and TO DATE.
If the user enters FROM = 5/10/2019
and TO = 5/19/2019
, the data only returns until 5/18
, but does not include 5/19
data.
I would like it to include the 5/19
as well.
I have this T-SQL code:
SELECT * FROM TABLE WHERE DATE >= '5/10/2019' AND DATE <= '5/19/2019'
But my issue is that if the date in the TABLE is 5/19 it will not show
So I need something like this?
SELECT * FROM TABLE WHERE DATE >= '5/10/2019' AND DATE <= (('5/19/2019') + 1)
I need to include the last date as well.
Advertisement
Answer
Your date column probably has a time component. The safest method is:
WHERE DATE >= '2019-05-10' AND DATE < '2019-05-20' -- note one day later
You can express this as:
WHERE DATE >= '2019-05-10' AND DATE < DATEADD(DAY, 1, '2019-05-20')
So you can capture the inputs that you want.
SQL Server will use indexes for conversions to date, so it is also reasonable to do:
WHERE CONVERT(DATE, DATE) >= '2019-05-10' AND CONVERT(DATE, DATE) <- '2019-05-19'
In most databases, such conversions preclude the use of indexes, but SQL Server is an exception.