Sobes.tech
Middle

What is an index in PostgreSQL? Why is it needed? What types are there?

sobes.tech AI

Answer from AI

An index in PostgreSQL is a special data structure that speeds up the search and retrieval of rows from a table based on certain columns. Without indexes, the DBMS has to scan the entire table, which slows down queries.

Indexes are needed to improve query performance, especially with large volumes of data and frequent retrieval operations.

Main types of indexes in PostgreSQL:

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

Example of creating an index:

CREATE INDEX idx_users_email ON users(email);

This creates a B-tree index on the email column of the users table, speeding up searches by email.