I create a VIEW locally that SELECTs from the remote DB.
The VIEW statement is 2 selects with a UNION. Depending on the records returned a STRING value is used as an identifier so that when I SELECT * FROM VIEW I know where the records came from (i.e.)
CREATE VIEW test_view (fred, john, tom, qty, type)
AS (
SELECT col_a, col_b, col_c, SUM(col_d), 'Type A'
FROM table_1@remote_db
UNION
SELECT col_1, col_2, col_3, SUM(col_4), 'Type B'
FROM table_2@remote_db
GROUP BY
fred,
john,
tom,
type;
When I run a SELECT * FROM test_view it takes 15-20 seconds before anything is returned. If I remove the string identifier ('Type A') it runs instantaneously. Is there a problem sorting and grouping the remote rows with a local string value?
Have a look at the explain plan of your 2 queries and you will see why one is slower as the other.
To see the explain plan execute SET AUTOTRACE ON in SQL*Plus.
Since the "type" column makes the parts of the UNION
mutually exclusive, and since you are grouping on the "type" column, then the GROUP BY of the UNION
is the same as a UNION ALL of each part with a GROUP BY.
So this query could be:
CREATE VIEW test_view (fred, john, tom, qty, type)
AS (
SELECT col_a, col_b, col_c, SUM(col_d), 'Type A'
FROM table_1@remote_db
GROUP BY col_a, col_b, col_c
UNION ALL
SELECT col_1, col_2, col_3, SUM(col_4), 'Type B'
FROM table_2@remote_db
GROUP BY col_1, col_2, col_3;
Notice that each part of the UNION (including the GROUP BY)
can be processed by the remote database,
instead of performing the GROUP BY on the local side.
Bookmarks