Learning Objectives – after this chapter you will be able to:
  • Explain what an index is (compared with a book index) and why it is used.
  • Create normal, unique, composite, function-based and online indexes; drop an index.
  • Identify when Oracle does not use an index and the drawbacks of indexes.
  • Create a cluster, a cluster index and clustered tables.
  • Create, use, alter and drop sequences with NEXTVAL and CURRVAL.
  • Use pseudo columns – ROWID, ROWNUM, SYSDATE, USER, UID.
What is an Index?

An Oracle index works like the index at the end of a textbook: topics in alphabetical order, each followed by a page number, it adds a few pages to the book, and you use it only when it helps.

  • An index is used to search for required rows quickly.
  • It occupies extra space and is stored separately from the table.
  • It holds the values of the key (indexed column) in ascending order, each with the ROWID of its row (like the page number).
  • Internally it is stored as a self-balancing (B-)tree, so searching is fast.
  • Oracle uses it only when it improves performance – automatically; you never refer to it in a query.

Two purposes: (1) speed up searching (without an index Oracle reads the table from the first row to the end; with one it finds the key in the tree and fetches the row by ROWID) and (2) enforce uniqueness – a UNIQUE index is created automatically for PRIMARY KEY and UNIQUE constraints.

CREATE [UNIQUE] INDEX index_name ON table (column-1 [, column-2] ...) [ONLINE]; DROP INDEX index_name;
Creating indexes
create index students_name_idx on students (name);
create unique index students_name_idx on students (name);
create index batches_ccode_fcode_idx on batches (ccode, fcode);   -- most used column first

create index students_name_idx on students ( upper(name) );       -- function-based (8i)
create index batches_duration_idx on batches ( enddate - stdate );
create index students_name_idx on students (name) online;         -- table not locked
  • Function-based index (Oracle8i): an index on an expression; used when the query uses the same expression (e.g. where upper(name) = 'RICHARD MARX'). Requires the QUERY REWRITE system privilege.
  • Online indexing (Oracle8i): the table is not locked while the index is built – higher availability, important for Internet databases.
  • USER_INDEXES describes your indexes.
When Oracle Does Not Use an Index
SituationExample
SELECT has no WHERE clause (all rows are needed)select * from students;
WHERE does not refer to an indexed columnwhere dj > '16-jan-2001' (no index on DJ)
The indexed column is modified by a function/expression in WHEREwhere substr(name,4,3) = 'Joh', where upper(name) = ... (unless a matching function-based index exists)
Drawbacks of indexes

Indexes speed up queries but slow down DML: with 5 indexes, one INSERT becomes six insertions, and every change to an indexed column changes the index. Many indexes suit tables used mainly for querying. Dropping an index affects only performance, never functionality. (Users can influence index usage with hints.)

Clustering

A cluster stores tables that are often joined together in one area of the disk, so joins are faster. The tables must share a common column – the cluster key – and each key value is stored only once, saving space.

Steps to create a cluster
create cluster course_batches (ccode varchar2(5));        -- 1. cluster + key

create index cl_ccode_index on cluster course_batches;    -- 2. cluster index (before any DML)

create table courses ( ccode varchar2(5), name varchar2(30), ... )
cluster course_batches (ccode);                           -- 3. place tables at creation
create table batches ( bcode varchar2(5), ccode varchar2(5), ... )
cluster course_batches (ccode);

A table can be placed in a cluster only when it is created (CLUSTER option of CREATE TABLE). Clustering is transparent to users and applications.

Sequence

A sequence is a database object used by multiple users to generate unique numbers – typically primary keys such as account or employee numbers.

CREATE SEQUENCE name [INCREMENT BY n] -- default 1; negative for descending numbers [START WITH n] -- default 1 [MAXVALUE n | NOMAXVALUE] [MINVALUE n | NOMINVALUE] [CYCLE | NOCYCLE]; -- CYCLE restarts from MINVALUE after MAXVALUE
Using a sequence
create sequence rollno start with 100 increment by 1;

select rollno.nextval from dual;      -- 100
select rollno.nextval from dual;      -- 101
select rollno.currval from dual;      -- 101 (value of the most recent NEXTVAL)

insert into students values (rollno.nextval, ...);
insert into payments values (rollno.currval, ...);     -- same roll number

alter sequence rollno maxvalue 1000;
drop sequence rollno;
  • NEXTVAL returns the next value and increments the sequence; CURRVAL returns the value of the most recent NEXTVAL and cannot be used before NEXTVAL.
  • Sequences guarantee uniqueness, not consecutiveness: a number taken by a rolled-back INSERT is lost, leaving a gap.
  • ALTER SEQUENCE can change INCREMENT BY, MAXVALUE and MINVALUE.
Pseudo Columns

A pseudo column is used like a table column but is not a column of any table and cannot be modified.

Pseudo columnReturns
CURRVAL / NEXTVALCurrent / next value of a sequence
NULLA null value
ROWIDAddress of a row; never changes during the row’s lifetime; stored in indexes (decode with the DBMS_ROWID package)
ROWNUMOrder in which Oracle selected the rows (1, 2, 3 …)
SYSDATECurrent date and time
USER / UIDName / unique number of the current user
Pseudo columns
select user, uid from dual;
select rowid, ccode from courses;
select rownum, ccode from courses where rownum <= 5;      -- first five rows
select rownum, ccode from courses where rownum = 5;       -- no rows selected
select rownum, ccode, fee from courses order by fee;      -- ROWNUM assigned before sorting
ROWNUM is assigned after a row is selected and before ORDER BY; only < and <= make sense with it.
Key Takeaways
  • Indexes store key + ROWID in a B-tree; Oracle decides when to use them.
  • No WHERE, non-indexed column or a function on the column → index not used.
  • Clusters store joined tables together; sequences generate unique (not gap-free) numbers.
  • ROWNUM works with < and <=, and is assigned before ORDER BY.
Chapter 12 Notes (PDF)
ch12.pdf 17 pages 372 KB Open in PDF Viewer (Free Tool)

Your browser cannot show this PDF here. Open Chapter 12 Notes (PDF)

ch12.pdfKeys: ← → page · + − zoom · F full screen
Question / Answer (15 questions)

Moderate-level questions based on the Chapter 12 notes (PDF). Click a question to see the answer.

Answer : Like a book index, an Oracle index is used to locate data quickly, contains key values in ascending order, stores a pointer to the data (ROWID, like a page number), occupies extra space and is used only when it helps. Oracle stores the index separately from the table and uses it only when it improves the performance of a query.

Answer : For each entry an index stores the key (value of the indexed column) and the corresponding ROWID of the row. Internally the index is stored as a self-balancing binary tree, a data structure that makes searching for a value faster.

Answer : To speed up searching for a particular value, thereby improving the performance of queries, and to enforce uniqueness of the indexed column(s) through a UNIQUE index.

Answer : PRIMARY KEY and UNIQUE constraints – Oracle automatically creates a unique index on those columns to enforce uniqueness.

Answer : CREATE INDEX batches_ccode_fcode_idx ON batches (ccode, fcode). When two or more columns are used, they should be given in the order of frequency of usage – the most frequently used column first.

Answer : When the SELECT has no WHERE clause (all rows are retrieved), when the WHERE clause does not refer to an indexed column, and when the indexed column is modified in the WHERE clause, e.g. by a function such as SUBSTR(name,4,3) or UPPER(name).

Answer : Introduced in Oracle8i, it is an index created on the result of an expression, e.g. CREATE INDEX students_name_idx ON students (UPPER(name)) or ON batches (enddate - stdate). Oracle can use it when the query uses the same expression. The user needs the QUERY REWRITE system privilege.

Answer : Before Oracle8i the table was locked throughout index creation, making it unavailable for data manipulation. With ONLINE (Oracle8i), Oracle does not lock the table while building the index, increasing availability – important for Internet databases.

Answer : Indexes can decrease the performance of data manipulation: with 5 indexes on a table every insertion of a row updates all 5 indexes, so one insertion results in six insertions, and every change to an indexed column needs a change to the index. They also occupy extra space. Many indexes suit tables used mainly for querying.

