You are on page 1of 16

Chapter 12

INDEXING, CLUSTERING, SEQUENCE AND PSEUDO COLUMNS


What is an index Why to use an index Creating an index When Oracle does not use index Clustering Sequence Pseudo columns

What is an Index?
I believe, the best way of understanding an index in Oracle (or any database system is by com!aring it with the index that we find at the end of a textboo"# $or instance, if you want to read about indexing in an Oracle textboo", you will use index of the boo" to locate the to!ic indexing# Once the to!ic is found in index then you ta"e the !age number of that to!ic from index# %hen you go to the !age with that !age number and start reading about indexing# %he conce!t of indexing in Oracle is same as the conce!t of boo" index# $irst let us loo" at the features of an index of a textboo"#

It is at the end of the textbox so that you need not search for the index in the It contains all to!ics of the boo" in the ascending (al!habetical order of the &fter the to!ic the !age number(s where the to!ic is found in the boo" is Index does increase the si'e of the boo" by a few !ages# We use index only when we need it# In other words, we use index when we

first !lace#

to!ics#

listed#

feel it is going to hel! locating the to!ic quic"ly#

&ll the characteristics of an index in a textboo" will be found in an index of Oracle# %he following are the characteristics of an index in Oracle#

Index is used to search for required rows quic"ly# Index occu!ies extra s!ace# Index is stored se!arately from table#

Index contains the values of "ey ( column on which index is created ( in the )ust li"e the !age number in boo" index, Oracle index stores *OWI+ ( a

ascending order#

unique value to internally identify each row of the table# $or each entry in the index a "ey and corres!onding *OWI+ are stored#

Oracle uses index only when it feels the index is going to im!rove !erformance

of the query#

Note: ROWID is a unique value assigned to each row created in a table. Once ROWID is assigned to a row it doesnt change during the lifetime of the row. Oracle access rows internally using ROWID. &n index in Oracle is internally stored as Self balancing binary tree. & data structure that ma"es searching for a !articular value faster#

Why To Use An INDEX


&n index in Oracle is used for two !ur!oses#

%o s!eed u! searching for a !articular value thereby im!roving !erformance of %o enforce uniqueness

query#

Using index to improving performan e


)ust li"e how you can quic"ly locate a !articular to!ic in the boo" by using index at the end of the boo", Oracle uses index to quic"ly locate the row with the given value in the indexed column# Indexed column is the one on which index is created# $or exam!le if you want to search for a !articular student by name then Oracle does the following without and with index#

Without index, Oracle will start loo"ing for the given name at the first row of

the table and continues until it finds the name or until end of the table is reached# %his could be very time consuming !rocess es!ecially for tables with many rows#

With index, Oracle will use index to search for the given name# Since index is

stored in the form of binary tree, locating the name in the index is going to be very fast# %hen by using the *OWI+ obtained from index entry, Oracle will ta"e the row from the table#

%ables with more number of rows will greatly benefit from indexes# ,aving an index and not having an index could ma"e a lot of difference for large tables with thousands of rows#

Enfor ing !ni"!eness #ith index


&n index may also be used to enforce uniqueness in the column(s given in the index# Once a -.I/-0 index is created, Oracle ma"es sure values in the indexed column(s are unique#

Note! " #$I%#& index is automatically created on the columns with 'RI("R) *&) and #$I%#& constraints.

Creating an Index
++1 command C*0&%0 I.+02 is used to create an index# %he following is the syntax of this command#

