WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

PostgreSQL · Advanced · question 41 of 100

What are the different types of indexes in PostgreSQL, and when should you use each one?

📕 Buy this interview preparation book: 100 PostgreSQL questions & answers — PDF + EPUB for $5

PostgreSQL supports different types of indexes, each with its unique strengths and usage scenarios. Here are some of the most common index types in PostgreSQL:

1. B-tree index - This is the default index in PostgreSQL and is suitable for most use cases. It is a balanced tree data structure that allows fast lookup, sorting, and range queries for data stored in a table. B-tree indexes work best for columns with high selectivity (i.e., columns that have a wide range of distinct values), and the data is frequently updated.

Example code:

CREATE INDEX btree_index ON table_name (column_name);

2. Hash index - Hash indexes are faster than B-tree indexes for exact match queries, but they are not suitable for range queries. This type of index is best suited for columns with a small number of distinct values.

Example code:

CREATE INDEX hash_index ON table_name USING hash (column_name);

3. GiST index - GiST (Generalized Search Tree) index is an extensible index that supports different types of data structures and search algorithms. It is useful for complex data types such as geometric shapes, geolocation data, and full-text search.

Example code:

CREATE INDEX gist_index ON table_name USING gist (column_name);

4. GIN index - GIN (Generalized Inverted Index) index is designed for use with composite types and supports fast search and partial match operations. It is useful for columns that contain arrays or JSON data.

Example code:

CREATE INDEX gin_index ON table_name USING gin (column_name);

5. BRIN index - BRIN (Block Range INdex) index is useful for large tables that are frequently updated by appending data. It divides data into blocks and stores the minimum and maximum values for each block, making it efficient to scan and filter large tables.

Example code:

CREATE INDEX brin_index ON table_name USING brin (column_name);

In conclusion, choosing the right index type depends on the use case and the data type being indexed. For a standard data table with an integer ID column, B-tree index is the default and most commonly used type. But for more complex data types, choosing the right index is crucial for better query performance.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic PostgreSQL interview — then scores it.
📞 Practice PostgreSQL — free 15 min
📕 Buy this interview preparation book: 100 PostgreSQL questions & answers — PDF + EPUB for $5

All 100 PostgreSQL questions · All topics