Database Indexing
Database indexing is a technique used to improve the performance of queries on a database table. It involves creating a separate data structure, known as an index, that contains the values of one or more table columns.
Importance of Database Indexing
Database indexing provides several benefits:
Improved Query Performance: By creating indexes on frequently queried columns, the database can locate the required data more quickly, resulting in faster query execution.
Reduced Disk I/O: Indexing allows the database to retrieve data directly from the index structure, reducing the need to perform expensive disk I/O operations.
Efficient Data Retrieval: With an index, the database can locate specific rows or ranges of rows based on the indexed columns, enabling efficient data retrieval.
Index Types
There are different types of database indexes, including:
B-Tree Index: B-Tree indexes are commonly used in databases. They provide efficient searching and sorting operations and are suitable for a wide range of data types.
Hash Index: Hash indexes are useful for equality queries, where the indexed column is matched exactly. They are fast for exact match lookups but not well-suited for range queries.
Bitmap Index: Bitmap indexes store the presence or absence of values for each indexed column, allowing for efficient filtering of multiple columns.
Example
Let's consider an example to understand the concept of database indexing.
Suppose we have a table called 'Players' with the following columns:
- PlayerID (Primary Key)
- PlayerName
To improve the performance of queries that search for a specific player, we can create an index on the 'PlayerName' column:
1CREATE INDEX idx_PlayerName ON Players (PlayerName);
With the index in place, queries that search for a player by name will be able to locate the desired row(s) more efficiently.
1-- Perform a linear search to find a player
2linearSearch('Kobe Bryant');
3
4-- Perform a binary search to find a player
5binarySearch('Kobe Bryant');
xxxxxxxxxx
}
const players = ['LeBron James', 'Kobe Bryant', 'Michael Jordan'];
// Perform a linear search to find a player
function linearSearch(playerName) {
for (let i = 0; i < players.length; i++) {
if (players[i] === playerName) {
return i;
}
}
return -1;
}
// Perform a binary search to find a player
function binarySearch(playerName) {
let start = 0;
let end = players.length - 1;
while (start <= end) {
let mid = Math.floor((start + end) / 2);
if (players[mid] === playerName) {
return mid;
} else if (players[mid] < playerName) {
start = mid + 1;
} else {
end = mid - 1;
}
}
return -1;