Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
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#
&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#
%o s!eed u! searching for a !articular value thereby im!roving !erformance of %o enforce uniqueness
query#
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#
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#
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#
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: +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.
.
$ 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.
&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]%
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#
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+
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-