In a more generic case, where you can have duplicates in both tables, this could be a way.
test data:
create table table1(id) as ( select 1 from dual union all select 1 from dual union all select 2 from dual union all select 2 from dual union all select 1 from dual ) create table table2(fk_id) as ( select 1 from dual union all select 1 from dual union all select 1 from dual union all select 3 from dual union all select 4 from dual union all select 1 from dual union all select 4 from dual union all select 2 from dual )
query:
with tab1_union_all_tab2 as ( select 'tab1'||rownum as uniqueId, id from table1 UNION ALL select 'tab2'||rownum , fk_id from table2 ) select id from tab1_union_all_tab2 u1 where not exists ( select 1 from tab1_union_all_tab2 u2 where u1.id = u2.id and u1.uniqueId < u2.uniqueId )
result:
ID ---------- 3 4 1 2
This should clarify the idea behind:
with tab1_union_all_tab2 as ( select 'tab1'||rownum as uniqueId, id from table1 UNION ALL select 'tab2'||rownum , fk_id from table2 ) select uniqueId, id, ( select nvl(listagg ( uniqueId, ', ') within group ( order by uniqueId), 'NO DUPLICATES') from tab1_union_all_tab2 u2 where u1.id = u2.id and u1.uniqueId < u2.uniqueId ) duplicates from tab1_union_all_tab2 u1 UNIQUEID ID DUPLICATES ---------- ---------- -------------------------------------------------- tab11 1 tab12, tab15, tab21, tab22, tab23, tab26 tab12 1 tab15, tab21, tab22, tab23, tab26 tab13 2 tab14, tab28 tab14 2 tab28 tab15 1 tab21, tab22, tab23, tab26 tab21 1 tab22, tab23, tab26 tab22 1 tab23, tab26 tab23 1 tab26 tab24 3 NO DUPLICATES tab25 4 tab27 tab26 1 NO DUPLICATES tab27 4 NO DUPLICATES tab28 2 NO DUPLICATES
As rightly observed by Thorsten Kettner, you can easily edit this to use rowid instead of building a unique id by concatenating a string and the rownum:
with tab1_union_all_tab2 as ( select rowid uniqueId, id from table1 UNION ALL select rowid , fk_id from table2 ) select id from tab1_union_all_tab2 u1 where not exists ( select 1 from tab1_union_all_tab2 u2 where u1.id = u2.id and u1.uniqueId < u2.uniqueId )