Sobes.tech
Senior

What are indexes in PostgreSQL? Pros and cons, types of indexes.

sobes.tech AI

Answer from AI

Indexes in PostgreSQL are special data structures that speed up searching and sorting data in tables. They allow the database to quickly find the needed records without scanning the entire table.

Pros:

  • Significantly accelerate SELECT operations with search conditions.
  • Can improve the performance of sorting and joining tables.
  • Support data uniqueness (unique indexes).

Cons:

  • Take up additional disk space.
  • Slow down insert, update, and delete operations because the index needs to be updated.
  • Improperly chosen indexes may not provide a performance boost.

Types of indexes in PostgreSQL:

  • B-tree — the most common, suitable for most comparison operations (=, <, >, BETWEEN).
  • Hash — for fast equality searches, but less versatile.
  • GIN (Generalized Inverted Index) — for full-text search and array indexing.
  • GiST (Generalized Search Tree) — for complex data structures, e.g., geometric.
  • SP-GiST — for specific structures, e.g., prefix trees.
  • BRIN (Block Range Index) — for very large tables with ordered data, saves space.

Example of creating a B-tree index:

CREATE INDEX idx_users_email ON users(email);