CREATE [UNIQUE] INDEX index_name ON table (column- [! column-"]###$%


UNIQUE "eyword is used to create a unique index# -nique index ma"es sure that the indexed column(s is always unique# %o create an index on .&30 column of S%-+0.%S table, enter4 c&eate index 'tudent'_name_idx on 'tudent' (name$% If you want to create a unique index on .&30 column of S%-+0.%S table, enter4 c&eate uni(ue index 'tudent'_name_idx on 'tudent'(name$% It is also !ossible to create an index on more than one column# %he following command creates an index on CCO+0 and $CO+0 columns of 5&%C,0S table# c&eate index batc)e'_ccode_*code_idx on batc)e' ( ccode!*code$%

Note: When two or more columns are used in an index then give the column in the order of frequency of usage. +hat means the most frequently used column should be given first.

)ust li"e an index of the boo", which is not used every time you read the boo", even Oracle index is not used every time by Oracle# In the next section we will see when Oracle uses index and when not#

When $ra %e does not !se index?


%he best !art of Oracle index is6 it is com!letely automatic# %hat means, you never have to ex!licitly refer to an index# Oracle decides whether to use an index or not de!ending u!on the query# Oracle can understand whether using an index will im!rove the !erformance in the given query# If Oracle thin"s using an index will im!rove !erformance, it will use the index otherwise it will ignore the index#

Let us assume we have an index on NAME column of STUDETNS table. Then the following que ! will use the index as we a e t !ing to get info mation about a student based on the name.
'elect + *&om 'tudent' ,)e&e name - .Ric)a&d /a&x.%

"ut in the following case # acle does N#T use index$ as index%s usage doesn%t im& ove &e fo mance of the que !. &E'ECT doesn(t ontain W)E*E %a!se
If SELECT command doesnt contain WHERE clause then Oracle doesnt use any inde ! Since all ro"s of the ta#le are to #e retrie$ed% Oracle "ill directly access the ta#le "ithout referrin& to any inde ! In the follo"in& e am'le no inde of ST()E*TS ta#le "ill #e used!
'elect + *&om 'tudent'%

&E'ECT ontains W)E*E %a!se+ ,!t W)E*E %a!se doesn(t refer to indexed o%!mnIn this case S010C% contains W,0*0 clause but the W,0*0 clause is not referring to any columns on which an index is created# $or exam!le, S%-+0%.S table contains two indexes ( one on *O11.O, as it is !rimary "ey and another on .&30 (created earlier in this cha!ter # %he following query uses W,0*0 clause but condition is based on +) column for which there is no index# 'elect + *&om 'tudent' ,)e&e d0 1 2 3-0an-"44 2% ,owever, note that if there is any index on +) then Oracle will use that index#

W)E*E %a!se !ses indexed o%!mns ,!t indexed o%!mn is modified in the W)E*E %a!seIn this case W,0*0 clause refers to indexed columns but doesn7t refer to indexed column as it is# In the query below, .&30 column is used but as it is used with S-5S%* function that modifies the column in the condition, index created on .&30 column will not be used# 'elect + *&om 'tudent' ,)e&e 'ub't&(name!5!6$ - 78o)2%

Note: Data dictionary view #S&R,I$D&-&S .rovides information about indexes.

Creating f!n tion.,ased index


Prior to Oracle8i, it is not !ossible to create an index with an ex!ression as the index column# Index column must be column of the table# If any function is used with indexed column in the query then Oracle does not use index# $or exam!le, if we created an index on .&30 column of S%-+0.%S table as follows4 c&eate index 'tudent'_name_idx on 'tudent' (name$% %hen the above index cannot be used for the following query as indexed column is used with -PP0* function# select 9 from students where u!!er(name : ;*IC,&*+ 3&*2;6 It is also not !ossible to create any index based on an ex!ression# Oracle8i allows indexes to be created on the result of the ex!ression# $or exam!le, the following command creates an index on the result of -PP0* function# c&eate index 'tudent'_name_idx on 'tudent' ( U99ER(name$$% &s the result if we issue the following command Oracle can use index as the ex!ression used in the query and ex!ression used to crate index are same# 'elect + *&om 'tudent' ,)e&e u::e&(name$ - 7RIC;ARD /ARX2%

Note: +o create a function based index/ user must have %#&R) R&WRI+& system .rivilege.

