Documented By :
SQL> create or replace function f_null return varchar2
2 is
3 begin
4 dbms_lock.sleep(1);
5 return '--null--';
6 end;
7 /
Function created.
Following are the queries which I used to demonstrate that NVL evaluates both arguments even if the second argument is not used and COALESCE uses short-circuit evaluation i.e. it only evaluates the arguments only if they are needed.
SQL> select e.empno, e.ename ename, nvl(m.ename,f_null) mname
2 from scott.emp e, scott.emp m
3 where e.mgr = m.empno(+);
EMPNO ENAME MNAME
---------- ---------- ----------
7902 FORD JONES
7788 SCOTT JONES
7900 JAMES BLAKE
7844 TURNER BLAKE
7654 MARTIN BLAKE
7521 WARD BLAKE
7499 ALLEN BLAKE
7934 MILLER CLARK
7876 ADAMS SCOTT
7782 CLARK KING
7698 BLAKE KING
7566 JONES KING
7369 SMITH FORD
7839 KING --null--
14 rows selected.
Elapsed: 00:00:14.01
SQL> select e.empno, e.ename ename, coalesce(m.ename,f_null) mname
2 from scott.emp e, scott.emp m
3 where e.mgr = m.empno(+);
EMPNO ENAME MNAME
---------- ---------- ----------
7902 FORD JONES
7788 SCOTT JONES
7900 JAMES BLAKE
7844 TURNER BLAKE
7654 MARTIN BLAKE
7521 WARD BLAKE
7499 ALLEN BLAKE
7934 MILLER CLARK
7876 ADAMS SCOTT
7782 CLARK KING
7698 BLAKE KING
7566 JONES KING
7369 SMITH FORD
7839 KING --null--
14 rows selected.
Elapsed: 00:00:01.01
Here we can see easily that the first query with NVL took 14+ seconds, one second for each record even if the "f_null" value was used only in one record. On the contrary as mentioned in Oracle Documentation "COALESCE" uses its "short-circuit evaluation" and "f_null" was called only once and so second query took only One Second. "COALESCE" is certainly use less resources than NVL.
ReplyDeleteThank you for excellent article.I enjoyed reading your blog!!
Spoken English Training in coimbatore|ProSteel training in Coimbatore|Revit Architecture training in Coimbatore|Staad Pro training in Coimbatore||Building Estimation and Costing training in Coimbatore
Keep the good work and write more like this..