I have a table in an Oracle DB wich has two indices, one for table field A, one for table field B. Now I need to select all records that have a specific value in field A or another specific value in field B.
To make use of the indices I could of course make one SELECT on field A and then another SELECT on field B. So I can make sure both indices are being used.
However, I would rather do that with one SELECT and both fields in the WHERE clause connected with OR. In such a case and my setup as described above, do you know whether Oracle is smart enough to make use of my two indices, or isn't that possible so that I should stick with those two SELECTs?
Thanks!
You can use a UNION
(or UNION ALL
if you don't want to eliminate duplicates).
select ... from myTable where A = <something>
UNION [ALL]
select ... from myTable where B = <something>
Or you can combine that in one query with an OR, as you have described, and take a look at the query plan to see if the index really is excluded.
Oracle has a very smart optimizer and the whole point of making SQL declarative is that you then spend your time telling the database what you want, and leave the database to decide how best to get it (with a fairly loud caveat, it must be said, as there many situations where you can force the optimizer to make a bad choice: but in my experience, you tend to reach that hurdle somewhat later than with other databases).
What Oracle will probably do, in your case, is to examine:
and then make an informed decision. And that decision will be based on the data current to the time the query is executed (or at least, the last time the statistics were updated). so it may be possible to use hints to force index use, but in doing so you could prevent Oracle from finding the most efficient path through your data at later date, when the data looks vastly different.