%he following is another exam!le of ex!ression<based index# ,ere index is created on duration of the batch# c&eate index batc)e'_du&ation_idx on batc)e' ( enddate - 'tdate$% %he following query will ma"e use of the above index# 'elect + *&om batc)e' ,)e&e enddate - 'tdate 1 64%

$n%ine indexing
Prior to Oracle8i, Oracle used to loc" the table on which index is being created throughout creation !rocess# %his ma"es table unavailable for data mani!ulation during the creation of index# 5ut Oracle8i introduced online indexing, where Oracle doesn7t loc" the table on which index is being built# Online indexing is !rovided through the "eyword O.1I.0# %he following command creates index on .&30 column of S%-+0.%S table without loc"ing the table# c&eate index 'tudent'_name_idx on 'tudent' (name$ online% Note: Online indexing increases availability of the table. +his is a very im.ortant facility es.ecially for Internet databases where availability matters a lot.

Dra#,a /s of indexes
%hough indexes increase !erformance of query, they can also decrease !erformance of data mani!ulation# 3any indexes on a table can slow down I.S0*%S and +010%0S drastically# $or exam!le, if we ta"e = indexes on a table then every insertion of a new row will u!date all = indexes of the table# %hat means, one insertion will actually result in six insertions# Similarly every change to an indexed column will need a change to index# ,aving more indexes is advantageous in case of tables that are !rimarily used only for querying and not u!dated frequently# %hough the extra s!ace occu!ied by indexes is also a consideration, it may not matter much since the cost of data storage has declined substantially#

Dropping an index
-

>ou can dro! an index using +*OP I.+02 command# It removes the named index# *emoving an index will effect the !erformance of existing a!!lications but not the functionality in any way# -sing and not using an index is trans!arent to users# Oracle decides whether to use or not on its own# ,owever, it is !ossible for users to control the usage of index to certain extent using hints, which are directive to Oracle regarding how to execute a command# 5ut hints are too heavy in a boo" meant for beginners#

DRO9 INDEX

indexname%

%he following exam!le dro!s the index created on .&30 of S%-+0.%S table# d&o: index 'tudent_name_idx%

C%!stering
Clustering is a method of storing tables that are often used together (in ?oining in one area of the dis"# &s tables that are related are stored in one area of the dis", !erformance of ?oining will im!rove# In order to !lace tables in a cluster, tables have to have a common column# $or exam!le the following ste!s will create a cluster and !lace CO-*S0S and 5&%C,0S tables in the cluster# & cluster is created with a name and a "ey# %he "ey is the column, which must be !resent in each table that is !laced in the cluster# %he "ey is also called as cluster 0ey#

&teps
%he following are the required ste!s to create a cluster and !lace tables into it# @# A# B# Create a cluster with C*0&%0 C1-S%0* command# Create an index on the cluster using C*0&%0 I.+02 command# %his must be done before you insert rows into clustered tables# Place the tables into cluster using C1-S%0* o!tion of C*0&%0 %&510 command#

Creating a %!ster
A cluste is c eated using '(EATE 'LUSTE( command. At the time of c eating a cluste the name of the cluste and data t!&e and name of the )e! must be given. The following is the s!ntax of '(EATE 'LUSTE( command.
.

CREATE C<U=TER clu'te&name (column datat>:e [! column datat>:e] ### $%


%he following command creates a cluster to store 5&%C,0S and CO-*S0S table# &s CCO+0 is the common column of these two tables, it is to be the cluster "ey# We s!ecify the data ty!e and name of the cluster "ey# ,owever, name may be anything and it is never used after cluster is created#

c&eate clu'te& cou&'e_batc)e' (ccode ?a&c)a&"(@$$%

Creating %!ster index


&fter the cluster is created and before any rows can be inserted into tables in the cluster, an index on the cluster must be created# C*0&%0 I.+02 command is used to create an index on the cluster# -nless an index is created on the cluster no data mani!ulation can be done on the tables that are !laced in the cluster#

c&eate index cl_ccode_index on clu'te& cou&'e_batc)e'%

