Converting a character column containing dates to a DATE column in Oracle

I have a table with a column called hold_dt which is of type VARCHAR2. I use it to 'hold' the date field stored as a character, formatted as ddmmyy. I also have a date column in the same table which is of type DATE. How do I use the hold_dt column to populate the real date column?
This problem requires that the database be capable of converting a character string to a date. Fortunately, most are. Sadly, they all do it differently. However, the considerations for dealing with the conversion apply to all databases, so since you're using Oracle, let's look at the problem using Oracle's TO_DATE() function --

update yourTable
   set theDatefield = TO_DATE(hold_dt,'DDMMYY')

There are several things to watch out for:

  • NULLs in hold_dt will give NULLs in theDatefield

    If you want to set a valid date instead, use COALESCE() --

    update yourTable
       set theDatefield = TO_DATE(COALESCE(hold_dt,'311299'),'DDMMYY')
  • invalid dates in hold_dt will cause exceptions

    If you have blanks, for example, do two passes --

    update yourTable
       set theDatefield = TO_DATE(hold_dt,'DDMMYY')
     where hold_dt <> '';
    update yourTable set theDatefield = TO_DATE('311299','DDMMYY') where hold_dt = '';
  • converted dates will include times that default to midnight

    Oracle DATE fields include a time. If you later want to compare the converted dates against, say, SYSDATE, chances are infinitessimal that they will match (those chances being the same as the query running at exactly midnight). Use TRUNC() to compare just the date portions --

    select "a hit! a palpable hit!"
      from yourTable
     where TRUNC(theDatefield) = TRUNC(SYSDATE)

Philip Greenspun has a very informative article on Oracle Dates on the Arsdigita web site. (Note: Arsdigita has been sold so that URL may not last forever.)

For More Information

  • What do you think about this answer? E-mail the edtiors at [email protected] with your feedback.
  • The Best SQL Web Links: tips, tutorials, scripts, and more.
  • Have an SQL tip to offer your fellow DBAs and developers? The best tips submitted will receive a cool prize. Submit your tip today!
  • Ask your technical SQL questions -- or help out your peers by answering them -- in our live discussion forums.
  • Ask the Experts yourself: Our SQL, database design, Oracle, SQL Server, DB2, metadata, object-oriented and data warehousing gurus are waiting to answer your toughest questions.

Dig Deeper on Oracle and SQL