Sobes.tech
Middle+

Tell me about indexes in PostgreSQL — what types are there, composite indexes, and the order of columns.

sobes.tech AI

Answer from AI

In PostgreSQL, there are several types of indexes, the most common ones:

  • B-tree — the standard index for fast equality and range searches.
  • Hash — an index for fast equality searches (rarely used).
  • GIN and GiST — for full-text search, geospatial data, and other specialized data.

A composite index is created on multiple columns, for example:

CREATE INDEX idx_name ON table_name (col1, col2);

The order of columns in a composite index is important: the index is efficient for queries that filter or sort by the first column, then the second, and so on. If a query uses only the second column, the index may not be used.

For example, an index on (col1, col2) is well-suited for queries with conditions on col1 or on both col1 and col2, but not for queries only on col2.