0%a ing ta,%es into a %!ster


Once a cluster is created, it may be used to store tables that are related# 0ach table loaded into cluster, must have a column that matches with cluster "ey# & table must be !laced in to cluster at the time of creation# C1-S%0* o!tion of C*0&%0 %&510 command s!ecifies the cluster in to which the table must be !laced# It also s!ecifies the name of the column in the table that matches the cluster "ey of the cluster# %he following commands create CO-*S0S and 5&%C,0S tables and !lace them into cluster# c&eate table cou&'e' ( ccode ?a&c)a&"(@$! name ?a&c)a&"(64$! # # # $ clu'te& cou&'e_batc)e'(ccode$% c&eate table batc)e'

( bcode ccode # # # ?a&c)a&"(@$! ?a&c)a&"(@$!

$ clu'te& cou&'e_batc)e'(ccode$% Note: 'lacing a table into cluster is trans.arent to users. #sers and a..lication will use the table in the same manner whether the table is in the cluster or not.

&torage of %!stered ta,%es


When two tables are !laced in a cluster, they are stored together on the dis" ma"ing ?oining these tables faster# &!art from that storing table in a cluster will also reduce the s!ace requirement# %his is because of cluster storing common column of the clustered tables only for once# In the above exam!le, each unique CCO+0 is stored only for once# %hat means for course O*& though there are multi!le batches, the value O*& is stored only for once in the cluster#

&e"!en e
Sequence is an ob?ect in Oracle database, which is used by multi!le users to generate unique numbers# Sequence is ty!ically used to generate !rimary "eys li"e account number, em!loyee number etc#, where uniqueness and sequence matter# In order to use a sequence, first it is to be created using C*0&%0 S0/-0.C0 command# %hen !seudo columns .02%C&1 and C-**C&1 are used to retrieve unique values from sequence# %he following is the syntax of C*0&%0 S0/-0.C0 command #

CREATE =EQUENCE 'e(uencename [INCRE/ENT AB inteCe&] [=TART DIT; inteCe&] [/AXEA<UE inteCe& F NO/AXEA<UE] [/INEA<UE inteCe& F NO/INEA<UE] [CBC<E F NOCBC<E]%

The following is the desc i&tion of available o&tions.


Option S%&*% WI%, 3&2C&1-0 3I.C&1-0 Meaning S!ecifies the values at which sequence must start# +efault is @# 3aximum value the sequence can generate# +efault is @DeAE<@# 3inimum value the sequence can generate# +efault is @#

S!ecifies by how much the value of the sequence is to be incremented# If you want numbers in the descending order give negative value# +efault is @# C>C10 *estarts numbers from 3I.C&1-0 after reaching 3&2C&1-0# Table 4 O!tions of C*0&%0 S0/-0.C0 command#

I.C*030.% 5>

%he following command creates a sequence called *O11.O to generate roll numbers for students# c&eate 'e(uence &ollno 'ta&t ,it) 44 inc&ement b> % %he above sequence starts generating numbers at @DD and increments the number by @ every time the number is ta"en# Once a sequence is created, it can be used to generate unique numbers in the sequence# Once a value is ta"en from sequence, Oracle automatically increments the value by one (or whatever value s!ecified using I.C*030.% 5> o!tion # Oracle guarantees uniqueness# Once it gives the number then it doesn7t give that number to anyone else# %he following two !seudo columns are used to access the next and current value of the sequence#

NEXT1A'
%his !seudo column will yield the next value from sequence and automatically increments the value of the sequence#

CU**1A'
%his returns the value that is ta"en by most recent .02%C&1# %his cannot be used unless .02%C&1 is first called# %he following exam!les will demonstrate how to use .02%C&1 and C-**C&1 !seudo columns# 'elect &ollno#next?al *&om dual%

