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
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]);
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.