Answer : Clustering stores tables that are often used together in joins in one area of the disk, improving join performance. It also reduces space because the common column (cluster key) is stored only once for each unique value.

Answer : 1. Create the cluster with CREATE CLUSTER, giving the name and the cluster key column and datatype. 2. Create an index on the cluster with CREATE INDEX ... ON CLUSTER before any rows are inserted. 3. Place tables into the cluster using the CLUSTER option of CREATE TABLE, naming the column that matches the cluster key.

Answer : No. A table must be placed into a cluster at the time of its creation using the CLUSTER option of CREATE TABLE; an existing table therefore has to be created again with that option.

Answer : A sequence is a database object used by multiple users to generate unique numbers, typically for primary keys. NEXTVAL yields the next value and automatically increments the sequence; CURRVAL returns the value taken by the most recent NEXTVAL and cannot be used unless NEXTVAL has been called first.

Answer : No. It guarantees uniqueness, but not consecutiveness. If an INSERT that took a number with NEXTVAL is rolled back, that number is not used, and the next NEXTVAL returns the following number – leaving a gap (e.g. 103 is skipped).

Answer : Pseudo columns are used like table columns but are not columns of any table and cannot be modified (CURRVAL, NEXTVAL, NULL, ROWID, ROWNUM, SYSDATE, USER, UID). ROWID is the address of a row, assigned when the row is created and unchanged for its lifetime; Oracle stores it in indexes to access rows. ROWNUM is the order in which Oracle selects rows; it is assigned after a row is selected and before ORDER BY, so only < and <= are meaningful (WHERE ROWNUM = 5 returns no rows).
MCQ Test : Check Your Understanding (5 questions)

Select an option and press Check Answer, or answer all questions and press Submit Test to see your score. Each answer comes with an explanation.

Q1. Which option of CREATE SEQUENCE generates numbers in the reverse (descending) order?

Show Answer

Correct Answer : A. A negative INCREMENT BY
INCREMENT BY with a negative value generates numbers in descending order.

Q2. Which pseudo column gives the next available number from a sequence?

Show Answer

Correct Answer : B. NEXTVAL
NEXTVAL returns the next value and increments the sequence.

Q3. Which option of CREATE TABLE places a table in a cluster?

Show Answer

Correct Answer : C. CLUSTER
The CLUSTER cluster_name(column) option of CREATE TABLE places the table in the cluster.

Q4. Oracle will NOT use the index on NAME for which query?

Show Answer

Correct Answer : D. where substr(name,4,3) = 'Joh'
When the indexed column is modified by a function in the WHERE clause, a normal index on that column is not used.

Q5. What does SELECT rownum, ccode FROM courses WHERE rownum = 5 return?

Show Answer

Correct Answer : A. No rows
ROWNUM is assigned after a row is selected, so the first row (ROWNUM 1) fails the test and no row ever reaches 5.

Bibliography/References

The chapter notes PDF is the course study material and is credited to its author below. The explanations, questions and MCQs on this page are original study aids written for this course from the topics covered in that PDF. The other works are cited for verification and further reading. Oracle, SQL*Plus and PL/SQL are trademarks of Oracle Corporation; other names belong to their respective owners.

  1. Srikanth, P. (n.d.). Oracle For Beginners (chapter notes – the PDF shown on each chapter page). Srikanth Technologies. http://www.srikanthtechnologies.com/
  2. Oracle Corporation. (n.d.). Oracle Database SQL Language Reference, 19c. https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/
  3. Oracle Corporation. (n.d.). Oracle Database Concepts, 19c. https://docs.oracle.com/en/database/oracle/oracle-database/19/cncpt/
  4. Oracle Corporation. (n.d.). Oracle Database Administrator’s Guide, 19c. https://docs.oracle.com/en/database/oracle/oracle-database/19/admin/
  5. Silberschatz, A., Korth, H. F., & Sudarshan, S. (2019). Database System Concepts (7th ed.). McGraw-Hill Education.