Database.What are “indexes”? What are they used for? What are their advantages and disadvantages?

An index is a special lookup data structure that a database uses to speed up the retrieval of rows based on certain column values.

Think of an index like the index of a book — it helps you find content quickly, without scanning every page.

🎯 What Are Indexes Used For?

  • Speed up queries that use WHERE, JOIN, ORDER BY, GROUP BY
  • Help databases find rows without scanning the entire table
  • Enforce uniqueness in columns (e.g., primary keys, unique constraints)

🧱 Types of Indexes (commonly used)

TypeDescription
B-Tree IndexDefault in most RDBMS; good for range and equality queries
Hash IndexFast for equality (=), not for ranges
Unique IndexEnsures values in the column are unique
Composite IndexIndex over multiple columns ((A, B))
Full-Text IndexUsed for text search in large text fields

Advantages of Indexes

AdvantageBenefit
🚀 Faster SELECT queriesEspecially on large datasets
🔗 Faster JOINsSpeeds up joining related tables
🔍 Quick lookup/searchIdeal for searching by key or common columns
🧱 Enforces constraintsE.g., UNIQUE, PRIMARY KEY
📈 Improves sorting/groupingHelps with ORDER BY, GROUP BY clauses

Disadvantages of Indexes

DisadvantageProblem
🐌 Slower INSERT, UPDATE, DELETEIndexes must be updated along with the data
💾 Extra storageIndexes consume disk space
🧠 Over-indexing hurtsToo many indexes can confuse the query planner or cause overhead
Wrong index choiceMay lead to worse performance than no index

🛠️ Example:

-- Create an index on the email column
CREATE INDEX idx_email ON Users(email);

-- Now this query is fast
SELECT * FROM Users WHERE email = 'alice@example.com';

🧠 Tip: When to Use Indexes

Use indexes when:

  • You frequently query or filter on a column
  • A column is used in joins or sorting
  • The table has many rows (thousands or millions)

Avoid or limit indexes when:

  • You write-heavy tables (frequent updates/inserts)
  • You index columns with low uniqueness (e.g., gender, boolean)
This entry was posted in Без рубрики. Bookmark the permalink.