An index is a special database object that improves the speed of data retrieval from a table. It works like the index in a book: instead of scanning every page, the database can directly locate the required data.
Internally, most databases use B-Tree data structures for indexes, allowing fast searching, sorting, and filtering operations.
Without index:
With index:
CREATE INDEX idx_last_name ON employees(last_name);
Use Case
WHERE last_name = 'Smith'CREATE INDEX idx_dept_salary ON employees(department, salary);
Important Rule
departmentdepartment AND salarysalaryCREATE UNIQUE INDEX idx_email ON employees(email);
Benefits
| Operation | Effect of Index |
|---|---|
| SELECT | Faster |
| INSERT | Slower |
| UPDATE | Slower |
| DELETE | Slower |
Reason: Indexes must be updated whenever data changes.
CREATE INDEX idx_department ON employees(department);
CREATE INDEX idx_customer_id ON orders(customer_id);
CREATE INDEX idx_order_date ON orders(order_date);
CREATE INDEX idx_fk_department ON employees(department_id);
Why?
SHOW INDEXES FROM employees;
SELECT *
FROM information_schema.statistics
WHERE table_name = 'employees';
DROP INDEX idx_last_name ON employees;
CREATE FULLTEXT INDEX idx_description ON products(description);
Cardinality = Number of unique values in a column
| Cardinality | Index Effectiveness |
|---|---|
| High (email, ID) | Excellent |
| Medium (city) | Good |
| Low (gender, boolean) | Poor |
EXPLAIN to analyze queriesEXPLAIN SELECT * FROM employees WHERE department = 'IT';
Helps You Understand
| Feature | Index | Constraint |
|---|---|---|
| Purpose | Performance | Data integrity |
| Enforces rules | ❌ | ✅ |
| Improves speed | ✅ | ❌ |