Indexing is a technique used to improve the performance and speed of data retrieval operations in a database. It allows the database to find and access specific rows much faster, especially when working with large datasets. An index is created on one or more columns of a table and acts like a "lookup" to help locate the data quickly.
Indexes work similarly to a book's index: instead of reading through the entire book, you can quickly locate a topic by referring to the index.
Indexes are primarily used to:
However, while indexes can improve data retrieval speed, they also come with trade-offs:
An index can be created on a single column to speed up queries that filter or sort by that column.
CREATE INDEX index_name ON table_name (column_name);
Create an index on the LastName column in the Employees table.
CREATE INDEX idx_lastname ON Employees (LastName);
Now, when you query using the LastName column, the database can use this index to quickly find the relevant rows.
A composite index is created on two or more columns. It's useful for queries that filter or sort on multiple columns.
CREATE INDEX index_name ON table_name (column1, column2);
Create an index on the LastName and FirstName columns in the Employees table.
CREATE INDEX idx_fullname ON Employees (LastName, FirstName);
This composite index will improve queries that filter or sort on both the LastName and FirstName columns together.
A unique index ensures that the values in the indexed column(s) are unique. It is often used to enforce data integrity.
CREATE UNIQUE INDEX index_name ON table_name (column_name);
Create a unique index on the Email column to ensure no two employees have the same email address.
CREATE UNIQUE INDEX idx_email ON Employees (Email);
This will prevent duplicate email addresses in the Employees table.
A full-text index is used for performing advanced text searches on large amounts of text data.
CREATE FULLTEXT INDEX index_name ON table_name (column_name);
Create a full-text index on the Description column in a Products table to support full-text search.
CREATE FULLTEXT INDEX idx_description ON Products (Description);
Full-text indexes are helpful for searching keywords within text fields, such as product descriptions or document contents.
A clustered index determines the physical order of the rows in a table. There can only be one clustered index per table since data can only be physically sorted in one way.
CREATE CLUSTERED INDEX index_name ON table_name (column_name);
Create a clustered index on the EmployeeID column of the Employees table.
CREATE CLUSTERED INDEX idx_employeeid ON Employees (EmployeeID);
With this index, the rows in the Employees table are physically ordered by EmployeeID.
If an index is no longer needed or if it affects performance negatively, it can be dropped.
DROP INDEX index_name ON table_name;
DROP INDEX idx_lastname ON Employees;
This removes the idx_lastname index from the Employees table.