05.11.2015 Views

Apress.Expert.Oracle.Database.Architecture.9i.and.10g.Programming.Techniques.and.Solutions.Sep.2005

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

524<br />

CHAPTER 12 ■ DATATYPES<br />

To truncate that date down to the year, all the database had to do was put 1s in the last<br />

5 bytes—a very fast operation. We now have a sortable, comparable DATE field that is truncated<br />

to the year level, <strong>and</strong> we got it as efficiently as possible. What many people do instead of using<br />

TRUNC, however, is use a date format in the TO_CHAR function. For example, they will use<br />

Where to_char(date_column,'yyyy') = '2005'<br />

instead of<br />

Where trunc(date_column,'y') = to_date('01-jan-2005','dd-mon-yyyy')<br />

The latter is a far more performant <strong>and</strong> less resource-intensive approach. If we make a<br />

copy of ALL_OBJECTS <strong>and</strong> save out just the CREATED column<br />

ops$tkyte@ORA10G> create table t<br />

2 as<br />

3 select created from all_objects;<br />

Table created.<br />

ops$tkyte@ORA10G> exec dbms_stats.gather_table_stats( user, 'T' );<br />

PL/SQL procedure successfully completed.<br />

<strong>and</strong> then, with SQL_TRACE enabled, we repeatedly query this table using both techniques, we<br />

see the following results:<br />

select count(*)<br />

from<br />

t where to_char(created,'yyyy') = '2005'<br />

call count cpu elapsed disk query current rows<br />

------- ------ -------- ---------- ---------- ---------- ---------- ----------<br />

Parse 4 0.01 0.05 0 0 0 0<br />

Execute 4 0.00 0.00 0 0 0 0<br />

Fetch 8 0.41 0.59 0 372 0 4<br />

------- ------ -------- ---------- ---------- ---------- ---------- ----------<br />

total 16 0.42 0.64 0 372 0 4<br />

select count(*)<br />

from<br />

t where trunc(created,'y') = to_date('01-jan-2005','dd-mon-yyyy')<br />

call count cpu elapsed disk query current rows<br />

------- ------ -------- ---------- ---------- ---------- ---------- ----------<br />

Parse 4 0.00 0.00 0 0 0 0<br />

Execute 4 0.00 0.00 0 0 0 0<br />

Fetch 8 0.04 0.16 0 372 0 4<br />

------- ------ -------- ---------- ---------- ---------- ---------- ----------<br />

total 16 0.04 0.16 0 372 0 4

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!