sql优化之多列索引的使用
在一个表的多列上建立索引create index ind_t on t(id,object_id,owner);查询的where 条件中只有包含了索引第一列才会使索引生效。下面的使用情况使索引生效;select * from t where id=20;select * from t where id=20 and owner='SCOTT';select * from t where id=20 and object_type='TABLE';包含第一列,索引就会生效。没有包含第一列,索引将失效。eg:select * from t where object_id=20;select * from t where owner='SCOTT';索引都将失效。[@more@]
sql 优化过程之union 替换 or
在网上看了一些sql优化的文章,其中有一条就是使用union 替换 or。原因是在索引列上使用or,会使索引失效,从而走全表扫描。说的比较笼统,我今天特意试验了一下:在什么情况下可以用union 替换 or才会使索引生效。create table t as select * from all_objects;然后又在t上添加了一列id,使用object_id填充的。create index ind_t_id on t(id);只在id上建立索引。set autotrace traceonlyselect * from t where object_id=10 or id=20;SQL> select * from t where object_id=10 or id=20;未选定行执行计划---------------------------
查找一个表的一列插入到另一个表
create table t as select * from all_objects;create table t1 as select * from all_objects;alter table t add id number;现在要往t中的id列用object_id填充不使用存贮过程:1.使用updateupdate t a set a.id=(select object_id from t1 b where a.object_id=b.object_id);已用时间: 00: 00: 00.26SQL> update t a set a.id=(select object_id from t2 b where a.object_id=b.object_id);已更新53842行。已用时间: 00: 11: 40.23执行计划----------------------------------------------------------Plan hash value: 848927671--
Merge用法
Merge是一个非常有用的功能,类似于Mysql里的insert into on duplicate key. Oracle在9i引入了merge命令, 通过这个merge你能够在一个SQL语句中对一个表同时执行inserts和updates操作. 当然是update还是insert是依据于你的指定的条件判断的,Merge into可以实现用B表来更新A表数据,如果A表中没有,则把B表的数据插入A表. MERGE命令从一个或多个数据源中选择行来updating或inserting到一个或多个表 语法如下 MERGE INTO [your table-name] [rename your table here] USING ( [write your query here] )[rename your query-sql and using ju