Thursday, 17 May 2012

Using 'BETWEEN' and 'AND' to retrieve dates in MYSQL

Hi Guys,

Im at work now so I have to be quick!!

Quick word of advice before I forget! I was working on a piece of MYSQL code just now and I realised something. When retrieving data within a specific period, if your datatype for the field to specify is 'timestamp' or 'datetime', PLEASE, convert to date first before you specify the interval.

Example
----------
Customer table has fields:
id int,
name varchar(50),
createdTime  timestamp;

To retrieve data for customers who were created between Jan1,2012 and Jan 31, 2012, use;

select * from Customer where DATE(createdTime) BETWEEN '2012-01-01' AND '2012-01-31'; 

If you don't use the DATE function, for some weird reason, some of the right data is excluded from your select.


Alright, gotta go!
Cheers, fellows!

2 comments:

  1. A very informative article and lots of really honest and forthright comments made! This certainly got me thinking a lot about this issue so thanks a lot for posting!
    Vonage

    ReplyDelete
    Replies
    1. oh Thanks for the encouraging comment neil..

      Delete