I'm presenting a query wherein I want to pull only the earliest date from a table that has two date fields. It is possible that both date fields are null. However, I only want to pull values if at least one of the fields is not null. Also, if the first date field is not null, then I want that value. In other words, I prefer the first date field.
Here is what I've come up with, but I don't feel 100% this is correct. And, I'm also thinking there's a better way to skin the proverbial cat.
Select
o.order_num,
Case
when ro.pay1_date is not null then ro.pay1_date
when ro.pay2_date is not null then ro.pay2_date
End as funding_date
From orders o
left join recon_order ro on(ro.order_id = o.order_id)
Where (ro.pay1_date is not null or ro.pay2_date is not null)
Order by funding_date desc
Limit 500
I first ran this query without the Where clause, but that just returned 500 Null values, which I never completely understood.
And as a side note I'm working with an older version of PostgreSQL 8.1 (not my choice). But just saying this because perhaps the old version won't support certain new query syntax.
Thanks in advance for any input that corrects or improves this!