Junior — Middle
Can you explain what an index in a database means and how it works?
sobes.tech AI
Answer from AI
An index in a database is a special data structure that speeds up the search and sorting of records in a table.
Basically, an index is like a table of contents in a book: instead of scanning the entire table, the DBMS refers to the index to quickly find the needed rows.
How it works:
- The index is built on one or more columns of the table.
- A data structure, such as a B-tree, is usually used, which allows for fast value lookups.
- When queries with conditions on indexed columns are made, the DBMS refers to the index to get the addresses of the needed rows, bypassing a full scan.
Advantages:
- Significantly speeds up SELECT operations with filtering and sorting.
Disadvantages:
- Indexes take up additional space on disk.
- When inserting, updating, or deleting data, indexes need to be updated, which can slow down these operations.
Example: if you have a users table with an "email" column, and you create an index on email, searching for a user by email will be much faster.