Skip to content
Advertisement

Case when date = current_date then text

I have a table like this:

| id | token_date |
|----|------------|
| 10 | 2020-03-24 |
| 14 | 2020-03-25 |
| 16 | 2020-03-26 |
|  9 | 2020-03-26 |
| 21 | 2020-03-27 |
| 25 | 2020-03-28 |

But when I execute this query:

SELECT token_date = CURRENT_DATE AS "is_equal",
       CASE
          WHEN token_date=CURRENT_DATE THEN 'TODAY'
          ELSE token_date
       END AS "result"
FROM DATA

I get this result:

| is_equal |     result |
|----------|------------|
|    false | 2020-03-24 |
|    false | 2020-03-25 |
|     true | 2020-03-26 |
|     true | 2020-03-26 |
|    false | 2020-03-27 |
|    false | 2020-03-28 |

SQL Fiddle

I would expect that in the rows where is_equal is true, the result should be TODAY. What am I doing wrong?

Advertisement

Answer

Nevermind, I solved it, but I don’t want to discard the question. The solution is to CAST(token_date as varchar) in the else clause

Edit: See @a_horse_with_no_name ‘s comment – it is better to use the to_char function to format the date to get a consistent output.
E.g. to_char(token_date, 'yyyy-mm-dd')

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement