0

I have field a VARCHAR fielddob in mysql table where dates are saved in two format :

1> y-m-d
2> d/m/y

Now I want to select candidates whose dob <= '01/01/1979' (born on or before 01 January, 1979)

but i am unable to understand how to compare these two time formats at once.

is there any way to handle this like either convert one format into another format and then compare.

3
  • 2
    Perhaps take the time to fix this problem by creating a new DATETIME column and updating it with the string values converted to a DATETIME. Commented Jul 30, 2018 at 15:25
  • how you can choice between the two format ?? Commented Jul 30, 2018 at 15:28
  • You should fix the data. But if you can't: where coalesce(date(dob), str_to_date(dob, '%d/%m/%Y')) <= '1979-01-01' Commented Jul 30, 2018 at 15:38

3 Answers 3

1

Your current table design is bad because the dob column is:

  • storing date information as text, and on top of this
  • storing two different date formats in the same column

You absolutely should fix this long term by storing your date information in a proper date/time column.

Here is one temporary workaround:

SELECT *
FROM yourTable
WHERE
    (dob LIKE '%-%' AND STR_TO_DATE(dob, '%Y-%m-%d') < '1979-01-01') OR
    (dob LIKE '%/%' AND STR_TO_DATE(dob, '%d/%m/%Y') < '1979-01-01');
Sign up to request clarification or add additional context in comments.

Comments

1

I almost hate to write this code, but...

...
where str_to_date(dob, if(dob like '%/%', '%d/%m/%y', '%y-%m-%d')) <= '01/01/1970'

Comments

1

You can also use the IFNULL and STR_TO_DATE on the two date formats:

SELECT
    IFNULL(STR_TO_DATE(col_, '%Y-%m-%d'), STR_TO_DATE(col_, '%m/%d/%Y')) AS 'my_date'
    , col_
FROM
    date_test
WHERE 
    IFNULL(STR_TO_DATE(col_, '%Y-%m-%d'), STR_TO_DATE(col_, '%m/%d/%Y')) <= '1979-01-01';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.