Вопрос

I'm using Postgres 9.1. The following query does not work as expected. Coalesce should return the first non-null value. However, this query returns null (1?) instead of the date (2).

select COALESCE(
    TO_DATE('','yyyymmdd'), --(1)
    TO_DATE('20130201','yyyymmdd') --(2)
    );

--(1) this evaluates independently to null
--(2) this evaluates independently to the date,
--    and therefore is the first non-null value

What am I doing wrong? Any workaround?

Edit: This may have nothing to do with Coalesce at all. I tried some experiments with Case When constructs; it turns out, Postgres has this big ugly bug where it treats TO_DATE('','yyyymmdd') as not null, even though selecting it returns null.

[PS: Strike-out above to avoid misleading. Postgres doesn't have a bug, but rather does not treat empty strings as null. See answer.]

Это было полезно?

Решение

SELECT TO_DATE('','yyyymmdd');

doesn't evaluates to NULL since you passing an empty string instead of NULL as an argument to TO_DATE()

This will successfully evaluate to NULL

SELECT TO_DATE(NULL,'yyyymmdd');

If you expect an empty string and want to treat it as a NULL you can use NULLIF()

SELECT TO_DATE(NULLIF(dt, ''),'yyyymmdd')
  FROM 
(
  SELECT CAST('' AS VARCHAR(32)) dt
) q

That being said your sample code that evaluates (1) as NULL

SELECT COALESCE(
    TO_DATE(NULLIF('', ''),'yyyymmdd'),       --(1)
    TO_DATE(NULLIF('20130201',''),'yyyymmdd') --(2)
);

and returns

|                        COALESCE |
-----------------------------------
| February, 01 2013 00:00:00+0000 |

Here is SQLFiddle demo

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top