Kashif Hussain Kashif Hussain - 3 months ago 7
SQL Question

How to use the to_char funtion with different formats based on condition

I want to know how I can use the to_char query in SQL.

Name Gender Salary Start_Date
------- ------- ------- ----------
Sally Female 45000 23/02/2001
Frank Male 23200 15/12/2008


The start_date is in the format DD/MM/YYYY, from my understanding the to_char function allows us to view dates in other formats. How do I use it to show MM/DD/YYYY for Frank only?

MT0 MT0
Answer

How do I use it to show MM/DD/YYYY for Frank only?

Use a CASE statement:

SELECT name,
       gender,
       salary,
       CASE name
         WHEN 'Frank'
         THEN TO_CHAR( start_date, 'MM/DD/YYYY' )
         ELSE TO_CHAR( start_date, 'DD/MM/YYYY' )
       END AS start_date
FROM   your_table;
Comments