简体   繁体   中英

Matching value on date (year, month, day) but not time

In this answer , it's suggested to use teh following syntax for matching against a given date, all day long.

select * from Info
  where DateColumn 
    between '2014-08-25 00:00:00' 
    and '2014-08-25 23:59:59'

Besides the fact that we're missing the last second of each day, which practically perhaps isn't a large issue but principally might be a deal-breaker, I don't see why not use the simple expression below.

The matching is done with on a semi-open interval with the upper bound being exclusive (ie fromAndInclusive <= date < toButNotInclusive ) and a date without any time specified is assumed to be at midnight (ie 00:00:00.000).

select * from Info
  where DateColumn 
    between '2014-08-25' and '2014-08-26'

Please note that I'm not even close to be claiming any level of competence when it comes to SQL so this question shouldn't be been as pointing out any errors. I'm cocky otherwise but when it comes to DBs, I've been humbled once or twice. :)

Both will return incorrect results.

Between is inclusive at both ends so your first query

select * from Info
  where DateColumn 
  between '2014-08-25 00:00:00' 
  and '2014-08-25 23:59:59'

will ignore anything in the last second of 2014-08-25 as you point out.

The second query you propose is too greedy. It will include anything at exactly midnight on the 26th ie 2014-08-26 00:00:00 .

select * from Info
  where DateColumn 
  between '2014-08-25' and '2014-08-26'

To get the results you need you should use >= and < (as @Lamak) points out in the comments:

select * from Info
  where DateColumn >= '2014-08-25' and DateColumn < '2014-08-26'.

Given the following data in the table:

2014-08-25 23:59:59
2014-08-25 23:59:59.500
2014-08-26 00:00:00
2014-08-26 00:00:00.500
2014-08-26 00:00:01

The first query matches just:

2014-08-25 23:59:59.000

The second matches:

2014-08-25 23:59:59.000
2014-08-25 23:59:59.500
2014-08-26 00:00:00.000 --this is wrong!

and finally the third (correctly) matches:

2014-08-25 23:59:59.000
2014-08-25 23:59:59.500
select * from Info
  where DateColumn >='2014-08-25 00:00:00' 
    and datecolumn<='2014-08-25 23:59:59'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM