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.

472<br />

CHAPTER 11 ■ INDEXES<br />

ops$tkyte@ORA10GR1> analyze index t_idx validate structure;<br />

Index analyzed.<br />

ops$tkyte@ORA10GR1> select name, lf_rows from index_stats;<br />

NAME<br />

LF_ROWS<br />

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

T_IDX 3<br />

The table has four rows, whereas the index only has three. The first three rows, where at<br />

least one of the index key elements was not null, are in the index. The last row with (NULL,<br />

NULL) is not in the index. One of the areas of confusion is when the index is a unique index,<br />

as just shown. Consider the effect of the following three INSERT statements:<br />

ops$tkyte@ORA10GR1> insert into t values ( NULL, NULL );<br />

1 row created.<br />

ops$tkyte@ORA10GR1> insert into t values ( NULL, 1 );<br />

insert into t values ( NULL, 1 )<br />

*<br />

ERROR at line 1:<br />

ORA-00001: unique constraint (OPS$TKYTE.T_IDX) violated<br />

ops$tkyte@ORA10GR1> insert into t values ( 1, NULL );<br />

insert into t values ( 1, NULL )<br />

*<br />

ERROR at line 1:<br />

ORA-00001: unique constraint (OPS$TKYTE.T_IDX) violated<br />

The new (NULL, NULL) row is not considered to be the same as the old row with<br />

(NULL, NULL):<br />

ops$tkyte@ORA10GR1> select x, y, count(*)<br />

2 from t<br />

3 group by x,y<br />

4 having count(*) > 1;<br />

X Y COUNT(*)<br />

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

2<br />

This seems impossible; our unique key isn’t unique if we consider all null entries. The fact<br />

is that, in <strong>Oracle</strong>, (NULL, NULL) is not the same as (NULL, NULL) when considering uniqueness—the<br />

SQL st<strong>and</strong>ard m<strong>and</strong>ates this. (NULL,NULL) <strong>and</strong> (NULL,NULL) are considered the same<br />

with regard to aggregation, however. The two are unique for comparisons but are the same as<br />

far as the GROUP BY clause is concerned. That is something to consider: each unique constraint<br />

should have at least one NOT NULL column to be truly unique.<br />

The question that comes up with regard to indexes <strong>and</strong> null values is, “Why isn’t my query<br />

using the index?” The query in question is something like the following:

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

Saved successfully!

Ooh no, something went wrong!