1

Let's say I have two Oracle SQL queries that I'm using in various places in my code:

select *
from employees
where manager_id IS NULL
and etc etc etc...

and

select *
from employees
where manager_id IS NOT NULL
and etc etc etc...

The only difference between the two queries is that manager_id is NULL in the first one, and NOT NULL in the second one.

Is there any way to write this as one generic statement? Is it possible to pass in NULL or NOT NULL in a parameter? Something like this:

select *
from employees
where manager_id = ?
and etc etc etc...

I know the above example doesn't work (and I know why). My question is more along the lines of is there a more elegant solution than managing two separate SQL strings that are 99% similar?

1
  • @DmitryAgibov Sorry, but this is not a good idea - it would make manager_id non-sargable. Also, the database would need to defend itself from ever getting this "special" value (e.g. through a CHECK). Commented Sep 10, 2018 at 11:49

1 Answer 1

8

You would need to use more complex logic. Perhaps:

where ( (? = 'not null' and manager_id is not null) or
        (? = 'null' and manager_id is null)
      )
Sign up to request clarification or add additional context in comments.

1 Comment

is there a specific term for this approach?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.