views:

72

answers:

2

Hey guys, I am just trying to pull all the records from my database who have a rec_date (varchar) stored as m/d/Y and are expired (as in, less than curdate()), and this call isn't giving me what I want:

SELECT member_id, 
       status, 
       DATE_FORMAT(STR_TO_DATE(rec_date, '%m/%d/%Y'), '%Y-%m-%d') AS rec
  FROM members 
 WHERE rec_date > CURDATE() 
   AND status = '1'

I'm obviously doing something wrong, so can you help?

A: 

The right way - is to store data in proper field type. Use "date" type instead of "varchar".

anyway - you can use DATE_FORMAT to format rec_date to string right in WHERE clause and compare it to CURDATE().

zerkms
A: 

I agree with zerkms that appropriate data types should be used whenever possible. Otherwise, you have to use a subquery to convert the string/varchar into a DATE/TIME data type first:

SELECT x.member_id,
       x.status,
       DATE_FORMAT(x.rec_dt, '%Y-%m-%d')
  FROM (SELECT m.member_id,
               m.status,
               STR_TO_DATE(m.rec_date, '%m/%d/%Y') AS rec_dt
          FROM MEMBERS m
         WHERE m.status = '1') x
 WHERE x.rec_dt < CURDATE()
OMG Ponies
Yep, that will do... and I know I'd ideally want to store this under "date" type, but I don't have control over that unfortunately and have to work with what I'm given. I know, sucks, but hey.Thanks again.
Crazy Serb
why do you need in subquery here? terrible solution. why don't use STR_TO_DATE(m.rec_date, '%m/%d/%Y') right in WHERE as i proposed?
zerkms
@OMG: this subquery will be much worse than fullscan with one query. because once the subquery result created in the memory and don't fit in - it will be temporary table on disc, written and readed after, for outer query. you could check it with EXPLAIN ;-)actually you will get the same query plan but with one more step, which will be fullscan too.
zerkms
You save a table scan, for having to update two (or possibly more) places to keep things in sync.
OMG Ponies
@OMG: you're wrong. with my proposal there is only 1 table scan. with your - copying the data from one table to another (temporary) and after that - the same table scan. so you lose in copying.
zerkms