Developer
Developer

Reputation: 8636

Mysql query help to display results less than given date

I am having my date field in Mysql which is stored as char is as follows 050712.. Now I would like to display the results which are available in the database which are less than this date. I write as follows

Condition should fail

select * from tblFedACHRDFI where date_format(changedate,'%m/%d/%Y')> 05/08/12;

This is displaying all records which are available but I don't need that I would like to display only when date is 05/06/12 which means

True Condition

select * from tblFedACHRDFI where date_format(changedate,'%m/%d/%Y')> 05/06/12;

The same worked for me in Sqlserver when I write as follows

Records not getting displayed which is true as per my requirement

select * from tblFedACHRDFI where
 CONVERT(datetime,(SUBSTRING(ChangeDate,1,2)+'/'
+SUBSTRING(ChangeDate,3,2)+'/'+dbo.Years
(SUBSTRING(ChangeDate,5,2))+SUBSTRING(ChangeDate,5,2)))>
 '05/08/2012'

So can any one help me where I went wrong in MySql statement..

Upvotes: 1

Views: 6288

Answers (1)

Konerak
Konerak

Reputation: 39763

A MySQL date should be YYYY-MM-DD, column type should be DATE.

If you wish to store a date any other way (for example, a CHAR(6) as you do here), you'll have to use conversions each time you use the date. This is slower, uses more CPU, and can fail because you can store invalid values in your CHAR field.

It does work, however. Use the STR_TO_DATE function to convert your CHAR column to a proper date. Now you can compare it against a proper date, use INTERVAL functions, the whole shebang:

select * 
from tblFedACHRDFI 
where str_to_date(changedate,'%m%d%Y') > "2012-08-05";

Upvotes: 3

Related Questions