An article about Optimizing your SQL queries has suggested to use Union insted of OR `cause:
Utilize Union instead of OR
Indexes lose their speed advantage when using them in OR-situations in
MySQL at least. Hence, this will not be useful although indexes is
being applied 1 SELECT * FROM TABLE WHERE COLUMN_A = ‘value’ OR
COLUMN_B = ‘value’On the other hand, using Union such as this will utilize Indexes.
1- SELECT * FROM TABLE WHERE COLUMN_A = ‘value’
2- UNION
3- SELECT * FROM
TABLE WHERE COLUMN_B = ‘value’
How much this suggestion is true? Should I turn my OR queries to Union?
I do not recommend this as a general rule. I don’t have MySQL installed here so can’t check the generated execution plan, but certainly in Oracle the plans are much different and the ‘OR’ plan is more efficient than the ‘UNION’ plan. (Basically, the ‘UNION’ has to perform two SELECT’s and then merge the results – the ‘OR’ only has to do a single SELECT). Even a ‘UNION ALL’ plan has a higher cost than the ‘OR’ plan. Stick with the ‘OR’.
I very strongly recommend writing the clearest, simplest code you possibly can. To me, that means you should use the ‘OR’ rather than the ‘UNION’. I’ve found over the years that attempting to “pre-optimize” something, or in other words to guess where I’ll encounter performance problems and then to try and code around those problems, is a waste of time. Code tends to spend a lot of time in the darndest places, and you’ll only find them once you’ve got your code running. A long time ago I learned three rules that I’ve found to be useful in this context:
Optimization is literally the last thing you should be doing.
Share and enjoy.
Followup: I hadn’t noticed that the ‘OR’ was looking at different columns (my bad), but my advice regarding “keep it simple” still holds.