What is a Database Index?

A database index is a data structure that improves the speed of data retrieval operations on a table. Think of it like the index at the back of a book — instead of scanning every page, the database can jump directly to the relevant rows.

Indexes come with trade-offs: they speed up SELECT queries but slow down INSERT, UPDATE, and DELETE operations because the index must be maintained. They also consume disk space. The key is to index the right columns — primarily those used in WHERE, JOIN, ORDER BY, and GROUP BY clauses.

Basic CREATE INDEX Syntax

CREATE INDEX index_name ON table_name(column_name);

Types of Indexes

⚡ CREATE INDEX — All Dialects

Copy-paste ready index creation scripts with composite, covering, and online build options.

-- Single-column index
CREATE INDEX idx_users_email ON users(email);

-- Composite index
CREATE INDEX idx_users_name_status ON users(name, status);

-- Unique index
CREATE UNIQUE INDEX idx_users_email_unique ON users(email);

-- Full-text index (MyISAM or InnoDB 5.6+)
CREATE FULLTEXT INDEX idx_posts_content ON posts(content);

-- Online index build (InnoDB, MySQL 5.6+)
ALTER TABLE users
  ADD INDEX idx_users_email (email),
  ALGORITHM=INPLACE, LOCK=NONE;

-- Prefix index (for long VARCHAR columns)
CREATE INDEX idx_users_email_prefix ON users(email(50));
⚠️ Safety Note: Adding an index on a large table can lock the table and consume significant disk I/O. On PostgreSQL, always use CREATE INDEX CONCURRENTLY in production. On MySQL, use ALGORITHM=INPLACE, LOCK=NONE. On SQL Server, use WITH (ONLINE = ON). Schedule index builds during low-traffic windows when possible.
💡 Index Naming Convention: Use idx_<table>_<column> for single-column indexes and idx_<table>_<col1>_<col2> for composite indexes. This makes it easy to identify which indexes are safe to drop when optimizing.
Compare indexes across staging and production. Compare Schemas →

When to Create an Index

When NOT to Create an Index

Composite Index Column Order

The order of columns in a composite index matters. A composite index on (last_name, first_name) can be used for queries on:

Put the most selective column first, and consider your query patterns carefully.

Related Migration Recipes