SQL “between” not inclusive

后端 未结 8 1634
情歌与酒
情歌与酒 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 18:00

    Dyamic date BETWEEN sql query

    var startDate = '2019-08-22';
    var Enddate = '2019-10-22'
         let sql = "SELECT * FROM Cases WHERE created_at BETWEEN '?' AND '?'";
         const users = await mysql.query( sql, [startDate, Enddate]);
    
    0 讨论(0)
  • 2020-11-30 18:04

    It has been assumed that the second date reference in the BETWEEN syntax is magically considered to be the "end of the day" but this is untrue.

    i.e. this was expected:

    SELECT * FROM Cases 
    WHERE created_at BETWEEN the beginning of '2013-05-01' AND the end of '2013-05-01'

    but what really happen is this:

    SELECT * FROM Cases 
    WHERE created_at BETWEEN '2013-05-01 00:00:00+00000' AND '2013-05-01 00:00:00+00000'
    

    Which becomes the equivalent of:

    SELECT * FROM Cases WHERE created_at = '2013-05-01 00:00:00+00000'
    

    The problem is one of perceptions/expectations about BETWEEN which does include BOTH the lower value and the upper values in the range, but does not magically make a date the "beginning of" or "the end of".

    BETWEEN should be avoided when filtering by date ranges.

    Always use the >= AND < instead

    SELECT * FROM Cases 
    WHERE (created_at >= '20130501' AND created_at < '20130502')

    the parentheses are optional here but can be important in more complex queries.

    0 讨论(0)
提交回复
热议问题