Thursday, July 11, 2013

Query from Today and Last XX Days - MySQ

This is a common line i always add to my queries in MySQL and just wanted to back it up here . How do you go about in 1 line with querying data for the last xx days :) having the current date or specific date you want to start from. Yes i got an answer for you :). First thing is you need to apply DATE_FORMAT in the SELECT clause, not the WHERE clause:
SELECT  DATE_FORMAT(createDate, '%m/%d/%Y')
FROM    refugeeTable
WHERE   createDate BETWEEN CURDATE() - INTERVAL 60 DAY AND CURDATE()
Along the way i found out that the CURDATE() returns only the DATE portion of the date. In otherwords, if you store createDate as a DATETIME with the time portion filled, this query will not select the today's records.
In this case, you'll need to use SYSDATE instead:
SELECT  DATE_FORMAT(createDate, '%m/%d/%Y')
FROM    refugeeTable
WHERE   createDate BETWEEN SYSDATE() - INTERVAL 60 DAY AND SYSDATE()
OR (specific dates)
SELECT  DATE_FORMAT(createDate, '%m/%d/%Y')
FROM    refugeeTable
WHERE   createDate BETWEEN ‘2013-07-01’ - INTERVAL 60 DAY AND ‘2013-07-30’

No comments:

Post a Comment

Add any comments if it helped :)