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.]