Junior
What are indexes and how do they work?
sobes.tech AI
Answer from AI
Indexes are data structures that accelerate data lookup in database tables. They work like a pointer in a book.
How they work:
- Create an index on one or more columns.
- The database builds a separate data structure (often B-tree or B+-tree) containing values from indexed columns and pointers to corresponding rows.
- When a query with a condition on indexed columns (e.g.,
WHERE column = value) is executed, the database first searches for the value in the index, which is much faster than scanning the entire table. - Finding the value in the index, the database uses the pointer to quickly access the row(s) in the main table.
Example of creating an index in SQL:
-- Create index on 'email' column of 'users' table
CREATE INDEX idx_users_email ON users (email);
Advantages:
- Speed up
SELECToperations. - Speed up
JOINandORDER BYon indexed columns.
Disadvantages:
- Slower
INSERT,UPDATE,DELETEoperations, as index must also be updated. - Additional disk space for storing the index.
- Not always useful for columns with low cardinality or very small tables.