
那么二者有什么区别呢? 本节我们就简单的分析下。
测试环境
建立两个表t1,t2
SQL> create table t1 as select * from dba_objects where object_id is not null;
SQL> alter table t1 modify object_id not null;
SQL> create table t2 as select * from dba_objects where object_id is not null;
SQL> alter table t2 modify object_id not null;
SQL> set linesize 1000
SQL> set autotrace traceonly
union排序
SQL> select object_id from t1
union
select object_id from t2;
索引无法消除union排序
给t1,t2添加索引:
SQL> create index idx_t1_object_id on t1(object_id);
SQL> create index idx_t2_object_id on t2(object_id);
SQL> select object_id from t1
union
select object_id from t2;
添加索引依然存在排序,索引不能消除union排序。一般来说在使用UNION时要确定必要性,在数据不会重复时只需UNION ALL即可。因为union all仅仅是简单的合并查询结果, 并不会做去重操作, 也不会排序, 所以union all效率要比union高。
union all不会去掉重复的记录,没有排序
SQL> select object_id from t1
union all
select object_id from t2;
union all会按照关联的次序组织数据,而union会依据字段出现的顺序进行排序。
扩展
通常如果表有多个索引列时, 用union替换where子句中的or会起到较好的效果, 索引列使用or会造成全表扫描。
注意: 以上规则只针对多个索引列有效, 假如有column没有被索引, 那还是用or吧。
例(还是使用上面的表,假定object_id和object_name上建有索引):
高效的语句:
SQL> select object_id,object_name from t1 where object_name like '%n%
union
select object_id,object_name from t1 where object_id between 10 and 20;
低效的语句:
SQL> select object_id,object_name from t1 where object_name like '%n% or object_id between 10 and 20;








