SQL “between” not inclusive

后端 未结 8 1633
情歌与酒
情歌与酒 2020-11-30 17:05

I have a query like this:

SELECT * FROM Cases WHERE created_at BETWEEN \'2013-05-01\' AND \'2013-05-01\'

But this gives no results even tho

相关标签:
8条回答
  • 2020-11-30 17:39

    It is inclusive. You are comparing datetimes to dates. The second date is interpreted as midnight when the day starts.

    One way to fix this is:

    SELECT *
    FROM Cases
    WHERE cast(created_at as date) BETWEEN '2013-05-01' AND '2013-05-01'
    

    Another way to fix it is with explicit binary comparisons

    SELECT *
    FROM Cases
    WHERE created_at >= '2013-05-01' AND created_at < '2013-05-02'
    

    Aaron Bertrand has a long blog entry on dates (here), where he discusses this and other date issues.

    0 讨论(0)
  • 2020-11-30 17:45

    You need to do one of these two options:

    1. Include the time component in your between condition: ... where created_at between '2013-05-01 00:00:00' and '2013-05-01 23:59:59' (not recommended... see the last paragraph)
    2. Use inequalities instead of between. Notice that then you'll have to add one day to the second value: ... where (created_at >= '2013-05-01' and created_at < '2013-05-02')

    My personal preference is the second option. Also, Aaron Bertrand has a very clear explanation on why it should be used.

    0 讨论(0)
  • 2020-11-30 17:48

    Just use the time stamp as date:

    SELECT * FROM Cases WHERE date(created_at)='2013-05-01' 
    
    0 讨论(0)
  • 2020-11-30 17:48
    cast(created_at as date)
    

    That will work only in 2008 and newer versions of SQL Server

    If you are using older version then use

    convert(varchar, created_at, 101)
    
    0 讨论(0)
  • 2020-11-30 17:51

    I find that the best solution to comparing a datetime field to a date field is the following:

    DECLARE @StartDate DATE = '5/1/2013', 
            @EndDate   DATE = '5/1/2013' 
    
    SELECT * 
    FROM   cases 
    WHERE  Datediff(day, created_at, @StartDate) <= 0 
           AND Datediff(day, created_at, @EndDate) >= 0 
    

    This is equivalent to an inclusive between statement as it includes both the start and end date as well as those that fall between.

    0 讨论(0)
  • 2020-11-30 17:56

    You can use the date() function which will extract the date from a datetime and give you the result as inclusive date:

    SELECT * FROM Cases WHERE date(created_at)='2013-05-01' AND '2013-05-01'
    
    0 讨论(0)
提交回复
热议问题