NEXTEA< --------44 &s the sequence starts with @DD, first .02%C&1 returned @DD# &nd it also increments the sequence by @# See the next exam!le below# 'elect &ollno#next?al *&om dual%

NEXTEA< ---------

11

4 C-**C&1 !seudo column returns the current value of the sequence, which is the value returned by most recent .02%C&1# In the following exam!le C-**C&1 returns @D@ since that is the most recent value returned by .02%C&1# 'elect &ollno#cu&&?al *&om dual% CURREA< --------4 C-**C&1 is used to reuse the values returned by most recent .02%C&1# %he real usage of sequence is in inserting rows into table# %he following I.S0*% command will use *O11.O sequence to get next available roll number for a new student# in'e&t into 'tudent' ?alue' (&ollno#next?al !

###$%

&nd if you want to insert a row into P&>30.%S table immediately with the same roll number then you can use C-**C&1 as follows# in'e&t into :a>ment' ?alue' ( &ollno#cu&&?al! ###$% %hough a sequence can guarantees uniqueness and sequence, its usage may not guarantee consecutiveness# See the following scenario# in'e&t into commit% in'e&t into &ollbacG% in'e&t into 'tudent' ?alue' ( &ollno#next?al! # # # $% 'tudent' ?alue' ( &ollno#next?al! # # # $% 'tudent' ?alue' ( &ollno#next?al! # # # $%

commit% In the above scenario, if you ta"e the value of *O11.O#.02%C&1 as @DA for first I.S0*% then the value in the second I.S0*% will be @DB# 5ut as second I.S0*% command is rolled bac" that number is not actually used as roll number# %hird I.S0*% command now ta"es @DF but not @DB as Oracle returns next available number, which is @DF# &s you can see, @DB is not used at all in the roll number# While using sequence one must be aware of this !otential ga!s#

11

A%tering a se"!en e
Some attributes of a sequence can be altered using &1%0* S0/-0.C0 command#

A<TER =EQUENCE 'e(uencename [INCRE/ENT AB inteCe&] [/AXEA<UE inteCe& F NO/AXEA<UE] [/INEA<UE inteCe& F NO/INEA<UE]
$or instance, the following command changes 3&2C&1-0 of *O11.O sequence to @DDD# alte& 'e(uence &ollno max?alue 444%

Dropping a &e"!en e
+*OP S0/-0.C0 command is used to dro! a sequence#

DRO9 =EQUENCE 'e(uencename%

The following command drops ROLLNO sequence.


d&o: 'e(uence &ollno%

0se!do Co%!mns
& !seudo column is used li"e a column in a table but it is not a column of any table# >ou can use !seudo columns ?ust li"e table columns but you cannot modify them# %he following is the list of available !seudo columns in Oracle# Pse!"o Col!#n C-**C&1 .02%C&1 .-11 *OWI+ *OW.-3 Meaning

*eturns the current value of a sequence# *eturns the next value of a sequence# *eturn a null value# *eturns the *OWI+ of a row# See *OWI+ section below# *eturns the number indicating in which order Oracle selects rows# $irst row selected will be *OW.-3 of @ and second row *OW.-3 of A and so on# S>S+&%0 *eturns current date and time# -S0* *eturns the name of the current user# -I+ *eturns the unique number assigned to the current user# Table $% Pseudo Columns# %he following are a few exam!les on usage of !seudo columns# Displa& the na#e o' the (!))ent !se) an" !se)*s i"+

12

=Q<1 'elect u'e&! uid *&om dual% U=ER UID ------------------------------ --------AOOH 6I

*$WID
Pseudo column *OWI+ returns the address of each row in the table# Oracle assigns a *OWI+ to each row# Oracle uses *OWI+ internally to access rows# $or instance, Oracle stores *OWI+ in index and uses it to access the row in the table# >ou can dis!lay *OWI+ of rows using S010C% command as follows4 'elect &o,id! ccode *&om cou&'e'% RODID -----------------AAADC@AAAAAAHa=AAA AAADC@AAAAAAHa=AAA AAADC@AAAAAAHa=AAC AAADC@AAAAAAHa=AAD AAADC@AAAAAAHa=AAE AAADC@AAAAAAHa=AAJ AAADC@AAAAAAHa=AAK CCODE ----o&a ?bnet c a': 0a?a xml c'

