week 9
Teaching and Learning Methods to be Employed
1. Illustrated lecture on query processing pipeline
2. Lab: Using EXPLAIN in MySQL to analyse query execution plans
3. Index creation and performance comparison exercise
4. Collection of Assignment 3
Learning Outcomes / Objectives
By the end of this week, students should be able to:
1. Describe the steps in query processing from SQL statement to query result.
2. Explain the role of the query optimiser in a DBMS.
3. Understand relational algebra as the basis for query evaluation.
4. Describe the structure and benefits of database indexes.
5. Use MySQL's EXPLAIN statement to interpret a query execution plan.
6. Apply basic query optimisation techniques.
9.4 Indexes
An index is an auxiliary data structure that speeds up data retrieval at the cost of additional storage and slower write operations. Without an index, the DBMS must perform a FULL TABLE SCAN — reading every row to find matches.
ANALOGY: An index in a database is like the index at the back of a textbook. Instead of reading the entire book to find where 'normalisation' is discussed, you look it up in the index and go directly to page 145. This is the difference between O(n) and O(log n) performance.
|
Index Type |
Description and Use Case |
|
B-Tree Index (default) |
Balanced tree structure. Good for range queries (BETWEEN, >, <) and equality searches. Most common type in MySQL. |
|
Hash Index |
Uses a hash table. Very fast for equality searches (=) only. Not useful for range queries. Used in MEMORY tables. |
|
Full-Text Index |
For text searching (MATCH...AGAINST). Useful for product descriptions, article content. |
|
Composite Index |
Index on multiple columns. Order matters: INDEX(LastName, FirstName) helps queries on LastName alone or (LastName, FirstName) together, but NOT FirstName alone. |
|
Unique Index |
Ensures no duplicate values. MySQL creates one automatically for PRIMARY KEY and UNIQUE constraints. |
|
Clustered Index |
Rows are physically stored in index order. Each table has at most one clustered index (the PRIMARY KEY in MySQL InnoDB). |
SQL COMMANDS FOR INDEXES:
-- Create an index on LastName for faster name searches
CREATE INDEX idx_lastname ON STUDENT(LastName);
-- Create a composite index for queries filtering by State and AccountType
CREATE INDEX idx_state_accttype ON CUSTOMER(State, AccountType);
-- Drop an index
DROP INDEX idx_lastname ON STUDENT;
-- Show all indexes on a table
SHOW INDEX FROM STUDENT;