对于oracle数据库来说,在条件允许的情况下,oracle可以帮我们自动做数据类型的转换,但是oracle还是建议我们最好使用转换函数(to_char()、to_date()、to_number()等)做显示的转换
下面这个例子简单的测试了,由于oracle自动执行隐式转换 ,导致索引无法正确使用的例子
建表T,其中ID列是字符类型
scott@DB01> create table t(id varchar2(10),name varchar2(10),sal number);
Table created.
描述表EMP,我们注意到empno是数字类型
scott@DB01> desc emp
使用子查询插入插入数据到T表,我们其实应该意识到这里就涉及到数据类型的转换,T表的ID列是字符类型,虽然查询的结果看着是数字
scott@DB01> insert into t select empno,ename,sal from emp;
14 rows created.
scott@DB01> commit;
Commit complete.
scott@DB01> select * from t;
ID
---------- ---------- ----------
7369
7499
7521
7566
7654
7698
7782
7788
7839
7844
7876
7900
7902
7934
14 rows selected.
在表T上创建索引T_IDX
scott@DB01> create index t_idx on t(id);
Index created.
scott@DB01> desc t
很多人会想当然的认为,oracle既然可以帮我们做隐式数据类型的转换,那么下面两个语句的效果应该是一样的,如果光从结果来看确实如此。但实际上性能是有非常大的差异的
scott@DB01> select * from t where id=7369;
ID
---------- ---------- ----------
7369
scott@DB01> select * from t where id='7369';
ID
---------- ---------- ----------
7369
使用autotrace工具查看语句的执行计划,我们会发现第一条语句发生了数据类型的隐式转换,导致的结果是语句没有使用到索引T_IDX
scott@DB01> set autotrace trace exp
scott@DB01> select * from t where id=7369;
Execution Plan
----------------------------------------------------------
Plan hash value: 1601196873
--------------------------------------------------------------------------
| Id
--------------------------------------------------------------------------
|
|*
--------------------------------------------------------------------------
Predicate Information (identified by operation id):
---------------------------------------------------
Note
-----
scott@DB01>
scott@DB01> select * from t where id='7369';
Execution Plan
----------------------------------------------------------
Plan hash value: 470836197
-------------------------------------------------------------------------------------
| Id
-------------------------------------------------------------------------------------
|
|
|*
-------------------------------------------------------------------------------------
Predicate Information (identified by operation id):
---------------------------------------------------
Note
-----