Middle+
Tell me about indexes in Postgres. What types are there, and how does a B-tree index work?
sobes.tech AI
Answer from AI
In PostgreSQL, indexes are used to speed up data search and sorting. They create a data structure that allows quick retrieval of rows without scanning the entire table.
Main types of indexes in Postgres:
- B-tree — the most common type, suitable for comparison operations (=, <, <=, >, >=) and sorting.
- 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.
- BRIN (Block Range Index) — for very large tables with ordered data.
How B-tree index works:
B-tree is a balanced tree where each node contains keys and references to child nodes or data. When searching via an index, Postgres quickly traverses the tree, comparing keys to find the desired data page. This is much faster than a sequential scan.
Example of creating a B-tree index:
CREATE INDEX idx_users_email ON users(email);
This index speeds up queries like:
SELECT * FROM users WHERE email = 'example@example.com';
Indexes require additional space and slow down insert/update operations, so they should be used thoughtfully.