Oracle !rovides a !ac"age called +53SG*OWI+ to decode *OWI+# %he following S010C% command dis!lays only the row number from *OWI+# 'elect dbm'_&o,id#&o,id_&o,_numbe&(&o,id$ a' &o,numbe& !ccode *&om cou&'e' RODNU/AER CCODE --------- ----4 o&a ?bnet " c 6 a': 5 0a?a @ xml 3 c' Note: Once a row is assigned a ROWID Oracle does not change ROWID during the lifetime of the row. "s the result you may see some row numbers missing in the out.ut of above command. It means those rows were deleted. $or more information about *OWI+ and +53SG*OWI+ !ac"age !lease see online documentation#

13

*$WNU2
%his !seudo column yields the order in which Oracle has selected rows# %he following command dis!lays row number of each row# 'elect &o,num! ccode *&om cou&'e'% RODNU/ CCODE --------- ----o&a " ?bnet 6 c 5 a': @ 0a?a 3 xml L c' *OW.-3 can also be used in conditions but only two o!erators6 , and H:# ma"e sense with *OW.-3# %he following query dis!lays first five courses# 'elect &o,num! ccode *&om cou&'e' ,)e&e &o,num M- @ RODNU/ CCODE --------- ----o&a " ?bnet 6 c 5 a': @ 0a?a ,owever, the following is not meaningful usage of *OW.-3# It is because of the fact that Oracle assigns number to row after row is selected# 'elect &o,num! ccode *&om cou&'e' ,)e&e &o,num - @% no &o,' 'elected &lso remember using Oracle assigns numbers to rows before rows are ordered using O*+0* 5> clause as demonstrated by the following query# 'elect &o,num!ccode!du&ation!*ee *&om cou&'e' o&de& b> *ee%

1+

RODNU/ --------6 3 @ 5 " L

CCODE DURATION JEE ----- --------- --------c "4 6@44 xml @ 5444 o&a "@ 5@44 0a?a "@ 5@44 a': "@ @444 ?bnet 64 @@44 c' 64 L444

1,

&!mmary
Index and cluster are used to im!rove !erformance# %he conce!t of index in Oracle is similar to index found at the end of textboo"# Oracle doesn7t always use index instead Oracle uses index only when it feels, usage of index im!roves !erformance# Cluster is another method of im!roving !erformance by storing related tables together on the dis"# Sequence is an ob?ect used to generate unique number in a sequence# Pseudo column yield values and used as columns of the table though they are not columns of any table#

Exer ises
@# A# B# F# =# J# E# 8# K# Which constraints automatically create indexI What does O.1I.0 o!tion in C*0&%0 %&510 command doI ,ow do you create an index on $CO+0 and CCO+0 of 5&%C,0S table# GGGGGGG o!tion in C*0&%0 S0/-0.C0 is used to generate numbers in reverse order# GGGGGGGGG is the !seudo column used to get the next available number from a sequence# GGGGGGGGGG o!tion is used in C*0&%0 %&510 command to !lace the table in a cluster# Which o!tion of C*0&%0 I.+02 is used to create an index on the cluster# Create a sequence called order *0C0*S0 to generate numbers in the descending from @DDDD to @DDD with a decrement of =# to A#

Create a cluster to store S%-+0.%S and P&>30.%S tables and !lace tables into it#

@D# Change the decrement value of sequence *0C0*S0 (created earlier the remedy you suggestI @A# What is the !ur!ose of *OWI+I

@@# Is it !ossible to !lace an existing table into clusterI If yes howI If no, then what is

1-

You might also like