Datetime BETWEEN statement not working in SQL Server Datetime BETWEEN statement not working in SQL Server sql-server sql-server

Datetime BETWEEN statement not working in SQL Server


Do you have times associated with your dates? BETWEEN is inclusive, but when you convert 2013-10-18 to a date it becomes 2013-10-18 00:00:000.00. Anything that is logged after the first second of the 18th will not shown using BETWEEN, unless you include a time value.

Try:

SELECT * FROM LOGS WHERE CHECK_IN BETWEEN     CONVERT(datetime,'2013-10-17')     AND CONVERT(datetime,'2013-10-18 23:59:59:998')

if you want to search the entire day of the 18th. I set miliseconds to 998 because SQL Server was pulling in 2013-10-19 00:00:00:0000 in the query.

SQL DATETIME fields have milliseconds. So I added 999 to the field.


Does the second query return any results from the 17th, or just from the 18th?

The first query will only return results from the 17th, or midnight on the 18th.

Try this instead

select * from LOGS where check_in >= CONVERT(datetime,'2013-10-17') and check_in< CONVERT(datetime,'2013-10-19')


From Sql Server 2008 you have "date" format.

So you can use

SELECT * FROM LOGS WHERE CONVERT(date,[CHECK_IN]) BETWEEN '2013-10-18' AND '2013-10-18'

https://docs.microsoft.com/en-us/sql/t-sql/data-types/date-transact-sql