Compare dates in Oracle SQL

All we need is an easy explanation of the problem, so here it is.

I have a table LoanDeadline that has a column called deadline, it’s simple text and not Date and it’s in the format of

July 25, 2014

How do I compare this with sysdate ?
So far I have

SELECT 'YOUR LOAN IS APPROVED'
FROM LOANDEADLINE LD
WHERE SYSDATE < LD.DEADLINE;

But this doesnt work because my SYSDATE and LD.DEADLINE are different data types.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

WHERE SYSDATE < to_date( LD.DEADLINE, 'Month DD, YYYY' );

would work assuming all your data is perfect and that all your session are configured to use English month names. I would strongly recommend, however, that you fix the data model. Storing strings that represent dates rather than actual dates is a terrible practice. Inevitably, you end up with at least a handful of columns where the data is invalid which would cause this query to fail. You could work around that by creating a function that attempts to convert the string to a date and catches the exception if there is an error and then use that function in your query, i.e.

CREATE OR REPLACE FUNCTION my_to_date( p_str IN VARCHAR2, p_format IN VARCHAR2 )
  RETURN date
IS
BEGIN
  RETURN to_date( p_str, p_format );
EXCEPTION
  WHEN others
  THEN
    RETURN NULL;
END;

and then

WHERE SYSDATE < my_to_date( LD.DEADLINE, 'Month DD, YYYY' );

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply