Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Oracle SQL NVL return more than one value

I want to list active and inactive employee when pIsActive is null.

pIsActive = (0,1,null)

select e.*
from employee e
where e.id in (1,2,3,4,5)
and (e.isactiv = NVL(pIsActive, (0,1)));

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

NVL and COALESCE will only return a scalar value not a list of values.

Instead, use OR and IN:

SELECT e.*
FROM   employee e
WHERE  e.id IN (1,2,3,4,5)
AND    (  e.isactiv = pIsActive
       OR (pIsActive IS NULL AND e.isactiv IN (0,1))
       );

You could also write the query as:

SELECT e.*
FROM   employee e
WHERE  e.id IN (1,2,3,4,5)
AND    e.isactiv IN ( NVL(pIsActive, 0), NVL(pIsActive, 1) );

But I find the first option to be easier to understand and this second option I have to think about for a while to work out that you are effectively doing e.isactive = pIsActive if pIsActive IS NOT NULL and e.isactive IN (0,1) otherwise.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading