Skip to main content

Command Palette

Search for a command to run...

SQL Indexes: Boosting Query Performance

Updated
2 min readView as Markdown

Indexes are special data structure in SQL. They make data retrieval faster, working like a quick lookup table for the database instead of scanning the whole table row by row. The database can directly jump to the needed rows, which improves the performance and efficiency of queries.

Indexes make queries like SELECT, JOIN, WHERE, and ORDER BY run faster. They reduce disk work (I/O) and improve efficiency in large tables. Unique indexes help keep data accurate (no duplicate values). Too many indexes can slow down INSERT, UPDATE, and DELETE operations. Primary Key and Unique constraints automatically create indexes.

There are three main ways to create an index in SQL

Single Column Index

Made on one column. Speeds up queries when we search, filter, or sort by that column.

CREATE INDEX idx_product_id ON employees(product_id);

Multi-Column Index

Made on two or more columns. Useful when queries use multiple columns together (like filtering or joining).

CREATE INDEX idx_product_quantity ON sales(product_id, quantity);

Unique Index

Makes sure column values are unique (no duplicates). Helps maintain data accuracy.

CREATE UNIQUE INDEX idx_employee_id ON employee(employee_id);

Single column → one column

Multi column → two or more columns

Unique → prevents duplicates

Removing an Index

Indexes use extra storage and slow down write operations (INSERT, UPDATE, DELETE).

If not needed, remove it:

DROP INDEX idx_product_id;

Altering an Index

Indexes can be rebuilt/reorganized to improve performance as tables grow.

This does not affect the data.

ALTER INDEX idx_product_id ON product_table REBUILD;

Viewing Indexes

To check which indexes exist in a table:

SHOW INDEXES FROM sales;

Renaming an Index

SQL doesn’t have a direct rename option.

In SQL Server, you can rename using:

EXEC sp_rename 'old_index_name', 'new_index_name', 'INDEX';

Summary:

  • Drop = remove index

  • Alter = rebuild/reorganize index

  • Show = list indexes

  • Rename = change index name (with sp_rename in SQL Server)

Note:- Indexes take up extra storage space.

  • An index is a separate data structure (like a lookup table) stored by the database.

  • It keeps copies of the indexed column(s) plus pointers to the actual rows.

  • The more indexes you create, the more storage space gets used.

  • For small tables, the extra storage is usually negligible, but for large tables with many indexes, it can be significant.

Index = faster reads but extra storage + slower writes (INSERT/UPDATE/DELETE).