The UNION operator is great for merging the results of multiple
queries that return similar rowsets, essentially executing each
query separately and merging the results together into a single
result set. This is especially useful for merging remote tables
using database links:
select * from fact_table@new_york
union
select * from
fact_table@denver;
Whenever we need to address multiple tables in a single operation
and we know that there will be no duplicate rows, we can use the
UNION ALL statement to merge the tables together, as follows:
select * from fact_table_1_2011
union all
select * from
fact_table_2_2011
union all
select *
from fact_table_3_2011
order by
order_year,
order_month;
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.
However, there are several alternatives to the union SQL
operator:
- Use UNION ALL: The UNION ALL may be faster when you don't
mind the possibility of having duplicate rows in the result set.
- Execute each SQL separately and merge and
sort
the result sets within your program! Sometimes, an external
sort may be faster.
- Join the tables manually. This is slow and inefficient.
- In versions, 10g and beyond, use the
MODEL clause can simulate the behavior of the UNION clause.
- Use a
scalar subquery. Here we see a scalar subquery equivalent
to a UNION operator:
select * from
(select col1, col2, col3
from Table_1) q1,
(select col1, col2, col3 from Table_2) q2;
- Use an in-line view: Starting in Oracle 11g release 2,
the optimizer starts rewriting UNION ALL queries with the
Join
Factorization transformation (JFT) that rewrites some UNION ALL
queries into in-line views.
- Re-write the UNION using
a 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;
When tuning alternatives to UNION or UNION ALL, you always
start by comparing and examining the execution plans, and tune each
alternative independently, using the SQL*Plus �set timing on� to
compares real run times. See here, the ways to
tune SQL
queries by changing execution plans.
|
|
Get the Complete
Oracle SQL Tuning Information
The landmark book
"Advanced Oracle
SQL Tuning The Definitive Reference" is
filled with valuable information on Oracle SQL Tuning.
This book includes scripts and tools to hypercharge Oracle 11g
performance and you can
buy it
for 30% off directly from the publisher.
|