1

I am trying to change the type of the data type (from VARCHAR to DATE in PostgreSQL).

Generally the below code works but as you can see there are two date types for cc_active_date. Is there a way to emulate try catch in such scenario so that if casting DD/MM/YYYY fails then it takes YYYY-MM-DD hh:mm:ss?

alter table credit_card.hsbc alter column cc_active_date type date
using to_date(cc_active_date, 'DD/MM/YYYY')

enter image description here

3
  • dba.stackexchange.com/questions/244328/… Commented Nov 25, 2019 at 4:19
  • Seen that, unable to do it, can u give me a simple syntax for alter column? Commented Nov 25, 2019 at 4:22
  • Do you see the part that says "statements" after the BEGIN? I would imagine that's where your ALTER COLUMN goes. Commented Nov 25, 2019 at 4:23

1 Answer 1

2

DATE is very flexible in recognizing the date format, and it already masters your formats. With SET datestyle you can control it so that you don't need to distinguish between cases:

SET datestyle TO ISO, DMY;
ALTER TABLE credit_card.hsbc ALTER COLUMN cc_active_date type DATE
USING cc_active_date::DATE;

An alternative for unsupported formats is an if-condition:

ALTER TABLE credit_card.hsbc ALTER COLUMN cc_active_date type DATE
USING TO_DATE(cc_active_date, CASE WHEN cc_active_date ~ '^\d{2}/\d{2}/\d{4}$' THEN 
    'DD/MM/YYYY' ELSE 'YYYY-MM-DD hh:mm:ss' END);

But I would only use something like this if the simpler variant doesn't work.

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

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.