0

I need to convert dates of birth from type varchar into date. The table is called "customer" and the column is called "date_of_birth".

The Column has entries where the format of the date is dd.MM.YYYY and dd/MM/YYYY and I want to change every entry of the column.

The code I have right now is:

ALTER COLUMN date_of_birth type date USING to_date(date_of_birth, 'dd.MM.YYYY');

This code would work if the existing entries would all have the format "dd.MM.YYYY. Can someone help me adding the last piece of code, which also uses the other date format that I've mentioned above (dd/MM/YYYY).

I thank you for your time!

2 Answers 2

1

If you only need to deal with those two formats mentioned, you can use a CASE expression:

ALTER TABLE your_table
  ALTER COLUMN date_of_birth type date 
    USING case 
            when date_of_birth like '%/%' then to_date(date_of_birth, 'dd/MM/YYYY')
            else to_date(date_of_birth, 'dd.MM.YYYY')
          end;

If you have more then those two formats, you need to extend the tests to find out which format each value uses.

Sign up to request clarification or add additional context in comments.

Comments

1

If you set datestyle appropriately, the type input function will do that automatically:

SET datestyle = ISO, DMY;

ALTER TABLE xxx
   ALTER date_of_birth TYPE date;

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.