SQL限制条件应尽量避免使用SYSDATE

如果可以明确的使用日期常量来表示,那么就尽量避免使用SYSDATE作为替代。以前写过一篇SQL中如何处理常量的,其实已经包含了这个含义。

sql语句中常量的处理:http://yangtingkun.itpub.net/post/468/20038

 

 

有时候出于偷懒的目的,有些人习惯在应该输入常量的地方使用类似SYSDATE的函数来代替,但是这会带来额外的性能代价:

[oracle@yans1 ~]$ sqlplus test/test

SQL*Plus: Release 10.2.0.3.0 - Production on 星期二 7 14 10:00:52 2009

Copyright (c) 1982, 2006, Oracle.  All Rights Reserved.


Connected to:
Oracle Database 10g Enterprise Edition Release 10.2.0.3.0 - 64bit Production
With the Partitioning, OLAP and Data Mining options

SQL> set pages 100 lines 120
SQL> create table t (id number, name varchar2(30), created date);

Table created.

SQL> insert into t select rownum, object_name, created from dba_objects;

70739 rows created.

SQL> insert into t select * from t;

70739 rows created.

SQL> insert into t select * from t;

141478 rows created.

SQL> insert into t select * from t;

282956 rows created.

SQL> insert into t select * from t;

565912 rows created.

SQL> insert into t select * from t;

1131824 rows created.

SQL> insert into t select * from t;

2263648 rows created.

SQL> insert into t select * from t;

4527296 rows created.

SQL> commit;

Commit complete.

SQL> set timing on
SQL> select count(*) from t where created >= to_date('2009-1-1', 'yyyy-mm-dd');

  COUNT(*)
----------
    744960

Elapsed: 00:00:00.56
SQL> select count(*) from t where created >= to_date('2009-1-1', 'yyyy-mm-dd');

  COUNT(*)
----------
    744960

Elapsed: 00:00:00.40
SQL> select count(*) from t where created >= trunc(sysdate, 'yyyy');

  COUNT(*)
----------
    744960

Elapsed: 00:00:01.58
SQL> select count(*) from t where created >= trunc(sysdate, 'yyyy');

  COUNT(*)
----------
    744960

Elapsed: 00:00:01.54

上面两个SQL等价,但是使用常量方式所需的执行时间,仅是使用SYSDATE函数的1/3左右。这时由于对于常量的计算,Oracle只需要在执行前运行一次得到结果就可以了,但是对于SYSDATE函数,则需要在与每条记录进行比较的时候都进行调用。

不仅仅是SYSDATE函数,其他函数也是一样的道理。应该只是在需要的时候进行调用:

SQL> select count(*) from t where name = 'TEST';

  COUNT(*)
----------
       768

Elapsed: 00:00:00.32
SQL> select count(*) from t where name = 'TEST';

  COUNT(*)
----------
       768

Elapsed: 00:00:00.31
SQL> select count(*) from t where name = user;

  COUNT(*)
----------
       768

Elapsed: 00:00:00.58
SQL> select count(*) from t where name = user;

  COUNT(*)
----------
       768

Elapsed: 00:00:00.57

 

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/4227/viewspace-609180/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/4227/viewspace-609180/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值