Thursday, October 18, 2007

Bind variables in oracle

After every sql submitted into Oracle, Oracle will first check the shared pool to see if there were any same statements submitted before. If there was, Oracle will use previous statement. If there wasn't, Oracle will parse the statement and analyze out a couple of executable plans and select an optimal one for this case. This process is so-called hard parse.

How about the amount of similar SQLs? such as:
select term_id, term_name, term_description from terms where term_id='1'
select term_id, term_name, term_description from terms where term_id='2'
select term_id, term_name, term_description from terms where term_id='3'
select term_id, term_name, term_description from terms where term_id='4'

Will Oracle regard them as same statements? The answer is NO. This can be a vampire for CPU, especially for web-based applications. For instance, a hundred users are listing terms which ids are from "1" to "100" at the same time. There will be 10,000 sql submitted to oracle server. And oracel has to hard parse every statement althought they are extremely similar.

Bind variables is actually designed for this. So the upper SQL could become:
SQL> variable term_id number
SQL> exec :term_id := 10
SQL> select term_id, term_name, term_description from terms where term_id=:term_id;

For using Oracle bind variables in Java, http://www.oracle.com/technology/oramag/oracle/06-mar/o26frame.html

No comments: