Where and how data sits on disk decides how fast queries run. Indexes are the main tool to make searches fast.

Data on external storage

Memory is fast but small and loses data on power cut. Disks are large and permanent but much slower. A DBMS reads data in pages (blocks), so the main cost of a query is the number of pages read. Good design reduces that number.

File organizations

Organization How rows are stored Good for Weak at
Heap (unordered) In insertion order Fast insert, full scans Searching for one row
Sorted Ordered by a key Range queries, ordered output Inserts
Hashed Placed by a hash of the key Equality search Range queries

Index

An index is a separate structure that maps key values to row locations, like the index at the back of a book.

CREATE INDEX idx_student_name ON student(name);
SELECT * FROM student WHERE name = 'Ravi';  -- can use the index

Kinds of index

  • Clustered: the table rows are stored in the order of the index key. Only one per table.
  • Non-clustered (secondary): a separate sorted list with pointers to rows. Many per table.
  • Dense: an entry for every row. Sparse: an entry for each page.
  • Single or composite: on one column or several.

Index data structures

  • B+ tree: a balanced tree that keeps keys sorted and has all data pointers in the leaves, which are linked. It supports equality and range searches and stays shallow, so a search needs only a few page reads. This is the default in most DBMSs.
  • Hash index: a hash function gives the bucket directly. Very fast for =, useless for ranges.

Comparison of costs

For a table of N pages, a heap file scan reads about N pages. A B+ tree lookup reads about 3 or 4 pages even for millions of rows. A hash lookup usually needs 1 to 2.

Common mistakes

  • Indexing every column. Each index speeds reads but slows inserts, updates and deletes, and uses space.
  • Expecting an index to help a query with LIKE '%abc', since the pattern starts with a wildcard.

Practice questions

  1. Differentiate heap, sorted and hashed file organizations.
  2. What is an index? Write the SQL to create one.
  3. Differentiate clustered and non-clustered indexes.
  4. Why is a B+ tree preferred over a hash index in many systems?
  5. Why not create an index on every column?

Answers to the practice questions

  1. Heap is unordered, sorted is ordered by key, hashed is placed by hash of key.
  2. A structure that finds rows quickly: CREATE INDEX idx ON student(name);
  3. Clustered decides the physical order of rows (one per table); non-clustered is a separate structure with pointers (many).
  4. It supports both equality and range queries and stays balanced.
  5. Indexes cost space and slow down data changes.

Sources

  • Official BCA syllabus Database Management Systems, course code CC202, Unit III
  • Raghu Ramakrishnan and Johannes Gehrke, Database Management Systems, 3rd edition, McGraw-Hill