-2

Need suggestion as due to performance improvement i need to convert all loop queries to IN clause. I have following where conditions which may vary based on iteration..

Where recordID=2323 and (origin=626 or destination=319);
Where recordID=2323 and (origin=319 or destination=789);
Where recordID=2323 and (origin=567 or destination=989);
Where recordID=2323 and (origin=767 or destination=626);

For performacne improvement i want to convert those queries to IN Clause like this..

  Where recordID=2323 and (origin IN(626,319,567,767) or destination IN (319, 789, 989, 626));

My question is the results count from both approach will be the same? Is there any other approach or any other way to do this.

Problem is my final count is not samilar compare to each approach.

Prashant Katara
  • 95
  • 1
  • 1
  • 14

1 Answers1

1

Unfortunately, there is not great way to optimize queries with or conditions on different columns. If the query is simple, you can use union all:

select t.*
from t
where recordID = 2323 and origin = 626
union all
select t.*
from t
where recordID = 2323 and destination = 319 and origin <> 626;

This version of the query can then make use of two indexes:

  • (recordID, origin)
  • (recordID, destination, origin)

EDIT:

If you don't care about performance, then your method with in is fine -- and equivalent to your original logic.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
  • Thanks Gordon for quick response, Union all can solve problem but my java program iterations will change origin/destination every time and I will end up with multiple execution. Like last iteration was 1000. – Prashant Katara Nov 06 '20 at 13:29