Question: I am running a SQL statement with an
union and it runs slowly. Is there an alternative to the UNION SQL
operator?
Answer:
A UNION is highly optimized and really fast, except in cases where
one query finishes long before the other, and Oracle must wait to
get the whole result set before starting sorting.
There are several alternatives to the union SQL operator:
- Use
UNION ALL.
- Execute each SQL separately and merge and
sort
the result sets within your program! Sometimes, an external
sort may be faster.
- Join the tables. This can be kinda slow, but it is an
alternative to using UNION.
- In versions, 10g and beyond, explore the
MODEL clause.
- Use a
scalar subquery.
select
select col1, col2, col3 from Table_1 q1,
select col1,
col2, col3 from Table_2 q2
from dual;
- Try UNION using FULL OUTER JOIN with the NVL function:
It is suggested that this has faster performance than the UNION
operator.
select
empno,
ename,
nvl(dept.deptno,emp.deptno)
deptno, dname
from
emp
full outer join
dept
on
(emp.deptno = dept.deptno)
order by 1,2,3,4;
******************************************
You start by examining the execution plans, and tune them
independently.
A union simply executes two independent
queries and merges the result sets.
There is one tuning trick
you can use if the union contains an ORDER BY or GROUP BY ...
I just came out with a book that discusses this in great detail:
Advanced Oracle SQL Tuning: The Definitive Reference.