Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

My Sql Date comparision including given date range

Tags:

sql

mysql

I have date stored as updatedOn (values like '2012-11-12 12:38:43')

My queries is:

select * from mytable 
where updatedOn >= '11/12/2012' AND updatedOn <= '11/12/2012'

My goal is to get all records inclusive given from & to dates

like image 330
hemu Avatar asked Sep 28 '26 11:09

hemu


2 Answers

If you avoid <= and use < instead, you end up being forced to use logic that works regardless of whether or not your data has a time component.

SELECT
  *
FROM
  myTable
WHERE
      updatedOn >= '2012-12-11'
  AND updatedOn <  '2012-12-11' + INTERVAL '1' DAY
like image 56
MatBailie Avatar answered Sep 30 '26 01:09

MatBailie


You need to take the DATE() component of your updatedOn column and format your date literals in one of the formats supported by MySQL:

SELECT *
FROM   mytable
WHERE  DATE(updatedOn) BETWEEN '2012-12-11'
                           AND '2012-12-11'

Or else, use MySQL's STR_TO_DATE() function to convert your strings to MySQL dates:

SELECT *
FROM   mytable
WHERE  DATE(updatedOn) BETWEEN STR_TO_DATE('11/12/2012', '%d/%m/%Y')
                           AND STR_TO_DATE('11/12/2012', '%d/%m/%Y') 
like image 20
eggyal Avatar answered Sep 30 '26 00:09

eggyal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!