How to optimize the following query if the OR operator is used in a join condition to avoid the OR expansion in terms of SQL tuning?
SELECT t1.A, t2.B, t1.C, t1.D, t2.E
FROM t1 LEFT JOIN t2
ON t1.A=t2.A OR t1.B=t2.C;
How to optimize the following query if the OR operator is used in a join condition to avoid the OR expansion in terms of SQL tuning?
SELECT t1.A, t2.B, t1.C, t1.D, t2.E
FROM t1 LEFT JOIN t2
ON t1.A=t2.A OR t1.B=t2.C;
Having OR condition will ignore using indexes. So once you have the following indexes -
t1 (A, B)
t2 (A, C)
You may try below query having UNION ALL clause -
SELECT t1.A, t2.B, t1.C, t1.D, t2.E
FROM t1 LEFT JOIN t2 ON t1.A=t2.A
UNION ALL
SELECT t1.A, t2.B, t1.C, t1.D, t2.E
FROM t1 LEFT JOIN t2 ON t1.B=t2.C;
This query will use index and might perform faster.
Use the NO_EXPAND
hint to prevent OR-expansion:
SELECT /*+ NO_EXPAND */ t1.A, t2.B, t1.C, t1.D, t2.E
FROM t1 LEFT JOIN t2
ON t1.A=t2.A OR t1.B=t2.C;
However, the chances are very small that the above hint will improve your query performance. There is no rule that says OR-expansion is a bad thing. Telling the Oracle optimizer precisely how to do its job is usually a bad idea. Ideally, you want to create useful information by gathering statistics, and let the optimizer do its job.