0

I was searching for it but could not find any propiate solution for this.

SELECT a, b, c FROM table WHERE d := parameter1 AND e := parameter2;

So if d and e are given, the result query is working. d parameter is always requiered but e is optional so if there is no input for e I dont want to consider the AND e := parameter2 Statement and getting all the rows with only the d parameter.

2
  • (d := parameter1 or parameter1 is null) AND (...) Commented Jul 4, 2018 at 8:19
  • Is column e defined as NOT NULL in the table? If it is, you can use and e = nvl(parameter2,e). Commented Jul 4, 2018 at 8:35

4 Answers 4

3
WHERE d = parameter1 AND (e = parameter2 OR parameter2 is null)

Please be careful about = instead of :=.

Sign up to request clarification or add additional context in comments.

Comments

1
SELECT a, b, c FROM table WHERE d := parameter1 AND (e is not null and e := parameter2 or e is null);

2 Comments

What does not work? Can you provide sample data with expected result?
This will not work as it will consider when value of e is null but he dont want to consider e condition at all.
0

Try this

SELECT a, b, c FROM table WHERE d := parameter1 AND case when e is null then parameter2 else e end := parameter2;

Comments

0

The other answers are generally correct, but you might actually be better using 2 different queries and choosing which one in the calling code. While smarter than the old days, the query plans can get "locked in" based upon the parameters used in the first invocation. If those are atypical you may get plan that is not generally the best. This behaviour will vary between DB engines (Oracle I think is quite good).

Seeing as you already know whether you have a value or not when you make the call, simply execute one bit of SQL or the other.

If you have lots of values then this can get out of hand, but then you also run a larger risk of missing out on the best execution plan.

Comments

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.