Search code examples
sqlpostgresqldatepostgresql-9.3

Where Criteria on empty field


Consider I have a table Plan with following values.

planName(VARCHAR2) | validFrom(timestamp) | validTo(timestamp)
---------------------------------------------------------------
planA              |         20-10-2013   |

What select query should I write with a where criteria on 'validTo' field so that to obtain that row even if the value is empty in 'validTo'

for Example, if I write the query like :-

select * 
from plan 
where validFrom > to_Date('20-10-2013', 'DD-MM,YYYY') 
  and validTo < to_Date('31-12-2029', 'DD-MM,YYYY')

and obtaining result like

planName(VARCHAR2) | validFrom(timestamp) | validTo(timestamp)
---------------------------------------------------------------
                   |                      |

but I need to fetch that row also.


Solution

  • Thanks every one I got the approach, hope this will support others too.

    select * from plan where COALESCE(validFrom , to_date('12/10/2799', 'DD/MM/YYYY')) > to_Date('20/10/2013', 'DD/MM/YYYY') AND COALESCE(validFrom , to_date('1/01/1700', 'DD/MM/YYYY'))< to_Date('31/12/2029', 'DD/MM/YYYY'); 
    

    If the value is null COALESCE() will compare with the next not null value.

    COALESCE is an alternate approach to NVL.